FtpFileSystem.cpp 80 KB

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