2 Copyright (C) 2010-2018 MegaBrutal
4 This unit is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This unit is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 It holds some common definitions for MgSMTP, and some helper functions.
29 uses Windows
, SysUtils
, DateUtils
, Classes
, INIFiles
;
33 TStringArray
= array of string;
34 TUnixTimeStamp
= longint;
38 Option
, Value
: string;
42 TArgumentParser
= class
43 constructor Create(RawArguments
: array of string; AllowedPrefixes
: array of string);
44 destructor Destroy
; override;
46 Arguments
: array of TArgument
;
47 procedure ParseArgument(Arg
: string; const AllowedPrefixes
: array of string);
49 function GetArgument(ID
: integer): TArgument
;
50 function IsPresent(ArgumentName
: string): boolean;
51 function GetValue(ArgumentName
: string; DefValue
: string = ''): string;
52 function ValidateArguments(ValidArguments
: array of string): integer;
57 constructor Create(const Name
: string; Config
: TINIFile
; const Section
: string);
62 property Name
: string read FName
;
63 property Aliases
: TStrings read FAliases
;
64 function IsItYourName(const Name
: string): boolean; virtual;
68 TMainServerConfig
= class(TNamedObject
)
69 constructor Create(Config
: TINIFile
);
71 FPolicies
, FMailbox
, FRelay
, FLog
: boolean;
73 {FTimeCorrection: integer;}
75 FTimeOffsetStr
: string;
76 FListenAddresses
: TStrings
;
78 function GetVersionStr
: string;
79 property ListenAddresses
: TStrings read FListenAddresses
;
80 property Databytes
: longint read FDatabytes
;
81 {property TimeCorrection: integer read FTimeCorrection;}
82 property TimeOffset
: integer read FTimeOffset
;
83 property TimeOffsetStr
: string read FTimeOffsetStr
;
84 property Policies
: boolean read FPolicies
;
85 property Mailbox
: boolean read FMailbox
;
86 property Relay
: boolean read FRelay
;
87 property Log
: boolean read FLog
;
88 property VersionStr
: string read GetVersionStr
;
94 TEMailProperties
= class
100 procedure SetSize(Value
: longint);
101 procedure WriteFlags(Value
: TEMailFlags
);
102 procedure SetFlag(Flag
: TEMailFlags
);
103 function HasFlag(Flag
: TEMailFlags
): boolean;
104 property Size
: longint read FSize write SetSize
;
105 property Flags
: TEMailFlags read FFlags write WriteFlags
;
110 Address
, RMsg
: string;
116 constructor Create(const Name
, IP
: string);
120 property Name
: string read FName
;
121 property IP
: string read FIP
;
122 function Copy
: TIPNamePair
;
128 destructor Destroy
; override;
130 FReturnPath
, FRelayHost
: string;
131 FReturnPathSpecified
: boolean;
132 FRecipients
: array of TRecipient
;
134 function GetNumberOfRecipients
: integer;
135 function GetRecipient(Index
: integer): TRecipient
;
136 function IsComplete
: boolean;
137 procedure AddRecipient(Address
: string; Data
: integer = 0; RMsg
: string = ''); overload
;
138 procedure AddRecipient(Recipient
: TRecipient
); overload
;
139 procedure SetReturnPath(Address
: string);
140 procedure SetRecipientData(Index
, Data
: integer; RMsg
: string = '');
141 procedure SetAllRecipientData(Data
: integer; RMsg
: string = '');
142 procedure SetRelayHost(HostName
: string);
143 property ReturnPath
: string read FReturnPath write SetReturnPath
;
144 property RelayHost
: string read FRelayHost write SetRelayHost
;
148 TEnvelopeArray
= array of TEnvelope
;
151 function EMailUserName(EMail
: string): string;
152 function EMailHost(EMail
: string): string;
153 function CleanEMailAddress(EMail
: string): string;
154 function IsValidEMailAddress(EMail
: string): boolean;
155 function EMailTimeStamp(DateTime
: TDateTime
): string;
156 function EMailTimeStampCorrected(DateTime
: TDateTime
): string;
157 function StatusToStr(Status
: integer): string;
158 procedure AssignDeliveryStatusToSMTPCodes(Envelope
: TEnvelope
; TransactionComplete
: boolean);
160 function CleanEOLN(S
: string): string;
161 function GenerateRandomString(Length
: integer): string;
162 function GetAlphabetStr
: string;
163 function GetServiceCodeStr(Ctrl
: dword
): string;
164 function GetWinMajorVersion
: longword
;
165 function IsPrintableString(S
: string): boolean;
166 function UnixTimeStamp(DateTime
: TDateTime
): TUnixTimeStamp
;
167 function CmdlineToStringArray
: TStringArray
;
168 procedure SplitParameters(S
: string; var FirstPrm
, Remainder
: string; Separator
: char = #32);
170 function ReadLineFromStream(Stream
: TStream
): string;
171 function WriteLineToStream(Stream
: TStream
; Line
: string): boolean;
177 VERSION_STR
= '0.9t';
188 { Delivery statuses: }
189 DS_DELIVERED
= 1 shl 10;
190 DS_DELAYED
= 1 shl 11;
191 DS_PERMANENT
= 1 shl 12;
192 DS_INTERNALFAIL
= 1 shl 13;
193 DS_CONNECTIONFAIL
= 1 shl 14;
194 DS_UNEXPECTEDFAIL
= 1 shl 15;
195 DS_SMTPFAIL
= 1 shl 16;
196 DS_SMTPREPLYMASK
= $000003FF;
197 DS_ALLFLAGS
= $FFFFFFFF;
199 { E-mail property flags: }
202 DayNames
: array[1..7] of shortstring
= ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
203 MonthNames
: array[1..12] of shortstring
= ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
204 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
206 { Support for PRESHUTDOWN is not yet present in the Free Pascal library,
207 therefore I define the necessary constants here. It's a temporary
208 solution, I hope I won't need it for the next release of FPC. }
209 SERVICE_ACCEPT_PRESHUTDOWN
= $00000100;
210 SERVICE_CONTROL_PRESHUTDOWN
= $0000000F;
215 MainServerConfig
: TMainServerConfig
;
221 { Unit-private functions/prodecures: }
223 function InStringArray(const S
: string; const SA
: array of string): boolean;
227 while (i
< Length(SA
)) and (SA
[i
] <> S
) do Inc(i
);
228 Result
:= i
< Length(SA
);
231 function MakeTimeOffsetStr(TimeOffset
: integer): string;
232 var CorrS
: string; CorrI
: integer;
235 CorrS
:= IntToStr(Abs(CorrI
));
236 while Length(CorrS
) < 4 do CorrS
:= '0' + CorrS
;
237 if CorrI
>= 0 then CorrS
:= '+' + CorrS
else CorrS
:= '-' + CorrS
;
242 { Unit-public functions/procedures: }
244 function EMailUserName(EMail
: string): string;
248 while (p
> 0) and (EMail
[p
] <> '@') do Dec(p
);
250 Result
:= Copy(EMail
, 1, p
- 1);
255 function EMailHost(EMail
: string): string;
259 while (p
> 0) and (EMail
[p
] <> '@') do Dec(p
);
260 if (p
<> 0) and (p
< Length(EMail
)) then begin
261 Result
:= Copy(EMail
, p
+ 1, Length(EMail
) - p
);
266 function CleanEMailAddress(EMail
: string): string;
267 var po
, pc
, p
: integer;
269 po
:= Pos('<', EMail
);
270 pc
:= Pos('>', EMail
);
271 if (po
<> 0) and (pc
<> 0) and (po
< pc
) then begin
272 Result
:= Copy(EMail
, po
+ 1, pc
- po
- 1);
273 p
:= Pos(':', Result
);
275 Result
:= Copy(Result
, p
+ 1, Length(Result
) - p
);
281 function IsValidEMailAddress(EMail
: string): boolean;
283 { !!! TODO: Implement more strict checking later !!! }
284 Result
:= Pos('@', EMail
) <> 0;
287 function EMailTimeStamp(DateTime
: TDateTime
): string;
288 var Year
, Month
, Day
: word;
290 DecodeDate(DateTime
, Year
, Month
, Day
);
291 Result
:= DayNames
[DayOfWeek(DateTime
)] + ' ' + MonthNames
[Month
] + ' '
292 + FormatDateTime('dd hh:nn:ss', DateTime
) + ' ' + IntToStr(Year
);
295 function EMailTimeStampCorrected(DateTime
: TDateTime
): string;
297 Result
:= EMailTimeStamp(DateTime
) + ' ' + MainServerConfig
.TimeOffsetStr
;
300 function StatusToStr(Status
: integer): string;
301 { Returns the delivery status code in human-readable format. }
303 Result
:= IntToStr(Status
and (DS_ALLFLAGS
- DS_SMTPREPLYMASK
- DS_SMTPFAIL
))
304 + '+' + IntToStr(Status
and DS_SMTPREPLYMASK
);
307 procedure AssignDeliveryStatusToSMTPCodes(Envelope
: TEnvelope
; TransactionComplete
: boolean);
308 var i
, code
, cond
, status
: integer; Recipient
: TRecipient
;
310 for i
:= 0 to Envelope
.GetNumberOfRecipients
- 1 do begin
311 Recipient
:= Envelope
.GetRecipient(i
);
312 code
:= Recipient
.Data
and DS_SMTPREPLYMASK
;
315 0: status
:= DS_DELAYED
or DS_UNEXPECTEDFAIL
;
316 2: if TransactionComplete
then status
:= DS_DELIVERED
317 else status
:= DS_DELAYED
or DS_UNEXPECTEDFAIL
;
318 4: status
:= DS_DELAYED
;
319 5: status
:= DS_PERMANENT
;
320 else status
:= DS_PERMANENT
or DS_UNEXPECTEDFAIL
;
322 if code
<> 0 then status
:= status
or DS_SMTPFAIL
;
323 Envelope
.SetRecipientData(i
, code
or status
, Recipient
.RMsg
);
328 function CleanEOLN(S
: string): string;
330 while (Length(S
) <> 0) and (S
[Length(S
)] in [#13, #10]) do Delete(S
, Length(S
), 1);
334 function GenerateRandomString(Length
: integer): string;
335 var What
, Chrn
, i
: integer; Value
: string;
338 for i
:= 1 to Length
do begin
341 0: begin Chrn
:= Random(10)+48; Value
:= Value
+ Chr(Chrn
); end;
342 1: begin Chrn
:= Random(26)+65; Value
:= Value
+ Chr(Chrn
); end;
343 2: begin Chrn
:= Random(26)+97; Value
:= Value
+ Chr(Chrn
); end;
349 function GetAlphabetStr
: string;
353 for i
:= Ord('0') to Ord('9') do Result
:= Result
+ Chr(i
);
354 for i
:= Ord('A') to Ord('Z') do Result
:= Result
+ Chr(i
);
357 function GetServiceCodeStr(Ctrl
: dword
): string;
360 SERVICE_CONTROL_STOP
: Result
:= 'STOP';
361 SERVICE_CONTROL_SHUTDOWN
: Result
:= 'SHUTDOWN';
362 SERVICE_CONTROL_PRESHUTDOWN
: Result
:= 'PRESHUTDOWN';
363 else Result
:= IntToStr(Ctrl
);
367 function GetWinMajorVersion
: longword
;
368 var OSVersionInfo
: TOSVersionInfo
;
370 { Get OS version info. }
371 OSVersionInfo
.dwOSVersionInfoSize
:= SizeOf(TOSVersionInfo
);
372 GetVersionEx(OSVersionInfo
);
373 Result
:= OSVersionInfo
.dwMajorVersion
;
376 function IsPrintableString(S
: string): boolean;
377 { Check if string contains only printable ASCII characters. }
382 while Result
and (i
<= Length(S
)) do begin
383 Result
:= (Ord(S
[i
]) > 31) and (Ord(S
[i
]) < 127);
388 procedure SplitParameters(S
: string; var FirstPrm
, Remainder
: string; Separator
: char = #32);
391 i
:= pos(Separator
, S
);
393 FirstPrm
:= Copy(S
, 1, i
- 1);
394 Remainder
:= Copy(S
, i
+ 1, Length(S
) - i
);
402 function CmdlineToStringArray
: TStringArray
;
405 SetLength(Result
, ParamCount
);
406 for i
:= 1 to ParamCount
do
407 Result
[i
-1]:= ParamStr(i
);
410 function UnixTimeStamp(DateTime
: TDateTime
): TUnixTimeStamp
;
412 {Result:= Trunc((DateTime - EncodeDate(1970, 1 ,1)) * 24 * 60 * 60);}
413 Result
:= DateTimeToUnix(DateTime
);
417 function ReadLineFromStream(Stream
: TStream
): string;
418 var S
: string; B
: char;
423 B
:= Char(Stream
.ReadByte
);
424 if not (B
in [#10, #13]) then S
:= S
+ B
;
431 function WriteLineToStream(Stream
: TStream
; Line
: string): boolean;
437 Stream
.WriteBuffer(PChar(Line
)^, Length(Line
));
444 { Object constructors/destructors: }
446 constructor TArgumentParser
.Create(RawArguments
: array of string; AllowedPrefixes
: array of string);
449 for i
:= 0 to Length(RawArguments
) - 1 do
450 ParseArgument(RawArguments
[i
], AllowedPrefixes
);
453 destructor TArgumentParser
.Destroy
;
455 SetLength(Arguments
, 0);
458 constructor TNamedObject
.Create(const Name
: string; Config
: TINIFile
; const Section
: string);
462 FAliases
:= TStringList
.Create
;
463 FAliases
.Delimiter
:= ',';
464 FAliases
.DelimitedText
:= FName
+ ',' + Config
.ReadString(Section
, 'Alias', '');
467 constructor TMainServerConfig
.Create(Config
: TINIFile
);
468 var i
: integer; rawaddresslist
: string; portlist
: TStringList
;
470 inherited Create(Config
.ReadString('Server', 'Name', ''), Config
, 'Server');
471 FListenAddresses
:= TStringList
.Create
;
472 FListenAddresses
.Delimiter
:= ',';
474 rawaddresslist
:= Config
.ReadString('Server', 'ListenAddress', '');
475 if rawaddresslist
<> '' then
476 FListenAddresses
.DelimitedText
:= rawaddresslist
478 portlist
:= TStringList
.Create
;
479 portlist
.Delimiter
:= ',';
480 portlist
.DelimitedText
:= Config
.ReadString('Server', 'ListenPort', '25');
481 for i
:= 0 to portlist
.Count
- 1 do
482 FListenAddresses
.Add('0.0.0.0:' + portlist
.Strings
[i
]);
486 FDatabytes
:= Config
.ReadInteger('Server', 'Databytes', 1024 * 1024 * 1024);
487 FTimeOffset
:= Config
.ReadInteger('Server', 'TimeOffset', Config
.ReadInteger('Server', 'TimeCorrection', 0) * 100);
488 FTimeOffsetStr
:= MakeTimeOffsetStr(FTimeOffset
);
490 FPolicies
:= Config
.ReadBool('Server', 'Policies', false);
491 FMailbox
:= Config
.ReadBool('Server', 'Mailbox', false);
492 FRelay
:= Config
.ReadBool('Server', 'Relay', false);
493 FLog
:= Config
.ReadBool('Server', 'Log', false);
496 constructor TEMailProperties
.Create
;
503 constructor TIPNamePair
.Create(const Name
, IP
: string);
509 constructor TEnvelope
.Create
;
513 FReturnPathSpecified
:= false;
515 SetLength(FRecipients
, 0);
518 destructor TEnvelope
.Destroy
;
520 SetLength(FRecipients
, 0);
527 procedure TArgumentParser
.ParseArgument(Arg
: string; const AllowedPrefixes
: array of string);
528 var i
, n
: integer; found
: boolean;
530 { Strip prefix if present. }
531 i
:= 0; found
:= false;
532 while ((i
< Length(AllowedPrefixes
)) and (not found
)) do begin
533 if pos(AllowedPrefixes
[i
], Arg
) = 1 then
535 Delete(Arg
, 1, Length(AllowedPrefixes
[i
]));
541 n
:= Length(Arguments
);
542 SetLength(Arguments
, n
+ 1);
543 SplitParameters(Arg
, Arguments
[n
].Option
, Arguments
[n
].Value
, '=');
544 { To be case-insensitive: }
545 Arguments
[n
].Option
:= UpCase(Arguments
[n
].Option
);
548 function TArgumentParser
.GetArgument(ID
: integer): TArgument
;
550 { No index checking... you'd better use it return value of ValidateArguments. }
551 Result
:= Arguments
[ID
];
554 function TArgumentParser
.IsPresent(ArgumentName
: string): boolean;
558 while (i
< Length(Arguments
)) and (Arguments
[i
].Option
<> UpCase(ArgumentName
)) do
560 Result
:= i
< Length(Arguments
);
563 function TArgumentParser
.GetValue(ArgumentName
: string; DefValue
: string = ''): string;
567 while (i
< Length(Arguments
)) and (Arguments
[i
].Option
<> UpCase(ArgumentName
)) do
570 if i
< Length(Arguments
) then begin
571 if Arguments
[i
].Value
<> '' then
572 Result
:= Arguments
[i
].Value
580 function TArgumentParser
.ValidateArguments(ValidArguments
: array of string): integer;
581 { Returns -1 if all arguments are valid. Otherwise, returns the ID of the first
586 while (i
< Length(Arguments
)) and InStringArray(Arguments
[i
].Option
, ValidArguments
) do
589 if i
>= Length(Arguments
) then
596 function TNamedObject
.IsItYourName(const Name
: string): boolean;
598 Result
:= FAliases
.IndexOf(Name
) <> -1;
602 function TMainServerConfig
.GetVersionStr
: string;
604 Result
:= VERSION_STR
;
608 function TIPNamePair
.Copy
: TIPNamePair
;
610 Result
:= TIPNamePair
.Create(Name
, IP
);
614 procedure TEMailProperties
.SetSize(Value
: longint);
619 procedure TEMailProperties
.WriteFlags(Value
: TEMailFlags
);
624 procedure TEMailProperties
.SetFlag(Flag
: TEMailFlags
);
626 FFlags
:= FFlags
or Flag
;
629 function TEMailProperties
.HasFlag(Flag
: TEMailFlags
): boolean;
631 Result
:= (FFlags
and Flag
) = Flag
;
635 function TEnvelope
.GetNumberOfRecipients
: integer;
637 Result
:= Length(FRecipients
);
640 function TEnvelope
.GetRecipient(Index
: integer): TRecipient
;
642 Result
:= FRecipients
[Index
];
645 function TEnvelope
.IsComplete
: boolean;
647 Result
:= FReturnPathSpecified
and (Length(FRecipients
) > 0);
650 procedure TEnvelope
.AddRecipient(Address
: string; Data
: integer = 0; RMsg
: string = '');
653 i
:= Length(FRecipients
);
654 SetLength(FRecipients
, i
+ 1);
655 FRecipients
[i
].Address
:= Address
;
656 FRecipients
[i
].RMsg
:= RMsg
;
657 FRecipients
[i
].Data
:= Data
;
660 procedure TEnvelope
.AddRecipient(Recipient
: TRecipient
);
663 i
:= Length(FRecipients
);
664 SetLength(FRecipients
, i
+ 1);
665 FRecipients
[i
]:= Recipient
;
668 procedure TEnvelope
.SetRecipientData(Index
, Data
: integer; RMsg
: string = '');
670 FRecipients
[Index
].RMsg
:= RMsg
;
671 FRecipients
[Index
].Data
:= Data
;
674 procedure TEnvelope
.SetAllRecipientData(Data
: integer; RMsg
: string = '');
677 for i
:= 0 to Length(FRecipients
) - 1 do
678 SetRecipientData(i
, Data
, RMsg
);
681 procedure TEnvelope
.SetReturnPath(Address
: string);
683 FReturnPath
:= Address
;
684 FReturnPathSpecified
:= true;
687 procedure TEnvelope
.SetRelayHost(HostName
: string);
689 FRelayHost
:= HostName
;