-
Notifications
You must be signed in to change notification settings - Fork 4
/
ftpsend.pas
2101 lines (1946 loc) · 60.5 KB
/
ftpsend.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
{==============================================================================|
| Project : Ararat Synapse | 004.001.000 |
|==============================================================================|
| Content: FTP client |
|==============================================================================|
| Copyright (c)1999-2011, Lukas Gebauer |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c) 1999-2010. |
| Portions created by Jan Fiala are Copyright (c) 2019. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
| Petr Esner <[email protected]> |
| Jan Fiala |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
{: @abstract(FTP client protocol)
Used RFC: RFC-959, RFC-2228, RFC-2428
}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$H+}
{$TYPEINFO ON}// Borland changed defualt Visibility from Public to Published
// and it requires RTTI to be generated $M+
{$M+}
{$IFDEF UNICODE}
{$WARN IMPLICIT_STRING_CAST OFF}
{$WARN IMPLICIT_STRING_CAST_LOSS OFF}
{$ENDIF}
unit ftpsend;
interface
uses
SysUtils, Classes,
{$IfDef POSIX}
,System.Generics.Collections, System.Generics.Defaults
{$EndIf}
blcksock, synautil, synaip, synsock;
const
cFtpProtocol = '21';
cFtpDataProtocol = '20';
{:Terminating value for TLogonActions}
FTP_OK = 255;
{:Terminating value for TLogonActions}
FTP_ERR = 254;
type
{:Array for holding definition of logon sequence.}
TLogonActions = array [0..17] of byte;
{:Procedural type for OnStatus event. Sender is calling @link(TFTPSend) object.
Value is FTP command or reply to this comand. (if it is reply, Response
is @True).}
TFTPStatus = procedure(Sender: TObject; Response: Boolean;
const Value: string) of object;
{: @abstract(Object for holding file information) parsed from directory
listing of FTP server.}
TFTPListRec = class(TObject)
private
FFileName: String;
FDirectory: Boolean;
FReadable: Boolean;
FFileSize: int64;
FFileTime: TDateTime;
FOriginalLine: string;
FMask: string;
FPermission: String;
public
{: You can assign another TFTPListRec to this object.}
procedure Assign(Value: TFTPListRec); virtual;
{:name of file}
property FileName: string read FFileName write FFileName;
{:if name is subdirectory not file.}
property Directory: Boolean read FDirectory write FDirectory;
{:if you have rights to read}
property Readable: Boolean read FReadable write FReadable;
{:size of file in bytes}
property FileSize: int64 read FFileSize write FFileSize;
{:date and time of file. Local server timezone is used. Any timezone
conversions was not done!}
property FileTime: TDateTime read FFileTime write FFileTime;
{:original unparsed line}
property OriginalLine: string read FOriginalLine write FOriginalLine;
{:mask what was used for parsing}
property Mask: string read FMask write FMask;
{:permission string (depending on used mask!)}
property Permission: string read FPermission write FPermission;
end;
{$IFDEF POSIX}
TFTPRecList = TList<TFTPListRec>;
{$ELSE}
TFTPRecList = TList;
{$ENDIF}
{:@abstract(This is TList of TFTPListRec objects.)
This object is used for holding lististing of all files information in listed
directory on FTP server.}
TFTPList = class(TObject)
protected
FList: TFTPRecList;
FLines: TStringList;
FMasks: TStringList;
FUnparsedLines: TStringList;
Monthnames: string;
BlockSize: string;
DirFlagValue: string;
FileName: string;
VMSFileName: string;
Day: string;
Month: string;
ThreeMonth: string;
YearTime: string;
Year: string;
Hours: string;
HoursModif: string;
Minutes: string;
Seconds: string;
Size: string;
Permissions: string;
DirFlag: string;
function GetListItem(Index: integer): TFTPListRec; virtual;
function ParseEPLF(Value: string): Boolean; virtual;
procedure ClearStore; virtual;
function ParseByMask(Value, NextValue, Mask: string): Integer; virtual;
function CheckValues: Boolean; virtual;
procedure FillRecord(const Value: TFTPListRec); virtual;
public
{:Constructor. You not need create this object, it is created by TFTPSend
class as their property.}
constructor Create;
destructor Destroy; override;
{:Clear list.}
procedure Clear; virtual;
{:count of holded @link(TFTPListRec) objects}
function Count: integer; virtual;
{:Assigns one list to another}
procedure Assign(Value: TFTPList); virtual;
{:try to parse raw directory listing in @link(lines) to list of
@link(TFTPListRec).}
procedure ParseLines; virtual;
{:try to parse MLSD directory listing in @link(lines) to list of
@link(TFTPListRec).}
procedure ParseMLSDLines; virtual;
{:By this property you have access to list of @link(TFTPListRec).
This is for compatibility only. Please, use @link(Items) instead.}
property List: TFTPRecList read FList;
{:By this property you have access to list of @link(TFTPListRec).}
property Items[Index: Integer]: TFTPListRec read GetListItem; default;
{:Set of lines with RAW directory listing for @link(parseLines)}
property Lines: TStringList read FLines;
{:Set of masks for directory listing parser. It is predefined by default,
however you can modify it as you need. (for example, you can add your own
definition mask.) Mask is same as mask used in TotalCommander.}
property Masks: TStringList read FMasks;
{:After @link(ParseLines) it holding lines what was not sucessfully parsed.}
property UnparsedLines: TStringList read FUnparsedLines;
end;
{:@abstract(Implementation of FTP protocol.)
Note: Are you missing properties for setting Username and Password? Look to
parent @link(TSynaClient) object! (Username and Password have default values
for "anonymous" FTP login)
Are you missing properties for specify server address and port? Look to
parent @link(TSynaClient) too!}
TFTPSend = class(TSynaClient)
protected
FOnStatus: TFTPStatus;
FSock: TTCPBlockSocket;
FDSock: TTCPBlockSocket;
FResultCode: Integer;
FResultString: string;
FFullResult: TStringList;
FAccount: string;
FFWHost: string;
FFWPort: string;
FFWUsername: string;
FFWPassword: string;
FFWMode: integer;
FDataStream: TMemoryStream;
FDataIP: string;
FDataPort: string;
FDirectFile: Boolean;
FDirectFileName: string;
FCanResume: Boolean;
FPassiveMode: Boolean;
FForceDefaultPort: Boolean;
FForceOldPort: Boolean;
FFtpList: TFTPList;
FBinaryMode: Boolean;
FAutoTLS: Boolean;
FIsTLS: Boolean;
FIsDataTLS: Boolean;
FTLSonData: Boolean;
FFullSSL: Boolean;
FUseMLSDList: Boolean;
function Auth(Mode: integer): Boolean; virtual;
function Connect: Boolean; virtual;
function InternalStor(const Command: string; RestoreAt: int64): Boolean; virtual;
function DataSocket: Boolean; virtual;
function AcceptDataSocket: Boolean; virtual;
procedure DoStatus(Response: Boolean; const Value: string); virtual;
public
{:Custom definition of login sequence. You can use this when you set
@link(FWMode) to value -1.}
CustomLogon: TLogonActions;
constructor Create;
destructor Destroy; override;
{:Waits and read FTP server response. You need this only in special cases!}
function ReadResult: Integer; virtual;
{:Parse remote side information of data channel from value string (returned
by PASV command). This function you need only in special cases!}
procedure ParseRemote(Value: string); virtual;
{:Parse remote side information of data channel from value string (returned
by EPSV command). This function you need only in special cases!}
procedure ParseRemoteEPSV(Value: string); virtual;
{:Send Value as FTP command to FTP server. Returned result code is result of
this function.
This command is good for sending site specific command, or non-standard
commands.}
function FTPCommand(const Value: string): integer; virtual;
{:Connect and logon to FTP server. If you specify any FireWall, connect to
firewall and throw them connect to FTP server. Login sequence depending on
@link(FWMode).}
function Login: Boolean; virtual;
{:Logoff and disconnect from FTP server.}
function Logout: Boolean; virtual;
{:Break current transmission of data. (You can call this method from
Sock.OnStatus event, or from another thread.)}
procedure Abort; virtual;
{:Break current transmission of data. It is same as Abort, but it send abort
telnet commands prior ABOR FTP command. Some servers need it. (You can call
this method from Sock.OnStatus event, or from another thread.)}
procedure TelnetAbort; virtual;
{:Download directory listing of Directory on FTP server. If Directory is
empty string, download listing of current working directory.
If NameList is @true, download only names of files in directory.
(internally use NLST command instead LIST command)
If NameList is @false, returned list is also parsed to @link(FTPList)
property.}
function List(Directory: string; NameList: Boolean): Boolean; virtual;
{:Read data from FileName on FTP server. If Restore is @true and server
supports resume dowloads, download is resumed. (received is only rest
of file)}
function RetrieveFile(const FileName: string; Restore: Boolean): Boolean; virtual;
{:Send data to FileName on FTP server. If Restore is @true and server
supports resume upload, upload is resumed. (send only rest of file)
In this case if remote file is same length as local file, nothing will be
done. If remote file is larger then local, resume is disabled and file is
transfered from begin!}
function StoreFile(const FileName: string; Restore: Boolean): Boolean; virtual;
{:Send data to FTP server and assing unique name for this file.}
function StoreUniqueFile: Boolean; virtual;
{:Append data to FileName on FTP server.}
function AppendFile(const FileName: string): Boolean; virtual;
{:Rename on FTP server file with OldName to NewName.}
function RenameFile(const OldName, NewName: string): Boolean; virtual;
{:Delete file FileName on FTP server.}
function DeleteFile(const FileName: string): Boolean; virtual;
{:Return size of Filename file on FTP server. If command failed (i.e. not
implemented), return -1.}
function FileSize(const FileName: string): int64; virtual;
{:Send NOOP command to FTP server for preserve of disconnect by inactivity
timeout.}
function NoOp: Boolean; virtual;
{:Change currect working directory to Directory on FTP server.}
function ChangeWorkingDir(const Directory: string): Boolean; virtual;
{:walk to upper directory on FTP server.}
function ChangeToParentDir: Boolean; virtual;
{:walk to root directory on FTP server. (May not work with all servers properly!)}
function ChangeToRootDir: Boolean; virtual;
{:Delete Directory on FTP server.}
function DeleteDir(const Directory: string): Boolean; virtual;
{:Create Directory on FTP server.}
function CreateDir(const Directory: string): Boolean; virtual;
{:Return current working directory on FTP server.}
function GetCurrentDir: String; virtual;
{:Establish data channel to FTP server and retrieve data.
This function you need only in special cases, i.e. when you need to implement
some special unsupported FTP command!}
function DataRead(const DestStream: TStream): Boolean; virtual;
{:Establish data channel to FTP server and send data.
This function you need only in special cases, i.e. when you need to implement
some special unsupported FTP command.}
function DataWrite(const SourceStream: TStream): Boolean; virtual;
published
{:After FTP command contains result number of this operation.}
property ResultCode: Integer read FResultCode;
{:After FTP command contains main line of result.}
property ResultString: string read FResultString;
{:After any FTP command it contains all lines of FTP server reply.}
property FullResult: TStringList read FFullResult;
{:Account information used in some cases inside login sequence.}
property Account: string read FAccount Write FAccount;
{:Address of firewall. If empty string (default), firewall not used.}
property FWHost: string read FFWHost Write FFWHost;
{:port of firewall. standard value is same port as ftp server used. (21)}
property FWPort: string read FFWPort Write FFWPort;
{:Username for login to firewall. (if needed)}
property FWUsername: string read FFWUsername Write FFWUsername;
{:password for login to firewall. (if needed)}
property FWPassword: string read FFWPassword Write FFWPassword;
{:Type of Firewall. Used only if you set some firewall address. Supported
predefined firewall login sequences are described by comments in source
file where you can see pseudocode decribing each sequence.}
property FWMode: integer read FFWMode Write FFWMode;
{:Socket object used for TCP/IP operation on control channel. Good for
seting OnStatus hook, etc.}
property Sock: TTCPBlockSocket read FSock;
{:Socket object used for TCP/IP operation on data channel. Good for seting
OnStatus hook, etc.}
property DSock: TTCPBlockSocket read FDSock;
{:If you not use @link(DirectFile) mode, all data transfers is made to or
from this stream.}
property DataStream: TMemoryStream read FDataStream;
{:After data connection is established, contains remote side IP of this
connection.}
property DataIP: string read FDataIP;
{:After data connection is established, contains remote side port of this
connection.}
property DataPort: string read FDataPort;
{:Mode of data handling by data connection. If @False, all data operations
are made to or from @link(DataStream) TMemoryStream.
If @true, data operations is made directly to file in your disk. (filename
is specified by @link(DirectFileName) property.) Dafault is @False!}
property DirectFile: Boolean read FDirectFile Write FDirectFile;
{:Filename for direct disk data operations.}
property DirectFileName: string read FDirectFileName Write FDirectFileName;
{:Indicate after @link(Login) if remote server support resume downloads and
uploads.}
property CanResume: Boolean read FCanResume;
{:If true (default value), all transfers is made by passive method.
It is safer method for various firewalls.}
property PassiveMode: Boolean read FPassiveMode Write FPassiveMode;
{:Force to listen for dataconnection on standard port (20). Default is @false,
dataconnections will be made to any non-standard port reported by PORT FTP
command. This setting is not used, if you use passive mode.}
property ForceDefaultPort: Boolean read FForceDefaultPort Write FForceDefaultPort;
{:When is @true, then is disabled EPSV and EPRT support. However without this
commands you cannot use IPv6! (Disabling of this commands is needed only
when you are behind some crap firewall/NAT.}
property ForceOldPort: Boolean read FForceOldPort Write FForceOldPort;
{:You may set this hook for monitoring FTP commands and replies.}
property OnStatus: TFTPStatus read FOnStatus write FOnStatus;
{:After LIST command is here parsed list of files in given directory.}
property FtpList: TFTPList read FFtpList;
{:if @true (default), then data transfers is in binary mode. If this is set
to @false, then ASCII mode is used.}
property BinaryMode: Boolean read FBinaryMode Write FBinaryMode;
{:if is true, then if server support upgrade to SSL/TLS mode, then use them.}
property AutoTLS: Boolean read FAutoTLS Write FAutoTLS;
{:if server listen on SSL/TLS port, then you set this to true.}
property FullSSL: Boolean read FFullSSL Write FFullSSL;
{:Signalise, if control channel is in SSL/TLS mode.}
property IsTLS: Boolean read FIsTLS;
{:Signalise, if data transfers is in SSL/TLS mode.}
property IsDataTLS: Boolean read FIsDataTLS;
{:If @true (default), then try to use SSL/TLS on data transfers too.
If @false, then SSL/TLS is used only for control connection.}
property TLSonData: Boolean read FTLSonData write FTLSonData;
{:Enable MLSD support for directory list.}
property UseMLSDList: Boolean read FUseMLSDList write FUseMLSDList;
end;
{:A very useful function, and example of use can be found in the TFtpSend object.
Dowload specified file from FTP server to LocalFile.}
function FtpGetFile(const IP, Port, FileName, LocalFile,
User, Pass: string): Boolean;
{:A very useful function, and example of use can be found in the TFtpSend object.
Upload specified LocalFile to FTP server.}
function FtpPutFile(const IP, Port, FileName, LocalFile,
User, Pass: string): Boolean;
{:A very useful function, and example of use can be found in the TFtpSend object.
Initiate transfer of file between two FTP servers.}
function FtpInterServerTransfer(
const FromIP, FromPort, FromFile, FromUser, FromPass: string;
const ToIP, ToPort, ToFile, ToUser, ToPass: string): Boolean;
implementation
constructor TFTPSend.Create;
begin
inherited Create;
FFullResult := TStringList.Create;
FDataStream := TMemoryStream.Create;
FSock := TTCPBlockSocket.Create;
FSock.Owner := self;
FSock.ConvertLineEnd := True;
FDSock := TTCPBlockSocket.Create;
FDSock.Owner := self;
FFtpList := TFTPList.Create;
FTimeout := 300000;
FTargetPort := cFtpProtocol;
FUsername := 'anonymous';
FPassword := 'anonymous@' + FSock.LocalName;
FDirectFile := False;
FPassiveMode := True;
FForceDefaultPort := False;
FForceOldPort := false;
FAccount := '';
FFWHost := '';
FFWPort := cFtpProtocol;
FFWUsername := '';
FFWPassword := '';
FFWMode := 0;
FBinaryMode := True;
FAutoTLS := False;
FFullSSL := False;
FIsTLS := False;
FIsDataTLS := False;
FTLSonData := True;
UseMLSDList := false;
end;
destructor TFTPSend.Destroy;
begin
FDSock.Free;
FSock.Free;
FFTPList.Free;
FDataStream.Free;
FFullResult.Free;
inherited Destroy;
end;
procedure TFTPSend.DoStatus(Response: Boolean; const Value: string);
begin
if assigned(OnStatus) then
OnStatus(Self, Response, Value);
end;
function TFTPSend.ReadResult: Integer;
var
s, c: string;
begin
FFullResult.Clear;
c := '';
repeat
s := FSock.RecvString(FTimeout);
if c = '' then
if length(s) > 3 then
if s[4] in [' ', '-'] then
c :=Copy(s, 1, 3);
FResultString := s;
FFullResult.Add(s);
DoStatus(True, s);
if FSock.LastError <> 0 then
Break;
until (c <> '') and (Pos(c + ' ', s) = 1);
Result := StrToIntDef(c, 0);
FResultCode := Result;
end;
function TFTPSend.FTPCommand(const Value: string): integer;
begin
FSock.Purge;
FSock.SendString(Value + CRLF);
DoStatus(False, Value);
Result := ReadResult;
end;
// based on idea by Petr Esner <[email protected]>
function TFTPSend.Auth(Mode: integer): Boolean;
const
//if not USER <username> then
// if not PASS <password> then
// if not ACCT <account> then ERROR!
//OK!
Action0: TLogonActions =
(0, FTP_OK, 3,
1, FTP_OK, 6,
2, FTP_OK, FTP_ERR,
0, 0, 0, 0, 0, 0, 0, 0, 0);
//if not USER <FWusername> then
// if not PASS <FWPassword> then ERROR!
//if SITE <FTPServer> then ERROR!
//if not USER <username> then
// if not PASS <password> then
// if not ACCT <account> then ERROR!
//OK!
Action1: TLogonActions =
(3, 6, 3,
4, 6, FTP_ERR,
5, FTP_ERR, 9,
0, FTP_OK, 12,
1, FTP_OK, 15,
2, FTP_OK, FTP_ERR);
//if not USER <FWusername> then
// if not PASS <FWPassword> then ERROR!
//if USER <UserName>'@'<FTPServer> then OK!
//if not PASS <password> then
// if not ACCT <account> then ERROR!
//OK!
Action2: TLogonActions =
(3, 6, 3,
4, 6, FTP_ERR,
6, FTP_OK, 9,
1, FTP_OK, 12,
2, FTP_OK, FTP_ERR,
0, 0, 0);
//if not USER <FWusername> then
// if not PASS <FWPassword> then ERROR!
//if not USER <username> then
// if not PASS <password> then
// if not ACCT <account> then ERROR!
//OK!
Action3: TLogonActions =
(3, 6, 3,
4, 6, FTP_ERR,
0, FTP_OK, 9,
1, FTP_OK, 12,
2, FTP_OK, FTP_ERR,
0, 0, 0);
//OPEN <FTPserver>
//if not USER <username> then
// if not PASS <password> then
// if not ACCT <account> then ERROR!
//OK!
Action4: TLogonActions =
(7, 3, 3,
0, FTP_OK, 6,
1, FTP_OK, 9,
2, FTP_OK, FTP_ERR,
0, 0, 0, 0, 0, 0);
//if USER <UserName>'@'<FTPServer> then OK!
//if not PASS <password> then
// if not ACCT <account> then ERROR!
//OK!
Action5: TLogonActions =
(6, FTP_OK, 3,
1, FTP_OK, 6,
2, FTP_OK, FTP_ERR,
0, 0, 0, 0, 0, 0, 0, 0, 0);
//if not USER <FWUserName>@<FTPServer> then
// if not PASS <FWPassword> then ERROR!
//if not USER <username> then
// if not PASS <password> then
// if not ACCT <account> then ERROR!
//OK!
Action6: TLogonActions =
(8, 6, 3,
4, 6, FTP_ERR,
0, FTP_OK, 9,
1, FTP_OK, 12,
2, FTP_OK, FTP_ERR,
0, 0, 0);
//if USER <UserName>@<FTPServer> <FWUserName> then ERROR!
//if not PASS <password> then
// if not ACCT <account> then ERROR!
//OK!
Action7: TLogonActions =
(9, FTP_ERR, 3,
1, FTP_OK, 6,
2, FTP_OK, FTP_ERR,
0, 0, 0, 0, 0, 0, 0, 0, 0);
//if not USER <UserName>@<FWUserName>@<FTPServer> then
// if not PASS <Password>@<FWPassword> then
// if not ACCT <account> then ERROR!
//OK!
Action8: TLogonActions =
(10, FTP_OK, 3,
11, FTP_OK, 6,
2, FTP_OK, FTP_ERR,
0, 0, 0, 0, 0, 0, 0, 0, 0);
var
FTPServer: string;
LogonActions: TLogonActions;
i: integer;
s: string;
x: integer;
begin
Result := False;
if FFWHost = '' then
Mode := 0;
if (FTargetPort = cFtpProtocol) or (FTargetPort = '21') then
FTPServer := FTargetHost
else
FTPServer := FTargetHost + ':' + FTargetPort;
case Mode of
-1:
LogonActions := CustomLogon;
1:
LogonActions := Action1;
2:
LogonActions := Action2;
3:
LogonActions := Action3;
4:
LogonActions := Action4;
5:
LogonActions := Action5;
6:
LogonActions := Action6;
7:
LogonActions := Action7;
8:
LogonActions := Action8;
else
LogonActions := Action0;
end;
i := 0;
repeat
case LogonActions[i] of
0: s := 'USER ' + FUserName;
1: s := 'PASS ' + FPassword;
2: s := 'ACCT ' + FAccount;
3: s := 'USER ' + FFWUserName;
4: s := 'PASS ' + FFWPassword;
5: s := 'SITE ' + FTPServer;
6: s := 'USER ' + FUserName + '@' + FTPServer;
7: s := 'OPEN ' + FTPServer;
8: s := 'USER ' + FFWUserName + '@' + FTPServer;
9: s := 'USER ' + FUserName + '@' + FTPServer + ' ' + FFWUserName;
10: s := 'USER ' + FUserName + '@' + FFWUserName + '@' + FTPServer;
11: s := 'PASS ' + FPassword + '@' + FFWPassword;
end;
x := FTPCommand(s);
x := x div 100;
if (x <> 2) and (x <> 3) then
Exit;
i := LogonActions[i + x - 1];
case i of
FTP_ERR:
Exit;
FTP_OK:
begin
Result := True;
Exit;
end;
end;
until False;
end;
function TFTPSend.Connect: Boolean;
begin
FSock.CloseSocket;
FSock.Bind(FIPInterface, cAnyPort);
if FSock.LastError = 0 then
if FFWHost = '' then
FSock.Connect(FTargetHost, FTargetPort)
else
FSock.Connect(FFWHost, FFWPort);
if FSock.LastError = 0 then
if FFullSSL then
FSock.SSLDoConnect;
Result := FSock.LastError = 0;
end;
function TFTPSend.Login: Boolean;
var
x: integer;
begin
Result := False;
FCanResume := False;
if not Connect then
Exit;
FIsTLS := FFullSSL;
FIsDataTLS := False;
repeat
x := ReadResult div 100;
until x <> 1;
if x <> 2 then
Exit;
if FAutoTLS and not(FIsTLS) then
if (FTPCommand('AUTH TLS') div 100) = 2 then
begin
FSock.SSLDoConnect;
FIsTLS := FSock.LastError = 0;
if not FIsTLS then
begin
Result := False;
Exit;
end;
end;
if not Auth(FFWMode) then
Exit;
if FIsTLS then
begin
FTPCommand('PBSZ 0');
if FTLSonData then
FIsDataTLS := (FTPCommand('PROT P') div 100) = 2;
if not FIsDataTLS then
FTPCommand('PROT C');
end;
FTPCommand('TYPE I');
FTPCommand('STRU F');
FTPCommand('MODE S');
if FTPCommand('REST 0') = 350 then
if FTPCommand('REST 1') = 350 then
begin
FTPCommand('REST 0');
FCanResume := True;
end;
Result := True;
end;
function TFTPSend.Logout: Boolean;
begin
Result := (FTPCommand('QUIT') div 100) = 2;
FSock.CloseSocket;
end;
procedure TFTPSend.ParseRemote(Value: string);
var
n: integer;
nb, ne: integer;
s: string;
x: integer;
begin
Value := trim(Value);
nb := Pos('(',Value);
ne := Pos(')',Value);
if (nb = 0) or (ne = 0) then
begin
nb:=RPos(' ',Value);
s:=Copy(Value, nb + 1, Length(Value) - nb);
end
else
begin
s:=Copy(Value,nb+1,ne-nb-1);
end;
for n := 1 to 4 do
if n = 1 then
FDataIP := Fetch(s, ',')
else
FDataIP := FDataIP + '.' + Fetch(s, ',');
x := StrToIntDef(Fetch(s, ','), 0) * 256;
x := x + StrToIntDef(Fetch(s, ','), 0);
FDataPort := IntToStr(x);
end;
procedure TFTPSend.ParseRemoteEPSV(Value: string);
var
n: integer;
s, v: string;
begin
s := SeparateRight(Value, '(');
s := Trim(SeparateLeft(s, ')'));
Delete(s, Length(s), 1);
v := '';
for n := Length(s) downto 1 do
if s[n] in ['0'..'9'] then
v := s[n] + v
else
Break;
FDataPort := v;
FDataIP := FTargetHost;
end;
function TFTPSend.DataSocket: boolean;
var
s: string;
begin
Result := False;
if FIsDataTLS then
FPassiveMode := True;
if FPassiveMode then
begin
if FSock.IP6used then
s := '2'
else
s := '1';
if FSock.IP6used and not(FForceOldPort) and ((FTPCommand('EPSV ' + s) div 100) = 2) then
begin
ParseRemoteEPSV(FResultString);
end
else
if FSock.IP6used then
Exit
else
begin
if (FTPCommand('PASV') div 100) <> 2 then
Exit;
ParseRemote(FResultString);
end;
FDSock.CloseSocket;
FDSock.Bind(FIPInterface, cAnyPort);
FDSock.Connect(FDataIP, FDataPort);
Result := FDSock.LastError = 0;
end
else
begin
FDSock.CloseSocket;
if FForceDefaultPort then
s := cFtpDataProtocol
else
s := '0';
//data conection from same interface as command connection
FDSock.Bind(FSock.GetLocalSinIP, s);
if FDSock.LastError <> 0 then
Exit;
FDSock.SetLinger(True, 10000);
FDSock.Listen;
FDSock.GetSins;
FDataIP := FDSock.GetLocalSinIP;
FDataIP := FDSock.ResolveName(FDataIP);
FDataPort := IntToStr(FDSock.GetLocalSinPort);
if FSock.IP6used and (not FForceOldPort) then
begin
if IsIp6(FDataIP) then
s := '2'
else
s := '1';
s := 'EPRT |' + s +'|' + FDataIP + '|' + FDataPort + '|';
Result := (FTPCommand(s) div 100) = 2;
end;
if not Result and IsIP(FDataIP) then
begin
s := ReplaceString(FDataIP, '.', ',');
s := 'PORT ' + s + ',' + IntToStr(FDSock.GetLocalSinPort div 256)
+ ',' + IntToStr(FDSock.GetLocalSinPort mod 256);
Result := (FTPCommand(s) div 100) = 2;
end;
end;
end;
function TFTPSend.AcceptDataSocket: Boolean;
var
x: TSocket;
begin
if FPassiveMode then
Result := True
else
begin
Result := False;
if FDSock.CanRead(FTimeout) then
begin
x := FDSock.Accept;
if not FDSock.UsingSocks then
FDSock.CloseSocket;
FDSock.Socket := x;
Result := True;
end;
end;
if Result and FIsDataTLS then
begin
FDSock.SSL.Assign(FSock.SSL);
FDSock.SSLDoConnect;
Result := FDSock.LastError = 0;
end;
end;
function TFTPSend.DataRead(const DestStream: TStream): Boolean;
var
x: integer;
begin
Result := False;
try
if not AcceptDataSocket then
Exit;
FDSock.RecvStreamRaw(DestStream, FTimeout);
FDSock.CloseSocket;
x := ReadResult;
Result := (x div 100) = 2;
finally
FDSock.CloseSocket;
end;
end;
function TFTPSend.DataWrite(const SourceStream: TStream): Boolean;
var
x: integer;
b: Boolean;
begin
Result := False;
try
if not AcceptDataSocket then
Exit;
FDSock.SendStreamRaw(SourceStream);
b := FDSock.LastError = 0;
FDSock.CloseSocket;
x := ReadResult;
Result := b and ((x div 100) = 2);
finally
FDSock.CloseSocket;
end;
end;
function TFTPSend.List(Directory: string; NameList: Boolean): Boolean;
var
x: integer;
begin
Result := False;
FDataStream.Clear;
FFTPList.Clear;