-
Notifications
You must be signed in to change notification settings - Fork 1
/
iraMtpSrv.pas
2105 lines (1690 loc) · 65.8 KB
/
iraMtpSrv.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit iraMtpSrv;
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$H+} { Use long strings }
{$J+} { Allow typed constant to be modified }
interface
uses
Winapi.Windows,
Winapi.Messages,
OverbyteIcsWinSock,
System.SysUtils,
System.Classes,
{$IFNDEF NOFORMS}
{$IFDEF FMX}
FMX.Forms,
{$ELSE}
Vcl.Forms,
{$ENDIF}
{$ENDIF}
OverbyteIcsTypes,
OverbyteIcsUtils,
{$IFDEF FMX}
Ics.Fmx.OverbyteIcsSocketUtils,
Ics.Fmx.OverbyteIcsWndControl,
Ics.Fmx.OverbyteIcsWSocket,
Ics.Fmx.OverbyteIcsWSocketS,
{$ELSE}
OverbyteIcsWndControl,
OverbyteIcsWSocket,
OverbyteIcsSocketUtils,
OverbyteIcsWSocketS,
{$ENDIF}
OverbyteIcsFtpSrvT,
OverbyteIcsWSockBuf,
StrUtils
;
const
DefaultRcvSize = 16384;
const
ftpcPORT = 0;
ftpcSTOR = 1;
ftpcRETR = 2;
ftpcQUIT = 3;
ftpcABOR = 4;
type
PBoolean = ^Boolean;
FtpServerException = class(Exception);
TFtpString = type String;
type
EFtpCtrlSocketException = class(Exception);
TFtpCtrlState = (ftpcInvalid, ftpcWaitingUserCode,
ftpcReady, ftpcWaitingAnswer, ftpcFailedAuth);
TFtpCmdType = Byte;
type
TDisplayEvent = procedure (Sender : TObject; Msg : String) of object;
TCommandEvent = procedure (Sender : TObject; CmdBuf : PAnsiChar; CmdLen : Integer) of object;
TMtpCtrlSocket = class;
TClientProcessingThread = class(TThread)
public
Client : TMtpCtrlSocket;
Keyword : String;
Params : String;
InData : String;
OutData : String;
AuxData : String;
ClientID : Integer;
StartTick : LongWord;
Sender : TObject;
protected
procedure TriggerEnterSecurityContext;
procedure TriggerLeaveSecurityContext;
procedure Execute; override;
end;
TMtpServer = class;
TMtpCtrlSocket = class(TWSocketClient)
protected
FDataSocket : TWSocket;
FRcvBuf : PAnsiChar;
FRcvCnt : Integer;
FRcvSize : Integer;
FBusy : Boolean;
FLastCommand : TDateTime;
FCommandCount : LongInt;
FCloseRequest : Boolean;
FFtpState : TFtpCtrlState;
FAbortingTransfer : Boolean;
FUserData : LongInt;
FPeerAddr : String;
FPeerSAddr : TSockAddr;
FHost : String;
FOnDisplay : TDisplayEvent;
FOnCommand : TCommandEvent;
FEpsvAllArgReceived: Boolean;
FSndBufSize : Integer;
FRcvBufSize : Integer;
FStreamSize : LongInt;
procedure TriggerSessionConnected(Error : Word); override;
function TriggerDataAvailable(Error : Word) : boolean; override;
procedure TriggerCommand(CmdBuf : PAnsiChar; CmdLen : Integer); virtual;
procedure SetRcvSize(newValue : Integer);
procedure SetOnBgException(const Value: TIcsBgExceptionEvent); override;
procedure SetRcvBufSize(newValue : Integer);
procedure SetSndBufSize(newValue : Integer);
procedure SetStreamSize(newValue : Integer);
public
FtpServer : TMtpServer;
BinaryMode : Boolean;
DataAddr : String;
DataPort : String;
MemoryName : String;
DataSessionActive : Boolean;
DataStream : TMemoryStream;
HasOpenedFile : Boolean;
TransferError : String;
DataSent : Boolean;
CurCmdType : TFtpCmdType;
ProcessingThread : TClientProcessingThread;
AnswerDelayed : Boolean;
ByteCount : Int64;
RestartPos : Int64;
LastTick : Longword;
SessStartTick : Longword;
ReqStartTick : Longword;
XferStartTick : Longword;
ReqDurMilliSecs : Integer;
TotGetBytes : Int64;
TotPutBytes : Int64;
SessIdInfo : String;
FailedAttempts : Integer;
DelayAnswerTick : Longword;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SendAnswer(const Answer : RawByteString);
procedure SetAbortingTransfer(newValue : Boolean);
procedure TriggerSessionClosed(Error : Word); override;
procedure DataStreamWriteString(const Str: AnsiString); overload;
procedure DataStreamWriteString(const Str: AnsiString; DstCodePage: LongWord); overload;
procedure DataStreamWriteString(const Str: UnicodeString; DstCodePage: LongWord); overload;
procedure DataStreamWriteString(const Str: UnicodeString); overload;
procedure DataStreamReadString(var Str: AnsiString; Len: TFtpBigInt); overload;
procedure DataStreamReadString(var Str: AnsiString; Len: TFtpBigInt; SrcCodePage: LongWord); overload;
procedure DataStreamReadString(var Str: UnicodeString; Len: TFtpBigInt); overload;
property DataSocket : TWSocket read FDataSocket;
property LastCommand : TDateTime read FLastCommand;
property CommandCount : LongInt read FCommandCount;
property RcvBuf : PAnsiChar read FRcvBuf;
property RcvdCount;
property CloseRequest : Boolean read FCloseRequest write FCloseRequest;
property AbortingTransfer : Boolean read FAbortingTransfer write SetAbortingTransfer;
property ID : LongInt read FCliId write FCliId;
property PeerSAddr : TSockAddr read FPeerSAddr;
property ReadCount : Int64 read FReadCount;
published
property FtpState : TFtpCtrlState read FFtpState write FFtpState;
property RcvSize : Integer read FRcvSize write SetRcvSize;
property Busy : Boolean read FBusy write FBusy;
property UserData : LongInt read FUserData write FUserData;
property Host : String read FHost write FHost;
property SndBufSize : Integer read FSndBufSize write SetSndBufSize;
property RcvBufSize : Integer read FRcvBufSize write SetRcvBufSize;
property StreamSize : Integer read FStreamSize write SetStreamSize;
property OnDisplay : TDisplayEvent read FOnDisplay write FOnDisplay;
property OnCommand : TCommandEvent read FOnCommand write FOnCommand;
property OnSessionClosed;
property OnDataSent;
property HSocket;
property AllSent;
property State;
end;
TMtpCtrlSocketClass = class of TMtpCtrlSocket;
TFtpSrvClientConnectEvent = procedure (Sender: TObject; Client: TMtpCtrlSocket; AError: Word) of object;
TFtpSrvDataSessionConnectedEvent = procedure (Sender: TObject; Client: TMtpCtrlSocket; Data : TWSocket; AError: Word) of object;
TFtpSrvClientCommandEvent = procedure (Sender: TObject; Client: TMtpCtrlSocket; var Keyword : TFtpString; var Params: TFtpString;
var Answer: TFtpString) of object;
TFtpSrvAnswerToClientEvent = procedure (Sender: TObject; Client: TMtpCtrlSocket; var Answer : TFtpString) of object;
TFtpSrvDataAvailableEvent = procedure (Sender: TObject; Client: TMtpCtrlSocket; Data : TWSocket; Buf: PAnsiChar; Len: LongInt;
AError: Word) of object;
TFtpSrvRetrDataSentEvent = procedure (Sender: TObject; Client: TMtpCtrlSocket; Data : TWSocket; AError: Word) of object;
TFtpSrvGetProcessingEvent = procedure (Sender : TObject; Client: TMtpCtrlSocket; var DelayedSend: Boolean) of object;
TFtpSrvCommandProc = procedure (Client: TMtpCtrlSocket; var Keyword: TFtpString; var Params : TFtpString; var Answer : TFtpString) of object;
TFtpSrvCommandTableItem = record
KeyWord : String;
Proc : TFtpSrvCommandProc;
end;
TFtpSrvCommandTable = array of TFtpSrvCommandTableItem;
TFtpSecurityContextEvent = procedure (Sender: TObject;Client: TMtpCtrlSocket) of object;
TFtpSrvGeneralEvent = procedure (Sender: TObject; Client: TMtpCtrlSocket; var Params: TFtpString; var Answer: TFtpString) of object;
TFtpSrvTimeoutEvent = procedure (Sender: TObject; Client: TMtpCtrlSocket; Duration: Integer; var Abort: Boolean) of object;
TFtpSrvDisplayEvent = procedure (Sender: TObject; Client: TMtpCtrlSocket; Msg: TFtpString) of object;
TMtpServer = class(TIcsWndControl)
protected
FAddr : String;
FSocketFamily : TSocketFamily;
FPort : String;
FListenBackLog : Integer;
FSocketServer : TWSocketServer ;
FClientClass : TMtpCtrlSocketClass;
FMaxClients : LongInt;
FCmdTable : TFtpSrvCommandTable;
FLastCmd : Integer;
FUserData : LongInt;
FTimeoutSecsLogin : Integer;
FTimeoutSecsIdle : Integer;
FTimeoutSecsXfer : Integer;
FEventTimer : TIcsTimer;
FAlloExtraSpace : Integer;
FMaxAttempts : Integer;
FBindFtpData : Boolean;
FMsg_WM_FTPSRV_CLOSE_REQUEST : UINT;
FMsg_WM_FTPSRV_ABORT_TRANSFER : UINT;
FMsg_WM_FTPSRV_CLOSE_DATA : UINT;
FMsg_WM_FTPSRV_START_SEND : UINT;
FOnStart : TNotifyEvent;
FOnStop : TNotifyEvent;
FOnClientConnect : TFtpSrvClientConnectEvent;
FOnClientDisconnect : TFtpSrvClientConnectEvent;
FOnClientCommand : TFtpSrvClientCommandEvent;
FOnAnswerToClient : TFtpSrvAnswerToClientEvent;
FOnStorSessionConnected : TFtpSrvDataSessionConnectedEvent;
FOnStorSessionClosed : TFtpSrvDataSessionConnectedEvent;
FOnStorDataAvailable : TFtpSrvDataAvailableEvent;
FOnRetrSessionConnected : TFtpSrvDataSessionConnectedEvent;
FOnRetrSessionClosed : TFtpSrvDataSessionConnectedEvent;
FOnRetrDataSent : TFtpSrvRetrDataSentEvent;
FOnGetProcessing : TFtpSrvGetProcessingEvent;
FOnEnterSecurityContext : TFtpSecurityContextEvent;
FOnLeaveSecurityContext : TFtpSecurityContextEvent;
FOnTimeout : TFtpSrvTimeoutEvent;
FOnDisplay : TFtpSrvDisplayEvent;
procedure CreateSocket; virtual;
function GetMultiListenIndex: Integer;
function GetMultiListenSockets: TWSocketMultiListenCollection;
procedure SetMultiListenSockets(const Value: TWSocketMultiListenCollection);
procedure SetOnBgException(const Value: TIcsBgExceptionEvent); override;
procedure ClientProcessingThreadTerminate(Sender : TObject);
procedure Notification(AComponent: TComponent; operation: TOperation); override;
procedure ServSocketStateChange(Sender: TObject; OldState, NewState: TSocketState);
procedure ClientDataSent(Sender: TObject; AError : Word); virtual;
procedure ClientCommand(Sender: TObject; CmdBuf: PAnsiChar; CmdLen: Integer);
procedure ClientStorSessionConnected(Sender: TObject; AError : Word);
procedure ClientStorSessionClosed(Sender: TObject; AError : Word);
procedure ClientStorDataAvailable(Sender: TObject; AError : word); virtual;
procedure ClientRetrSessionConnected(Sender: TObject; AError : Word); virtual;
procedure ClientRetrSessionClosed(Sender: TObject; AError : Word);
procedure ClientRetrDataSent(Sender: TObject; AError : Word);
procedure SendAnswer(Client: TMtpCtrlSocket; Answer: TFtpString); virtual;
procedure SendNextDataChunk(Client: TMtpCtrlSocket; Data: TWSocket); virtual;
procedure StartSendData(Client: TMtpCtrlSocket);
procedure PrepareStorDataSocket(Client: TMtpCtrlSocket);
procedure EventTimerOnTimer(Sender: TObject);
procedure ServerClientConnect(Sender: TObject; Client: TWSocketClient; Error: Word);
procedure ServerClientDisconnect(Sender: TObject; Client: TWSocketClient; Error: Word);
procedure TriggerServerStart; virtual;
procedure TriggerServerStop; virtual;
procedure TriggerSendAnswer(Client: TMtpCtrlSocket; var Answer: TFtpString); virtual;
procedure TriggerClientConnect(Client: TMtpCtrlSocket; AError: Word); virtual;
procedure TriggerClientDisconnect(Client: TMtpCtrlSocket; AError: Word); virtual;
procedure TriggerClientCommand(Client: TMtpCtrlSocket; var Keyword: TFtpString; var Params: TFtpString; var Answer: TFtpString); virtual;
procedure TriggerStorSessionConnected(Client: TMtpCtrlSocket; Data: TWSocket; AError: Word); virtual;
procedure TriggerStorSessionClosed(Client: TMtpCtrlSocket; Data: TWSocket; AError: Word); virtual;
procedure TriggerRetrSessionConnected(Client: TMtpCtrlSocket; Data: TWSocket; AError: Word); virtual;
procedure TriggerRetrSessionClosed(Client: TMtpCtrlSocket; Data: TWSocket; AError: Word); virtual;
procedure TriggerStorDataAvailable(Client: TMtpCtrlSocket; Data: TWSocket; Buf: PAnsiChar; Len: LongInt; AError: Word); virtual;
procedure TriggerRetrDataSent(Client: TMtpCtrlSocket;Data: TWSocket; AError: Word); virtual;
procedure TriggerEnterSecurityContext(Client: TMtpCtrlSocket); virtual;
procedure TriggerLeaveSecurityContext(Client: TMtpCtrlSocket); virtual;
procedure TriggerTimeout (Client: TMtpCtrlSocket; Duration: Integer; var Abort : Boolean); virtual;
procedure TriggerDisplay (Client : TMtpCtrlSocket; Msg: TFtpString); virtual;
function GetClientCount: Integer; virtual;
function GetClient(nIndex: Integer): TMtpCtrlSocket; virtual;
function GetActive: Boolean;
procedure SetActive(newValue: Boolean);
procedure SetClientClass(const NewValue: TMtpCtrlSocketClass);
procedure AddCommand(const Keyword: String; const Proc: TFtpSrvCommandProc); virtual;
procedure WMFtpSrvCloseRequest(var msg: TMessage); virtual;
procedure WMFtpSrvAbortTransfer(var msg: TMessage); virtual;
procedure WMFtpSrvCloseData(var msg: TMessage); virtual;
procedure WMFtpSrvStartSend(var msg: TMessage); virtual;
procedure CommandQUIT(Client: TMtpCtrlSocket; var Keyword: TFtpString; var Params: TFtpString; var Answer: TFtpString); virtual;
procedure CommandPORT(Client: TMtpCtrlSocket; var Keyword: TFtpString; var Params: TFtpString; var Answer: TFtpString); virtual;
procedure CommandSTOR(Client: TMtpCtrlSocket; var Keyword: TFtpString; var Params: TFtpString; var Answer: TFtpString); virtual;
procedure CommandRETR(Client: TMtpCtrlSocket; var Keyword: TFtpString; var Params: TFtpString; var Answer: TFtpString); virtual;
procedure CommandABOR(Client: TMtpCtrlSocket; var Keyword: TFtpString; var Params: TFtpString; var Answer: TFtpString); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Start;
procedure Stop;
procedure Disconnect(Client : TMtpCtrlSocket);
procedure DisconnectAll;
procedure DoStartSendData(Client: TMtpCtrlSocket; var Answer : TFtpString); virtual;
procedure AllocateMsgHandlers; override;
procedure FreeMsgHandlers; override;
function MsgHandlersCount: Integer; override;
procedure WndProc(var MsgRec: TMessage); override;
function IsClient(SomeThing : TObject) : Boolean;
function OpenMemoryStream( ): TMemoryStream;
procedure CloseMemoryStreams(Client : TMtpCtrlSocket);
property ServSocket : TWSocketServer read FSocketServer;
property ClientCount : Integer read GetClientCount;
property Active : Boolean read GetActive write SetActive;
property ClientClass : TMtpCtrlSocketClass read FClientClass write SetClientClass;
property Client[nIndex : Integer] : TMtpCtrlSocket read GetClient;
property MultiListenIndex : Integer read GetMultiListenIndex;
published
property Addr : String read FAddr write FAddr;
property BindFtpData : Boolean read FBindFtpData write FBindFtpData default True;
property SocketFamily : TSocketFamily read FSocketFamily write FSocketFamily;
property Port : String read FPort write FPort;
property ListenBackLog : Integer read FListenBackLog write FListenBackLog;
property MultiListenSockets : TWSocketMultiListenCollection read GetMultiListenSockets write SetMultiListenSockets;
property UserData : LongInt read FUserData write FUserData;
property MaxClients : LongInt read FMaxClients write FMaxClients;
property TimeoutSecsLogin : Integer read FTimeoutSecsLogin write FTimeoutSecsLogin;
property TimeoutSecsIdle : Integer read FTimeoutSecsIdle write FTimeoutSecsIdle;
property TimeoutSecsXfer : Integer read FTimeoutSecsXfer write FTimeoutSecsXfer;
property AlloExtraSpace : Integer read FAlloExtraSpace write FAlloExtraSpace;
property MaxAttempts : Integer read FMaxAttempts write FMaxAttempts ;
property OnStart : TNotifyEvent read FOnStart write FOnStart;
property OnStop : TNotifyEvent read FOnStop write FOnStop;
property OnClientDisconnect : TFtpSrvClientConnectEvent read FOnClientDisconnect write FOnClientDisconnect;
property OnClientConnect : TFtpSrvClientConnectEvent read FOnClientConnect write FOnClientConnect;
property OnClientCommand : TFtpSrvClientCommandEvent read FOnClientCommand write FOnClientCommand;
property OnAnswerToClient : TFtpSrvAnswerToClientEvent read FOnAnswerToClient write FOnAnswerToClient;
property OnStorSessionConnected : TFtpSrvDataSessionConnectedEvent read FOnStorSessionConnected write FOnStorSessionConnected;
property OnRetrSessionConnected : TFtpSrvDataSessionConnectedEvent read FOnRetrSessionConnected write FOnRetrSessionConnected;
property OnStorSessionClosed : TFtpSrvDataSessionConnectedEvent read FOnStorSessionClosed write FOnStorSessionClosed;
property OnRetrSessionClosed : TFtpSrvDataSessionConnectedEvent read FOnRetrSessionClosed write FOnRetrSessionClosed;
property OnRetrDataSent : TFtpSrvRetrDataSentEvent read FOnRetrDataSent write FOnRetrDataSent;
property OnStorDataAvailable : TFtpSrvDataAvailableEvent read FOnStorDataAvailable write FOnStorDataAvailable;
property OnGetProcessing : TFtpSrvGetProcessingEvent read FOnGetProcessing write FOnGetProcessing;
property OnEnterSecurityContext : TFtpSecurityContextEvent read FOnEnterSecurityContext write FOnEnterSecurityContext;
property OnLeaveSecurityContext : TFtpSecurityContextEvent read FOnLeaveSecurityContext write FOnLeaveSecurityContext;
property OnTimeout : TFtpSrvTimeoutEvent read FOnTimeout write FOnTimeout;
property OnDisplay : TFtpSrvDisplayEvent read FOnDisplay write FOnDisplay;
property OnBgException;
end;
procedure UpdateThreadOnProgress(Obj: TObject; Count: Int64; var Cancel: Boolean);
procedure register;
implementation
const
msgCmdUnknown = '500 ''%s'': command not understood.';
msgOptRespRequired = '331 Response to %s required for %s.';
msgQuit = '221 Goodbye.';
msgPortSuccess = '200 Port command successful.';
msgPortFailed = '501 Invalid PORT command.';
msgStorDisabled = '501 Permission Denied'; {'500 Cannot STOR.';}
msgStorSuccess = '150 Opening data connection for %s.';
msgStorFailed = '501 Cannot STOR. %s';
msgStorAborted = '426 Connection closed; %s.';
msgStorOk = '226 File received ok';
{ msgStorOk = '226-Multiple lines answer'#13#10' Test'#13#10#13#10'226 File received OK'; }
msgStorError = '426 Connection closed; transfer aborted. Error %s';
msgRetrDisabled = '500 Cannot RETR.';
msgRetrSuccess = '150 Opening retrieve data connection for ';
msgRetrFailed = '501 Cannot RETR. %s';
msgRetrAborted = '426 Connection closed; %s.';
msgRetrOk = '226 File sent ok';
msgRetrError = '426 Connection closed; transfer aborted. Error %s';
msgRetrNotExists = '550 ''%s'': no such file or directory.';
msgRetrFileErr = '451 Cannot open file: %s.';
msgAborOk = '225 ABOR command successful.';
msgTimeout = '421 Connection closed, timed out after %d secs.';
msgNotAllowed = '421 Connection not allowed.';
procedure register;
begin
RegisterComponents('ira Mtp', [TMtpServer]);
end;
function atosi(const value : String) : Integer;
var
i, j : Integer;
begin
Result := 0;
i := 1;
while (i <= Length(Value)) and (Value[i] = ' ') do
i := i + 1;
j := i;
while (i <= Length(Value)) and ((Value[i] = '+') or (Value[i] = '-')) do
i := i + 1;
while (i <= Length(Value)) and (Value[i] >= '0') and (Value[i] <= '9')do begin
Result := Result * 10 + ord(Value[i]) - ord('0');
i := i + 1;
end;
if j < Length(Value) then begin
if value[j] = '-' then
Result := -Result;
end;
end;
procedure TMtpServer.CreateSocket;
begin
FSocketServer := TWSocketServer.Create(Self);
end;
constructor TMtpServer.Create(AOwner: TComponent);
var
Len : Cardinal;
begin
inherited Create(AOwner);
AllocateHWnd;
FClientClass := TMtpCtrlSocket;
//FSocketServer := TWSocketServer.Create(Self);
CreateSocket;
FSocketServer.Name := 'WSocketServer';
FSocketServer.ClientClass := FClientClass;
FSocketServer.OnClientConnect := ServerClientConnect;
FSocketServer.OnClientDisconnect := ServerClientDisconnect;
FPort := 'ftp';
FSocketFamily := DefaultSocketFamily;
FAddr := ICS_ANY_HOST_V4;
FListenBackLog := 5;
FTimeoutSecsLogin := 60;
FTimeoutSecsIdle := 300;
FTimeoutSecsXfer := 60;
FAlloExtraSpace := 1000000;
FEventTimer := TIcsTimer.Create(Self);
FEventTimer.Enabled := false;
FEventTimer.OnTimer := EventTimerOnTimer;
FEventTimer.Interval := 5000;
FMaxAttempts := 12 ;
FBindFtpData := True;
SetLength(FCmdTable, 5 + 1 + 5);
AddCommand('PORT', CommandPORT);
AddCommand('STOR', CommandSTOR);
AddCommand('RETR', CommandRETR);
AddCommand('QUIT', CommandQUIT);
AddCommand('ABOR', CommandABOR);
end;
destructor TMtpServer.Destroy;
begin
if Assigned(FEventTimer) then begin
FEventTimer.Destroy;
FEventTimer := nil;
end;
if Assigned(FSocketServer) then begin
FSocketServer.Destroy;
FSocketServer := nil;
end;
SetLength(FCmdTable, 0);
inherited Destroy;
end;
function TMtpServer.MsgHandlersCount : Integer;
begin
Result := 5 + inherited MsgHandlersCount;
end;
procedure TMtpServer.AllocateMsgHandlers;
begin
inherited AllocateMsgHandlers;
FMsg_WM_FTPSRV_CLOSE_REQUEST := FWndHandler.AllocateMsgHandler(Self);
FMsg_WM_FTPSRV_ABORT_TRANSFER := FWndHandler.AllocateMsgHandler(Self);
FMsg_WM_FTPSRV_CLOSE_DATA := FWndHandler.AllocateMsgHandler(Self);
FMsg_WM_FTPSRV_START_SEND := FWndHandler.AllocateMsgHandler(Self);
end;
procedure TMtpServer.FreeMsgHandlers;
begin
if Assigned(FWndHandler) then begin
FWndHandler.UnregisterMessage(FMsg_WM_FTPSRV_CLOSE_REQUEST);
FWndHandler.UnregisterMessage(FMsg_WM_FTPSRV_ABORT_TRANSFER);
FWndHandler.UnregisterMessage(FMsg_WM_FTPSRV_CLOSE_DATA);
FWndHandler.UnregisterMessage(FMsg_WM_FTPSRV_START_SEND);
end;
inherited FreeMsgHandlers;
end;
procedure TMtpServer.WndProc(var MsgRec: TMessage);
begin
try
with MsgRec do begin
if Msg = FMsg_WM_FTPSRV_CLOSE_REQUEST then
WMFtpSrvCloseRequest(MsgRec)
else if Msg = FMsg_WM_FTPSRV_ABORT_TRANSFER then
WMFtpSrvAbortTransfer(MsgRec)
else if Msg = FMsg_WM_FTPSRV_CLOSE_DATA then
WMFtpSrvCloseData(MsgRec)
else if Msg = FMsg_WM_FTPSRV_START_SEND then
WMFtpSrvStartSend(MsgRec)
else
inherited WndProc(MsgRec);
end;
except
on E:Exception do
HandleBackGroundException(E);
end;
end;
procedure TMtpServer.WMFtpSrvCloseRequest(var msg: TMessage);
var
Client : TMtpCtrlSocket;
begin
Client := TMtpCtrlSocket(msg.LParam);
if FSocketServer.IsClient(Client) then begin
{ Check if client.ID is still the same as when message where posted }
if WPARAM(Client.ID) = Msg.WParam then begin
if Client.AllSent then
Client.Close
else
Client.CloseRequest := TRUE;
end;
end;
end;
procedure TMtpServer.Notification(AComponent: TComponent; operation: TOperation);
begin
inherited Notification(AComponent, operation);
if operation = opRemove then begin
if AComponent = FSocketServer then
FSocketServer := nil;
end;
end;
function TMtpServer.OpenMemoryStream ( ): TMemoryStream;
begin
Result := TMemoryStream.Create ; //( MAX_BUFSIZE);
end ;
procedure TMtpServer.CloseMemoryStreams(Client : TMtpCtrlSocket);
begin
if Client.HasOpenedFile then begin
if Assigned(Client.DataStream) then Client.DataStream.Destroy;
Client.DataStream := nil;
Client.HasOpenedFile := FALSE;
end;
end;
procedure TMtpServer.AddCommand(
const Keyword : String;
const Proc : TFtpSrvCommandProc);
begin
if FLastCmd > High(FCmdTable) then
raise FtpServerException.Create('Too many command');
FCmdTable[FLastCmd].KeyWord := KeyWord;
FCmdTable[FLastCmd].Proc := Proc;
Inc(FLastCmd);
end;
procedure TMtpServer.Start;
begin
if FSocketServer.State = wsListening then
Exit;
FSocketServer.Port := Port;
FSocketServer.Proto := 'tcp';
FSocketServer.SocketFamily := FSocketFamily;
FSocketServer.Addr := FAddr;
FSocketServer.ListenBacklog := FListenBackLog;
FSocketServer.banner := '';
FSocketServer.MaxClients := FMaxClients;
FSocketServer.OnChangeState := ServSocketStateChange;
FSocketServer.ComponentOptions := [wsoNoReceiveLoop];
FSocketServer.MultiListen;
FEventTimer.Enabled := true;
end;
procedure TMtpServer.Stop;
begin
FEventTimer.Enabled := false;
FSocketServer.Close;
end;
procedure TMtpServer.DisconnectAll;
begin
FSocketServer.DisconnectAll;
end;
procedure TMtpServer.Disconnect(Client : TMtpCtrlSocket);
begin
if NOT FSocketServer.IsClient(Client) then
raise FtpServerException.Create('Disconnect: Not one of our clients');
FSocketServer.Disconnect(Client);
end;
function TMtpServer.GetActive : Boolean;
begin
Result := (FSocketServer.State = wsListening);
end;
procedure TMtpServer.SetActive(newValue : Boolean);
begin
if newValue then
Start
else
Stop;
end;
procedure TMtpServer.SetClientClass(const NewValue: TMtpCtrlSocketClass);
begin
if NewValue <> FSocketServer.ClientClass then begin
FClientClass := NewValue;
FSocketServer.ClientClass := NewValue;
end;
end;
procedure TMtpServer.ServSocketStateChange(Sender : TObject; OldState, NewState : TSocketState);
begin
if csDestroying in ComponentState then
Exit;
if NewState = wsListening then
TriggerServerStart
else if NewState = wsClosed then
TriggerServerStop;
end;
procedure TMtpServer.ServerClientConnect(Sender: TObject;
Client: TWSocketClient; Error: Word);
var
MyClient: TMtpCtrlSocket;
begin
if Error <> 0 then
raise FtpServerException.Create('Session Available Error - ' +
GetWinsockErr(Error));
MyClient := Client as TMtpCtrlSocket;
MyClient.DataSocket.Name := Name + '_DataWSocket' + IntToStr(MyClient.ID);
MyClient.OnCommand := ClientCommand;
MyClient.OnDataSent := ClientDataSent;
MyClient.FtpServer := Self;
MyClient.SessIdInfo := Client.GetPeerAddr + ' [' + IntToStr (Client.CliId) + ']' ;
MyClient.FLastCommand := 0;
MyClient.FCommandCount := 0;
MyClient.FFtpState := ftpcWaitingUserCode; // ftpcReady;
end;
procedure TMtpServer.SendAnswer(Client : TMtpCtrlSocket; Answer : TFtpString);
begin
try
Client.ReqDurMilliSecs := IcsElapsedMsecs (Client.ReqStartTick);
TriggerSendAnswer(Client, Answer);
Client.SendAnswer(Answer);
except
end;
end;
procedure TMtpServer.ClientCommand(Sender : TObject; CmdBuf : PAnsiChar; CmdLen : Integer);
const
TELNET_IAC = #255;
TELNET_IP = #244;
TELNET_DATA_MARK = #242;
var
Client : TMtpCtrlSocket;
Answer : TFtpString;
Params : TFtpString;
KeyWord : TFtpString;
I : Integer;
RawParams: RawByteString;
begin
Client := Sender as TMtpCtrlSocket;
Answer := '';
try
Client.ReqStartTick := IcsGetTickCountX;
Client.ReqDurMilliSecs := 0;
RawParams := '';
I := 0;
while I < CmdLen do begin
if CmdBuf[I] <> TELNET_IAC then begin
RawParams := RawParams + CmdBuf[I];
Inc(I);
end
else begin
Inc(I);
if CmdBuf[I] = TELNET_IAC then
RawParams := RawParams + CmdBuf[I];
Inc(I);
end;
end;
Params := RawParams;
I := 1;
KeyWord := UpperCase(ScanGetAsciiArg (Params, I));
ScanFindArg (Params, I);
Params := Copy(Params, I, Length(Params));
TriggerClientCommand(Client, Keyword, Params, Answer);
if Answer <> '' then begin
SendAnswer(Client, Answer);
Exit;
end;
if Keyword = '' then begin
SendAnswer(Client, Format(msgCmdUnknown, [Params]));
Exit;
end;
I := 0;
while I <= High(FCmdTable) do begin
if FCmdTable[I].KeyWord = KeyWord then begin
if I <> ftpcABOR then { AG V8.02 }
Client.CurCmdType := I;
Client.AnswerDelayed := FALSE;
FCmdTable[I].Proc(Client, KeyWord, Params, Answer);
if not Client.AnswerDelayed then
SendAnswer(Client, Answer);
Exit;
end;
Inc(I);
end;
SendAnswer(Client, Format(msgCmdUnknown, [KeyWord]));
except
on E:Exception do begin
SendAnswer(Client, '501 ' + E.Message);
end;
end;
end;
procedure TMtpServer.ClientDataSent(Sender : TObject; AError : Word);
var
Client : TMtpCtrlSocket;
begin
Client := Sender as TMtpCtrlSocket;
if Client.CloseRequest then begin
PostMessage(Handle, FMsg_WM_FTPSRV_CLOSE_REQUEST,
WPARAM(Client.ID), LPARAM(Client));
end;
end;
procedure TMtpServer.ServerClientDisconnect(Sender: TObject; Client: TWSocketClient; Error: Word);
var
MyClient: TMtpCtrlSocket;
begin
try
MyClient := Client as TMtpCtrlSocket;
if MyClient.DataSocket.State = wsConnected then begin
MyClient.TransferError := 'ABORT on Disconnect';
MyClient.AbortingTransfer := TRUE;
MyClient.DataSocket.Close;
end;
CloseMemoryStreams(MyClient);
TriggerClientDisconnect(MyClient, Error);
except
end;
end;
procedure TMtpServer.WMFtpSrvAbortTransfer(var msg: TMessage);
var
Client : TMtpCtrlSocket;
Data : TWSocket;
begin
Client := TMtpCtrlSocket(Msg.LParam);
if FSocketServer.IsClient(Client) then begin
if WPARAM(Client.ID) = Msg.WParam then begin
Data := Client.DataSocket;
if Assigned(Data) then begin
Data.ShutDown(2);
Data.Close;
end;
Client.DataStream.position:=0;
end;
end;
end;
procedure TMtpServer.WMFtpSrvCloseData(var msg: TMessage);
var
Client : TMtpCtrlSocket;
Data : TWSocket;
begin
Client := TMtpCtrlSocket(Msg.LParam);
if FSocketServer.IsClient(Client) then begin
{ Check if client.ID is still the same as when message where posted }
if WPARAM(Client.ID) = Msg.WParam then begin
Data := Client.DataSocket;
if Assigned(Data) then begin
Data.ShutDown(1); { Wilfried 24/02/04 }
end;
Client.DataStream.position:=0;
end;
end;
end;
function TMtpServer.GetClient(nIndex : Integer) : TMtpCtrlSocket;
begin
Result := FSocketServer.Client [nIndex] as TMtpCtrlSocket;
end;
function TMtpServer.IsClient(SomeThing : TObject) : Boolean;
begin
Result := FSocketServer.IsClient(Something);
end;
function TMtpServer.GetClientCount : Integer;
begin
Result := FSocketServer.ClientCount;
end;
procedure TMtpServer.TriggerServerStart;
begin
if Assigned(FOnStart) then
FOnStart(Self);
end;
procedure TMtpServer.TriggerServerStop;
begin
if Assigned(FOnStop) then
FOnStop(Self);
end;
procedure TMtpServer.TriggerSendAnswer(Client : TMtpCtrlSocket; var Answer : TFtpString);
begin
if Assigned(FOnAnswerToClient) then
FOnAnswerToClient(Self, Client, Answer);
end;
procedure TMtpServer.TriggerClientDisconnect(Client : TMtpCtrlSocket; AError : Word);
begin
if Assigned(FOnClientDisconnect) then
FOnClientDisconnect(Self, Client, AError);
end;
procedure TMtpServer.TriggerClientConnect(Client : TMtpCtrlSocket; AError : Word);
begin
if Assigned(FOnClientConnect) then
FOnClientConnect(Self, Client, AError);
end;
procedure TMtpServer.TriggerStorSessionConnected(Client : TMtpCtrlSocket; Data : TWSocket; AError : Word);
begin
if Assigned(FOnStorSessionConnected) then
FOnStorSessionConnected(Self, Client, Data, AError);
end;
procedure TMtpServer.TriggerRetrSessionConnected(Client : TMtpCtrlSocket; Data : TWSocket; AError : Word);
begin
if Assigned(FOnRetrSessionConnected) then
FOnRetrSessionConnected(Self, Client, Data, AError);
end;
procedure TMtpServer.TriggerStorSessionClosed( Client : TMtpCtrlSocket; Data : TWSocket; AError : Word);
begin
if Assigned(FOnStorSessionClosed) then
FOnStorSessionClosed(Self, Client, Data, AError);
end;
procedure TMtpServer.TriggerRetrSessionClosed(Client : TMtpCtrlSocket; Data : TWSocket; AError : Word);
begin
if Assigned(FOnRetrSessionClosed) then
FOnRetrSessionClosed(Self, Client, Data, AError);
end;
procedure TMtpServer.TriggerClientCommand(
Client : TMtpCtrlSocket;
var Keyword : TFtpString;
var Params : TFtpString;
var Answer : TFtpString);
begin
if Assigned(FOnClientCommand) then
FOnClientCommand(Self, Client, KeyWord, Params, Answer);
end;
procedure TMtpServer.TriggerStorDataAvailable(
Client : TMtpCtrlSocket;
Data : TWSocket;
Buf : PAnsiChar;
Len : LongInt;
AError : Word);
begin
if Assigned(FOnStorDataAvailable) then
FOnStorDataAvailable(Self, Client, Data, Buf, Len, AError);
end;
procedure TMtpServer.TriggerRetrDataSent(
Client : TMtpCtrlSocket;
Data : TWSocket;