FtpFileSystem.cpp 152 KB

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