S3FileSystem.cpp 37 KB

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