2 Copyright (C) 2010-2014 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
: TStringArray
; AllowedPrefixes
: TStringArray
= []);
44 destructor Destroy
; override;
46 Arguments
: array of TArgument
;
47 procedure ParseArgument(Arg
: string; const AllowedPrefixes
: TStringArray
);
49 function GetArgument(ID
: integer): TArgument
;
50 function IsPresent(ArgumentName
: string): boolean;
51 function GetValue(ArgumentName
: string; DefValue
: string = ''): string;
52 function ValidateArguments(ValidArguments
: TStringArray
): 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.9s';
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 MakeTimeOffsetStr(TimeOffset
: integer): string;
223 var CorrS
: string; CorrI
: integer;
226 CorrS
:= IntToStr(Abs(CorrI
));
227 while Length(CorrS
) < 4 do CorrS
:= '0' + CorrS
;
228 if CorrI
>= 0 then CorrS
:= '+' + CorrS
else CorrS
:= '-' + CorrS
;
233 { Unit-public functions/procedures: }
235 function EMailUserName(EMail
: string): string;
239 while (p
> 0) and (EMail
[p
] <> '@') do Dec(p
);
241 Result
:= Copy(EMail
, 1, p
- 1);
246 function EMailHost(EMail
: string): string;
250 while (p
> 0) and (EMail
[p
] <> '@') do Dec(p
);
251 if (p
<> 0) and (p
< Length(EMail
)) then begin
252 Result
:= Copy(EMail
, p
+ 1, Length(EMail
) - p
);
257 function CleanEMailAddress(EMail
: string): string;
258 var po
, pc
, p
: integer;
260 po
:= Pos('<', EMail
);
261 pc
:= Pos('>', EMail
);
262 if (po
<> 0) and (pc
<> 0) and (po
< pc
) then begin
263 Result
:= Copy(EMail
, po
+ 1, pc
- po
- 1);
264 p
:= Pos(':', Result
);
266 Result
:= Copy(Result
, p
+ 1, Length(Result
) - p
);
272 function IsValidEMailAddress(EMail
: string): boolean;
274 { !!! TODO: Implement more strict checking later !!! }
275 Result
:= Pos('@', EMail
) <> 0;
278 function EMailTimeStamp(DateTime
: TDateTime
): string;
279 var Year
, Month
, Day
: word;
281 DecodeDate(DateTime
, Year
, Month
, Day
);
282 Result
:= DayNames
[DayOfWeek(DateTime
)] + ' ' + MonthNames
[Month
] + ' '
283 + FormatDateTime('dd hh:nn:ss', DateTime
) + ' ' + IntToStr(Year
);
286 function EMailTimeStampCorrected(DateTime
: TDateTime
): string;
288 Result
:= EMailTimeStamp(DateTime
) + ' ' + MainServerConfig
.TimeOffsetStr
;
291 function StatusToStr(Status
: integer): string;
292 { Returns the delivery status code in human-readable format. }
294 Result
:= IntToStr(Status
and (DS_ALLFLAGS
- DS_SMTPREPLYMASK
- DS_SMTPFAIL
))
295 + '+' + IntToStr(Status
and DS_SMTPREPLYMASK
);
298 procedure AssignDeliveryStatusToSMTPCodes(Envelope
: TEnvelope
);
299 var i
, code
, cond
, status
: integer; Recipient
: TRecipient
;
301 for i
:= 0 to Envelope
.GetNumberOfRecipients
- 1 do begin
302 Recipient
:= Envelope
.GetRecipient(i
);
303 code
:= Recipient
.Data
and DS_SMTPREPLYMASK
;
306 0: status
:= DS_DELAYED
or DS_UNEXPECTEDFAIL
;
307 2: status
:= DS_DELIVERED
;
308 4: status
:= DS_DELAYED
;
309 5: status
:= DS_PERMANENT
;
310 else status
:= DS_PERMANENT
or DS_UNEXPECTEDFAIL
;
312 if code
<> 0 then status
:= status
or DS_SMTPFAIL
;
313 Envelope
.SetRecipientData(i
, code
or status
, Recipient
.RMsg
);
318 function CleanEOLN(S
: string): string;
320 while (Length(S
) <> 0) and (S
[Length(S
)] in [#13, #10]) do Delete(S
, Length(S
), 1);
324 function GenerateRandomString(Length
: integer): string;
325 var What
, Chrn
, i
: integer; Value
: string;
328 for i
:= 1 to Length
do begin
331 0: begin Chrn
:= Random(10)+48; Value
:= Value
+ Chr(Chrn
); end;
332 1: begin Chrn
:= Random(26)+65; Value
:= Value
+ Chr(Chrn
); end;
333 2: begin Chrn
:= Random(26)+97; Value
:= Value
+ Chr(Chrn
); end;
339 function GetAlphabetStr
: string;
343 for i
:= Ord('0') to Ord('9') do Result
:= Result
+ Chr(i
);
344 for i
:= Ord('A') to Ord('Z') do Result
:= Result
+ Chr(i
);
347 function GetServiceCodeStr(Ctrl
: dword
): string;
350 SERVICE_CONTROL_STOP
: Result
:= 'STOP';
351 SERVICE_CONTROL_SHUTDOWN
: Result
:= 'SHUTDOWN';
352 SERVICE_CONTROL_PRESHUTDOWN
: Result
:= 'PRESHUTDOWN';
353 else Result
:= IntToStr(Ctrl
);
357 function GetWinMajorVersion
: longword
;
358 var OSVersionInfo
: TOSVersionInfo
;
360 { Get OS version info. }
361 OSVersionInfo
.dwOSVersionInfoSize
:= SizeOf(TOSVersionInfo
);
362 GetVersionEx(OSVersionInfo
);
363 Result
:= OSVersionInfo
.dwMajorVersion
;
366 function IsPrintableString(S
: string): boolean;
367 { Check if string contains only printable ASCII characters. }
372 while Result
and (i
<= Length(S
)) do begin
373 Result
:= (Ord(S
[i
]) > 31) and (Ord(S
[i
]) < 127);
378 procedure SplitParameters(S
: string; var FirstPrm
, Remainder
: string; Separator
: char = #32);
381 i
:= pos(Separator
, S
);
383 FirstPrm
:= Copy(S
, 1, i
- 1);
384 Remainder
:= Copy(S
, i
+ 1, Length(S
) - i
);
392 function UnixTimeStamp(DateTime
: TDateTime
): TUnixTimeStamp
;
394 {Result:= Trunc((DateTime - EncodeDate(1970, 1 ,1)) * 24 * 60 * 60);}
395 Result
:= DateTimeToUnix(DateTime
);
399 function ReadLineFromStream(Stream
: TStream
): string;
400 var S
: string; B
: char;
405 B
:= Char(Stream
.ReadByte
);
406 if not (B
in [#10, #13]) then S
:= S
+ B
;
413 function WriteLineToStream(Stream
: TStream
; Line
: string): boolean;
419 Stream
.WriteBuffer(PChar(Line
)^, Length(Line
));
426 { Object constructors/destructors: }
428 constructor TArgumentParser
.Create(RawArguments
: TStringArray
; AllowedPrefixes
: TStringArray
= []);
431 for i
:= 0 to Length(RawArguments
) - 1 do
432 ParseArgument(RawArguments
[i
], AllowedPrefixes
);
435 destructor TArgumentParser
.Destroy
;
437 SetLength(Arguments
, 0);
440 constructor TNamedObject
.Create(const Name
: string; Config
: TINIFile
; const Section
: string);
444 FAliases
:= TStringList
.Create
;
445 FAliases
.Delimiter
:= ',';
446 FAliases
.DelimitedText
:= FName
+ ',' + Config
.ReadString(Section
, 'Alias', '');
449 constructor TMainServerConfig
.Create(Config
: TINIFile
);
451 inherited Create(Config
.ReadString('Server', 'Name', ''), Config
, 'Server');
452 FListenPorts
:= TStringList
.Create
;
453 FListenPorts
.Delimiter
:= ',';
454 FListenPorts
.DelimitedText
:= Config
.ReadString('Server', 'ListenPort', '25');
456 FDatabytes
:= Config
.ReadInteger('Server', 'Databytes', 1024 * 1024 * 1024);
457 {FTimeCorrection:= Config.ReadInteger('Server', 'TimeCorrection', 0);}
458 FTimeOffset
:= Config
.ReadInteger('Server', 'TimeOffset', Config
.ReadInteger('Server', 'TimeCorrection', 0) * 100);
459 FTimeOffsetStr
:= MakeTimeOffsetStr(FTimeOffset
);
461 FPolicies
:= Config
.ReadBool('Server', 'Policies', false);
462 FMailbox
:= Config
.ReadBool('Server', 'Mailbox', false);
463 FRelay
:= Config
.ReadBool('Server', 'Relay', false);
464 FLog
:= Config
.ReadBool('Server', 'Log', false);
467 constructor TEMailProperties
.Create
;
474 constructor TIPNamePair
.Create(const Name
, IP
: string);
480 constructor TEnvelope
.Create
;
484 FReturnPathSpecified
:= false;
486 SetLength(FRecipients
, 0);
489 destructor TEnvelope
.Destroy
;
491 SetLength(FRecipients
, 0);
498 procedure TArgumentParser
.ParseArgument(Arg
: string; const AllowedPrefixes
: TStringArray
);
499 var i
, n
: integer; found
: boolean;
501 { Strip prefix if present. }
502 i
:= 0; found
:= false;
503 while ((i
< Length(AllowedPrefixes
)) and (not found
)) do begin
504 if pos(AllowedPrefixes
[i
], Arg
) = 1 then
506 Delete(Arg
, 1, Length(AllowedPrefixes
[i
]));
512 n
:= Length(Arguments
);
513 SetLength(Arguments
, n
+ 1);
514 SplitParameters(Arg
, Arguments
[n
].Option
, Arguments
[n
].Value
, '=');
515 { To be case-insensitive: }
516 Arguments
[n
].Option
:= UpCase(Arguments
[n
].Option
);
519 function TArgumentParser
.GetArgument(ID
: integer): TArgument
;
521 { No index checking... you'd better use it return value of ValidateArguments. }
522 Result
:= Arguments
[ID
];
525 function TArgumentParser
.IsPresent(ArgumentName
: string): boolean;
529 while (i
< Length(Arguments
)) and (Arguments
[i
].Option
<> UpCase(ArgumentName
)) do
531 Result
:= i
< Length(Arguments
);
534 function TArgumentParser
.GetValue(ArgumentName
: string; DefValue
: string = ''): string;
538 while (i
< Length(Arguments
)) and (Arguments
[i
].Option
<> UpCase(ArgumentName
)) do
541 if i
< Length(Arguments
) then begin
542 if Arguments
[i
].Value
<> '' then
543 Result
:= Arguments
[i
].Value
551 function TArgumentParser
.ValidateArguments(ValidArguments
: TStringArray
): integer;
552 { Returns -1 if all arguments are valid. Otherwise, returns the ID of the first
557 while (i
< Length(Arguments
)) and (Arguments
[i
] in ValidArguments
) do
560 if i
< Length(Arguments
) then
567 function TNamedObject
.IsItYourName(const Name
: string): boolean;
569 Result
:= FAliases
.IndexOf(Name
) <> -1;
573 function TMainServerConfig
.GetVersionStr
: string;
575 Result
:= VERSION_STR
;
579 function TIPNamePair
.Copy
: TIPNamePair
;
581 Result
:= TIPNamePair
.Create(Name
, IP
);
585 procedure TEMailProperties
.SetSize(Value
: longint);
590 procedure TEMailProperties
.WriteFlags(Value
: TEMailFlags
);
595 procedure TEMailProperties
.SetFlag(Flag
: TEMailFlags
);
597 FFlags
:= FFlags
or Flag
;
600 function TEMailProperties
.HasFlag(Flag
: TEMailFlags
): boolean;
602 Result
:= (FFlags
and Flag
) = Flag
;
606 function TEnvelope
.GetNumberOfRecipients
: integer;
608 Result
:= Length(FRecipients
);
611 function TEnvelope
.GetRecipient(Index
: integer): TRecipient
;
613 Result
:= FRecipients
[Index
];
616 function TEnvelope
.IsComplete
: boolean;
618 Result
:= FReturnPathSpecified
and (Length(FRecipients
) > 0);
621 procedure TEnvelope
.AddRecipient(Address
: string; Data
: integer = 0; RMsg
: string = '');
624 i
:= Length(FRecipients
);
625 SetLength(FRecipients
, i
+ 1);
626 FRecipients
[i
].Address
:= Address
;
627 FRecipients
[i
].RMsg
:= RMsg
;
628 FRecipients
[i
].Data
:= Data
;
631 procedure TEnvelope
.AddRecipient(Recipient
: TRecipient
);
634 i
:= Length(FRecipients
);
635 SetLength(FRecipients
, i
+ 1);
636 FRecipients
[i
]:= Recipient
;
639 procedure TEnvelope
.SetRecipientData(Index
, Data
: integer; RMsg
: string = '');
641 FRecipients
[Index
].RMsg
:= RMsg
;
642 FRecipients
[Index
].Data
:= Data
;
645 procedure TEnvelope
.SetReturnPath(Address
: string);
647 FReturnPath
:= Address
;
648 FReturnPathSpecified
:= true;
651 procedure TEnvelope
.SetRelayHost(HostName
: string);
653 FRelayHost
:= HostName
;