FtpFileSystem.cpp 142 KB

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