FtpFileSystem.cpp 77 KB

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