SMTPServer works basicly with some problems

This commit is contained in:
Fabian Stamm 2016-11-28 17:26:04 +01:00
parent 181f5ef908
commit 68e0ac2ef0
6 changed files with 91 additions and 82 deletions

View File

@ -1,53 +1,74 @@
using System; using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
//namespace Logging //namespace Logging
//{ //{
public class Logging public class Logging
{
private static LoggingType[] ActiveLoggingTypes { get; set; }
public string LogFolder { get; private set; }
public enum LoggingType
{ {
private static LoggingType[] _ActiveLoggingTypes { get; set; } TRACE,
ERROR,
public enum LoggingType DEBUG,
{ WARNING,
TRACE, INFO,
ERROR, ALL
DEBUG,
WARNING,
INFO,
ALL
}
public static void AddLogMessage(LoggingType messagetype, string message)
{
if(CheckLoggingType(messagetype)) PrintToConsole(messagetype, message);
}
public static void AddException(Exception e)
{
AddLogMessage(LoggingType.ERROR, e.Message);
}
private static bool CheckLoggingType(LoggingType lt){
if (_ActiveLoggingTypes == null ||_ActiveLoggingTypes.Length < 1) {
_ActiveLoggingTypes = new LoggingType[1];
_ActiveLoggingTypes[0] = LoggingType.ALL;
}
bool found = false;
foreach(LoggingType l in _ActiveLoggingTypes)
{
if (l == lt || l == LoggingType.ALL)
{
found = true;
break;
}
}
return found;
}
private static void PrintToConsole(LoggingType lt, string message)
{
Console.WriteLine("[" + lt.ToString() + "]" + message);
}
} }
//}
public Logging()
{
System.IO.Directory.GetCurrentDirectory();
ActiveLoggingTypes = new LoggingType[] { LoggingType.ALL };
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
LogFolder = "/var/log/mail/mail.log";
}
}
public static void AddLogMessage(LoggingType messagetype, string message)
{
new TaskFactory(TaskScheduler.Current);
new Task(() =>
{
if (CheckLoggingType(messagetype)) PrintToConsole(messagetype, message);
}).Start();
}
public static void AddException(Exception e)
{
AddLogMessage(LoggingType.ERROR, e.Message);
}
private static bool CheckLoggingType(LoggingType lt)
{
if (ActiveLoggingTypes == null || ActiveLoggingTypes.Length < 1)
{
ActiveLoggingTypes = new LoggingType[1];
ActiveLoggingTypes[0] = LoggingType.ALL;
}
bool found = false;
foreach (LoggingType l in ActiveLoggingTypes)
{
if (l == lt || l == LoggingType.ALL)
{
found = true;
break;
}
}
return found;
}
private static void PrintToConsole(LoggingType lt, string message)
{
Console.WriteLine("[" + lt.ToString() + "]" + message);
}
}

View File

@ -9,44 +9,20 @@ namespace SMTPServer
{ {
static void Main(string[] args) static void Main(string[] args)
{ {
/*using (var context = new MysqlDB())
{
context.Database.EnsureCreated();
var domain = new Domains()
{
Domain = "HI",
IsMail = true
};
context.Add(domain);
context.SaveChanges();
var res = context.Domains.Find();
}*/
//Console.WriteLine("####################");
/*var request = new DnsQueryRequest(); /*var request = new DnsQueryRequest();
var response = request.ResolveAsync("fabianstamm.de", DnDns.Enums.NsType.MX, DnDns.Enums.NsClass.ANY, System.Net.Sockets.ProtocolType.Tcp); var response = request.ResolveAsync("fabianstamm.de", DnDns.Enums.NsType.MX, DnDns.Enums.NsClass.ANY, System.Net.Sockets.ProtocolType.Tcp);
OutputResults(response);*/ OutputResults(response);*/
//var t = new Thread(new ThreadStart(Test));
//t.Start();
//TestAsync();
//var listener = new PortListener(5122);
//listener.OnConnected += Listener_OnConnected;
var l = new MailServer.SMTPServer.SmtpPortListener(5122); var l = new MailServer.SMTPServer.SmtpPortListener(25);
while (true) while (true)
{ {
Thread.Sleep(500); Thread.Sleep(500);
} }
//var listener = new PortListener(5122);
//listener.OnConnected += Listener_OnConnected;
} }
private static async void TestAsync() private static async void TestAsync()

View File

@ -12,7 +12,7 @@ namespace MailServer.SMTPServer
public SmtpCommand(string command) public SmtpCommand(string command)
{ {
Parameters = new string[0]; Parameters = new string[0];
if (command.Length == 0) if (command.Length == 0 || command.Equals(""))
{ {
Command = "FREELINE"; Command = "FREELINE";
return; return;

View File

@ -12,12 +12,11 @@ namespace MailServer.SMTPServer
private static List<int> Ports { get; set; } private static List<int> Ports { get; set; }
private int Port { get; set; } private int Port { get; set; }
private TcpListener Listener; private TcpListener Listener;
private List<SmtpServerSession> Sessions { get; set; }
public SmtpPortListener(int port) public SmtpPortListener(int port)
{ {
Sessions = new List<SmtpServerSession>();
Port = port; Port = port;
Logging.AddLogMessage(Logging.LoggingType.INFO, "Start TCP listener on port: " + Port);
Thread thread = new Thread(StartListeningAsync); Thread thread = new Thread(StartListeningAsync);
thread.Start(); thread.Start();
} }
@ -29,10 +28,10 @@ namespace MailServer.SMTPServer
while (true) while (true)
{ {
//var socket = await Listener.AcceptSocketAsync();
var client = await Listener.AcceptTcpClientAsync(); var client = await Listener.AcceptTcpClientAsync();
var session = new SmtpServerSession(client); var ip = (IPEndPoint)client.Client.RemoteEndPoint;
Sessions.Add(session); Logging.AddLogMessage(Logging.LoggingType.INFO, "New Client Logged in with ip: " + ip.Address.ToString() + "On port: " + Port + " to port: " + ip.Port);
new SmtpServerSession(client);
} }
} }
} }

View File

@ -47,6 +47,7 @@ namespace MailServer.SMTPServer
dataend = true; dataend = true;
} }
#endif #endif
FreeLine = true;
if (!FreeLine && command.Command.Equals("FREELINE")) if (!FreeLine && command.Command.Equals("FREELINE"))
{ {
FreeLine = true; FreeLine = true;
@ -109,16 +110,18 @@ namespace MailServer.SMTPServer
AccountId = accountId, AccountId = accountId,
ReceiveDate = DateTime.Now, ReceiveDate = DateTime.Now,
Data = Data, Data = Data,
SendedByServerIp = "0.0.0.0", SendedByServerIp = IPEndPoint.Address.ToString(),
From = MailFrom, From = MailFrom,
To = r, To = r,
Folder = folderid Folder = folderid
}; };
context.Mails.Add(nm); context.Mails.Add(nm);
context.SaveChangesAsync(); context.SaveChangesAsync();
} }
MailFromSet = false;
Recipients.Clear();
WaitForData = false;
return; return;
} }
SendResponse(ResponseCodes.C250, "OK"); SendResponse(ResponseCodes.C250, "OK");
@ -133,7 +136,7 @@ namespace MailServer.SMTPServer
Data += " " + s; Data += " " + s;
} }
Data += "\n"; Data += "\r\n";
FreeLine = false; FreeLine = false;
} }
return; return;
@ -141,6 +144,7 @@ namespace MailServer.SMTPServer
switch (command.Command.ToUpper()) switch (command.Command.ToUpper())
{ {
case "EHLO":
case "HELO": case "HELO":
if (command.Parameters.Length < 1) if (command.Parameters.Length < 1)
{ {
@ -270,7 +274,7 @@ namespace MailServer.SMTPServer
switch (command.Command.ToUpper()) switch (command.Command.ToUpper())
{ {
case "DATA": case "DATA":
SendResponse(ResponseCodes.C354, "Start mail input, end with <CRLF>.<CRLS>"); SendResponse(ResponseCodes.C354, "Start mail input, end with <CRLF>.<CRLF>");
WaitForData = true; WaitForData = true;
return; return;
} }

View File

@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
@ -15,17 +16,22 @@ namespace MailServer.SMTPServer
public event ReceivedLineEventHandler NewLine; public event ReceivedLineEventHandler NewLine;
private TcpClient Client { get; set; } private TcpClient Client { get; set; }
public IPEndPoint IPEndPoint { get; private set; }
private NetworkStream Stream { get; set; } private NetworkStream Stream { get; set; }
private Encoding Encoding = Encoding.ASCII; private Encoding Encoding = Encoding.ASCII;
private string Others; private string Others;
private Thread Worker; private Thread Worker;
private bool Active = true; private bool Active = true;
private int SessionID { get; set; }
public SmtpSession(TcpClient client) public SmtpSession(TcpClient client)
{ {
Client = client; Client = client;
IPEndPoint = (IPEndPoint)client.Client.RemoteEndPoint;
Stream = client.GetStream(); Stream = client.GetStream();
Others = ""; Others = "";
SessionID = new Random(123).Next(10000, 99999);
Logging.AddLogMessage(Logging.LoggingType.INFO, "New SMTPSession with id '" + SessionID + "' started");
Worker = new Thread(ReadClientInput); Worker = new Thread(ReadClientInput);
Worker.Start(); Worker.Start();
} }
@ -35,6 +41,7 @@ namespace MailServer.SMTPServer
public void SendResponse(ResponseCodes responseCode, string args) public void SendResponse(ResponseCodes responseCode, string args)
{ {
var text = ((int)responseCode).ToString(); var text = ((int)responseCode).ToString();
Logging.AddLogMessage(Logging.LoggingType.DEBUG, "Send back: " + text + " " + args);
text += " " + args +'\r' + '\n'; text += " " + args +'\r' + '\n';
var bytes = Encoding.UTF8.GetBytes(text); var bytes = Encoding.UTF8.GetBytes(text);
Stream.Write(bytes, 0, bytes.Length); Stream.Write(bytes, 0, bytes.Length);
@ -62,6 +69,7 @@ namespace MailServer.SMTPServer
Thread.Sleep(10); Thread.Sleep(10);
} }
} }
} }
private bool r = false; private bool r = false;
@ -80,6 +88,7 @@ namespace MailServer.SMTPServer
else if (r && c.Equals('\n')) else if (r && c.Equals('\n'))
{ {
//Console.WriteLine(line); //Console.WriteLine(line);
Logging.AddLogMessage(Logging.LoggingType.DEBUG, "Seession " + SessionID + ": received line: " + line);
NewLine(line); NewLine(line);
line = ""; line = "";
} }