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. !File->IsParentDirectory && !File->IsThisDirectory &&
  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. Progress.Start(foCalculateChecksum, osRemote, FileList->Count);
  1149. FTerminal->FOperationProgress = &Progress;
  1150. try
  1151. {
  1152. UnicodeString NormalizedAlg = FindIdent(FindIdent(Alg, FHashAlgs.get()), FChecksumAlgs.get());
  1153. bool UsingHashCommand = (FHashAlgs->IndexOf(NormalizedAlg) >= 0);
  1154. if (UsingHashCommand)
  1155. {
  1156. // The server should understand lowercase alg name by spec,
  1157. // but we should use uppercase anyway
  1158. SendCommand(FORMAT(L"OPTS %s %s", (HashCommand, UpperCase(NormalizedAlg))));
  1159. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1160. }
  1161. else if (FChecksumAlgs->IndexOf(NormalizedAlg) >= 0)
  1162. {
  1163. // will use algorithm-specific command
  1164. }
  1165. else
  1166. {
  1167. throw Exception(FMTLOAD(UNKNOWN_CHECKSUM, (Alg)));
  1168. }
  1169. DoCalculateFilesChecksum(UsingHashCommand, NormalizedAlg, FileList, Checksums, OnCalculatedChecksum,
  1170. &Progress, true);
  1171. }
  1172. __finally
  1173. {
  1174. FTerminal->FOperationProgress = NULL;
  1175. Progress.Stop();
  1176. }
  1177. }
  1178. //---------------------------------------------------------------------------
  1179. bool __fastcall TFTPFileSystem::ConfirmOverwrite(
  1180. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1181. TOverwriteMode & OverwriteMode, TFileOperationProgressType * OperationProgress,
  1182. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1183. int Params, bool AutoResume)
  1184. {
  1185. bool Result;
  1186. bool CanAutoResume = FLAGSET(Params, cpNoConfirmation) && AutoResume;
  1187. bool DestIsSmaller = (FileParams != NULL) && (FileParams->DestSize < FileParams->SourceSize);
  1188. bool DestIsSame = (FileParams != NULL) && (FileParams->DestSize == FileParams->SourceSize);
  1189. bool CanResume =
  1190. !OperationProgress->AsciiTransfer &&
  1191. // when resuming transfer after interrupted connection,
  1192. // do nothing (dummy resume) when the files has the same size.
  1193. // this is workaround for servers that strangely fails just after successful
  1194. // upload.
  1195. (DestIsSmaller || (DestIsSame && CanAutoResume));
  1196. unsigned int Answer;
  1197. if (CanAutoResume && CanResume)
  1198. {
  1199. if (DestIsSame)
  1200. {
  1201. DebugAssert(CanAutoResume);
  1202. Answer = qaSkip;
  1203. }
  1204. else
  1205. {
  1206. Answer = qaRetry;
  1207. }
  1208. }
  1209. else
  1210. {
  1211. // retry = "resume"
  1212. // all = "yes to newer"
  1213. // ignore = "rename"
  1214. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  1215. if (CanResume)
  1216. {
  1217. Answers |= qaRetry;
  1218. }
  1219. TQueryButtonAlias Aliases[5];
  1220. Aliases[0].Button = qaRetry;
  1221. Aliases[0].Alias = LoadStr(RESUME_BUTTON);
  1222. Aliases[0].GroupWith = qaNo;
  1223. Aliases[0].GrouppedShiftState = TShiftState() << ssAlt;
  1224. Aliases[1] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
  1225. Aliases[2] = TQueryButtonAlias::CreateIgnoreAsRenameGrouppedWithNo();
  1226. Aliases[3] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
  1227. Aliases[4] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
  1228. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1229. QueryParams.Aliases = Aliases;
  1230. QueryParams.AliasesCount = LENOF(Aliases);
  1231. {
  1232. TSuspendFileOperationProgress Suspend(OperationProgress);
  1233. Answer = FTerminal->ConfirmFileOverwrite(
  1234. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1235. ReverseOperationSide(OperationProgress->Side),
  1236. CopyParam, Params, OperationProgress);
  1237. }
  1238. }
  1239. Result = true;
  1240. switch (Answer)
  1241. {
  1242. // resume
  1243. case qaRetry:
  1244. OverwriteMode = omResume;
  1245. DebugAssert(FileParams != NULL);
  1246. DebugAssert(CanResume);
  1247. FFileTransferResumed = FileParams->DestSize;
  1248. break;
  1249. // rename
  1250. case qaIgnore:
  1251. if (FTerminal->PromptUser(FTerminal->SessionData, pkFileName,
  1252. LoadStr(RENAME_TITLE), L"", LoadStr(RENAME_PROMPT2), true, 0, TargetFileName))
  1253. {
  1254. OverwriteMode = omOverwrite;
  1255. }
  1256. else
  1257. {
  1258. OperationProgress->SetCancelAtLeast(csCancel);
  1259. FFileTransferAbort = ftaCancel;
  1260. Result = false;
  1261. }
  1262. break;
  1263. case qaYes:
  1264. OverwriteMode = omOverwrite;
  1265. break;
  1266. case qaCancel:
  1267. OperationProgress->SetCancelAtLeast(csCancel);
  1268. FFileTransferAbort = ftaCancel;
  1269. Result = false;
  1270. break;
  1271. case qaNo:
  1272. FFileTransferAbort = ftaSkip;
  1273. Result = false;
  1274. break;
  1275. case qaSkip:
  1276. OverwriteMode = omComplete;
  1277. break;
  1278. default:
  1279. DebugFail();
  1280. Result = false;
  1281. break;
  1282. }
  1283. return Result;
  1284. }
  1285. //---------------------------------------------------------------------------
  1286. void __fastcall TFTPFileSystem::ResetFileTransfer()
  1287. {
  1288. FFileTransferAbort = ftaNone;
  1289. FFileTransferCancelled = false;
  1290. FFileTransferResumed = 0;
  1291. }
  1292. //---------------------------------------------------------------------------
  1293. void __fastcall TFTPFileSystem::ReadDirectoryProgress(__int64 Bytes)
  1294. {
  1295. // with FTP we do not know exactly how many entries we have received,
  1296. // instead we know number of bytes received only.
  1297. // so we report approximation based on average size of entry.
  1298. int Progress = int(Bytes / 80);
  1299. if (Progress - FLastReadDirectoryProgress >= 10)
  1300. {
  1301. bool Cancel = false;
  1302. FLastReadDirectoryProgress = Progress;
  1303. FTerminal->DoReadDirectoryProgress(Progress, 0, Cancel);
  1304. if (Cancel)
  1305. {
  1306. FTerminal->DoReadDirectoryProgress(-2, 0, Cancel);
  1307. FFileZillaIntf->Cancel();
  1308. }
  1309. }
  1310. }
  1311. //---------------------------------------------------------------------------
  1312. void __fastcall TFTPFileSystem::DoFileTransferProgress(__int64 TransferSize,
  1313. __int64 Bytes)
  1314. {
  1315. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  1316. OperationProgress->SetTransferSize(TransferSize);
  1317. if (FFileTransferResumed > 0)
  1318. {
  1319. OperationProgress->AddResumed(FFileTransferResumed);
  1320. FFileTransferResumed = 0;
  1321. }
  1322. __int64 Diff = Bytes - OperationProgress->TransferredSize;
  1323. if (DebugAlwaysTrue(Diff >= 0))
  1324. {
  1325. OperationProgress->AddTransferred(Diff);
  1326. FFileTransferAny = true;
  1327. }
  1328. if (OperationProgress->Cancel != csContinue)
  1329. {
  1330. if (OperationProgress->ClearCancelFile())
  1331. {
  1332. FFileTransferAbort = ftaSkip;
  1333. }
  1334. else
  1335. {
  1336. FFileTransferAbort = ftaCancel;
  1337. }
  1338. FFileTransferCancelled = true;
  1339. FFileZillaIntf->Cancel();
  1340. }
  1341. if (FFileTransferCPSLimit != OperationProgress->CPSLimit)
  1342. {
  1343. SetCPSLimit(OperationProgress);
  1344. }
  1345. }
  1346. //---------------------------------------------------------------------------
  1347. void __fastcall TFTPFileSystem::SetCPSLimit(TFileOperationProgressType * OperationProgress)
  1348. {
  1349. // Any reason we use separate field intead of directly using OperationProgress->CPSLimit?
  1350. // Maybe thread-safety?
  1351. FFileTransferCPSLimit = OperationProgress->CPSLimit;
  1352. OperationProgress->SetSpeedCounters();
  1353. }
  1354. //---------------------------------------------------------------------------
  1355. void __fastcall TFTPFileSystem::FileTransferProgress(__int64 TransferSize,
  1356. __int64 Bytes)
  1357. {
  1358. TGuard Guard(FTransferStatusCriticalSection);
  1359. DoFileTransferProgress(TransferSize, Bytes);
  1360. }
  1361. //---------------------------------------------------------------------------
  1362. void __fastcall TFTPFileSystem::FileTransfer(const UnicodeString & FileName,
  1363. const UnicodeString & LocalFile, const UnicodeString & RemoteFile,
  1364. const UnicodeString & RemotePath, bool Get, __int64 Size, int Type,
  1365. TFileTransferData & UserData, TFileOperationProgressType * OperationProgress)
  1366. {
  1367. FILE_OPERATION_LOOP_BEGIN
  1368. {
  1369. FFileZillaIntf->FileTransfer(LocalFile.c_str(), RemoteFile.c_str(),
  1370. RemotePath.c_str(), Get, Size, Type, &UserData);
  1371. // we may actually catch response code of the listing
  1372. // command (when checking for existence of the remote file)
  1373. unsigned int Reply = WaitForCommandReply();
  1374. GotReply(Reply, FLAGMASK(FFileTransferCancelled, REPLY_ALLOW_CANCEL));
  1375. }
  1376. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1377. switch (FFileTransferAbort)
  1378. {
  1379. case ftaSkip:
  1380. throw ESkipFile();
  1381. case ftaCancel:
  1382. Abort();
  1383. break;
  1384. }
  1385. if (!FFileTransferCancelled)
  1386. {
  1387. // show completion of transfer
  1388. // call non-guarded variant to avoid deadlock with keepalives
  1389. // (we are not waiting for reply anymore so keepalives are free to proceed)
  1390. DoFileTransferProgress(OperationProgress->TransferSize, OperationProgress->TransferSize);
  1391. }
  1392. }
  1393. //---------------------------------------------------------------------------
  1394. void __fastcall TFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1395. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1396. int Params, TFileOperationProgressType * OperationProgress,
  1397. TOnceDoneOperation & OnceDoneOperation)
  1398. {
  1399. Params &= ~cpAppend;
  1400. FTerminal->DoCopyToLocal(
  1401. FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfUseFileTransferAny, OnceDoneOperation);
  1402. }
  1403. //---------------------------------------------------------------------------
  1404. void __fastcall TFTPFileSystem::Sink(
  1405. const UnicodeString & FileName, const TRemoteFile * File,
  1406. const UnicodeString & TargetDir, UnicodeString & DestFileName, int Attrs,
  1407. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  1408. unsigned int Flags, TDownloadSessionAction & Action)
  1409. {
  1410. AutoDetectTimeDifference(UnixExtractFileDir(FileName), CopyParam, Params);
  1411. ResetFileTransfer();
  1412. TFileTransferData UserData;
  1413. UnicodeString DestFullName = TargetDir + DestFileName;
  1414. UnicodeString FilePath = UnixExtractFilePath(FileName);
  1415. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1416. {
  1417. // ignore file list
  1418. TFileListHelper Helper(this, NULL, true);
  1419. SetCPSLimit(OperationProgress);
  1420. FFileTransferPreserveTime = CopyParam->PreserveTime;
  1421. // not used for downloads anyway
  1422. FFileTransferRemoveBOM = CopyParam->RemoveBOM;
  1423. FFileTransferNoList = CanTransferSkipList(Params, Flags, CopyParam);
  1424. UserData.FileName = DestFileName;
  1425. UserData.Params = Params;
  1426. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1427. UserData.CopyParam = CopyParam;
  1428. UserData.Modification = File->Modification;
  1429. UnicodeString OnlyFileName = UnixExtractFileName(FileName);
  1430. FileTransfer(FileName, DestFullName, OnlyFileName,
  1431. FilePath, true, File->Size, TransferType, UserData, OperationProgress);
  1432. }
  1433. // in case dest filename is changed from overwrite dialog
  1434. if (DestFileName != UserData.FileName)
  1435. {
  1436. DestFullName = TargetDir + UserData.FileName;
  1437. Attrs = FileGetAttrFix(ApiPath(DestFullName));
  1438. }
  1439. UnicodeString ExpandedDestFullName = ExpandUNCFileName(DestFullName);
  1440. Action.Destination(ExpandedDestFullName);
  1441. FTerminal->UpdateTargetAttrs(DestFullName, File, CopyParam, Attrs);
  1442. FLastDataSent = Now();
  1443. }
  1444. //---------------------------------------------------------------------------
  1445. void __fastcall TFTPFileSystem::TransferOnDirectory(
  1446. const UnicodeString & Directory, const TCopyParamType * CopyParam, int Params)
  1447. {
  1448. AutoDetectTimeDifference(Directory, CopyParam, Params);
  1449. }
  1450. //---------------------------------------------------------------------------
  1451. void __fastcall TFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1452. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1453. int Params, TFileOperationProgressType * OperationProgress,
  1454. TOnceDoneOperation & OnceDoneOperation)
  1455. {
  1456. Params &= ~cpAppend;
  1457. FTerminal->DoCopyToRemote(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfUseFileTransferAny, OnceDoneOperation);
  1458. }
  1459. //---------------------------------------------------------------------------
  1460. bool __fastcall TFTPFileSystem::CanTransferSkipList(int Params, unsigned int Flags, const TCopyParamType * CopyParam)
  1461. {
  1462. bool Result =
  1463. FLAGSET(Params, cpNoConfirmation) &&
  1464. // cpAppend is not supported with FTP
  1465. DebugAlwaysTrue(FLAGCLEAR(Params, cpAppend)) &&
  1466. FLAGCLEAR(Params, cpResume) &&
  1467. FLAGCLEAR(Flags, tfAutoResume) &&
  1468. !CopyParam->NewerOnly;
  1469. return Result;
  1470. }
  1471. //---------------------------------------------------------------------------
  1472. void __fastcall TFTPFileSystem::Source(
  1473. TLocalFileHandle & Handle, const UnicodeString & TargetDir, UnicodeString & DestFileName,
  1474. const TCopyParamType * CopyParam, int Params,
  1475. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1476. TUploadSessionAction & Action, bool & /*ChildError*/)
  1477. {
  1478. Handle.Close();
  1479. ResetFileTransfer();
  1480. TFileTransferData UserData;
  1481. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1482. {
  1483. // ignore file list
  1484. TFileListHelper Helper(this, NULL, true);
  1485. SetCPSLimit(OperationProgress);
  1486. // not used for uploads anyway
  1487. FFileTransferPreserveTime = CopyParam->PreserveTime;
  1488. FFileTransferRemoveBOM = CopyParam->RemoveBOM;
  1489. FFileTransferNoList = CanTransferSkipList(Params, Flags, CopyParam);
  1490. // not used for uploads, but we get new name (if any) back in this field
  1491. UserData.FileName = DestFileName;
  1492. UserData.Params = Params;
  1493. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1494. UserData.CopyParam = CopyParam;
  1495. UserData.Modification = Handle.Modification;
  1496. FileTransfer(Handle.FileName, Handle.FileName, DestFileName,
  1497. TargetDir, false, Handle.Size, TransferType, UserData, OperationProgress);
  1498. }
  1499. UnicodeString DestFullName = TargetDir + UserData.FileName;
  1500. // only now, we know the final destination
  1501. Action.Destination(DestFullName);
  1502. // We are not able to tell if setting timestamp succeeded,
  1503. // so we log it always (if supported).
  1504. // Support for MDTM does not necessarily mean that the server supports
  1505. // non-standard hack of setting timestamp using
  1506. // MFMT-like (two argument) call to MDTM.
  1507. // IIS definitelly does.
  1508. if (FFileTransferPreserveTime &&
  1509. ((FServerCapabilities->GetCapability(mfmt_command) == yes) ||
  1510. ((FServerCapabilities->GetCapability(mdtm_command) == yes))))
  1511. {
  1512. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Handle.Modification);
  1513. if (!FFileZillaIntf->UsingMlsd())
  1514. {
  1515. FUploadedTimes[DestFullName] = Handle.Modification;
  1516. if ((FTerminal->Configuration->ActualLogProtocol >= 2))
  1517. {
  1518. FTerminal->LogEvent(
  1519. FORMAT(L"Remembering modification time of \"%s\" as [%s]",
  1520. (DestFullName, StandardTimestamp(FUploadedTimes[DestFullName]))));
  1521. }
  1522. }
  1523. }
  1524. FLastDataSent = Now();
  1525. }
  1526. //---------------------------------------------------------------------------
  1527. void __fastcall TFTPFileSystem::CreateDirectory(const UnicodeString ADirName)
  1528. {
  1529. UnicodeString DirName = AbsolutePath(ADirName, false);
  1530. {
  1531. // ignore file list
  1532. TFileListHelper Helper(this, NULL, true);
  1533. FFileZillaIntf->MakeDir(DirName.c_str());
  1534. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1535. }
  1536. }
  1537. //---------------------------------------------------------------------------
  1538. void __fastcall TFTPFileSystem::CreateLink(const UnicodeString FileName,
  1539. const UnicodeString PointTo, bool Symbolic)
  1540. {
  1541. DebugAssert(SupportsSiteCommand(SymlinkSiteCommand));
  1542. if (DebugAlwaysTrue(Symbolic))
  1543. {
  1544. EnsureLocation();
  1545. UnicodeString Command = FORMAT(L"%s %s %s %s", (SiteCommand, SymlinkSiteCommand, PointTo, FileName));
  1546. SendCommand(Command);
  1547. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1548. }
  1549. }
  1550. //---------------------------------------------------------------------------
  1551. void __fastcall TFTPFileSystem::DeleteFile(const UnicodeString AFileName,
  1552. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  1553. {
  1554. UnicodeString FileName = AbsolutePath(AFileName, false);
  1555. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  1556. UnicodeString FilePath = UnixExtractFilePath(FileName);
  1557. bool Dir = FTerminal->DeleteContentsIfDirectory(FileName, File, Params, Action);
  1558. {
  1559. // ignore file list
  1560. TFileListHelper Helper(this, NULL, true);
  1561. if (Dir)
  1562. {
  1563. // If current remote directory is in the directory being removed,
  1564. // some servers may refuse to delete it
  1565. // This is common as ProcessDirectory above would CWD to
  1566. // the directory to LIST it.
  1567. // EnsureLocation should reset actual current directory to user's working directory.
  1568. // If user's working directory is still below deleted directory, it is
  1569. // perfectly correct to report an error.
  1570. if (UnixIsChildPath(ActualCurrentDirectory(), FileName))
  1571. {
  1572. EnsureLocation();
  1573. }
  1574. FFileZillaIntf->RemoveDir(FileNameOnly.c_str(), FilePath.c_str());
  1575. }
  1576. else
  1577. {
  1578. if ((FTerminal->SessionData->FtpDeleteFromCwd == asOn) ||
  1579. ((FTerminal->SessionData->FtpDeleteFromCwd == asAuto) && FVMS))
  1580. {
  1581. EnsureLocation(FilePath, false);
  1582. FFileZillaIntf->Delete(FileNameOnly.c_str(), L"", true);
  1583. }
  1584. else
  1585. {
  1586. FFileZillaIntf->Delete(FileNameOnly.c_str(), FilePath.c_str(), false);
  1587. }
  1588. }
  1589. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1590. }
  1591. }
  1592. //---------------------------------------------------------------------------
  1593. void __fastcall TFTPFileSystem::CustomCommandOnFile(const UnicodeString /*FileName*/,
  1594. const TRemoteFile * /*File*/, UnicodeString /*Command*/, int /*Params*/,
  1595. TCaptureOutputEvent /*OutputEvent*/)
  1596. {
  1597. // if ever implemented, do not forget to add EnsureLocation,
  1598. // see AnyCommand for a reason why
  1599. DebugFail();
  1600. }
  1601. //---------------------------------------------------------------------------
  1602. void __fastcall TFTPFileSystem::DoStartup()
  1603. {
  1604. TStrings * PostLoginCommands = new TStringList();
  1605. try
  1606. {
  1607. PostLoginCommands->Text = FTerminal->SessionData->PostLoginCommands;
  1608. for (int Index = 0; Index < PostLoginCommands->Count; Index++)
  1609. {
  1610. UnicodeString Command = PostLoginCommands->Strings[Index];
  1611. if (!Command.IsEmpty())
  1612. {
  1613. SendCommand(Command);
  1614. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_3XX_CODE);
  1615. }
  1616. }
  1617. }
  1618. __finally
  1619. {
  1620. delete PostLoginCommands;
  1621. }
  1622. // retrieve initialize working directory to save it as home directory
  1623. ReadCurrentDirectory();
  1624. FHomeDirectory = FCurrentDirectory;
  1625. }
  1626. //---------------------------------------------------------------------------
  1627. void __fastcall TFTPFileSystem::HomeDirectory()
  1628. {
  1629. // FHomeDirectory is an absolute path, so avoid unnecessary overhead
  1630. // of ChangeDirectory, such as EnsureLocation
  1631. DoChangeDirectory(FHomeDirectory);
  1632. FCurrentDirectory = FHomeDirectory;
  1633. FReadCurrentDirectory = false;
  1634. // make sure FZAPI is aware that we changed current working directory
  1635. FFileZillaIntf->SetCurrentPath(FCurrentDirectory.c_str());
  1636. }
  1637. //---------------------------------------------------------------------------
  1638. bool __fastcall TFTPFileSystem::IsCapable(int Capability) const
  1639. {
  1640. DebugAssert(FTerminal);
  1641. switch (Capability)
  1642. {
  1643. case fcResolveSymlink: // sic
  1644. case fcTextMode:
  1645. case fcModeChanging: // but not fcModeChangingUpload
  1646. case fcNewerOnlyUpload:
  1647. case fcAnyCommand: // but not fcShellAnyCommand
  1648. case fcRename:
  1649. case fcRemoteMove:
  1650. case fcRemoveBOMUpload:
  1651. case fcMoveToQueue:
  1652. case fsSkipTransfer:
  1653. case fsParallelTransfers:
  1654. return true;
  1655. case fcPreservingTimestampUpload:
  1656. return (FServerCapabilities->GetCapability(mfmt_command) == yes);
  1657. case fcRemoteCopy:
  1658. return SupportsSiteCommand(CopySiteCommand);
  1659. case fcSymbolicLink:
  1660. return SupportsSiteCommand(SymlinkSiteCommand);
  1661. case fcCalculatingChecksum:
  1662. return FSupportsAnyChecksumFeature;
  1663. case fcCheckingSpaceAvailable:
  1664. return FBytesAvailableSuppoted || SupportsCommand(AvblCommand) || SupportsCommand(XQuotaCommand);
  1665. case fcModeChangingUpload:
  1666. case fcLoadingAdditionalProperties:
  1667. case fcShellAnyCommand:
  1668. case fcHardLink:
  1669. case fcUserGroupListing:
  1670. case fcGroupChanging:
  1671. case fcOwnerChanging:
  1672. case fcGroupOwnerChangingByID:
  1673. case fcSecondaryShell:
  1674. case fcNativeTextMode:
  1675. case fcTimestampChanging:
  1676. case fcIgnorePermErrors:
  1677. case fcRemoveCtrlZUpload:
  1678. case fcLocking:
  1679. case fcPreservingTimestampDirs:
  1680. case fcResumeSupport:
  1681. case fcChangePassword:
  1682. return false;
  1683. default:
  1684. DebugFail();
  1685. return false;
  1686. }
  1687. }
  1688. //---------------------------------------------------------------------------
  1689. void __fastcall TFTPFileSystem::LookupUsersGroups()
  1690. {
  1691. DebugFail();
  1692. }
  1693. //---------------------------------------------------------------------------
  1694. void __fastcall TFTPFileSystem::ReadCurrentDirectory()
  1695. {
  1696. // ask the server for current directory on startup only
  1697. // and immediately after call to CWD,
  1698. // later our current directory may be not synchronized with FZAPI current
  1699. // directory anyway, see comments in EnsureLocation
  1700. if (FReadCurrentDirectory || DebugAlwaysFalse(FCurrentDirectory.IsEmpty()))
  1701. {
  1702. UnicodeString Command = L"PWD";
  1703. SendCommand(Command);
  1704. unsigned int Code;
  1705. TStrings * Response = NULL;
  1706. GotReply(WaitForCommandReply(), REPLY_2XX_CODE, L"", &Code, &Response);
  1707. try
  1708. {
  1709. DebugAssert(Response != NULL);
  1710. bool Result = false;
  1711. // the only allowed 2XX code to "PWD"
  1712. if ((Code == 257) &&
  1713. (Response->Count == 1))
  1714. {
  1715. UnicodeString Path = Response->Text;
  1716. int P = Path.Pos(L"\"");
  1717. if (P == 0)
  1718. {
  1719. // some systems use single quotes, be tolerant
  1720. P = Path.Pos(L"'");
  1721. }
  1722. if (P != 0)
  1723. {
  1724. Path.Delete(1, P - 1);
  1725. if (Unquote(Path))
  1726. {
  1727. Result = true;
  1728. }
  1729. }
  1730. else
  1731. {
  1732. P = Path.Pos(L" ");
  1733. Path.Delete(P, Path.Length() - P + 1);
  1734. Result = true;
  1735. }
  1736. if (Result)
  1737. {
  1738. if ((Path.Length() > 0) && !UnixIsAbsolutePath(Path))
  1739. {
  1740. Path = L"/" + Path;
  1741. }
  1742. FCurrentDirectory = UnixExcludeTrailingBackslash(Path);
  1743. FReadCurrentDirectory = false;
  1744. }
  1745. }
  1746. if (Result)
  1747. {
  1748. FFileZillaIntf->SetCurrentPath(FCurrentDirectory.c_str());
  1749. }
  1750. else
  1751. {
  1752. throw Exception(FMTLOAD(FTP_RESPONSE_ERROR, (Command, Response->Text)));
  1753. }
  1754. }
  1755. __finally
  1756. {
  1757. delete Response;
  1758. }
  1759. }
  1760. }
  1761. //---------------------------------------------------------------------------
  1762. void __fastcall TFTPFileSystem::DoReadDirectory(TRemoteFileList * FileList)
  1763. {
  1764. FBytesAvailable = -1;
  1765. FileList->Reset();
  1766. // FZAPI does not list parent directory, add it
  1767. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  1768. FLastReadDirectoryProgress = 0;
  1769. TFileListHelper Helper(this, FileList, false);
  1770. // always specify path to list, do not attempt to list "current" dir as:
  1771. // 1) List() lists again the last listed directory, not the current working directory
  1772. // 2) we handle this way the cached directory change
  1773. UnicodeString Directory = AbsolutePath(FileList->Directory, false);
  1774. FFileZillaIntf->List(Directory.c_str());
  1775. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_ALLOW_CANCEL);
  1776. AutoDetectTimeDifference(FileList);
  1777. if (!IsEmptyFileList(FileList))
  1778. {
  1779. CheckTimeDifference();
  1780. if ((FTimeDifference != 0) || !FUploadedTimes.empty())// optimization
  1781. {
  1782. for (int Index = 0; Index < FileList->Count; Index++)
  1783. {
  1784. ApplyTimeDifference(FileList->Files[Index]);
  1785. }
  1786. }
  1787. }
  1788. FLastDataSent = Now();
  1789. }
  1790. //---------------------------------------------------------------------------
  1791. void __fastcall TFTPFileSystem::CheckTimeDifference()
  1792. {
  1793. if (NeedAutoDetectTimeDifference())
  1794. {
  1795. FTerminal->LogEvent("Warning: Timezone difference was not detected yet, timestamps may be incorrect");
  1796. }
  1797. }
  1798. //---------------------------------------------------------------------------
  1799. void __fastcall TFTPFileSystem::ApplyTimeDifference(TRemoteFile * File)
  1800. {
  1801. DebugAssert(File->Modification == File->LastAccess);
  1802. File->ShiftTimeInSeconds(FTimeDifference);
  1803. TDateTime Modification = File->Modification;
  1804. if (LookupUploadModificationTime(File->FullFileName, Modification, File->ModificationFmt))
  1805. {
  1806. // implicitly sets ModificationFmt to mfFull
  1807. File->Modification = Modification;
  1808. }
  1809. }
  1810. //---------------------------------------------------------------------------
  1811. void __fastcall TFTPFileSystem::ApplyTimeDifference(
  1812. const UnicodeString & FileName, TDateTime & Modification, TModificationFmt & ModificationFmt)
  1813. {
  1814. CheckTimeDifference();
  1815. TRemoteFile::ShiftTimeInSeconds(Modification, ModificationFmt, FTimeDifference);
  1816. if (LookupUploadModificationTime(FileName, Modification, ModificationFmt))
  1817. {
  1818. ModificationFmt = mfFull;
  1819. }
  1820. }
  1821. //---------------------------------------------------------------------------
  1822. bool __fastcall TFTPFileSystem::LookupUploadModificationTime(
  1823. const UnicodeString & FileName, TDateTime & Modification, TModificationFmt ModificationFmt)
  1824. {
  1825. bool Result = false;
  1826. if (ModificationFmt != mfFull)
  1827. {
  1828. TUploadedTimes::iterator Iterator = FUploadedTimes.find(AbsolutePath(FileName, false));
  1829. if (Iterator != FUploadedTimes.end())
  1830. {
  1831. TDateTime UploadModification = Iterator->second;
  1832. TDateTime UploadModificationReduced = ReduceDateTimePrecision(UploadModification, ModificationFmt);
  1833. if (UploadModificationReduced == Modification)
  1834. {
  1835. if ((FTerminal->Configuration->ActualLogProtocol >= 2))
  1836. {
  1837. FTerminal->LogEvent(
  1838. FORMAT(L"Enriching modification time of \"%s\" from [%s] to [%s]",
  1839. (FileName, StandardTimestamp(Modification), StandardTimestamp(UploadModification))));
  1840. }
  1841. Modification = UploadModification;
  1842. Result = true;
  1843. }
  1844. else
  1845. {
  1846. if ((FTerminal->Configuration->ActualLogProtocol >= 2))
  1847. {
  1848. FTerminal->LogEvent(
  1849. FORMAT(L"Remembered modification time [%s]/[%s] of \"%s\" is obsolete, keeping [%s]",
  1850. (StandardTimestamp(UploadModification), StandardTimestamp(UploadModificationReduced), FileName, StandardTimestamp(Modification))));
  1851. }
  1852. FUploadedTimes.erase(Iterator);
  1853. }
  1854. }
  1855. }
  1856. return Result;
  1857. }
  1858. //---------------------------------------------------------------------------
  1859. bool __fastcall TFTPFileSystem::NeedAutoDetectTimeDifference()
  1860. {
  1861. return
  1862. FDetectTimeDifference &&
  1863. // Does not support MLST/MLSD, but supports MDTM at least
  1864. !FFileZillaIntf->UsingMlsd() && SupportsReadingFile();
  1865. }
  1866. //---------------------------------------------------------------------------
  1867. bool __fastcall TFTPFileSystem::IsEmptyFileList(TRemoteFileList * FileList)
  1868. {
  1869. return
  1870. // (note that it's actually never empty here, there's always at least parent directory,
  1871. // added explicitly by DoReadDirectory)
  1872. (FileList->Count == 0) ||
  1873. ((FileList->Count == 1) && FileList->Files[0]->IsParentDirectory);
  1874. }
  1875. //---------------------------------------------------------------------------
  1876. void __fastcall TFTPFileSystem::AutoDetectTimeDifference(TRemoteFileList * FileList)
  1877. {
  1878. if (NeedAutoDetectTimeDifference())
  1879. {
  1880. FTerminal->LogEvent(L"Detecting timezone difference...");
  1881. for (int Index = 0; Index < FileList->Count; Index++)
  1882. {
  1883. TRemoteFile * File = FileList->Files[Index];
  1884. // For directories, we do not do MDTM in ReadFile
  1885. // (it should not be problem to use them otherwise).
  1886. // We are also not interested in files with day precision only.
  1887. if (!File->IsDirectory && !File->IsSymLink &&
  1888. File->IsTimeShiftingApplicable())
  1889. {
  1890. TRemoteFile * UtcFile = NULL;
  1891. try
  1892. {
  1893. ReadFile(File->FullFileName, UtcFile);
  1894. }
  1895. catch (Exception & E)
  1896. {
  1897. FDetectTimeDifference = false;
  1898. if (!FTerminal->Active)
  1899. {
  1900. throw;
  1901. }
  1902. FTerminal->LogEvent(FORMAT(L"Failed to retrieve file %s attributes to detect timezone difference", (File->FullFileName)));
  1903. break;
  1904. }
  1905. TDateTime UtcModification = UtcFile->Modification;
  1906. delete UtcFile;
  1907. if (UtcModification > Now())
  1908. {
  1909. FTerminal->LogEvent(
  1910. FORMAT(L"Not using file %s to detect timezone difference as it has the timestamp in the future [%s]",
  1911. (File->FullFileName, StandardTimestamp(UtcModification))));
  1912. }
  1913. else
  1914. {
  1915. FDetectTimeDifference = false;
  1916. // MDTM returns seconds, trim those
  1917. UtcModification = ReduceDateTimePrecision(UtcModification, File->ModificationFmt);
  1918. // Time difference between timestamp retrieved using MDTM (UTC converted to local timezone)
  1919. // and using LIST (no conversion, expecting the server uses the same timezone as the client).
  1920. // Note that FormatTimeZone reverses the value.
  1921. FTimeDifference = static_cast<__int64>(SecsPerDay * (UtcModification - File->Modification));
  1922. UnicodeString FileLog =
  1923. FORMAT(L"%s (Listing: %s, UTF: %s)", (File->FullFileName, StandardTimestamp(File->Modification), StandardTimestamp(UtcModification)));
  1924. UnicodeString LogMessage;
  1925. if (FTimeDifference == 0)
  1926. {
  1927. LogMessage = FORMAT(L"No timezone difference detected using file %s", (FileLog));
  1928. }
  1929. else
  1930. {
  1931. LogMessage = FORMAT(L"Timezone difference of %s detected using file %s", (FormatTimeZone(FTimeDifference), FileLog));
  1932. }
  1933. FTerminal->LogEvent(LogMessage);
  1934. break;
  1935. }
  1936. }
  1937. }
  1938. if (FDetectTimeDifference)
  1939. {
  1940. FTerminal->LogEvent(L"Found no file to use for detecting timezone difference");
  1941. }
  1942. }
  1943. }
  1944. //---------------------------------------------------------------------------
  1945. void __fastcall TFTPFileSystem::AutoDetectTimeDifference(
  1946. const UnicodeString & Directory, const TCopyParamType * CopyParam, int Params)
  1947. {
  1948. if (NeedAutoDetectTimeDifference() &&
  1949. // do we need FTimeDifference for the operation?
  1950. // (tmAutomatic - AsciiFileMask can theoretically include time constraints, while it is unlikely)
  1951. (!FLAGSET(Params, cpNoConfirmation) ||
  1952. CopyParam->NewerOnly || (!CopyParam->TransferMode == tmAutomatic) || !CopyParam->IncludeFileMask.Masks.IsEmpty()))
  1953. {
  1954. FTerminal->LogEvent(L"Retrieving listing to detect timezone difference");
  1955. DummyReadDirectory(Directory);
  1956. }
  1957. }
  1958. //---------------------------------------------------------------------------
  1959. void __fastcall TFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  1960. {
  1961. // whole below "-a" logic is for LIST,
  1962. // if we know we are going to use MLSD, skip it
  1963. if (FFileZillaIntf->UsingMlsd())
  1964. {
  1965. DoReadDirectory(FileList);
  1966. }
  1967. else
  1968. {
  1969. bool GotNoFilesForAll = false;
  1970. bool Repeat;
  1971. do
  1972. {
  1973. Repeat = false;
  1974. try
  1975. {
  1976. FDoListAll = (FListAll == asAuto) || (FListAll == asOn);
  1977. DoReadDirectory(FileList);
  1978. // We got no files with "-a", but again no files w/o "-a",
  1979. // so it was not "-a"'s problem, revert to auto and let it decide the next time
  1980. if (GotNoFilesForAll && (FileList->Count == 0))
  1981. {
  1982. DebugAssert(FListAll == asOff);
  1983. FListAll = asAuto;
  1984. }
  1985. else if (FListAll == asAuto)
  1986. {
  1987. // some servers take "-a" as a mask and return empty directory listing
  1988. if (IsEmptyFileList(FileList))
  1989. {
  1990. Repeat = true;
  1991. FListAll = asOff;
  1992. GotNoFilesForAll = true;
  1993. FTerminal->LogEvent(L"LIST with -a switch returned empty directory listing, will try pure LIST");
  1994. }
  1995. else
  1996. {
  1997. // reading first directory has succeeded, always use "-a"
  1998. FListAll = asOn;
  1999. }
  2000. }
  2001. // use "-a" even for implicit directory reading by FZAPI?
  2002. // (e.g. before file transfer)
  2003. FDoListAll = (FListAll == asOn);
  2004. }
  2005. catch(Exception & E)
  2006. {
  2007. FDoListAll = false;
  2008. // reading the first directory has failed,
  2009. // further try without "-a" only as the server may not support it
  2010. if (FListAll == asAuto)
  2011. {
  2012. FTerminal->LogEvent(L"LIST with -a failed, will try pure LIST");
  2013. if (!FTerminal->Active)
  2014. {
  2015. FTerminal->Reopen(ropNoReadDirectory);
  2016. }
  2017. FListAll = asOff;
  2018. Repeat = true;
  2019. }
  2020. else
  2021. {
  2022. throw;
  2023. }
  2024. }
  2025. }
  2026. while (Repeat);
  2027. }
  2028. }
  2029. //---------------------------------------------------------------------------
  2030. void __fastcall TFTPFileSystem::DoReadFile(const UnicodeString & AFileName,
  2031. TRemoteFile *& AFile)
  2032. {
  2033. UnicodeString FileName = AbsolutePath(AFileName, false);
  2034. UnicodeString FileNameOnly;
  2035. UnicodeString FilePath;
  2036. if (IsUnixRootPath(FileName))
  2037. {
  2038. FileNameOnly = FileName;
  2039. FilePath = FileName;
  2040. }
  2041. else
  2042. {
  2043. FileNameOnly = UnixExtractFileName(FileName);
  2044. FilePath = UnixExtractFilePath(FileName);
  2045. }
  2046. TRemoteFileList * FileList = new TRemoteFileList();
  2047. try
  2048. {
  2049. // Duplicate() call below would use this to compose FullFileName
  2050. FileList->Directory = FilePath;
  2051. TFileListHelper Helper(this, FileList, false);
  2052. FFileZillaIntf->ListFile(FileNameOnly.c_str(), FilePath.c_str());
  2053. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_ALLOW_CANCEL);
  2054. TRemoteFile * File = FileList->FindFile(FileNameOnly);
  2055. if (File != NULL)
  2056. {
  2057. AFile = File->Duplicate();
  2058. }
  2059. FLastDataSent = Now();
  2060. }
  2061. __finally
  2062. {
  2063. delete FileList;
  2064. }
  2065. }
  2066. //---------------------------------------------------------------------------
  2067. bool __fastcall TFTPFileSystem::SupportsReadingFile()
  2068. {
  2069. return
  2070. FFileZillaIntf->UsingMlsd() ||
  2071. ((FServerCapabilities->GetCapability(mdtm_command) == yes) &&
  2072. (FServerCapabilities->GetCapability(size_command) == yes));
  2073. }
  2074. //---------------------------------------------------------------------------
  2075. void __fastcall TFTPFileSystem::ReadFile(const UnicodeString FileName,
  2076. TRemoteFile *& File)
  2077. {
  2078. File = NULL;
  2079. if (SupportsReadingFile())
  2080. {
  2081. DoReadFile(FileName, File);
  2082. }
  2083. else
  2084. {
  2085. if (IsUnixRootPath(FileName))
  2086. {
  2087. FTerminal->LogEvent(FORMAT(L"%s is a root path", (FileName)));
  2088. File = new TRemoteDirectoryFile();
  2089. File->FullFileName = FileName;
  2090. File->FileName = L"";
  2091. }
  2092. else
  2093. {
  2094. UnicodeString Path = UnixExtractFilePath(FileName);
  2095. UnicodeString NameOnly;
  2096. int P;
  2097. bool MVSPath =
  2098. FMVS && Path.IsEmpty() &&
  2099. (FileName.SubString(1, 1) == L"'") && (FileName.SubString(FileName.Length(), 1) == L"'") &&
  2100. ((P = FileName.Pos(L".")) > 0);
  2101. if (!MVSPath)
  2102. {
  2103. NameOnly = UnixExtractFileName(FileName);
  2104. }
  2105. else
  2106. {
  2107. NameOnly = FileName.SubString(P + 1, FileName.Length() - P - 1);
  2108. }
  2109. TRemoteFile * AFile = NULL;
  2110. // FZAPI does not have efficient way to read properties of one file.
  2111. // In case we need properties of set of files from the same directory,
  2112. // cache the file list for future
  2113. if ((FFileListCache != NULL) &&
  2114. UnixSamePath(Path, FFileListCache->Directory) &&
  2115. (UnixIsAbsolutePath(FFileListCache->Directory) ||
  2116. (FFileListCachePath == CurrentDirectory)))
  2117. {
  2118. AFile = FFileListCache->FindFile(NameOnly);
  2119. }
  2120. // if cache is invalid or file is not in cache, (re)read the directory
  2121. if (AFile == NULL)
  2122. {
  2123. TRemoteFileList * FileListCache = new TRemoteFileList();
  2124. FileListCache->Directory = Path;
  2125. try
  2126. {
  2127. ReadDirectory(FileListCache);
  2128. }
  2129. catch(...)
  2130. {
  2131. delete FileListCache;
  2132. throw;
  2133. }
  2134. // set only after we successfully read the directory,
  2135. // otherwise, when we reconnect from ReadDirectory,
  2136. // the FFileListCache is reset from ResetCache.
  2137. delete FFileListCache;
  2138. FFileListCache = FileListCache;
  2139. FFileListCachePath = GetCurrentDirectory();
  2140. AFile = FFileListCache->FindFile(NameOnly);
  2141. }
  2142. if (AFile != NULL)
  2143. {
  2144. File = AFile->Duplicate();
  2145. if (MVSPath)
  2146. {
  2147. File->FileName = FileName;
  2148. File->FullFileName = FileName;
  2149. }
  2150. }
  2151. }
  2152. }
  2153. if (File == NULL)
  2154. {
  2155. throw Exception(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  2156. }
  2157. }
  2158. //---------------------------------------------------------------------------
  2159. void __fastcall TFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  2160. TRemoteFile *& File)
  2161. {
  2162. // Resolving symlinks over FTP is big overhead
  2163. // (involves opening TCPIP connection for retrieving "directory listing").
  2164. // Moreover FZAPI does not support that anyway.
  2165. // Though nowadays we could use MLST to read the symlink.
  2166. File = new TRemoteFile(SymlinkFile);
  2167. try
  2168. {
  2169. File->Terminal = FTerminal;
  2170. File->FileName = UnixExtractFileName(SymlinkFile->LinkTo);
  2171. // FZAPI treats all symlink target as directories
  2172. File->Type = FILETYPE_DIRECTORY;
  2173. }
  2174. catch(...)
  2175. {
  2176. delete File;
  2177. File = NULL;
  2178. throw;
  2179. }
  2180. }
  2181. //---------------------------------------------------------------------------
  2182. void __fastcall TFTPFileSystem::RenameFile(const UnicodeString AFileName, const TRemoteFile * /*File*/,
  2183. const UnicodeString ANewName)
  2184. {
  2185. UnicodeString FileName = AbsolutePath(AFileName, false);
  2186. UnicodeString NewName = AbsolutePath(ANewName, false);
  2187. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  2188. UnicodeString FilePathOnly = UnixExtractFilePath(FileName);
  2189. UnicodeString NewNameOnly = UnixExtractFileName(NewName);
  2190. UnicodeString NewPathOnly = UnixExtractFilePath(NewName);
  2191. {
  2192. // ignore file list
  2193. TFileListHelper Helper(this, NULL, true);
  2194. FFileZillaIntf->Rename(FileNameOnly.c_str(), NewNameOnly.c_str(),
  2195. FilePathOnly.c_str(), NewPathOnly.c_str());
  2196. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  2197. }
  2198. }
  2199. //---------------------------------------------------------------------------
  2200. void __fastcall TFTPFileSystem::CopyFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  2201. const UnicodeString NewName)
  2202. {
  2203. DebugAssert(SupportsSiteCommand(CopySiteCommand));
  2204. EnsureLocation();
  2205. UnicodeString Command;
  2206. Command = FORMAT(L"%s CPFR %s", (SiteCommand, FileName));
  2207. SendCommand(Command);
  2208. GotReply(WaitForCommandReply(), REPLY_3XX_CODE);
  2209. Command = FORMAT(L"%s CPTO %s", (SiteCommand, NewName));
  2210. SendCommand(Command);
  2211. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  2212. }
  2213. //---------------------------------------------------------------------------
  2214. TStrings * __fastcall TFTPFileSystem::GetFixedPaths()
  2215. {
  2216. return NULL;
  2217. }
  2218. //---------------------------------------------------------------------------
  2219. void __fastcall TFTPFileSystem::SpaceAvailable(const UnicodeString Path,
  2220. TSpaceAvailable & ASpaceAvailable)
  2221. {
  2222. if (FBytesAvailableSuppoted)
  2223. {
  2224. std::unique_ptr<TRemoteFileList> DummyFileList(new TRemoteFileList());
  2225. DummyFileList->Directory = Path;
  2226. ReadDirectory(DummyFileList.get());
  2227. ASpaceAvailable.UnusedBytesAvailableToUser = FBytesAvailable;
  2228. }
  2229. else if (SupportsCommand(XQuotaCommand))
  2230. {
  2231. // WS_FTP:
  2232. // XQUOTA
  2233. // 213-File and disk usage
  2234. // File count: 3
  2235. // File limit: 10000
  2236. // Disk usage: 1532791
  2237. // Disk limit: 2048000
  2238. // 213 File and disk usage end
  2239. // XQUOTA is global not path-specific
  2240. UnicodeString Command = XQuotaCommand;
  2241. SendCommand(Command);
  2242. TStrings * Response = NULL;
  2243. GotReply(WaitForCommandReply(), REPLY_2XX_CODE, L"", NULL, &Response);
  2244. std::unique_ptr<TStrings> ResponseOwner(Response);
  2245. __int64 UsedBytes = -1;
  2246. for (int Index = 0; Index < Response->Count; Index++)
  2247. {
  2248. // trimming padding
  2249. UnicodeString Line = Trim(Response->Strings[Index]);
  2250. UnicodeString Label = CutToChar(Line, L':', true);
  2251. if (SameText(Label, L"Disk usage"))
  2252. {
  2253. UsedBytes = StrToInt64(Line);
  2254. }
  2255. else if (SameText(Label, L"Disk limit") && !SameText(Line, L"unlimited"))
  2256. {
  2257. ASpaceAvailable.BytesAvailableToUser = StrToInt64(Line);
  2258. }
  2259. }
  2260. if ((UsedBytes >= 0) && (ASpaceAvailable.BytesAvailableToUser > 0))
  2261. {
  2262. ASpaceAvailable.UnusedBytesAvailableToUser = ASpaceAvailable.BytesAvailableToUser - UsedBytes;
  2263. }
  2264. }
  2265. else if (SupportsCommand(AvblCommand))
  2266. {
  2267. // draft-peterson-streamlined-ftp-command-extensions-10
  2268. // Implemented by Serv-U.
  2269. UnicodeString Command = FORMAT(L"%s %s", (AvblCommand, Path));
  2270. SendCommand(Command);
  2271. UnicodeString Response = GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_SINGLE_LINE);
  2272. ASpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(Response);
  2273. }
  2274. }
  2275. //---------------------------------------------------------------------------
  2276. const TSessionInfo & __fastcall TFTPFileSystem::GetSessionInfo()
  2277. {
  2278. return FSessionInfo;
  2279. }
  2280. //---------------------------------------------------------------------------
  2281. const TFileSystemInfo & __fastcall TFTPFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  2282. {
  2283. if (!FFileSystemInfoValid)
  2284. {
  2285. FFileSystemInfo.RemoteSystem = FSystem;
  2286. FFileSystemInfo.RemoteSystem.Unique();
  2287. if (FFeatures->Count == 0)
  2288. {
  2289. FFileSystemInfo.AdditionalInfo = LoadStr(FTP_NO_FEATURE_INFO);
  2290. }
  2291. else
  2292. {
  2293. FFileSystemInfo.AdditionalInfo =
  2294. FORMAT(L"%s\r\n", (LoadStr(FTP_FEATURE_INFO)));
  2295. for (int Index = 0; Index < FFeatures->Count; Index++)
  2296. {
  2297. // For TrimLeft, refer to HandleFeatReply
  2298. FFileSystemInfo.AdditionalInfo += FORMAT(L" %s\r\n", (TrimLeft(FFeatures->Strings[Index])));
  2299. }
  2300. }
  2301. FTerminal->SaveCapabilities(FFileSystemInfo);
  2302. FFileSystemInfoValid = true;
  2303. }
  2304. return FFileSystemInfo;
  2305. }
  2306. //---------------------------------------------------------------------------
  2307. bool __fastcall TFTPFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
  2308. {
  2309. return false;
  2310. }
  2311. //---------------------------------------------------------------------------
  2312. bool __fastcall TFTPFileSystem::GetStoredCredentialsTried()
  2313. {
  2314. return FStoredPasswordTried;
  2315. }
  2316. //---------------------------------------------------------------------------
  2317. UnicodeString __fastcall TFTPFileSystem::GetUserName()
  2318. {
  2319. return FUserName;
  2320. }
  2321. //---------------------------------------------------------------------------
  2322. UnicodeString __fastcall TFTPFileSystem::GetCurrentDirectory()
  2323. {
  2324. return FCurrentDirectory;
  2325. }
  2326. //---------------------------------------------------------------------------
  2327. const wchar_t * __fastcall TFTPFileSystem::GetOption(int OptionID) const
  2328. {
  2329. TSessionData * Data = FTerminal->SessionData;
  2330. switch (OptionID)
  2331. {
  2332. case OPTION_PROXYHOST:
  2333. case OPTION_FWHOST:
  2334. FOptionScratch = Data->ProxyHost;
  2335. break;
  2336. case OPTION_PROXYUSER:
  2337. case OPTION_FWUSER:
  2338. FOptionScratch = Data->ProxyUsername;
  2339. break;
  2340. case OPTION_PROXYPASS:
  2341. case OPTION_FWPASS:
  2342. FOptionScratch = Data->ProxyPassword;
  2343. break;
  2344. case OPTION_TRANSFERIP:
  2345. FOptionScratch = FTerminal->Configuration->ExternalIpAddress;
  2346. break;
  2347. case OPTION_ANONPWD:
  2348. case OPTION_TRANSFERIP6:
  2349. FOptionScratch = L"";
  2350. break;
  2351. default:
  2352. DebugFail();
  2353. FOptionScratch = L"";
  2354. }
  2355. return FOptionScratch.c_str();
  2356. }
  2357. //---------------------------------------------------------------------------
  2358. int __fastcall TFTPFileSystem::GetOptionVal(int OptionID) const
  2359. {
  2360. TSessionData * Data = FTerminal->SessionData;
  2361. int Result;
  2362. switch (OptionID)
  2363. {
  2364. case OPTION_PROXYTYPE:
  2365. switch (Data->ProxyMethod)
  2366. {
  2367. case ::pmNone:
  2368. Result = 0; // PROXYTYPE_NOPROXY;
  2369. break;
  2370. case pmSocks4:
  2371. Result = 2; // PROXYTYPE_SOCKS4A
  2372. break;
  2373. case pmSocks5:
  2374. Result = 3; // PROXYTYPE_SOCKS5
  2375. break;
  2376. case pmHTTP:
  2377. Result = 4; // PROXYTYPE_HTTP11
  2378. break;
  2379. case pmTelnet:
  2380. case pmCmd:
  2381. default:
  2382. DebugFail();
  2383. Result = 0; // PROXYTYPE_NOPROXY;
  2384. break;
  2385. }
  2386. break;
  2387. case OPTION_PROXYPORT:
  2388. case OPTION_FWPORT:
  2389. Result = Data->ProxyPort;
  2390. break;
  2391. case OPTION_PROXYUSELOGON:
  2392. Result = !Data->ProxyUsername.IsEmpty();
  2393. break;
  2394. case OPTION_LOGONTYPE:
  2395. Result = Data->FtpProxyLogonType;
  2396. break;
  2397. case OPTION_TIMEOUTLENGTH:
  2398. Result = Data->Timeout;
  2399. break;
  2400. case OPTION_DEBUGSHOWLISTING:
  2401. Result = (FTerminal->Configuration->ActualLogProtocol >= 0);
  2402. break;
  2403. case OPTION_PASV:
  2404. // should never get here t_server.nPasv being nonzero
  2405. DebugFail();
  2406. Result = FALSE;
  2407. break;
  2408. case OPTION_PRESERVEDOWNLOADFILETIME:
  2409. case OPTION_MPEXT_PRESERVEUPLOADFILETIME:
  2410. Result = FFileTransferPreserveTime ? TRUE : FALSE;
  2411. break;
  2412. case OPTION_LIMITPORTRANGE:
  2413. Result = FALSE;
  2414. break;
  2415. case OPTION_PORTRANGELOW:
  2416. case OPTION_PORTRANGEHIGH:
  2417. // should never get here OPTION_LIMITPORTRANGE being zero
  2418. DebugFail();
  2419. Result = 0;
  2420. break;
  2421. case OPTION_ENABLE_IPV6:
  2422. Result = ((Data->AddressFamily != afIPv4) ? TRUE : FALSE);
  2423. break;
  2424. case OPTION_KEEPALIVE:
  2425. Result = ((Data->FtpPingType != ptOff) ? TRUE : FALSE);
  2426. break;
  2427. case OPTION_INTERVALLOW:
  2428. case OPTION_INTERVALHIGH:
  2429. Result = Data->FtpPingInterval;
  2430. break;
  2431. case OPTION_VMSALLREVISIONS:
  2432. Result = FALSE;
  2433. break;
  2434. case OPTION_SPEEDLIMIT_DOWNLOAD_TYPE:
  2435. case OPTION_SPEEDLIMIT_UPLOAD_TYPE:
  2436. Result = (FFileTransferCPSLimit == 0 ? 0 : 1);
  2437. break;
  2438. case OPTION_SPEEDLIMIT_DOWNLOAD_VALUE:
  2439. case OPTION_SPEEDLIMIT_UPLOAD_VALUE:
  2440. Result = (FFileTransferCPSLimit / 1024); // FZAPI expects KB/s
  2441. break;
  2442. case OPTION_MPEXT_SHOWHIDDEN:
  2443. Result = (FDoListAll ? TRUE : FALSE);
  2444. break;
  2445. case OPTION_MPEXT_SSLSESSIONREUSE:
  2446. Result = (Data->SslSessionReuse ? TRUE : FALSE);
  2447. break;
  2448. case OPTION_MPEXT_MIN_TLS_VERSION:
  2449. Result = Data->MinTlsVersion;
  2450. break;
  2451. case OPTION_MPEXT_MAX_TLS_VERSION:
  2452. Result = Data->MaxTlsVersion;
  2453. break;
  2454. case OPTION_MPEXT_SNDBUF:
  2455. Result = Data->SendBuf;
  2456. break;
  2457. case OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY:
  2458. Result = FTransferActiveImmediately;
  2459. break;
  2460. case OPTION_MPEXT_REMOVE_BOM:
  2461. Result = FFileTransferRemoveBOM ? TRUE : FALSE;
  2462. break;
  2463. case OPTION_MPEXT_LOG_SENSITIVE:
  2464. Result = FTerminal->Configuration->LogSensitive ? TRUE : FALSE;
  2465. break;
  2466. case OPTION_MPEXT_HOST:
  2467. Result = (Data->FtpHost == asOn);
  2468. break;
  2469. case OPTION_MPEXT_NODELAY:
  2470. Result = Data->TcpNoDelay;
  2471. break;
  2472. case OPTION_MPEXT_NOLIST:
  2473. Result = FFileTransferNoList ? TRUE : FALSE;
  2474. break;
  2475. default:
  2476. DebugFail();
  2477. Result = FALSE;
  2478. break;
  2479. }
  2480. return Result;
  2481. }
  2482. //---------------------------------------------------------------------------
  2483. bool __fastcall TFTPFileSystem::PostMessage(unsigned int Type, WPARAM wParam, LPARAM lParam)
  2484. {
  2485. if (Type == TFileZillaIntf::MSG_TRANSFERSTATUS)
  2486. {
  2487. // Stop here if FileTransferProgress is proceeding,
  2488. // it makes "pause" in queue work.
  2489. // Paused queue item stops in some of the TFileOperationProgressType
  2490. // methods called from FileTransferProgress
  2491. TGuard Guard(FTransferStatusCriticalSection);
  2492. }
  2493. TGuard Guard(FQueueCriticalSection);
  2494. FQueue->push_back(TMessageQueue::value_type(wParam, lParam));
  2495. SetEvent(FQueueEvent);
  2496. return true;
  2497. }
  2498. //---------------------------------------------------------------------------
  2499. bool __fastcall TFTPFileSystem::ProcessMessage()
  2500. {
  2501. bool Result;
  2502. TMessageQueue::value_type Message;
  2503. {
  2504. TGuard Guard(FQueueCriticalSection);
  2505. Result = !FQueue->empty();
  2506. if (Result)
  2507. {
  2508. Message = FQueue->front();
  2509. FQueue->pop_front();
  2510. }
  2511. else
  2512. {
  2513. // now we are perfectly sure that the queue is empty as it is locked,
  2514. // so reset the event
  2515. ResetEvent(FQueueEvent);
  2516. }
  2517. }
  2518. if (Result)
  2519. {
  2520. FFileZillaIntf->HandleMessage(Message.first, Message.second);
  2521. }
  2522. return Result;
  2523. }
  2524. //---------------------------------------------------------------------------
  2525. void __fastcall TFTPFileSystem::DiscardMessages()
  2526. {
  2527. while (ProcessMessage());
  2528. }
  2529. //---------------------------------------------------------------------------
  2530. void __fastcall TFTPFileSystem::WaitForMessages()
  2531. {
  2532. unsigned int Result;
  2533. do
  2534. {
  2535. Result = WaitForSingleObject(FQueueEvent, GUIUpdateInterval);
  2536. FTerminal->ProcessGUI();
  2537. } while (Result == WAIT_TIMEOUT);
  2538. if (Result != WAIT_OBJECT_0)
  2539. {
  2540. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, (L"ftp#1", IntToStr(int(Result)))));
  2541. }
  2542. }
  2543. //---------------------------------------------------------------------------
  2544. void __fastcall TFTPFileSystem::PoolForFatalNonCommandReply()
  2545. {
  2546. DebugAssert(FReply == 0);
  2547. DebugAssert(FCommandReply == 0);
  2548. DebugAssert(!FWaitingForReply);
  2549. FWaitingForReply = true;
  2550. unsigned int Reply;
  2551. try
  2552. {
  2553. // discard up to one reply
  2554. // (it should not happen here that two replies are posted anyway)
  2555. while (ProcessMessage() && (FReply == 0));
  2556. Reply = FReply;
  2557. }
  2558. __finally
  2559. {
  2560. FReply = 0;
  2561. DebugAssert(FCommandReply == 0);
  2562. FCommandReply = 0;
  2563. DebugAssert(FWaitingForReply);
  2564. FWaitingForReply = false;
  2565. }
  2566. if (Reply != 0)
  2567. {
  2568. // throws
  2569. GotNonCommandReply(Reply);
  2570. }
  2571. }
  2572. //---------------------------------------------------------------------------
  2573. bool __fastcall TFTPFileSystem::NoFinalLastCode()
  2574. {
  2575. return (FLastCodeClass == 0) || (FLastCodeClass == 1);
  2576. }
  2577. //---------------------------------------------------------------------------
  2578. bool __fastcall TFTPFileSystem::KeepWaitingForReply(unsigned int & ReplyToAwait, bool WantLastCode)
  2579. {
  2580. // to keep waiting,
  2581. // non-command reply must be unset,
  2582. // the reply we wait for must be unset or
  2583. // last code must be unset (if we wait for it)
  2584. return
  2585. (FReply == 0) &&
  2586. ((ReplyToAwait == 0) ||
  2587. (WantLastCode && NoFinalLastCode()));
  2588. }
  2589. //---------------------------------------------------------------------------
  2590. void __fastcall TFTPFileSystem::DoWaitForReply(unsigned int & ReplyToAwait, bool WantLastCode)
  2591. {
  2592. try
  2593. {
  2594. while (KeepWaitingForReply(ReplyToAwait, WantLastCode))
  2595. {
  2596. WaitForMessages();
  2597. // wait for the first reply only,
  2598. // i.e. in case two replies are posted get the first only.
  2599. // e.g. when server closes the connection, but posts error message before,
  2600. // sometime it happens that command (like download) fails because of the error
  2601. // and does not catch the disconnection. then asynchronous "disconnect reply"
  2602. // is posted immediately afterwards. leave detection of that to Idle()
  2603. while (ProcessMessage() && KeepWaitingForReply(ReplyToAwait, WantLastCode));
  2604. }
  2605. if (FReply != 0)
  2606. {
  2607. // throws
  2608. GotNonCommandReply(FReply);
  2609. }
  2610. }
  2611. catch(...)
  2612. {
  2613. // even if non-fatal error happens, we must process pending message,
  2614. // so that we "eat" the reply message, so that it gets not mistakenly
  2615. // associated with future connect
  2616. if (FTerminal->Active)
  2617. {
  2618. DoWaitForReply(ReplyToAwait, WantLastCode);
  2619. }
  2620. throw;
  2621. }
  2622. }
  2623. //---------------------------------------------------------------------------
  2624. unsigned int __fastcall TFTPFileSystem::WaitForReply(bool Command, bool WantLastCode)
  2625. {
  2626. DebugAssert(FReply == 0);
  2627. DebugAssert(FCommandReply == 0);
  2628. DebugAssert(!FWaitingForReply);
  2629. ResetReply();
  2630. FWaitingForReply = true;
  2631. unsigned int Reply;
  2632. try
  2633. {
  2634. unsigned int & ReplyToAwait = (Command ? FCommandReply : FReply);
  2635. DoWaitForReply(ReplyToAwait, WantLastCode);
  2636. Reply = ReplyToAwait;
  2637. }
  2638. __finally
  2639. {
  2640. FReply = 0;
  2641. FCommandReply = 0;
  2642. DebugAssert(FWaitingForReply);
  2643. FWaitingForReply = false;
  2644. }
  2645. return Reply;
  2646. }
  2647. //---------------------------------------------------------------------------
  2648. unsigned int __fastcall TFTPFileSystem::WaitForCommandReply(bool WantLastCode)
  2649. {
  2650. return WaitForReply(true, WantLastCode);
  2651. }
  2652. //---------------------------------------------------------------------------
  2653. void __fastcall TFTPFileSystem::WaitForFatalNonCommandReply()
  2654. {
  2655. WaitForReply(false, false);
  2656. DebugFail();
  2657. }
  2658. //---------------------------------------------------------------------------
  2659. void __fastcall TFTPFileSystem::ResetReply()
  2660. {
  2661. FLastCode = 0;
  2662. FLastCodeClass = 0;
  2663. DebugAssert(FLastResponse != NULL);
  2664. FLastResponse->Clear();
  2665. DebugAssert(FLastErrorResponse != NULL);
  2666. FLastErrorResponse->Clear();
  2667. DebugAssert(FLastError != NULL);
  2668. FLastError->Clear();
  2669. }
  2670. //---------------------------------------------------------------------------
  2671. void __fastcall TFTPFileSystem::GotNonCommandReply(unsigned int Reply)
  2672. {
  2673. DebugAssert(FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2674. GotReply(Reply);
  2675. // should never get here as GotReply should raise fatal exception
  2676. DebugFail();
  2677. }
  2678. //---------------------------------------------------------------------------
  2679. UnicodeString __fastcall TFTPFileSystem::GotReply(unsigned int Reply, unsigned int Flags,
  2680. UnicodeString Error, unsigned int * Code, TStrings ** Response)
  2681. {
  2682. UnicodeString Result;
  2683. try
  2684. {
  2685. if (FLAGSET(Reply, TFileZillaIntf::REPLY_OK))
  2686. {
  2687. DebugAssert(Reply == TFileZillaIntf::REPLY_OK);
  2688. // With REPLY_2XX_CODE treat "OK" non-2xx code like an error.
  2689. // REPLY_3XX_CODE has to be always used along with REPLY_2XX_CODE.
  2690. if ((FLAGSET(Flags, REPLY_2XX_CODE) && (FLastCodeClass != 2)) &&
  2691. ((FLAGCLEAR(Flags, REPLY_3XX_CODE) || (FLastCodeClass != 3))))
  2692. {
  2693. GotReply(TFileZillaIntf::REPLY_ERROR, Flags, Error);
  2694. }
  2695. }
  2696. else if (FLAGSET(Reply, TFileZillaIntf::REPLY_CANCEL) &&
  2697. FLAGSET(Flags, REPLY_ALLOW_CANCEL))
  2698. {
  2699. DebugAssert(
  2700. (Reply == (TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)) ||
  2701. (Reply == (TFileZillaIntf::REPLY_ABORTED | TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)));
  2702. // noop
  2703. }
  2704. // we do not expect these with our usage of FZ
  2705. else if (Reply &
  2706. (TFileZillaIntf::REPLY_WOULDBLOCK | TFileZillaIntf::REPLY_OWNERNOTSET |
  2707. TFileZillaIntf::REPLY_INVALIDPARAM | TFileZillaIntf::REPLY_ALREADYCONNECTED |
  2708. TFileZillaIntf::REPLY_IDLE | TFileZillaIntf::REPLY_NOTINITIALIZED |
  2709. TFileZillaIntf::REPLY_ALREADYINIZIALIZED))
  2710. {
  2711. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, (L"ftp#2", FORMAT(L"0x%x", (int(Reply))))));
  2712. }
  2713. else
  2714. {
  2715. // everything else must be an error or disconnect notification
  2716. DebugAssert(
  2717. FLAGSET(Reply, TFileZillaIntf::REPLY_ERROR) ||
  2718. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2719. // TODO: REPLY_CRITICALERROR ignored
  2720. // REPLY_NOTCONNECTED happens if connection is closed between moment
  2721. // when FZAPI interface method dispatches the command to FZAPI thread
  2722. // and moment when FZAPI thread receives the command
  2723. bool Disconnected =
  2724. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED) ||
  2725. FLAGSET(Reply, TFileZillaIntf::REPLY_NOTCONNECTED);
  2726. UnicodeString HelpKeyword;
  2727. TStrings * MoreMessages = new TStringList();
  2728. try
  2729. {
  2730. if (Disconnected)
  2731. {
  2732. if (FLAGCLEAR(Flags, REPLY_CONNECT))
  2733. {
  2734. MoreMessages->Add(LoadStr(LOST_CONNECTION));
  2735. Discard();
  2736. FTerminal->Closed();
  2737. }
  2738. else
  2739. {
  2740. // For connection failure, do not report that connection was lost,
  2741. // its obvious.
  2742. // Also do not report to terminal that we are closed as
  2743. // that turns terminal into closed mode, but we want to
  2744. // pretend (at least with failed authentication) to retry
  2745. // with the same connection (as with SSH), so we explicitly
  2746. // close terminal in Open() only after we give up
  2747. Discard();
  2748. }
  2749. }
  2750. if (FLAGSET(Reply, TFileZillaIntf::REPLY_ABORTED))
  2751. {
  2752. MoreMessages->Add(LoadStr(USER_TERMINATED));
  2753. }
  2754. if (FLAGSET(Reply, TFileZillaIntf::REPLY_NOTSUPPORTED))
  2755. {
  2756. MoreMessages->Add(LoadStr(NOTSUPPORTED));
  2757. }
  2758. if (FLastCode == 530)
  2759. {
  2760. // Serv-U also uses this code in response to "SITE PSWD"
  2761. MoreMessages->Add(LoadStr(AUTHENTICATION_FAILED));
  2762. }
  2763. if (FLastCode == 425)
  2764. {
  2765. if (!FTerminal->SessionData->FtpPasvMode)
  2766. {
  2767. MoreMessages->Add(LoadStr(FTP_CANNOT_OPEN_ACTIVE_CONNECTION2));
  2768. HelpKeyword = HELP_FTP_CANNOT_OPEN_ACTIVE_CONNECTION;
  2769. }
  2770. }
  2771. if (FLastCode == DummyTimeoutCode)
  2772. {
  2773. HelpKeyword = HELP_ERRORMSG_TIMEOUT;
  2774. }
  2775. if (FLastCode == DummyDisconnectCode)
  2776. {
  2777. HelpKeyword = HELP_STATUSMSG_DISCONNECTED;
  2778. }
  2779. MoreMessages->AddStrings(FLastError);
  2780. // already cleared from WaitForReply, but GotReply can be also called
  2781. // from Closed. then make sure that error from previous command not
  2782. // associated with session closure is not reused
  2783. FLastError->Clear();
  2784. MoreMessages->AddStrings(FLastErrorResponse);
  2785. // see comment for FLastError
  2786. FLastResponse->Clear();
  2787. FLastErrorResponse->Clear();
  2788. if (MoreMessages->Count == 0)
  2789. {
  2790. delete MoreMessages;
  2791. MoreMessages = NULL;
  2792. }
  2793. }
  2794. catch(...)
  2795. {
  2796. delete MoreMessages;
  2797. throw;
  2798. }
  2799. if (Error.IsEmpty() && (MoreMessages != NULL))
  2800. {
  2801. DebugAssert(MoreMessages->Count > 0);
  2802. // bit too generic assigning of main instructions, let's see how it works
  2803. Error = MainInstructions(MoreMessages->Strings[0]);
  2804. MoreMessages->Delete(0);
  2805. }
  2806. if (Disconnected)
  2807. {
  2808. // for fatal error, it is essential that there is some message
  2809. DebugAssert(!Error.IsEmpty());
  2810. ExtException * E = new ExtException(Error, MoreMessages, true, HelpKeyword);
  2811. try
  2812. {
  2813. FTerminal->FatalError(E, L"");
  2814. }
  2815. __finally
  2816. {
  2817. delete E;
  2818. }
  2819. }
  2820. else
  2821. {
  2822. throw ExtException(Error, MoreMessages, true, HelpKeyword);
  2823. }
  2824. }
  2825. if ((Code != NULL) && (FLastCodeClass != DummyCodeClass))
  2826. {
  2827. *Code = FLastCode;
  2828. }
  2829. if (FLAGSET(Flags, REPLY_SINGLE_LINE))
  2830. {
  2831. if (FLastResponse->Count != 1)
  2832. {
  2833. throw Exception(FMTLOAD(FTP_RESPONSE_ERROR, (FLastCommandSent, FLastResponse->Text)));
  2834. }
  2835. Result = FLastResponse->Strings[0];
  2836. }
  2837. if (Response != NULL)
  2838. {
  2839. *Response = FLastResponse;
  2840. FLastResponse = new TStringList();
  2841. // just to be consistent
  2842. delete FLastErrorResponse;
  2843. FLastErrorResponse = new TStringList();
  2844. }
  2845. }
  2846. __finally
  2847. {
  2848. ResetReply();
  2849. }
  2850. return Result;
  2851. }
  2852. //---------------------------------------------------------------------------
  2853. void __fastcall TFTPFileSystem::SendCommand(const UnicodeString & Command)
  2854. {
  2855. FFileZillaIntf->CustomCommand(Command.c_str());
  2856. FLastCommandSent = CopyToChar(Command, L' ', false);
  2857. }
  2858. //---------------------------------------------------------------------------
  2859. void __fastcall TFTPFileSystem::SetLastCode(int Code)
  2860. {
  2861. FLastCode = Code;
  2862. FLastCodeClass = (Code / 100);
  2863. }
  2864. //---------------------------------------------------------------------------
  2865. void __fastcall TFTPFileSystem::StoreLastResponse(const UnicodeString & Text)
  2866. {
  2867. FLastResponse->Add(Text);
  2868. if (FLastCodeClass >= 4)
  2869. {
  2870. FLastErrorResponse->Add(Text);
  2871. }
  2872. }
  2873. //---------------------------------------------------------------------------
  2874. void __fastcall TFTPFileSystem::HandleReplyStatus(UnicodeString Response)
  2875. {
  2876. int Code;
  2877. if (FOnCaptureOutput != NULL)
  2878. {
  2879. FOnCaptureOutput(Response, cotOutput);
  2880. }
  2881. if (FWelcomeMessage.IsEmpty() && StartsStr(L"SSH", Response))
  2882. {
  2883. FLastErrorResponse->Add(LoadStr(SFTP_AS_FTP_ERROR));
  2884. }
  2885. // Two forms of multiline responses were observed
  2886. // (the first is according to the RFC 959):
  2887. // 211-Features:
  2888. // MDTM
  2889. // REST STREAM
  2890. // SIZE
  2891. // 211 End
  2892. // This format is according to RFC 2228.
  2893. // Is used by ProFTPD when MultilineRFC2228 is enabled
  2894. // http://www.proftpd.org/docs/directives/linked/config_ref_MultilineRFC2228.html
  2895. // 211-Features:
  2896. // 211-MDTM
  2897. // 211-REST STREAM
  2898. // 211-SIZE
  2899. // 211-AUTH TLS
  2900. // 211-PBSZ
  2901. // 211-PROT
  2902. // 211 End
  2903. // IIS 2003:
  2904. // 211-FEAT
  2905. // SIZE
  2906. // MDTM
  2907. // 211 END
  2908. // Partially duplicated in CFtpControlSocket::OnReceive
  2909. bool HasCodePrefix =
  2910. (Response.Length() >= 3) &&
  2911. TryStrToInt(Response.SubString(1, 3), Code) &&
  2912. (Code >= 100) && (Code <= 599) &&
  2913. ((Response.Length() == 3) || (Response[4] == L' ') || (Response[4] == L'-'));
  2914. if (HasCodePrefix && !FMultineResponse)
  2915. {
  2916. FMultineResponse = (Response.Length() >= 4) && (Response[4] == L'-');
  2917. FLastResponse->Clear();
  2918. FLastErrorResponse->Clear();
  2919. SetLastCode(Code);
  2920. if (Response.Length() >= 5)
  2921. {
  2922. StoreLastResponse(Response.SubString(5, Response.Length() - 4));
  2923. }
  2924. }
  2925. else
  2926. {
  2927. int Start;
  2928. // response with code prefix
  2929. if (HasCodePrefix && (FLastCode == Code))
  2930. {
  2931. // End of multiline response?
  2932. if ((Response.Length() <= 3) || (Response[4] == L' '))
  2933. {
  2934. FMultineResponse = false;
  2935. }
  2936. Start = 5;
  2937. }
  2938. else
  2939. {
  2940. Start = (((Response.Length() >= 1) && (Response[1] == L' ')) ? 2 : 1);
  2941. }
  2942. // Intermediate empty lines are being added
  2943. if (FMultineResponse || (Response.Length() >= Start))
  2944. {
  2945. StoreLastResponse(Response.SubString(Start, Response.Length() - Start + 1));
  2946. }
  2947. }
  2948. if (StartsStr(DirectoryHasBytesPrefix, Response))
  2949. {
  2950. UnicodeString Buf = Response;
  2951. Buf.Delete(1, DirectoryHasBytesPrefix.Length());
  2952. Buf = Buf.TrimLeft();
  2953. UnicodeString BytesStr = CutToChar(Buf, L' ', true);
  2954. BytesStr = ReplaceStr(BytesStr, L",", L"");
  2955. FBytesAvailable = StrToInt64Def(BytesStr, -1);
  2956. if (FBytesAvailable >= 0)
  2957. {
  2958. FBytesAvailableSuppoted = true;
  2959. }
  2960. }
  2961. if (!FMultineResponse)
  2962. {
  2963. if (FLastCode == 220)
  2964. {
  2965. // HOST command also uses 220 response.
  2966. // Neither our use of welcome message is prepared for changing it
  2967. // during the session, so we keep the initial message only.
  2968. // Theoretically the welcome message can be host-specific,
  2969. // but IIS uses "220 Host accepted", and we are not interested in that anyway.
  2970. // Serv-U repeats the initial welcome message.
  2971. // WS_FTP uses "200 Command HOST succeed"
  2972. if (FWelcomeMessage.IsEmpty())
  2973. {
  2974. FWelcomeMessage = FLastResponse->Text;
  2975. if (FTerminal->Configuration->ShowFtpWelcomeMessage)
  2976. {
  2977. FTerminal->DisplayBanner(FWelcomeMessage);
  2978. }
  2979. // Idea FTP Server v0.80
  2980. if ((FTerminal->SessionData->FtpTransferActiveImmediately == asAuto) &&
  2981. FWelcomeMessage.Pos(L"Idea FTP Server") > 0)
  2982. {
  2983. FTerminal->LogEvent(L"The server requires TLS/SSL handshake on transfer connection before responding 1yz to STOR/APPE");
  2984. FTransferActiveImmediately = true;
  2985. }
  2986. }
  2987. }
  2988. else if (FLastCommand == PASS)
  2989. {
  2990. FStoredPasswordTried = true;
  2991. // 530 = "Not logged in."
  2992. if (FLastCode == 530)
  2993. {
  2994. FPasswordFailed = true;
  2995. }
  2996. }
  2997. else if (FLastCommand == SYST)
  2998. {
  2999. DebugAssert(FSystem.IsEmpty());
  3000. // Positive reply to "SYST" must be 215, see RFC 959
  3001. if (FLastCode == 215)
  3002. {
  3003. FSystem = FLastResponse->Text.TrimRight();
  3004. // full name is "MVS is the operating system of this server. FTP Server is running on ..."
  3005. // (the ... can be "z/OS")
  3006. // https://www.ibm.com/support/knowledgecenter/SSLTBW_2.1.0/com.ibm.zos.v2r1.cs3cod0/ftp215-02.htm
  3007. FMVS = (FSystem.SubString(1, 3) == L"MVS");
  3008. if ((FListAll == asAuto) &&
  3009. // full name is "Personal FTP Server PRO K6.0"
  3010. ((FSystem.Pos(L"Personal FTP Server") > 0) ||
  3011. FMVS))
  3012. {
  3013. FTerminal->LogEvent(L"Server is known not to support LIST -a");
  3014. FListAll = asOff;
  3015. }
  3016. // The FWelcomeMessage usually contains "Microsoft FTP Service" but can be empty
  3017. if (ContainsText(FSystem, L"Windows_NT"))
  3018. {
  3019. FTerminal->LogEvent(L"The server is probably running Windows, assuming that directory listing timestamps are affected by DST.");
  3020. FWindowsServer = true;
  3021. }
  3022. // VMS system type. VMS V5.5-2.
  3023. FVMS = (FSystem.SubString(1, 3) == L"VMS");
  3024. }
  3025. else
  3026. {
  3027. FSystem = L"";
  3028. }
  3029. }
  3030. else if (FLastCommand == FEAT)
  3031. {
  3032. HandleFeatReply();
  3033. }
  3034. }
  3035. }
  3036. //---------------------------------------------------------------------------
  3037. void __fastcall TFTPFileSystem::ResetFeatures()
  3038. {
  3039. FFeatures->Clear();
  3040. FSupportedCommands->Clear();
  3041. FSupportedSiteCommands->Clear();
  3042. FHashAlgs->Clear();
  3043. FSupportsAnyChecksumFeature = false;
  3044. }
  3045. //---------------------------------------------------------------------------
  3046. void __fastcall TFTPFileSystem::HandleFeatReply()
  3047. {
  3048. ResetFeatures();
  3049. // Response to FEAT must be multiline, where leading and trailing line
  3050. // is "meaningless". See RFC 2389.
  3051. if ((FLastCode == 211) && (FLastResponse->Count > 2))
  3052. {
  3053. FLastResponse->Delete(0);
  3054. FLastResponse->Delete(FLastResponse->Count - 1);
  3055. FFeatures->Assign(FLastResponse);
  3056. for (int Index = 0; Index < FFeatures->Count; Index++)
  3057. {
  3058. // IIS 2003 indents response by 4 spaces, instead of one,
  3059. // see example in HandleReplyStatus
  3060. UnicodeString Feature = TrimLeft(FFeatures->Strings[Index]);
  3061. UnicodeString Args = Feature;
  3062. UnicodeString Command = CutToChar(Args, L' ', true);
  3063. // Serv-U lists Xalg commands like:
  3064. // XSHA1 filename;start;end
  3065. FSupportedCommands->Add(Command);
  3066. if (SameText(Command, SiteCommand))
  3067. {
  3068. // Serv-U lists all SITE commands in one line like:
  3069. // SITE PSWD;SET;ZONE;CHMOD;MSG;EXEC;HELP
  3070. // But ProFTPD lists them separatelly:
  3071. // SITE UTIME
  3072. // SITE RMDIR
  3073. // SITE COPY
  3074. // SITE MKDIR
  3075. // SITE SYMLINK
  3076. while (!Args.IsEmpty())
  3077. {
  3078. UnicodeString Arg = CutToChar(Args, L';', true);
  3079. FSupportedSiteCommands->Add(Arg);
  3080. }
  3081. }
  3082. else if (SameText(Command, HashCommand))
  3083. {
  3084. while (!Args.IsEmpty())
  3085. {
  3086. UnicodeString Alg = CutToChar(Args, L';', true);
  3087. if ((Alg.Length() > 0) && (Alg[Alg.Length()] == L'*'))
  3088. {
  3089. Alg.Delete(Alg.Length(), 1);
  3090. }
  3091. // FTP HASH alg names follow IANA as we do,
  3092. // but using uppercase and we use lowercase
  3093. FHashAlgs->Add(LowerCase(Alg));
  3094. FSupportsAnyChecksumFeature = true;
  3095. }
  3096. }
  3097. if (FChecksumCommands->IndexOf(Command) >= 0)
  3098. {
  3099. FSupportsAnyChecksumFeature = true;
  3100. }
  3101. }
  3102. }
  3103. }
  3104. //---------------------------------------------------------------------------
  3105. bool __fastcall TFTPFileSystem::HandleStatus(const wchar_t * AStatus, int Type)
  3106. {
  3107. TLogLineType LogType = (TLogLineType)-1;
  3108. UnicodeString Status(AStatus);
  3109. switch (Type)
  3110. {
  3111. case TFileZillaIntf::LOG_STATUS:
  3112. FTerminal->Information(Status, true);
  3113. LogType = llMessage;
  3114. break;
  3115. case TFileZillaIntf::LOG_COMMAND:
  3116. if (Status == L"SYST")
  3117. {
  3118. // not to trigger the assert in HandleReplyStatus,
  3119. // when SYST command is used by the user
  3120. FSystem = "";
  3121. FLastCommand = SYST;
  3122. }
  3123. else if (Status == L"FEAT")
  3124. {
  3125. FLastCommand = FEAT;
  3126. }
  3127. else if (Status.SubString(1, 5) == L"PASS ")
  3128. {
  3129. FLastCommand = PASS;
  3130. }
  3131. else
  3132. {
  3133. FLastCommand = CMD_UNKNOWN;
  3134. }
  3135. if (!FLoggedIn || (FTerminal->Configuration->ActualLogProtocol >= 0))
  3136. {
  3137. LogType = llInput;
  3138. }
  3139. break;
  3140. case TFileZillaIntf::LOG_ERROR:
  3141. case TFileZillaIntf::LOG_APIERROR:
  3142. case TFileZillaIntf::LOG_WARNING:
  3143. // when timeout message occurs, break loop waiting for response code
  3144. // by setting dummy one
  3145. if (Type == TFileZillaIntf::LOG_ERROR)
  3146. {
  3147. if (StartsStr(FTimeoutStatus, Status))
  3148. {
  3149. if (NoFinalLastCode())
  3150. {
  3151. SetLastCode(DummyTimeoutCode);
  3152. }
  3153. }
  3154. else if (Status == FDisconnectStatus)
  3155. {
  3156. if (NoFinalLastCode())
  3157. {
  3158. SetLastCode(DummyDisconnectCode);
  3159. }
  3160. }
  3161. }
  3162. // there can be multiple error messages associated with single failure
  3163. // (such as "cannot open local file..." followed by "download failed")
  3164. FLastError->Add(Status);
  3165. LogType = llMessage;
  3166. break;
  3167. case TFileZillaIntf::LOG_PROGRESS:
  3168. LogType = llMessage;
  3169. break;
  3170. case TFileZillaIntf::LOG_REPLY:
  3171. HandleReplyStatus(AStatus);
  3172. if (!FLoggedIn || (FTerminal->Configuration->ActualLogProtocol >= 0))
  3173. {
  3174. LogType = llOutput;
  3175. }
  3176. break;
  3177. case TFileZillaIntf::LOG_INFO:
  3178. LogType = llMessage;
  3179. break;
  3180. case TFileZillaIntf::LOG_DEBUG:
  3181. LogType = llMessage;
  3182. break;
  3183. default:
  3184. DebugFail();
  3185. break;
  3186. }
  3187. if (FTerminal->Log->Logging && (LogType != (TLogLineType)-1))
  3188. {
  3189. FTerminal->Log->Add(LogType, Status);
  3190. }
  3191. return true;
  3192. }
  3193. //---------------------------------------------------------------------------
  3194. TDateTime __fastcall TFTPFileSystem::ConvertLocalTimestamp(time_t Time)
  3195. {
  3196. // This reverses how FZAPI converts FILETIME to time_t,
  3197. // before passing it to FZ_ASYNCREQUEST_OVERWRITE.
  3198. __int64 Timestamp;
  3199. tm * Tm = localtime(&Time);
  3200. if (Tm != NULL)
  3201. {
  3202. SYSTEMTIME SystemTime;
  3203. SystemTime.wYear = static_cast<WORD>(Tm->tm_year + 1900);
  3204. SystemTime.wMonth = static_cast<WORD>(Tm->tm_mon + 1);
  3205. SystemTime.wDayOfWeek = 0;
  3206. SystemTime.wDay = static_cast<WORD>(Tm->tm_mday);
  3207. SystemTime.wHour = static_cast<WORD>(Tm->tm_hour);
  3208. SystemTime.wMinute = static_cast<WORD>(Tm->tm_min);
  3209. SystemTime.wSecond = static_cast<WORD>(Tm->tm_sec);
  3210. SystemTime.wMilliseconds = 0;
  3211. FILETIME LocalTime;
  3212. SystemTimeToFileTime(&SystemTime, &LocalTime);
  3213. FILETIME FileTime;
  3214. LocalFileTimeToFileTime(&LocalTime, &FileTime);
  3215. Timestamp = ConvertTimestampToUnixSafe(FileTime, dstmUnix);
  3216. }
  3217. else
  3218. {
  3219. // incorrect, but at least something
  3220. Timestamp = Time;
  3221. }
  3222. return UnixToDateTime(Timestamp, dstmUnix);
  3223. }
  3224. //---------------------------------------------------------------------------
  3225. bool __fastcall TFTPFileSystem::HandleAsynchRequestOverwrite(
  3226. wchar_t * FileName1, size_t FileName1Len, const wchar_t * FileName2,
  3227. const wchar_t * Path1, const wchar_t * Path2,
  3228. __int64 Size1, __int64 Size2, time_t LocalTime,
  3229. bool /*HasLocalTime*/, const TRemoteFileTime & RemoteTime, void * AUserData, int & RequestResult)
  3230. {
  3231. if (!FActive)
  3232. {
  3233. return false;
  3234. }
  3235. else
  3236. {
  3237. TFileTransferData & UserData = *((TFileTransferData *)AUserData);
  3238. if (UserData.OverwriteResult >= 0)
  3239. {
  3240. // on retry, use the same answer as on the first attempt
  3241. RequestResult = UserData.OverwriteResult;
  3242. }
  3243. else
  3244. {
  3245. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  3246. UnicodeString TargetFileName = FileName1;
  3247. DebugAssert(UserData.FileName == TargetFileName);
  3248. UnicodeString SourceFullFileName = Path2;
  3249. UnicodeString TargetFullFileName = Path1;
  3250. if (OperationProgress->Side == osLocal)
  3251. {
  3252. SourceFullFileName = IncludeTrailingBackslash(SourceFullFileName);
  3253. TargetFullFileName = UnixIncludeTrailingBackslash(TargetFullFileName);
  3254. }
  3255. else
  3256. {
  3257. SourceFullFileName = UnixIncludeTrailingBackslash(SourceFullFileName);
  3258. TargetFullFileName = IncludeTrailingBackslash(TargetFullFileName);
  3259. }
  3260. SourceFullFileName += FileName2;
  3261. TargetFullFileName += FileName1;
  3262. TOverwriteMode OverwriteMode = omOverwrite;
  3263. TOverwriteFileParams FileParams;
  3264. bool NoFileParams =
  3265. (Size1 < 0) || (LocalTime == 0) ||
  3266. (Size2 < 0) || !RemoteTime.HasDate;
  3267. if (!NoFileParams)
  3268. {
  3269. FileParams.SourceSize = Size2;
  3270. FileParams.DestSize = Size1;
  3271. // Time is coming from LIST (not from MLSD or MDTM)
  3272. bool NeedApplyTimeDifference = !RemoteTime.Utc && DebugAlwaysTrue(!FFileZillaIntf->UsingMlsd());
  3273. if (OperationProgress->Side == osLocal)
  3274. {
  3275. FileParams.SourceTimestamp = ConvertLocalTimestamp(LocalTime);
  3276. RemoteFileTimeToDateTimeAndPrecision(RemoteTime, FileParams.DestTimestamp, FileParams.DestPrecision);
  3277. if (NeedApplyTimeDifference)
  3278. {
  3279. ApplyTimeDifference(TargetFullFileName, FileParams.DestTimestamp, FileParams.DestPrecision);
  3280. }
  3281. }
  3282. else
  3283. {
  3284. FileParams.DestTimestamp = ConvertLocalTimestamp(LocalTime);
  3285. RemoteFileTimeToDateTimeAndPrecision(RemoteTime, FileParams.SourceTimestamp, FileParams.SourcePrecision);
  3286. if (NeedApplyTimeDifference)
  3287. {
  3288. ApplyTimeDifference(SourceFullFileName, FileParams.SourceTimestamp, FileParams.SourcePrecision);
  3289. }
  3290. }
  3291. }
  3292. if (ConfirmOverwrite(SourceFullFileName, TargetFileName, OverwriteMode, OperationProgress,
  3293. (NoFileParams ? NULL : &FileParams), UserData.CopyParam, UserData.Params,
  3294. UserData.AutoResume && UserData.CopyParam->AllowResume(FileParams.SourceSize)))
  3295. {
  3296. switch (OverwriteMode)
  3297. {
  3298. case omOverwrite:
  3299. if (TargetFileName != FileName1)
  3300. {
  3301. wcsncpy(FileName1, TargetFileName.c_str(), FileName1Len);
  3302. FileName1[FileName1Len - 1] = L'\0';
  3303. UserData.FileName = FileName1;
  3304. RequestResult = TFileZillaIntf::FILEEXISTS_RENAME;
  3305. }
  3306. else
  3307. {
  3308. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  3309. }
  3310. break;
  3311. case omResume:
  3312. RequestResult = TFileZillaIntf::FILEEXISTS_RESUME;
  3313. break;
  3314. case omComplete:
  3315. FTerminal->LogEvent(L"File transfer was completed before disconnect");
  3316. RequestResult = TFileZillaIntf::FILEEXISTS_COMPLETE;
  3317. break;
  3318. default:
  3319. DebugFail();
  3320. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  3321. break;
  3322. }
  3323. }
  3324. else
  3325. {
  3326. RequestResult = TFileZillaIntf::FILEEXISTS_SKIP;
  3327. }
  3328. }
  3329. // remember the answer for the retries
  3330. UserData.OverwriteResult = RequestResult;
  3331. if (RequestResult == TFileZillaIntf::FILEEXISTS_SKIP)
  3332. {
  3333. // when user chooses not to overwrite, break loop waiting for response code
  3334. // by setting dummy one, as FZAPI won't do anything then
  3335. SetLastCode(DummyTimeoutCode);
  3336. }
  3337. return true;
  3338. }
  3339. }
  3340. //---------------------------------------------------------------------------
  3341. UnicodeString __fastcall FormatContactList(UnicodeString Entry1, UnicodeString Entry2)
  3342. {
  3343. if (!Entry1.IsEmpty() && !Entry2.IsEmpty())
  3344. {
  3345. return FORMAT(L"%s, %s", (Entry1, Entry2));
  3346. }
  3347. else
  3348. {
  3349. return Entry1 + Entry2;
  3350. }
  3351. }
  3352. //---------------------------------------------------------------------------
  3353. UnicodeString __fastcall FormatContact(const TFtpsCertificateData::TContact & Contact)
  3354. {
  3355. UnicodeString Result =
  3356. FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 1),
  3357. (FormatContactList(FormatContactList(FormatContactList(
  3358. Contact.Organization, Contact.Unit), Contact.CommonName), Contact.Mail)));
  3359. if ((wcslen(Contact.Country) > 0) ||
  3360. (wcslen(Contact.StateProvince) > 0) ||
  3361. (wcslen(Contact.Town) > 0))
  3362. {
  3363. Result +=
  3364. FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 2),
  3365. (FormatContactList(FormatContactList(
  3366. Contact.Country, Contact.StateProvince), Contact.Town)));
  3367. }
  3368. if (wcslen(Contact.Other) > 0)
  3369. {
  3370. Result += FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 3), (Contact.Other));
  3371. }
  3372. return Result;
  3373. }
  3374. //---------------------------------------------------------------------------
  3375. UnicodeString __fastcall FormatValidityTime(const TFtpsCertificateData::TValidityTime & ValidityTime)
  3376. {
  3377. return FormatDateTime(L"ddddd tt",
  3378. EncodeDateVerbose(
  3379. (unsigned short)ValidityTime.Year, (unsigned short)ValidityTime.Month,
  3380. (unsigned short)ValidityTime.Day) +
  3381. EncodeTimeVerbose(
  3382. (unsigned short)ValidityTime.Hour, (unsigned short)ValidityTime.Min,
  3383. (unsigned short)ValidityTime.Sec, 0));
  3384. }
  3385. //---------------------------------------------------------------------------
  3386. bool __fastcall VerifyNameMask(UnicodeString Name, UnicodeString Mask)
  3387. {
  3388. bool Result = true;
  3389. int Pos;
  3390. while (Result && (Pos = Mask.Pos(L"*")) > 0)
  3391. {
  3392. // Pos will typically be 1 here, so not actual comparison is done
  3393. Result = SameText(Mask.SubString(1, Pos - 1), Name.SubString(1, Pos - 1));
  3394. if (Result)
  3395. {
  3396. Mask.Delete(1, Pos); // including *
  3397. Name.Delete(1, Pos - 1);
  3398. // remove everything until the next dot
  3399. Pos = Name.Pos(L".");
  3400. if (Pos == 0)
  3401. {
  3402. Pos = Name.Length() + 1;
  3403. }
  3404. Name.Delete(1, Pos - 1);
  3405. }
  3406. }
  3407. if (Result)
  3408. {
  3409. Result = SameText(Mask, Name);
  3410. }
  3411. return Result;
  3412. }
  3413. //---------------------------------------------------------------------------
  3414. bool __fastcall TFTPFileSystem::VerifyCertificateHostName(const TFtpsCertificateData & Data)
  3415. {
  3416. UnicodeString HostName = FTerminal->SessionData->HostNameExpanded;
  3417. UnicodeString CommonName = Data.Subject.CommonName;
  3418. bool NoMask = CommonName.IsEmpty();
  3419. bool Result = !NoMask && VerifyNameMask(HostName, CommonName);
  3420. if (Result)
  3421. {
  3422. FTerminal->LogEvent(FORMAT(L"Certificate common name \"%s\" matches hostname", (CommonName)));
  3423. }
  3424. else
  3425. {
  3426. if (!NoMask && (FTerminal->Configuration->ActualLogProtocol >= 1))
  3427. {
  3428. FTerminal->LogEvent(FORMAT(L"Certificate common name \"%s\" does not match hostname", (CommonName)));
  3429. }
  3430. UnicodeString SubjectAltName = Data.SubjectAltName;
  3431. while (!Result && !SubjectAltName.IsEmpty())
  3432. {
  3433. UnicodeString Entry = CutToChar(SubjectAltName, L',', true);
  3434. UnicodeString EntryName = CutToChar(Entry, L':', true);
  3435. if (SameText(EntryName, L"DNS"))
  3436. {
  3437. NoMask = false;
  3438. Result = VerifyNameMask(HostName, Entry);
  3439. if (Result)
  3440. {
  3441. FTerminal->LogEvent(FORMAT(L"Certificate subject alternative name \"%s\" matches hostname", (Entry)));
  3442. }
  3443. else
  3444. {
  3445. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  3446. {
  3447. FTerminal->LogEvent(FORMAT(L"Certificate subject alternative name \"%s\" does not match hostname", (Entry)));
  3448. }
  3449. }
  3450. }
  3451. }
  3452. }
  3453. if (!Result && NoMask)
  3454. {
  3455. FTerminal->LogEvent(L"Certificate has no common name nor subject alternative name, not verifying hostname");
  3456. Result = true;
  3457. }
  3458. return Result;
  3459. }
  3460. //---------------------------------------------------------------------------
  3461. static bool __fastcall IsIPAddress(const UnicodeString & HostName)
  3462. {
  3463. bool IPv4 = true;
  3464. bool IPv6 = true;
  3465. bool AnyColon = false;
  3466. for (int Index = 1; Index <= HostName.Length(); Index++)
  3467. {
  3468. wchar_t C = HostName[Index];
  3469. if (!IsDigit(C) && (C != L'.'))
  3470. {
  3471. IPv4 = false;
  3472. }
  3473. if (!IsHex(C) && (C != L':'))
  3474. {
  3475. IPv6 = false;
  3476. }
  3477. if (C == L':')
  3478. {
  3479. AnyColon = true;
  3480. }
  3481. }
  3482. return IPv4 || (IPv6 && AnyColon);
  3483. }
  3484. //---------------------------------------------------------------------------
  3485. bool __fastcall TFTPFileSystem::HandleAsynchRequestVerifyCertificate(
  3486. const TFtpsCertificateData & Data, int & RequestResult)
  3487. {
  3488. if (!FActive)
  3489. {
  3490. return false;
  3491. }
  3492. else
  3493. {
  3494. FSessionInfo.CertificateFingerprint =
  3495. BytesToHex(RawByteString((const char*)Data.Hash, Data.HashLen), false, L':');
  3496. if (FTerminal->SessionData->FingerprintScan)
  3497. {
  3498. RequestResult = 0;
  3499. }
  3500. else
  3501. {
  3502. UnicodeString CertificateSubject = Data.Subject.Organization;
  3503. FTerminal->LogEvent(FORMAT(L"Verifying certificate for \"%s\" with fingerprint %s and %d failures", (CertificateSubject, FSessionInfo.CertificateFingerprint, Data.VerificationResult)));
  3504. bool Trusted = false;
  3505. bool TryWindowsSystemCertificateStore = false;
  3506. UnicodeString VerificationResultStr;
  3507. switch (Data.VerificationResult)
  3508. {
  3509. case X509_V_OK:
  3510. Trusted = true;
  3511. break;
  3512. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
  3513. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_GET_ISSUER_CERT);
  3514. TryWindowsSystemCertificateStore = true;
  3515. break;
  3516. case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
  3517. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE);
  3518. break;
  3519. case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
  3520. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY);
  3521. break;
  3522. case X509_V_ERR_CERT_SIGNATURE_FAILURE:
  3523. VerificationResultStr = LoadStr(CERT_ERR_CERT_SIGNATURE_FAILURE);
  3524. break;
  3525. case X509_V_ERR_CERT_NOT_YET_VALID:
  3526. VerificationResultStr = LoadStr(CERT_ERR_CERT_NOT_YET_VALID);
  3527. break;
  3528. case X509_V_ERR_CERT_HAS_EXPIRED:
  3529. VerificationResultStr = LoadStr(CERT_ERR_CERT_HAS_EXPIRED);
  3530. break;
  3531. case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
  3532. VerificationResultStr = LoadStr(CERT_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD);
  3533. break;
  3534. case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
  3535. VerificationResultStr = LoadStr(CERT_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD);
  3536. break;
  3537. case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
  3538. VerificationResultStr = LoadStr(CERT_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
  3539. TryWindowsSystemCertificateStore = true;
  3540. break;
  3541. case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
  3542. VerificationResultStr = LoadStr(CERT_ERR_SELF_SIGNED_CERT_IN_CHAIN);
  3543. TryWindowsSystemCertificateStore = true;
  3544. break;
  3545. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
  3546. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY);
  3547. TryWindowsSystemCertificateStore = true;
  3548. break;
  3549. case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
  3550. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
  3551. TryWindowsSystemCertificateStore = true;
  3552. break;
  3553. case X509_V_ERR_INVALID_CA:
  3554. VerificationResultStr = LoadStr(CERT_ERR_INVALID_CA);
  3555. break;
  3556. case X509_V_ERR_PATH_LENGTH_EXCEEDED:
  3557. VerificationResultStr = LoadStr(CERT_ERR_PATH_LENGTH_EXCEEDED);
  3558. break;
  3559. case X509_V_ERR_INVALID_PURPOSE:
  3560. VerificationResultStr = LoadStr(CERT_ERR_INVALID_PURPOSE);
  3561. break;
  3562. case X509_V_ERR_CERT_UNTRUSTED:
  3563. VerificationResultStr = LoadStr(CERT_ERR_CERT_UNTRUSTED);
  3564. TryWindowsSystemCertificateStore = true;
  3565. break;
  3566. case X509_V_ERR_CERT_REJECTED:
  3567. VerificationResultStr = LoadStr(CERT_ERR_CERT_REJECTED);
  3568. break;
  3569. case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
  3570. VerificationResultStr = LoadStr(CERT_ERR_KEYUSAGE_NO_CERTSIGN);
  3571. break;
  3572. case X509_V_ERR_CERT_CHAIN_TOO_LONG:
  3573. VerificationResultStr = LoadStr(CERT_ERR_CERT_CHAIN_TOO_LONG);
  3574. break;
  3575. default:
  3576. VerificationResultStr =
  3577. FORMAT(L"%s (%s)",
  3578. (LoadStr(CERT_ERR_UNKNOWN), X509_verify_cert_error_string(Data.VerificationResult)));
  3579. break;
  3580. }
  3581. bool IsHostNameIPAddress = IsIPAddress(FTerminal->SessionData->HostNameExpanded);
  3582. bool CertificateHostNameVerified = !IsHostNameIPAddress && VerifyCertificateHostName(Data);
  3583. bool VerificationResult = Trusted;
  3584. if (IsHostNameIPAddress || !CertificateHostNameVerified)
  3585. {
  3586. VerificationResult = false;
  3587. TryWindowsSystemCertificateStore = false;
  3588. }
  3589. if (!VerificationResult)
  3590. {
  3591. if (FTerminal->VerifyCertificate(CertificateStorageKey, FTerminal->SessionData->SiteKey,
  3592. FSessionInfo.CertificateFingerprint, CertificateSubject, Data.VerificationResult))
  3593. {
  3594. // certificate is trusted, but for not purposes of info dialog
  3595. VerificationResult = true;
  3596. }
  3597. }
  3598. // TryWindowsSystemCertificateStore is set for the same set of failures
  3599. // as trigger NE_SSL_UNTRUSTED flag in ne_openssl.c's verify_callback().
  3600. // Use WindowsValidateCertificate only as a last resort (after checking the cached fiungerprint)
  3601. // as it can take a very long time (up to 1 minute).
  3602. if (!VerificationResult && TryWindowsSystemCertificateStore)
  3603. {
  3604. UnicodeString WindowsCertificateError;
  3605. if (WindowsValidateCertificate(Data.Certificate, Data.CertificateLen, WindowsCertificateError))
  3606. {
  3607. FTerminal->LogEvent(L"Certificate verified against Windows certificate store");
  3608. VerificationResult = true;
  3609. // certificate is trusted for all purposes
  3610. Trusted = true;
  3611. }
  3612. else
  3613. {
  3614. FTerminal->LogEvent(
  3615. FORMAT(L"Certificate failed to verify against Windows certificate store: %s", (DefaultStr(WindowsCertificateError, L"no details"))));
  3616. }
  3617. }
  3618. const UnicodeString SummarySeparator = L"\n\n";
  3619. UnicodeString Summary;
  3620. // even if the fingerprint is cached, the certificate is still not trusted for a purposes of the info dialog.
  3621. if (!Trusted)
  3622. {
  3623. AddToList(Summary, VerificationResultStr + L" " + FMTLOAD(CERT_ERRDEPTH, (Data.VerificationDepth + 1)), SummarySeparator);
  3624. }
  3625. if (IsHostNameIPAddress)
  3626. {
  3627. AddToList(Summary, FMTLOAD(CERT_IP_CANNOT_VERIFY, (FTerminal->SessionData->HostNameExpanded)), SummarySeparator);
  3628. }
  3629. else if (!CertificateHostNameVerified)
  3630. {
  3631. AddToList(Summary, FMTLOAD(CERT_NAME_MISMATCH, (FTerminal->SessionData->HostNameExpanded)), SummarySeparator);
  3632. }
  3633. if (Summary.IsEmpty())
  3634. {
  3635. Summary = LoadStr(CERT_OK);
  3636. }
  3637. FSessionInfo.Certificate =
  3638. FMTLOAD(CERT_TEXT, (
  3639. FormatContact(Data.Issuer),
  3640. FormatContact(Data.Subject),
  3641. FormatValidityTime(Data.ValidFrom),
  3642. FormatValidityTime(Data.ValidUntil),
  3643. FSessionInfo.CertificateFingerprint,
  3644. Summary));
  3645. RequestResult = VerificationResult ? 1 : 0;
  3646. if (RequestResult == 0)
  3647. {
  3648. bool Confirmed = FTerminal->ConfirmCertificate(FSessionInfo, Data.VerificationResult, CertificateStorageKey, true);
  3649. // FZ's VerifyCertDlg.cpp returns 2 for "cached", what we do nto distinguish here,
  3650. // however FZAPI takes all non-zero values equally.
  3651. RequestResult = Confirmed ? 1 : 0;
  3652. }
  3653. }
  3654. return true;
  3655. }
  3656. }
  3657. //---------------------------------------------------------------------------
  3658. bool __fastcall TFTPFileSystem::HandleAsynchRequestNeedPass(
  3659. struct TNeedPassRequestData & Data, int & RequestResult)
  3660. {
  3661. if (!FActive)
  3662. {
  3663. return false;
  3664. }
  3665. else
  3666. {
  3667. UnicodeString Password;
  3668. if (FCertificate != NULL)
  3669. {
  3670. FTerminal->LogEvent(L"Server asked for password, but we are using certificate, and no password was specified upfront, using fake password");
  3671. Password = L"USINGCERT";
  3672. RequestResult = TFileZillaIntf::REPLY_OK;
  3673. }
  3674. else
  3675. {
  3676. if (FTerminal->PromptUser(FTerminal->SessionData, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  3677. LoadStr(PASSWORD_PROMPT), false, 0, Password))
  3678. {
  3679. RequestResult = TFileZillaIntf::REPLY_OK;
  3680. }
  3681. else
  3682. {
  3683. RequestResult = TFileZillaIntf::REPLY_ABORTED;
  3684. }
  3685. }
  3686. // When returning REPLY_OK, we need to return an allocated password,
  3687. // even if we were returning and empty string we got on input.
  3688. if (RequestResult == TFileZillaIntf::REPLY_OK)
  3689. {
  3690. Data.Password = _wcsdup(Password.c_str());
  3691. }
  3692. return true;
  3693. }
  3694. }
  3695. //---------------------------------------------------------------------------
  3696. void __fastcall TFTPFileSystem::RemoteFileTimeToDateTimeAndPrecision(const TRemoteFileTime & Source, TDateTime & DateTime, TModificationFmt & ModificationFmt)
  3697. {
  3698. // ModificationFmt must be set after Modification
  3699. if (Source.HasDate)
  3700. {
  3701. DateTime =
  3702. EncodeDateVerbose((unsigned short)Source.Year, (unsigned short)Source.Month,
  3703. (unsigned short)Source.Day);
  3704. if (Source.HasTime)
  3705. {
  3706. DateTime = DateTime +
  3707. EncodeTimeVerbose((unsigned short)Source.Hour, (unsigned short)Source.Minute,
  3708. (unsigned short)Source.Second, 0);
  3709. // not exact as we got year as well, but it is most probably
  3710. // guessed by FZAPI anyway
  3711. ModificationFmt = Source.HasSeconds ? mfFull : mfMDHM;
  3712. // With IIS, the Utc should be false only for MDTM
  3713. if (FWindowsServer && !Source.Utc)
  3714. {
  3715. DateTime -= DSTDifferenceForTime(DateTime);
  3716. }
  3717. }
  3718. else
  3719. {
  3720. ModificationFmt = mfMDY;
  3721. }
  3722. if (Source.Utc)
  3723. {
  3724. DateTime = ConvertTimestampFromUTC(DateTime);
  3725. }
  3726. }
  3727. else
  3728. {
  3729. // With SCP we estimate date to be today, if we have at least time
  3730. DateTime = double(0);
  3731. ModificationFmt = mfNone;
  3732. }
  3733. }
  3734. //---------------------------------------------------------------------------
  3735. bool __fastcall TFTPFileSystem::HandleListData(const wchar_t * Path,
  3736. const TListDataEntry * Entries, unsigned int Count)
  3737. {
  3738. if (!FActive)
  3739. {
  3740. return false;
  3741. }
  3742. else if (FIgnoreFileList)
  3743. {
  3744. // directory listing provided implicitly by FZAPI during certain operations is ignored
  3745. DebugAssert(FFileList == NULL);
  3746. return false;
  3747. }
  3748. else
  3749. {
  3750. DebugAssert(FFileList != NULL);
  3751. // This can actually fail in real life,
  3752. // when connected to server with case insensitive paths.
  3753. // Is empty when called from DoReadFile
  3754. DebugAssert(FFileList->Directory.IsEmpty() || UnixSamePath(AbsolutePath(FFileList->Directory, false), Path));
  3755. DebugUsedParam(Path);
  3756. for (unsigned int Index = 0; Index < Count; Index++)
  3757. {
  3758. const TListDataEntry * Entry = &Entries[Index];
  3759. TRemoteFile * File = new TRemoteFile();
  3760. try
  3761. {
  3762. File->Terminal = FTerminal;
  3763. File->FileName = Entry->Name;
  3764. try
  3765. {
  3766. int PermissionsLen = wcslen(Entry->Permissions);
  3767. if (PermissionsLen >= 10)
  3768. {
  3769. File->Rights->Text = Entry->Permissions + 1;
  3770. }
  3771. else if ((PermissionsLen == 3) || (PermissionsLen == 4))
  3772. {
  3773. File->Rights->Octal = Entry->Permissions;
  3774. }
  3775. }
  3776. catch(...)
  3777. {
  3778. // ignore permissions errors with FTP
  3779. }
  3780. File->HumanRights = Entry->HumanPerm;
  3781. // deprecated, to be replaced with Owner/Group
  3782. if (wcslen(Entry->OwnerGroup) > 0)
  3783. {
  3784. const wchar_t * Space = wcschr(Entry->OwnerGroup, L' ');
  3785. if (Space != NULL)
  3786. {
  3787. File->Owner.Name = UnicodeString(Entry->OwnerGroup, Space - Entry->OwnerGroup);
  3788. File->Group.Name = Space + 1;
  3789. }
  3790. else
  3791. {
  3792. File->Owner.Name = Entry->OwnerGroup;
  3793. }
  3794. }
  3795. else
  3796. {
  3797. File->Owner.Name = Entry->Owner;
  3798. File->Group.Name = Entry->Group;
  3799. }
  3800. File->Size = Entry->Size;
  3801. if (Entry->Link)
  3802. {
  3803. File->Type = FILETYPE_SYMLINK;
  3804. }
  3805. else if (Entry->Dir)
  3806. {
  3807. File->Type = FILETYPE_DIRECTORY;
  3808. }
  3809. else
  3810. {
  3811. File->Type = FILETYPE_DEFAULT;
  3812. }
  3813. TDateTime Modification;
  3814. TModificationFmt ModificationFmt;
  3815. RemoteFileTimeToDateTimeAndPrecision(Entry->Time, Modification, ModificationFmt);
  3816. File->Modification = Modification;
  3817. File->ModificationFmt = ModificationFmt;
  3818. File->LastAccess = File->Modification;
  3819. File->LinkTo = Entry->LinkTarget;
  3820. File->Complete();
  3821. }
  3822. catch (Exception & E)
  3823. {
  3824. delete File;
  3825. UnicodeString EntryData =
  3826. FORMAT(L"%s/%s/%s/%s/%s/%s/%s/%d/%d/%d/%d/%d/%d/%d/%d/%d/%d",
  3827. (Entry->Name, Entry->Permissions, Entry->HumanPerm, Entry->Owner, Entry->Group, Entry->OwnerGroup, IntToStr(Entry->Size),
  3828. int(Entry->Dir), int(Entry->Link), Entry->Time.Year, Entry->Time.Month, Entry->Time.Day,
  3829. Entry->Time.Hour, Entry->Time.Minute, int(Entry->Time.HasTime),
  3830. int(Entry->Time.HasSeconds), int(Entry->Time.HasDate)));
  3831. throw ETerminal(&E, FMTLOAD(LIST_LINE_ERROR, (EntryData)), HELP_LIST_LINE_ERROR);
  3832. }
  3833. FFileList->AddFile(File);
  3834. }
  3835. return true;
  3836. }
  3837. }
  3838. //---------------------------------------------------------------------------
  3839. bool __fastcall TFTPFileSystem::HandleTransferStatus(bool Valid, __int64 TransferSize,
  3840. __int64 Bytes, bool FileTransfer)
  3841. {
  3842. if (!FActive)
  3843. {
  3844. return false;
  3845. }
  3846. else if (!Valid)
  3847. {
  3848. }
  3849. else if (FileTransfer)
  3850. {
  3851. FileTransferProgress(TransferSize, Bytes);
  3852. }
  3853. else
  3854. {
  3855. ReadDirectoryProgress(Bytes);
  3856. }
  3857. return true;
  3858. }
  3859. //---------------------------------------------------------------------------
  3860. bool __fastcall TFTPFileSystem::HandleReply(int Command, unsigned int Reply)
  3861. {
  3862. if (!FActive)
  3863. {
  3864. return false;
  3865. }
  3866. else
  3867. {
  3868. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  3869. {
  3870. FTerminal->LogEvent(FORMAT(L"Got reply %x to the command %d", (int(Reply), Command)));
  3871. }
  3872. // reply with Command 0 is not associated with current operation
  3873. // so do not treat is as a reply
  3874. // (it is typically used asynchronously to notify about disconnects)
  3875. if (Command != 0)
  3876. {
  3877. DebugAssert(FCommandReply == 0);
  3878. FCommandReply = Reply;
  3879. }
  3880. else
  3881. {
  3882. DebugAssert(FReply == 0);
  3883. FReply = Reply;
  3884. }
  3885. return true;
  3886. }
  3887. }
  3888. //---------------------------------------------------------------------------
  3889. bool __fastcall TFTPFileSystem::HandleCapabilities(
  3890. TFTPServerCapabilities * ServerCapabilities)
  3891. {
  3892. FServerCapabilities->Assign(ServerCapabilities);
  3893. FFileSystemInfoValid = false;
  3894. return true;
  3895. }
  3896. //---------------------------------------------------------------------------
  3897. bool __fastcall TFTPFileSystem::CheckError(int ReturnCode, const wchar_t * Context)
  3898. {
  3899. // we do not expect any FZAPI call to fail as it generally can fail only due to:
  3900. // - invalid parameters
  3901. // - busy FZAPI core
  3902. // the only exception is REPLY_NOTCONNECTED that can happen if
  3903. // connection is closed just between the last call to Idle()
  3904. // and call to any FZAPI command
  3905. // in such case reply without associated command is posted,
  3906. // which we are going to wait for unless we are already waiting
  3907. // on higher level (this typically happens if connection is lost while
  3908. // waiting for user interaction and is detected within call to
  3909. // SetAsyncRequestResult)
  3910. if (FLAGSET(ReturnCode, TFileZillaIntf::REPLY_NOTCONNECTED))
  3911. {
  3912. if (!FWaitingForReply)
  3913. {
  3914. // throws
  3915. WaitForFatalNonCommandReply();
  3916. }
  3917. }
  3918. else
  3919. {
  3920. FTerminal->FatalError(NULL,
  3921. FMTLOAD(INTERNAL_ERROR, (FORMAT(L"fz#%s", (Context)), IntToHex(ReturnCode, 4))));
  3922. DebugFail();
  3923. }
  3924. return false;
  3925. }
  3926. //---------------------------------------------------------------------------
  3927. bool __fastcall TFTPFileSystem::Unquote(UnicodeString & Str)
  3928. {
  3929. enum
  3930. {
  3931. INIT,
  3932. QUOTE,
  3933. QUOTED,
  3934. DONE
  3935. } State;
  3936. State = INIT;
  3937. DebugAssert((Str.Length() > 0) && ((Str[1] == L'"') || (Str[1] == L'\'')));
  3938. int Index = 1;
  3939. wchar_t Quote;
  3940. while (Index <= Str.Length())
  3941. {
  3942. switch (State)
  3943. {
  3944. case INIT:
  3945. if ((Str[Index] == L'"') || (Str[Index] == L'\''))
  3946. {
  3947. Quote = Str[Index];
  3948. State = QUOTED;
  3949. Str.Delete(Index, 1);
  3950. }
  3951. else
  3952. {
  3953. DebugFail();
  3954. // no quoted string
  3955. Str.SetLength(0);
  3956. }
  3957. break;
  3958. case QUOTED:
  3959. if (Str[Index] == Quote)
  3960. {
  3961. State = QUOTE;
  3962. Str.Delete(Index, 1);
  3963. }
  3964. else
  3965. {
  3966. Index++;
  3967. }
  3968. break;
  3969. case QUOTE:
  3970. if (Str[Index] == Quote)
  3971. {
  3972. Index++;
  3973. }
  3974. else
  3975. {
  3976. // end of quoted string, trim the rest
  3977. Str.SetLength(Index - 1);
  3978. State = DONE;
  3979. }
  3980. break;
  3981. }
  3982. }
  3983. return (State == DONE);
  3984. }
  3985. //---------------------------------------------------------------------------
  3986. void __fastcall TFTPFileSystem::PreserveDownloadFileTime(HANDLE Handle, void * UserData)
  3987. {
  3988. TFileTransferData * Data = static_cast<TFileTransferData *>(UserData);
  3989. FTerminal->UpdateTargetTime(Handle, Data->Modification, dstmUnix);
  3990. }
  3991. //---------------------------------------------------------------------------
  3992. bool __fastcall TFTPFileSystem::GetFileModificationTimeInUtc(const wchar_t * FileName, struct tm & Time)
  3993. {
  3994. bool Result;
  3995. try
  3996. {
  3997. // error-handling-free and DST-mode-inaware copy of TTerminal::OpenLocalFile
  3998. HANDLE Handle = CreateFile(ApiPath(FileName).c_str(), GENERIC_READ,
  3999. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
  4000. if (Handle == INVALID_HANDLE_VALUE)
  4001. {
  4002. Result = false;
  4003. }
  4004. else
  4005. {
  4006. FILETIME MTime;
  4007. if (!GetFileTime(Handle, NULL, NULL, &MTime))
  4008. {
  4009. Result = false;
  4010. }
  4011. else
  4012. {
  4013. TDateTime Modification = ConvertTimestampToUTC(FileTimeToDateTime(MTime));
  4014. unsigned short Year;
  4015. unsigned short Month;
  4016. unsigned short Day;
  4017. Modification.DecodeDate(&Year, &Month, &Day);
  4018. Time.tm_year = Year - 1900;
  4019. Time.tm_mon = Month - 1;
  4020. Time.tm_mday = Day;
  4021. unsigned short Hour;
  4022. unsigned short Min;
  4023. unsigned short Sec;
  4024. unsigned short MSec;
  4025. Modification.DecodeTime(&Hour, &Min, &Sec, &MSec);
  4026. Time.tm_hour = Hour;
  4027. Time.tm_min = Min;
  4028. Time.tm_sec = Sec;
  4029. Result = true;
  4030. }
  4031. CloseHandle(Handle);
  4032. }
  4033. }
  4034. catch (...)
  4035. {
  4036. Result = false;
  4037. }
  4038. return Result;
  4039. }
  4040. //---------------------------------------------------------------------------
  4041. void __fastcall TFTPFileSystem::RegisterChecksumAlgCommand(const UnicodeString & Alg, const UnicodeString & Command)
  4042. {
  4043. FChecksumAlgs->Add(Alg);
  4044. FChecksumCommands->Add(Command);
  4045. }
  4046. //---------------------------------------------------------------------------
  4047. void __fastcall TFTPFileSystem::GetSupportedChecksumAlgs(TStrings * Algs)
  4048. {
  4049. for (int Index = 0; Index < FHashAlgs->Count; Index++)
  4050. {
  4051. Algs->Add(FHashAlgs->Strings[Index]);
  4052. }
  4053. for (int Index = 0; Index < FChecksumAlgs->Count; Index++)
  4054. {
  4055. UnicodeString Alg = FChecksumAlgs->Strings[Index];
  4056. UnicodeString Command = FChecksumCommands->Strings[Index];
  4057. if (SupportsCommand(Command) && (Algs->IndexOf(Alg) < 0))
  4058. {
  4059. Algs->Add(Alg);
  4060. }
  4061. }
  4062. }
  4063. //---------------------------------------------------------------------------
  4064. bool __fastcall TFTPFileSystem::SupportsSiteCommand(const UnicodeString & Command) const
  4065. {
  4066. return (FSupportedSiteCommands->IndexOf(Command) >= 0);
  4067. }
  4068. //---------------------------------------------------------------------------
  4069. bool __fastcall TFTPFileSystem::SupportsCommand(const UnicodeString & Command) const
  4070. {
  4071. return (FSupportedCommands->IndexOf(Command) >= 0);
  4072. }
  4073. //---------------------------------------------------------------------------
  4074. void __fastcall TFTPFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  4075. {
  4076. DebugFail();
  4077. }
  4078. //---------------------------------------------------------------------------
  4079. void __fastcall TFTPFileSystem::UnlockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  4080. {
  4081. DebugFail();
  4082. }
  4083. //---------------------------------------------------------------------------
  4084. void __fastcall TFTPFileSystem::UpdateFromMain(TCustomFileSystem * /*MainFileSystem*/)
  4085. {
  4086. // noop
  4087. }
  4088. //---------------------------------------------------------------------------
  4089. void __fastcall TFTPFileSystem::ClearCaches()
  4090. {
  4091. // noop
  4092. }
  4093. //---------------------------------------------------------------------------
  4094. UnicodeString __fastcall GetOpenSSLVersionText()
  4095. {
  4096. return OPENSSL_VERSION_TEXT;
  4097. }
  4098. //---------------------------------------------------------------------------