2 Copyright (C) 2010-2015 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 FListenPorts
: TStrings
;
78 function GetVersionStr
: string;
79 property ListenPorts
: TStrings read FListenPorts
;
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 SetRelayHost(HostName
: string);
142 property ReturnPath
: string read FReturnPath write SetReturnPath
;
143 property RelayHost
: string read FRelayHost write SetRelayHost
;
147 TEnvelopeArray
= array of TEnvelope
;
150 function EMailUserName(EMail
: string): string;
151 function EMailHost(EMail
: string): string;
152 function CleanEMailAddress(EMail
: string): string;
153 function IsValidEMailAddress(EMail
: string): boolean;
154 function EMailTimeStamp(DateTime
: TDateTime
): string;
155 function EMailTimeStampCorrected(DateTime
: TDateTime
): string;
156 function StatusToStr(Status
: integer): string;
157 procedure AssignDeliveryStatusToSMTPCodes(Envelope
: TEnvelope
);
159 function CleanEOLN(S
: string): string;
160 function GenerateRandomString(Length
: integer): string;
161 function GetAlphabetStr
: string;
162 function GetServiceCodeStr(Ctrl
: dword
): string;
163 function GetWinMajorVersion
: longword
;
164 function IsPrintableString(S
: string): boolean;
165 function UnixTimeStamp(DateTime
: TDateTime
): TUnixTimeStamp
;
166 function CmdlineToStringArray
: TStringArray
;
167 procedure SplitParameters(S
: string; var FirstPrm
, Remainder
: string; Separator
: char = #32);
169 function ReadLineFromStream(Stream
: TStream
): string;
170 function WriteLineToStream(Stream
: TStream
; Line
: string): boolean;
176 VERSION_STR
= '0.9t';
187 { Delivery statuses: }
188 DS_DELIVERED
= 1 shl 10;
189 DS_DELAYED
= 1 shl 11;
190 DS_PERMANENT
= 1 shl 12;
191 DS_INTERNALFAIL
= 1 shl 13;
192 DS_CONNECTIONFAIL
= 1 shl 14;
193 DS_UNEXPECTEDFAIL
= 1 shl 15;
194 DS_SMTPFAIL
= 1 shl 16;
195 DS_SMTPREPLYMASK
= $000003FF;
196 DS_ALLFLAGS
= $FFFFFFFF;
198 { E-mail property flags: }
201 DayNames
: array[1..7] of shortstring
= ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
202 MonthNames
: array[1..12] of shortstring
= ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
203 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
205 { Support for PRESHUTDOWN is not yet present in the Free Pascal library,
206 therefore I define the necessary constants here. It's a temporary
207 solution, I hope I won't need it for the next release of FPC. }
208 SERVICE_ACCEPT_PRESHUTDOWN
= $00000100;
209 SERVICE_CONTROL_PRESHUTDOWN
= $0000000F;
214 MainServerConfig
: TMainServerConfig
;
220 { Unit-private functions/prodecures: }
222 function InStringArray(const S
: string; const SA
: array of string): boolean;
226 while (i
< Length(SA
)) and (SA
[i
] <> S
) do Inc(i
);
227 Result
:= i
< Length(SA
);
230 function MakeTimeOffsetStr(TimeOffset
: integer): string;
231 var CorrS
: string; CorrI
: integer;
234 CorrS
:= IntToStr(Abs(CorrI
));
235 while Length(CorrS
) < 4 do CorrS
:= '0' + CorrS
;
236 if CorrI
>= 0 then CorrS
:= '+' + CorrS
else CorrS
:= '-' + CorrS
;
241 { Unit-public functions/procedures: }
243 function EMailUserName(EMail
: string): string;
247 while (p
> 0) and (EMail
[p
] <> '@') do Dec(p
);
249 Result
:= Copy(EMail
, 1, p
- 1);
254 function EMailHost(EMail
: string): string;
258 while (p
> 0) and (EMail
[p
] <> '@') do Dec(p
);
259 if (p
<> 0) and (p
< Length(EMail
)) then begin
260 Result
:= Copy(EMail
, p
+ 1, Length(EMail
) - p
);
265 function CleanEMailAddress(EMail
: string): string;
266 var po
, pc
, p
: integer;
268 po
:= Pos('<', EMail
);
269 pc
:= Pos('>', EMail
);
270 if (po
<> 0) and (pc
<> 0) and (po
< pc
) then begin
271 Result
:= Copy(EMail
, po
+ 1, pc
- po
- 1);
272 p
:= Pos(':', Result
);
274 Result
:= Copy(Result
, p
+ 1, Length(Result
) - p
);
280 function IsValidEMailAddress(EMail
: string): boolean;
282 { !!! TODO: Implement more strict checking later !!! }
283 Result
:= Pos('@', EMail
) <> 0;
286 function EMailTimeStamp(DateTime
: TDateTime
): string;
287 var Year
, Month
, Day
: word;
289 DecodeDate(DateTime
, Year
, Month
, Day
);
290 Result
:= DayNames
[DayOfWeek(DateTime
)] + ' ' + MonthNames
[Month
] + ' '
291 + FormatDateTime('dd hh:nn:ss', DateTime
) + ' ' + IntToStr(Year
);
294 function EMailTimeStampCorrected(DateTime
: TDateTime
): string;
296 Result
:= EMailTimeStamp(DateTime
) + ' ' + MainServerConfig
.TimeOffsetStr
;
299 function StatusToStr(Status
: integer): string;
300 { Returns the delivery status code in human-readable format. }
302 Result
:= IntToStr(Status
and (DS_ALLFLAGS
- DS_SMTPREPLYMASK
- DS_SMTPFAIL
))
303 + '+' + IntToStr(Status
and DS_SMTPREPLYMASK
);
306 procedure AssignDeliveryStatusToSMTPCodes(Envelope
: TEnvelope
);
307 var i
, code
, cond
, status
: integer; Recipient
: TRecipient
;
309 for i
:= 0 to Envelope
.GetNumberOfRecipients
- 1 do begin
310 Recipient
:= Envelope
.GetRecipient(i
);
311 code
:= Recipient
.Data
and DS_SMTPREPLYMASK
;
314 0: status
:= DS_DELAYED
or DS_UNEXPECTEDFAIL
;
315 2: status
:= DS_DELIVERED
;
316 4: status
:= DS_DELAYED
;
317 5: status
:= DS_PERMANENT
;
318 else status
:= DS_PERMANENT
or DS_UNEXPECTEDFAIL
;
320 if code
<> 0 then status
:= status
or DS_SMTPFAIL
;
321 Envelope
.SetRecipientData(i
, code
or status
, Recipient
.RMsg
);
326 function CleanEOLN(S
: string): string;
328 while (Length(S
) <> 0) and (S
[Length(S
)] in [#13, #10]) do Delete(S
, Length(S
), 1);
332 function GenerateRandomString(Length
: integer): string;
333 var What
, Chrn
, i
: integer; Value
: string;
336 for i
:= 1 to Length
do begin
339 0: begin Chrn
:= Random(10)+48; Value
:= Value
+ Chr(Chrn
); end;
340 1: begin Chrn
:= Random(26)+65; Value
:= Value
+ Chr(Chrn
); end;
341 2: begin Chrn
:= Random(26)+97; Value
:= Value
+ Chr(Chrn
); end;
347 function GetAlphabetStr
: string;
351 for i
:= Ord('0') to Ord('9') do Result
:= Result
+ Chr(i
);
352 for i
:= Ord('A') to Ord('Z') do Result
:= Result
+ Chr(i
);
355 function GetServiceCodeStr(Ctrl
: dword
): string;
358 SERVICE_CONTROL_STOP
: Result
:= 'STOP';
359 SERVICE_CONTROL_SHUTDOWN
: Result
:= 'SHUTDOWN';
360 SERVICE_CONTROL_PRESHUTDOWN
: Result
:= 'PRESHUTDOWN';
361 else Result
:= IntToStr(Ctrl
);
365 function GetWinMajorVersion
: longword
;
366 var OSVersionInfo
: TOSVersionInfo
;
368 { Get OS version info. }
369 OSVersionInfo
.dwOSVersionInfoSize
:= SizeOf(TOSVersionInfo
);
370 GetVersionEx(OSVersionInfo
);
371 Result
:= OSVersionInfo
.dwMajorVersion
;
374 function IsPrintableString(S
: string): boolean;
375 { Check if string contains only printable ASCII characters. }
380 while Result
and (i
<= Length(S
)) do begin
381 Result
:= (Ord(S
[i
]) > 31) and (Ord(S
[i
]) < 127);
386 procedure SplitParameters(S
: string; var FirstPrm
, Remainder
: string; Separator
: char = #32);
389 i
:= pos(Separator
, S
);
391 FirstPrm
:= Copy(S
, 1, i
- 1);
392 Remainder
:= Copy(S
, i
+ 1, Length(S
) - i
);
400 function CmdlineToStringArray
: TStringArray
;
403 SetLength(Result
, ParamCount
);
404 for i
:= 1 to ParamCount
do
405 Result
[i
-1]:= ParamStr(i
);
408 function UnixTimeStamp(DateTime
: TDateTime
): TUnixTimeStamp
;
410 {Result:= Trunc((DateTime - EncodeDate(1970, 1 ,1)) * 24 * 60 * 60);}
411 Result
:= DateTimeToUnix(DateTime
);
415 function ReadLineFromStream(Stream
: TStream
): string;
416 var S
: string; B
: char;
421 B
:= Char(Stream
.ReadByte
);
422 if not (B
in [#10, #13]) then S
:= S
+ B
;
429 function WriteLineToStream(Stream
: TStream
; Line
: string): boolean;
435 Stream
.WriteBuffer(PChar(Line
)^, Length(Line
));
442 { Object constructors/destructors: }
444 constructor TArgumentParser
.Create(RawArguments
: array of string; AllowedPrefixes
: array of string);
447 for i
:= 0 to Length(RawArguments
) - 1 do
448 ParseArgument(RawArguments
[i
], AllowedPrefixes
);
451 destructor TArgumentParser
.Destroy
;
453 SetLength(Arguments
, 0);
456 constructor TNamedObject
.Create(const Name
: string; Config
: TINIFile
; const Section
: string);
460 FAliases
:= TStringList
.Create
;
461 FAliases
.Delimiter
:= ',';
462 FAliases
.DelimitedText
:= FName
+ ',' + Config
.ReadString(Section
, 'Alias', '');
465 constructor TMainServerConfig
.Create(Config
: TINIFile
);
467 inherited Create(Config
.ReadString('Server', 'Name', ''), Config
, 'Server');
468 FListenPorts
:= TStringList
.Create
;
469 FListenPorts
.Delimiter
:= ',';
470 FListenPorts
.DelimitedText
:= Config
.ReadString('Server', 'ListenPort', '25');
472 FDatabytes
:= Config
.ReadInteger('Server', 'Databytes', 1024 * 1024 * 1024);
473 {FTimeCorrection:= Config.ReadInteger('Server', 'TimeCorrection', 0);}
474 FTimeOffset
:= Config
.ReadInteger('Server', 'TimeOffset', Config
.ReadInteger('Server', 'TimeCorrection', 0) * 100);
475 FTimeOffsetStr
:= MakeTimeOffsetStr(FTimeOffset
);
477 FPolicies
:= Config
.ReadBool('Server', 'Policies', false);
478 FMailbox
:= Config
.ReadBool('Server', 'Mailbox', false);
479 FRelay
:= Config
.ReadBool('Server', 'Relay', false);
480 FLog
:= Config
.ReadBool('Server', 'Log', false);
483 constructor TEMailProperties
.Create
;
490 constructor TIPNamePair
.Create(const Name
, IP
: string);
496 constructor TEnvelope
.Create
;
500 FReturnPathSpecified
:= false;
502 SetLength(FRecipients
, 0);
505 destructor TEnvelope
.Destroy
;
507 SetLength(FRecipients
, 0);
514 procedure TArgumentParser
.ParseArgument(Arg
: string; const AllowedPrefixes
: array of string);
515 var i
, n
: integer; found
: boolean;
517 { Strip prefix if present. }
518 i
:= 0; found
:= false;
519 while ((i
< Length(AllowedPrefixes
)) and (not found
)) do begin
520 if pos(AllowedPrefixes
[i
], Arg
) = 1 then
522 Delete(Arg
, 1, Length(AllowedPrefixes
[i
]));
528 n
:= Length(Arguments
);
529 SetLength(Arguments
, n
+ 1);
530 SplitParameters(Arg
, Arguments
[n
].Option
, Arguments
[n
].Value
, '=');
531 { To be case-insensitive: }
532 Arguments
[n
].Option
:= UpCase(Arguments
[n
].Option
);
535 function TArgumentParser
.GetArgument(ID
: integer): TArgument
;
537 { No index checking... you'd better use it return value of ValidateArguments. }
538 Result
:= Arguments
[ID
];
541 function TArgumentParser
.IsPresent(ArgumentName
: string): boolean;
545 while (i
< Length(Arguments
)) and (Arguments
[i
].Option
<> UpCase(ArgumentName
)) do
547 Result
:= i
< Length(Arguments
);
550 function TArgumentParser
.GetValue(ArgumentName
: string; DefValue
: string = ''): string;
554 while (i
< Length(Arguments
)) and (Arguments
[i
].Option
<> UpCase(ArgumentName
)) do
557 if i
< Length(Arguments
) then begin
558 if Arguments
[i
].Value
<> '' then
559 Result
:= Arguments
[i
].Value
567 function TArgumentParser
.ValidateArguments(ValidArguments
: array of string): integer;
568 { Returns -1 if all arguments are valid. Otherwise, returns the ID of the first
573 while (i
< Length(Arguments
)) and InStringArray(Arguments
[i
].Option
, ValidArguments
) do
576 if i
>= Length(Arguments
) then
583 function TNamedObject
.IsItYourName(const Name
: string): boolean;
585 Result
:= FAliases
.IndexOf(Name
) <> -1;
589 function TMainServerConfig
.GetVersionStr
: string;
591 Result
:= VERSION_STR
;
595 function TIPNamePair
.Copy
: TIPNamePair
;
597 Result
:= TIPNamePair
.Create(Name
, IP
);
601 procedure TEMailProperties
.SetSize(Value
: longint);
606 procedure TEMailProperties
.WriteFlags(Value
: TEMailFlags
);
611 procedure TEMailProperties
.SetFlag(Flag
: TEMailFlags
);
613 FFlags
:= FFlags
or Flag
;
616 function TEMailProperties
.HasFlag(Flag
: TEMailFlags
): boolean;
618 Result
:= (FFlags
and Flag
) = Flag
;
622 function TEnvelope
.GetNumberOfRecipients
: integer;
624 Result
:= Length(FRecipients
);
627 function TEnvelope
.GetRecipient(Index
: integer): TRecipient
;
629 Result
:= FRecipients
[Index
];
632 function TEnvelope
.IsComplete
: boolean;
634 Result
:= FReturnPathSpecified
and (Length(FRecipients
) > 0);
637 procedure TEnvelope
.AddRecipient(Address
: string; Data
: integer = 0; RMsg
: string = '');
640 i
:= Length(FRecipients
);
641 SetLength(FRecipients
, i
+ 1);
642 FRecipients
[i
].Address
:= Address
;
643 FRecipients
[i
].RMsg
:= RMsg
;
644 FRecipients
[i
].Data
:= Data
;
647 procedure TEnvelope
.AddRecipient(Recipient
: TRecipient
);
650 i
:= Length(FRecipients
);
651 SetLength(FRecipients
, i
+ 1);
652 FRecipients
[i
]:= Recipient
;
655 procedure TEnvelope
.SetRecipientData(Index
, Data
: integer; RMsg
: string = '');
657 FRecipients
[Index
].RMsg
:= RMsg
;
658 FRecipients
[Index
].Data
:= Data
;
661 procedure TEnvelope
.SetReturnPath(Address
: string);
663 FReturnPath
:= Address
;
664 FReturnPathSpecified
:= true;
667 procedure TEnvelope
.SetRelayHost(HostName
: string);
669 FRelayHost
:= HostName
;