FtpFileSystem.cpp 79 KB

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