Cleaned & Modernized SMTPProxy.cs to add extra error catching.

This commit is contained in:
2026-08-17 10:32:08 +10:00
parent 44e40c7846
commit 67ea57cd9e

View File

@@ -14,26 +14,18 @@ using System.Text.RegularExpressions;
using System.Threading;
using Newtonsoft.Json.Linq;
namespace smtpproxy.net;
namespace smtpproxy.net
{
public class SMTPProxy : ServiceBase
{
private ConcurrentQueue<Email> EmailQueue;
private ManualResetEvent mre;
private bool bRunning;
private Thread Sending;
private Thread Listening;
private long ThreadCount;
private bool ConsoleMode;
private static readonly object _syncObject = new object();
private IContainer components;
public SMTPProxy()
@@ -42,25 +34,25 @@ public class SMTPProxy : ServiceBase
base.ServiceName = "SMTPProxy.net";
ConsoleMode = false;
EmailQueue = new ConcurrentQueue<Email>();
mre = new ManualResetEvent(initialState: false);
mre = new ManualResetEvent(false);
bRunning = true;
ThreadCount = 0L;
}
protected override void OnStart(string[] args)
{
Listening = new Thread(StartListening);
Listening = new Thread(StartListening) { IsBackground = true };
Listening.Start();
Sending = new Thread(StartSending);
Sending = new Thread(StartSending) { IsBackground = true };
Sending.Start();
}
public void Start()
{
ConsoleMode = true;
Listening = new Thread(StartListening);
Listening = new Thread(StartListening) { IsBackground = true };
Listening.Start();
Sending = new Thread(StartSending);
Sending = new Thread(StartSending) { IsBackground = true };
Sending.Start();
}
@@ -70,24 +62,41 @@ public class SMTPProxy : ServiceBase
mre.Set();
}
public void Reload(string Folder)
public void Reload(string folder)
{
foreach (string item in Directory.EnumerateFiles(Folder, "*.eml").ToList())
if (!Directory.Exists(folder)) return;
foreach (string item in Directory.EnumerateFiles(folder, "*.eml"))
{
Email email = new Email();
email.sDATA = File.ReadAllText(item);
email.sHELO = File.ReadAllText(item.Replace(".eml", ".HELO"));
email.sMAIL = File.ReadAllText(item.Replace(".eml", ".MAIL"));
foreach (string item2 in File.ReadAllLines(item.Replace(".eml", ".RCPTS")).ToList())
try
{
if (item2.Length > 0)
Email email = new Email
{
email.sRCPTs.Add(item2 + "\r\n");
sDATA = File.ReadAllText(item),
sHELO = File.Exists(item.Replace(".eml", ".HELO")) ? File.ReadAllText(item.Replace(".eml", ".HELO")) : "HELO localhost\r\n",
sMAIL = File.Exists(item.Replace(".eml", ".MAIL")) ? File.ReadAllText(item.Replace(".eml", ".MAIL")) : "",
FromIP = "127.0.0.1"
};
string rcptFile = item.Replace(".eml", ".RCPTS");
if (File.Exists(rcptFile))
{
foreach (string rcpt in File.ReadAllLines(rcptFile))
{
if (!string.IsNullOrWhiteSpace(rcpt))
{
email.sRCPTs.Add(rcpt.Trim() + "\r\n");
}
}
email.FromIP = "127.0.0.1";
}
EmailQueue.Enqueue(email);
}
catch (Exception ex)
{
Log($"Failed to reload email file {item}: {ex.Message}");
}
}
SendQueuedEmails();
}
@@ -101,457 +110,561 @@ public class SMTPProxy : ServiceBase
public void StartListening()
{
Dns.GetHostEntry(Dns.GetHostName());
IPAddress iPAddress = IPAddress.Parse(ConfigurationManager.AppSettings["ListeningAddress"]);
IPEndPoint localEP = new IPEndPoint(iPAddress, 25);
Socket socket = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Log("Started Listening on port 25 at " + iPAddress.ToString());
try
{
string listenSetting = ConfigurationManager.AppSettings["ListeningAddress"] ?? "0.0.0.0";
IPAddress ipAddress = IPAddress.Parse(listenSetting);
IPEndPoint localEP = new IPEndPoint(ipAddress, 25);
Socket socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(localEP);
socket.Listen(100);
while (true)
Log($"Started Listening on port 25 at {ipAddress}");
while (bRunning)
{
try
{
Socket socket2 = socket.Accept();
if (socket2.Connected)
Socket clientSocket = socket.Accept();
if (clientSocket.Connected)
{
Log("New Connection:" + DateTime.Now.ToString("G", CultureInfo.CreateSpecificCulture("en-AU")));
ThreadPool.QueueUserWorkItem(ProcessMailClient, socket2);
Log($"New Connection: {DateTime.Now.ToString("G", CultureInfo.CreateSpecificCulture("en-AU"))}");
ThreadPool.QueueUserWorkItem(ProcessMailClient, clientSocket);
}
}
catch (SocketException ex)
{
Log($"SocketException : {ex.ToString()}");
if (!bRunning) break;
Log($"SocketException accepting client: {ex.Message}");
}
catch (Exception ex2)
catch (Exception ex)
{
Log($"Unexpected exception : {ex2.ToString()}");
Log($"Unexpected exception accepting client: {ex.Message}");
}
}
}
catch (Exception ex)
{
Log($"Fatal listening error: {ex}");
}
}
private void ProcessMailClient(object stateinfo)
private void ProcessMailClient(object stateInfo)
{
Socket socket = (Socket)stateinfo;
Socket socket = (Socket)stateInfo;
socket.ReceiveTimeout = 180000;
socket.SendTimeout = 180000;
byte[] bytes = Encoding.ASCII.GetBytes("220 Connected to SBC SMTPProxy.net\r\n");
socket.Send(bytes);
IPEndPoint iPEndPoint = socket.RemoteEndPoint as IPEndPoint;
string text = ConfigurationManager.AppSettings["LogFolder"] + "in";
Directory.CreateDirectory(text);
string logFileName = $"{text}\\{Guid.NewGuid()}_{iPEndPoint.Address}.log";
Log("New Client Connected from " + iPEndPoint.Address, logFileName);
new List<Email>();
List<string> list = new List<string>();
byte[] array = new byte[2000];
StringBuilder stringBuilder = new StringBuilder();
string text2 = "";
string text3 = "";
string text4 = "";
string text5 = "";
string text6 = "";
int num = 0;
bool flag = false;
do
{
IPEndPoint remoteEndPoint = socket.RemoteEndPoint as IPEndPoint;
string clientIp = remoteEndPoint?.Address.ToString() ?? "0.0.0.0";
string logDir = Path.Combine(ConfigurationManager.AppSettings["LogFolder"] ?? "C:\\Logs\\", "in");
Directory.CreateDirectory(logDir);
string logFileName = Path.Combine(logDir, $"{Guid.NewGuid()}_{clientIp}.log");
Log($"New Client Connected from {clientIp}", logFileName);
byte[] welcome = Encoding.ASCII.GetBytes("220 Connected to SBC SMTPProxy.net\r\n");
socket.Send(welcome);
List<string> rcptList = new List<string>();
byte[] buffer = new byte[4096];
StringBuilder commandBuffer = new StringBuilder();
string heloHeader = "";
string mailFrom = "";
string dataBody = "";
bool receivingData = false;
try
{
num = socket.Receive(array, 1999, SocketFlags.None);
if (num > 0)
while (socket.Connected)
{
array[num] = 0;
string text7 = Encoding.Default.GetString(array, 0, num);
text3 = text2 + text7;
text2 = text7;
stringBuilder.Append(text7);
if (num == 1999 || !text3.Contains("\r\n"))
int bytesRead = socket.Receive(buffer, SocketFlags.None);
if (bytesRead == 0)
{
Log("Client disconnected gracefully.", logFileName);
break;
}
string chunk = Encoding.Default.GetString(buffer, 0, bytesRead);
commandBuffer.Append(chunk);
if (receivingData)
{
dataBody += chunk;
if (dataBody.EndsWith("\r\n.\r\n") || dataBody == ".\r\n")
{
receivingData = false;
Email email = new Email
{
sHELO = heloHeader,
sMAIL = mailFrom,
sRCPTs = new List<string>(rcptList),
sDATA = dataBody,
FromIP = clientIp
};
EmailQueue.Enqueue(email);
Log("Queued inbound message.", logFileName);
mailFrom = "";
dataBody = "";
rcptList.Clear();
commandBuffer.Clear();
byte[] okBytes = Encoding.ASCII.GetBytes("250 OK\r\n");
socket.Send(okBytes);
Log("250 OK", logFileName);
}
continue;
}
// Process complete commands ending in newline
string fullBuffer = commandBuffer.ToString();
if (!fullBuffer.Contains("\r\n"))
{
continue;
}
string text8 = stringBuilder.ToString();
string text9 = ((text8.Length < 4) ? text8 : text8.Substring(0, 4));
string text10 = "500 Invalid Command\r\n";
bool flag2 = false;
if (flag)
string[] lines = fullBuffer.Split(new[] { "\r\n" }, StringSplitOptions.None);
// Keep uncompleted line in buffer
commandBuffer.Clear();
commandBuffer.Append(lines[lines.Length - 1]);
for (int i = 0; i < lines.Length - 1; i++)
{
text6 += text8;
if (text8 == ".\r\n" || text8.Contains("\r\n.\r\n"))
{
flag = false;
text10 = "250 OK\r\n";
Email email = new Email();
email.sHELO = text4;
email.sMAIL = text5;
email.sRCPTs = new List<string>(list);
email.sDATA = text6;
email.FromIP = iPEndPoint.Address.ToString();
EmailQueue.Enqueue(email);
text5 = (text6 = "");
list.Clear();
}
}
else
{
switch (text9)
string line = lines[i].Trim();
if (string.IsNullOrEmpty(line)) continue;
string verb = line.Length >= 4 ? line.Substring(0, 4).ToUpperInvariant() : line.ToUpperInvariant();
string response = "500 Invalid Command\r\n";
switch (verb)
{
case "HELO":
case "EHLO":
text4 = stringBuilder.ToString();
text10 = "250 Hi\r\n";
heloHeader = line + "\r\n";
response = "250 Hi\r\n";
break;
case "MAIL":
if (text4.Length == 0)
if (string.IsNullOrEmpty(heloHeader))
{
text10 = "503 Do HELO first\r\n";
break;
response = "503 Do HELO first\r\n";
}
if (text5.Length > 0)
else if (!string.IsNullOrEmpty(mailFrom))
{
text10 = "503 Already have MAIL\r\n";
break;
response = "503 Already have MAIL\r\n";
}
else
{
mailFrom = line + "\r\n";
response = "250 MAIL command recorded\r\n";
}
text5 = stringBuilder.ToString();
text10 = "250 MAIL command recorded\r\n";
break;
case "RCPT":
if (text4.Length == 0)
if (string.IsNullOrEmpty(heloHeader))
{
text10 = "503 Do HELO first\r\n";
break;
response = "503 Do HELO first\r\n";
}
if (text5.Length == 0)
else if (string.IsNullOrEmpty(mailFrom))
{
text10 = "503 Do MAIL first\r\n";
break;
response = "503 Do MAIL first\r\n";
}
else
{
rcptList.Add(line + "\r\n");
response = "250 RCPT command recorded\r\n";
}
list.Add(stringBuilder.ToString());
text10 = "250 RCPT command recorded\r\n";
break;
case "DATA":
if (text4.Length == 0)
if (string.IsNullOrEmpty(heloHeader))
{
text10 = "503 Do HELO first\r\n";
response = "503 Do HELO first\r\n";
}
else if (text5.Length == 0)
else if (string.IsNullOrEmpty(mailFrom))
{
text10 = "503 Do MAIL first\r\n";
response = "503 Do MAIL first\r\n";
}
else if (list.Count == 0)
else if (rcptList.Count == 0)
{
text10 = "503 Do RCPT first\r\n";
response = "503 Do RCPT first\r\n";
}
else
{
response = "354 Start mail input; end with <CRLF>.<CRLF>\r\n";
receivingData = true;
dataBody = "";
}
text10 = "354 DATA\r\n";
flag2 = true;
break;
case "RSET":
text10 = "250 OK\r\n";
text5 = (text6 = "");
list.Clear();
response = "250 OK\r\n";
mailFrom = "";
dataBody = "";
rcptList.Clear();
break;
case "QUIT":
byte[] quitBytes = Encoding.ASCII.GetBytes("221 Bye\r\n");
socket.Send(quitBytes);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
num = 0;
goto end_IL_00ed;
return;
default:
Log("Unknown:" + text9, logFileName);
Log($"Unknown command: {line}", logFileName);
break;
}
byte[] respBytes = Encoding.ASCII.GetBytes(response);
socket.Send(respBytes);
Log(response.TrimEnd(), logFileName);
}
if (!flag)
}
}
catch (Exception ex)
{
byte[] bytes2 = Encoding.ASCII.GetBytes(text10);
socket.Send(bytes2);
Log(text10, logFileName);
Log($"Session exception: {ex.Message}", logFileName);
}
if (flag2)
finally
{
flag = true;
}
stringBuilder.Clear();
array[0] = 0;
continue;
}
if (num == 0)
try
{
if (socket.Connected)
{
Log("Client disconnected.", logFileName);
continue;
}
Log("Client reset the connection.", logFileName);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
num = 0;
end_IL_00ed:;
}
catch (SocketException ex)
{
Log($"SocketException : {ex.ToString()}", logFileName);
num = 0;
}
catch (Exception ex2)
{
Log($"Unexpected exception : {ex2.ToString()}", logFileName);
num = 0;
}
}
while (socket.Connected && num > 0);
if (EmailQueue.Count > 5 && Interlocked.Read(ref ThreadCount) < Convert.ToUInt32(ConfigurationManager.AppSettings["ThreadMax"]))
catch { }
}
// Trigger worker threads if backlog grows
int threadMax = int.TryParse(ConfigurationManager.AppSettings["ThreadMax"], out var tm) ? tm : 5;
if (EmailQueue.Count > 5 && Interlocked.Read(ref ThreadCount) < threadMax)
{
Interlocked.Increment(ref ThreadCount);
SendQueuedEmails();
Interlocked.Decrement(ref ThreadCount);
ThreadPool.QueueUserWorkItem(state =>
{
try { SendQueuedEmails(); }
finally { Interlocked.Decrement(ref ThreadCount); }
});
}
}
private void Log(string info, string LogFileName = null)
private void Log(string info, string logFileName = null)
{
if (ConsoleMode)
{
Console.WriteLine(info.Replace("\r\n", ""));
Console.WriteLine(info?.Replace("\r\n", ""));
}
if (!string.IsNullOrEmpty(LogFileName))
if (!string.IsNullOrEmpty(logFileName))
{
using (StreamWriter streamWriter = File.AppendText(LogFileName))
try
{
streamWriter.WriteLine("{0}", info);
streamWriter.Flush();
using (StreamWriter sw = File.AppendText(logFileName))
{
sw.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {info}");
}
return;
}
catch { }
}
lock (_syncObject)
{
DateTime now = DateTime.Now;
using StreamWriter streamWriter2 = File.AppendText(string.Format("{0}\\{1:00}{2:00}{3:00}.log", ConfigurationManager.AppSettings["LogFolder"] + "in", now.Year, now.Month, now.Day));
streamWriter2.WriteLine("{0}", info);
streamWriter2.Flush();
try
{
string logDir = Path.Combine(ConfigurationManager.AppSettings["LogFolder"] ?? "C:\\Logs\\", "in");
Directory.CreateDirectory(logDir);
string path = Path.Combine(logDir, $"{DateTime.Now:yyyyMMdd}.log");
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {info}");
}
}
catch { }
}
}
private void SendQueuedEmails()
{
JToken val2 = default(JToken);
while (!EmailQueue.IsEmpty)
string profilesBase = ConfigurationManager.AppSettings["Profiles"] ?? "C:\\Profiles\\";
while (EmailQueue.TryDequeue(out Email email))
{
if (!EmailQueue.TryDequeue(out var result))
string cleanSender = email.sMAIL
.Replace(" ", "")
.Replace("MAILFROM:", "")
.Replace("<", "")
.Replace(">", "")
.Replace("\r", "")
.Replace("\n", "");
string profilePath = Path.Combine(profilesBase, email.FromIP, $"{cleanSender}.json");
if (!File.Exists(profilePath))
{
int atIndex = cleanSender.IndexOf('@');
string domain = atIndex >= 0 ? cleanSender.Substring(atIndex + 1) : "";
profilePath = Path.Combine(profilesBase, email.FromIP, $"default@{domain}.json");
if (!File.Exists(profilePath))
{
profilePath = Path.Combine(profilesBase, email.FromIP, "default.json");
}
}
if (!File.Exists(profilePath))
{
Log($"No configuration profile found for IP {email.FromIP} and sender {cleanSender}");
continue;
}
string sMAIL = result.sMAIL;
sMAIL = sMAIL.Replace(" ", "");
sMAIL = sMAIL.Replace("MAILFROM:", "");
sMAIL = sMAIL.Replace("<", "");
sMAIL = sMAIL.Replace(">", "");
sMAIL = sMAIL.Replace("\r", "");
sMAIL = sMAIL.Replace("\n", "");
string path = ConfigurationManager.AppSettings["Profiles"] + result.FromIP + "\\" + sMAIL + ".json";
if (!File.Exists(path))
{
int num = sMAIL.IndexOf('@');
string text = sMAIL.Substring(num + 1);
path = ConfigurationManager.AppSettings["Profiles"] + result.FromIP + "\\default@" + text + ".json";
if (!File.Exists(path))
{
path = ConfigurationManager.AppSettings["Profiles"] + result.FromIP + "\\default.json";
}
}
JObject val;
JObject config;
try
{
val = JObject.Parse(File.ReadAllText(path));
config = JObject.Parse(File.ReadAllText(profilePath));
}
catch (Exception ex)
{
Log(ex.Message);
Log($"Error parsing JSON profile at {profilePath}: {ex.Message}");
continue;
}
int num2 = Convert.ToInt32(val["logging"][(object)"enabled"]);
bool bHideRecipients = Convert.ToInt32(val["HideRecipients"]) == 1;
bool num3 = num2 == 1;
string text2 = "";
string text3 = ((object)val["logging"][(object)"path"]).ToString() + "\\log";
Directory.CreateDirectory(text3);
bool loggingEnabled = config["logging"]?["enabled"]?.Value<int>() == 1;
string logBasePath = config["logging"]?["path"]?.ToString() ?? "C:\\Logs\\";
bool hideRecipients = config["HideRecipients"]?.Value<int>() == 1;
string logDir = Path.Combine(logBasePath, "log");
string outDir = Path.Combine(logBasePath, "out");
Directory.CreateDirectory(logDir);
Directory.CreateDirectory(outDir);
Guid guid = Guid.NewGuid();
string recipientEmail = result.GetRecipientEmail(result.sRCPTs[0]);
text2 = $"{text3}\\{recipientEmail}.{guid}.log";
string text4 = ((object)val["logging"][(object)"path"]).ToString() + "\\out";
Directory.CreateDirectory(text4);
if (num3)
string primaryRcpt = email.sRCPTs.Count > 0 ? email.GetRecipientEmail(email.sRCPTs[0]) : "unknown";
string mailLogPath = Path.Combine(logDir, $"{primaryRcpt}.{guid}.log");
if (loggingEnabled)
{
File.WriteAllText($"{text4}\\{recipientEmail}.{guid}.eml", result.sDATA);
File.WriteAllText($"{text4}\\{recipientEmail}.{guid}.HELO", result.sHELO);
File.WriteAllText($"{text4}\\{recipientEmail}.{guid}.MAIL", result.sMAIL);
File.WriteAllLines($"{text4}\\{recipientEmail}.{guid}.RCPTS", result.sRCPTs);
File.WriteAllText(Path.Combine(outDir, $"{primaryRcpt}.{guid}.eml"), email.sDATA);
File.WriteAllText(Path.Combine(outDir, $"{primaryRcpt}.{guid}.HELO"), email.sHELO);
File.WriteAllText(Path.Combine(outDir, $"{primaryRcpt}.{guid}.MAIL"), email.sMAIL);
File.WriteAllLines(Path.Combine(outDir, $"{primaryRcpt}.{guid}.RCPTS"), email.sRCPTs);
}
IPAddress iPAddress = Dns.GetHostEntry(((object)val["smtpserver"]).ToString()).AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(iPAddress, Convert.ToInt32(((object)val["smtpserverport"]).ToString()));
int num4 = Convert.ToInt32(val["recipientreplacement"][(object)"enabled"]);
List<string> list = val["recipientreplacement"][(object)"replacements"].ToObject<List<string>>();
int num5 = Convert.ToInt32(val["recipientfilter"][(object)"enabled"]);
List<string> list2 = val["recipientfilter"][(object)"whitelist"].ToObject<List<string>>();
bool flag = false;
List<string> list3 = null;
if (val.TryGetValue("bcc", ref val2))
string smtpHost = config["smtpserver"]?.ToString();
int smtpPort = config["smtpserverport"]?.Value<int>() ?? 25;
if (string.IsNullOrEmpty(smtpHost))
{
flag = Extensions.Value<int>((IEnumerable<JToken>)val2[(object)"enabled"]) == 1;
list3 = val2[(object)"recipients"].ToObject<List<string>>();
Log("Missing smtpserver target in configuration profile.", mailLogPath);
continue;
}
Socket socket = null;
bool flag2 = num4 == 1;
bool flag3 = num5 == 1;
bool replaceRecipients = config["recipientreplacement"]?["enabled"]?.Value<int>() == 1;
List<string> replacementList = config["recipientreplacement"]?["replacements"]?.ToObject<List<string>>() ?? new List<string>();
bool filterRecipients = config["recipientfilter"]?["enabled"]?.Value<int>() == 1;
List<string> whitelist = config["recipientfilter"]?["whitelist"]?.ToObject<List<string>>() ?? new List<string>();
bool bccEnabled = config["bcc"]?["enabled"]?.Value<int>() == 1;
List<string> bccRecipients = config["bcc"]?["recipients"]?.ToObject<List<string>>() ?? new List<string>();
Socket relaySocket = null;
try
{
socket = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(remoteEP);
if (!CheckAndSend("220", result.sHELO, socket, text2) || !CheckAndSend("250", result.sMAIL, socket, text2))
IPAddress targetIp;
if (!IPAddress.TryParse(smtpHost, out targetIp))
{
var hostEntry = Dns.GetHostEntry(smtpHost);
targetIp = hostEntry.AddressList.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork) ?? hostEntry.AddressList[0];
}
relaySocket = new Socket(targetIp.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
relaySocket.ReceiveTimeout = 60000;
relaySocket.SendTimeout = 60000;
relaySocket.Connect(new IPEndPoint(targetIp, smtpPort));
if (!CheckAndSend("220", email.sHELO, relaySocket, mailLogPath) ||
!CheckAndSend("250", email.sMAIL, relaySocket, mailLogPath))
{
continue;
}
if (flag2)
bool hasValidRecipients = false;
if (replaceRecipients)
{
foreach (string item in list)
foreach (string rep in replacementList)
{
string nextCommand = $"RCPT TO: {item}\r\n";
CheckAndSend("250", nextCommand, socket, text2);
if (CheckAndSend("250", $"RCPT TO: <{rep}>\r\n", relaySocket, mailLogPath))
{
hasValidRecipients = true;
}
goto IL_053d;
}
int num6 = 0;
foreach (string sRCPT in result.sRCPTs)
}
else
{
if (sRCPT.Length < 8)
foreach (string rcptLine in email.sRCPTs)
{
if (rcptLine.Trim().Length < 8) continue;
if (filterRecipients)
{
string extractedEmail = email.GetRecipientEmail(rcptLine);
if (!whitelist.Any(w => w.Equals(extractedEmail, StringComparison.OrdinalIgnoreCase)))
{
Log($"Filtering recipient: {extractedEmail}", mailLogPath);
continue;
}
if (flag3)
Log($"Recipient approved by whitelist: {extractedEmail}", mailLogPath);
}
if (CheckAndSend("250", rcptLine, relaySocket, mailLogPath))
{
string r = result.GetRecipientEmail(sRCPT);
if (!list2.Exists((string prd) => prd.Equals(r)))
hasValidRecipients = true;
}
}
}
if (!hasValidRecipients)
{
Log("Filtering Recipient " + r, text2);
Log("No valid recipients accepted by upstream relay. Aborting.", mailLogPath);
continue;
}
Log("Recipient " + r + " OK", text2);
}
if (CheckAndSend("250", sRCPT, socket, text2))
if (bccEnabled)
{
num6++;
}
}
if (num6 != 0)
foreach (string bcc in bccRecipients)
{
goto IL_053d;
CheckAndSend("250", $"RCPT TO: <{bcc}>\r\n", relaySocket, mailLogPath);
}
Log("No Valid recipients, aborting", text2);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
goto end_IL_03a8;
IL_053d:
if (flag)
}
if (CheckAndSend("250", "DATA\r\n", relaySocket, mailLogPath))
{
foreach (string item2 in list3)
string cleansedData = CleanseDataBlock(email.sDATA, hideRecipients);
if (!cleansedData.EndsWith("\r\n")) cleansedData += "\r\n";
if (!cleansedData.EndsWith("\r\n.\r\n")) cleansedData += ".\r\n";
if (CheckAndSend("354", cleansedData, relaySocket, mailLogPath))
{
string nextCommand2 = $"RCPT TO: {item2}\r\n";
CheckAndSend("250", nextCommand2, socket, text2);
CheckAndSend("250", "RSET\r\n", relaySocket, mailLogPath);
CheckAndSend("250", "QUIT\r\n", relaySocket, mailLogPath);
}
}
if (CheckAndSend("250", "DATA\r\n", socket, text2) && CheckAndSend("354", CleanseDataBlock(result.sDATA, bHideRecipients), socket, text2) && CheckAndSend("250", "RSET\r\n", socket, text2) && CheckAndSend("250", "QUIT\r\n", socket, text2))
}
catch (Exception ex)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
Log($"Upstream relay transmission failed: {ex.Message}", mailLogPath);
}
end_IL_03a8:;
}
catch (ArgumentNullException ex2)
finally
{
Log($"ArgumentNullException : {ex2.ToString()}", text2);
}
catch (SocketException ex3)
if (relaySocket != null)
{
Log($"SocketException : {ex3.ToString()}", text2);
}
catch (Exception ex4)
try
{
Log($"Unexpected exception : {ex4.ToString()}", text2);
if (relaySocket.Connected) relaySocket.Shutdown(SocketShutdown.Both);
relaySocket.Close();
}
catch { }
}
}
}
}
private static string CleanseDataBlock(string sData, bool bHideRecipients)
{
if (bHideRecipients)
if (!bHideRecipients || string.IsNullOrEmpty(sData)) return sData;
StringBuilder sb = new StringBuilder();
using (StringReader reader = new StringReader(sData))
{
StringBuilder stringBuilder = new StringBuilder();
using StringReader stringReader = new StringReader(sData);
string pattern = "^[Tt][Oo]: *$";
string pattern2 = "^[Dd][Aa][Tt][Ee]:.*$";
bool flag = false;
bool flag2 = false;
for (string text = stringReader.ReadLine(); text != null; text = stringReader.ReadLine())
string line;
bool inHeaderSection = true;
bool skippingToHeader = false;
while ((line = reader.ReadLine()) != null)
{
if (flag2)
// Empty line marks end of email headers and start of MIME/Body
if (inHeaderSection && line.Length == 0)
{
stringBuilder.Append(text + "\r\n");
}
else if (!flag)
{
if (Regex.Match(text, pattern).Success)
{
flag = true;
}
stringBuilder.Append(text + "\r\n");
}
else if (Regex.Match(text, pattern2).Success)
{
flag = false;
stringBuilder.Append(text + "\r\n");
flag2 = true;
}
}
return stringBuilder.ToString();
}
return sData;
inHeaderSection = false;
skippingToHeader = false;
}
private bool CheckAndSend(string PrevSuccessCode, string NextCommand, Socket sock, string LogFileName)
if (inHeaderSection)
{
byte[] array = new byte[2500];
string text = "";
int num = sock.Receive(array);
if (num <= 0)
if (Regex.IsMatch(line, @"^[Tt][Oo]:", RegexOptions.IgnoreCase))
{
Log("recv failed", LogFileName);
sock.Shutdown(SocketShutdown.Both);
sock.Close();
return false;
skippingToHeader = true;
continue; // Strip To: line
}
array[num] = 0;
text = Encoding.ASCII.GetString(array, 0, num);
Log(text, LogFileName);
if (text.Substring(0, 3) != PrevSuccessCode)
// Check for header folding (continuation line starting with whitespace)
if (skippingToHeader && (line.StartsWith(" ") || line.StartsWith("\t")))
{
sock.Shutdown(SocketShutdown.Both);
sock.Close();
return false;
}
if (NextCommand.Length > 500)
{
Log(NextCommand.Substring(0, 500), LogFileName);
continue; // Strip folded recipient lines
}
else
{
Log(NextCommand, LogFileName);
skippingToHeader = false;
}
byte[] bytes = Encoding.ASCII.GetBytes(NextCommand);
sock.Send(bytes);
}
sb.Append(line).Append("\r\n");
}
}
return sb.ToString();
}
private bool CheckAndSend(string prevSuccessCode, string nextCommand, Socket sock, string logFileName)
{
byte[] buffer = new byte[4096];
try
{
int bytesRead = sock.Receive(buffer);
if (bytesRead <= 0)
{
Log("Upstream closed connection unexpectedly.", logFileName);
return false;
}
string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Log($"Upstream << {response.TrimEnd()}", logFileName);
if (!response.StartsWith(prevSuccessCode, StringComparison.Ordinal))
{
Log($"Expected response code {prevSuccessCode}, received: {response}", logFileName);
return false;
}
Log($"Upstream >> {(nextCommand.Length > 200 ? nextCommand.Substring(0, 200) + "..." : nextCommand.TrimEnd())}", logFileName);
byte[] sendBytes = Encoding.ASCII.GetBytes(nextCommand);
sock.Send(sendBytes);
return true;
}
catch (Exception ex)
{
Log($"CheckAndSend failed: {ex.Message}", logFileName);
return false;
}
}
protected override void Dispose(bool disposing)
{
if (disposing && components != null)
if (disposing)
{
components.Dispose();
components?.Dispose();
mre?.Dispose();
}
base.Dispose(disposing);
}
@@ -559,6 +672,7 @@ public class SMTPProxy : ServiceBase
private void InitializeComponent()
{
components = new Container();
base.ServiceName = "Service1";
base.ServiceName = "SMTPProxy.net";
}
}
}