1
0

FtpFileSystem.cpp 153 KB

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