FtpFileSystem.cpp 147 KB

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