/
FtpFileSystem.cpp
5336 lines (4729 loc) · 156 KB
/
FtpFileSystem.cpp
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
#include <vcl.h>
#pragma hdrstop
#ifndef NO_FILEZILLA
#include <rdestl/list.h>
#ifndef MPEXT
#define MPEXT
#endif
#include "FtpFileSystem.h"
#include "FileZillaIntf.h"
#include <Common.h>
#include <nbutils.h>
#include <Exceptions.h>
#include "Terminal.h"
#include "TextsCore.h"
#include "TextsFileZilla.h"
#include "HelpCore.h"
#include "WinSCPSecurity.h"
#include <StrUtils.hpp>
#include <openssl/x509_vfy.h>
const int DummyCodeClass = 8;
const int DummyTimeoutCode = 801;
const int DummyCancelCode = 802;
const int DummyDisconnectCode = 803;
class TFileZillaImpl : public TFileZillaIntf
{
public:
explicit TFileZillaImpl(TFTPFileSystem *FileSystem);
virtual ~TFileZillaImpl()
{
}
virtual const wchar_t *Option(intptr_t OptionID) const override;
virtual intptr_t OptionVal(intptr_t OptionID) const override;
protected:
virtual bool DoPostMessage(TMessageType Type, WPARAM wParam, LPARAM lParam) override;
virtual bool HandleStatus(const wchar_t *Status, int Type) override;
virtual bool HandleAsynchRequestOverwrite(
wchar_t *FileName1, size_t FileName1Len, const wchar_t *FileName2,
const wchar_t *Path1, const wchar_t *Path2,
int64_t Size1, int64_t Size2, time_t LocalTime,
bool HasLocalTime, const TRemoteFileTime &RemoteTime, void *UserData,
HANDLE &LocalFileHandle, int &RequestResult) override;
virtual bool HandleAsynchRequestVerifyCertificate(
const TFtpsCertificateData &Data, int &RequestResult) override;
virtual bool HandleAsynchRequestNeedPass(
struct TNeedPassRequestData &Data, int &RequestResult) override;
virtual bool HandleListData(const wchar_t *Path, const TListDataEntry *Entries,
uintptr_t Count) override;
virtual bool HandleTransferStatus(bool Valid, int64_t TransferSize,
int64_t Bytes, bool FileTransfer) override;
virtual bool HandleReply(intptr_t Command, uintptr_t Reply) override;
virtual bool HandleCapabilities(TFTPServerCapabilities *ServerCapabilities) override;
virtual bool CheckError(intptr_t ReturnCode, const wchar_t *Context) override;
virtual void PreserveDownloadFileTime(HANDLE AHandle, void *UserData) override;
virtual bool GetFileModificationTimeInUtc(const wchar_t *FileName, struct tm &Time) override;
virtual wchar_t *LastSysErrorMessage() const override;
virtual std::wstring GetClientString() const override;
private:
TFTPFileSystem *FFileSystem;
};
TFileZillaImpl::TFileZillaImpl(TFTPFileSystem *FileSystem) :
TFileZillaIntf(),
FFileSystem(FileSystem)
{
}
const wchar_t *TFileZillaImpl::Option(intptr_t OptionID) const
{
return FFileSystem->GetOption(OptionID);
}
intptr_t TFileZillaImpl::OptionVal(intptr_t OptionID) const
{
return FFileSystem->GetOptionVal(OptionID);
}
bool TFileZillaImpl::DoPostMessage(TMessageType Type, WPARAM wParam, LPARAM lParam)
{
return FFileSystem->FTPPostMessage(Type, wParam, lParam);
}
bool TFileZillaImpl::HandleStatus(const wchar_t *Status, int Type)
{
return FFileSystem->HandleStatus(Status, Type);
}
bool TFileZillaImpl::HandleAsynchRequestOverwrite(
wchar_t *FileName1, size_t FileName1Len, const wchar_t *FileName2,
const wchar_t *Path1, const wchar_t *Path2,
int64_t Size1, int64_t Size2, time_t LocalTime,
bool HasLocalTime, const TRemoteFileTime &RemoteTime, void *UserData,
HANDLE &LocalFileHandle,
int &RequestResult)
{
return FFileSystem->HandleAsynchRequestOverwrite(
FileName1, FileName1Len, FileName2, Path1, Path2, Size1, Size2, LocalTime,
HasLocalTime, RemoteTime, UserData, LocalFileHandle, RequestResult);
}
bool TFileZillaImpl::HandleAsynchRequestVerifyCertificate(
const TFtpsCertificateData &Data, int &RequestResult)
{
return FFileSystem->HandleAsynchRequestVerifyCertificate(Data, RequestResult);
}
bool TFileZillaImpl::HandleAsynchRequestNeedPass(
struct TNeedPassRequestData &Data, int &RequestResult)
{
return FFileSystem->HandleAsynchRequestNeedPass(Data, RequestResult);
}
bool TFileZillaImpl::HandleListData(const wchar_t *Path,
const TListDataEntry *Entries, uintptr_t Count)
{
return FFileSystem->HandleListData(Path, Entries, Count);
}
bool TFileZillaImpl::HandleTransferStatus(bool Valid, int64_t TransferSize,
int64_t Bytes, bool FileTransfer)
{
return FFileSystem->HandleTransferStatus(Valid, TransferSize, Bytes, FileTransfer);
}
bool TFileZillaImpl::HandleReply(intptr_t Command, uintptr_t Reply)
{
return FFileSystem->HandleReply(Command, Reply);
}
bool TFileZillaImpl::HandleCapabilities(TFTPServerCapabilities *ServerCapabilities)
{
return FFileSystem->HandleCapabilities(ServerCapabilities);
}
bool TFileZillaImpl::CheckError(intptr_t ReturnCode, const wchar_t *Context)
{
return FFileSystem->CheckError(ReturnCode, Context);
}
void TFileZillaImpl::PreserveDownloadFileTime(HANDLE AHandle, void *UserData)
{
return FFileSystem->PreserveDownloadFileTime(AHandle, UserData);
}
bool TFileZillaImpl::GetFileModificationTimeInUtc(const wchar_t *FileName, struct tm &Time)
{
return FFileSystem->GetFileModificationTimeInUtc(FileName, Time);
}
wchar_t *TFileZillaImpl::LastSysErrorMessage() const
{
return _wcsdup(::LastSysErrorMessage().c_str());
}
std::wstring TFileZillaImpl::GetClientString() const
{
return std::wstring(GetSshVersionString().c_str());
}
struct message_t
{
CUSTOM_MEM_ALLOCATION_IMPL
message_t() : wparam(0),
lparam(0)
{
}
message_t(WPARAM w, LPARAM l) : wparam(w),
lparam(l)
{
}
WPARAM wparam;
LPARAM lparam;
};
class TMessageQueue : public TObject, public rde::list<message_t>
{
public:
typedef message_t value_type;
};
#if 0
// moved to FileSystems.h
struct TFileTransferData
{
TFileTransferData()
{
Params = 0;
AutoResume = false;
OverwriteResult = -1;
CopyParam = nullptr;
}
UnicodeString FileName;
int Params;
bool AutoResume;
int OverwriteResult;
const TCopyParamType *CopyParam;
TDateTime Modification;
};
const int tfFirstLevel = 0x01;
const int tfAutoResume = 0x02;
#endif // #if 0
static const wchar_t FtpsCertificateStorageKey[] = L"FtpsCertificates";
const UnicodeString SiteCommand(L"SITE");
const UnicodeString SymlinkSiteCommand(L"SYMLINK");
const UnicodeString CopySiteCommand(L"COPY");
const UnicodeString HashCommand(L"HASH"); // Cerberos + FileZilla servers
const UnicodeString AvblCommand(L"AVBL");
const UnicodeString XQuotaCommand(L"XQUOTA");
const UnicodeString DirectoryHasBytesPrefix(L"226-Directory has");
#if 0
// moved to FileSystems.h
struct TSinkFileParams
{
UnicodeString TargetDir;
const TCopyParamType *CopyParam;
int Params;
TFileOperationProgressType *OperationProgress;
bool Skipped;
unsigned int Flags;
};
#endif // #if 0
class TFTPFileListHelper : public TObject
{
NB_DISABLE_COPY(TFTPFileListHelper)
public:
explicit TFTPFileListHelper(TFTPFileSystem *FileSystem, TRemoteFileList *FileList,
bool IgnoreFileList) :
FFileSystem(FileSystem),
FFileList(FFileSystem->FFileList),
FIgnoreFileList(FFileSystem->FIgnoreFileList)
{
FFileSystem->FFileList = FileList;
FFileSystem->FIgnoreFileList = IgnoreFileList;
}
~TFTPFileListHelper()
{
FFileSystem->FFileList = FFileList;
FFileSystem->FIgnoreFileList = FIgnoreFileList;
}
private:
TFTPFileSystem *FFileSystem;
TRemoteFileList *FFileList;
bool FIgnoreFileList;
};
TFTPFileSystem::TFTPFileSystem(TTerminal *ATerminal) :
TCustomFileSystem(OBJECT_CLASS_TFTPFileSystem, ATerminal),
FFileZillaIntf(nullptr),
FQueue(new TMessageQueue),
FQueueEvent(::CreateEvent(nullptr, true, false, nullptr)),
FFileSystemInfoValid(false),
FReply(0),
FCommandReply(0),
FLastCommand(CMD_UNKNOWN),
FPasswordFailed(false),
FStoredPasswordTried(false),
FMultineResponse(false),
FLastCode(0),
FLastCodeClass(0),
FLastReadDirectoryProgress(0),
FLastResponse(new TStringList()),
FLastErrorResponse(new TStringList()),
FLastError(new TStringList()),
FFeatures(new TStringList()),
FReadCurrentDirectory(false),
FFileList(nullptr),
FFileListCache(nullptr),
FActive(false),
FOpening(false),
FWaitingForReply(false),
FFileTransferAbort(ftaNone),
FIgnoreFileList(false),
FFileTransferCancelled(false),
FFileTransferResumed(0),
FFileTransferPreserveTime(false),
FFileTransferRemoveBOM(false),
FFileTransferNoList(false),
FFileTransferCPSLimit(0),
FAwaitingProgress(false),
FOnCaptureOutput(nullptr),
FListAll(asOn),
FDoListAll(false),
FServerCapabilities(new TFTPServerCapabilities()),
FDetectTimeDifference(false),
FTimeDifference(0),
FSupportsAnyChecksumFeature(false),
FCertificate(nullptr),
FPrivateKey(nullptr),
FTransferActiveImmediately(false),
FWindowsServer(false),
FBytesAvailable(0),
FBytesAvailableSupported(false),
FMVS(false),
FVMS(false),
FFileTransferAny(false)
{
}
void TFTPFileSystem::Init(void *)
{
//FQueue.reserve(1000);
ResetReply();
FListAll = FTerminal->GetSessionData()->GetFtpListAll();
FFileSystemInfo.ProtocolBaseName = L"FTP";
FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
FTimeoutStatus = LoadStr(IDS_ERRORMSG_TIMEOUT);
FDisconnectStatus = LoadStr(IDS_STATUSMSG_DISCONNECTED);
FServerCapabilities = new TFTPServerCapabilities();
FHashAlgs.reset(new TStringList());
FSupportedCommands.reset(CreateSortedStringList());
FSupportedSiteCommands.reset(CreateSortedStringList());
FCertificate = nullptr;
FPrivateKey = nullptr;
FBytesAvailable = -1;
FBytesAvailableSupported = false;
FChecksumAlgs.reset(new TStringList());
FChecksumCommands.reset(new TStringList());
RegisterChecksumAlgCommand(Sha1ChecksumAlg, L"XSHA1"); // e.g. Cerberos FTP
RegisterChecksumAlgCommand(Sha256ChecksumAlg, L"XSHA256"); // e.g. Cerberos FTP
RegisterChecksumAlgCommand(Sha512ChecksumAlg, L"XSHA512"); // e.g. Cerberos FTP
RegisterChecksumAlgCommand(Md5ChecksumAlg, L"XMD5"); // e.g. Cerberos FTP
RegisterChecksumAlgCommand(Md5ChecksumAlg, L"MD5"); // e.g. Apache FTP
RegisterChecksumAlgCommand(Crc32ChecksumAlg, L"XCRC"); // e.g. Cerberos FTP
}
TFTPFileSystem::~TFTPFileSystem()
{
DebugAssert(FFileList == nullptr);
if (FFileZillaIntf)
{
FFileZillaIntf->Destroying();
// to release memory associated with the messages
DiscardMessages();
}
SAFE_DESTROY_EX(CFileZillaTools, FFileZillaIntf);
SAFE_DESTROY(FQueue);
SAFE_CLOSE_HANDLE(FQueueEvent);
SAFE_DESTROY(FLastResponse);
SAFE_DESTROY(FLastErrorResponse);
SAFE_DESTROY(FLastError);
SAFE_DESTROY(FFeatures);
SAFE_DESTROY_EX(TFTPServerCapabilities, FServerCapabilities);
SAFE_DESTROY(FLastError);
SAFE_DESTROY(FFeatures);
ResetCaches();
}
void TFTPFileSystem::Open()
{
// on reconnect, typically there may be pending status messages from previous session
DiscardMessages();
ResetCaches();
FReadCurrentDirectory = true;
FCurrentDirectory.Clear();
FHomeDirectory.Clear();
TSessionData *Data = FTerminal->GetSessionData();
FSessionInfo.LoginTime = Now();
FSessionInfo.ProtocolBaseName = L"FTP";
FSessionInfo.ProtocolName = FSessionInfo.ProtocolBaseName;
switch (Data->GetFtps())
{
case ftpsNone:
// noop;
break;
case ftpsImplicit:
FSessionInfo.SecurityProtocolName = LoadStr(FTPS_IMPLICIT);
break;
case ftpsExplicitSsl:
case ftpsExplicitTls:
FSessionInfo.SecurityProtocolName = LoadStr(FTPS_EXPLICIT);
break;
default:
DebugFail();
break;
}
FLastDataSent = Now();
FMultineResponse = false;
// initialize FZAPI on the first connect only
if (FFileZillaIntf == nullptr)
{
std::unique_ptr<TFileZillaIntf> FileZillaImpl(new TFileZillaImpl(this));
try__catch
{
TFileZillaIntf::TLogLevel LogLevel;
switch (FTerminal->GetConfiguration()->GetActualLogProtocol())
{
default:
case 0:
case 1:
LogLevel = TFileZillaIntf::LOG_PROGRESS;
break;
case 2:
LogLevel = TFileZillaIntf::LOG_INFO;
break;
}
FileZillaImpl->SetDebugLevel(LogLevel);
FileZillaImpl->Init();
FFileZillaIntf = FileZillaImpl.release();
}
#if 0
catch (...)
{
delete FFileZillaIntf;
FFileZillaIntf = nullptr;
throw;
}
#endif // #if 0
}
FWindowsServer = false;
FMVS = false;
FVMS = false;
FTransferActiveImmediately = (Data->GetFtpTransferActiveImmediately() == asOn);
FSessionInfo.LoginTime = Now();
UnicodeString HostName = Data->GetHostNameExpanded();
UnicodeString UserName = Data->GetUserNameExpanded();
UnicodeString Password = Data->GetPassword();
UnicodeString Account = Data->GetFtpAccount();
UnicodeString Path = Data->GetRemoteDirectory();
int ServerType = 0;
switch (Data->GetFtps())
{
case ftpsNone:
ServerType = TFileZillaIntf::SERVER_FTP;
break;
case ftpsImplicit:
ServerType = TFileZillaIntf::SERVER_FTP_SSL_IMPLICIT;
FSessionInfo.SecurityProtocolName = LoadStr(FTPS_IMPLICIT);
break;
case ftpsExplicitSsl:
ServerType = TFileZillaIntf::SERVER_FTP_SSL_EXPLICIT;
FSessionInfo.SecurityProtocolName = LoadStr(FTPS_EXPLICIT);
break;
case ftpsExplicitTls:
ServerType = TFileZillaIntf::SERVER_FTP_TLS_EXPLICIT;
FSessionInfo.SecurityProtocolName = LoadStr(FTPS_EXPLICIT);
break;
default:
DebugFail();
break;
}
intptr_t Pasv = (Data->GetFtpPasvMode() ? 1 : 2);
intptr_t TimeZoneOffset = Data->GetTimeDifferenceAuto() ? 0 : TimeToMinutes(Data->GetTimeDifference());
int UTF8;
uintptr_t CodePage = Data->GetCodePageAsNumber();
switch (CodePage)
{
case CP_ACP:
UTF8 = 2; // no UTF8
break;
case CP_UTF8:
UTF8 = 1; // always UTF8
break;
default:
UTF8 = 0; // auto detect
break;
}
FPasswordFailed = false;
FStoredPasswordTried = false;
bool PromptedForCredentials = false;
do
{
FDetectTimeDifference = Data->GetTimeDifferenceAuto();
FTimeDifference = 0;
ResetFeatures();
FSystem.Clear();
FWelcomeMessage.Clear();
FFileSystemInfoValid = false;
TODO("the same for account? it ever used?");
// ask for username if it was not specified in advance, even on retry,
// but keep previous one as default,
if (Data->GetUserNameExpanded().IsEmpty() && !FTerminal->GetSessionData()->GetFingerprintScan())
{
FTerminal->LogEvent("Username prompt (no username provided)");
if (!FPasswordFailed && !PromptedForCredentials)
{
FTerminal->Information(LoadStr(FTP_CREDENTIAL_PROMPT), false);
PromptedForCredentials = true;
}
if (!FTerminal->PromptUser(Data, pkUserName, LoadStr(USERNAME_TITLE), L"",
LoadStr(USERNAME_PROMPT2), true, 0, UserName))
{
FTerminal->FatalError(nullptr, LoadStr(AUTHENTICATION_FAILED));
}
else
{
FUserName = UserName;
}
}
// On retry ask for password.
// This is particularly important, when stored password is no longer valid,
// so we do not blindly try keep trying it in a loop (possibly causing account lockout)
if (FPasswordFailed)
{
FTerminal->LogEvent("Password prompt (last login attempt failed)");
Password.Clear();
if (!FTerminal->PromptUser(Data, pkPassword, LoadStr(PASSWORD_TITLE), L"",
LoadStr(PASSWORD_PROMPT), false, 0, Password))
{
FTerminal->FatalError(nullptr, LoadStr(AUTHENTICATION_FAILED));
}
}
if ((Data->GetFtps() != ftpsNone) && (FCertificate == nullptr))
{
FTerminal->LoadTlsCertificate(FCertificate, FPrivateKey);
}
FPasswordFailed = false;
TAutoFlag OpeningFlag(FOpening);
FActive = FFileZillaIntf->Connect(
HostName.c_str(), ToInt(Data->GetPortNumber()), UserName.c_str(),
Password.c_str(), Account.c_str(), Path.c_str(),
ServerType, ToInt(Pasv), ToInt(TimeZoneOffset), UTF8,
ToInt(CodePage),
ToInt(Data->GetFtpForcePasvIp()),
ToInt(Data->GetFtpUseMlsd()),
ToInt(Data->GetFtpDupFF()),
ToInt(Data->GetFtpUndupFF()),
FCertificate, FPrivateKey);
DebugAssert(FActive);
try
{
// do not wait for FTP response code as Connect is complex operation
GotReply(WaitForCommandReply(false), REPLY_CONNECT, LoadStr(CONNECTION_FAILED));
Shred(Password);
// we have passed, even if we got 530 on the way (if it is possible at all),
// ignore it
DebugAssert(!FPasswordFailed);
FPasswordFailed = false;
}
catch (...)
{
if (FPasswordFailed)
{
FTerminal->Information(LoadStr(Password.IsEmpty() ? FTP_ACCESS_DENIED_EMPTY_PASSWORD : FTP_ACCESS_DENIED), false);
}
else
{
// see handling of REPLY_CONNECT in GotReply
FTerminal->Closed();
throw;
}
}
}
while (FPasswordFailed);
// see also TWebDAVFileSystem::CollectTLSSessionInfo()
FSessionInfo.CSCipher = FFileZillaIntf->GetCipherName().c_str();
FSessionInfo.SCCipher = FSessionInfo.CSCipher;
UnicodeString TlsVersionStr = FFileZillaIntf->GetTlsVersionStr().c_str();
AddToList(FSessionInfo.SecurityProtocolName, TlsVersionStr, L", ");
}
void TFTPFileSystem::Close()
{
DebugAssert(FActive);
bool Result = DoQuit();
if (!Result)
{
if (FFileZillaIntf->Close(FOpening))
{
DebugCheck(FLAGSET(WaitForCommandReply(false), TFileZillaIntf::REPLY_DISCONNECTED));
Result = true;
}
else
{
// See TFileZillaIntf::Close
Result = FOpening;
}
}
if (DebugAlwaysTrue(Result))
{
DebugAssert(FActive);
Discard();
FTerminal->Closed();
}
}
bool TFTPFileSystem::GetActive() const
{
return FActive;
}
void TFTPFileSystem::CollectUsage()
{
#if 0
switch (FTerminal->SessionData->Ftps)
{
case ftpsNone:
// noop
break;
case ftpsImplicit:
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPSImplicit");
break;
case ftpsExplicitSsl:
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPSExplicitSSL");
break;
case ftpsExplicitTls:
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPSExplicitTLS");
break;
default:
DebugFail();
break;
}
if (!FTerminal->SessionData->TlsCertificateFile.IsEmpty())
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPSCertificate");
}
if (FFileZillaIntf->UsingMlsd())
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPMLSD");
}
else
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPLIST");
}
if (FFileZillaIntf->UsingUtf8())
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPUTF8");
}
else
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPNonUTF8");
}
if (!GetCurrentDirectory().IsEmpty() && (GetCurrentDirectory()[1] != L'/'))
{
if (::IsUnixStyleWindowsPath(GetCurrentDirectory()))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPWindowsPath");
}
else if ((GetCurrentDirectory().Length() >= 3) && IsLetter(GetCurrentDirectory()[1]) && (GetCurrentDirectory()[2] == L':') && (CurrentDirectory[3] == L'/'))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPRealWindowsPath");
}
else
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPOtherPath");
}
}
UnicodeString TlsVersionStr = FFileZillaIntf->GetTlsVersionStr().c_str();
if (!TlsVersionStr.IsEmpty())
{
FTerminal->CollectTlsUsage(TlsVersionStr);
}
// 220-FileZilla Server version 0.9.43 beta
// 220-written by Tim Kosse (Tim.Kosse@gmx.de)
// 220 Please visit http://sourceforge.net/projects/filezilla/
// SYST
// 215 UNIX emulated by FileZilla
// (Welcome message is configurable)
if (ContainsText(FSystem, L"FileZilla"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPFileZilla");
}
// 220 ProFTPD 1.3.4a Server (Debian) [::ffff:192.168.179.137]
// SYST
// 215 UNIX Type: L8
else if (ContainsText(FWelcomeMessage, L"ProFTPD"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPProFTPD");
}
// 220 Microsoft FTP Service
// SYST
// 215 Windows_NT
else if (ContainsText(FWelcomeMessage, L"Microsoft FTP Service") ||
ContainsText(FSystem, L"Windows_NT"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPIIS");
}
// 220 (vsFTPd 3.0.2)
// SYST
// 215 UNIX Type: L8
// (Welcome message is configurable)
else if (ContainsText(FWelcomeMessage, L"vsFTPd"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPvsFTPd");
}
// 220 Welcome to Pure-FTPd.
// ...
// SYST
// 215 UNIX Type: L8
else if (ContainsText(FWelcomeMessage, L"Pure-FTPd"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPPureFTPd");
}
// 220 Titan FTP Server 10.47.1892 Ready.
// ...
// SYST
// 215 UNIX Type: L8
else if (ContainsText(FWelcomeMessage, L"Titan FTP Server"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPTitan");
}
// 220-Cerberus FTP Server - Home Edition
// 220-This is the UNLICENSED Home Edition and may be used for home, personal use only
// 220-Welcome to Cerberus FTP Server
// 220 Created by Cerberus, LLC
else if (ContainsText(FWelcomeMessage, L"Cerberus FTP Server"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPCerberus");
}
// 220 Serv-U FTP Server v15.1 ready...
else if (ContainsText(FWelcomeMessage, L"Serv-U FTP Server"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPServU");
}
else if (ContainsText(FWelcomeMessage, L"WS_FTP"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPWSFTP");
}
// 220 Welcome to the most popular FTP hosting service! Save on hardware, software, hosting and admin. Share files/folders with read-write permission. Visit http://www.drivehq.com/ftp/
// ...
// SYST
// 215 UNIX emulated by DriveHQ FTP Server.
else if (ContainsText(FSystem, L"DriveHQ"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPDriveHQ");
}
// 220 GlobalSCAPE EFT Server (v. 6.0) * UNREGISTERED COPY *
// ...
// SYST
// 215 UNIX Type: L8
else if (ContainsText(FWelcomeMessage, L"GlobalSCAPE"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPGlobalScape");
}
// 220-<custom message>
// 220 CompleteFTP v 8.1.3
// ...
// SYST
// UNIX Type: L8
else if (ContainsText(FWelcomeMessage, L"CompleteFTP"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPComplete");
}
// 220 Core FTP Server Version 1.2, build 567, 64-bit, installed 8 days ago Unregistered
// ...
// SYST
// 215 UNIX Type: L8
else if (ContainsText(FWelcomeMessage, L"Core FTP Server"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPCore");
}
// 220 Service ready for new user.
// ..
// SYST
// 215 UNIX Type: Apache FtpServer
// (e.g. brickftp.com)
else if (ContainsText(FSystem, L"Apache FtpServer"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPApache");
}
// 220 pos1 FTP server (GNU inetutils 1.3b) ready.
// ...
// SYST
// 215 UNIX Type: L8 Version: Linux 2.6.15.7-ELinOS-314pm3
// Displaying "(GNU inetutils 1.3b)" in a welcome message can be turned off (-q switch):
// 220 pos1 FTP server ready.
// (the same for "Version: Linux 2.6.15.7-ELinOS-314pm3" in SYST response)
else if (ContainsText(FWelcomeMessage, L"GNU inetutils"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPInetutils");
}
// 220 Syncplify.me Server! FTP(S) Service Ready
// Message is configurable
else if (ContainsText(FWelcomeMessage, L"Syncplify"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPSyncplify");
}
// 220-Idea FTP Server v0.80 (xxx.home.pl) [xxx.xxx.xxx.xxx]
// 220 Ready
// ...
// SYST
// UNIX Type: L8
else if (ContainsText(FWelcomeMessage, L"Idea FTP Server"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPIdea");
}
// 220-FTPD1 IBM FTP CS V2R1 at name.test.com, 13:49:38 on 2016-01-28.
// ...
// SYST
// 215 MVS is the operating system of this server. FTP Server is running on z/OS.
else if (FMVS)
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPMVS");
}
// 220 xxx.xxx.xxx (xxx.xxx.xxx) FTP-OpenVMS FTPD V5.3-3 (c) 1998 Process Software Corporation
// ...
// SYST
// 215 VMS system type. VMS V5.5-2.
else if (FVMS)
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPVMS");
}
else
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPOther");
}
#endif // #if 0
}
void TFTPFileSystem::DummyReadDirectory(UnicodeString Directory)
{
std::unique_ptr<TRemoteDirectory> Files(new TRemoteDirectory(FTerminal));
try
{
Files->SetDirectory(Directory);
DoReadDirectory(Files.get());
}
catch (...)
{
// ignore non-fatal errors
// (i.e. current directory may not exist anymore)
if (!FTerminal->GetActive())
{
throw;
}
}
}
void TFTPFileSystem::Idle()
{
if (FActive && !FWaitingForReply)
{
PoolForFatalNonCommandReply();
// Keep session alive
if ((FTerminal->GetSessionData()->GetFtpPingType() != ptOff) &&
((Now() - FLastDataSent).GetValue() > FTerminal->GetSessionData()->GetFtpPingIntervalDT().GetValue() * 4))
{
FTerminal->LogEvent("Dummy directory read to keep session alive.");
FLastDataSent = Now(); // probably redundant to the same statement in DoReadDirectory
DummyReadDirectory(RemoteGetCurrentDirectory());
}
}
}
void TFTPFileSystem::Discard()
{
// remove all pending messages, to get complete log
// note that we need to retry discard on reconnect, as there still may be another
// "disconnect/timeout/..." status messages coming
DiscardMessages();
DebugAssert(FActive);
FActive = false;
// See neon's ne_ssl_clicert_free
if (FPrivateKey != nullptr)
{
EVP_PKEY_free(FPrivateKey);
FPrivateKey = nullptr;
}
if (FCertificate != nullptr)
{
X509_free(FCertificate);
FCertificate = nullptr;
}
}
UnicodeString TFTPFileSystem::GetAbsolutePath(UnicodeString APath, bool Local)
{
return static_cast<const TFTPFileSystem *>(this)->GetAbsolutePath(APath, Local);
}
UnicodeString TFTPFileSystem::GetAbsolutePath(UnicodeString APath, bool /*Local*/) const
{
TODO("improve (handle .. etc.)");
if (base::UnixIsAbsolutePath(APath))
{
return APath;
}
return base::AbsolutePath(FCurrentDirectory, APath);
}
UnicodeString TFTPFileSystem::GetActualCurrentDirectory() const
{
UnicodeString CurrentPath(NB_MAX_PATH, 0);
UnicodeString Result;
if (FFileZillaIntf->GetCurrentPath(ToWChar(CurrentPath), CurrentPath.Length()))
{
Result = base::UnixExcludeTrailingBackslash(CurrentPath);
}
PackStr(Result);
return Result;
}
void TFTPFileSystem::EnsureLocation(UnicodeString ADirectory, bool Log)
{
UnicodeString Directory = base::UnixExcludeTrailingBackslash(ADirectory);
if (!base::UnixSamePath(GetActualCurrentDirectory(), Directory))
{
if (Log)
{
FTerminal->LogEvent(FORMAT(L"Synchronizing current directory \"%s\".",
Directory));
}
DoChangeDirectory(Directory);
// make sure FZAPI is aware that we changed current working directory
FFileZillaIntf->SetCurrentPath(Directory.c_str());
}
}
void TFTPFileSystem::EnsureLocation()
{
// if we do not know what's the current directory, do nothing
if (!FCurrentDirectory.IsEmpty())
{
// Make sure that the FZAPI current working directory,
// is actually our working directory.
// It may not be because:
// 1) We did cached directory change
// 2) Listing was requested for non-current directory, which
// makes FZAPI change its current directory (and not restoring it back afterwards)
EnsureLocation(FCurrentDirectory, true);
}
}
void TFTPFileSystem::AnyCommand(UnicodeString Command,
TCaptureOutputEvent OutputEvent)
{
// end-user has right to expect that client current directory is really