FtpFileSystem.cpp 152 KB

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