FtpFileSystem.cpp 154 KB

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