S3FileSystem.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #define NE_LFS
  5. #define WINSCP
  6. #define NEED_LIBS3
  7. #include "S3FileSystem.h"
  8. #include "SessionData.h"
  9. #include "Interface.h"
  10. #include "Common.h"
  11. #include "Exceptions.h"
  12. #include "Terminal.h"
  13. #include "TextsCore.h"
  14. #include "HelpCore.h"
  15. #include "NeonIntf.h"
  16. #include <ne_request.h>
  17. //---------------------------------------------------------------------------
  18. #pragma package(smart_init)
  19. //---------------------------------------------------------------------------
  20. #define StrFromS3(S) StrFromNeon(S)
  21. #define StrToS3(S) StrToNeon(S)
  22. //---------------------------------------------------------------------------
  23. #define FILE_OPERATION_LOOP_TERMINAL FTerminal
  24. //---------------------------------------------------------------------------
  25. static std::unique_ptr<TCriticalSection> LibS3Section(TraceInitPtr(new TCriticalSection()));
  26. //---------------------------------------------------------------------------
  27. UTF8String LibS3Delimiter(L"/");
  28. //---------------------------------------------------------------------------
  29. UnicodeString __fastcall S3LibVersion()
  30. {
  31. return FORMAT(L"%s.%s", (LIBS3_VER_MAJOR, LIBS3_VER_MINOR));
  32. }
  33. //---------------------------------------------------------------------------
  34. UnicodeString __fastcall S3LibDefaultHostName()
  35. {
  36. return UnicodeString(S3_DEFAULT_HOSTNAME);
  37. }
  38. //---------------------------------------------------------------------------
  39. UnicodeString __fastcall S3LibDefaultRegion()
  40. {
  41. return StrFromS3(S3_DEFAULT_REGION);
  42. }
  43. //---------------------------------------------------------------------------
  44. //---------------------------------------------------------------------------
  45. TS3FileSystem::TS3FileSystem(TTerminal * ATerminal) :
  46. TCustomFileSystem(ATerminal),
  47. FActive(false)
  48. {
  49. FFileSystemInfo.ProtocolBaseName = L"S3";
  50. FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
  51. S3_create_request_context(&FRequestContext);
  52. S3_set_request_context_session_callback(FRequestContext, LibS3SessionCallback, this);
  53. S3_set_request_context_ssl_callback(FRequestContext, LibS3SslCallback, this);
  54. S3_set_request_context_response_data_callback(FRequestContext, LibS3ResponseDataCallback, this);
  55. }
  56. //---------------------------------------------------------------------------
  57. __fastcall TS3FileSystem::~TS3FileSystem()
  58. {
  59. S3_destroy_request_context(FRequestContext);
  60. FRequestContext = NULL;
  61. UnregisterFromNeonDebug(FTerminal);
  62. }
  63. //---------------------------------------------------------------------------
  64. void __fastcall TS3FileSystem::Open()
  65. {
  66. FTlsVersionStr = L"";
  67. FNeonSession = NULL;
  68. FCurrentDirectory = L"";
  69. RequireNeon(FTerminal);
  70. FTerminal->Information(LoadStr(STATUS_CONNECT), true);
  71. TSessionData * Data = FTerminal->SessionData;
  72. FSessionInfo.LoginTime = Now();
  73. FLibS3Protocol = (Data->Ftps != ftpsNone) ? S3ProtocolHTTPS : S3ProtocolHTTP;
  74. UnicodeString AccessKeyId = Data->UserNameExpanded;
  75. if (AccessKeyId.IsEmpty())
  76. {
  77. if (!FTerminal->PromptUser(Data, pkUserName, LoadStr(S3_ACCESS_KEY_ID_TITLE), L"",
  78. LoadStr(S3_ACCESS_KEY_ID_PROMPT), true, 0, AccessKeyId))
  79. {
  80. // note that we never get here actually
  81. throw Exception(L"");
  82. }
  83. }
  84. FAccessKeyId = UTF8String(AccessKeyId);
  85. UnicodeString SecretAccessKey = UTF8String(Data->Password);
  86. if (SecretAccessKey.IsEmpty())
  87. {
  88. if (!FTerminal->PromptUser(Data, pkPassword, LoadStr(S3_SECRET_ACCESS_KEY_TITLE), L"",
  89. LoadStr(S3_SECRET_ACCESS_KEY_PROMPT), false, 0, SecretAccessKey))
  90. {
  91. // note that we never get here actually
  92. throw Exception(L"");
  93. }
  94. }
  95. FSecretAccessKey = UTF8String(SecretAccessKey);
  96. FHostName = UTF8String(Data->HostNameExpanded);
  97. FTimeout = Data->Timeout;
  98. RegisterForNeonDebug(FTerminal);
  99. UpdateNeonDebugMask();
  100. {
  101. TGuard Guard(LibS3Section.get());
  102. S3_initialize(NULL, S3_INIT_ALL, NULL);
  103. }
  104. FActive = false;
  105. try
  106. {
  107. TryOpenDirectory(ROOTDIRECTORY);
  108. }
  109. catch (Exception & E)
  110. {
  111. LibS3Deinitialize();
  112. FTerminal->Closed();
  113. FTerminal->FatalError(&E, LoadStr(CONNECTION_FAILED));
  114. }
  115. FActive = true;
  116. }
  117. //---------------------------------------------------------------------------
  118. struct TLibS3CallbackData
  119. {
  120. TLibS3CallbackData()
  121. {
  122. Status = (S3Status)-1;
  123. }
  124. TS3FileSystem * FileSystem;
  125. S3Status Status;
  126. UnicodeString RegionDetail;
  127. UnicodeString EndpointDetail;
  128. UnicodeString ErrorMessage;
  129. UnicodeString ErrorDetails;
  130. };
  131. //---------------------------------------------------------------------------
  132. TS3FileSystem * TS3FileSystem::GetFileSystem(void * CallbackData)
  133. {
  134. return static_cast<TLibS3CallbackData *>(CallbackData)->FileSystem;
  135. }
  136. //---------------------------------------------------------------------------
  137. void TS3FileSystem::LibS3SessionCallback(ne_session_s * Session, void * CallbackData)
  138. {
  139. TS3FileSystem * FileSystem = static_cast<TS3FileSystem *>(CallbackData);
  140. TSessionData * Data = FileSystem->FTerminal->SessionData;
  141. InitNeonSession(
  142. Session, Data->ProxyMethod, Data->ProxyHost, Data->ProxyPort,
  143. Data->ProxyUsername, Data->ProxyPassword, FileSystem->FTerminal);
  144. SetNeonTlsInit(Session, FileSystem->InitSslSession);
  145. // Data->Timeout is propagated via timeoutMs parameter of functions like S3_list_service
  146. FileSystem->FNeonSession = Session;
  147. }
  148. //------------------------------------------------------------------------------
  149. void TS3FileSystem::InitSslSession(ssl_st * Ssl, ne_session * /*Session*/)
  150. {
  151. // See also CAsyncSslSocketLayer::InitSSLConnection
  152. SetupSsl(Ssl, FTerminal->SessionData->MinTlsVersion, FTerminal->SessionData->MaxTlsVersion);
  153. }
  154. //---------------------------------------------------------------------------
  155. int TS3FileSystem::LibS3SslCallback(int Failures, const ne_ssl_certificate_s * Certificate, void * CallbackData)
  156. {
  157. TNeonCertificateData Data;
  158. RetrieveNeonCertificateData(Failures, Certificate, Data);
  159. TS3FileSystem * FileSystem = static_cast<TS3FileSystem *>(CallbackData);
  160. return FileSystem->VerifyCertificate(Data) ? NE_OK : NE_ERROR;
  161. }
  162. //---------------------------------------------------------------------------
  163. // Similar to TWebDAVFileSystem::VerifyCertificate
  164. bool TS3FileSystem::VerifyCertificate(TNeonCertificateData Data)
  165. {
  166. FSessionInfo.CertificateFingerprint = Data.Fingerprint;
  167. bool Result;
  168. if (FTerminal->SessionData->FingerprintScan)
  169. {
  170. Result = false;
  171. }
  172. else
  173. {
  174. FTerminal->LogEvent(CertificateVerificationMessage(Data));
  175. UnicodeString SiteKey = TSessionData::FormatSiteKey(FTerminal->SessionData->HostNameExpanded, FTerminal->SessionData->PortNumber);
  176. Result =
  177. FTerminal->VerifyCertificate(HttpsCertificateStorageKey, SiteKey, Data.Fingerprint, Data.Subject, Data.Failures);
  178. if (!Result)
  179. {
  180. UnicodeString Message;
  181. Result = NeonWindowsValidateCertificateWithMessage(Data, Message);
  182. FTerminal->LogEvent(Message);
  183. }
  184. FSessionInfo.Certificate = CertificateSummary(Data, FTerminal->SessionData->HostNameExpanded);
  185. if (!Result)
  186. {
  187. Result = FTerminal->ConfirmCertificate(FSessionInfo, Data.Failures, HttpsCertificateStorageKey, true);
  188. }
  189. if (Result)
  190. {
  191. CollectTLSSessionInfo();
  192. }
  193. }
  194. return Result;
  195. }
  196. //------------------------------------------------------------------------------
  197. void TS3FileSystem::CollectTLSSessionInfo()
  198. {
  199. // See also TFTPFileSystem::Open().
  200. // Have to cache the value as the connection (the neon HTTP session, not "our" session)
  201. // can be closed at the time we need it in CollectUsage().
  202. UnicodeString Message = NeonTlsSessionInfo(FNeonSession, FSessionInfo, FTlsVersionStr);
  203. FTerminal->LogEvent(Message);
  204. }
  205. //---------------------------------------------------------------------------
  206. S3Status TS3FileSystem::LibS3ResponsePropertiesCallback(const S3ResponseProperties * /*Properties*/, void * /*CallbackData*/)
  207. {
  208. // TODO
  209. return S3StatusOK;
  210. }
  211. //---------------------------------------------------------------------------
  212. void TS3FileSystem::LibS3ResponseDataCallback(const char * Data, size_t Size, void * CallbackData)
  213. {
  214. TS3FileSystem * FileSystem = static_cast<TS3FileSystem *>(CallbackData);
  215. if (FileSystem->FTerminal->Log->Logging)
  216. {
  217. UnicodeString Content = UnicodeString(UTF8String(Data, Size)).Trim();
  218. FileSystem->FResponse += Content;
  219. }
  220. }
  221. //---------------------------------------------------------------------------
  222. void TS3FileSystem::LibS3ResponseCompleteCallback(S3Status Status, const S3ErrorDetails * Error, void * CallbackData)
  223. {
  224. TLibS3CallbackData & Data = *static_cast<TLibS3CallbackData *>(CallbackData);
  225. TS3FileSystem * FileSystem = Data.FileSystem;
  226. Data.Status = Status;
  227. Data.RegionDetail = L"";
  228. Data.EndpointDetail = L"";
  229. Data.ErrorMessage = L"";
  230. Data.ErrorDetails = L"";
  231. if (Error != NULL)
  232. {
  233. if (Error->message != NULL)
  234. {
  235. Data.ErrorMessage = StrFromS3(Error->message);
  236. FileSystem->FTerminal->LogEvent(Data.ErrorMessage);
  237. }
  238. UnicodeString ErrorDetails;
  239. if (Error->resource != NULL)
  240. {
  241. AddToList(ErrorDetails, FMTLOAD(S3_ERROR_RESOURCE, (StrFromS3(Error->resource))), L"\n");
  242. }
  243. if (Error->furtherDetails != NULL)
  244. {
  245. AddToList(ErrorDetails, FMTLOAD(S3_ERROR_FURTHER_DETAILS, (StrFromS3(Error->furtherDetails))), L"\n");
  246. }
  247. if (Error->extraDetailsCount)
  248. {
  249. UnicodeString ExtraDetails;
  250. for (int I = 0; I < Error->extraDetailsCount; I++)
  251. {
  252. UnicodeString DetailName = StrFromS3(Error->extraDetails[I].name);
  253. UnicodeString DetailValue = StrFromS3(Error->extraDetails[I].value);
  254. if (SameText(DetailName, L"Region"))
  255. {
  256. Data.RegionDetail = DetailValue;
  257. }
  258. else if (SameText(DetailName, L"Endpoint"))
  259. {
  260. Data.EndpointDetail = DetailValue;
  261. }
  262. AddToList(ExtraDetails, FORMAT(L"%s: %s", (DetailName, DetailValue)), L", ");
  263. }
  264. AddToList(ErrorDetails, LoadStr(S3_ERROR_EXTRA_DETAILS) + ExtraDetails, L"\n");
  265. }
  266. if (!ErrorDetails.IsEmpty())
  267. {
  268. FileSystem->FTerminal->LogEvent(ErrorDetails);
  269. Data.ErrorDetails = ErrorDetails;
  270. }
  271. }
  272. if (!FileSystem->FResponse.IsEmpty())
  273. {
  274. FileSystem->FTerminal->Log->Add(llOutput, FileSystem->FResponse);
  275. }
  276. }
  277. //---------------------------------------------------------------------------
  278. void TS3FileSystem::RequestInit(TLibS3CallbackData & Data)
  279. {
  280. Data.FileSystem = this;
  281. FResponse = L"";
  282. }
  283. //---------------------------------------------------------------------------
  284. void TS3FileSystem::CheckLibS3Error(const TLibS3CallbackData & Data)
  285. {
  286. if (Data.Status != S3StatusOK)
  287. {
  288. UnicodeString Error, Details;
  289. switch (Data.Status)
  290. {
  291. case S3StatusErrorAccessDenied:
  292. Error = LoadStr(S3_STATUS_ACCESS_DENIED);
  293. break;
  294. case S3StatusErrorSignatureDoesNotMatch: // While it can mean an implementation fault, it will typically mean a wrong secure key.
  295. case S3StatusErrorInvalidAccessKeyId:
  296. Error = LoadStr(AUTHENTICATION_FAILED);
  297. break;
  298. }
  299. if (!Error.IsEmpty())
  300. {
  301. Details = Data.ErrorMessage;
  302. AddToList(Details, Data.ErrorDetails, L"\n");
  303. }
  304. else
  305. {
  306. if (!Data.ErrorMessage.IsEmpty())
  307. {
  308. Error = Data.ErrorMessage;
  309. }
  310. else
  311. {
  312. // only returns name of the S3 status code symbol, like S3StatusErrorAccountProblem,
  313. // not something we should really display to an user, but still better than an internal error code
  314. Error = S3_get_status_name(Data.Status);
  315. }
  316. Details = Data.ErrorDetails;
  317. }
  318. throw ExtException(MainInstructions(Error), Details);
  319. }
  320. }
  321. //---------------------------------------------------------------------------
  322. void TS3FileSystem::LibS3Deinitialize()
  323. {
  324. TGuard Guard(LibS3Section.get());
  325. S3_deinitialize();
  326. }
  327. //---------------------------------------------------------------------------
  328. UnicodeString TS3FileSystem::GetFolderKey(const UnicodeString & Key)
  329. {
  330. return Key + L"/";
  331. }
  332. //---------------------------------------------------------------------------
  333. void TS3FileSystem::ParsePath(UnicodeString Path, UnicodeString & BucketName, UnicodeString & Key)
  334. {
  335. if (DebugAlwaysTrue(Path.SubString(1, 1) == L"/"))
  336. {
  337. Path.Delete(1, 1);
  338. }
  339. int P = Path.Pos(L"/");
  340. UnicodeString Result;
  341. if (P == 0)
  342. {
  343. BucketName = Path;
  344. Key = L"";
  345. }
  346. else
  347. {
  348. BucketName = Path.SubString(0, P - 1);
  349. Key = Path.SubString(P + 1, Path.Length() - P);
  350. }
  351. }
  352. //---------------------------------------------------------------------------
  353. struct TLibS3BucketContext : S3BucketContext
  354. {
  355. // These keep data that that we point the native S3BucketContext fields to
  356. UTF8String HostNameBuf;
  357. UTF8String BucketNameBuf;
  358. UTF8String AuthRegionBuf;
  359. };
  360. //---------------------------------------------------------------------------
  361. struct TLibS3ListBucketCallbackData : TLibS3CallbackData
  362. {
  363. TRemoteFileList * FileList;
  364. int KeyCount;
  365. UTF8String NextMarker;
  366. bool IsTruncated;
  367. };
  368. //---------------------------------------------------------------------------
  369. TLibS3BucketContext TS3FileSystem::GetBucketContext(const UnicodeString & BucketName)
  370. {
  371. TLibS3BucketContext Result;
  372. bool First = true;
  373. bool Retry = false;
  374. do
  375. {
  376. TRegions::const_iterator I;
  377. I = FRegions.find(BucketName);
  378. UnicodeString Region;
  379. if (I != FRegions.end())
  380. {
  381. Region = I->second;
  382. }
  383. else
  384. {
  385. Region = FTerminal->SessionData->S3DefaultRegion;
  386. if (First)
  387. {
  388. FTerminal->LogEvent(FORMAT(L"Unknown bucket \"%s\", will detect its region (and service endpoint)", (BucketName)));
  389. First = false;
  390. }
  391. Retry = true;
  392. }
  393. I = FHostNames.find(BucketName);
  394. UnicodeString HostName;
  395. if (I != FHostNames.end())
  396. {
  397. HostName = I->second;
  398. }
  399. else
  400. {
  401. HostName = UnicodeString(FHostName);
  402. }
  403. Result.HostNameBuf = UTF8String(HostName);
  404. Result.hostName = Result.HostNameBuf.c_str();
  405. Result.BucketNameBuf = UTF8String(BucketName);
  406. Result.bucketName = Result.BucketNameBuf.c_str();
  407. Result.protocol = FLibS3Protocol;
  408. Result.uriStyle = S3UriStyleVirtualHost;
  409. Result.accessKeyId = FAccessKeyId.c_str();
  410. Result.secretAccessKey = FSecretAccessKey.c_str();
  411. Result.securityToken = NULL;
  412. Result.AuthRegionBuf = UTF8String(Region);
  413. Result.authRegion = Result.AuthRegionBuf.c_str();
  414. if (Retry)
  415. {
  416. std::unique_ptr<TRemoteFileList> FileList(new TRemoteFileList());
  417. TLibS3ListBucketCallbackData Data;
  418. DoListBucket(UnicodeString(), FileList.get(), 1, Result, Data);
  419. Retry = false;
  420. UnicodeString EndpointDetail = Data.EndpointDetail;
  421. if ((Data.Status == S3StatusErrorAuthorizationHeaderMalformed) &&
  422. (Region != Data.RegionDetail))
  423. {
  424. FTerminal->LogEvent(FORMAT("Will use region \"%s\" for bucket \"%s\" from now on.", (Data.RegionDetail, BucketName)));
  425. FRegions.insert(std::make_pair(BucketName, Data.RegionDetail));
  426. Result.AuthRegionBuf = UTF8String(Data.RegionDetail);
  427. Result.authRegion = Result.AuthRegionBuf.c_str();
  428. }
  429. // happens with newly created buckets (and happens before the region redirect)
  430. else if ((Data.Status == S3StatusErrorTemporaryRedirect) && !Data.EndpointDetail.IsEmpty())
  431. {
  432. UnicodeString Endpoint = Data.EndpointDetail;
  433. if (SameText(Endpoint.SubString(1, BucketName.Length() + 1), BucketName + L"."))
  434. {
  435. Endpoint.Delete(1, BucketName.Length() + 1);
  436. }
  437. if (HostName != Endpoint)
  438. {
  439. FTerminal->LogEvent(FORMAT("Will use endpoint \"%s\" for bucket \"%s\" from now on.", (Endpoint, BucketName)));
  440. FHostNames.insert(std::make_pair(BucketName, Endpoint));
  441. Retry = true;
  442. }
  443. }
  444. }
  445. }
  446. while (Retry);
  447. return Result;
  448. }
  449. //---------------------------------------------------------------------------
  450. #define CreateResponseHandler() { &LibS3ResponsePropertiesCallback, &LibS3ResponseCompleteCallback }
  451. //---------------------------------------------------------------------------
  452. void __fastcall TS3FileSystem::Close()
  453. {
  454. DebugAssert(FActive);
  455. LibS3Deinitialize();
  456. FTerminal->Closed();
  457. FActive = false;
  458. UnregisterFromNeonDebug(FTerminal);
  459. }
  460. //---------------------------------------------------------------------------
  461. bool __fastcall TS3FileSystem::GetActive()
  462. {
  463. return FActive;
  464. }
  465. //---------------------------------------------------------------------------
  466. void __fastcall TS3FileSystem::CollectUsage()
  467. {
  468. // noop
  469. }
  470. //---------------------------------------------------------------------------
  471. const TSessionInfo & __fastcall TS3FileSystem::GetSessionInfo()
  472. {
  473. return FSessionInfo;
  474. }
  475. //---------------------------------------------------------------------------
  476. const TFileSystemInfo & __fastcall TS3FileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  477. {
  478. return FFileSystemInfo;
  479. }
  480. //---------------------------------------------------------------------------
  481. bool __fastcall TS3FileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
  482. {
  483. return false;
  484. }
  485. //---------------------------------------------------------------------------
  486. bool __fastcall TS3FileSystem::GetStoredCredentialsTried()
  487. {
  488. // if we have one, we always try it
  489. return !FTerminal->SessionData->Password.IsEmpty();
  490. }
  491. //---------------------------------------------------------------------------
  492. UnicodeString __fastcall TS3FileSystem::GetUserName()
  493. {
  494. return UnicodeString(FAccessKeyId);
  495. }
  496. //---------------------------------------------------------------------------
  497. void __fastcall TS3FileSystem::Idle()
  498. {
  499. // noop
  500. }
  501. //---------------------------------------------------------------------------
  502. UnicodeString __fastcall TS3FileSystem::AbsolutePath(const UnicodeString Path, bool /*Local*/)
  503. {
  504. if (UnixIsAbsolutePath(Path))
  505. {
  506. return Path;
  507. }
  508. else
  509. {
  510. return ::AbsolutePath(FCurrentDirectory, Path);
  511. }
  512. }
  513. //---------------------------------------------------------------------------
  514. bool __fastcall TS3FileSystem::IsCapable(int Capability) const
  515. {
  516. DebugAssert(FTerminal);
  517. switch (Capability)
  518. {
  519. // Only to make double-click on file edit/open the file,
  520. // instead of trying to open it as directory
  521. case fcResolveSymlink:
  522. case fcRemoteCopy:
  523. case fcRename:
  524. case fcRemoteMove:
  525. return true;
  526. case fcMoveToQueue:
  527. case fcPreservingTimestampUpload:
  528. case fcCheckingSpaceAvailable:
  529. case fsSkipTransfer:
  530. case fsParallelTransfers:
  531. case fcUserGroupListing:
  532. case fcModeChanging:
  533. case fcModeChangingUpload:
  534. case fcGroupChanging:
  535. case fcOwnerChanging:
  536. case fcAnyCommand:
  537. case fcShellAnyCommand:
  538. case fcHardLink:
  539. case fcSymbolicLink:
  540. case fcTextMode:
  541. case fcNativeTextMode:
  542. case fcNewerOnlyUpload:
  543. case fcTimestampChanging:
  544. case fcLoadingAdditionalProperties:
  545. case fcIgnorePermErrors:
  546. case fcCalculatingChecksum:
  547. case fcSecondaryShell:
  548. case fcGroupOwnerChangingByID:
  549. case fcRemoveCtrlZUpload:
  550. case fcRemoveBOMUpload:
  551. case fcPreservingTimestampDirs:
  552. case fcResumeSupport:
  553. case fcChangePassword:
  554. case fcLocking:
  555. return false;
  556. default:
  557. DebugFail();
  558. return false;
  559. }
  560. }
  561. //---------------------------------------------------------------------------
  562. UnicodeString __fastcall TS3FileSystem::GetCurrentDirectory()
  563. {
  564. return FCurrentDirectory;
  565. }
  566. //---------------------------------------------------------------------------
  567. void __fastcall TS3FileSystem::DoStartup()
  568. {
  569. FTerminal->SetExceptionOnFail(true);
  570. // retrieve initialize working directory to save it as home directory
  571. ReadCurrentDirectory();
  572. FTerminal->SetExceptionOnFail(false);
  573. }
  574. //---------------------------------------------------------------------------
  575. void __fastcall TS3FileSystem::LookupUsersGroups()
  576. {
  577. DebugFail();
  578. }
  579. //---------------------------------------------------------------------------
  580. void __fastcall TS3FileSystem::ReadCurrentDirectory()
  581. {
  582. if (FCachedDirectoryChange.IsEmpty())
  583. {
  584. FCurrentDirectory = FCurrentDirectory.IsEmpty() ? UnicodeString(L"/") : FCurrentDirectory;
  585. }
  586. else
  587. {
  588. FCurrentDirectory = FCachedDirectoryChange;
  589. FCachedDirectoryChange = L"";
  590. }
  591. }
  592. //---------------------------------------------------------------------------
  593. void __fastcall TS3FileSystem::HomeDirectory()
  594. {
  595. ChangeDirectory(L"/");
  596. }
  597. //---------------------------------------------------------------------------
  598. void __fastcall TS3FileSystem::AnnounceFileListOperation()
  599. {
  600. // noop
  601. }
  602. //---------------------------------------------------------------------------
  603. void TS3FileSystem::TryOpenDirectory(const UnicodeString & Directory)
  604. {
  605. FTerminal->LogEvent(FORMAT(L"Trying to open directory \"%s\".", (Directory)));
  606. std::unique_ptr<TRemoteFileList> FileList(new TRemoteFileList());
  607. ReadDirectoryInternal(Directory, FileList.get(), 1, UnicodeString());
  608. }
  609. //---------------------------------------------------------------------------
  610. void __fastcall TS3FileSystem::ChangeDirectory(const UnicodeString ADirectory)
  611. {
  612. UnicodeString Path = AbsolutePath(ADirectory, false);
  613. // to verify existence of directory try to open it
  614. TryOpenDirectory(Path);
  615. // if open dir did not fail, directory exists -> success.
  616. FCachedDirectoryChange = Path;
  617. }
  618. //---------------------------------------------------------------------------
  619. void __fastcall TS3FileSystem::CachedChangeDirectory(const UnicodeString Directory)
  620. {
  621. FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
  622. }
  623. //---------------------------------------------------------------------------
  624. TRemoteToken TS3FileSystem::MakeRemoteToken(const char * OwnerId, const char * OwnerDisplayName)
  625. {
  626. TRemoteToken Result;
  627. Result.Name = StrFromS3(OwnerDisplayName);
  628. if (Result.Name.IsEmpty())
  629. {
  630. Result.Name = StrFromS3(OwnerId);
  631. }
  632. return Result;
  633. }
  634. //---------------------------------------------------------------------------
  635. struct TLibS3ListServiceCallbackData : TLibS3CallbackData
  636. {
  637. TRemoteFileList * FileList;
  638. UnicodeString FileName; // filter for buckets
  639. };
  640. //---------------------------------------------------------------------------
  641. S3Status TS3FileSystem::LibS3ListServiceCallback(
  642. const char * OwnerId, const char * OwnerDisplayName, const char * BucketName,
  643. int64_t /*CreationDate*/, void * CallbackData)
  644. {
  645. TLibS3ListServiceCallbackData & Data = *static_cast<TLibS3ListServiceCallbackData *>(CallbackData);
  646. UnicodeString FileName = StrFromS3(BucketName);
  647. if (Data.FileName.IsEmpty() || (Data.FileName == FileName))
  648. {
  649. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  650. File->Terminal = Data.FileSystem->FTerminal;
  651. File->FileName = StrFromS3(BucketName);
  652. File->Type = FILETYPE_DIRECTORY;
  653. File->Owner = Data.FileSystem->MakeRemoteToken(OwnerId, OwnerDisplayName);
  654. File->ModificationFmt = mfNone;
  655. Data.FileList->AddFile(File.release());
  656. }
  657. return S3StatusOK;
  658. }
  659. //---------------------------------------------------------------------------
  660. S3Status TS3FileSystem::LibS3ListBucketCallback(
  661. int IsTruncated, const char * NextMarker, int ContentsCount, const S3ListBucketContent * Contents,
  662. int CommonPrefixesCount, const char ** CommonPrefixes, void * CallbackData)
  663. {
  664. TLibS3ListBucketCallbackData & Data = *static_cast<TLibS3ListBucketCallbackData *>(CallbackData);
  665. Data.IsTruncated = IsTruncated;
  666. // This is being called in chunks, not once for all data in a response.
  667. Data.KeyCount += ContentsCount;
  668. Data.NextMarker = StrFromS3(NextMarker);
  669. for (int Index = 0; Index < ContentsCount; Index++)
  670. {
  671. const S3ListBucketContent * Content = &Contents[Index];
  672. UnicodeString FileName = UnixExtractFileName(StrFromS3(Content->key));
  673. if (!FileName.IsEmpty())
  674. {
  675. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  676. File->Terminal = Data.FileSystem->FTerminal;
  677. File->FileName = FileName;
  678. File->Type = FILETYPE_DEFAULT;
  679. File->Modification = UnixToDateTime(Content->lastModified, dstmWin);
  680. File->Size = Content->size;
  681. File->Owner = Data.FileSystem->MakeRemoteToken(Content->ownerId, Content->ownerDisplayName);
  682. Data.FileList->AddFile(File.release());
  683. }
  684. else
  685. {
  686. // We needs this to distinguish empty and non-existing folders, see comments in ReadDirectoryInternal.
  687. Data.FileList->AddFile(new TRemoteParentDirectory(Data.FileSystem->FTerminal));
  688. }
  689. }
  690. for (int Index = 0; Index < CommonPrefixesCount; Index++)
  691. {
  692. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  693. File->Terminal = Data.FileSystem->FTerminal;
  694. File->FileName = UnixExtractFileName(UnixExcludeTrailingBackslash(StrFromS3(CommonPrefixes[Index])));
  695. File->Type = FILETYPE_DIRECTORY;
  696. File->ModificationFmt = mfNone;
  697. Data.FileList->AddFile(File.release());
  698. }
  699. return S3StatusOK;
  700. }
  701. //---------------------------------------------------------------------------
  702. void TS3FileSystem::DoListBucket(
  703. const UnicodeString & Prefix, TRemoteFileList * FileList, int MaxKeys, const TLibS3BucketContext & BucketContext,
  704. TLibS3ListBucketCallbackData & Data)
  705. {
  706. S3ListBucketHandler ListBucketHandler = { CreateResponseHandler(), &LibS3ListBucketCallback };
  707. RequestInit(Data);
  708. Data.KeyCount = 0;
  709. Data.FileList = FileList;
  710. Data.IsTruncated = false;
  711. S3_list_bucket(
  712. &BucketContext, StrToS3(Prefix), StrToS3(Data.NextMarker),
  713. LibS3Delimiter.c_str(), MaxKeys, FRequestContext, FTimeout, &ListBucketHandler, &Data);
  714. }
  715. //---------------------------------------------------------------------------
  716. void TS3FileSystem::ReadDirectoryInternal(
  717. const UnicodeString & APath, TRemoteFileList * FileList, int MaxKeys, const UnicodeString & FileName)
  718. {
  719. UnicodeString Path = AbsolutePath(APath, false);
  720. if (IsUnixRootPath(Path))
  721. {
  722. DebugAssert(FileList != NULL);
  723. S3ListServiceHandler ListServiceHandler = { CreateResponseHandler(), &LibS3ListServiceCallback };
  724. TLibS3ListServiceCallbackData Data;
  725. RequestInit(Data);
  726. Data.FileSystem = this;
  727. Data.FileList = FileList;
  728. Data.FileName = FileName;
  729. S3_list_service(
  730. FLibS3Protocol, FAccessKeyId.c_str(), FSecretAccessKey.c_str(), 0, FHostName.c_str(),
  731. NULL, MaxKeys, FRequestContext, FTimeout, &ListServiceHandler, &Data);
  732. CheckLibS3Error(Data);
  733. }
  734. else
  735. {
  736. UnicodeString BucketName, Prefix;
  737. ParsePath(Path, BucketName, Prefix);
  738. if (!Prefix.IsEmpty())
  739. {
  740. Prefix = GetFolderKey(Prefix);
  741. }
  742. Prefix += FileName;
  743. TLibS3BucketContext BucketContext = GetBucketContext(BucketName);
  744. TLibS3ListBucketCallbackData Data;
  745. bool Continue;
  746. do
  747. {
  748. DoListBucket(Prefix, FileList, MaxKeys, BucketContext, Data);
  749. CheckLibS3Error(Data);
  750. Continue = false;
  751. if (Data.IsTruncated && ((MaxKeys == 0) || (Data.KeyCount < MaxKeys)))
  752. {
  753. bool Cancel = false;
  754. FTerminal->DoReadDirectoryProgress(FileList->Count, false, Cancel);
  755. if (!Cancel)
  756. {
  757. Continue = true;
  758. }
  759. }
  760. } while (Continue);
  761. // Listing bucket root directory will report an error if the bucket does not exist.
  762. // But there won't be any prefix/ entry, so no ".." entry is created, so we have to add it explicitly
  763. if (Prefix.IsEmpty())
  764. {
  765. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  766. }
  767. else
  768. {
  769. // We do not get any error, when the "prefix" does not exist. But when prefix does exist, there's at least
  770. // prefix/ entry (translated to ..). If there's none, it means that the path does not exist.
  771. if (FileList->Count == 0)
  772. {
  773. throw Exception(FMTLOAD(FILE_NOT_EXISTS, (APath)));
  774. }
  775. }
  776. }
  777. }
  778. //---------------------------------------------------------------------------
  779. void __fastcall TS3FileSystem::ReadDirectory(TRemoteFileList * FileList)
  780. {
  781. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  782. ReadDirectoryInternal(FileList->Directory, FileList, 0, UnicodeString());
  783. }
  784. //---------------------------------------------------------------------------
  785. void __fastcall TS3FileSystem::ReadSymlink(TRemoteFile * /*SymlinkFile*/,
  786. TRemoteFile *& /*File*/)
  787. {
  788. // we never set SymLink flag, so we should never get here
  789. DebugFail();
  790. }
  791. //---------------------------------------------------------------------------
  792. void __fastcall TS3FileSystem::ReadFile(const UnicodeString FileName,
  793. TRemoteFile *& File)
  794. {
  795. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  796. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  797. std::unique_ptr<TRemoteFileList> FileList(new TRemoteFileList());
  798. ReadDirectoryInternal(UnixExtractFileDir(FileName), FileList.get(), 1, FileNameOnly);
  799. TRemoteFile * AFile = FileList->FindFile(FileNameOnly);
  800. if (AFile == NULL)
  801. {
  802. throw Exception(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  803. }
  804. File = AFile->Duplicate();
  805. }
  806. //---------------------------------------------------------------------------
  807. void __fastcall TS3FileSystem::DeleteFile(const UnicodeString AFileName,
  808. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  809. {
  810. UnicodeString FileName = AbsolutePath(AFileName, false);
  811. bool Dir = FTerminal->DeleteContentsIfDirectory(FileName, File, Params, Action);
  812. UnicodeString BucketName, Key;
  813. ParsePath(FileName, BucketName, Key);
  814. TLibS3BucketContext BucketContext = GetBucketContext(BucketName);
  815. S3ResponseHandler ResponseHandler = CreateResponseHandler();
  816. TLibS3CallbackData Data;
  817. RequestInit(Data);
  818. if (Key.IsEmpty())
  819. {
  820. S3_delete_bucket(
  821. BucketContext.protocol, BucketContext.uriStyle, BucketContext.accessKeyId, BucketContext.secretAccessKey,
  822. BucketContext.securityToken, BucketContext.hostName, BucketContext.bucketName, BucketContext.authRegion,
  823. FRequestContext, FTimeout, &ResponseHandler, &Data);
  824. }
  825. else
  826. {
  827. if (Dir)
  828. {
  829. Key = GetFolderKey(Key);
  830. }
  831. S3_delete_object(&BucketContext, StrToS3(Key), FRequestContext, FTimeout, &ResponseHandler, &Data);
  832. }
  833. CheckLibS3Error(Data);
  834. }
  835. //---------------------------------------------------------------------------
  836. void __fastcall TS3FileSystem::RenameFile(const UnicodeString FileName, const TRemoteFile * File,
  837. const UnicodeString NewName)
  838. {
  839. CopyFile(FileName, File, NewName);
  840. TRmSessionAction DummyAction(FTerminal->ActionLog, FileName);
  841. DeleteFile(FileName, File, dfForceDelete, DummyAction);
  842. DummyAction.Cancel();
  843. }
  844. //---------------------------------------------------------------------------
  845. void __fastcall TS3FileSystem::CopyFile(const UnicodeString AFileName, const TRemoteFile * File,
  846. const UnicodeString ANewName)
  847. {
  848. if (DebugAlwaysTrue(File != NULL) && File->IsDirectory)
  849. {
  850. throw Exception(LoadStr(DUPLICATE_FOLDER_NOT_SUPPORTED));
  851. }
  852. UnicodeString FileName = AbsolutePath(AFileName, false);
  853. UnicodeString NewName = AbsolutePath(ANewName, false);
  854. UnicodeString SourceBucketName, SourceKey;
  855. ParsePath(FileName, SourceBucketName, SourceKey);
  856. DebugAssert(!SourceKey.IsEmpty()); // it's not a folder, so it cannot be a bucket or root
  857. UnicodeString DestBucketName, DestKey;
  858. ParsePath(NewName, DestBucketName, DestKey);
  859. if (DestKey.IsEmpty())
  860. {
  861. throw Exception(LoadStr(MISSING_TARGET_BUCKET));
  862. }
  863. TLibS3BucketContext BucketContext = GetBucketContext(DestBucketName);
  864. BucketContext.BucketNameBuf = SourceBucketName;
  865. BucketContext.bucketName = BucketContext.BucketNameBuf.c_str();
  866. S3ResponseHandler ResponseHandler = CreateResponseHandler();
  867. TLibS3CallbackData Data;
  868. RequestInit(Data);
  869. S3_copy_object(
  870. &BucketContext, StrToS3(SourceKey), StrToS3(DestBucketName), StrToS3(DestKey),
  871. NULL, NULL, 0, NULL, FRequestContext, FTimeout, &ResponseHandler, &Data);
  872. CheckLibS3Error(Data);
  873. }
  874. //---------------------------------------------------------------------------
  875. void __fastcall TS3FileSystem::CreateDirectory(const UnicodeString ADirName)
  876. {
  877. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  878. UnicodeString DirName = AbsolutePath(ADirName, false);
  879. UnicodeString BucketName, Key;
  880. ParsePath(DirName, BucketName, Key);
  881. TLibS3CallbackData Data;
  882. RequestInit(Data);
  883. if (Key.IsEmpty())
  884. {
  885. S3ResponseHandler ResponseHandler = CreateResponseHandler();
  886. // Not using GetBucketContext here, as the bucket does not exist, so we have to explicitly use S3DefaultRegion
  887. S3_create_bucket(
  888. FLibS3Protocol, FAccessKeyId.c_str(), FSecretAccessKey.c_str(), NULL, FHostName.c_str(), StrToS3(BucketName),
  889. StrToS3(FTerminal->SessionData->S3DefaultRegion), S3CannedAclPrivate, NULL, FRequestContext, FTimeout,
  890. &ResponseHandler, &Data);
  891. }
  892. else
  893. {
  894. Key = GetFolderKey(Key);
  895. TLibS3BucketContext BucketContext = GetBucketContext(BucketName);
  896. S3PutObjectHandler PutObjectHandler = { CreateResponseHandler(), NULL };
  897. S3_put_object(&BucketContext, StrToS3(Key), 0, NULL, FRequestContext, FTimeout, &PutObjectHandler, &Data);
  898. }
  899. CheckLibS3Error(Data);
  900. }
  901. //---------------------------------------------------------------------------
  902. void __fastcall TS3FileSystem::CreateLink(const UnicodeString FileName,
  903. const UnicodeString PointTo, bool /*Symbolic*/)
  904. {
  905. DebugFail();
  906. }
  907. //---------------------------------------------------------------------------
  908. void __fastcall TS3FileSystem::ChangeFileProperties(const UnicodeString FileName,
  909. const TRemoteFile * /*File*/, const TRemoteProperties * /*Properties*/,
  910. TChmodSessionAction & /*Action*/)
  911. {
  912. DebugFail();
  913. }
  914. //---------------------------------------------------------------------------
  915. bool __fastcall TS3FileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  916. {
  917. DebugFail();
  918. return false;
  919. }
  920. //---------------------------------------------------------------------------
  921. void __fastcall TS3FileSystem::CalculateFilesChecksum(const UnicodeString & /*Alg*/,
  922. TStrings * /*FileList*/, TStrings * /*Checksums*/,
  923. TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
  924. {
  925. DebugFail();
  926. }
  927. //---------------------------------------------------------------------------
  928. void __fastcall TS3FileSystem::CustomCommandOnFile(const UnicodeString FileName,
  929. const TRemoteFile * /*File*/, UnicodeString Command, int /*Params*/, TCaptureOutputEvent /*OutputEvent*/)
  930. {
  931. DebugFail();
  932. }
  933. //---------------------------------------------------------------------------
  934. void __fastcall TS3FileSystem::AnyCommand(const UnicodeString Command,
  935. TCaptureOutputEvent /*OutputEvent*/)
  936. {
  937. DebugFail();
  938. }
  939. //---------------------------------------------------------------------------
  940. TStrings * __fastcall TS3FileSystem::GetFixedPaths()
  941. {
  942. return NULL;
  943. }
  944. //---------------------------------------------------------------------------
  945. void __fastcall TS3FileSystem::SpaceAvailable(const UnicodeString Path,
  946. TSpaceAvailable & /*ASpaceAvailable*/)
  947. {
  948. DebugFail();
  949. }
  950. //---------------------------------------------------------------------------
  951. void __fastcall TS3FileSystem::CopyToRemote(TStrings * /*FilesToCopy*/,
  952. const UnicodeString ATargetDir, const TCopyParamType * /*CopyParam*/,
  953. int /*Params*/, TFileOperationProgressType * /*OperationProgress*/,
  954. TOnceDoneOperation & /*OnceDoneOperation*/)
  955. {
  956. throw Exception(L"Not implemented");
  957. }
  958. //---------------------------------------------------------------------------
  959. void __fastcall TS3FileSystem::Source(
  960. TLocalFileHandle & /*Handle*/, const UnicodeString & /*TargetDir*/, UnicodeString & /*DestFileName*/,
  961. const TCopyParamType * /*CopyParam*/, int /*Params*/,
  962. TFileOperationProgressType * /*OperationProgress*/, unsigned int /*Flags*/,
  963. TUploadSessionAction & /*Action*/, bool & /*ChildError*/)
  964. {
  965. throw Exception(L"Not implemented");
  966. }
  967. //---------------------------------------------------------------------------
  968. void __fastcall TS3FileSystem::CopyToLocal(TStrings * /*FilesToCopy*/,
  969. const UnicodeString TargetDir, const TCopyParamType * /*CopyParam*/,
  970. int /*Params*/, TFileOperationProgressType * /*OperationProgress*/,
  971. TOnceDoneOperation & /*OnceDoneOperation*/)
  972. {
  973. throw Exception(L"Not implemented");
  974. }
  975. //---------------------------------------------------------------------------
  976. void __fastcall TS3FileSystem::GetSupportedChecksumAlgs(TStrings * /*Algs*/)
  977. {
  978. // NOOP
  979. }
  980. //---------------------------------------------------------------------------
  981. void __fastcall TS3FileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  982. {
  983. DebugFail();
  984. }
  985. //---------------------------------------------------------------------------
  986. void __fastcall TS3FileSystem::UnlockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  987. {
  988. DebugFail();
  989. }
  990. //---------------------------------------------------------------------------
  991. void __fastcall TS3FileSystem::UpdateFromMain(TCustomFileSystem * /*AMainFileSystem*/)
  992. {
  993. // noop
  994. }
  995. //------------------------------------------------------------------------------
  996. void __fastcall TS3FileSystem::ClearCaches()
  997. {
  998. FRegions.clear();
  999. FHostNames.clear();
  1000. }
  1001. //------------------------------------------------------------------------------