FtpFileSystem.cpp 142 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. //---------------------------------------------------------------------------
  5. #include <list>
  6. #define MPEXT
  7. #include "FtpFileSystem.h"
  8. #include "FileZillaIntf.h"
  9. #include "Common.h"
  10. #include "Exceptions.h"
  11. #include "Terminal.h"
  12. #include "TextsCore.h"
  13. #include "TextsFileZilla.h"
  14. #include "HelpCore.h"
  15. #include "Security.h"
  16. #include <StrUtils.hpp>
  17. #include <DateUtils.hpp>
  18. #include <openssl/x509_vfy.h>
  19. //---------------------------------------------------------------------------
  20. #pragma package(smart_init)
  21. //---------------------------------------------------------------------------
  22. #define FILE_OPERATION_LOOP_TERMINAL FTerminal
  23. //---------------------------------------------------------------------------
  24. const int DummyCodeClass = 8;
  25. const int DummyTimeoutCode = 801;
  26. const int DummyCancelCode = 802;
  27. const int DummyDisconnectCode = 803;
  28. //---------------------------------------------------------------------------
  29. class TFileZillaImpl : public TFileZillaIntf
  30. {
  31. public:
  32. __fastcall TFileZillaImpl(TFTPFileSystem * FileSystem);
  33. virtual const wchar_t * __fastcall Option(int OptionID) const;
  34. virtual int __fastcall OptionVal(int OptionID) const;
  35. protected:
  36. virtual bool __fastcall DoPostMessage(TMessageType Type, WPARAM wParam, LPARAM lParam);
  37. virtual bool __fastcall HandleStatus(const wchar_t * Status, int Type);
  38. virtual bool __fastcall HandleAsynchRequestOverwrite(
  39. wchar_t * FileName1, size_t FileName1Len, const wchar_t * FileName2,
  40. const wchar_t * Path1, const wchar_t * Path2,
  41. __int64 Size1, __int64 Size2, time_t LocalTime,
  42. bool HasLocalTime, const TRemoteFileTime & RemoteTime, void * UserData, int & RequestResult);
  43. virtual bool __fastcall HandleAsynchRequestVerifyCertificate(
  44. const TFtpsCertificateData & Data, int & RequestResult);
  45. virtual bool __fastcall HandleAsynchRequestNeedPass(
  46. struct TNeedPassRequestData & Data, int & RequestResult);
  47. virtual bool __fastcall HandleListData(const wchar_t * Path, const TListDataEntry * Entries,
  48. unsigned int Count);
  49. virtual bool __fastcall HandleTransferStatus(bool Valid, __int64 TransferSize,
  50. __int64 Bytes, bool FileTransfer);
  51. virtual bool __fastcall HandleReply(int Command, unsigned int Reply);
  52. virtual bool __fastcall HandleCapabilities(TFTPServerCapabilities * ServerCapabilities);
  53. virtual bool __fastcall CheckError(int ReturnCode, const wchar_t * Context);
  54. virtual void PreserveDownloadFileTime(HANDLE Handle, void * UserData);
  55. virtual bool GetFileModificationTimeInUtc(const wchar_t * FileName, struct tm & Time);
  56. virtual wchar_t * LastSysErrorMessage();
  57. virtual std::wstring GetClientString();
  58. private:
  59. TFTPFileSystem * FFileSystem;
  60. };
  61. //---------------------------------------------------------------------------
  62. __fastcall TFileZillaImpl::TFileZillaImpl(TFTPFileSystem * FileSystem) :
  63. TFileZillaIntf(),
  64. FFileSystem(FileSystem)
  65. {
  66. }
  67. //---------------------------------------------------------------------------
  68. const wchar_t * __fastcall TFileZillaImpl::Option(int OptionID) const
  69. {
  70. return FFileSystem->GetOption(OptionID);
  71. }
  72. //---------------------------------------------------------------------------
  73. int __fastcall TFileZillaImpl::OptionVal(int OptionID) const
  74. {
  75. return FFileSystem->GetOptionVal(OptionID);
  76. }
  77. //---------------------------------------------------------------------------
  78. bool __fastcall TFileZillaImpl::DoPostMessage(TMessageType Type, WPARAM wParam, LPARAM lParam)
  79. {
  80. return FFileSystem->PostMessage(Type, wParam, lParam);
  81. }
  82. //---------------------------------------------------------------------------
  83. bool __fastcall TFileZillaImpl::HandleStatus(const wchar_t * Status, int Type)
  84. {
  85. return FFileSystem->HandleStatus(Status, Type);
  86. }
  87. //---------------------------------------------------------------------------
  88. bool __fastcall TFileZillaImpl::HandleAsynchRequestOverwrite(
  89. wchar_t * FileName1, size_t FileName1Len, const wchar_t * FileName2,
  90. const wchar_t * Path1, const wchar_t * Path2,
  91. __int64 Size1, __int64 Size2, time_t LocalTime,
  92. bool HasLocalTime, const TRemoteFileTime & RemoteTime, void * UserData, int & RequestResult)
  93. {
  94. return FFileSystem->HandleAsynchRequestOverwrite(
  95. FileName1, FileName1Len, FileName2, Path1, Path2, Size1, Size2, LocalTime,
  96. HasLocalTime, RemoteTime, UserData, RequestResult);
  97. }
  98. //---------------------------------------------------------------------------
  99. bool __fastcall TFileZillaImpl::HandleAsynchRequestVerifyCertificate(
  100. const TFtpsCertificateData & Data, int & RequestResult)
  101. {
  102. return FFileSystem->HandleAsynchRequestVerifyCertificate(Data, RequestResult);
  103. }
  104. //---------------------------------------------------------------------------
  105. bool __fastcall TFileZillaImpl::HandleAsynchRequestNeedPass(
  106. struct TNeedPassRequestData & Data, int & RequestResult)
  107. {
  108. return FFileSystem->HandleAsynchRequestNeedPass(Data, RequestResult);
  109. }
  110. //---------------------------------------------------------------------------
  111. bool __fastcall TFileZillaImpl::HandleListData(const wchar_t * Path,
  112. const TListDataEntry * Entries, unsigned int Count)
  113. {
  114. return FFileSystem->HandleListData(Path, Entries, Count);
  115. }
  116. //---------------------------------------------------------------------------
  117. bool __fastcall TFileZillaImpl::HandleTransferStatus(bool Valid, __int64 TransferSize,
  118. __int64 Bytes, bool FileTransfer)
  119. {
  120. return FFileSystem->HandleTransferStatus(Valid, TransferSize, Bytes, FileTransfer);
  121. }
  122. //---------------------------------------------------------------------------
  123. bool __fastcall TFileZillaImpl::HandleReply(int Command, unsigned int Reply)
  124. {
  125. return FFileSystem->HandleReply(Command, Reply);
  126. }
  127. //---------------------------------------------------------------------------
  128. bool __fastcall TFileZillaImpl::HandleCapabilities(TFTPServerCapabilities * ServerCapabilities)
  129. {
  130. return FFileSystem->HandleCapabilities(ServerCapabilities);
  131. }
  132. //---------------------------------------------------------------------------
  133. bool __fastcall TFileZillaImpl::CheckError(int ReturnCode, const wchar_t * Context)
  134. {
  135. return FFileSystem->CheckError(ReturnCode, Context);
  136. }
  137. //---------------------------------------------------------------------------
  138. void TFileZillaImpl::PreserveDownloadFileTime(HANDLE Handle, void * UserData)
  139. {
  140. return FFileSystem->PreserveDownloadFileTime(Handle, UserData);
  141. }
  142. //---------------------------------------------------------------------------
  143. bool TFileZillaImpl::GetFileModificationTimeInUtc(const wchar_t * FileName, struct tm & Time)
  144. {
  145. return FFileSystem->GetFileModificationTimeInUtc(FileName, Time);
  146. }
  147. //---------------------------------------------------------------------------
  148. wchar_t * TFileZillaImpl::LastSysErrorMessage()
  149. {
  150. return _wcsdup(::LastSysErrorMessage().c_str());
  151. }
  152. //---------------------------------------------------------------------------
  153. std::wstring TFileZillaImpl::GetClientString()
  154. {
  155. return std::wstring(SshVersionString().c_str());
  156. }
  157. //---------------------------------------------------------------------------
  158. //---------------------------------------------------------------------------
  159. class TMessageQueue : public std::list<std::pair<WPARAM, LPARAM> >
  160. {
  161. };
  162. //---------------------------------------------------------------------------
  163. //---------------------------------------------------------------------------
  164. struct TFileTransferData
  165. {
  166. TFileTransferData()
  167. {
  168. Params = 0;
  169. AutoResume = false;
  170. OverwriteResult = -1;
  171. CopyParam = NULL;
  172. }
  173. UnicodeString FileName;
  174. int Params;
  175. bool AutoResume;
  176. int OverwriteResult;
  177. const TCopyParamType * CopyParam;
  178. TDateTime Modification;
  179. };
  180. //---------------------------------------------------------------------------
  181. const UnicodeString SiteCommand(L"SITE");
  182. const UnicodeString SymlinkSiteCommand(L"SYMLINK");
  183. const UnicodeString CopySiteCommand(L"COPY");
  184. const UnicodeString HashCommand(L"HASH"); // Cerberos + FileZilla servers
  185. const UnicodeString AvblCommand(L"AVBL");
  186. const UnicodeString XQuotaCommand(L"XQUOTA");
  187. const UnicodeString DirectoryHasBytesPrefix(L"226-Directory has");
  188. //---------------------------------------------------------------------------
  189. class TFileListHelper
  190. {
  191. public:
  192. TFileListHelper(TFTPFileSystem * FileSystem, TRemoteFileList * FileList,
  193. bool IgnoreFileList) :
  194. FFileSystem(FileSystem),
  195. FFileList(FFileSystem->FFileList),
  196. FIgnoreFileList(FFileSystem->FIgnoreFileList)
  197. {
  198. FFileSystem->FFileList = FileList;
  199. FFileSystem->FIgnoreFileList = IgnoreFileList;
  200. }
  201. ~TFileListHelper()
  202. {
  203. FFileSystem->FFileList = FFileList;
  204. FFileSystem->FIgnoreFileList = FIgnoreFileList;
  205. }
  206. private:
  207. TFTPFileSystem * FFileSystem;
  208. TRemoteFileList * FFileList;
  209. bool FIgnoreFileList;
  210. };
  211. //---------------------------------------------------------------------------
  212. __fastcall TFTPFileSystem::TFTPFileSystem(TTerminal * ATerminal):
  213. TCustomFileSystem(ATerminal),
  214. FFileZillaIntf(NULL),
  215. FQueueCriticalSection(new TCriticalSection),
  216. FTransferStatusCriticalSection(new TCriticalSection),
  217. FQueueEvent(CreateEvent(NULL, true, false, NULL)),
  218. FQueue(new TMessageQueue),
  219. FReply(0),
  220. FCommandReply(0),
  221. FLastCommand(CMD_UNKNOWN),
  222. FLastResponse(new TStringList()),
  223. FLastErrorResponse(new TStringList()),
  224. FLastError(new TStringList()),
  225. FFeatures(new TStringList()),
  226. FFileList(NULL),
  227. FFileListCache(NULL),
  228. FActive(false),
  229. FOpening(false),
  230. FWaitingForReply(false),
  231. FIgnoreFileList(false),
  232. FOnCaptureOutput(NULL),
  233. FFileSystemInfoValid(false),
  234. FDoListAll(false),
  235. FServerCapabilities(NULL),
  236. FReadCurrentDirectory(false)
  237. {
  238. ResetReply();
  239. FListAll = FTerminal->SessionData->FtpListAll;
  240. FFileSystemInfo.ProtocolBaseName = L"FTP";
  241. FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
  242. FTimeoutStatus = LoadStr(IDS_ERRORMSG_TIMEOUT);
  243. FDisconnectStatus = LoadStr(IDS_STATUSMSG_DISCONNECTED);
  244. FServerCapabilities = new TFTPServerCapabilities();
  245. FHashAlgs.reset(new TStringList());
  246. FSupportedCommands.reset(CreateSortedStringList());
  247. FSupportedSiteCommands.reset(CreateSortedStringList());
  248. FCertificate = NULL;
  249. FPrivateKey = NULL;
  250. FBytesAvailable = -1;
  251. FBytesAvailableSuppoted = false;
  252. FLoggedIn = false;
  253. FChecksumAlgs.reset(new TStringList());
  254. FChecksumCommands.reset(new TStringList());
  255. RegisterChecksumAlgCommand(Sha1ChecksumAlg, L"XSHA1"); // e.g. Cerberos FTP
  256. RegisterChecksumAlgCommand(Sha256ChecksumAlg, L"XSHA256"); // e.g. Cerberos FTP
  257. RegisterChecksumAlgCommand(Sha512ChecksumAlg, L"XSHA512"); // e.g. Cerberos FTP
  258. RegisterChecksumAlgCommand(Md5ChecksumAlg, L"XMD5"); // e.g. Cerberos FTP
  259. RegisterChecksumAlgCommand(Md5ChecksumAlg, L"MD5"); // e.g. Apache FTP
  260. RegisterChecksumAlgCommand(Crc32ChecksumAlg, L"XCRC"); // e.g. Cerberos FTP
  261. }
  262. //---------------------------------------------------------------------------
  263. __fastcall TFTPFileSystem::~TFTPFileSystem()
  264. {
  265. DebugAssert(FFileList == NULL);
  266. FFileZillaIntf->Destroying();
  267. // to release memory associated with the messages
  268. DiscardMessages();
  269. delete FFileZillaIntf;
  270. FFileZillaIntf = NULL;
  271. delete FQueue;
  272. FQueue = NULL;
  273. CloseHandle(FQueueEvent);
  274. delete FQueueCriticalSection;
  275. FQueueCriticalSection = NULL;
  276. delete FTransferStatusCriticalSection;
  277. FTransferStatusCriticalSection = NULL;
  278. delete FLastResponse;
  279. FLastResponse = NULL;
  280. delete FLastErrorResponse;
  281. FLastErrorResponse = NULL;
  282. delete FLastError;
  283. FLastError = NULL;
  284. delete FFeatures;
  285. FFeatures = NULL;
  286. delete FServerCapabilities;
  287. FServerCapabilities = NULL;
  288. ResetCaches();
  289. }
  290. //---------------------------------------------------------------------------
  291. void __fastcall TFTPFileSystem::Open()
  292. {
  293. // on reconnect, typically there may be pending status messages from previous session
  294. DiscardMessages();
  295. ResetCaches();
  296. FReadCurrentDirectory = true;
  297. FHomeDirectory = L"";
  298. FLoggedIn = false;
  299. FLastDataSent = Now();
  300. FMultineResponse = false;
  301. // initialize FZAPI on the first connect only
  302. if (FFileZillaIntf == NULL)
  303. {
  304. FFileZillaIntf = new TFileZillaImpl(this);
  305. try
  306. {
  307. TFileZillaIntf::TLogLevel LogLevel;
  308. switch (FTerminal->Configuration->ActualLogProtocol)
  309. {
  310. default:
  311. case -1:
  312. LogLevel = TFileZillaIntf::LOG_WARNING;
  313. break;
  314. case 0:
  315. case 1:
  316. LogLevel = TFileZillaIntf::LOG_PROGRESS;
  317. break;
  318. case 2:
  319. LogLevel = TFileZillaIntf::LOG_INFO;
  320. break;
  321. }
  322. FFileZillaIntf->SetDebugLevel(LogLevel);
  323. FFileZillaIntf->Init();
  324. }
  325. catch(...)
  326. {
  327. delete FFileZillaIntf;
  328. FFileZillaIntf = NULL;
  329. throw;
  330. }
  331. }
  332. TSessionData * Data = FTerminal->SessionData;
  333. FWindowsServer = false;
  334. FMVS = false;
  335. FVMS = false;
  336. FTransferActiveImmediately = (Data->FtpTransferActiveImmediately == asOn);
  337. FSessionInfo.LoginTime = Now();
  338. FSessionInfo.CertificateVerifiedManually = false;
  339. UnicodeString HostName = Data->HostNameExpanded;
  340. UnicodeString UserName = Data->UserNameExpanded;
  341. UnicodeString Password = NormalizeString(Data->Password);
  342. UnicodeString Account = Data->FtpAccount;
  343. UnicodeString Path = Data->RemoteDirectory;
  344. int ServerType;
  345. switch (Data->Ftps)
  346. {
  347. case ftpsNone:
  348. ServerType = TFileZillaIntf::SERVER_FTP;
  349. break;
  350. case ftpsImplicit:
  351. ServerType = TFileZillaIntf::SERVER_FTP_SSL_IMPLICIT;
  352. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_IMPLICIT);
  353. break;
  354. case ftpsExplicitSsl:
  355. ServerType = TFileZillaIntf::SERVER_FTP_SSL_EXPLICIT;
  356. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_EXPLICIT);
  357. break;
  358. case ftpsExplicitTls:
  359. ServerType = TFileZillaIntf::SERVER_FTP_TLS_EXPLICIT;
  360. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_EXPLICIT);
  361. break;
  362. default:
  363. DebugFail();
  364. break;
  365. }
  366. int Pasv = (Data->FtpPasvMode ? 1 : 2);
  367. int TimeZoneOffset = Data->TimeDifferenceAuto ? 0 : TimeToMinutes(Data->TimeDifference);
  368. int UTF8 = 0;
  369. switch (Data->NotUtf)
  370. {
  371. case asOn:
  372. UTF8 = 2;
  373. break;
  374. case asOff:
  375. UTF8 = 1;
  376. break;
  377. case asAuto:
  378. UTF8 = 0;
  379. break;
  380. }
  381. FPasswordFailed = false;
  382. FStoredPasswordTried = false;
  383. bool PromptedForCredentials = false;
  384. do
  385. {
  386. FDetectTimeDifference = Data->TimeDifferenceAuto;
  387. FTimeDifference = 0;
  388. ResetFeatures();
  389. FSystem = L"";
  390. FWelcomeMessage = L"";
  391. FFileSystemInfoValid = false;
  392. // TODO: the same for account? it ever used?
  393. // ask for username if it was not specified in advance, even on retry,
  394. // but keep previous one as default,
  395. if (Data->UserNameExpanded.IsEmpty() && !FTerminal->SessionData->FingerprintScan)
  396. {
  397. FTerminal->LogEvent(L"Username prompt (no username provided)");
  398. if (!PromptedForCredentials)
  399. {
  400. FTerminal->Information(LoadStr(FTP_CREDENTIAL_PROMPT), false);
  401. PromptedForCredentials = true;
  402. }
  403. if (!FTerminal->PromptUser(Data, pkUserName, LoadStr(USERNAME_TITLE), L"",
  404. LoadStr(USERNAME_PROMPT2), true, 0, UserName))
  405. {
  406. FTerminal->FatalError(NULL, LoadStr(AUTHENTICATION_FAILED));
  407. }
  408. else
  409. {
  410. FUserName = UserName;
  411. }
  412. }
  413. // On retry ask for password.
  414. // This is particularly important, when stored password is no longer valid,
  415. // so we do not blindly try keep trying it in a loop (possibly causing account lockout)
  416. if (FPasswordFailed)
  417. {
  418. FTerminal->LogEvent(L"Password prompt (last login attempt failed)");
  419. Password = L"";
  420. if (!FTerminal->PromptUser(Data, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  421. LoadStr(PASSWORD_PROMPT), false, 0, Password))
  422. {
  423. FTerminal->FatalError(NULL, LoadStr(AUTHENTICATION_FAILED));
  424. }
  425. }
  426. if ((Data->Ftps != ftpsNone) && (FCertificate == NULL))
  427. {
  428. FTerminal->LoadTlsCertificate(FCertificate, FPrivateKey);
  429. }
  430. FPasswordFailed = false;
  431. TAutoFlag OpeningFlag(FOpening);
  432. FActive = FFileZillaIntf->Connect(
  433. HostName.c_str(), Data->PortNumber, UserName.c_str(),
  434. Password.c_str(), Account.c_str(), Path.c_str(),
  435. ServerType, Pasv, TimeZoneOffset, UTF8, Data->FtpForcePasvIp,
  436. Data->FtpUseMlsd, FCertificate, FPrivateKey);
  437. DebugAssert(FActive);
  438. try
  439. {
  440. // do not wait for FTP response code as Connect is complex operation
  441. GotReply(WaitForCommandReply(false), REPLY_CONNECT, LoadStr(CONNECTION_FAILED));
  442. Shred(Password);
  443. // we have passed, even if we got 530 on the way (if it is possible at all),
  444. // ignore it
  445. DebugAssert(!FPasswordFailed);
  446. FPasswordFailed = false;
  447. }
  448. catch(...)
  449. {
  450. if (FPasswordFailed)
  451. {
  452. FTerminal->Information(LoadStr(FTP_ACCESS_DENIED), false);
  453. }
  454. else
  455. {
  456. // see handling of REPLY_CONNECT in GotReply
  457. FTerminal->Closed();
  458. throw;
  459. }
  460. }
  461. }
  462. while (FPasswordFailed);
  463. // see also TWebDAVFileSystem::CollectTLSSessionInfo()
  464. FSessionInfo.CSCipher = FFileZillaIntf->GetCipherName().c_str();
  465. FSessionInfo.SCCipher = FSessionInfo.CSCipher;
  466. UnicodeString TlsVersionStr = FFileZillaIntf->GetTlsVersionStr().c_str();
  467. AddToList(FSessionInfo.SecurityProtocolName, TlsVersionStr, L", ");
  468. FLoggedIn = true;
  469. }
  470. //---------------------------------------------------------------------------
  471. void __fastcall TFTPFileSystem::Close()
  472. {
  473. DebugAssert(FActive);
  474. bool Result;
  475. if (FFileZillaIntf->Close(FOpening))
  476. {
  477. DebugCheck(FLAGSET(WaitForCommandReply(false), TFileZillaIntf::REPLY_DISCONNECTED));
  478. Result = true;
  479. }
  480. else
  481. {
  482. // See TFileZillaIntf::Close
  483. Result = FOpening;
  484. }
  485. if (DebugAlwaysTrue(Result))
  486. {
  487. DebugAssert(FActive);
  488. Disconnect();
  489. }
  490. }
  491. //---------------------------------------------------------------------------
  492. bool __fastcall TFTPFileSystem::GetActive()
  493. {
  494. return FActive;
  495. }
  496. //---------------------------------------------------------------------------
  497. void __fastcall TFTPFileSystem::CollectUsage()
  498. {
  499. switch (FTerminal->SessionData->Ftps)
  500. {
  501. case ftpsNone:
  502. // noop
  503. break;
  504. case ftpsImplicit:
  505. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPSImplicit");
  506. break;
  507. case ftpsExplicitSsl:
  508. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPSExplicitSSL");
  509. break;
  510. case ftpsExplicitTls:
  511. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPSExplicitTLS");
  512. break;
  513. default:
  514. DebugFail();
  515. break;
  516. }
  517. if (!FTerminal->SessionData->TlsCertificateFile.IsEmpty())
  518. {
  519. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPSCertificate");
  520. }
  521. if (FFileZillaIntf->UsingMlsd())
  522. {
  523. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPMLSD");
  524. }
  525. else
  526. {
  527. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPLIST");
  528. }
  529. if (FFileZillaIntf->UsingUtf8())
  530. {
  531. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPUTF8");
  532. }
  533. else
  534. {
  535. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPNonUTF8");
  536. }
  537. if (!CurrentDirectory.IsEmpty() && (CurrentDirectory[1] != L'/'))
  538. {
  539. if (IsUnixStyleWindowsPath(CurrentDirectory))
  540. {
  541. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPWindowsPath");
  542. }
  543. else if ((CurrentDirectory.Length() >= 3) && IsLetter(CurrentDirectory[1]) && (CurrentDirectory[2] == L':') && (CurrentDirectory[3] == L'/'))
  544. {
  545. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPRealWindowsPath");
  546. }
  547. else
  548. {
  549. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPOtherPath");
  550. }
  551. }
  552. UnicodeString TlsVersionStr = FFileZillaIntf->GetTlsVersionStr().c_str();
  553. if (!TlsVersionStr.IsEmpty())
  554. {
  555. FTerminal->CollectTlsUsage(TlsVersionStr);
  556. }
  557. // 220-FileZilla Server version 0.9.43 beta
  558. // 220-written by Tim Kosse ([email protected])
  559. // 220 Please visit http://sourceforge.net/projects/filezilla/
  560. // SYST
  561. // 215 UNIX emulated by FileZilla
  562. // (Welcome message is configurable)
  563. if (ContainsText(FSystem, L"FileZilla"))
  564. {
  565. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPFileZilla");
  566. }
  567. // 220 ProFTPD 1.3.4a Server (Debian) [::ffff:192.168.179.137]
  568. // SYST
  569. // 215 UNIX Type: L8
  570. else if (ContainsText(FWelcomeMessage, L"ProFTPD"))
  571. {
  572. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPProFTPD");
  573. }
  574. // 220 Microsoft FTP Service
  575. // SYST
  576. // 215 Windows_NT
  577. else if (ContainsText(FWelcomeMessage, L"Microsoft FTP Service") ||
  578. ContainsText(FSystem, L"Windows_NT"))
  579. {
  580. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPIIS");
  581. }
  582. // 220 (vsFTPd 3.0.2)
  583. // SYST
  584. // 215 UNIX Type: L8
  585. // (Welcome message is configurable)
  586. else if (ContainsText(FWelcomeMessage, L"vsFTPd"))
  587. {
  588. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPvsFTPd");
  589. }
  590. // 220 Welcome to Pure-FTPd.
  591. // ...
  592. // SYST
  593. // 215 UNIX Type: L8
  594. else if (ContainsText(FWelcomeMessage, L"Pure-FTPd"))
  595. {
  596. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPPureFTPd");
  597. }
  598. // 220 Titan FTP Server 10.47.1892 Ready.
  599. // ...
  600. // SYST
  601. // 215 UNIX Type: L8
  602. else if (ContainsText(FWelcomeMessage, L"Titan FTP Server"))
  603. {
  604. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPTitan");
  605. }
  606. // 220-Cerberus FTP Server - Home Edition
  607. // 220-This is the UNLICENSED Home Edition and may be used for home, personal use only
  608. // 220-Welcome to Cerberus FTP Server
  609. // 220 Created by Cerberus, LLC
  610. else if (ContainsText(FWelcomeMessage, L"Cerberus FTP Server"))
  611. {
  612. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPCerberus");
  613. }
  614. // 220 Serv-U FTP Server v15.1 ready...
  615. else if (ContainsText(FWelcomeMessage, L"Serv-U FTP Server"))
  616. {
  617. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPServU");
  618. }
  619. else if (ContainsText(FWelcomeMessage, L"WS_FTP"))
  620. {
  621. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPWSFTP");
  622. }
  623. // 220 Welcome to the most popular FTP hosting service! Save on hardware, software, hosting and admin. Share files/folders with read-write permission. Visit http://www.drivehq.com/ftp/
  624. // ...
  625. // SYST
  626. // 215 UNIX emulated by DriveHQ FTP Server.
  627. else if (ContainsText(FSystem, L"DriveHQ"))
  628. {
  629. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPDriveHQ");
  630. }
  631. // 220 GlobalSCAPE EFT Server (v. 6.0) * UNREGISTERED COPY *
  632. // ...
  633. // SYST
  634. // 215 UNIX Type: L8
  635. else if (ContainsText(FWelcomeMessage, L"GlobalSCAPE"))
  636. {
  637. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPGlobalScape");
  638. }
  639. // 220-<custom message>
  640. // 220 CompleteFTP v 8.1.3
  641. // ...
  642. // SYST
  643. // UNIX Type: L8
  644. else if (ContainsText(FWelcomeMessage, L"CompleteFTP"))
  645. {
  646. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPComplete");
  647. }
  648. // 220 Core FTP Server Version 1.2, build 567, 64-bit, installed 8 days ago Unregistered
  649. // ...
  650. // SYST
  651. // 215 UNIX Type: L8
  652. else if (ContainsText(FWelcomeMessage, L"Core FTP Server"))
  653. {
  654. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPCore");
  655. }
  656. // 220 Service ready for new user.
  657. // ..
  658. // SYST
  659. // 215 UNIX Type: Apache FtpServer
  660. // (e.g. brickftp.com)
  661. else if (ContainsText(FSystem, L"Apache FtpServer"))
  662. {
  663. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPApache");
  664. }
  665. // 220 pos1 FTP server (GNU inetutils 1.3b) ready.
  666. // ...
  667. // SYST
  668. // 215 UNIX Type: L8 Version: Linux 2.6.15.7-ELinOS-314pm3
  669. // Displaying "(GNU inetutils 1.3b)" in a welcome message can be turned off (-q switch):
  670. // 220 pos1 FTP server ready.
  671. // (the same for "Version: Linux 2.6.15.7-ELinOS-314pm3" in SYST response)
  672. else if (ContainsText(FWelcomeMessage, L"GNU inetutils"))
  673. {
  674. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPInetutils");
  675. }
  676. // 220 Syncplify.me Server! FTP(S) Service Ready
  677. // Message is configurable
  678. else if (ContainsText(FWelcomeMessage, L"Syncplify"))
  679. {
  680. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPSyncplify");
  681. }
  682. // 220-Idea FTP Server v0.80 (xxx.home.pl) [xxx.xxx.xxx.xxx]
  683. // 220 Ready
  684. // ...
  685. // SYST
  686. // UNIX Type: L8
  687. else if (ContainsText(FWelcomeMessage, L"Idea FTP Server"))
  688. {
  689. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPIdea");
  690. }
  691. // 220-FTPD1 IBM FTP CS V2R1 at name.test.com, 13:49:38 on 2016-01-28.
  692. // ...
  693. // SYST
  694. // 215 MVS is the operating system of this server. FTP Server is running on z/OS.
  695. else if (FMVS)
  696. {
  697. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPMVS");
  698. }
  699. // 220 xxx.xxx.xxx (xxx.xxx.xxx) FTP-OpenVMS FTPD V5.3-3 (c) 1998 Process Software Corporation
  700. // ...
  701. // SYST
  702. // 215 VMS system type. VMS V5.5-2.
  703. else if (FVMS)
  704. {
  705. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPVMS");
  706. }
  707. else
  708. {
  709. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPOther");
  710. }
  711. }
  712. //---------------------------------------------------------------------------
  713. void __fastcall TFTPFileSystem::DummyReadDirectory(const UnicodeString & Directory)
  714. {
  715. std::unique_ptr<TRemoteDirectory> Files(new TRemoteDirectory(FTerminal));
  716. try
  717. {
  718. Files->Directory = Directory;
  719. DoReadDirectory(Files.get());
  720. }
  721. catch(...)
  722. {
  723. // ignore non-fatal errors
  724. // (i.e. current directory may not exist anymore)
  725. if (!FTerminal->Active)
  726. {
  727. throw;
  728. }
  729. }
  730. }
  731. //---------------------------------------------------------------------------
  732. void __fastcall TFTPFileSystem::Idle()
  733. {
  734. if (FActive && !FWaitingForReply)
  735. {
  736. PoolForFatalNonCommandReply();
  737. // Keep session alive
  738. if ((FTerminal->SessionData->FtpPingType != ptOff) &&
  739. (double(Now() - FLastDataSent) > double(FTerminal->SessionData->FtpPingIntervalDT) * 4))
  740. {
  741. FTerminal->LogEvent(L"Dummy directory read to keep session alive.");
  742. FLastDataSent = Now(); // probably redundant to the same statement in DoReadDirectory
  743. DummyReadDirectory(CurrentDirectory);
  744. }
  745. }
  746. }
  747. //---------------------------------------------------------------------------
  748. void __fastcall TFTPFileSystem::Discard()
  749. {
  750. // remove all pending messages, to get complete log
  751. // note that we need to retry discard on reconnect, as there still may be another
  752. // "disconnect/timeout/..." status messages coming
  753. DiscardMessages();
  754. DebugAssert(FActive);
  755. FActive = false;
  756. // See neon's ne_ssl_clicert_free
  757. if (FPrivateKey != NULL)
  758. {
  759. EVP_PKEY_free(FPrivateKey);
  760. FPrivateKey = NULL;
  761. }
  762. if (FCertificate != NULL)
  763. {
  764. X509_free(FCertificate);
  765. FCertificate = NULL;
  766. }
  767. }
  768. //---------------------------------------------------------------------------
  769. UnicodeString __fastcall TFTPFileSystem::AbsolutePath(UnicodeString Path, bool /*Local*/)
  770. {
  771. // TODO: improve (handle .. etc.)
  772. if (UnixIsAbsolutePath(Path))
  773. {
  774. return Path;
  775. }
  776. else
  777. {
  778. return ::AbsolutePath(FCurrentDirectory, Path);
  779. }
  780. }
  781. //---------------------------------------------------------------------------
  782. UnicodeString __fastcall TFTPFileSystem::ActualCurrentDirectory()
  783. {
  784. wchar_t CurrentPath[1024];
  785. FFileZillaIntf->GetCurrentPath(CurrentPath, LENOF(CurrentPath));
  786. return UnixExcludeTrailingBackslash(CurrentPath);
  787. }
  788. //---------------------------------------------------------------------------
  789. void __fastcall TFTPFileSystem::EnsureLocation(const UnicodeString & Directory, bool Log)
  790. {
  791. UnicodeString ADirectory = UnixExcludeTrailingBackslash(Directory);
  792. if (!UnixSamePath(ActualCurrentDirectory(), ADirectory))
  793. {
  794. if (Log)
  795. {
  796. FTerminal->LogEvent(FORMAT(L"Synchronizing current directory \"%s\".",
  797. (ADirectory)));
  798. }
  799. DoChangeDirectory(ADirectory);
  800. // make sure FZAPI is aware that we changed current working directory
  801. FFileZillaIntf->SetCurrentPath(ADirectory.c_str());
  802. }
  803. }
  804. //---------------------------------------------------------------------------
  805. void __fastcall TFTPFileSystem::EnsureLocation()
  806. {
  807. // if we do not know what's the current directory, do nothing
  808. if (!FCurrentDirectory.IsEmpty())
  809. {
  810. // Make sure that the FZAPI current working directory,
  811. // is actually our working directory.
  812. // It may not be because:
  813. // 1) We did cached directory change
  814. // 2) Listing was requested for non-current directory, which
  815. // makes FZAPI change its current directory (and not restoring it back afterwards)
  816. EnsureLocation(FCurrentDirectory, true);
  817. }
  818. }
  819. //---------------------------------------------------------------------------
  820. void __fastcall TFTPFileSystem::AnyCommand(const UnicodeString Command,
  821. TCaptureOutputEvent OutputEvent)
  822. {
  823. // end-user has right to expect that client current directory is really
  824. // current directory for the server
  825. EnsureLocation();
  826. DebugAssert(FOnCaptureOutput == NULL);
  827. FOnCaptureOutput = OutputEvent;
  828. try
  829. {
  830. SendCommand(Command);
  831. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_3XX_CODE);
  832. }
  833. __finally
  834. {
  835. FOnCaptureOutput = NULL;
  836. }
  837. }
  838. //---------------------------------------------------------------------------
  839. void __fastcall TFTPFileSystem::ResetCaches()
  840. {
  841. delete FFileListCache;
  842. FFileListCache = NULL;
  843. }
  844. //---------------------------------------------------------------------------
  845. void __fastcall TFTPFileSystem::AnnounceFileListOperation()
  846. {
  847. ResetCaches();
  848. }
  849. //---------------------------------------------------------------------------
  850. void __fastcall TFTPFileSystem::DoChangeDirectory(const UnicodeString & Directory)
  851. {
  852. UnicodeString Command = FORMAT(L"CWD %s", (Directory));
  853. SendCommand(Command);
  854. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  855. }
  856. //---------------------------------------------------------------------------
  857. void __fastcall TFTPFileSystem::ChangeDirectory(const UnicodeString ADirectory)
  858. {
  859. UnicodeString Directory = ADirectory;
  860. try
  861. {
  862. // For changing directory, we do not make paths absolute, instead we
  863. // delegate this to the server, hence we synchronize current working
  864. // directory with the server and only then we ask for the change with
  865. // relative path.
  866. // But if synchronization fails, typically because current working directory
  867. // no longer exists, we fall back to out own resolution, to give
  868. // user chance to leave the non-existing directory.
  869. EnsureLocation();
  870. }
  871. catch(...)
  872. {
  873. if (FTerminal->Active)
  874. {
  875. Directory = AbsolutePath(Directory, false);
  876. }
  877. else
  878. {
  879. throw;
  880. }
  881. }
  882. DoChangeDirectory(Directory);
  883. // make next ReadCurrentDirectory retrieve actual server-side current directory
  884. FReadCurrentDirectory = true;
  885. }
  886. //---------------------------------------------------------------------------
  887. void __fastcall TFTPFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  888. {
  889. FCurrentDirectory = UnixExcludeTrailingBackslash(Directory);
  890. FReadCurrentDirectory = false;
  891. }
  892. //---------------------------------------------------------------------------
  893. void __fastcall TFTPFileSystem::ChangeFileProperties(const UnicodeString AFileName,
  894. const TRemoteFile * File, const TRemoteProperties * Properties,
  895. TChmodSessionAction & Action)
  896. {
  897. DebugAssert(Properties);
  898. DebugAssert(!Properties->Valid.Contains(vpGroup));
  899. DebugAssert(!Properties->Valid.Contains(vpOwner));
  900. DebugAssert(!Properties->Valid.Contains(vpLastAccess));
  901. DebugAssert(!Properties->Valid.Contains(vpModification));
  902. if (Properties->Valid.Contains(vpRights))
  903. {
  904. TRemoteFile * OwnedFile = NULL;
  905. try
  906. {
  907. UnicodeString FileName = AbsolutePath(AFileName, false);
  908. if (File == NULL)
  909. {
  910. ReadFile(FileName, OwnedFile);
  911. File = OwnedFile;
  912. }
  913. if ((File != NULL) && File->IsDirectory && FTerminal->CanRecurseToDirectory(File) && Properties->Recursive)
  914. {
  915. try
  916. {
  917. FTerminal->ProcessDirectory(AFileName, FTerminal->ChangeFileProperties,
  918. (void*)Properties);
  919. }
  920. catch(...)
  921. {
  922. Action.Cancel();
  923. throw;
  924. }
  925. }
  926. TRights Rights;
  927. if (File != NULL)
  928. {
  929. Rights = *File->Rights;
  930. }
  931. Rights |= Properties->Rights.NumberSet;
  932. Rights &= (unsigned short)~Properties->Rights.NumberUnset;
  933. if ((File != NULL) && File->IsDirectory && Properties->AddXToDirectories)
  934. {
  935. Rights.AddExecute();
  936. }
  937. Action.Rights(Rights);
  938. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  939. UnicodeString FilePath = UnixExtractFilePath(FileName);
  940. // FZAPI wants octal number represented as decadic
  941. FFileZillaIntf->Chmod(Rights.NumberDecadic, FileNameOnly.c_str(), FilePath.c_str());
  942. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  943. }
  944. __finally
  945. {
  946. delete OwnedFile;
  947. }
  948. }
  949. else
  950. {
  951. Action.Cancel();
  952. }
  953. }
  954. //---------------------------------------------------------------------------
  955. bool __fastcall TFTPFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  956. {
  957. DebugFail();
  958. return false;
  959. }
  960. //---------------------------------------------------------------------------
  961. UnicodeString __fastcall TFTPFileSystem::DoCalculateFileChecksum(
  962. bool UsingHashCommand, const UnicodeString & Alg, TRemoteFile * File)
  963. {
  964. // Overview of server supporting various hash commands is at:
  965. // https://tools.ietf.org/html/draft-bryan-ftpext-hash-02#appendix-B
  966. UnicodeString CommandName;
  967. if (UsingHashCommand)
  968. {
  969. CommandName = HashCommand;
  970. }
  971. else
  972. {
  973. int Index = FChecksumAlgs->IndexOf(Alg);
  974. if (Index < 0)
  975. {
  976. DebugFail();
  977. EXCEPTION;
  978. }
  979. else
  980. {
  981. CommandName = FChecksumCommands->Strings[Index];
  982. }
  983. }
  984. UnicodeString FileName = File->FullFileName;
  985. // FTP way is not to quote.
  986. // But as Serv-U, GlobalSCAPE and possibly others allow
  987. // additional parameters (SP ER range), they need to quote file name.
  988. // Cerberus and FileZilla Server on the other hand can do without quotes
  989. // (but they can handle them, not sure about other servers)
  990. // Quoting:
  991. // FileZilla Server simply checks if argument starts and ends with double-quote
  992. // and strips them, no double-quote escaping is possible.
  993. // That's for all commands, not just HASH
  994. // ProFTPD: TODO: Check how "SITE SYMLINK target link" is parsed
  995. // We can possibly autodetect this from announced command format:
  996. // XCRC filename;start;end
  997. // XMD5 filename;start;end
  998. // XSHA1 filename;start;end
  999. // XSHA256 filename;start;end
  1000. // XSHA512 filename;start;end
  1001. if (FileName.Pos(L" ") > 0)
  1002. {
  1003. FileName = FORMAT(L"\"%s\"", (FileName));
  1004. }
  1005. UnicodeString Command = FORMAT(L"%s %s", (CommandName, FileName));
  1006. SendCommand(Command);
  1007. UnicodeString ResponseText = GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_SINGLE_LINE);
  1008. UnicodeString Hash;
  1009. if (UsingHashCommand)
  1010. {
  1011. // Code should be 213, but let's be tolerant and accept any 2xx
  1012. // ("213" SP) hashname SP start-point "-" end-point SP filehash SP <pathname> (CRLF)
  1013. UnicodeString Buf = ResponseText;
  1014. // skip alg
  1015. CutToChar(Buf, L' ', true);
  1016. // skip range
  1017. UnicodeString Range = CutToChar(Buf, L' ', true);
  1018. // This should be range (SP-EP), but if it does not conform to the format,
  1019. // it's likely because the server uses version of the HASH spec
  1020. // before draft-ietf-ftpext2-hash-01
  1021. // (including draft-bryan-ftp-hash-06 implemented by FileZilla server; or Cerberus),
  1022. // that did not have the "range" part.
  1023. // The FileZilla Server even omits the file name.
  1024. // The latest draft as of implementing this is draft-bryan-ftpext-hash-02.
  1025. if (Range.Pos(L"-") > 0)
  1026. {
  1027. Hash = CutToChar(Buf, L' ', true);
  1028. }
  1029. else
  1030. {
  1031. Hash = Range;
  1032. }
  1033. }
  1034. else // All hash-specific commands
  1035. {
  1036. // Accepting any 2xx response. Most servers use 213,
  1037. // but for example WS_FTP uses non-sense code 220 (Service ready for new user)
  1038. // MD5 response according to a draft-twine-ftpmd5-00 includes a file name
  1039. // (implemented by Apache FtpServer).
  1040. // Other commands (X<hash>) return the hash only.
  1041. ResponseText = ResponseText.Trim();
  1042. int P = ResponseText.LastDelimiter(L" ");
  1043. if (P > 0)
  1044. {
  1045. ResponseText.Delete(1, P);
  1046. }
  1047. Hash = ResponseText;
  1048. }
  1049. if (Hash.IsEmpty())
  1050. {
  1051. throw Exception(FMTLOAD(FTP_RESPONSE_ERROR, (CommandName, ResponseText)));
  1052. }
  1053. return LowerCase(Hash);
  1054. }
  1055. //---------------------------------------------------------------------------
  1056. void __fastcall TFTPFileSystem::DoCalculateFilesChecksum(bool UsingHashCommand,
  1057. const UnicodeString & Alg, TStrings * FileList, TStrings * Checksums,
  1058. TCalculatedChecksumEvent OnCalculatedChecksum,
  1059. TFileOperationProgressType * OperationProgress, bool FirstLevel)
  1060. {
  1061. TOnceDoneOperation OnceDoneOperation; // not used
  1062. int Index = 0;
  1063. while ((Index < FileList->Count) && !OperationProgress->Cancel)
  1064. {
  1065. TRemoteFile * File = (TRemoteFile *)FileList->Objects[Index];
  1066. DebugAssert(File != NULL);
  1067. if (File->IsDirectory)
  1068. {
  1069. if (FTerminal->CanRecurseToDirectory(File) &&
  1070. IsRealFile(File->FileName) &&
  1071. // recurse into subdirectories only if we have callback function
  1072. (OnCalculatedChecksum != NULL))
  1073. {
  1074. OperationProgress->SetFile(File->FileName);
  1075. TRemoteFileList * SubFiles =
  1076. FTerminal->CustomReadDirectoryListing(File->FullFileName, false);
  1077. if (SubFiles != NULL)
  1078. {
  1079. TStrings * SubFileList = new TStringList();
  1080. bool Success = false;
  1081. try
  1082. {
  1083. OperationProgress->SetFile(File->FileName);
  1084. for (int Index = 0; Index < SubFiles->Count; Index++)
  1085. {
  1086. TRemoteFile * SubFile = SubFiles->Files[Index];
  1087. SubFileList->AddObject(SubFile->FullFileName, SubFile);
  1088. }
  1089. // do not collect checksums for files in subdirectories,
  1090. // only send back checksums via callback
  1091. DoCalculateFilesChecksum(UsingHashCommand, Alg, SubFileList, NULL,
  1092. OnCalculatedChecksum, OperationProgress, false);
  1093. Success = true;
  1094. }
  1095. __finally
  1096. {
  1097. delete SubFiles;
  1098. delete SubFileList;
  1099. if (FirstLevel)
  1100. {
  1101. OperationProgress->Finish(File->FileName, Success, OnceDoneOperation);
  1102. }
  1103. }
  1104. }
  1105. }
  1106. }
  1107. else
  1108. {
  1109. TChecksumSessionAction Action(FTerminal->ActionLog);
  1110. try
  1111. {
  1112. OperationProgress->SetFile(File->FileName);
  1113. Action.FileName(FTerminal->AbsolutePath(File->FullFileName, true));
  1114. UnicodeString Checksum = DoCalculateFileChecksum(UsingHashCommand, Alg, File);
  1115. if (OnCalculatedChecksum != NULL)
  1116. {
  1117. OnCalculatedChecksum(File->FileName, Alg, Checksum);
  1118. }
  1119. Action.Checksum(Alg, Checksum);
  1120. if (Checksums != NULL)
  1121. {
  1122. Checksums->Add(Checksum);
  1123. }
  1124. }
  1125. catch (Exception & E)
  1126. {
  1127. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1128. // Error formatting expanded from inline to avoid strange exceptions
  1129. UnicodeString Error =
  1130. FMTLOAD(CHECKSUM_ERROR,
  1131. (File != NULL ? File->FullFileName : UnicodeString(L"")));
  1132. FTerminal->CommandError(&E, Error);
  1133. // Abort loop.
  1134. // TODO: retries? resume?
  1135. Index = FileList->Count;
  1136. }
  1137. }
  1138. Index++;
  1139. }
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. void __fastcall TFTPFileSystem::CalculateFilesChecksum(const UnicodeString & Alg,
  1143. TStrings * FileList, TStrings * Checksums,
  1144. TCalculatedChecksumEvent OnCalculatedChecksum)
  1145. {
  1146. TFileOperationProgressType Progress(&FTerminal->DoProgress, &FTerminal->DoFinished);
  1147. FTerminal->OperationStart(Progress, foCalculateChecksum, osRemote, FileList->Count);
  1148. try
  1149. {
  1150. UnicodeString NormalizedAlg = FindIdent(FindIdent(Alg, FHashAlgs.get()), FChecksumAlgs.get());
  1151. bool UsingHashCommand = (FHashAlgs->IndexOf(NormalizedAlg) >= 0);
  1152. if (UsingHashCommand)
  1153. {
  1154. // The server should understand lowercase alg name by spec,
  1155. // but we should use uppercase anyway
  1156. SendCommand(FORMAT(L"OPTS %s %s", (HashCommand, UpperCase(NormalizedAlg))));
  1157. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1158. }
  1159. else if (FChecksumAlgs->IndexOf(NormalizedAlg) >= 0)
  1160. {
  1161. // will use algorithm-specific command
  1162. }
  1163. else
  1164. {
  1165. throw Exception(FMTLOAD(UNKNOWN_CHECKSUM, (Alg)));
  1166. }
  1167. DoCalculateFilesChecksum(UsingHashCommand, NormalizedAlg, FileList, Checksums, OnCalculatedChecksum,
  1168. &Progress, true);
  1169. }
  1170. __finally
  1171. {
  1172. FTerminal->OperationStop(Progress);
  1173. }
  1174. }
  1175. //---------------------------------------------------------------------------
  1176. bool __fastcall TFTPFileSystem::ConfirmOverwrite(
  1177. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1178. TOverwriteMode & OverwriteMode, TFileOperationProgressType * OperationProgress,
  1179. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1180. int Params, bool AutoResume)
  1181. {
  1182. bool Result;
  1183. bool CanAutoResume = FLAGSET(Params, cpNoConfirmation) && AutoResume;
  1184. bool DestIsSmaller = (FileParams != NULL) && (FileParams->DestSize < FileParams->SourceSize);
  1185. bool DestIsSame = (FileParams != NULL) && (FileParams->DestSize == FileParams->SourceSize);
  1186. bool CanResume =
  1187. !OperationProgress->AsciiTransfer &&
  1188. // when resuming transfer after interrupted connection,
  1189. // do nothing (dummy resume) when the files has the same size.
  1190. // this is workaround for servers that strangely fails just after successful
  1191. // upload.
  1192. (DestIsSmaller || (DestIsSame && CanAutoResume));
  1193. unsigned int Answer;
  1194. if (CanAutoResume && CanResume)
  1195. {
  1196. if (DestIsSame)
  1197. {
  1198. DebugAssert(CanAutoResume);
  1199. Answer = qaSkip;
  1200. }
  1201. else
  1202. {
  1203. Answer = qaRetry;
  1204. }
  1205. }
  1206. else
  1207. {
  1208. // retry = "resume"
  1209. // all = "yes to newer"
  1210. // ignore = "rename"
  1211. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  1212. if (CanResume)
  1213. {
  1214. Answers |= qaRetry;
  1215. }
  1216. TQueryButtonAlias Aliases[5];
  1217. Aliases[0].Button = qaRetry;
  1218. Aliases[0].Alias = LoadStr(RESUME_BUTTON);
  1219. Aliases[0].GroupWith = qaNo;
  1220. Aliases[0].GrouppedShiftState = TShiftState() << ssAlt;
  1221. Aliases[1] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
  1222. Aliases[2] = TQueryButtonAlias::CreateIgnoreAsRenameGrouppedWithNo();
  1223. Aliases[3] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
  1224. Aliases[4] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
  1225. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1226. QueryParams.Aliases = Aliases;
  1227. QueryParams.AliasesCount = LENOF(Aliases);
  1228. {
  1229. TSuspendFileOperationProgress Suspend(OperationProgress);
  1230. Answer = FTerminal->ConfirmFileOverwrite(
  1231. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1232. ReverseOperationSide(OperationProgress->Side),
  1233. CopyParam, Params, OperationProgress);
  1234. }
  1235. }
  1236. Result = true;
  1237. switch (Answer)
  1238. {
  1239. // resume
  1240. case qaRetry:
  1241. OverwriteMode = omResume;
  1242. DebugAssert(FileParams != NULL);
  1243. DebugAssert(CanResume);
  1244. FFileTransferResumed = FileParams->DestSize;
  1245. break;
  1246. // rename
  1247. case qaIgnore:
  1248. if (FTerminal->PromptUser(FTerminal->SessionData, pkFileName,
  1249. LoadStr(RENAME_TITLE), L"", LoadStr(RENAME_PROMPT2), true, 0, TargetFileName))
  1250. {
  1251. OverwriteMode = omOverwrite;
  1252. }
  1253. else
  1254. {
  1255. OperationProgress->SetCancelAtLeast(csCancel);
  1256. FFileTransferAbort = ftaCancel;
  1257. Result = false;
  1258. }
  1259. break;
  1260. case qaYes:
  1261. OverwriteMode = omOverwrite;
  1262. break;
  1263. case qaCancel:
  1264. OperationProgress->SetCancelAtLeast(csCancel);
  1265. FFileTransferAbort = ftaCancel;
  1266. Result = false;
  1267. break;
  1268. case qaNo:
  1269. FFileTransferAbort = ftaSkip;
  1270. Result = false;
  1271. break;
  1272. case qaSkip:
  1273. OverwriteMode = omComplete;
  1274. break;
  1275. default:
  1276. DebugFail();
  1277. Result = false;
  1278. break;
  1279. }
  1280. return Result;
  1281. }
  1282. //---------------------------------------------------------------------------
  1283. void __fastcall TFTPFileSystem::ResetFileTransfer()
  1284. {
  1285. FFileTransferAbort = ftaNone;
  1286. FFileTransferCancelled = false;
  1287. FFileTransferResumed = 0;
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. void __fastcall TFTPFileSystem::ReadDirectoryProgress(__int64 Bytes)
  1291. {
  1292. // with FTP we do not know exactly how many entries we have received,
  1293. // instead we know number of bytes received only.
  1294. // so we report approximation based on average size of entry.
  1295. int Progress = int(Bytes / 80);
  1296. if (Progress - FLastReadDirectoryProgress >= 10)
  1297. {
  1298. bool Cancel = false;
  1299. FLastReadDirectoryProgress = Progress;
  1300. FTerminal->DoReadDirectoryProgress(Progress, 0, Cancel);
  1301. if (Cancel)
  1302. {
  1303. FTerminal->DoReadDirectoryProgress(-2, 0, Cancel);
  1304. FFileZillaIntf->Cancel();
  1305. }
  1306. }
  1307. }
  1308. //---------------------------------------------------------------------------
  1309. void __fastcall TFTPFileSystem::DoFileTransferProgress(__int64 TransferSize,
  1310. __int64 Bytes)
  1311. {
  1312. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  1313. OperationProgress->SetTransferSize(TransferSize);
  1314. if (FFileTransferResumed > 0)
  1315. {
  1316. OperationProgress->AddResumed(FFileTransferResumed);
  1317. FFileTransferResumed = 0;
  1318. }
  1319. __int64 Diff = Bytes - OperationProgress->TransferredSize;
  1320. if (DebugAlwaysTrue(Diff >= 0))
  1321. {
  1322. OperationProgress->AddTransferred(Diff);
  1323. FFileTransferAny = true;
  1324. }
  1325. if (OperationProgress->Cancel != csContinue)
  1326. {
  1327. if (OperationProgress->ClearCancelFile())
  1328. {
  1329. FFileTransferAbort = ftaSkip;
  1330. }
  1331. else
  1332. {
  1333. FFileTransferAbort = ftaCancel;
  1334. }
  1335. FFileTransferCancelled = true;
  1336. FFileZillaIntf->Cancel();
  1337. }
  1338. if (FFileTransferCPSLimit != OperationProgress->CPSLimit)
  1339. {
  1340. SetCPSLimit(OperationProgress);
  1341. }
  1342. }
  1343. //---------------------------------------------------------------------------
  1344. void __fastcall TFTPFileSystem::SetCPSLimit(TFileOperationProgressType * OperationProgress)
  1345. {
  1346. // Any reason we use separate field intead of directly using OperationProgress->CPSLimit?
  1347. // Maybe thread-safety?
  1348. FFileTransferCPSLimit = OperationProgress->CPSLimit;
  1349. OperationProgress->SetSpeedCounters();
  1350. }
  1351. //---------------------------------------------------------------------------
  1352. void __fastcall TFTPFileSystem::FileTransferProgress(__int64 TransferSize,
  1353. __int64 Bytes)
  1354. {
  1355. TGuard Guard(FTransferStatusCriticalSection);
  1356. DoFileTransferProgress(TransferSize, Bytes);
  1357. }
  1358. //---------------------------------------------------------------------------
  1359. void __fastcall TFTPFileSystem::FileTransfer(const UnicodeString & FileName,
  1360. const UnicodeString & LocalFile, const UnicodeString & RemoteFile,
  1361. const UnicodeString & RemotePath, bool Get, __int64 Size, int Type,
  1362. TFileTransferData & UserData, TFileOperationProgressType * OperationProgress)
  1363. {
  1364. FILE_OPERATION_LOOP_BEGIN
  1365. {
  1366. FFileZillaIntf->FileTransfer(ApiPath(LocalFile).c_str(), RemoteFile.c_str(),
  1367. RemotePath.c_str(), Get, Size, Type, &UserData);
  1368. // we may actually catch response code of the listing
  1369. // command (when checking for existence of the remote file)
  1370. unsigned int Reply = WaitForCommandReply();
  1371. GotReply(Reply, FLAGMASK(FFileTransferCancelled, REPLY_ALLOW_CANCEL));
  1372. }
  1373. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1374. switch (FFileTransferAbort)
  1375. {
  1376. case ftaSkip:
  1377. throw ESkipFile();
  1378. case ftaCancel:
  1379. Abort();
  1380. break;
  1381. }
  1382. if (!FFileTransferCancelled)
  1383. {
  1384. // show completion of transfer
  1385. // call non-guarded variant to avoid deadlock with keepalives
  1386. // (we are not waiting for reply anymore so keepalives are free to proceed)
  1387. DoFileTransferProgress(OperationProgress->TransferSize, OperationProgress->TransferSize);
  1388. }
  1389. }
  1390. //---------------------------------------------------------------------------
  1391. void __fastcall TFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1392. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1393. int Params, TFileOperationProgressType * OperationProgress,
  1394. TOnceDoneOperation & OnceDoneOperation)
  1395. {
  1396. Params &= ~cpAppend;
  1397. FTerminal->DoCopyToLocal(
  1398. FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfUseFileTransferAny, OnceDoneOperation);
  1399. }
  1400. //---------------------------------------------------------------------------
  1401. void __fastcall TFTPFileSystem::Sink(
  1402. const UnicodeString & FileName, const TRemoteFile * File,
  1403. const UnicodeString & TargetDir, UnicodeString & DestFileName, int Attrs,
  1404. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  1405. unsigned int Flags, TDownloadSessionAction & Action)
  1406. {
  1407. AutoDetectTimeDifference(UnixExtractFileDir(FileName), CopyParam, Params);
  1408. ResetFileTransfer();
  1409. TFileTransferData UserData;
  1410. UnicodeString DestFullName = TargetDir + DestFileName;
  1411. UnicodeString FilePath = UnixExtractFilePath(FileName);
  1412. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1413. {
  1414. // ignore file list
  1415. TFileListHelper Helper(this, NULL, true);
  1416. SetCPSLimit(OperationProgress);
  1417. FFileTransferPreserveTime = CopyParam->PreserveTime;
  1418. // not used for downloads anyway
  1419. FFileTransferRemoveBOM = CopyParam->RemoveBOM;
  1420. FFileTransferNoList = CanTransferSkipList(Params, Flags, CopyParam);
  1421. UserData.FileName = DestFileName;
  1422. UserData.Params = Params;
  1423. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1424. UserData.CopyParam = CopyParam;
  1425. UserData.Modification = File->Modification;
  1426. UnicodeString OnlyFileName = UnixExtractFileName(FileName);
  1427. FileTransfer(FileName, DestFullName, OnlyFileName,
  1428. FilePath, true, File->Size, TransferType, UserData, OperationProgress);
  1429. }
  1430. // in case dest filename is changed from overwrite dialog
  1431. if (DestFileName != UserData.FileName)
  1432. {
  1433. DestFullName = TargetDir + UserData.FileName;
  1434. Attrs = FileGetAttrFix(ApiPath(DestFullName));
  1435. }
  1436. UnicodeString ExpandedDestFullName = ExpandUNCFileName(DestFullName);
  1437. Action.Destination(ExpandedDestFullName);
  1438. FTerminal->UpdateTargetAttrs(DestFullName, File, CopyParam, Attrs);
  1439. FLastDataSent = Now();
  1440. }
  1441. //---------------------------------------------------------------------------
  1442. void __fastcall TFTPFileSystem::TransferOnDirectory(
  1443. const UnicodeString & Directory, const TCopyParamType * CopyParam, int Params)
  1444. {
  1445. AutoDetectTimeDifference(Directory, CopyParam, Params);
  1446. }
  1447. //---------------------------------------------------------------------------
  1448. void __fastcall TFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1449. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1450. int Params, TFileOperationProgressType * OperationProgress,
  1451. TOnceDoneOperation & OnceDoneOperation)
  1452. {
  1453. Params &= ~cpAppend;
  1454. FTerminal->DoCopyToRemote(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfUseFileTransferAny, OnceDoneOperation);
  1455. }
  1456. //---------------------------------------------------------------------------
  1457. bool __fastcall TFTPFileSystem::CanTransferSkipList(int Params, unsigned int Flags, const TCopyParamType * CopyParam)
  1458. {
  1459. bool Result =
  1460. FLAGSET(Params, cpNoConfirmation) &&
  1461. // cpAppend is not supported with FTP
  1462. DebugAlwaysTrue(FLAGCLEAR(Params, cpAppend)) &&
  1463. FLAGCLEAR(Params, cpResume) &&
  1464. FLAGCLEAR(Flags, tfAutoResume) &&
  1465. !CopyParam->NewerOnly;
  1466. return Result;
  1467. }
  1468. //---------------------------------------------------------------------------
  1469. void __fastcall TFTPFileSystem::Source(
  1470. TLocalFileHandle & Handle, const UnicodeString & TargetDir, UnicodeString & DestFileName,
  1471. const TCopyParamType * CopyParam, int Params,
  1472. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1473. TUploadSessionAction & Action, bool & /*ChildError*/)
  1474. {
  1475. Handle.Close();
  1476. ResetFileTransfer();
  1477. TFileTransferData UserData;
  1478. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1479. {
  1480. // ignore file list
  1481. TFileListHelper Helper(this, NULL, true);
  1482. SetCPSLimit(OperationProgress);
  1483. // not used for uploads anyway
  1484. FFileTransferPreserveTime = CopyParam->PreserveTime;
  1485. FFileTransferRemoveBOM = CopyParam->RemoveBOM;
  1486. FFileTransferNoList = CanTransferSkipList(Params, Flags, CopyParam);
  1487. // not used for uploads, but we get new name (if any) back in this field
  1488. UserData.FileName = DestFileName;
  1489. UserData.Params = Params;
  1490. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1491. UserData.CopyParam = CopyParam;
  1492. UserData.Modification = Handle.Modification;
  1493. FileTransfer(Handle.FileName, Handle.FileName, DestFileName,
  1494. TargetDir, false, Handle.Size, TransferType, UserData, OperationProgress);
  1495. }
  1496. UnicodeString DestFullName = TargetDir + UserData.FileName;
  1497. // only now, we know the final destination
  1498. Action.Destination(DestFullName);
  1499. // We are not able to tell if setting timestamp succeeded,
  1500. // so we log it always (if supported).
  1501. // Support for MDTM does not necessarily mean that the server supports
  1502. // non-standard hack of setting timestamp using
  1503. // MFMT-like (two argument) call to MDTM.
  1504. // IIS definitelly does.
  1505. if (FFileTransferPreserveTime &&
  1506. ((FServerCapabilities->GetCapability(mfmt_command) == yes) ||
  1507. ((FServerCapabilities->GetCapability(mdtm_command) == yes))))
  1508. {
  1509. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Handle.Modification);
  1510. if (!FFileZillaIntf->UsingMlsd())
  1511. {
  1512. FUploadedTimes[DestFullName] = Handle.Modification;
  1513. if ((FTerminal->Configuration->ActualLogProtocol >= 2))
  1514. {
  1515. FTerminal->LogEvent(
  1516. FORMAT(L"Remembering modification time of \"%s\" as [%s]",
  1517. (DestFullName, StandardTimestamp(FUploadedTimes[DestFullName]))));
  1518. }
  1519. }
  1520. }
  1521. FLastDataSent = Now();
  1522. }
  1523. //---------------------------------------------------------------------------
  1524. void __fastcall TFTPFileSystem::CreateDirectory(const UnicodeString & ADirName, bool /*Encrypt*/)
  1525. {
  1526. UnicodeString DirName = AbsolutePath(ADirName, false);
  1527. {
  1528. // ignore file list
  1529. TFileListHelper Helper(this, NULL, true);
  1530. FFileZillaIntf->MakeDir(DirName.c_str());
  1531. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1532. }
  1533. }
  1534. //---------------------------------------------------------------------------
  1535. void __fastcall TFTPFileSystem::CreateLink(const UnicodeString FileName,
  1536. const UnicodeString PointTo, bool Symbolic)
  1537. {
  1538. DebugAssert(SupportsSiteCommand(SymlinkSiteCommand));
  1539. if (DebugAlwaysTrue(Symbolic))
  1540. {
  1541. EnsureLocation();
  1542. UnicodeString Command = FORMAT(L"%s %s %s %s", (SiteCommand, SymlinkSiteCommand, PointTo, FileName));
  1543. SendCommand(Command);
  1544. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1545. }
  1546. }
  1547. //---------------------------------------------------------------------------
  1548. void __fastcall TFTPFileSystem::DeleteFile(const UnicodeString AFileName,
  1549. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  1550. {
  1551. UnicodeString FileName = AbsolutePath(AFileName, false);
  1552. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  1553. UnicodeString FilePath = UnixExtractFilePath(FileName);
  1554. bool Dir = FTerminal->DeleteContentsIfDirectory(FileName, File, Params, Action);
  1555. {
  1556. // ignore file list
  1557. TFileListHelper Helper(this, NULL, true);
  1558. if (Dir)
  1559. {
  1560. // If current remote directory is in the directory being removed,
  1561. // some servers may refuse to delete it
  1562. // This is common as ProcessDirectory above would CWD to
  1563. // the directory to LIST it.
  1564. // EnsureLocation should reset actual current directory to user's working directory.
  1565. // If user's working directory is still below deleted directory, it is
  1566. // perfectly correct to report an error.
  1567. if (UnixIsChildPath(ActualCurrentDirectory(), FileName))
  1568. {
  1569. EnsureLocation();
  1570. }
  1571. FFileZillaIntf->RemoveDir(FileNameOnly.c_str(), FilePath.c_str());
  1572. }
  1573. else
  1574. {
  1575. if ((FTerminal->SessionData->FtpDeleteFromCwd == asOn) ||
  1576. ((FTerminal->SessionData->FtpDeleteFromCwd == asAuto) && FVMS))
  1577. {
  1578. EnsureLocation(FilePath, false);
  1579. FFileZillaIntf->Delete(FileNameOnly.c_str(), L"", true);
  1580. }
  1581. else
  1582. {
  1583. FFileZillaIntf->Delete(FileNameOnly.c_str(), FilePath.c_str(), false);
  1584. }
  1585. }
  1586. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1587. }
  1588. }
  1589. //---------------------------------------------------------------------------
  1590. void __fastcall TFTPFileSystem::CustomCommandOnFile(const UnicodeString /*FileName*/,
  1591. const TRemoteFile * /*File*/, UnicodeString /*Command*/, int /*Params*/,
  1592. TCaptureOutputEvent /*OutputEvent*/)
  1593. {
  1594. // if ever implemented, do not forget to add EnsureLocation,
  1595. // see AnyCommand for a reason why
  1596. DebugFail();
  1597. }
  1598. //---------------------------------------------------------------------------
  1599. void __fastcall TFTPFileSystem::DoStartup()
  1600. {
  1601. TStrings * PostLoginCommands = new TStringList();
  1602. try
  1603. {
  1604. PostLoginCommands->Text = FTerminal->SessionData->PostLoginCommands;
  1605. for (int Index = 0; Index < PostLoginCommands->Count; Index++)
  1606. {
  1607. UnicodeString Command = PostLoginCommands->Strings[Index];
  1608. if (!Command.IsEmpty())
  1609. {
  1610. SendCommand(Command);
  1611. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_3XX_CODE);
  1612. }
  1613. }
  1614. }
  1615. __finally
  1616. {
  1617. delete PostLoginCommands;
  1618. }
  1619. // retrieve initialize working directory to save it as home directory
  1620. ReadCurrentDirectory();
  1621. FHomeDirectory = FCurrentDirectory;
  1622. }
  1623. //---------------------------------------------------------------------------
  1624. void __fastcall TFTPFileSystem::HomeDirectory()
  1625. {
  1626. // FHomeDirectory is an absolute path, so avoid unnecessary overhead
  1627. // of ChangeDirectory, such as EnsureLocation
  1628. DoChangeDirectory(FHomeDirectory);
  1629. FCurrentDirectory = FHomeDirectory;
  1630. FReadCurrentDirectory = false;
  1631. // make sure FZAPI is aware that we changed current working directory
  1632. FFileZillaIntf->SetCurrentPath(FCurrentDirectory.c_str());
  1633. }
  1634. //---------------------------------------------------------------------------
  1635. bool __fastcall TFTPFileSystem::IsCapable(int Capability) const
  1636. {
  1637. DebugAssert(FTerminal);
  1638. switch (Capability)
  1639. {
  1640. case fcResolveSymlink: // sic
  1641. case fcTextMode:
  1642. case fcModeChanging: // but not fcModeChangingUpload
  1643. case fcNewerOnlyUpload:
  1644. case fcAnyCommand: // but not fcShellAnyCommand
  1645. case fcRename:
  1646. case fcRemoteMove:
  1647. case fcRemoveBOMUpload:
  1648. case fcMoveToQueue:
  1649. case fsSkipTransfer:
  1650. case fsParallelTransfers:
  1651. return true;
  1652. case fcPreservingTimestampUpload:
  1653. return (FServerCapabilities->GetCapability(mfmt_command) == yes);
  1654. case fcRemoteCopy:
  1655. return SupportsSiteCommand(CopySiteCommand);
  1656. case fcSymbolicLink:
  1657. return SupportsSiteCommand(SymlinkSiteCommand);
  1658. case fcCalculatingChecksum:
  1659. return FSupportsAnyChecksumFeature;
  1660. case fcCheckingSpaceAvailable:
  1661. return FBytesAvailableSuppoted || SupportsCommand(AvblCommand) || SupportsCommand(XQuotaCommand);
  1662. case fcModeChangingUpload:
  1663. case fcLoadingAdditionalProperties:
  1664. case fcShellAnyCommand:
  1665. case fcHardLink:
  1666. case fcUserGroupListing:
  1667. case fcGroupChanging:
  1668. case fcOwnerChanging:
  1669. case fcGroupOwnerChangingByID:
  1670. case fcSecondaryShell:
  1671. case fcNativeTextMode:
  1672. case fcTimestampChanging:
  1673. case fcIgnorePermErrors:
  1674. case fcRemoveCtrlZUpload:
  1675. case fcLocking:
  1676. case fcPreservingTimestampDirs:
  1677. case fcResumeSupport:
  1678. case fcChangePassword:
  1679. return false;
  1680. default:
  1681. DebugFail();
  1682. return false;
  1683. }
  1684. }
  1685. //---------------------------------------------------------------------------
  1686. void __fastcall TFTPFileSystem::LookupUsersGroups()
  1687. {
  1688. DebugFail();
  1689. }
  1690. //---------------------------------------------------------------------------
  1691. void __fastcall TFTPFileSystem::ReadCurrentDirectory()
  1692. {
  1693. // ask the server for current directory on startup only
  1694. // and immediately after call to CWD,
  1695. // later our current directory may be not synchronized with FZAPI current
  1696. // directory anyway, see comments in EnsureLocation
  1697. if (FReadCurrentDirectory || DebugAlwaysFalse(FCurrentDirectory.IsEmpty()))
  1698. {
  1699. UnicodeString Command = L"PWD";
  1700. SendCommand(Command);
  1701. unsigned int Code;
  1702. TStrings * Response = NULL;
  1703. GotReply(WaitForCommandReply(), REPLY_2XX_CODE, L"", &Code, &Response);
  1704. try
  1705. {
  1706. DebugAssert(Response != NULL);
  1707. bool Result = false;
  1708. // the only allowed 2XX code to "PWD"
  1709. if ((Code == 257) &&
  1710. (Response->Count == 1))
  1711. {
  1712. UnicodeString Path = Response->Text;
  1713. int P = Path.Pos(L"\"");
  1714. if (P == 0)
  1715. {
  1716. // some systems use single quotes, be tolerant
  1717. P = Path.Pos(L"'");
  1718. }
  1719. if (P != 0)
  1720. {
  1721. Path.Delete(1, P - 1);
  1722. if (Unquote(Path))
  1723. {
  1724. Result = true;
  1725. }
  1726. }
  1727. else
  1728. {
  1729. P = Path.Pos(L" ");
  1730. Path.Delete(P, Path.Length() - P + 1);
  1731. Result = true;
  1732. }
  1733. if (Result)
  1734. {
  1735. if ((Path.Length() > 0) && !UnixIsAbsolutePath(Path))
  1736. {
  1737. Path = L"/" + Path;
  1738. }
  1739. FCurrentDirectory = UnixExcludeTrailingBackslash(Path);
  1740. FReadCurrentDirectory = false;
  1741. }
  1742. }
  1743. if (Result)
  1744. {
  1745. FFileZillaIntf->SetCurrentPath(FCurrentDirectory.c_str());
  1746. }
  1747. else
  1748. {
  1749. throw Exception(FMTLOAD(FTP_RESPONSE_ERROR, (Command, Response->Text)));
  1750. }
  1751. }
  1752. __finally
  1753. {
  1754. delete Response;
  1755. }
  1756. }
  1757. }
  1758. //---------------------------------------------------------------------------
  1759. void __fastcall TFTPFileSystem::DoReadDirectory(TRemoteFileList * FileList)
  1760. {
  1761. FBytesAvailable = -1;
  1762. FileList->Reset();
  1763. // FZAPI does not list parent directory, add it
  1764. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  1765. FLastReadDirectoryProgress = 0;
  1766. TFileListHelper Helper(this, FileList, false);
  1767. // always specify path to list, do not attempt to list "current" dir as:
  1768. // 1) List() lists again the last listed directory, not the current working directory
  1769. // 2) we handle this way the cached directory change
  1770. UnicodeString Directory = AbsolutePath(FileList->Directory, false);
  1771. FFileZillaIntf->List(Directory.c_str());
  1772. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_ALLOW_CANCEL);
  1773. AutoDetectTimeDifference(FileList);
  1774. if (!IsEmptyFileList(FileList))
  1775. {
  1776. CheckTimeDifference();
  1777. if ((FTimeDifference != 0) || !FUploadedTimes.empty())// optimization
  1778. {
  1779. for (int Index = 0; Index < FileList->Count; Index++)
  1780. {
  1781. ApplyTimeDifference(FileList->Files[Index]);
  1782. }
  1783. }
  1784. }
  1785. FLastDataSent = Now();
  1786. }
  1787. //---------------------------------------------------------------------------
  1788. void __fastcall TFTPFileSystem::CheckTimeDifference()
  1789. {
  1790. if (NeedAutoDetectTimeDifference())
  1791. {
  1792. FTerminal->LogEvent("Warning: Timezone difference was not detected yet, timestamps may be incorrect");
  1793. }
  1794. }
  1795. //---------------------------------------------------------------------------
  1796. void __fastcall TFTPFileSystem::ApplyTimeDifference(TRemoteFile * File)
  1797. {
  1798. DebugAssert(File->Modification == File->LastAccess);
  1799. File->ShiftTimeInSeconds(FTimeDifference);
  1800. TDateTime Modification = File->Modification;
  1801. if (LookupUploadModificationTime(File->FullFileName, Modification, File->ModificationFmt))
  1802. {
  1803. // implicitly sets ModificationFmt to mfFull
  1804. File->Modification = Modification;
  1805. }
  1806. }
  1807. //---------------------------------------------------------------------------
  1808. void __fastcall TFTPFileSystem::ApplyTimeDifference(
  1809. const UnicodeString & FileName, TDateTime & Modification, TModificationFmt & ModificationFmt)
  1810. {
  1811. CheckTimeDifference();
  1812. TRemoteFile::ShiftTimeInSeconds(Modification, ModificationFmt, FTimeDifference);
  1813. if (LookupUploadModificationTime(FileName, Modification, ModificationFmt))
  1814. {
  1815. ModificationFmt = mfFull;
  1816. }
  1817. }
  1818. //---------------------------------------------------------------------------
  1819. bool __fastcall TFTPFileSystem::LookupUploadModificationTime(
  1820. const UnicodeString & FileName, TDateTime & Modification, TModificationFmt ModificationFmt)
  1821. {
  1822. bool Result = false;
  1823. if (ModificationFmt != mfFull)
  1824. {
  1825. TUploadedTimes::iterator Iterator = FUploadedTimes.find(AbsolutePath(FileName, false));
  1826. if (Iterator != FUploadedTimes.end())
  1827. {
  1828. TDateTime UploadModification = Iterator->second;
  1829. TDateTime UploadModificationReduced = ReduceDateTimePrecision(UploadModification, ModificationFmt);
  1830. if (UploadModificationReduced == Modification)
  1831. {
  1832. if ((FTerminal->Configuration->ActualLogProtocol >= 2))
  1833. {
  1834. FTerminal->LogEvent(
  1835. FORMAT(L"Enriching modification time of \"%s\" from [%s] to [%s]",
  1836. (FileName, StandardTimestamp(Modification), StandardTimestamp(UploadModification))));
  1837. }
  1838. Modification = UploadModification;
  1839. Result = true;
  1840. }
  1841. else
  1842. {
  1843. if ((FTerminal->Configuration->ActualLogProtocol >= 2))
  1844. {
  1845. FTerminal->LogEvent(
  1846. FORMAT(L"Remembered modification time [%s]/[%s] of \"%s\" is obsolete, keeping [%s]",
  1847. (StandardTimestamp(UploadModification), StandardTimestamp(UploadModificationReduced), FileName, StandardTimestamp(Modification))));
  1848. }
  1849. FUploadedTimes.erase(Iterator);
  1850. }
  1851. }
  1852. }
  1853. return Result;
  1854. }
  1855. //---------------------------------------------------------------------------
  1856. bool __fastcall TFTPFileSystem::NeedAutoDetectTimeDifference()
  1857. {
  1858. return
  1859. FDetectTimeDifference &&
  1860. // Does not support MLST/MLSD, but supports MDTM at least
  1861. !FFileZillaIntf->UsingMlsd() && SupportsReadingFile();
  1862. }
  1863. //---------------------------------------------------------------------------
  1864. bool __fastcall TFTPFileSystem::IsEmptyFileList(TRemoteFileList * FileList)
  1865. {
  1866. return
  1867. // (note that it's actually never empty here, there's always at least parent directory,
  1868. // added explicitly by DoReadDirectory)
  1869. (FileList->Count == 0) ||
  1870. ((FileList->Count == 1) && FileList->Files[0]->IsParentDirectory);
  1871. }
  1872. //---------------------------------------------------------------------------
  1873. void __fastcall TFTPFileSystem::AutoDetectTimeDifference(TRemoteFileList * FileList)
  1874. {
  1875. if (NeedAutoDetectTimeDifference())
  1876. {
  1877. FTerminal->LogEvent(L"Detecting timezone difference...");
  1878. for (int Index = 0; Index < FileList->Count; Index++)
  1879. {
  1880. TRemoteFile * File = FileList->Files[Index];
  1881. // For directories, we do not do MDTM in ReadFile
  1882. // (it should not be problem to use them otherwise).
  1883. // We are also not interested in files with day precision only.
  1884. if (!File->IsDirectory && !File->IsSymLink &&
  1885. File->IsTimeShiftingApplicable())
  1886. {
  1887. TRemoteFile * UtcFile = NULL;
  1888. try
  1889. {
  1890. ReadFile(File->FullFileName, UtcFile);
  1891. }
  1892. catch (Exception & E)
  1893. {
  1894. FDetectTimeDifference = false;
  1895. if (!FTerminal->Active)
  1896. {
  1897. throw;
  1898. }
  1899. FTerminal->LogEvent(FORMAT(L"Failed to retrieve file %s attributes to detect timezone difference", (File->FullFileName)));
  1900. break;
  1901. }
  1902. TDateTime UtcModification = UtcFile->Modification;
  1903. delete UtcFile;
  1904. if (UtcModification > Now())
  1905. {
  1906. FTerminal->LogEvent(
  1907. FORMAT(L"Not using file %s to detect timezone difference as it has the timestamp in the future [%s]",
  1908. (File->FullFileName, StandardTimestamp(UtcModification))));
  1909. }
  1910. // "SecureLink FTP Proxy" succeeds CWD for a file, so we never get a timestamp here
  1911. else if (UtcModification == TDateTime())
  1912. {
  1913. FTerminal->LogEvent(
  1914. FORMAT(L"Not using file %s to detect timezone difference as its timestamp was not resolved",
  1915. (File->FullFileName)));
  1916. }
  1917. else
  1918. {
  1919. FDetectTimeDifference = false;
  1920. // MDTM returns seconds, trim those
  1921. UtcModification = ReduceDateTimePrecision(UtcModification, File->ModificationFmt);
  1922. // Time difference between timestamp retrieved using MDTM (UTC converted to local timezone)
  1923. // and using LIST (no conversion, expecting the server uses the same timezone as the client).
  1924. // Note that FormatTimeZone reverses the value.
  1925. FTimeDifference = static_cast<__int64>(SecsPerDay * (UtcModification - File->Modification));
  1926. UnicodeString FileLog =
  1927. FORMAT(L"%s (Listing: %s, UTC: %s)", (File->FullFileName, StandardTimestamp(File->Modification), StandardTimestamp(UtcModification)));
  1928. UnicodeString LogMessage;
  1929. if (FTimeDifference == 0)
  1930. {
  1931. LogMessage = FORMAT(L"No timezone difference detected using file %s", (FileLog));
  1932. }
  1933. else
  1934. {
  1935. LogMessage = FORMAT(L"Timezone difference of %s detected using file %s", (FormatTimeZone(FTimeDifference), FileLog));
  1936. }
  1937. FTerminal->LogEvent(LogMessage);
  1938. break;
  1939. }
  1940. }
  1941. }
  1942. if (FDetectTimeDifference)
  1943. {
  1944. FTerminal->LogEvent(L"Found no file to use for detecting timezone difference");
  1945. }
  1946. }
  1947. }
  1948. //---------------------------------------------------------------------------
  1949. void __fastcall TFTPFileSystem::AutoDetectTimeDifference(
  1950. const UnicodeString & Directory, const TCopyParamType * CopyParam, int Params)
  1951. {
  1952. if (NeedAutoDetectTimeDifference() &&
  1953. // do we need FTimeDifference for the operation?
  1954. // (tmAutomatic - AsciiFileMask can theoretically include time constraints, while it is unlikely)
  1955. (!FLAGSET(Params, cpNoConfirmation) ||
  1956. CopyParam->NewerOnly || (!CopyParam->TransferMode == tmAutomatic) || !CopyParam->IncludeFileMask.Masks.IsEmpty()))
  1957. {
  1958. FTerminal->LogEvent(L"Retrieving listing to detect timezone difference");
  1959. DummyReadDirectory(Directory);
  1960. }
  1961. }
  1962. //---------------------------------------------------------------------------
  1963. void __fastcall TFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  1964. {
  1965. // whole below "-a" logic is for LIST,
  1966. // if we know we are going to use MLSD, skip it
  1967. if (FFileZillaIntf->UsingMlsd())
  1968. {
  1969. DoReadDirectory(FileList);
  1970. }
  1971. else
  1972. {
  1973. bool GotNoFilesForAll = false;
  1974. bool Repeat;
  1975. do
  1976. {
  1977. Repeat = false;
  1978. try
  1979. {
  1980. FDoListAll = (FListAll == asAuto) || (FListAll == asOn);
  1981. DoReadDirectory(FileList);
  1982. // We got no files with "-a", but again no files w/o "-a",
  1983. // so it was not "-a"'s problem, revert to auto and let it decide the next time
  1984. if (GotNoFilesForAll && (FileList->Count == 0))
  1985. {
  1986. DebugAssert(FListAll == asOff);
  1987. FListAll = asAuto;
  1988. }
  1989. else if (FListAll == asAuto)
  1990. {
  1991. // some servers take "-a" as a mask and return empty directory listing
  1992. if (IsEmptyFileList(FileList))
  1993. {
  1994. Repeat = true;
  1995. FListAll = asOff;
  1996. GotNoFilesForAll = true;
  1997. FTerminal->LogEvent(L"LIST with -a switch returned empty directory listing, will try pure LIST");
  1998. }
  1999. else
  2000. {
  2001. // reading first directory has succeeded, always use "-a"
  2002. FListAll = asOn;
  2003. }
  2004. }
  2005. // use "-a" even for implicit directory reading by FZAPI?
  2006. // (e.g. before file transfer)
  2007. FDoListAll = (FListAll == asOn);
  2008. }
  2009. catch(Exception & E)
  2010. {
  2011. FDoListAll = false;
  2012. // reading the first directory has failed,
  2013. // further try without "-a" only as the server may not support it
  2014. if (FListAll == asAuto)
  2015. {
  2016. FTerminal->LogEvent(L"LIST with -a failed, will try pure LIST");
  2017. if (!FTerminal->Active)
  2018. {
  2019. FTerminal->Reopen(ropNoReadDirectory);
  2020. }
  2021. FListAll = asOff;
  2022. Repeat = true;
  2023. }
  2024. else
  2025. {
  2026. throw;
  2027. }
  2028. }
  2029. }
  2030. while (Repeat);
  2031. }
  2032. }
  2033. //---------------------------------------------------------------------------
  2034. void __fastcall TFTPFileSystem::DoReadFile(const UnicodeString & AFileName,
  2035. TRemoteFile *& AFile)
  2036. {
  2037. UnicodeString FileName = AbsolutePath(AFileName, false);
  2038. UnicodeString FileNameOnly;
  2039. UnicodeString FilePath;
  2040. if (IsUnixRootPath(FileName))
  2041. {
  2042. FileNameOnly = FileName;
  2043. FilePath = FileName;
  2044. }
  2045. else
  2046. {
  2047. FileNameOnly = UnixExtractFileName(FileName);
  2048. FilePath = UnixExtractFilePath(FileName);
  2049. }
  2050. TRemoteFileList * FileList = new TRemoteFileList();
  2051. try
  2052. {
  2053. // Duplicate() call below would use this to compose FullFileName
  2054. FileList->Directory = FilePath;
  2055. TFileListHelper Helper(this, FileList, false);
  2056. FFileZillaIntf->ListFile(FileNameOnly.c_str(), FilePath.c_str());
  2057. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_ALLOW_CANCEL);
  2058. TRemoteFile * File = FileList->FindFile(FileNameOnly);
  2059. if (File != NULL)
  2060. {
  2061. AFile = File->Duplicate();
  2062. }
  2063. FLastDataSent = Now();
  2064. }
  2065. __finally
  2066. {
  2067. delete FileList;
  2068. }
  2069. }
  2070. //---------------------------------------------------------------------------
  2071. bool __fastcall TFTPFileSystem::SupportsReadingFile()
  2072. {
  2073. return
  2074. FFileZillaIntf->UsingMlsd() ||
  2075. ((FServerCapabilities->GetCapability(mdtm_command) == yes) &&
  2076. (FServerCapabilities->GetCapability(size_command) == yes));
  2077. }
  2078. //---------------------------------------------------------------------------
  2079. void __fastcall TFTPFileSystem::ReadFile(const UnicodeString FileName,
  2080. TRemoteFile *& File)
  2081. {
  2082. File = NULL;
  2083. if (SupportsReadingFile())
  2084. {
  2085. DoReadFile(FileName, File);
  2086. }
  2087. else
  2088. {
  2089. if (IsUnixRootPath(FileName))
  2090. {
  2091. FTerminal->LogEvent(FORMAT(L"%s is a root path", (FileName)));
  2092. File = new TRemoteDirectoryFile();
  2093. File->FullFileName = FileName;
  2094. File->FileName = L"";
  2095. }
  2096. else
  2097. {
  2098. UnicodeString Path = UnixExtractFilePath(FileName);
  2099. UnicodeString NameOnly;
  2100. int P;
  2101. bool MVSPath =
  2102. FMVS && Path.IsEmpty() &&
  2103. (FileName.SubString(1, 1) == L"'") && (FileName.SubString(FileName.Length(), 1) == L"'") &&
  2104. ((P = FileName.Pos(L".")) > 0);
  2105. if (!MVSPath)
  2106. {
  2107. NameOnly = UnixExtractFileName(FileName);
  2108. }
  2109. else
  2110. {
  2111. NameOnly = FileName.SubString(P + 1, FileName.Length() - P - 1);
  2112. }
  2113. TRemoteFile * AFile = NULL;
  2114. // FZAPI does not have efficient way to read properties of one file.
  2115. // In case we need properties of set of files from the same directory,
  2116. // cache the file list for future
  2117. if ((FFileListCache != NULL) &&
  2118. UnixSamePath(Path, FFileListCache->Directory) &&
  2119. (UnixIsAbsolutePath(FFileListCache->Directory) ||
  2120. (FFileListCachePath == CurrentDirectory)))
  2121. {
  2122. AFile = FFileListCache->FindFile(NameOnly);
  2123. }
  2124. // if cache is invalid or file is not in cache, (re)read the directory
  2125. if (AFile == NULL)
  2126. {
  2127. TRemoteFileList * FileListCache = new TRemoteFileList();
  2128. FileListCache->Directory = Path;
  2129. try
  2130. {
  2131. ReadDirectory(FileListCache);
  2132. }
  2133. catch(...)
  2134. {
  2135. delete FileListCache;
  2136. throw;
  2137. }
  2138. // set only after we successfully read the directory,
  2139. // otherwise, when we reconnect from ReadDirectory,
  2140. // the FFileListCache is reset from ResetCache.
  2141. delete FFileListCache;
  2142. FFileListCache = FileListCache;
  2143. FFileListCachePath = GetCurrentDirectory();
  2144. AFile = FFileListCache->FindFile(NameOnly);
  2145. }
  2146. if (AFile != NULL)
  2147. {
  2148. File = AFile->Duplicate();
  2149. if (MVSPath)
  2150. {
  2151. File->FileName = FileName;
  2152. File->FullFileName = FileName;
  2153. }
  2154. }
  2155. }
  2156. }
  2157. if (File == NULL)
  2158. {
  2159. throw Exception(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  2160. }
  2161. }
  2162. //---------------------------------------------------------------------------
  2163. void __fastcall TFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  2164. TRemoteFile *& File)
  2165. {
  2166. // Resolving symlinks over FTP is big overhead
  2167. // (involves opening TCPIP connection for retrieving "directory listing").
  2168. // Moreover FZAPI does not support that anyway.
  2169. // Though nowadays we could use MLST to read the symlink.
  2170. File = new TRemoteFile(SymlinkFile);
  2171. try
  2172. {
  2173. File->Terminal = FTerminal;
  2174. File->FileName = UnixExtractFileName(SymlinkFile->LinkTo);
  2175. // FZAPI treats all symlink target as directories
  2176. File->Type = FILETYPE_DIRECTORY;
  2177. }
  2178. catch(...)
  2179. {
  2180. delete File;
  2181. File = NULL;
  2182. throw;
  2183. }
  2184. }
  2185. //---------------------------------------------------------------------------
  2186. void __fastcall TFTPFileSystem::RenameFile(const UnicodeString AFileName, const TRemoteFile * /*File*/,
  2187. const UnicodeString ANewName)
  2188. {
  2189. UnicodeString FileName = AbsolutePath(AFileName, false);
  2190. UnicodeString NewName = AbsolutePath(ANewName, false);
  2191. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  2192. UnicodeString FilePathOnly = UnixExtractFilePath(FileName);
  2193. UnicodeString NewNameOnly = UnixExtractFileName(NewName);
  2194. UnicodeString NewPathOnly = UnixExtractFilePath(NewName);
  2195. {
  2196. // ignore file list
  2197. TFileListHelper Helper(this, NULL, true);
  2198. FFileZillaIntf->Rename(FileNameOnly.c_str(), NewNameOnly.c_str(),
  2199. FilePathOnly.c_str(), NewPathOnly.c_str());
  2200. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  2201. }
  2202. }
  2203. //---------------------------------------------------------------------------
  2204. void __fastcall TFTPFileSystem::CopyFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  2205. const UnicodeString NewName)
  2206. {
  2207. DebugAssert(SupportsSiteCommand(CopySiteCommand));
  2208. EnsureLocation();
  2209. UnicodeString Command;
  2210. Command = FORMAT(L"%s CPFR %s", (SiteCommand, FileName));
  2211. SendCommand(Command);
  2212. GotReply(WaitForCommandReply(), REPLY_3XX_CODE);
  2213. Command = FORMAT(L"%s CPTO %s", (SiteCommand, NewName));
  2214. SendCommand(Command);
  2215. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  2216. }
  2217. //---------------------------------------------------------------------------
  2218. TStrings * __fastcall TFTPFileSystem::GetFixedPaths()
  2219. {
  2220. return NULL;
  2221. }
  2222. //---------------------------------------------------------------------------
  2223. void __fastcall TFTPFileSystem::SpaceAvailable(const UnicodeString Path,
  2224. TSpaceAvailable & ASpaceAvailable)
  2225. {
  2226. if (FBytesAvailableSuppoted)
  2227. {
  2228. std::unique_ptr<TRemoteFileList> DummyFileList(new TRemoteFileList());
  2229. DummyFileList->Directory = Path;
  2230. ReadDirectory(DummyFileList.get());
  2231. ASpaceAvailable.UnusedBytesAvailableToUser = FBytesAvailable;
  2232. }
  2233. else if (SupportsCommand(XQuotaCommand))
  2234. {
  2235. // WS_FTP:
  2236. // XQUOTA
  2237. // 213-File and disk usage
  2238. // File count: 3
  2239. // File limit: 10000
  2240. // Disk usage: 1532791
  2241. // Disk limit: 2048000
  2242. // 213 File and disk usage end
  2243. // XQUOTA is global not path-specific
  2244. UnicodeString Command = XQuotaCommand;
  2245. SendCommand(Command);
  2246. TStrings * Response = NULL;
  2247. GotReply(WaitForCommandReply(), REPLY_2XX_CODE, L"", NULL, &Response);
  2248. std::unique_ptr<TStrings> ResponseOwner(Response);
  2249. __int64 UsedBytes = -1;
  2250. for (int Index = 0; Index < Response->Count; Index++)
  2251. {
  2252. // trimming padding
  2253. UnicodeString Line = Trim(Response->Strings[Index]);
  2254. UnicodeString Label = CutToChar(Line, L':', true);
  2255. if (SameText(Label, L"Disk usage"))
  2256. {
  2257. UsedBytes = StrToInt64(Line);
  2258. }
  2259. else if (SameText(Label, L"Disk limit") && !SameText(Line, L"unlimited"))
  2260. {
  2261. ASpaceAvailable.BytesAvailableToUser = StrToInt64(Line);
  2262. }
  2263. }
  2264. if ((UsedBytes >= 0) && (ASpaceAvailable.BytesAvailableToUser > 0))
  2265. {
  2266. ASpaceAvailable.UnusedBytesAvailableToUser = ASpaceAvailable.BytesAvailableToUser - UsedBytes;
  2267. }
  2268. }
  2269. else if (SupportsCommand(AvblCommand))
  2270. {
  2271. // draft-peterson-streamlined-ftp-command-extensions-10
  2272. // Implemented by Serv-U.
  2273. UnicodeString Command = FORMAT(L"%s %s", (AvblCommand, Path));
  2274. SendCommand(Command);
  2275. UnicodeString Response = GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_SINGLE_LINE);
  2276. ASpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(Response);
  2277. }
  2278. }
  2279. //---------------------------------------------------------------------------
  2280. const TSessionInfo & __fastcall TFTPFileSystem::GetSessionInfo()
  2281. {
  2282. return FSessionInfo;
  2283. }
  2284. //---------------------------------------------------------------------------
  2285. const TFileSystemInfo & __fastcall TFTPFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  2286. {
  2287. if (!FFileSystemInfoValid)
  2288. {
  2289. FFileSystemInfo.RemoteSystem = FSystem;
  2290. FFileSystemInfo.RemoteSystem.Unique();
  2291. if (FFeatures->Count == 0)
  2292. {
  2293. FFileSystemInfo.AdditionalInfo = LoadStr(FTP_NO_FEATURE_INFO);
  2294. }
  2295. else
  2296. {
  2297. FFileSystemInfo.AdditionalInfo =
  2298. FORMAT(L"%s\r\n", (LoadStr(FTP_FEATURE_INFO)));
  2299. for (int Index = 0; Index < FFeatures->Count; Index++)
  2300. {
  2301. // For TrimLeft, refer to HandleFeatReply
  2302. FFileSystemInfo.AdditionalInfo += FORMAT(L" %s\r\n", (TrimLeft(FFeatures->Strings[Index])));
  2303. }
  2304. }
  2305. FTerminal->SaveCapabilities(FFileSystemInfo);
  2306. FFileSystemInfoValid = true;
  2307. }
  2308. return FFileSystemInfo;
  2309. }
  2310. //---------------------------------------------------------------------------
  2311. bool __fastcall TFTPFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
  2312. {
  2313. return false;
  2314. }
  2315. //---------------------------------------------------------------------------
  2316. bool __fastcall TFTPFileSystem::GetStoredCredentialsTried()
  2317. {
  2318. return FStoredPasswordTried;
  2319. }
  2320. //---------------------------------------------------------------------------
  2321. UnicodeString __fastcall TFTPFileSystem::GetUserName()
  2322. {
  2323. return FUserName;
  2324. }
  2325. //---------------------------------------------------------------------------
  2326. UnicodeString __fastcall TFTPFileSystem::GetCurrentDirectory()
  2327. {
  2328. return FCurrentDirectory;
  2329. }
  2330. //---------------------------------------------------------------------------
  2331. const wchar_t * __fastcall TFTPFileSystem::GetOption(int OptionID) const
  2332. {
  2333. TSessionData * Data = FTerminal->SessionData;
  2334. switch (OptionID)
  2335. {
  2336. case OPTION_PROXYHOST:
  2337. case OPTION_FWHOST:
  2338. FOptionScratch = Data->ProxyHost;
  2339. break;
  2340. case OPTION_PROXYUSER:
  2341. case OPTION_FWUSER:
  2342. FOptionScratch = Data->ProxyUsername;
  2343. break;
  2344. case OPTION_PROXYPASS:
  2345. case OPTION_FWPASS:
  2346. FOptionScratch = Data->ProxyPassword;
  2347. break;
  2348. case OPTION_TRANSFERIP:
  2349. FOptionScratch = FTerminal->Configuration->ExternalIpAddress;
  2350. break;
  2351. case OPTION_ANONPWD:
  2352. case OPTION_TRANSFERIP6:
  2353. FOptionScratch = L"";
  2354. break;
  2355. default:
  2356. DebugFail();
  2357. FOptionScratch = L"";
  2358. }
  2359. return FOptionScratch.c_str();
  2360. }
  2361. //---------------------------------------------------------------------------
  2362. int __fastcall TFTPFileSystem::GetOptionVal(int OptionID) const
  2363. {
  2364. TSessionData * Data = FTerminal->SessionData;
  2365. int Result;
  2366. switch (OptionID)
  2367. {
  2368. case OPTION_PROXYTYPE:
  2369. switch (Data->ProxyMethod)
  2370. {
  2371. case ::pmNone:
  2372. Result = 0; // PROXYTYPE_NOPROXY;
  2373. break;
  2374. case pmSocks4:
  2375. Result = 2; // PROXYTYPE_SOCKS4A
  2376. break;
  2377. case pmSocks5:
  2378. Result = 3; // PROXYTYPE_SOCKS5
  2379. break;
  2380. case pmHTTP:
  2381. Result = 4; // PROXYTYPE_HTTP11
  2382. break;
  2383. case pmTelnet:
  2384. case pmCmd:
  2385. default:
  2386. DebugFail();
  2387. Result = 0; // PROXYTYPE_NOPROXY;
  2388. break;
  2389. }
  2390. break;
  2391. case OPTION_PROXYPORT:
  2392. case OPTION_FWPORT:
  2393. Result = Data->ProxyPort;
  2394. break;
  2395. case OPTION_PROXYUSELOGON:
  2396. Result = !Data->ProxyUsername.IsEmpty();
  2397. break;
  2398. case OPTION_LOGONTYPE:
  2399. Result = Data->FtpProxyLogonType;
  2400. break;
  2401. case OPTION_TIMEOUTLENGTH:
  2402. Result = Data->Timeout;
  2403. break;
  2404. case OPTION_DEBUGSHOWLISTING:
  2405. Result = (FTerminal->Configuration->ActualLogProtocol >= 0);
  2406. break;
  2407. case OPTION_PASV:
  2408. // should never get here t_server.nPasv being nonzero
  2409. DebugFail();
  2410. Result = FALSE;
  2411. break;
  2412. case OPTION_PRESERVEDOWNLOADFILETIME:
  2413. case OPTION_MPEXT_PRESERVEUPLOADFILETIME:
  2414. Result = FFileTransferPreserveTime ? TRUE : FALSE;
  2415. break;
  2416. case OPTION_LIMITPORTRANGE:
  2417. Result = FALSE;
  2418. break;
  2419. case OPTION_PORTRANGELOW:
  2420. case OPTION_PORTRANGEHIGH:
  2421. // should never get here OPTION_LIMITPORTRANGE being zero
  2422. DebugFail();
  2423. Result = 0;
  2424. break;
  2425. case OPTION_ENABLE_IPV6:
  2426. Result = ((Data->AddressFamily != afIPv4) ? TRUE : FALSE);
  2427. break;
  2428. case OPTION_KEEPALIVE:
  2429. Result = ((Data->FtpPingType != ptOff) ? TRUE : FALSE);
  2430. break;
  2431. case OPTION_INTERVALLOW:
  2432. case OPTION_INTERVALHIGH:
  2433. Result = Data->FtpPingInterval;
  2434. break;
  2435. case OPTION_VMSALLREVISIONS:
  2436. Result = FALSE;
  2437. break;
  2438. case OPTION_SPEEDLIMIT_DOWNLOAD_TYPE:
  2439. case OPTION_SPEEDLIMIT_UPLOAD_TYPE:
  2440. Result = (FFileTransferCPSLimit == 0 ? 0 : 1);
  2441. break;
  2442. case OPTION_SPEEDLIMIT_DOWNLOAD_VALUE:
  2443. case OPTION_SPEEDLIMIT_UPLOAD_VALUE:
  2444. Result = (FFileTransferCPSLimit / 1024); // FZAPI expects KB/s
  2445. break;
  2446. case OPTION_MPEXT_SHOWHIDDEN:
  2447. Result = (FDoListAll ? TRUE : FALSE);
  2448. break;
  2449. case OPTION_MPEXT_SSLSESSIONREUSE:
  2450. Result = (Data->SslSessionReuse ? TRUE : FALSE);
  2451. break;
  2452. case OPTION_MPEXT_MIN_TLS_VERSION:
  2453. Result = Data->MinTlsVersion;
  2454. break;
  2455. case OPTION_MPEXT_MAX_TLS_VERSION:
  2456. Result = Data->MaxTlsVersion;
  2457. break;
  2458. case OPTION_MPEXT_SNDBUF:
  2459. Result = Data->SendBuf;
  2460. break;
  2461. case OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY:
  2462. Result = FTransferActiveImmediately;
  2463. break;
  2464. case OPTION_MPEXT_REMOVE_BOM:
  2465. Result = FFileTransferRemoveBOM ? TRUE : FALSE;
  2466. break;
  2467. case OPTION_MPEXT_LOG_SENSITIVE:
  2468. Result = FTerminal->Configuration->LogSensitive ? TRUE : FALSE;
  2469. break;
  2470. case OPTION_MPEXT_HOST:
  2471. Result = (Data->FtpHost == asOn);
  2472. break;
  2473. case OPTION_MPEXT_NODELAY:
  2474. Result = Data->TcpNoDelay;
  2475. break;
  2476. case OPTION_MPEXT_NOLIST:
  2477. Result = FFileTransferNoList ? TRUE : FALSE;
  2478. break;
  2479. default:
  2480. DebugFail();
  2481. Result = FALSE;
  2482. break;
  2483. }
  2484. return Result;
  2485. }
  2486. //---------------------------------------------------------------------------
  2487. bool __fastcall TFTPFileSystem::PostMessage(unsigned int Type, WPARAM wParam, LPARAM lParam)
  2488. {
  2489. if (Type == TFileZillaIntf::MSG_TRANSFERSTATUS)
  2490. {
  2491. // Stop here if FileTransferProgress is proceeding,
  2492. // it makes "pause" in queue work.
  2493. // Paused queue item stops in some of the TFileOperationProgressType
  2494. // methods called from FileTransferProgress
  2495. TGuard Guard(FTransferStatusCriticalSection);
  2496. }
  2497. TGuard Guard(FQueueCriticalSection);
  2498. FQueue->push_back(TMessageQueue::value_type(wParam, lParam));
  2499. SetEvent(FQueueEvent);
  2500. return true;
  2501. }
  2502. //---------------------------------------------------------------------------
  2503. bool __fastcall TFTPFileSystem::ProcessMessage()
  2504. {
  2505. bool Result;
  2506. TMessageQueue::value_type Message;
  2507. {
  2508. TGuard Guard(FQueueCriticalSection);
  2509. Result = !FQueue->empty();
  2510. if (Result)
  2511. {
  2512. Message = FQueue->front();
  2513. FQueue->pop_front();
  2514. }
  2515. else
  2516. {
  2517. // now we are perfectly sure that the queue is empty as it is locked,
  2518. // so reset the event
  2519. ResetEvent(FQueueEvent);
  2520. }
  2521. }
  2522. if (Result)
  2523. {
  2524. FFileZillaIntf->HandleMessage(Message.first, Message.second);
  2525. }
  2526. return Result;
  2527. }
  2528. //---------------------------------------------------------------------------
  2529. void __fastcall TFTPFileSystem::DiscardMessages()
  2530. {
  2531. while (ProcessMessage());
  2532. }
  2533. //---------------------------------------------------------------------------
  2534. void __fastcall TFTPFileSystem::WaitForMessages()
  2535. {
  2536. unsigned int Result;
  2537. do
  2538. {
  2539. Result = WaitForSingleObject(FQueueEvent, GUIUpdateInterval);
  2540. FTerminal->ProcessGUI();
  2541. } while (Result == WAIT_TIMEOUT);
  2542. if (Result != WAIT_OBJECT_0)
  2543. {
  2544. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, (L"ftp#1", IntToStr(int(Result)))));
  2545. }
  2546. }
  2547. //---------------------------------------------------------------------------
  2548. void __fastcall TFTPFileSystem::PoolForFatalNonCommandReply()
  2549. {
  2550. DebugAssert(FReply == 0);
  2551. DebugAssert(FCommandReply == 0);
  2552. DebugAssert(!FWaitingForReply);
  2553. FWaitingForReply = true;
  2554. unsigned int Reply;
  2555. try
  2556. {
  2557. // discard up to one reply
  2558. // (it should not happen here that two replies are posted anyway)
  2559. while (ProcessMessage() && (FReply == 0));
  2560. Reply = FReply;
  2561. }
  2562. __finally
  2563. {
  2564. FReply = 0;
  2565. DebugAssert(FCommandReply == 0);
  2566. FCommandReply = 0;
  2567. DebugAssert(FWaitingForReply);
  2568. FWaitingForReply = false;
  2569. }
  2570. if (Reply != 0)
  2571. {
  2572. // throws
  2573. GotNonCommandReply(Reply);
  2574. }
  2575. }
  2576. //---------------------------------------------------------------------------
  2577. bool __fastcall TFTPFileSystem::NoFinalLastCode()
  2578. {
  2579. return (FLastCodeClass == 0) || (FLastCodeClass == 1);
  2580. }
  2581. //---------------------------------------------------------------------------
  2582. bool __fastcall TFTPFileSystem::KeepWaitingForReply(unsigned int & ReplyToAwait, bool WantLastCode)
  2583. {
  2584. // To keep waiting,
  2585. // non-command reply must be unset,
  2586. // the reply we wait for must be unset or
  2587. // last code must be unset (if we wait for it).
  2588. // Though make sure that disconnect makes it through always. As for example when connection is closed already,
  2589. // when sending commands, we may get REPLY_DISCONNECTED as a command response and no other response after,
  2590. // what would cause a hang.
  2591. return
  2592. (FReply == 0) &&
  2593. ((ReplyToAwait == 0) ||
  2594. (WantLastCode && NoFinalLastCode() && FLAGCLEAR(ReplyToAwait, TFileZillaIntf::REPLY_DISCONNECTED)));
  2595. }
  2596. //---------------------------------------------------------------------------
  2597. void __fastcall TFTPFileSystem::DoWaitForReply(unsigned int & ReplyToAwait, bool WantLastCode)
  2598. {
  2599. try
  2600. {
  2601. while (KeepWaitingForReply(ReplyToAwait, WantLastCode))
  2602. {
  2603. WaitForMessages();
  2604. // wait for the first reply only,
  2605. // i.e. in case two replies are posted get the first only.
  2606. // e.g. when server closes the connection, but posts error message before,
  2607. // sometime it happens that command (like download) fails because of the error
  2608. // and does not catch the disconnection. then asynchronous "disconnect reply"
  2609. // is posted immediately afterwards. leave detection of that to Idle()
  2610. while (ProcessMessage() && KeepWaitingForReply(ReplyToAwait, WantLastCode));
  2611. }
  2612. if (FReply != 0)
  2613. {
  2614. // throws
  2615. GotNonCommandReply(FReply);
  2616. }
  2617. }
  2618. catch(...)
  2619. {
  2620. // even if non-fatal error happens, we must process pending message,
  2621. // so that we "eat" the reply message, so that it gets not mistakenly
  2622. // associated with future connect
  2623. if (FTerminal->Active)
  2624. {
  2625. DoWaitForReply(ReplyToAwait, WantLastCode);
  2626. }
  2627. throw;
  2628. }
  2629. }
  2630. //---------------------------------------------------------------------------
  2631. unsigned int __fastcall TFTPFileSystem::WaitForReply(bool Command, bool WantLastCode)
  2632. {
  2633. DebugAssert(FReply == 0);
  2634. DebugAssert(FCommandReply == 0);
  2635. DebugAssert(!FWaitingForReply);
  2636. ResetReply();
  2637. FWaitingForReply = true;
  2638. unsigned int Reply;
  2639. try
  2640. {
  2641. unsigned int & ReplyToAwait = (Command ? FCommandReply : FReply);
  2642. DoWaitForReply(ReplyToAwait, WantLastCode);
  2643. Reply = ReplyToAwait;
  2644. }
  2645. __finally
  2646. {
  2647. FReply = 0;
  2648. FCommandReply = 0;
  2649. DebugAssert(FWaitingForReply);
  2650. FWaitingForReply = false;
  2651. }
  2652. return Reply;
  2653. }
  2654. //---------------------------------------------------------------------------
  2655. unsigned int __fastcall TFTPFileSystem::WaitForCommandReply(bool WantLastCode)
  2656. {
  2657. return WaitForReply(true, WantLastCode);
  2658. }
  2659. //---------------------------------------------------------------------------
  2660. void __fastcall TFTPFileSystem::WaitForFatalNonCommandReply()
  2661. {
  2662. WaitForReply(false, false);
  2663. DebugFail();
  2664. }
  2665. //---------------------------------------------------------------------------
  2666. void __fastcall TFTPFileSystem::ResetReply()
  2667. {
  2668. FLastCode = 0;
  2669. FLastCodeClass = 0;
  2670. DebugAssert(FLastResponse != NULL);
  2671. FLastResponse->Clear();
  2672. DebugAssert(FLastErrorResponse != NULL);
  2673. FLastErrorResponse->Clear();
  2674. DebugAssert(FLastError != NULL);
  2675. FLastError->Clear();
  2676. }
  2677. //---------------------------------------------------------------------------
  2678. void __fastcall TFTPFileSystem::GotNonCommandReply(unsigned int Reply)
  2679. {
  2680. DebugAssert(FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2681. GotReply(Reply);
  2682. // should never get here as GotReply should raise fatal exception
  2683. DebugFail();
  2684. }
  2685. //---------------------------------------------------------------------------
  2686. void __fastcall TFTPFileSystem::Disconnect()
  2687. {
  2688. Discard();
  2689. FTerminal->Closed();
  2690. }
  2691. //---------------------------------------------------------------------------
  2692. UnicodeString __fastcall TFTPFileSystem::GotReply(unsigned int Reply, unsigned int Flags,
  2693. UnicodeString Error, unsigned int * Code, TStrings ** Response)
  2694. {
  2695. UnicodeString Result;
  2696. try
  2697. {
  2698. if (FLAGSET(Reply, TFileZillaIntf::REPLY_OK))
  2699. {
  2700. DebugAssert(Reply == TFileZillaIntf::REPLY_OK);
  2701. // With REPLY_2XX_CODE treat "OK" non-2xx code like an error.
  2702. // REPLY_3XX_CODE has to be always used along with REPLY_2XX_CODE.
  2703. if ((FLAGSET(Flags, REPLY_2XX_CODE) && (FLastCodeClass != 2)) &&
  2704. ((FLAGCLEAR(Flags, REPLY_3XX_CODE) || (FLastCodeClass != 3))))
  2705. {
  2706. GotReply(TFileZillaIntf::REPLY_ERROR, Flags, Error);
  2707. }
  2708. }
  2709. else if (FLAGSET(Reply, TFileZillaIntf::REPLY_CANCEL) &&
  2710. FLAGSET(Flags, REPLY_ALLOW_CANCEL))
  2711. {
  2712. DebugAssert(
  2713. (Reply == (TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)) ||
  2714. (Reply == (TFileZillaIntf::REPLY_ABORTED | TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)));
  2715. // noop
  2716. }
  2717. // we do not expect these with our usage of FZ
  2718. else if (Reply &
  2719. (TFileZillaIntf::REPLY_WOULDBLOCK | TFileZillaIntf::REPLY_OWNERNOTSET |
  2720. TFileZillaIntf::REPLY_INVALIDPARAM | TFileZillaIntf::REPLY_ALREADYCONNECTED |
  2721. TFileZillaIntf::REPLY_IDLE | TFileZillaIntf::REPLY_NOTINITIALIZED |
  2722. TFileZillaIntf::REPLY_ALREADYINIZIALIZED))
  2723. {
  2724. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, (L"ftp#2", FORMAT(L"0x%x", (int(Reply))))));
  2725. }
  2726. else
  2727. {
  2728. // everything else must be an error or disconnect notification
  2729. DebugAssert(
  2730. FLAGSET(Reply, TFileZillaIntf::REPLY_ERROR) ||
  2731. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2732. // TODO: REPLY_CRITICALERROR ignored
  2733. // REPLY_NOTCONNECTED happens if connection is closed between moment
  2734. // when FZAPI interface method dispatches the command to FZAPI thread
  2735. // and moment when FZAPI thread receives the command
  2736. bool Disconnected =
  2737. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED) ||
  2738. FLAGSET(Reply, TFileZillaIntf::REPLY_NOTCONNECTED);
  2739. UnicodeString HelpKeyword;
  2740. TStrings * MoreMessages = new TStringList();
  2741. try
  2742. {
  2743. if (Disconnected)
  2744. {
  2745. if (FLAGCLEAR(Flags, REPLY_CONNECT))
  2746. {
  2747. MoreMessages->Add(LoadStr(LOST_CONNECTION));
  2748. Disconnect();
  2749. }
  2750. else
  2751. {
  2752. // For connection failure, do not report that connection was lost,
  2753. // its obvious.
  2754. // Also do not report to terminal that we are closed as
  2755. // that turns terminal into closed mode, but we want to
  2756. // pretend (at least with failed authentication) to retry
  2757. // with the same connection (as with SSH), so we explicitly
  2758. // close terminal in Open() only after we give up
  2759. Discard();
  2760. }
  2761. }
  2762. if (FLAGSET(Reply, TFileZillaIntf::REPLY_ABORTED))
  2763. {
  2764. MoreMessages->Add(LoadStr(USER_TERMINATED));
  2765. }
  2766. if (FLAGSET(Reply, TFileZillaIntf::REPLY_NOTSUPPORTED))
  2767. {
  2768. MoreMessages->Add(LoadStr(NOTSUPPORTED));
  2769. }
  2770. if (FLastCode == 530)
  2771. {
  2772. // Serv-U also uses this code in response to "SITE PSWD"
  2773. MoreMessages->Add(LoadStr(AUTHENTICATION_FAILED));
  2774. }
  2775. if (FLastCode == 425)
  2776. {
  2777. if (!FTerminal->SessionData->FtpPasvMode)
  2778. {
  2779. MoreMessages->Add(LoadStr(FTP_CANNOT_OPEN_ACTIVE_CONNECTION2));
  2780. HelpKeyword = HELP_FTP_CANNOT_OPEN_ACTIVE_CONNECTION;
  2781. }
  2782. }
  2783. if (FLastCode == DummyTimeoutCode)
  2784. {
  2785. HelpKeyword = HELP_ERRORMSG_TIMEOUT;
  2786. }
  2787. if (FLastCode == DummyDisconnectCode)
  2788. {
  2789. HelpKeyword = HELP_STATUSMSG_DISCONNECTED;
  2790. }
  2791. MoreMessages->AddStrings(FLastError);
  2792. // already cleared from WaitForReply, but GotReply can be also called
  2793. // from Closed. then make sure that error from previous command not
  2794. // associated with session closure is not reused
  2795. FLastError->Clear();
  2796. MoreMessages->AddStrings(FLastErrorResponse);
  2797. // see comment for FLastError
  2798. FLastResponse->Clear();
  2799. FLastErrorResponse->Clear();
  2800. if (MoreMessages->Count == 0)
  2801. {
  2802. delete MoreMessages;
  2803. MoreMessages = NULL;
  2804. }
  2805. }
  2806. catch(...)
  2807. {
  2808. delete MoreMessages;
  2809. throw;
  2810. }
  2811. if (Error.IsEmpty() && (MoreMessages != NULL))
  2812. {
  2813. DebugAssert(MoreMessages->Count > 0);
  2814. // bit too generic assigning of main instructions, let's see how it works
  2815. Error = MainInstructions(MoreMessages->Strings[0]);
  2816. MoreMessages->Delete(0);
  2817. }
  2818. if (Disconnected)
  2819. {
  2820. // for fatal error, it is essential that there is some message
  2821. DebugAssert(!Error.IsEmpty());
  2822. ExtException * E = new ExtException(Error, MoreMessages, true, HelpKeyword);
  2823. try
  2824. {
  2825. FTerminal->FatalError(E, L"");
  2826. }
  2827. __finally
  2828. {
  2829. delete E;
  2830. }
  2831. }
  2832. else
  2833. {
  2834. throw ExtException(Error, MoreMessages, true, HelpKeyword);
  2835. }
  2836. }
  2837. if ((Code != NULL) && (FLastCodeClass != DummyCodeClass))
  2838. {
  2839. *Code = FLastCode;
  2840. }
  2841. if (FLAGSET(Flags, REPLY_SINGLE_LINE))
  2842. {
  2843. if (FLastResponse->Count != 1)
  2844. {
  2845. throw Exception(FMTLOAD(FTP_RESPONSE_ERROR, (FLastCommandSent, FLastResponse->Text)));
  2846. }
  2847. Result = FLastResponse->Strings[0];
  2848. }
  2849. if (Response != NULL)
  2850. {
  2851. *Response = FLastResponse;
  2852. FLastResponse = new TStringList();
  2853. // just to be consistent
  2854. delete FLastErrorResponse;
  2855. FLastErrorResponse = new TStringList();
  2856. }
  2857. }
  2858. __finally
  2859. {
  2860. ResetReply();
  2861. }
  2862. return Result;
  2863. }
  2864. //---------------------------------------------------------------------------
  2865. void __fastcall TFTPFileSystem::SendCommand(const UnicodeString & Command)
  2866. {
  2867. FFileZillaIntf->CustomCommand(Command.c_str());
  2868. FLastCommandSent = CopyToChar(Command, L' ', false);
  2869. }
  2870. //---------------------------------------------------------------------------
  2871. void __fastcall TFTPFileSystem::SetLastCode(int Code)
  2872. {
  2873. FLastCode = Code;
  2874. FLastCodeClass = (Code / 100);
  2875. }
  2876. //---------------------------------------------------------------------------
  2877. void __fastcall TFTPFileSystem::StoreLastResponse(const UnicodeString & Text)
  2878. {
  2879. FLastResponse->Add(Text);
  2880. if (FLastCodeClass >= 4)
  2881. {
  2882. FLastErrorResponse->Add(Text);
  2883. }
  2884. }
  2885. //---------------------------------------------------------------------------
  2886. void __fastcall TFTPFileSystem::HandleReplyStatus(UnicodeString Response)
  2887. {
  2888. int Code;
  2889. if (FOnCaptureOutput != NULL)
  2890. {
  2891. FOnCaptureOutput(Response, cotOutput);
  2892. }
  2893. if (FWelcomeMessage.IsEmpty() && StartsStr(L"SSH", Response))
  2894. {
  2895. FLastErrorResponse->Add(LoadStr(SFTP_AS_FTP_ERROR));
  2896. }
  2897. // Two forms of multiline responses were observed
  2898. // (the first is according to the RFC 959):
  2899. // 211-Features:
  2900. // MDTM
  2901. // REST STREAM
  2902. // SIZE
  2903. // 211 End
  2904. // This format is according to RFC 2228.
  2905. // Is used by ProFTPD when MultilineRFC2228 is enabled
  2906. // http://www.proftpd.org/docs/directives/linked/config_ref_MultilineRFC2228.html
  2907. // 211-Features:
  2908. // 211-MDTM
  2909. // 211-REST STREAM
  2910. // 211-SIZE
  2911. // 211-AUTH TLS
  2912. // 211-PBSZ
  2913. // 211-PROT
  2914. // 211 End
  2915. // IIS 2003:
  2916. // 211-FEAT
  2917. // SIZE
  2918. // MDTM
  2919. // 211 END
  2920. // Partially duplicated in CFtpControlSocket::OnReceive
  2921. bool HasCodePrefix =
  2922. (Response.Length() >= 3) &&
  2923. TryStrToInt(Response.SubString(1, 3), Code) &&
  2924. (Code >= 100) && (Code <= 599) &&
  2925. ((Response.Length() == 3) || (Response[4] == L' ') || (Response[4] == L'-'));
  2926. if (HasCodePrefix && !FMultineResponse)
  2927. {
  2928. FMultineResponse = (Response.Length() >= 4) && (Response[4] == L'-');
  2929. FLastResponse->Clear();
  2930. FLastErrorResponse->Clear();
  2931. SetLastCode(Code);
  2932. if (Response.Length() >= 5)
  2933. {
  2934. StoreLastResponse(Response.SubString(5, Response.Length() - 4));
  2935. }
  2936. }
  2937. else
  2938. {
  2939. int Start;
  2940. // response with code prefix
  2941. if (HasCodePrefix && (FLastCode == Code))
  2942. {
  2943. // End of multiline response?
  2944. if ((Response.Length() <= 3) || (Response[4] == L' '))
  2945. {
  2946. FMultineResponse = false;
  2947. }
  2948. Start = 5;
  2949. }
  2950. else
  2951. {
  2952. Start = (((Response.Length() >= 1) && (Response[1] == L' ')) ? 2 : 1);
  2953. }
  2954. // Intermediate empty lines are being added
  2955. if (FMultineResponse || (Response.Length() >= Start))
  2956. {
  2957. StoreLastResponse(Response.SubString(Start, Response.Length() - Start + 1));
  2958. }
  2959. }
  2960. if (StartsStr(DirectoryHasBytesPrefix, Response))
  2961. {
  2962. UnicodeString Buf = Response;
  2963. Buf.Delete(1, DirectoryHasBytesPrefix.Length());
  2964. Buf = Buf.TrimLeft();
  2965. UnicodeString BytesStr = CutToChar(Buf, L' ', true);
  2966. BytesStr = ReplaceStr(BytesStr, L",", L"");
  2967. FBytesAvailable = StrToInt64Def(BytesStr, -1);
  2968. if (FBytesAvailable >= 0)
  2969. {
  2970. FBytesAvailableSuppoted = true;
  2971. }
  2972. }
  2973. if (!FMultineResponse)
  2974. {
  2975. if (FLastCode == 220)
  2976. {
  2977. // HOST command also uses 220 response.
  2978. // Neither our use of welcome message is prepared for changing it
  2979. // during the session, so we keep the initial message only.
  2980. // Theoretically the welcome message can be host-specific,
  2981. // but IIS uses "220 Host accepted", and we are not interested in that anyway.
  2982. // Serv-U repeats the initial welcome message.
  2983. // WS_FTP uses "200 Command HOST succeed"
  2984. if (FWelcomeMessage.IsEmpty())
  2985. {
  2986. FWelcomeMessage = FLastResponse->Text;
  2987. if (FTerminal->Configuration->ShowFtpWelcomeMessage)
  2988. {
  2989. FTerminal->DisplayBanner(FWelcomeMessage);
  2990. }
  2991. // Idea FTP Server v0.80
  2992. if ((FTerminal->SessionData->FtpTransferActiveImmediately == asAuto) &&
  2993. FWelcomeMessage.Pos(L"Idea FTP Server") > 0)
  2994. {
  2995. FTerminal->LogEvent(L"The server requires TLS/SSL handshake on transfer connection before responding 1yz to STOR/APPE");
  2996. FTransferActiveImmediately = true;
  2997. }
  2998. }
  2999. }
  3000. else if (FLastCommand == PASS)
  3001. {
  3002. FStoredPasswordTried = true;
  3003. // 530 = "Not logged in."
  3004. if (FLastCode == 530)
  3005. {
  3006. FPasswordFailed = true;
  3007. }
  3008. }
  3009. else if (FLastCommand == SYST)
  3010. {
  3011. DebugAssert(FSystem.IsEmpty());
  3012. // Positive reply to "SYST" must be 215, see RFC 959
  3013. if (FLastCode == 215)
  3014. {
  3015. FSystem = FLastResponse->Text.TrimRight();
  3016. // full name is "MVS is the operating system of this server. FTP Server is running on ..."
  3017. // (the ... can be "z/OS")
  3018. // https://www.ibm.com/support/knowledgecenter/SSLTBW_2.1.0/com.ibm.zos.v2r1.cs3cod0/ftp215-02.htm
  3019. FMVS = (FSystem.SubString(1, 3) == L"MVS");
  3020. if ((FListAll == asAuto) &&
  3021. // full name is "Personal FTP Server PRO K6.0"
  3022. ((FSystem.Pos(L"Personal FTP Server") > 0) ||
  3023. FMVS))
  3024. {
  3025. FTerminal->LogEvent(L"Server is known not to support LIST -a");
  3026. FListAll = asOff;
  3027. }
  3028. // The FWelcomeMessage usually contains "Microsoft FTP Service" but can be empty
  3029. if (ContainsText(FSystem, L"Windows_NT"))
  3030. {
  3031. FTerminal->LogEvent(L"The server is probably running Windows, assuming that directory listing timestamps are affected by DST.");
  3032. FWindowsServer = true;
  3033. }
  3034. // VMS system type. VMS V5.5-2.
  3035. FVMS = (FSystem.SubString(1, 3) == L"VMS");
  3036. }
  3037. else
  3038. {
  3039. FSystem = L"";
  3040. }
  3041. }
  3042. else if (FLastCommand == FEAT)
  3043. {
  3044. HandleFeatReply();
  3045. }
  3046. }
  3047. }
  3048. //---------------------------------------------------------------------------
  3049. void __fastcall TFTPFileSystem::ResetFeatures()
  3050. {
  3051. FFeatures->Clear();
  3052. FSupportedCommands->Clear();
  3053. FSupportedSiteCommands->Clear();
  3054. FHashAlgs->Clear();
  3055. FSupportsAnyChecksumFeature = false;
  3056. }
  3057. //---------------------------------------------------------------------------
  3058. void __fastcall TFTPFileSystem::HandleFeatReply()
  3059. {
  3060. ResetFeatures();
  3061. // Response to FEAT must be multiline, where leading and trailing line
  3062. // is "meaningless". See RFC 2389.
  3063. if ((FLastCode == 211) && (FLastResponse->Count > 2))
  3064. {
  3065. FLastResponse->Delete(0);
  3066. FLastResponse->Delete(FLastResponse->Count - 1);
  3067. FFeatures->Assign(FLastResponse);
  3068. for (int Index = 0; Index < FFeatures->Count; Index++)
  3069. {
  3070. // IIS 2003 indents response by 4 spaces, instead of one,
  3071. // see example in HandleReplyStatus
  3072. UnicodeString Feature = TrimLeft(FFeatures->Strings[Index]);
  3073. UnicodeString Args = Feature;
  3074. UnicodeString Command = CutToChar(Args, L' ', true);
  3075. // Serv-U lists Xalg commands like:
  3076. // XSHA1 filename;start;end
  3077. FSupportedCommands->Add(Command);
  3078. if (SameText(Command, SiteCommand))
  3079. {
  3080. // Serv-U lists all SITE commands in one line like:
  3081. // SITE PSWD;SET;ZONE;CHMOD;MSG;EXEC;HELP
  3082. // But ProFTPD lists them separatelly:
  3083. // SITE UTIME
  3084. // SITE RMDIR
  3085. // SITE COPY
  3086. // SITE MKDIR
  3087. // SITE SYMLINK
  3088. while (!Args.IsEmpty())
  3089. {
  3090. UnicodeString Arg = CutToChar(Args, L';', true);
  3091. FSupportedSiteCommands->Add(Arg);
  3092. }
  3093. }
  3094. else if (SameText(Command, HashCommand))
  3095. {
  3096. while (!Args.IsEmpty())
  3097. {
  3098. UnicodeString Alg = CutToChar(Args, L';', true);
  3099. if ((Alg.Length() > 0) && (Alg[Alg.Length()] == L'*'))
  3100. {
  3101. Alg.Delete(Alg.Length(), 1);
  3102. }
  3103. // FTP HASH alg names follow IANA as we do,
  3104. // but using uppercase and we use lowercase
  3105. FHashAlgs->Add(LowerCase(Alg));
  3106. FSupportsAnyChecksumFeature = true;
  3107. }
  3108. }
  3109. if (FChecksumCommands->IndexOf(Command) >= 0)
  3110. {
  3111. FSupportsAnyChecksumFeature = true;
  3112. }
  3113. }
  3114. }
  3115. }
  3116. //---------------------------------------------------------------------------
  3117. bool __fastcall TFTPFileSystem::HandleStatus(const wchar_t * AStatus, int Type)
  3118. {
  3119. TLogLineType LogType = (TLogLineType)-1;
  3120. UnicodeString Status(AStatus);
  3121. switch (Type)
  3122. {
  3123. case TFileZillaIntf::LOG_STATUS:
  3124. FTerminal->Information(Status, true);
  3125. LogType = llMessage;
  3126. break;
  3127. case TFileZillaIntf::LOG_COMMAND:
  3128. if (Status == L"SYST")
  3129. {
  3130. // not to trigger the assert in HandleReplyStatus,
  3131. // when SYST command is used by the user
  3132. FSystem = "";
  3133. FLastCommand = SYST;
  3134. }
  3135. else if (Status == L"FEAT")
  3136. {
  3137. FLastCommand = FEAT;
  3138. }
  3139. else if (Status.SubString(1, 5) == L"PASS ")
  3140. {
  3141. FLastCommand = PASS;
  3142. }
  3143. else
  3144. {
  3145. FLastCommand = CMD_UNKNOWN;
  3146. }
  3147. if (!FLoggedIn || (FTerminal->Configuration->ActualLogProtocol >= 0))
  3148. {
  3149. LogType = llInput;
  3150. }
  3151. break;
  3152. case TFileZillaIntf::LOG_ERROR:
  3153. case TFileZillaIntf::LOG_APIERROR:
  3154. case TFileZillaIntf::LOG_WARNING:
  3155. // when timeout message occurs, break loop waiting for response code
  3156. // by setting dummy one
  3157. if (Type == TFileZillaIntf::LOG_ERROR)
  3158. {
  3159. if (StartsStr(FTimeoutStatus, Status))
  3160. {
  3161. if (NoFinalLastCode())
  3162. {
  3163. SetLastCode(DummyTimeoutCode);
  3164. }
  3165. }
  3166. else if (Status == FDisconnectStatus)
  3167. {
  3168. if (NoFinalLastCode())
  3169. {
  3170. SetLastCode(DummyDisconnectCode);
  3171. }
  3172. }
  3173. }
  3174. // there can be multiple error messages associated with single failure
  3175. // (such as "cannot open local file..." followed by "download failed")
  3176. FLastError->Add(Status);
  3177. LogType = llMessage;
  3178. break;
  3179. case TFileZillaIntf::LOG_PROGRESS:
  3180. LogType = llMessage;
  3181. break;
  3182. case TFileZillaIntf::LOG_REPLY:
  3183. HandleReplyStatus(AStatus);
  3184. if (!FLoggedIn || (FTerminal->Configuration->ActualLogProtocol >= 0))
  3185. {
  3186. LogType = llOutput;
  3187. }
  3188. break;
  3189. case TFileZillaIntf::LOG_INFO:
  3190. LogType = llMessage;
  3191. break;
  3192. case TFileZillaIntf::LOG_DEBUG:
  3193. LogType = llMessage;
  3194. break;
  3195. default:
  3196. DebugFail();
  3197. break;
  3198. }
  3199. if (FTerminal->Log->Logging && (LogType != (TLogLineType)-1))
  3200. {
  3201. FTerminal->Log->Add(LogType, Status);
  3202. }
  3203. return true;
  3204. }
  3205. //---------------------------------------------------------------------------
  3206. TDateTime __fastcall TFTPFileSystem::ConvertLocalTimestamp(time_t Time)
  3207. {
  3208. // This reverses how FZAPI converts FILETIME to time_t,
  3209. // before passing it to FZ_ASYNCREQUEST_OVERWRITE.
  3210. __int64 Timestamp;
  3211. tm * Tm = localtime(&Time);
  3212. if (Tm != NULL)
  3213. {
  3214. SYSTEMTIME SystemTime;
  3215. SystemTime.wYear = static_cast<WORD>(Tm->tm_year + 1900);
  3216. SystemTime.wMonth = static_cast<WORD>(Tm->tm_mon + 1);
  3217. SystemTime.wDayOfWeek = 0;
  3218. SystemTime.wDay = static_cast<WORD>(Tm->tm_mday);
  3219. SystemTime.wHour = static_cast<WORD>(Tm->tm_hour);
  3220. SystemTime.wMinute = static_cast<WORD>(Tm->tm_min);
  3221. SystemTime.wSecond = static_cast<WORD>(Tm->tm_sec);
  3222. SystemTime.wMilliseconds = 0;
  3223. FILETIME LocalTime;
  3224. SystemTimeToFileTime(&SystemTime, &LocalTime);
  3225. FILETIME FileTime;
  3226. LocalFileTimeToFileTime(&LocalTime, &FileTime);
  3227. Timestamp = ConvertTimestampToUnixSafe(FileTime, dstmUnix);
  3228. }
  3229. else
  3230. {
  3231. // incorrect, but at least something
  3232. Timestamp = Time;
  3233. }
  3234. return UnixToDateTime(Timestamp, dstmUnix);
  3235. }
  3236. //---------------------------------------------------------------------------
  3237. bool __fastcall TFTPFileSystem::HandleAsynchRequestOverwrite(
  3238. wchar_t * FileName1, size_t FileName1Len, const wchar_t * FileName2,
  3239. const wchar_t * Path1, const wchar_t * Path2,
  3240. __int64 Size1, __int64 Size2, time_t LocalTime,
  3241. bool /*HasLocalTime*/, const TRemoteFileTime & RemoteTime, void * AUserData, int & RequestResult)
  3242. {
  3243. if (!FActive)
  3244. {
  3245. return false;
  3246. }
  3247. else
  3248. {
  3249. TFileTransferData & UserData = *((TFileTransferData *)AUserData);
  3250. if (UserData.OverwriteResult >= 0)
  3251. {
  3252. // on retry, use the same answer as on the first attempt
  3253. RequestResult = UserData.OverwriteResult;
  3254. }
  3255. else
  3256. {
  3257. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  3258. UnicodeString TargetFileName = FileName1;
  3259. DebugAssert(UserData.FileName == TargetFileName);
  3260. UnicodeString SourceFullFileName = Path2;
  3261. UnicodeString TargetFullFileName = Path1;
  3262. if (OperationProgress->Side == osLocal)
  3263. {
  3264. SourceFullFileName = IncludeTrailingBackslash(SourceFullFileName);
  3265. TargetFullFileName = UnixIncludeTrailingBackslash(TargetFullFileName);
  3266. }
  3267. else
  3268. {
  3269. SourceFullFileName = UnixIncludeTrailingBackslash(SourceFullFileName);
  3270. TargetFullFileName = IncludeTrailingBackslash(TargetFullFileName);
  3271. }
  3272. SourceFullFileName += FileName2;
  3273. TargetFullFileName += FileName1;
  3274. TOverwriteMode OverwriteMode = omOverwrite;
  3275. TOverwriteFileParams FileParams;
  3276. bool NoFileParams =
  3277. (Size1 < 0) || (LocalTime == 0) ||
  3278. (Size2 < 0) || !RemoteTime.HasDate;
  3279. if (!NoFileParams)
  3280. {
  3281. FileParams.SourceSize = Size2;
  3282. FileParams.DestSize = Size1;
  3283. // Time is coming from LIST (not from MLSD or MDTM)
  3284. bool NeedApplyTimeDifference = !RemoteTime.Utc && DebugAlwaysTrue(!FFileZillaIntf->UsingMlsd());
  3285. if (OperationProgress->Side == osLocal)
  3286. {
  3287. FileParams.SourceTimestamp = ConvertLocalTimestamp(LocalTime);
  3288. RemoteFileTimeToDateTimeAndPrecision(RemoteTime, FileParams.DestTimestamp, FileParams.DestPrecision);
  3289. if (NeedApplyTimeDifference)
  3290. {
  3291. ApplyTimeDifference(TargetFullFileName, FileParams.DestTimestamp, FileParams.DestPrecision);
  3292. }
  3293. }
  3294. else
  3295. {
  3296. FileParams.DestTimestamp = ConvertLocalTimestamp(LocalTime);
  3297. RemoteFileTimeToDateTimeAndPrecision(RemoteTime, FileParams.SourceTimestamp, FileParams.SourcePrecision);
  3298. if (NeedApplyTimeDifference)
  3299. {
  3300. ApplyTimeDifference(SourceFullFileName, FileParams.SourceTimestamp, FileParams.SourcePrecision);
  3301. }
  3302. }
  3303. }
  3304. if (ConfirmOverwrite(SourceFullFileName, TargetFileName, OverwriteMode, OperationProgress,
  3305. (NoFileParams ? NULL : &FileParams), UserData.CopyParam, UserData.Params,
  3306. UserData.AutoResume && UserData.CopyParam->AllowResume(FileParams.SourceSize)))
  3307. {
  3308. switch (OverwriteMode)
  3309. {
  3310. case omOverwrite:
  3311. if (TargetFileName != FileName1)
  3312. {
  3313. wcsncpy(FileName1, TargetFileName.c_str(), FileName1Len);
  3314. FileName1[FileName1Len - 1] = L'\0';
  3315. UserData.FileName = FileName1;
  3316. RequestResult = TFileZillaIntf::FILEEXISTS_RENAME;
  3317. }
  3318. else
  3319. {
  3320. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  3321. }
  3322. break;
  3323. case omResume:
  3324. RequestResult = TFileZillaIntf::FILEEXISTS_RESUME;
  3325. break;
  3326. case omComplete:
  3327. FTerminal->LogEvent(L"File transfer was completed before disconnect");
  3328. RequestResult = TFileZillaIntf::FILEEXISTS_COMPLETE;
  3329. break;
  3330. default:
  3331. DebugFail();
  3332. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  3333. break;
  3334. }
  3335. }
  3336. else
  3337. {
  3338. RequestResult = TFileZillaIntf::FILEEXISTS_SKIP;
  3339. }
  3340. }
  3341. // remember the answer for the retries
  3342. UserData.OverwriteResult = RequestResult;
  3343. if (RequestResult == TFileZillaIntf::FILEEXISTS_SKIP)
  3344. {
  3345. // when user chooses not to overwrite, break loop waiting for response code
  3346. // by setting dummy one, as FZAPI won't do anything then
  3347. SetLastCode(DummyTimeoutCode);
  3348. }
  3349. return true;
  3350. }
  3351. }
  3352. //---------------------------------------------------------------------------
  3353. UnicodeString __fastcall FormatContactList(UnicodeString Entry1, UnicodeString Entry2)
  3354. {
  3355. if (!Entry1.IsEmpty() && !Entry2.IsEmpty())
  3356. {
  3357. return FORMAT(L"%s, %s", (Entry1, Entry2));
  3358. }
  3359. else
  3360. {
  3361. return Entry1 + Entry2;
  3362. }
  3363. }
  3364. //---------------------------------------------------------------------------
  3365. UnicodeString __fastcall FormatContact(const TFtpsCertificateData::TContact & Contact)
  3366. {
  3367. UnicodeString Result =
  3368. FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 1),
  3369. (FormatContactList(FormatContactList(FormatContactList(
  3370. Contact.Organization, Contact.Unit), Contact.CommonName), Contact.Mail)));
  3371. if ((wcslen(Contact.Country) > 0) ||
  3372. (wcslen(Contact.StateProvince) > 0) ||
  3373. (wcslen(Contact.Town) > 0))
  3374. {
  3375. Result +=
  3376. FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 2),
  3377. (FormatContactList(FormatContactList(
  3378. Contact.Country, Contact.StateProvince), Contact.Town)));
  3379. }
  3380. if (wcslen(Contact.Other) > 0)
  3381. {
  3382. Result += FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 3), (Contact.Other));
  3383. }
  3384. return Result;
  3385. }
  3386. //---------------------------------------------------------------------------
  3387. UnicodeString __fastcall FormatValidityTime(const TFtpsCertificateData::TValidityTime & ValidityTime)
  3388. {
  3389. return FormatDateTime(L"ddddd tt",
  3390. EncodeDateVerbose(
  3391. (unsigned short)ValidityTime.Year, (unsigned short)ValidityTime.Month,
  3392. (unsigned short)ValidityTime.Day) +
  3393. EncodeTimeVerbose(
  3394. (unsigned short)ValidityTime.Hour, (unsigned short)ValidityTime.Min,
  3395. (unsigned short)ValidityTime.Sec, 0));
  3396. }
  3397. //---------------------------------------------------------------------------
  3398. bool __fastcall VerifyNameMask(UnicodeString Name, UnicodeString Mask)
  3399. {
  3400. bool Result = true;
  3401. int Pos;
  3402. while (Result && (Pos = Mask.Pos(L"*")) > 0)
  3403. {
  3404. // Pos will typically be 1 here, so not actual comparison is done
  3405. Result = SameText(Mask.SubString(1, Pos - 1), Name.SubString(1, Pos - 1));
  3406. if (Result)
  3407. {
  3408. Mask.Delete(1, Pos); // including *
  3409. Name.Delete(1, Pos - 1);
  3410. // remove everything until the next dot
  3411. Pos = Name.Pos(L".");
  3412. if (Pos == 0)
  3413. {
  3414. Pos = Name.Length() + 1;
  3415. }
  3416. Name.Delete(1, Pos - 1);
  3417. }
  3418. }
  3419. if (Result)
  3420. {
  3421. Result = SameText(Mask, Name);
  3422. }
  3423. return Result;
  3424. }
  3425. //---------------------------------------------------------------------------
  3426. bool __fastcall TFTPFileSystem::VerifyCertificateHostName(const TFtpsCertificateData & Data)
  3427. {
  3428. UnicodeString HostName = FTerminal->SessionData->HostNameExpanded;
  3429. UnicodeString CommonName = Data.Subject.CommonName;
  3430. bool NoMask = CommonName.IsEmpty();
  3431. bool Result = !NoMask && VerifyNameMask(HostName, CommonName);
  3432. if (Result)
  3433. {
  3434. FTerminal->LogEvent(FORMAT(L"Certificate common name \"%s\" matches hostname", (CommonName)));
  3435. }
  3436. else
  3437. {
  3438. if (!NoMask && (FTerminal->Configuration->ActualLogProtocol >= 1))
  3439. {
  3440. FTerminal->LogEvent(FORMAT(L"Certificate common name \"%s\" does not match hostname", (CommonName)));
  3441. }
  3442. UnicodeString SubjectAltName = Data.SubjectAltName;
  3443. while (!Result && !SubjectAltName.IsEmpty())
  3444. {
  3445. UnicodeString Entry = CutToChar(SubjectAltName, L',', true);
  3446. UnicodeString EntryName = CutToChar(Entry, L':', true);
  3447. if (SameText(EntryName, L"DNS"))
  3448. {
  3449. NoMask = false;
  3450. Result = VerifyNameMask(HostName, Entry);
  3451. if (Result)
  3452. {
  3453. FTerminal->LogEvent(FORMAT(L"Certificate subject alternative name \"%s\" matches hostname", (Entry)));
  3454. }
  3455. else
  3456. {
  3457. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  3458. {
  3459. FTerminal->LogEvent(FORMAT(L"Certificate subject alternative name \"%s\" does not match hostname", (Entry)));
  3460. }
  3461. }
  3462. }
  3463. }
  3464. }
  3465. if (!Result && NoMask)
  3466. {
  3467. FTerminal->LogEvent(L"Certificate has no common name nor subject alternative name, not verifying hostname");
  3468. Result = true;
  3469. }
  3470. return Result;
  3471. }
  3472. //---------------------------------------------------------------------------
  3473. static bool __fastcall IsIPAddress(const UnicodeString & HostName)
  3474. {
  3475. bool IPv4 = true;
  3476. bool IPv6 = true;
  3477. bool AnyColon = false;
  3478. for (int Index = 1; Index <= HostName.Length(); Index++)
  3479. {
  3480. wchar_t C = HostName[Index];
  3481. if (!IsDigit(C) && (C != L'.'))
  3482. {
  3483. IPv4 = false;
  3484. }
  3485. if (!IsHex(C) && (C != L':'))
  3486. {
  3487. IPv6 = false;
  3488. }
  3489. if (C == L':')
  3490. {
  3491. AnyColon = true;
  3492. }
  3493. }
  3494. return IPv4 || (IPv6 && AnyColon);
  3495. }
  3496. //---------------------------------------------------------------------------
  3497. bool __fastcall TFTPFileSystem::HandleAsynchRequestVerifyCertificate(
  3498. const TFtpsCertificateData & Data, int & RequestResult)
  3499. {
  3500. if (!FActive)
  3501. {
  3502. return false;
  3503. }
  3504. else
  3505. {
  3506. FSessionInfo.CertificateFingerprint =
  3507. BytesToHex(RawByteString((const char*)Data.Hash, Data.HashLen), false, L':');
  3508. if (FTerminal->SessionData->FingerprintScan)
  3509. {
  3510. RequestResult = 0;
  3511. }
  3512. else
  3513. {
  3514. UnicodeString CertificateSubject = Data.Subject.Organization;
  3515. FTerminal->LogEvent(FORMAT(L"Verifying certificate for \"%s\" with fingerprint %s and %d failures", (CertificateSubject, FSessionInfo.CertificateFingerprint, Data.VerificationResult)));
  3516. bool Trusted = false;
  3517. bool TryWindowsSystemCertificateStore = false;
  3518. UnicodeString VerificationResultStr;
  3519. switch (Data.VerificationResult)
  3520. {
  3521. case X509_V_OK:
  3522. Trusted = true;
  3523. break;
  3524. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
  3525. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_GET_ISSUER_CERT);
  3526. TryWindowsSystemCertificateStore = true;
  3527. break;
  3528. case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
  3529. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE);
  3530. break;
  3531. case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
  3532. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY);
  3533. break;
  3534. case X509_V_ERR_CERT_SIGNATURE_FAILURE:
  3535. VerificationResultStr = LoadStr(CERT_ERR_CERT_SIGNATURE_FAILURE);
  3536. break;
  3537. case X509_V_ERR_CERT_NOT_YET_VALID:
  3538. VerificationResultStr = LoadStr(CERT_ERR_CERT_NOT_YET_VALID);
  3539. break;
  3540. case X509_V_ERR_CERT_HAS_EXPIRED:
  3541. VerificationResultStr = LoadStr(CERT_ERR_CERT_HAS_EXPIRED);
  3542. break;
  3543. case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
  3544. VerificationResultStr = LoadStr(CERT_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD);
  3545. break;
  3546. case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
  3547. VerificationResultStr = LoadStr(CERT_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD);
  3548. break;
  3549. case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
  3550. VerificationResultStr = LoadStr(CERT_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
  3551. TryWindowsSystemCertificateStore = true;
  3552. break;
  3553. case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
  3554. VerificationResultStr = LoadStr(CERT_ERR_SELF_SIGNED_CERT_IN_CHAIN);
  3555. TryWindowsSystemCertificateStore = true;
  3556. break;
  3557. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
  3558. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY);
  3559. TryWindowsSystemCertificateStore = true;
  3560. break;
  3561. case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
  3562. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
  3563. TryWindowsSystemCertificateStore = true;
  3564. break;
  3565. case X509_V_ERR_INVALID_CA:
  3566. VerificationResultStr = LoadStr(CERT_ERR_INVALID_CA);
  3567. break;
  3568. case X509_V_ERR_PATH_LENGTH_EXCEEDED:
  3569. VerificationResultStr = LoadStr(CERT_ERR_PATH_LENGTH_EXCEEDED);
  3570. break;
  3571. case X509_V_ERR_INVALID_PURPOSE:
  3572. VerificationResultStr = LoadStr(CERT_ERR_INVALID_PURPOSE);
  3573. break;
  3574. case X509_V_ERR_CERT_UNTRUSTED:
  3575. VerificationResultStr = LoadStr(CERT_ERR_CERT_UNTRUSTED);
  3576. TryWindowsSystemCertificateStore = true;
  3577. break;
  3578. case X509_V_ERR_CERT_REJECTED:
  3579. VerificationResultStr = LoadStr(CERT_ERR_CERT_REJECTED);
  3580. break;
  3581. case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
  3582. VerificationResultStr = LoadStr(CERT_ERR_KEYUSAGE_NO_CERTSIGN);
  3583. break;
  3584. case X509_V_ERR_CERT_CHAIN_TOO_LONG:
  3585. VerificationResultStr = LoadStr(CERT_ERR_CERT_CHAIN_TOO_LONG);
  3586. break;
  3587. default:
  3588. VerificationResultStr =
  3589. FORMAT(L"%s (%s)",
  3590. (LoadStr(CERT_ERR_UNKNOWN), X509_verify_cert_error_string(Data.VerificationResult)));
  3591. break;
  3592. }
  3593. bool IsHostNameIPAddress = IsIPAddress(FTerminal->SessionData->HostNameExpanded);
  3594. bool CertificateHostNameVerified = !IsHostNameIPAddress && VerifyCertificateHostName(Data);
  3595. bool VerificationResult = Trusted;
  3596. if (IsHostNameIPAddress || !CertificateHostNameVerified)
  3597. {
  3598. VerificationResult = false;
  3599. TryWindowsSystemCertificateStore = false;
  3600. }
  3601. if (!VerificationResult)
  3602. {
  3603. if (FTerminal->VerifyCertificate(FtpsCertificateStorageKey, FTerminal->SessionData->SiteKey,
  3604. FSessionInfo.CertificateFingerprint, CertificateSubject, Data.VerificationResult))
  3605. {
  3606. // certificate is trusted, but for not purposes of info dialog
  3607. VerificationResult = true;
  3608. FSessionInfo.CertificateVerifiedManually = true;
  3609. }
  3610. }
  3611. // TryWindowsSystemCertificateStore is set for the same set of failures
  3612. // as trigger NE_SSL_UNTRUSTED flag in ne_openssl.c's verify_callback().
  3613. // Use WindowsValidateCertificate only as a last resort (after checking the cached fiungerprint)
  3614. // as it can take a very long time (up to 1 minute).
  3615. if (!VerificationResult && TryWindowsSystemCertificateStore)
  3616. {
  3617. UnicodeString WindowsCertificateError;
  3618. if (WindowsValidateCertificate(Data.Certificate, Data.CertificateLen, WindowsCertificateError))
  3619. {
  3620. FTerminal->LogEvent(L"Certificate verified against Windows certificate store");
  3621. VerificationResult = true;
  3622. // certificate is trusted for all purposes
  3623. Trusted = true;
  3624. }
  3625. else
  3626. {
  3627. FTerminal->LogEvent(
  3628. FORMAT(L"Certificate failed to verify against Windows certificate store: %s", (DefaultStr(WindowsCertificateError, L"no details"))));
  3629. }
  3630. }
  3631. const UnicodeString SummarySeparator = L"\n\n";
  3632. UnicodeString Summary;
  3633. // even if the fingerprint is cached, the certificate is still not trusted for a purposes of the info dialog.
  3634. if (!Trusted)
  3635. {
  3636. AddToList(Summary, VerificationResultStr + L" " + FMTLOAD(CERT_ERRDEPTH, (Data.VerificationDepth + 1)), SummarySeparator);
  3637. }
  3638. if (IsHostNameIPAddress)
  3639. {
  3640. AddToList(Summary, FMTLOAD(CERT_IP_CANNOT_VERIFY, (FTerminal->SessionData->HostNameExpanded)), SummarySeparator);
  3641. }
  3642. else if (!CertificateHostNameVerified)
  3643. {
  3644. AddToList(Summary, FMTLOAD(CERT_NAME_MISMATCH, (FTerminal->SessionData->HostNameExpanded)), SummarySeparator);
  3645. }
  3646. if (Summary.IsEmpty())
  3647. {
  3648. Summary = LoadStr(CERT_OK);
  3649. }
  3650. FSessionInfo.Certificate =
  3651. FMTLOAD(CERT_TEXT, (
  3652. FormatContact(Data.Issuer),
  3653. FormatContact(Data.Subject),
  3654. FormatValidityTime(Data.ValidFrom),
  3655. FormatValidityTime(Data.ValidUntil),
  3656. FSessionInfo.CertificateFingerprint,
  3657. Summary));
  3658. RequestResult = VerificationResult ? 1 : 0;
  3659. if (RequestResult == 0)
  3660. {
  3661. if (FTerminal->ConfirmCertificate(FSessionInfo, Data.VerificationResult, FtpsCertificateStorageKey, true))
  3662. {
  3663. // FZ's VerifyCertDlg.cpp returns 2 for "cached", what we do nto distinguish here,
  3664. // however FZAPI takes all non-zero values equally.
  3665. RequestResult = 1;
  3666. FSessionInfo.CertificateVerifiedManually = true;
  3667. }
  3668. }
  3669. }
  3670. return true;
  3671. }
  3672. }
  3673. //---------------------------------------------------------------------------
  3674. bool __fastcall TFTPFileSystem::HandleAsynchRequestNeedPass(
  3675. struct TNeedPassRequestData & Data, int & RequestResult)
  3676. {
  3677. if (!FActive)
  3678. {
  3679. return false;
  3680. }
  3681. else
  3682. {
  3683. UnicodeString Password;
  3684. if (FCertificate != NULL)
  3685. {
  3686. FTerminal->LogEvent(L"Server asked for password, but we are using certificate, and no password was specified upfront, using fake password");
  3687. Password = L"USINGCERT";
  3688. RequestResult = TFileZillaIntf::REPLY_OK;
  3689. }
  3690. else
  3691. {
  3692. if (FTerminal->PromptUser(FTerminal->SessionData, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  3693. LoadStr(PASSWORD_PROMPT), false, 0, Password))
  3694. {
  3695. RequestResult = TFileZillaIntf::REPLY_OK;
  3696. }
  3697. else
  3698. {
  3699. RequestResult = TFileZillaIntf::REPLY_ABORTED;
  3700. }
  3701. }
  3702. // When returning REPLY_OK, we need to return an allocated password,
  3703. // even if we were returning and empty string we got on input.
  3704. if (RequestResult == TFileZillaIntf::REPLY_OK)
  3705. {
  3706. Data.Password = _wcsdup(Password.c_str());
  3707. }
  3708. return true;
  3709. }
  3710. }
  3711. //---------------------------------------------------------------------------
  3712. void __fastcall TFTPFileSystem::RemoteFileTimeToDateTimeAndPrecision(const TRemoteFileTime & Source, TDateTime & DateTime, TModificationFmt & ModificationFmt)
  3713. {
  3714. // ModificationFmt must be set after Modification
  3715. if (Source.HasDate)
  3716. {
  3717. DateTime =
  3718. EncodeDateVerbose((unsigned short)Source.Year, (unsigned short)Source.Month,
  3719. (unsigned short)Source.Day);
  3720. if (Source.HasTime)
  3721. {
  3722. DateTime = DateTime +
  3723. EncodeTimeVerbose((unsigned short)Source.Hour, (unsigned short)Source.Minute,
  3724. (unsigned short)Source.Second, 0);
  3725. // not exact as we got year as well, but it is most probably
  3726. // guessed by FZAPI anyway
  3727. ModificationFmt = Source.HasSeconds ? mfFull : mfMDHM;
  3728. // With IIS, the Utc should be false only for MDTM
  3729. if (FWindowsServer && !Source.Utc)
  3730. {
  3731. DateTime -= DSTDifferenceForTime(DateTime);
  3732. }
  3733. }
  3734. else
  3735. {
  3736. ModificationFmt = mfMDY;
  3737. }
  3738. if (Source.Utc)
  3739. {
  3740. DateTime = ConvertTimestampFromUTC(DateTime);
  3741. }
  3742. }
  3743. else
  3744. {
  3745. // With SCP we estimate date to be today, if we have at least time
  3746. DateTime = double(0);
  3747. ModificationFmt = mfNone;
  3748. }
  3749. }
  3750. //---------------------------------------------------------------------------
  3751. bool __fastcall TFTPFileSystem::HandleListData(const wchar_t * Path,
  3752. const TListDataEntry * Entries, unsigned int Count)
  3753. {
  3754. if (!FActive)
  3755. {
  3756. return false;
  3757. }
  3758. else if (FIgnoreFileList)
  3759. {
  3760. // directory listing provided implicitly by FZAPI during certain operations is ignored
  3761. DebugAssert(FFileList == NULL);
  3762. return false;
  3763. }
  3764. else
  3765. {
  3766. DebugAssert(FFileList != NULL);
  3767. DebugUsedParam(Path);
  3768. for (unsigned int Index = 0; Index < Count; Index++)
  3769. {
  3770. const TListDataEntry * Entry = &Entries[Index];
  3771. TRemoteFile * File = new TRemoteFile();
  3772. try
  3773. {
  3774. File->Terminal = FTerminal;
  3775. File->FileName = Entry->Name;
  3776. try
  3777. {
  3778. int PermissionsLen = wcslen(Entry->Permissions);
  3779. if (PermissionsLen >= 10)
  3780. {
  3781. File->Rights->Text = Entry->Permissions + 1;
  3782. }
  3783. else if ((PermissionsLen == 3) || (PermissionsLen == 4))
  3784. {
  3785. File->Rights->Octal = Entry->Permissions;
  3786. }
  3787. }
  3788. catch(...)
  3789. {
  3790. // ignore permissions errors with FTP
  3791. }
  3792. File->HumanRights = Entry->HumanPerm;
  3793. // deprecated, to be replaced with Owner/Group
  3794. if (wcslen(Entry->OwnerGroup) > 0)
  3795. {
  3796. const wchar_t * Space = wcschr(Entry->OwnerGroup, L' ');
  3797. if (Space != NULL)
  3798. {
  3799. File->Owner.Name = UnicodeString(Entry->OwnerGroup, Space - Entry->OwnerGroup);
  3800. File->Group.Name = Space + 1;
  3801. }
  3802. else
  3803. {
  3804. File->Owner.Name = Entry->OwnerGroup;
  3805. }
  3806. }
  3807. else
  3808. {
  3809. File->Owner.Name = Entry->Owner;
  3810. File->Group.Name = Entry->Group;
  3811. }
  3812. File->Size = Entry->Size;
  3813. if (Entry->Link)
  3814. {
  3815. File->Type = FILETYPE_SYMLINK;
  3816. }
  3817. else if (Entry->Dir)
  3818. {
  3819. File->Type = FILETYPE_DIRECTORY;
  3820. }
  3821. else
  3822. {
  3823. File->Type = FILETYPE_DEFAULT;
  3824. }
  3825. TDateTime Modification;
  3826. TModificationFmt ModificationFmt;
  3827. RemoteFileTimeToDateTimeAndPrecision(Entry->Time, Modification, ModificationFmt);
  3828. File->Modification = Modification;
  3829. File->ModificationFmt = ModificationFmt;
  3830. File->LastAccess = File->Modification;
  3831. File->LinkTo = Entry->LinkTarget;
  3832. File->Complete();
  3833. }
  3834. catch (Exception & E)
  3835. {
  3836. delete File;
  3837. UnicodeString EntryData =
  3838. FORMAT(L"%s/%s/%s/%s/%s/%s/%s/%d/%d/%d/%d/%d/%d/%d/%d/%d/%d",
  3839. (Entry->Name, Entry->Permissions, Entry->HumanPerm, Entry->Owner, Entry->Group, Entry->OwnerGroup, IntToStr(Entry->Size),
  3840. int(Entry->Dir), int(Entry->Link), Entry->Time.Year, Entry->Time.Month, Entry->Time.Day,
  3841. Entry->Time.Hour, Entry->Time.Minute, int(Entry->Time.HasTime),
  3842. int(Entry->Time.HasSeconds), int(Entry->Time.HasDate)));
  3843. throw ETerminal(&E, FMTLOAD(LIST_LINE_ERROR, (EntryData)), HELP_LIST_LINE_ERROR);
  3844. }
  3845. FFileList->AddFile(File);
  3846. }
  3847. return true;
  3848. }
  3849. }
  3850. //---------------------------------------------------------------------------
  3851. bool __fastcall TFTPFileSystem::HandleTransferStatus(bool Valid, __int64 TransferSize,
  3852. __int64 Bytes, bool FileTransfer)
  3853. {
  3854. if (!FActive)
  3855. {
  3856. return false;
  3857. }
  3858. else if (!Valid)
  3859. {
  3860. }
  3861. else if (FileTransfer)
  3862. {
  3863. FileTransferProgress(TransferSize, Bytes);
  3864. }
  3865. else
  3866. {
  3867. ReadDirectoryProgress(Bytes);
  3868. }
  3869. return true;
  3870. }
  3871. //---------------------------------------------------------------------------
  3872. bool __fastcall TFTPFileSystem::HandleReply(int Command, unsigned int Reply)
  3873. {
  3874. if (!FActive)
  3875. {
  3876. return false;
  3877. }
  3878. else
  3879. {
  3880. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  3881. {
  3882. FTerminal->LogEvent(FORMAT(L"Got reply %x to the command %d", (int(Reply), Command)));
  3883. }
  3884. // reply with Command 0 is not associated with current operation
  3885. // so do not treat is as a reply
  3886. // (it is typically used asynchronously to notify about disconnects)
  3887. if (Command != 0)
  3888. {
  3889. DebugAssert(FCommandReply == 0);
  3890. FCommandReply = Reply;
  3891. }
  3892. else
  3893. {
  3894. DebugAssert(FReply == 0);
  3895. FReply = Reply;
  3896. }
  3897. return true;
  3898. }
  3899. }
  3900. //---------------------------------------------------------------------------
  3901. bool __fastcall TFTPFileSystem::HandleCapabilities(
  3902. TFTPServerCapabilities * ServerCapabilities)
  3903. {
  3904. FServerCapabilities->Assign(ServerCapabilities);
  3905. FFileSystemInfoValid = false;
  3906. return true;
  3907. }
  3908. //---------------------------------------------------------------------------
  3909. bool __fastcall TFTPFileSystem::CheckError(int ReturnCode, const wchar_t * Context)
  3910. {
  3911. // we do not expect any FZAPI call to fail as it generally can fail only due to:
  3912. // - invalid parameters
  3913. // - busy FZAPI core
  3914. // the only exception is REPLY_NOTCONNECTED that can happen if
  3915. // connection is closed just between the last call to Idle()
  3916. // and call to any FZAPI command
  3917. // in such case reply without associated command is posted,
  3918. // which we are going to wait for unless we are already waiting
  3919. // on higher level (this typically happens if connection is lost while
  3920. // waiting for user interaction and is detected within call to
  3921. // SetAsyncRequestResult)
  3922. if (FLAGSET(ReturnCode, TFileZillaIntf::REPLY_NOTCONNECTED))
  3923. {
  3924. if (!FWaitingForReply)
  3925. {
  3926. // throws
  3927. WaitForFatalNonCommandReply();
  3928. }
  3929. }
  3930. else
  3931. {
  3932. FTerminal->FatalError(NULL,
  3933. FMTLOAD(INTERNAL_ERROR, (FORMAT(L"fz#%s", (Context)), IntToHex(ReturnCode, 4))));
  3934. DebugFail();
  3935. }
  3936. return false;
  3937. }
  3938. //---------------------------------------------------------------------------
  3939. bool __fastcall TFTPFileSystem::Unquote(UnicodeString & Str)
  3940. {
  3941. enum
  3942. {
  3943. INIT,
  3944. QUOTE,
  3945. QUOTED,
  3946. DONE
  3947. } State;
  3948. State = INIT;
  3949. DebugAssert((Str.Length() > 0) && ((Str[1] == L'"') || (Str[1] == L'\'')));
  3950. int Index = 1;
  3951. wchar_t Quote;
  3952. while (Index <= Str.Length())
  3953. {
  3954. switch (State)
  3955. {
  3956. case INIT:
  3957. if ((Str[Index] == L'"') || (Str[Index] == L'\''))
  3958. {
  3959. Quote = Str[Index];
  3960. State = QUOTED;
  3961. Str.Delete(Index, 1);
  3962. }
  3963. else
  3964. {
  3965. DebugFail();
  3966. // no quoted string
  3967. Str.SetLength(0);
  3968. }
  3969. break;
  3970. case QUOTED:
  3971. if (Str[Index] == Quote)
  3972. {
  3973. State = QUOTE;
  3974. Str.Delete(Index, 1);
  3975. }
  3976. else
  3977. {
  3978. Index++;
  3979. }
  3980. break;
  3981. case QUOTE:
  3982. if (Str[Index] == Quote)
  3983. {
  3984. Index++;
  3985. }
  3986. else
  3987. {
  3988. // end of quoted string, trim the rest
  3989. Str.SetLength(Index - 1);
  3990. State = DONE;
  3991. }
  3992. break;
  3993. }
  3994. }
  3995. return (State == DONE);
  3996. }
  3997. //---------------------------------------------------------------------------
  3998. void __fastcall TFTPFileSystem::PreserveDownloadFileTime(HANDLE Handle, void * UserData)
  3999. {
  4000. TFileTransferData * Data = static_cast<TFileTransferData *>(UserData);
  4001. FTerminal->UpdateTargetTime(Handle, Data->Modification, dstmUnix);
  4002. }
  4003. //---------------------------------------------------------------------------
  4004. bool __fastcall TFTPFileSystem::GetFileModificationTimeInUtc(const wchar_t * FileName, struct tm & Time)
  4005. {
  4006. bool Result;
  4007. try
  4008. {
  4009. // error-handling-free and DST-mode-inaware copy of TTerminal::OpenLocalFile
  4010. HANDLE Handle = CreateFile(ApiPath(FileName).c_str(), GENERIC_READ,
  4011. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
  4012. if (Handle == INVALID_HANDLE_VALUE)
  4013. {
  4014. Result = false;
  4015. }
  4016. else
  4017. {
  4018. FILETIME MTime;
  4019. if (!GetFileTime(Handle, NULL, NULL, &MTime))
  4020. {
  4021. Result = false;
  4022. }
  4023. else
  4024. {
  4025. TDateTime Modification = ConvertTimestampToUTC(FileTimeToDateTime(MTime));
  4026. unsigned short Year;
  4027. unsigned short Month;
  4028. unsigned short Day;
  4029. Modification.DecodeDate(&Year, &Month, &Day);
  4030. Time.tm_year = Year - 1900;
  4031. Time.tm_mon = Month - 1;
  4032. Time.tm_mday = Day;
  4033. unsigned short Hour;
  4034. unsigned short Min;
  4035. unsigned short Sec;
  4036. unsigned short MSec;
  4037. Modification.DecodeTime(&Hour, &Min, &Sec, &MSec);
  4038. Time.tm_hour = Hour;
  4039. Time.tm_min = Min;
  4040. Time.tm_sec = Sec;
  4041. Result = true;
  4042. }
  4043. CloseHandle(Handle);
  4044. }
  4045. }
  4046. catch (...)
  4047. {
  4048. Result = false;
  4049. }
  4050. return Result;
  4051. }
  4052. //---------------------------------------------------------------------------
  4053. void __fastcall TFTPFileSystem::RegisterChecksumAlgCommand(const UnicodeString & Alg, const UnicodeString & Command)
  4054. {
  4055. FChecksumAlgs->Add(Alg);
  4056. FChecksumCommands->Add(Command);
  4057. }
  4058. //---------------------------------------------------------------------------
  4059. void __fastcall TFTPFileSystem::GetSupportedChecksumAlgs(TStrings * Algs)
  4060. {
  4061. for (int Index = 0; Index < FHashAlgs->Count; Index++)
  4062. {
  4063. Algs->Add(FHashAlgs->Strings[Index]);
  4064. }
  4065. for (int Index = 0; Index < FChecksumAlgs->Count; Index++)
  4066. {
  4067. UnicodeString Alg = FChecksumAlgs->Strings[Index];
  4068. UnicodeString Command = FChecksumCommands->Strings[Index];
  4069. if (SupportsCommand(Command) && (Algs->IndexOf(Alg) < 0))
  4070. {
  4071. Algs->Add(Alg);
  4072. }
  4073. }
  4074. }
  4075. //---------------------------------------------------------------------------
  4076. bool __fastcall TFTPFileSystem::SupportsSiteCommand(const UnicodeString & Command) const
  4077. {
  4078. return (FSupportedSiteCommands->IndexOf(Command) >= 0);
  4079. }
  4080. //---------------------------------------------------------------------------
  4081. bool __fastcall TFTPFileSystem::SupportsCommand(const UnicodeString & Command) const
  4082. {
  4083. return (FSupportedCommands->IndexOf(Command) >= 0);
  4084. }
  4085. //---------------------------------------------------------------------------
  4086. void __fastcall TFTPFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  4087. {
  4088. DebugFail();
  4089. }
  4090. //---------------------------------------------------------------------------
  4091. void __fastcall TFTPFileSystem::UnlockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  4092. {
  4093. DebugFail();
  4094. }
  4095. //---------------------------------------------------------------------------
  4096. void __fastcall TFTPFileSystem::UpdateFromMain(TCustomFileSystem * /*MainFileSystem*/)
  4097. {
  4098. // noop
  4099. }
  4100. //---------------------------------------------------------------------------
  4101. void __fastcall TFTPFileSystem::ClearCaches()
  4102. {
  4103. // noop
  4104. }
  4105. //---------------------------------------------------------------------------
  4106. UnicodeString __fastcall GetOpenSSLVersionText()
  4107. {
  4108. return OPENSSL_VERSION_TEXT;
  4109. }
  4110. //---------------------------------------------------------------------------