Debian Codegraph @

plugins/wfx/ftp/synapse/ftpsend.pas

raw
1 {==============================================================================|
2 | Project : Ararat Synapse | 004.000.000 |
3 |==============================================================================|
4 | Content: FTP client |
5 |==============================================================================|
6 | Copyright (c)1999-2011, Lukas Gebauer |
7 | All rights reserved. |
8 | |
9 | Redistribution and use in source and binary forms, with or without |
10 | modification, are permitted provided that the following conditions are met: |
11 | |
12 | Redistributions of source code must retain the above copyright notice, this |
13 | list of conditions and the following disclaimer. |
14 | |
15 | Redistributions in binary form must reproduce the above copyright notice, |
16 | this list of conditions and the following disclaimer in the documentation |
17 | and/or other materials provided with the distribution. |
18 | |
19 | Neither the name of Lukas Gebauer nor the names of its contributors may |
20 | be used to endorse or promote products derived from this software without |
21 | specific prior written permission. |
22 | |
23 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
24 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
25 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
26 | ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
27 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
28 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
29 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
30 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
31 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
32 | OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
33 | DAMAGE. |
34 |==============================================================================|
35 | The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
36 | Portions created by Lukas Gebauer are Copyright (c) 1999-2010. |
37 | All Rights Reserved. |
38 |==============================================================================|
39 | Contributor(s): |
40 | Petr Esner <[email protected]> |
41 |==============================================================================|
42 | History: see HISTORY.HTM from distribution package |
43 | (Found at URL: http://www.ararat.cz/synapse/) |
44 |==============================================================================}
45
46 {: @abstract(FTP client protocol)
47
48 Used RFC: RFC-959, RFC-2228, RFC-2428
49 }
50
51 {$IFDEF FPC}
52 {$MODE DELPHI}
53 {$ENDIF}
54 {$H+}
55 {$TYPEINFO ON}// Borland changed defualt Visibility from Public to Published
56 // and it requires RTTI to be generated $M+
57 {$M+}
58
59 {$IFDEF UNICODE}
60 {$WARN IMPLICIT_STRING_CAST OFF}
61 {$WARN IMPLICIT_STRING_CAST_LOSS OFF}
62 {$ENDIF}
63
64 unit ftpsend;
65
66 interface
67
68 uses
69 SysUtils, Classes,
70 blcksock, synautil, synaip, synsock;
71
72 const
73 cFtpProtocol = '21';
74 cFtpDataProtocol = '20';
75
76 {:Terminating value for TLogonActions}
77 FTP_OK = 255;
78 {:Terminating value for TLogonActions}
79 FTP_ERR = 254;
80
81 type
82 {:Array for holding definition of logon sequence.}
83 TLogonActions = array [0..17] of byte;
84
85 {:Procedural type for OnStatus event. Sender is calling @link(TFTPSend) object.
86 Value is FTP command or reply to this comand. (if it is reply, Response
87 is @True).}
88 TFTPStatus = procedure(Sender: TObject; Response: Boolean;
89 const Value: string) of object;
90
91 {: @abstract(Object for holding file information) parsed from directory
92 listing of FTP server.}
93 TFTPListRec = class(TObject)
94 private
95 FFileName: String;
96 FDirectory: Boolean;
97 FReadable: Boolean;
98 FFileSize: int64;
99 FFileTime: TDateTime;
100 FOriginalLine: string;
101 FMask: string;
102 FPermission: String;
103 public
104 {: You can assign another TFTPListRec to this object.}
105 procedure Assign(Value: TFTPListRec); virtual;
106 {:name of file}
107 property FileName: string read FFileName write FFileName;
108 {:if name is subdirectory not file.}
109 property Directory: Boolean read FDirectory write FDirectory;
110 {:if you have rights to read}
111 property Readable: Boolean read FReadable write FReadable;
112 {:size of file in bytes}
113 property FileSize: int64 read FFileSize write FFileSize;
114 {:date and time of file. Local server timezone is used. Any timezone
115 conversions was not done!}
116 property FileTime: TDateTime read FFileTime write FFileTime;
117 {:original unparsed line}
118 property OriginalLine: string read FOriginalLine write FOriginalLine;
119 {:mask what was used for parsing}
120 property Mask: string read FMask write FMask;
121 {:permission string (depending on used mask!)}
122 property Permission: string read FPermission write FPermission;
123 end;
124
125 {:@abstract(This is TList of TFTPListRec objects.)
126 This object is used for holding lististing of all files information in listed
127 directory on FTP server.}
128 TFTPList = class(TObject)
129 protected
130 FList: TList;
131 FLines: TStringList;
132 FMasks: TStringList;
133 FUnparsedLines: TStringList;
134 Monthnames: string;
135 BlockSize: string;
136 DirFlagValue: string;
137 FileName: string;
138 VMSFileName: string;
139 Day: string;
140 Month: string;
141 ThreeMonth: string;
142 YearTime: string;
143 Year: string;
144 Hours: string;
145 HoursModif: Ansistring;
146 Minutes: string;
147 Seconds: string;
148 Size: Ansistring;
149 Permissions: Ansistring;
150 DirFlag: string;
151 function GetListItem(Index: integer): TFTPListRec; virtual;
152 function ParseEPLF(Value: string): Boolean; virtual;
153 procedure ClearStore; virtual;
154 function ParseByMask(Value, NextValue, Mask: ansistring): Integer; virtual;
155 function CheckValues: Boolean; virtual;
156 procedure FillRecord(const Value: TFTPListRec); virtual;
157 public
158 {:Constructor. You not need create this object, it is created by TFTPSend
159 class as their property.}
160 constructor Create;
161 destructor Destroy; override;
162
163 {:Clear list.}
164 procedure Clear; virtual;
165
166 {:count of holded @link(TFTPListRec) objects}
167 function Count: integer; virtual;
168
169 {:Assigns one list to another}
170 procedure Assign(Value: TFTPList); virtual;
171
172 {:try to parse raw directory listing in @link(lines) to list of
173 @link(TFTPListRec).}
174 procedure ParseLines; virtual;
175
176 {:By this property you have access to list of @link(TFTPListRec).
177 This is for compatibility only. Please, use @link(Items) instead.}
178 property List: TList read FList;
179
180 {:By this property you have access to list of @link(TFTPListRec).}
181 property Items[Index: Integer]: TFTPListRec read GetListItem; default;
182
183 {:Set of lines with RAW directory listing for @link(parseLines)}
184 property Lines: TStringList read FLines;
185
186 {:Set of masks for directory listing parser. It is predefined by default,
187 however you can modify it as you need. (for example, you can add your own
188 definition mask.) Mask is same as mask used in TotalCommander.}
189 property Masks: TStringList read FMasks;
190
191 {:After @link(ParseLines) it holding lines what was not sucessfully parsed.}
192 property UnparsedLines: TStringList read FUnparsedLines;
193 end;
194
195 {:@abstract(Implementation of FTP protocol.)
196 Note: Are you missing properties for setting Username and Password? Look to
197 parent @link(TSynaClient) object! (Username and Password have default values
198 for "anonymous" FTP login)
199
200 Are you missing properties for specify server address and port? Look to
201 parent @link(TSynaClient) too!}
202 TFTPSend = class(TSynaClient)
203 protected
204 FOnStatus: TFTPStatus;
205 FSock: TTCPBlockSocket;
206 FDSock: TTCPBlockSocket;
207 FResultCode: Integer;
208 FResultString: string;
209 FFullResult: TStringList;
210 FAccount: string;
211 FFWHost: string;
212 FFWPort: string;
213 FFWUsername: string;
214 FFWPassword: string;
215 FFWMode: integer;
216 FDataStream: TMemoryStream;
217 FDataIP: string;
218 FDataPort: string;
219 FDirectFile: Boolean;
220 FDirectFileName: string;
221 FCanResume: Boolean;
222 FPassiveMode: Boolean;
223 FForceDefaultPort: Boolean;
224 FForceOldPort: Boolean;
225 FFtpList: TFTPList;
226 FBinaryMode: Boolean;
227 FAutoTLS: Boolean;
228 FIsTLS: Boolean;
229 FIsDataTLS: Boolean;
230 FTLSonData: Boolean;
231 FFullSSL: Boolean;
232 function Auth(Mode: integer): Boolean; virtual;
233 function Connect: Boolean; virtual;
234 function InternalStor(const Command: string; RestoreAt: int64): Boolean; virtual;
235 function DataSocket: Boolean; virtual;
236 function AcceptDataSocket: Boolean; virtual;
237 procedure DoStatus(Response: Boolean; const Value: string); virtual;
238 public
239 {:Custom definition of login sequence. You can use this when you set
240 @link(FWMode) to value -1.}
241 CustomLogon: TLogonActions;
242
243 constructor Create;
244 destructor Destroy; override;
245
246 {:Waits and read FTP server response. You need this only in special cases!}
247 function ReadResult: Integer; virtual;
248
249 {:Parse remote side information of data channel from value string (returned
250 by PASV command). This function you need only in special cases!}
251 procedure ParseRemote(Value: string); virtual;
252
253 {:Parse remote side information of data channel from value string (returned
254 by EPSV command). This function you need only in special cases!}
255 procedure ParseRemoteEPSV(Value: string); virtual;
256
257 {:Send Value as FTP command to FTP server. Returned result code is result of
258 this function.
259 This command is good for sending site specific command, or non-standard
260 commands.}
261 function FTPCommand(const Value: string): integer; virtual;
262
263 {:Connect and logon to FTP server. If you specify any FireWall, connect to
264 firewall and throw them connect to FTP server. Login sequence depending on
265 @link(FWMode).}
266 function Login: Boolean; virtual;
267
268 {:Logoff and disconnect from FTP server.}
269 function Logout: Boolean; virtual;
270
271 {:Break current transmission of data. (You can call this method from
272 Sock.OnStatus event, or from another thread.)}
273 procedure Abort; virtual;
274
275 {:Break current transmission of data. It is same as Abort, but it send abort
276 telnet commands prior ABOR FTP command. Some servers need it. (You can call
277 this method from Sock.OnStatus event, or from another thread.)}
278 procedure TelnetAbort; virtual;
279
280 {:Download directory listing of Directory on FTP server. If Directory is
281 empty string, download listing of current working directory.
282 If NameList is @true, download only names of files in directory.
283 (internally use NLST command instead LIST command)
284 If NameList is @false, returned list is also parsed to @link(FTPList)
285 property.}
286 function List(Directory: string; NameList: Boolean): Boolean; virtual;
287
288 {:Read data from FileName on FTP server. If Restore is @true and server
289 supports resume dowloads, download is resumed. (received is only rest
290 of file)}
291 function RetrieveFile(const FileName: string; Restore: Boolean): Boolean; virtual;
292
293 {:Send data to FileName on FTP server. If Restore is @true and server
294 supports resume upload, upload is resumed. (send only rest of file)
295 In this case if remote file is same length as local file, nothing will be
296 done. If remote file is larger then local, resume is disabled and file is
297 transfered from begin!}
298 function StoreFile(const FileName: string; Restore: Boolean): Boolean; virtual;
299
300 {:Send data to FTP server and assing unique name for this file.}
301 function StoreUniqueFile: Boolean; virtual;
302
303 {:Append data to FileName on FTP server.}
304 function AppendFile(const FileName: string): Boolean; virtual;
305
306 {:Rename on FTP server file with OldName to NewName.}
307 function RenameFile(const OldName, NewName: string): Boolean; virtual;
308
309 {:Delete file FileName on FTP server.}
310 function DeleteFile(const FileName: string): Boolean; virtual;
311
312 {:Return size of Filename file on FTP server. If command failed (i.e. not
313 implemented), return -1.}
314 function FileSize(const FileName: string): int64; virtual;
315
316 {:Send NOOP command to FTP server for preserve of disconnect by inactivity
317 timeout.}
318 function NoOp: Boolean; virtual;
319
320 {:Change currect working directory to Directory on FTP server.}
321 function ChangeWorkingDir(const Directory: string): Boolean; virtual;
322
323 {:walk to upper directory on FTP server.}
324 function ChangeToParentDir: Boolean; virtual;
325
326 {:walk to root directory on FTP server. (May not work with all servers properly!)}
327 function ChangeToRootDir: Boolean; virtual;
328
329 {:Delete Directory on FTP server.}
330 function DeleteDir(const Directory: string): Boolean; virtual;
331
332 {:Create Directory on FTP server.}
333 function CreateDir(const Directory: string): Boolean; virtual;
334
335 {:Return current working directory on FTP server.}
336 function GetCurrentDir: String; virtual;
337
338 {:Establish data channel to FTP server and retrieve data.
339 This function you need only in special cases, i.e. when you need to implement
340 some special unsupported FTP command!}
341 function DataRead(const DestStream: TStream): Boolean; virtual;
342
343 {:Establish data channel to FTP server and send data.
344 This function you need only in special cases, i.e. when you need to implement
345 some special unsupported FTP command.}
346 function DataWrite(const SourceStream: TStream): Boolean; virtual;
347 published
348 {:After FTP command contains result number of this operation.}
349 property ResultCode: Integer read FResultCode;
350
351 {:After FTP command contains main line of result.}
352 property ResultString: string read FResultString;
353
354 {:After any FTP command it contains all lines of FTP server reply.}
355 property FullResult: TStringList read FFullResult;
356
357 {:Account information used in some cases inside login sequence.}
358 property Account: string read FAccount Write FAccount;
359
360 {:Address of firewall. If empty string (default), firewall not used.}
361 property FWHost: string read FFWHost Write FFWHost;
362
363 {:port of firewall. standard value is same port as ftp server used. (21)}
364 property FWPort: string read FFWPort Write FFWPort;
365
366 {:Username for login to firewall. (if needed)}
367 property FWUsername: string read FFWUsername Write FFWUsername;
368
369 {:password for login to firewall. (if needed)}
370 property FWPassword: string read FFWPassword Write FFWPassword;
371
372 {:Type of Firewall. Used only if you set some firewall address. Supported
373 predefined firewall login sequences are described by comments in source
374 file where you can see pseudocode decribing each sequence.}
375 property FWMode: integer read FFWMode Write FFWMode;
376
377 {:Socket object used for TCP/IP operation on control channel. Good for
378 seting OnStatus hook, etc.}
379 property Sock: TTCPBlockSocket read FSock;
380
381 {:Socket object used for TCP/IP operation on data channel. Good for seting
382 OnStatus hook, etc.}
383 property DSock: TTCPBlockSocket read FDSock;
384
385 {:If you not use @link(DirectFile) mode, all data transfers is made to or
386 from this stream.}
387 property DataStream: TMemoryStream read FDataStream;
388
389 {:After data connection is established, contains remote side IP of this
390 connection.}
391 property DataIP: string read FDataIP;
392
393 {:After data connection is established, contains remote side port of this
394 connection.}
395 property DataPort: string read FDataPort;
396
397 {:Mode of data handling by data connection. If @False, all data operations
398 are made to or from @link(DataStream) TMemoryStream.
399 If @true, data operations is made directly to file in your disk. (filename
400 is specified by @link(DirectFileName) property.) Dafault is @False!}
401 property DirectFile: Boolean read FDirectFile Write FDirectFile;
402
403 {:Filename for direct disk data operations.}
404 property DirectFileName: string read FDirectFileName Write FDirectFileName;
405
406 {:Indicate after @link(Login) if remote server support resume downloads and
407 uploads.}
408 property CanResume: Boolean read FCanResume;
409
410 {:If true (default value), all transfers is made by passive method.
411 It is safer method for various firewalls.}
412 property PassiveMode: Boolean read FPassiveMode Write FPassiveMode;
413
414 {:Force to listen for dataconnection on standard port (20). Default is @false,
415 dataconnections will be made to any non-standard port reported by PORT FTP
416 command. This setting is not used, if you use passive mode.}
417 property ForceDefaultPort: Boolean read FForceDefaultPort Write FForceDefaultPort;
418
419 {:When is @true, then is disabled EPSV and EPRT support. However without this
420 commands you cannot use IPv6! (Disabling of this commands is needed only
421 when you are behind some crap firewall/NAT.}
422 property ForceOldPort: Boolean read FForceOldPort Write FForceOldPort;
423
424 {:You may set this hook for monitoring FTP commands and replies.}
425 property OnStatus: TFTPStatus read FOnStatus write FOnStatus;
426
427 {:After LIST command is here parsed list of files in given directory.}
428 property FtpList: TFTPList read FFtpList;
429
430 {:if @true (default), then data transfers is in binary mode. If this is set
431 to @false, then ASCII mode is used.}
432 property BinaryMode: Boolean read FBinaryMode Write FBinaryMode;
433
434 {:if is true, then if server support upgrade to SSL/TLS mode, then use them.}
435 property AutoTLS: Boolean read FAutoTLS Write FAutoTLS;
436
437 {:if server listen on SSL/TLS port, then you set this to true.}
438 property FullSSL: Boolean read FFullSSL Write FFullSSL;
439
440 {:Signalise, if control channel is in SSL/TLS mode.}
441 property IsTLS: Boolean read FIsTLS;
442
443 {:Signalise, if data transfers is in SSL/TLS mode.}
444 property IsDataTLS: Boolean read FIsDataTLS;
445
446 {:If @true (default), then try to use SSL/TLS on data transfers too.
447 If @false, then SSL/TLS is used only for control connection.}
448 property TLSonData: Boolean read FTLSonData write FTLSonData;
449 end;
450
451 {:A very useful function, and example of use can be found in the TFtpSend object.
452 Dowload specified file from FTP server to LocalFile.}
453 function FtpGetFile(const IP, Port, FileName, LocalFile,
454 User, Pass: string): Boolean;
455
456 {:A very useful function, and example of use can be found in the TFtpSend object.
457 Upload specified LocalFile to FTP server.}
458 function FtpPutFile(const IP, Port, FileName, LocalFile,
459 User, Pass: string): Boolean;
460
461 {:A very useful function, and example of use can be found in the TFtpSend object.
462 Initiate transfer of file between two FTP servers.}
463 function FtpInterServerTransfer(
464 const FromIP, FromPort, FromFile, FromUser, FromPass: string;
465 const ToIP, ToPort, ToFile, ToUser, ToPass: string): Boolean;
466
467 implementation
468
469 constructor TFTPSend.Create;
470 begin
471 inherited Create;
472 FFullResult := TStringList.Create;
473 FDataStream := TMemoryStream.Create;
474 FSock := TTCPBlockSocket.Create;
475 FSock.Owner := self;
476 FSock.ConvertLineEnd := True;
477 FDSock := TTCPBlockSocket.Create;
478 FDSock.Owner := self;
479 FFtpList := TFTPList.Create;
480 FTimeout := 300000;
481 FTargetPort := cFtpProtocol;
482 FUsername := 'anonymous';
483 FPassword := 'anonymous@' + FSock.LocalName;
484 FDirectFile := False;
485 FPassiveMode := True;
486 FForceDefaultPort := False;
487 FForceOldPort := false;
488 FAccount := '';
489 FFWHost := '';
490 FFWPort := cFtpProtocol;
491 FFWUsername := '';
492 FFWPassword := '';
493 FFWMode := 0;
494 FBinaryMode := True;
495 FAutoTLS := False;
496 FFullSSL := False;
497 FIsTLS := False;
498 FIsDataTLS := False;
499 FTLSonData := True;
500 end;
501
502 destructor TFTPSend.Destroy;
503 begin
504 FDSock.Free;
505 FSock.Free;
506 FFTPList.Free;
507 FDataStream.Free;
508 FFullResult.Free;
509 inherited Destroy;
510 end;
511
512 procedure TFTPSend.DoStatus(Response: Boolean; const Value: string);
513 begin
514 if assigned(OnStatus) then
515 OnStatus(Self, Response, Value);
516 end;
517
518 function TFTPSend.ReadResult: Integer;
519 var
520 s, c: AnsiString;
521 begin
522 FFullResult.Clear;
523 c := '';
524 repeat
525 s := FSock.RecvString(FTimeout);
526 if c = '' then
527 if length(s) > 3 then
528 if s[4] in [' ', '-'] then
529 c :=Copy(s, 1, 3);
530 FResultString := s;
531 FFullResult.Add(s);
532 DoStatus(True, s);
533 if FSock.LastError <> 0 then
534 Break;
535 until (c <> '') and (Pos(c + ' ', s) = 1);
536 Result := StrToIntDef(c, 0);
537 FResultCode := Result;
538 end;
539
540 function TFTPSend.FTPCommand(const Value: string): integer;
541 begin
542 FSock.Purge;
543 FSock.SendString(Value + CRLF);
544 DoStatus(False, Value);
545 Result := ReadResult;
546 end;
547
548 // based on idea by Petr Esner <[email protected]>
549 function TFTPSend.Auth(Mode: integer): Boolean;
550 const
551 //if not USER <username> then
552 // if not PASS <password> then
553 // if not ACCT <account> then ERROR!
554 //OK!
555 Action0: TLogonActions =
556 (0, FTP_OK, 3,
557 1, FTP_OK, 6,
558 2, FTP_OK, FTP_ERR,
559 0, 0, 0, 0, 0, 0, 0, 0, 0);
560
561 //if not USER <FWusername> then
562 // if not PASS <FWPassword> then ERROR!
563 //if SITE <FTPServer> then ERROR!
564 //if not USER <username> then
565 // if not PASS <password> then
566 // if not ACCT <account> then ERROR!
567 //OK!
568 Action1: TLogonActions =
569 (3, 6, 3,
570 4, 6, FTP_ERR,
571 5, FTP_ERR, 9,
572 0, FTP_OK, 12,
573 1, FTP_OK, 15,
574 2, FTP_OK, FTP_ERR);
575
576 //if not USER <FWusername> then
577 // if not PASS <FWPassword> then ERROR!
578 //if USER <UserName>'@'<FTPServer> then OK!
579 //if not PASS <password> then
580 // if not ACCT <account> then ERROR!
581 //OK!
582 Action2: TLogonActions =
583 (3, 6, 3,
584 4, 6, FTP_ERR,
585 6, FTP_OK, 9,
586 1, FTP_OK, 12,
587 2, FTP_OK, FTP_ERR,
588 0, 0, 0);
589
590 //if not USER <FWusername> then
591 // if not PASS <FWPassword> then ERROR!
592 //if not USER <username> then
593 // if not PASS <password> then
594 // if not ACCT <account> then ERROR!
595 //OK!
596 Action3: TLogonActions =
597 (3, 6, 3,
598 4, 6, FTP_ERR,
599 0, FTP_OK, 9,
600 1, FTP_OK, 12,
601 2, FTP_OK, FTP_ERR,
602 0, 0, 0);
603
604 //OPEN <FTPserver>
605 //if not USER <username> then
606 // if not PASS <password> then
607 // if not ACCT <account> then ERROR!
608 //OK!
609 Action4: TLogonActions =
610 (7, 3, 3,
611 0, FTP_OK, 6,
612 1, FTP_OK, 9,
613 2, FTP_OK, FTP_ERR,
614 0, 0, 0, 0, 0, 0);
615
616 //if USER <UserName>'@'<FTPServer> then OK!
617 //if not PASS <password> then
618 // if not ACCT <account> then ERROR!
619 //OK!
620 Action5: TLogonActions =
621 (6, FTP_OK, 3,
622 1, FTP_OK, 6,
623 2, FTP_OK, FTP_ERR,
624 0, 0, 0, 0, 0, 0, 0, 0, 0);
625
626 //if not USER <FWUserName>@<FTPServer> then
627 // if not PASS <FWPassword> then ERROR!
628 //if not USER <username> then
629 // if not PASS <password> then
630 // if not ACCT <account> then ERROR!
631 //OK!
632 Action6: TLogonActions =
633 (8, 6, 3,
634 4, 6, FTP_ERR,
635 0, FTP_OK, 9,
636 1, FTP_OK, 12,
637 2, FTP_OK, FTP_ERR,
638 0, 0, 0);
639
640 //if USER <UserName>@<FTPServer> <FWUserName> then ERROR!
641 //if not PASS <password> then
642 // if not ACCT <account> then ERROR!
643 //OK!
644 Action7: TLogonActions =
645 (9, FTP_ERR, 3,
646 1, FTP_OK, 6,
647 2, FTP_OK, FTP_ERR,
648 0, 0, 0, 0, 0, 0, 0, 0, 0);
649
650 //if not USER <UserName>@<FWUserName>@<FTPServer> then
651 // if not PASS <Password>@<FWPassword> then
652 // if not ACCT <account> then ERROR!
653 //OK!
654 Action8: TLogonActions =
655 (10, FTP_OK, 3,
656 11, FTP_OK, 6,
657 2, FTP_OK, FTP_ERR,
658 0, 0, 0, 0, 0, 0, 0, 0, 0);
659 var
660 FTPServer: string;
661 LogonActions: TLogonActions;
662 i: integer;
663 s: string;
664 x: integer;
665 begin
666 Result := False;
667 if FFWHost = '' then
668 Mode := 0;
669 if (FTargetPort = cFtpProtocol) or (FTargetPort = '21') then
670 FTPServer := FTargetHost
671 else
672 FTPServer := FTargetHost + ':' + FTargetPort;
673 case Mode of
674 -1:
675 LogonActions := CustomLogon;
676 1:
677 LogonActions := Action1;
678 2:
679 LogonActions := Action2;
680 3:
681 LogonActions := Action3;
682 4:
683 LogonActions := Action4;
684 5:
685 LogonActions := Action5;
686 6:
687 LogonActions := Action6;
688 7:
689 LogonActions := Action7;
690 8:
691 LogonActions := Action8;
692 else
693 LogonActions := Action0;
694 end;
695 i := 0;
696 repeat
697 case LogonActions[i] of
698 0: s := 'USER ' + FUserName;
699 1: s := 'PASS ' + FPassword;
700 2: s := 'ACCT ' + FAccount;
701 3: s := 'USER ' + FFWUserName;
702 4: s := 'PASS ' + FFWPassword;
703 5: s := 'SITE ' + FTPServer;
704 6: s := 'USER ' + FUserName + '@' + FTPServer;
705 7: s := 'OPEN ' + FTPServer;
706 8: s := 'USER ' + FFWUserName + '@' + FTPServer;
707 9: s := 'USER ' + FUserName + '@' + FTPServer + ' ' + FFWUserName;
708 10: s := 'USER ' + FUserName + '@' + FFWUserName + '@' + FTPServer;
709 11: s := 'PASS ' + FPassword + '@' + FFWPassword;
710 end;
711 x := FTPCommand(s);
712 x := x div 100;
713 if (x <> 2) and (x <> 3) then
714 Exit;
715 i := LogonActions[i + x - 1];
716 case i of
717 FTP_ERR:
718 Exit;
719 FTP_OK:
720 begin
721 Result := True;
722 Exit;
723 end;
724 end;
725 until False;
726 end;
727
728
729 function TFTPSend.Connect: Boolean;
730 begin
731 FSock.CloseSocket;
732 FSock.Bind(FIPInterface, cAnyPort);
733 if FSock.LastError = 0 then
734 if FFWHost = '' then
735 FSock.Connect(FTargetHost, FTargetPort)
736 else
737 FSock.Connect(FFWHost, FFWPort);
738 if FSock.LastError = 0 then
739 if FFullSSL then
740 FSock.SSLDoConnect;
741 Result := FSock.LastError = 0;
742 end;
743
744 function TFTPSend.Login: Boolean;
745 var
746 x: integer;
747 begin
748 Result := False;
749 FCanResume := False;
750 if not Connect then
751 Exit;
752 FIsTLS := FFullSSL;
753 FIsDataTLS := False;
754 repeat
755 x := ReadResult div 100;
756 until x <> 1;
757 if x <> 2 then
758 Exit;
759 if FAutoTLS and not(FIsTLS) then
760 if (FTPCommand('AUTH TLS') div 100) = 2 then
761 begin
762 FSock.SSLDoConnect;
763 FIsTLS := FSock.LastError = 0;
764 if not FIsTLS then
765 begin
766 Result := False;
767 Exit;
768 end;
769 end;
770 if not Auth(FFWMode) then
771 Exit;
772 if FIsTLS then
773 begin
774 FTPCommand('PBSZ 0');
775 if FTLSonData then
776 FIsDataTLS := (FTPCommand('PROT P') div 100) = 2;
777 if not FIsDataTLS then
778 FTPCommand('PROT C');
779 end;
780 FTPCommand('TYPE I');
781 FTPCommand('STRU F');
782 FTPCommand('MODE S');
783 if FTPCommand('REST 0') = 350 then
784 if FTPCommand('REST 1') = 350 then
785 begin
786 FTPCommand('REST 0');
787 FCanResume := True;
788 end;
789 Result := True;
790 end;
791
792 function TFTPSend.Logout: Boolean;
793 begin
794 Result := (FTPCommand('QUIT') div 100) = 2;
795 FSock.CloseSocket;
796 end;
797
798 procedure TFTPSend.ParseRemote(Value: string);
799 var
800 n: integer;
801 nb, ne: integer;
802 s: string;
803 x: integer;
804 begin
805 Value := trim(Value);
806 nb := Pos('(',Value);
807 ne := Pos(')',Value);
808 if (nb = 0) or (ne = 0) then
809 begin
810 nb:=RPos(' ',Value);
811 s:=Copy(Value, nb + 1, Length(Value) - nb);
812 end
813 else
814 begin
815 s:=Copy(Value,nb+1,ne-nb-1);
816 end;
817 for n := 1 to 4 do
818 if n = 1 then
819 FDataIP := Fetch(s, ',')
820 else
821 FDataIP := FDataIP + '.' + Fetch(s, ',');
822 x := StrToIntDef(Fetch(s, ','), 0) * 256;
823 x := x + StrToIntDef(Fetch(s, ','), 0);
824 FDataPort := IntToStr(x);
825 end;
826
827 procedure TFTPSend.ParseRemoteEPSV(Value: string);
828 var
829 n: integer;
830 s, v: AnsiString;
831 begin
832 s := SeparateRight(Value, '(');
833 s := Trim(SeparateLeft(s, ')'));
834 Delete(s, Length(s), 1);
835 v := '';
836 for n := Length(s) downto 1 do
837 if s[n] in ['0'..'9'] then
838 v := s[n] + v
839 else
840 Break;
841 FDataPort := v;
842 FDataIP := FTargetHost;
843 end;
844
845 function TFTPSend.DataSocket: boolean;
846 var
847 s: string;
848 begin
849 Result := False;
850 if FIsDataTLS then
851 FPassiveMode := True;
852 if FPassiveMode then
853 begin
854 if FSock.IP6used then
855 s := '2'
856 else
857 s := '1';
858 if FSock.IP6used and not(FForceOldPort) and ((FTPCommand('EPSV ' + s) div 100) = 2) then
859 begin
860 ParseRemoteEPSV(FResultString);
861 end
862 else
863 if FSock.IP6used then
864 Exit
865 else
866 begin
867 if (FTPCommand('PASV') div 100) <> 2 then
868 Exit;
869 ParseRemote(FResultString);
870 end;
871 FDSock.CloseSocket;
872 FDSock.Bind(FIPInterface, cAnyPort);
873
874 if FIsDataTLS then begin
875 FDSock.SSL.Session := FSock.SSL.Session;
876 end;
877
878 FDSock.Connect(FDataIP, FDataPort);
879 Result := FDSock.LastError = 0;
880 end
881 else
882 begin
883 FDSock.CloseSocket;
884 if FForceDefaultPort then
885 s := cFtpDataProtocol
886 else
887 s := '0';
888 //data conection from same interface as command connection
889 FDSock.Bind(FSock.GetLocalSinIP, s);
890 if FDSock.LastError <> 0 then
891 Exit;
892 FDSock.SetLinger(True, 10000);
893 FDSock.Listen;
894 FDSock.GetSins;
895 FDataIP := FDSock.GetLocalSinIP;
896 FDataIP := FDSock.ResolveName(FDataIP);
897 FDataPort := IntToStr(FDSock.GetLocalSinPort);
898 if FSock.IP6used and (not FForceOldPort) then
899 begin
900 if IsIp6(FDataIP) then
901 s := '2'
902 else
903 s := '1';
904 s := 'EPRT |' + s +'|' + FDataIP + '|' + FDataPort + '|';
905 Result := (FTPCommand(s) div 100) = 2;
906 end;
907 if not Result and IsIP(FDataIP) then
908 begin
909 s := ReplaceString(FDataIP, '.', ',');
910 s := 'PORT ' + s + ',' + IntToStr(FDSock.GetLocalSinPort div 256)
911 + ',' + IntToStr(FDSock.GetLocalSinPort mod 256);
912 Result := (FTPCommand(s) div 100) = 2;
913 end;
914 end;
915 end;
916
917 function TFTPSend.AcceptDataSocket: Boolean;
918 var
919 x: TSocket;
920 begin
921 if FPassiveMode then
922 Result := True
923 else
924 begin
925 Result := False;
926 if FDSock.CanRead(FTimeout) then
927 begin
928 x := FDSock.Accept;
929 if not FDSock.UsingSocks then
930 FDSock.CloseSocket;
931 FDSock.Socket := x;
932 Result := True;
933 end;
934 end;
935 if Result and FIsDataTLS then
936 begin
937 FDSock.SSL.Assign(FSock.SSL);
938 FDSock.SSLDoConnect;
939 Result := FDSock.LastError = 0;
940 end;
941 end;
942
943 function TFTPSend.DataRead(const DestStream: TStream): Boolean;
944 var
945 x: integer;
946 begin
947 Result := False;
948 try
949 if not AcceptDataSocket then
950 Exit;
951 FDSock.RecvStreamRaw(DestStream, FTimeout);
952 FDSock.CloseSocket;
953 x := ReadResult;
954 Result := (x div 100) = 2;
955 finally
956 FDSock.CloseSocket;
957 end;
958 end;
959
960 function TFTPSend.DataWrite(const SourceStream: TStream): Boolean;
961 var
962 x: integer;
963 b: Boolean;
964 begin
965 Result := False;
966 try
967 if not AcceptDataSocket then
968 Exit;
969 FDSock.SendStreamRaw(SourceStream);
970 b := FDSock.LastError = 0;
971 FDSock.CloseSocket;
972 x := ReadResult;
973 Result := b and ((x div 100) = 2);
974 finally
975 FDSock.CloseSocket;
976 end;
977 end;
978
979 function TFTPSend.List(Directory: string; NameList: Boolean): Boolean;
980 var
981 x: integer;
982 begin
983 Result := False;
984 FDataStream.Clear;
985 FFTPList.Clear;
986 if Directory <> '' then
987 Directory := ' ' + Directory;
988 FTPCommand('TYPE A');
989 if not DataSocket then
990 Exit;
991 if NameList then
992 x := FTPCommand('NLST' + Directory)
993 else
994 x := FTPCommand('LIST' + Directory);
995 if (x div 100) <> 1 then
996 Exit;
997 Result := DataRead(FDataStream);
998 if (not NameList) and Result then
999 begin
1000 FDataStream.Position := 0;
1001 FFTPList.Lines.LoadFromStream(FDataStream);
1002 FFTPList.ParseLines;
1003 end;
1004 FDataStream.Position := 0;
1005 end;
1006
1007 function TFTPSend.RetrieveFile(const FileName: string; Restore: Boolean): Boolean;
1008 var
1009 RetrStream: TStream;
1010 begin
1011 Result := False;
1012 if FileName = '' then
1013 Exit;
1014 if not DataSocket then
1015 Exit;
1016 Restore := Restore and FCanResume;
1017 if FDirectFile then
1018 if Restore and FileExists(FDirectFileName) then
1019 RetrStream := TFileStream.Create(FDirectFileName,
1020 fmOpenReadWrite or fmShareExclusive)
1021 else
1022 RetrStream := TFileStream.Create(FDirectFileName,
1023 fmCreate or fmShareDenyWrite)
1024 else
1025 RetrStream := FDataStream;
1026 try
1027 if FBinaryMode then
1028 FTPCommand('TYPE I')
1029 else
1030 FTPCommand('TYPE A');
1031 if Restore then
1032 begin
1033 RetrStream.Position := RetrStream.Size;
1034 if (FTPCommand('REST ' + IntToStr(RetrStream.Size)) div 100) <> 3 then
1035 Exit;
1036 end
1037 else
1038 if RetrStream is TMemoryStream then
1039 TMemoryStream(RetrStream).Clear;
1040 if (FTPCommand('RETR ' + FileName) div 100) <> 1 then
1041 Exit;
1042 Result := DataRead(RetrStream);
1043 if not FDirectFile then
1044 RetrStream.Position := 0;
1045 finally
1046 if FDirectFile then
1047 RetrStream.Free;
1048 end;
1049 end;
1050
1051 function TFTPSend.InternalStor(const Command: string; RestoreAt: int64): Boolean;
1052 var
1053 SendStream: TStream;
1054 StorSize: int64;
1055 begin
1056 Result := False;
1057 if FDirectFile then
1058 if not FileExists(FDirectFileName) then
1059 Exit
1060 else
1061 SendStream := TFileStream.Create(FDirectFileName,
1062 fmOpenRead or fmShareDenyWrite)
1063 else
1064 SendStream := FDataStream;
1065 try
1066 if not DataSocket then
1067 Exit;
1068 if FBinaryMode then
1069 FTPCommand('TYPE I')
1070 else
1071 FTPCommand('TYPE A');
1072 StorSize := SendStream.Size;
1073 if not FCanResume then
1074 RestoreAt := 0;
1075 if (StorSize > 0) and (RestoreAt = StorSize) then
1076 begin
1077 Result := True;
1078 Exit;
1079 end;
1080 if RestoreAt > StorSize then
1081 RestoreAt := 0;
1082 FTPCommand('ALLO ' + IntToStr(StorSize - RestoreAt));
1083 if FCanResume then
1084 if (FTPCommand('REST ' + IntToStr(RestoreAt)) div 100) <> 3 then
1085 Exit;
1086 SendStream.Position := RestoreAt;
1087 if (FTPCommand(Command) div 100) <> 1 then
1088 Exit;
1089 Result := DataWrite(SendStream);
1090 finally
1091 if FDirectFile then
1092 SendStream.Free;
1093 end;
1094 end;
1095
1096 function TFTPSend.StoreFile(const FileName: string; Restore: Boolean): Boolean;
1097 var
1098 RestoreAt: int64;
1099 begin
1100 Result := False;
1101 if FileName = '' then
1102 Exit;
1103 RestoreAt := 0;
1104 Restore := Restore and FCanResume;
1105 if Restore then
1106 begin
1107 RestoreAt := Self.FileSize(FileName);
1108 if RestoreAt < 0 then
1109 RestoreAt := 0;
1110 end;
1111 Result := InternalStor('STOR ' + FileName, RestoreAt);
1112 end;
1113
1114 function TFTPSend.StoreUniqueFile: Boolean;
1115 begin
1116 Result := InternalStor('STOU', 0);
1117 end;
1118
1119 function TFTPSend.AppendFile(const FileName: string): Boolean;
1120 begin
1121 Result := False;
1122 if FileName = '' then
1123 Exit;
1124 Result := InternalStor('APPE ' + FileName, 0);
1125 end;
1126
1127 function TFTPSend.NoOp: Boolean;
1128 begin
1129 Result := (FTPCommand('NOOP') div 100) = 2;
1130 end;
1131
1132 function TFTPSend.RenameFile(const OldName, NewName: string): Boolean;
1133 begin
1134 Result := False;
1135 if (FTPCommand('RNFR ' + OldName) div 100) <> 3 then
1136 Exit;
1137 Result := (FTPCommand('RNTO ' + NewName) div 100) = 2;
1138 end;
1139
1140 function TFTPSend.DeleteFile(const FileName: string): Boolean;
1141 begin
1142 Result := (FTPCommand('DELE ' + FileName) div 100) = 2;
1143 end;
1144
1145 function TFTPSend.FileSize(const FileName: string): int64;
1146 var
1147 s: string;
1148 begin
1149 Result := -1;
1150 if (FTPCommand('SIZE ' + FileName) div 100) = 2 then
1151 begin
1152 s := Trim(SeparateRight(ResultString, ' '));
1153 s := Trim(SeparateLeft(s, ' '));
1154 {$IFDEF VER100}
1155 Result := StrToIntDef(s, -1);
1156 {$ELSE}
1157 Result := StrToInt64Def(s, -1);
1158 {$ENDIF}
1159 end;
1160 end;
1161
1162 function TFTPSend.ChangeWorkingDir(const Directory: string): Boolean;
1163 begin
1164 Result := (FTPCommand('CWD ' + Directory) div 100) = 2;
1165 end;
1166
1167 function TFTPSend.ChangeToParentDir: Boolean;
1168 begin
1169 Result := (FTPCommand('CDUP') div 100) = 2;
1170 end;
1171
1172 function TFTPSend.ChangeToRootDir: Boolean;
1173 begin
1174 Result := ChangeWorkingDir('/');
1175 end;
1176
1177 function TFTPSend.DeleteDir(const Directory: string): Boolean;
1178 begin
1179 Result := (FTPCommand('RMD ' + Directory) div 100) = 2;
1180 end;
1181
1182 function TFTPSend.CreateDir(const Directory: string): Boolean;
1183 begin
1184 Result := (FTPCommand('MKD ' + Directory) div 100) = 2;
1185 end;
1186
1187 function TFTPSend.GetCurrentDir: String;
1188 begin
1189 Result := '';
1190 if (FTPCommand('PWD') div 100) = 2 then
1191 begin
1192 Result := SeparateRight(FResultString, '"');
1193 Result := Trim(Separateleft(Result, '"'));
1194 end;
1195 end;
1196
1197 procedure TFTPSend.Abort;
1198 begin
1199 FSock.SendString('ABOR' + CRLF);
1200 FDSock.StopFlag := True;
1201 end;
1202
1203 procedure TFTPSend.TelnetAbort;
1204 begin
1205 FSock.SendString(#$FF + #$F4 + #$FF + #$F2);
1206 Abort;
1207 end;
1208
1209 {==============================================================================}
1210
1211 procedure TFTPListRec.Assign(Value: TFTPListRec);
1212 begin
1213 FFileName := Value.FileName;
1214 FDirectory := Value.Directory;
1215 FReadable := Value.Readable;
1216 FFileSize := Value.FileSize;
1217 FFileTime := Value.FileTime;
1218 FOriginalLine := Value.OriginalLine;
1219 FMask := Value.Mask;
1220 end;
1221
1222 constructor TFTPList.Create;
1223 begin
1224 inherited Create;
1225 FList := TList.Create;
1226 FLines := TStringList.Create;
1227 FMasks := TStringList.Create;
1228 FUnparsedLines := TStringList.Create;
1229 //various UNIX
1230 FMasks.add('pppppppppp $!!!S*$TTT$DD$hh mm ss$YYYY$n*');
1231 FMasks.add('pppppppppp $!!!S*$DD$TTT$hh mm ss$YYYY$n*');
1232 FMasks.add('pppppppppp $!!!S*$TTT$DD$UUUUU$n*'); //mostly used UNIX format
1233 FMasks.add('pppppppppp $!!!S*$DD$TTT$UUUUU$n*');
1234 //MacOS
1235 FMasks.add('pppppppppp $!!S*$TTT$DD$UUUUU$n*');
1236 FMasks.add('pppppppppp $!S*$TTT$DD$UUUUU$n*');
1237 //Novell
1238 FMasks.add('d $!S*$TTT$DD$UUUUU$n*');
1239 //Windows
1240 FMasks.add('MM DD YY hh mmH !S* n*');
1241 FMasks.add('MM DD YY hh mmH $ d!n*');
1242 FMasks.add('MM DD YYYY hh mmH !S* n*');
1243 FMasks.add('MM DD YYYY hh mmH $ d!n*');
1244 FMasks.add('DD MM YYYY hh mmH !S* n*');
1245 FMasks.add('DD MM YYYY hh mmH $ d!n*');
1246 //VMS
1247 FMasks.add('v*$ DD TTT YYYY hh mm');
1248 FMasks.add('v*$!DD TTT YYYY hh mm');
1249 FMasks.add('n*$ YYYY MM DD hh mm$S*');
1250 //AS400
1251 FMasks.add('!S*$MM DD YY hh mm ss !n*');
1252 FMasks.add('!S*$DD MM YY hh mm ss !n*');
1253 FMasks.add('n*!S*$MM DD YY hh mm ss d');
1254 FMasks.add('n*!S*$DD MM YY hh mm ss d');
1255 //VxWorks
1256 FMasks.add('$S* TTT DD YYYY hh mm ss $n* $ d');
1257 FMasks.add('$S* TTT DD YYYY hh mm ss $n*');
1258 //Distinct
1259 FMasks.add('d $S*$TTT DD YYYY hh mm$n*');
1260 FMasks.add('d $S*$TTT DD$hh mm$n*');
1261 //PC-NFSD
1262 FMasks.add('nnnnnnnn.nnn dSSSSSSSSSSS MM DD YY hh mmH');
1263 //VOS
1264 FMasks.add('- SSSSS YY MM DD hh mm ss n*');
1265 FMasks.add('- d= SSSSS YY MM DD hh mm ss n*');
1266 //Unissys ClearPath
1267 FMasks.add('nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn SSSSSSSSS MM DD YYYY hh mm');
1268 FMasks.add('n*\x SSSSSSSSS MM DD YYYY hh mm');
1269 //IBM
1270 FMasks.add('- SSSSSSSSSSSS d MM DD YYYY hh mm n*');
1271 //OS9
1272 FMasks.add('- YY MM DD hhmm d SSSSSSSSS n*');
1273 //tandem
1274 FMasks.add('nnnnnnnn SSSSSSS DD TTT YY hh mm ss');
1275 //MVS
1276 FMasks.add('- YYYY MM DD SSSSS d=O n*');
1277 //BullGCOS8
1278 FMasks.add(' $S* MM DD YY hh mm ss !n*');
1279 FMasks.add('d $S* MM DD YY !n*');
1280 //BullGCOS7
1281 FMasks.add(' TTT DD YYYY n*');
1282 FMasks.add(' d n*');
1283 end;
1284
1285 destructor TFTPList.Destroy;
1286 begin
1287 Clear;
1288 FList.Free;
1289 FLines.Free;
1290 FMasks.Free;
1291 FUnparsedLines.Free;
1292 inherited Destroy;
1293 end;
1294
1295 procedure TFTPList.Clear;
1296 var
1297 n:integer;
1298 begin
1299 for n := 0 to FList.Count - 1 do
1300 if Assigned(FList[n]) then
1301 TFTPListRec(FList[n]).Free;
1302 FList.Clear;
1303 FLines.Clear;
1304 FUnparsedLines.Clear;
1305 end;
1306
1307 function TFTPList.Count: integer;
1308 begin
1309 Result := FList.Count;
1310 end;
1311
1312 function TFTPList.GetListItem(Index: integer): TFTPListRec;
1313 begin
1314 Result := nil;
1315 if Index < Count then
1316 Result := TFTPListRec(FList[Index]);
1317 end;
1318
1319 procedure TFTPList.Assign(Value: TFTPList);
1320 var
1321 flr: TFTPListRec;
1322 n: integer;
1323 begin
1324 Clear;
1325 for n := 0 to Value.Count - 1 do
1326 begin
1327 flr := TFTPListRec.Create;
1328 flr.Assign(Value[n]);
1329 Flist.Add(flr);
1330 end;
1331 Lines.Assign(Value.Lines);
1332 Masks.Assign(Value.Masks);
1333 UnparsedLines.Assign(Value.UnparsedLines);
1334 end;
1335
1336 procedure TFTPList.ClearStore;
1337 begin
1338 Monthnames := '';
1339 BlockSize := '';
1340 DirFlagValue := '';
1341 FileName := '';
1342 VMSFileName := '';
1343 Day := '';
1344 Month := '';
1345 ThreeMonth := '';
1346 YearTime := '';
1347 Year := '';
1348 Hours := '';
1349 HoursModif := '';
1350 Minutes := '';
1351 Seconds := '';
1352 Size := '';
1353 Permissions := '';
1354 DirFlag := '';
1355 end;
1356
1357 function TFTPList.ParseByMask(Value, NextValue, Mask: AnsiString): Integer;
1358 var
1359 Ivalue, IMask: integer;
1360 MaskC, LastMaskC: AnsiChar;
1361 c: AnsiChar;
1362 s: string;
1363 begin
1364 ClearStore;
1365 Result := 0;
1366 if Value = '' then
1367 Exit;
1368 if Mask = '' then
1369 Exit;
1370 Ivalue := 1;
1371 IMask := 1;
1372 Result := 1;
1373 LastMaskC := ' ';
1374 while Imask <= Length(mask) do
1375 begin
1376 if (Mask[Imask] <> '*') and (Ivalue > Length(Value)) then
1377 begin
1378 Result := 0;
1379 Exit;
1380 end;
1381 MaskC := Mask[Imask];
1382 if Ivalue > Length(Value) then
1383 Exit;
1384 c := Value[Ivalue];
1385 case MaskC of
1386 'n':
1387 FileName := FileName + c;
1388 'v':
1389 VMSFileName := VMSFileName + c;
1390 '.':
1391 begin
1392 if c in ['.', ' '] then
1393 FileName := TrimSP(FileName) + '.'
1394 else
1395 begin
1396 Result := 0;
1397 Exit;
1398 end;
1399 end;
1400 'D':
1401 Day := Day + c;
1402 'M':
1403 Month := Month + c;
1404 'T':
1405 ThreeMonth := ThreeMonth + c;
1406 'U':
1407 YearTime := YearTime + c;
1408 'Y':
1409 Year := Year + c;
1410 'h':
1411 Hours := Hours + c;
1412 'H':
1413 HoursModif := HoursModif + c;
1414 'm':
1415 Minutes := Minutes + c;
1416 's':
1417 Seconds := Seconds + c;
1418 'S':
1419 Size := Size + c;
1420 'p':
1421 Permissions := Permissions + c;
1422 'd':
1423 DirFlag := DirFlag + c;
1424 'x':
1425 if c <> ' ' then
1426 begin
1427 Result := 0;
1428 Exit;
1429 end;
1430 '*':
1431 begin
1432 s := '';
1433 if LastMaskC in ['n', 'v'] then
1434 begin
1435 if Imask = Length(Mask) then
1436 s := Copy(Value, IValue, Maxint)
1437 else
1438 while IValue <= Length(Value) do
1439 begin
1440 if Value[Ivalue] = ' ' then
1441 break;
1442 s := s + Value[Ivalue];
1443 Inc(Ivalue);
1444 end;
1445 if LastMaskC = 'n' then
1446 FileName := FileName + s
1447 else
1448 VMSFileName := VMSFileName + s;
1449 end
1450 else
1451 begin
1452 while IValue <= Length(Value) do
1453 begin
1454 if not(Value[Ivalue] in ['0'..'9']) then
1455 break;
1456 s := s + Value[Ivalue];
1457 Inc(Ivalue);
1458 end;
1459 case LastMaskC of
1460 'S':
1461 Size := Size + s;
1462 end;
1463 end;
1464 Dec(IValue);
1465 end;
1466 '!':
1467 begin
1468 while IValue <= Length(Value) do
1469 begin
1470 if Value[Ivalue] = ' ' then
1471 break;
1472 Inc(Ivalue);
1473 end;
1474 while IValue <= Length(Value) do
1475 begin
1476 if Value[Ivalue] <> ' ' then
1477 break;
1478 Inc(Ivalue);
1479 end;
1480 Dec(IValue);
1481 end;
1482 '$':
1483 begin
1484 while IValue <= Length(Value) do
1485 begin
1486 if not(Value[Ivalue] in [' ', #9]) then
1487 break;
1488 Inc(Ivalue);
1489 end;
1490 Dec(IValue);
1491 end;
1492 '=':
1493 begin
1494 s := '';
1495 case LastmaskC of
1496 'S':
1497 begin
1498 while Imask <= Length(Mask) do
1499 begin
1500 if not(Mask[Imask] in ['0'..'9']) then
1501 break;
1502 s := s + Mask[Imask];
1503 Inc(Imask);
1504 end;
1505 Dec(Imask);
1506 BlockSize := s;
1507 end;
1508 'T':
1509 begin
1510 Monthnames := Copy(Mask, IMask, 12 * 3);
1511 Inc(IMask, 12 * 3);
1512 end;
1513 'd':
1514 begin
1515 Inc(Imask);
1516 DirFlagValue := Mask[Imask];
1517 end;
1518 end;
1519 end;
1520 '\':
1521 begin
1522 Value := NextValue;
1523 IValue := 0;
1524 Result := 2;
1525 end;
1526 end;
1527 Inc(Ivalue);
1528 Inc(Imask);
1529 LastMaskC := MaskC;
1530 end;
1531 end;
1532
1533 function TFTPList.CheckValues: Boolean;
1534 var
1535 x, n: integer;
1536 begin
1537 Result := false;
1538 if FileName <> '' then
1539 begin
1540 if pos('?', VMSFilename) > 0 then
1541 Exit;
1542 if pos('*', VMSFilename) > 0 then
1543 Exit;
1544 end;
1545 if VMSFileName <> '' then
1546 if pos(';', VMSFilename) <= 0 then
1547 Exit;
1548 if (FileName = '') and (VMSFileName = '') then
1549 Exit;
1550 if Permissions <> '' then
1551 begin
1552 if length(Permissions) <> 10 then
1553 Exit;
1554 for n := 1 to 10 do
1555 if not(Permissions[n] in
1556 ['a', 'b', 'c', 'd', 'h', 'l', 'p', 'r', 's', 't', 'w', 'x', 'y', '-']) then
1557 Exit;
1558 end;
1559 if Day <> '' then
1560 begin
1561 Day := TrimSP(Day);
1562 x := StrToIntDef(day, -1);
1563 if (x < 1) or (x > 31) then
1564 Exit;
1565 end;
1566 if Month <> '' then
1567 begin
1568 Month := TrimSP(Month);
1569 x := StrToIntDef(Month, -1);
1570 if (x < 1) or (x > 12) then
1571 Exit;
1572 end;
1573 if Hours <> '' then
1574 begin
1575 Hours := TrimSP(Hours);
1576 x := StrToIntDef(Hours, -1);
1577 if (x < 0) or (x > 24) then
1578 Exit;
1579 end;
1580 if HoursModif <> '' then
1581 begin
1582 if not (HoursModif[1] in ['a', 'A', 'p', 'P']) then
1583 Exit;
1584 end;
1585 if Minutes <> '' then
1586 begin
1587 Minutes := TrimSP(Minutes);
1588 x := StrToIntDef(Minutes, -1);
1589 if (x < 0) or (x > 59) then
1590 Exit;
1591 end;
1592 if Seconds <> '' then
1593 begin
1594 Seconds := TrimSP(Seconds);
1595 x := StrToIntDef(Seconds, -1);
1596 if (x < 0) or (x > 59) then
1597 Exit;
1598 end;
1599 if Size <> '' then
1600 begin
1601 Size := TrimSP(Size);
1602 for n := 1 to Length(Size) do
1603 if not (Size[n] in ['0'..'9']) then
1604 Exit;
1605 end;
1606
1607 if length(Monthnames) = (12 * 3) then
1608 for n := 1 to 12 do
1609 CustomMonthNames[n] := Copy(Monthnames, ((n - 1) * 3) + 1, 3);
1610 if ThreeMonth <> '' then
1611 begin
1612 x := GetMonthNumber(ThreeMonth);
1613 if (x = 0) then
1614 Exit;
1615 end;
1616 if YearTime <> '' then
1617 begin
1618 YearTime := ReplaceString(YearTime, '-', ':');
1619 if pos(':', YearTime) > 0 then
1620 begin
1621 if (GetTimeFromstr(YearTime) = -1) then
1622 Exit;
1623 end
1624 else
1625 begin
1626 YearTime := TrimSP(YearTime);
1627 x := StrToIntDef(YearTime, -1);
1628 if (x = -1) then
1629 Exit;
1630 if (x < 1900) or (x > 2100) then
1631 Exit;
1632 end;
1633 end;
1634 if Year <> '' then
1635 begin
1636 Year := TrimSP(Year);
1637 x := StrToIntDef(Year, -1);
1638 if (x = -1) then
1639 Exit;
1640 if Length(Year) = 4 then
1641 begin
1642 if not((x > 1900) and (x < 2100)) then
1643 Exit;
1644 end
1645 else
1646 if Length(Year) = 2 then
1647 begin
1648 if not((x >= 0) and (x <= 99)) then
1649 Exit;
1650 end
1651 else
1652 if Length(Year) = 3 then
1653 begin
1654 if not((x >= 100) and (x <= 110)) then
1655 Exit;
1656 end
1657 else
1658 Exit;
1659 end;
1660 Result := True;
1661 end;
1662
1663 procedure TFTPList.FillRecord(const Value: TFTPListRec);
1664 var
1665 s: string;
1666 x: integer;
1667 myear: Word;
1668 mmonth: Word;
1669 mday: Word;
1670 mhours, mminutes, mseconds: word;
1671 n: integer;
1672 begin
1673 s := DirFlagValue;
1674 if s = '' then
1675 s := 'D';
1676 s := Uppercase(s);
1677 Value.Directory := s = Uppercase(DirFlag);
1678 if FileName <> '' then
1679 Value.FileName := SeparateLeft(Filename, ' -> ');
1680 if VMSFileName <> '' then
1681 begin
1682 Value.FileName := VMSFilename;
1683 Value.Directory := Pos('.DIR;',VMSFilename) > 0;
1684 end;
1685 Value.FileName := TrimSPRight(Value.FileName);
1686 Value.Readable := not Value.Directory;
1687 if BlockSize <> '' then
1688 x := StrToIntDef(BlockSize, 1)
1689 else
1690 x := 1;
1691 {$IFDEF VER100}
1692 Value.FileSize := x * StrToIntDef(Size, 0);
1693 {$ELSE}
1694 Value.FileSize := x * StrToInt64Def(Size, 0);
1695 {$ENDIF}
1696
1697 DecodeDate(Date,myear,mmonth,mday);
1698 mhours := 0;
1699 mminutes := 0;
1700 mseconds := 0;
1701
1702 if Day <> '' then
1703 mday := StrToIntDef(day, 1);
1704 if Month <> '' then
1705 mmonth := StrToIntDef(Month, 1);
1706 if length(Monthnames) = (12 * 3) then
1707 for n := 1 to 12 do
1708 CustomMonthNames[n] := Copy(Monthnames, ((n - 1) * 3) + 1, 3);
1709 if ThreeMonth <> '' then
1710 mmonth := GetMonthNumber(ThreeMonth);
1711 if Year <> '' then
1712 begin
1713 myear := StrToIntDef(Year, 0);
1714 if (myear <= 99) and (myear > 50) then
1715 myear := myear + 1900;
1716 if myear <= 50 then
1717 myear := myear + 2000;
1718 end;
1719 if YearTime <> '' then
1720 begin
1721 if pos(':', YearTime) > 0 then
1722 begin
1723 YearTime := TrimSP(YearTime);
1724 mhours := StrToIntDef(Separateleft(YearTime, ':'), 0);
1725 mminutes := StrToIntDef(SeparateRight(YearTime, ':'), 0);
1726 if (Encodedate(myear, mmonth, mday)
1727 + EncodeTime(mHours, mminutes, 0, 0)) > now then
1728 Dec(mYear);
1729 end
1730 else
1731 myear := StrToIntDef(YearTime, 0);
1732 end;
1733 if Minutes <> '' then
1734 mminutes := StrToIntDef(Minutes, 0);
1735 if Seconds <> '' then
1736 mseconds := StrToIntDef(Seconds, 0);
1737 if Hours <> '' then
1738 begin
1739 mHours := StrToIntDef(Hours, 0);
1740 if HoursModif <> '' then
1741 if Uppercase(HoursModif[1]) = 'P' then
1742 if mHours <> 12 then
1743 mHours := MHours + 12;
1744 end;
1745 Value.FileTime := Encodedate(myear, mmonth, mday)
1746 + EncodeTime(mHours, mminutes, mseconds, 0);
1747 if Permissions <> '' then
1748 begin
1749 Value.Permission := Permissions;
1750 Value.Readable := Uppercase(permissions)[2] = 'R';
1751 if Uppercase(permissions)[1] = 'D' then
1752 begin
1753 Value.Directory := True;
1754 Value.Readable := false;
1755 end
1756 else
1757 if Uppercase(permissions)[1] = 'L' then
1758 Value.Directory := True;
1759 end;
1760 end;
1761
1762 function TFTPList.ParseEPLF(Value: string): Boolean;
1763 var
1764 s, os: string;
1765 flr: TFTPListRec;
1766 begin
1767 Result := False;
1768 if Value <> '' then
1769 if Value[1] = '+' then
1770 begin
1771 os := Value;
1772 Delete(Value, 1, 1);
1773 flr := TFTPListRec.create;
1774 flr.FileName := SeparateRight(Value, #9);
1775 s := Fetch(Value, ',');
1776 while s <> '' do
1777 begin
1778 if s[1] = #9 then
1779 Break;
1780 case s[1] of
1781 '/':
1782 flr.Directory := true;
1783 'r':
1784 flr.Readable := true;
1785 's':
1786 {$IFDEF VER100}
1787 flr.FileSize := StrToIntDef(Copy(s, 2, Length(s) - 1), 0);
1788 {$ELSE}
1789 flr.FileSize := StrToInt64Def(Copy(s, 2, Length(s) - 1), 0);
1790 {$ENDIF}
1791 'm':
1792 flr.FileTime := (StrToIntDef(Copy(s, 2, Length(s) - 1), 0) / 86400)
1793 + 25569;
1794 end;
1795 s := Fetch(Value, ',');
1796 end;
1797 if flr.FileName <> '' then
1798 if (flr.Directory and ((flr.FileName = '.') or (flr.FileName = '..')))
1799 or (flr.FileName = '') then
1800 flr.free
1801 else
1802 begin
1803 flr.OriginalLine := os;
1804 flr.Mask := 'EPLF';
1805 Flist.Add(flr);
1806 Result := True;
1807 end;
1808 end;
1809 end;
1810
1811 procedure TFTPList.ParseLines;
1812 var
1813 flr: TFTPListRec;
1814 n, m: Integer;
1815 S: string;
1816 x: integer;
1817 b: Boolean;
1818 begin
1819 n := 0;
1820 while n < Lines.Count do
1821 begin
1822 if n = Lines.Count - 1 then
1823 s := ''
1824 else
1825 s := Lines[n + 1];
1826 b := False;
1827 x := 0;
1828 if ParseEPLF(Lines[n]) then
1829 begin
1830 b := True;
1831 x := 1;
1832 end
1833 else
1834 for m := 0 to Masks.Count - 1 do
1835 begin
1836 x := ParseByMask(Lines[n], s, Masks[m]);
1837 if x > 0 then
1838 if CheckValues then
1839 begin
1840 flr := TFTPListRec.create;
1841 FillRecord(flr);
1842 flr.OriginalLine := Lines[n];
1843 flr.Mask := Masks[m];
1844 if flr.Directory and ((flr.FileName = '.') or (flr.FileName = '..')) then
1845 flr.free
1846 else
1847 Flist.Add(flr);
1848 b := True;
1849 Break;
1850 end;
1851 end;
1852 if not b then
1853 FUnparsedLines.Add(Lines[n]);
1854 Inc(n);
1855 if x > 1 then
1856 Inc(n, x - 1);
1857 end;
1858 end;
1859
1860 {==============================================================================}
1861
1862 function FtpGetFile(const IP, Port, FileName, LocalFile,
1863 User, Pass: string): Boolean;
1864 begin
1865 Result := False;
1866 with TFTPSend.Create do
1867 try
1868 if User <> '' then
1869 begin
1870 Username := User;
1871 Password := Pass;
1872 end;
1873 TargetHost := IP;
1874 TargetPort := Port;
1875 if not Login then
1876 Exit;
1877 DirectFileName := LocalFile;
1878 DirectFile:=True;
1879 Result := RetrieveFile(FileName, False);
1880 Logout;
1881 finally
1882 Free;
1883 end;
1884 end;
1885
1886 function FtpPutFile(const IP, Port, FileName, LocalFile,
1887 User, Pass: string): Boolean;
1888 begin
1889 Result := False;
1890 with TFTPSend.Create do
1891 try
1892 if User <> '' then
1893 begin
1894 Username := User;
1895 Password := Pass;
1896 end;
1897 TargetHost := IP;
1898 TargetPort := Port;
1899 if not Login then
1900 Exit;
1901 DirectFileName := LocalFile;
1902 DirectFile:=True;
1903 Result := StoreFile(FileName, False);
1904 Logout;
1905 finally
1906 Free;
1907 end;
1908 end;
1909
1910 function FtpInterServerTransfer(
1911 const FromIP, FromPort, FromFile, FromUser, FromPass: string;
1912 const ToIP, ToPort, ToFile, ToUser, ToPass: string): Boolean;
1913 var
1914 FromFTP, ToFTP: TFTPSend;
1915 s: string;
1916 x: integer;
1917 begin
1918 Result := False;
1919 FromFTP := TFTPSend.Create;
1920 toFTP := TFTPSend.Create;
1921 try
1922 if FromUser <> '' then
1923 begin
1924 FromFTP.Username := FromUser;
1925 FromFTP.Password := FromPass;
1926 end;
1927 if ToUser <> '' then
1928 begin
1929 ToFTP.Username := ToUser;
1930 ToFTP.Password := ToPass;
1931 end;
1932 FromFTP.TargetHost := FromIP;
1933 FromFTP.TargetPort := FromPort;
1934 ToFTP.TargetHost := ToIP;
1935 ToFTP.TargetPort := ToPort;
1936 if not FromFTP.Login then
1937 Exit;
1938 if not ToFTP.Login then
1939 Exit;
1940 if (FromFTP.FTPCommand('PASV') div 100) <> 2 then
1941 Exit;
1942 FromFTP.ParseRemote(FromFTP.ResultString);
1943 s := ReplaceString(FromFTP.DataIP, '.', ',');
1944 s := 'PORT ' + s + ',' + IntToStr(StrToIntDef(FromFTP.DataPort, 0) div 256)
1945 + ',' + IntToStr(StrToIntDef(FromFTP.DataPort, 0) mod 256);
1946 if (ToFTP.FTPCommand(s) div 100) <> 2 then
1947 Exit;
1948 x := ToFTP.FTPCommand('RETR ' + FromFile);
1949 if (x div 100) <> 1 then
1950 Exit;
1951 x := FromFTP.FTPCommand('STOR ' + ToFile);
1952 if (x div 100) <> 1 then
1953 Exit;
1954 FromFTP.Timeout := 21600000;
1955 x := FromFTP.ReadResult;
1956 if (x div 100) <> 2 then
1957 Exit;
1958 ToFTP.Timeout := 21600000;
1959 x := ToFTP.ReadResult;
1960 if (x div 100) <> 2 then
1961 Exit;
1962 Result := True;
1963 finally
1964 ToFTP.Free;
1965 FromFTP.Free;
1966 end;
1967 end;
1968
1969 end.