FtpFileSystem.cpp 153 KB

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