FtpFileSystem.cpp 147 KB

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