1
0

FtpFileSystem.cpp 151 KB

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