FtpFileSystem.cpp 143 KB

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