FtpFileSystem.cpp 144 KB

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