Initial commit
authorMegaBrutal <code+git@megabrutal.com>
Fri, 5 Dec 2014 15:43:54 +0000 (16:43 +0100)
committerMegaBrutal <code+git@megabrutal.com>
Fri, 5 Dec 2014 15:43:54 +0000 (16:43 +0100)
new file:   Bounce.pas
new file:   Common.pas
new file:   DNSMX.pas
new file:   DNSResolve.pas
new file:   EINIFiles.pas
new file:   Listener.pas
new file:   Log.pas
new file:   Mailbox.pas
new file:   MgSMTP.pas
new file:   NetRFC.pas
new file:   Network.pas
new file:   Policies.pas
new file:   RFCSMTP.pas
new file:   Relay.pas
new file:   SocketUtils.pas
new file:   Spool.pas
new file:   changelog.txt
new file:   comparewild.pas
new file:   lgpl-2.0.txt
new file:   license.txt
new file:   license_gpl-2.0.txt
new file:   license_lesser.txt
new file:   mgsmtp_server_example.ini
new file:   readme.txt
new file:   readme_source.txt
new file:   todo.txt

26 files changed:
Bounce.pas [new file with mode: 0644]
Common.pas [new file with mode: 0644]
DNSMX.pas [new file with mode: 0644]
DNSResolve.pas [new file with mode: 0644]
EINIFiles.pas [new file with mode: 0644]
Listener.pas [new file with mode: 0644]
Log.pas [new file with mode: 0644]
Mailbox.pas [new file with mode: 0644]
MgSMTP.pas [new file with mode: 0644]
NetRFC.pas [new file with mode: 0644]
Network.pas [new file with mode: 0644]
Policies.pas [new file with mode: 0644]
RFCSMTP.pas [new file with mode: 0644]
Relay.pas [new file with mode: 0644]
SocketUtils.pas [new file with mode: 0644]
Spool.pas [new file with mode: 0644]
changelog.txt [new file with mode: 0644]
comparewild.pas [new file with mode: 0644]
lgpl-2.0.txt [new file with mode: 0644]
license.txt [new file with mode: 0644]
license_gpl-2.0.txt [new file with mode: 0644]
license_lesser.txt [new file with mode: 0644]
mgsmtp_server_example.ini [new file with mode: 0644]
readme.txt [new file with mode: 0644]
readme_source.txt [new file with mode: 0644]
todo.txt [new file with mode: 0644]

diff --git a/Bounce.pas b/Bounce.pas
new file mode 100644 (file)
index 0000000..b1f66a2
--- /dev/null
@@ -0,0 +1,162 @@
+{
+   MegaBrutal's SMTP Server (MgSMTP)
+   Copyright (C) 2010-2012 MegaBrutal
+
+   This program is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Affero General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Affero General Public License for more details.
+
+   You should have received a copy of the GNU Affero General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+
+{$MODE DELPHI}
+unit Bounce;
+
+interface
+uses SysUtils, Classes, Common;
+
+const
+
+   DSMSG_CONNECTIONFAIL    = 'Failed to establish connection with relay server: ';
+   DSMSG_INTERNALFAIL      = 'Internal failure: ';
+   {DSMSG_MAILBOXNOTEXISTS  = 'Although the recipient addressed a valid local mailbox'#13#10
+                           + 'at the time when I queued it, meanwhile it became invalid'#13#10
+                           + 'due to changes in the mail server''s configuration, thanks'#13#10
+                           + 'to the beloved postmaster. I apologise.';}
+   DSMSG_MAILBOXNOTEXISTS  = 'Local mailbox does not exist.';
+   DSMSG_QUOTAEXCEEDED     = 'User quota exceeded.';
+
+
+   function GenerateBounceMessage(FailedRecipient: TRecipient; Headers: TStrings; ReturnPath: string): TStrings; overload;
+   function GenerateBounceMessage(Envelope: TEnvelope; Headers: TStrings): TStrings; overload;
+
+
+implementation
+
+
+function GetFailureTypeStr(Status: integer): string;
+begin
+   if (Status and DS_UNEXPECTEDFAIL) <> 0 then
+      Result:= 'an unexpected'
+   else if (Status and DS_CONNECTIONFAIL) <> 0 then
+      Result:= 'a connection'
+   else if (Status and DS_INTERNALFAIL) <> 0 then
+      Result:= 'an internal'
+   else if (Status and DS_PERMANENT) <> 0 then
+      Result:= 'a permanent'
+   else if (Status and DS_DELAYED) <> 0 then
+      Result:= 'a temporary'
+   else
+      Result:= '';
+end;
+
+procedure GenerateHeader(Msg: TStrings; ReturnPath: string);
+begin
+   with Msg do begin
+      Add('From: Mail Delivery System <MAILER-DAEMON@' + MainServerConfig.Name + '>');
+      Add('To: <' + ReturnPath + '>');
+      Add('Subject: Delivery Status Notification');
+      Add('');
+      Add('This is the mail delivery system at host ' + MainServerConfig.Name + ',');
+      Add('embodied by MgSMTP software version ' + MainServerConfig.VersionStr + '.');
+      Add('');
+   end;
+end;
+
+procedure AddTechnicalDetails(Msg: TStrings; FailedRecipient: TRecipient);
+begin
+   with Msg do begin
+      if (FailedRecipient.Data and DS_SMTPFAIL) <> 0 then begin
+         Add('The targetted mail server has rejected the message:');
+         Add(IntToStr(FailedRecipient.Data and DS_SMTPREPLYMASK) + #32 + CleanEOLN(FailedRecipient.RMsg));
+      end
+      else begin
+         if Length(FailedRecipient.RMsg) > 0 then
+            Add(CleanEOLN(FailedRecipient.RMsg))
+         else begin
+            Add('No error message. This is an unexpected failure.');
+            Add('Possible that the relay server has unexpectedly');
+            Add('closed the connection.');
+         end;
+      end;
+   end;
+end;
+
+procedure AddHeaders(Msg, Headers: TStrings);
+begin
+   with Msg do begin
+      Add('');
+      Add('Below you can see the headers of your undelivered message.');
+      Add('Pay attention to the "Subject" and "Message-Id" headers to');
+      Add('get a clue which was it exactly.');
+      Add('------------------------------------------------------------');
+      AddStrings(Headers);
+   end;
+end;
+
+function GenerateBounceMessage(FailedRecipient: TRecipient; Headers: TStrings; ReturnPath: string): TStrings;
+var Msg: TStrings;
+begin
+   Msg:= TStringList.Create;
+   with Msg do begin
+      GenerateHeader(Msg, ReturnPath);
+      Add('I am sorry to inform you that I encountered a problem');
+      Add('while I was trying to deliver your message to the following');
+      Add('recipient: <' + FailedRecipient.Address + '>.');
+      Add('This is ' + GetFailureTypeStr(FailedRecipient.Data) + ' failure.');
+      Add('');
+      Add('Technical details:');
+      AddTechnicalDetails(Msg, FailedRecipient);
+      if (FailedRecipient.Data and DS_DELAYED) <> 0 then begin
+         Add('');
+         Add('It seems it''s a temporary failure, so I''ll keep on trying.');
+      end
+      else if (FailedRecipient.Data and DS_PERMANENT) <> 0 then begin
+         Add('');
+         Add('It''s a permanent failure, I''ve given up trying.');
+      end;
+      AddHeaders(Msg, Headers);
+   end;
+   Result:= Msg;
+end;
+
+function GenerateBounceMessage(Envelope: TEnvelope; Headers: TStrings): TStrings;
+var Msg: TStrings; FailedRecipient: TRecipient; i: integer;
+begin
+   Msg:= TStringList.Create;
+   with Msg do begin
+      GenerateHeader(Msg, Envelope.ReturnPath);
+      Add('I am sorry to inform you that I encountered several');
+      Add('problems while I was trying to deliver your message to');
+      Add('multiple recipients.');
+      Add('');
+      Add('Details follow:');
+      Add('');
+      for i:= 0 to Envelope.GetNumberOfRecipients - 1 do begin
+         Add('');
+         FailedRecipient:= Envelope.GetRecipient(i);
+         Add('Recipient <' + FailedRecipient.Address + '>:');
+         AddTechnicalDetails(Msg, FailedRecipient);
+         Add('');
+         Add('This is ' + GetFailureTypeStr(FailedRecipient.Data) + ' failure.');
+         if (FailedRecipient.Data and DS_DELAYED) <> 0 then
+            Add('Delivery will be retried by certain intervals.')
+         else if (FailedRecipient.Data and DS_PERMANENT) <> 0 then
+            Add('Delivery to this recipient has failed permanently.');
+         Add('');
+      end;
+      AddHeaders(Msg, Headers);
+   end;
+   Result:= Msg;
+end;
+
+
+end.
diff --git a/Common.pas b/Common.pas
new file mode 100644 (file)
index 0000000..b7a6ec8
--- /dev/null
@@ -0,0 +1,657 @@
+{
+   Copyright (C) 2010-2014 MegaBrutal
+
+   This unit is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Lesser General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This unit is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+{
+   Unit: Common
+   It holds some common definitions for MgSMTP, and some helper functions.
+}
+
+
+{$MODE DELPHI}
+
+unit Common;
+
+interface
+uses Windows, SysUtils, DateUtils, Classes, INIFiles;
+
+type
+
+   TStringArray = array of string;
+   TUnixTimeStamp = longint;
+
+
+   TArgument = record
+      Option, Value: string;
+   end;
+
+
+   TArgumentParser = class
+      constructor Create(RawArguments: TStringArray; AllowedPrefixes: TStringArray = []);
+      destructor Destroy; override;
+   private
+      Arguments: array of TArgument;
+      procedure ParseArgument(Arg: string; const AllowedPrefixes: TStringArray);
+   public
+      function GetArgument(ID: integer): TArgument;
+      function IsPresent(ArgumentName: string): boolean;
+      function GetValue(ArgumentName: string; DefValue: string = ''): string;
+      function ValidateArguments(ValidArguments: TStringArray): integer;
+   end;
+
+
+   TNamedObject = class
+      constructor Create(const Name: string; Config: TINIFile; const Section: string);
+   private
+      FName: string;
+      FAliases: TStrings;
+   public
+      property Name: string read FName;
+      property Aliases: TStrings read FAliases;
+      function IsItYourName(const Name: string): boolean; virtual;
+   end;
+
+
+   TMainServerConfig = class(TNamedObject)
+      constructor Create(Config: TINIFile);
+   private
+      FPolicies, FMailbox, FRelay, FLog: boolean;
+      FDatabytes: longint;
+      {FTimeCorrection: integer;}
+      FTimeOffset: integer;
+      FTimeOffsetStr: string;
+      FListenPorts: TStrings;
+   public
+      function GetVersionStr: string;
+      property ListenPorts: TStrings read FListenPorts;
+      property Databytes: longint read FDatabytes;
+      {property TimeCorrection: integer read FTimeCorrection;}
+      property TimeOffset: integer read FTimeOffset;
+      property TimeOffsetStr: string read FTimeOffsetStr;
+      property Policies: boolean read FPolicies;
+      property Mailbox: boolean read FMailbox;
+      property Relay: boolean read FRelay;
+      property Log: boolean read FLog;
+      property VersionStr: string read GetVersionStr;
+   end;
+
+
+   TEMailFlags = word;
+
+   TEMailProperties = class
+      constructor Create;
+   protected
+      FSize: longint;
+      FFlags: TEMailFlags;
+   public
+      procedure SetSize(Value: longint);
+      procedure WriteFlags(Value: TEMailFlags);
+      procedure SetFlag(Flag: TEMailFlags);
+      function HasFlag(Flag: TEMailFlags): boolean;
+      property Size: longint read FSize write SetSize;
+      property Flags: TEMailFlags read FFlags write WriteFlags;
+   end;
+
+
+   TRecipient = record
+      Address, RMsg: string;
+      Data: integer;
+   end;
+
+
+   TIPNamePair = class
+      constructor Create(const Name, IP: string);
+   protected
+      FName, FIP: string;
+   public
+      property Name: string read FName;
+      property IP: string read FIP;
+      function Copy: TIPNamePair;
+   end;
+
+
+   TEnvelope = class
+      constructor Create;
+      destructor Destroy; override;
+   private
+      FReturnPath, FRelayHost: string;
+      FReturnPathSpecified: boolean;
+      FRecipients: array of TRecipient;
+   public
+      function GetNumberOfRecipients: integer;
+      function GetRecipient(Index: integer): TRecipient;
+      function IsComplete: boolean;
+      procedure AddRecipient(Address: string; Data: integer = 0; RMsg: string = ''); overload;
+      procedure AddRecipient(Recipient: TRecipient); overload;
+      procedure SetReturnPath(Address: string);
+      procedure SetRecipientData(Index, Data: integer; RMsg: string = '');
+      procedure SetRelayHost(HostName: string);
+      property ReturnPath: string read FReturnPath write SetReturnPath;
+      property RelayHost: string read FRelayHost write SetRelayHost;
+   end;
+
+
+   TEnvelopeArray = array of TEnvelope;
+
+
+   function EMailUserName(EMail: string): string;
+   function EMailHost(EMail: string): string;
+   function CleanEMailAddress(EMail: string): string;
+   function IsValidEMailAddress(EMail: string): boolean;
+   function EMailTimeStamp(DateTime: TDateTime): string;
+   function EMailTimeStampCorrected(DateTime: TDateTime): string;
+   function StatusToStr(Status: integer): string;
+   procedure AssignDeliveryStatusToSMTPCodes(Envelope: TEnvelope);
+
+   function CleanEOLN(S: string): string;
+   function GenerateRandomString(Length: integer): string;
+   function GetAlphabetStr: string;
+   function GetServiceCodeStr(Ctrl: dword): string;
+   function GetWinMajorVersion: longword;
+   function IsPrintableString(S: string): boolean;
+   function UnixTimeStamp(DateTime: TDateTime): TUnixTimeStamp;
+   function CmdlineToStringArray: TStringArray;
+   procedure SplitParameters(S: string; var FirstPrm, Remainder: string; Separator: char = #32);
+
+   function ReadLineFromStream(Stream: TStream): string;
+   function WriteLineToStream(Stream: TStream; Line: string): boolean;
+
+
+const
+
+   { MgSMTP version: }
+   VERSION_STR       = '0.9s';
+
+   { Architecture: }
+{$IFDEF CPU64}
+   PLATFORM_BITS     =  64;
+{$ELSE}
+{$IFDEF CPU32}
+   PLATFORM_BITS     =  32;
+{$ENDIF}
+{$ENDIF}
+
+   { Delivery statuses: }
+   DS_DELIVERED      = 1 shl 10;
+   DS_DELAYED        = 1 shl 11;
+   DS_PERMANENT      = 1 shl 12;
+   DS_INTERNALFAIL   = 1 shl 13;
+   DS_CONNECTIONFAIL = 1 shl 14;
+   DS_UNEXPECTEDFAIL = 1 shl 15;
+   DS_SMTPFAIL       = 1 shl 16;
+   DS_SMTPREPLYMASK  = $000003FF;
+   DS_ALLFLAGS       = $FFFFFFFF;
+
+   { E-mail property flags: }
+   EF_8BITMIME       =   1;
+
+   DayNames: array[1..7] of shortstring = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
+   MonthNames: array[1..12] of shortstring = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+      'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
+
+   { Support for PRESHUTDOWN is not yet present in the Free Pascal library,
+     therefore I define the necessary constants here. It's a temporary
+     solution, I hope I won't need it for the next release of FPC. }
+   SERVICE_ACCEPT_PRESHUTDOWN  = $00000100;
+   SERVICE_CONTROL_PRESHUTDOWN = $0000000F;
+
+
+var
+
+   MainServerConfig: TMainServerConfig;
+
+
+implementation
+
+
+{ Unit-private functions/prodecures: }
+
+function MakeTimeOffsetStr(TimeOffset: integer): string;
+var CorrS: string; CorrI: integer;
+begin
+   CorrI:= TimeOffset;
+   CorrS:= IntToStr(Abs(CorrI));
+   while Length(CorrS) < 4 do CorrS:= '0' + CorrS;
+   if CorrI >= 0 then CorrS:= '+' + CorrS else CorrS:= '-' + CorrS;
+   Result:= CorrS;
+end;
+
+
+{ Unit-public functions/procedures: }
+
+function EMailUserName(EMail: string): string;
+var p: integer;
+begin
+   p:= Length(EMail);
+   while (p > 0) and (EMail[p] <> '@') do Dec(p);
+   if p <> 0 then begin
+      Result:= Copy(EMail, 1, p - 1);
+   end
+   else Result:= EMail;
+end;
+
+function EMailHost(EMail: string): string;
+var p: integer;
+begin
+   p:= Length(EMail);
+   while (p > 0) and (EMail[p] <> '@') do Dec(p);
+   if (p <> 0) and (p < Length(EMail)) then begin
+      Result:= Copy(EMail, p + 1, Length(EMail) - p);
+   end
+   else Result:= '';
+end;
+
+function CleanEMailAddress(EMail: string): string;
+var po, pc, p: integer;
+begin
+   po:= Pos('<', EMail);
+   pc:= Pos('>', EMail);
+   if (po <> 0) and (pc <> 0) and (po < pc) then begin
+      Result:= Copy(EMail, po + 1, pc - po - 1);
+      p:= Pos(':', Result);
+      if p <> 0 then
+         Result:= Copy(Result, p + 1, Length(Result) - p);
+   end
+   else
+      Result:= EMail;
+end;
+
+function IsValidEMailAddress(EMail: string): boolean;
+begin
+   { !!! TODO: Implement more strict checking later !!! }
+   Result:= Pos('@', EMail) <> 0;
+end;
+
+function EMailTimeStamp(DateTime: TDateTime): string;
+var Year, Month, Day: word;
+begin
+   DecodeDate(DateTime, Year, Month, Day);
+   Result:= DayNames[DayOfWeek(DateTime)] + ' ' + MonthNames[Month] + ' '
+      + FormatDateTime('dd hh:nn:ss', DateTime) + ' ' + IntToStr(Year);
+end;
+
+function EMailTimeStampCorrected(DateTime: TDateTime): string;
+begin
+   Result:= EMailTimeStamp(DateTime) + ' ' + MainServerConfig.TimeOffsetStr;
+end;
+
+function StatusToStr(Status: integer): string;
+{ Returns the delivery status code in human-readable format. }
+begin
+   Result:= IntToStr(Status and (DS_ALLFLAGS - DS_SMTPREPLYMASK - DS_SMTPFAIL))
+      + '+' + IntToStr(Status and DS_SMTPREPLYMASK);
+end;
+
+procedure AssignDeliveryStatusToSMTPCodes(Envelope: TEnvelope);
+var i, code, cond, status: integer; Recipient: TRecipient;
+begin
+   for i:= 0 to Envelope.GetNumberOfRecipients - 1 do begin
+      Recipient:= Envelope.GetRecipient(i);
+      code:= Recipient.Data and DS_SMTPREPLYMASK;
+      cond:= code div 100;
+      case cond of
+         0: status:= DS_DELAYED or DS_UNEXPECTEDFAIL;
+         2: status:= DS_DELIVERED;
+         4: status:= DS_DELAYED;
+         5: status:= DS_PERMANENT;
+         else status:= DS_PERMANENT or DS_UNEXPECTEDFAIL;
+      end;
+      if code <> 0 then status:= status or DS_SMTPFAIL;
+      Envelope.SetRecipientData(i, code or status, Recipient.RMsg);
+   end;
+end;
+
+
+function CleanEOLN(S: string): string;
+begin
+   while (Length(S) <> 0) and (S[Length(S)] in [#13, #10]) do Delete(S, Length(S), 1);
+   Result:= S;
+end;
+
+function GenerateRandomString(Length: integer): string;
+var What, Chrn, i: integer; Value: string;
+begin
+   Value:= '';
+   for i:= 1 to Length do begin
+     What:= Random(3);
+     case What of
+     0: begin Chrn:= Random(10)+48; Value:= Value + Chr(Chrn); end;
+     1: begin Chrn:= Random(26)+65; Value:= Value + Chr(Chrn); end;
+     2: begin Chrn:= Random(26)+97; Value:= Value + Chr(Chrn); end;
+     end;
+   end;
+   Result:= Value;
+end;
+
+function GetAlphabetStr: string;
+var i: byte;
+begin
+   Result:= '';
+   for i:= Ord('0') to Ord('9') do Result:= Result + Chr(i);
+   for i:= Ord('A') to Ord('Z') do Result:= Result + Chr(i);
+end;
+
+function GetServiceCodeStr(Ctrl: dword): string;
+begin
+   case Ctrl of
+   SERVICE_CONTROL_STOP:         Result:= 'STOP';
+   SERVICE_CONTROL_SHUTDOWN:     Result:= 'SHUTDOWN';
+   SERVICE_CONTROL_PRESHUTDOWN:  Result:= 'PRESHUTDOWN';
+   else                          Result:= IntToStr(Ctrl);
+   end;
+end;
+
+function GetWinMajorVersion: longword;
+var OSVersionInfo: TOSVersionInfo;
+begin
+   { Get OS version info. }
+   OSVersionInfo.dwOSVersionInfoSize:= SizeOf(TOSVersionInfo);
+   GetVersionEx(OSVersionInfo);
+   Result:= OSVersionInfo.dwMajorVersion;
+end;
+
+function IsPrintableString(S: string): boolean;
+{ Check if string contains only printable ASCII characters. }
+var i: integer;
+begin
+   i:= 1;
+   Result:= true;
+   while Result and (i <= Length(S)) do begin
+      Result:= (Ord(S[i]) > 31) and (Ord(S[i]) < 127);
+      Inc(i);
+   end;
+end;
+
+procedure SplitParameters(S: string; var FirstPrm, Remainder: string; Separator: char = #32);
+var i: integer;
+begin
+   i:= pos(Separator, S);
+   if i > 0 then begin
+      FirstPrm:= Copy(S, 1, i - 1);
+      Remainder:= Copy(S, i + 1, Length(S) - i);
+   end
+   else begin
+      FirstPrm:= S;
+      Remainder:= '';
+   end;
+end;
+
+function UnixTimeStamp(DateTime: TDateTime): TUnixTimeStamp;
+begin
+   {Result:= Trunc((DateTime - EncodeDate(1970, 1 ,1)) * 24 * 60 * 60);}
+   Result:= DateTimeToUnix(DateTime);
+end;
+
+
+function ReadLineFromStream(Stream: TStream): string;
+var S: string; B: char;
+begin
+   S:= '';
+   try
+      repeat
+         B:= Char(Stream.ReadByte);
+         if not (B in [#10, #13]) then S:= S + B;
+      until (B = #10);
+   finally
+      Result:= S;
+   end;
+end;
+
+function WriteLineToStream(Stream: TStream; Line: string): boolean;
+const EOLN = #13#10;
+begin
+   Result:= true;
+   Line:= Line + EOLN;
+   try
+      Stream.WriteBuffer(PChar(Line)^, Length(Line));
+   except
+      Result:= false;
+   end;
+end;
+
+
+{ Object constructors/destructors: }
+
+constructor TArgumentParser.Create(RawArguments: TStringArray; AllowedPrefixes: TStringArray = []);
+var i: integer;
+begin
+   for i:= 0 to Length(RawArguments) - 1 do
+      ParseArgument(RawArguments[i], AllowedPrefixes);
+end;
+
+destructor TArgumentParser.Destroy;
+begin
+   SetLength(Arguments, 0);
+end;
+
+constructor TNamedObject.Create(const Name: string; Config: TINIFile; const Section: string);
+begin
+   inherited Create;
+   FName:= Name;
+   FAliases:= TStringList.Create;
+   FAliases.Delimiter:= ',';
+   FAliases.DelimitedText:= FName + ',' + Config.ReadString(Section, 'Alias', '');
+end;
+
+constructor TMainServerConfig.Create(Config: TINIFile);
+begin
+   inherited Create(Config.ReadString('Server', 'Name', ''), Config, 'Server');
+   FListenPorts:= TStringList.Create;
+   FListenPorts.Delimiter:= ',';
+   FListenPorts.DelimitedText:= Config.ReadString('Server', 'ListenPort', '25');
+
+   FDatabytes:=      Config.ReadInteger('Server', 'Databytes', 1024 * 1024 * 1024);
+   {FTimeCorrection:= Config.ReadInteger('Server', 'TimeCorrection', 0);}
+   FTimeOffset:=     Config.ReadInteger('Server', 'TimeOffset', Config.ReadInteger('Server', 'TimeCorrection', 0) * 100);
+   FTimeOffsetStr:=  MakeTimeOffsetStr(FTimeOffset);
+
+   FPolicies:=  Config.ReadBool('Server', 'Policies',  false);
+   FMailbox:=   Config.ReadBool('Server', 'Mailbox',   false);
+   FRelay:=     Config.ReadBool('Server', 'Relay',     false);
+   FLog:=       Config.ReadBool('Server', 'Log',       false);
+end;
+
+constructor TEMailProperties.Create;
+begin
+   inherited Create;
+   SetSize(0);
+   WriteFlags(0);
+end;
+
+constructor TIPNamePair.Create(const Name, IP: string);
+begin
+   FName:= Name;
+   FIP:= IP;
+end;
+
+constructor TEnvelope.Create;
+begin
+   inherited Create;
+   FReturnPath:= '';
+   FReturnPathSpecified:= false;
+   FRelayHost:= '';
+   SetLength(FRecipients, 0);
+end;
+
+destructor TEnvelope.Destroy;
+begin
+   SetLength(FRecipients, 0);
+   inherited Destroy;
+end;
+
+
+{ Object methods: }
+
+procedure TArgumentParser.ParseArgument(Arg: string; const AllowedPrefixes: TStringArray);
+var i, n: integer; found: boolean;
+begin
+   { Strip prefix if present. }
+   i:= 0; found:= false;
+   while ((i < Length(AllowedPrefixes)) and (not found)) do begin
+      if pos(AllowedPrefixes[i], Arg) = 1 then
+      begin
+         Delete(Arg, 1, Length(AllowedPrefixes[i]));
+         found:= true;
+      end;
+      Inc(i);
+   end;
+
+   n:= Length(Arguments);
+   SetLength(Arguments, n + 1);
+   SplitParameters(Arg, Arguments[n].Option, Arguments[n].Value, '=');
+   { To be case-insensitive: }
+   Arguments[n].Option:= UpCase(Arguments[n].Option);
+end;
+
+function TArgumentParser.GetArgument(ID: integer): TArgument;
+begin
+   { No index checking... you'd better use it return value of ValidateArguments. }
+   Result:= Arguments[ID];
+end;
+
+function TArgumentParser.IsPresent(ArgumentName: string): boolean;
+var i: integer;
+begin
+   i:= 0;
+   while (i < Length(Arguments)) and (Arguments[i].Option <> UpCase(ArgumentName)) do
+      Inc(i);
+   Result:= i < Length(Arguments);
+end;
+
+function TArgumentParser.GetValue(ArgumentName: string; DefValue: string = ''): string;
+var i: integer;
+begin
+   i:= 0;
+   while (i < Length(Arguments)) and (Arguments[i].Option <> UpCase(ArgumentName)) do
+      Inc(i);
+
+   if i < Length(Arguments) then begin
+      if Arguments[i].Value <> '' then
+         Result:= Arguments[i].Value
+      else
+         Result:= DefValue;
+   end
+   else
+      Result:= DefValue;
+end;
+
+function TArgumentParser.ValidateArguments(ValidArguments: TStringArray): integer;
+{ Returns -1 if all arguments are valid. Otherwise, returns the ID of the first
+  invalid parameter. }
+var i: integer;
+begin
+   i:= 0;
+   while (i < Length(Arguments)) and (Arguments[i] in ValidArguments) do
+      Inc(i);
+
+   if i < Length(Arguments) then
+      Result:= -1
+   else
+      Result:= i;
+end;
+
+
+function TNamedObject.IsItYourName(const Name: string): boolean;
+begin
+   Result:= FAliases.IndexOf(Name) <> -1;
+end;
+
+
+function TMainServerConfig.GetVersionStr: string;
+begin
+   Result:= VERSION_STR;
+end;
+
+
+function TIPNamePair.Copy: TIPNamePair;
+begin
+   Result:= TIPNamePair.Create(Name, IP);
+end;
+
+
+procedure TEMailProperties.SetSize(Value: longint);
+begin
+   FSize:= Value;
+end;
+
+procedure TEMailProperties.WriteFlags(Value: TEMailFlags);
+begin
+   FFlags:= Value;
+end;
+
+procedure TEMailProperties.SetFlag(Flag: TEMailFlags);
+begin
+   FFlags:= FFlags or Flag;
+end;
+
+function TEMailProperties.HasFlag(Flag: TEMailFlags): boolean;
+begin
+   Result:= (FFlags and Flag) = Flag;
+end;
+
+
+function TEnvelope.GetNumberOfRecipients: integer;
+begin
+   Result:= Length(FRecipients);
+end;
+
+function TEnvelope.GetRecipient(Index: integer): TRecipient;
+begin
+   Result:= FRecipients[Index];
+end;
+
+function TEnvelope.IsComplete: boolean;
+begin
+   Result:= FReturnPathSpecified and (Length(FRecipients) > 0);
+end;
+
+procedure TEnvelope.AddRecipient(Address: string; Data: integer = 0; RMsg: string = '');
+var i: integer;
+begin
+   i:= Length(FRecipients);
+   SetLength(FRecipients, i + 1);
+   FRecipients[i].Address:= Address;
+   FRecipients[i].RMsg:= RMsg;
+   FRecipients[i].Data:= Data;
+end;
+
+procedure TEnvelope.AddRecipient(Recipient: TRecipient);
+var i: integer;
+begin
+   i:= Length(FRecipients);
+   SetLength(FRecipients, i + 1);
+   FRecipients[i]:= Recipient;
+end;
+
+procedure TEnvelope.SetRecipientData(Index, Data: integer; RMsg: string = '');
+begin
+   FRecipients[Index].RMsg:= RMsg;
+   FRecipients[Index].Data:= Data;
+end;
+
+procedure TEnvelope.SetReturnPath(Address: string);
+begin
+   FReturnPath:= Address;
+   FReturnPathSpecified:= true;
+end;
+
+procedure TEnvelope.SetRelayHost(HostName: string);
+begin
+   FRelayHost:= HostName;
+end;
+
+
+end.
diff --git a/DNSMX.pas b/DNSMX.pas
new file mode 100644 (file)
index 0000000..d18dc6b
--- /dev/null
+++ b/DNSMX.pas
@@ -0,0 +1,180 @@
+{
+   Copyright (C) 2010-2014 MegaBrutal
+
+   This unit is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Lesser General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This unit is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+
+{$MODE DELPHI}
+unit DNSMX;
+
+(*
+
+   For reference, here are the C declarations of the used
+   functions and structures:
+
+   DNS_STATUS WINAPI DnsQuery(
+     __in         PCTSTR lpstrName,
+     __in         WORD wType,
+     __in         DWORD Options,
+     __inout_opt  PVOID pExtra,
+     __out_opt    PDNS_RECORD *ppQueryResultsSet,
+     __out_opt    PVOID *pReserved
+   );
+
+   void WINAPI DnsRecordListFree(
+     __inout_opt  PDNS_RECORD pRecordList,
+     __in         DNS_FREE_TYPE FreeType
+   );
+
+   typedef struct _DnsRecord {
+     DNS_RECORD *pNext;
+     PWSTR      pName;
+     WORD       wType;
+     WORD       wDataLength;
+     union {
+       DWORD            DW;
+       DNS_RECORD_FLAGS S;
+     } Flags;
+     DWORD      dwTtl;
+     DWORD      dwReserved;
+     union {
+       DNS_MX_DATA     MX, Mx, AFSDB, Afsdb, RT, Rt;
+     } Data;
+   } DNS_RECORD, *PDNS_RECORD;
+
+   typedef struct {
+     PWSTR pNameExchange;
+     WORD  wPreference;
+     WORD  Pad;
+   } DNS_MX_DATA, *PDNS_MX_DATA;
+
+*)
+
+interface
+uses SysUtils, Classes;
+
+const
+
+   DNS_TYPE_MX = $000F;
+
+type
+
+   pWideChar = pChar;
+
+   DnsMXData = packed record
+      pNameExchange: pWideChar;
+      wPreference: word;
+      Pad: word;
+   end;
+
+   ppDnsRecord = ^pDnsRecord;
+   pDnsRecord = ^DnsRecord;
+   DnsRecord = packed record
+      pNext: pDnsRecord;
+      pName: pWideChar;
+      wType: word;
+      wDataLength: word;
+      Flags: longword;
+      dwTtl: longword;
+      dwReserved: longword;
+      Data: DnsMXData;
+   end;
+
+   { Better to have a Pascal-format DnsMXData: }
+   TDNSMXRecord = record
+      Preference: word;
+      HostName: string;
+   end;
+
+   TDNSMXRecordArray = array of TDNSMXRecord;
+
+
+   function DnsQuery(lsstrName: PChar; wType: word; Options: longword;
+      pExtra: pointer; ppQueryResultsSet: ppDnsRecord; pReserved: pointer): longword; stdcall;
+      external 'dnsapi.dll' name 'DnsQuery_A';
+
+   procedure DnsRecordListFree(pRecordList: pDnsRecord; FreeType: word); stdcall;
+      external 'dnsapi.dll' name 'DnsRecordListFree';
+
+
+   function GetMXRecordArray(HostName: string; var ResultArray: TDNSMXRecordArray): boolean;
+   procedure SortMXRecordArray(var DNSMXRecordArray: TDNSMXRecordArray);
+   function MakeMXRecordList(const DNSMXRecordArray: TDNSMXRecordArray): TStrings;
+   function GetCorrectMXRecordList(HostName: string): TStrings;
+
+
+
+implementation
+
+
+function GetMXRecordArray(HostName: string; var ResultArray: TDNSMXRecordArray): boolean;
+var P, N: pDnsRecord; DNSMXRecord: TDNSMXRecord; ap: integer;
+begin
+   P:= nil;
+   DnsQuery(PChar(HostName), DNS_TYPE_MX, 0, nil, @P, nil);
+   N:= P;
+   while N <> nil do begin
+      if N^.wType = DNS_TYPE_MX then begin
+         DNSMXRecord.Preference:= N^.Data.wPreference;
+         DNSMXRecord.HostName:= N^.Data.pNameExchange;
+         ap:= Length(ResultArray);
+         SetLength(ResultArray, ap + 1);
+         ResultArray[ap]:= DNSMXRecord;
+      end;
+      N:= N^.pNext;
+   end;
+   if P <> nil then DnsRecordListFree(P, 0);
+   Result:= Length(ResultArray) <> 0;
+end;
+
+procedure SortMXRecordArray(var DNSMXRecordArray: TDNSMXRecordArray);
+var i, j: integer; T: TDNSMXRecord;
+begin
+   for i:= 1 to Length(DNSMXRecordArray) - 1 do begin
+      T:= DNSMXRecordArray[i];
+      j:= i;
+      while (j > 0) and (DNSMXRecordArray[j-1].Preference > T.Preference) do begin
+         DNSMXRecordArray[j]:= DNSMXRecordArray[j-1];
+         Dec(j);
+      end;
+      DNSMXRecordArray[j]:= T;
+   end;
+end;
+
+function MakeMXRecordList(const DNSMXRecordArray: TDNSMXRecordArray): TStrings;
+var i: integer;
+begin
+   Result:= TStringList.Create;
+   for i:= 0 to Length(DNSMXRecordArray) - 1 do
+      Result.Add(DNSMXRecordArray[i].HostName);
+end;
+
+function GetCorrectMXRecordList(HostName: string): TStrings;
+var DNSMXRecordArray: TDNSMXRecordArray;
+begin
+   SetLength(DNSMXRecordArray, 0);
+   if GetMXRecordArray(HostName, DNSMXRecordArray) then begin
+      SortMXRecordArray(DNSMXRecordArray);
+      Result:= MakeMXRecordList(DNSMXRecordArray);
+   end
+   else begin
+      { If the domain has no MX record, the A record shall be used. }
+      Result:= TStringList.Create;
+      Result.Add(HostName);
+   end;
+end;
+
+
+end.
diff --git a/DNSResolve.pas b/DNSResolve.pas
new file mode 100644 (file)
index 0000000..6e6acff
--- /dev/null
@@ -0,0 +1,58 @@
+{
+   Copyright (C) 2010 MegaBrutal
+
+   This unit is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Lesser General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This unit is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+
+{$MODE FPC}
+
+unit DNSResolve;
+
+interface
+uses WinSock, Sockets;
+
+
+   function ResolveHost(HostName: ansistring): in_addr;
+   function ResolveIP(IP: in_addr): ansistring;
+
+
+implementation
+
+
+function ResolveHost(HostName: ansistring): in_addr;
+var
+   HostEnt: PHostEnt;
+begin
+   HostEnt:= gethostbyname(PChar(HostName));
+   if HostEnt <> nil then
+      ResolveHost.s_addr:= PLongWord(HostEnt^.h_addr_list[0])^
+   else
+      ResolveHost.s_addr:= 0;
+end;
+
+function ResolveIP(IP: in_addr): ansistring;
+var
+   HostEnt: PHostEnt;
+begin
+   HostEnt:= gethostbyaddr(@IP, 4, AF_INET);
+   if HostEnt <> nil then
+      ResolveIP:= HostEnt^.h_name
+   else
+      ResolveIP:= NetAddrToStr(IP);
+end;
+
+
+
+end.
diff --git a/EINIFiles.pas b/EINIFiles.pas
new file mode 100644 (file)
index 0000000..c17c6b8
--- /dev/null
@@ -0,0 +1,48 @@
+{
+   Copyright (C) 2010 MegaBrutal
+
+   This unit is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Lesser General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This unit is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+
+{$MODE DELPHI}
+unit EINIFiles;
+
+interface
+uses SysUtils, INIFiles;
+
+type
+
+   TExtBoolINIFile = class(TINIFile)
+   public
+      function ReadBool(const Section, Ident: string; Default: boolean): boolean; override;
+   end;
+
+
+
+implementation
+
+
+function TExtBoolINIFile.ReadBool(const Section, Ident: string; Default: boolean): boolean;
+var Value: string; DefValStr: shortstring;
+begin
+   if Default then DefValStr:= 'ON' else DefValStr:= 'OFF';
+   Value:= UpperCase(ReadString(Section, Ident, DefValStr));
+   if Value = 'ON' then        Result:= true
+   else if Value = 'OFF' then  Result:= false
+   else                        Result:= inherited ReadBool(Section, Ident, Default);
+end;
+
+
+end.
\ No newline at end of file
diff --git a/Listener.pas b/Listener.pas
new file mode 100644 (file)
index 0000000..a4d94f0
--- /dev/null
@@ -0,0 +1,559 @@
+{
+   MegaBrutal's SMTP Server (MgSMTP)
+   Copyright (C) 2010-2014 MegaBrutal
+
+   This program is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Affero General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Affero General Public License for more details.
+
+   You should have received a copy of the GNU Affero General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+{
+   Unit: Listener
+   This unit is responsible for listening for incoming connections, and
+   serve them, communicating by the SMTP protocol.
+
+   It always places incoming e-mails in the spool, and lets it to process
+   them later. However, this unit still links the Mailbox and Relay unit to
+   verify addresses. The Policies unit also plays an important role, it
+   determines what rights does the client have, and it authenticates users.
+}
+
+
+{$MODE DELPHI}
+unit Listener;
+
+interface
+uses SysUtils, Classes, Base64, Network, NetRFC, RFCSMTP,
+     Common, Log, Policies, Spool, Mailbox, Relay;
+
+type
+
+   TMgSMTPListener = class(TTCPListener)
+      constructor Create(Port: word);
+   protected
+      procedure HandleClient(Connection: TTCPConnection); override;
+      procedure ReceiveEMailData(TCP: TTCPRFCConnection; Response: TRFCReply; SpoolObject: TSpoolObjectCreator);
+   end;
+
+
+   procedure StartListeners;
+   procedure StopListeners;
+
+
+implementation
+
+var
+
+   MgSMTPListeners: array of TMgSMTPListener;
+
+
+procedure StartListeners;
+var i: integer;
+begin
+   SetLength(MgSMTPListeners, MainServerConfig.ListenPorts.Count);
+   for i:= 0 to Length(MgSMTPListeners) - 1 do begin
+      MgSMTPListeners[i]:= TMgSMTPListener.Create(StrToIntDef(MainServerConfig.ListenPorts.Strings[i], STANDARD_SMTP_PORT));
+      MgSMTPListeners[i].StartListen;
+   end;
+end;
+
+procedure StopListeners;
+var i: integer;
+begin
+   for i:= 0 to Length(MgSMTPListeners) - 1 do begin
+      MgSMTPListeners[i].StopListen;
+      MgSMTPListeners[i].Free;
+   end;
+   SetLength(MgSMTPListeners, 0);
+end;
+
+
+function Base64Decode(Source: string): string;
+var StringStream: TStringStream; Base64DecodingStream: TBase64DecodingStream;
+    c: char;
+begin
+   StringStream:= TStringStream.Create(Source);
+   Base64DecodingStream:= TBase64DecodingStream.Create(StringStream);
+   Result:= '';
+   while not Base64DecodingStream.EOF do begin
+      Base64DecodingStream.Read(c, 1);
+      Result:= Result + c;
+   end;
+   Base64DecodingStream.Destroy;
+   StringStream.Destroy;
+end;
+
+procedure SetEMailProperties(Parameters: string; SpoolObject: TSpoolObject);
+var CPrm, Rem, Key, Value: string;
+begin
+   { Cut down e-mail address. }
+   SplitParameters(Parameters, CPrm, Rem);
+   repeat
+      SplitParameters(Rem, CPrm, Rem);
+      SplitParameters(CPrm, Key, Value, '=');
+      Key:= UpperCase(Key);
+      if Key = 'SIZE' then SpoolObject.EMailProperties.Size:= StrToIntDef(Value, 0)
+      else if Key = 'BODY' then begin
+         if UpperCase(Value) = '8BITMIME' then
+            SpoolObject.EMailProperties.SetFlag(EF_8BITMIME);
+      end;
+   until (Rem = '');
+end;
+
+function HandleRewrite(OriginalAddress: string; Mailbox: PMailbox; SpoolObject: TSpoolObjectCreator): string;
+var i: integer;
+begin
+   for i:= 0 to Mailbox^.RewriteCount - 1 do
+      SpoolObject.Envelope.AddRecipient(Mailbox^.GetRewriteToEntry(i));
+   if Mailbox^.RewritePassThru then
+      SpoolObject.Envelope.AddRecipient(OriginalAddress);
+   if Mailbox^.RewriteCount > 0 then begin
+      if Mailbox^.RewritePassThru then
+         Result:= 'Rewrite: ' + OriginalAddress + ' -> ' + OriginalAddress + ',' + Mailbox^.GetRewriteToListStr
+      else
+         Result:= 'Rewrite: ' + OriginalAddress + ' -> ' + Mailbox^.GetRewriteToListStr;
+   end
+   else
+      Result:= '';
+end;
+
+
+constructor TMgSMTPListener.Create(Port: word);
+begin
+   { Request connection objects with support for RFC-style commands & responses. }
+   inherited Create(Port, NET_TCP_RFCSUPPORT);
+   Logger.AddLine('Server', 'Listening on port: ' + IntToStr(Port));
+end;
+
+
+procedure TMgSMTPListener.HandleClient(Connection: TTCPConnection);
+{ This is the procedure that actually handles the clients. It receives
+  an object that manages the established connection in the parameter.
+  TTCPConnection is defined in the Network unit. }
+var
+   TCP: TTCPRFCConnection;
+   Originator: TIPNamePair;
+   Response: TRFCReply;
+   PolicyObject: TPolicyObject;
+   SpoolObject: TSpoolObjectCreator;
+   Cmd: shortstring; Prm, OPrm: string;
+   Auth_Username, Auth_Password: string; FailedAuthAttempts: integer;
+   HELOSent, SpoolAllocated, ReadSucceeded, UnexpectedFail: boolean;
+   VStr: string; LogAgent: string;
+   TempStr: string;
+
+   procedure SendAndLogResponse(NumericCode: word; ReplyText: shortstring; ExpectFail: boolean = false);
+   begin
+      if (Logger.AddLine(LogAgent, 'Response: ' + IntToStr(NumericCode) + ' ' + ReplyText)) or ExpectFail then begin
+         Response.SetReply(NumericCode, ReplyText);
+         TCP.SendResponse(Response);
+      end
+      else begin
+         SendAndLogResponse(SMTP_R_SERVICE_NA, 'Internal error: could not write log', true);
+         Logger.AddStdLine(LogAgent, 'Log write failure. Terminating active connection.');
+         UnexpectedFail:= true;
+      end;
+   end;
+
+begin
+   TCP:= Connection as TTCPRFCConnection;
+   TCP.SetSockTimeOut(DEF_SOCK_TIMEOUT);
+   TCP.ReverseDNSLookup;
+   Originator:= TCP.HostIP.Copy;
+   Response:= TRFCReply.Create;
+   {PolicyObject:= PolicyManager.MakePolicyObject(Originator.Copy);}
+   PolicyObject:= PolicyManager.MakePolicyObject(Originator);
+   SpoolObject:= nil;
+   HELOSent:= false; SpoolAllocated:= false; UnexpectedFail:= false;
+   FailedAuthAttempts:= 0;
+
+   { Prepare for logging. To make this connection distinguishable, we add
+     the actual thread's ID to each log entry. }
+   LogAgent:= 'Server ' + IntToStr(GetCurrentThreadId);
+   Logger.AddLine(LogAgent, 'Client connected: ' + Originator.Name + ' (' + Originator.IP + ')');
+   Logger.AddLine(LogAgent, 'Assigned rights (for host): ' + PolicyObject.RightsStr);
+
+   { Verify FCrDNS if necessary. Note, maybe it would have been simpler to
+     check it around the TCP.ReverseDNSLookup call, and then only pass the
+     trusted result to PolicyManager.MakePolicyObject. The main idea why I
+     didn't implement it that way is that I'd like to see if the granted
+     rights actually change after the FCrDNS check. }
+   if PolicyManager.FCrDNSPolicy <> FCRDNS_NAIVE then begin
+      if not TCP.VerifyFCrDNS then begin
+         PolicyManager.RevalidatePolicyObject(PolicyObject, Originator, false, PolicyManager.FCrDNSPolicy = FCRDNS_MEAN);
+         if PolicyManager.FCrDNSPolicy = FCRDNS_STRICT then
+            PolicyObject.Deny(RIGHT_CONNECT);
+         Logger.AddLine(LogAgent, 'WARNING: "' + Originator.Name + '" is not a forward-confirmed reverse hostname! Rights will be reassigned by IP only!');
+         Logger.AddLine(LogAgent, 'Assigned rights (for host): ' + PolicyObject.RightsStr);
+      end;
+   end;
+
+   if PolicyObject.HasRight(RIGHT_CONNECT) then begin
+      if not PolicyManager.HideVersion then VStr:= ' ' + MainServerConfig.VersionStr else VStr:= '';
+      Response.SetReply(SMTP_R_READY, MainServerConfig.Name + ' SMTP server ready (MgSMTP' + VStr + ')');
+      TCP.SendResponse(Response);
+
+      repeat
+         ReadSucceeded:= TCP.ReadCommand(Cmd, Prm);
+
+         { Check if command only contains printable ASCII characters, not some binary garbage. }
+         if ReadSucceeded then begin
+            if IsPrintableString(Cmd) and IsPrintableString(Prm) then begin
+               Logger.AddLine(LogAgent, 'Command: ' + Cmd + ' ' + Prm);
+               Cmd:= UpperCase(Cmd);
+            end
+            else begin
+               SendAndLogResponse(SMTP_R_SERVICE_NA, 'Non-printable characters are not allowed in SMTP commands! Stop abusing my service!');
+               UnexpectedFail:= true;
+            end;
+         end;
+
+         if (Length(Cmd) = 0) or (not ReadSucceeded) or UnexpectedFail then { Nothing. }
+
+         else if (Cmd = 'GET') or (Cmd = 'HEAD') or (Cmd = 'POST') then begin
+            SendAndLogResponse(SMTP_R_SERVICE_NA, 'Please learn to speak SMTP for I won''t speak HTTP. Stop abusing my service!');
+            UnexpectedFail:= true;
+         end
+
+         else if (Cmd = SMTP_C_HELO) or (Cmd = SMTP_C_EHLO) then begin
+            Response.SetReply(SMTP_R_OK, MainServerConfig.Name);
+            if Cmd = SMTP_C_EHLO then begin
+               Response.Add('SIZE ' + IntToStr(PolicyObject.Databytes));
+               {Response.Add('VRFY');}
+               Response.Add('PIPELINING');
+               Response.Add('8BITMIME');
+               if PolicyManager.Users then begin
+                  Response.Add('AUTH LOGIN');
+                  Response.Add('AUTH=LOGIN');
+               end;
+            end;
+            TCP.SendResponse(Response);
+            Originator.Free;
+            Originator:= TIPNamePair.Create(Prm, TCP.HostIP.IP);
+            HELOSent:= true;
+            Logger.AddLine(LogAgent, 'Client identified: ' + Originator.Name + ' (' + Originator.IP + ')');
+         end
+
+         else if Cmd = SMTP_C_AUTH then begin
+            if PolicyManager.Users then begin
+               { Only "AUTH LOGIN" is supported. }
+               SplitParameters(Prm, Prm, OPrm);
+               if Prm = 'LOGIN' then begin
+                  if OPrm = '' then begin
+                     { Base64-encoded "Username:" }
+                     Response.SetReply(SMTP_R_AUTH_MESSAGE, 'VXNlcm5hbWU6');
+                     TCP.SendResponse(Response);
+                     TCP.ReadLn(Auth_Username);
+                     Auth_Username:= Base64Decode(Auth_Username);
+                  end
+                  else
+                     Auth_Username:= Base64Decode(OPrm);
+                  { Base64-encoded "Password:" }
+                  Response.SetReply(SMTP_R_AUTH_MESSAGE, 'UGFzc3dvcmQ6');
+                  TCP.SendResponse(Response);
+                  TCP.ReadLn(Auth_Password);
+                  { Verify }
+                  if PolicyManager.AuthenticateUser(Auth_Username, Base64Decode(Auth_Password), PolicyObject) then begin
+                     Response.SetReply(SMTP_R_AUTH_SUCCESSFUL, 'Authentication successful');
+                     Logger.AddLine(LogAgent, 'Successfully authenticated as user: ' + Auth_Username);
+                     Logger.AddLine(LogAgent, 'Assigned rights (for user): ' + PolicyObject.RightsStr);
+                  end
+                  else begin
+                     Inc(FailedAuthAttempts);
+                     Response.SetReply(SMTP_R_AUTH_FAILED, 'Authentication failed');
+                     Logger.AddLine(LogAgent, 'AUTHENTICATION FAILED as user: ' + Auth_Username);
+                  end;
+                  TCP.SendResponse(Response);
+                  if (PolicyManager.MaxAuthAttempts <> 0) and (PolicyManager.MaxAuthAttempts <= FailedAuthAttempts) then begin
+                     SendAndLogResponse(SMTP_R_SERVICE_NA, 'Too many unsuccessful authentication attempts! Stop abusing my service!');
+                     UnexpectedFail:= true;
+                     Logger.AddLine(LogAgent, 'MAXIMUM AUTHENTICATION ATTEMPTS REACHED - DISCONNECTING CLIENT!');
+                  end;
+               end
+               else
+                  SendAndLogResponse(SMTP_R_PRM_NOT_IMPLEMENTED, 'Authentication type not implemented');
+            end
+            else
+               SendAndLogResponse(SMTP_R_CMD_NOT_IMPLEMENTED, 'User authentication is not enabled on this server.');
+         end
+
+         else if Cmd = SMTP_C_RSET then begin
+            { We must be careful to always free the spool object, if we
+              have allocated one, but we don't need it anymore. }
+            if SpoolAllocated then begin
+               if SpoolObject.Opened then SpoolObject.Discard;
+               SpoolObject.Free;
+               SpoolAllocated:= false;
+            end;
+            Response.SetReply(SMTP_R_OK, 'OK');
+            TCP.SendResponse(Response);
+         end
+
+         else if Cmd = SMTP_C_NOOP then begin
+            Response.SetReply(SMTP_R_OK, 'Not like I was doing anything...');
+            TCP.SendResponse(Response);
+         end
+
+         else if Cmd = SMTP_C_QUIT then begin
+            { No extra action is required here to close the connection.
+              The repeat-until loop will quit anyway, and the connection
+              will be closed afterwards. }
+            Response.SetReply(SMTP_R_CLOSE, 'Goodbye. :)');
+            TCP.SendResponse(Response);
+         end
+
+         else if (HELOSent) or (not PolicyManager.ReqHELO) then begin
+
+            { Some commands are only accepted after the client has greeted
+              us with a HELO or EHLO command. }
+
+            if Cmd = SMTP_C_MAIL then begin
+               { A new spool object is allocated with the mail command. }
+               if not SpoolAllocated then begin
+                  OPrm:= Prm;
+                  Prm:= CleanEMailAddress(Prm);
+                  if (Prm = '') or (IsValidEMailAddress(Prm)) then begin
+                     SpoolObject:= SpoolManager.CreateSpoolObject(Originator.Copy);
+                     SpoolObject.Envelope.ReturnPath:= Prm;
+                     SpoolObject.Databytes:= PolicyObject.Databytes;
+                     SetEMailProperties(OPrm, SpoolObject);
+                     if (SpoolObject.EMailProperties.Size <= SpoolObject.Databytes) then begin
+                        Response.SetReply(SMTP_R_OK, 'OK');
+                        TCP.SendResponse(Response);
+                        SpoolAllocated:= true;
+                        Logger.AddLine(LogAgent, 'Return-Path accepted: <' + Prm + '>');
+                     end
+                     else begin
+                        SendAndLogResponse(SMTP_R_STOR_EXCEEDED, 'Declared message size exceeds the configured databytes limit');
+                        SpoolObject.Free;
+                     end;
+                  end
+                  else
+                     SendAndLogResponse(SMTP_R_MB_SYNTAX_ERROR, '<' + Prm + '>: Sender address rejected: Syntax error');
+               end
+               else
+                  SendAndLogResponse(SMTP_R_BAD_SEQUENCE, 'Return-Path is already specified, use RSET to discard it');
+            end
+
+            else if Cmd = SMTP_C_RCPT then begin
+               if SpoolAllocated then begin
+                  Prm:= CleanEMailAddress(Prm);
+
+                  { According to the RFC, we must accept "POSTMASTER" address without a hostname. }
+                  if UpperCase(Prm) = 'POSTMASTER' then Prm:= Prm + '@' + MainServerConfig.Name;
+                  if IsValidEMailAddress(Prm) then begin
+
+                     if MailboxManager.IsLocalAddress(Prm) then begin
+
+                        { Many conditions need to be checked before accepting a local e-mail:
+                          - Does this server accept local e-mails by configuration?
+                          - Does the client have the right to STORE a local e-mail?
+                          - Does the addressed mailbox exist?
+                          - Does the mailbox have free quota?
+                          If the answer is "no" for any of these questions, reject the address
+                          with a proper error response. }
+
+                        if MainServerConfig.Mailbox then begin
+                           if PolicyObject.HasRight(RIGHT_STORE) then begin
+                              if MailboxManager.Verify(Prm) then begin
+                                 if MailboxManager.VerifyAlias(Prm) then begin
+                                    if ((not SpoolManager.AllowExceedQuota) and (MailboxManager.CheckQuota(EMailUserName(Prm), EMailHost(Prm), SpoolObject.EMailProperties.Size)))
+                                    or ((SpoolManager.AllowExceedQuota) and (MailboxManager.CheckQuota(EMailUserName(Prm), EMailHost(Prm), 0))) then begin
+
+                                       if MailboxManager.Rewrite then begin
+                                          TempStr:= HandleRewrite(Prm, MailboxManager.GetMailbox(EMailUserName(Prm), EMailHost(Prm)), SpoolObject);
+                                          if Length(TempStr) > 0 then
+                                             Logger.AddLine(LogAgent, TempStr);
+                                       end
+                                       else
+                                          SpoolObject.Envelope.AddRecipient(Prm);
+
+                                       Response.SetReply(SMTP_R_OK, 'OK');
+                                       TCP.SendResponse(Response);
+                                       Logger.AddLine(LogAgent, 'Local recipient accepted: <' + Prm + '>');
+                                    end
+                                    else
+                                       SendAndLogResponse(SMTP_R_STOR_EXCEEDED, '<' + Prm + '>: User quota exceeded');
+                                 end
+                                 else
+                                    SendAndLogResponse(SMTP_R_MAILBOX_NA, '<' + Prm + '>: Mailbox alias rejected');
+                              end
+                              else
+                                 SendAndLogResponse(SMTP_R_MAILBOX_NA, '<' + Prm + '>: No mailbox here by that name');
+                           end
+                           else
+                              SendAndLogResponse(SMTP_R_MAILBOX_NA, '<' + Prm + '>: Store access denied');
+                        end
+                        else
+                           SendAndLogResponse(SMTP_R_MAILBOX_NA, '<' + Prm + '>: This server doesn''t store local messages');
+                     end
+
+                     else if MainServerConfig.Relay then begin
+
+                        { Things to check for relay addresses:
+                          - Does the server ever accept relay addresses by configuration?
+                          - Does the client has the right to RELAY messages or in the case
+                            if the relay address is on the RelayTo list, does the client
+                            has the STORE right?
+                        }
+
+                        if (PolicyObject.HasRight(RIGHT_RELAY))
+                           or (PolicyObject.HasRight(RIGHT_STORE) and RelayManager.IsOnRelayToList(EMailHost(Prm))) then begin
+                           if not RelayManager.IsOnNoRelayToList(EMailHost(Prm)) then begin
+                              SpoolObject.Envelope.AddRecipient(Prm);
+                              Response.SetReply(SMTP_R_OK, 'OK');
+                              TCP.SendResponse(Response);
+                              Logger.AddLine(LogAgent, 'Relay recipient accepted: <' + Prm + '>');
+                           end
+                           else
+                              SendAndLogResponse(SMTP_R_TRANS_FAILED, '<' + Prm + '>: Relaying towards this domain is not permitted');
+                        end
+                        else
+                           SendAndLogResponse(SMTP_R_TRANS_FAILED, '<' + Prm + '>: Relay access denied, or maybe I just don''t like you');
+                     end
+                     else
+                        SendAndLogResponse(SMTP_R_TRANS_FAILED, '<' + Prm + '>: Relaying has been disabled by configuration');
+                  end
+                  else
+                     SendAndLogResponse(SMTP_R_MB_SYNTAX_ERROR, '<' + Prm + '>: Recipient address rejected: Syntax error');
+               end
+               else
+                  SendAndLogResponse(SMTP_R_BAD_SEQUENCE, 'You must initiate e-mail transactions with MAIL command');
+            end
+
+            else if Cmd = SMTP_C_DATA then begin
+               if SpoolAllocated then begin
+                  if SpoolObject.Envelope.IsComplete then begin
+                     ReceiveEMailData(TCP, Response, SpoolObject);
+                     Logger.AddLine(LogAgent, 'Response: ' + IntToStr(Response.NumericCode) + ' ' + Response.GetLine(0));
+                     TCP.SendResponse(Response);
+                     Logger.AddLine('Object ' + SpoolObject.Name, 'Message-ID: <' + SpoolObject.OriginalMessageID + '>');
+                     SpoolObject.Free;
+                     SpoolAllocated:= false;
+                  end
+                  else
+                     SendAndLogResponse(SMTP_R_TRANS_FAILED, 'No valid recipients');
+               end
+               else
+                  SendAndLogResponse(SMTP_R_BAD_SEQUENCE, 'You must initiate e-mail transactions with MAIL command');
+            end
+
+            else if Cmd = SMTP_C_VRFY then
+               SendAndLogResponse(SMTP_R_CANNOTVERIFY, 'Honestly, I don''t like to verify addresses')
+
+            else
+               SendAndLogResponse(SMTP_R_CMD_SYNTAX_ERROR, 'Command not recognized (' + Cmd + ')');
+         end
+
+         else
+            SendAndLogResponse(SMTP_R_BAD_SEQUENCE, 'It would be more polite to say HELO first');
+
+      until (Cmd = SMTP_C_QUIT) or (not ReadSucceeded) or (UnexpectedFail);
+
+      if not ReadSucceeded then
+         SendAndLogResponse(SMTP_R_SERVICE_NA, 'Socket read error');
+   end
+
+   else begin
+
+      { If the client doesn't have the right to CONNECT here, disconnect it
+        with a rather unfriendly message. }
+
+      SendAndLogResponse(SMTP_R_TRANS_FAILED, 'Host is not permitted by server configuration');
+      SendAndLogResponse(SMTP_R_SERVICE_NA, 'You are not welcome here, I shall disconnect you');
+      {repeat
+         TCP.ReadCommand(Cmd, Prm);
+         if Cmd <> SMTP_C_QUIT then
+            Response.SetReply(SMTP_R_BAD_SEQUENCE, 'You are not welcome here, I suggest you to QUIT')
+         else
+            Response.SetReply(SMTP_R_CLOSE, 'Closing connection');
+         TCP.SendResponse(Response);
+      until Cmd = SMTP_C_QUIT;}
+   end;
+
+   { Free the spool object (if we have any), close the connection,
+     and free other allocated resources, log disconnection. }
+
+   if SpoolAllocated then begin
+      if SpoolObject.Opened then SpoolObject.Discard;
+      SpoolObject.Free;
+   end;
+   PolicyObject.Free;
+   Response.Free;
+   Originator.Free;
+   TCP.Free;
+   Logger.AddLine(LogAgent, 'Client disconnected.');
+end;
+
+procedure TMgSMTPListener.ReceiveEMailData(TCP: TTCPRFCConnection; Response: TRFCReply; SpoolObject: TSpoolObjectCreator);
+{ Receive e-mail lines until a line with a single dot (".") arrives.
+  Check databytes limit!
+  This procedure should never call TCP.SendResponse - the set up response
+  will be sent by the caller! }
+var Line: string; Done, ReadOK: boolean;
+begin
+   if SpoolObject.Open then begin
+      Response.SetReply(SMTP_R_START_MAIL_INPUT, 'Start mail input; end with "<CRLF>.<CRLF>" sequence');
+      TCP.SendResponse(Response);
+      Done:= false;
+      repeat
+         ReadOK:= TCP.ReadLn(Line);
+         if Line <> '.' then
+            SpoolObject.DeliverMessagePart(Line)
+         else
+            Done:= true;
+      until Done or (not ReadOK);
+      if ReadOK then begin
+         if SpoolObject.GetErrorCode <> SCE_NO_ERROR then begin
+
+            case SpoolObject.GetErrorCode of
+
+               SCE_SIZE_EXCEEDED:
+                  Response.SetReply(SMTP_R_STOR_EXCEEDED, 'Message size exceeds the configured databytes limit');
+
+               SCE_LOOP_DETECTED:
+               begin
+                  Response.Clear;
+                  Response.SetNumericCode(SMTP_R_TRANS_FAILED);
+                  Response.Add('Too many "Received" headers in mail data.');
+                  Response.Add('It''s likely that your message got trapped in a mail relay loop. In most');
+                  Response.Add('cases it is caused by faulty mail server configuration. Please notify the');
+                  Response.Add('administrator by forwarding this failure notice to the following address:');
+                  Response.Add('<postmaster@' + MainServerConfig.Name + '>!');
+               end;
+
+               SCE_WRITE_FAIL:
+                  Response.SetReply(SMTP_R_ABORTED, 'Could not write mail data. Try again later.');
+
+               else
+                  Response.SetReply(SMTP_R_ABORTED, 'Unknown error. Could not queue mail data.');
+
+            end;
+
+            SpoolObject.Discard;
+
+         end
+         else begin
+            Response.SetReply(SMTP_R_OK, 'Queued as ' + SpoolObject.Name);
+            SpoolObject.Close;
+         end;
+      end
+      else begin
+         Response.SetReply(SMTP_R_SERVICE_NA, 'Socket read error in DATA phase (timeout?)');
+         SpoolObject.Discard;
+      end;
+   end
+   else Response.SetReply(SMTP_R_ABORTED, 'Internal error: could not open spool object');
+end;
+
+
+end.
diff --git a/Log.pas b/Log.pas
new file mode 100644 (file)
index 0000000..9800121
--- /dev/null
+++ b/Log.pas
@@ -0,0 +1,171 @@
+{
+   MegaBrutal's SMTP Server (MgSMTP)
+   Copyright (C) 2010-2014 MegaBrutal
+
+   This program is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Affero General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Affero General Public License for more details.
+
+   You should have received a copy of the GNU Affero General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+{
+   Unit: Log
+   Supports basic logging features.
+}
+
+
+{$MODE DELPHI}
+unit Log;
+
+interface
+uses SysUtils, Classes, INIFiles, Common;
+
+type
+
+   TStreamLogger = class
+      constructor Create(Stream: TStream);
+      destructor Destroy; override;
+   protected
+      LogFile: TStream;
+      function AddPureLine(Line: string): boolean; virtual;
+   public
+      function AddLine(Line: string): boolean; overload;
+      function AddLine(Agent, Line: string): boolean; overload;
+      function WriteLn(Line: string): boolean; overload;
+      function WriteLn: boolean; overload;
+   end;
+
+
+   TLogger = class(TStreamLogger)
+      constructor Create(Config: TINIFile);
+      destructor Destroy; override;
+   protected
+      FLogOn: boolean;
+      FLogFileName: string;
+      {FLogLevel: integer;}
+      function AddPureLine(Line: string): boolean; override;
+   public
+      function AddStdLine(Line: string): boolean; overload;
+      function AddStdLine(Agent, Line: string): boolean; overload;
+   end;
+
+
+var
+
+   Out: TStreamLogger;
+   Logger: TLogger;
+
+
+
+implementation
+
+const
+
+   LOG_FN_STDOUT        =  'mgsmtp_stdout.log';
+   LOG_FN_STDOUT_PREV   =  'mgsmtp_stdout_previousrun.log';
+   LOG_FN_SMTP          =  'smtp.log';
+
+
+constructor TStreamLogger.Create(Stream: TStream);
+begin
+   LogFile:= Stream;
+end;
+
+destructor TStreamLogger.Destroy;
+begin
+   LogFile.Free;
+end;
+
+constructor TLogger.Create(Config: TINIFile);
+begin
+   FLogOn:= MainServerConfig.Log;
+   if FLogOn then begin
+      FLogFileName:= Config.ReadString('Log', 'Filename', LOG_FN_SMTP);
+      if not FileExists(FLogFileName) then begin
+         LogFile:= TFileStream.Create(FLogFileName, fmCreate);
+         LogFile.Free;
+      end;
+      LogFile:= TFileStream.Create(FLogFileName, fmOpenWrite or fmShareDenyWrite);
+      LogFile.Seek(0, soFromEnd);
+      AddPureLine('');
+      AddPureLine('');
+      AddPureLine('MgSMTP version ' + MainServerConfig.VersionStr + ', session log');
+      AddPureLine('Log started: ' + DateTimeToStr(Now));
+   end;
+end;
+
+destructor TLogger.Destroy;
+begin
+   if FLogOn then
+      AddPureLine('Log finished: ' + DateTimeToStr(Now));
+   inherited Destroy;
+end;
+
+
+function TStreamLogger.AddPureLine(Line: string): boolean;
+begin
+   Result:= WriteLineToStream(LogFile, Line);
+end;
+
+function TStreamLogger.AddLine(Line: string): boolean;
+begin
+   Result:= AddPureLine('[' + DateTimeToStr(Now) + '] ' + Line);
+end;
+
+function TStreamLogger.AddLine(Agent, Line: string): boolean;
+begin
+   Result:= AddPureLine('[' + DateTimeToStr(Now) + '] <' + Agent + '> ' + Line);
+end;
+
+function TStreamLogger.WriteLn(Line: string): boolean;
+{ Only a wrapper for AddPureLine for convenience. }
+begin
+   Result:= AddPureLine(Line);
+end;
+
+function TStreamLogger.WriteLn: boolean;
+begin
+   Result:= AddPureLine('');
+end;
+
+function TLogger.AddPureLine(Line: string): boolean;
+begin
+   if FLogOn then
+      Result:= inherited AddPureLine(Line)
+   else
+      Result:= true;
+end;
+
+function TLogger.AddStdLine(Line: string): boolean;
+{ Log message to both stdout and smtp.log. }
+begin
+   Result:= Out.AddLine(Line) and AddLine(Line);
+end;
+
+function TLogger.AddStdLine(Agent, Line: string): boolean;
+{ Log message to both stdout and smtp.log. }
+begin
+   Result:= Out.AddLine(Agent, Line) and AddLine(Agent, Line);
+end;
+
+
+
+initialization
+   if StdOutputHandle > 0 then
+      Out:= TStreamLogger.Create(THandleStream.Create(StdOutputHandle))
+   else begin
+      DeleteFile(LOG_FN_STDOUT_PREV);
+      RenameFile(LOG_FN_STDOUT, LOG_FN_STDOUT_PREV);
+      Out:= TStreamLogger.Create(TFileStream.Create(LOG_FN_STDOUT, fmCreate or fmShareDenyWrite));
+   end;
+finalization
+   Out.Free;
+end.
diff --git a/Mailbox.pas b/Mailbox.pas
new file mode 100644 (file)
index 0000000..b600a2a
--- /dev/null
@@ -0,0 +1,678 @@
+{
+   MegaBrutal's SMTP Server (MgSMTP)
+   Copyright (C) 2010-2014 MegaBrutal
+
+   This program is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Affero General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Affero General Public License for more details.
+
+   You should have received a copy of the GNU Affero General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+{
+   Unit: Mailbox
+   Administers mailboxes. It implements methods to place messages into the
+   mailbox files.
+}
+
+
+{$MODE DELPHI}
+
+unit Mailbox;
+
+interface
+uses SysUtils, SyncObjs, Classes, INIFiles, Common, Log, Spool;
+
+type
+
+   PMailbox = ^TMailbox;
+   TMailbox = class(TNamedObject)
+      constructor Create(const Name, Domain: string; Config: TINIFile; Slave: boolean; DefaultQuota: longint);
+      destructor Destroy; override;
+   protected
+      FDomain: string;
+      FQuota, FLockID: longint;
+      CriticalSection: TCriticalSection;
+   private
+      FPlusAliases: boolean;
+      FRewritePassThru: boolean;
+      PlusAliasExceptList: TStringList;
+      RewriteToList: TStringList;
+      MailboxFile: TStream;
+      procedure AddTrackHeaders(EMail, Recipient: string; Headers: TStrings);
+      { class function GetConfigSectionName(const Name, Domain: string): string; }
+      class function GetMailboxConfig(Config: TINIFile; const Name, Domain, Ident, Default: string): string; overload;
+      class function GetMailboxConfig(Config: TINIFile; const Name, Domain, Ident: string; Default: boolean): boolean; overload;
+   public
+      function IsItYourName(const Name: string): boolean; override;
+      function GetMailboxAddress: string;
+      function CheckAlias(const Name: string): boolean;
+      function CheckQuota(MailSize: longint): boolean; virtual; abstract;
+      function BeginDeliverMessage(LockID: longint; EMail, Recipient, SpoolID: string; EMailProperties: TEMailProperties; Headers: TStrings): boolean; virtual; abstract;
+      function DeliverMessagePart(LockID: longint; Message: TStrings): boolean; virtual; abstract;
+      function FinishDeliverMessage(LockID: longint): boolean; virtual; abstract;
+      function Lock: longint; virtual; abstract;
+      function Release(LockID: longint): boolean; virtual; abstract;
+      function GetRewriteCount: integer;
+      function GetRewriteToEntry(i: integer): string;
+      function GetRewriteToListStr: string;
+      property Domain: string read FDomain;
+      property Quota: longint read FQuota;
+      property RewriteCount: integer read GetRewriteCount;
+      property RewritePassThru: boolean read FRewritePassThru;
+   end;
+
+   TMailbox_mbox = class(TMailbox)
+   private
+      procedure FromQuote(var Message: TStrings);
+      function MakeMailboxFilename: string;
+   public
+      function CheckQuota(MailSize: longint): boolean; override;
+      function BeginDeliverMessage(LockID: longint; EMail, Recipient, SpoolID: string; EMailProperties: TEMailProperties; Headers: TStrings): boolean; override;
+      function DeliverMessagePart(LockID: longint; Message: TStrings): boolean; override;
+      function FinishDeliverMessage(LockID: longint): boolean; override;
+      function Lock: longint; override;
+      function Release(LockID: longint): boolean; override;
+   end;
+
+   TForwarderMailbox = class(TMailbox)
+      constructor Create(const Name, Domain: string; Config: TINIFile; Slave: boolean; DefaultQuota: longint; PhysicalMailbox: TMailbox);
+      destructor Destroy; override;
+   private
+      PhysicalMailbox: TMailbox;
+      ForwardToList: TStringList;
+      SpoolObject: TSpoolObjectCreator;
+      OrigSpoolID: string;
+      FForwardHeaders, FRemail: boolean;
+   public
+      function CheckQuota(MailSize: longint): boolean; override;
+      function BeginDeliverMessage(LockID: longint; EMail, Recipient, SpoolID: string; EMailProperties: TEMailProperties; Headers: TStrings): boolean; override;
+      function DeliverMessagePart(LockID: longint; Message: TStrings): boolean; override;
+      function FinishDeliverMessage(LockID: longint): boolean; override;
+      function Lock: longint; override;
+      function Release(LockID: longint): boolean; override;
+      property ForwardHeaders: boolean read FForwardHeaders;
+      property Remail: boolean read FRemail;
+   end;
+
+
+   TBoxes = array of TMailbox;
+   TDomainBoxes = array of TBoxes;
+
+   TMailboxContainer = class(TStringList)
+   public
+      destructor Destroy; override;
+   protected
+      DomainBoxes: TDomainBoxes;
+   public
+      procedure AddMailbox(const Domain: string; Mailbox: TMailbox);
+      function GetMailbox(const Name, Domain: string): PMailbox;
+   end;
+
+
+   TMailboxManager = class
+      constructor Create(Config: TINIFile);
+      destructor Destroy; override;
+   private
+      MailboxContainer: TMailboxContainer;
+      DefaultQuota: longint;
+      FDomainSpecific: boolean;
+      FRewrite, FForward: boolean;
+   public
+      property DomainSpecific: boolean read FDomainSpecific;
+      property Rewrite: boolean read FRewrite;
+      property Forward: boolean read FForward;
+      function CheckQuota(const Name, Domain: string; MailSize: longint): boolean;
+      function GetMailbox(const Name, Domain: string): PMailbox;
+      function IsLocalAddress(const EMail: string): boolean;
+      function Verify(const EMail: string): boolean;
+      function VerifyAlias(const EMail: string): boolean;
+   end;
+
+
+var
+
+   MailboxManager: TMailboxManager;
+
+
+implementation
+
+const
+
+   { Search attributes: }
+   SEARCH_ATTR = faAnyFile - faDirectory - faVolumeID - faHidden;
+
+
+constructor TMailbox.Create(const Name, Domain: string; Config: TINIFile; Slave: boolean; DefaultQuota: longint);
+var Section, BaseList: string;
+begin
+   if Length(Domain) = 0 then
+      Section:= 'Mailbox\' + Name
+   else
+      Section:= 'Mailbox\' + Name + '@' + Domain;
+
+   inherited Create(Name, Config, Section);
+   FDomain:= Domain;
+   FQuota:= Config.ReadInteger(Section, 'Quota', DefaultQuota);
+   FQuota:= StrToIntDef(GetMailboxConfig(Config, Name, Domain, 'Quota', IntToStr(DefaultQuota)), DefaultQuota);
+   FLockID:= 0;
+   CriticalSection:= TCriticalSection.Create;
+
+   if (not Slave) then begin
+      FPlusAliases:= GetMailboxConfig(Config, Name, Domain, 'PlusAliases', true);
+      if FPlusAliases then begin
+         PlusAliasExceptList:= TStringList.Create;
+         PlusAliasExceptList.Delimiter:= ',';
+         BaseList:= GetMailboxConfig(Config, Name, Domain, 'PlusAliasExcept', '');
+         if Length(Domain) > 0 then
+            PlusAliasExceptList.DelimitedText:= BaseList + ',' + Config.ReadString('Mailbox\@' + Domain, 'GlobalPlusAliasExcept', '')
+         else
+            PlusAliasExceptList.DelimitedText:= BaseList + ',' + Config.ReadString('Mailbox', 'GlobalPlusAliasExcept', '');
+
+     end;
+   end;
+
+   if (not Slave) and Config.ReadBool('Mailbox', 'Rewrite', false) then begin
+      RewriteToList:= TStringList.Create;
+      RewriteToList.Delimiter:= ',';
+      RewriteToList.DelimitedText:= GetMailboxConfig(Config, Name, Domain, 'RewriteTo', '');
+      FRewritePassThru:= GetMailboxConfig(Config, Name, Domain, 'RewritePassThru', true);
+   end
+   else FRewritePassThru:= true;
+end;
+
+destructor TMailbox.Destroy;
+begin
+   CriticalSection.Free;
+end;
+
+constructor TForwarderMailbox.Create(const Name, Domain: string; Config: TINIFile; Slave: boolean; DefaultQuota: longint; PhysicalMailbox: TMailbox);
+begin
+   inherited Create(Name, Domain, Config, Slave, DefaultQuota);
+   Self.PhysicalMailbox:= PhysicalMailbox;
+
+   FForwardHeaders:= GetMailboxConfig(Config, Name, Domain, 'ForwardHeaders', true);
+   FRemail:= GetMailboxConfig(Config, Name, Domain, 'Remail', false);
+
+   ForwardToList:= TStringList.Create;
+   ForwardToList.Delimiter:= ',';
+   ForwardToList.DelimitedText:= GetMailboxConfig(Config, Name, Domain, 'ForwardTo', '');
+end;
+
+destructor TForwarderMailbox.Destroy;
+begin
+   inherited Destroy;
+   ForwardToList.Free;
+   if (PhysicalMailbox <> nil) then PhysicalMailbox.Free;
+end;
+
+destructor TMailboxContainer.Destroy;
+var i, j: integer;
+begin
+   for i:= Length(DomainBoxes) - 1 downto 0 do begin
+      for j:= Length(DomainBoxes[i]) - 1 downto 0 do begin
+         DomainBoxes[i][j].Free;
+      end;
+   end;
+   inherited Destroy;
+end;
+
+constructor TMailboxManager.Create(Config: TINIFile);
+var SearchRec: TSearchRec; i: integer; BoxName, BoxDomain: string;
+    SlaveMailbox: TMailBox;
+begin
+   inherited Create;
+   DefaultQuota:=       Config.ReadInteger('Mailbox', 'Quota', 0);
+   FDomainSpecific:=    Config.ReadBool('Mailbox', 'DomainSpecific', false);
+   FRewrite:=           Config.ReadBool('Mailbox', 'Rewrite', false);
+   FForward:=           Config.ReadBool('Mailbox', 'Forward', false);
+   MailboxContainer:=   TMailboxContainer.Create;
+   if FindFirst('mail\*', SEARCH_ATTR, SearchRec) = 0 then begin
+      i:= 0;
+      repeat
+         if DomainSpecific then begin
+            BoxName:= EMailUserName(SearchRec.Name);
+            BoxDomain:= EMailHost(SearchRec.Name);
+         end
+         else begin
+            BoxName:= SearchRec.Name;
+            BoxDomain:= '';
+         end;
+
+         { If forwarding requested, set up a forwarder mailbox. }
+
+         if Forward and (Length(TMailbox.GetMailboxConfig(Config, BoxName, BoxDomain, 'ForwardTo', '')) > 0) then begin
+
+            if TMailbox.GetMailboxConfig(Config, BoxName, BoxDomain, 'StoreLocalCopy', true) then
+               SlaveMailbox:= TMailbox_mbox.Create(BoxName, BoxDomain, Config, true, DefaultQuota)
+            else
+               SlaveMailbox:= nil;
+
+            MailboxContainer.AddMailbox(BoxDomain, TForwarderMailbox.Create(BoxName, BoxDomain, Config, false, DefaultQuota, SlaveMailbox));
+         end
+         else
+            MailboxContainer.AddMailbox(BoxDomain, TMailbox_mbox.Create(BoxName, BoxDomain, Config, false, DefaultQuota));
+
+         Inc(i);
+      until FindNext(SearchRec) <> 0;
+   end;
+   FindClose(SearchRec);
+end;
+
+destructor TMailboxManager.Destroy;
+begin
+   MailboxContainer.Free;
+   inherited Destroy;
+end;
+
+
+procedure TMailbox.AddTrackHeaders(EMail, Recipient: string; Headers: TStrings);
+begin
+   Headers.Insert(0, 'Return-Path: <' + EMail + '>');
+   Headers.Insert(0, 'X-Original-To: <' + Recipient + '>');
+end;
+
+{class function TMailbox.GetConfigSectionName(const Name, Domain: string): string;
+begin
+   if Length(Domain) = 0 then
+      Result:= 'Mailbox\' + Name
+   else
+      Result:= 'Mailbox\' + Name + '@' + Domain;
+end;}
+
+class function TMailbox.GetMailboxConfig(Config: TINIFile; const Name, Domain, Ident, Default: string): string;
+begin
+   if Length(Domain) > 0 then
+      Result:= Config.ReadString('Mailbox\' + Name + '@' + Domain, Ident,
+         Config.ReadString('Mailbox\@' + Domain, Ident,
+         Config.ReadString('Mailbox', Ident, Default)))
+   else
+      Result:= Config.ReadString('Mailbox\' + Name, Ident,
+         Config.ReadString('Mailbox', Ident, Default));
+end;
+
+class function TMailbox.GetMailboxConfig(Config: TINIFile; const Name, Domain, Ident: string; Default: boolean): boolean;
+begin
+   if Length(Domain) > 0 then
+      Result:= Config.ReadBool('Mailbox\' + Name + '@' + Domain, Ident,
+         Config.ReadBool('Mailbox\@' + Domain, Ident,
+         Config.ReadBool('Mailbox', Ident, Default)))
+   else
+      Result:= Config.ReadBool('Mailbox\' + Name, Ident,
+         Config.ReadBool('Mailbox', Ident, Default));
+end;
+
+function TMailbox.IsItYourName(const Name: string): boolean;
+var p: integer;
+begin
+   if FPlusAliases then begin
+      p:= Pos('+', Name);
+      if p <> 0 then
+         Result:= inherited IsItYourName(Copy(Name, 1, p - 1))
+      else
+         Result:= inherited IsItYourName(Name);
+   end
+   else
+      Result:= inherited IsItYourName(Name);
+end;
+
+function TMailbox.GetMailboxAddress: string;
+begin
+   if Length(Domain) = 0 then
+      Result:= Name + '@' + MainServerConfig.Name
+   else
+      Result:= Name + '@' + Domain;
+end;
+
+function TMailbox.CheckAlias(const Name: string): boolean;
+var p: integer;
+begin
+   p:= Pos('+', Name);
+   if p <> 0 then
+      Result:= PlusAliasExceptList.IndexOf(Copy(Name, p + 1, Length(Name) - p)) = -1
+   else
+      Result:= true;
+end;
+
+function TMailbox.GetRewriteCount: integer;
+begin
+   Result:= RewriteToList.Count;
+end;
+
+function TMailbox.GetRewriteToEntry(i: integer): string;
+begin
+   Result:= RewriteToList.Strings[i];
+end;
+
+function TMailbox.GetRewriteToListStr: string;
+begin
+   Result:= RewriteToList.DelimitedText;
+end;
+
+
+procedure TMailbox_mbox.FromQuote(var Message: TStrings);
+var i: integer;
+begin
+   for i:= 0 to Message.Count - 1 do
+      if pos('From ', Message.Strings[i]) = 1 then
+         Message.Strings[i]:= '>' + Message.Strings[i];
+end;
+
+function TMailbox_mbox.MakeMailboxFilename: string;
+begin
+   if Length(Domain) = 0 then
+      Result:= 'mail\' + Name
+   else
+      Result:= 'mail\' + Name + '@' + Domain;
+end;
+
+function TMailbox_mbox.CheckQuota(MailSize: longint): boolean;
+{ Returns FALSE if the given message size would exceed the quota. }
+var SearchRec: TSearchRec;
+begin
+   if FindFirst(MakeMailboxFilename, SEARCH_ATTR, SearchRec) = 0 then
+      Result:= ((SearchRec.Size + MailSize) <= FQuota) or (FQuota = 0)
+   else
+      Result:= false;
+   FindClose(SearchRec);
+end;
+
+function TMailbox_mbox.BeginDeliverMessage(LockID: longint; EMail, Recipient, SpoolID: string; EMailProperties: TEMailProperties; Headers: TStrings): boolean;
+var NL, Line: string;
+begin
+   if (FLockID <> 0) and (FLockID = LockID) then begin
+      case DefaultTextLineBreakStyle of
+         tlbsLF:     NL:= #10;
+         tlbsCRLF:   NL:= #13#10;
+         tlbsCR:     NL:= #13;
+      end;
+
+      {FromQuote(Headers);}
+      AddTrackHeaders(EMail, Recipient, Headers);
+      Headers.Insert(0, 'Delivered-To: ' + GetMailboxAddress);
+      try
+         if Length(EMail) = 0 then EMail:= 'MAILER-DAEMON';
+         Line:= 'From ' + EMail + ' ' + EMailTimeStamp(Now) + NL;
+         MailboxFile.WriteBuffer(Pointer(Line)^,Length(Line));
+         Headers.SaveToStream(MailboxFile);
+         MailboxFile.WriteBuffer(Pointer(NL)^,Length(NL));
+         Result:= true;
+      except
+         Result:= false;
+      end;
+   end
+   else Result:= false;
+end;
+
+function TMailbox_mbox.DeliverMessagePart(LockID: longint; Message: TStrings): boolean;
+begin
+   if (FLockID <> 0) and (FLockID = LockID) then begin
+      FromQuote(Message);
+      try
+         Message.SaveToStream(MailboxFile);
+         Result:= true;
+      except
+         Result:= false;
+      end;
+   end
+   else Result:= false;
+end;
+
+function TMailbox_mbox.FinishDeliverMessage(LockID: longint): boolean;
+begin
+   if (FLockID <> 0) and (FLockID = LockID) then begin
+      try
+         MailboxFile.WriteBuffer(#13#10, 2);
+         Result:= true;
+      except
+         Result:= false;
+      end;
+   end
+   else Result:= false;
+end;
+
+function TMailbox_mbox.Lock: longint;
+begin
+   CriticalSection.Acquire;
+   if FLockID = 0 then begin
+      try
+         MailboxFile:= TFileStream.Create(MakeMailboxFilename, fmOpenReadWrite);
+         FLockID:= (MailboxFile as TFileStream).Handle;
+         MailboxFile.Seek(0, soFromEnd);
+      except
+         try
+            FreeAndNil(MailboxFile);
+         except
+         end;
+         FLockID:= 0;
+      end;
+      Result:= FLockID;
+   end
+   else Result:= 0;
+   CriticalSection.Release;
+end;
+
+function TMailbox_mbox.Release(LockID: longint): boolean;
+begin
+   CriticalSection.Acquire;
+   if (FLockID <> 0) and (FLockID = LockID) then begin
+      FreeAndNil(MailboxFile);
+      FLockID:= 0;
+   end
+   else Result:= false;
+   CriticalSection.Release;
+end;
+
+
+function TForwarderMailbox.CheckQuota(MailSize: longint): boolean;
+{ Returns FALSE if the given message size would exceed the quota. }
+begin
+   if PhysicalMailbox <> nil then
+      Result:= PhysicalMailbox.CheckQuota(MailSize)
+   else
+      Result:= true;
+end;
+
+function TForwarderMailbox.BeginDeliverMessage(LockID: longint; EMail, Recipient, SpoolID: string; EMailProperties: TEMailProperties; Headers: TStrings): boolean;
+var i: integer;
+begin
+   if (FLockID <> 0) and (FLockID = LockID) then begin
+      if PhysicalMailbox = nil then begin
+         AddTrackHeaders(EMail, Recipient, Headers);
+         Result:= true;
+      end
+      else begin
+         Result:= PhysicalMailbox.BeginDeliverMessage(LockID, EMail, Recipient, SpoolID, EMailProperties, Headers);
+      end;
+
+      if Result then begin
+         SpoolObject:= SpoolManager.CreateSpoolObject(TIPNamePair.Create('internal', ''));
+         //PrepareSpoolObject(EMail, ForwardSpoolObject, Headers);
+         SpoolObject.Databytes:= 0;
+
+         SpoolObject.EMailProperties.Size:=  EMailProperties.Size;
+         SpoolObject.EMailProperties.Flags:= EMailProperties.Flags;
+         OrigSpoolID:= SpoolID;
+
+         { Forward or remail? Regardless of the settings, DSNs only get forwarded
+           and never get remailed. (Remailing them could cause a loop.) }
+         if (not Remail) or (EMail = '') then
+            SpoolObject.Envelope.ReturnPath:= EMail
+         else
+            SpoolObject.Envelope.ReturnPath:= Recipient;
+
+         for i:= 0 to ForwardToList.Count - 1 do
+            SpoolObject.Envelope.AddRecipient(ForwardToList.Strings[i]);
+
+         if ForwardHeaders then begin
+            Headers.Insert(0, 'X-Forwarded-For: ' + Recipient + ' ' + ForwardToList.DelimitedText);
+            Headers.Insert(0, 'X-Forwarded-To: ' + ForwardToList.DelimitedText);
+         end;
+
+         SpoolObject.Open;
+         for i:= 0 to Headers.Count - 1 do
+            SpoolObject.DeliverMessagePart(Headers.Strings[i]);
+
+         SpoolObject.DeliverMessagePart('');
+      end;
+   end
+   else
+      Result:= false;
+end;
+
+function TForwarderMailbox.DeliverMessagePart(LockID: longint; Message: TStrings): boolean;
+var i: integer;
+begin
+   if (FLockID <> 0) and (FLockID = LockID) then begin
+      if PhysicalMailbox <> nil then
+         Result:= PhysicalMailbox.DeliverMessagePart(LockID, Message)
+      else
+         Result:= true;
+
+      for i:= 0 to Message.Count - 1 do
+         SpoolObject.DeliverMessagePart(Message.Strings[i]);
+   end
+   else
+      Result:= false;
+end;
+
+function TForwarderMailbox.FinishDeliverMessage(LockID: longint): boolean;
+var action: string;
+begin
+   if (FLockID <> 0) and (FLockID = LockID) then begin
+      if PhysicalMailbox <> nil then
+         Result:= PhysicalMailbox.FinishDeliverMessage(LockID)
+      else
+         Result:= true;
+
+      if not Remail then action:= 'forwarding' else action:= 'remailing';
+
+      if SpoolObject.GetErrorCode = SCE_NO_ERROR then begin
+         Logger.AddLine('Mailbox ' + GetMailboxAddress, 'Message ' + OrigSpoolID + ' has been copied to '
+            + SpoolObject.Name + ' for ' + action + ' to ' + ForwardToList.DelimitedText);
+         SpoolObject.Close;
+      end
+      else begin
+         Logger.AddLine('Mailbox ' + GetMailboxAddress, 'Failed to copy message <' + SpoolObject.OriginalMessageID + '> for '
+            + action + ' to ' + ForwardToList.DelimitedText
+            + '; Spool error code: ' + IntToStr(SpoolObject.GetErrorCode));
+         SpoolObject.Discard;
+      end;
+      SpoolObject.Free;
+   end
+   else
+      Result:= false;
+end;
+
+function TForwarderMailbox.Lock: longint;
+{ Very-very sensitive method that induced lots of cursing.
+  Pay a lot of attention when you do any change to it! }
+begin
+   CriticalSection.Acquire;
+   if FLockID = 0 then begin
+      if PhysicalMailbox <> nil then begin
+         FLockID:= PhysicalMailbox.Lock;
+         Result:= FLockID;
+      end
+      else begin
+         FLockID:= GetCurrentThreadID;
+         Result:= FLockID;
+      end;
+   end
+   else Result:= 0;
+   CriticalSection.Release;
+end;
+
+function TForwarderMailbox.Release(LockID: longint): boolean;
+begin
+   CriticalSection.Acquire;
+   if (FLockID <> 0) and (FLockID = LockID) then begin
+      if PhysicalMailbox <> nil then
+         Result:= PhysicalMailbox.Release(LockID)
+      else
+         Result:= true;
+   end
+   else
+      Result:= false;
+   if Result then FLockID:= 0;
+   CriticalSection.Release;
+end;
+
+
+procedure TMailboxContainer.AddMailbox(const Domain: string; Mailbox: TMailbox);
+var i, j: integer;
+begin
+   { IndexOf is supposed to be case-insensitive, but it depends on locales.
+     It's safer to uppercase the string before passing to it.
+     See: http://62.166.198.202/view.php?id=15489 }
+   i:= IndexOf(UpperCase(Domain));
+   if i = -1 then begin
+      Add(Domain);
+      i:= Count - 1;
+      SetLength(DomainBoxes, Count);
+   end;
+   j:= Length(DomainBoxes[i]);
+   SetLength(DomainBoxes[i], j + 1);
+   DomainBoxes[i][j]:= Mailbox;
+end;
+
+function TMailboxContainer.GetMailbox(const Name, Domain: string): PMailbox;
+var i, j: integer;
+begin
+   i:= IndexOf(UpperCase(Domain));
+   if i <> -1 then begin
+      j:= 0;
+      while (j < Length(DomainBoxes[i])) and (not(DomainBoxes[i][j].IsItYourName(Name))) do Inc(j);
+      if (j < Length(DomainBoxes[i])) then Result:= @DomainBoxes[i][j]
+      else if Domain <> '' then Result:= GetMailbox(Name, '')
+      else Result:= nil;
+   end
+   else if Domain <> '' then Result:= GetMailbox(Name, '')
+   else Result:= nil;
+end;
+
+
+function TMailboxManager.CheckQuota(const Name, Domain: string; MailSize: longint): boolean;
+var Mailbox: PMailbox;
+begin
+   Mailbox:= GetMailbox(Name, Domain);
+   if Mailbox <> nil then
+      Result:= Mailbox^.CheckQuota(MailSize)
+   else
+      Result:= false;
+end;
+
+function TMailboxManager.GetMailbox(const Name, Domain: string): PMailbox;
+begin
+   Result:= MailboxContainer.GetMailbox(Name, Domain);
+end;
+
+function TMailboxManager.IsLocalAddress(const EMail: string): boolean;
+begin
+   Result:= MainServerConfig.IsItYourName(EMailHost(EMail));
+end;
+
+function TMailboxManager.Verify(const EMail: string): boolean;
+begin
+   Result:= GetMailbox(EMailUserName(EMail), EMailHost(EMail)) <> nil;
+end;
+
+function TMailboxManager.VerifyAlias(const EMail: string): boolean;
+var Mailbox: PMailbox;
+begin
+   Mailbox:= GetMailbox(EMailUserName(EMail), EMailHost(EMail));
+   if Mailbox <> nil then
+      Result:= Mailbox^.CheckAlias(EMailUserName(EMail))
+   else
+      Result:= false;
+end;
+
+
+end.
diff --git a/MgSMTP.pas b/MgSMTP.pas
new file mode 100644 (file)
index 0000000..cecfdc9
--- /dev/null
@@ -0,0 +1,316 @@
+{
+   MegaBrutal's SMTP Server (MgSMTP)
+   Copyright (C) 2010-2014 MegaBrutal
+
+   This program is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Affero General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Affero General Public License for more details.
+
+   You should have received a copy of the GNU Affero General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+
+{$MODE DELPHI}
+{$APPTYPE CONSOLE}
+
+program MgSMTP;
+uses Windows, SysUtils, INIFiles, EINIFiles,
+     Common, Log, Spool, Listener, Mailbox, Relay, Policies;
+
+
+function RegisterServiceCtrlHandlerEx(lpServiceName: LPCSTR; lpHandlerProc: pointer; lpContext: LPVOID): SERVICE_STATUS_HANDLE; stdcall; external 'advapi32.dll' name 'RegisterServiceCtrlHandlerExA';
+procedure Service(Argc: dword; Argv: pointer); stdcall; forward;
+
+const
+
+   ServiceTable: array[0..1] of TServiceTableEntry =
+      (
+         (
+            lpServiceName: 'MgSMTP';
+            lpServiceProc: @Service;
+         ),
+         (
+            lpServiceName: nil;
+            lpServiceProc: nil;
+         )
+      );
+
+   { For development test builds, you can add a developer comment here to
+     document what bugfix/feature are you testing with the actual build.
+     This will be logged to help you differentiate outputs of subsequent
+     builds in your logs. If left empty, it won't be added to the logs. }
+   DEVCOMMENT  =  'Testing new parameters';
+
+var
+
+   Config: TINIFile;
+   hSCManager, hService: THandle;
+   hSvcStatusHandle: THandle;
+   SvcStatus: TServiceStatus;
+   ServiceMode, Stopping: boolean;
+
+
+procedure AddDevComment(Log: TStreamLogger);
+begin
+   if DEVCOMMENT <> '' then begin
+      Log.writeln('Build: ' + {$INCLUDE %DATE%} + ' ' + {$INCLUDE %TIME%});
+      Log.writeln('Developer note: ' + DEVCOMMENT);
+   end;
+end;
+
+procedure ReportSvcStatus(CurrentState, WinExitCode, WaitHint: dword);
+{ Report a service status to the Windows SCM. }
+begin
+   if ServiceMode then begin
+      SvcStatus.dwCurrentState:= CurrentState;
+      SvcStatus.dwWaitHint:= WaitHint;
+      if WinExitCode <> 0 then begin
+         SvcStatus.dwWin32ExitCode:= ERROR_SERVICE_SPECIFIC_ERROR;
+         SvcStatus.dwServiceSpecificExitCode:= WinExitCode;
+      end
+      else begin
+         SvcStatus.dwWin32ExitCode:= NO_ERROR;
+      end;
+
+      if CurrentState = SERVICE_START_PENDING then
+         SvcStatus.dwControlsAccepted:= 0
+      else begin
+         if GetWinMajorVersion >= 6 then begin
+            SvcStatus.dwControlsAccepted:=
+               SERVICE_ACCEPT_STOP or SERVICE_ACCEPT_SHUTDOWN or SERVICE_ACCEPT_PRESHUTDOWN;
+         end
+         else begin
+            SvcStatus.dwControlsAccepted:=
+               SERVICE_ACCEPT_STOP or SERVICE_ACCEPT_SHUTDOWN;
+         end;
+      end;
+
+      if (CurrentState = SERVICE_RUNNING) or (CurrentState = SERVICE_STOPPED) then
+         SvcStatus.dwCheckPoint:= 0
+      else
+         Inc(SvcStatus.dwCheckPoint);
+
+      SetServiceStatus(hSvcStatusHandle, SvcStatus);
+   end;
+end;
+
+procedure SvcCtrlHandlerEx(Ctrl, EventType: dword; EventData, Context: pointer); stdcall;
+{ Receive a service control code from the Windows SCM, and handle it. }
+begin
+   case Ctrl of
+   SERVICE_CONTROL_STOP,
+   SERVICE_CONTROL_SHUTDOWN,
+   SERVICE_CONTROL_PRESHUTDOWN:
+   begin
+      Out.writeln('Received service control: ' + GetServiceCodeStr(Ctrl));
+      ReportSvcStatus(SERVICE_STOP_PENDING, 0, 1500);
+      Stopping:= true;
+   end;
+
+   SERVICE_CONTROL_INTERROGATE:
+      ReportSvcStatus(SERVICE_RUNNING, 0, 0);
+
+   else begin
+      Out.writeln('Received unknown service control: ' + IntToStr(Ctrl));
+      ReportSvcStatus(SERVICE_STOPPED, 1, 0);
+      Stopping:= true;
+   end;
+   end;
+end;
+
+procedure Service(Argc: dword; Argv: pointer); stdcall;
+var ProposedExitCode: integer;
+begin
+   ProposedExitCode:= 0;
+   Stopping:= false;
+   SetLastError(0);
+
+   if ServiceMode then
+      hSvcStatusHandle:= RegisterServiceCtrlHandlerEx('MgSMTP', @SvcCtrlHandlerEx, nil);
+
+   if ServiceMode and (hSvcStatusHandle = 0) then
+      Out.writeln('RegisterServiceCtrlHandlerEx failed!'#13#10'Error code: ' + IntToStr(GetLastError))
+   else begin
+      SvcStatus.dwServiceType:= SERVICE_WIN32_OWN_PROCESS;
+      SvcStatus.dwServiceSpecificExitCode:= 0;
+      SvcStatus.dwCheckPoint:= 0;
+
+      ReportSvcStatus(SERVICE_START_PENDING, 0, 1000);
+
+      if ServiceMode then Out.writeln('Started in service mode.');
+
+      Randomize;
+      SetCurrentDir(ExtractFilePath(ParamStr(0)));
+
+      if not DirectoryExists('mail')  then CreateDir('mail');
+      if not DirectoryExists('spool') then CreateDir('spool');
+
+      if FileExists('mgsmtp_server.ini') then begin
+
+         Config:= TExtBoolINIFile.Create('mgsmtp_server.ini');
+
+         if Config.ReadString('Server', 'Name', '') <> '' then begin
+            MainServerConfig:= TMainServerConfig.Create(Config);
+            Logger:=           TLogger.Create(Config);
+            MailboxManager:=   TMailboxManager.Create(Config);
+            RelayManager:=     TRelayManager.Create(Config);
+            SpoolManager:=     TSpoolManager.Create(Config);
+            PolicyManager:=    TPolicyManager.Create(Config);
+
+            if Config.ReadBool('Spool', 'KeepProcessedEnvelopes', false)
+            or Config.ReadBool('Spool', 'KeepProcessedEMails', false) then
+               if not DirectoryExists('processed') then CreateDir('processed');
+
+            Config.Free;
+
+            AddDevComment(Logger);
+            Logger.AddStdLine('Primary server name: ' + MainServerConfig.Name);
+            Logger.AddStdLine('FCrDNS policy: ' + FCrDNSPolicyToStr(PolicyManager.FCrDNSPolicy));
+            if MailboxManager.DomainSpecific then
+               Logger.AddStdLine('Domain-specific mailbox support is enabled.');
+
+            if not MailboxManager.Verify('postmaster') then
+               ProposedExitCode:= 3;
+
+            if SpoolManager.DeliveryThreadNumber > Length(GetAlphabetStr) then
+               ProposedExitCode:= 4;
+
+            if ProposedExitCode = 0 then begin
+               SpoolManager.StartDeliveryThreads;
+               StartListeners;
+
+               ReportSvcStatus(SERVICE_RUNNING, 0, 0);
+               while not Stopping do Sleep(1000);
+
+               ReportSvcStatus(SERVICE_STOP_PENDING, 0, SpoolManager.ThreadWait * 2);
+
+               StopListeners;
+               SpoolManager.StopDeliveryThreads;
+            end
+            else begin
+               case ProposedExitCode of
+               3: Logger.AddStdLine('Error: Mandatory mailbox missing. Create a mailbox for "postmaster"!');
+               4: Logger.AddStdLine('Error: The maximum allowed number of delivery threads is ' + IntToStr(Length(GetAlphabetStr)) + '.');
+               end;
+               ReportSvcStatus(SERVICE_STOPPED, ProposedExitCode, 0);
+            end;
+
+            ReportSvcStatus(SERVICE_STOP_PENDING, 0, 2000);
+
+            Logger.AddStdLine('Clean shutdown.');
+
+            PolicyManager.Free;
+            SpoolManager.Free;
+            RelayManager.Free;
+            MailboxManager.Free;
+            Logger.Free;
+            MainServerConfig.Free;
+            ReportSvcStatus(SERVICE_STOPPED, 0, 0);
+         end
+         else begin
+            Config.Free;
+            Out.writeln('Error: Server/Name is a mandatory configuration entry.'#13#10
+               + 'Please configure the application properly, refer to the manual.');
+            ReportSvcStatus(SERVICE_STOPPED, 2, 0);
+         end;
+      end
+      else begin
+         Out.writeln('Error: Missing configuration file.');
+         ReportSvcStatus(SERVICE_STOPPED, 1, 0);
+      end;
+   end;
+end;
+
+
+begin
+   Out.writeln('MegaBrutal''s SMTP Server, version ' + VERSION_STR + ', ' + IntToStr(PLATFORM_BITS) + ' bits');
+   Out.writeln('Copyright (C) 2010-2014 MegaBrutal');
+   AddDevComment(Out);
+   Out.writeln;
+
+   { TODO: Process arguments here. }
+
+   ServiceMode:= false;
+
+   if ParamCount > 0 then begin
+
+      if UpperCase(ParamStr(1)) = '/USERMODE' then begin
+         Out.writeln('Starting MgSMTP in user mode...');
+         Service(0, nil);
+      end
+
+      else if ParamStr(1) = '/?' then begin
+         Out.writeln('Supported arguments:');
+         Out.writeln('/INSTALL   - registers the actual MgSMTP binary');
+         Out.writeln('             as a Windows service.');
+         Out.writeln('/UNINSTALL - unregisters the MgSMTP service.');
+         Out.writeln('/USERMODE  - starts MgSMTP in user mode');
+         Out.writeln('             (not recommended, should be only');
+         Out.writeln('             used for debugging).');
+         Out.writeln;
+         Out.writeln('For more information on usage, see readme.txt.');
+         Out.writeln('For license details, see license.txt.');
+         Out.writeln;
+         Out.writeln('If you can''t find any of these files, you');
+         Out.writeln('don''t have the complete distribution of');
+         Out.writeln('this software. In that case, download a');
+         Out.writeln('proper distribution from SourceForge:');
+         Out.writeln('https://sourceforge.net/projects/mgsmtp/');
+      end
+
+      else if (UpperCase(ParamStr(1)) = '/INSTALL') or (UpperCase(ParamStr(1)) = '/UNINSTALL') then begin
+         { Register / unregister service. }
+         hSCManager:= OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
+         if hSCManager <> 0 then begin
+            if UpperCase(ParamStr(1)) = '/INSTALL' then begin
+               if CreateService(hSCManager, 'MgSMTP', 'MegaBrutal''s SMTP Server (MgSMTP)', SC_MANAGER_ALL_ACCESS,
+                  SERVICE_WIN32_OWN_PROCESS,
+                  SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
+                  PChar(ParamStr(0)),
+                  nil,
+                  nil,
+                  nil,
+                  nil,
+                  nil) <> 0 then
+                     Out.writeln('Service registered successfully.')
+                  else
+                     Out.writeln('CreateService failed!');
+            end
+            else if UpperCase(ParamStr(1)) = '/UNINSTALL' then begin
+               hService:= OpenService(hSCManager, 'MgSMTP', SC_MANAGER_ALL_ACCESS);
+               if hService <> 0 then begin
+                  if DeleteService(hService) then
+                     Out.writeln('Service unregistered successfully.')
+                  else
+                     Out.writeln('DeleteService failed!');
+               end
+               else Out.writeln('OpenService failed!');
+            end
+            else Out.writeln('Unknown parameter.');
+         end
+         else Out.writeln('OpenSCManager failed!');
+      end
+      else Out.writeln('Unknown parameter specified!');
+   end
+   else begin
+
+      Out.writeln('Trying to contact Service Control Manager...');
+      ServiceMode:= true;
+      if not StartServiceCtrlDispatcher(ServiceTable) then begin
+         ServiceMode:= false;
+         Out.writeln('Failed!');
+         Out.writeln;
+         Out.writeln('You need to start MgSMTP as a service,');
+         Out.writeln('or supply proper arguments!');
+         Out.writeln('Issue with /? for more information.');
+      end;
+
+   end;
+end.
diff --git a/NetRFC.pas b/NetRFC.pas
new file mode 100644 (file)
index 0000000..b6cdc24
--- /dev/null
@@ -0,0 +1,181 @@
+{
+   Copyright (C) 2010 MegaBrutal
+
+   This unit is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Lesser General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This unit is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+
+unit NetRFC;
+
+{$MODE DELPHI}
+
+interface
+uses SysUtils, Classes, SocketUtils;
+
+type
+
+   PRFCReply = ^TRFCReply;
+   TRFCReply = class
+   private
+      FNumericCode: word;
+      FReplyText: TStringList;
+   public
+      constructor Create;
+      destructor Destroy; override;
+      function Count: integer;
+      function GetLine(n: integer): string;
+      function GetNumericCode: word;
+      procedure Add(Line: string);
+      procedure Clear;
+      procedure SetNumericCode(Code: word);
+      procedure SetReply(NumericCode: word; Text: shortstring);
+      property NumericCode: word read GetNumericCode;
+      property ReplyText: TStringList read FReplyText;
+   end;
+
+   function ReadCommand(Sock: socket; var Command: shortstring; var Prms: string): boolean;
+   function ReadResponse(Sock: socket; Response: TRFCReply): boolean;
+   function SendCommand(Sock: socket; Command: shortstring): boolean; overload;
+   function SendCommand(Sock: socket; Command: shortstring; Prms: string): boolean; overload;
+   function SendResponse(Sock: socket; Response: TRFCReply): boolean;
+
+
+implementation
+
+constructor TRFCReply.Create;
+begin
+   inherited Create;
+   FNumericCode:= 0;
+   FReplyText:= TStringList.Create;
+   FReplyText.Clear;
+end;
+
+destructor TRFCReply.Destroy;
+begin
+   FReplyText.Free;
+   inherited Destroy;
+end;
+
+function TRFCReply.Count: integer;
+begin
+   Count:= FReplyText.Count;
+end;
+
+function TRFCReply.GetLine(n: integer): string;
+begin
+   GetLine:= FReplyText.Strings[n];
+end;
+
+function TRFCReply.GetNumericCode: word;
+begin
+   GetNumericCode:= FNumericCode;
+end;
+
+procedure TRFCReply.Add(Line: string);
+begin
+   FReplyText.Add(Line);
+end;
+
+procedure TRFCReply.Clear;
+begin
+   SetNumericCode(0);
+   FReplyText.Clear;
+end;
+
+procedure TRFCReply.SetNumericCode(Code: word);
+begin
+   FNumericCode:= Code;
+end;
+
+procedure TRFCReply.SetReply(NumericCode: word; Text: shortstring);
+begin
+   SetNumericCode(NumericCode);
+   FReplyText.Clear;
+   FReplyText.Add(Text);
+end;
+
+
+function ReadCommand(Sock: socket; var Command: shortstring; var Prms: string): boolean;
+var Line: string; i: integer;
+begin
+   ReadCommand:= true;
+   try
+      if SockReadLn(Sock, Line) then begin
+         i:= pos(#32, Line);
+         if i > 0 then begin
+            Command:= Copy(Line, 1, i - 1);
+            Prms:= Copy(Line, i + 1, Length(Line) - i);
+         end
+         else begin
+            Command:= Line;
+            Prms:= '';
+         end;
+      end
+      else ReadCommand:= false;
+   except
+      ReadCommand:= false;
+   end;
+end;
+
+function ReadResponse(Sock: socket; Response: TRFCReply): boolean;
+var Line: string; ReadOK: boolean;
+begin
+   ReadResponse:= true;
+   try
+      Response.Clear;
+      repeat
+         ReadOK:= SockReadLn(Sock, Line);
+         if ReadOK then Response.Add(Copy(Line, 5, Length(Line) - 4));
+      until (Line[4] = #32) or (not ReadOK);
+      if ReadOK then Response.SetNumericCode(StrToInt(Copy(Line, 1, 3)));
+      ReadResponse:= ReadOK;
+   except
+      ReadResponse:= false;
+   end;
+end;
+
+function SendCommand(Sock: socket; Command: shortstring): boolean;
+begin
+   try
+      SendCommand:= SockWriteLn(Sock, Command);
+   except
+      SendCommand:= false;
+   end;
+end;
+
+function SendCommand(Sock: socket; Command: shortstring; Prms: string): boolean;
+begin
+   try
+      SendCommand:= SockWriteLn(Sock, Command + #32 + Prms);
+   except
+      SendCommand:= false;
+   end;
+end;
+
+function SendResponse(Sock: socket; Response: TRFCReply): boolean;
+var c, i: integer;
+begin
+   try
+      c:= Response.Count;
+      if c > 0 then begin
+         for i:= 0 to c - 2 do SockWriteLn(Sock, IntToStr(Response.GetNumericCode) + '-' + Response.GetLine(i));
+         SendResponse:= SockWriteLn(Sock, IntToStr(Response.GetNumericCode) + #32 + Response.GetLine(c - 1));
+      end;
+   except
+      SendResponse:= false;
+   end;
+end;
+
+
+end.
diff --git a/Network.pas b/Network.pas
new file mode 100644 (file)
index 0000000..5ef2616
--- /dev/null
@@ -0,0 +1,350 @@
+{
+   Basic object-oriented network functions
+   Copyright (C) 2010-2014 MegaBrutal
+
+   This unit is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Lesser General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This unit is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+{
+   Unit: Network
+   This unit provides an object-oriented interface to manage TCP/IPv4
+   connections.
+
+   TTCPConnection - provides methods for sending/receiving buffers through
+      the connection, and some support for text-based communication.
+
+   TTCPRFCConnection - in addition to TTCPConnection, it provides methods
+      to send/receive RFC-style commands and responses.
+
+   TTCPListener - opens a port to listen on, and accepts incoming connections
+      through it. Override its "HandleClient" method to serve connected
+      clients.
+}
+
+
+{$MODE DELPHI}
+unit Network;
+
+interface
+uses Classes, Sockets, SocketUtils, DNSResolve, NetRFC, Common;
+
+const
+
+   { Connection feature requests: }
+   NET_TCP_BASIC        =  0;
+   NET_TCP_RFCSUPPORT   =  1;
+
+   { Default socket timeout: }
+   DEF_SOCK_TIMEOUT     =  5 * 60000;     { 5 minutes. }
+
+
+type
+
+   TTCPConnection = class
+      constructor Create; overload;
+      constructor Create(const HostName: string; Port: word); overload;
+      constructor Create(Socket: socket; const Addr: TSockAddr); overload;
+      destructor Destroy; override;
+   private
+      FConnected: boolean;
+      FSocket: socket;
+      FHostIP: TIPNamePair;
+      FSockTimeOut: DWord;
+      sAddr: TSockAddr;
+   public
+      function Connect(const HostName: string; Port: word): boolean;
+      procedure Disconnect;
+      procedure ReverseDNSLookup;
+      function VerifyFCrDNS: boolean;
+      procedure SetSockTimeOut(TimeOut: DWord);
+      function ReadBuffer(PtrBuffer: pointer; Len: size_t): ssize_t;
+      function WriteBuffer(PtrBuffer: pointer; Len: size_t): ssize_t;
+      function ReadLn(var Line: string): boolean;
+      function WriteLn(const Line: string): boolean;
+      property Connected: boolean read FConnected;
+      property Socket: socket read FSocket;
+      property HostIP: TIPNamePair read FHostIP;
+      property SockTimeOut: DWord read FSockTimeOut write SetSockTimeOut;
+   end;
+
+   TTCPRFCConnection = class(TTCPConnection)
+   public
+      function ReadCommand(var Command: shortstring; var Prms: string): boolean;
+      function ReadResponse(Response: TRFCReply): boolean;
+      function SendCommand(Command: shortstring): boolean; overload;
+      function SendCommand(Command: shortstring; Prms: string): boolean; overload;
+      function SendResponse(Response: TRFCReply): boolean;
+   end;
+
+
+   TTCPAcceptHandler = procedure(Connection: TTCPConnection) of object;
+
+   TTCPAcceptor = class(TThread)
+      constructor Create(Handler: TTCPAcceptHandler; TCPConnection: TTCPConnection);
+   protected
+      FHandler: TTCPAcceptHandler;
+      FTCPConnection: TTCPConnection;
+      procedure Execute; override;
+   end;
+
+   TTCPListener = class(TThread)
+      constructor Create(Port: word; FeatureRequest: word);
+      {destructor Destroy; override;}
+   private
+      FFeatureRequest: word;
+      FListenPort: word;
+      FListenSocket: socket;
+      sAddr: TSockAddr;
+   protected
+      procedure HandleClient(Connection: TTCPConnection); virtual; abstract;
+      procedure Execute; override;
+   public
+      property ListenPort: word read FListenPort;
+      function StartListen: boolean;
+      procedure StopListen;
+   end;
+
+
+
+implementation
+
+
+constructor TTCPConnection.Create;
+{ Create an instance, but don't connect to anywhere yet. }
+begin
+   inherited Create;
+   FConnected:= false;
+   FSocket:= -1;
+   FSockTimeOut:= DEF_SOCK_TIMEOUT;
+end;
+
+constructor TTCPConnection.Create(const HostName: string; Port: word);
+{ Connect to the given port on the given hostname. }
+begin
+   inherited Create;
+   Connect(HostName, Port);
+end;
+
+constructor TTCPConnection.Create(Socket: socket; const Addr: TSockAddr);
+{ Use an already connected socket. }
+begin
+   inherited Create;
+   FSocket:= Socket;
+   sAddr:= Addr;
+   FHostIP:= TIPNamePair.Create('', NetAddrToStr(Addr.sin_addr));
+   FConnected:= true;
+end;
+
+destructor TTCPConnection.Destroy;
+begin
+   if FConnected then Disconnect;
+   inherited Destroy;
+end;
+
+
+constructor TTCPAcceptor.Create(Handler: TTCPAcceptHandler; TCPConnection: TTCPConnection);
+{ Start a connection handler on a distinct thread. }
+begin
+   FHandler:= Handler;
+   FTCPConnection:= TCPConnection;
+   FreeOnTerminate:= true;
+   inherited Create(false);
+end;
+
+
+constructor TTCPListener.Create(Port: word; FeatureRequest: word);
+begin
+   FListenPort:= Port;
+   FFeatureRequest:= FeatureRequest;
+   FreeOnTerminate:= false;
+   inherited Create(true);
+end;
+
+
+function TTCPConnection.Connect(const HostName: string; Port: word): boolean;
+{ Resolves the given hostname, and tries to connect it on the given port. }
+begin
+   FSocket:= fpSocket(af_inet, sock_stream, 0);
+   if (FSocket <> -1) then begin
+      with sAddr do begin
+         sin_family:= af_inet;
+         sin_port:= htons(Port);
+         { Resolve hostname to IP address. }
+         sin_addr:= ResolveHost(HostName);
+      end;
+
+      if sAddr.sin_addr.s_addr <> 0 then
+         { Try to initiate connection. }
+         FConnected:= fpConnect(FSocket, @sAddr, SizeOf(sAddr)) <> -1;
+
+      if FConnected then begin
+         FHostIP:= TIPNamePair.Create(HostName, NetAddrToStr(sAddr.sin_addr));
+         SetSockTimeOut(FSockTimeOut);
+      end
+      else
+         CloseSocket(FSocket);
+   end;
+   Result:= FConnected;
+end;
+
+procedure TTCPConnection.Disconnect;
+begin
+   fpShutdown(FSocket, 2);
+   CloseSocket(FSocket);
+   FSocket:= -1;
+   FHostIP.Free;
+   FConnected:= false;
+end;
+
+procedure TTCPConnection.ReverseDNSLookup;
+{ Performs a reverse DNS lookup, and updates the HostIP structure. }
+var NHostIP: TIPNamePair;
+begin
+   if FConnected then begin
+      NHostIP:= TIPNamePair.Create(ResolveIP(sAddr.sin_addr), FHostIP.IP);
+      FHostIP.Free;
+      FHostIP:= NHostIP;
+   end;
+end;
+
+function TTCPConnection.VerifyFCrDNS: boolean;
+begin
+   Result:= NetAddrToStr(ResolveHost(HostIP.Name)) = HostIP.IP;
+end;
+
+procedure TTCPConnection.SetSockTimeOut(TimeOut: DWord);
+begin
+   FSockTimeOut:= TimeOut;
+   if Connected then begin
+      fpSetSockOpt(FSocket, SOL_SOCKET, SO_RCVTIMEO, @FSockTimeOut, SizeOf(FSockTimeOut));
+      fpSetSockOpt(FSocket, SOL_SOCKET, SO_SNDTIMEO, @FSockTimeOut, SizeOf(FSockTimeOut));
+   end;
+end;
+
+function TTCPConnection.ReadBuffer(PtrBuffer: pointer; Len: size_t): ssize_t;
+begin
+   Result:= fpRecv(FSocket, PtrBuffer, Len, 0);
+end;
+
+function TTCPConnection.WriteBuffer(PtrBuffer: pointer; Len: size_t): ssize_t;
+begin
+   Result:= fpSend(FSocket, PtrBuffer, Len, 0);
+end;
+
+function TTCPConnection.ReadLn(var Line: string): boolean;
+begin
+   Result:= SockReadLn(FSocket, Line);
+end;
+
+function TTCPConnection.WriteLn(const Line: string): boolean;
+begin
+   Result:= SockWriteLn(FSocket, Line);
+end;
+
+
+function TTCPRFCConnection.ReadCommand(var Command: shortstring; var Prms: string): boolean;
+begin
+   Result:= NetRFC.ReadCommand(FSocket, Command, Prms);
+end;
+
+function TTCPRFCConnection.ReadResponse(Response: TRFCReply): boolean;
+begin
+   Result:= NetRFC.ReadResponse(FSocket, Response);
+end;
+
+function TTCPRFCConnection.SendCommand(Command: shortstring): boolean;
+begin
+   Result:= NetRFC.SendCommand(FSocket, Command);
+end;
+
+function TTCPRFCConnection.SendCommand(Command: shortstring; Prms: string): boolean;
+begin
+   Result:= NetRFC.SendCommand(FSocket, Command, Prms);
+end;
+
+function TTCPRFCConnection.SendResponse(Response: TRFCReply): boolean;
+begin
+   Result:= NetRFC.SendResponse(FSocket, Response);
+end;
+
+
+procedure TTCPAcceptor.Execute;
+begin
+   FHandler(FTCPConnection);
+end;
+
+
+function TTCPListener.StartListen: boolean;
+begin
+   FListenSocket:= fpSocket(af_inet, sock_stream, 0);
+   if FListenSocket <> -1 then begin
+      with sAddr do begin
+         sin_family:= af_inet;
+         sin_port:= htons(FListenPort);
+         sin_addr.s_addr:= 0;
+      end;
+      if fpBind(FListenSocket, @sAddr, sizeof(sAddr)) <> -1 then begin
+         { It seems the maximum connection value isn't enforced by the
+           Free Pascal library, so this 512 is a constant, dummy value. }
+           { TEMPORARY SETTING OF 1 FROM 512! }
+         if fpListen(FListenSocket, 512) <> -1 then begin
+            Result:= true;
+            Start;
+         end
+         else Result:= false;
+      end
+      else Result:= false;
+   end
+   else Result:= false;
+end;
+
+procedure TTCPListener.StopListen;
+begin
+   Terminate;
+   KillThread(Handle);
+end;
+
+procedure TTCPListener.Execute;
+var ClientSocket: socket; AcceptFailCount: word; Len: longint;
+    TCPConnection: TTCPConnection;
+begin
+   { Now, accept connections. }
+   AcceptFailCount:= 0;
+   while not Terminated do begin
+      Len:= SizeOf(sAddr);
+      ClientSocket:= fpAccept(FListenSocket, @sAddr, @Len);
+      if ClientSocket <> -1 then begin
+         AcceptFailCount:= 0;
+
+         { Creates the requested TTCPConnection object for the accepted
+           connection. }
+         case FFeatureRequest of
+         NET_TCP_BASIC:
+            TCPConnection:= TTCPConnection.Create(ClientSocket, sAddr);
+         NET_TCP_RFCSUPPORT:
+            TCPConnection:= TTCPRFCConnection.Create(ClientSocket, sAddr);
+         end;
+
+         { Then start a new thread with the connection handler. }
+         TTCPAcceptor.Create(HandleClient, TCPConnection);
+      end
+      else begin
+         Inc(AcceptFailCount);
+         if AcceptFailCount >= 512 then Terminate;
+      end;
+   end;
+end;
+
+
+end.
diff --git a/Policies.pas b/Policies.pas
new file mode 100644 (file)
index 0000000..228fd35
--- /dev/null
@@ -0,0 +1,464 @@
+{
+   MegaBrutal's SMTP Server (MgSMTP)
+   Copyright (C) 2010-2014 MegaBrutal
+
+   This program is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Affero General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Affero General Public License for more details.
+
+   You should have received a copy of the GNU Affero General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+{
+   Unit: Policies
+   Responsible for manage rights for hosts and users, it also authenticates
+   users.
+}
+
+
+{$MODE DELPHI}
+unit Policies;
+
+interface
+uses SysUtils, Classes, INIFiles, md5, CompareWild, Common, Spool;
+
+const
+
+   { Rights can be assigned to connections and users. }
+   RIGHT_CONNECT      =   1;
+   RIGHT_STORE        =   2;
+   RIGHT_RELAY        =   4;
+
+   DEFAULT_RIGHTS     = RIGHT_CONNECT;
+   ALL_RIGHTS         = 255;
+
+
+   { Password types: }
+   PASSTYPE_PLAIN     =   0;
+   PASSTYPE_MD5       =   1;
+   PASSTYPE_INVALID   = 255;
+
+   { FCrDNS policies: }
+   FCRDNS_NAIVE       =   0;
+   FCRDNS_AWARE       =   1;
+   FCRDNS_MEAN        =   2;
+   FCRDNS_STRICT      =   3;
+
+
+type
+
+   TRights = byte;
+   TPassType = byte;
+
+   { TRuleHolder administers the rule table (given in the configuration)
+     for hosts or users, and it's capable of holding anything else's
+     rights that may have rights at all. }
+
+   TRuleHolder = class(TStringList)
+      constructor Create(WildcardSupport: boolean);
+   protected
+      FWildcardSupport: boolean;
+      Rights: array of TRights;
+   public
+      procedure AddRights(ItemName: string; AssignedRights: TRights);
+      function GetRightsOf(ItemName: string): TRights;
+      function GetRightsOfPair(FirstName, SecondName: string): TRights;
+   end;
+
+   { TPolicyObject holds the rights for one single object.
+     And additionally, it holds the databytes limit for it. }
+
+   TPolicyObject = class
+      constructor Create(Rights: TRights; Databytes: longint);
+   protected
+      FRights: TRights;
+      FDatabytes: longint;
+      procedure Reset(Rights: TRights; Databytes: longint);
+   public
+      procedure Grant(Right: TRights);
+      procedure Deny(Right: TRights);
+      function HasRight(Right: TRights): boolean;
+      function RightsStr: string;
+      property Databytes: longint read FDatabytes;
+   end;
+
+   { TUserPolicies holds the data assigned for a single user, except
+     rights. }
+
+   TUserPolicies = class(TNamedObject)
+      constructor Create(Name: string; Config: TINIFile);
+   protected
+      FAuth: boolean;
+      FDatabytes: longint;
+      FPassType: TPassType;
+      FPassword: string;
+   public
+      function Authenticate(Password: string): boolean;
+      property Databytes: longint read FDatabytes;
+   end;
+
+   { TPolicyManager is the interface for this unit. It sets up objects
+     corresponding the configuration, creates policy objects on request,
+     authenticates users, and so on. }
+
+   TPolicyManager = class
+      constructor Create(Config: TINIFile);
+      destructor Destroy; override;
+   protected
+      FHideVersion, FReqHELO, FHosts, FUsers: boolean;
+      FMaxAuthAttempts: integer;
+      FFCrDNSPolicy: byte;
+      HostRights, UserRights: TRuleHolder;
+      UserData: array of TUserPolicies;
+   public
+      function AuthenticateUser(Username, Password: string; PolicyObject: TPolicyObject): boolean;
+      function MakePolicyObject(Originator: TIPNamePair): TPolicyObject;
+      procedure RevalidatePolicyObject(PolicyObject: TPolicyObject; Originator: TIPNamePair; EvaluateHostname, MeanMode: boolean);
+      property HideVersion: boolean read FHideVersion;
+      property ReqHELO: boolean read FReqHELO;
+      property Hosts: boolean read FHosts;
+      property Users: boolean read FUsers;
+      property MaxAuthAttempts: integer read FMaxAuthAttempts;
+      property FCrDNSPolicy: byte read FFCrDNSPolicy;
+   end;
+
+
+   function RightsToStr(Rights: TRights): string;
+   function FCrDNSPolicyToStr(FCrDNSPolicy: byte): string;
+
+
+var
+
+   PolicyManager: TPolicyManager;
+
+
+implementation
+
+
+function StrToPassType(S: string): TPassType;
+begin
+   S:= UpperCase(S);
+   if S = 'PLAIN' then     Result:= PASSTYPE_PLAIN
+   else if S = 'MD5' then  Result:= PASSTYPE_MD5
+   else                    Result:= PASSTYPE_INVALID;
+end;
+
+function StrToRights(S: string): TRights;
+var SL: TStringList; i: integer; R: TRights;
+begin
+   S:= UpperCase(S);
+   SL:= TStringList.Create;
+   SL.Delimiter:= ',';
+   SL.DelimitedText:= S;
+   R:= DEFAULT_RIGHTS;
+
+   for i:= 0 to SL.Count - 1 do begin
+
+      if SL.Strings[i] = 'ALLOWSTORE' then
+         R:= R or RIGHT_STORE
+
+      else if SL.Strings[i] = 'ALLOWRELAY' then
+         R:= R or RIGHT_RELAY
+
+      else if SL.Strings[i] = 'CONNECT' then
+         R:= R or RIGHT_CONNECT
+
+      else if SL.Strings[i] = 'DENYSTORE' then
+         R:= R and (ALL_RIGHTS - RIGHT_STORE)
+
+      else if SL.Strings[i] = 'DENYRELAY' then
+         R:= R and (ALL_RIGHTS - RIGHT_RELAY)
+
+      else if SL.Strings[i] = 'DISCONNECT' then
+         R:= R and (ALL_RIGHTS - RIGHT_CONNECT)
+
+      else
+         { !!! TODO: Somehow report error !!! }
+         ;
+
+   end;
+
+   SL.Free;
+   Result:= R;
+end;
+
+function RightsToStr(Rights: TRights): string;
+var S: string;
+
+   procedure AddSep;
+   begin
+      if S <> '' then S:= S + ', ';
+   end;
+
+begin
+   S:= '';
+
+   if (Rights and RIGHT_CONNECT) <> 0 then
+      S:= 'CONNECT';
+
+   if (Rights and RIGHT_STORE) <> 0 then begin
+      AddSep; S:= S + 'STORE';
+   end;
+
+   if (Rights and RIGHT_RELAY) <> 0 then begin
+      AddSep; S:= S + 'RELAY';
+   end;
+
+   if S = '' then S:= '<NONE>';
+   Result:= S;
+end;
+
+function FCrDNSPolicyToStr(FCrDNSPolicy: byte): string;
+begin
+   case FCrDNSPolicy of
+      FCRDNS_NAIVE:  Result:= 'Naive';
+      FCRDNS_AWARE:  Result:= 'Aware';
+      FCRDNS_MEAN:   Result:= 'Mean';
+      FCRDNS_STRICT: Result:= 'Strict';
+      else           Result:= 'Unknown';
+   end;
+end;
+
+
+constructor TRuleHolder.Create(WildcardSupport: boolean);
+begin
+   inherited Create;
+   FWildcardSupport:= WildcardSupport;
+   SetLength(Rights, 0);
+end;
+
+
+constructor TPolicyObject.Create(Rights: TRights; Databytes: longint);
+begin
+   inherited Create;
+   Reset(Rights, Databytes);
+end;
+
+
+constructor TUserPolicies.Create(Name: string; Config: TINIFile);
+var Section: string;
+begin
+   Section:= 'Policies\Users\' + Name;
+   inherited Create(Name, Config, Section);
+   FAuth:=        Config.ReadBool(Section, 'Auth', true);
+   FDatabytes:=   Config.ReadInteger(Section, 'Databytes', SpoolManager.Databytes);
+   FPassType:=    StrToPassType(Config.ReadString(Section, 'PassType', 'plain'));
+   FPassword:=    Config.ReadString(Section, 'Password', '');
+end;
+
+
+constructor TPolicyManager.Create(Config: TINIFile);
+var Section, RS, TS: string; i: integer; SL: TStringList;
+begin
+   inherited Create;
+   SetLength(UserData, 0);
+   if MainServerConfig.Policies then begin
+      Section:= 'Policies';
+      FHideVersion:= Config.ReadBool(Section, 'HideVersion', false);
+      FHosts:=       Config.ReadBool(Section, 'Hosts', true);
+      FUsers:=       Config.ReadBool(Section, 'Users', true);
+      FReqHELO:=     Config.ReadBool(Section, 'ReqHELO', false);
+
+      FMaxAuthAttempts:= Config.ReadInteger(Section, 'MaxAuthAttempts', 0);
+
+      HostRights:=   TRuleHolder.Create(true);
+      UserRights:=   TRuleHolder.Create(false);
+
+      { Load FCrDNSPolicy. }
+      TS:= UpperCase(Config.ReadString(Section, 'FCrDNSPolicy', 'AWARE'));
+      if TS = 'AWARE' then FFCrDNSPolicy:= FCRDNS_AWARE
+      else if TS = 'MEAN' then FFCrDNSPolicy:= FCRDNS_MEAN
+      else if TS = 'STRICT' then FFCrDNSPolicy:= FCRDNS_STRICT
+      else FFCrDNSPolicy:= FCRDNS_NAIVE;
+
+      SL:= TStringList.Create;
+
+      { Load the rules (rights) for hosts. }
+      Config.ReadSection(Section + '\Hosts', SL);
+      for i:= 0 to SL.Count - 1 do begin
+         RS:= Config.ReadString(Section + '\Hosts', SL.Strings[i], '');
+         HostRights.AddRights(SL.Strings[i], StrToRights(RS));
+      end;
+
+      SL.Clear;
+
+      { Load the rules (rights) and other data for users. }
+      if FUsers then begin
+         Config.ReadSection(Section + '\Users', SL);
+         SetLength(UserData, SL.Count);
+         for i:= 0 to SL.Count - 1 do begin
+            RS:= Config.ReadString(Section + '\Users', SL.Strings[i], '');
+            UserRights.AddRights(SL.Strings[i], StrToRights(RS));
+            UserData[i]:= TUserPolicies.Create(SL.Strings[i], Config);
+         end;
+      end;
+
+      { Disable user authentication, if there are no users. }
+      FUsers:= Length(UserData) <> 0;
+
+      SL.Free;
+   end
+   else begin
+      FHosts:= false; FUsers:= false; FReqHELO:= false; FHideVersion:= false;
+      FMaxAuthAttempts:= 0;
+      FFCrDNSPolicy:= FCRDNS_NAIVE;
+   end;
+end;
+
+destructor TPolicyManager.Destroy;
+var i: integer;
+begin
+   HostRights.Free;
+   UserRights.Free;
+   for i:= 0 to Length(UserData) - 1 do
+      UserData[i].Free;
+   SetLength(UserData, 0);
+   inherited Destroy;
+end;
+
+
+procedure TRuleHolder.AddRights(ItemName: string; AssignedRights: TRights);
+var i: integer;
+begin
+   i:= Count;
+   Add(ItemName);
+   SetLength(Rights, i + 1);
+   Rights[i]:= AssignedRights;
+end;
+
+function TRuleHolder.GetRightsOf(ItemName: string): TRights;
+begin
+   Result:= GetRightsOfPair(ItemName, '');
+end;
+
+function TRuleHolder.GetRightsOfPair(FirstName, SecondName: string): TRights;
+{ GetRightsOfPair takes 2 names, usually a hostname and an IP, and checks
+  which entry in the rule table matches for any of them, in the correct order.
+  It only jumps to the next item of the list if neither of the names match
+  for the actual one.
+  If there are no rights associated to the names, DEFAULT_RIGHTS will be
+  returned. }
+var i: integer; f: boolean;
+begin
+   i:= 0; f:= false;
+   while (i < Count) and (not f) do begin
+      if FWildcardSupport then
+         f:= WildComp(UpperCase(Strings[i]), UpperCase(FirstName)) or WildComp(UpperCase(Strings[i]), UpperCase(SecondName))
+      else
+         f:= (Strings[i] = FirstName) or (Strings[i] = SecondName);
+      Inc(i);
+   end;
+   Dec(i);
+   if f then Result:= Rights[i] else Result:= DEFAULT_RIGHTS;
+end;
+
+
+procedure TPolicyObject.Reset(Rights: TRights; Databytes: longint);
+begin
+   FRights:= Rights; FDatabytes:= Databytes;
+end;
+
+procedure TPolicyObject.Grant(Right: TRights);
+begin
+   FRights:= FRights or Right;
+end;
+
+procedure TPolicyObject.Deny(Right: TRights);
+begin
+   FRights:= FRights and (not Right);
+end;
+
+function TPolicyObject.HasRight(Right: TRights): boolean;
+{ If "Right" has more than one right-flags set, the function only returns
+  TRUE, when the object has all the rights. }
+begin
+   Result:= (FRights and Right) = Right;
+end;
+
+function TPolicyObject.RightsStr: string;
+begin
+   Result:= RightsToStr(FRights);
+end;
+
+
+function TUserPolicies.Authenticate(Password: string): boolean;
+begin
+   case FPassType of
+
+   PASSTYPE_PLAIN:
+      Result:= FPassword = Password;
+
+   PASSTYPE_MD5:
+      Result:= FPassword = MD5Print(MD5String(Password));
+
+   else
+      { I can't authenticate anything with an invalid password type. }
+      Result:= false;
+
+   end;
+
+end;
+
+
+function TPolicyManager.AuthenticateUser(Username, Password: string; PolicyObject: TPolicyObject): boolean;
+{ Authenticates a user, returns true if successful, and updates PolicyObject
+  with the new rights acquired. }
+var i: integer; f: boolean;
+begin
+   if (MainServerConfig.Policies) and (FUsers) then begin
+      i:= 0; f:= false;
+      while (i < Length(UserData)) and (not f) do begin
+         f:= UserData[i].IsItYourName(Username);
+         Inc(i);
+      end;
+      Dec(i);
+
+      if f then begin
+         if UserData[i].Authenticate(Password) then begin
+            PolicyObject.Reset(UserRights.GetRightsOf(Username), UserData[i].Databytes);
+            Result:= true;
+         end
+         else Result:= false;
+      end
+      else Result:= false;
+   end
+   else Result:= false;
+end;
+
+function TPolicyManager.MakePolicyObject(Originator: TIPNamePair): TPolicyObject;
+{ Make a policy object, and assign the rights corresponding to the given
+  originator. If Policies are disabled by configuration, assign ALL_RIGHTS. }
+begin
+   if MainServerConfig.Policies then begin
+      Result:= TPolicyObject.Create(
+                  HostRights.GetRightsOfPair(Originator.Name, Originator.IP),
+                  SpoolManager.Databytes
+               );
+   end
+   else begin
+      Result:= TPolicyObject.Create(
+                  ALL_RIGHTS,
+                  SpoolManager.Databytes
+               );
+   end;
+end;
+
+procedure TPolicyManager.RevalidatePolicyObject(PolicyObject: TPolicyObject; Originator: TIPNamePair; EvaluateHostname, MeanMode: boolean);
+var RestrictiveMask: TRights;
+begin
+   if MeanMode then RestrictiveMask:= PolicyObject.FRights else RestrictiveMask:= ALL_RIGHTS;
+   if EvaluateHostname then
+      PolicyObject.Reset(HostRights.GetRightsOfPair(Originator.Name, Originator.IP) and RestrictiveMask, PolicyObject.Databytes)
+   else
+      PolicyObject.Reset(HostRights.GetRightsOf(Originator.IP) and RestrictiveMask, PolicyObject.Databytes);
+end;
+
+
+end.
diff --git a/RFCSMTP.pas b/RFCSMTP.pas
new file mode 100644 (file)
index 0000000..48de473
--- /dev/null
@@ -0,0 +1,80 @@
+{
+   Copyright (C) 2010 MegaBrutal
+
+   This unit is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Lesser General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This unit is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+
+{$MODE DELPHI}
+
+unit RFCSMTP;
+
+interface
+
+const
+
+   STANDARD_SMTP_PORT         =     25;
+
+
+   SMTP_R_READY               =    220;
+   SMTP_R_CLOSE               =    221;
+   SMTP_R_SERVICE_NA          =    421;
+
+   SMTP_R_OK                  =    250;
+   SMTP_R_USERNOTLOCAL        =    251;
+   SMTP_R_CANNOTVERIFY        =    252;
+   SMTP_R_MAILBOX_BUSY        =    450;
+   SMTP_R_MAILBOX_NA          =    550;
+
+   SMTP_R_ABORTED             =    451;
+   SMTP_R_TRYFORWARD          =    551;
+   SMTP_R_STOR_FULL           =    452;
+   SMTP_R_STOR_EXCEEDED       =    552;
+   SMTP_R_MB_SYNTAX_ERROR     =    553;
+
+   SMTP_R_START_MAIL_INPUT    =    354;
+   SMTP_R_TRANS_FAILED        =    554;
+
+   SMTP_R_CMD_SYNTAX_ERROR    =    500;
+   SMTP_R_PRM_SYNTAX_ERROR    =    501;
+   SMTP_R_CMD_NOT_IMPLEMENTED =    502;
+   SMTP_R_BAD_SEQUENCE        =    503;
+   SMTP_R_PRM_NOT_IMPLEMENTED =    504;
+
+   SMTP_R_SYSTEM_STATUS       =    211;
+   SMTP_R_HELP_MESSAGE        =    214;
+
+   SMTP_R_AUTH_MESSAGE        =    334;
+   SMTP_R_AUTH_SUCCESSFUL     =    235;
+   SMTP_R_AUTH_FAILED         =    535;
+
+
+   SMTP_C_EHLO                = 'EHLO';
+   SMTP_C_HELO                = 'HELO';
+   SMTP_C_RSET                = 'RSET';
+   SMTP_C_NOOP                = 'NOOP';
+   SMTP_C_QUIT                = 'QUIT';
+   SMTP_C_AUTH                = 'AUTH';
+
+   SMTP_C_MAIL                = 'MAIL';
+   SMTP_C_RCPT                = 'RCPT';
+   SMTP_C_DATA                = 'DATA';
+   SMTP_C_VRFY                = 'VRFY';
+
+
+
+implementation
+
+
+end.
diff --git a/Relay.pas b/Relay.pas
new file mode 100644 (file)
index 0000000..4984bc1
--- /dev/null
+++ b/Relay.pas
@@ -0,0 +1,565 @@
+{
+   MegaBrutal's SMTP Server (MgSMTP)
+   Copyright (C) 2010 MegaBrutal
+
+   This program is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Affero General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Affero General Public License for more details.
+
+   You should have received a copy of the GNU Affero General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+{
+   Unit: Relay
+   This unit implements the necessary objects to relay messages towards
+   remote servers. It handles the re-routing of messages, when it's
+   configured.
+}
+
+
+{$MODE DELPHI}
+unit Relay;
+
+interface
+uses SysUtils, Classes, INIFiles, Base64, CompareWild, Common, Network,
+     DNSMX, NetRFC, RFCSMTP;
+
+type
+
+   TMailRoute = record
+      Mask: string;
+      Target: integer;
+   end;
+
+   TSMTPExtensions = record
+      Pipelining, Size, EbitMIME: boolean;
+   end;
+
+   { A TRoutingTarget holds the data for a single relay host.
+     The administrator may give a symbolic name to some relay hosts that
+     identifies a distinct section in the configuration INI file, where
+     all necessary data can be found to contact the particular relay host. }
+
+   TRoutingTarget = class
+      constructor Create(Name, TargetHost: string; Port: integer; Auth: boolean; Username, Password: string);
+   protected
+      FName, FTargetHost, FUsername, FPassword: string;
+      FPort: integer;
+      FAuth: boolean;
+   public
+      property Name: string read FName;
+      property Host: string read FTargetHost;
+      property Port: integer read FPort;
+      property Auth: boolean read FAuth;
+      property Username: string read FUsername;
+      property Password: string read FPassword;
+      function Copy: TRoutingTarget;
+   end;
+
+   { TRoutingTable manages re-routing. It can be asked where to relay e-mails
+     for a specific host. It holds multiple instances of TRoutingTarget. }
+
+   TRoutingTable = class
+      constructor Create;
+      destructor Destroy; override;
+   protected
+      Targets: array of TRoutingTarget;
+      Routes: array of TMailRoute;
+      function FindOrLoadTarget(TargetName, TargetHost: string; Port: integer; Auth: boolean; Username, Password: string): integer;
+   public
+      procedure AddRoute(Mask: string; TargetName, TargetHost: string; Port: integer; Auth: boolean; Username, Password: string);
+      function ReRoute(Host: string): string;
+      function GetRouteInfo(Host: string): TRoutingTarget;
+   end;
+
+   { TRelayer does the actual relaying to a host. It connects the target server
+     and passes the message to it by SMTP protocol. }
+
+   TRelayer = class
+      constructor Create(RoutingTable: TRoutingTable; Envelope: TEnvelope; EMailProperties: TEMailProperties);
+      destructor Destroy; override;
+   protected
+      FEnvelope: TEnvelope;
+      FEMailProperties: TEMailProperties;
+      FRoutingTarget: TRoutingTarget;
+      RoutingTable: TRoutingTable;
+      TCP: TTCPRFCConnection;
+      Response: TRFCReply;
+      SMTPExtensions: TSMTPExtensions;
+      procedure AdministerMassFailure(var Result: boolean);
+      function GetRelayServerName: string;
+      function GetRelayServerPort: integer;
+   public
+      property Envelope: TEnvelope read FEnvelope;
+      property EMailProperties: TEMailProperties read FEMailProperties;
+      property RelayServerName: string read GetRelayServerName;
+      property RelayServerPort: integer read GetRelayServerPort;
+      function OpenConnection: boolean;
+      function Greet: boolean;
+      function SendEnvelope: boolean;
+      function PrepareSendMessage: boolean;
+      function DeliverMessagePart(Chunk: TStrings): boolean;
+      procedure FinishDeliverMessage;
+      procedure CloseConnection;
+   end;
+
+   { TRelayManager is the main manager object of the entire relay unit.
+     It loads all the configuration, sets up the corresponding objects,
+     and it creates configured TRelayer-s. }
+
+   TRelayManager = class
+      constructor Create(Config: TINIFile);
+      destructor Destroy; override;
+   protected
+      RelayToList, NoRelayToList: TStrings;
+      RoutingTable: TRoutingTable;
+   public
+      function CreateRelayer(Envelope: TEnvelope; EMailProperties: TEMailProperties): TRelayer;
+      function IsOnRelayToList(HostName: string): boolean;
+      function IsOnNoRelayToList(HostName: string): boolean;
+      function OrganizeEnvelopes(Envelopes: TEnvelopeArray): TEnvelopeArray;
+   end;
+
+
+var
+
+   RelayManager: TRelayManager;
+
+
+
+implementation
+
+
+constructor TRoutingTarget.Create(Name, TargetHost: string; Port: Integer; Auth: boolean; Username, Password: string);
+begin
+   inherited Create;
+   FName:= Name;
+   if TargetHost = '' then FTargetHost:= Name else FTargetHost:= TargetHost;
+   FPort:= Port;
+   FAuth:= Auth;
+   FUsername:= Username;
+   FPassword:= Password;
+end;
+
+constructor TRoutingTable.Create;
+begin
+   inherited Create;
+   SetLength(Targets, 0);
+   SetLength(Routes, 0);
+end;
+
+destructor TRoutingTable.Destroy;
+var i: integer;
+begin
+   for i:= 0 to Length(Targets) - 1 do
+      Targets[i].Free;
+   SetLength(Routes, 0);
+   SetLength(Targets, 0);
+   inherited Destroy;
+end;
+
+constructor TRelayer.Create(RoutingTable: TRoutingTable; Envelope: TEnvelope; EMailProperties: TEMailProperties);
+begin
+   inherited Create;
+   Self.RoutingTable:= RoutingTable;
+   FEnvelope:= Envelope;
+   FEMailProperties:= EMailProperties;
+   FRoutingTarget:= RoutingTable.GetRouteInfo(Envelope.RelayHost);
+   Response:= TRFCReply.Create;
+   FillChar(SMTPExtensions, SizeOf(TSMTPExtensions), #0);
+end;
+
+destructor TRelayer.Destroy;
+begin
+   FRoutingTarget.Free;
+   Response.Free;
+   inherited Destroy;
+end;
+
+constructor TRelayManager.Create(Config: TINIFile);
+var i: integer; RouteMasks: TStringList; RouteName: string;
+begin
+   inherited Create;
+
+   RelayToList:= TStringList.Create;
+   RelayToList.Delimiter:= ',';
+   RelayToList.DelimitedText:= Config.ReadString('Relay', 'RelayTo', '');
+
+   NoRelayToList:= TStringList.Create;
+   NoRelayToList.Delimiter:= ',';
+   NoRelayToList.DelimitedText:= Config.ReadString('Relay', 'NoRelayTo', '');
+
+   RoutingTable:= TRoutingTable.Create;
+   RouteMasks:= TStringList.Create;
+   Config.ReadSection('Relay\Routes', RouteMasks);
+   for i:= 0 to RouteMasks.Count - 1 do begin
+      RouteName:= Config.ReadString('Relay\Routes', RouteMasks.Strings[i], '!');
+      RoutingTable.AddRoute(RouteMasks.Strings[i],
+         RouteName,
+         Config.ReadString('Relay\Routes\' + RouteName, 'Host', ''),
+         Config.ReadInteger('Relay\Routes\' + RouteName, 'Port', STANDARD_SMTP_PORT),
+         Config.ReadBool('Relay\Routes\' + RouteName, 'Auth', false),
+         Config.ReadString('Relay\Routes\' + RouteName, 'Username', ''),
+         Config.ReadString('Relay\Routes\' + RouteName, 'Password', '')
+      );
+   end;
+   RouteMasks.Free;
+end;
+
+destructor TRelayManager.Destroy;
+begin
+   RelayToList.Free;
+   RoutingTable.Free;
+   inherited Destroy;
+end;
+
+
+function TRoutingTarget.Copy: TRoutingTarget;
+begin
+   Result:= TRoutingTarget.Create(Name, Host, Port, Auth, Username, Password);
+end;
+
+procedure TRoutingTable.AddRoute(Mask: string; TargetName, TargetHost: string; Port: integer; Auth: boolean; Username, Password: string);
+{ It should be only called at start-up. It creates the necessary TRountingTarget
+  objects. It doesn't create redundant targets. If more entries are there to
+  relay to a specific server, then only one TRoutingTarget will be created
+  for that relay host. It is ensured by FindOrLoadTarget. }
+var i: integer;
+begin
+   i:= Length(Routes);
+   SetLength(Routes, i + 1);
+   Routes[i].Mask:= Mask;
+   Routes[i].Target:= FindOrLoadTarget(TargetName, TargetHost, Port, Auth, Username, Password);
+end;
+
+function TRoutingTable.FindOrLoadTarget(TargetName, TargetHost: string; Port: integer; Auth: boolean; Username, Password: string): integer;
+{ Creates a new TRoutingTarget, but only if no other TRoutingTarget exists
+  with the same name. If it does find an already-existing TRoutingTarget
+  with the given name, it returns that instance. }
+var i, x: integer; Found: boolean;
+begin
+   i:= 0; Found:= false;
+   while (i < Length(Targets)) and (not Found) do begin
+      if Targets[i].Name = TargetName then begin
+         Found:= true;
+         x:= i;
+      end;
+      Inc(i);
+   end;
+   if not Found then begin
+      x:= Length(Targets);
+      SetLength(Targets, x + 1);
+      Targets[x]:= TRoutingTarget.Create(TargetName, TargetHost, Port, Auth, Username, Password);
+   end;
+   Result:= x;
+end;
+
+function TRoutingTable.ReRoute(Host: string): string;
+{ It returns the NAME of the relay host that's supposed to relay messages
+  towards the specified host. The mentioned NAME can be a hostname or
+  a symbolic name given in the configuration. If this function returns "!",
+  that means that the message should be relayed to the named host itself. }
+var i: integer; Found: boolean;
+begin
+   i:= 0; Found:= false;
+   while (i < Length(Routes)) and (not Found) do begin
+      if WildComp(UpperCase(Routes[i].Mask), UpperCase(Host)) then begin
+         Result:= Targets[Routes[i].Target].Name;
+         Found:= true;
+      end;
+      Inc(i);
+   end;
+   if not Found then Result:= Host;
+end;
+
+function TRoutingTable.GetRouteInfo(Host: string): TRoutingTarget;
+{ It returns the corresponding TRoutingTarget for a given name.
+  That name may be a symbolic name, given in the configuration,
+  or a valid hostname.
+  Note, this function returns a COPY of the TRoutingTarget.
+  The caller is responsible for freeing it.
+  If there is no TRoutingTarget with the given name, the function
+  creates a new TRoutingTarget and puts the given hostname into it. }
+var i: integer; Found: boolean;
+begin
+   i:= 0; Found:= false;
+   while (i < Length(Targets)) and (not Found) do begin
+      if Targets[i].Name = Host then begin
+         Result:= Targets[i].Copy;
+         Found:= true;
+      end;
+      Inc(i);
+   end;
+   if not Found then Result:= TRoutingTarget.Create(Host, Host, STANDARD_SMTP_PORT, false, '', '');
+end;
+
+
+procedure TRelayer.AdministerMassFailure(var Result: boolean);
+var i: integer;
+begin
+   for i:= 0 to Envelope.GetNumberOfRecipients - 1 do
+      Envelope.SetRecipientData(i, Response.GetNumericCode, Response.ReplyText.Text);
+   Result:= false;
+end;
+
+function TRelayer.GetRelayServerName: string;
+begin
+   Result:= FRoutingTarget.Host;
+end;
+
+function TRelayer.GetRelayServerPort: integer;
+begin
+   Result:= FRoutingTarget.Port;
+end;
+
+function TRelayer.OpenConnection: boolean;
+{ Initiates connection to the relay site. It queries the MX records for the
+  relay site's domain, and tries to connect the resulting hosts in the
+  order of MX priorities. If there are no MX records for the domain,
+  the domain's A record will be connected.
+  The function returns TRUE, if it successfully established connection
+  to any of the MX hostnames. }
+var MXList: TStrings; i: integer;
+begin
+   MXList:= GetCorrectMXRecordList(RelayServerName);
+   if MXList.Count >= 1 then begin
+      TCP:= TTCPRFCConnection.Create(MXList.Strings[0], RelayServerPort);
+      TCP.SetSockTimeOut(DEF_SOCK_TIMEOUT);
+      i:= 1;
+      while (not TCP.Connected) and (i < MXList.Count) do begin
+         TCP.Connect(MXList.Strings[i], RelayServerPort);
+         Inc(i);
+      end;
+      Result:= TCP.Connected;
+   end
+   else Result:= false;
+   MXList.Free;
+end;
+
+function TRelayer.Greet: boolean;
+{ This function reads and checks the relay server's greeting.
+  Then, if necessary, authenticates at the connected relay server.
+  Then identifies this server with a HELO.
+  The function returns true, if the authentication and the EHLO command were
+  successful. }
+var
+   i: integer;
+   Authenticated: boolean;
+   StringStream: TStringStream;
+   Base64EncodingStream: TBase64EncodingStream;
+   Line: string;
+
+begin
+   Response.Clear;
+   AdministerMassFailure(Result);
+   TCP.ReadResponse(Response);
+   if Response.GetNumericCode = SMTP_R_READY then begin
+
+      TCP.SendCommand(SMTP_C_EHLO, MainServerConfig.Name);
+      TCP.ReadResponse(Response);
+
+      if Response.GetNumericCode = SMTP_R_OK then begin
+         for i:= 1 to Response.Count - 1 do begin
+            Line:= UpperCase(Response.GetLine(i));
+            if pos('PIPELINING', Line) = 1 then
+               SMTPExtensions.Pipelining:= true
+            else if pos('SIZE', Line) = 1 then
+               SMTPExtensions.Size:= true
+            else if pos('8BITMIME', Line) = 1 then
+               SMTPExtensions.EbitMIME:= true;
+         end;
+         Result:= true;
+      end
+      else AdministerMassFailure(Result);
+
+      if Result then begin
+         if FRoutingTarget.Auth then begin
+            TCP.SendCommand(SMTP_C_AUTH, 'LOGIN');
+            TCP.ReadResponse(Response);
+            if Response.GetNumericCode = SMTP_R_AUTH_MESSAGE then begin
+               StringStream:= TStringStream.Create('');
+               Base64EncodingStream:= TBase64EncodingStream.Create(StringStream);
+               Base64EncodingStream.Write(PChar(FRoutingTarget.Username)^, Length(FRoutingTarget.Username));
+               Base64EncodingStream.Destroy;
+               TCP.WriteLn(StringStream.DataString);
+               StringStream.Destroy;
+               TCP.ReadResponse(Response);
+               if Response.GetNumericCode = SMTP_R_AUTH_MESSAGE then begin
+                  StringStream:= TStringStream.Create('');
+                  Base64EncodingStream:= TBase64EncodingStream.Create(StringStream);
+                  Base64EncodingStream.Write(PChar(FRoutingTarget.Password)^, Length(FRoutingTarget.Password));
+                  Base64EncodingStream.Destroy;
+                  TCP.WriteLn(StringStream.DataString);
+                  StringStream.Destroy;
+                  TCP.ReadResponse(Response);
+                  Authenticated:= Response.GetNumericCode = SMTP_R_AUTH_SUCCESSFUL;
+               end
+               else Authenticated:= false;
+            end
+            else Authenticated:= false;
+         end
+         else Authenticated:= true;
+
+         if not Authenticated then AdministerMassFailure(Result);
+      end;
+
+   end
+   else AdministerMassFailure(Result);
+end;
+
+function TRelayer.SendEnvelope: boolean;
+{ Sends the envelope (that is the return-path and the recipient addresses).
+  The function returns true, if the MAIL command were successful, and the
+  relay server has accepted at least one of the recipient addresses.
+  This function is aware of the SMTP extension, named PIPELINING. If it's
+  supported by the server, we send RCPT commands stuffed, without waiting
+  for a response. After all RCPTs are sent, we check all responses. }
+var
+   i, c: integer; Prms: string;
+
+   procedure ProcessRCPTResponse;
+   begin
+      TCP.ReadResponse(Response);
+      if Response.GetNumericCode = SMTP_R_OK then Inc(c);
+      Envelope.SetRecipientData(i, Response.GetNumericCode, Response.ReplyText.Text);
+   end;
+
+begin
+   Response.Clear;
+   Prms:= 'FROM:<' + Envelope.ReturnPath + '>';
+
+   if SMTPExtensions.Size then
+      Prms:= Prms + ' SIZE=' + IntToStr(EMailProperties.Size);
+   if SMTPExtensions.EbitMIME and EMailProperties.HasFlag(EF_8BITMIME) then
+      Prms:= Prms + ' BODY=8BITMIME';
+
+   TCP.SendCommand(SMTP_C_MAIL, Prms);
+   TCP.ReadResponse(Response);
+   if Response.GetNumericCode = SMTP_R_OK then begin
+      c:= 0;
+      for i:= 0 to Envelope.GetNumberOfRecipients - 1 do begin
+         TCP.SendCommand(SMTP_C_RCPT, 'TO:<' + Envelope.GetRecipient(i).Address + '>');
+         { If pipelining is not supported, read the responses now. }
+         if not SMTPExtensions.Pipelining then ProcessRCPTResponse;
+      end;
+
+      { If pipelining is supported, process all responses. }
+      if SMTPExtensions.Pipelining then
+         for i:= 0 to Envelope.GetNumberOfRecipients - 1 do
+            ProcessRCPTResponse;
+
+      Result:= c <> 0;
+      if not Result then begin
+         TCP.SendCommand(SMTP_C_RSET);
+         TCP.ReadResponse(Response);
+      end;
+   end
+   else AdministerMassFailure(Result);
+end;
+
+function TRelayer.PrepareSendMessage;
+{ Prepares mail transmission with the DATA command. }
+begin
+   TCP.SendCommand(SMTP_C_DATA);
+   TCP.ReadResponse(Response);
+   Result:= Response.GetNumericCode = SMTP_R_START_MAIL_INPUT;
+end;
+
+function TRelayer.DeliverMessagePart(Chunk: TStrings): boolean;
+{ Sends a chunk of the message. }
+begin
+   Result:= TCP.WriteBuffer(PChar(Chunk.Text), Length(Chunk.Text)) <> -1;
+end;
+
+procedure TRelayer.FinishDeliverMessage;
+{ Finishes the message with a line containing a single dot. }
+var i: integer;
+begin
+   TCP.WriteLn('.');
+   TCP.ReadResponse(Response);
+   for i:= 0 to Envelope.GetNumberOfRecipients - 1 do begin
+      if Envelope.GetRecipient(i).Data = SMTP_R_OK then
+         Envelope.SetRecipientData(i, Response.GetNumericCode, Response.ReplyText.Text);
+   end;
+end;
+
+procedure TRelayer.CloseConnection;
+begin
+   TCP.SendCommand(SMTP_C_QUIT);
+   {TCP.ReadResponse(Response);}
+   TCP.Free;
+end;
+
+
+function TRelayManager.CreateRelayer(Envelope: TEnvelope; EMailProperties: TEMailProperties): TRelayer;
+begin
+   Result:= TRelayer.Create(RoutingTable, Envelope, EMailProperties);
+end;
+
+function TRelayManager.IsOnRelayToList(HostName: string): boolean;
+begin
+   Result:= RelayToList.IndexOf(HostName) <> -1;
+end;
+
+function TRelayManager.IsOnNoRelayToList(HostName: string): boolean;
+begin
+   Result:= NoRelayToList.IndexOf(HostName) <> -1;
+end;
+
+function TRelayManager.OrganizeEnvelopes(Envelopes: TEnvelopeArray): TEnvelopeArray;
+{ Organizes the given envelopes for relaying.
+  This function assumes that input envelopes are containing recipient
+  addresses orientating to the same site.
+  If it turns out that e-mails for multiple sites must be actually relayed
+  through the same relay server, this function merges the envelopes for
+  those sites; so later, such e-mails will be transmitted though a single
+  connection.
+
+  For example, the configuration file indicates:
+  - E-mails for "foo.com" must be relayed through "myrelaysmtp".
+  - E-mails for "bar.com" must be also relayed through "myrelaysmtp".
+  In this case, the envelopes for "foo.com" and "bar.com" will be merged,
+  and the e-mail for these sites will be transmitted in one TCP connection. }
+
+var i, j, k: integer; f: boolean; Recipient: TRecipient; OrgHost, TrgHost: string;
+begin
+   SetLength(Result, 0);
+   for i:= 0 to Length(Envelopes) - 1 do begin
+      if Envelopes[i].GetNumberOfRecipients > 0 then begin
+         Recipient:= Envelopes[i].GetRecipient(0);
+         OrgHost:= EMailHost(Recipient.Address);
+         TrgHost:= RoutingTable.ReRoute(OrgHost);
+         if TrgHost = '!' then TrgHost:= OrgHost;
+         j:= 0; f:= false;
+         while (j < Length(Result)) and (not f) do begin
+            f:= Result[j].RelayHost = TrgHost;
+            Inc(j);
+         end;
+         { Note, if (not f) then j holds Length(Result). }
+         if not f then begin
+            SetLength(Result, j + 1);
+            Result[j]:= TEnvelope.Create;
+            Result[j].ReturnPath:= Envelopes[i].ReturnPath;
+            Result[j].RelayHost:= TrgHost;
+         end
+         else Dec(j); { j must be decremented, because we over-incremented it in the loop. }
+         with Result[j] do begin
+            { Add first recipient to the envelope. }
+            AddRecipient(Recipient);
+            { Add the remaining recipients. }
+            for k:= 1 to Envelopes[i].GetNumberOfRecipients - 1 do
+               AddRecipient(Envelopes[i].GetRecipient(k));
+         end;
+      end;
+   end;
+end;
+
+
+end.
diff --git a/SocketUtils.pas b/SocketUtils.pas
new file mode 100644 (file)
index 0000000..e9bf4f8
--- /dev/null
@@ -0,0 +1,57 @@
+{
+   Copyright (C) 2010 MegaBrutal
+
+   This unit is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Lesser General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This unit is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+
+{$MODE DELPHI}
+
+unit SocketUtils;
+
+interface
+uses Sockets;
+
+type
+
+   socket = longint;
+
+
+   function SockReadLn(Sock: socket; var Line: string): boolean;
+   function SockWriteLn(Sock: socket; const Line: string): boolean;
+
+
+
+implementation
+
+
+function SockReadLn(Sock: socket; var Line: string): boolean;
+var recvb: longint; ch: char;
+begin
+   Line:= '';
+   repeat
+      recvb:= fpRecv(Sock, @ch, 1, 0);
+      if (recvb = 1) and ((ch <> #13) and (ch <> #10)) then
+         Line:= Line + ch;
+   until (recvb <> 1) or (ch = #10);
+   Result:= (recvb = 1);
+end;
+
+function SockWriteLn(Sock: socket; const Line: string): boolean;
+begin
+   Result:= fpSend(Sock, PChar(Line + #13#10), Length(Line) + 2, 0) <> -1;
+end;
+
+
+end.
diff --git a/Spool.pas b/Spool.pas
new file mode 100644 (file)
index 0000000..558205d
--- /dev/null
+++ b/Spool.pas
@@ -0,0 +1,992 @@
+{
+   MegaBrutal's SMTP Server (MgSMTP)
+   Copyright (C) 2010-2014 MegaBrutal
+
+   This program is free software: you can redistribute it and/or modify
+   it under the terms of the GNU Affero General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Affero General Public License for more details.
+
+   You should have received a copy of the GNU Affero General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+}
+
+{
+   Unit: Spool
+   The Spool unit is the soul of MgSMTP. It implements objects to create
+   and read "spool objects" (e-mails being queued by the mail server),
+   and delivery threads (the threads those actually delivers a queued
+   message to a local mailbox or a remote server.
+}
+
+
+{$MODE DELPHI}
+unit Spool;
+
+interface
+uses SysUtils, Classes, INIFiles, Common, Log, Relay, Bounce;
+
+type
+
+   TSpoolFilters = array of string;
+
+   TSpoolConfig = record
+      AllowExceedQuota: boolean;
+      MaxReceivedHeaders: integer;
+      ThreadWait: integer;
+      TryCount, TryDelay: integer;
+      TempFailNotifyFirst: boolean;
+      TempFailNotify: integer;
+      KeepProcessedEnvelopes: boolean;
+      KeepProcessedEMails: boolean;
+   end;
+
+
+   PSpoolObject = ^TSpoolObject;
+   TSpoolObject = class
+      constructor Create(const Name: string; const SpoolConfig: TSpoolConfig);
+      destructor Destroy; override;
+   protected
+      FName: string;
+      FOpened: boolean;
+      FEnvelope: TEnvelope;
+      FOriginator: TIPNamePair;
+      FEMailProperties: TEMailProperties;
+      SpoolConfig: TSpoolConfig;
+      SpoolData: TINIFile;
+      MailFile: TStream;
+      StringBuffer: TStrings;
+   public
+      property Name: string read FName;
+      property Envelope: TEnvelope read FEnvelope;
+      property EMailProperties: TEMailProperties read FEMailProperties;
+      property Originator: TIPNamePair read FOriginator;
+      property Opened: boolean read FOpened;
+      function Open: boolean; virtual; abstract;
+      procedure Close; virtual;
+      procedure Discard; virtual; abstract;
+      function IsActual(DelaySeconds: TUnixTimeStamp): boolean; virtual;
+      function IsExpired(MaxTryCount: integer; BeforeIncrement: boolean): boolean; virtual;
+      function GetAccessTime: TUnixTimeStamp; virtual;
+      function GetCurrentTryCount: integer; virtual;
+      procedure IncrementTryCount; virtual;
+      procedure SetAccessTime(TimeStamp: TUnixTimeStamp); virtual;
+      procedure SetThreadInfo(ThreadNum: integer; ThreadOSID: TThreadID); virtual;
+      procedure Actualize; virtual;
+      function GetMessageSize: longint; virtual;
+   end;
+
+   TSpoolObjectCreator = class(TSpoolObject)
+      constructor Create(const SpoolConfig: TSpoolConfig; Databytes: longint; LineBuffer: integer; Originator: TIPNamePair);
+      destructor Destroy; override;
+   protected
+      FDatabytes: longint;
+      FDatabytesCounter: longint;
+      FLineBuffer: integer;
+      FOriginalMessageID: string;
+      ReceivedCount: integer;
+      ReceivingHeaders: boolean;
+      HasDate, HasMessageID: boolean;
+      WriteFail: boolean;
+      procedure AddNewHeaders;
+      procedure TransferEnvelope;
+   public
+      procedure SetDatabytes(DatabytesLimit: longint);
+      function GetOriginalMessageID: string;
+      function DeliverMessagePart(Line: string): boolean;
+      function GetErrorCode: integer;
+      function Open: boolean; override;
+      procedure Close; override;
+      procedure Discard; override;
+      property Databytes: longint read FDatabytes write SetDatabytes;
+      property OriginalMessageID: string read GetOriginalMessageID;
+   end;
+
+   TSpoolObjectReader = class(TSpoolObject)
+      constructor Create(const Name: string; const SpoolConfig: TSpoolConfig);
+   protected
+      {LockFile: THandle;}
+   public
+      function GetHeaders: TStrings;
+      function IsEOF: boolean;
+      function MakeEnvelopes(Relay: boolean): TEnvelopeArray;
+      procedure QuickSetDeliveryStatus(IsLocal: boolean; Recipient: string; Status: integer; RMsg: string);
+      procedure SetDeliveryStatus(IsLocal: boolean; Envelope: TEnvelope; AddStatus: integer = 0);
+      procedure ReadChunk(Strings: TStrings; Lines: integer);
+      function Open: boolean; override;
+      procedure Close; override;
+      procedure Discard; override;
+   end;
+
+
+   TDeliveryThread = class(TThread)
+      constructor Create(CreateSuspended: boolean; ThreadNum: integer; const SpoolConfig: TSpoolConfig; const SpoolFilters: TSpoolFilters);
+      destructor Destroy; override;
+   protected
+      FFinished: boolean;
+      FThreadNum: integer;
+      SpoolConfig: TSpoolConfig;
+      SpoolFilters: TSpoolFilters;
+      function DeliverLocalMessage(SpoolObject: TSpoolObjectReader; MailboxPtr: pointer; ReturnPath, Recipient: string): integer;
+      procedure DeliverRelayMessage(SpoolObject: TSpoolObjectReader; Relayer: TRelayer);
+      procedure HandleFailure(SpoolObject: TSpoolObjectReader; IsLocal: boolean; FailEnvelope: TEnvelope; FailedRecipient: TRecipient; AddStatus: integer; FailMsg: string);
+      procedure HandleDeliveryResults(SpoolObject: TSpoolObjectReader; IsLocal: boolean; Envelope, FailEnvelope: TEnvelope; AddStatus: integer; FailMsg: string);
+      procedure CreateBounceMessage(SourceSpoolObject: TSpoolObjectReader; FailEnvelope: TEnvelope);
+      function NeedSendReport(SpoolObject: TSpoolObject): boolean;
+      procedure Execute; override;
+   public
+      procedure CallExecute;
+      property Finished: boolean read FFinished;
+      property ThreadNum: integer read FThreadNum;
+   end;
+
+
+   TSpoolManager = class
+      constructor Create(Config: TINIFile);
+   protected
+      FDatabytes: longint;
+      FLineBuffer: integer;
+      SpoolConfig: TSpoolConfig;
+      DeliveryThreads: array of TDeliveryThread;
+   public
+      function GetNumberOfDeliveryThreads: integer;
+      function CreateSpoolObject(Originator: TIPNamePair): TSpoolObjectCreator;
+      procedure DebugDeliveryThread;
+      procedure StartDeliveryThreads;
+      procedure StopDeliveryThreads;
+      property Databytes: longint read FDatabytes;
+      property AllowExceedQuota: boolean read SpoolConfig.AllowExceedQuota;
+      property ThreadWait: integer read SpoolConfig.ThreadWait;
+      property DeliveryThreadNumber: integer read GetNumberOfDeliveryThreads;
+   end;
+
+
+const
+
+   { SpoolObjectCreator errors: }
+   SCE_NO_ERROR         =  0;
+   SCE_SIZE_EXCEEDED    =  1;
+   SCE_LOOP_DETECTED    =  2;
+   SCE_WRITE_FAIL       =  3;
+
+
+var
+
+   SpoolManager: TSpoolManager;
+
+
+implementation
+uses Mailbox;
+
+const
+
+   { Search attributes: }
+   SEARCH_ATTR = faAnyFile - faDirectory - faVolumeID - faHidden;
+
+
+constructor TSpoolObject.Create(const Name: string; const SpoolConfig: TSpoolConfig);
+begin
+   inherited Create;
+   FName:= Name;
+   FOpened:= false;
+   FEnvelope:= TEnvelope.Create;
+   FEMailProperties:= TEMailProperties.Create;
+   Self.SpoolConfig:= SpoolConfig;
+end;
+
+destructor TSpoolObject.Destroy;
+begin
+   FEMailProperties.Free;
+   FEnvelope.Free;
+   inherited Destroy;
+end;
+
+constructor TSpoolObjectCreator.Create(const SpoolConfig: TSpoolConfig; Databytes: longint; LineBuffer: integer; Originator: TIPNamePair);
+begin
+   inherited Create(GenerateRandomString(16), SpoolConfig);
+   FDatabytes:= Databytes;
+   FLineBuffer:= LineBuffer;
+   FOriginator:= Originator;
+   WriteFail:= false;
+end;
+
+destructor TSpoolObjectCreator.Destroy;
+begin
+   FOriginator.Free;
+   inherited Destroy;
+end;
+
+constructor TSpoolObjectReader.Create(const Name: string; const SpoolConfig: TSpoolConfig);
+begin
+   inherited Create(Name, SpoolConfig);
+end;
+
+constructor TDeliveryThread.Create(CreateSuspended: boolean; ThreadNum: integer; const SpoolConfig: TSpoolConfig; const SpoolFilters: TSpoolFilters);
+begin
+   FreeOnTerminate:= false;
+   FFinished:= false;
+   FThreadNum:= ThreadNum;
+   Self.SpoolConfig:= SpoolConfig;
+   Self.SpoolFilters:= SpoolFilters;
+   inherited Create(CreateSuspended);
+end;
+
+destructor TDeliveryThread.Destroy;
+begin
+   SetLength(SpoolFilters, 0);
+   inherited Destroy;
+end;
+
+constructor TSpoolManager.Create(Config: TINIFile);
+begin
+   inherited Create;
+   FDatabytes:=         Config.ReadInteger('Spool', 'Databytes', MainServerConfig.Databytes);
+   FLineBuffer:=        Config.ReadInteger('Spool', 'LineBuffer', 64);
+   SetLength(DeliveryThreads, Config.ReadInteger('Spool', 'DeliveryThreads', 8));
+   SpoolConfig.AllowExceedQuota:=         Config.ReadBool('Spool', 'AllowExceedQuota', false);
+   SpoolConfig.MaxReceivedHeaders:=       Config.ReadInteger('Spool', 'MaxReceivedHeaders', 32);
+   SpoolConfig.ThreadWait:=               Config.ReadInteger('Spool', 'ThreadWait', 250);
+   SpoolConfig.TryCount:=                 Config.ReadInteger('Spool', 'TryCount', 0);
+   SpoolConfig.TryDelay:=                 Config.ReadInteger('Spool', 'TryDelay', 2);
+   SpoolConfig.TempFailNotifyFirst:=      Config.ReadBool('Spool', 'TempFailNotifyFirst', false);
+   SpoolConfig.TempFailNotify:=           Config.ReadInteger('Spool', 'TempFailNotify', 720);
+   SpoolConfig.KeepProcessedEnvelopes:=   Config.ReadBool('Spool', 'KeepProcessedEnvelopes', false);
+   SpoolConfig.KeepProcessedEMails:=      Config.ReadBool('Spool', 'KeepProcessedEMails', false);
+end;
+
+
+procedure TSpoolObject.Close;
+begin
+   MailFile.Free;
+   SpoolData.Free;
+   FOpened:= false;
+end;
+
+function TSpoolObject.IsActual(DelaySeconds: TUnixTimeStamp): boolean;
+begin
+   Result:= UnixTimeStamp(Now) >= (GetAccessTime + DelaySeconds);
+end;
+
+function TSpoolObject.IsExpired(MaxTryCount: integer; BeforeIncrement: boolean): boolean;
+begin
+   if MaxTryCount > 0 then begin
+      if BeforeIncrement then Dec(MaxTryCount);
+      Result:= GetCurrentTryCount >= MaxTryCount;
+   end
+   else
+      Result:= false;
+end;
+
+function TSpoolObject.GetAccessTime: TUnixTimeStamp;
+begin
+   Result:= SpoolData.ReadInteger('SpoolObject', 'AccessTime', 0);
+end;
+
+function TSpoolObject.GetCurrentTryCount: integer;
+begin
+   Result:= SpoolData.ReadInteger('SpoolObject', 'TryCount', 0);
+end;
+
+procedure TSpoolObject.IncrementTryCount;
+begin
+   SpoolData.WriteInteger('SpoolObject', 'TryCount', GetCurrentTryCount + 1);
+end;
+
+procedure TSpoolObject.SetAccessTime(TimeStamp: TUnixTimeStamp);
+begin
+   SpoolData.WriteInteger('SpoolObject', 'AccessTime', TimeStamp);
+end;
+
+procedure TSpoolObject.SetThreadInfo(ThreadNum: integer; ThreadOSID: TThreadID);
+begin
+   SpoolData.WriteString('SpoolObject', 'ThreadInfo', IntToStr(ThreadNum) + ',' + IntToStr(ThreadOSID));
+end;
+
+procedure TSpoolObject.Actualize;
+begin
+   IncrementTryCount;
+   SetAccessTime(UnixTimeStamp(Now));
+end;
+
+function TSpoolObject.GetMessageSize: longint;
+var SearchRec: TSearchRec;
+begin
+   if FindFirst('spool\' + FName + '.eml', SEARCH_ATTR, SearchRec) = 0 then
+      Result:= SearchRec.Size
+   else
+      Result:= 0;
+   FindClose(SearchRec);
+end;
+
+
+procedure TSpoolObjectCreator.AddNewHeaders;
+begin
+   { Add a date, if not present. }
+   if not HasDate then StringBuffer.Insert(0, 'Date: ' + EMailTimeStampCorrected(Now));
+
+   { Add Message-Id, if not present. }
+   if not HasMessageID then StringBuffer.Insert(0,
+      'Message-Id: <' + OriginalMessageID + '>');
+
+   { Add Received by... }
+   StringBuffer.Insert(0, 'Received: from ' + Originator.Name
+      + ' ([' + Originator.IP + ']) ');
+   StringBuffer.Insert(1, #9'by ' + MainServerConfig.Name + ' with SMTP (MgSMTP '
+      + MainServerConfig.VersionStr + ')');
+   StringBuffer.Insert(2, #9'id ' + Name + '; ' + EMailTimeStampCorrected(Now));
+
+   { Flush it to the file. }
+   try
+      StringBuffer.SaveToStream(MailFile);
+      StringBuffer.Clear;
+   except
+   end;
+   ReceivingHeaders:= false;
+end;
+
+procedure TSpoolObjectCreator.TransferEnvelope;
+{ Write the actual envelope structure to the data file of the spool object.
+  (That's actually an INI file.) }
+var i: integer; Recipient: TRecipient; Pref: string;
+begin
+   with SpoolData do begin
+      WriteString('SpoolObject', 'ID', Name);
+      WriteString('SpoolObject', 'Return-Path', Envelope.ReturnPath);
+      WriteString('Originator', 'Name', Originator.Name);
+      WriteString('Originator', 'IP', Originator.IP);
+      for i:= 0 to Envelope.GetNumberOfRecipients - 1 do begin
+         Recipient:= Envelope.GetRecipient(i);
+         if MailboxManager.IsLocalAddress(Recipient.Address) then Pref:= 'Local\' else Pref:= 'Relay\';
+         WriteInteger(Pref + EMailHost(Recipient.Address), EMailUserName(Recipient.Address),
+            Recipient.Data);
+      end;
+   end;
+end;
+
+procedure TSpoolObjectCreator.SetDatabytes(DatabytesLimit: longint);
+begin
+   FDatabytes:= DatabytesLimit;
+end;
+
+function TSpoolObjectCreator.GetOriginalMessageID: string;
+begin
+   if HasMessageID then
+      Result:= FOriginalMessageID
+   else
+      Result:= Name + '@' + MainServerConfig.Name;
+end;
+
+function TSpoolObjectCreator.GetErrorCode: integer;
+begin
+   if WriteFail then
+      Result:= SCE_WRITE_FAIL
+   else if (FDatabytesCounter > FDatabytes) and (FDatabytes <> 0) then
+      Result:= SCE_SIZE_EXCEEDED
+   else if ReceivedCount >= SpoolConfig.MaxReceivedHeaders then
+      Result:= SCE_LOOP_DETECTED
+   else
+      Result:= SCE_NO_ERROR;
+end;
+
+function TSpoolObjectCreator.DeliverMessagePart(Line: string): boolean;
+var Header, Value: string;
+begin
+   if Opened and (not WriteFail) then begin
+
+      { If we haven't received all the headers of the e-mail, keep checking
+        the incoming headers - we need to check for the existence of some
+        headers, and add missing headers after all headers have arrived. }
+      if ReceivingHeaders then begin
+         if Length(Line) = 0 then begin
+            { End of headers. }
+            AddNewHeaders;
+         end
+         else if pos('MESSAGE-ID:', UpperCase(Line)) = 1 then begin
+            HasMessageID:= true;
+            SplitParameters(Line, Header, Value, ':');
+            FOriginalMessageID:= CleanEMailAddress(Value);
+         end
+         else if pos('DATE:', UpperCase(Line)) = 1 then HasDate:= true
+         else if pos('RECEIVED:', UpperCase(Line)) = 1 then Inc(ReceivedCount);
+      end;
+
+      { In any way, write the received line to the buffer, unless the databytes
+        limit has been reached. }
+      if (FDatabytesCounter <= FDatabytes) or (FDatabytes = 0) then begin
+         StringBuffer.Add(Line);
+         FDatabytesCounter:= FDatabytesCounter + Length(Line) + 2;
+         { Don't flush the buffer, until all the headers received. }
+         if not ReceivingHeaders and (StringBuffer.Count >= FLineBuffer) then begin
+            try
+               StringBuffer.SaveToStream(MailFile);
+               StringBuffer.Clear;
+               Result:= true;
+            except
+               Result:= false;
+               WriteFail:= true;
+            end;
+         end
+         else Result:= true;
+      end
+      else Result:= false;
+   end
+   else Result:= false;
+end;
+
+function TSpoolObjectCreator.Open: boolean;
+begin
+   try
+      MailFile:= TFileStream.Create('spool\' + Name + '.eml', fmCreate);
+      SpoolData:= TINIFile.Create('spool\' + Name + '.tmp');
+      FOpened:= true;
+      StringBuffer:= TStringList.Create;
+      ReceivedCount:= 0;
+      ReceivingHeaders:= true;
+      HasDate:= false; HasMessageID:= false;
+      FDatabytesCounter:= 0;
+      TransferEnvelope;
+      Result:= true;
+   except
+      MailFile.Free;
+      SpoolData.Free;
+      Result:= false;
+   end;
+end;
+
+procedure TSpoolObjectCreator.Close;
+begin
+   SpoolData.WriteInteger('SpoolObject', 'Flags', EMailProperties.Flags);
+   SpoolData.WriteInteger('SpoolObject', 'TryCount', 0);
+   if ReceivingHeaders then AddNewHeaders;
+   StringBuffer.SaveToStream(MailFile);
+   inherited Close;
+   StringBuffer.Free;
+   RenameFile('spool\' + Name + '.tmp', 'spool\' + Name + '.dat');
+end;
+
+procedure TSpoolObjectCreator.Discard;
+begin
+   MailFile.Free;
+   SpoolData.Free;
+   DeleteFile('spool\' + FName + '.tmp');
+   DeleteFile('spool\' + FName + '.eml');
+   StringBuffer.Free;
+   FOpened:= false;
+end;
+
+
+function TSpoolObjectReader.Open: boolean;
+begin
+   {LockFile:= FileCreate('spool\' + FName + '.lck', fmShareExclusive);
+   if LockFile <> feInvalidHandle then begin}
+   try
+      MailFile:= TFileStream.Create('spool\' + Name + '.eml', fmOpenRead);
+      { !!! TODO: Someday it would be nice to add a working buffer... !!! }
+      { 16 KB read buffer - maybe it should be configurable. }
+      {MailFile:= TReadBufStream.Create(TFileStream.Create('spool\' + Name + '.eml', fmOpenRead), 16 * 1024);}
+      {(MailFile as TReadBufStream).SourceOwner:= true;}
+      SpoolData:= TINIFile.Create('spool\' + Name + '.dat');
+      Envelope.ReturnPath:= SpoolData.ReadString('SpoolObject', 'Return-Path', '');
+      FOriginator:= TIPNamePair.Create(SpoolData.ReadString('Originator', 'Name', ''),
+         SpoolData.ReadString('Originator', 'IP', ''));
+      FEMailProperties.Size:= GetMessageSize;
+      FEMailProperties.Flags:= SpoolData.ReadInteger('SpoolObject', 'Flags', 0);
+      FOpened:= true;
+      Result:= true;
+   except
+      MailFile.Free;
+      SpoolData.Free;
+      {FileClose(LockFile);}
+      Result:= false;
+   end;
+end;
+
+procedure TSpoolObjectReader.Close;
+begin
+   inherited Close;
+   {FileClose(LockFile);}
+   DeleteFile('spool\' + FName + '.lck');
+   FOriginator.Free;
+end;
+
+procedure TSpoolObjectReader.Discard;
+{ Discard should be called when the spool object is opened, and instead
+  of Close! }
+begin
+   MailFile.Free;
+   SpoolData.Free;
+   if SpoolConfig.KeepProcessedEnvelopes then
+      RenameFile('spool\' + FName + '.dat', 'processed\' + FName + '.dat');
+   if SpoolConfig.KeepProcessedEMails then
+      RenameFile('spool\' + FName + '.eml', 'processed\' + FName + '.eml');
+   DeleteFile('spool\' + FName + '.dat');
+   DeleteFile('spool\' + FName + '.eml');
+   {FileClose(LockFile);}
+   DeleteFile('spool\' + FName + '.lck');
+   FOriginator.Free;
+end;
+
+function TSpoolObjectReader.GetHeaders: TStrings;
+var Strings: TStrings; S: string; EH: boolean;
+begin
+   Strings:= TStringList.Create;
+   MailFile.Seek(0, soFromBeginning);
+   {repeat
+      S:= ReadLineFromStream(MailFile);
+      if S <> '' then Strings.Add(S);
+   until (S = '') or (IsEOF);}
+   EH:= false;
+   while (not IsEOF) and (not EH) do begin
+      S:= ReadLineFromStream(MailFile);
+      if S <> '' then Strings.Add(S) else EH:= true;
+   end;
+   Result:= Strings;
+end;
+
+function TSpoolObjectReader.IsEOF: boolean;
+begin
+   Result:= (not Opened) or (MailFile.Position >= MailFile.Size);
+end;
+
+procedure TSpoolObjectReader.ReadChunk(Strings: TStrings; Lines: integer);
+var S: string; C: integer;
+begin
+   C:= 0;
+   while (not IsEOF) and (C < Lines) do begin
+      S:= ReadLineFromStream(MailFile);
+      Strings.Add(S);
+      Inc(C);
+   end;
+end;
+
+function TSpoolObjectReader.MakeEnvelopes(Relay: boolean): TEnvelopeArray;
+var HostList, Usernames: TStringList; i, j, f: integer; Pref, Host: string;
+    Env: TEnvelope;
+begin
+   if Opened then begin
+      HostList:= TStringList.Create;
+      SpoolData.ReadSections(HostList);
+      i:= 0;
+      while (i < HostList.Count) do begin
+         if Relay then Pref:= 'Relay\' else Pref:= 'Local\';
+         if pos(Pref, HostList.Strings[i]) <> 1 then
+            HostList.Delete(i)
+         else
+            Inc(i);
+      end;
+      SetLength(Result, HostList.Count);
+      Usernames:= TStringList.Create;
+      f:= 0;
+      for i:= 0 to HostList.Count - 1 do begin
+         Usernames.Clear;
+         Host:= Copy(HostList.Strings[i], 7, Length(HostList.Strings[i]) - 6);
+         SpoolData.ReadSection(HostList.Strings[i], Usernames);
+         if Usernames.Count > 0 then begin
+            Env:= TEnvelope.Create;
+            Env.SetReturnPath(SpoolData.ReadString('SpoolObject', 'Return-Path', ''));
+            for j:= 0 to Usernames.Count - 1 do
+               Env.AddRecipient(Usernames.Strings[j] + '@' + Host,
+                  { It turned out we don't really need the status of the previous
+                    attempt of delivery. It only caused confusion. }
+                  {SpoolData.ReadInteger(HostList.Strings[i], Usernames.Strings[j], 0)}
+                  0);
+            Result[i-f]:= Env;
+         end
+         else begin
+            { This is a faulty envelope which has no recipients, yet its INI section exists.
+              Ignore it and go on. }
+            SpoolData.EraseSection(HostList.Strings[i]);
+            SetLength(Result, Length(Result) - 1);
+            Inc(f);
+         end;
+      end;
+      Usernames.Free;
+      HostList.Free;
+   end
+   else SetLength(Result, 0);
+end;
+
+procedure TSpoolObjectReader.QuickSetDeliveryStatus(IsLocal: boolean; Recipient: string; Status: integer; RMsg: string);
+{ "Quick" because it bypasses the TEnvelope structures cached in memory, so
+  it writes the data immediately into the spool data file. }
+var Pref, StatStr: string;
+begin
+   if IsLocal then Pref:= 'Local\' else Pref:= 'Relay\';
+   if (Status and (DS_DELIVERED or DS_PERMANENT)) <> 0 then begin
+      SpoolData.DeleteKey(Pref + EMailHost(Recipient), EMailUserName(Recipient));
+      if (Status and DS_DELIVERED) <> 0 then
+         StatStr:= 'Delivered'
+      else
+         StatStr:= 'Failed';
+      Pref:= StatStr + Pref;
+      Logger.AddLine('Object ' + Name, 'Permanent status has been set on recipient <' + Recipient + '>: '
+         + Pref + StatusToStr(Status) + ' (' + CleanEOLN(RMsg) + ')');
+   end;
+   SpoolData.WriteInteger(Pref + EMailHost(Recipient), EMailUserName(Recipient), Status);
+end;
+
+procedure TSpoolObjectReader.SetDeliveryStatus(IsLocal: boolean; Envelope: TEnvelope; AddStatus: integer = 0);
+{ It writes all data of an envelope to the spool data file. }
+var i: integer; Recipient: TRecipient;
+begin
+   for i:= 0 to Envelope.GetNumberOfRecipients - 1 do begin
+      Recipient:= Envelope.GetRecipient(i);
+      QuickSetDeliveryStatus(IsLocal, Recipient.Address, Recipient.Data or AddStatus, Recipient.RMsg);
+   end;
+end;
+
+
+function TDeliveryThread.DeliverLocalMessage(SpoolObject: TSpoolObjectReader; MailboxPtr: pointer; ReturnPath, Recipient: string): integer;
+var LockID: integer; Headers, Chunk: TStrings; R: boolean;
+    { This absolute declaration is necessary to avoid circular unit depedency
+      between Spool and Mailbox, ever since Mailbox creates spool objects
+      to implement forwarding/remailing. }
+    Mailbox: PMailbox absolute MailboxPtr;
+begin
+   { !!! TODO: Change return values to named constants !!! }
+   LockID:= Mailbox^.Lock;
+   if LockID <> 0 then begin
+      Headers:= SpoolObject.GetHeaders;
+      if Mailbox^.BeginDeliverMessage(LockID, ReturnPath, Recipient, SpoolObject.Name, SpoolObject.EMailProperties, Headers) then begin
+         Chunk:= TStringList.Create;
+         R:= true;
+         while (not SpoolObject.IsEOF) and R do begin
+            { Maybe constant "32" should be configurable? }
+            Chunk.Clear;
+            SpoolObject.ReadChunk(Chunk, 32);
+            R:= Mailbox^.DeliverMessagePart(LockID, Chunk);
+         end;
+         if R then begin
+            if Mailbox^.FinishDeliverMessage(LockID) then begin
+               Result:= 0;
+               { It's better to set in Execute. }
+               {SpoolObject.QuickSetDeliveryStatus(Recipient, DS_DELIVERED);}
+            end
+            else
+               Result:= 4;
+         end
+         else
+            Result:= 3;
+         Chunk.Free;
+      end
+      else Result:= 2;
+      Headers.Free;
+      Mailbox^.Release(LockID);
+   end
+   else
+      Result:= 1;
+end;
+
+procedure TDeliveryThread.DeliverRelayMessage(SpoolObject: TSpoolObjectReader; Relayer: TRelayer);
+var Headers, Chunk: TStrings; R: boolean;
+begin
+   if Relayer.PrepareSendMessage then begin
+      Headers:= SpoolObject.GetHeaders;
+      Chunk:= TStringList.Create;
+      { Leave a line between the headers and the body. }
+      Headers.Add('');
+      R:= Relayer.DeliverMessagePart(Headers);
+      while (not SpoolObject.IsEOF) and R do begin
+         { Maybe constant "32" should be configurable? }
+         Chunk.Clear;
+         SpoolObject.ReadChunk(Chunk, 32);
+         R:= Relayer.DeliverMessagePart(Chunk);
+      end;
+      if R then begin
+         Relayer.FinishDeliverMessage;
+      end
+      else
+         SpoolObject.SetDeliveryStatus(false, Relayer.Envelope, DS_DELAYED or DS_CONNECTIONFAIL);
+      Chunk.Free;
+      Headers.Free;
+   end;
+end;
+
+function TDeliveryThread.NeedSendReport(SpoolObject: TSpoolObject): boolean;
+{ Check if there is necessary to send a temporary failure notification,
+  according to the configuration. }
+var CurrentTryCount: integer;
+begin
+   CurrentTryCount:= SpoolObject.GetCurrentTryCount;
+   Result:= ((CurrentTryCount = 0) and SpoolConfig.TempFailNotifyFirst)
+      or ((CurrentTryCount <> 0) and ((CurrentTryCount mod SpoolConfig.TempFailNotify) = 0));
+end;
+
+procedure TDeliveryThread.HandleFailure(SpoolObject: TSpoolObjectReader; IsLocal: boolean; FailEnvelope: TEnvelope; FailedRecipient: TRecipient; AddStatus: integer; FailMsg: string);
+{ Administer failure on a single recipient. }
+begin
+   if Length(FailMsg) <> 0 then FailedRecipient.RMsg:= FailMsg;
+   FailedRecipient.Data:= FailedRecipient.Data or AddStatus;
+   {CreateBounceMessage(SpoolObject, FailedRecipient, ReturnPath, FailMsg);}
+   FailEnvelope.AddRecipient(FailedRecipient);
+   SpoolObject.QuickSetDeliveryStatus(IsLocal, FailedRecipient.Address, FailedRecipient.Data, FailedRecipient.RMsg);
+end;
+
+procedure TDeliveryThread.HandleDeliveryResults(SpoolObject: TSpoolObjectReader; IsLocal: boolean; Envelope, FailEnvelope: TEnvelope; AddStatus: integer; FailMsg: string);
+{ Administer results on multiple recipients (passed in a TEnvelope). }
+var i: integer; Recipient: TRecipient; Expired: boolean;
+begin
+   Expired:= SpoolObject.IsExpired(SpoolConfig.TryCount, true);
+   for i:= 0 to Envelope.GetNumberOfRecipients - 1 do begin
+      Recipient:= Envelope.GetRecipient(i);
+      Recipient.Data:= Recipient.Data or AddStatus;
+      if Expired then
+         Recipient.Data:= (Recipient.Data or DS_PERMANENT) and (DS_ALLFLAGS xor DS_DELAYED);
+      if (Recipient.Data and DS_DELIVERED) <> 0 then
+         SpoolObject.QuickSetDeliveryStatus(IsLocal, Recipient.Address, Recipient.Data, Recipient.RMsg)
+      else begin
+         if ((Recipient.Data and DS_PERMANENT) <> 0)
+         or (((Recipient.Data and DS_DELAYED) <> 0) and NeedSendReport(SpoolObject)) then begin
+            { In the case of failures, HandleFailure will call QuickSetDeliveryStatus. }
+            HandleFailure(SpoolObject, IsLocal, FailEnvelope, Recipient, 0, FailMsg);
+         end
+         else
+            SpoolObject.QuickSetDeliveryStatus(IsLocal, Recipient.Address, Recipient.Data, Recipient.RMsg);
+      end;
+   end;
+end;
+
+procedure TDeliveryThread.CreateBounceMessage(SourceSpoolObject: TSpoolObjectReader; FailEnvelope: TEnvelope);
+{ Generates failure notification messages, and places them into a new spool
+  object to queue them for delivery. }
+var BounceSpoolObject: TSpoolObjectCreator; Headers, BounceMessage: TStrings; i: integer;
+    FailedRecipient: TRecipient;
+begin
+   { Don't do anything, if we don't have a return-path. }
+   if (FailEnvelope.ReturnPath <> '') and (FailEnvelope.GetNumberOfRecipients <> 0) then begin
+      BounceSpoolObject:= TSpoolObjectCreator.Create(SpoolConfig, 1024 * 1024, 32, TIPNamePair.Create('localhost', '127.0.0.1'));
+      BounceSpoolObject.Envelope.SetReturnPath('');
+      BounceSpoolObject.Envelope.AddRecipient(FailEnvelope.ReturnPath);
+      if BounceSpoolObject.Open then begin
+         Headers:= SourceSpoolObject.GetHeaders;
+
+         if FailEnvelope.GetNumberOfRecipients = 1 then
+            BounceMessage:= GenerateBounceMessage(FailEnvelope.GetRecipient(0), Headers, FailEnvelope.ReturnPath)
+         else
+            BounceMessage:= GenerateBounceMessage(FailEnvelope, Headers);
+
+         for i:= 0 to BounceMessage.Count - 1 do
+            BounceSpoolObject.DeliverMessagePart(BounceMessage.Strings[i]);
+
+         BounceSpoolObject.Close;
+
+         for i:= 0 to FailEnvelope.GetNumberOfRecipients - 1 do begin
+            FailedRecipient:= FailEnvelope.GetRecipient(i);
+            Logger.AddLine('Spool', 'Bounce message created in ' + BounceSpoolObject.Name
+               + ' for object ' + SourceSpoolObject.Name
+               + ' for address <' + FailEnvelope.ReturnPath
+               + '>; concerning recipient <' + FailedRecipient.Address
+               + '>; reported status: ' + StatusToStr(FailedRecipient.Data) + ' (' + CleanEOLN(FailedRecipient.RMsg) + ')');
+         end;
+
+         BounceMessage.Free;
+         Headers.Free;
+      end;
+      BounceSpoolObject.Free;
+   end;
+end;
+
+procedure TDeliveryThread.Execute;
+{ This is a very important thread, because this delivers e-mails to local
+  mailboxes and to remote servers. }
+var SearchRec: TSearchRec; SR: longint; SpoolObject: TSpoolObjectReader;
+    Found: boolean; Envelopes: TEnvelopeArray;
+    CurrEnv, FailEnv: TEnvelope; CurrRec: TRecipient;
+    Mailbox: PMailbox; Relayer: TRelayer;
+    NumOfEnvelopes: integer;
+    a, i, j, r: integer;
+begin
+   while not Terminated do begin
+      for a:= 0 to Length(SpoolFilters) - 1 do begin
+         if FindFirst('spool\' + SpoolFilters[a] + '*.dat', SEARCH_ATTR, SearchRec) = 0 then begin
+            repeat
+               Found:= false; SR:= 0;
+               { Try to find a spool object that's not busy, and also actual. }
+               repeat
+                  SpoolObject:= TSpoolObjectReader.Create(Copy(SearchRec.Name, 1, Length(SearchRec.Name) - 4), SpoolConfig);
+                  if not SpoolObject.Open then begin
+                     SpoolObject.Free;
+                     SR:= FindNext(SearchRec);
+                  end
+                  else if not SpoolObject.IsActual(SpoolConfig.TryDelay * 60) then begin
+                     SpoolObject.Close;
+                     SpoolObject.Free;
+                     SR:= FindNext(SearchRec);
+                  end
+                  else Found:= true;
+               until Found or (SR <> 0);
+               if Found then begin
+                  NumOfEnvelopes:= -1;
+
+                  FailEnv:= TEnvelope.Create;
+                  FailEnv.ReturnPath:= SpoolObject.Envelope.ReturnPath;
+
+                  { Check local addresses first. }
+                  Envelopes:= SpoolObject.MakeEnvelopes(false);
+                  NumOfEnvelopes:= Length(Envelopes);
+                  for i:= 0 to Length(Envelopes) - 1 do begin
+                     CurrEnv:= Envelopes[i];
+                     for j:= 0 to CurrEnv.GetNumberOfRecipients - 1 do begin
+                        CurrRec:= CurrEnv.GetRecipient(j);
+                        Mailbox:= MailboxManager.GetMailbox(EMailUserName(CurrRec.Address), EMailHost(CurrRec.Address));
+                        if Mailbox <> nil then begin
+                           if SpoolConfig.AllowExceedQuota or Mailbox^.CheckQuota(SpoolObject.GetMessageSize) then begin
+                              r:= DeliverLocalMessage(SpoolObject, Mailbox, CurrEnv.ReturnPath, CurrRec.Address);
+                              if r > 1 then
+                                 HandleFailure(SpoolObject, true, FailEnv, CurrRec, DS_PERMANENT or DS_INTERNALFAIL,
+                                    DSMSG_INTERNALFAIL + 'DeliverLocalMessage = ' + IntToStr(r))
+                              else if r = 0 then
+                                 SpoolObject.QuickSetDeliveryStatus(true, CurrRec.Address, DS_DELIVERED, CurrRec.RMsg)
+                              else
+                                 SpoolObject.QuickSetDeliveryStatus(true, CurrRec.Address, r, CurrRec.RMsg);
+                           end
+                           else
+                              HandleFailure(SpoolObject, true, FailEnv, CurrRec, DS_PERMANENT, DSMSG_QUOTAEXCEEDED);
+                        end
+                        else
+                           HandleFailure(SpoolObject, true, FailEnv, CurrRec, DS_PERMANENT, DSMSG_MAILBOXNOTEXISTS);
+                     end;
+                     { Free envelope. }
+                     CurrEnv.Free;
+                  end;
+
+                  { Check relay addresses as well. }
+                  SetLength(Envelopes, 0);
+                  Envelopes:= RelayManager.OrganizeEnvelopes(SpoolObject.MakeEnvelopes(true));
+                  NumOfEnvelopes:= NumOfEnvelopes + Length(Envelopes);
+                  for i:= 0 to Length(Envelopes) - 1 do begin
+                     CurrEnv:= Envelopes[i];
+                     Relayer:= RelayManager.CreateRelayer(CurrEnv, SpoolObject.EMailProperties);
+                     if Relayer.OpenConnection then begin
+                        if Relayer.Greet then
+                           if Relayer.SendEnvelope then
+                              DeliverRelayMessage(SpoolObject, Relayer);
+                        Relayer.CloseConnection;
+                        Relayer.Free;
+                        AssignDeliveryStatusToSMTPCodes(CurrEnv);
+                        HandleDeliveryResults(SpoolObject, false, CurrEnv, FailEnv, 0, '');
+                     end
+                     else begin
+                        HandleDeliveryResults(SpoolObject, false, CurrEnv, FailEnv, DS_DELAYED or DS_CONNECTIONFAIL, DSMSG_CONNECTIONFAIL + Relayer.RelayServerName);
+                     end;
+                     { Free envelope. }
+                     CurrEnv.Free;
+                  end;
+
+                  { Create a bounce message if necessary. }
+                  CreateBounceMessage(SpoolObject, FailEnv);
+                  FailEnv.Free;
+
+                  SpoolObject.Actualize;
+                  SpoolObject.SetThreadInfo(ThreadNum, ThreadID);
+
+                  if (NumOfEnvelopes <> 0) and (not SpoolObject.IsExpired(SpoolConfig.TryCount, false)) then
+                     SpoolObject.Close
+                  else begin
+                     SpoolObject.Discard;
+                     Logger.AddLine('Spool', 'Object ' + SpoolObject.Name + ' has been processed.');
+                  end;
+                  SpoolObject.Free;
+               end;
+            until (SR <> 0) or (FindNext(SearchRec) <> 0);
+         end;
+         FindClose(SearchRec);
+      end;
+      Sleep(SpoolConfig.ThreadWait);
+   end;
+   FFinished:= true;
+end;
+
+procedure TDeliveryThread.CallExecute;
+begin
+   Execute;
+end;
+
+
+function TSpoolManager.GetNumberOfDeliveryThreads: integer;
+begin
+   Result:= Length(DeliveryThreads);
+end;
+
+function TSpoolManager.CreateSpoolObject(Originator: TIPNamePair): TSpoolObjectCreator;
+begin
+   Result:= TSpoolObjectCreator.Create(SpoolConfig, FDatabytes, FLineBuffer, Originator);
+end;
+
+procedure TSpoolManager.DebugDeliveryThread;
+{ You only need it when you need to trace the delivery thread.
+  Normally it never gets called. Write a separate program to use it.
+  (I've presented one, test_threaddebug.pas.) }
+var i: integer; Delivery: TDeliveryThread; SpoolFilters: TSpoolFilters;
+    Alphabet: string;
+begin
+   Alphabet:= GetAlphabetStr;
+   SetLength(SpoolFilters, Length(Alphabet));
+   for i:= 1 to Length(Alphabet) do SpoolFilters[i - 1]:= Alphabet[i];
+
+   Delivery:= TDeliveryThread.Create(true, 0, SpoolConfig, SpoolFilters);
+   Delivery.CallExecute;
+   Delivery.Free;
+end;
+
+procedure TSpoolManager.StartDeliveryThreads;
+var i, j, n, x: integer; ThreadFilters: array of TSpoolFilters; Alphabet: string;
+begin
+   n:= Length(DeliveryThreads);
+   SetLength(ThreadFilters, n);
+   Alphabet:= GetAlphabetStr;
+
+   if n > 0 then begin
+      for i:= 1 to Length(Alphabet) do begin
+         x:= (i - 1) mod n;
+         j:= Length(ThreadFilters[x]);
+         SetLength(ThreadFilters[x], j + 1);
+         ThreadFilters[x][j]:= Alphabet[i];
+      end;
+   end;
+
+   Logger.AddStdLine('Spool', 'Starting ' + IntToStr(n) + ' delivery threads...');
+   for i:= 0 to n - 1 do begin
+      DeliveryThreads[i]:= TDeliveryThread.Create(false, i, SpoolConfig, ThreadFilters[i]);
+      Sleep(25);
+   end;
+   Logger.AddStdLine('Spool', 'Delivery threads have been started.');
+end;
+
+procedure TSpoolManager.StopDeliveryThreads;
+{ Signals delivery threads to end, and waits for them to quit. }
+var i, Counter: integer; AllFinished: boolean;
+begin
+   Logger.AddStdLine('Spool', 'Stopping delivery threads...');
+   for i:= 0 to Length(DeliveryThreads) - 1 do
+      DeliveryThreads[i].Terminate;
+
+   Counter:= 0;
+
+   repeat
+      Sleep(50);
+      AllFinished:= true;
+      for i:= 0 to Length(DeliveryThreads) - 1 do
+         if not DeliveryThreads[i].Finished then AllFinished:= false;
+      Inc(Counter);
+   until AllFinished or (Counter >= 600);
+
+   { Threads those didn't finish on time will be terminated. }
+   for i:= 0 to Length(DeliveryThreads) - 1 do begin
+      if not DeliveryThreads[i].Finished then begin
+         Logger.AddStdLine('Spool', 'WARNING: Delivery thread #' + IntToStr(i) + ' hasn''t finished properly on time!');
+         //DeliveryThreads[i].Suspend;    { Suspend has been deprecated, but we'll kill the thread regardless. }
+         KillThread(DeliveryThreads[i].Handle);
+      end;
+      DeliveryThreads[i].Free;
+   end;
+   Logger.AddStdLine('Spool', 'Delivery threads have been stopped.');
+end;
+
+
+end.
diff --git a/changelog.txt b/changelog.txt
new file mode 100644 (file)
index 0000000..556cd2e
--- /dev/null
@@ -0,0 +1,73 @@
+MgSMTP v0.9r - 2012.01.15.
+--------------------------
+- MgSMTP now supports recipient address rewriting, forwarding and remailing. These features can be enabled on local mailboxes.
+- The "Message-ID" headers of incoming e-mails are now logged.
+- If multiple recipients fail on a single e-mail, only one DSN is sent which lists all failed recipients. (Previously, individual DSNs were sent concerning each failed recipient.)
+- The timezone offset is now added to "Received" headers as well.
+- An "X-Original-To" header is added to e-mails upon being delivered to mailboxes. This records the recipient address in its original form, while "Delivered-To" only shows the primary name of the mailbox. (If the mailbox was addressed by an alias, the two headers will differ.)
+
+
+MgSMTP v0.9q - 2011.10.03.
+--------------------------
+- Support for FCrDNS verification of connecting hosts. There are 4 strictness levels that can be set, on how to treat non-compliant hosts.
+- Support for domain-specific mailboxes, which enables a limited form of virtual hosting.
+- Like GET HTTP requests, now HEAD and POST requests also trigger a disconnection.
+- The "TimeCorrection" key is replaced with "TimeOffset", which allows to set timezones those aren't offset by a whole number of hours.
+- Fixed a bug in the spool's iterator loop which prevented some spool objects to be touched at all when a large number of temporarily undeliverable e-mails were queued.
+- The numbers and IDs of delivery threads are now recorded in the spool .DAT files as "ThreadInfo". This serves debug purposes.
+- A "Return-Path" header is added to e-mails upon being delivered to local mailboxes.
+
+
+MgSMTP v0.9p - 2011.07.17.
+--------------------------
+- Reading from a socket times out after 5 minutes. It helps to prune down dead connections, which the process hasn't been notified of for some reason. It increases the server's reliability, because delivery threads won't stuck because of a dead connection.
+- Status codes are now logged in more human-readable format in the SMTP log. SMTP reply codes are now clearly viewable (previously they were incorporated in the internal status code, it required some binary math to extract them).
+- MgSMTP now logs the reply messages of remote servers.
+- MgSMTP now accepts SMTP commands in lowercase (and mixed-case) as well, as the RFC requires it anyway.
+- The function that handled DNS MX queries had a serious bug that came forward when the domain name to resolve was a CNAME. Now it is corrected.
+- Added the "NoRelayTo" value, which is the exact opposite of the "RelayTo" list: even hosts with RELAY right aren't allowed to relay to a domain that is listed in "NoRelayTo".
+- MgSMTP now doesn't remember the status codes of previous delivery attempts.
+
+
+MgSMTP v0.9o - 2011.04.07.
+--------------------------
+- Added support for strange AUTH LOGIN attempts, when the client puts the Base64-encoded username in one line with the "AUTH LOGIN" command. This is added to support the command-line "email" client of CleanCode.org.
+- Made efforts to ensure WINE compatibility. Now you are able to run MgSMTP under Linux, if you really want to. Note that it's a bit of tricky to get a Windows service running with WINE, but it's possible.
+- Added the "TimeCorrection" key to enable setting the timezone of the SMTP server. It only affects the "Date" headers appended by MgSMTP, they'll have corrections like "+0200". "Date" headers are used by e-mail clients to show the correct send time of e-mails. Note however that MgSMTP only adds a "Date" header to an e-mail if it doesn't already have one upon receipt.
+- MgSMTP now disconnects HTTP agents with an error message. This is added against abuse.
+- Made efforts to drastically reduce the number of wasted Windows handles that could be observable after prolonged run of MgSMTP.
+
+
+MgSMTP v0.9n - 2010.12.20.
+--------------------------
+- Added support for alternate port numbers. Use the "ListenPort" value to specify a list of port numbers to listen on, and set the "Port" value for a relay route to specify an alternate port for relaying.
+- Added support for the "PRESHUTDOWN" notification introduced in Windows Vista. Backward compatibility with older Windows versions was preserved.
+- EHLO is now always sent before AUTH to relay servers (if AUTH is necessary at all).
+
+
+MgSMTP v0.9m - 2010.12.01.
+--------------------------
+- Introduced a feature I call "careful threading". Now all threads will work on messages those name starts with specific letters, thus they will never interfere each other. I implemented this feature, because the previously used lockfile technique wasn't safe enough with low "ThreadWait" values. Note, this new technique limits the possible number of delivery threads to 36.
+- Enforced the effect of "Policies\Users" (key!) setting to control user authentication. If the option is disabled, MgSMTP will ignore the "Policies\Users" section in the config file. Moreover, if there are no users listed in the config file, user authentication will be disabled anyway. If user authentication is completely disabled, MgSMTP won't even report the AUTH SMTP extension in responses to EHLO commands.
+- Added protection against mail relay loops. MgSMTP now counts the "Received" headers of e-mails to detect messages those are trapped in a mail relay loop. See the "MaxReceivedHeaders" setting.
+- The "Relay\Routes" table is now interpreted case-insensitively.
+
+
+MgSMTP v0.9l - 2010.11.22.
+--------------------------
+- Added a short help text to the executable (issued by the "/?" parameter).
+- Added full support for the SIZE SMTP extension. (Check databytes limit when a client sends a MAIL command with SIZE parameter; check quota on RCPT command; send MAIL SIZE parameter to other servers those support.)
+- Added better support for 8BITMIME. (Note when received a message with 8BITMIME, then relay with 8BITMIME declaration to other servers. But still attempt to relay 8BITMIME messages in 8 bits to other servers, without any conversion, and it is considered illegal.)
+
+
+MgSMTP v0.9k - 2010.11.20.
+--------------------------
+- Added a configuration option, "MaxAuthAttempts" to limit the number of AUTH attempts a client may make in one session.
+- The server now reports 8BITMIME support, even though it won't translate 8bit e-mails to 7bit for servers those don't support 8BITMIME. MgSMTP always relays e-mails as it receives them.
+- Added support for the PIPELINING extension. MgSMTP pipelines RCPT commands if the other server supports pipelining.
+
+
+MgSMTP v0.9j - 2010.11.18.
+--------------------------
+- FIXED SERIOUS BUG: Upon delivery to multiple addresses through a single remote SMTP server, if the multiple RCPT commands had mixed results (some successes and some fails), MgSMTP incorrectly administered all addresses as succeded, if the DATA transaction was also successful.
+- A minor grammar mistake has been fixed.
\ No newline at end of file
diff --git a/comparewild.pas b/comparewild.pas
new file mode 100644 (file)
index 0000000..c88f319
--- /dev/null
@@ -0,0 +1,126 @@
+{$MODE DELPHI}
+unit comparewild;
+{Copyright (C) 2007 Thomas Kelsey; 2010 MegaBrutal
+
+This program is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.}
+
+{
+   COMMENTS FOR MY MODIFICATION TO THE ORIGINAL CODE:
+   This unit is originally written by Thomas Kelsey to match wildcards
+   for filenames in Borland Delphi. I've adapted it to match internet
+   hostnames and IPs instead, and I've added the $MODE DELPHI directive
+   to make the unit usable in Free Pascal.
+   Basically, the only difference between matching filenames and
+   hostnames is that '*' should match '.' as well, while in the case of
+   filenames, it shouldn't.
+   (MegaBrutal, 2010)
+}
+
+// KNOWN BUGS: accepts wildcards in target string
+interface
+
+function WildComp(const mask: String; const target: String): Boolean;
+
+{function Test: Boolean;}
+
+implementation
+
+function WildComp(const mask: String; const target: String): Boolean;
+
+    // '*' matches greedy & ungreedy
+    // simple recursive descent parser - not fast but easy to understand
+    function WComp(const maskI: Integer; const targetI: Integer): Boolean;
+    begin
+
+        if maskI > Length(mask) then begin
+            Result := targetI = Length(target) + 1;
+            Exit;
+        end;
+        if targetI > Length(target) then begin
+            // unread chars in filter or would have read '#0'
+            Result := False;
+            Exit;
+        end;
+
+        case mask[maskI] of
+            '*':
+                // CHANGED BY MegaBrutal
+                // If I compare hostnames, '*' should match '.' as well.
+                Result := WComp(succ(maskI), Succ(targetI)) or WComp(maskI, Succ(targetI));
+
+            '?':
+                // ? doesnt match '.'
+                if target[targetI] <> '.' then
+                    Result := WComp(succ(maskI), Succ(targetI))
+                else
+                    Result := False;
+
+            else     // includes '.' which only matches itself
+                if mask[maskI] = target[targetI] then
+                    Result := WComp(succ(maskI), Succ(targetI))
+                else
+                    Result := False;
+        end;// case
+
+    end;
+
+begin
+    WildComp := WComp(1, 1);
+end;
+
+
+{ This test function should always return true, I modified it to test
+  if the function fulfills my needs.
+  I commented it out, because I don't really need it in my project,
+  but I left it here for others to inspect. (MegaBrutal) }
+
+{
+function Test: Boolean;
+begin
+Result := WildComp('a*.bmp', 'auto.bmp');
+    Result := Result and (not WildComp('a*x.bmp', 'auto.bmp'));
+    Result := Result and WildComp('a*o.bmp', 'auto.bmp');
+    Result := Result and (not WildComp('a*tu.bmp', 'auto.bmp'));
+    Result := Result and WildComp('a*o.b*p', 'auto.bmp') and (WildComp('a*to.*', 'auto.bmp'));
+    Result := Result and WildComp('a**o.b*p', 'auto.bmp');
+    Result := Result and (WildComp('*ut*.**', 'auto.bmp'));
+    Result := Result and (WildComp('*ut*.*.*', 'auto.bmp.splack'));
+    Result := Result and WildComp('**.**', 'auto.bmp') and (WildComp('*ut*', 'auto.bmp'));
+    // '*' = at least 1 char
+    Result := Result and not WildComp('**', 'a');
+    // shows '.' -> '*'
+    Result := Result and (WildComp('*ut*.*', 'auto.bmp.foo'));
+    // shows un-greedy match
+    Result := Result and (WildComp('*ut', 'autout'));
+
+    Result := Result and (not WildComp('auto?', 'auto'));
+    Result := Result and not WildComp('?uto', 'uto');
+    Result := Result and WildComp('aut?', 'auto');
+    Result := Result and WildComp('???', 'uto');
+    Result := Result and not WildComp('????', 'uto');
+    Result := Result and not WildComp('??', 'uto');
+
+    // ADDED BY MegaBrutal
+    // We should still match '.' for '*':
+    Result := Result and WildComp('*.t-online.hu', 'dslwhatever.pool.t-online.hu');
+    Result := Result and WildComp('192.168.*', '192.168.1.25');
+    // But we shouldn't match '.' for '?':
+    Result := Result and (not WildComp('whatever?net', 'whatever.net'));
+
+end;
+}
+
+
+end.
diff --git a/lgpl-2.0.txt b/lgpl-2.0.txt
new file mode 100644 (file)
index 0000000..5bc8fb2
--- /dev/null
@@ -0,0 +1,481 @@
+                  GNU LIBRARY GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1991 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the library GPL.  It is
+ numbered 2 because it goes with version 2 of the ordinary GPL.]
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Library General Public License, applies to some
+specially designated Free Software Foundation software, and to any
+other libraries whose authors decide to use it.  You can use it for
+your libraries, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if
+you distribute copies of the library, or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link a program with the library, you must provide
+complete object files to the recipients so that they can relink them
+with the library, after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  Our method of protecting your rights has two steps: (1) copyright
+the library, and (2) offer you this license which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  Also, for each distributor's protection, we want to make certain
+that everyone understands that there is no warranty for this free
+library.  If the library is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original
+version, so that any problems introduced by others will not reflect on
+the original authors' reputations.
+\f
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that companies distributing free
+software will individually obtain patent licenses, thus in effect
+transforming the program into proprietary software.  To prevent this,
+we have made it clear that any patent must be licensed for everyone's
+free use or not licensed at all.
+
+  Most GNU software, including some libraries, is covered by the ordinary
+GNU General Public License, which was designed for utility programs.  This
+license, the GNU Library General Public License, applies to certain
+designated libraries.  This license is quite different from the ordinary
+one; be sure to read it in full, and don't assume that anything in it is
+the same as in the ordinary license.
+
+  The reason we have a separate public license for some libraries is that
+they blur the distinction we usually make between modifying or adding to a
+program and simply using it.  Linking a program with a library, without
+changing the library, is in some sense simply using the library, and is
+analogous to running a utility program or application program.  However, in
+a textual and legal sense, the linked executable is a combined work, a
+derivative of the original library, and the ordinary General Public License
+treats it as such.
+
+  Because of this blurred distinction, using the ordinary General
+Public License for libraries did not effectively promote software
+sharing, because most developers did not use the libraries.  We
+concluded that weaker conditions might promote sharing better.
+
+  However, unrestricted linking of non-free programs would deprive the
+users of those programs of all benefit from the free status of the
+libraries themselves.  This Library General Public License is intended to
+permit developers of non-free programs to use free libraries, while
+preserving your freedom as a user of such programs to change the free
+libraries that are incorporated in them.  (We have not seen how to achieve
+this as regards changes in header files, but we have achieved it as regards
+changes in the actual functions of the Library.)  The hope is that this
+will lead to faster development of free libraries.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, while the latter only
+works together with the library.
+
+  Note that it is possible for a library to be covered by the ordinary
+General Public License rather than by this special one.
+\f
+                  GNU LIBRARY GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library which
+contains a notice placed by the copyright holder or other authorized
+party saying it may be distributed under the terms of this Library
+General Public License (also called "this License").  Each licensee is
+addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+  
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+\f
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+\f
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+\f
+  6. As an exception to the Sections above, you may also compile or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    c) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    d) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the source code distributed need not include anything that is normally
+distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+\f
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+\f
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Library General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+\f
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+                            NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+\f
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Library General Public
+    License as published by the Free Software Foundation; either
+    version 2 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Library General Public License for more details.
+
+    You should have received a copy of the GNU Library General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/license.txt b/license.txt
new file mode 100644 (file)
index 0000000..dba13ed
--- /dev/null
@@ -0,0 +1,661 @@
+                    GNU AFFERO GENERAL PUBLIC LICENSE
+                       Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+  A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate.  Many developers of free software are heartened and
+encouraged by the resulting cooperation.  However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+  The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community.  It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server.  Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+  An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals.  This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU Affero General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Remote Network Interaction; Use with the GNU General Public License.
+
+  Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software.  This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time.  Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source.  For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code.  There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<http://www.gnu.org/licenses/>.
diff --git a/license_gpl-2.0.txt b/license_gpl-2.0.txt
new file mode 100644 (file)
index 0000000..d159169
--- /dev/null
@@ -0,0 +1,339 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/license_lesser.txt b/license_lesser.txt
new file mode 100644 (file)
index 0000000..65c5ca8
--- /dev/null
@@ -0,0 +1,165 @@
+                   GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+  Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/mgsmtp_server_example.ini b/mgsmtp_server_example.ini
new file mode 100644 (file)
index 0000000..bee29de
--- /dev/null
@@ -0,0 +1,734 @@
+; MegaBrutal's SMTP Server (MgSMTP)
+; Copyright (C) 2010-2011 MegaBrutal
+
+; This is an example configuration file for MgSMTP.
+; You may inspect it to learn about the configuration options of MgSMTP, and (if
+; you find it convenient) you may copy and edit it to make your own configuration
+; file.
+
+; You should read readme.txt prior reading this file.
+
+; The "Server" section contains some basic, general settings for your server.
+
+[Server]
+
+; The "Name" key specifies the hostname as MgSMTP will identify itself. The server
+; will report it in greetings, in HELO commands sent to other servers, in failure
+; notices, and it'll accept e-mail addresses with the given hostname as local.
+; It can be a virtual hostname (such as a No-IP domain pointed to your IP), it's
+; not required to be the server's forward-confirmed reverse DNS. In any case,
+; however, this hostname must be resolvable to your IP address. Moreover, you
+; SHOULD specify your server's FCrDNS, if you can, and your server MUST have a
+; valid FCrDNS in any case (even if it's not the one supplied as "Server\Name").
+
+; If you have a dynamic IP address, unfortunately you can't use your reverse hostname
+; as your server's name because it changes too often, and your server name MUST
+; always resolve to your actual IP, as mentioned above.
+
+; The "Alias" key is optional. You may use it to specify other destination domains for
+; your mail server.
+
+; Here's one example:
+
+;Name = example.org
+;Alias = example.com,example.net
+
+; According to the example above, this server will accept e-mails with recipient
+; addresses such as foobar@example.org, foobar@example.com, and foobar@example.net
+; as ones destinated to this server. All of the listed addresses will address the same
+; mailbox: "foobar" - unless domain-specific mailbox support is enabled (see below).
+
+; Another example:
+
+;Name = mx.mycutedomain.com
+;Alias = mycutedomain.com
+
+; For example, you'd like to run a mail service for mycutedomain.com on the host named
+; mx.mycutedomain.com. You need to add mx.mycutedomain.com as an MX record for
+; mycutedomain.com.
+
+Name = 
+
+
+; "ListenPort" is a list of port numbers MgSMTP will listen on. More than one port
+; numbers may be given, separated by commas. The standard (IANA-assigned) port for
+; SMTP service is 25.
+
+ListenPort = 25
+
+
+; Use "TimeOffset" to set the timezone of your SMTP server. It is used to append
+; corrections to "Date" headers. Note that MgSMTP only appends a "Date" header to an
+; e-mail if it receives it without one present.
+; Most e-mail clients use the correction to show the e-mail's send time correctly.
+; Such corrections consist of 4 decimal digits, with the 2 more significant ones
+; denoting the hours and the 2 least significant ones denoting the minutes of offset.
+; This field is interpreted as an integer, so "200" and "+0200" do the same.
+; For example, if the server's clock runs in the timezone GMT+2:00, set "+0200" for
+; "TimeOffset". Negative numbers are also accepted, of course.
+; The "TimeCorrection" key previously used for this purpose is now deprecated, but still
+; interpreted if specified. If both "TimeCorrection" and "TimeOffset" keys are present,
+; then "TimeCorrection" will be ignored.
+
+TimeOffset = +0000
+
+
+; The "Policies" switch enables or disables the enforcement of policy settings for
+; your server. If this option is disabled, MgSMTP will ignore any settings
+; specified under the "Policies" section, such as rule tables for hosts and users.
+; All hosts will get all rights by default. I really don't recommend to disable
+; "Policies", if your server is accessible from any untrusted network. If you
+; let your server to operate on the Internet with this option disabled, your mail
+; system will act as an open mail relay. Open relays are often used to broadcast SPAM,
+; thus they often get blacklisted!
+; Still, there is an option to disable policies, because it may be convenient for
+; testing and use on trusted networks.
+
+Policies = On
+
+
+; The "Mailbox" switch enables or disables local mailboxes on your mail server.
+; If disabled, your server will never accept any e-mails those are addressed for
+; this server.
+
+Mailbox = On
+
+
+; The "Relay" switch enables or disables the server's willingness to relay e-mails.
+; If you disable this option, your server in no circumstances will accept any
+; e-mails those need to be relayed. Even from hosts those are set to have the right
+; to relay by the policy settings.
+; Note, previously queued e-mails will still be relayed; and DSNs to be relayed may
+; still be generated internally.
+
+Relay = Off
+
+
+; The "Log" switch enables or disables logging.
+
+Log = On
+
+
+; The "Policies" section defines the policy settings for the server. Note, if you
+; have disabled the "Policies" switch above, the settings below will be ignored.
+
+[Policies]
+
+; If "ReqHELO" is enabled, the server won't process any commands sent by the client
+; (except "AUTH") until it identifies itself with the "HELO" or "EHLO" command, as
+; the RFC for SMTP recommends it. Since MgSMTP will only use the reverse DNS of a
+; host (and its IP) to determine its rights, I don't think it's necessary to require
+; a HELO. However, I've never seen any mail delivery systems or e-mail clients those
+; don't start conversations with other systems with a HELO, so a client that doesn't
+; do so might be considered suspicious.
+
+ReqHELO = Off
+
+
+; If "HideVersion" is enabled, MgSMTP will not reveal its version number in its
+; initial greeting. Though it will still report the fact that it's an "MgSMTP"
+; instance, however; and it will still reveal its version number in Delivery Status
+; Notification e-mails and in "Received" headers.
+
+HideVersion = Off
+
+
+; "Users" enables or disables the user authentication feature. If disabled, the
+; software ignores the "Policies\Users" section (see below) completely, and won't
+; even report the AUTH feature in responses to EHLO commands.
+; If you enable "Users" here, but don't define user accounts below, that will have
+; the very same effect as you set "Off" here.
+
+Users = Off
+
+
+; To prevent abuse, you can limit the number of AUTH attempts a client may make in
+; one session. After "MaxAuthAttempts" number of failed AUTH negotiations, the client
+; will get disconnected. Supply "0" if you don't want to limit AUTH attempts.
+; Though the client is free to connect again to make further attempts, but at least it
+; will stop some of those malicious bots.
+
+MaxAuthAttempts = 4
+
+
+; The "FCrDNSPolicy" key tells MgSMTP whether to verify if the reverse hostnames of
+; connecting clients are forward-confirmed, and if so, how to handle the result.
+; Forward-confirmed reverse DNS means, if you take an IP and resolve its reverse name,
+; and then you resolve the IP for the resulting hostname, you get the original IP. This
+; is the expected situation. But technically it is possible that the results of reverse
+; and forward lookups are inconsistent. Basically, if you own a static IP, you may set
+; any reverse hostname (PTR record) for it. Even obscure ones like "i.am.the.king" and
+; stuff like that - actually it can be any string that the DNS protocol permits, it may
+; not even forward resolve at all.
+
+; The following values are permitted for "FCrDNSPolicy":
+; Naive      - don't verify reverse hostnames at all
+; Aware      - verify reverse hostnames, re-evaluate host rights by IP only if
+;              an inconsistency is found
+; Mean       - verify reverse hostnames, re-evaluate host rights by IP only if
+;              an inconsistency is found, but disallow to acquire additional rights
+; Strict     - verify reverse hostnames, disconnect the client if an inconsistency
+;              is found
+
+; On LAN, you can go with "Naive". For DMZ hosts, the minimum you should set is "Aware".
+; The difference between "Aware" and "Mean" is that the latter won't let the host to
+; acquire rights those it wouldn't get if it had a forward-confirmed reverse hostname.
+; For example, you banned a host by its hostname, but you didn't ban it by its IP,
+; and the FCrDNS test fails on it. Then "Aware" would let the host in, because after
+; all it will completely ignore the fact that you've banned the host by hostname, since
+; that reverse name is invalid anyway. But "Mean" would take into account that you've
+; banned the host by hostname, and it would see that the host would actually get more
+; rights after the re-evaluation by IP only, and so it wouldn't let the host to get
+; those additional rights.
+; Use "Strict" if you wouldn't like to accept e-mails from hosts with invalid reverse
+; hostnames at all. In this case, such hosts will get disconnected with a permanent
+; failure SMTP reply code (554). Sadly there are legitimate mail servers out there
+; those have invalid reverse hostnames, thus banning all of them can be too radical,
+; you may lose legitimate e-mails by doing so. If you didn't understand anything of
+; this section, read back later.
+
+; Again, now in layman's terms: THIS IS A SECURITY MEASURE!
+; If you use "Naive", you allow hosts to trick your server to believe they are
+; connecting from elsewhere.
+; A drastical example is that you set "localhost = AllowStore,AllowRelay" in the
+; "Policies\Hosts" table below, thinking that this line only gives RELAY right to
+; "127.0.0.1". Then a malicious bot connects your SMTP server which happens to have
+; "localhost" as its reverse hostname. If you don't verify the validity of its reverse
+; DNS, then MgSMTP will grant it the RELAY right. If you verify its reverse DNS (i.e.
+; you have any other setting than "Naive"), you don't let yourself tricked.
+
+FCrDNSPolicy = Aware
+
+
+; The "Policies\Hosts" section defines a list of rights assigned to specific hosts.
+; (Actually, it's an ACL.)
+; You may use wildcards in the hostnames, and you may also specify IPs. When a
+; client connects, MgSMTP will resolve its reverse DNS, and match that hostname and
+; the client's IP with the items on the list one by one. If it finds a line that
+; matches for either the hostname or the IP, the rights specified in that line will
+; be assigned to the connection.
+
+; The assigned rights are specified by lists of the following strings:
+; AllowStore - the host will be permitted to send messages destined to this server
+; DenyStore  - the host will not be allowed to send messages to any local mailboxes
+; AllowRelay - the host will be permitted to send messages those need to be relayed
+;              to another server
+; DenyRelay  - the host can't send any e-mails destined to foreign servers
+; Disconnect - the host won't be allowed to communicate this server at all, any
+;              connection from such host will be closed with a 554 response code
+
+; Note, in some cases it may be better to block unwanted systems by firewall settings
+; instead of assigning the "Disconnect" option to them.
+
+; Here's an example list:
+
+;[Policies\Hosts]
+;localhost = AllowStore,AllowRelay
+;192.168.1.* = AllowStore,AllowRelay
+;evil.com = Disconnect
+;*.dontlike.net = DenyStore,DenyRelay
+;* = AllowStore,DenyRelay
+
+; So "localhost" will have all permissions, such as all computers on the LAN
+; (assuming they are in the subnet 192.168.1.*). The host, evil.com, on the other
+; hand will be disconnected, so it won't be allowed to even greet the server. The
+; subdomains of dontlike.net will be allowed to communicate to the server, though
+; all messages will be rejected from them politely. Any other hosts will be permitted
+; to deliver messages destined to this server, but they won't be allowed to relay
+; e-mails through it.
+; Note, relaying towards hosts those are listed on the "RelayTo" list (see below, at
+; section "Relay") doesn't require the "RELAY" right; however it still requires the
+; "STORE" right. Don't worry if you don't get it here, just read on - it's explained
+; thoroughly somewhere below.
+
+; Here is your default "Policies\Hosts" list, you may change it if you want:
+
+[Policies\Hosts]
+localhost = AllowStore,AllowRelay
+* = AllowStore,DenyRelay
+
+
+; The "Policies\Users" section is similar to the above-described "Policies\Hosts"
+; section in many ways. The difference, that it assigns rights for specific users,
+; who may authenticate themselves with the "AUTH LOGIN" command. Note, rights
+; assigned to users will completely override the rights assigned for hosts. What
+; does it mean? If a user connects from a host, such as foobar.dontlike.net from the
+; above example, she won't have any rights initially. But if she identifies herself
+; as user "LBurke", she will have all rights.
+; However, a user may even have more restrictive privileges that the connection will
+; permit them by default. For example, "Eli" connects from 192.168.1.32 (a host that
+; has full rights according to the above example), and authenticates herself. She'll
+; lose the "RELAY" right.
+; All user accounts must have a password set, see below.
+; A user account doesn't need to have a corresponding local mailbox, and generally,
+; user accounts have nothing to do with mailboxes.
+; Note, it is pointless to supply "Disconnect" in this ACL, because it won't be checked
+; and enforced after the user has been greeted. And obviously, if the host the user is
+; connecting from has "Disconnect" set in the "Policies\Hosts" ACL, the user won't be
+; able to authenticate because they'll get disconnected before they could attempt to.
+
+; Here's our example as an illustration:
+
+;[Policies\Users]
+;LBurke = AllowStore,AllowRelay
+;Eli = AllowStore,DenyRelay
+;SomeGroup = AllowStore,AllowRelay
+
+; And here you may add your own users:
+
+[Policies\Users]
+
+
+; If you add users, you must set their passwords which they can authenticate with, in
+; "Policies\Users\<username>" sections. Passwords can be specified by plaintext or by
+; their MD5 checksums (the latter is more secure). Also, you can add alias usernames
+; for a user. (Though I must admit it's pretty useless since you can't supply distinct
+; passwords for them.)
+; You can even modify the databytes limit valid for a user - if a user authenticates,
+; their databytes limit completely overrides the default databytes limit given in the
+; "Spool" section. That means, the user's databytes limit can be either smaller or
+; larger than the default. Databytes limit is always specified in bytes. The detailed
+; description of "databytes limit" can be found somewhere below, under the "Spool"
+; section.
+
+; See the example settings for our example users:
+
+;[Policies\Users\LBurke]
+;Auth = On
+;Databytes = 134217728
+;PassType = md5
+;Password = 7947ba4e6c4bede8896b1c0e28d5f258
+;
+;[Policies\Users\Eli]
+;Auth = On
+;PassType = plain
+;Password = alwaysthirsty
+;
+;[Policies\Users\SomeGroup]
+;Auth = On
+;Databytes = 8388608
+;Alias = Monkey,Donkey,Hippo
+;PassType = plain
+;Password = LuckyAmI
+
+
+; The "Spool" section defines the behaviour of the message queue. All e-mails are
+; queued in the spool after they are received, even local messages. The reason why
+; local messages get queued instead of being delivered to the appropriate mailbox
+; immediately, is that mailboxes have to be locked when an e-mail is being delivered
+; to them. Thus, the mail server couldn't receive more than one e-mails for the same
+; mailbox at the same moment. Queueing even local messages allows the server to accept
+; multiple e-mails for the same mailbox at once.
+; The queue function can't be disabled.
+
+[Spool]
+
+; The "Databytes" entry specifies the so-called databytes limit for incoming e-mails.
+; (I don't really know why is it actually called "databytes limit", but other mail
+; servers name it like that.)
+; Unlike mailbox quota, databytes limit sets the maximum size of a single e-mail that
+; the mail server is willing to process. The databytes limit set here may get
+; overridden for specific users who must authenticate themselves with "AUTH LOGIN".
+; (See "Policies\Users\<username>" sections above.)
+; The databytes limit is specified in bytes.
+
+Databytes = 16777216
+
+
+; The "AllowExceedQuota" switch defines the policies of delivery to local mailboxes.
+; Assume that a particular mailbox's quota is almost exceeded. Then the mail server
+; receives an e-mail with a size that would surely take the mailbox over quota.
+; When "AllowExceedQuota" is enabled, the spool will deliver this e-mail to the
+; mailbox, so it allows it to exceed its quota. The next e-mail however will be
+; refused by the server with an error message (so that won't get into the spool).
+; If "AllowExceedQuota" is disabled, the spool won't let the mailbox to get over
+; quota, so it guarantees the mailbox will never be bigger than its quota. In that
+; case, the spool will generate a Delivery Status Notification to inform the sender
+; of the failure. E-mails may still be accepted by the server for such mailboxes,
+; they get the error message later. It is not a common technique.
+; If the sender is so kind that it supplies a SIZE declaration in its the MAIL command,
+; then the server will check the mailbox's quota and refuse the e-mail if it wouldn't
+; fit in, when "AllowExceedQuota" is disabled.
+; Note, as I see most mail servers allow their users to exceed their quotas with
+; one last e-mail.
+
+AllowExceedQuota = On
+
+
+; "MaxReceivedHeaders" is invented to detect possible mail relay loops. In some cases,
+; if a mail server is configured incorrectly, it may relay some e-mails to itself, or
+; to another mail server that will relay the e-mail back, thus it will be stuck in an
+; infinite mail relay loop. To prevent mail relay loops to go far, MgSMTP counts the
+; "Received" headers of e-mails, and rejects messages those have "MaxReceivedHeaders"
+; or more number of "Received" headers.
+
+MaxReceivedHeaders = 16
+
+
+; The "DeliveryThreads" key tells the spool how many delivery threads to start.
+; These threads constantly watch the spool for e-mails need to be delivered. If your
+; server has many messages in the spool, then all your threads get busy, and each
+; thread will try to deliver an e-mail. If you have 8 threads for example, then a
+; maximum of 8 e-mails will be delivered in paralell.
+; NOTE: To avoid collisions of delivery threads, possible first characters of spool
+; object names are assigned to specific threads. (Numbers 0-9 and letters A-Z.)
+; Thus, one thread will never try to open a spool object that another thread is
+; working on. The drawback of this feature is that it maximizes the number of delivery
+; threads to 36. If the maximum value is set, each threads will bother only with
+; spool objects those names start with one specific number or letter.
+
+DeliveryThreads = 8
+
+
+; The "ThreadWait" key defines the "heartbeat" of your delivery threads. More
+; precisely, the threads will wait a "ThreadWait" number of milliseconds after it
+; glanced through the spool for deliverable e-mails, before it checks the spool again.
+; The more busy is your server, the smaller "ThreadWait" value you should have.
+; If your mail server is really busy, I suggest you to set a value less than 1000.
+; NOTE: If you find that your server has a pretty large CPU utilization even when it's
+; idle (no messages in spool), you should set a higher "ThreadWait" value.
+
+ThreadWait = 1000
+
+
+; The "TryCount" value tells the spool how many times should it try to deliver a queued
+; message that has temporary failures. The server should keep trying for several days.
+; Use the "TryDelay" value to calculate the actual length of trying in time.
+
+TryCount = 4320
+
+
+; The "TryDelay" value tells the spool the number of MINUTES it has to wait before
+; retrying to deliver an e-mail to recipients those failed with temporary errors at
+; previous attempts.
+
+TryDelay = 2
+
+
+; The "TempFailNotifyFirst" switch tells MgSMTP whether to send a temporary failure
+; notice after the very first attempt of delivery (if that fails with a temporary
+; failure). It's not a common setting by the way.
+; According to my own experiences, this option comes really handy for testing relay
+; configuration, and it is useful when you get noticed that your e-mail delays,
+; even if it's because of greylisting on the target server.
+; But in some cases it can be very annoying when random folks out there receive
+; temporary failure notifications from your mail system at the first place, and in
+; the case if they don't know anything about how do SMTP networks work, they can
+; easily interpret your temporary failure notification as permanent...
+
+TempFailNotifyFirst = On
+
+
+; MgSMTP sends temporary failure notices of undelivered messages after "TempFailNotify"
+; tries. If the setting is 1440 for example, a failure notice will be sent after
+; the 1440th try, then the 2880th try, then the 4320th try, and so on. If a number of
+; "TryCount" tries has been reached, a permanent failure notice will be sent in any
+; way, and the queued message will be administered and deleted as failed.
+
+TempFailNotify = 1440
+
+
+; If "KeepProcessedEnvelopes" is enabled, MgSMTP will move the .DAT files of processed
+; e-mails to the "processed" directory, instead of removing them. There you can see
+; the final state of the "spool object"/".DAT file"/"envelope", or whatever you would
+; like to call it. The .DAT file is actually in INI format, it's quite easy to read and
+; understand.
+
+KeepProcessedEnvelopes = Off
+
+
+; If "KeepProcessedEMails" is enabled, MgSMTP will move processed e-mails (stored in
+; .EML files) to the "processed" directory, instead of deleting them. Note, this
+; option actually allows you to see/archive all e-mails passed through your SMTP
+; server. If there are more people using your system, it may involve moral questions.
+; Moreover, if there are many large e-mails passing through your server, it may fill
+; up a lot of space in a short time.
+
+KeepProcessedEMails = Off
+
+
+; The "Mailbox" section contains settings regarding local mailboxes.
+
+[Mailbox]
+
+; This is the global quota setting - it will apply to any mailboxes those don't have
+; a specific quota set. If you set it to "0", the quotas will be unlimited.
+
+Quota = 67108864
+
+
+; Below you can enable "domain-specific mailboxes", which allows you to set up a limited
+; form of virtual hosting. Assume your mail server is receiving e-mails for
+; yourdomain.com and otherdomain.com. Both of these domains are supplied at
+; "Server\Name" or "Server\Alias". Then you'd like to run 2 separate mailboxes for
+; info@yourdomain.com and info@otherdomain.com. If you simply create a file named
+; "info" in the "mail" directory, then both of the mentioned e-mail addresses will
+; address that single mailbox, while you want separate mailboxes.
+; The "DomainSpecific" option enables a feature that allows you to create mailboxes
+; those are only valid for a specific alias domain. To use it, create mailbox files in
+; the "mail" directory by supplying their domains as well: create files named
+; "info@yourdomain.com" and "info@otherdomain.com".
+; Note that this is not standard - it is not ensured that your e-mail client will be
+; able to read your mailbox files, or your POP3/IMAP server (if you have such - really,
+; if you have a suitable open-source POP3 or IMAP server for Windows, please tell me!)
+; will handle such mailboxes. The POP3 protocol, in fact, doesn't support virtual
+; hosting at all.
+
+DomainSpecific = Off
+
+
+; Enable or disable the rewriting feature globally. If disabled, none of the
+; "RewriteTo" lines will be in effect. (See below.)
+
+Rewrite = Off
+
+
+; Global "RewritePassThru" setting. It will be applied to all mailboxes on which you
+; don't set a "ForwardHeaders" value explicitly. (See individual mailboxes for
+; explanation.)
+
+RewritePassThru = On
+
+
+; Default "RewriteTo" setting. Please only fill it if you really find it necessary.
+; In most cases, you'd better provide RewriteTo lists for individual mailboxes only.
+
+;RewriteTo =
+
+
+; Enable or disable the forwarding feature globally. If disabled, none of the
+; "ForwardTo" lines will be in effect. (See below.)
+
+Forward = Off
+
+
+; Global "ForwardHeaders" setting. It will be applied to all mailboxes on which you
+; don't set a "ForwardHeaders" value explicitly. (See individual mailboxes for
+; explanation.)
+
+ForwardHeaders = On
+
+
+; Default "Remail" setting for mailboxes. (See below.)
+
+Remail = On
+
+
+; Default "StoreLocalCopy" setting for mailboxes. (See below.)
+
+StoreLocalCopy = On
+
+
+; Default "ForwardTo" setting. Please only fill it if you really find it necessary.
+; In most cases, you'd better provide ForwardTo lists for individual mailboxes only.
+
+;ForwardTo =
+
+
+; "Mailbox\<name>" sections define settings for specific mailboxes. Note, it is not
+; mandatory to have such sections for all existing mailboxes. If there is nothing
+; specific to set for a mailbox, then it's useless to have a section for it here.
+; If you have sections for non-existent mailboxes, those will be ignored.
+
+; Here's an example section for a hypothethical mailbox named "foobar":
+
+;[Mailbox\foobar]
+;Quota = 8388608
+;Alias = moo,cow
+
+; Obviously, the "Quota" setting sets the quota for the specific mailbox. The "Alias"
+; list adds aliases to the mailbox, so it will be accessed by multiple names.
+
+; Rewriting and forwarding:
+
+;[Mailbox\info]
+;RewriteTo = you@gmail.com
+;RewritePassThru = On
+
+; The "info" mailbox above utilizes rewriting. Whenever the mail server receives an
+; e-mail for this mailbox, MgSMTP will also add "you@gmail.com" to the envelope as
+; recipient, as if the client would have sent the e-mail to that address too. (The
+; client doesn't need to have relay rights, rights are not checked upon rewriting.)
+; "RewritePassThru" controls whether the original recipient should be kept: if it's
+; "Off", the e-mail won't be delivered to the "info" mailbox, it will only be sent to
+; "you@gmail.com".
+; Be aware that rewriting is not recursive!
+; Also, since rewriting takes effect when an e-mail is received from a client,
+; rewriting won't be applied to internally generated e-mails (such as DSNs, forwarded
+; messages).
+
+;[Mailbox\monkey]
+;ForwardTo = you@gmail.com
+;ForwardHeaders = On
+;StoreLocalCopy = On
+
+; The "monkey" mailbox utilizes forwarding. When MgSMTP is about to deliver a message
+; to this mailbox, the message will be copied, and the copy will be sent to
+; "you@gmail.com". If "ForwardHeaders" is enabled, MgSMTP will add an "X-Forwarded-For"
+; and an "X-Forwarded-To" header to make this event traceable.
+; If "StoreLocalCopy" is disabled, the message won't be delivered to the originally
+; addressed "monkey" mailbox, it will be just forwarded on-the-fly.
+; In the case of forwarding, the original Return-Path will be used for the copied
+; message.
+
+;[Mailbox\donkey]
+;ForwardTo = you@gmail.com
+;ForwardHeaders = On
+;StoreLocalCopy = On
+;Remail = On
+
+; The "donkey" mailbox utilizes remailing. Remailing is pretty much like forwarding,
+; except that the Return-Path of the copied message will be replaced by the address
+; of the actual mailbox ("donkey@yourdomain.com", in this case). This has several
+; advantages:
+; - incidental failure notices will arrive to "donkey", instead of the unsuspecting
+;   sender of the original message who should not be aware of the remailing (assume
+;   "donkey" still visits his mailbox here as well for time to time, so he'll see his
+;   failure notices);
+; - if the target domain uses the SPF SPAM filtering technique (GMail does, for
+;   example), the result will depend on your domain's SPF record (which is controlled
+;   by you, hopefully), and not on the original sender's one, which supposedly won't
+;   designate your host as a permitted sender for their domain.
+; Remailing won't be applied to DSNs (or any e-mails with empty Return-Path), because
+; supplying a Return-Path for such a message could easily cause a remailing loop. Such
+; messages will be simply forwarded instead.
+
+; Note: Both "RewriteTo" and "ForwardTo" keys are lists, so you can supply multiple
+; addresses separated by commas. E.g.:
+; ForwardTo = jane@nowhere.com,jack@somewhereelse.com
+
+; ESSENTIAL DIFFERENCES BETWEEN REWRITING AND FORWARDING/REMAILING:
+; In the case of rewriting, the original message's envelope will get modified before the
+; server receives the e-mail. This means, rewriting happens before the message gets to
+; the spool. No headers can be added to track what was rewritten to what. The message
+; will seem like it was just relayed through your SMTP server, as if it was addressed to
+; the rewritten address originally.
+; On the other hand, forwarding happens after the message has been stored in the spool.
+; It happens when the spool delivers the message to the local recipient. Then the
+; message gets copied, and the copy will be sent to the forward addresses. The copy will
+; contain "X-Forwarded-*" headers (if "ForwardHeaders" is on), and an additional
+; "Received" header. If the original message has been actually stored to the originally
+; addressed mailbox as well (depends on "StoreLocalCopy"), a "Delivered-To" header will
+; be also present.
+
+; Rewriting is not recursive, while forwarding/remailing is. Rewriting won't apply to
+; internally generated e-mails (such as DSNs and forwarded messages), while forwarding
+; will.
+
+; Since forwarding/remailing is more traceable, and remailing also protects you from
+; negative SPF results, forwarding or remailing is usually more preferable over
+; rewriting. However, rewriting is a much simpler and resource cheaper operation than
+; forwarding. I suggest to use rewriting for addresses within your network, or to add
+; aliases for domain-specific mailboxes those belong to other alias domains. To forward
+; mail to other domains, use forwarding or remailing!
+
+; USING BOTH REWRITING AND FORWARDING ON A SINGLE MAILBOX:
+; It's possible, but "RewritePassThru" must be enabled to allow forwarding to apply!
+; (You can still have "StoreLocalCopy" off, if you don't want your message to be
+; actually delivered to the mailbox.)
+
+; Domain-specific mailboxes:
+
+;[Mailbox\info@otherdomain.com]
+;Alias = contact,information
+
+; Here are a some rules applying to domain-specific mailboxes:
+; - If you have an "info@otherdomain.com" file in your "mail" folder, then it will only
+;   override the "info" mailbox, unless "info@otherdomain.com" has aliases. So the
+;   mailbox "sam" will still receive e-mails for all alias domains (assuming there are
+;   no domain-specific mailboxes with username "sam").
+; - If you have both "info" and "info@otherdomain.com" files in your "mail" folder, then
+;   the former mailbox will still receive e-mails for all alias domains, except
+;   otherdomain.com.
+; - If you have aliases for "info@otherdomain.com", those will be only valid for
+;   otherdomain.com. The aliases for a domain-specific mailbox will override the normal
+;   mailboxes with the corresponding names, see the 2nd point above.
+; - If you want to add aliases for domain-specific mailboxes those belong to other
+;   domains (i.e. you want to add "monkey@xxdomain.com" as an alias for
+;   "donkey@yydomain.com"), the normal "Alias" key won't work! In this case, you need to
+;   use "RewriteTo" or "ForwardTo".
+
+
+; The "Relay" section defines the server's relay rules.
+
+[Relay]
+
+; The "RelayTo" list gives hostnames which the server is designated to relay towards.
+; Even hosts those don't have the RELAY right will be allowed to relay towards these
+; addresses. (However, those hosts still need to have the STORE right to be eligible
+; to relay to "RelayTo" addresses.) In an aspect, MgSMTP considers recipient addresses
+; destinating to a host listed on the "RelayTo" list as local.
+; You need to use this for setting up backup MX servers.
+; It can be also useful if you'd like to receive e-mails for a computer on your LAN.
+
+; RelayTo = abcdef.com,ghijkl.org
+
+
+; The "NoRelayTo" list is the exact opposite of the "RelayTo" list: it prevents
+; relaying to specific domains, even for clients those would be permitted to relay
+; otherwise.
+
+; NoRelayTo = forumspammer.net
+
+
+; The "Relay\Routes" section defines a routing table. You can specify a mask on the
+; left sides of each item of the list. On the right side, you can specify a host where
+; you would like to relay matching addresses. You can define a host by giving its
+; hostname, or by associating a symbolic name you choose. If you use a symbolic name,
+; you must expand the settings applying to that host in a distinct section (see below).
+; A special character may also be used: "!", it means e-mails for those hosts will be
+; relayed to the named host directly.
+
+; See this example:
+
+;[Relay\Routes]
+;donkey.net = monkey.org
+;*.lucky.com = !
+;foobar.com = foobar.com
+;* = MyISP
+
+;[Relay\Routes\foobar.com]
+;Port = 600
+
+;[Relay\Routes\MyISP]
+;Host = mail.myisp.net
+;Auth = On
+;Username = myusername
+;Password = mypassword
+
+; According to this example, e-mails addressed to host donkey.net will be relayed
+; to monkey.org. (So e-mails addressed to anything@donkey.net will be actually sent to
+; the MX-es of monkey.org.)
+; E-mails destined to whatever.lucky.com will be passed to the MX-es of
+; whatever.lucky.com, as it would be normal.
+; E-mails destined to foobar.com will be delivered to the MX-es of foobar.com, but
+; they will be connected on an alternate port (600).
+; Any other e-mails will be relayed through your ISP's SMTP, defined by the symbolic
+; name, "MyISP". Settings for "MyISP" are defined in a distinct section. There, the
+; real hostname of the ISP's SMTP server is specified. This SMTP server requires user
+; authentication, it is indicated by the "Auth" switch, and of course, the username
+; and the password need to be revealed as well. MgSMTP will authenticate itself with
+; "AUTH LOGIN" at the ISP's SMTP server when it relays e-mails through it.
+; Note, you don't have any option to store this password in an encrypted form. So it is
+; crucial to deny all unwanted users to view this file.
+
+; Here is your default routing table:
+
+[Relay\Routes]
+* = !
+
+
+; The "Log" section configures MgSMTP's logging behaviour.
+
+[Log]
+
+; Maybe you are glad that there aren't a lot of things to be set here.
+; MgSMTP writes its log to "smtp.log" in its own directory. You can override this
+; default filename if you want.
+
+Filename = smtp.log
+
+
+; That's all, folks. I told you, it's a minimal-featured SMTP server. But anyway, if
+; you miss something, tell me your ideas by sending an e-mail to
+; <megabrutal@mgsmtp.eu>.
diff --git a/readme.txt b/readme.txt
new file mode 100644 (file)
index 0000000..4a2403c
--- /dev/null
@@ -0,0 +1,208 @@
+                        MegaBrutal's SMTP Server (MgSMTP)
+
+                           ~~~ BASIC USER'S GUIDE ~~~
+
+
+    I. Foreword
+   II. Features
+  III. Installation/Uninstallation
+   IV. Configuration
+    V. Managing mailboxes
+   VI. Reading your local e-mails
+  VII. Running in user mode
+ VIII. Service-specific exit codes
+   IX. Disclaimer
+
+
+I. Foreword
+-----------
+
+MgSMTP is a lightweight SMTP server for Windows, with minimal feature support. (However, the list of its features is constantly augmenting.) MgSMTP is suitable for you, if you'd like to run a simple, low-traffic mail server on Windows. You can use it as a relay on your LAN, or a primary or backup MX server for your domain(s). It runs as a Windows service. MgSMTP is a free and open-source software released under the GNU GPL.
+
+Common uses of MgSMTP:
+- As an SMTP relay on a Windows desktop OS to accept e-mails from your applications, other computers, devices on your LAN.
+- SMTP relay for scan-to-mail printers.
+- To make the PHP mail function work for your Apache/PHP installation on Windows.
+
+Thanks for downloading MgSMTP! If you have any comments, questions, feature or support requests, bug reports regarding the software, please send an e-mail to <megabrutal@mgsmtp.eu>. In case of bug reports and support requests, please try to explain your problem in details and (if applicable) include relevant snippets from your smtp.log.
+
+Currently, MgSMTP is in BETA state. I don't recommend to use it for critical purposes. MgSMTP has never been tested under high traffic, and most likely it would provide very poor performance in such conditions. I suggest you to check for new MgSMTP versions frequently, because crucial bugfixes may be released at any day.
+
+Also note, I don't provide any warranty for MgSMTP (and the voluntary support I provide for it). Of course, I'll do my best to make it a good-quality software, but I can't promise anything. See the official disclaimer at the end of this file.
+
+If you use the software, I highly recommend you to subscribe to the project's mailing list here:
+https://lists.sourceforge.net/lists/listinfo/mgsmtp-general
+
+MgSMTP is a one-man project that I do in my free time. Any donations would be highly appreciated.
+http://sourceforge.net/project/project_donations.php?group_id=371997
+
+
+II. Features
+------------
+
+As of now, MgSMTP only supports a very basic set of features. Read mgsmtp_server_example.ini for details. Sadly, MgSMTP still lacks some common features those are widely supported by most mail servers. As of yet, MgSMTP doesn't support SSL/TLS, and doesn't utilize any SPAM-prevention techniques.
+
+Supported features:
+- Mail routing table
+- Mail forwarding/remailing
+- User authentication (AUTH LOGIN)
+- ACLs
+- Domain-specific mailboxes
+
+Unsupported, planned features:
+- DNSBL check (RBL, RHSBL)
+- Message piping
+- Greylisting
+- Bind to specific interfaces only
+- IPv6
+- SSL/TLS
+
+
+III. Installation/Uninstallation
+--------------------------------
+
+Note, some steps of the installation (or uninstallation) may require administrative rights. If UAC is enabled on your system, ensure that you start applications necessary for doing the following steps (such as Total Commander, if you use, and command-line) as administrator. (UAC is only available on Windows Vista and newer systems, you don't need to worry about it if you have an older OS - just log in as an administrator account.)
+
+
+To install:
+
+1. Extract the contents of the package to a directory you'd like it. For example: "C:\Program Files\MgSMTP".
+
+2. Make a configuration file ("mgsmtp_server.ini") and create a mailbox for "postmaster". (See below.)
+
+3. Open up a command-line in the target directory. Type: "mgsmtp /INSTALL" to register MgSMTP as a Windows service.
+
+4. Type "net start MgSMTP" to start the service.
+
+If you get an error message at the last step, see the service-specific exit codes below. Also don't forget to inspect your log file (smtp.log by default)!
+
+
+To uninstall:
+
+1. Open up a privileged command line, and go to the directory of MgSMTP.
+
+2. Stop the MgSMTP service. (You can do this by issuing the "net stop MgSMTP" command.)
+
+3. Type "mgsmtp /UNINSTALL" to unregister the MgSMTP service.
+
+You have successfully uninstalled MgSMTP. You may safely remove its subdirectory if you want.
+
+
+IV. Configuration
+-----------------
+
+The configuration file for MgSMTP is actually an INI file that you need to prepare carefully before you use the software. I've presented a sample configuration file ("mgsmtp_server_example.ini") that you should read to get a clue how to configure MgSMTP. You should make your configuration file as "mgsmtp_server.ini" in MgSMTP's directory.
+
+I list some hints and warnings here:
+
+- You must supply the "Server\Name" entry to start the service. This will be the virtual hostname of your server that it'll report in greetings, in HELO commands sent to other servers, in failure notices; and most importantly, it'll accept e-mail addresses with the given hostname as local. You may supply additional hostnames in "Server\Alias" to tell the server to treat those hostnames as local as well.
+
+- If your server is able to accept connections from the Internet, or otherwise untrusted network, ALWAYS enable the "Server\Policies" setting, and set up rights for foreign hosts wisely. If you neglect to do so, you expose your server to the risk of acting as an open relay, and it's pretty unlikely that you'd like that.
+
+- If you make any modifications to the configuration file, you need to restart the service for changes to take effect. To do this, open up a command-line, and issue the following commands:
+net stop MgSMTP
+net start MgSMTP
+
+
+V. Managing mailboxes
+---------------------
+
+MgSMTP uses the mbox format to store e-mails in local mailboxes. Such mailboxes are located in the "mail" directory, relative to the executable's path.
+
+
+To add a new mailbox:
+
+1. Locate the "mail" directory. If you've never run MgSMTP before, you should create that directory. It must be a subdirectory of the directory where mgsmtp.exe is located.
+
+2. Create an empty file with the name of the desired mailbox in the "mail" directory. There are several methods, e.g. you can use the "touch" command (though you need the appropriate GnuWin32 package for that), or Notepad. For example, you'd like to create a mailbox named "postmaster". Open up a command-line, go to the "mail" directory, and type:
+notepad postmaster
+
+A Notepad will open, and it'll notify you that the given file doesn't exist, and ask you whether you'd like to create that file. Click Yes, and close the Notepad. A 0-byte file should show up in the directory.
+
+NOTE: If you use Windows Explorer, be sure that the created file doesn't have any extension. The above command-line approaches ensure that, while Windows Explorer may trick you because it hides the file extensions by default. Notepad may automatically add a ".txt" extension if you use the "Save As..." panel. A mailbox file with an extension will still work technically, but it will be addressed like "postmaster.txt@yourdomain.tld". If that's what you want, go ahead! :p
+
+3. If you need to configure special parameters, features for this mailbox (e.g. aliases, quota setting, forwarding), open your configuration file and add a proper "Mailbox\mailboxname" section (see "mgsmtp_server_example.ini").
+
+4. Restart MgSMTP, for it won't be aware of the new mailbox until you do so.
+
+
+To remove a mailbox:
+
+1. Stop MgSMTP!
+
+2. Simply delete the mailbox file from the "mail" directory, or move it to another directory.
+
+3. Check the configuration file if there are entries concerning the removed mailbox. (E.g. if there are rewriting or forwarding settings those target the removed mailbox, and other references those might cause anomalies. Leaving the "Mailbox\mailboxname" section there is OK, it'll be just ignored by MgSMTP - though it may be still confusing for you, so it's better to at least comment it out.)
+
+4. Start MgSMTP again.
+
+
+To rename a mailbox:
+
+Follow the steps of "To remove a mailbox", with the difference that you'd rather rename the mailbox file instead of removing it. In the configuration file, you'll need to replace references to the renamed mailbox with its new name.
+NOTE: Instead of renaming the mailbox, you should consider adding an alias for it!
+
+
+To add aliases and setting the quota of a mailbox:
+
+See the example configuration file to see how to adjust the settings of existing mailboxes.
+NOTE: It's best to add aliases by editing the configuration file! Avoid creating hardlinks or symlinks for mailboxes (even though theoretically it wouldn't break MgSMTP)! If you need aliases for domain-specific mailboxes those are in a different domain, you can still use the "RewriteTo" feature.
+
+
+VI. Reading your local e-mails
+------------------------------
+
+Mailboxes stored on your local computer can be read using Pine or Alpine. These e-mail clients are available for Windows. To configure Alpine to read your local mailbox, set the path for that mailbox as "inbox-path". For example:
+inbox-path=C:\Program Files\MgSMTP\mail\postmaster
+
+If you'd like to use multiple mailboxes with Alpine on the same computer, under the same Windows user account, you can use multiple configuration files, each can be supplied with the "-p" command-line switch. You may create distinct shortcuts to start Alpine with different configuration files. Alpine also has an option to use alternate sender addresses.
+
+I don't know about any other mail client that is able to read e-mails from mailboxes directly, and runs on Windows. So it really seems Alpine is the only option. (But if you know about such a client, please tell me!)
+
+If you'd like to read your mailboxes on a remote machine, or with other mail clients than Alpine, you need to install a POP3 or IMAP server, and configure it to operate with your mailboxes. Honestly, I don't know about any softwares those may work like that on Windows. Probably later I'll implement a software named "MgPOP3" (or something like that) as MgSMTP's POP3 counterpart service. Though personally I don't need such a software, because I'm fine with Alpine, so I won't be in hurry with a POP3 implementation.
+
+
+VII. Running in user mode
+-------------------------
+
+First, I don't recommend running MgSMTP in user mode, because in that case, you can't shut it down cleanly. However it could be useful to start MgSMTP in user mode, if you'd like to debug it, or you'd just like to get error messages those are hidden when you run MgSMTP in service mode.
+
+1. Ensure that your user profile has administrative rights.
+
+2. Open up a command-line, go to the directory of MgSMTP. If UAC is enabled on your system, right click on the icon of command-line, and select the option to "run as administrator".
+
+3. Type "mgsmtp /USERMODE" at the command-line.
+
+4. To stop MgSMTP, hit CTRL-C at the command-line. You should get your prompt back.
+
+
+VIII. Service-specific exit codes
+---------------------------------
+
+If MgSMTP fails to start up, you may see service-specific exit codes either on the command-line (if you've tried to start the service with the "net" command) or in the system logs. PowerShell may also show the service-specific exit code when you use the "Start-Service" command, however I'm not sure.
+
+Here are the meanings of these service specific exit codes:
+
+1: The configuration file, "mgsmtp_server.ini" is missing, or otherwise inaccessible.
+
+2: You haven't supplied a name for your mail server in the configuration file. You must fill in the "Server\Name" entry.
+
+3: You don't have a mailbox named "postmaster". Either create a new mailbox with that name, or add "postmaster" as an alias for an existing mailbox.
+
+4: You've attempted to start too many delivery threads. The maximum number of delivery threads is 36. See the explanation in the example configuration file.
+
+
+IX. Disclaimer
+--------------
+
+MegaBrutal's SMTP Server (MgSMTP)
+Copyright (C) 2010-2012 MegaBrutal
+
+This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+
+~~~ By MegaBrutal ~~~
\ No newline at end of file
diff --git a/readme_source.txt b/readme_source.txt
new file mode 100644 (file)
index 0000000..b8b9650
--- /dev/null
@@ -0,0 +1,43 @@
+MegaBrutal's SMTP Server (MgSMTP)
+Copyright (C) 2010-2012 MegaBrutal
+
+
+This is the source code for MgSMTP version 0.9r. View the changelog to be informed about the advances made since the previous version. Versions prior to 0.9i were private, their changes were not noted.
+
+
+For source files those implement core features of MgSMTP, the GNU Affero General Public License applies:
+- MgSMTP.pas
+- Log.pas
+- Spool.pas
+- Mailbox.pas
+- Relay.pas
+- Bounce.pas
+- Listener.pas
+- Policies.pas
+
+For other files, mostly helper units, the GNU Lesser General Public License applies:
+- Common.pas
+- DNSMX.pas
+- DNSResolve.pas
+- EINIFiles.pas
+- NetRFC.pas
+- Network.pas
+- RFCSMTP.pas
+- SocketUtils.pas
+
+I've used and modified the unit, "comparewild.pas", originally published by Thomas Kelsey in 2007. For this single file, the GNU General Public License applies.
+
+
+See license.txt and license_lesser.txt, and license_gpl-2.0.txt to read the mentioned licenses.
+
+
+Compiling this source is really easy. You need the FPC (Free Pascal Compiler) installed on your computer. Supporting environmental variables (such as the compiler's directory in PATH) should be set up as well. I suggest you to use the most recent stable version of FPC to compile MgSMTP. I used 2.4.0 when released this package. To actually compile the source code, open up a command-line, and issue the following command:
+
+fpc MgSMTP.pas
+
+Magic happens! FPC will compile the entire source code in a few seconds. You should get an MGSMTP.EXE as a result. Please read the other README file on instructions how to install it.
+
+The mgsmtp_tests.zip package contains some test programs I used. If you do changes to this software, they may come handy for debugging.
+
+
+~~~ By MegaBrutal ~~~
\ No newline at end of file
diff --git a/todo.txt b/todo.txt
new file mode 100644 (file)
index 0000000..dfd4890
--- /dev/null
+++ b/todo.txt
@@ -0,0 +1,94 @@
+Future:
+- SPF
+- SpamAssassin / procmail support
+- Additional AUTH methods
+- Greylisting
+- Verify sender address (domain, corresponding authenticated user)
+- Temporarily unavailable (Test mode?)
+- Reason for disconnect
+- Proper handling of "ReqHELO" and "Unknown command"
+- Log outgoing SMTP transactions
+- Show delivery thread IDs
+- Watchdog for delivery threads
+- IPv6
+- Bind to user-specified IPs
+- VRFY?
+- Show authenticated user in "Received" headers
+- Delivery threads should finish sooner
+
+v0.9t:
+- NATIVE LINUX PORT!
+- DNSBL
+- Option to disable MX lookups
+- Ensure random spool object names
+- Process CTRL-C properly to quit from user mode gracefully
+
+v0.9s:
++ Change "Client disconnected, and thread exited successfully." to "Client disconnected."
++ Fix "Internal error" bug - this should be a temporary failure
++ Fix bug regarding simultaneous delivery to forwarded mailboxes
++ Fix bug in DNSMX.pas: improper handling of MX precedence values larger than 100
++ Fix bug regarding Policies/Hosts table not being case-insensitive
++ Fix service mode not working when compiled with FPC 2.6.2!
++ Alternate mailbox names with + signs (e.g. "megabrutal+games@domain")
++ Domain-scope mailbox settings
+- Separate config files or work directories supplied in parameters
++ Improved Wine compatibility
++ Consistent handling of local/relay spool objects
++ Implement Win64 support
++ Fix PRESHUTDOWN
++ Enforce ASCII printable characters in commands
++ Developer comment for test/debug builds
+
+v0.9r:
++ Forwarding
++ Show Message-IDs upon receipt
++ Send one cumulative DSN when multiple recipients fail
++ Revise DSN text
++ Add timestamp correction to "Received" headers
++ Append "Original-To" header
+
+v0.9q:
++ FCrDNS verification
++ Reject HEAD and POST requests too
++ Domain-specific mailboxes (virtual hosting)
++ Correct incorrect timezone correction
++ Correct bug in address interpretation
++ Correct bug in spool iteration
++ Write thread IDs in spool objects
++ Append "Return-Path" header
+
+v0.9p:
++ Time-outs in reads
++ Meaningful status codes (in smtp.log)
++ Accept mixed-case commands
++ Correct bug in DNS MX queries
++ NoRelayTo list
++ Log SMTP responses on permanent status changes
++ Don't remember status codes (never needed, only causes confusion)
+
+v0.9o:
++ Disconnect HTTP agents
++ WINE compatibility
++ Accept awkward AUTH LOGIN attempts
++ Correct timestamps
++ Fix memory/handle leak
+
+v0.9n:
++ Alternate port
++ PRESHUTDOWN
+
+v0.9m:
++ Careful threading
++ Hide AUTH feature when no users
++ Add protection against loops
++ Ensure case-insensitive relay routes
+
+v0.9l:
++ ParamCount check!
++ Fully support SIZE parameter
++ Better support for 8BITMIME
+
+v0.9k:
++ MaxAuthAttempts
++ Pipelining