FtpFileSystem.cpp 150 KB

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