FtpFileSystem.cpp 153 KB

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