MailSharp / MailSharp.IMAP / Session / ImapSession.cs
Code · 306 lines · 11498 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
306using MailSharp.Common;
using MailSharp.Common.Services;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Text;
using MailSharp.IMAP.Metrics;

namespace MailSharp.IMAP.Session;

public class ImapSession(
	TcpClient client,
	IConfiguration configuration,
	SecurityEnum security,
	AuthenticationService authService,
	MailboxService mailboxService,
	ImapMetrics metrics,
	ILogger<ImapSession> logger)
{
	private Stream? stream;
	private string? selectedFolder;

	public async Task ProcessAsync(CancellationToken cancellationToken)
	{
		metrics.IncrementConnections();
		metrics.IncrementActive();
		try
		{
			stream = security == SecurityEnum.Tls ? await InitializeTlsStreamAsync() : client.GetStream();
			await SendResponseAsync("* OK IMAP4rev1 server ready", cancellationToken);
			bool isAuthenticated = false;
			string? username = null;
			while (!cancellationToken.IsCancellationRequested)
			{
				string? command = await ReadCommandAsync(cancellationToken);
				if (string.IsNullOrEmpty(command))
				{
					break;
				}
				var parts = command.Split(' ', StringSplitOptions.RemoveEmptyEntries);
				if (parts.Length < 2)
				{
					await SendResponseAsync($"{parts[0]} BAD Invalid command", cancellationToken);
					continue;
				}
				string tag = parts[0];
				string cmd = parts[1].ToUpper();
				metrics.IncrementCommands();
				switch (cmd)
				{
					case "LOGIN":
						if (parts.Length != 4)
						{
							await SendResponseAsync($"{tag} BAD LOGIN requires username and password", cancellationToken);
							continue;
						}
						username = parts[2];
						isAuthenticated = await authService.AuthenticateAsync(username, parts[3], cancellationToken);
						if (isAuthenticated)
							metrics.LoginSucceeded(username);
						else
							metrics.IncrementLoginFailed();
						await SendResponseAsync(
							isAuthenticated ? $"{tag} OK LOGIN completed" : $"{tag} NO LOGIN failed",
							cancellationToken);
						break;
					case "LIST":
						if (!isAuthenticated)
						{
							await SendResponseAsync($"{tag} NO Authentication required", cancellationToken);
							continue;
						}
						var folders = await mailboxService.ListFoldersAsync(username!, cancellationToken);
						foreach (var folder1 in folders)
						{
							await SendResponseAsync($"* LIST (\\NoSelect) \"/\" \"{folder1}\"", cancellationToken);
						}
						await SendResponseAsync($"{tag} OK LIST completed", cancellationToken);
						break;
					case "SELECT":
						if (!isAuthenticated)
						{
							await SendResponseAsync($"{tag} NO Authentication required", cancellationToken);
							continue;
						}
						metrics.IncrementFolderSelects();
						if (parts.Length != 3)
						{
							await SendResponseAsync($"{tag} BAD SELECT requires folder name", cancellationToken);
							continue;
						}
						string folder = parts[2].Trim('"');
						var folderExists = (await mailboxService.ListFoldersAsync(username!, cancellationToken)).Contains(folder);
						if (!folderExists)
						{
							await SendResponseAsync($"{tag} NO Folder does not exist", cancellationToken);
							continue;
						}
						selectedFolder = folder;
						var messages = await mailboxService.GetMessagesAsync(username!, folder, cancellationToken);
						await SendResponseAsync($"* {messages.Count} EXISTS", cancellationToken);
						await SendResponseAsync($"{tag} OK SELECT completed", cancellationToken);
						break;
					case "CREATE":
						if (!isAuthenticated)
						{
							await SendResponseAsync($"{tag} NO Authentication required", cancellationToken);
							continue;
						}
						if (parts.Length != 3)
						{
							await SendResponseAsync($"{tag} BAD CREATE requires folder name", cancellationToken);
							continue;
						}
						string newFolder = parts[2].Trim('"');
						bool created = await mailboxService.CreateFolderAsync(username!, newFolder, cancellationToken);
						await SendResponseAsync(
							created ? $"{tag} OK CREATE completed" : $"{tag} NO Folder creation failed",
							cancellationToken);
						break;
					case "DELETE":
						if (!isAuthenticated)
						{
							await SendResponseAsync($"{tag} NO Authentication required", cancellationToken);
							continue;
						}
						if (parts.Length != 3)
						{
							await SendResponseAsync($"{tag} BAD DELETE requires folder name", cancellationToken);
							continue;
						}
						string deleteFolder = parts[2].Trim('"');
						if (deleteFolder == "INBOX")
						{
							await SendResponseAsync($"{tag} NO Cannot delete INBOX", cancellationToken);
							continue;
						}
						bool deleted = await mailboxService.DeleteFolderAsync(username!, deleteFolder, cancellationToken);
						await SendResponseAsync(
							deleted ? $"{tag} OK DELETE completed" : $"{tag} NO Folder deletion failed",
							cancellationToken);
						break;
					case "FETCH":
						if (!isAuthenticated || selectedFolder == null)
						{
							await SendResponseAsync($"{tag} NO Authentication or folder selection required", cancellationToken);
							continue;
						}
						if (parts.Length < 4)
						{
							await SendResponseAsync($"{tag} BAD FETCH requires message sequence and items", cancellationToken);
							continue;
						}
						string sequence = parts[2];
						string items = parts[3].ToUpper();
						var fetchMessages = await mailboxService.GetMessagesAsync(username!, selectedFolder, cancellationToken);
						int seqNum;
						if (!int.TryParse(sequence, out seqNum) || seqNum < 1 || seqNum > fetchMessages.Count)
						{
							await SendResponseAsync($"{tag} NO Invalid message sequence", cancellationToken);
							continue;
						}
						var message = fetchMessages[seqNum - 1];
						if (items.Contains("FLAGS"))
						{
							string flags = $"FLAGS (\\{(message.Flags.Seen ? "Seen" : "")} \\{(message.Flags.Deleted ? "Deleted" : "")} \\{(message.Flags.Flagged ? "Flagged" : "")} \\{(message.Flags.Answered ? "Answered" : "")})";
							await SendResponseAsync($"* {seqNum} FETCH ({flags})", cancellationToken);
						}
						if (items.Contains("BODY[]"))
						{
							string? content = await mailboxService.GetMessageContentAsync(username!, selectedFolder, message.Uid, cancellationToken);
							if (content != null)
							{
								await SendResponseAsync($"* {seqNum} FETCH (BODY[] {{{content.Length}}}", cancellationToken);
								await SendResponseAsync(content, cancellationToken);
								await SendResponseAsync(")", cancellationToken);
								metrics.MessageFetched(content.Length);
							}
						}
						await SendResponseAsync($"{tag} OK FETCH completed", cancellationToken);
						break;
					case "STORE":
						if (!isAuthenticated || selectedFolder == null)
						{
							await SendResponseAsync($"{tag} NO Authentication or folder selection required", cancellationToken);
							continue;
						}
						if (parts.Length < 5)
						{
							await SendResponseAsync($"{tag} BAD STORE requires message sequence, operation, and flags", cancellationToken);
							continue;
						}
						string storeSequence = parts[2];
						string operation = parts[3].ToUpper();
						string flagList = parts[4].Trim('(', ')');
						if (!int.TryParse(storeSequence, out int storeSeqNum) || storeSeqNum < 1 || storeSeqNum > (await mailboxService.GetMessagesAsync(username!, selectedFolder, cancellationToken)).Count)
						{
							await SendResponseAsync($"{tag} NO Invalid message sequence", cancellationToken);
							continue;
						}
						var storeMessage = (await mailboxService.GetMessagesAsync(username!, selectedFolder, cancellationToken))[storeSeqNum - 1];
						var newFlags = new MessageFlags();
						foreach (string flag in flagList.Split(' ', StringSplitOptions.RemoveEmptyEntries))
						{
							if (flag == "\\Seen") newFlags.Seen = true;
							if (flag == "\\Deleted") newFlags.Deleted = true;
							if (flag == "\\Flagged") newFlags.Flagged = true;
							if (flag == "\\Answered") newFlags.Answered = true;
						}
						bool updated = await mailboxService.SetMessageFlagsAsync(username!, selectedFolder, storeMessage.Uid, newFlags, cancellationToken);
						await SendResponseAsync(
							updated ? $"{tag} OK STORE completed" : $"{tag} NO STORE failed",
							cancellationToken);
						break;
					case "LOGOUT":
						await SendResponseAsync("* BYE IMAP4rev1 server logging out", cancellationToken);
						await SendResponseAsync($"{tag} OK LOGOUT completed", cancellationToken);
						return;
					case "STARTTLS":
						if (security !=  SecurityEnum.StartTls)
						{
							await SendResponseAsync($"{tag} NO STARTTLS not supported", cancellationToken);
							continue;
						}
						await SendResponseAsync($"{tag} OK Begin TLS negotiation", cancellationToken);
						stream = await InitializeTlsStreamAsync();
						break;
					default:
						await SendResponseAsync($"{tag} BAD Unknown command", cancellationToken);
						break;
				}
			}
		}
		catch (Exception ex)
		{
			var eventIdConfig = configuration.GetSection("ImapEventIds:SessionError").Get<EventIdConfig>()
				?? throw new InvalidOperationException("Missing ImapEventIds:SessionError");
			logger.LogError(
				new EventId(eventIdConfig.Id, eventIdConfig.Name),
				ex,
				configuration["ImapLogMessages:SessionError"],
				client.Client.RemoteEndPoint);
		}
		finally
		{
			metrics.DecrementActive();
			stream?.Dispose();
			client.Close();
		}
	}

	// Initialize TLS stream for IMAP session
	private async Task<Stream> InitializeTlsStreamAsync()
	{
		try
		{
			string certPath = configuration["ImapSettings:CertificatePath"] ?? throw new InvalidOperationException("CertificatePath not configured");
			string certPassword = configuration["ImapSettings:CertificatePassword"] ?? string.Empty;
			X509Certificate2 certificate = X509CertificateLoader.LoadPkcs12FromFile(certPath, certPassword);
			SslStream sslStream = new(client.GetStream(), false);
			await sslStream.AuthenticateAsServerAsync(certificate, false, System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls13, false);

			var eventIdConfig = configuration.GetSection("ImapEventIds:TlsInitialized").Get<EventIdConfig>()
				?? throw new InvalidOperationException("Missing ImapEventIds:TlsInitialized");
			logger.LogInformation(
				new EventId(eventIdConfig.Id, eventIdConfig.Name),
				configuration["ImapLogMessages:TlsInitialized"],
				client.Client.RemoteEndPoint);

			return sslStream;
		}
		catch (Exception ex)
		{
			var eventIdConfig = configuration.GetSection("ImapEventIds:TlsInitializationFailed").Get<EventIdConfig>()
				?? throw new InvalidOperationException("Missing ImapEventIds:TlsInitializationFailed");
			logger.LogError(
				new EventId(eventIdConfig.Id, eventIdConfig.Name),
				ex,
				configuration["ImapLogMessages:TlsInitializationFailed"],
				client.Client.RemoteEndPoint);
			throw;
		}
	}

	private async Task<string?> ReadCommandAsync(CancellationToken cancellationToken)
	{
		if (stream == null)
		{
			return null;
		}
		byte[] buffer = new byte[1024];
		int bytesRead = await stream.ReadAsync(buffer, cancellationToken);
		return Encoding.ASCII.GetString(buffer, 0, bytesRead).Trim();
	}

	private async Task SendResponseAsync(string response, CancellationToken cancellationToken)
	{
		if (stream == null)
		{
			return;
		}
		byte[] data = Encoding.ASCII.GetBytes(response + "\r\n");
		await stream.WriteAsync(data, cancellationToken);
		await stream.FlushAsync(cancellationToken);
	}
}