FtpFileSystem.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #ifndef NO_FILEZILLA
  5. //---------------------------------------------------------------------------
  6. #include <list>
  7. #include "FtpFileSystem.h"
  8. #include "FileZillaIntf.h"
  9. #include "Common.h"
  10. #include "Exceptions.h"
  11. #include "Terminal.h"
  12. #include "TextsCore.h"
  13. //---------------------------------------------------------------------------
  14. #pragma package(smart_init)
  15. //---------------------------------------------------------------------------
  16. #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
  17. FILE_OPERATION_LOOP_CUSTOM(FTerminal, ALLOW_SKIP, MESSAGE, OPERATION)
  18. //---------------------------------------------------------------------------
  19. class TFileZillaImpl : public TFileZillaIntf
  20. {
  21. public:
  22. __fastcall TFileZillaImpl(TFTPFileSystem * FileSystem);
  23. virtual const char * __fastcall Option(int OptionID) const;
  24. virtual int __fastcall OptionVal(int OptionID) const;
  25. protected:
  26. virtual bool __fastcall DoPostMessage(WPARAM wParam, LPARAM lParam);
  27. virtual bool __fastcall HandleStatus(const char * Status, int Type);
  28. virtual bool __fastcall HandleAsynchRequestOverwrite(
  29. char * FileName1, size_t FileName1Len, const char * FileName2,
  30. const char * Path1, const char * Path2,
  31. __int64 Size1, __int64 Size2, time_t Time1, time_t Time2,
  32. bool HasTime1, bool HasTime2, void * UserData, int & RequestResult);
  33. virtual bool __fastcall HandleListData(const char * Path, const TListDataEntry * Entries,
  34. unsigned int Count);
  35. virtual bool __fastcall HandleTransferStatus(bool Valid, __int64 TransferSize,
  36. __int64 Bytes, int Percent, int TimeElapsed, int TimeLeft, int TransferRate,
  37. bool FileTransfer);
  38. virtual bool __fastcall HandleReply(int Command, unsigned int Reply);
  39. virtual bool __fastcall CheckError(int ReturnCode, const char * Context);
  40. private:
  41. TFTPFileSystem * FFileSystem;
  42. };
  43. //---------------------------------------------------------------------------
  44. __fastcall TFileZillaImpl::TFileZillaImpl(TFTPFileSystem * FileSystem) :
  45. TFileZillaIntf(),
  46. FFileSystem(FileSystem)
  47. {
  48. }
  49. //---------------------------------------------------------------------------
  50. const char * __fastcall TFileZillaImpl::Option(int OptionID) const
  51. {
  52. return FFileSystem->GetOption(OptionID);
  53. }
  54. //---------------------------------------------------------------------------
  55. int __fastcall TFileZillaImpl::OptionVal(int OptionID) const
  56. {
  57. return FFileSystem->GetOptionVal(OptionID);
  58. }
  59. //---------------------------------------------------------------------------
  60. bool __fastcall TFileZillaImpl::DoPostMessage(WPARAM wParam, LPARAM lParam)
  61. {
  62. return FFileSystem->PostMessage(wParam, lParam);
  63. }
  64. //---------------------------------------------------------------------------
  65. bool __fastcall TFileZillaImpl::HandleStatus(const char * Status, int Type)
  66. {
  67. return FFileSystem->HandleStatus(Status, Type);
  68. }
  69. //---------------------------------------------------------------------------
  70. bool __fastcall TFileZillaImpl::HandleAsynchRequestOverwrite(
  71. char * FileName1, size_t FileName1Len, const char * FileName2,
  72. const char * Path1, const char * Path2,
  73. __int64 Size1, __int64 Size2, time_t Time1, time_t Time2,
  74. bool HasTime1, bool HasTime2, void * UserData, int & RequestResult)
  75. {
  76. return FFileSystem->HandleAsynchRequestOverwrite(
  77. FileName1, FileName1Len, FileName2, Path1, Path2, Size1, Size2, Time1, Time2,
  78. HasTime1, HasTime2, UserData, RequestResult);
  79. }
  80. //---------------------------------------------------------------------------
  81. bool __fastcall TFileZillaImpl::HandleListData(const char * Path,
  82. const TListDataEntry * Entries, unsigned int Count)
  83. {
  84. return FFileSystem->HandleListData(Path, Entries, Count);
  85. }
  86. //---------------------------------------------------------------------------
  87. bool __fastcall TFileZillaImpl::HandleTransferStatus(bool Valid, __int64 TransferSize,
  88. __int64 Bytes, int Percent, int TimeElapsed, int TimeLeft, int TransferRate,
  89. bool FileTransfer)
  90. {
  91. return FFileSystem->HandleTransferStatus(Valid, TransferSize, Bytes, Percent,
  92. TimeElapsed, TimeLeft, TransferRate, FileTransfer);
  93. }
  94. //---------------------------------------------------------------------------
  95. bool __fastcall TFileZillaImpl::HandleReply(int Command, unsigned int Reply)
  96. {
  97. return FFileSystem->HandleReply(Command, Reply);
  98. }
  99. //---------------------------------------------------------------------------
  100. bool __fastcall TFileZillaImpl::CheckError(int ReturnCode, const char * Context)
  101. {
  102. return FFileSystem->CheckError(ReturnCode, Context);
  103. }
  104. //---------------------------------------------------------------------------
  105. //---------------------------------------------------------------------------
  106. class TMessageQueue : public std::list<std::pair<WPARAM, LPARAM> >
  107. {
  108. };
  109. //---------------------------------------------------------------------------
  110. //---------------------------------------------------------------------------
  111. struct TFileTransferData
  112. {
  113. int Params;
  114. bool AutoResume;
  115. };
  116. //---------------------------------------------------------------------------
  117. const int tfFirstLevel = 0x01;
  118. const int tfAutoResume = 0x02;
  119. //---------------------------------------------------------------------------
  120. struct TSinkFileParams
  121. {
  122. AnsiString TargetDir;
  123. const TCopyParamType * CopyParam;
  124. int Params;
  125. TFileOperationProgressType * OperationProgress;
  126. bool Skipped;
  127. unsigned int Flags;
  128. };
  129. //---------------------------------------------------------------------------
  130. __fastcall TFTPFileSystem::TFTPFileSystem(TTerminal * ATerminal):
  131. TCustomFileSystem(ATerminal),
  132. FFileZillaIntf(NULL),
  133. FQueueCriticalSection(new TCriticalSection),
  134. FQueueEvent(CreateEvent(NULL, true, false, NULL)),
  135. FQueue(new TMessageQueue),
  136. FReply(0),
  137. FCommandReply(0),
  138. FLastCommand(CMD_UNKNOWN),
  139. FLastResponse(new TStringList()),
  140. FLastError(new TStringList()),
  141. FFeatures(new TStringList()),
  142. FFileList(NULL),
  143. FFileListCache(NULL),
  144. FActive(false),
  145. FWaitingForReply(false),
  146. FIgnoreFileList(false),
  147. FOnCaptureOutput(NULL),
  148. FFileSystemInfoValid(false)
  149. {
  150. ResetReply();
  151. FFileSystemInfo.ProtocolBaseName = "FTP";
  152. FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
  153. // capabilities of FTP protocol are fixed
  154. for (int Index = 0; Index < fcCount; Index++)
  155. {
  156. FFileSystemInfo.IsCapable[Index] = IsCapable((TFSCapability)Index);
  157. }
  158. }
  159. //---------------------------------------------------------------------------
  160. __fastcall TFTPFileSystem::~TFTPFileSystem()
  161. {
  162. assert(FFileList == NULL);
  163. FFileZillaIntf->Destroying();
  164. // to release memory associated with the messages
  165. DiscardMessages();
  166. delete FFileZillaIntf;
  167. FFileZillaIntf = NULL;
  168. delete FQueue;
  169. FQueue = NULL;
  170. CloseHandle(FQueueEvent);
  171. delete FQueueCriticalSection;
  172. FQueueCriticalSection = NULL;
  173. delete FLastResponse;
  174. FLastResponse = NULL;
  175. delete FLastError;
  176. FLastError = NULL;
  177. delete FFeatures;
  178. FFeatures = NULL;
  179. ResetCaches();
  180. }
  181. //---------------------------------------------------------------------------
  182. void __fastcall TFTPFileSystem::Open()
  183. {
  184. // on reconnect, typically there may be pending status messages from previous session
  185. DiscardMessages();
  186. FSessionInfo.LoginTime = Now();
  187. FSessionInfo.ProtocolBaseName = "FTP";
  188. FSessionInfo.ProtocolName = FSessionInfo.ProtocolBaseName;
  189. FMultineResponse = false;
  190. // initialize FZAPI on the first connect only
  191. if (FFileZillaIntf == NULL)
  192. {
  193. FFileZillaIntf = new TFileZillaImpl(this);
  194. try
  195. {
  196. TFileZillaIntf::TLogLevel LogLevel;
  197. switch (FTerminal->Configuration->LogProtocol)
  198. {
  199. default:
  200. case 0:
  201. LogLevel = TFileZillaIntf::LOG_LIST;
  202. break;
  203. case 1:
  204. LogLevel = TFileZillaIntf::LOG_WARNING;
  205. break;
  206. case 2:
  207. LogLevel = TFileZillaIntf::LOG_DEBUG;
  208. break;
  209. }
  210. FFileZillaIntf->SetDebugLevel(LogLevel);
  211. FFileZillaIntf->Init();
  212. }
  213. catch(...)
  214. {
  215. delete FFileZillaIntf;
  216. FFileZillaIntf = NULL;
  217. throw;
  218. }
  219. }
  220. TSessionData * Data = FTerminal->SessionData;
  221. AnsiString HostName = Data->HostName;
  222. AnsiString UserName = Data->UserName;
  223. AnsiString Password = Data->Password;
  224. AnsiString Account = Data->FtpAccount;
  225. AnsiString Path = Data->RemoteDirectory;
  226. int ServerType = 0x1000; // FZ_SERVERTYPE_FTP
  227. int Pasv = (Data->FtpPasvMode ? 1 : 2);
  228. int TimeZoneOffset = int(double(Data->TimeDifference) * 24 * 60);
  229. int UTF8 = 0;
  230. switch (Data->SFTPBug[sbUtf])
  231. {
  232. case asOn:
  233. UTF8 = 1;
  234. break;
  235. case asOff:
  236. UTF8 = 2;
  237. break;
  238. case asAuto:
  239. UTF8 = 0;
  240. break;
  241. };
  242. FPasswordFailed = false;
  243. bool PromptedForCredentials = false;
  244. do
  245. {
  246. FSystem = "";
  247. FFeatures->Clear();
  248. FFileSystemInfoValid = false;
  249. // !!! the same for account? it ever used?
  250. // ask for username if it was not specified in advance, even on retry,
  251. // but keep previous one as default,
  252. if (Data->UserName.IsEmpty())
  253. {
  254. FTerminal->LogEvent("Username prompt (no username provided)");
  255. if (!FPasswordFailed && !PromptedForCredentials)
  256. {
  257. FTerminal->Information(LoadStr(FTP_CREDENTIAL_PROMPT), false);
  258. PromptedForCredentials = true;
  259. }
  260. if (!FTerminal->PromptUser(Data,
  261. FMTLOAD(USERNAME_PROMPT, (Data->SessionName)),
  262. pkPrompt, UserName))
  263. {
  264. FTerminal->FatalError(NULL, LoadStr(AUTHENTICATION_FAILED));
  265. }
  266. else
  267. {
  268. FUserName = UserName;
  269. }
  270. }
  271. // ask for username if it was not specified in advance,
  272. // on retry ask always
  273. if (Data->Password.IsEmpty() || FPasswordFailed)
  274. {
  275. FTerminal->LogEvent("Password prompt (no password provided or last login attempt failed)");
  276. if (!FPasswordFailed && !PromptedForCredentials)
  277. {
  278. FTerminal->Information(LoadStr(FTP_CREDENTIAL_PROMPT), false);
  279. PromptedForCredentials = true;
  280. }
  281. // on retry ask for new password
  282. Password = "";
  283. if (!FTerminal->PromptUser(Data,
  284. FMTLOAD(PROMPT_SESSION_PASSWORD, (Data->SessionName)),
  285. pkPassword, Password))
  286. {
  287. FTerminal->FatalError(NULL, LoadStr(AUTHENTICATION_FAILED));
  288. }
  289. }
  290. FActive = FFileZillaIntf->Connect(
  291. HostName.c_str(), Data->PortNumber, UserName.c_str(),
  292. Password.c_str(), Account.c_str(), false, Path.c_str(),
  293. ServerType, Pasv, TimeZoneOffset, UTF8);
  294. assert(FActive);
  295. FPasswordFailed = false;
  296. try
  297. {
  298. GotReply(WaitForReply(), REPLY_CONNECT, LoadStr(CONNECTION_FAILED));
  299. // we have passed, even if we got 530 on the way (if it is possible at all),
  300. // ignore it
  301. assert(!FPasswordFailed);
  302. FPasswordFailed = false;
  303. }
  304. catch(...)
  305. {
  306. if (FPasswordFailed)
  307. {
  308. FTerminal->Information(LoadStr(FTP_ACCESS_DENIED), false);
  309. }
  310. else
  311. {
  312. throw;
  313. }
  314. }
  315. }
  316. while (FPasswordFailed);
  317. }
  318. //---------------------------------------------------------------------------
  319. void __fastcall TFTPFileSystem::Close()
  320. {
  321. assert(FActive);
  322. if (FFileZillaIntf->Close())
  323. {
  324. CHECK(FLAGSET(WaitForReply(), TFileZillaIntf::REPLY_DISCONNECTED));
  325. assert(FActive);
  326. Discard();
  327. }
  328. else
  329. {
  330. assert(false);
  331. }
  332. }
  333. //---------------------------------------------------------------------------
  334. bool __fastcall TFTPFileSystem::GetActive()
  335. {
  336. return FActive;
  337. }
  338. //---------------------------------------------------------------------------
  339. void __fastcall TFTPFileSystem::Idle()
  340. {
  341. if (FActive && !FWaitingForReply)
  342. {
  343. unsigned int Reply = PoolForReply();
  344. if (Reply != 0)
  345. {
  346. assert(FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  347. GotReply(Reply);
  348. }
  349. }
  350. }
  351. //---------------------------------------------------------------------------
  352. void __fastcall TFTPFileSystem::Discard()
  353. {
  354. // remove all pending messages, to get complete log
  355. // note that we need to retry discard on reconnect, as there still may be another
  356. // "disconnect/timeout/..." status messages coming
  357. DiscardMessages();
  358. assert(FActive);
  359. FActive = false;
  360. FTerminal->Closed();
  361. }
  362. //---------------------------------------------------------------------------
  363. AnsiString __fastcall TFTPFileSystem::AbsolutePath(AnsiString Path)
  364. {
  365. // TODO: improve (handle .. etc.)
  366. if (TTerminal::IsAbsolutePath(Path))
  367. {
  368. return Path;
  369. }
  370. else
  371. {
  372. return ::AbsolutePath(FCurrentDirectory, Path);
  373. }
  374. }
  375. //---------------------------------------------------------------------------
  376. void __fastcall TFTPFileSystem::EnsureLocation()
  377. {
  378. // if we do not know what's the current directory, do nothing
  379. if (!FCurrentDirectory.IsEmpty())
  380. {
  381. // Make sure that the FZAPI current working directory,
  382. // is actually our working directory.
  383. // It may not be because:
  384. // 1) We did cached directory change
  385. // 2) Listing was requested for non-current directory, which
  386. // makes FAPI change its current directory (and not restoring it back afterwards)
  387. char CurrentPath[1024];
  388. FFileZillaIntf->GetCurrentPath(CurrentPath, sizeof(CurrentPath));
  389. if (!UnixComparePaths(CurrentPath, FCurrentDirectory))
  390. {
  391. FTerminal->LogEvent(FORMAT("Synchronizing current directory \"%s\".",
  392. (FCurrentDirectory)));
  393. DoChangeDirectory(FCurrentDirectory);
  394. }
  395. }
  396. }
  397. //---------------------------------------------------------------------------
  398. void __fastcall TFTPFileSystem::AnyCommand(const AnsiString Command,
  399. TCaptureOutputEvent OutputEvent)
  400. {
  401. // end-user has right to expect that client current directory is really
  402. // current directory for the server
  403. EnsureLocation();
  404. assert(FOnCaptureOutput == NULL);
  405. FOnCaptureOutput = OutputEvent;
  406. try
  407. {
  408. FFileZillaIntf->CustomCommand(Command.c_str());
  409. GotReply(WaitForReply(), REPLY_2XX_CODE);
  410. }
  411. __finally
  412. {
  413. FOnCaptureOutput = NULL;
  414. }
  415. }
  416. //---------------------------------------------------------------------------
  417. void __fastcall TFTPFileSystem::ResetCaches()
  418. {
  419. delete FFileListCache;
  420. FFileListCache = NULL;
  421. }
  422. //---------------------------------------------------------------------------
  423. void __fastcall TFTPFileSystem::AnnounceFileListOperation()
  424. {
  425. ResetCaches();
  426. }
  427. //---------------------------------------------------------------------------
  428. void __fastcall TFTPFileSystem::DoChangeDirectory(const AnsiString & Directory)
  429. {
  430. AnsiString Command = FORMAT("CWD %s", (Directory));
  431. FFileZillaIntf->CustomCommand(Command.c_str());
  432. GotReply(WaitForReply(), REPLY_2XX_CODE);
  433. }
  434. //---------------------------------------------------------------------------
  435. void __fastcall TFTPFileSystem::ChangeDirectory(const AnsiString ADirectory)
  436. {
  437. AnsiString Directory = ADirectory;
  438. try
  439. {
  440. // For changing directory, we do not make paths absolute, instead we
  441. // delegate this to the server, hence we sychronize current working
  442. // directory with the server and only then we ask for the change with
  443. // relative path.
  444. // But if synchronization fails, typically because current working directory
  445. // no longer exists, we fall back to out own resolution, to give
  446. // user chance to leave the non-existing directory.
  447. EnsureLocation();
  448. }
  449. catch(...)
  450. {
  451. if (FTerminal->Active)
  452. {
  453. Directory = AbsolutePath(Directory);
  454. }
  455. else
  456. {
  457. throw;
  458. }
  459. }
  460. DoChangeDirectory(Directory);
  461. // make next ReadCurrentDirectory retrieve actual server-side current directory
  462. FCurrentDirectory = "";
  463. }
  464. //---------------------------------------------------------------------------
  465. void __fastcall TFTPFileSystem::CachedChangeDirectory(const AnsiString Directory)
  466. {
  467. FCurrentDirectory = Directory;
  468. }
  469. //---------------------------------------------------------------------------
  470. void __fastcall TFTPFileSystem::ChangeFileProperties(const AnsiString AFileName,
  471. const TRemoteFile * File, const TRemoteProperties * Properties)
  472. {
  473. assert(!Properties->Valid.Contains(vpGroup));
  474. assert(!Properties->Valid.Contains(vpOwner));
  475. assert(!Properties->Valid.Contains(vpLastAccess));
  476. assert(!Properties->Valid.Contains(vpModification));
  477. if (Properties->Valid.Contains(vpRights))
  478. {
  479. assert(Properties);
  480. TRemoteFile * OwnedFile = NULL;
  481. try
  482. {
  483. AnsiString FileName = AbsolutePath(AFileName);
  484. if (File == NULL)
  485. {
  486. ReadFile(FileName, OwnedFile);
  487. File = OwnedFile;
  488. }
  489. if ((File != NULL) && File->IsDirectory && !File->IsSymLink && Properties->Recursive)
  490. {
  491. FTerminal->ProcessDirectory(AFileName, FTerminal->ChangeFileProperties,
  492. (void*)Properties);
  493. }
  494. TRights Rights;
  495. if (File != NULL)
  496. {
  497. Rights = *File->Rights;
  498. }
  499. Rights |= Properties->Rights.NumberSet;
  500. Rights &= (unsigned short)~Properties->Rights.NumberUnset;
  501. if ((File != NULL) && File->IsDirectory && Properties->AddXToDirectories)
  502. {
  503. Rights.AddExecute();
  504. }
  505. AnsiString FileNameOnly = UnixExtractFileName(FileName);
  506. AnsiString FilePath = UnixExtractFilePath(FileName);
  507. // FZAPI wants octal number represented as decadic
  508. FFileZillaIntf->Chmod(Rights.NumberDecadic, FileNameOnly.c_str(), FilePath.c_str());
  509. GotReply(WaitForReply(), REPLY_2XX_CODE);
  510. }
  511. __finally
  512. {
  513. delete OwnedFile;
  514. }
  515. }
  516. }
  517. //---------------------------------------------------------------------------
  518. bool __fastcall TFTPFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  519. {
  520. assert(false);
  521. return false;
  522. }
  523. //---------------------------------------------------------------------------
  524. void __fastcall TFTPFileSystem::CalculateFilesChecksum(const AnsiString & /*Alg*/,
  525. TStrings * /*FileList*/, TStrings * /*Checksums*/,
  526. TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
  527. {
  528. assert(false);
  529. }
  530. //---------------------------------------------------------------------------
  531. bool __fastcall TFTPFileSystem::ConfirmOverwrite(AnsiString & FileName,
  532. TOverwriteMode & OverwriteMode, TFileOperationProgressType * OperationProgress,
  533. const TOverwriteFileParams * FileParams, int Params, bool AutoResume)
  534. {
  535. bool Result;
  536. if (OperationProgress->YesToAll)
  537. {
  538. OverwriteMode = omOverwrite;
  539. Result = true;
  540. }
  541. else if (OperationProgress->NoToAll)
  542. {
  543. FFileTransferAbort = ftaSkip;
  544. Result = false;
  545. }
  546. else
  547. {
  548. bool CanResume = (FileParams->DestSize < FileParams->SourceSize);
  549. int Answer;
  550. if (FLAGSET(Params, cpNoConfirmation))
  551. {
  552. Answer = (CanResume && AutoResume ? qaRetry : qaYes);
  553. }
  554. else
  555. {
  556. // retry = "resume"
  557. // all = "yes to newer"
  558. // ignore = "rename"
  559. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  560. if (CanResume)
  561. {
  562. Answers |= qaRetry;
  563. }
  564. TQueryButtonAlias Aliases[3];
  565. Aliases[0].Button = qaRetry;
  566. Aliases[0].Alias = LoadStr(RESUME_BUTTON);
  567. Aliases[1].Button = qaAll;
  568. Aliases[1].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  569. Aliases[2].Button = qaIgnore;
  570. Aliases[2].Alias = LoadStr(RENAME_BUTTON);
  571. TQueryParams Params(qpNeverAskAgainCheck);
  572. Params.Aliases = Aliases;
  573. Params.AliasesCount = LENOF(Aliases);
  574. SUSPEND_OPERATION
  575. (
  576. Answer = FTerminal->ConfirmFileOverwrite(FileName, FileParams,
  577. Answers, &Params,
  578. OperationProgress->Side == osLocal ? osRemote : osLocal,
  579. OperationProgress);
  580. )
  581. }
  582. Result = true;
  583. switch (Answer)
  584. {
  585. // resume
  586. case qaRetry:
  587. OverwriteMode = omResume;
  588. FFileTransferResumed = FileParams->DestSize;
  589. break;
  590. // rename
  591. case qaIgnore:
  592. if (FTerminal->PromptUser(FTerminal->SessionData, LoadStr(RENAME_PROMPT),
  593. pkPrompt, FileName))
  594. {
  595. OverwriteMode = omOverwrite;
  596. }
  597. else
  598. {
  599. if (!OperationProgress->Cancel)
  600. {
  601. OperationProgress->Cancel = csCancel;
  602. }
  603. FFileTransferAbort = ftaCancel;
  604. Result = false;
  605. }
  606. break;
  607. case qaYes:
  608. OverwriteMode = omOverwrite;
  609. break;
  610. case qaCancel:
  611. if (!OperationProgress->Cancel)
  612. {
  613. OperationProgress->Cancel = csCancel;
  614. }
  615. FFileTransferAbort = ftaCancel;
  616. Result = false;
  617. break;
  618. case qaNo:
  619. FFileTransferAbort = ftaSkip;
  620. Result = false;
  621. break;
  622. default:
  623. assert(false);
  624. Result = false;
  625. break;
  626. }
  627. }
  628. return Result;
  629. }
  630. //---------------------------------------------------------------------------
  631. void __fastcall TFTPFileSystem::ResetFileTransfer()
  632. {
  633. FFileTransferAbort = ftaNone;
  634. FFileTransferCancelled = false;
  635. FFileTransferResumed = 0;
  636. }
  637. //---------------------------------------------------------------------------
  638. void __fastcall TFTPFileSystem::CheckFileTransferAbort()
  639. {
  640. switch (FFileTransferAbort)
  641. {
  642. case ftaSkip:
  643. THROW_SKIP_FILE_NULL;
  644. case ftaCancel:
  645. Abort();
  646. break;
  647. }
  648. }
  649. //---------------------------------------------------------------------------
  650. void __fastcall TFTPFileSystem::ReadDirectoryProgress(__int64 Bytes)
  651. {
  652. // with FTP we do not know exactly how many entries we have received,
  653. // instead we know number of bytes received only.
  654. // so we report approximation based on average size of entry.
  655. int Progress = int(Bytes / 80);
  656. if (Progress - FLastReadDirectoryProgress >= 10)
  657. {
  658. bool Cancel = false;
  659. FLastReadDirectoryProgress = Progress;
  660. FTerminal->DoReadDirectoryProgress(Progress, Cancel);
  661. if (Cancel)
  662. {
  663. FTerminal->DoReadDirectoryProgress(-2, Cancel);
  664. FFileZillaIntf->Cancel();
  665. }
  666. }
  667. }
  668. //---------------------------------------------------------------------------
  669. void __fastcall TFTPFileSystem::FileTransferProgress(__int64 TransferSize,
  670. __int64 Bytes, int /*Percent*/)
  671. {
  672. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  673. OperationProgress->SetTransferSize(TransferSize);
  674. if (FFileTransferResumed > 0)
  675. {
  676. OperationProgress->AddResumed(FFileTransferResumed);
  677. FFileTransferResumed = 0;
  678. }
  679. assert(OperationProgress->TransferedSize <= Bytes);
  680. OperationProgress->AddTransfered(Bytes - OperationProgress->TransferedSize);
  681. if (OperationProgress->Cancel == csCancel)
  682. {
  683. FFileTransferCancelled = true;
  684. FFileZillaIntf->Cancel();
  685. }
  686. }
  687. //---------------------------------------------------------------------------
  688. void __fastcall TFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  689. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  690. int Params, TFileOperationProgressType * OperationProgress,
  691. bool & DisconnectWhenComplete)
  692. {
  693. AnsiString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  694. int Index = 0;
  695. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  696. {
  697. AnsiString FileName = FilesToCopy->Strings[Index];
  698. const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
  699. bool Success = false;
  700. try
  701. {
  702. try
  703. {
  704. SinkRobust(AbsolutePath(FileName), File, FullTargetDir, CopyParam, Params,
  705. OperationProgress, tfFirstLevel);
  706. Success = true;
  707. }
  708. catch(EScpSkipFile & E)
  709. {
  710. SUSPEND_OPERATION (
  711. if (!FTerminal->HandleException(&E)) throw;
  712. );
  713. }
  714. }
  715. __finally
  716. {
  717. OperationProgress->Finish(FileName, Success, DisconnectWhenComplete);
  718. }
  719. Index++;
  720. }
  721. }
  722. //---------------------------------------------------------------------------
  723. void __fastcall TFTPFileSystem::SinkRobust(const AnsiString FileName,
  724. const TRemoteFile * File, const AnsiString TargetDir,
  725. const TCopyParamType * CopyParam, int Params,
  726. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  727. {
  728. // the same in TSFTPFileSystem
  729. bool Retry;
  730. // set in advance as particularly cpNoConfirmation may change
  731. int ReopenParams =
  732. ropNoReadDirectory |
  733. FLAGMASK(FLAGSET(Params, cpNoConfirmation), ropNoConfirmation);
  734. do
  735. {
  736. Retry = false;
  737. try
  738. {
  739. Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress, Flags);
  740. }
  741. catch(Exception & E)
  742. {
  743. Retry = true;
  744. if (FTerminal->Active ||
  745. !FTerminal->QueryReopen(&E, ReopenParams, OperationProgress))
  746. {
  747. throw;
  748. }
  749. }
  750. if (Retry)
  751. {
  752. OperationProgress->RollbackTransfer();
  753. assert(File != NULL);
  754. if (!File->IsDirectory)
  755. {
  756. // prevent overwrite confirmations
  757. Params |= cpNoConfirmation;
  758. Flags |= tfAutoResume;
  759. }
  760. }
  761. }
  762. while (Retry);
  763. }
  764. //---------------------------------------------------------------------------
  765. void __fastcall TFTPFileSystem::Sink(const AnsiString FileName,
  766. const TRemoteFile * File, const AnsiString TargetDir,
  767. const TCopyParamType * CopyParam, int Params,
  768. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  769. {
  770. AnsiString OnlyFileName = UnixExtractFileName(FileName);
  771. TFileMasks::TParams MaskParams;
  772. MaskParams.Size = File->Size;
  773. if (FLAGCLEAR(Params, cpDelete) &&
  774. !CopyParam->AllowTransfer(FileName, osRemote, File->IsDirectory, MaskParams))
  775. {
  776. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  777. THROW_SKIP_FILE_NULL;
  778. }
  779. assert(File);
  780. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  781. OperationProgress->SetFile(OnlyFileName);
  782. AnsiString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
  783. osRemote, FLAGSET(Flags, tfFirstLevel));
  784. AnsiString DestFullName = TargetDir + DestFileName;
  785. if (File->IsDirectory)
  786. {
  787. if (!File->IsSymLink)
  788. {
  789. FILE_OPERATION_LOOP (FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)),
  790. int Attrs = FileGetAttr(DestFullName);
  791. if (FLAGCLEAR(Attrs, faDirectory))
  792. {
  793. EXCEPTION;
  794. }
  795. );
  796. FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFullName)),
  797. if (!ForceDirectories(DestFullName))
  798. {
  799. EXCEPTION;
  800. }
  801. );
  802. TSinkFileParams SinkFileParams;
  803. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  804. SinkFileParams.CopyParam = CopyParam;
  805. SinkFileParams.Params = Params;
  806. SinkFileParams.OperationProgress = OperationProgress;
  807. SinkFileParams.Skipped = false;
  808. SinkFileParams.Flags = Flags & ~(tfFirstLevel | tfAutoResume);
  809. FTerminal->ProcessDirectory(FileName, SinkFile, &SinkFileParams);
  810. // Do not delete directory if some of its files were skip.
  811. // Throw "skip file" for the directory to avoid attempt to deletion
  812. // of any parent directory
  813. if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
  814. {
  815. THROW_SKIP_FILE_NULL;
  816. }
  817. }
  818. else
  819. {
  820. // file is symlink to directory, currently do nothing, but it should be
  821. // reported to user
  822. }
  823. }
  824. else
  825. {
  826. FTerminal->LogEvent(FORMAT("Copying \"%s\" to local directory started.", (FileName)));
  827. // Will we use ASCII of BINARY file tranfer?
  828. OperationProgress->SetAsciiTransfer(
  829. CopyParam->UseAsciiTransfer(FileName, osRemote, MaskParams));
  830. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  831. " transfer mode selected.");
  832. // Suppose same data size to transfer as to write
  833. OperationProgress->SetTransferSize(File->Size);
  834. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  835. int Attrs;
  836. FILE_OPERATION_LOOP (FMTLOAD(NOT_FILE_ERROR, (DestFullName)),
  837. Attrs = FileGetAttr(DestFullName);
  838. if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory))
  839. {
  840. EXCEPTION;
  841. }
  842. );
  843. OperationProgress->TransferingFile = false; // not set with FTP protocol
  844. ResetFileTransfer();
  845. AnsiString FilePath = UnixExtractFilePath(FileName);
  846. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  847. assert(!FIgnoreFileList);
  848. FIgnoreFileList = true;
  849. try
  850. {
  851. FFileTransferPreserveTime = CopyParam->PreserveTime;
  852. FFileTransferFileName = DestFileName;
  853. TFileTransferData UserData;
  854. UserData.Params = Params;
  855. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  856. FFileZillaIntf->FileTransfer(DestFullName.c_str(), OnlyFileName.c_str(),
  857. FilePath.c_str(), true, File->Size, TransferType, &UserData);
  858. unsigned int Reply = WaitForReply();
  859. GotReply(Reply, FLAGMASK(FFileTransferCancelled, REPLY_ALLOW_CANCEL));
  860. }
  861. __finally
  862. {
  863. FIgnoreFileList = false;
  864. }
  865. CheckFileTransferAbort();
  866. // in case dest filename is changed from overwrite dialog
  867. if (DestFileName != FFileTransferFileName)
  868. {
  869. DestFullName = TargetDir + FFileTransferFileName;
  870. Attrs = FileGetAttr(DestFullName);
  871. }
  872. if (Attrs == -1)
  873. {
  874. Attrs = faArchive;
  875. }
  876. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  877. if ((NewAttrs & Attrs) != NewAttrs)
  878. {
  879. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFullName)),
  880. THROWIFFALSE(FileSetAttr(DestFullName, Attrs | NewAttrs) == 0);
  881. );
  882. }
  883. }
  884. if (FLAGSET(Params, cpDelete))
  885. {
  886. // If file is directory, do not delete it recursively, because it should be
  887. // empty already. If not, it should not be deleted (some files were
  888. // skipped or some new files were copied to it, while we were downloading)
  889. bool Recursive = false;
  890. FTerminal->DeleteFile(FileName, File, &Recursive);
  891. }
  892. }
  893. //---------------------------------------------------------------------------
  894. void __fastcall TFTPFileSystem::SinkFile(AnsiString FileName,
  895. const TRemoteFile * File, void * Param)
  896. {
  897. TSinkFileParams * Params = (TSinkFileParams *)Param;
  898. assert(Params->OperationProgress);
  899. try
  900. {
  901. SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  902. Params->Params, Params->OperationProgress, Params->Flags);
  903. }
  904. catch(EScpSkipFile & E)
  905. {
  906. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  907. Params->Skipped = true;
  908. SUSPEND_OPERATION (
  909. if (!FTerminal->HandleException(&E))
  910. {
  911. throw;
  912. }
  913. );
  914. if (OperationProgress->Cancel)
  915. {
  916. Abort();
  917. }
  918. }
  919. }
  920. //---------------------------------------------------------------------------
  921. void __fastcall TFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  922. const AnsiString ATargetDir, const TCopyParamType * CopyParam,
  923. int Params, TFileOperationProgressType * OperationProgress,
  924. bool & DisconnectWhenComplete)
  925. {
  926. assert((FilesToCopy != NULL) && (OperationProgress != NULL));
  927. AnsiString FileName, FileNameOnly;
  928. AnsiString TargetDir = AbsolutePath(ATargetDir);
  929. AnsiString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  930. int Index = 0;
  931. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  932. {
  933. bool Success = false;
  934. FileName = FilesToCopy->Strings[Index];
  935. FileNameOnly = ExtractFileName(FileName);
  936. try
  937. {
  938. try
  939. {
  940. if (FTerminal->SessionData->CacheDirectories)
  941. {
  942. FTerminal->DirectoryModified(TargetDir, false);
  943. if (DirectoryExists(FileName))
  944. {
  945. FTerminal->DirectoryModified(FullTargetDir + FileNameOnly, true);
  946. }
  947. }
  948. SourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  949. tfFirstLevel);
  950. Success = true;
  951. }
  952. catch(EScpSkipFile & E)
  953. {
  954. SUSPEND_OPERATION (
  955. if (!FTerminal->HandleException(&E)) throw;
  956. );
  957. }
  958. }
  959. __finally
  960. {
  961. OperationProgress->Finish(FileName, Success, DisconnectWhenComplete);
  962. }
  963. Index++;
  964. }
  965. }
  966. //---------------------------------------------------------------------------
  967. void __fastcall TFTPFileSystem::SourceRobust(const AnsiString FileName,
  968. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  969. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  970. {
  971. // the same in TSFTPFileSystem
  972. bool Retry;
  973. // set in advance as particularly cpNoConfirmation may change
  974. int ReopenParams =
  975. ropNoReadDirectory |
  976. FLAGMASK(FLAGSET(Params, cpNoConfirmation), ropNoConfirmation);
  977. do
  978. {
  979. Retry = false;
  980. try
  981. {
  982. Source(FileName, TargetDir, CopyParam, Params, OperationProgress, Flags);
  983. }
  984. catch(Exception & E)
  985. {
  986. Retry = true;
  987. if (FTerminal->Active ||
  988. !FTerminal->QueryReopen(&E, ReopenParams, OperationProgress))
  989. {
  990. throw;
  991. }
  992. }
  993. if (Retry)
  994. {
  995. OperationProgress->RollbackTransfer();
  996. // prevent overwrite confirmations
  997. // (should not be set for directories!)
  998. Params |= cpNoConfirmation;
  999. Flags |= tfAutoResume;
  1000. }
  1001. }
  1002. while (Retry);
  1003. }
  1004. //---------------------------------------------------------------------------
  1005. void __fastcall TFTPFileSystem::Source(const AnsiString FileName,
  1006. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  1007. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1008. {
  1009. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  1010. OperationProgress->SetFile(FileName);
  1011. __int64 Size;
  1012. int Attrs;
  1013. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &Attrs,
  1014. NULL, NULL, NULL, NULL, &Size);
  1015. bool Dir = FLAGSET(Attrs, faDirectory);
  1016. TFileMasks::TParams MaskParams;
  1017. MaskParams.Size = Size;
  1018. if (FLAGCLEAR(Params, cpDelete) &&
  1019. !CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams))
  1020. {
  1021. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  1022. THROW_SKIP_FILE_NULL;
  1023. }
  1024. if (Dir)
  1025. {
  1026. DirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  1027. Attrs, CopyParam, Params, OperationProgress, Flags);
  1028. }
  1029. else
  1030. {
  1031. AnsiString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
  1032. osLocal, FLAGSET(Flags, tfFirstLevel));
  1033. AnsiString DestFullName = TargetDir + DestFileName;
  1034. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  1035. OperationProgress->SetLocalSize(Size);
  1036. // Suppose same data size to transfer as to read
  1037. // (not true with ASCII transfer)
  1038. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1039. OperationProgress->TransferingFile = false;
  1040. // Will we use ASCII of BINARY file tranfer?
  1041. OperationProgress->SetAsciiTransfer(
  1042. CopyParam->UseAsciiTransfer(FileName, osLocal, MaskParams));
  1043. FTerminal->LogEvent(
  1044. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  1045. " transfer mode selected.");
  1046. ResetFileTransfer();
  1047. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1048. assert(!FIgnoreFileList);
  1049. FIgnoreFileList = true;
  1050. try
  1051. {
  1052. // not supports for uploads anyway
  1053. FFileTransferPreserveTime = CopyParam->PreserveTime;
  1054. // not used for uploads
  1055. FFileTransferFileName = DestFileName;
  1056. TFileTransferData UserData;
  1057. UserData.Params = Params;
  1058. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1059. FFileZillaIntf->FileTransfer(FileName.c_str(), DestFileName.c_str(),
  1060. TargetDir.c_str(), false, Size, TransferType, &UserData);
  1061. unsigned int Reply = WaitForReply();
  1062. GotReply(Reply, FLAGMASK(FFileTransferCancelled, REPLY_ALLOW_CANCEL));
  1063. }
  1064. __finally
  1065. {
  1066. FIgnoreFileList = false;
  1067. }
  1068. }
  1069. /* TODO : Delete also read-only files. */
  1070. /* TODO : Show error message on failure. */
  1071. if (FLAGSET(Params, cpDelete))
  1072. {
  1073. Sysutils::DeleteFile(FileName);
  1074. }
  1075. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1076. {
  1077. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  1078. THROWIFFALSE(FileSetAttr(FileName, Attrs & ~faArchive) == 0);
  1079. )
  1080. }
  1081. }
  1082. //---------------------------------------------------------------------------
  1083. void __fastcall TFTPFileSystem::DirectorySource(const AnsiString DirectoryName,
  1084. const AnsiString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  1085. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1086. {
  1087. AnsiString DestDirectoryName = CopyParam->ChangeFileName(
  1088. ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal,
  1089. FLAGSET(Flags, tfFirstLevel));
  1090. AnsiString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  1091. OperationProgress->SetFile(DirectoryName);
  1092. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1093. TSearchRec SearchRec;
  1094. bool FindOK;
  1095. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1096. FindOK = (bool)(FindFirst(DirectoryName + "*.*",
  1097. FindAttrs, SearchRec) == 0);
  1098. );
  1099. while (FindOK && !OperationProgress->Cancel)
  1100. {
  1101. AnsiString FileName = DirectoryName + SearchRec.Name;
  1102. try
  1103. {
  1104. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  1105. {
  1106. SourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  1107. Flags & ~(tfFirstLevel | tfAutoResume));
  1108. }
  1109. }
  1110. catch (EScpSkipFile &E)
  1111. {
  1112. // If ESkipFile occurs, just log it and continue with next file
  1113. SUSPEND_OPERATION (
  1114. // here a message to user was displayed, which was not appropriate
  1115. // when user refused to overwrite the file in subdirectory.
  1116. // hopefuly it won't be missing in other situations.
  1117. if (!FTerminal->HandleException(&E)) throw;
  1118. );
  1119. }
  1120. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1121. FindOK = (FindNext(SearchRec) == 0);
  1122. );
  1123. };
  1124. FindClose(SearchRec);
  1125. /* TODO : Delete also read-only directories. */
  1126. /* TODO : Show error message on failure. */
  1127. if (!OperationProgress->Cancel)
  1128. {
  1129. if (FLAGSET(Params, cpDelete))
  1130. {
  1131. RemoveDir(DirectoryName);
  1132. }
  1133. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1134. {
  1135. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DirectoryName)),
  1136. THROWIFFALSE(FileSetAttr(DirectoryName, Attrs & ~faArchive) == 0);
  1137. )
  1138. }
  1139. }
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. void __fastcall TFTPFileSystem::CreateDirectory(const AnsiString ADirName,
  1143. const TRemoteProperties * Properties)
  1144. {
  1145. AnsiString DirName = AbsolutePath(ADirName);
  1146. FIgnoreFileList = true;
  1147. try
  1148. {
  1149. FFileZillaIntf->MakeDir(DirName.c_str());
  1150. GotReply(WaitForReply(), REPLY_2XX_CODE);
  1151. }
  1152. __finally
  1153. {
  1154. FIgnoreFileList = false;
  1155. }
  1156. if (Properties != NULL)
  1157. {
  1158. ChangeFileProperties(DirName, NULL, Properties);
  1159. }
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. void __fastcall TFTPFileSystem::CreateLink(const AnsiString /*FileName*/,
  1163. const AnsiString /*PointTo*/, bool /*Symbolic*/)
  1164. {
  1165. assert(false);
  1166. }
  1167. //---------------------------------------------------------------------------
  1168. void __fastcall TFTPFileSystem::DeleteFile(const AnsiString AFileName,
  1169. const TRemoteFile * File, bool Recursive)
  1170. {
  1171. AnsiString FileName = AbsolutePath(AFileName);
  1172. AnsiString FileNameOnly = UnixExtractFileName(FileName);
  1173. AnsiString FilePath = UnixExtractFilePath(FileName);
  1174. bool Dir = (File != NULL) && File->IsDirectory && !File->IsSymLink;
  1175. if (Dir && Recursive)
  1176. {
  1177. FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Recursive);
  1178. }
  1179. assert(!FIgnoreFileList);
  1180. FIgnoreFileList = true;
  1181. try
  1182. {
  1183. if (Dir)
  1184. {
  1185. FFileZillaIntf->RemoveDir(FileNameOnly.c_str(), FilePath.c_str());
  1186. }
  1187. else
  1188. {
  1189. FFileZillaIntf->Delete(FileNameOnly.c_str(), FilePath.c_str());
  1190. }
  1191. GotReply(WaitForReply(), REPLY_2XX_CODE);
  1192. }
  1193. __finally
  1194. {
  1195. FIgnoreFileList = false;
  1196. }
  1197. }
  1198. //---------------------------------------------------------------------------
  1199. void __fastcall TFTPFileSystem::CustomCommandOnFile(const AnsiString /*FileName*/,
  1200. const TRemoteFile * /*File*/, AnsiString /*Command*/, int /*Params*/,
  1201. TCaptureOutputEvent /*OutputEvent*/)
  1202. {
  1203. // if ever implemeneted, do not forget to add EnsureLocation,
  1204. // see AnyCommand for a reason why
  1205. assert(false);
  1206. }
  1207. //---------------------------------------------------------------------------
  1208. void __fastcall TFTPFileSystem::DoStartup()
  1209. {
  1210. // retrieve initialize working directory to save it as home directory
  1211. ReadCurrentDirectory();
  1212. FHomeDirectory = FCurrentDirectory;
  1213. }
  1214. //---------------------------------------------------------------------------
  1215. void __fastcall TFTPFileSystem::HomeDirectory()
  1216. {
  1217. // FHomeDirectory is an absolute path, so avoid unnecessary overhead
  1218. // of ChangeDirectory, such as EnsureLocation
  1219. DoChangeDirectory(FHomeDirectory);
  1220. FCurrentDirectory = FHomeDirectory;
  1221. }
  1222. //---------------------------------------------------------------------------
  1223. bool __fastcall TFTPFileSystem::IsCapable(int Capability) const
  1224. {
  1225. assert(FTerminal);
  1226. switch (Capability)
  1227. {
  1228. case fcResolveSymlink: // sic
  1229. case fcTextMode:
  1230. case fcModeChanging: // but not fcModeChangingUpload
  1231. case fcNewerOnlyUpload:
  1232. case fcAnyCommand: // but not fcShellAnyCommand
  1233. case fcRename:
  1234. case fcRemoteMove:
  1235. return true;
  1236. case fcModeChangingUpload:
  1237. case fcPreservingTimestampUpload:
  1238. case fcLoadingAdditionalProperties:
  1239. case fcShellAnyCommand:
  1240. case fcCalculatingChecksum:
  1241. case fcHardLink:
  1242. case fcSymbolicLink:
  1243. case fcCheckingSpaceAvailable:
  1244. case fcUserGroupListing:
  1245. case fcGroupChanging:
  1246. case fcOwnerChanging:
  1247. case fcSecondaryShell:
  1248. case fcRemoteCopy:
  1249. case fcNativeTextMode:
  1250. case fcTimestampChanging:
  1251. case fcIgnorePermErrors:
  1252. return false;
  1253. default:
  1254. assert(false);
  1255. return false;
  1256. }
  1257. }
  1258. //---------------------------------------------------------------------------
  1259. void __fastcall TFTPFileSystem::LookupUsersGroups()
  1260. {
  1261. assert(false);
  1262. }
  1263. //---------------------------------------------------------------------------
  1264. void __fastcall TFTPFileSystem::ReadCurrentDirectory()
  1265. {
  1266. // ask the server for current directory on startup only
  1267. // and immediatelly after call to CWD,
  1268. // later our current directory may be not synchronized with FZAPI current
  1269. // directory anyway, see comments in EnsureLocation
  1270. if (FCurrentDirectory.IsEmpty())
  1271. {
  1272. FFileZillaIntf->CustomCommand("PWD");
  1273. unsigned int Code;
  1274. TStrings * Response = NULL;
  1275. GotReply(WaitForReply(), REPLY_2XX_CODE, "", &Code, &Response);
  1276. try
  1277. {
  1278. assert(Response != NULL);
  1279. bool Result = false;
  1280. // the only allowed 2XX code to "PWD"
  1281. if ((Code == 257) &&
  1282. (Response->Count == 1))
  1283. {
  1284. AnsiString Path = Response->Text;
  1285. int P = Path.Pos("\"");
  1286. if (P != 0)
  1287. {
  1288. Path.Delete(1, P - 1);
  1289. if (Unquote(Path))
  1290. {
  1291. FCurrentDirectory = Path;
  1292. Result = true;
  1293. }
  1294. }
  1295. }
  1296. if (Result)
  1297. {
  1298. FFileZillaIntf->SetCurrentPath(FCurrentDirectory.c_str());
  1299. }
  1300. else
  1301. {
  1302. throw Exception(FMTLOAD(FTP_PWD_RESPONSE_ERROR, (Response->Text)));
  1303. }
  1304. }
  1305. __finally
  1306. {
  1307. delete Response;
  1308. }
  1309. }
  1310. }
  1311. //---------------------------------------------------------------------------
  1312. void __fastcall TFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  1313. {
  1314. FileList->Clear();
  1315. // FZAPI does not list parent directory, add it
  1316. FileList->Add(new TRemoteParentDirectory());
  1317. FLastReadDirectoryProgress = 0;
  1318. assert(FFileList == NULL);
  1319. FFileList = FileList;
  1320. try
  1321. {
  1322. // always specify path to list, do not attempt to list "current" dir as:
  1323. // 1) List() lists again the last listed directory, not the current working directory
  1324. // 2) we handle this way the cached directory change
  1325. AnsiString Directory = AbsolutePath(FileList->Directory);
  1326. FFileZillaIntf->List(Directory.c_str());
  1327. GotReply(WaitForReply(), REPLY_2XX_CODE | REPLY_ALLOW_CANCEL);
  1328. }
  1329. __finally
  1330. {
  1331. FFileList = NULL;
  1332. }
  1333. }
  1334. //---------------------------------------------------------------------------
  1335. void __fastcall TFTPFileSystem::ReadFile(const AnsiString FileName,
  1336. TRemoteFile *& File)
  1337. {
  1338. AnsiString Path = UnixExtractFilePath(FileName);
  1339. AnsiString NameOnly = UnixExtractFileName(FileName);
  1340. // FZAPI does not have efficient way to read properties of one file.
  1341. // If case we need properties of set of files from the same directory,
  1342. // cache the file list for future
  1343. if ((FFileListCache == NULL) ||
  1344. !UnixComparePaths(Path, FFileListCache->Directory))
  1345. {
  1346. delete FFileListCache;
  1347. FFileListCache = NULL;
  1348. FFileListCache = new TRemoteFileList();
  1349. FFileListCache->Directory = Path;
  1350. ReadDirectory(FFileListCache);
  1351. }
  1352. TRemoteFile * AFile = FFileListCache->FindFile(NameOnly);
  1353. if (AFile != NULL)
  1354. {
  1355. File = AFile->Duplicate();
  1356. }
  1357. else
  1358. {
  1359. File = NULL;
  1360. }
  1361. }
  1362. //---------------------------------------------------------------------------
  1363. void __fastcall TFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  1364. TRemoteFile *& File)
  1365. {
  1366. // Resolving symlinks over FTP is big overhead
  1367. // (involves opening TCPIP connection for retrieving "directory listing").
  1368. // Moreover FZAPI does not support that anyway.
  1369. File = new TRemoteFile(SymlinkFile);
  1370. try
  1371. {
  1372. File->Terminal = FTerminal;
  1373. File->FileName = UnixExtractFileName(SymlinkFile->LinkTo);
  1374. // FZAPI treats all symlink target as directories
  1375. File->Type = FILETYPE_DIRECTORY;
  1376. }
  1377. catch(...)
  1378. {
  1379. delete File;
  1380. File = NULL;
  1381. throw;
  1382. }
  1383. }
  1384. //---------------------------------------------------------------------------
  1385. void __fastcall TFTPFileSystem::RenameFile(const AnsiString AFileName,
  1386. const AnsiString ANewName)
  1387. {
  1388. AnsiString FileName = AbsolutePath(AFileName);
  1389. AnsiString NewName = AbsolutePath(ANewName);
  1390. AnsiString FileNameOnly = UnixExtractFileName(FileName);
  1391. AnsiString FilePathOnly = UnixExtractFilePath(FileName);
  1392. AnsiString NewNameOnly = UnixExtractFileName(NewName);
  1393. AnsiString NewPathOnly = UnixExtractFilePath(NewName);
  1394. FIgnoreFileList = true;
  1395. try
  1396. {
  1397. FFileZillaIntf->Rename(FileNameOnly.c_str(), NewNameOnly.c_str(),
  1398. FilePathOnly.c_str(), NewPathOnly.c_str());
  1399. GotReply(WaitForReply(), REPLY_2XX_CODE);
  1400. }
  1401. __finally
  1402. {
  1403. FIgnoreFileList = false;
  1404. }
  1405. }
  1406. //---------------------------------------------------------------------------
  1407. void __fastcall TFTPFileSystem::CopyFile(const AnsiString FileName,
  1408. const AnsiString NewName)
  1409. {
  1410. assert(false);
  1411. }
  1412. //---------------------------------------------------------------------------
  1413. AnsiString __fastcall TFTPFileSystem::FileUrl(const AnsiString FileName)
  1414. {
  1415. return FTerminal->FileUrl("ftp", FileName);
  1416. }
  1417. //---------------------------------------------------------------------------
  1418. TStrings * __fastcall TFTPFileSystem::GetFixedPaths()
  1419. {
  1420. return NULL;
  1421. }
  1422. //---------------------------------------------------------------------------
  1423. void __fastcall TFTPFileSystem::SpaceAvailable(const AnsiString /*Path*/,
  1424. TSpaceAvailable & /*ASpaceAvailable*/)
  1425. {
  1426. assert(false);
  1427. }
  1428. //---------------------------------------------------------------------------
  1429. const TSessionInfo & __fastcall TFTPFileSystem::GetSessionInfo()
  1430. {
  1431. return FSessionInfo;
  1432. }
  1433. //---------------------------------------------------------------------------
  1434. const TFileSystemInfo & __fastcall TFTPFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  1435. {
  1436. if (!FFileSystemInfoValid)
  1437. {
  1438. FFileSystemInfo.RemoteSystem = FSystem;
  1439. FFileSystemInfo.RemoteSystem.Unique();
  1440. if (FFeatures->Count == 0)
  1441. {
  1442. FFileSystemInfo.AdditionalInfo = LoadStr(FTP_NO_FEATURE_INFO);
  1443. }
  1444. else
  1445. {
  1446. FFileSystemInfo.AdditionalInfo =
  1447. FORMAT("%s\r\n", (LoadStr(FTP_FEATURE_INFO)));
  1448. for (int Index = 0; Index < FFeatures->Count; Index++)
  1449. {
  1450. FFileSystemInfo.AdditionalInfo += FORMAT(" %s\r\n", (FFeatures->Strings[Index]));
  1451. }
  1452. }
  1453. FFileSystemInfoValid = true;
  1454. }
  1455. return FFileSystemInfo;
  1456. }
  1457. //---------------------------------------------------------------------------
  1458. bool __fastcall TFTPFileSystem::TemporaryTransferFile(const AnsiString & /*FileName*/)
  1459. {
  1460. return false;
  1461. }
  1462. //---------------------------------------------------------------------------
  1463. bool __fastcall TFTPFileSystem::GetStoredCredentialsTried()
  1464. {
  1465. return !FTerminal->SessionData->Password.IsEmpty();
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. AnsiString __fastcall TFTPFileSystem::GetUserName()
  1469. {
  1470. return FUserName;
  1471. }
  1472. //---------------------------------------------------------------------------
  1473. AnsiString __fastcall TFTPFileSystem::GetCurrentDirectory()
  1474. {
  1475. return FCurrentDirectory;
  1476. }
  1477. //---------------------------------------------------------------------------
  1478. const char * __fastcall TFTPFileSystem::GetOption(int OptionID) const
  1479. {
  1480. TSessionData * Data = FTerminal->SessionData;
  1481. switch (OptionID)
  1482. {
  1483. case OPTION_PROXYHOST:
  1484. FOptionScratch = Data->ProxyHost;
  1485. break;
  1486. case OPTION_PROXYUSER:
  1487. FOptionScratch = Data->ProxyUsername;
  1488. break;
  1489. case OPTION_PROXYPASS:
  1490. FOptionScratch = Data->ProxyPassword;
  1491. break;
  1492. case OPTION_ANONPWD:
  1493. case OPTION_TRANSFERIP:
  1494. case OPTION_TRANSFERIP6:
  1495. FOptionScratch = "";
  1496. break;
  1497. case OPTION_FWHOST:
  1498. case OPTION_FWUSER:
  1499. case OPTION_FWPASS:
  1500. // should never get here OPTION_LOGONTYPE being 0
  1501. assert(false);
  1502. FOptionScratch = "";
  1503. break;
  1504. default:
  1505. assert(false);
  1506. FOptionScratch = "";
  1507. }
  1508. return FOptionScratch.c_str();
  1509. }
  1510. //---------------------------------------------------------------------------
  1511. int __fastcall TFTPFileSystem::GetOptionVal(int OptionID) const
  1512. {
  1513. TSessionData * Data = FTerminal->SessionData;
  1514. int Result;
  1515. switch (OptionID)
  1516. {
  1517. case OPTION_PROXYTYPE:
  1518. switch (Data->ProxyMethod)
  1519. {
  1520. case pmNone:
  1521. Result = 0; // PROXYTYPE_NOPROXY;
  1522. break;
  1523. case pmSocks4:
  1524. Result = 2; // PROXYTYPE_SOCKS4A
  1525. break;
  1526. case pmSocks5:
  1527. Result = 3; // PROXYTYPE_SOCKS5
  1528. break;
  1529. case pmHTTP:
  1530. Result = 4; // PROXYTYPE_HTTP11
  1531. break;
  1532. case pmTelnet:
  1533. default:
  1534. assert(false);
  1535. Result = 0; // PROXYTYPE_NOPROXY;
  1536. break;
  1537. }
  1538. break;
  1539. case OPTION_PROXYPORT:
  1540. Result = Data->ProxyPort;
  1541. break;
  1542. case OPTION_PROXYUSELOGON:
  1543. Result = !Data->ProxyUsername.IsEmpty();
  1544. break;
  1545. case OPTION_LOGONTYPE:
  1546. Result = 0; // no FTP proxy
  1547. break;
  1548. case OPTION_FWPORT:
  1549. // should never get here OPTION_LOGONTYPE being 0
  1550. assert(false);
  1551. Result = 0;
  1552. break;
  1553. case OPTION_TIMEOUTLENGTH:
  1554. Result = Data->Timeout;
  1555. break;
  1556. case OPTION_DEBUGSHOWLISTING:
  1557. // Listing is logged on FZAPI level 5 (what is strangely LOG_APIERROR)
  1558. Result = (FTerminal->Configuration->LogProtocol >= 1);
  1559. break;
  1560. case OPTION_PASV:
  1561. // should never get here t_server.nPasv being nonzero
  1562. assert(false);
  1563. Result = FALSE;
  1564. break;
  1565. case OPTION_PRESERVEDOWNLOADFILETIME:
  1566. Result = FFileTransferPreserveTime ? TRUE : FALSE;
  1567. break;
  1568. case OPTION_LIMITPORTRANGE:
  1569. Result = FALSE;
  1570. break;
  1571. case OPTION_PORTRANGELOW:
  1572. case OPTION_PORTRANGEHIGH:
  1573. // should never get here OPTION_LIMITPORTRANGE being zero
  1574. assert(false);
  1575. Result = 0;
  1576. break;
  1577. case OPTION_ENABLE_IPV6:
  1578. Result = ((Data->AddressFamily == afIPv6) ? TRUE : FALSE);
  1579. break;
  1580. case OPTION_KEEPALIVE:
  1581. Result = ((Data->FtpPingType != ptOff) ? TRUE : FALSE);
  1582. break;
  1583. case OPTION_INTERVALLOW:
  1584. case OPTION_INTERVALHIGH:
  1585. Result = Data->FtpPingInterval;
  1586. break;
  1587. case OPTION_VMSALLREVISIONS:
  1588. Result = FALSE;
  1589. break;
  1590. default:
  1591. assert(false);
  1592. Result = FALSE;
  1593. break;
  1594. }
  1595. return Result;
  1596. }
  1597. //---------------------------------------------------------------------------
  1598. bool __fastcall TFTPFileSystem::PostMessage(WPARAM wParam, LPARAM lParam)
  1599. {
  1600. TGuard Guard(FQueueCriticalSection);
  1601. FQueue->push_back(TMessageQueue::value_type(wParam, lParam));
  1602. SetEvent(FQueueEvent);
  1603. return true;
  1604. }
  1605. //---------------------------------------------------------------------------
  1606. bool __fastcall TFTPFileSystem::ProcessMessage()
  1607. {
  1608. bool Result;
  1609. TMessageQueue::value_type Message;
  1610. {
  1611. TGuard Guard(FQueueCriticalSection);
  1612. Result = !FQueue->empty();
  1613. if (Result)
  1614. {
  1615. Message = FQueue->front();
  1616. FQueue->pop_front();
  1617. }
  1618. else
  1619. {
  1620. // now we are perfecly sure that the queue is empty as it is locked,
  1621. // so reset the event
  1622. ResetEvent(FQueueEvent);
  1623. }
  1624. }
  1625. if (Result)
  1626. {
  1627. FFileZillaIntf->HandleMessage(Message.first, Message.second);
  1628. }
  1629. return Result;
  1630. }
  1631. //---------------------------------------------------------------------------
  1632. void __fastcall TFTPFileSystem::DiscardMessages()
  1633. {
  1634. while (ProcessMessage());
  1635. }
  1636. //---------------------------------------------------------------------------
  1637. void __fastcall TFTPFileSystem::WaitForMessages()
  1638. {
  1639. unsigned int Result = WaitForSingleObject(FQueueEvent, INFINITE);
  1640. if (Result != WAIT_OBJECT_0)
  1641. {
  1642. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, ("ftp#1", IntToStr(Result))));
  1643. }
  1644. }
  1645. //---------------------------------------------------------------------------
  1646. unsigned int __fastcall TFTPFileSystem::PoolForReply()
  1647. {
  1648. assert(FReply == 0);
  1649. assert(FCommandReply == 0);
  1650. assert(!FWaitingForReply);
  1651. FWaitingForReply = true;
  1652. unsigned int Reply;
  1653. try
  1654. {
  1655. // discard up to one reply
  1656. // (it should not happen here that two replies are posted anyway)
  1657. while (ProcessMessage() && (FReply == 0));
  1658. Reply = FReply;
  1659. }
  1660. __finally
  1661. {
  1662. FReply = 0;
  1663. assert(FCommandReply == 0);
  1664. FCommandReply = 0;
  1665. assert(FWaitingForReply);
  1666. FWaitingForReply = false;
  1667. }
  1668. return Reply;
  1669. }
  1670. //---------------------------------------------------------------------------
  1671. unsigned int __fastcall TFTPFileSystem::WaitForReply(bool Command)
  1672. {
  1673. assert(FReply == 0);
  1674. assert(FCommandReply == 0);
  1675. assert(!FWaitingForReply);
  1676. ResetReply();
  1677. FWaitingForReply = true;
  1678. unsigned int Reply;
  1679. try
  1680. {
  1681. unsigned int& ReplyToAwait = (Command ? FCommandReply : FReply);
  1682. while (ReplyToAwait == 0)
  1683. {
  1684. WaitForMessages();
  1685. // wait for the first reply only,
  1686. // i.e. in case two replies are posted get the first only.
  1687. // e.g. when server closes the connection, but posts error message before,
  1688. // sometime it happens that command (like download) fails because of the error
  1689. // and does not catch the disconnection. then asynchronous "disconnect reply"
  1690. // is posted immediately afterwards. leave detection of that to Idle()
  1691. while (ProcessMessage() && (ReplyToAwait == 0));
  1692. }
  1693. Reply = ReplyToAwait;
  1694. }
  1695. __finally
  1696. {
  1697. FReply = 0;
  1698. FCommandReply = 0;
  1699. assert(FWaitingForReply);
  1700. FWaitingForReply = false;
  1701. }
  1702. return Reply;
  1703. }
  1704. //---------------------------------------------------------------------------
  1705. void __fastcall TFTPFileSystem::ResetReply()
  1706. {
  1707. FLastCode = 0;
  1708. FLastCodeClass = 0;
  1709. assert(FLastResponse != NULL);
  1710. FLastResponse->Clear();
  1711. assert(FLastError != NULL);
  1712. FLastError->Clear();
  1713. }
  1714. //---------------------------------------------------------------------------
  1715. void __fastcall TFTPFileSystem::GotReply(unsigned int Reply, unsigned int Flags,
  1716. AnsiString Error, unsigned int * Code, TStrings ** Response)
  1717. {
  1718. try
  1719. {
  1720. if (FLAGSET(Reply, TFileZillaIntf::REPLY_OK))
  1721. {
  1722. assert(Reply == TFileZillaIntf::REPLY_OK);
  1723. // With REPLY_2XX_CODE treat "OK" non-2xx code like an error
  1724. if (FLAGSET(Flags, REPLY_2XX_CODE) && (FLastCodeClass != 2))
  1725. {
  1726. GotReply(TFileZillaIntf::REPLY_ERROR, Flags, Error);
  1727. }
  1728. }
  1729. else if (FLAGSET(Reply, TFileZillaIntf::REPLY_CANCEL) &&
  1730. FLAGSET(Flags, REPLY_ALLOW_CANCEL))
  1731. {
  1732. assert(
  1733. (Reply == (TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)) ||
  1734. (Reply == (TFileZillaIntf::REPLY_ABORTED | TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)));
  1735. // noop
  1736. }
  1737. // we do not expect these with our usage of FZ
  1738. else if (Reply &
  1739. (TFileZillaIntf::REPLY_WOULDBLOCK | TFileZillaIntf::REPLY_OWNERNOTSET |
  1740. TFileZillaIntf::REPLY_INVALIDPARAM | TFileZillaIntf::REPLY_ALREADYCONNECTED |
  1741. TFileZillaIntf::REPLY_IDLE | TFileZillaIntf::REPLY_NOTINITIALIZED |
  1742. TFileZillaIntf::REPLY_ALREADYINIZIALIZED))
  1743. {
  1744. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, ("ftp#2", FORMAT("0x%x", (int(Reply))))));
  1745. }
  1746. else
  1747. {
  1748. // everything else must be an error or disconnect notification
  1749. assert(
  1750. FLAGSET(Reply, TFileZillaIntf::REPLY_ERROR) ||
  1751. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  1752. // TODO: REPLY_CRITICALERROR ignored
  1753. // REPLY_NOTCONNECTED happens if connection is closed between moment
  1754. // when FZAPI interface method dispatches the command to FZAPI thread
  1755. // and moment when FZAPI thread receives the command
  1756. bool Disconnected =
  1757. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED) ||
  1758. FLAGSET(Reply, TFileZillaIntf::REPLY_NOTCONNECTED);
  1759. TStrings * MoreMessages = new TStringList();
  1760. try
  1761. {
  1762. if (Disconnected)
  1763. {
  1764. // for connection failure, do not report that connection was lost, its obvious
  1765. if (FLAGCLEAR(Flags, REPLY_CONNECT))
  1766. {
  1767. MoreMessages->Add(LoadStr(LOST_CONNECTION));
  1768. }
  1769. Discard();
  1770. }
  1771. if (FLAGSET(Reply, TFileZillaIntf::REPLY_ABORTED))
  1772. {
  1773. MoreMessages->Add(LoadStr(USER_TERMINATED));
  1774. }
  1775. if (FLAGSET(Reply, TFileZillaIntf::REPLY_NOTSUPPORTED))
  1776. {
  1777. MoreMessages->Add(LoadStr(FZ_NOTSUPPORTED));
  1778. }
  1779. if (FLastCode == 530)
  1780. {
  1781. MoreMessages->Add(LoadStr(AUTHENTICATION_FAILED));
  1782. }
  1783. MoreMessages->AddStrings(FLastError);
  1784. // already cleared from WaitForReply, but GotReply can be also called
  1785. // from Closed. then make sure that error from previous command not
  1786. // associated with session closure is not reused
  1787. FLastError->Clear();
  1788. MoreMessages->AddStrings(FLastResponse);
  1789. // see comment for FLastError
  1790. FLastResponse->Clear();
  1791. if (MoreMessages->Count == 0)
  1792. {
  1793. delete MoreMessages;
  1794. MoreMessages = NULL;
  1795. }
  1796. }
  1797. catch(...)
  1798. {
  1799. delete MoreMessages;
  1800. throw;
  1801. }
  1802. if (Error.IsEmpty() && (MoreMessages != NULL))
  1803. {
  1804. assert(MoreMessages->Count > 0);
  1805. Error = MoreMessages->Strings[0];
  1806. MoreMessages->Delete(0);
  1807. }
  1808. if (Disconnected)
  1809. {
  1810. // for fatal error, it is essential that there is some message
  1811. assert(!Error.IsEmpty());
  1812. ExtException * E = new ExtException(Error, MoreMessages, true);
  1813. try
  1814. {
  1815. FTerminal->FatalError(E, "");
  1816. }
  1817. __finally
  1818. {
  1819. delete E;
  1820. }
  1821. }
  1822. else
  1823. {
  1824. throw ExtException(Error, MoreMessages, true);
  1825. }
  1826. }
  1827. if (Code != NULL)
  1828. {
  1829. *Code = FLastCode;
  1830. }
  1831. if (Response != NULL)
  1832. {
  1833. *Response = FLastResponse;
  1834. FLastResponse = new TStringList();
  1835. }
  1836. }
  1837. __finally
  1838. {
  1839. ResetReply();
  1840. }
  1841. }
  1842. //---------------------------------------------------------------------------
  1843. void __fastcall TFTPFileSystem::HandleReplyStatus(const char * AStatus)
  1844. {
  1845. int Code;
  1846. AnsiString Response(AStatus);
  1847. if (FOnCaptureOutput != NULL)
  1848. {
  1849. FOnCaptureOutput(Response, false);
  1850. }
  1851. // Two forms of multiline responses were observed
  1852. // (the first is according to the RFC 959):
  1853. // 211-Features:
  1854. // MDTM
  1855. // REST STREAM
  1856. // SIZE
  1857. // 211 End
  1858. // 211-Features:
  1859. // 211-MDTM
  1860. // 211-REST STREAM
  1861. // 211-SIZE
  1862. // 211-AUTH TLS
  1863. // 211-PBSZ
  1864. // 211-PROT
  1865. // 211 End
  1866. bool HasCodePrefix =
  1867. (Response.Length() >= 3) &&
  1868. TryStrToInt(Response.SubString(1, 3), Code) &&
  1869. (Code >= 100) && (Code <= 599) &&
  1870. ((Response.Length() == 3) || (Response[4] == ' ') || (Response[4] == '-'));
  1871. if (HasCodePrefix && !FMultineResponse)
  1872. {
  1873. FMultineResponse = (Response.Length() >= 4) && (Response[4] == '-');
  1874. FLastResponse->Clear();
  1875. if (Response.Length() >= 5)
  1876. {
  1877. FLastResponse->Add(Response.SubString(5, Response.Length() - 4));
  1878. }
  1879. FLastCode = Code;
  1880. FLastCodeClass = (Code / 100);
  1881. }
  1882. else
  1883. {
  1884. int Start;
  1885. // response with code prefix
  1886. if (HasCodePrefix && (FLastCode == Code))
  1887. {
  1888. // End of multiline response?
  1889. if ((Response.Length() <= 3) || (Response[4] == ' '))
  1890. {
  1891. FMultineResponse = false;
  1892. }
  1893. Start = 5;
  1894. }
  1895. else
  1896. {
  1897. Start = (((Response.Length() >= 1) && (Response[1] == ' ')) ? 2 : 1);
  1898. }
  1899. // Intermediate empty lines are being added
  1900. if (FMultineResponse || (Response.Length() >= Start))
  1901. {
  1902. FLastResponse->Add(Response.SubString(Start, Response.Length() - Start + 1));
  1903. }
  1904. }
  1905. if (!FMultineResponse)
  1906. {
  1907. if (FLastCode == 220)
  1908. {
  1909. if (FTerminal->Configuration->ShowFtpWelcomeMessage)
  1910. {
  1911. FTerminal->DisplayBanner(FLastResponse->Text);
  1912. }
  1913. }
  1914. else if (FLastCommand == PASS)
  1915. {
  1916. // 530 = "Not logged in."
  1917. if (FLastCode == 530)
  1918. {
  1919. FPasswordFailed = true;
  1920. };
  1921. }
  1922. else if (FLastCommand == SYST)
  1923. {
  1924. assert(FSystem.IsEmpty());
  1925. // Possitive reply to "SYST" must be 215, see RFC 959
  1926. if (FLastCode == 215)
  1927. {
  1928. FSystem = FLastResponse->Text.TrimRight();
  1929. }
  1930. else
  1931. {
  1932. FSystem = "";
  1933. }
  1934. }
  1935. else if (FLastCommand == FEAT)
  1936. {
  1937. // Response to FEAT must be multiline, where leading and trailing line
  1938. // is "meaningless". See RFC 2389.
  1939. if ((FLastCode == 211) && (FLastResponse->Count > 2))
  1940. {
  1941. FLastResponse->Delete(0);
  1942. FLastResponse->Delete(FLastResponse->Count - 1);
  1943. FFeatures->Assign(FLastResponse);
  1944. }
  1945. else
  1946. {
  1947. FFeatures->Clear();
  1948. }
  1949. }
  1950. }
  1951. }
  1952. //---------------------------------------------------------------------------
  1953. bool __fastcall TFTPFileSystem::HandleStatus(const char * Status, int Type)
  1954. {
  1955. assert(
  1956. (Type <= TFileZillaIntf::LOG_LIST) ||
  1957. ((Type <= TFileZillaIntf::LOG_WARNING) && (FTerminal->Configuration->LogProtocol >= 1)) ||
  1958. (FTerminal->Configuration->LogProtocol >= 2));
  1959. TLogLineType LogType;
  1960. switch (Type)
  1961. {
  1962. case TFileZillaIntf::LOG_STATUS:
  1963. FTerminal->Information(Status, true);
  1964. LogType = llMessage;
  1965. break;
  1966. case TFileZillaIntf::LOG_COMMAND:
  1967. if (strcmp(Status, "SYST") == 0)
  1968. {
  1969. FLastCommand = SYST;
  1970. }
  1971. else if (strcmp(Status, "FEAT") == 0)
  1972. {
  1973. FLastCommand = FEAT;
  1974. }
  1975. else if (strncmp(Status, "PASS ", 5) == 0)
  1976. {
  1977. FLastCommand = PASS;
  1978. }
  1979. else
  1980. {
  1981. FLastCommand = CMD_UNKNOWN;
  1982. }
  1983. LogType = llInput;
  1984. break;
  1985. case TFileZillaIntf::LOG_ERROR:
  1986. // there can be multiple error messages associated with single failure
  1987. // (such as "cannot open local file..." followed by "download failed"
  1988. FLastError->Add(Status);
  1989. LogType = llMessage;
  1990. break;
  1991. case TFileZillaIntf::LOG_REPLY:
  1992. HandleReplyStatus(Status);
  1993. LogType = llOutput;
  1994. break;
  1995. default:
  1996. LogType = llMessage;
  1997. break;
  1998. }
  1999. if (FTerminal->Log->Logging)
  2000. {
  2001. FTerminal->Log->Add(LogType, Status);
  2002. }
  2003. return true;
  2004. }
  2005. //---------------------------------------------------------------------------
  2006. bool __fastcall TFTPFileSystem::HandleAsynchRequestOverwrite(
  2007. char * FileName1, size_t FileName1Len, const char * /*FileName2*/,
  2008. const char * /*Path1*/, const char * /*Path2*/,
  2009. __int64 Size1, __int64 Size2, time_t Time1, time_t Time2,
  2010. bool HasTime1, bool HasTime2, void * AUserData, int & RequestResult)
  2011. {
  2012. if (!FActive)
  2013. {
  2014. return false;
  2015. }
  2016. else
  2017. {
  2018. TFileTransferData & UserData = *((TFileTransferData *)AUserData);
  2019. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  2020. AnsiString FileName = FileName1;
  2021. assert(FFileTransferFileName == FileName);
  2022. TOverwriteMode OverwriteMode = omOverwrite;
  2023. TOverwriteFileParams FileParams;
  2024. FileParams.SourceSize = Size2;
  2025. FileParams.DestSize = Size1;
  2026. // !!! TODO DST
  2027. FileParams.SourceTimestamp = UnixToDateTime(Time2, dstmUnix);
  2028. FileParams.DestTimestamp = UnixToDateTime(Time1, dstmUnix);
  2029. if ((OperationProgress->Side == osLocal) && !HasTime1)
  2030. {
  2031. FileParams.DestPrecision = mfMDY;
  2032. }
  2033. if ((OperationProgress->Side == osRemote) && !HasTime2)
  2034. {
  2035. FileParams.SourcePrecision = mfMDY;
  2036. }
  2037. if (ConfirmOverwrite(FileName, OverwriteMode, OperationProgress,
  2038. &FileParams, UserData.Params, UserData.AutoResume))
  2039. {
  2040. switch (OverwriteMode)
  2041. {
  2042. case omOverwrite:
  2043. if (FileName != FileName1)
  2044. {
  2045. strncpy(FileName1, FileName.c_str(), FileName1Len);
  2046. FileName1[FileName1Len - 1] = '\0';
  2047. FFileTransferFileName = FileName1;
  2048. RequestResult = TFileZillaIntf::FILEEXISTS_RENAME;
  2049. }
  2050. else
  2051. {
  2052. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  2053. }
  2054. break;
  2055. case omResume:
  2056. RequestResult = TFileZillaIntf::FILEEXISTS_RESUME;
  2057. break;
  2058. default:
  2059. assert(false);
  2060. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  2061. break;
  2062. }
  2063. }
  2064. else
  2065. {
  2066. RequestResult = TFileZillaIntf::FILEEXISTS_SKIP;
  2067. }
  2068. return true;
  2069. }
  2070. }
  2071. //---------------------------------------------------------------------------
  2072. bool __fastcall TFTPFileSystem::HandleListData(const char * Path,
  2073. const TListDataEntry * Entries, unsigned int Count)
  2074. {
  2075. if (!FActive)
  2076. {
  2077. return false;
  2078. }
  2079. else if (FIgnoreFileList)
  2080. {
  2081. // directory listing provided implicitly by FZAPI during certain operations is ignored
  2082. assert(FFileList == NULL);
  2083. return false;
  2084. }
  2085. else
  2086. {
  2087. assert(FFileList != NULL);
  2088. assert(UnixComparePaths(AbsolutePath(FFileList->Directory), Path));
  2089. USEDPARAM(Path);
  2090. for (unsigned int Index = 0; Index < Count; Index++)
  2091. {
  2092. const TListDataEntry * Entry = &Entries[Index];
  2093. TRemoteFile * File = new TRemoteFile();
  2094. try
  2095. {
  2096. File->Terminal = FTerminal;
  2097. File->FileName = Entry->Name;
  2098. if (strlen(Entry->Permissions) >= 10)
  2099. {
  2100. File->Rights->Text = Entry->Permissions + 1;
  2101. }
  2102. const char * Space = strchr(Entry->OwnerGroup, ' ');
  2103. if (Space != NULL)
  2104. {
  2105. File->Owner = AnsiString(Entry->OwnerGroup, Space - Entry->OwnerGroup);
  2106. File->Group = Space + 1;
  2107. }
  2108. else
  2109. {
  2110. File->Owner = Entry->OwnerGroup;
  2111. }
  2112. File->Size = Entry->Size;
  2113. if (Entry->Link)
  2114. {
  2115. File->Type = FILETYPE_SYMLINK;
  2116. }
  2117. else if (Entry->Dir)
  2118. {
  2119. File->Type = FILETYPE_DIRECTORY;
  2120. }
  2121. else
  2122. {
  2123. File->Type = '-';
  2124. }
  2125. // ModificationFmt must be set after Modification
  2126. if (Entry->HasDate)
  2127. {
  2128. TDateTime Modification =
  2129. EncodeDate((unsigned short)Entry->Year, (unsigned short)Entry->Month,
  2130. (unsigned short)Entry->Day);
  2131. if (Entry->HasTime)
  2132. {
  2133. File->Modification = Modification +
  2134. EncodeTime((unsigned short)Entry->Hour, (unsigned short)Entry->Minute, 0, 0);
  2135. // not exact as we got year as well, but it is most probably
  2136. // guessed by FZAPI anyway
  2137. File->ModificationFmt = mfMDHM;
  2138. }
  2139. else
  2140. {
  2141. File->Modification = Modification;
  2142. File->ModificationFmt = mfMDY;
  2143. }
  2144. }
  2145. else
  2146. {
  2147. // With SCP we estimate date to be today, if we have at least time
  2148. File->Modification = double(0);
  2149. File->ModificationFmt = mfNone;
  2150. }
  2151. File->LastAccess = File->Modification;
  2152. File->LinkTo = Entry->LinkTarget;
  2153. File->Complete();
  2154. }
  2155. catch (Exception & E)
  2156. {
  2157. delete File;
  2158. throw ETerminal(&E, FMTLOAD(LIST_LINE_ERROR, (
  2159. FORMAT("%s/%s/%s/%s/%d/%d/%d/%d/%d/%d/%d/%d/%d",
  2160. (Entry->Name, Entry->Permissions, Entry->OwnerGroup, IntToStr(Entry->Size),
  2161. Entry->Dir, Entry->Link, Entry->Year, Entry->Month, Entry->Day,
  2162. Entry->Hour, Entry->Minute, Entry->HasTime, Entry->HasDate)))));
  2163. }
  2164. FFileList->AddFile(File);
  2165. }
  2166. return true;
  2167. }
  2168. }
  2169. //---------------------------------------------------------------------------
  2170. bool __fastcall TFTPFileSystem::HandleTransferStatus(bool Valid, __int64 TransferSize,
  2171. __int64 Bytes, int Percent, int /*TimeElapsed*/, int /*TimeLeft*/, int /*TransferRate*/,
  2172. bool FileTransfer)
  2173. {
  2174. if (!FActive)
  2175. {
  2176. return false;
  2177. }
  2178. else if (!Valid)
  2179. {
  2180. }
  2181. else if (FileTransfer)
  2182. {
  2183. FileTransferProgress(TransferSize, Bytes, Percent);
  2184. }
  2185. else
  2186. {
  2187. assert(Percent == -1);
  2188. ReadDirectoryProgress(Bytes);
  2189. }
  2190. return true;
  2191. }
  2192. //---------------------------------------------------------------------------
  2193. bool __fastcall TFTPFileSystem::HandleReply(int Command, unsigned int Reply)
  2194. {
  2195. if (!FActive)
  2196. {
  2197. return false;
  2198. }
  2199. else
  2200. {
  2201. if (FTerminal->Configuration->LogProtocol >= 1)
  2202. {
  2203. FTerminal->LogEvent(FORMAT("Got reply %x to the command %d", (int(Reply), Command)));
  2204. }
  2205. // reply with Command 0 is not associated with current operation
  2206. // so do not treat is as a reply
  2207. // (it is typically used asynchronously to notify about disconnects,
  2208. // this is handled in TFileZillaIntf::PostMessage already)
  2209. if (Command != 0)
  2210. {
  2211. assert(FCommandReply == 0);
  2212. FCommandReply = Reply;
  2213. }
  2214. else
  2215. {
  2216. assert(FReply == 0);
  2217. FReply = Reply;
  2218. }
  2219. return true;
  2220. }
  2221. }
  2222. //---------------------------------------------------------------------------
  2223. bool __fastcall TFTPFileSystem::CheckError(int ReturnCode, const char * Context)
  2224. {
  2225. // we do not expect any FZAPI call to fail as it generally can fail only due to:
  2226. // - invalid paramerers
  2227. // - busy FZAPI core
  2228. // the only exception is REPLY_NOTCONNECTED that can happen if
  2229. // connection is closed just between the last call to Idle()
  2230. // and call to any FZAPI command
  2231. // in such case reply without associated command is posted,
  2232. // which we are going to wait for unless we are already waiting
  2233. // on higher level (this typically happens if connection is lost while
  2234. // waiting for user interaction and is detected with call to
  2235. // SetAsyncRequestResult)
  2236. if (FLAGSET(ReturnCode, TFileZillaIntf::REPLY_NOTCONNECTED))
  2237. {
  2238. if (!FWaitingForReply)
  2239. {
  2240. unsigned int Reply = WaitForReply(false);
  2241. assert(FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2242. GotReply(Reply);
  2243. // should never get here as GotReply should raise fatal exception
  2244. assert(false);
  2245. }
  2246. }
  2247. else
  2248. {
  2249. FTerminal->FatalError(NULL,
  2250. FMTLOAD(INTERNAL_ERROR, (FORMAT("fz#%s", (Context)), IntToHex(ReturnCode, 4))));
  2251. assert(false);
  2252. }
  2253. return false;
  2254. }
  2255. //---------------------------------------------------------------------------
  2256. bool __fastcall TFTPFileSystem::Unquote(AnsiString & Str)
  2257. {
  2258. enum
  2259. {
  2260. INIT,
  2261. QUOTE,
  2262. QUOTED,
  2263. DONE
  2264. } State;
  2265. State = INIT;
  2266. assert((Str.Length() > 0) && (Str[1] == '"'));
  2267. int Index = 1;
  2268. while (Index <= Str.Length())
  2269. {
  2270. switch (State)
  2271. {
  2272. case INIT:
  2273. switch (Str[Index])
  2274. {
  2275. case '"':
  2276. State = QUOTED;
  2277. Str.Delete(Index, 1);
  2278. break;
  2279. default:
  2280. assert(false);
  2281. // no quoted string
  2282. Str.SetLength(0);
  2283. break;
  2284. }
  2285. break;
  2286. case QUOTED:
  2287. switch (Str[Index])
  2288. {
  2289. case '"':
  2290. State = QUOTE;
  2291. Str.Delete(Index, 1);
  2292. break;
  2293. default:
  2294. Index++;
  2295. break;
  2296. }
  2297. break;
  2298. case QUOTE:
  2299. switch (Str[Index])
  2300. {
  2301. case '"':
  2302. Index++;
  2303. break;
  2304. default:
  2305. // end of quoted string, trim the rest
  2306. Str.SetLength(Index - 1);
  2307. State = DONE;
  2308. break;
  2309. }
  2310. break;
  2311. }
  2312. }
  2313. return (State == DONE);
  2314. }
  2315. //---------------------------------------------------------------------------
  2316. #endif NO_FILEZILLA