FtpFileSystem.cpp 143 KB

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