FtpFileSystem.cpp 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396
  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. #include "TextsFileZilla.h"
  14. #include "HelpCore.h"
  15. #include <openssl/x509_vfy.h>
  16. //---------------------------------------------------------------------------
  17. #pragma package(smart_init)
  18. //---------------------------------------------------------------------------
  19. #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
  20. FILE_OPERATION_LOOP_CUSTOM(FTerminal, ALLOW_SKIP, MESSAGE, OPERATION)
  21. //---------------------------------------------------------------------------
  22. const int DummyCodeClass = 8;
  23. const int DummyTimeoutCode = 801;
  24. const int DummyCancelCode = 802;
  25. const int DummyDisconnectCode = 803;
  26. //---------------------------------------------------------------------------
  27. class TFileZillaImpl : public TFileZillaIntf
  28. {
  29. public:
  30. __fastcall TFileZillaImpl(TFTPFileSystem * FileSystem);
  31. virtual const char * __fastcall Option(int OptionID) const;
  32. virtual int __fastcall OptionVal(int OptionID) const;
  33. protected:
  34. virtual bool __fastcall DoPostMessage(TMessageType Type, WPARAM wParam, LPARAM lParam);
  35. virtual bool __fastcall HandleStatus(const char * Status, int Type);
  36. virtual bool __fastcall HandleAsynchRequestOverwrite(
  37. char * FileName1, size_t FileName1Len, const char * FileName2,
  38. const char * Path1, const char * Path2,
  39. __int64 Size1, __int64 Size2, time_t Time1, time_t Time2,
  40. bool HasTime1, bool HasTime2, void * UserData, int & RequestResult);
  41. virtual bool __fastcall HandleAsynchRequestVerifyCertificate(
  42. const TFtpsCertificateData & Data, int & RequestResult);
  43. virtual bool __fastcall HandleListData(const char * Path, const TListDataEntry * Entries,
  44. unsigned int Count);
  45. virtual bool __fastcall HandleTransferStatus(bool Valid, __int64 TransferSize,
  46. __int64 Bytes, int Percent, int TimeElapsed, int TimeLeft, int TransferRate,
  47. bool FileTransfer);
  48. virtual bool __fastcall HandleReply(int Command, unsigned int Reply);
  49. virtual bool __fastcall HandleCapabilities(bool Mfmt);
  50. virtual bool __fastcall CheckError(int ReturnCode, const char * Context);
  51. private:
  52. TFTPFileSystem * FFileSystem;
  53. };
  54. //---------------------------------------------------------------------------
  55. __fastcall TFileZillaImpl::TFileZillaImpl(TFTPFileSystem * FileSystem) :
  56. TFileZillaIntf(),
  57. FFileSystem(FileSystem)
  58. {
  59. }
  60. //---------------------------------------------------------------------------
  61. const char * __fastcall TFileZillaImpl::Option(int OptionID) const
  62. {
  63. return FFileSystem->GetOption(OptionID);
  64. }
  65. //---------------------------------------------------------------------------
  66. int __fastcall TFileZillaImpl::OptionVal(int OptionID) const
  67. {
  68. return FFileSystem->GetOptionVal(OptionID);
  69. }
  70. //---------------------------------------------------------------------------
  71. bool __fastcall TFileZillaImpl::DoPostMessage(TMessageType Type, WPARAM wParam, LPARAM lParam)
  72. {
  73. return FFileSystem->PostMessage(Type, wParam, lParam);
  74. }
  75. //---------------------------------------------------------------------------
  76. bool __fastcall TFileZillaImpl::HandleStatus(const char * Status, int Type)
  77. {
  78. return FFileSystem->HandleStatus(Status, Type);
  79. }
  80. //---------------------------------------------------------------------------
  81. bool __fastcall TFileZillaImpl::HandleAsynchRequestOverwrite(
  82. char * FileName1, size_t FileName1Len, const char * FileName2,
  83. const char * Path1, const char * Path2,
  84. __int64 Size1, __int64 Size2, time_t Time1, time_t Time2,
  85. bool HasTime1, bool HasTime2, void * UserData, int & RequestResult)
  86. {
  87. return FFileSystem->HandleAsynchRequestOverwrite(
  88. FileName1, FileName1Len, FileName2, Path1, Path2, Size1, Size2, Time1, Time2,
  89. HasTime1, HasTime2, UserData, RequestResult);
  90. }
  91. //---------------------------------------------------------------------------
  92. bool __fastcall TFileZillaImpl::HandleAsynchRequestVerifyCertificate(
  93. const TFtpsCertificateData & Data, int & RequestResult)
  94. {
  95. return FFileSystem->HandleAsynchRequestVerifyCertificate(Data, RequestResult);
  96. }
  97. //---------------------------------------------------------------------------
  98. bool __fastcall TFileZillaImpl::HandleListData(const char * Path,
  99. const TListDataEntry * Entries, unsigned int Count)
  100. {
  101. return FFileSystem->HandleListData(Path, Entries, Count);
  102. }
  103. //---------------------------------------------------------------------------
  104. bool __fastcall TFileZillaImpl::HandleTransferStatus(bool Valid, __int64 TransferSize,
  105. __int64 Bytes, int Percent, int TimeElapsed, int TimeLeft, int TransferRate,
  106. bool FileTransfer)
  107. {
  108. return FFileSystem->HandleTransferStatus(Valid, TransferSize, Bytes, Percent,
  109. TimeElapsed, TimeLeft, TransferRate, FileTransfer);
  110. }
  111. //---------------------------------------------------------------------------
  112. bool __fastcall TFileZillaImpl::HandleReply(int Command, unsigned int Reply)
  113. {
  114. return FFileSystem->HandleReply(Command, Reply);
  115. }
  116. //---------------------------------------------------------------------------
  117. bool __fastcall TFileZillaImpl::HandleCapabilities(bool Mfmt)
  118. {
  119. return FFileSystem->HandleCapabilities(Mfmt);
  120. }
  121. //---------------------------------------------------------------------------
  122. bool __fastcall TFileZillaImpl::CheckError(int ReturnCode, const char * Context)
  123. {
  124. return FFileSystem->CheckError(ReturnCode, Context);
  125. }
  126. //---------------------------------------------------------------------------
  127. //---------------------------------------------------------------------------
  128. class TMessageQueue : public std::list<std::pair<WPARAM, LPARAM> >
  129. {
  130. };
  131. //---------------------------------------------------------------------------
  132. //---------------------------------------------------------------------------
  133. struct TFileTransferData
  134. {
  135. TFileTransferData()
  136. {
  137. Params = 0;
  138. AutoResume = false;
  139. OverwriteResult = -1;
  140. CopyParam = NULL;
  141. }
  142. AnsiString FileName;
  143. int Params;
  144. bool AutoResume;
  145. int OverwriteResult;
  146. const TCopyParamType * CopyParam;
  147. };
  148. //---------------------------------------------------------------------------
  149. const int tfFirstLevel = 0x01;
  150. const int tfAutoResume = 0x02;
  151. const char CertificateStorageKey[] = "FtpsCertificates";
  152. //---------------------------------------------------------------------------
  153. struct TSinkFileParams
  154. {
  155. AnsiString TargetDir;
  156. const TCopyParamType * CopyParam;
  157. int Params;
  158. TFileOperationProgressType * OperationProgress;
  159. bool Skipped;
  160. unsigned int Flags;
  161. };
  162. //---------------------------------------------------------------------------
  163. class TFileListHelper
  164. {
  165. public:
  166. TFileListHelper(TFTPFileSystem * FileSystem, TRemoteFileList * FileList,
  167. bool IgnoreFileList) :
  168. FFileSystem(FileSystem),
  169. FFileList(FFileSystem->FFileList),
  170. FIgnoreFileList(FFileSystem->FIgnoreFileList)
  171. {
  172. FFileSystem->FFileList = FileList;
  173. FFileSystem->FIgnoreFileList = IgnoreFileList;
  174. }
  175. ~TFileListHelper()
  176. {
  177. FFileSystem->FFileList = FFileList;
  178. FFileSystem->FIgnoreFileList = FIgnoreFileList;
  179. }
  180. private:
  181. TFTPFileSystem * FFileSystem;
  182. TRemoteFileList * FFileList;
  183. bool FIgnoreFileList;
  184. };
  185. //---------------------------------------------------------------------------
  186. __fastcall TFTPFileSystem::TFTPFileSystem(TTerminal * ATerminal):
  187. TCustomFileSystem(ATerminal),
  188. FFileZillaIntf(NULL),
  189. FQueueCriticalSection(new TCriticalSection),
  190. FTransferStatusCriticalSection(new TCriticalSection),
  191. FQueueEvent(CreateEvent(NULL, true, false, NULL)),
  192. FQueue(new TMessageQueue),
  193. FReply(0),
  194. FCommandReply(0),
  195. FLastCommand(CMD_UNKNOWN),
  196. FLastResponse(new TStringList()),
  197. FLastError(new TStringList()),
  198. FFeatures(new TStringList()),
  199. FFileList(NULL),
  200. FFileListCache(NULL),
  201. FActive(false),
  202. FWaitingForReply(false),
  203. FIgnoreFileList(false),
  204. FOnCaptureOutput(NULL),
  205. FFileSystemInfoValid(false),
  206. FDoListAll(false),
  207. FMfmt(false)
  208. {
  209. ResetReply();
  210. FListAll = FTerminal->SessionData->FtpListAll;
  211. FFileSystemInfo.ProtocolBaseName = "FTP";
  212. FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
  213. FTimeoutStatus = LoadStr(IDS_ERRORMSG_TIMEOUT);
  214. FDisconnectStatus = LoadStr(IDS_STATUSMSG_DISCONNECTED);
  215. }
  216. //---------------------------------------------------------------------------
  217. __fastcall TFTPFileSystem::~TFTPFileSystem()
  218. {
  219. assert(FFileList == NULL);
  220. FFileZillaIntf->Destroying();
  221. // to release memory associated with the messages
  222. DiscardMessages();
  223. delete FFileZillaIntf;
  224. FFileZillaIntf = NULL;
  225. delete FQueue;
  226. FQueue = NULL;
  227. CloseHandle(FQueueEvent);
  228. delete FQueueCriticalSection;
  229. FQueueCriticalSection = NULL;
  230. delete FTransferStatusCriticalSection;
  231. FTransferStatusCriticalSection = NULL;
  232. delete FLastResponse;
  233. FLastResponse = NULL;
  234. delete FLastError;
  235. FLastError = NULL;
  236. delete FFeatures;
  237. FFeatures = NULL;
  238. ResetCaches();
  239. }
  240. //---------------------------------------------------------------------------
  241. void __fastcall TFTPFileSystem::Open()
  242. {
  243. // on reconnect, typically there may be pending status messages from previous session
  244. DiscardMessages();
  245. TSessionData * Data = FTerminal->SessionData;
  246. FSessionInfo.LoginTime = Now();
  247. FSessionInfo.ProtocolBaseName = "FTP";
  248. FSessionInfo.ProtocolName = FSessionInfo.ProtocolBaseName;
  249. switch (Data->Ftps)
  250. {
  251. case ftpsImplicit:
  252. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_IMPLICIT);
  253. break;
  254. case ftpsExplicitSsl:
  255. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_EXPLICIT_SSL);
  256. break;
  257. case ftpsExplicitTls:
  258. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_EXPLICIT_TLS);
  259. break;
  260. }
  261. FLastDataSent = Now();
  262. FMultineResponse = false;
  263. // initialize FZAPI on the first connect only
  264. if (FFileZillaIntf == NULL)
  265. {
  266. FFileZillaIntf = new TFileZillaImpl(this);
  267. try
  268. {
  269. TFileZillaIntf::TLogLevel LogLevel;
  270. switch (FTerminal->Configuration->ActualLogProtocol)
  271. {
  272. default:
  273. case 0:
  274. case 1:
  275. LogLevel = TFileZillaIntf::LOG_WARNING;
  276. break;
  277. case 2:
  278. LogLevel = TFileZillaIntf::LOG_INFO;
  279. break;
  280. }
  281. FFileZillaIntf->SetDebugLevel(LogLevel);
  282. FFileZillaIntf->Init();
  283. }
  284. catch(...)
  285. {
  286. delete FFileZillaIntf;
  287. FFileZillaIntf = NULL;
  288. throw;
  289. }
  290. }
  291. AnsiString HostName = Data->HostName;
  292. AnsiString UserName = Data->UserName;
  293. AnsiString Password = Data->Password;
  294. AnsiString Account = Data->FtpAccount;
  295. AnsiString Path = Data->RemoteDirectory;
  296. int ServerType;
  297. switch (Data->Ftps)
  298. {
  299. case ftpsImplicit:
  300. ServerType = TFileZillaIntf::SERVER_FTP_SSL_IMPLICIT;
  301. break;
  302. case ftpsExplicitSsl:
  303. ServerType = TFileZillaIntf::SERVER_FTP_SSL_EXPLICIT;
  304. break;
  305. case ftpsExplicitTls:
  306. ServerType = TFileZillaIntf::SERVER_FTP_TLS_EXPLICIT;
  307. break;
  308. default:
  309. assert(Data->Ftps == ftpsNone);
  310. ServerType = TFileZillaIntf::SERVER_FTP;
  311. break;
  312. }
  313. int Pasv = (Data->FtpPasvMode ? 1 : 2);
  314. int TimeZoneOffset = int(double(Data->TimeDifference) * 24 * 60);
  315. int UTF8 = 0;
  316. switch (Data->NotUtf)
  317. {
  318. case asOn:
  319. UTF8 = 2;
  320. break;
  321. case asOff:
  322. UTF8 = 1;
  323. break;
  324. case asAuto:
  325. UTF8 = 0;
  326. break;
  327. };
  328. FPasswordFailed = false;
  329. bool PromptedForCredentials = false;
  330. do
  331. {
  332. FSystem = "";
  333. FFeatures->Clear();
  334. FFileSystemInfoValid = false;
  335. // TODO: the same for account? it ever used?
  336. // ask for username if it was not specified in advance, even on retry,
  337. // but keep previous one as default,
  338. if (Data->UserName.IsEmpty())
  339. {
  340. FTerminal->LogEvent("Username prompt (no username provided)");
  341. if (!FPasswordFailed && !PromptedForCredentials)
  342. {
  343. FTerminal->Information(LoadStr(FTP_CREDENTIAL_PROMPT), false);
  344. PromptedForCredentials = true;
  345. }
  346. if (!FTerminal->PromptUser(Data, pkUserName, LoadStr(USERNAME_TITLE), "",
  347. LoadStr(USERNAME_PROMPT2), true, 0, UserName))
  348. {
  349. FTerminal->FatalError(NULL, LoadStr(AUTHENTICATION_FAILED));
  350. }
  351. else
  352. {
  353. FUserName = UserName;
  354. }
  355. }
  356. // ask for password if it was not specified in advance,
  357. // on retry ask always
  358. if ((Data->Password.IsEmpty() && !Data->Passwordless) || FPasswordFailed)
  359. {
  360. FTerminal->LogEvent("Password prompt (no password provided or last login attempt failed)");
  361. if (!FPasswordFailed && !PromptedForCredentials)
  362. {
  363. FTerminal->Information(LoadStr(FTP_CREDENTIAL_PROMPT), false);
  364. PromptedForCredentials = true;
  365. }
  366. // on retry ask for new password
  367. Password = "";
  368. if (!FTerminal->PromptUser(Data, pkPassword, LoadStr(PASSWORD_TITLE), "",
  369. LoadStr(PASSWORD_PROMPT), false, 0, Password))
  370. {
  371. FTerminal->FatalError(NULL, LoadStr(AUTHENTICATION_FAILED));
  372. }
  373. }
  374. FActive = FFileZillaIntf->Connect(
  375. HostName.c_str(), Data->PortNumber, UserName.c_str(),
  376. Password.c_str(), Account.c_str(), false, Path.c_str(),
  377. ServerType, Pasv, TimeZoneOffset, UTF8, Data->FtpForcePasvIp);
  378. assert(FActive);
  379. FPasswordFailed = false;
  380. try
  381. {
  382. // do not wait for FTP response code as Connect is complex operation
  383. GotReply(WaitForCommandReply(false), REPLY_CONNECT, LoadStr(CONNECTION_FAILED));
  384. // we have passed, even if we got 530 on the way (if it is possible at all),
  385. // ignore it
  386. assert(!FPasswordFailed);
  387. FPasswordFailed = false;
  388. }
  389. catch(...)
  390. {
  391. if (FPasswordFailed)
  392. {
  393. FTerminal->Information(LoadStr(FTP_ACCESS_DENIED), false);
  394. }
  395. else
  396. {
  397. // see handling of REPLY_CONNECT in GotReply
  398. FTerminal->Closed();
  399. throw;
  400. }
  401. }
  402. }
  403. while (FPasswordFailed);
  404. }
  405. //---------------------------------------------------------------------------
  406. void __fastcall TFTPFileSystem::Close()
  407. {
  408. assert(FActive);
  409. if (FFileZillaIntf->Close())
  410. {
  411. CHECK(FLAGSET(WaitForCommandReply(false), TFileZillaIntf::REPLY_DISCONNECTED));
  412. assert(FActive);
  413. Discard();
  414. FTerminal->Closed();
  415. }
  416. else
  417. {
  418. assert(false);
  419. }
  420. }
  421. //---------------------------------------------------------------------------
  422. bool __fastcall TFTPFileSystem::GetActive()
  423. {
  424. return FActive;
  425. }
  426. //---------------------------------------------------------------------------
  427. void __fastcall TFTPFileSystem::Idle()
  428. {
  429. if (FActive && !FWaitingForReply)
  430. {
  431. PoolForFatalNonCommandReply();
  432. // Keep session alive
  433. if ((FTerminal->SessionData->FtpPingType != ptOff) &&
  434. (double(Now() - FLastDataSent) > double(FTerminal->SessionData->FtpPingIntervalDT) * 4))
  435. {
  436. FLastDataSent = Now();
  437. TRemoteDirectory * Files = new TRemoteDirectory(FTerminal);
  438. try
  439. {
  440. try
  441. {
  442. Files->Directory = CurrentDirectory;
  443. DoReadDirectory(Files);
  444. }
  445. catch(...)
  446. {
  447. // ignore non-fatal errors
  448. // (i.e. current directory may not exist anymore)
  449. if (!FTerminal->Active)
  450. {
  451. throw;
  452. }
  453. }
  454. }
  455. __finally
  456. {
  457. delete Files;
  458. }
  459. }
  460. }
  461. }
  462. //---------------------------------------------------------------------------
  463. void __fastcall TFTPFileSystem::Discard()
  464. {
  465. // remove all pending messages, to get complete log
  466. // note that we need to retry discard on reconnect, as there still may be another
  467. // "disconnect/timeout/..." status messages coming
  468. DiscardMessages();
  469. assert(FActive);
  470. FActive = false;
  471. }
  472. //---------------------------------------------------------------------------
  473. AnsiString __fastcall TFTPFileSystem::AbsolutePath(AnsiString Path, bool /*Local*/)
  474. {
  475. // TODO: improve (handle .. etc.)
  476. if (TTerminal::IsAbsolutePath(Path))
  477. {
  478. return Path;
  479. }
  480. else
  481. {
  482. return ::AbsolutePath(FCurrentDirectory, Path);
  483. }
  484. }
  485. //---------------------------------------------------------------------------
  486. AnsiString __fastcall TFTPFileSystem::ActualCurrentDirectory()
  487. {
  488. char CurrentPath[1024];
  489. FFileZillaIntf->GetCurrentPath(CurrentPath, sizeof(CurrentPath));
  490. return UnixExcludeTrailingBackslash(AnsiString(CurrentPath));
  491. }
  492. //---------------------------------------------------------------------------
  493. void __fastcall TFTPFileSystem::EnsureLocation()
  494. {
  495. // if we do not know what's the current directory, do nothing
  496. if (!FCurrentDirectory.IsEmpty())
  497. {
  498. // Make sure that the FZAPI current working directory,
  499. // is actually our working directory.
  500. // It may not be because:
  501. // 1) We did cached directory change
  502. // 2) Listing was requested for non-current directory, which
  503. // makes FAPI change its current directory (and not restoring it back afterwards)
  504. if (!UnixComparePaths(ActualCurrentDirectory(), FCurrentDirectory))
  505. {
  506. FTerminal->LogEvent(FORMAT("Synchronizing current directory \"%s\".",
  507. (FCurrentDirectory)));
  508. DoChangeDirectory(FCurrentDirectory);
  509. }
  510. }
  511. }
  512. //---------------------------------------------------------------------------
  513. void __fastcall TFTPFileSystem::AnyCommand(const AnsiString Command,
  514. TCaptureOutputEvent OutputEvent)
  515. {
  516. // end-user has right to expect that client current directory is really
  517. // current directory for the server
  518. EnsureLocation();
  519. assert(FOnCaptureOutput == NULL);
  520. FOnCaptureOutput = OutputEvent;
  521. try
  522. {
  523. FFileZillaIntf->CustomCommand(Command.c_str());
  524. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  525. }
  526. __finally
  527. {
  528. FOnCaptureOutput = NULL;
  529. }
  530. }
  531. //---------------------------------------------------------------------------
  532. void __fastcall TFTPFileSystem::ResetCaches()
  533. {
  534. delete FFileListCache;
  535. FFileListCache = NULL;
  536. }
  537. //---------------------------------------------------------------------------
  538. void __fastcall TFTPFileSystem::AnnounceFileListOperation()
  539. {
  540. ResetCaches();
  541. }
  542. //---------------------------------------------------------------------------
  543. void __fastcall TFTPFileSystem::DoChangeDirectory(const AnsiString & Directory)
  544. {
  545. AnsiString Command = FORMAT("CWD %s", (Directory));
  546. FFileZillaIntf->CustomCommand(Command.c_str());
  547. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  548. }
  549. //---------------------------------------------------------------------------
  550. void __fastcall TFTPFileSystem::ChangeDirectory(const AnsiString ADirectory)
  551. {
  552. AnsiString Directory = ADirectory;
  553. try
  554. {
  555. // For changing directory, we do not make paths absolute, instead we
  556. // delegate this to the server, hence we sychronize current working
  557. // directory with the server and only then we ask for the change with
  558. // relative path.
  559. // But if synchronization fails, typically because current working directory
  560. // no longer exists, we fall back to out own resolution, to give
  561. // user chance to leave the non-existing directory.
  562. EnsureLocation();
  563. }
  564. catch(...)
  565. {
  566. if (FTerminal->Active)
  567. {
  568. Directory = AbsolutePath(Directory, false);
  569. }
  570. else
  571. {
  572. throw;
  573. }
  574. }
  575. DoChangeDirectory(Directory);
  576. // make next ReadCurrentDirectory retrieve actual server-side current directory
  577. FCurrentDirectory = "";
  578. }
  579. //---------------------------------------------------------------------------
  580. void __fastcall TFTPFileSystem::CachedChangeDirectory(const AnsiString Directory)
  581. {
  582. FCurrentDirectory = UnixExcludeTrailingBackslash(Directory);
  583. }
  584. //---------------------------------------------------------------------------
  585. void __fastcall TFTPFileSystem::ChangeFileProperties(const AnsiString AFileName,
  586. const TRemoteFile * File, const TRemoteProperties * Properties,
  587. TChmodSessionAction & Action)
  588. {
  589. assert(!Properties->Valid.Contains(vpGroup));
  590. assert(!Properties->Valid.Contains(vpOwner));
  591. assert(!Properties->Valid.Contains(vpLastAccess));
  592. assert(!Properties->Valid.Contains(vpModification));
  593. if (Properties->Valid.Contains(vpRights))
  594. {
  595. assert(Properties);
  596. TRemoteFile * OwnedFile = NULL;
  597. try
  598. {
  599. AnsiString FileName = AbsolutePath(AFileName, false);
  600. if (File == NULL)
  601. {
  602. ReadFile(FileName, OwnedFile);
  603. File = OwnedFile;
  604. }
  605. if ((File != NULL) && File->IsDirectory && !File->IsSymLink && Properties->Recursive)
  606. {
  607. try
  608. {
  609. FTerminal->ProcessDirectory(AFileName, FTerminal->ChangeFileProperties,
  610. (void*)Properties);
  611. }
  612. catch(...)
  613. {
  614. Action.Cancel();
  615. throw;
  616. }
  617. }
  618. TRights Rights;
  619. if (File != NULL)
  620. {
  621. Rights = *File->Rights;
  622. }
  623. Rights |= Properties->Rights.NumberSet;
  624. Rights &= (unsigned short)~Properties->Rights.NumberUnset;
  625. if ((File != NULL) && File->IsDirectory && Properties->AddXToDirectories)
  626. {
  627. Rights.AddExecute();
  628. }
  629. Action.Rights(Rights);
  630. AnsiString FileNameOnly = UnixExtractFileName(FileName);
  631. AnsiString FilePath = UnixExtractFilePath(FileName);
  632. // FZAPI wants octal number represented as decadic
  633. FFileZillaIntf->Chmod(Rights.NumberDecadic, FileNameOnly.c_str(), FilePath.c_str());
  634. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  635. }
  636. __finally
  637. {
  638. delete OwnedFile;
  639. }
  640. }
  641. else
  642. {
  643. Action.Cancel();
  644. }
  645. }
  646. //---------------------------------------------------------------------------
  647. bool __fastcall TFTPFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  648. {
  649. assert(false);
  650. return false;
  651. }
  652. //---------------------------------------------------------------------------
  653. void __fastcall TFTPFileSystem::CalculateFilesChecksum(const AnsiString & /*Alg*/,
  654. TStrings * /*FileList*/, TStrings * /*Checksums*/,
  655. TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
  656. {
  657. assert(false);
  658. }
  659. //---------------------------------------------------------------------------
  660. bool __fastcall TFTPFileSystem::ConfirmOverwrite(AnsiString & FileName,
  661. TOverwriteMode & OverwriteMode, TFileOperationProgressType * OperationProgress,
  662. const TOverwriteFileParams * FileParams, int Params, bool AutoResume)
  663. {
  664. bool Result;
  665. bool CanAutoResume = FLAGSET(Params, cpNoConfirmation) && AutoResume;
  666. // when resuming transfer after interrupted connection,
  667. // do nothing (dummy resume) when the files has the same size.
  668. // this is workaround for servers that strangely fails just after successful
  669. // upload.
  670. bool CanResume =
  671. (FileParams != NULL) &&
  672. (((FileParams->DestSize < FileParams->SourceSize)) ||
  673. ((FileParams->DestSize == FileParams->SourceSize) && CanAutoResume));
  674. int Answer;
  675. if (CanAutoResume && CanResume)
  676. {
  677. Answer = qaRetry;
  678. }
  679. else
  680. {
  681. // retry = "resume"
  682. // all = "yes to newer"
  683. // ignore = "rename"
  684. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  685. if (CanResume)
  686. {
  687. Answers |= qaRetry;
  688. }
  689. TQueryButtonAlias Aliases[3];
  690. Aliases[0].Button = qaRetry;
  691. Aliases[0].Alias = LoadStr(RESUME_BUTTON);
  692. Aliases[1].Button = qaAll;
  693. Aliases[1].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  694. Aliases[2].Button = qaIgnore;
  695. Aliases[2].Alias = LoadStr(RENAME_BUTTON);
  696. TQueryParams QueryParams(qpNeverAskAgainCheck);
  697. QueryParams.Aliases = Aliases;
  698. QueryParams.AliasesCount = LENOF(Aliases);
  699. SUSPEND_OPERATION
  700. (
  701. Answer = FTerminal->ConfirmFileOverwrite(FileName, FileParams,
  702. Answers, &QueryParams,
  703. OperationProgress->Side == osLocal ? osRemote : osLocal,
  704. Params, OperationProgress);
  705. )
  706. }
  707. Result = true;
  708. switch (Answer)
  709. {
  710. // resume
  711. case qaRetry:
  712. OverwriteMode = omResume;
  713. assert(FileParams != NULL);
  714. assert(CanResume);
  715. FFileTransferResumed = FileParams->DestSize;
  716. break;
  717. // rename
  718. case qaIgnore:
  719. if (FTerminal->PromptUser(FTerminal->SessionData, pkPrompt,
  720. LoadStr(RENAME_TITLE), "", LoadStr(RENAME_PROMPT2), true, 0, FileName))
  721. {
  722. OverwriteMode = omOverwrite;
  723. }
  724. else
  725. {
  726. if (!OperationProgress->Cancel)
  727. {
  728. OperationProgress->Cancel = csCancel;
  729. }
  730. FFileTransferAbort = ftaCancel;
  731. Result = false;
  732. }
  733. break;
  734. case qaYes:
  735. OverwriteMode = omOverwrite;
  736. break;
  737. case qaCancel:
  738. if (!OperationProgress->Cancel)
  739. {
  740. OperationProgress->Cancel = csCancel;
  741. }
  742. FFileTransferAbort = ftaCancel;
  743. Result = false;
  744. break;
  745. case qaNo:
  746. FFileTransferAbort = ftaSkip;
  747. Result = false;
  748. break;
  749. default:
  750. assert(false);
  751. Result = false;
  752. break;
  753. }
  754. return Result;
  755. }
  756. //---------------------------------------------------------------------------
  757. void __fastcall TFTPFileSystem::ResetFileTransfer()
  758. {
  759. FFileTransferAbort = ftaNone;
  760. FFileTransferCancelled = false;
  761. FFileTransferResumed = 0;
  762. }
  763. //---------------------------------------------------------------------------
  764. void __fastcall TFTPFileSystem::ReadDirectoryProgress(__int64 Bytes)
  765. {
  766. // with FTP we do not know exactly how many entries we have received,
  767. // instead we know number of bytes received only.
  768. // so we report approximation based on average size of entry.
  769. int Progress = int(Bytes / 80);
  770. if (Progress - FLastReadDirectoryProgress >= 10)
  771. {
  772. bool Cancel = false;
  773. FLastReadDirectoryProgress = Progress;
  774. FTerminal->DoReadDirectoryProgress(Progress, Cancel);
  775. if (Cancel)
  776. {
  777. FTerminal->DoReadDirectoryProgress(-2, Cancel);
  778. FFileZillaIntf->Cancel();
  779. }
  780. }
  781. }
  782. //---------------------------------------------------------------------------
  783. void __fastcall TFTPFileSystem::DoFileTransferProgress(__int64 TransferSize,
  784. __int64 Bytes)
  785. {
  786. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  787. OperationProgress->SetTransferSize(TransferSize);
  788. if (FFileTransferResumed > 0)
  789. {
  790. OperationProgress->AddResumed(FFileTransferResumed);
  791. FFileTransferResumed = 0;
  792. }
  793. __int64 Diff = Bytes - OperationProgress->TransferedSize;
  794. assert(Diff >= 0);
  795. if (Diff >= 0)
  796. {
  797. OperationProgress->AddTransfered(Diff);
  798. }
  799. if (OperationProgress->Cancel == csCancel)
  800. {
  801. FFileTransferCancelled = true;
  802. FFileTransferAbort = ftaCancel;
  803. FFileZillaIntf->Cancel();
  804. }
  805. if (FFileTransferCPSLimit != OperationProgress->CPSLimit)
  806. {
  807. FFileTransferCPSLimit = OperationProgress->CPSLimit;
  808. }
  809. }
  810. //---------------------------------------------------------------------------
  811. void __fastcall TFTPFileSystem::FileTransferProgress(__int64 TransferSize,
  812. __int64 Bytes)
  813. {
  814. TGuard Guard(FTransferStatusCriticalSection);
  815. DoFileTransferProgress(TransferSize, Bytes);
  816. }
  817. //---------------------------------------------------------------------------
  818. void __fastcall TFTPFileSystem::FileTransfer(const AnsiString & FileName,
  819. const AnsiString & LocalFile, const AnsiString & RemoteFile,
  820. const AnsiString & RemotePath, bool Get, __int64 Size, int Type,
  821. TFileTransferData & UserData, TFileOperationProgressType * OperationProgress)
  822. {
  823. FILE_OPERATION_LOOP(FMTLOAD(TRANSFER_ERROR, (FileName)),
  824. FFileZillaIntf->FileTransfer(LocalFile.c_str(), RemoteFile.c_str(),
  825. RemotePath.c_str(), Get, Size, Type, &UserData);
  826. // we may actually catch reponse code of the listing
  827. // command (when checking for existence of the remote file)
  828. unsigned int Reply = WaitForCommandReply();
  829. GotReply(Reply, FLAGMASK(FFileTransferCancelled, REPLY_ALLOW_CANCEL));
  830. );
  831. switch (FFileTransferAbort)
  832. {
  833. case ftaSkip:
  834. THROW_SKIP_FILE_NULL;
  835. case ftaCancel:
  836. Abort();
  837. break;
  838. }
  839. if (!FFileTransferCancelled)
  840. {
  841. // show completion of transfer
  842. // call non-guarded variant to avoid deadlock with keepalives
  843. // (we are not waiting for reply anymore so keepalives are free to proceed)
  844. DoFileTransferProgress(OperationProgress->TransferSize, OperationProgress->TransferSize);
  845. }
  846. }
  847. //---------------------------------------------------------------------------
  848. void __fastcall TFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  849. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  850. int Params, TFileOperationProgressType * OperationProgress,
  851. TOnceDoneOperation & OnceDoneOperation)
  852. {
  853. Params &= ~cpAppend;
  854. AnsiString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  855. int Index = 0;
  856. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  857. {
  858. AnsiString FileName = FilesToCopy->Strings[Index];
  859. const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
  860. bool Success = false;
  861. try
  862. {
  863. try
  864. {
  865. SinkRobust(AbsolutePath(FileName, false), File, FullTargetDir, CopyParam, Params,
  866. OperationProgress, tfFirstLevel);
  867. Success = true;
  868. FLastDataSent = Now();
  869. }
  870. catch(EScpSkipFile & E)
  871. {
  872. SUSPEND_OPERATION (
  873. if (!FTerminal->HandleException(&E)) throw;
  874. );
  875. }
  876. }
  877. __finally
  878. {
  879. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  880. }
  881. Index++;
  882. }
  883. }
  884. //---------------------------------------------------------------------------
  885. void __fastcall TFTPFileSystem::SinkRobust(const AnsiString FileName,
  886. const TRemoteFile * File, const AnsiString TargetDir,
  887. const TCopyParamType * CopyParam, int Params,
  888. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  889. {
  890. // the same in TSFTPFileSystem
  891. bool Retry;
  892. TDownloadSessionAction Action(FTerminal->Log);
  893. do
  894. {
  895. Retry = false;
  896. try
  897. {
  898. Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress,
  899. Flags, Action);
  900. }
  901. catch(Exception & E)
  902. {
  903. Retry = true;
  904. if (FTerminal->Active ||
  905. !FTerminal->QueryReopen(&E, ropNoReadDirectory, OperationProgress))
  906. {
  907. FTerminal->RollbackAction(Action, OperationProgress, &E);
  908. throw;
  909. }
  910. }
  911. if (Retry)
  912. {
  913. OperationProgress->RollbackTransfer();
  914. Action.Restart();
  915. assert(File != NULL);
  916. if (!File->IsDirectory)
  917. {
  918. // prevent overwrite confirmations
  919. Params |= cpNoConfirmation;
  920. Flags |= tfAutoResume;
  921. }
  922. }
  923. }
  924. while (Retry);
  925. }
  926. //---------------------------------------------------------------------------
  927. void __fastcall TFTPFileSystem::Sink(const AnsiString FileName,
  928. const TRemoteFile * File, const AnsiString TargetDir,
  929. const TCopyParamType * CopyParam, int Params,
  930. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  931. TDownloadSessionAction & Action)
  932. {
  933. AnsiString OnlyFileName = UnixExtractFileName(FileName);
  934. Action.FileName(FileName);
  935. TFileMasks::TParams MaskParams;
  936. MaskParams.Size = File->Size;
  937. if (FLAGCLEAR(Params, cpDelete) &&
  938. !CopyParam->AllowTransfer(FileName, osRemote, File->IsDirectory, MaskParams))
  939. {
  940. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  941. THROW_SKIP_FILE_NULL;
  942. }
  943. assert(File);
  944. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  945. OperationProgress->SetFile(OnlyFileName);
  946. AnsiString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
  947. osRemote, FLAGSET(Flags, tfFirstLevel));
  948. AnsiString DestFullName = TargetDir + DestFileName;
  949. if (File->IsDirectory)
  950. {
  951. Action.Cancel();
  952. if (!File->IsSymLink)
  953. {
  954. FILE_OPERATION_LOOP (FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)),
  955. int Attrs = FileGetAttr(DestFullName);
  956. if (FLAGCLEAR(Attrs, faDirectory))
  957. {
  958. EXCEPTION;
  959. }
  960. );
  961. FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFullName)),
  962. if (!ForceDirectories(DestFullName))
  963. {
  964. RaiseLastOSError();
  965. }
  966. );
  967. TSinkFileParams SinkFileParams;
  968. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  969. SinkFileParams.CopyParam = CopyParam;
  970. SinkFileParams.Params = Params;
  971. SinkFileParams.OperationProgress = OperationProgress;
  972. SinkFileParams.Skipped = false;
  973. SinkFileParams.Flags = Flags & ~(tfFirstLevel | tfAutoResume);
  974. FTerminal->ProcessDirectory(FileName, SinkFile, &SinkFileParams);
  975. // Do not delete directory if some of its files were skip.
  976. // Throw "skip file" for the directory to avoid attempt to deletion
  977. // of any parent directory
  978. if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
  979. {
  980. THROW_SKIP_FILE_NULL;
  981. }
  982. }
  983. else
  984. {
  985. // file is symlink to directory, currently do nothing, but it should be
  986. // reported to user
  987. }
  988. }
  989. else
  990. {
  991. FTerminal->LogEvent(FORMAT("Copying \"%s\" to local directory started.", (FileName)));
  992. // Will we use ASCII of BINARY file tranfer?
  993. OperationProgress->SetAsciiTransfer(
  994. CopyParam->UseAsciiTransfer(FileName, osRemote, MaskParams));
  995. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  996. " transfer mode selected.");
  997. // Suppose same data size to transfer as to write
  998. OperationProgress->SetTransferSize(File->Size);
  999. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  1000. int Attrs;
  1001. FILE_OPERATION_LOOP (FMTLOAD(NOT_FILE_ERROR, (DestFullName)),
  1002. Attrs = FileGetAttr(DestFullName);
  1003. if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory))
  1004. {
  1005. EXCEPTION;
  1006. }
  1007. );
  1008. OperationProgress->TransferingFile = false; // not set with FTP protocol
  1009. ResetFileTransfer();
  1010. TFileTransferData UserData;
  1011. AnsiString FilePath = UnixExtractFilePath(FileName);
  1012. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1013. {
  1014. // ignore file list
  1015. TFileListHelper Helper(this, NULL, true);
  1016. FFileTransferCPSLimit = OperationProgress->CPSLimit;
  1017. FFileTransferPreserveTime = CopyParam->PreserveTime;
  1018. UserData.FileName = DestFileName;
  1019. UserData.Params = Params;
  1020. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1021. UserData.CopyParam = CopyParam;
  1022. FileTransfer(FileName, DestFullName, OnlyFileName,
  1023. FilePath, true, File->Size, TransferType, UserData, OperationProgress);
  1024. }
  1025. // in case dest filename is changed from overwrite dialog
  1026. if (DestFileName != UserData.FileName)
  1027. {
  1028. DestFullName = TargetDir + UserData.FileName;
  1029. Attrs = FileGetAttr(DestFullName);
  1030. }
  1031. Action.Destination(ExpandUNCFileName(DestFullName));
  1032. if (Attrs == -1)
  1033. {
  1034. Attrs = faArchive;
  1035. }
  1036. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  1037. if ((NewAttrs & Attrs) != NewAttrs)
  1038. {
  1039. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFullName)),
  1040. THROWOSIFFALSE(FileSetAttr(DestFullName, Attrs | NewAttrs) == 0);
  1041. );
  1042. }
  1043. }
  1044. if (FLAGSET(Params, cpDelete))
  1045. {
  1046. // If file is directory, do not delete it recursively, because it should be
  1047. // empty already. If not, it should not be deleted (some files were
  1048. // skipped or some new files were copied to it, while we were downloading)
  1049. int Params = dfNoRecursive;
  1050. FTerminal->DeleteFile(FileName, File, &Params);
  1051. }
  1052. }
  1053. //---------------------------------------------------------------------------
  1054. void __fastcall TFTPFileSystem::SinkFile(AnsiString FileName,
  1055. const TRemoteFile * File, void * Param)
  1056. {
  1057. TSinkFileParams * Params = (TSinkFileParams *)Param;
  1058. assert(Params->OperationProgress);
  1059. try
  1060. {
  1061. SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  1062. Params->Params, Params->OperationProgress, Params->Flags);
  1063. }
  1064. catch(EScpSkipFile & E)
  1065. {
  1066. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  1067. Params->Skipped = true;
  1068. SUSPEND_OPERATION (
  1069. if (!FTerminal->HandleException(&E))
  1070. {
  1071. throw;
  1072. }
  1073. );
  1074. if (OperationProgress->Cancel)
  1075. {
  1076. Abort();
  1077. }
  1078. }
  1079. }
  1080. //---------------------------------------------------------------------------
  1081. void __fastcall TFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1082. const AnsiString ATargetDir, const TCopyParamType * CopyParam,
  1083. int Params, TFileOperationProgressType * OperationProgress,
  1084. TOnceDoneOperation & OnceDoneOperation)
  1085. {
  1086. assert((FilesToCopy != NULL) && (OperationProgress != NULL));
  1087. Params &= ~cpAppend;
  1088. AnsiString FileName, FileNameOnly;
  1089. AnsiString TargetDir = AbsolutePath(ATargetDir, false);
  1090. AnsiString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  1091. int Index = 0;
  1092. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  1093. {
  1094. bool Success = false;
  1095. FileName = FilesToCopy->Strings[Index];
  1096. FileNameOnly = ExtractFileName(FileName);
  1097. try
  1098. {
  1099. try
  1100. {
  1101. if (FTerminal->SessionData->CacheDirectories)
  1102. {
  1103. FTerminal->DirectoryModified(TargetDir, false);
  1104. if (DirectoryExists(FileName))
  1105. {
  1106. FTerminal->DirectoryModified(FullTargetDir + FileNameOnly, true);
  1107. }
  1108. }
  1109. SourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  1110. tfFirstLevel);
  1111. Success = true;
  1112. FLastDataSent = Now();
  1113. }
  1114. catch(EScpSkipFile & E)
  1115. {
  1116. SUSPEND_OPERATION (
  1117. if (!FTerminal->HandleException(&E)) throw;
  1118. );
  1119. }
  1120. }
  1121. __finally
  1122. {
  1123. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1124. }
  1125. Index++;
  1126. }
  1127. }
  1128. //---------------------------------------------------------------------------
  1129. void __fastcall TFTPFileSystem::SourceRobust(const AnsiString FileName,
  1130. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  1131. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1132. {
  1133. // the same in TSFTPFileSystem
  1134. bool Retry;
  1135. TUploadSessionAction Action(FTerminal->Log);
  1136. do
  1137. {
  1138. Retry = false;
  1139. try
  1140. {
  1141. Source(FileName, TargetDir, CopyParam, Params, OperationProgress,
  1142. Flags, Action);
  1143. }
  1144. catch(Exception & E)
  1145. {
  1146. Retry = true;
  1147. if (FTerminal->Active ||
  1148. !FTerminal->QueryReopen(&E, ropNoReadDirectory, OperationProgress))
  1149. {
  1150. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1151. throw;
  1152. }
  1153. }
  1154. if (Retry)
  1155. {
  1156. OperationProgress->RollbackTransfer();
  1157. Action.Restart();
  1158. // prevent overwrite confirmations
  1159. // (should not be set for directories!)
  1160. Params |= cpNoConfirmation;
  1161. Flags |= tfAutoResume;
  1162. }
  1163. }
  1164. while (Retry);
  1165. }
  1166. //---------------------------------------------------------------------------
  1167. void __fastcall TFTPFileSystem::Source(const AnsiString FileName,
  1168. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  1169. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1170. TUploadSessionAction & Action)
  1171. {
  1172. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  1173. Action.FileName(ExpandUNCFileName(FileName));
  1174. OperationProgress->SetFile(FileName, false);
  1175. if (FLAGCLEAR(Params, cpDelete) &&
  1176. !FTerminal->AllowLocalFileTransfer(FileName, CopyParam))
  1177. {
  1178. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  1179. THROW_SKIP_FILE_NULL;
  1180. }
  1181. __int64 Size;
  1182. int Attrs;
  1183. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &Attrs,
  1184. NULL, NULL, NULL, NULL, &Size);
  1185. OperationProgress->SetFileInProgress();
  1186. bool Dir = FLAGSET(Attrs, faDirectory);
  1187. if (Dir)
  1188. {
  1189. DirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  1190. Attrs, CopyParam, Params, OperationProgress, Flags);
  1191. Action.Cancel();
  1192. }
  1193. else
  1194. {
  1195. AnsiString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
  1196. osLocal, FLAGSET(Flags, tfFirstLevel));
  1197. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  1198. OperationProgress->SetLocalSize(Size);
  1199. // Suppose same data size to transfer as to read
  1200. // (not true with ASCII transfer)
  1201. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1202. OperationProgress->TransferingFile = false;
  1203. // Will we use ASCII of BINARY file tranfer?
  1204. TFileMasks::TParams MaskParams;
  1205. MaskParams.Size = Size;
  1206. OperationProgress->SetAsciiTransfer(
  1207. CopyParam->UseAsciiTransfer(FileName, osLocal, MaskParams));
  1208. FTerminal->LogEvent(
  1209. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  1210. " transfer mode selected.");
  1211. ResetFileTransfer();
  1212. TFileTransferData UserData;
  1213. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1214. {
  1215. // ignore file list
  1216. TFileListHelper Helper(this, NULL, true);
  1217. FFileTransferCPSLimit = OperationProgress->CPSLimit;
  1218. // not used for uploads anyway
  1219. FFileTransferPreserveTime = CopyParam->PreserveTime;
  1220. // not used for uploads, but we get new name (if any) back in this field
  1221. UserData.FileName = DestFileName;
  1222. UserData.Params = Params;
  1223. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1224. UserData.CopyParam = CopyParam;
  1225. FileTransfer(FileName, FileName, DestFileName,
  1226. TargetDir, false, Size, TransferType, UserData, OperationProgress);
  1227. }
  1228. AnsiString DestFullName = TargetDir + UserData.FileName;
  1229. // only now, we know the final destination
  1230. Action.Destination(DestFullName);
  1231. // we are not able to tell if setting timestamp succeeded,
  1232. // so we log it always (if supported)
  1233. if (FFileTransferPreserveTime && FMfmt)
  1234. {
  1235. // Inspired by SysUtils::FileAge
  1236. WIN32_FIND_DATA FindData;
  1237. HANDLE Handle = FindFirstFile(DestFullName.c_str(), &FindData);
  1238. if (Handle != INVALID_HANDLE_VALUE)
  1239. {
  1240. TTouchSessionAction TouchAction(FTerminal->Log, DestFullName,
  1241. UnixToDateTime(
  1242. ConvertTimestampToUnixSafe(FindData.ftLastWriteTime, dstmUnix),
  1243. dstmUnix));
  1244. FindClose(Handle);
  1245. }
  1246. }
  1247. }
  1248. /* TODO : Delete also read-only files. */
  1249. if (FLAGSET(Params, cpDelete))
  1250. {
  1251. if (!Dir)
  1252. {
  1253. FILE_OPERATION_LOOP (FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)),
  1254. THROWOSIFFALSE(Sysutils::DeleteFile(FileName));
  1255. )
  1256. }
  1257. }
  1258. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1259. {
  1260. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  1261. THROWOSIFFALSE(FileSetAttr(FileName, Attrs & ~faArchive) == 0);
  1262. )
  1263. }
  1264. }
  1265. //---------------------------------------------------------------------------
  1266. void __fastcall TFTPFileSystem::DirectorySource(const AnsiString DirectoryName,
  1267. const AnsiString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  1268. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1269. {
  1270. AnsiString DestDirectoryName = CopyParam->ChangeFileName(
  1271. ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal,
  1272. FLAGSET(Flags, tfFirstLevel));
  1273. AnsiString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  1274. OperationProgress->SetFile(DirectoryName);
  1275. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1276. TSearchRec SearchRec;
  1277. bool FindOK;
  1278. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1279. FindOK = (bool)(FindFirst(DirectoryName + "*.*",
  1280. FindAttrs, SearchRec) == 0);
  1281. );
  1282. bool CreateDir = true;
  1283. try
  1284. {
  1285. while (FindOK && !OperationProgress->Cancel)
  1286. {
  1287. AnsiString FileName = DirectoryName + SearchRec.Name;
  1288. try
  1289. {
  1290. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  1291. {
  1292. SourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  1293. Flags & ~(tfFirstLevel | tfAutoResume));
  1294. // if any file got uploaded (i.e. there were any file in the
  1295. // directory and at least one was not skipped),
  1296. // do not try to create the directory,
  1297. // as it should be already created by FZAPI during upload
  1298. CreateDir = false;
  1299. }
  1300. }
  1301. catch (EScpSkipFile &E)
  1302. {
  1303. // If ESkipFile occurs, just log it and continue with next file
  1304. SUSPEND_OPERATION (
  1305. // here a message to user was displayed, which was not appropriate
  1306. // when user refused to overwrite the file in subdirectory.
  1307. // hopefuly it won't be missing in other situations.
  1308. if (!FTerminal->HandleException(&E)) throw;
  1309. );
  1310. }
  1311. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1312. FindOK = (FindNext(SearchRec) == 0);
  1313. );
  1314. };
  1315. }
  1316. __finally
  1317. {
  1318. FindClose(SearchRec);
  1319. }
  1320. if (CreateDir)
  1321. {
  1322. TRemoteProperties Properties;
  1323. if (CopyParam->PreserveRights)
  1324. {
  1325. Properties.Valid = TValidProperties() << vpRights;
  1326. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  1327. }
  1328. try
  1329. {
  1330. FTerminal->ExceptionOnFail = true;
  1331. try
  1332. {
  1333. FTerminal->CreateDirectory(DestFullName, &Properties);
  1334. }
  1335. __finally
  1336. {
  1337. FTerminal->ExceptionOnFail = false;
  1338. }
  1339. }
  1340. catch(...)
  1341. {
  1342. TRemoteFile * File = NULL;
  1343. // ignore non-fatal error when the directory already exists
  1344. bool Rethrow =
  1345. !FTerminal->Active ||
  1346. !FTerminal->FileExists(UnixExcludeTrailingBackslash(DestFullName), &File) ||
  1347. !File->IsDirectory;
  1348. delete File;
  1349. if (Rethrow)
  1350. {
  1351. throw;
  1352. }
  1353. }
  1354. }
  1355. /* TODO : Delete also read-only directories. */
  1356. /* TODO : Show error message on failure. */
  1357. if (!OperationProgress->Cancel)
  1358. {
  1359. if (FLAGSET(Params, cpDelete))
  1360. {
  1361. RemoveDir(DirectoryName);
  1362. }
  1363. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1364. {
  1365. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DirectoryName)),
  1366. THROWOSIFFALSE(FileSetAttr(DirectoryName, Attrs & ~faArchive) == 0);
  1367. )
  1368. }
  1369. }
  1370. }
  1371. //---------------------------------------------------------------------------
  1372. void __fastcall TFTPFileSystem::CreateDirectory(const AnsiString ADirName)
  1373. {
  1374. AnsiString DirName = AbsolutePath(ADirName, false);
  1375. {
  1376. // ignore file list
  1377. TFileListHelper Helper(this, NULL, true);
  1378. FFileZillaIntf->MakeDir(DirName.c_str());
  1379. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1380. }
  1381. }
  1382. //---------------------------------------------------------------------------
  1383. void __fastcall TFTPFileSystem::CreateLink(const AnsiString /*FileName*/,
  1384. const AnsiString /*PointTo*/, bool /*Symbolic*/)
  1385. {
  1386. assert(false);
  1387. }
  1388. //---------------------------------------------------------------------------
  1389. void __fastcall TFTPFileSystem::DeleteFile(const AnsiString AFileName,
  1390. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  1391. {
  1392. AnsiString FileName = AbsolutePath(AFileName, false);
  1393. AnsiString FileNameOnly = UnixExtractFileName(FileName);
  1394. AnsiString FilePath = UnixExtractFilePath(FileName);
  1395. bool Dir = (File != NULL) && File->IsDirectory && !File->IsSymLink;
  1396. if (Dir && FLAGCLEAR(Params, dfNoRecursive))
  1397. {
  1398. try
  1399. {
  1400. FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Params);
  1401. }
  1402. catch(...)
  1403. {
  1404. Action.Cancel();
  1405. throw;
  1406. }
  1407. }
  1408. {
  1409. // ignore file list
  1410. TFileListHelper Helper(this, NULL, true);
  1411. if (Dir)
  1412. {
  1413. // If current remote directory is in the directory being removed,
  1414. // some servers may refuse to delete it
  1415. // This is common as ProcessDirectory above would CWD to
  1416. // the directory to LIST it.
  1417. // EnsureLocation should reset actual current directory to user's working directory.
  1418. // If user's working directory is still below deleted directory, it is
  1419. // perfectly correct to report an error.
  1420. if (UnixIsChildPath(ActualCurrentDirectory(), FileName))
  1421. {
  1422. EnsureLocation();
  1423. }
  1424. FFileZillaIntf->RemoveDir(FileNameOnly.c_str(), FilePath.c_str());
  1425. }
  1426. else
  1427. {
  1428. FFileZillaIntf->Delete(FileNameOnly.c_str(), FilePath.c_str());
  1429. }
  1430. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1431. }
  1432. }
  1433. //---------------------------------------------------------------------------
  1434. void __fastcall TFTPFileSystem::CustomCommandOnFile(const AnsiString /*FileName*/,
  1435. const TRemoteFile * /*File*/, AnsiString /*Command*/, int /*Params*/,
  1436. TCaptureOutputEvent /*OutputEvent*/)
  1437. {
  1438. // if ever implemented, do not forget to add EnsureLocation,
  1439. // see AnyCommand for a reason why
  1440. assert(false);
  1441. }
  1442. //---------------------------------------------------------------------------
  1443. void __fastcall TFTPFileSystem::DoStartup()
  1444. {
  1445. TStrings * PostLoginCommands = new TStringList();
  1446. try
  1447. {
  1448. PostLoginCommands->Text = FTerminal->SessionData->PostLoginCommands;
  1449. for (int Index = 0; Index < PostLoginCommands->Count; Index++)
  1450. {
  1451. AnsiString Command = PostLoginCommands->Strings[Index];
  1452. if (!Command.IsEmpty())
  1453. {
  1454. FFileZillaIntf->CustomCommand(Command.c_str());
  1455. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1456. }
  1457. }
  1458. }
  1459. __finally
  1460. {
  1461. delete PostLoginCommands;
  1462. }
  1463. // retrieve initialize working directory to save it as home directory
  1464. ReadCurrentDirectory();
  1465. FHomeDirectory = FCurrentDirectory;
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. void __fastcall TFTPFileSystem::HomeDirectory()
  1469. {
  1470. // FHomeDirectory is an absolute path, so avoid unnecessary overhead
  1471. // of ChangeDirectory, such as EnsureLocation
  1472. DoChangeDirectory(FHomeDirectory);
  1473. FCurrentDirectory = FHomeDirectory;
  1474. }
  1475. //---------------------------------------------------------------------------
  1476. bool __fastcall TFTPFileSystem::IsCapable(int Capability) const
  1477. {
  1478. assert(FTerminal);
  1479. switch (Capability)
  1480. {
  1481. case fcResolveSymlink: // sic
  1482. case fcTextMode:
  1483. case fcModeChanging: // but not fcModeChangingUpload
  1484. case fcNewerOnlyUpload:
  1485. case fcAnyCommand: // but not fcShellAnyCommand
  1486. case fcRename:
  1487. case fcRemoteMove:
  1488. return true;
  1489. case fcPreservingTimestampUpload:
  1490. return FMfmt;
  1491. case fcModeChangingUpload:
  1492. case fcLoadingAdditionalProperties:
  1493. case fcShellAnyCommand:
  1494. case fcCalculatingChecksum:
  1495. case fcHardLink:
  1496. case fcSymbolicLink:
  1497. case fcCheckingSpaceAvailable:
  1498. case fcUserGroupListing:
  1499. case fcGroupChanging:
  1500. case fcOwnerChanging:
  1501. case fcGroupOwnerChangingByID:
  1502. case fcSecondaryShell:
  1503. case fcRemoteCopy:
  1504. case fcNativeTextMode:
  1505. case fcTimestampChanging:
  1506. case fcIgnorePermErrors:
  1507. return false;
  1508. default:
  1509. assert(false);
  1510. return false;
  1511. }
  1512. }
  1513. //---------------------------------------------------------------------------
  1514. void __fastcall TFTPFileSystem::LookupUsersGroups()
  1515. {
  1516. assert(false);
  1517. }
  1518. //---------------------------------------------------------------------------
  1519. void __fastcall TFTPFileSystem::ReadCurrentDirectory()
  1520. {
  1521. // ask the server for current directory on startup only
  1522. // and immediatelly after call to CWD,
  1523. // later our current directory may be not synchronized with FZAPI current
  1524. // directory anyway, see comments in EnsureLocation
  1525. if (FCurrentDirectory.IsEmpty())
  1526. {
  1527. FFileZillaIntf->CustomCommand("PWD");
  1528. unsigned int Code;
  1529. TStrings * Response = NULL;
  1530. GotReply(WaitForCommandReply(), REPLY_2XX_CODE, "", &Code, &Response);
  1531. try
  1532. {
  1533. assert(Response != NULL);
  1534. bool Result = false;
  1535. // the only allowed 2XX code to "PWD"
  1536. if ((Code == 257) &&
  1537. (Response->Count == 1))
  1538. {
  1539. AnsiString Path = Response->Text;
  1540. int P = Path.Pos("\"");
  1541. if (P == 0)
  1542. {
  1543. // some systems use single quotes, be tolerant
  1544. P = Path.Pos("'");
  1545. }
  1546. if (P != 0)
  1547. {
  1548. Path.Delete(1, P - 1);
  1549. if (Unquote(Path))
  1550. {
  1551. FCurrentDirectory = UnixExcludeTrailingBackslash(Path);
  1552. Result = true;
  1553. }
  1554. }
  1555. }
  1556. if (Result)
  1557. {
  1558. FFileZillaIntf->SetCurrentPath(FCurrentDirectory.c_str());
  1559. }
  1560. else
  1561. {
  1562. throw Exception(FMTLOAD(FTP_PWD_RESPONSE_ERROR, (Response->Text)));
  1563. }
  1564. }
  1565. __finally
  1566. {
  1567. delete Response;
  1568. }
  1569. }
  1570. }
  1571. //---------------------------------------------------------------------------
  1572. void __fastcall TFTPFileSystem::DoReadDirectory(TRemoteFileList * FileList)
  1573. {
  1574. FileList->Clear();
  1575. // FZAPI does not list parent directory, add it
  1576. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  1577. FLastReadDirectoryProgress = 0;
  1578. TFileListHelper Helper(this, FileList, false);
  1579. // always specify path to list, do not attempt to list "current" dir as:
  1580. // 1) List() lists again the last listed directory, not the current working directory
  1581. // 2) we handle this way the cached directory change
  1582. AnsiString Directory = AbsolutePath(FileList->Directory, false);
  1583. FFileZillaIntf->List(Directory.c_str());
  1584. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_ALLOW_CANCEL);
  1585. FLastDataSent = Now();
  1586. }
  1587. //---------------------------------------------------------------------------
  1588. void __fastcall TFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  1589. {
  1590. bool Repeat;
  1591. do
  1592. {
  1593. Repeat = false;
  1594. try
  1595. {
  1596. FDoListAll = (FListAll == asAuto) || (FListAll == asOn);
  1597. DoReadDirectory(FileList);
  1598. if (FListAll == asAuto)
  1599. {
  1600. // reading first directory has succeeded, always use "-a"
  1601. FListAll = asOn;
  1602. }
  1603. // use "-a" even for implicit directory reading by FZAPI?
  1604. // (e.g. before file transfer)
  1605. FDoListAll = (FListAll == asOn);
  1606. }
  1607. catch(...)
  1608. {
  1609. FDoListAll = false;
  1610. // reading the first directory has failed,
  1611. // further try without "-a" only as the server may not support it
  1612. if ((FListAll == asAuto) && FTerminal->Active)
  1613. {
  1614. FListAll = asOff;
  1615. Repeat = true;
  1616. }
  1617. else
  1618. {
  1619. throw;
  1620. }
  1621. }
  1622. }
  1623. while (Repeat);
  1624. }
  1625. //---------------------------------------------------------------------------
  1626. void __fastcall TFTPFileSystem::ReadFile(const AnsiString FileName,
  1627. TRemoteFile *& File)
  1628. {
  1629. AnsiString Path = UnixExtractFilePath(FileName);
  1630. AnsiString NameOnly = UnixExtractFileName(FileName);
  1631. // FZAPI does not have efficient way to read properties of one file.
  1632. // If case we need properties of set of files from the same directory,
  1633. // cache the file list for future
  1634. TRemoteFile * AFile = NULL;
  1635. if ((FFileListCache != NULL) &&
  1636. UnixComparePaths(Path, FFileListCache->Directory) &&
  1637. (TTerminal::IsAbsolutePath(FFileListCache->Directory) ||
  1638. (FFileListCachePath == CurrentDirectory)))
  1639. {
  1640. AFile = FFileListCache->FindFile(NameOnly);
  1641. }
  1642. // if cache is invalid or file is not in cache, (re)read the directory
  1643. if (AFile == NULL)
  1644. {
  1645. delete FFileListCache;
  1646. FFileListCache = NULL;
  1647. FFileListCache = new TRemoteFileList();
  1648. FFileListCache->Directory = Path;
  1649. ReadDirectory(FFileListCache);
  1650. FFileListCachePath = CurrentDirectory;
  1651. AFile = FFileListCache->FindFile(NameOnly);
  1652. if (AFile == NULL)
  1653. {
  1654. File = NULL;
  1655. throw Exception(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  1656. }
  1657. }
  1658. assert(AFile != NULL);
  1659. File = AFile->Duplicate();
  1660. }
  1661. //---------------------------------------------------------------------------
  1662. void __fastcall TFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  1663. TRemoteFile *& File)
  1664. {
  1665. // Resolving symlinks over FTP is big overhead
  1666. // (involves opening TCPIP connection for retrieving "directory listing").
  1667. // Moreover FZAPI does not support that anyway.
  1668. File = new TRemoteFile(SymlinkFile);
  1669. try
  1670. {
  1671. File->Terminal = FTerminal;
  1672. File->FileName = UnixExtractFileName(SymlinkFile->LinkTo);
  1673. // FZAPI treats all symlink target as directories
  1674. File->Type = FILETYPE_DIRECTORY;
  1675. }
  1676. catch(...)
  1677. {
  1678. delete File;
  1679. File = NULL;
  1680. throw;
  1681. }
  1682. }
  1683. //---------------------------------------------------------------------------
  1684. void __fastcall TFTPFileSystem::RenameFile(const AnsiString AFileName,
  1685. const AnsiString ANewName)
  1686. {
  1687. AnsiString FileName = AbsolutePath(AFileName, false);
  1688. AnsiString NewName = AbsolutePath(ANewName, false);
  1689. AnsiString FileNameOnly = UnixExtractFileName(FileName);
  1690. AnsiString FilePathOnly = UnixExtractFilePath(FileName);
  1691. AnsiString NewNameOnly = UnixExtractFileName(NewName);
  1692. AnsiString NewPathOnly = UnixExtractFilePath(NewName);
  1693. {
  1694. // ignore file list
  1695. TFileListHelper Helper(this, NULL, true);
  1696. FFileZillaIntf->Rename(FileNameOnly.c_str(), NewNameOnly.c_str(),
  1697. FilePathOnly.c_str(), NewPathOnly.c_str());
  1698. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1699. }
  1700. }
  1701. //---------------------------------------------------------------------------
  1702. void __fastcall TFTPFileSystem::CopyFile(const AnsiString FileName,
  1703. const AnsiString NewName)
  1704. {
  1705. assert(false);
  1706. }
  1707. //---------------------------------------------------------------------------
  1708. AnsiString __fastcall TFTPFileSystem::FileUrl(const AnsiString FileName)
  1709. {
  1710. return FTerminal->FileUrl("ftp", FileName);
  1711. }
  1712. //---------------------------------------------------------------------------
  1713. TStrings * __fastcall TFTPFileSystem::GetFixedPaths()
  1714. {
  1715. return NULL;
  1716. }
  1717. //---------------------------------------------------------------------------
  1718. void __fastcall TFTPFileSystem::SpaceAvailable(const AnsiString /*Path*/,
  1719. TSpaceAvailable & /*ASpaceAvailable*/)
  1720. {
  1721. assert(false);
  1722. }
  1723. //---------------------------------------------------------------------------
  1724. const TSessionInfo & __fastcall TFTPFileSystem::GetSessionInfo()
  1725. {
  1726. return FSessionInfo;
  1727. }
  1728. //---------------------------------------------------------------------------
  1729. const TFileSystemInfo & __fastcall TFTPFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  1730. {
  1731. if (!FFileSystemInfoValid)
  1732. {
  1733. FFileSystemInfo.RemoteSystem = FSystem;
  1734. FFileSystemInfo.RemoteSystem.Unique();
  1735. if (FFeatures->Count == 0)
  1736. {
  1737. FFileSystemInfo.AdditionalInfo = LoadStr(FTP_NO_FEATURE_INFO);
  1738. }
  1739. else
  1740. {
  1741. FFileSystemInfo.AdditionalInfo =
  1742. FORMAT("%s\r\n", (LoadStr(FTP_FEATURE_INFO)));
  1743. for (int Index = 0; Index < FFeatures->Count; Index++)
  1744. {
  1745. FFileSystemInfo.AdditionalInfo += FORMAT(" %s\r\n", (FFeatures->Strings[Index]));
  1746. }
  1747. }
  1748. for (int Index = 0; Index < fcCount; Index++)
  1749. {
  1750. FFileSystemInfo.IsCapable[Index] = IsCapable((TFSCapability)Index);
  1751. }
  1752. FFileSystemInfoValid = true;
  1753. }
  1754. return FFileSystemInfo;
  1755. }
  1756. //---------------------------------------------------------------------------
  1757. bool __fastcall TFTPFileSystem::TemporaryTransferFile(const AnsiString & /*FileName*/)
  1758. {
  1759. return false;
  1760. }
  1761. //---------------------------------------------------------------------------
  1762. bool __fastcall TFTPFileSystem::GetStoredCredentialsTried()
  1763. {
  1764. return !FTerminal->SessionData->Password.IsEmpty();
  1765. }
  1766. //---------------------------------------------------------------------------
  1767. AnsiString __fastcall TFTPFileSystem::GetUserName()
  1768. {
  1769. return FUserName;
  1770. }
  1771. //---------------------------------------------------------------------------
  1772. AnsiString __fastcall TFTPFileSystem::GetCurrentDirectory()
  1773. {
  1774. return FCurrentDirectory;
  1775. }
  1776. //---------------------------------------------------------------------------
  1777. const char * __fastcall TFTPFileSystem::GetOption(int OptionID) const
  1778. {
  1779. TSessionData * Data = FTerminal->SessionData;
  1780. switch (OptionID)
  1781. {
  1782. case OPTION_PROXYHOST:
  1783. case OPTION_FWHOST:
  1784. FOptionScratch = Data->ProxyHost;
  1785. break;
  1786. case OPTION_PROXYUSER:
  1787. case OPTION_FWUSER:
  1788. FOptionScratch = Data->ProxyUsername;
  1789. break;
  1790. case OPTION_PROXYPASS:
  1791. case OPTION_FWPASS:
  1792. FOptionScratch = Data->ProxyPassword;
  1793. break;
  1794. case OPTION_ANONPWD:
  1795. case OPTION_TRANSFERIP:
  1796. case OPTION_TRANSFERIP6:
  1797. FOptionScratch = "";
  1798. break;
  1799. default:
  1800. assert(false);
  1801. FOptionScratch = "";
  1802. }
  1803. return FOptionScratch.c_str();
  1804. }
  1805. //---------------------------------------------------------------------------
  1806. int __fastcall TFTPFileSystem::GetOptionVal(int OptionID) const
  1807. {
  1808. TSessionData * Data = FTerminal->SessionData;
  1809. int Result;
  1810. switch (OptionID)
  1811. {
  1812. case OPTION_PROXYTYPE:
  1813. switch (Data->ProxyMethod)
  1814. {
  1815. case pmNone:
  1816. Result = 0; // PROXYTYPE_NOPROXY;
  1817. break;
  1818. case pmSocks4:
  1819. Result = 2; // PROXYTYPE_SOCKS4A
  1820. break;
  1821. case pmSocks5:
  1822. Result = 3; // PROXYTYPE_SOCKS5
  1823. break;
  1824. case pmHTTP:
  1825. Result = 4; // PROXYTYPE_HTTP11
  1826. break;
  1827. case pmTelnet:
  1828. case pmCmd:
  1829. default:
  1830. assert(false);
  1831. Result = 0; // PROXYTYPE_NOPROXY;
  1832. break;
  1833. }
  1834. break;
  1835. case OPTION_PROXYPORT:
  1836. case OPTION_FWPORT:
  1837. Result = Data->ProxyPort;
  1838. break;
  1839. case OPTION_PROXYUSELOGON:
  1840. Result = !Data->ProxyUsername.IsEmpty();
  1841. break;
  1842. case OPTION_LOGONTYPE:
  1843. Result = Data->FtpProxyLogonType;
  1844. break;
  1845. case OPTION_TIMEOUTLENGTH:
  1846. Result = Data->Timeout;
  1847. break;
  1848. case OPTION_DEBUGSHOWLISTING:
  1849. // Listing is logged on FZAPI level 5 (what is strangely LOG_APIERROR)
  1850. Result = (FTerminal->Configuration->ActualLogProtocol >= 1);
  1851. break;
  1852. case OPTION_PASV:
  1853. // should never get here t_server.nPasv being nonzero
  1854. assert(false);
  1855. Result = FALSE;
  1856. break;
  1857. case OPTION_PRESERVEDOWNLOADFILETIME:
  1858. case OPTION_MPEXT_PRESERVEUPLOADFILETIME:
  1859. Result = FFileTransferPreserveTime ? TRUE : FALSE;
  1860. break;
  1861. case OPTION_LIMITPORTRANGE:
  1862. Result = FALSE;
  1863. break;
  1864. case OPTION_PORTRANGELOW:
  1865. case OPTION_PORTRANGEHIGH:
  1866. // should never get here OPTION_LIMITPORTRANGE being zero
  1867. assert(false);
  1868. Result = 0;
  1869. break;
  1870. case OPTION_ENABLE_IPV6:
  1871. Result = ((Data->AddressFamily == afIPv6) ? TRUE : FALSE);
  1872. break;
  1873. case OPTION_KEEPALIVE:
  1874. Result = ((Data->FtpPingType != ptOff) ? TRUE : FALSE);
  1875. break;
  1876. case OPTION_INTERVALLOW:
  1877. case OPTION_INTERVALHIGH:
  1878. Result = Data->FtpPingInterval;
  1879. break;
  1880. case OPTION_VMSALLREVISIONS:
  1881. Result = FALSE;
  1882. break;
  1883. case OPTION_SPEEDLIMIT_DOWNLOAD_TYPE:
  1884. case OPTION_SPEEDLIMIT_UPLOAD_TYPE:
  1885. Result = (FFileTransferCPSLimit == 0 ? 0 : 1);
  1886. break;
  1887. case OPTION_SPEEDLIMIT_DOWNLOAD_VALUE:
  1888. case OPTION_SPEEDLIMIT_UPLOAD_VALUE:
  1889. Result = (FFileTransferCPSLimit / 1024); // FZAPI expects KiB/s
  1890. break;
  1891. case OPTION_MPEXT_SHOWHIDDEN:
  1892. Result = (FDoListAll ? TRUE : FALSE);
  1893. break;
  1894. default:
  1895. assert(false);
  1896. Result = FALSE;
  1897. break;
  1898. }
  1899. return Result;
  1900. }
  1901. //---------------------------------------------------------------------------
  1902. bool __fastcall TFTPFileSystem::PostMessage(unsigned int Type, WPARAM wParam, LPARAM lParam)
  1903. {
  1904. if (Type == TFileZillaIntf::MSG_TRANSFERSTATUS)
  1905. {
  1906. // Stop here if FileTransferProgress is proceeding,
  1907. // it makes "pause" in queue work.
  1908. // Paused queue item stops in some of the TFileOperationProgressType
  1909. // methods called from FileTransferProgress
  1910. TGuard Guard(FTransferStatusCriticalSection);
  1911. }
  1912. TGuard Guard(FQueueCriticalSection);
  1913. FQueue->push_back(TMessageQueue::value_type(wParam, lParam));
  1914. SetEvent(FQueueEvent);
  1915. return true;
  1916. }
  1917. //---------------------------------------------------------------------------
  1918. bool __fastcall TFTPFileSystem::ProcessMessage()
  1919. {
  1920. bool Result;
  1921. TMessageQueue::value_type Message;
  1922. {
  1923. TGuard Guard(FQueueCriticalSection);
  1924. Result = !FQueue->empty();
  1925. if (Result)
  1926. {
  1927. Message = FQueue->front();
  1928. FQueue->pop_front();
  1929. }
  1930. else
  1931. {
  1932. // now we are perfecly sure that the queue is empty as it is locked,
  1933. // so reset the event
  1934. ResetEvent(FQueueEvent);
  1935. }
  1936. }
  1937. if (Result)
  1938. {
  1939. FFileZillaIntf->HandleMessage(Message.first, Message.second);
  1940. }
  1941. return Result;
  1942. }
  1943. //---------------------------------------------------------------------------
  1944. void __fastcall TFTPFileSystem::DiscardMessages()
  1945. {
  1946. while (ProcessMessage());
  1947. }
  1948. //---------------------------------------------------------------------------
  1949. void __fastcall TFTPFileSystem::WaitForMessages()
  1950. {
  1951. unsigned int Result = WaitForSingleObject(FQueueEvent, INFINITE);
  1952. if (Result != WAIT_OBJECT_0)
  1953. {
  1954. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, ("ftp#1", IntToStr(Result))));
  1955. }
  1956. }
  1957. //---------------------------------------------------------------------------
  1958. void __fastcall TFTPFileSystem::PoolForFatalNonCommandReply()
  1959. {
  1960. assert(FReply == 0);
  1961. assert(FCommandReply == 0);
  1962. assert(!FWaitingForReply);
  1963. FWaitingForReply = true;
  1964. unsigned int Reply;
  1965. try
  1966. {
  1967. // discard up to one reply
  1968. // (it should not happen here that two replies are posted anyway)
  1969. while (ProcessMessage() && (FReply == 0));
  1970. Reply = FReply;
  1971. }
  1972. __finally
  1973. {
  1974. FReply = 0;
  1975. assert(FCommandReply == 0);
  1976. FCommandReply = 0;
  1977. assert(FWaitingForReply);
  1978. FWaitingForReply = false;
  1979. }
  1980. if (Reply != 0)
  1981. {
  1982. // throws
  1983. GotNonCommandReply(Reply);
  1984. }
  1985. }
  1986. //---------------------------------------------------------------------------
  1987. bool __fastcall TFTPFileSystem::NoFinalLastCode()
  1988. {
  1989. return (FLastCodeClass == 0) || (FLastCodeClass == 1);
  1990. }
  1991. //---------------------------------------------------------------------------
  1992. bool __fastcall TFTPFileSystem::KeepWaitingForReply(unsigned int & ReplyToAwait, bool WantLastCode)
  1993. {
  1994. // to keep waiting,
  1995. // non-command reply must be unset,
  1996. // the reply we wait for must be unset or
  1997. // last code must be unset (if we wait for it)
  1998. return
  1999. (FReply == 0) &&
  2000. ((ReplyToAwait == 0) ||
  2001. (WantLastCode && NoFinalLastCode()));
  2002. }
  2003. //---------------------------------------------------------------------------
  2004. void __fastcall TFTPFileSystem::DoWaitForReply(unsigned int & ReplyToAwait, bool WantLastCode)
  2005. {
  2006. try
  2007. {
  2008. while (KeepWaitingForReply(ReplyToAwait, WantLastCode))
  2009. {
  2010. WaitForMessages();
  2011. // wait for the first reply only,
  2012. // i.e. in case two replies are posted get the first only.
  2013. // e.g. when server closes the connection, but posts error message before,
  2014. // sometime it happens that command (like download) fails because of the error
  2015. // and does not catch the disconnection. then asynchronous "disconnect reply"
  2016. // is posted immediately afterwards. leave detection of that to Idle()
  2017. while (ProcessMessage() && KeepWaitingForReply(ReplyToAwait, WantLastCode));
  2018. }
  2019. if (FReply != 0)
  2020. {
  2021. // throws
  2022. GotNonCommandReply(FReply);
  2023. }
  2024. }
  2025. catch(...)
  2026. {
  2027. // even if non-fatal error happens, we must process pending message,
  2028. // so that we "eat" the reply message, so that it gets not mistakenly
  2029. // associated with future connect
  2030. if (FTerminal->Active)
  2031. {
  2032. DoWaitForReply(ReplyToAwait, WantLastCode);
  2033. }
  2034. throw;
  2035. }
  2036. }
  2037. //---------------------------------------------------------------------------
  2038. unsigned int __fastcall TFTPFileSystem::WaitForReply(bool Command, bool WantLastCode)
  2039. {
  2040. assert(FReply == 0);
  2041. assert(FCommandReply == 0);
  2042. assert(!FWaitingForReply);
  2043. assert(!FTransferStatusCriticalSection->Acquired);
  2044. ResetReply();
  2045. FWaitingForReply = true;
  2046. unsigned int Reply;
  2047. try
  2048. {
  2049. unsigned int & ReplyToAwait = (Command ? FCommandReply : FReply);
  2050. DoWaitForReply(ReplyToAwait, WantLastCode);
  2051. Reply = ReplyToAwait;
  2052. }
  2053. __finally
  2054. {
  2055. FReply = 0;
  2056. FCommandReply = 0;
  2057. assert(FWaitingForReply);
  2058. FWaitingForReply = false;
  2059. }
  2060. return Reply;
  2061. }
  2062. //---------------------------------------------------------------------------
  2063. unsigned int __fastcall TFTPFileSystem::WaitForCommandReply(bool WantLastCode)
  2064. {
  2065. return WaitForReply(true, WantLastCode);
  2066. }
  2067. //---------------------------------------------------------------------------
  2068. void __fastcall TFTPFileSystem::WaitForFatalNonCommandReply()
  2069. {
  2070. WaitForReply(false, false);
  2071. assert(false);
  2072. }
  2073. //---------------------------------------------------------------------------
  2074. void __fastcall TFTPFileSystem::ResetReply()
  2075. {
  2076. FLastCode = 0;
  2077. FLastCodeClass = 0;
  2078. assert(FLastResponse != NULL);
  2079. FLastResponse->Clear();
  2080. assert(FLastError != NULL);
  2081. FLastError->Clear();
  2082. }
  2083. //---------------------------------------------------------------------------
  2084. void __fastcall TFTPFileSystem::GotNonCommandReply(unsigned int Reply)
  2085. {
  2086. assert(FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2087. GotReply(Reply);
  2088. // should never get here as GotReply should raise fatal exception
  2089. assert(false);
  2090. }
  2091. //---------------------------------------------------------------------------
  2092. void __fastcall TFTPFileSystem::GotReply(unsigned int Reply, unsigned int Flags,
  2093. AnsiString Error, unsigned int * Code, TStrings ** Response)
  2094. {
  2095. try
  2096. {
  2097. if (FLAGSET(Reply, TFileZillaIntf::REPLY_OK))
  2098. {
  2099. assert(Reply == TFileZillaIntf::REPLY_OK);
  2100. // With REPLY_2XX_CODE treat "OK" non-2xx code like an error
  2101. if (FLAGSET(Flags, REPLY_2XX_CODE) && (FLastCodeClass != 2))
  2102. {
  2103. GotReply(TFileZillaIntf::REPLY_ERROR, Flags, Error);
  2104. }
  2105. }
  2106. else if (FLAGSET(Reply, TFileZillaIntf::REPLY_CANCEL) &&
  2107. FLAGSET(Flags, REPLY_ALLOW_CANCEL))
  2108. {
  2109. assert(
  2110. (Reply == (TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)) ||
  2111. (Reply == (TFileZillaIntf::REPLY_ABORTED | TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)));
  2112. // noop
  2113. }
  2114. // we do not expect these with our usage of FZ
  2115. else if (Reply &
  2116. (TFileZillaIntf::REPLY_WOULDBLOCK | TFileZillaIntf::REPLY_OWNERNOTSET |
  2117. TFileZillaIntf::REPLY_INVALIDPARAM | TFileZillaIntf::REPLY_ALREADYCONNECTED |
  2118. TFileZillaIntf::REPLY_IDLE | TFileZillaIntf::REPLY_NOTINITIALIZED |
  2119. TFileZillaIntf::REPLY_ALREADYINIZIALIZED))
  2120. {
  2121. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, ("ftp#2", FORMAT("0x%x", (int(Reply))))));
  2122. }
  2123. else
  2124. {
  2125. // everything else must be an error or disconnect notification
  2126. assert(
  2127. FLAGSET(Reply, TFileZillaIntf::REPLY_ERROR) ||
  2128. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2129. // TODO: REPLY_CRITICALERROR ignored
  2130. // REPLY_NOTCONNECTED happens if connection is closed between moment
  2131. // when FZAPI interface method dispatches the command to FZAPI thread
  2132. // and moment when FZAPI thread receives the command
  2133. bool Disconnected =
  2134. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED) ||
  2135. FLAGSET(Reply, TFileZillaIntf::REPLY_NOTCONNECTED);
  2136. TStrings * MoreMessages = new TStringList();
  2137. try
  2138. {
  2139. if (Disconnected)
  2140. {
  2141. if (FLAGCLEAR(Flags, REPLY_CONNECT))
  2142. {
  2143. MoreMessages->Add(LoadStr(LOST_CONNECTION));
  2144. Discard();
  2145. FTerminal->Closed();
  2146. }
  2147. else
  2148. {
  2149. // For connection failure, do not report that connection was lost,
  2150. // its obvious.
  2151. // Also do not report to terminal that we are closed as
  2152. // that turns terminal into closed mode, but we want to
  2153. // pretend (at least with failed authentication) to retry
  2154. // with the same connection (as with SSH), so we explicitly
  2155. // close terminal in Open() only after we give up
  2156. Discard();
  2157. }
  2158. }
  2159. if (FLAGSET(Reply, TFileZillaIntf::REPLY_ABORTED))
  2160. {
  2161. MoreMessages->Add(LoadStr(USER_TERMINATED));
  2162. }
  2163. if (FLAGSET(Reply, TFileZillaIntf::REPLY_NOTSUPPORTED))
  2164. {
  2165. MoreMessages->Add(LoadStr(FZ_NOTSUPPORTED));
  2166. }
  2167. if (FLastCode == 530)
  2168. {
  2169. MoreMessages->Add(LoadStr(AUTHENTICATION_FAILED));
  2170. }
  2171. if (FLastCode == 425)
  2172. {
  2173. if (!FTerminal->SessionData->FtpPasvMode)
  2174. {
  2175. MoreMessages->Add(LoadStr(FTP_CANNOT_OPEN_ACTIVE_CONNECTION));
  2176. }
  2177. }
  2178. MoreMessages->AddStrings(FLastError);
  2179. // already cleared from WaitForReply, but GotReply can be also called
  2180. // from Closed. then make sure that error from previous command not
  2181. // associated with session closure is not reused
  2182. FLastError->Clear();
  2183. MoreMessages->AddStrings(FLastResponse);
  2184. // see comment for FLastError
  2185. FLastResponse->Clear();
  2186. if (MoreMessages->Count == 0)
  2187. {
  2188. delete MoreMessages;
  2189. MoreMessages = NULL;
  2190. }
  2191. }
  2192. catch(...)
  2193. {
  2194. delete MoreMessages;
  2195. throw;
  2196. }
  2197. if (Error.IsEmpty() && (MoreMessages != NULL))
  2198. {
  2199. assert(MoreMessages->Count > 0);
  2200. Error = MoreMessages->Strings[0];
  2201. MoreMessages->Delete(0);
  2202. }
  2203. if (Disconnected)
  2204. {
  2205. // for fatal error, it is essential that there is some message
  2206. assert(!Error.IsEmpty());
  2207. ExtException * E = new ExtException(Error, MoreMessages, true);
  2208. try
  2209. {
  2210. FTerminal->FatalError(E, "");
  2211. }
  2212. __finally
  2213. {
  2214. delete E;
  2215. }
  2216. }
  2217. else
  2218. {
  2219. throw ExtException(Error, MoreMessages, true);
  2220. }
  2221. }
  2222. if ((Code != NULL) && (FLastCodeClass != DummyCodeClass))
  2223. {
  2224. *Code = FLastCode;
  2225. }
  2226. if (Response != NULL)
  2227. {
  2228. *Response = FLastResponse;
  2229. FLastResponse = new TStringList();
  2230. }
  2231. }
  2232. __finally
  2233. {
  2234. ResetReply();
  2235. }
  2236. }
  2237. //---------------------------------------------------------------------------
  2238. void __fastcall TFTPFileSystem::SetLastCode(int Code)
  2239. {
  2240. FLastCode = Code;
  2241. FLastCodeClass = (Code / 100);
  2242. }
  2243. //---------------------------------------------------------------------------
  2244. void __fastcall TFTPFileSystem::HandleReplyStatus(AnsiString Response)
  2245. {
  2246. int Code;
  2247. if (FOnCaptureOutput != NULL)
  2248. {
  2249. FOnCaptureOutput(Response, false);
  2250. }
  2251. // Two forms of multiline responses were observed
  2252. // (the first is according to the RFC 959):
  2253. // 211-Features:
  2254. // MDTM
  2255. // REST STREAM
  2256. // SIZE
  2257. // 211 End
  2258. // 211-Features:
  2259. // 211-MDTM
  2260. // 211-REST STREAM
  2261. // 211-SIZE
  2262. // 211-AUTH TLS
  2263. // 211-PBSZ
  2264. // 211-PROT
  2265. // 211 End
  2266. bool HasCodePrefix =
  2267. (Response.Length() >= 3) &&
  2268. TryStrToInt(Response.SubString(1, 3), Code) &&
  2269. (Code >= 100) && (Code <= 599) &&
  2270. ((Response.Length() == 3) || (Response[4] == ' ') || (Response[4] == '-'));
  2271. if (HasCodePrefix && !FMultineResponse)
  2272. {
  2273. FMultineResponse = (Response.Length() >= 4) && (Response[4] == '-');
  2274. FLastResponse->Clear();
  2275. if (Response.Length() >= 5)
  2276. {
  2277. FLastResponse->Add(Response.SubString(5, Response.Length() - 4));
  2278. }
  2279. SetLastCode(Code);
  2280. }
  2281. else
  2282. {
  2283. int Start;
  2284. // response with code prefix
  2285. if (HasCodePrefix && (FLastCode == Code))
  2286. {
  2287. // End of multiline response?
  2288. if ((Response.Length() <= 3) || (Response[4] == ' '))
  2289. {
  2290. FMultineResponse = false;
  2291. }
  2292. Start = 5;
  2293. }
  2294. else
  2295. {
  2296. Start = (((Response.Length() >= 1) && (Response[1] == ' ')) ? 2 : 1);
  2297. }
  2298. // Intermediate empty lines are being added
  2299. if (FMultineResponse || (Response.Length() >= Start))
  2300. {
  2301. FLastResponse->Add(Response.SubString(Start, Response.Length() - Start + 1));
  2302. }
  2303. }
  2304. if (!FMultineResponse)
  2305. {
  2306. if (FLastCode == 220)
  2307. {
  2308. if (FTerminal->Configuration->ShowFtpWelcomeMessage)
  2309. {
  2310. FTerminal->DisplayBanner(FLastResponse->Text);
  2311. }
  2312. }
  2313. else if (FLastCommand == PASS)
  2314. {
  2315. // 530 = "Not logged in."
  2316. if (FLastCode == 530)
  2317. {
  2318. FPasswordFailed = true;
  2319. };
  2320. }
  2321. else if (FLastCommand == SYST)
  2322. {
  2323. assert(FSystem.IsEmpty());
  2324. // Possitive reply to "SYST" must be 215, see RFC 959
  2325. if (FLastCode == 215)
  2326. {
  2327. FSystem = FLastResponse->Text.TrimRight();
  2328. // full name is "Personal FTP Server PRO K6.0"
  2329. if ((FListAll == asAuto) &&
  2330. (FSystem.Pos("Personal FTP Server") > 0))
  2331. {
  2332. FTerminal->LogEvent("Server is known not to support LIST -a");
  2333. FListAll = asOff;
  2334. }
  2335. }
  2336. else
  2337. {
  2338. FSystem = "";
  2339. }
  2340. }
  2341. else if (FLastCommand == FEAT)
  2342. {
  2343. // Response to FEAT must be multiline, where leading and trailing line
  2344. // is "meaningless". See RFC 2389.
  2345. if ((FLastCode == 211) && (FLastResponse->Count > 2))
  2346. {
  2347. FLastResponse->Delete(0);
  2348. FLastResponse->Delete(FLastResponse->Count - 1);
  2349. FFeatures->Assign(FLastResponse);
  2350. }
  2351. else
  2352. {
  2353. FFeatures->Clear();
  2354. }
  2355. }
  2356. }
  2357. }
  2358. //---------------------------------------------------------------------------
  2359. AnsiString __fastcall TFTPFileSystem::ExtractStatusMessage(AnsiString Status)
  2360. {
  2361. // CApiLog::LogMessage
  2362. // (note that the formatting may not be present when LogMessageRaw is used)
  2363. int P1 = Status.Pos("): ");
  2364. if (P1 > 0)
  2365. {
  2366. int P2 = Status.Pos(".cpp(");
  2367. if ((P2 > 0) && (P2 < P1))
  2368. {
  2369. int P3 = Status.Pos(" caller=0x");
  2370. if ((P3 > 0) && (P3 > P1))
  2371. {
  2372. Status = Status.SubString(P1 + 3, P3 - P1 - 3);
  2373. }
  2374. }
  2375. }
  2376. return Status;
  2377. }
  2378. //---------------------------------------------------------------------------
  2379. bool __fastcall TFTPFileSystem::HandleStatus(const char * AStatus, int Type)
  2380. {
  2381. TLogLineType LogType = (TLogLineType)-1;
  2382. AnsiString Status(AStatus);
  2383. switch (Type)
  2384. {
  2385. case TFileZillaIntf::LOG_STATUS:
  2386. FTerminal->Information(Status, true);
  2387. LogType = llMessage;
  2388. break;
  2389. case TFileZillaIntf::LOG_COMMAND:
  2390. if (Status == "SYST")
  2391. {
  2392. FLastCommand = SYST;
  2393. }
  2394. else if (Status == "FEAT")
  2395. {
  2396. FLastCommand = FEAT;
  2397. }
  2398. else if (Status.SubString(1, 5) == "PASS ")
  2399. {
  2400. FLastCommand = PASS;
  2401. }
  2402. else
  2403. {
  2404. FLastCommand = CMD_UNKNOWN;
  2405. }
  2406. LogType = llInput;
  2407. break;
  2408. case TFileZillaIntf::LOG_ERROR:
  2409. case TFileZillaIntf::LOG_APIERROR:
  2410. case TFileZillaIntf::LOG_WARNING:
  2411. // when timeout message occurs, break loop waiting for response code
  2412. // by setting dummy one
  2413. if (Type == TFileZillaIntf::LOG_ERROR)
  2414. {
  2415. if (Status == FTimeoutStatus)
  2416. {
  2417. if (NoFinalLastCode())
  2418. {
  2419. SetLastCode(DummyTimeoutCode);
  2420. }
  2421. }
  2422. else if (Status == FDisconnectStatus)
  2423. {
  2424. if (NoFinalLastCode())
  2425. {
  2426. SetLastCode(DummyDisconnectCode);
  2427. }
  2428. }
  2429. }
  2430. // there can be multiple error messages associated with single failure
  2431. // (such as "cannot open local file..." followed by "download failed")
  2432. Status = ExtractStatusMessage(Status);
  2433. FLastError->Add(Status);
  2434. LogType = llMessage;
  2435. break;
  2436. case TFileZillaIntf::LOG_REPLY:
  2437. HandleReplyStatus(AStatus);
  2438. LogType = llOutput;
  2439. break;
  2440. case TFileZillaIntf::LOG_INFO:
  2441. Status = ExtractStatusMessage(Status);
  2442. LogType = llMessage;
  2443. break;
  2444. default:
  2445. assert(false);
  2446. break;
  2447. }
  2448. if (FTerminal->Log->Logging && (LogType != (TLogLineType)-1))
  2449. {
  2450. FTerminal->Log->Add(LogType, Status);
  2451. }
  2452. return true;
  2453. }
  2454. //---------------------------------------------------------------------------
  2455. TDateTime __fastcall TFTPFileSystem::ConvertLocalTimestamp(time_t Time)
  2456. {
  2457. // This reverses how FZAPI converts FILETIME to time_t,
  2458. // before passing it to FZ_ASYNCREQUEST_OVERWRITE.
  2459. __int64 Timestamp;
  2460. tm * Tm = localtime(&Time);
  2461. if (Tm != NULL)
  2462. {
  2463. SYSTEMTIME SystemTime;
  2464. SystemTime.wYear = static_cast<WORD>(Tm->tm_year + 1900);
  2465. SystemTime.wMonth = static_cast<WORD>(Tm->tm_mon + 1);
  2466. SystemTime.wDayOfWeek = 0;
  2467. SystemTime.wDay = static_cast<WORD>(Tm->tm_mday);
  2468. SystemTime.wHour = static_cast<WORD>(Tm->tm_hour);
  2469. SystemTime.wMinute = static_cast<WORD>(Tm->tm_min);
  2470. SystemTime.wSecond = static_cast<WORD>(Tm->tm_sec);
  2471. SystemTime.wMilliseconds = 0;
  2472. FILETIME LocalTime;
  2473. SystemTimeToFileTime(&SystemTime, &LocalTime);
  2474. FILETIME FileTime;
  2475. LocalFileTimeToFileTime(&LocalTime, &FileTime);
  2476. Timestamp = ConvertTimestampToUnixSafe(FileTime, dstmUnix);
  2477. }
  2478. else
  2479. {
  2480. // incorrect, but at least something
  2481. Timestamp = Time;
  2482. }
  2483. return UnixToDateTime(Timestamp, dstmUnix);
  2484. }
  2485. //---------------------------------------------------------------------------
  2486. TDateTime __fastcall TFTPFileSystem::ConvertRemoteTimestamp(time_t Time, bool HasTime)
  2487. {
  2488. TDateTime Result;
  2489. tm * Tm = localtime(&Time);
  2490. if (Tm != NULL)
  2491. {
  2492. // should be the same as HandleListData
  2493. Result = EncodeDateVerbose(
  2494. static_cast<unsigned short>(Tm->tm_year + 1900),
  2495. static_cast<unsigned short>(Tm->tm_mon + 1),
  2496. static_cast<unsigned short>(Tm->tm_mday));
  2497. if (HasTime)
  2498. {
  2499. Result += EncodeTimeVerbose(
  2500. static_cast<unsigned short>(Tm->tm_hour),
  2501. static_cast<unsigned short>(Tm->tm_min),
  2502. static_cast<unsigned short>(Tm->tm_sec), 0);
  2503. }
  2504. }
  2505. else
  2506. {
  2507. // incorrect, but at least something
  2508. Result = UnixToDateTime(Time, dstmUnix);
  2509. }
  2510. return Result;
  2511. }
  2512. //---------------------------------------------------------------------------
  2513. bool __fastcall TFTPFileSystem::HandleAsynchRequestOverwrite(
  2514. char * FileName1, size_t FileName1Len, const char * /*FileName2*/,
  2515. const char * /*Path1*/, const char * /*Path2*/,
  2516. __int64 Size1, __int64 Size2, time_t Time1, time_t Time2,
  2517. bool HasTime1, bool HasTime2, void * AUserData, int & RequestResult)
  2518. {
  2519. if (!FActive)
  2520. {
  2521. return false;
  2522. }
  2523. else
  2524. {
  2525. TFileTransferData & UserData = *((TFileTransferData *)AUserData);
  2526. if (UserData.OverwriteResult >= 0)
  2527. {
  2528. // on retry, use the same answer as on the first attempt
  2529. RequestResult = UserData.OverwriteResult;
  2530. }
  2531. else
  2532. {
  2533. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  2534. AnsiString FileName = FileName1;
  2535. assert(UserData.FileName == FileName);
  2536. TOverwriteMode OverwriteMode = omOverwrite;
  2537. TOverwriteFileParams FileParams;
  2538. bool NoFileParams =
  2539. (Size1 < 0) || (Time1 == 0) ||
  2540. (Size2 < 0) || (Time2 == 0);
  2541. if (!NoFileParams)
  2542. {
  2543. FileParams.SourceSize = Size2;
  2544. FileParams.DestSize = Size1;
  2545. if (OperationProgress->Side == osLocal)
  2546. {
  2547. FileParams.SourceTimestamp = ConvertLocalTimestamp(Time2);
  2548. FileParams.DestTimestamp = ConvertRemoteTimestamp(Time1, HasTime1);
  2549. FileParams.DestPrecision = (HasTime1 ? mfMDHM : mfMDY);
  2550. }
  2551. else
  2552. {
  2553. FileParams.SourceTimestamp = ConvertRemoteTimestamp(Time2, HasTime2);
  2554. FileParams.SourcePrecision = (HasTime2 ? mfMDHM : mfMDY);
  2555. FileParams.DestTimestamp = ConvertLocalTimestamp(Time1);
  2556. }
  2557. }
  2558. if (ConfirmOverwrite(FileName, OverwriteMode, OperationProgress,
  2559. (NoFileParams ? NULL : &FileParams), UserData.Params,
  2560. UserData.AutoResume && UserData.CopyParam->AllowResume(FileParams.SourceSize)))
  2561. {
  2562. switch (OverwriteMode)
  2563. {
  2564. case omOverwrite:
  2565. if (FileName != FileName1)
  2566. {
  2567. strncpy(FileName1, FileName.c_str(), FileName1Len);
  2568. FileName1[FileName1Len - 1] = '\0';
  2569. UserData.FileName = FileName1;
  2570. RequestResult = TFileZillaIntf::FILEEXISTS_RENAME;
  2571. }
  2572. else
  2573. {
  2574. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  2575. }
  2576. break;
  2577. case omResume:
  2578. RequestResult = TFileZillaIntf::FILEEXISTS_RESUME;
  2579. break;
  2580. default:
  2581. assert(false);
  2582. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  2583. break;
  2584. }
  2585. }
  2586. else
  2587. {
  2588. RequestResult = TFileZillaIntf::FILEEXISTS_SKIP;
  2589. }
  2590. }
  2591. // remember the answer for the retries
  2592. UserData.OverwriteResult = RequestResult;
  2593. if (RequestResult == TFileZillaIntf::FILEEXISTS_SKIP)
  2594. {
  2595. // when user chosses not to overwrite, break loop waiting for response code
  2596. // by setting dummy one, az FZAPI won't do anything then
  2597. SetLastCode(DummyTimeoutCode);
  2598. }
  2599. return true;
  2600. }
  2601. }
  2602. //---------------------------------------------------------------------------
  2603. struct TClipboardHandler
  2604. {
  2605. AnsiString Text;
  2606. void __fastcall Copy(TObject * /*Sender*/)
  2607. {
  2608. CopyToClipboard(Text);
  2609. }
  2610. };
  2611. //---------------------------------------------------------------------------
  2612. AnsiString __fastcall FormatContactList(AnsiString Entry1, AnsiString Entry2)
  2613. {
  2614. if (!Entry1.IsEmpty() && !Entry2.IsEmpty())
  2615. {
  2616. return FORMAT("%s, %s", (Entry1, Entry2));
  2617. }
  2618. else
  2619. {
  2620. return Entry1 + Entry2;
  2621. }
  2622. }
  2623. //---------------------------------------------------------------------------
  2624. AnsiString __fastcall FormatContact(const TFtpsCertificateData::TContact & Contact)
  2625. {
  2626. AnsiString Result =
  2627. FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 1),
  2628. (FormatContactList(FormatContactList(FormatContactList(
  2629. Contact.Organization, Contact.Unit), Contact.CommonName), Contact.Mail)));
  2630. if ((strlen(Contact.Country) > 0) ||
  2631. (strlen(Contact.StateProvince) > 0) ||
  2632. (strlen(Contact.Town) > 0))
  2633. {
  2634. Result +=
  2635. FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 2),
  2636. (FormatContactList(FormatContactList(
  2637. Contact.Country, Contact.StateProvince), Contact.Town)));
  2638. }
  2639. if (strlen(Contact.Other) > 0)
  2640. {
  2641. Result += FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 3), (Contact.Other));
  2642. }
  2643. return Result;
  2644. }
  2645. //---------------------------------------------------------------------------
  2646. AnsiString __fastcall FormatValidityTime(const TFtpsCertificateData::TValidityTime & ValidityTime)
  2647. {
  2648. return FormatDateTime("ddddd tt",
  2649. EncodeDateVerbose(
  2650. (unsigned short)ValidityTime.Year, (unsigned short)ValidityTime.Month,
  2651. (unsigned short)ValidityTime.Day) +
  2652. EncodeTimeVerbose(
  2653. (unsigned short)ValidityTime.Hour, (unsigned short)ValidityTime.Min,
  2654. (unsigned short)ValidityTime.Sec, 0));
  2655. }
  2656. //---------------------------------------------------------------------------
  2657. bool __fastcall TFTPFileSystem::HandleAsynchRequestVerifyCertificate(
  2658. const TFtpsCertificateData & Data, int & RequestResult)
  2659. {
  2660. if (!FActive)
  2661. {
  2662. return false;
  2663. }
  2664. else
  2665. {
  2666. FSessionInfo.CertificateFingerprint =
  2667. StrToHex(AnsiString((const char*)Data.Hash, Data.HashLen), false, ':');
  2668. int VerificationResultStr;
  2669. switch (Data.VerificationResult)
  2670. {
  2671. case X509_V_OK:
  2672. VerificationResultStr = CERT_OK;
  2673. break;
  2674. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
  2675. VerificationResultStr = CERT_ERR_UNABLE_TO_GET_ISSUER_CERT;
  2676. break;
  2677. case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
  2678. VerificationResultStr = CERT_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE;
  2679. break;
  2680. case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
  2681. VerificationResultStr = CERT_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
  2682. break;
  2683. case X509_V_ERR_CERT_SIGNATURE_FAILURE:
  2684. VerificationResultStr = CERT_ERR_CERT_SIGNATURE_FAILURE;
  2685. break;
  2686. case X509_V_ERR_CERT_NOT_YET_VALID:
  2687. VerificationResultStr = CERT_ERR_CERT_NOT_YET_VALID;
  2688. break;
  2689. case X509_V_ERR_CERT_HAS_EXPIRED:
  2690. VerificationResultStr = CERT_ERR_CERT_HAS_EXPIRED;
  2691. break;
  2692. case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
  2693. VerificationResultStr = CERT_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
  2694. break;
  2695. case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
  2696. VerificationResultStr = CERT_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
  2697. break;
  2698. case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
  2699. VerificationResultStr = CERT_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
  2700. break;
  2701. case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
  2702. VerificationResultStr = CERT_ERR_SELF_SIGNED_CERT_IN_CHAIN;
  2703. break;
  2704. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
  2705. VerificationResultStr = CERT_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
  2706. break;
  2707. case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
  2708. VerificationResultStr = CERT_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
  2709. break;
  2710. case X509_V_ERR_INVALID_CA:
  2711. VerificationResultStr = CERT_ERR_INVALID_CA;
  2712. break;
  2713. case X509_V_ERR_PATH_LENGTH_EXCEEDED:
  2714. VerificationResultStr = CERT_ERR_PATH_LENGTH_EXCEEDED;
  2715. break;
  2716. case X509_V_ERR_INVALID_PURPOSE:
  2717. VerificationResultStr = CERT_ERR_INVALID_PURPOSE;
  2718. break;
  2719. case X509_V_ERR_CERT_UNTRUSTED:
  2720. VerificationResultStr = CERT_ERR_CERT_UNTRUSTED;
  2721. break;
  2722. case X509_V_ERR_CERT_REJECTED:
  2723. VerificationResultStr = CERT_ERR_CERT_REJECTED;
  2724. break;
  2725. case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
  2726. VerificationResultStr = CERT_ERR_KEYUSAGE_NO_CERTSIGN;
  2727. break;
  2728. case X509_V_ERR_CERT_CHAIN_TOO_LONG:
  2729. VerificationResultStr = CERT_ERR_CERT_CHAIN_TOO_LONG;
  2730. break;
  2731. default:
  2732. VerificationResultStr = CERT_ERR_UNKNOWN;
  2733. break;
  2734. }
  2735. AnsiString Summary = LoadStr(VerificationResultStr);
  2736. if (Data.VerificationResult != X509_V_OK)
  2737. {
  2738. Summary += " " + FMTLOAD(CERT_ERRDEPTH, (Data.VerificationDepth + 1));
  2739. }
  2740. FSessionInfo.Certificate =
  2741. FMTLOAD(CERT_TEXT, (
  2742. FormatContact(Data.Subject),
  2743. FormatContact(Data.Issuer),
  2744. FormatValidityTime(Data.ValidFrom),
  2745. FormatValidityTime(Data.ValidUntil),
  2746. FSessionInfo.CertificateFingerprint,
  2747. Summary));
  2748. RequestResult = 0;
  2749. THierarchicalStorage * Storage =
  2750. FTerminal->Configuration->CreateScpStorage(false);
  2751. try
  2752. {
  2753. Storage->AccessMode = smRead;
  2754. if (Storage->OpenSubKey(CertificateStorageKey, false) &&
  2755. Storage->ValueExists(FSessionInfo.CertificateFingerprint))
  2756. {
  2757. RequestResult = 1;
  2758. }
  2759. }
  2760. __finally
  2761. {
  2762. delete Storage;
  2763. }
  2764. if (RequestResult == 0)
  2765. {
  2766. AnsiString Buf = FTerminal->SessionData->HostKey;
  2767. while ((RequestResult == 0) && !Buf.IsEmpty())
  2768. {
  2769. AnsiString ExpectedKey = CutToChar(Buf, ';', false);
  2770. if (ExpectedKey == FSessionInfo.CertificateFingerprint)
  2771. {
  2772. RequestResult = 1;
  2773. }
  2774. }
  2775. }
  2776. if (RequestResult == 0)
  2777. {
  2778. TClipboardHandler ClipboardHandler;
  2779. ClipboardHandler.Text = FSessionInfo.CertificateFingerprint;
  2780. TQueryButtonAlias Aliases[1];
  2781. Aliases[0].Button = qaRetry;
  2782. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  2783. Aliases[0].OnClick = &ClipboardHandler.Copy;
  2784. TQueryParams Params;
  2785. Params.HelpKeyword = HELP_VERIFY_CERTIFICATE;
  2786. Params.NoBatchAnswers = qaYes | qaRetry;
  2787. Params.Aliases = Aliases;
  2788. Params.AliasesCount = LENOF(Aliases);
  2789. int Answer = FTerminal->QueryUser(
  2790. FMTLOAD(VERIFY_CERT_PROMPT2, (FSessionInfo.Certificate)),
  2791. NULL, qaYes | qaNo | qaCancel | qaRetry, &Params, qtWarning);
  2792. switch (Answer)
  2793. {
  2794. case qaYes:
  2795. // 2 = always, as used by FZ's VerifyCertDlg.cpp,
  2796. // however FZAPI takes all non-zero values equally
  2797. RequestResult = 2;
  2798. break;
  2799. case qaNo:
  2800. RequestResult = 1;
  2801. break;
  2802. case qaCancel:
  2803. RequestResult = 0;
  2804. break;
  2805. default:
  2806. assert(false);
  2807. RequestResult = 0;
  2808. break;
  2809. }
  2810. if (RequestResult == 2)
  2811. {
  2812. THierarchicalStorage * Storage =
  2813. FTerminal->Configuration->CreateScpStorage(false);
  2814. try
  2815. {
  2816. Storage->AccessMode = smReadWrite;
  2817. if (Storage->OpenSubKey(CertificateStorageKey, true))
  2818. {
  2819. Storage->WriteString(FSessionInfo.CertificateFingerprint, "");
  2820. }
  2821. }
  2822. __finally
  2823. {
  2824. delete Storage;
  2825. }
  2826. }
  2827. }
  2828. return true;
  2829. }
  2830. }
  2831. //---------------------------------------------------------------------------
  2832. bool __fastcall TFTPFileSystem::HandleListData(const char * Path,
  2833. const TListDataEntry * Entries, unsigned int Count)
  2834. {
  2835. if (!FActive)
  2836. {
  2837. return false;
  2838. }
  2839. else if (FIgnoreFileList)
  2840. {
  2841. // directory listing provided implicitly by FZAPI during certain operations is ignored
  2842. assert(FFileList == NULL);
  2843. return false;
  2844. }
  2845. else
  2846. {
  2847. assert(FFileList != NULL);
  2848. // this can actually fail in real life,
  2849. // when connected to server with case insensitive paths
  2850. assert(UnixComparePaths(AbsolutePath(FFileList->Directory, false), Path));
  2851. USEDPARAM(Path);
  2852. for (unsigned int Index = 0; Index < Count; Index++)
  2853. {
  2854. const TListDataEntry * Entry = &Entries[Index];
  2855. TRemoteFile * File = new TRemoteFile();
  2856. try
  2857. {
  2858. File->Terminal = FTerminal;
  2859. File->FileName = Entry->Name;
  2860. if (strlen(Entry->Permissions) >= 10)
  2861. {
  2862. try
  2863. {
  2864. File->Rights->Text = Entry->Permissions + 1;
  2865. }
  2866. catch(...)
  2867. {
  2868. // ignore permissions errors with FTP
  2869. }
  2870. }
  2871. const char * Space = strchr(Entry->OwnerGroup, ' ');
  2872. if (Space != NULL)
  2873. {
  2874. File->Owner.Name = AnsiString(Entry->OwnerGroup, Space - Entry->OwnerGroup);
  2875. File->Group.Name = Space + 1;
  2876. }
  2877. else
  2878. {
  2879. File->Owner.Name = Entry->OwnerGroup;
  2880. }
  2881. File->Size = Entry->Size;
  2882. if (Entry->Link)
  2883. {
  2884. File->Type = FILETYPE_SYMLINK;
  2885. }
  2886. else if (Entry->Dir)
  2887. {
  2888. File->Type = FILETYPE_DIRECTORY;
  2889. }
  2890. else
  2891. {
  2892. File->Type = '-';
  2893. }
  2894. // ModificationFmt must be set after Modification
  2895. if (Entry->HasDate)
  2896. {
  2897. // should be the same as ConvertRemoteTimestamp
  2898. TDateTime Modification =
  2899. EncodeDateVerbose((unsigned short)Entry->Year, (unsigned short)Entry->Month,
  2900. (unsigned short)Entry->Day);
  2901. if (Entry->HasTime)
  2902. {
  2903. File->Modification = Modification +
  2904. EncodeTimeVerbose((unsigned short)Entry->Hour, (unsigned short)Entry->Minute, 0, 0);
  2905. // not exact as we got year as well, but it is most probably
  2906. // guessed by FZAPI anyway
  2907. File->ModificationFmt = mfMDHM;
  2908. }
  2909. else
  2910. {
  2911. File->Modification = Modification;
  2912. File->ModificationFmt = mfMDY;
  2913. }
  2914. }
  2915. else
  2916. {
  2917. // With SCP we estimate date to be today, if we have at least time
  2918. File->Modification = double(0);
  2919. File->ModificationFmt = mfNone;
  2920. }
  2921. File->LastAccess = File->Modification;
  2922. File->LinkTo = Entry->LinkTarget;
  2923. File->Complete();
  2924. }
  2925. catch (Exception & E)
  2926. {
  2927. delete File;
  2928. AnsiString EntryData =
  2929. FORMAT("%s/%s/%s/%s/%d/%d/%d/%d/%d/%d/%d/%d/%d",
  2930. (Entry->Name, Entry->Permissions, Entry->OwnerGroup, IntToStr(Entry->Size),
  2931. int(Entry->Dir), int(Entry->Link), Entry->Year, Entry->Month, Entry->Day,
  2932. Entry->Hour, Entry->Minute, int(Entry->HasTime), int(Entry->HasDate)));
  2933. throw ETerminal(&E, FMTLOAD(LIST_LINE_ERROR, (EntryData)));
  2934. }
  2935. FFileList->AddFile(File);
  2936. }
  2937. return true;
  2938. }
  2939. }
  2940. //---------------------------------------------------------------------------
  2941. bool __fastcall TFTPFileSystem::HandleTransferStatus(bool Valid, __int64 TransferSize,
  2942. __int64 Bytes, int /*Percent*/, int /*TimeElapsed*/, int /*TimeLeft*/, int /*TransferRate*/,
  2943. bool FileTransfer)
  2944. {
  2945. if (!FActive)
  2946. {
  2947. return false;
  2948. }
  2949. else if (!Valid)
  2950. {
  2951. }
  2952. else if (FileTransfer)
  2953. {
  2954. FileTransferProgress(TransferSize, Bytes);
  2955. }
  2956. else
  2957. {
  2958. ReadDirectoryProgress(Bytes);
  2959. }
  2960. return true;
  2961. }
  2962. //---------------------------------------------------------------------------
  2963. bool __fastcall TFTPFileSystem::HandleReply(int Command, unsigned int Reply)
  2964. {
  2965. if (!FActive)
  2966. {
  2967. return false;
  2968. }
  2969. else
  2970. {
  2971. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  2972. {
  2973. FTerminal->LogEvent(FORMAT("Got reply %x to the command %d", (int(Reply), Command)));
  2974. }
  2975. // reply with Command 0 is not associated with current operation
  2976. // so do not treat is as a reply
  2977. // (it is typically used asynchronously to notify about disconnects)
  2978. if (Command != 0)
  2979. {
  2980. assert(FCommandReply == 0);
  2981. FCommandReply = Reply;
  2982. }
  2983. else
  2984. {
  2985. assert(FReply == 0);
  2986. FReply = Reply;
  2987. }
  2988. return true;
  2989. }
  2990. }
  2991. //---------------------------------------------------------------------------
  2992. bool __fastcall TFTPFileSystem::HandleCapabilities(bool Mfmt)
  2993. {
  2994. FMfmt = Mfmt;
  2995. FFileSystemInfoValid = false;
  2996. return true;
  2997. }
  2998. //---------------------------------------------------------------------------
  2999. bool __fastcall TFTPFileSystem::CheckError(int ReturnCode, const char * Context)
  3000. {
  3001. // we do not expect any FZAPI call to fail as it generally can fail only due to:
  3002. // - invalid paramerers
  3003. // - busy FZAPI core
  3004. // the only exception is REPLY_NOTCONNECTED that can happen if
  3005. // connection is closed just between the last call to Idle()
  3006. // and call to any FZAPI command
  3007. // in such case reply without associated command is posted,
  3008. // which we are going to wait for unless we are already waiting
  3009. // on higher level (this typically happens if connection is lost while
  3010. // waiting for user interaction and is detected within call to
  3011. // SetAsyncRequestResult)
  3012. if (FLAGSET(ReturnCode, TFileZillaIntf::REPLY_NOTCONNECTED))
  3013. {
  3014. if (!FWaitingForReply)
  3015. {
  3016. // throws
  3017. WaitForFatalNonCommandReply();
  3018. }
  3019. }
  3020. else
  3021. {
  3022. FTerminal->FatalError(NULL,
  3023. FMTLOAD(INTERNAL_ERROR, (FORMAT("fz#%s", (Context)), IntToHex(ReturnCode, 4))));
  3024. assert(false);
  3025. }
  3026. return false;
  3027. }
  3028. //---------------------------------------------------------------------------
  3029. bool __fastcall TFTPFileSystem::Unquote(AnsiString & Str)
  3030. {
  3031. enum
  3032. {
  3033. INIT,
  3034. QUOTE,
  3035. QUOTED,
  3036. DONE
  3037. } State;
  3038. State = INIT;
  3039. assert((Str.Length() > 0) && ((Str[1] == '"') || (Str[1] == '\'')));
  3040. int Index = 1;
  3041. char Quote;
  3042. while (Index <= Str.Length())
  3043. {
  3044. switch (State)
  3045. {
  3046. case INIT:
  3047. if ((Str[Index] == '"') || (Str[Index] == '\''))
  3048. {
  3049. Quote = Str[Index];
  3050. State = QUOTED;
  3051. Str.Delete(Index, 1);
  3052. }
  3053. else
  3054. {
  3055. assert(false);
  3056. // no quoted string
  3057. Str.SetLength(0);
  3058. }
  3059. break;
  3060. case QUOTED:
  3061. if (Str[Index] == Quote)
  3062. {
  3063. State = QUOTE;
  3064. Str.Delete(Index, 1);
  3065. }
  3066. else
  3067. {
  3068. Index++;
  3069. }
  3070. break;
  3071. case QUOTE:
  3072. if (Str[Index] == Quote)
  3073. {
  3074. Index++;
  3075. }
  3076. else
  3077. {
  3078. // end of quoted string, trim the rest
  3079. Str.SetLength(Index - 1);
  3080. State = DONE;
  3081. }
  3082. break;
  3083. }
  3084. }
  3085. return (State == DONE);
  3086. }
  3087. //---------------------------------------------------------------------------
  3088. #endif NO_FILEZILLA