MailSharp / MailSharp.SMTP / Session / SmtpSession.cs
Code · 241 lines · 9831 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
241using MailSharp.Common;
using MailSharp.SMTP.Extensions;
using MailSharp.SMTP.Metrics;
using MailSharp.SMTP.Server;
using MailSharp.SMTP.Services;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace MailSharp.SMTP.Session;

public enum SmtpState
{
	Initial,
	HeloReceived,
	MailFromReceived,
	RcptToReceived,
	HeaderStarted,
	DataStarted,
	TlsStarted
}

public partial class SmtpSession
{
	private SmtpMetrics metrics;
	private readonly TcpClient client;
	private readonly IConfiguration configuration;
	private readonly SecurityEnum security;
	private readonly ILogger<SmtpSession> logger;
	private readonly long sessionId;
	private SmtpState state;
	private string? mailFrom;
	private readonly List<string> rcptTo = [];
	private readonly StringBuilder data = new();
	private StreamWriter writer;
	private StreamReader reader;
	private Stream stream;
	private readonly Dictionary<string, Func<string[], string, CancellationToken, Task>> commandHandlers = [];
	private static long nextSessionId = 0;
	private IpGroup? ipGroup;
	private readonly DkimSigner dkimSigner;
	private readonly SpfChecker spfChecker;
	private readonly DkimVerifier dkimVerifier;
	private readonly DmarcChecker dmarcChecker;

	public SmtpSession(
		TcpClient client, 
		IConfiguration configuration, 
		SecurityEnum security, 
		DkimSigner dkimSigner, 
		SpfChecker spfChecker,
		DkimVerifier dkimVerifier, 
		DmarcChecker dmarcChecker,
		SmtpMetrics metrics,
		ILogger<SmtpSession> logger)
	{
		this.metrics = metrics;
		this.client = client;
		this.configuration = configuration;
		this.security = security;
		this.dkimSigner = dkimSigner;
		this.spfChecker = spfChecker;
		this.dkimVerifier = dkimVerifier;
		this.dmarcChecker = dmarcChecker;
		this.logger = logger;
		this.sessionId = Interlocked.Increment(ref nextSessionId);
		this.state = security == SecurityEnum.Tls ? SmtpState.TlsStarted : SmtpState.Initial;
		this.stream = client.GetStream();
		if (security == SecurityEnum.Tls)
		{
			string certPath = configuration["SmtpSettings:CertificatePath"] ?? throw new InvalidOperationException("CertificatePath not configured");
			string certPassword = configuration["SmtpSettings:CertificatePassword"] ?? string.Empty;
			X509Certificate2 certificate = X509CertificateLoader.LoadPkcs12FromFile(certPath, certPassword);
			SslStream sslStream = new(stream, false);
			sslStream.AuthenticateAsServer(certificate, false, System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls13, false);
			this.stream = sslStream;
		}
		this.reader = new StreamReader(stream, Encoding.ASCII);
		this.writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true };
		InitializeHandlers();
		using (logger.BeginScope(new Dictionary<string, object> { ["SessionId"] = sessionId }))
		{
			var eventIdConfig = configuration.GetSection("SmtpEventIds:SessionStarted").Get<EventIdConfig>()
				?? throw new InvalidOperationException("Missing SmtpEventIds:SessionStarted");
			logger.LogInformation(new EventId(eventIdConfig.Id, eventIdConfig.Name), configuration["SmtpLogMessages:SessionStarted"], sessionId, client.Client.RemoteEndPoint);
		}

		metrics.IncrementConnections();
		metrics.IncrementActive();
	}

	private void InitializeHandlers()
	{
		commandHandlers.Add("HELO", HandleHeloAsync);
		commandHandlers.Add("EHLO", HandleEhloAsync);
		commandHandlers.Add("MAIL", HandleMailAsync);
		commandHandlers.Add("RCPT", HandleRcptAsync);
		commandHandlers.Add("DATA", HandleDataAsync);
		commandHandlers.Add("QUIT", HandleQuitAsync);
		commandHandlers.Add("NOOP", HandleNoopAsync);
		commandHandlers.Add("RSET", HandleRsetAsync);
		commandHandlers.Add("VRFY", HandleVrfyAsync);
		commandHandlers.Add("EXPN", HandleExpnAsync);
		commandHandlers.Add("HELP", HandleHelpAsync);
		commandHandlers.Add("AUTH", HandleAuthAsync);
		commandHandlers.Add("STARTTLS", HandleStartTlsAsync);
	}

	public Task ProcessAsync(CancellationToken cancellationToken)
	{
		var task = ProcessInternalAsync(cancellationToken);

		// Zorgt dat DecrementActive() ALTIJD wordt aangeroepen, zelfs bij exception of cancel
		_ = task.ContinueWith(
			t => metrics.DecrementActive(),
			TaskScheduler.Default);

		return task; // voor als je ooit wil awaiten (kan geen kwaad)
	}

	public async Task ProcessInternalAsync(CancellationToken cancellationToken)
	{
		using (client)
		using (stream)
		using (reader)
		using (writer)
		{
			var clientEndPoint = (System.Net.IPEndPoint?)client.Client.RemoteEndPoint;
			var groups = configuration.GetSection("IpGroups").Get<List<IpGroup>>() ?? [];
			ipGroup = clientEndPoint != null ? IpGroupMatcher.Match(groups, clientEndPoint.Address) : null;

			if (ipGroup == null || !ipGroup.Access.Smtp)
			{
				await writer.WriteLineAsync("554 No access from your IP address", cancellationToken);
				return;
			}

			var hostname = configuration["SmtpSettings:LocalHostName"]?.Trim();
			if (string.IsNullOrEmpty(hostname)) hostname = System.Net.Dns.GetHostName();
			await writer.WriteLineAsync($"220 {hostname} ESMTP", cancellationToken);
			int timeoutSeconds = configuration.GetValue<int>("SmtpSettings:CommandTimeoutSeconds");

			using (logger.BeginScope(new Dictionary<string, object> { ["SessionId"] = sessionId }))
			{
				while (client.Connected && !cancellationToken.IsCancellationRequested)
				{
					using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));
					using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token);

					EventIdConfig eventIdConfig;
					try
					{
						string? line = await reader.ReadLineAsync(linkedCts.Token);
						if (line == null)
						{
							eventIdConfig = configuration.GetSection("SmtpEventIds:ClientDisconnected").Get<EventIdConfig>()
								?? throw new InvalidOperationException("Missing SmtpEventIds:ClientDisconnected");
							logger.LogWarning(new EventId(eventIdConfig.Id, eventIdConfig.Name), configuration["SmtpLogMessages:ClientDisconnected"], sessionId);
							return;
						}

						if (state == SmtpState.HeaderStarted)
						{
							data.AppendLine(line);

							if (line == string.Empty)
							{
								eventIdConfig = configuration.GetSection("SmtpEventIds:HeaderEnd").Get<EventIdConfig>()
									?? throw new InvalidOperationException("Missing SmtpEventIds:HeaderEnd");
								logger.LogInformation(new EventId(eventIdConfig.Id, eventIdConfig.Name), configuration["SmtpLogMessages:HeaderEnd"], sessionId);

								await HandleHeaderEndAsync([], line, linkedCts.Token);
							}
							continue;
						}

						if (state == SmtpState.DataStarted)
						{
							if (line == ".")
							{
								eventIdConfig = configuration.GetSection("SmtpEventIds:DataEnd").Get<EventIdConfig>()
									?? throw new InvalidOperationException("Missing SmtpEventIds:DataEnd");
								logger.LogInformation(new EventId(eventIdConfig.Id, eventIdConfig.Name), configuration["SmtpLogMessages:DataEnd"], sessionId);

								await HandleDataEndAsync([], line, linkedCts.Token);
							}
							else
								data.AppendLine(line);
							continue;
						}

						string[] parts = line.Split(' ');
						string command = parts[0].ToUpper();
						eventIdConfig = configuration.GetSection("SmtpEventIds:CommandReceived").Get<EventIdConfig>()
							?? throw new InvalidOperationException("Missing SmtpEventIds:CommandReceived");

						logger.LogInformation(new EventId(eventIdConfig.Id, eventIdConfig.Name), configuration["SmtpLogMessages:CommandReceived"], command, sessionId);

						if (commandHandlers.TryGetValue(command, out var handler))
						{
							await handler(parts, line, linkedCts.Token);
							if (command == "QUIT")
							{
								eventIdConfig = configuration.GetSection("SmtpEventIds:SessionEndedByQuit").Get<EventIdConfig>()
									?? throw new InvalidOperationException("Missing SmtpEventIds:SessionEndedByQuit");
								logger.LogInformation(new EventId(eventIdConfig.Id, eventIdConfig.Name), configuration["SmtpLogMessages:SessionEndedByQuit"], sessionId);
								return;
							}
						}
						else
						{
							await writer.WriteLineAsync(configuration["SmtpResponses:CommandNotRecognized"], linkedCts.Token);
							eventIdConfig = configuration.GetSection("SmtpEventIds:UnrecognizedCommand").Get<EventIdConfig>()
								?? throw new InvalidOperationException("Missing SmtpEventIds:UnrecognizedCommand");
							logger.LogWarning(new EventId(eventIdConfig.Id, eventIdConfig.Name), configuration["SmtpLogMessages:UnrecognizedCommand"], command, sessionId);
						}
					}
					catch (OperationCanceledException)
					{
						await writer.WriteLineAsync(timeoutCts.Token.IsCancellationRequested
							? configuration["SmtpResponses:Timeout"]
							: configuration["SmtpResponses:Shutdown"], linkedCts.Token);
						eventIdConfig = configuration.GetSection("SmtpEventIds:SessionTerminated").Get<EventIdConfig>()
							?? throw new InvalidOperationException("Missing SmtpEventIds:SessionTerminated");
						logger.LogWarning(new EventId(eventIdConfig.Id, eventIdConfig.Name), configuration["SmtpLogMessages:SessionTerminated"],
							timeoutCts.Token.IsCancellationRequested ? "timeout" : "shutdown", sessionId);
						return;
					}
					catch (Exception ex)
					{
						eventIdConfig = configuration.GetSection("SmtpEventIds:CommandProcessingError").Get<EventIdConfig>()
							?? throw new InvalidOperationException("Missing SmtpEventIds:CommandProcessingError");
						logger.LogError(new EventId(eventIdConfig.Id, eventIdConfig.Name), ex, configuration["SmtpLogMessages:CommandProcessingError"], sessionId);
						await writer.WriteLineAsync(configuration["SmtpResponses:CommandNotRecognized"], linkedCts.Token);
					}
				}
			}
		}
	}
}