forked from Taiizor/Zetian
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmtpRelayClient.cs
More file actions
659 lines (552 loc) · 24 KB
/
SmtpRelayClient.cs
File metadata and controls
659 lines (552 loc) · 24 KB
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Zetian.Abstractions;
using Zetian.Protocol;
using Zetian.Relay.Abstractions;
using Zetian.Relay.Models;
using Zetian.Relay.Services;
namespace Zetian.Relay.Client
{
/// <summary>
/// SMTP client for relaying messages to remote servers
/// </summary>
public class SmtpRelayClient(ILogger<SmtpRelayClient>? logger = null) : ISmtpClient
{
private readonly ILogger<SmtpRelayClient> _logger = logger ?? NullLogger<SmtpRelayClient>.Instance;
private TcpClient? _tcpClient;
private Stream? _stream;
private StreamReader? _reader;
private StreamWriter? _writer;
private bool _disposed;
private Dictionary<string, string>? _serverCapabilities;
public string Host { get; set; } = "localhost";
public int Port { get; set; } = 25;
public bool EnableSsl { get; set; }
public SslProtocols SslProtocols { get; set; } = SslProtocols.Tls12 | SslProtocols.Tls13;
public X509Certificate2? ClientCertificate { get; set; }
public NetworkCredential? Credentials { get; set; }
public string? LocalDomain { get; set; }
public TimeSpan Timeout { get; set; } = TimeSpan.FromMinutes(5);
public bool IsConnected => _tcpClient?.Connected ?? false;
public IReadOnlyDictionary<string, string>? ServerCapabilities => _serverCapabilities;
public async Task ConnectAsync(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
if (IsConnected)
{
_logger.LogWarning("Already connected to {Host}:{Port}", Host, Port);
return;
}
try
{
_logger.LogInformation("Connecting to {Host}:{Port}", Host, Port);
_tcpClient = new TcpClient();
using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(Timeout);
await _tcpClient.ConnectAsync(Host, Port, cts.Token).ConfigureAwait(false);
_stream = _tcpClient.GetStream();
if (EnableSsl)
{
try
{
await UpgradeToSslAsync(cts.Token).ConfigureAwait(false);
}
catch (Exception)
{
_logger.LogInformation("Failed to connect as SMTPS on {Host}:{Port}", Host, Port);
_stream.Close();
await _stream.DisposeAsync();
_tcpClient = new TcpClient();
await _tcpClient.ConnectAsync(Host, Port, cts.Token).ConfigureAwait(false);
_stream = _tcpClient.GetStream();
}
}
_reader = new StreamReader(_stream, Encoding.ASCII);
_writer = new StreamWriter(_stream, Encoding.ASCII) { AutoFlush = true };
// Read greeting
SmtpResponse greeting = await ReadResponseAsync(cts.Token).ConfigureAwait(false);
if (!greeting.IsSuccess)
{
throw new InvalidOperationException($"Server greeting failed: {greeting.Message}");
}
// Send EHLO
await SendEhloAsync(cts.Token).ConfigureAwait(false);
// Upgrade the connection to STARTTLS if allowed
if (EnableSsl && _stream is not SslStream && _serverCapabilities?.ContainsKey("STARTTLS") == true)
{
await UpgradeToStartTlsAsync(cts.Token).ConfigureAwait(false);
_reader = new StreamReader(_stream, Encoding.ASCII);
_writer = new StreamWriter(_stream, Encoding.ASCII) { AutoFlush = true };
}
_logger.LogInformation("Connected to {Host}:{Port}", Host, Port);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to connect to {Host}:{Port}", Host, Port);
Cleanup();
throw;
}
}
public async Task AuthenticateAsync(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
EnsureConnected();
if (Credentials == null)
{
_logger.LogDebug("No credentials provided, skipping authentication");
return;
}
try
{
using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(Timeout);
// Try AUTH PLAIN first
if (_serverCapabilities?.ContainsKey("AUTH") == true &&
_serverCapabilities["AUTH"].Contains("PLAIN", StringComparison.OrdinalIgnoreCase))
{
await AuthPlainAsync(cts.Token).ConfigureAwait(false);
}
// Try AUTH LOGIN
else if (_serverCapabilities?.ContainsKey("AUTH") == true &&
_serverCapabilities["AUTH"].Contains("LOGIN", StringComparison.OrdinalIgnoreCase))
{
await AuthLoginAsync(cts.Token).ConfigureAwait(false);
}
else
{
throw new InvalidOperationException("Server does not support authentication");
}
_logger.LogInformation("Authenticated as {Username}", Credentials.UserName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Authentication failed");
throw;
}
}
public async Task<SmtpDeliveryResult> SendAsync(
ISmtpMessage message,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(message);
List<string> recipients = message.Recipients.Select(r => r.Address).ToList();
return await SendAsync(message, recipients, cancellationToken).ConfigureAwait(false);
}
public async Task<SmtpDeliveryResult> SendAsync(
ISmtpMessage message,
IEnumerable<string> recipients,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(message);
ArgumentNullException.ThrowIfNull(recipients);
string from = message.From?.Address ?? "<>";
byte[] rawData = await message.GetRawDataAsync().ConfigureAwait(false);
return await SendRawAsync(from, recipients, rawData, cancellationToken).ConfigureAwait(false);
}
public async Task<SmtpDeliveryResult> SendRawAsync(
string from,
IEnumerable<string> recipients,
byte[] messageData,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
EnsureConnected();
if (string.IsNullOrWhiteSpace(from))
{
from = "<>";
}
List<string> recipientList = recipients?.ToList() ?? [];
if (recipientList.Count == 0)
{
return SmtpDeliveryResult.CreateFailure("No recipients specified", 550);
}
try
{
using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(Timeout);
// MAIL FROM
await SendCommandAsync($"MAIL FROM:<{from}>", cts.Token).ConfigureAwait(false);
SmtpResponse mailResponse = await ReadResponseAsync(cts.Token).ConfigureAwait(false);
if (!mailResponse.IsSuccess)
{
return SmtpDeliveryResult.CreateFailure(
mailResponse.Message ?? "MAIL FROM rejected",
mailResponse.Code);
}
// RCPT TO for each recipient
List<string> acceptedRecipients = [];
Dictionary<string, string> rejectedRecipients = [];
foreach (string recipient in recipientList)
{
await SendCommandAsync($"RCPT TO:<{recipient}>", cts.Token).ConfigureAwait(false);
SmtpResponse rcptResponse = await ReadResponseAsync(cts.Token).ConfigureAwait(false);
if (rcptResponse.IsSuccess)
{
acceptedRecipients.Add(recipient);
}
else
{
rejectedRecipients[recipient] = rcptResponse.Message ?? "Recipient rejected";
_logger.LogWarning("Recipient {Recipient} rejected: {Message}",
recipient, rcptResponse.Message);
}
}
if (acceptedRecipients.Count == 0)
{
// All recipients rejected, reset and return failure
await ResetAsync(cts.Token).ConfigureAwait(false);
return SmtpDeliveryResult.CreateFailure("All recipients rejected", 550);
}
// DATA
await SendCommandAsync("DATA", cts.Token).ConfigureAwait(false);
SmtpResponse dataResponse = await ReadResponseAsync(cts.Token).ConfigureAwait(false);
if (!dataResponse.IsPositiveIntermediate)
{
await ResetAsync(cts.Token).ConfigureAwait(false);
return SmtpDeliveryResult.CreateFailure(
dataResponse.Message ?? "DATA command rejected",
dataResponse.Code);
}
// Send message data
await SendDataAsync(messageData, cts.Token).ConfigureAwait(false);
// Read final response
SmtpResponse finalResponse = await ReadResponseAsync(cts.Token).ConfigureAwait(false);
if (finalResponse.IsSuccess)
{
// Extract transaction ID if available
string? transactionId = null;
if (!string.IsNullOrEmpty(finalResponse.Message))
{
string[] parts = finalResponse.Message.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 1)
{
transactionId = parts[^1];
}
}
if (rejectedRecipients.Count > 0)
{
// Partial success
return SmtpDeliveryResult.CreatePartial(acceptedRecipients, rejectedRecipients);
}
else
{
// Full success
return SmtpDeliveryResult.CreateSuccess(acceptedRecipients, transactionId);
}
}
else
{
return SmtpDeliveryResult.CreateFailure(
finalResponse.Message ?? "Message rejected",
finalResponse.Code,
finalResponse.IsTransientNegative);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending message");
return SmtpDeliveryResult.CreateFailure(ex.Message, 451, true);
}
}
public async Task<bool> VerifyAsync(string address, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
EnsureConnected();
try
{
using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(Timeout);
await SendCommandAsync($"VRFY {address}", cts.Token).ConfigureAwait(false);
SmtpResponse response = await ReadResponseAsync(cts.Token).ConfigureAwait(false);
return response.IsSuccess;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error verifying address {Address}", address);
return false;
}
}
public async Task NoOpAsync(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
EnsureConnected();
using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(30));
await SendCommandAsync("NOOP", cts.Token).ConfigureAwait(false);
await ReadResponseAsync(cts.Token).ConfigureAwait(false);
}
public async Task ResetAsync(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
EnsureConnected();
using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(30));
await SendCommandAsync("RSET", cts.Token).ConfigureAwait(false);
await ReadResponseAsync(cts.Token).ConfigureAwait(false);
}
public async Task DisconnectAsync(bool quit = true, CancellationToken cancellationToken = default)
{
if (!IsConnected)
{
return;
}
try
{
if (quit && _writer != null)
{
using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(10));
await SendCommandAsync("QUIT", cts.Token).ConfigureAwait(false);
await ReadResponseAsync(cts.Token).ConfigureAwait(false);
}
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Error during disconnect");
}
finally
{
Cleanup();
}
}
private async Task SendEhloAsync(CancellationToken cancellationToken)
{
string domain = LocalDomain ?? Dns.GetHostName();
await SendCommandAsync($"EHLO {domain}", cancellationToken).ConfigureAwait(false);
SmtpResponse response = await ReadMultilineResponseAsync(cancellationToken).ConfigureAwait(false);
if (!response.IsSuccess)
{
// Try HELO if EHLO fails
_logger.LogWarning("EHLO failed, trying HELO");
await SendCommandAsync($"HELO {domain}", cancellationToken).ConfigureAwait(false);
response = await ReadResponseAsync(cancellationToken).ConfigureAwait(false);
if (!response.IsSuccess)
{
throw new InvalidOperationException($"HELO/EHLO failed: {response.Message}");
}
}
else
{
// Parse capabilities from EHLO response
_serverCapabilities = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (string? line in response.Lines.Skip(1))
{
string[] parts = line.Split(' ', 2);
_serverCapabilities[parts[0]] = parts.Length > 1 ? parts[1] : string.Empty;
}
}
}
private async Task UpgradeToSslAsync(CancellationToken cancellationToken)
{
SslStream sslStream = new(_stream, false, ValidateServerCertificate);
await sslStream.AuthenticateAsClientAsync(
Host,
ClientCertificate != null ? [ClientCertificate] : null,
SslProtocols,
true).ConfigureAwait(false);
_stream = sslStream;
_logger.LogDebug("SSL/TLS connection established");
}
private async Task UpgradeToStartTlsAsync(CancellationToken cancellationToken)
{
await SendCommandAsync("STARTTLS", cancellationToken).ConfigureAwait(false);
SmtpResponse response = await ReadResponseAsync(cancellationToken).ConfigureAwait(false);
if (response.IsSuccess)
{
await UpgradeToSslAsync(cancellationToken);
}
}
private async Task AuthPlainAsync(CancellationToken cancellationToken)
{
if (Credentials == null)
{
throw new InvalidOperationException("Credentials not set");
}
string authString = $"\0{Credentials.UserName}\0{Credentials.Password}";
byte[] authBytes = Encoding.ASCII.GetBytes(authString);
string authBase64 = Convert.ToBase64String(authBytes);
await SendCommandAsync($"AUTH PLAIN {authBase64}", cancellationToken).ConfigureAwait(false);
SmtpResponse response = await ReadResponseAsync(cancellationToken).ConfigureAwait(false);
if (!response.IsSuccess)
{
throw new InvalidOperationException($"Authentication failed: {response.Message}");
}
}
private async Task AuthLoginAsync(CancellationToken cancellationToken)
{
if (Credentials == null)
{
throw new InvalidOperationException("Credentials not set");
}
await SendCommandAsync("AUTH LOGIN", cancellationToken).ConfigureAwait(false);
SmtpResponse response = await ReadResponseAsync(cancellationToken).ConfigureAwait(false);
if (!response.IsPositiveIntermediate)
{
throw new InvalidOperationException($"AUTH LOGIN failed: {response.Message}");
}
// Send username
string usernameBase64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(Credentials.UserName));
await SendCommandAsync(usernameBase64, cancellationToken).ConfigureAwait(false);
response = await ReadResponseAsync(cancellationToken).ConfigureAwait(false);
if (!response.IsPositiveIntermediate)
{
throw new InvalidOperationException($"Username rejected: {response.Message}");
}
// Send password
string passwordBase64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(Credentials.Password));
await SendCommandAsync(passwordBase64, cancellationToken).ConfigureAwait(false);
response = await ReadResponseAsync(cancellationToken).ConfigureAwait(false);
if (!response.IsSuccess)
{
throw new InvalidOperationException($"Authentication failed: {response.Message}");
}
}
private async Task SendDataAsync(byte[] data, CancellationToken cancellationToken)
{
using MemoryStream ms = new(data);
using StreamReader reader = new(ms);
string? line;
while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
{
// Apply dot-stuffing
if (line.StartsWith('.'))
{
line = "." + line;
}
await _writer!.WriteLineAsync(line).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
}
// Send terminating sequence
await _writer!.WriteLineAsync(".").ConfigureAwait(false);
await _writer.FlushAsync().ConfigureAwait(false);
}
private async Task SendCommandAsync(string command, CancellationToken cancellationToken)
{
_logger.LogDebug("C: {Command}", command.Contains("AUTH") ? "AUTH ***" : command);
await _writer!.WriteLineAsync(command).ConfigureAwait(false);
await _writer.FlushAsync().ConfigureAwait(false);
}
private async Task<SmtpResponse> ReadResponseAsync(CancellationToken cancellationToken)
{
string? line = await _reader!.ReadLineAsync().ConfigureAwait(false);
if (string.IsNullOrEmpty(line))
{
throw new InvalidOperationException("Empty response from server");
}
_logger.LogDebug("S: {Response}", line);
if (line.Length < 3 || !int.TryParse(line[..3], out int code))
{
throw new InvalidOperationException($"Invalid response format: {line}");
}
string message = line.Length > 4 ? line[4..] : string.Empty;
return new SmtpResponse(code, message);
}
private async Task<SmtpResponse> ReadMultilineResponseAsync(CancellationToken cancellationToken)
{
List<string> lines = [];
int code = 0;
while (true)
{
string? line = await _reader!.ReadLineAsync().ConfigureAwait(false);
if (string.IsNullOrEmpty(line))
{
throw new InvalidOperationException("Empty response from server");
}
_logger.LogDebug("S: {Response}", line);
if (line.Length < 3 || !int.TryParse(line[..3], out int currentCode))
{
throw new InvalidOperationException($"Invalid response format: {line}");
}
if (code == 0)
{
code = currentCode;
}
else if (code != currentCode)
{
throw new InvalidOperationException($"Inconsistent response code: {line}");
}
bool hasMore = line.Length > 3 && line[3] == '-';
string message = line.Length > 4 ? line[4..] : string.Empty;
lines.Add(message);
if (!hasMore)
{
break;
}
}
return new SmtpResponse(code, [.. lines]);
}
private bool ValidateServerCertificate(
object sender,
X509Certificate? certificate,
X509Chain? chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
_logger.LogWarning("SSL certificate validation error: {Errors}", sslPolicyErrors);
// You might want to make this configurable
return false;
}
private void EnsureConnected()
{
if (!IsConnected)
{
throw new InvalidOperationException("Not connected to SMTP server");
}
}
private void ThrowIfDisposed()
{
#if NET6_0
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
#else
ObjectDisposedException.ThrowIf(_disposed, this);
#endif
}
private void Cleanup()
{
_reader?.Dispose();
_writer?.Dispose();
_stream?.Dispose();
_tcpClient?.Dispose();
_reader = null;
_writer = null;
_stream = null;
_tcpClient = null;
_serverCapabilities = null;
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
try
{
DisconnectAsync(false).GetAwaiter().GetResult();
}
catch
{
// Ignore errors during dispose
}
Cleanup();
}
}
}