FtpFileSystem.cpp 77 KB

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