FtpFileSystem.cpp 147 KB

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