FtpFileSystem.cpp 110 KB

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