FtpFileSystem.cpp 79 KB

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