1
0

FtpFileSystem.cpp 146 KB

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