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
;
79 function GetVersionStr
: string;
80 property ListenAddresses
: TStrings read FListenAddresses
;
81 property BindAddress
: string read FBindAddress
;
82 property Databytes
: longint read FDatabytes
;
83 {property TimeCorrection: integer read FTimeCorrection;}
84 property TimeOffset
: integer read FTimeOffset
;
85 property TimeOffsetStr
: string read FTimeOffsetStr
;
86 property Policies
: boolean read FPolicies
;
87 property Mailbox
: boolean read FMailbox
;
88 property Relay
: boolean read FRelay
;
89 property Log
: boolean read FLog
;
90 property VersionStr
: string read GetVersionStr
;
96 TEMailProperties
= class
102 procedure SetSize(Value
: longint);
103 procedure WriteFlags(Value
: TEMailFlags
);
104 procedure SetFlag(Flag
: TEMailFlags
);
105 function HasFlag(Flag
: TEMailFlags
): boolean;
106 property Size
: longint read FSize write SetSize
;
107 property Flags
: TEMailFlags read FFlags write WriteFlags
;
112 Address
, RMsg
: string;
118 constructor Create(const Name
, IP
: string);
122 property Name
: string read FName
;
123 property IP
: string read FIP
;
124 function Copy
: TIPNamePair
;
130 destructor Destroy
; override;
132 FReturnPath
, FRelayHost
: string;
133 FReturnPathSpecified
: boolean;
134 FRecipients
: array of TRecipient
;
136 function GetNumberOfRecipients
: integer;
137 function GetRecipient(Index
: integer): TRecipient
;
138 function IsComplete
: boolean;
139 procedure AddRecipient(Address
: string; Data
: integer = 0; RMsg
: string = ''); overload
;
140 procedure AddRecipient(Recipient
: TRecipient
); overload
;
141 procedure SetReturnPath(Address
: string);
142 procedure SetRecipientData(Index
, Data
: integer; RMsg
: string = '');
143 procedure SetAllRecipientData(Data
: integer; RMsg
: string = '');
144 procedure SetRelayHost(HostName
: string);
145 property ReturnPath
: string read FReturnPath write SetReturnPath
;
146 property RelayHost
: string read FRelayHost write SetRelayHost
;
150 TEnvelopeArray
= array of TEnvelope
;
153 function EMailUserName(EMail
: string): string;
154 function EMailHost(EMail
: string): string;
155 function CleanEMailAddress(EMail
: string): string;
156 function IsValidEMailAddress(EMail
: string): boolean;
157 function EMailTimeStamp(DateTime
: TDateTime
): string;
158 function EMailTimeStampCorrected(DateTime
: TDateTime
): string;
159 function StatusToStr(Status
: integer): string;
160 procedure AssignDeliveryStatusToSMTPCodes(Envelope
: TEnvelope
; TransactionComplete
: boolean);
162 function CleanEOLN(S
: string): string;
163 function GenerateRandomString(Length
: integer): string;
164 function GetAlphabetStr
: string;
165 function GetServiceCodeStr(Ctrl
: dword
): string;
166 function GetWinMajorVersion
: longword
;
167 function IsPrintableString(S
: string): boolean;
168 function UnixTimeStamp(DateTime
: TDateTime
): TUnixTimeStamp
;
169 function CmdlineToStringArray
: TStringArray
;
170 procedure SplitParameters(S
: string; var FirstPrm
, Remainder
: string; Separator
: char = #32);
172 function ReadLineFromStream(Stream
: TStream
): string;
173 function WriteLineToStream(Stream
: TStream
; Line
: string): boolean;
179 VERSION_STR
= '0.9t';
190 { Delivery statuses: }
191 DS_DELIVERED
= 1 shl 10;
192 DS_DELAYED
= 1 shl 11;
193 DS_PERMANENT
= 1 shl 12;
194 DS_INTERNALFAIL
= 1 shl 13;
195 DS_CONNECTIONFAIL
= 1 shl 14;
196 DS_UNEXPECTEDFAIL
= 1 shl 15;
197 DS_SMTPFAIL
= 1 shl 16;
198 DS_SMTPREPLYMASK
= $000003FF;
199 DS_ALLFLAGS
= $FFFFFFFF;
201 { E-mail property flags: }
204 DayNames
: array[1..7] of shortstring
= ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
205 MonthNames
: array[1..12] of shortstring
= ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
206 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
208 { Support for PRESHUTDOWN is not yet present in the Free Pascal library,
209 therefore I define the necessary constants here. It's a temporary
210 solution, I hope I won't need it for the next release of FPC. }
211 SERVICE_ACCEPT_PRESHUTDOWN
= $00000100;
212 SERVICE_CONTROL_PRESHUTDOWN
= $0000000F;
217 MainServerConfig
: TMainServerConfig
;
223 { Unit-private functions/prodecures: }
225 function InStringArray(const S
: string; const SA
: array of string): boolean;
229 while (i
< Length(SA
)) and (SA
[i
] <> S
) do Inc(i
);
230 Result
:= i
< Length(SA
);
233 function MakeTimeOffsetStr(TimeOffset
: integer): string;
234 var CorrS
: string; CorrI
: integer;
237 CorrS
:= IntToStr(Abs(CorrI
));
238 while Length(CorrS
) < 4 do CorrS
:= '0' + CorrS
;
239 if CorrI
>= 0 then CorrS
:= '+' + CorrS
else CorrS
:= '-' + CorrS
;
244 { Unit-public functions/procedures: }
246 function EMailUserName(EMail
: string): string;
250 while (p
> 0) and (EMail
[p
] <> '@') do Dec(p
);
252 Result
:= Copy(EMail
, 1, p
- 1);
257 function EMailHost(EMail
: string): string;
261 while (p
> 0) and (EMail
[p
] <> '@') do Dec(p
);
262 if (p
<> 0) and (p
< Length(EMail
)) then begin
263 Result
:= Copy(EMail
, p
+ 1, Length(EMail
) - p
);
268 function CleanEMailAddress(EMail
: string): string;
269 var po
, pc
, p
: integer;
271 po
:= Pos('<', EMail
);
272 pc
:= Pos('>', EMail
);
273 if (po
<> 0) and (pc
<> 0) and (po
< pc
) then begin
274 Result
:= Copy(EMail
, po
+ 1, pc
- po
- 1);
275 p
:= Pos(':', Result
);
277 Result
:= Copy(Result
, p
+ 1, Length(Result
) - p
);
283 function IsValidEMailAddress(EMail
: string): boolean;
285 { !!! TODO: Implement more strict checking later !!! }
286 Result
:= Pos('@', EMail
) <> 0;
289 function EMailTimeStamp(DateTime
: TDateTime
): string;
290 var Year
, Month
, Day
: word;
292 DecodeDate(DateTime
, Year
, Month
, Day
);
293 Result
:= DayNames
[DayOfWeek(DateTime
)] + ' ' + MonthNames
[Month
] + ' '
294 + FormatDateTime('dd hh:nn:ss', DateTime
) + ' ' + IntToStr(Year
);
297 function EMailTimeStampCorrected(DateTime
: TDateTime
): string;
299 Result
:= EMailTimeStamp(DateTime
) + ' ' + MainServerConfig
.TimeOffsetStr
;
302 function StatusToStr(Status
: integer): string;
303 { Returns the delivery status code in human-readable format. }
305 Result
:= IntToStr(Status
and (DS_ALLFLAGS
- DS_SMTPREPLYMASK
- DS_SMTPFAIL
))
306 + '+' + IntToStr(Status
and DS_SMTPREPLYMASK
);
309 procedure AssignDeliveryStatusToSMTPCodes(Envelope
: TEnvelope
; TransactionComplete
: boolean);
310 var i
, code
, cond
, status
: integer; Recipient
: TRecipient
;
312 for i
:= 0 to Envelope
.GetNumberOfRecipients
- 1 do begin
313 Recipient
:= Envelope
.GetRecipient(i
);
314 code
:= Recipient
.Data
and DS_SMTPREPLYMASK
;
317 0: status
:= DS_DELAYED
or DS_UNEXPECTEDFAIL
;
318 2: if TransactionComplete
then status
:= DS_DELIVERED
319 else status
:= DS_DELAYED
or DS_UNEXPECTEDFAIL
;
320 4: status
:= DS_DELAYED
;
321 5: status
:= DS_PERMANENT
;
322 else status
:= DS_PERMANENT
or DS_UNEXPECTEDFAIL
;
324 if code
<> 0 then status
:= status
or DS_SMTPFAIL
;
325 Envelope
.SetRecipientData(i
, code
or status
, Recipient
.RMsg
);
330 function CleanEOLN(S
: string): string;
332 while (Length(S
) <> 0) and (S
[Length(S
)] in [#13, #10]) do Delete(S
, Length(S
), 1);
336 function GenerateRandomString(Length
: integer): string;
337 var What
, Chrn
, i
: integer; Value
: string;
340 for i
:= 1 to Length
do begin
343 0: begin Chrn
:= Random(10)+48; Value
:= Value
+ Chr(Chrn
); end;
344 1: begin Chrn
:= Random(26)+65; Value
:= Value
+ Chr(Chrn
); end;
345 2: begin Chrn
:= Random(26)+97; Value
:= Value
+ Chr(Chrn
); end;
351 function GetAlphabetStr
: string;
355 for i
:= Ord('0') to Ord('9') do Result
:= Result
+ Chr(i
);
356 for i
:= Ord('A') to Ord('Z') do Result
:= Result
+ Chr(i
);
359 function GetServiceCodeStr(Ctrl
: dword
): string;
362 SERVICE_CONTROL_STOP
: Result
:= 'STOP';
363 SERVICE_CONTROL_SHUTDOWN
: Result
:= 'SHUTDOWN';
364 SERVICE_CONTROL_PRESHUTDOWN
: Result
:= 'PRESHUTDOWN';
365 else Result
:= IntToStr(Ctrl
);
369 function GetWinMajorVersion
: longword
;
370 var OSVersionInfo
: TOSVersionInfo
;
372 { Get OS version info. }
373 OSVersionInfo
.dwOSVersionInfoSize
:= SizeOf(TOSVersionInfo
);
374 GetVersionEx(OSVersionInfo
);
375 Result
:= OSVersionInfo
.dwMajorVersion
;
378 function IsPrintableString(S
: string): boolean;
379 { Check if string contains only printable ASCII characters. }
384 while Result
and (i
<= Length(S
)) do begin
385 Result
:= (Ord(S
[i
]) > 31) and (Ord(S
[i
]) < 127);
390 procedure SplitParameters(S
: string; var FirstPrm
, Remainder
: string; Separator
: char = #32);
393 i
:= pos(Separator
, S
);
395 FirstPrm
:= Copy(S
, 1, i
- 1);
396 Remainder
:= Copy(S
, i
+ 1, Length(S
) - i
);
404 function CmdlineToStringArray
: TStringArray
;
407 SetLength(Result
, ParamCount
);
408 for i
:= 1 to ParamCount
do
409 Result
[i
-1]:= ParamStr(i
);
412 function UnixTimeStamp(DateTime
: TDateTime
): TUnixTimeStamp
;
414 {Result:= Trunc((DateTime - EncodeDate(1970, 1 ,1)) * 24 * 60 * 60);}
415 Result
:= DateTimeToUnix(DateTime
);
419 function ReadLineFromStream(Stream
: TStream
): string;
420 var S
: string; B
: char;
425 B
:= Char(Stream
.ReadByte
);
426 if not (B
in [#10, #13]) then S
:= S
+ B
;
433 function WriteLineToStream(Stream
: TStream
; Line
: string): boolean;
439 Stream
.WriteBuffer(PChar(Line
)^, Length(Line
));
446 { Object constructors/destructors: }
448 constructor TArgumentParser
.Create(RawArguments
: array of string; AllowedPrefixes
: array of string);
451 for i
:= 0 to Length(RawArguments
) - 1 do
452 ParseArgument(RawArguments
[i
], AllowedPrefixes
);
455 destructor TArgumentParser
.Destroy
;
457 SetLength(Arguments
, 0);
460 constructor TNamedObject
.Create(const Name
: string; Config
: TINIFile
; const Section
: string);
464 FAliases
:= TStringList
.Create
;
465 FAliases
.Delimiter
:= ',';
466 FAliases
.DelimitedText
:= FName
+ ',' + Config
.ReadString(Section
, 'Alias', '');
469 constructor TMainServerConfig
.Create(Config
: TINIFile
);
470 var i
: integer; rawaddresslist
: string; portlist
: TStringList
;
472 inherited Create(Config
.ReadString('Server', 'Name', ''), Config
, 'Server');
473 FListenAddresses
:= TStringList
.Create
;
474 FListenAddresses
.Delimiter
:= ',';
476 rawaddresslist
:= Config
.ReadString('Server', 'ListenAddress', '');
477 if rawaddresslist
<> '' then
478 FListenAddresses
.DelimitedText
:= rawaddresslist
480 portlist
:= TStringList
.Create
;
481 portlist
.Delimiter
:= ',';
482 portlist
.DelimitedText
:= Config
.ReadString('Server', 'ListenPort', '25');
483 for i
:= 0 to portlist
.Count
- 1 do
484 FListenAddresses
.Add('0.0.0.0:' + portlist
.Strings
[i
]);
488 FBindAddress
:= Config
.ReadString('Server', 'BindAddress', '0.0.0.0');
490 FDatabytes
:= Config
.ReadInteger('Server', 'Databytes', 1024 * 1024 * 1024);
491 FTimeOffset
:= Config
.ReadInteger('Server', 'TimeOffset', Config
.ReadInteger('Server', 'TimeCorrection', 0) * 100);
492 FTimeOffsetStr
:= MakeTimeOffsetStr(FTimeOffset
);
494 FPolicies
:= Config
.ReadBool('Server', 'Policies', false);
495 FMailbox
:= Config
.ReadBool('Server', 'Mailbox', false);
496 FRelay
:= Config
.ReadBool('Server', 'Relay', false);
497 FLog
:= Config
.ReadBool('Server', 'Log', false);
500 constructor TEMailProperties
.Create
;
507 constructor TIPNamePair
.Create(const Name
, IP
: string);
513 constructor TEnvelope
.Create
;
517 FReturnPathSpecified
:= false;
519 SetLength(FRecipients
, 0);
522 destructor TEnvelope
.Destroy
;
524 SetLength(FRecipients
, 0);
531 procedure TArgumentParser
.ParseArgument(Arg
: string; const AllowedPrefixes
: array of string);
532 var i
, n
: integer; found
: boolean;
534 { Strip prefix if present. }
535 i
:= 0; found
:= false;
536 while ((i
< Length(AllowedPrefixes
)) and (not found
)) do begin
537 if pos(AllowedPrefixes
[i
], Arg
) = 1 then
539 Delete(Arg
, 1, Length(AllowedPrefixes
[i
]));
545 n
:= Length(Arguments
);
546 SetLength(Arguments
, n
+ 1);
547 SplitParameters(Arg
, Arguments
[n
].Option
, Arguments
[n
].Value
, '=');
548 { To be case-insensitive: }
549 Arguments
[n
].Option
:= UpCase(Arguments
[n
].Option
);
552 function TArgumentParser
.GetArgument(ID
: integer): TArgument
;
554 { No index checking... you'd better use it return value of ValidateArguments. }
555 Result
:= Arguments
[ID
];
558 function TArgumentParser
.IsPresent(ArgumentName
: string): boolean;
562 while (i
< Length(Arguments
)) and (Arguments
[i
].Option
<> UpCase(ArgumentName
)) do
564 Result
:= i
< Length(Arguments
);
567 function TArgumentParser
.GetValue(ArgumentName
: string; DefValue
: string = ''): string;
571 while (i
< Length(Arguments
)) and (Arguments
[i
].Option
<> UpCase(ArgumentName
)) do
574 if i
< Length(Arguments
) then begin
575 if Arguments
[i
].Value
<> '' then
576 Result
:= Arguments
[i
].Value
584 function TArgumentParser
.ValidateArguments(ValidArguments
: array of string): integer;
585 { Returns -1 if all arguments are valid. Otherwise, returns the ID of the first
590 while (i
< Length(Arguments
)) and InStringArray(Arguments
[i
].Option
, ValidArguments
) do
593 if i
>= Length(Arguments
) then
600 function TNamedObject
.IsItYourName(const Name
: string): boolean;
602 Result
:= FAliases
.IndexOf(Name
) <> -1;
606 function TMainServerConfig
.GetVersionStr
: string;
608 Result
:= VERSION_STR
;
612 function TIPNamePair
.Copy
: TIPNamePair
;
614 Result
:= TIPNamePair
.Create(Name
, IP
);
618 procedure TEMailProperties
.SetSize(Value
: longint);
623 procedure TEMailProperties
.WriteFlags(Value
: TEMailFlags
);
628 procedure TEMailProperties
.SetFlag(Flag
: TEMailFlags
);
630 FFlags
:= FFlags
or Flag
;
633 function TEMailProperties
.HasFlag(Flag
: TEMailFlags
): boolean;
635 Result
:= (FFlags
and Flag
) = Flag
;
639 function TEnvelope
.GetNumberOfRecipients
: integer;
641 Result
:= Length(FRecipients
);
644 function TEnvelope
.GetRecipient(Index
: integer): TRecipient
;
646 Result
:= FRecipients
[Index
];
649 function TEnvelope
.IsComplete
: boolean;
651 Result
:= FReturnPathSpecified
and (Length(FRecipients
) > 0);
654 procedure TEnvelope
.AddRecipient(Address
: string; Data
: integer = 0; RMsg
: string = '');
657 i
:= Length(FRecipients
);
658 SetLength(FRecipients
, i
+ 1);
659 FRecipients
[i
].Address
:= Address
;
660 FRecipients
[i
].RMsg
:= RMsg
;
661 FRecipients
[i
].Data
:= Data
;
664 procedure TEnvelope
.AddRecipient(Recipient
: TRecipient
);
667 i
:= Length(FRecipients
);
668 SetLength(FRecipients
, i
+ 1);
669 FRecipients
[i
]:= Recipient
;
672 procedure TEnvelope
.SetRecipientData(Index
, Data
: integer; RMsg
: string = '');
674 FRecipients
[Index
].RMsg
:= RMsg
;
675 FRecipients
[Index
].Data
:= Data
;
678 procedure TEnvelope
.SetAllRecipientData(Data
: integer; RMsg
: string = '');
681 for i
:= 0 to Length(FRecipients
) - 1 do
682 SetRecipientData(i
, Data
, RMsg
);
685 procedure TEnvelope
.SetReturnPath(Address
: string);
687 FReturnPath
:= Address
;
688 FReturnPathSpecified
:= true;
691 procedure TEnvelope
.SetRelayHost(HostName
: string);
693 FRelayHost
:= HostName
;