init
This commit is contained in:
commit
dfa2fe0de4
14 changed files with 1483 additions and 0 deletions
71
src/smtprelay/Smtp/SmtpServer.cs
Normal file
71
src/smtprelay/Smtp/SmtpServer.cs
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace SmtpRelay;
|
||||
|
||||
public class SmtpServer(IServiceScopeFactory scopeFactory, ILogger<SmtpServer> logger)
|
||||
{
|
||||
private readonly ILogger<SmtpServer> _logger = logger;
|
||||
private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
|
||||
|
||||
public bool IsRunning { get; private set; } = false;
|
||||
|
||||
public async Task RunAsync(SmtpConfig config, CancellationToken cancellationToken)
|
||||
{
|
||||
if (IsRunning)
|
||||
return;
|
||||
|
||||
var ep = new IPEndPoint(IPAddress.Parse(config.Host), config.Port);
|
||||
|
||||
// start listener
|
||||
using var listener = new TcpListener(ep);
|
||||
listener.Start();
|
||||
|
||||
cancellationToken.Register(listener.Stop);
|
||||
|
||||
// set listener state
|
||||
IsRunning = true;
|
||||
|
||||
// log
|
||||
_logger.LogInformation("SMTP listening on {HOST}:{PORT}", config.Host, config.Port);
|
||||
|
||||
// handler loop
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
// await new client
|
||||
var client = await listener.AcceptTcpClientAsync(cancellationToken);
|
||||
|
||||
// handle client async
|
||||
_ = HandleClientAsync(client, config, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
// set listener state
|
||||
IsRunning = false;
|
||||
}
|
||||
|
||||
private async Task HandleClientAsync(TcpClient client, SmtpConfig config, CancellationToken cancellationToken)
|
||||
{
|
||||
// create session
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var session = scope.ServiceProvider.GetRequiredService<SmtpSession>();
|
||||
|
||||
try
|
||||
{
|
||||
await session.InitAsync(client.Client, config, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
client?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue