Files
amiga/Mail-TLS-Bridge/MailTlsBridge.cs
T

101 lines
3.8 KiB
C#

using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Threading;
using System.Threading.Tasks;
internal static class MailTlsBridge
{
const int LocalPort = 1465;
const string RemoteHost = "smtp.gmail.com";
const int RemotePort = 465;
static readonly object LogLock = new object();
static readonly string LogPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bridge.log");
static readonly SemaphoreSlim Slots = new SemaphoreSlim(4);
static int ConnectionId;
static void Log(string message)
{
lock (LogLock)
{
try
{
if (File.Exists(LogPath) && new FileInfo(LogPath).Length > 262144)
File.Move(LogPath, LogPath + "." + DateTime.UtcNow.ToString("yyyyMMddHHmmss") + ".old");
File.AppendAllText(LogPath, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss zzz") + " " + message + Environment.NewLine);
}
catch { }
}
}
static void Main()
{
bool created;
using (var mutex = new Mutex(true, "Local\\TilaroMailTlsBridge1465", out created))
{
if (!created) return;
try { Run().GetAwaiter().GetResult(); }
catch (Exception ex) { Log("STOP " + ex.Message); }
}
}
static async Task Run()
{
var listener = new TcpListener(IPAddress.Loopback, LocalPort);
listener.Start(8);
Log("START 127.0.0.1:" + LocalPort + " -> " + RemoteHost + ":" + RemotePort + " TLS; certificate validation enabled");
try
{
while (true)
{
var client = await listener.AcceptTcpClientAsync();
if (!Slots.Wait(0)) { client.Close(); continue; }
Handle(client);
}
}
finally { listener.Stop(); }
}
static async void Handle(TcpClient client)
{
int id = Interlocked.Increment(ref ConnectionId);
try
{
using (client)
using (var remote = new TcpClient())
{
client.NoDelay = true;
remote.NoDelay = true;
var connect = remote.ConnectAsync(RemoteHost, RemotePort);
if (await Task.WhenAny(connect, Task.Delay(15000)) != connect)
throw new TimeoutException("Remote TCP connection timed out");
await connect;
using (var tls = new SslStream(remote.GetStream(), false))
{
// The default validation checks both trust and the target hostname.
var authenticate = tls.AuthenticateAsClientAsync(RemoteHost, null, SslProtocols.Tls12, true);
if (await Task.WhenAny(authenticate, Task.Delay(20000)) != authenticate)
throw new TimeoutException("TLS handshake timed out");
await authenticate;
Log("CONNECTED #" + id + " TLS=" + tls.SslProtocol + " certificate=" + tls.RemoteCertificate.Subject);
var local = client.GetStream();
var upstream = local.CopyToAsync(tls);
var downstream = tls.CopyToAsync(local);
var finished = await Task.WhenAny(upstream, downstream);
client.Close();
remote.Close();
try { await finished; } catch (IOException) { }
try { await upstream; } catch { }
try { await downstream; } catch { }
}
}
Log("CLOSED #" + id);
}
catch (Exception ex) { Log("ERROR #" + id + " " + ex.GetBaseException().Message); }
finally { client.Dispose(); Slots.Release(); }
}
}