Debian Codegraph @

plugins/wfx/ftp/src/sftp/scpsend.pas

raw
1 {
2 Double commander
3 -------------------------------------------------------------------------
4 Wfx plugin for working with File Transfer Protocol
5
6 Copyright (C) 2013-2024 Alexander Koblov ([email protected])
7
8 This library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Lesser General Public
10 License as published by the Free Software Foundation; either
11 version 2.1 of the License, or (at your option) any later version.
12
13 This library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public
19 License along with this library; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 }
22
23 unit ScpSend;
24
25 {$mode delphi}
26 {$pointermath on}
27
28 interface
29
30 uses
31 Classes, SysUtils, WfxPlugin, FtpAdv, libssh;
32
33 type
34
35 { TScpSend }
36
37 TScpSend = class(TFTPSendEx)
38 private
39 FAutoDetect: Boolean;
40 FListCommand: String;
41 FPassphrase: AnsiString;
42 FChannel: PLIBSSH2_CHANNEL;
43 FErrorStream: TStringBuilder;
44 private
45 function OpenChannel: Boolean;
46 procedure PrintErrors(const E: String);
47 function CloseChannel(Channel: PLIBSSH2_CHANNEL): Boolean;
48 function SendCommand(const Command: String): Boolean; overload;
49 function SendCommand(const Command: String; out Answer: String; Err: Boolean = True): Boolean; overload;
50 private
51 FAnswer: String;
52 protected
53 FAgent: Boolean;
54 FCurrentDir: String;
55 FLastError: Integer;
56 FSavedPassword: Boolean;
57 FFingerprint: AnsiString;
58 FSession: PLIBSSH2_SESSION;
59 SourceName, TargetName: PWideChar;
60 procedure DoProgress(Percent: Int64);
61 protected
62 procedure PrintLastError;
63 procedure DetectEncoding;
64 function AuthKey: Integer;
65 function AuthAgent: Integer;
66 function Connect: Boolean; override;
67 public
68 constructor Create(const Encoding: String); override;
69 destructor Destroy; override;
70 function Login: Boolean; override;
71 function Logout: Boolean; override;
72 function GetCurrentDir: String; override;
73 function NetworkError: Boolean; override;
74 procedure CloneTo(AValue: TFTPSendEx); override;
75 function FileSize(const FileName: String): Int64; override;
76 function FileExists(const FileName: String): Boolean; override;
77 function CreateDir(const Directory: string): Boolean; override;
78 function DeleteDir(const Directory: string): Boolean; override;
79 function DeleteFile(const FileName: string): Boolean; override;
80 function FileProperties(const FileName: String): Boolean; override;
81 function CopyFile(const OldName, NewName: String): Boolean; override;
82 function ChangeWorkingDir(const Directory: string): Boolean; override;
83 function RenameFile(const OldName, NewName: string): Boolean; override;
84 function ChangeMode(const FileName, Mode: String): Boolean; override;
85 function ExecuteCommand(const Command, Directory: String): Boolean; override;
86 function StoreFile(const FileName: string; Restore: Boolean): Boolean; override;
87 function RetrieveFile(const FileName: string; FileSize: Int64; Restore: Boolean): Boolean; override;
88 public
89 function DataRead(const DestStream: TStream): Boolean; override;
90 public
91 function List(Directory: String; NameList: Boolean): Boolean; override;
92 function FsSetTime(const FileName: String; LastAccessTime, LastWriteTime: PWfxFileTime): BOOL; override;
93 public
94 property Agent: Boolean read FAgent write FAgent;
95 property Fingerprint: AnsiString read FFingerprint write FFingerprint;
96 end;
97
98 implementation
99
100 uses
101 CTypes, LazUTF8, FtpFunc, DCStrUtils, DCClassesUtf8, DCOSUtils, DCDateTimeUtils,
102 DCBasicTypes, DCConvertEncoding, FileUtil, Base64, LConvEncoding, SynaCode, StrUtils;
103
104 const
105 TXT_BUFFER_SIZE = 4096;
106 SMB_BUFFER_SIZE = 131072;
107 LIST_TIME_STYLE = ' --time-style=+%Y.%m.%d-%H:%M:%S';
108 LIST_LOCALE_C = 'export LC_TIME=C' + #10 + 'export LC_MESSAGES=C' + #10;
109
110 procedure userauth_kbdint(const name: PAnsiChar; name_len: cint;
111 const instruction: PAnsiChar; instruction_len: cint;
112 num_prompts: cint; const prompts: PLIBSSH2_USERAUTH_KBDINT_PROMPT;
113 responses: PLIBSSH2_USERAUTH_KBDINT_RESPONSE; abstract: PPointer); cdecl;
114 var
115 S: String;
116 I: Integer;
117 Sender: TScpSend;
118 Title, Message, Password: UnicodeString;
119 begin
120 Sender:= TScpSend(abstract^);
121 for I:= 0 to num_prompts - 1 do
122 begin
123 if (I = 0) and (Length(Sender.FPassword) > 0) and (not Sender.FSavedPassword) then
124 begin
125 Sender.FSavedPassword:= True;
126 responses^.text:= GetMem(Length(Sender.FPassword) + 1);
127 StrCopy(responses^.text, PAnsiChar(Sender.FPassword));
128 responses^.length:= Length(Sender.FPassword);
129 end
130 else begin
131 Title:= EmptyWideStr;
132 Message:= EmptyWideStr;
133 if Assigned(instruction) and (instruction_len > 0) then
134 begin
135 SetString(S, instruction, instruction_len);
136 Message:= Sender.ServerToClient(S) + LineEnding;
137 end;
138 if Assigned(prompts[I].text) and (prompts[I].length > 0) then
139 begin
140 SetString(S, prompts[I].text, prompts[I].length);
141 Message+= Sender.ServerToClient(S);
142 end;
143 if Assigned(name) and (name_len > 0) then
144 begin
145 SetString(S, name, name_len);
146 Title:= Sender.ServerToClient(S) + #32;
147 end;
148 SetLength(Password, MAX_PATH + 1);
149 Title+= 'ssh://' + UTF8ToUTF16(Sender.UserName + '@' + Sender.TargetHost);
150 if not RequestProc(PluginNumber, RT_Password, PWideChar(Title), PWideChar(Message), PWideChar(Password), MAX_PATH) then
151 begin
152 responses[I].text:= nil;
153 responses[I].length:= 0;
154 end
155 else begin
156 Sender.FPassword:= Sender.ClientToServer(Password);
157 responses[I].text:= GetMem(Length(Sender.FPassword) + 1);
158 StrCopy(responses[I].text, PAnsiChar(Sender.FPassword));
159 responses[I].length:= Length(Sender.FPassword);
160 end;
161 end;
162 end;
163 end;
164
165 { TScpSend }
166
167 function TScpSend.OpenChannel: Boolean;
168 begin
169 repeat
170 FChannel := libssh2_channel_open_session(FSession);
171 if not Assigned(FChannel) then
172 begin
173 FLastError:= libssh2_session_last_errno(FSession);
174 if (FLastError <> LIBSSH2_ERROR_EAGAIN) then
175 begin
176 PrintLastError;
177 Exit(False);
178 end;
179 end;
180 until not ((FChannel = nil) and (FLastError = LIBSSH2_ERROR_EAGAIN));
181 Result:= Assigned(FChannel);
182 end;
183
184 function TScpSend.CloseChannel(Channel: PLIBSSH2_CHANNEL): Boolean;
185 begin
186 repeat
187 FLastError:= libssh2_channel_free(Channel);
188 until (FLastError <> LIBSSH2_ERROR_EAGAIN);
189 Result:= (FLastError = 0);
190 end;
191
192 procedure TScpSend.PrintErrors(const E: String);
193 var
194 S: String = '';
195 Index: Integer = 1;
196 begin
197 while GetNextLine(E, S, Index) do
198 begin
199 LogProc(PluginNumber, msgtype_importanterror, PWideChar(ServerToClient(S)));
200 end;
201 end;
202
203 function TScpSend.SendCommand(const Command: String): Boolean;
204 begin
205 repeat
206 FLastError := libssh2_channel_exec(FChannel, PAnsiChar(Command));
207 until (FLastError <> LIBSSH2_ERROR_EAGAIN);
208
209 while (libssh2_channel_flush(FChannel) = LIBSSH2_ERROR_EAGAIN) do;
210
211 while (libssh2_channel_send_eof(FChannel) = LIBSSH2_ERROR_EAGAIN) do;
212
213 Result:= (FLastError >= 0);
214 end;
215
216 function TScpSend.SendCommand(const Command: String; out Answer: String;
217 Err: Boolean): Boolean;
218 var
219 Ret: cint;
220 E, Buffer: String;
221 begin
222 Result:= OpenChannel;
223 if Result then
224 begin
225 Result:= SendCommand(Command);
226 if Result then
227 begin
228 E:= EmptyStr;
229 Answer:= EmptyStr;
230 SetLength(Buffer, TXT_BUFFER_SIZE + 1);
231 while libssh2_channel_eof(FChannel) = 0 do
232 begin
233 repeat
234 Ret:= libssh2_channel_read_stderr(FChannel, Pointer(Buffer), TXT_BUFFER_SIZE);
235 until Ret <> LIBSSH2_ERROR_EAGAIN;
236 if Ret > 0 then E+= Copy(Buffer, 1, Ret);
237
238 repeat
239 Ret:= libssh2_channel_read(FChannel, Pointer(Buffer), TXT_BUFFER_SIZE);
240 until Ret <> LIBSSH2_ERROR_EAGAIN;
241 if (Ret > 0) then Answer+= Copy(Buffer, 1, Ret);
242 end;
243 Result:= (libssh2_channel_get_exit_status(FChannel) = 0) and (Length(E) = 0);
244 if Err and (Length(E) > 0) then PrintErrors(E);
245 end;
246 CloseChannel(FChannel);
247 end;
248 end;
249
250 procedure TScpSend.DoProgress(Percent: Int64);
251 begin
252 if ProgressProc(PluginNumber, SourceName, TargetName, Percent) = 1 then
253 raise EUserAbort.Create(EmptyStr);
254 end;
255
256 procedure TScpSend.PrintLastError;
257 var
258 Message: String;
259 errmsg_len: cint;
260 errmsg: PAnsiChar;
261 begin
262 FLastError:= libssh2_session_last_error(FSession, @errmsg, @errmsg_len, 0);
263 SetString(Message, errmsg, errmsg_len);
264 LogProc(PluginNumber, msgtype_importanterror, PWideChar(UnicodeString('SSH ERROR ' + Message)));
265 end;
266
267 procedure TScpSend.DetectEncoding;
268 begin
269 if SendCommand('echo $LANG $LC_CTYPE $LC_ALL', FAnswer) then
270 begin
271 FAuto:= False;
272 if Pos('UTF-8', FAnswer) > 0 then
273 begin
274 Encoding:= EncodingUTF8;
275 end;
276 end;
277 end;
278
279 function TScpSend.AuthKey: Integer;
280 const
281 Alphabet = ['a'..'z','A'..'Z','0'..'9','+','/','=', #10, #13];
282 var
283 Key: String;
284 Index: Integer;
285 Memory: PAnsiChar;
286 PrivateStream: String;
287 Encrypted: Boolean = False;
288 Passphrase: AnsiString = '';
289 Title, Message, Password: UnicodeString;
290 begin
291 PrivateStream:= ReadFileToString(FPrivateKey);
292 // Check private key format
293 Index:= Pos(#10, PrivateStream);
294 if Index = 0 then Index:= Pos(#13, PrivateStream);
295 if Index > 0 then begin
296 // Skip first line and empty lines
297 Memory:= Pointer(@PrivateStream[Index]) + 1;
298 while Memory^ in [#10, #13] do Inc(Memory);
299 // Check old private key format
300 for Index:= 0 to 31 do
301 begin
302 if (not (Memory[Index] in Alphabet)) then
303 begin
304 Encrypted:= True;
305 Break;
306 end;
307 end;
308 // Check new OpenSSH private key format
309 if not Encrypted then
310 begin
311 if Pos('-----BEGIN OPENSSH PRIVATE KEY-----', PrivateStream) > 0 then
312 begin
313 Key:= DecodeStringBase64(Memory);
314 Index:= Pos('bcrypt', Key);
315 Encrypted:= (Index > 0) and (Index <= 64);
316 end;
317 end;
318 end;
319 // Private key encrypted, request passphrase
320 if Encrypted then
321 begin
322 if (Length(FPassphrase) > 0) then
323 Passphrase:= FPassphrase
324 else begin
325 SetLength(Password, MAX_PATH + 1);
326 Message:= 'Private key passphrase:';
327 Title:= 'ssh://' + UTF8ToUTF16(FUserName + '@' + FTargetHost);
328 if RequestProc(PluginNumber, RT_Password, PWideChar(Title), PWideChar(Message), PWideChar(Password), MAX_PATH) then
329 begin
330 Passphrase:= ClientToServer(Password);
331 FillWord(Password[1], Length(Password), 0);
332 end;
333 end;
334 end;
335
336 repeat
337 FLastError:= libssh2_userauth_publickey_fromfile(FSession, PAnsiChar(FUserName),
338 PAnsiChar(CeUtf8ToSys(FPublicKey)),
339 PAnsiChar(CeUtf8ToSys(FPrivateKey)),
340 PAnsiChar(Passphrase));
341 until (FLastError <> LIBSSH2_ERROR_EAGAIN);
342
343 // Save passphrase to cache
344 if (FLastError = 0) and (Length(Passphrase) > 0) then
345 begin
346 FPassphrase:= Passphrase;
347 end;
348
349 Result:= FLastError;
350 end;
351
352 function TScpSend.AuthAgent: Integer;
353 var
354 agent: PLIBSSH2_AGENT;
355 identity, prev_identity: Plibssh2_agent_publickey;
356 begin
357 agent:= libssh2_agent_init(FSession);
358 if (agent = nil) then Exit(-1);
359 try
360 Result:= libssh2_agent_connect(agent);
361 if (Result = LIBSSH2_ERROR_NONE) then
362 try
363 Result:= libssh2_agent_list_identities(agent);
364 if Result < 0 then Exit;
365 prev_identity:= nil;
366
367 while True do
368 begin
369 Result:= libssh2_agent_get_identity(agent, @identity, prev_identity);
370 if (Result < 0) then Exit;
371 if (Result = 1) then Exit(-1);
372
373 repeat
374 FLastError:= libssh2_agent_userauth(agent, PAnsiChar(FUserName), identity);
375 until (FLastError <> LIBSSH2_ERROR_EAGAIN);
376
377 if (FLastError <> 0) then
378 begin
379 DoStatus(False, Format('Authentication with username %s and public key %s failed', [username, identity^.comment]));
380 end
381 else begin
382 DoStatus(False, Format('Authentication with username %s and public key %s succeeded', [username, identity^.comment]));
383 Break;
384 end;
385 prev_identity:= identity;
386 end;
387 finally
388 libssh2_agent_disconnect(agent);
389 end;
390 finally
391 libssh2_agent_free(agent);
392 end;
393 end;
394
395 function TScpSend.Connect: Boolean;
396 const
397 HASH_SIZE: array[1..3] of Byte = (16, 20, 32);
398 HASH_NAME: array[1..3] of String = ('(MD5) ', '(SHA1) ', '(SHA256) ');
399 var
400 S: String;
401 F: String = '';
402 SS: String = '';
403 CS, SC: PAnsiChar;
404 I, J, Finish: Integer;
405 Message: UnicodeString;
406 FingerPrint: PAnsiChar;
407 userauthlist: PAnsiChar;
408 begin
409 FSock.CloseSocket;
410 DoStatus(False, 'Connecting to: ' + FTargetHost);
411 FSock.Connect(FTargetHost, FTargetPort);
412 Result:= (FSock.LastError = 0);
413 if Result then
414 begin
415 FSession := libssh2_session_init(Self);
416 if not Assigned(FSession) then Exit(False);
417 try
418 libssh2_session_set_timeout(FSession, FTimeout);
419
420 //* Since we have not set non-blocking, tell libssh2 we are blocking */
421 libssh2_session_set_blocking(FSession, 1);
422
423 FLastError:= libssh2_session_handshake(FSession, FSock.Socket);
424
425 DoStatus(False, 'Key exchange method: ' + libssh2_session_methods(FSession, LIBSSH2_METHOD_KEX));
426
427 CS:= libssh2_session_methods(FSession, LIBSSH2_METHOD_CRYPT_CS);
428 SC:= libssh2_session_methods(FSession, LIBSSH2_METHOD_CRYPT_SC);
429
430 if Assigned(CS) and Assigned(SC) and (StrComp(SC, SC) = 0) then
431 DoStatus(False, 'Encryption method: ' + CS)
432 else begin
433 DoStatus(False, 'Encryption method (client to server): ' + CS);
434 DoStatus(False, 'Encryption method (server to client): ' + SC);
435 end;
436 DoStatus(False, 'Host key method: ' + libssh2_session_methods(FSession, LIBSSH2_METHOD_HOSTKEY));
437
438 if FLastError <> 0 then
439 begin
440 DoStatus(False, 'Cannot perform the SSH handshake ' + IntToStr(FLastError));
441 PrintLastError;
442 Exit(False);
443 end;
444 LogProc(PluginNumber, MSGTYPE_CONNECT, nil);
445
446 DoStatus(False, 'Connection established');
447
448 if libssh2_version($010900) = nil then
449 Finish:= LIBSSH2_HOSTKEY_HASH_SHA1
450 else begin
451 Finish:= LIBSSH2_HOSTKEY_HASH_SHA256;
452 end;
453
454 for J:= LIBSSH2_HOSTKEY_HASH_MD5 to Finish do
455 begin
456 FingerPrint := libssh2_hostkey_hash(FSession, J);
457 if Assigned(FingerPrint) then
458 begin
459 if (J >= LIBSSH2_HOSTKEY_HASH_SHA256) then
460 begin
461 SetString(S, FingerPrint, HASH_SIZE[J]);
462 S := TrimRightSet(EncodeBase64(S), ['=']);
463 end
464 else begin
465 S:= EmptyStr;
466 for I:= 0 to HASH_SIZE[J] - 1 do
467 begin
468 S+= IntToHex(Ord(FingerPrint[I]), 2) + #32;
469 end;
470 SetLength(S, Length(S) - 1); // Remove space
471 end;
472 SS += HASH_NAME[J] + S + LineEnding;
473 DoStatus(False, 'Server fingerprint: ' + HASH_NAME[J] + S);
474 if (J > LIBSSH2_HOSTKEY_HASH_MD5) and (Length(F) = 0) then F:= S;
475 end;
476 end;
477
478 // Verify server fingerprint
479 if FFingerPrint <> F then
480 begin
481 if FFingerprint = EmptyStr then
482 Message:= 'You are using this connection for the first time.' + LineEnding + 'Please verify that the following host fingerprint matches the fingerprint of your server:'
483 else begin
484 Message:= 'WARNING!' + LineEnding + 'The fingerprint of the host has changed!' + LineEnding + 'Please make sure that the new fingerprint matches your server:';
485 end;
486 Message += UnicodeString(LineEnding + LineEnding + SS);
487 if not RequestProc(PluginNumber, RT_MsgYesNo, nil, PWideChar(Message), nil, 0) then
488 begin
489 LogProc(PluginNumber, msgtype_importanterror, 'Wrong server fingerprint!');
490 Exit(False);
491 end;
492 FFingerprint:= F;
493 end;
494
495 //* check what authentication methods are available */
496 userauthlist := libssh2_userauth_list(FSession, PAnsiChar(FUserName), Length(FUserName));
497
498 DoStatus(False, 'Authentication methods: ' + userauthlist);
499
500 if (libssh2_userauth_authenticated(FSession) <> 0) then
501 begin
502 DoStatus(False, 'Username authentication');
503 end
504 else if (strpos(userauthlist, 'publickey') <> nil) and (FAgent or ((FPublicKey <> '') and (FPrivateKey <> ''))) then
505 begin
506 if FAgent then
507 begin
508 DoStatus(False, 'SSH-agent authentication');
509 FLastError:= AuthAgent;
510 end
511 else begin
512 DoStatus(False, 'Public key authentication');
513 FLastError:= AuthKey;
514 end;
515 if (FLastError < 0) then
516 begin
517 PrintLastError;
518 Exit(False);
519 end;
520 end
521 else if (strpos(userauthlist, 'password') <> nil) then
522 begin
523 DoStatus(False, 'Password authentication');
524 repeat
525 FLastError := libssh2_userauth_password(FSession, PAnsiChar(FUserName), PAnsiChar(FPassword));
526 until (FLastError <> LIBSSH2_ERROR_EAGAIN);
527 if FLastError < 0 then
528 begin
529 PrintLastError;
530 Exit(False);
531 end;
532 end
533 else if (strpos(userauthlist, 'keyboard-interactive') <> nil) then
534 begin
535 FSavedPassword:= False;
536 libssh2_session_set_timeout(FSession, 0);
537 DoStatus(False, 'Keyboard interactive authentication');
538 repeat
539 FLastError := libssh2_userauth_keyboard_interactive(FSession, PAnsiChar(FUserName), @userauth_kbdint);
540 until (FLastError <> LIBSSH2_ERROR_EAGAIN);
541 if FLastError < 0 then
542 begin
543 PrintLastError;
544 Exit(False);
545 end;
546 libssh2_session_set_timeout(FSession, FTimeout);
547 end
548 else begin
549 LogProc(PluginNumber, msgtype_importanterror, 'Authentication failed');
550 Exit(False);
551 end;
552
553 DoStatus(False, 'Authentication succeeded');
554 finally
555 if not Result then begin
556 libssh2_session_free(FSession);
557 FSock.CloseSocket;
558 end;
559 end;
560 end;
561 end;
562
563 constructor TScpSend.Create(const Encoding: String);
564 begin
565 inherited Create(Encoding);
566 FTargetPort:= '22';
567 FListCommand:= 'ls -la';
568 FErrorStream:= TStringBuilder.Create;
569 end;
570
571 destructor TScpSend.Destroy;
572 begin
573 if (Length(FPassphrase) > 0) then
574 begin
575 if (StringRefCount(FPassphrase) = 1) then
576 begin
577 FillChar(FPassphrase[1], Length(FPassphrase), 0);
578 SetLength(FPassphrase, 0);
579 end;
580 end;
581 inherited Destroy;
582 FErrorStream.Free
583 end;
584
585 function TScpSend.Login: Boolean;
586 var
587 ACommand: String;
588 begin
589 Result:= Connect;
590 if Result then
591 begin
592 if FAuto then DetectEncoding;
593
594 if (Length(FCurrentDir) = 0) then
595 begin
596 if not SendCommand('pwd', FAnswer) then
597 FCurrentDir:= '/'
598 else begin
599 FCurrentDir:= TrimRightLineEnding(FAnswer, tlbsLF);
600 FCurrentDir:= CeUtf16ToUtf8(ServerToClient(FCurrentDir));
601 end;
602 DoStatus(False, 'Remote directory: ' + FCurrentDir);
603 end;
604 if not FAutoDetect then
605 begin
606 FAutoDetect:= True;
607 // Try to use custom time style
608 ACommand:= LIST_LOCALE_C + FListCommand + LIST_TIME_STYLE;
609 if SendCommand(ACommand + ' > /dev/null', FAnswer, False) then
610 begin
611 FListCommand:= ACommand;
612 FFtpList.Masks.Insert(0, 'pppppppppp $!!!S* YYYY MM DD hh mm ss $n*');
613 end
614 else begin
615 // Try to use 'C' locale
616 ACommand:= LIST_LOCALE_C + FListCommand;
617 if SendCommand(ACommand + ' > /dev/null', FAnswer, False) then
618 begin
619 FListCommand:= ACommand
620 end;
621 end;
622 end;
623 end;
624 end;
625
626 function TScpSend.Logout: Boolean;
627 begin
628 Result:= libssh2_session_disconnect(FSession, 'Logout') = 0;
629 libssh2_session_free(FSession);
630 FSock.CloseSocket;
631 end;
632
633 function TScpSend.GetCurrentDir: String;
634 begin
635 Result:= FCurrentDir;
636 end;
637
638 function TScpSend.NetworkError: Boolean;
639 begin
640 Result:= FSock.CanRead(0) and (libssh2_session_last_errno(FSession) <> 0);
641 end;
642
643 procedure TScpSend.CloneTo(AValue: TFTPSendEx);
644 begin
645 inherited CloneTo(AValue);
646 TScpSend(AValue).FAgent:= FAgent;
647 TScpSend(AValue).FPassphrase:= FPassphrase;
648 TScpSend(AValue).FFingerprint:= FFingerprint;
649 end;
650
651 function TScpSend.FileSize(const FileName: String): Int64;
652 begin
653 Result:= -1;
654 end;
655
656 function TScpSend.FileExists(const FileName: String): Boolean;
657 begin
658 Result:= SendCommand('stat ' + EscapeNoQuotes(FileName), FAnswer, False);
659 end;
660
661 function TScpSend.CreateDir(const Directory: string): Boolean;
662 begin
663 Result:= SendCommand('mkdir ' + EscapeNoQuotes(Directory), FAnswer);
664 end;
665
666 function TScpSend.DeleteDir(const Directory: string): Boolean;
667 begin
668 Result:= SendCommand('rmdir ' + EscapeNoQuotes(Directory), FAnswer);
669 end;
670
671 function TScpSend.DeleteFile(const FileName: string): Boolean;
672 begin
673 Result:= SendCommand('rm -f ' + EscapeNoQuotes(FileName), FAnswer);
674 end;
675
676 function TScpSend.ExecuteCommand(const Command, Directory: String): Boolean;
677 var
678 Index: Integer;
679 ADirectory: String;
680 Answer: TStringList;
681 begin
682 FDataStream.Clear;
683 Result:= OpenChannel;
684 if Result then
685 begin
686 if Directory = EmptyStr then
687 ADirectory:= FCurrentDir
688 else begin
689 ADirectory:= Directory;
690 end;
691 DoStatus(False, Command);
692 Result:= SendCommand('cd ' + EscapeNoQuotes(ADirectory) + ' && ' + Command);
693 if Result then
694 begin
695 if DataRead(FDataStream) then
696 begin
697 FDataStream.Position:= 0;
698 Answer:= TStringList.Create;
699 try
700 Answer.LoadFromStream(FDataStream);
701 for Index:= 0 to Answer.Count - 1 do
702 DoStatus(True, Answer.Strings[Index]);
703 finally
704 Answer.Free;
705 end;
706 end;
707 FDataStream.Clear;
708 end;
709 CloseChannel(FChannel);
710 end;
711 end;
712
713 function TScpSend.FileProperties(const FileName: String): Boolean;
714 begin
715 Result:= SendCommand('stat ' + EscapeNoQuotes(FileName), FAnswer);
716 if Result then FFullResult.Text:= FAnswer;
717 end;
718
719 function TScpSend.CopyFile(const OldName, NewName: String): Boolean;
720 begin
721 Result:= SendCommand('cp -p ' + EscapeNoQuotes(OldName) + ' ' + EscapeNoQuotes(NewName), FAnswer);
722 end;
723
724 function TScpSend.ChangeWorkingDir(const Directory: string): Boolean;
725 begin
726 Result:= SendCommand('cd ' + EscapeNoQuotes(Directory), FAnswer);
727 if Result then FCurrentDir:= Directory;
728 end;
729
730 function TScpSend.RenameFile(const OldName, NewName: string): Boolean;
731 begin
732 Result:= SendCommand('mv ' + EscapeNoQuotes(OldName) + ' ' + EscapeNoQuotes(NewName), FAnswer);
733 end;
734
735 function TScpSend.ChangeMode(const FileName, Mode: String): Boolean;
736 begin
737 Result:= SendCommand('chmod ' + Mode + ' ' + EscapeNoQuotes(FileName), FAnswer);
738 end;
739
740 function TScpSend.StoreFile(const FileName: string; Restore: Boolean): Boolean;
741 var
742 Index: PtrInt;
743 FBuffer: PByte;
744 FileSize: Int64;
745 BytesRead: Integer;
746 BytesToRead: Integer;
747 BytesWritten: PtrInt;
748 BytesToWrite: Integer;
749 SendStream: TFileStreamEx;
750 TotalBytesToWrite: Int64 = 0;
751 TargetHandle: PLIBSSH2_CHANNEL = nil;
752 begin
753 SendStream := TFileStreamEx.Create(FDirectFileName, fmOpenRead or fmShareDenyWrite);
754
755 TargetName:= PWideChar(ServerToClient(FileName));
756 SourceName:= PWideChar(CeUtf8ToUtf16(FDirectFileName));
757
758 FileSize:= SendStream.Size;
759 FBuffer:= GetMem(SMB_BUFFER_SIZE);
760 libssh2_session_set_blocking(FSession, 0);
761 try
762 TotalBytesToWrite:= FileSize;
763
764 // Open remote file
765 repeat
766 TargetHandle:= libssh2_scp_send64(FSession,
767 PAnsiChar(FileName),
768 $1A0, FileSize, 0, 0);
769 if (TargetHandle = nil) then
770 begin
771 FLastError:= libssh2_session_last_errno(FSession);
772 if (FLastError <> LIBSSH2_ERROR_EAGAIN) then Exit(False);
773 if (FileSize > 0) then DoProgress((FileSize - TotalBytesToWrite) * 100 div FileSize);
774 FSock.CanRead(10);
775 end;
776 until not ((TargetHandle = nil) and (FLastError = LIBSSH2_ERROR_EAGAIN));
777
778 BytesToRead:= SMB_BUFFER_SIZE;
779 while (TotalBytesToWrite > 0) do
780 begin
781 if (BytesToRead > TotalBytesToWrite) then begin
782 BytesToRead:= TotalBytesToWrite;
783 end;
784 BytesRead:= SendStream.Read(FBuffer^, BytesToRead);
785 if (BytesRead = 0) then Exit(False);
786 // Start write operation
787 Index:= 0;
788 BytesToWrite:= BytesRead;
789 while (BytesToWrite > 0) do
790 begin
791 repeat
792 BytesWritten:= libssh2_channel_write(TargetHandle, PAnsiChar(FBuffer + Index), BytesToWrite);
793 if BytesWritten = LIBSSH2_ERROR_EAGAIN then begin
794 DoProgress((FileSize - TotalBytesToWrite) * 100 div FileSize);
795 FSock.CanRead(10);
796 end;
797 until BytesWritten <> LIBSSH2_ERROR_EAGAIN;
798 if (BytesWritten < 0) then Exit(False);
799 Dec(TotalBytesToWrite, BytesWritten);
800 Dec(BytesToWrite, BytesWritten);
801 Inc(Index, BytesWritten);
802 end;
803 DoProgress((FileSize - TotalBytesToWrite) * 100 div FileSize);
804 end;
805 // Close remote file
806 repeat
807 FLastError:= libssh2_channel_send_eof(TargetHandle);
808 DoProgress(100);
809 FSock.CanRead(10);
810 until FLastError <> LIBSSH2_ERROR_EAGAIN;
811 Result:= (FLastError = 0);
812 finally
813 SendStream.Free;
814 FreeMem(FBuffer);
815 Result:= CloseChannel(TargetHandle) and Result;
816 libssh2_session_set_blocking(FSession, 1);
817 end;
818 end;
819
820 function TScpSend.RetrieveFile(const FileName: string; FileSize: Int64;
821 Restore: Boolean): Boolean;
822 var
823 FBuffer: PByte;
824 BytesRead: PtrInt;
825 BytesToRead: Integer;
826 RetrStream: TFileStreamEx;
827 TotalBytesToRead: Int64 = 0;
828 SourceHandle: PLIBSSH2_CHANNEL;
829 begin
830 RetrStream := TFileStreamEx.Create(FDirectFileName, fmCreate or fmShareDenyWrite);
831
832 SourceName := PWideChar(ServerToClient(FileName));
833 TargetName := PWideChar(CeUtf8ToUtf16(FDirectFileName));
834
835 libssh2_session_set_blocking(FSession, 0);
836 try
837 repeat
838 SourceHandle:= libssh2_scp_recv2(FSession,
839 PAnsiChar(FileName),
840 nil);
841 if (SourceHandle = nil) then
842 begin
843 FLastError:= libssh2_session_last_errno(FSession);
844 if (FLastError <> LIBSSH2_ERROR_EAGAIN) then Exit(False);
845 if (FileSize > 0) then DoProgress(TotalBytesToRead * 100 div FileSize);
846 FSock.CanRead(10);
847 end;
848 until not ((SourceHandle = nil) and (FLastError = LIBSSH2_ERROR_EAGAIN));
849
850 FBuffer:= GetMem(SMB_BUFFER_SIZE);
851 TotalBytesToRead:= FileSize - TotalBytesToRead;
852 try
853 BytesToRead:= SMB_BUFFER_SIZE;
854 while TotalBytesToRead > 0 do
855 begin
856 if (BytesToRead > TotalBytesToRead) then begin
857 BytesToRead := TotalBytesToRead;
858 end;
859 repeat
860 BytesRead := libssh2_channel_read(SourceHandle, PAnsiChar(FBuffer), BytesToRead);
861 if BytesRead = LIBSSH2_ERROR_EAGAIN then begin
862 DoProgress((FileSize - TotalBytesToRead) * 100 div FileSize);
863 FSock.CanRead(10);
864 end;
865 until BytesRead <> LIBSSH2_ERROR_EAGAIN;
866
867 if (BytesRead < 0) then Exit(False);
868
869 if RetrStream.Write(FBuffer^, BytesRead) <> BytesRead then
870 Exit(False);
871
872 Dec(TotalBytesToRead, BytesRead);
873 DoProgress((FileSize - TotalBytesToRead) * 100 div FileSize);
874 end;
875 Result:= True;
876 finally
877 FreeMem(FBuffer);
878 Result:= CloseChannel(SourceHandle) and Result;
879 end;
880 finally
881 RetrStream.Free;
882 libssh2_session_set_blocking(FSession, 1);
883 end;
884 end;
885
886 function TScpSend.DataRead(const DestStream: TStream): Boolean;
887 var
888 Ret: cint;
889 Buffer: String;
890 begin
891 FErrorStream.Clear;
892 SetLength(Buffer, TXT_BUFFER_SIZE + 1);
893 while libssh2_channel_eof(FChannel) = 0 do
894 begin
895 repeat
896 Ret:= libssh2_channel_read_stderr(FChannel, Pointer(Buffer), TXT_BUFFER_SIZE);
897 until Ret <> LIBSSH2_ERROR_EAGAIN;
898 if Ret > 0 then FErrorStream.Append(Copy(Buffer, 1, Ret));
899
900 repeat
901 Ret:= libssh2_channel_read(FChannel, Pointer(Buffer), TXT_BUFFER_SIZE);
902 until Ret <> LIBSSH2_ERROR_EAGAIN;
903 if Ret > 0 then DestStream.Write(Buffer[1], Ret);
904 end;
905 if (FErrorStream.Length > 0) then
906 begin
907 PrintErrors(FErrorStream.ToString);
908 end;
909 Result:= DestStream.Position > 0;
910 end;
911
912 function TScpSend.List(Directory: String; NameList: Boolean): Boolean;
913 begin
914 FFTPList.Clear;
915 FDataStream.Clear;
916 Result:= OpenChannel;
917 if Result then
918 begin
919 if Directory <> '' then begin
920 Directory := ' ' + EscapeNoQuotes(Directory);
921 end;
922 Result:= SendCommand(FListCommand + Directory);
923 if Result then
924 begin
925 Result:= DataRead(FDataStream);
926 if Result then
927 begin
928 FDataStream.Position := 0;
929 FFTPList.Lines.LoadFromStream(FDataStream);
930 FFTPList.ParseLines;
931 end;
932 FDataStream.Position := 0;
933 end;
934 CloseChannel(FChannel);
935 end;
936 end;
937
938 function TScpSend.FsSetTime(const FileName: String; LastAccessTime,
939 LastWriteTime: PWfxFileTime): BOOL;
940 var
941 DateTime: String;
942 FileTime: TDateTime;
943 begin
944 if (LastWriteTime = nil) then Exit(False);
945 FileTime:= WinFileTimeToDateTime(TWinFileTime(LastWriteTime^));
946 DateTime:= FormatDateTime('yyyymmddhhnn.ss', FileTime);
947 Result:= SendCommand('touch -ct ' + DateTime + ' ' + EscapeNoQuotes(FileName), FAnswer);
948 end;
949
950 end.
951