MailSharp / MailSharp.WebManager / Services / ConfigService.cs
Code · 456 lines · 20029 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456using System.Text.Json;
using System.Text.Json.Nodes;

namespace MailSharp.WebManager.Services;

public class ConfigService(IWebHostEnvironment env)
{
	private static readonly JsonSerializerOptions Pretty = new() { WriteIndented = true };

	private string OverridePath => Path.Combine(env.ContentRootPath, "mailsharp.json");

	// ── Read ────────────────────────────────────────────────

	public SmtpConfigDto       GetSmtp()     => MakeSmtpDto(BuildMerged());
	public Pop3ConfigDto       GetPop3()     => MakePop3Dto(BuildMerged());
	public ImapConfigDto       GetImap()     => MakeImapDto(BuildMerged());
	public DmarcConfigDto      GetDmarc()    => MakeDmarcDto(BuildMerged());
	public MailboxConfigDto    GetMailbox()  => MakeMailboxDto(BuildMerged());
	public List<IpGroupDto>          GetIpGroups()          => MakeIpGroupsDto(BuildMerged());
	public List<MaintenanceUserDto>  GetMaintenanceUsers()  => MakeMaintenanceUsersDto(BuildMerged());
	public GeneralSettingsDto        GetGeneral()           => MakeGeneralDto(BuildMerged());

	private IConfiguration BuildMerged()
	{
		return new ConfigurationBuilder()
			.SetBasePath(env.ContentRootPath)
			.AddJsonFile("appsettings.json", optional: true)
			.AddJsonFile("mailsharp.json", optional: true)
			.Build();
	}

	private static SmtpConfigDto MakeSmtpDto(IConfiguration c) => new()
	{
		Enabled               = c.GetValue<bool?>("SmtpSettings:Enabled") ?? true,
		EmlStoragePath        = c["SmtpSettings:EmlStoragePath"] ?? string.Empty,
		CommandTimeoutSeconds = c.GetValue<int>("SmtpSettings:CommandTimeoutSeconds"),
		BackLog               = c.GetValue<int>("SmtpSettings:BackLog"),
		EnableVrfy            = c.GetValue<bool>("SmtpSettings:EnableVrfy"),
		EnableExpn            = c.GetValue<bool>("SmtpSettings:EnableExpn"),
		RequireDkim           = c.GetValue<bool>("SmtpSettings:RequireDkim"),
		CertificatePath       = c["SmtpSettings:CertificatePath"] ?? string.Empty,
		CertificatePassword   = c["SmtpSettings:CertificatePassword"] ?? string.Empty,
		DnsResolvers          = c.GetSection("SmtpSettings:DnsResolvers").Get<List<string>>() ?? [],
		MaxConnections        = c.GetValue<int>("SmtpSettings:MaxConnections"),
		MaxMessageSizeKb      = c.GetValue<int>("SmtpSettings:MaxMessageSizeKb"),
		RetryCount            = c.GetValue<int>("SmtpSettings:RetryCount"),
		RetryIntervalMinutes  = c.GetValue<int>("SmtpSettings:RetryIntervalMinutes"),
		LocalHostName         = c["SmtpSettings:LocalHostName"] ?? string.Empty,
		RelayEnabled          = c.GetValue<bool>("SmtpSettings:RelayEnabled"),
		RelayHost             = c["SmtpSettings:RelayHost"] ?? string.Empty,
		RelayPort             = c.GetValue<int>("SmtpSettings:RelayPort"),
		RelayRequiresAuth     = c.GetValue<bool>("SmtpSettings:RelayRequiresAuth"),
		RelayUsername         = c["SmtpSettings:RelayUsername"] ?? string.Empty,
		RelayPassword         = c["SmtpSettings:RelayPassword"] ?? string.Empty,
		RelayConnectionSecurity = c["SmtpSettings:RelayConnectionSecurity"] ?? "None",
		AllowPlainTextAuth    = c.GetValue<bool>("SmtpSettings:AllowPlainTextAuth"),
		AllowEmptySender      = c.GetValue<bool>("SmtpSettings:AllowEmptySender"),
		AllowBadLineEndings   = c.GetValue<bool>("SmtpSettings:AllowBadLineEndings"),
		DisconnectOnTooManyInvalidCommands = c.GetValue<bool>("SmtpSettings:DisconnectOnTooManyInvalidCommands"),
		MaxInvalidCommands    = c.GetValue<int>("SmtpSettings:MaxInvalidCommands"),
		MaxRecipientsPerBatch = c.GetValue<int>("SmtpSettings:MaxRecipientsPerBatch"),
		AddDeliveredToHeader  = c.GetValue<bool>("SmtpSettings:AddDeliveredToHeader"),
		RuleLoopLimit         = c.GetValue<int>("SmtpSettings:RuleLoopLimit"),
		MaxRecipientHosts     = c.GetValue<int>("SmtpSettings:MaxRecipientHosts"),
		RelayQueuePath        = c["SmtpSettings:RelayQueuePath"] ?? string.Empty,
		Ports                 = c.GetSection("SmtpSettings:Ports").Get<List<PortConfigDto>>() ?? []
	};

	private static Pop3ConfigDto MakePop3Dto(IConfiguration c) => new()
	{
		Enabled             = c.GetValue<bool?>("Pop3Settings:Enabled") ?? true,
		CertificatePath     = c["Pop3Settings:CertificatePath"] ?? string.Empty,
		CertificatePassword = c["Pop3Settings:CertificatePassword"] ?? string.Empty,
		Ports               = c.GetSection("Pop3Settings:Ports").Get<List<PortConfigDto>>() ?? [],
		MaxConnections      = c.GetValue<int>("Pop3Settings:MaxConnections"),
		WelcomeMessage      = c["Pop3Settings:WelcomeMessage"] ?? string.Empty
	};

	private static ImapConfigDto MakeImapDto(IConfiguration c) => new()
	{
		Enabled              = c.GetValue<bool?>("ImapSettings:Enabled") ?? true,
		CertificatePath      = c["ImapSettings:CertificatePath"] ?? string.Empty,
		CertificatePassword  = c["ImapSettings:CertificatePassword"] ?? string.Empty,
		Ports                = c.GetSection("ImapSettings:Ports").Get<List<PortConfigDto>>() ?? [],
		MaxConnections       = c.GetValue<int>("ImapSettings:MaxConnections"),
		WelcomeMessage       = c["ImapSettings:WelcomeMessage"] ?? string.Empty,
		PublicFolderName     = c["ImapSettings:PublicFolderName"] ?? "# Public",
		EnableSort           = c.GetValue<bool>("ImapSettings:EnableSort"),
		EnableQuota          = c.GetValue<bool>("ImapSettings:EnableQuota"),
		EnableIdle           = c.GetValue<bool>("ImapSettings:EnableIdle"),
		EnableAcl            = c.GetValue<bool>("ImapSettings:EnableAcl"),
		HierarchyDelimiter   = c["ImapSettings:HierarchyDelimiter"] ?? "."
	};

	private static DmarcConfigDto MakeDmarcDto(IConfiguration c) => new()
	{
		FailOpen     = c.GetValue<bool>("DmarcSettings:FailOpen"),
		RequireDmarc = c.GetValue<bool>("DmarcSettings:RequireDmarc")
	};

	private static MailboxConfigDto MakeMailboxDto(IConfiguration c) => new()
	{
		StoragePath = c["MailboxSettings:StoragePath"] ?? string.Empty
	};

	private static List<IpGroupDto> MakeIpGroupsDto(IConfiguration c) =>
		c.GetSection("IpGroups").Get<List<IpGroupDto>>() ?? [];

	private static List<MaintenanceUserDto> MakeMaintenanceUsersDto(IConfiguration c) =>
		c.GetSection("MaintenanceUsers").Get<List<MaintenanceUserDto>>() ?? [];

	private static GeneralSettingsDto MakeGeneralDto(IConfiguration c) => new()
	{
		EmlStoragePath       = c["SmtpSettings:EmlStoragePath"]                                    ?? string.Empty,
		CommandTimeoutSeconds = c.GetValue<int>("SmtpSettings:CommandTimeoutSeconds"),
		BackLog              = c.GetValue<int>("SmtpSettings:BackLog"),
		DnsResolvers         = c.GetSection("SmtpSettings:DnsResolvers").Get<List<string>>()       ?? []
	};

	// ── Write ───────────────────────────────────────────────

	public void SaveSmtpGeneral(SmtpGeneralDto dto)         => PatchFields("SmtpSettings", dto);
	public void SaveSmtpConnections(SmtpConnectionsDto dto) => PatchFields("SmtpSettings", dto);
	public void SaveSmtpDelivery(SmtpDeliveryDto dto)       => PatchFields("SmtpSettings", dto);
	public void SaveSmtpRelay(SmtpRelayDto dto)             => PatchFields("SmtpSettings", dto);
	public void SaveSmtpSecurity(SmtpSecurityDto dto)       => PatchFields("SmtpSettings", dto);
	public void SaveSmtpLimits(SmtpLimitsDto dto)           => PatchFields("SmtpSettings", dto);
	public void SavePop3General(Pop3GeneralDto dto)         => PatchFields("Pop3Settings", dto);
	public void SavePop3Connections(Pop3ConnectionsDto dto) => PatchFields("Pop3Settings", dto);
	public void SaveImapGeneral(ImapGeneralDto dto)         => PatchFields("ImapSettings", dto);
	public void SaveImapConnections(ImapConnectionsDto dto) => PatchFields("ImapSettings", dto);
	public void SaveImapFolders(ImapFoldersDto dto)         => PatchFields("ImapSettings", dto);
	public void SaveImapAdvanced(ImapAdvancedDto dto)       => PatchFields("ImapSettings", dto);
	public void SaveDmarc(DmarcConfigDto dto)               => PatchFields("DmarcSettings", dto);
	public void SaveMailbox(MailboxConfigDto dto)           => PatchFields("MailboxSettings", dto);
	public void SaveIpGroups(List<IpGroupDto> dto)                  => PatchSection("IpGroups", dto);
	public void SaveMaintenanceUsers(List<MaintenanceUserDto> dto)  => PatchSection("MaintenanceUsers", dto);
	public void SaveGeneral(GeneralSettingsDto dto)         => PatchFields("SmtpSettings", dto);

	// Merges only the fields present in dto into the existing section (no data loss).
	private void PatchFields(string section, object dto)
	{
		var root        = ReadOverride();
		var existing    = root[section]?.AsObject() ?? new JsonObject();
		var patch       = JsonNode.Parse(JsonSerializer.Serialize(dto, Pretty))!.AsObject();
		foreach (var (key, value) in patch)
			existing[key] = value?.DeepClone();
		root[section] = existing;
		File.WriteAllText(OverridePath, root.ToJsonString(Pretty));
	}

	// Replaces the entire section (used for arrays like IpGroups/MaintenanceUsers).
	private void PatchSection(string key, object dto)
	{
		var root = ReadOverride();
		root[key] = JsonNode.Parse(JsonSerializer.Serialize(dto, Pretty))!;
		File.WriteAllText(OverridePath, root.ToJsonString(Pretty));
	}

	// ── Startup initialisation ──────────────────────────────

	public void EnsureOverrideInitialized()
	{
		var root   = ReadOverride();
		bool dirty = false;

		// Build an appsettings-only config so we always get the canonical defaults,
		// even when the override file already exists but contains empty strings from
		// a previous failed save.
		var src = new ConfigurationBuilder()
			.SetBasePath(env.ContentRootPath)
			.AddJsonFile("appsettings.json", optional: false)
			.Build();

		void TrySeed(string section, string? probe, Func<IConfiguration, object> factory)
		{
			bool empty = probe is null
				? !root.ContainsKey(section)
				: string.IsNullOrEmpty(root[section]?[probe]?.GetValue<string>());
			if (empty)
			{
				root[section] = JsonNode.Parse(JsonSerializer.Serialize(factory(src), Pretty))!;
				dirty = true;
			}
		}

		TrySeed("SmtpSettings",    "EmlStoragePath", c => MakeSmtpDto(c));
		TrySeed("Pop3Settings",    "CertificatePath", c => MakePop3Dto(c));
		TrySeed("ImapSettings",    "CertificatePath", c => MakeImapDto(c));
		TrySeed("DmarcSettings",   null,              c => MakeDmarcDto(c));
		TrySeed("MailboxSettings", "StoragePath",     c => MakeMailboxDto(c));

		if (!root.ContainsKey("MaintenanceUsers"))
		{
			var users = MakeMaintenanceUsersDto(src);
			root["MaintenanceUsers"] = JsonNode.Parse(JsonSerializer.Serialize(users, Pretty))!;
			dirty = true;
		}

		if (!root.ContainsKey("IpGroups"))
		{
			var groups = MakeIpGroupsDto(src);
			root["IpGroups"] = JsonNode.Parse(JsonSerializer.Serialize(groups, Pretty))!;
			dirty = true;
		}

		if (dirty) File.WriteAllText(OverridePath, root.ToJsonString(Pretty));
	}

	private JsonObject ReadOverride()
	{
		if (!File.Exists(OverridePath))
			return [];
		try { return JsonNode.Parse(File.ReadAllText(OverridePath))?.AsObject() ?? []; }
		catch { return []; }
	}
}

// ── DTOs ────────────────────────────────────────────────────

public class PortConfigDto
{
	public string Host     { get; set; } = string.Empty;
	public int    Port     { get; set; }
	public string Security { get; set; } = string.Empty;
	public bool   Enabled  { get; set; } = true;
}

public class SmtpConfigDto
{
	public bool         Enabled               { get; set; } = true;
	// General
	public string       EmlStoragePath        { get; set; } = string.Empty;
	public int          CommandTimeoutSeconds { get; set; }
	public int          BackLog               { get; set; }
	public string       CertificatePath       { get; set; } = string.Empty;
	public string       CertificatePassword   { get; set; } = string.Empty;
	public List<string> DnsResolvers          { get; set; } = [];
	// Connections
	public int          MaxConnections        { get; set; }
	public int          MaxMessageSizeKb      { get; set; }
	// Delivery
	public int          RetryCount            { get; set; }
	public int          RetryIntervalMinutes  { get; set; }
	public string       LocalHostName         { get; set; } = string.Empty;
	// Relay
	public bool         RelayEnabled          { get; set; }
	public string       RelayHost             { get; set; } = string.Empty;
	public int          RelayPort             { get; set; }
	public bool         RelayRequiresAuth     { get; set; }
	public string       RelayUsername         { get; set; } = string.Empty;
	public string       RelayPassword         { get; set; } = string.Empty;
	public string       RelayConnectionSecurity { get; set; } = "None";
	public string       RelayQueuePath        { get; set; } = string.Empty;
	// RFC compliance
	public bool         AllowPlainTextAuth    { get; set; }
	public bool         AllowEmptySender      { get; set; }
	public bool         AllowBadLineEndings   { get; set; }
	public bool         DisconnectOnTooManyInvalidCommands { get; set; }
	public int          MaxInvalidCommands    { get; set; }
	// Advanced
	public int          MaxRecipientsPerBatch { get; set; }
	public bool         AddDeliveredToHeader  { get; set; }
	public int          RuleLoopLimit         { get; set; }
	public int          MaxRecipientHosts     { get; set; }
	// Auth / DKIM
	public bool         EnableVrfy            { get; set; }
	public bool         EnableExpn            { get; set; }
	public bool         RequireDkim           { get; set; }
	public List<PortConfigDto> Ports          { get; set; } = [];
}

public class Pop3ConfigDto
{
	public bool   Enabled             { get; set; } = true;
	public string CertificatePath     { get; set; } = string.Empty;
	public string CertificatePassword { get; set; } = string.Empty;
	public List<PortConfigDto> Ports  { get; set; } = [];
	public int    MaxConnections      { get; set; }
	public string WelcomeMessage      { get; set; } = string.Empty;
}

public class ImapConfigDto
{
	public bool   Enabled             { get; set; } = true;
	public string CertificatePath     { get; set; } = string.Empty;
	public string CertificatePassword { get; set; } = string.Empty;
	public List<PortConfigDto> Ports  { get; set; } = [];
	public int    MaxConnections      { get; set; }
	public string WelcomeMessage      { get; set; } = string.Empty;
	public string PublicFolderName    { get; set; } = "# Public";
	public bool   EnableSort          { get; set; }
	public bool   EnableQuota         { get; set; }
	public bool   EnableIdle          { get; set; }
	public bool   EnableAcl           { get; set; }
	public string HierarchyDelimiter  { get; set; } = ".";
}

public class DmarcConfigDto
{
	public bool FailOpen     { get; set; }
	public bool RequireDmarc { get; set; }
}

public class MailboxConfigDto
{
	public string StoragePath { get; set; } = string.Empty;
}

public class IpAccessDto
{
	public bool Smtp                { get; set; }
	public bool Pop3                { get; set; }
	public bool Imap                { get; set; }
	public bool AntiSpam            { get; set; }
	public bool AntiVirus           { get; set; }
	public bool RequireSslTlsForAuth { get; set; }
}

public class EmailFlowDto
{
	public bool Allowed     { get; set; }
	public bool RequireAuth { get; set; }
}

public class EmailFlowsDto
{
	public EmailFlowDto LocalToLocal         { get; set; } = new();
	public EmailFlowDto LocalToExternal      { get; set; } = new();
	public EmailFlowDto ExternalToLocal      { get; set; } = new();
	public EmailFlowDto ExternalToExternal   { get; set; } = new();
}

public class GeneralSettingsDto
{
	public string       EmlStoragePath        { get; set; } = string.Empty;
	public int          CommandTimeoutSeconds  { get; set; }
	public int          BackLog               { get; set; }
	public List<string> DnsResolvers          { get; set; } = [];
}

public class MaintenanceUserDto
{
	public string UserName   { get; set; } = string.Empty;
	public string Password   { get; set; } = string.Empty;
	public string Role       { get; set; } = "Unknown";
	public int    ExpireDays { get; set; } = 365;
	public bool   Enabled    { get; set; } = true;
}

public class IpGroupDto
{
	public string        Name       { get; set; } = string.Empty;
	public int           Priority   { get; set; }
	public string        Cidr       { get; set; } = string.Empty;
	public string?       Expires    { get; set; }
	public IpAccessDto   Access     { get; set; } = new();
	public EmailFlowsDto EmailFlows { get; set; } = new();
}

// ── Per-section write DTOs ───────────────────────────────────

public class SmtpGeneralDto
{
	public bool   Enabled       { get; set; } = true;
	public string LocalHostName { get; set; } = string.Empty;
}

public class SmtpConnectionsDto
{
	public int               MaxConnections      { get; set; }
	public int               MaxMessageSizeKb    { get; set; }
	public string            CertificatePath     { get; set; } = string.Empty;
	public string            CertificatePassword { get; set; } = string.Empty;
	public List<PortConfigDto> Ports             { get; set; } = [];
}

public class SmtpDeliveryDto
{
	public int RetryCount           { get; set; }
	public int RetryIntervalMinutes { get; set; }
}

public class SmtpRelayDto
{
	public bool   RelayEnabled            { get; set; }
	public bool   AddDeliveredToHeader    { get; set; }
	public string RelayHost               { get; set; } = string.Empty;
	public int    RelayPort               { get; set; }
	public string RelayQueuePath          { get; set; } = string.Empty;
	public string RelayConnectionSecurity { get; set; } = "None";
	public bool   RelayRequiresAuth       { get; set; }
	public string RelayUsername           { get; set; } = string.Empty;
	public string RelayPassword           { get; set; } = string.Empty;
}

public class SmtpSecurityDto
{
	public bool AllowPlainTextAuth                    { get; set; }
	public bool AllowEmptySender                      { get; set; }
	public bool AllowBadLineEndings                   { get; set; }
	public bool DisconnectOnTooManyInvalidCommands     { get; set; }
	public int  MaxInvalidCommands                    { get; set; }
	public bool EnableVrfy                            { get; set; }
	public bool EnableExpn                            { get; set; }
	public bool RequireDkim                           { get; set; }
}

public class SmtpLimitsDto
{
	public int MaxRecipientsPerBatch { get; set; }
	public int RuleLoopLimit         { get; set; }
	public int MaxRecipientHosts     { get; set; }
}

public class Pop3GeneralDto
{
	public bool   Enabled        { get; set; } = true;
	public string WelcomeMessage { get; set; } = string.Empty;
}

public class Pop3ConnectionsDto
{
	public int               MaxConnections      { get; set; }
	public string            CertificatePath     { get; set; } = string.Empty;
	public string            CertificatePassword { get; set; } = string.Empty;
	public List<PortConfigDto> Ports             { get; set; } = [];
}

public class ImapGeneralDto
{
	public bool   Enabled        { get; set; } = true;
	public string WelcomeMessage { get; set; } = string.Empty;
}

public class ImapConnectionsDto
{
	public int               MaxConnections      { get; set; }
	public string            CertificatePath     { get; set; } = string.Empty;
	public string            CertificatePassword { get; set; } = string.Empty;
	public List<PortConfigDto> Ports             { get; set; } = [];
}

public class ImapFoldersDto
{
	public string PublicFolderName   { get; set; } = "# Public";
	public string HierarchyDelimiter { get; set; } = ".";
}

public class ImapAdvancedDto
{
	public bool EnableSort  { get; set; }
	public bool EnableQuota { get; set; }
	public bool EnableIdle  { get; set; }
	public bool EnableAcl   { get; set; }
}