FtpFileSystem.cpp 154 KB

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