FtpFileSystem.cpp 110 KB

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