FtpFileSystem.cpp 154 KB

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