1
0

FtpFileSystem.cpp 151 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747
  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(const UnicodeString & Alg, TRemoteFile * File)
  1015. {
  1016. // Overview of server supporting various hash commands is at:
  1017. // https://datatracker.ietf.org/doc/html/draft-bryan-ftpext-hash-02#appendix-B
  1018. UnicodeString CommandName;
  1019. bool UsingHashCommand = UsingHashCommandChecksum(Alg);
  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::CalculateFilesChecksum(
  1120. const UnicodeString & Alg, TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  1121. TFileOperationProgressType * OperationProgress, bool FirstLevel)
  1122. {
  1123. FTerminal->CalculateSubFoldersChecksum(Alg, FileList, OnCalculatedChecksum, OperationProgress, FirstLevel);
  1124. int Index = 0;
  1125. TOnceDoneOperation OnceDoneOperation; // not used
  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. TChecksumSessionAction Action(FTerminal->ActionLog);
  1133. try
  1134. {
  1135. OperationProgress->SetFile(File->FileName);
  1136. Action.FileName(File->FullFileName);
  1137. bool Success = false;
  1138. try
  1139. {
  1140. UnicodeString Checksum = DoCalculateFileChecksum(Alg, File);
  1141. if (OnCalculatedChecksum != NULL)
  1142. {
  1143. OnCalculatedChecksum(File->FileName, Alg, Checksum);
  1144. }
  1145. Action.Checksum(Alg, Checksum);
  1146. Success = true;
  1147. }
  1148. __finally
  1149. {
  1150. if (FirstLevel)
  1151. {
  1152. OperationProgress->Finish(File->FileName, Success, OnceDoneOperation);
  1153. }
  1154. }
  1155. }
  1156. catch (Exception & E)
  1157. {
  1158. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1159. // Error formatting expanded from inline to avoid strange exceptions
  1160. UnicodeString Error = FMTLOAD(CHECKSUM_ERROR, (File->FullFileName));
  1161. FTerminal->CommandError(&E, Error);
  1162. // Abort loop.
  1163. // TODO: retries? resume?
  1164. Index = FileList->Count;
  1165. }
  1166. }
  1167. Index++;
  1168. }
  1169. }
  1170. //---------------------------------------------------------------------------
  1171. UnicodeString TFTPFileSystem::CalculateFilesChecksumInitialize(const UnicodeString & Alg)
  1172. {
  1173. UnicodeString NormalizedAlg = FindIdent(FindIdent(Alg, FHashAlgs.get()), FChecksumAlgs.get());
  1174. if (UsingHashCommandChecksum(NormalizedAlg))
  1175. {
  1176. // The server should understand lowercase alg name by spec,
  1177. // but we should use uppercase anyway
  1178. SendCommand(FORMAT(L"OPTS %s %s", (HashCommand, UpperCase(NormalizedAlg))));
  1179. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1180. }
  1181. else if (FChecksumAlgs->IndexOf(NormalizedAlg) >= 0)
  1182. {
  1183. // will use algorithm-specific command
  1184. }
  1185. else
  1186. {
  1187. throw Exception(FMTLOAD(UNKNOWN_CHECKSUM, (Alg)));
  1188. }
  1189. return NormalizedAlg;
  1190. }
  1191. //---------------------------------------------------------------------------
  1192. bool TFTPFileSystem::UsingHashCommandChecksum(const UnicodeString & Alg)
  1193. {
  1194. return (FHashAlgs->IndexOf(Alg) >= 0);
  1195. }
  1196. //---------------------------------------------------------------------------
  1197. bool __fastcall TFTPFileSystem::ConfirmOverwrite(
  1198. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1199. TOverwriteMode & OverwriteMode, TFileOperationProgressType * OperationProgress,
  1200. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1201. int Params, bool AutoResume)
  1202. {
  1203. bool Result;
  1204. bool CanAutoResume = FLAGSET(Params, cpNoConfirmation) && AutoResume;
  1205. bool DestIsSmaller = (FileParams != NULL) && (FileParams->DestSize < FileParams->SourceSize);
  1206. bool DestIsSame = (FileParams != NULL) && (FileParams->DestSize == FileParams->SourceSize);
  1207. bool CanResume =
  1208. !OperationProgress->AsciiTransfer &&
  1209. // when resuming transfer after interrupted connection,
  1210. // do nothing (dummy resume) when the files has the same size.
  1211. // this is workaround for servers that strangely fails just after successful
  1212. // upload.
  1213. (DestIsSmaller || (DestIsSame && CanAutoResume));
  1214. unsigned int Answer;
  1215. if (CanAutoResume && CanResume)
  1216. {
  1217. if (DestIsSame)
  1218. {
  1219. DebugAssert(CanAutoResume);
  1220. Answer = qaSkip;
  1221. }
  1222. else
  1223. {
  1224. Answer = qaRetry;
  1225. }
  1226. }
  1227. else
  1228. {
  1229. // retry = "resume"
  1230. // all = "yes to newer"
  1231. // ignore = "rename"
  1232. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  1233. if (CanResume)
  1234. {
  1235. Answers |= qaRetry;
  1236. }
  1237. TQueryButtonAlias Aliases[5];
  1238. Aliases[0].Button = qaRetry;
  1239. Aliases[0].Alias = LoadStr(RESUME_BUTTON);
  1240. Aliases[0].GroupWith = qaNo;
  1241. Aliases[0].GrouppedShiftState = TShiftState() << ssAlt;
  1242. Aliases[1] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
  1243. Aliases[2] = TQueryButtonAlias::CreateIgnoreAsRenameGrouppedWithNo();
  1244. Aliases[3] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
  1245. Aliases[4] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
  1246. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1247. QueryParams.Aliases = Aliases;
  1248. QueryParams.AliasesCount = LENOF(Aliases);
  1249. {
  1250. TSuspendFileOperationProgress Suspend(OperationProgress);
  1251. Answer = FTerminal->ConfirmFileOverwrite(
  1252. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1253. ReverseOperationSide(OperationProgress->Side),
  1254. CopyParam, Params, OperationProgress);
  1255. }
  1256. }
  1257. Result = true;
  1258. switch (Answer)
  1259. {
  1260. // resume
  1261. case qaRetry:
  1262. OverwriteMode = omResume;
  1263. DebugAssert(FileParams != NULL);
  1264. DebugAssert(CanResume);
  1265. FFileTransferResumed = FileParams->DestSize;
  1266. break;
  1267. // rename
  1268. case qaIgnore:
  1269. if (FTerminal->PromptUser(FTerminal->SessionData, pkFileName,
  1270. LoadStr(RENAME_TITLE), L"", LoadStr(RENAME_PROMPT2), true, 0, TargetFileName))
  1271. {
  1272. OverwriteMode = omOverwrite;
  1273. }
  1274. else
  1275. {
  1276. OperationProgress->SetCancelAtLeast(csCancel);
  1277. FFileTransferAbort = ftaCancel;
  1278. Result = false;
  1279. }
  1280. break;
  1281. case qaYes:
  1282. OverwriteMode = omOverwrite;
  1283. break;
  1284. case qaCancel:
  1285. OperationProgress->SetCancelAtLeast(csCancel);
  1286. FFileTransferAbort = ftaCancel;
  1287. Result = false;
  1288. break;
  1289. case qaNo:
  1290. FFileTransferAbort = ftaSkip;
  1291. Result = false;
  1292. break;
  1293. case qaSkip:
  1294. OverwriteMode = omComplete;
  1295. break;
  1296. default:
  1297. DebugFail();
  1298. Result = false;
  1299. break;
  1300. }
  1301. return Result;
  1302. }
  1303. //---------------------------------------------------------------------------
  1304. void __fastcall TFTPFileSystem::ResetFileTransfer()
  1305. {
  1306. FFileTransferAbort = ftaNone;
  1307. FFileTransferCancelled = false;
  1308. FFileTransferResumed = 0;
  1309. }
  1310. //---------------------------------------------------------------------------
  1311. void __fastcall TFTPFileSystem::ReadDirectoryProgress(__int64 Bytes)
  1312. {
  1313. // with FTP we do not know exactly how many entries we have received,
  1314. // instead we know number of bytes received only.
  1315. // so we report approximation based on average size of entry.
  1316. int Progress = int(Bytes / 80);
  1317. DWORD Ticks = GetTickCount();
  1318. if ((Ticks - FLastReadDirectoryProgress >= 100) &&
  1319. // Cannot call OnReadDirectoryProgress with 0 as it would unmatch the "starting" and "ending" signals for disabling the window
  1320. (Progress > 0))
  1321. {
  1322. FLastReadDirectoryProgress = Ticks;
  1323. bool Cancel = false;
  1324. FTerminal->DoReadDirectoryProgress(Progress, 0, Cancel);
  1325. if (Cancel)
  1326. {
  1327. FTerminal->DoReadDirectoryProgress(-2, 0, Cancel);
  1328. FFileZillaIntf->Cancel();
  1329. }
  1330. }
  1331. }
  1332. //---------------------------------------------------------------------------
  1333. void __fastcall TFTPFileSystem::DoFileTransferProgress(__int64 TransferSize,
  1334. __int64 Bytes)
  1335. {
  1336. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  1337. OperationProgress->SetTransferSize(TransferSize);
  1338. if (FFileTransferResumed > 0)
  1339. {
  1340. OperationProgress->AddResumed(FFileTransferResumed);
  1341. FFileTransferResumed = 0;
  1342. }
  1343. __int64 Diff = Bytes - OperationProgress->TransferredSize;
  1344. if (DebugAlwaysTrue(Diff >= 0))
  1345. {
  1346. OperationProgress->AddTransferred(Diff);
  1347. FFileTransferAny = true;
  1348. }
  1349. if (OperationProgress->Cancel != csContinue)
  1350. {
  1351. if (OperationProgress->ClearCancelFile())
  1352. {
  1353. FFileTransferAbort = ftaSkip;
  1354. }
  1355. else
  1356. {
  1357. FFileTransferAbort = ftaCancel;
  1358. }
  1359. FFileTransferCancelled = true;
  1360. FFileZillaIntf->Cancel();
  1361. }
  1362. if (FFileTransferCPSLimit != OperationProgress->CPSLimit)
  1363. {
  1364. SetCPSLimit(OperationProgress);
  1365. }
  1366. }
  1367. //---------------------------------------------------------------------------
  1368. void __fastcall TFTPFileSystem::SetCPSLimit(TFileOperationProgressType * OperationProgress)
  1369. {
  1370. // Any reason we use separate field intead of directly using OperationProgress->CPSLimit?
  1371. // Maybe thread-safety?
  1372. FFileTransferCPSLimit = OperationProgress->CPSLimit;
  1373. OperationProgress->SetSpeedCounters();
  1374. }
  1375. //---------------------------------------------------------------------------
  1376. void __fastcall TFTPFileSystem::FileTransferProgress(__int64 TransferSize,
  1377. __int64 Bytes)
  1378. {
  1379. TGuard Guard(FTransferStatusCriticalSection);
  1380. DoFileTransferProgress(TransferSize, Bytes);
  1381. }
  1382. //---------------------------------------------------------------------------
  1383. void __fastcall TFTPFileSystem::FileTransfer(const UnicodeString & FileName,
  1384. const UnicodeString & LocalFile, const UnicodeString & RemoteFile,
  1385. const UnicodeString & RemotePath, bool Get, __int64 Size, int Type,
  1386. TFileTransferData & UserData, TFileOperationProgressType * OperationProgress)
  1387. {
  1388. FILE_OPERATION_LOOP_BEGIN
  1389. {
  1390. FFileZillaIntf->FileTransfer(
  1391. ApiPath(LocalFile).c_str(), RemoteFile.c_str(), RemotePath.c_str(),
  1392. Get, Size, Type, &UserData, UserData.CopyParam->OnTransferOut, UserData.CopyParam->OnTransferIn);
  1393. // we may actually catch response code of the listing
  1394. // command (when checking for existence of the remote file)
  1395. unsigned int Reply = WaitForCommandReply();
  1396. GotReply(Reply, FLAGMASK(FFileTransferCancelled, REPLY_ALLOW_CANCEL));
  1397. }
  1398. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1399. switch (FFileTransferAbort)
  1400. {
  1401. case ftaSkip:
  1402. throw ESkipFile();
  1403. case ftaCancel:
  1404. Abort();
  1405. break;
  1406. }
  1407. if (!FFileTransferCancelled)
  1408. {
  1409. // show completion of transfer
  1410. // call non-guarded variant to avoid deadlock with keepalives
  1411. // (we are not waiting for reply anymore so keepalives are free to proceed)
  1412. DoFileTransferProgress(OperationProgress->TransferSize, OperationProgress->TransferSize);
  1413. FAnyTransferSucceeded = true;
  1414. }
  1415. }
  1416. //---------------------------------------------------------------------------
  1417. void __fastcall TFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1418. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1419. int Params, TFileOperationProgressType * OperationProgress,
  1420. TOnceDoneOperation & OnceDoneOperation)
  1421. {
  1422. Params &= ~cpAppend;
  1423. FTerminal->DoCopyToLocal(
  1424. FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfUseFileTransferAny, OnceDoneOperation);
  1425. }
  1426. //---------------------------------------------------------------------------
  1427. UnicodeString TFTPFileSystem::RemoteExtractFilePath(const UnicodeString & Path)
  1428. {
  1429. UnicodeString Result;
  1430. // If the path ends with a slash, FZAPI CServerPath contructor does not identify the path as VMS.
  1431. // It is probably ok to use UnixExtractFileDir for all paths passed to FZAPI,
  1432. // but for now, we limit the impact of the change to VMS.
  1433. if (FVMS)
  1434. {
  1435. Result = UnixExtractFileDir(Path);
  1436. }
  1437. else
  1438. {
  1439. Result = UnixExtractFilePath(Path);
  1440. }
  1441. return Result;
  1442. }
  1443. //---------------------------------------------------------------------------
  1444. void __fastcall TFTPFileSystem::Sink(
  1445. const UnicodeString & FileName, const TRemoteFile * File,
  1446. const UnicodeString & TargetDir, UnicodeString & DestFileName, int Attrs,
  1447. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  1448. unsigned int Flags, TDownloadSessionAction & Action)
  1449. {
  1450. AutoDetectTimeDifference(UnixExtractFileDir(FileName), CopyParam, Params);
  1451. ResetFileTransfer();
  1452. TFileTransferData UserData;
  1453. UnicodeString DestFullName = TargetDir + DestFileName;
  1454. UnicodeString FilePath = RemoteExtractFilePath(FileName);
  1455. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1456. UnicodeString AFileName;
  1457. UnicodeString OnlyFileName = UnixExtractFileName(FileName);
  1458. if (EnsureLocationWhenWorkFromCwd(FilePath))
  1459. {
  1460. AFileName = OnlyFileName;
  1461. FilePath = EmptyStr;
  1462. }
  1463. else
  1464. {
  1465. AFileName = FileName;
  1466. }
  1467. {
  1468. // ignore file list
  1469. TFileListHelper Helper(this, NULL, true);
  1470. SetCPSLimit(OperationProgress);
  1471. FFileTransferPreserveTime = CopyParam->PreserveTime;
  1472. // not used for downloads anyway
  1473. FFileTransferRemoveBOM = CopyParam->RemoveBOM;
  1474. FFileTransferNoList = CanTransferSkipList(Params, Flags, CopyParam);
  1475. UserData.FileName = DestFileName;
  1476. UserData.Params = Params;
  1477. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1478. UserData.CopyParam = CopyParam;
  1479. UserData.Modification = File->Modification;
  1480. FileTransfer(AFileName, DestFullName, OnlyFileName,
  1481. FilePath, true, File->Size, TransferType, UserData, OperationProgress);
  1482. }
  1483. // in case dest filename is changed from overwrite dialog
  1484. if (DestFileName != UserData.FileName)
  1485. {
  1486. DestFullName = TargetDir + UserData.FileName;
  1487. Attrs = FileGetAttrFix(ApiPath(DestFullName));
  1488. }
  1489. UnicodeString ExpandedDestFullName = ExpandUNCFileName(DestFullName);
  1490. Action.Destination(ExpandedDestFullName);
  1491. if (CopyParam->OnTransferOut == NULL)
  1492. {
  1493. FTerminal->UpdateTargetAttrs(DestFullName, File, CopyParam, Attrs);
  1494. }
  1495. FLastDataSent = Now();
  1496. }
  1497. //---------------------------------------------------------------------------
  1498. void __fastcall TFTPFileSystem::TransferOnDirectory(
  1499. const UnicodeString & Directory, const TCopyParamType * CopyParam, int Params)
  1500. {
  1501. AutoDetectTimeDifference(Directory, CopyParam, Params);
  1502. }
  1503. //---------------------------------------------------------------------------
  1504. void __fastcall TFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1505. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1506. int Params, TFileOperationProgressType * OperationProgress,
  1507. TOnceDoneOperation & OnceDoneOperation)
  1508. {
  1509. Params &= ~cpAppend;
  1510. FTerminal->DoCopyToRemote(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfUseFileTransferAny, OnceDoneOperation);
  1511. }
  1512. //---------------------------------------------------------------------------
  1513. bool __fastcall TFTPFileSystem::CanTransferSkipList(int Params, unsigned int Flags, const TCopyParamType * CopyParam)
  1514. {
  1515. bool Result =
  1516. (CopyParam->OnTransferIn != NULL) ||
  1517. (FLAGSET(Params, cpNoConfirmation) &&
  1518. // cpAppend is not supported with FTP
  1519. DebugAlwaysTrue(FLAGCLEAR(Params, cpAppend)) &&
  1520. FLAGCLEAR(Params, cpResume) &&
  1521. FLAGCLEAR(Flags, tfAutoResume) &&
  1522. !CopyParam->NewerOnly);
  1523. return Result;
  1524. }
  1525. //---------------------------------------------------------------------------
  1526. void __fastcall TFTPFileSystem::Source(
  1527. TLocalFileHandle & Handle, const UnicodeString & TargetDir, UnicodeString & DestFileName,
  1528. const TCopyParamType * CopyParam, int Params,
  1529. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1530. TUploadSessionAction & Action, bool & /*ChildError*/)
  1531. {
  1532. if (CopyParam->OnTransferIn == NULL)
  1533. {
  1534. Handle.Close();
  1535. }
  1536. ResetFileTransfer();
  1537. TFileTransferData UserData;
  1538. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1539. EnsureLocationWhenWorkFromCwd(TargetDir);
  1540. {
  1541. // ignore file list
  1542. TFileListHelper Helper(this, NULL, true);
  1543. SetCPSLimit(OperationProgress);
  1544. // not used for uploads anyway
  1545. FFileTransferPreserveTime = CopyParam->PreserveTime && (CopyParam->OnTransferIn == NULL);
  1546. FFileTransferRemoveBOM = CopyParam->RemoveBOM;
  1547. FFileTransferNoList = CanTransferSkipList(Params, Flags, CopyParam);
  1548. // not used for uploads, but we get new name (if any) back in this field
  1549. UserData.FileName = DestFileName;
  1550. UserData.Params = Params;
  1551. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1552. UserData.CopyParam = CopyParam;
  1553. UserData.Modification = Handle.Modification;
  1554. FileTransfer(Handle.FileName, Handle.FileName, DestFileName,
  1555. TargetDir, false, Handle.Size, TransferType, UserData, OperationProgress);
  1556. }
  1557. UnicodeString DestFullName = TargetDir + UserData.FileName;
  1558. // only now, we know the final destination
  1559. Action.Destination(DestFullName);
  1560. // We are not able to tell if setting timestamp succeeded,
  1561. // so we log it always (if supported).
  1562. // Support for MDTM does not necessarily mean that the server supports
  1563. // non-standard hack of setting timestamp using
  1564. // MFMT-like (two argument) call to MDTM.
  1565. // IIS definitelly does.
  1566. if (FFileTransferPreserveTime &&
  1567. ((FServerCapabilities->GetCapability(mfmt_command) == yes) ||
  1568. ((FServerCapabilities->GetCapability(mdtm_command) == yes))))
  1569. {
  1570. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Handle.Modification);
  1571. if (!FFileZillaIntf->UsingMlsd())
  1572. {
  1573. FUploadedTimes[DestFullName] = Handle.Modification;
  1574. if ((FTerminal->Configuration->ActualLogProtocol >= 2))
  1575. {
  1576. FTerminal->LogEvent(
  1577. FORMAT(L"Remembering modification time of \"%s\" as [%s]",
  1578. (DestFullName, StandardTimestamp(FUploadedTimes[DestFullName]))));
  1579. }
  1580. }
  1581. }
  1582. FLastDataSent = Now();
  1583. }
  1584. //---------------------------------------------------------------------------
  1585. void __fastcall TFTPFileSystem::CreateDirectory(const UnicodeString & ADirName, bool /*Encrypt*/)
  1586. {
  1587. UnicodeString DirName = AbsolutePath(ADirName, false);
  1588. {
  1589. // ignore file list
  1590. TFileListHelper Helper(this, NULL, true);
  1591. FFileZillaIntf->MakeDir(DirName.c_str());
  1592. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1593. }
  1594. }
  1595. //---------------------------------------------------------------------------
  1596. void __fastcall TFTPFileSystem::CreateLink(const UnicodeString FileName,
  1597. const UnicodeString PointTo, bool Symbolic)
  1598. {
  1599. DebugAssert(SupportsSiteCommand(SymlinkSiteCommand));
  1600. if (DebugAlwaysTrue(Symbolic))
  1601. {
  1602. EnsureLocation();
  1603. UnicodeString Command = FORMAT(L"%s %s %s %s", (SiteCommand, SymlinkSiteCommand, PointTo, FileName));
  1604. SendCommand(Command);
  1605. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1606. }
  1607. }
  1608. //---------------------------------------------------------------------------
  1609. void __fastcall TFTPFileSystem::DeleteFile(const UnicodeString AFileName,
  1610. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  1611. {
  1612. UnicodeString FileName = AbsolutePath(AFileName, false);
  1613. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  1614. UnicodeString FilePath = RemoteExtractFilePath(FileName);
  1615. bool Dir = FTerminal->DeleteContentsIfDirectory(FileName, File, Params, Action);
  1616. {
  1617. // ignore file list
  1618. TFileListHelper Helper(this, NULL, true);
  1619. if (Dir)
  1620. {
  1621. // If current remote directory is in the directory being removed,
  1622. // some servers may refuse to delete it
  1623. // This is common as ProcessDirectory above would CWD to
  1624. // the directory to LIST it.
  1625. // EnsureLocation should reset actual current directory to user's working directory.
  1626. // If user's working directory is still below deleted directory, it is
  1627. // perfectly correct to report an error.
  1628. if (UnixIsChildPath(ActualCurrentDirectory(), FileName))
  1629. {
  1630. EnsureLocation();
  1631. }
  1632. FFileZillaIntf->RemoveDir(FileNameOnly.c_str(), FilePath.c_str());
  1633. }
  1634. else
  1635. {
  1636. if (EnsureLocationWhenWorkFromCwd(FilePath))
  1637. {
  1638. FFileZillaIntf->Delete(FileNameOnly.c_str(), L"", true);
  1639. }
  1640. else
  1641. {
  1642. FFileZillaIntf->Delete(FileNameOnly.c_str(), FilePath.c_str(), false);
  1643. }
  1644. }
  1645. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1646. }
  1647. }
  1648. //---------------------------------------------------------------------------
  1649. void __fastcall TFTPFileSystem::CustomCommandOnFile(const UnicodeString /*FileName*/,
  1650. const TRemoteFile * /*File*/, UnicodeString /*Command*/, int /*Params*/,
  1651. TCaptureOutputEvent /*OutputEvent*/)
  1652. {
  1653. // if ever implemented, do not forget to add EnsureLocation,
  1654. // see AnyCommand for a reason why
  1655. DebugFail();
  1656. }
  1657. //---------------------------------------------------------------------------
  1658. void __fastcall TFTPFileSystem::DoStartup()
  1659. {
  1660. TStrings * PostLoginCommands = new TStringList();
  1661. try
  1662. {
  1663. PostLoginCommands->Text = FTerminal->SessionData->PostLoginCommands;
  1664. for (int Index = 0; Index < PostLoginCommands->Count; Index++)
  1665. {
  1666. UnicodeString Command = PostLoginCommands->Strings[Index];
  1667. if (!Command.IsEmpty())
  1668. {
  1669. SendCommand(Command);
  1670. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_3XX_CODE);
  1671. }
  1672. }
  1673. }
  1674. __finally
  1675. {
  1676. delete PostLoginCommands;
  1677. }
  1678. // retrieve initialize working directory to save it as home directory
  1679. ReadCurrentDirectory();
  1680. FHomeDirectory = FCurrentDirectory;
  1681. }
  1682. //---------------------------------------------------------------------------
  1683. void __fastcall TFTPFileSystem::HomeDirectory()
  1684. {
  1685. // FHomeDirectory is an absolute path, so avoid unnecessary overhead
  1686. // of ChangeDirectory, such as EnsureLocation
  1687. DoChangeDirectory(FHomeDirectory);
  1688. FCurrentDirectory = FHomeDirectory;
  1689. FReadCurrentDirectory = false;
  1690. // make sure FZAPI is aware that we changed current working directory
  1691. FFileZillaIntf->SetCurrentPath(FCurrentDirectory.c_str());
  1692. }
  1693. //---------------------------------------------------------------------------
  1694. bool __fastcall TFTPFileSystem::IsCapable(int Capability) const
  1695. {
  1696. DebugAssert(FTerminal);
  1697. switch (Capability)
  1698. {
  1699. case fcResolveSymlink: // sic
  1700. case fcTextMode:
  1701. case fcModeChanging: // but not fcModeChangingUpload
  1702. case fcNewerOnlyUpload:
  1703. case fcAnyCommand: // but not fcShellAnyCommand
  1704. case fcRename:
  1705. case fcRemoteMove:
  1706. case fcRemoveBOMUpload:
  1707. case fcMoveToQueue:
  1708. case fcSkipTransfer:
  1709. case fcParallelTransfers:
  1710. case fcTransferOut:
  1711. case fcTransferIn:
  1712. return true;
  1713. case fcPreservingTimestampUpload:
  1714. return (FServerCapabilities->GetCapability(mfmt_command) == yes);
  1715. case fcRemoteCopy:
  1716. return SupportsSiteCommand(CopySiteCommand);
  1717. case fcSymbolicLink:
  1718. return SupportsSiteCommand(SymlinkSiteCommand);
  1719. case fcCalculatingChecksum:
  1720. return FSupportsAnyChecksumFeature;
  1721. case fcCheckingSpaceAvailable:
  1722. return FBytesAvailableSupported || SupportsCommand(AvblCommand) || SupportsCommand(XQuotaCommand);
  1723. case fcAclChangingFiles:
  1724. case fcModeChangingUpload:
  1725. case fcLoadingAdditionalProperties:
  1726. case fcShellAnyCommand:
  1727. case fcHardLink:
  1728. case fcUserGroupListing:
  1729. case fcGroupChanging:
  1730. case fcOwnerChanging:
  1731. case fcGroupOwnerChangingByID:
  1732. case fcSecondaryShell:
  1733. case fcNativeTextMode:
  1734. case fcTimestampChanging:
  1735. case fcIgnorePermErrors:
  1736. case fcRemoveCtrlZUpload:
  1737. case fcLocking:
  1738. case fcPreservingTimestampDirs:
  1739. case fcResumeSupport:
  1740. case fcChangePassword:
  1741. return false;
  1742. default:
  1743. DebugFail();
  1744. return false;
  1745. }
  1746. }
  1747. //---------------------------------------------------------------------------
  1748. void __fastcall TFTPFileSystem::LookupUsersGroups()
  1749. {
  1750. DebugFail();
  1751. }
  1752. //---------------------------------------------------------------------------
  1753. void __fastcall TFTPFileSystem::ReadCurrentDirectory()
  1754. {
  1755. // ask the server for current directory on startup only
  1756. // and immediately after call to CWD,
  1757. // later our current directory may be not synchronized with FZAPI current
  1758. // directory anyway, see comments in EnsureLocation
  1759. if (FReadCurrentDirectory || DebugAlwaysFalse(FCurrentDirectory.IsEmpty()))
  1760. {
  1761. UnicodeString Command = L"PWD";
  1762. SendCommand(Command);
  1763. unsigned int Code;
  1764. TStrings * Response = NULL;
  1765. GotReply(WaitForCommandReply(), REPLY_2XX_CODE, L"", &Code, &Response);
  1766. try
  1767. {
  1768. DebugAssert(Response != NULL);
  1769. bool Result = false;
  1770. // The 257 is the only allowed 2XX code to "PWD"
  1771. if (((Code == 257) || FTerminal->SessionData->FtpAnyCodeForPwd) &&
  1772. (Response->Count == 1))
  1773. {
  1774. UnicodeString Path = Response->Text;
  1775. int P = Path.Pos(L"\"");
  1776. if (P == 0)
  1777. {
  1778. // some systems use single quotes, be tolerant
  1779. P = Path.Pos(L"'");
  1780. }
  1781. if (P != 0)
  1782. {
  1783. Path.Delete(1, P - 1);
  1784. if (Unquote(Path))
  1785. {
  1786. Result = true;
  1787. }
  1788. }
  1789. else
  1790. {
  1791. P = Path.Pos(L" ");
  1792. Path.Delete(P, Path.Length() - P + 1);
  1793. Result = true;
  1794. }
  1795. if (Result)
  1796. {
  1797. if ((Path.Length() > 0) && !UnixIsAbsolutePath(Path))
  1798. {
  1799. Path = L"/" + Path;
  1800. }
  1801. FCurrentDirectory = UnixExcludeTrailingBackslash(Path);
  1802. FReadCurrentDirectory = false;
  1803. }
  1804. }
  1805. if (Result)
  1806. {
  1807. FFileZillaIntf->SetCurrentPath(FCurrentDirectory.c_str());
  1808. }
  1809. else
  1810. {
  1811. throw Exception(FMTLOAD(FTP_RESPONSE_ERROR, (Command, Response->Text)));
  1812. }
  1813. }
  1814. __finally
  1815. {
  1816. delete Response;
  1817. }
  1818. }
  1819. }
  1820. //---------------------------------------------------------------------------
  1821. void __fastcall TFTPFileSystem::DoReadDirectory(TRemoteFileList * FileList)
  1822. {
  1823. UnicodeString Directory;
  1824. if (!EnsureLocationWhenWorkFromCwd(FileList->Directory))
  1825. {
  1826. Directory = AbsolutePath(FileList->Directory, false);
  1827. }
  1828. FBytesAvailable = -1;
  1829. FileList->Reset();
  1830. // FZAPI does not list parent directory, add it
  1831. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  1832. FLastReadDirectoryProgress = 0;
  1833. TFileListHelper Helper(this, FileList, false);
  1834. // always specify path to list, do not attempt to list "current" dir as:
  1835. // 1) List() lists again the last listed directory, not the current working directory
  1836. // 2) we handle this way the cached directory change
  1837. FFileZillaIntf->List(Directory.c_str());
  1838. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_ALLOW_CANCEL);
  1839. AutoDetectTimeDifference(FileList);
  1840. if (!IsEmptyFileList(FileList))
  1841. {
  1842. CheckTimeDifference();
  1843. if ((FTimeDifference != 0) || !FUploadedTimes.empty())// optimization
  1844. {
  1845. for (int Index = 0; Index < FileList->Count; Index++)
  1846. {
  1847. ApplyTimeDifference(FileList->Files[Index]);
  1848. }
  1849. }
  1850. }
  1851. FLastDataSent = Now();
  1852. FAnyTransferSucceeded = true;
  1853. }
  1854. //---------------------------------------------------------------------------
  1855. void __fastcall TFTPFileSystem::CheckTimeDifference()
  1856. {
  1857. if (NeedAutoDetectTimeDifference())
  1858. {
  1859. FTerminal->LogEvent("Warning: Timezone difference was not detected yet, timestamps may be incorrect");
  1860. }
  1861. }
  1862. //---------------------------------------------------------------------------
  1863. void __fastcall TFTPFileSystem::ApplyTimeDifference(TRemoteFile * File)
  1864. {
  1865. DebugAssert(File->Modification == File->LastAccess);
  1866. File->ShiftTimeInSeconds(FTimeDifference);
  1867. TDateTime Modification = File->Modification;
  1868. if (LookupUploadModificationTime(File->FullFileName, Modification, File->ModificationFmt))
  1869. {
  1870. // implicitly sets ModificationFmt to mfFull
  1871. File->Modification = Modification;
  1872. }
  1873. }
  1874. //---------------------------------------------------------------------------
  1875. void __fastcall TFTPFileSystem::ApplyTimeDifference(
  1876. const UnicodeString & FileName, TDateTime & Modification, TModificationFmt & ModificationFmt)
  1877. {
  1878. CheckTimeDifference();
  1879. TRemoteFile::ShiftTimeInSeconds(Modification, ModificationFmt, FTimeDifference);
  1880. if (LookupUploadModificationTime(FileName, Modification, ModificationFmt))
  1881. {
  1882. ModificationFmt = mfFull;
  1883. }
  1884. }
  1885. //---------------------------------------------------------------------------
  1886. bool __fastcall TFTPFileSystem::LookupUploadModificationTime(
  1887. const UnicodeString & FileName, TDateTime & Modification, TModificationFmt ModificationFmt)
  1888. {
  1889. bool Result = false;
  1890. if (ModificationFmt != mfFull)
  1891. {
  1892. TUploadedTimes::iterator Iterator = FUploadedTimes.find(AbsolutePath(FileName, false));
  1893. if (Iterator != FUploadedTimes.end())
  1894. {
  1895. TDateTime UploadModification = Iterator->second;
  1896. TDateTime UploadModificationReduced = ReduceDateTimePrecision(UploadModification, ModificationFmt);
  1897. if (UploadModificationReduced == Modification)
  1898. {
  1899. if ((FTerminal->Configuration->ActualLogProtocol >= 2))
  1900. {
  1901. FTerminal->LogEvent(
  1902. FORMAT(L"Enriching modification time of \"%s\" from [%s] to [%s]",
  1903. (FileName, StandardTimestamp(Modification), StandardTimestamp(UploadModification))));
  1904. }
  1905. Modification = UploadModification;
  1906. Result = true;
  1907. }
  1908. else
  1909. {
  1910. if ((FTerminal->Configuration->ActualLogProtocol >= 2))
  1911. {
  1912. FTerminal->LogEvent(
  1913. FORMAT(L"Remembered modification time [%s]/[%s] of \"%s\" is obsolete, keeping [%s]",
  1914. (StandardTimestamp(UploadModification), StandardTimestamp(UploadModificationReduced), FileName, StandardTimestamp(Modification))));
  1915. }
  1916. FUploadedTimes.erase(Iterator);
  1917. }
  1918. }
  1919. }
  1920. return Result;
  1921. }
  1922. //---------------------------------------------------------------------------
  1923. bool __fastcall TFTPFileSystem::NeedAutoDetectTimeDifference()
  1924. {
  1925. return
  1926. FDetectTimeDifference &&
  1927. // Does not support MLST/MLSD, but supports MDTM at least
  1928. !FFileZillaIntf->UsingMlsd() && SupportsReadingFile();
  1929. }
  1930. //---------------------------------------------------------------------------
  1931. bool __fastcall TFTPFileSystem::IsEmptyFileList(TRemoteFileList * FileList)
  1932. {
  1933. return
  1934. // (note that it's actually never empty here, there's always at least parent directory,
  1935. // added explicitly by DoReadDirectory)
  1936. (FileList->Count == 0) ||
  1937. ((FileList->Count == 1) && FileList->Files[0]->IsParentDirectory);
  1938. }
  1939. //---------------------------------------------------------------------------
  1940. void __fastcall TFTPFileSystem::AutoDetectTimeDifference(TRemoteFileList * FileList)
  1941. {
  1942. if (NeedAutoDetectTimeDifference())
  1943. {
  1944. FTerminal->LogEvent(L"Detecting timezone difference...");
  1945. for (int Index = 0; Index < FileList->Count; Index++)
  1946. {
  1947. TRemoteFile * File = FileList->Files[Index];
  1948. // For directories, we do not do MDTM in ReadFile
  1949. // (it should not be problem to use them otherwise).
  1950. // We are also not interested in files with day precision only.
  1951. if (!File->IsDirectory && !File->IsSymLink &&
  1952. File->IsTimeShiftingApplicable())
  1953. {
  1954. TRemoteFile * UtcFile = NULL;
  1955. try
  1956. {
  1957. ReadFile(File->FullFileName, UtcFile);
  1958. }
  1959. catch (Exception & E)
  1960. {
  1961. FDetectTimeDifference = false;
  1962. if (!FTerminal->Active)
  1963. {
  1964. throw;
  1965. }
  1966. FTerminal->LogEvent(FORMAT(L"Failed to retrieve file %s attributes to detect timezone difference", (File->FullFileName)));
  1967. break;
  1968. }
  1969. TDateTime UtcModification = UtcFile->Modification;
  1970. delete UtcFile;
  1971. if (UtcModification > Now())
  1972. {
  1973. FTerminal->LogEvent(
  1974. FORMAT(L"Not using file %s to detect timezone difference as it has the timestamp in the future [%s]",
  1975. (File->FullFileName, StandardTimestamp(UtcModification))));
  1976. }
  1977. // "SecureLink FTP Proxy" succeeds CWD for a file, so we never get a timestamp here
  1978. else if (UtcModification == TDateTime())
  1979. {
  1980. FTerminal->LogEvent(
  1981. FORMAT(L"Not using file %s to detect timezone difference as its timestamp was not resolved",
  1982. (File->FullFileName)));
  1983. }
  1984. else
  1985. {
  1986. FDetectTimeDifference = false;
  1987. // MDTM returns seconds, trim those
  1988. UtcModification = ReduceDateTimePrecision(UtcModification, File->ModificationFmt);
  1989. // Time difference between timestamp retrieved using MDTM (UTC converted to local timezone)
  1990. // and using LIST (no conversion, expecting the server uses the same timezone as the client).
  1991. // Note that FormatTimeZone reverses the value.
  1992. FTimeDifference = static_cast<__int64>(SecsPerDay * (UtcModification - File->Modification));
  1993. double Hours = TTimeSpan::FromSeconds(FTimeDifference).TotalHours;
  1994. UnicodeString FileLog =
  1995. FORMAT(L"%s (Listing: %s, UTC: %s)", (File->FullFileName, StandardTimestamp(File->Modification), StandardTimestamp(UtcModification)));
  1996. UnicodeString LogMessage;
  1997. if (FTimeDifference == 0)
  1998. {
  1999. LogMessage = FORMAT(L"No timezone difference detected using file %s", (FileLog));
  2000. }
  2001. // Seen with "GamingDeluxe FTP Server", which returns "213 00010101000000"
  2002. else if (fabs(Hours) >= 48)
  2003. {
  2004. FTimeDifference = 0;
  2005. LogMessage = FORMAT(L"Ignoring suspicious timezone difference of %s hours, detected using file %s", (IntToStr(__int64(Hours)), FileLog));
  2006. }
  2007. else
  2008. {
  2009. LogMessage = FORMAT(L"Timezone difference of %s detected using file %s", (FormatTimeZone(FTimeDifference), FileLog));
  2010. }
  2011. FTerminal->LogEvent(LogMessage);
  2012. break;
  2013. }
  2014. }
  2015. }
  2016. if (FDetectTimeDifference)
  2017. {
  2018. FTerminal->LogEvent(L"Found no file to use for detecting timezone difference");
  2019. }
  2020. }
  2021. }
  2022. //---------------------------------------------------------------------------
  2023. void __fastcall TFTPFileSystem::AutoDetectTimeDifference(
  2024. const UnicodeString & Directory, const TCopyParamType * CopyParam, int Params)
  2025. {
  2026. if (NeedAutoDetectTimeDifference() &&
  2027. // do we need FTimeDifference for the operation?
  2028. // (tmAutomatic - AsciiFileMask can theoretically include time constraints, while it is unlikely)
  2029. (!FLAGSET(Params, cpNoConfirmation) ||
  2030. CopyParam->NewerOnly || (!CopyParam->TransferMode == tmAutomatic) || !CopyParam->IncludeFileMask.Masks.IsEmpty()))
  2031. {
  2032. FTerminal->LogEvent(L"Retrieving listing to detect timezone difference");
  2033. DummyReadDirectory(Directory);
  2034. }
  2035. }
  2036. //---------------------------------------------------------------------------
  2037. void __fastcall TFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  2038. {
  2039. // whole below "-a" logic is for LIST,
  2040. // if we know we are going to use MLSD, skip it
  2041. if (FFileZillaIntf->UsingMlsd())
  2042. {
  2043. DoReadDirectory(FileList);
  2044. }
  2045. else
  2046. {
  2047. bool GotNoFilesForAll = false;
  2048. bool Repeat;
  2049. do
  2050. {
  2051. Repeat = false;
  2052. try
  2053. {
  2054. FDoListAll = (FListAll == asAuto) || (FListAll == asOn);
  2055. DoReadDirectory(FileList);
  2056. // We got no files with "-a", but again no files w/o "-a",
  2057. // so it was not "-a"'s problem, revert to auto and let it decide the next time
  2058. if (GotNoFilesForAll && (FileList->Count == 0))
  2059. {
  2060. DebugAssert(FListAll == asOff);
  2061. FListAll = asAuto;
  2062. }
  2063. else if (FListAll == asAuto)
  2064. {
  2065. // some servers take "-a" as a mask and return empty directory listing
  2066. if (IsEmptyFileList(FileList))
  2067. {
  2068. Repeat = true;
  2069. FListAll = asOff;
  2070. GotNoFilesForAll = true;
  2071. FTerminal->LogEvent(L"LIST with -a switch returned empty directory listing, will try pure LIST");
  2072. }
  2073. else
  2074. {
  2075. // reading first directory has succeeded, always use "-a"
  2076. FListAll = asOn;
  2077. }
  2078. }
  2079. // use "-a" even for implicit directory reading by FZAPI?
  2080. // (e.g. before file transfer)
  2081. // Note that FZAPI ignores this for VMS/MVS.
  2082. FDoListAll = (FListAll == asOn);
  2083. }
  2084. catch(Exception & E)
  2085. {
  2086. FDoListAll = false;
  2087. // reading the first directory has failed,
  2088. // further try without "-a" only as the server may not support it
  2089. if (FListAll == asAuto)
  2090. {
  2091. FTerminal->LogEvent(L"LIST with -a failed, will try pure LIST");
  2092. if (!FTerminal->Active)
  2093. {
  2094. FTerminal->Reopen(ropNoReadDirectory);
  2095. }
  2096. FListAll = asOff;
  2097. Repeat = true;
  2098. }
  2099. else
  2100. {
  2101. throw;
  2102. }
  2103. }
  2104. }
  2105. while (Repeat);
  2106. }
  2107. }
  2108. //---------------------------------------------------------------------------
  2109. void __fastcall TFTPFileSystem::DoReadFile(const UnicodeString & AFileName,
  2110. TRemoteFile *& AFile)
  2111. {
  2112. UnicodeString FileName = AbsolutePath(AFileName, false);
  2113. UnicodeString FileNameOnly;
  2114. UnicodeString FilePath;
  2115. if (IsUnixRootPath(FileName))
  2116. {
  2117. FileNameOnly = FileName;
  2118. FilePath = FileName;
  2119. }
  2120. else
  2121. {
  2122. FileNameOnly = UnixExtractFileName(FileName);
  2123. FilePath = RemoteExtractFilePath(FileName);
  2124. }
  2125. TRemoteFileList * FileList = new TRemoteFileList();
  2126. try
  2127. {
  2128. // Duplicate() call below would use this to compose FullFileName
  2129. FileList->Directory = FilePath;
  2130. TFileListHelper Helper(this, FileList, false);
  2131. FFileZillaIntf->ListFile(FileNameOnly.c_str(), FilePath.c_str());
  2132. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_ALLOW_CANCEL);
  2133. TRemoteFile * File = FileList->FindFile(FileNameOnly);
  2134. if (File != NULL)
  2135. {
  2136. AFile = File->Duplicate();
  2137. }
  2138. FLastDataSent = Now();
  2139. }
  2140. __finally
  2141. {
  2142. delete FileList;
  2143. }
  2144. }
  2145. //---------------------------------------------------------------------------
  2146. bool __fastcall TFTPFileSystem::SupportsReadingFile()
  2147. {
  2148. return
  2149. FFileZillaIntf->UsingMlsd() ||
  2150. (SupportsCommand(MdtmCommand) && SupportsCommand(SizeCommand));
  2151. }
  2152. //---------------------------------------------------------------------------
  2153. void __fastcall TFTPFileSystem::ReadFile(const UnicodeString FileName,
  2154. TRemoteFile *& File)
  2155. {
  2156. File = NULL;
  2157. if (SupportsReadingFile())
  2158. {
  2159. DoReadFile(FileName, File);
  2160. }
  2161. else
  2162. {
  2163. if (IsUnixRootPath(FileName))
  2164. {
  2165. FTerminal->LogEvent(FORMAT(L"%s is a root path", (FileName)));
  2166. File = new TRemoteDirectoryFile();
  2167. File->FullFileName = FileName;
  2168. File->FileName = L"";
  2169. }
  2170. else
  2171. {
  2172. UnicodeString Path = RemoteExtractFilePath(FileName);
  2173. UnicodeString NameOnly;
  2174. int P;
  2175. bool MVSPath =
  2176. FMVS && Path.IsEmpty() &&
  2177. (FileName.SubString(1, 1) == L"'") && (FileName.SubString(FileName.Length(), 1) == L"'") &&
  2178. ((P = FileName.Pos(L".")) > 0);
  2179. if (!MVSPath)
  2180. {
  2181. NameOnly = UnixExtractFileName(FileName);
  2182. }
  2183. else
  2184. {
  2185. NameOnly = FileName.SubString(P + 1, FileName.Length() - P - 1);
  2186. }
  2187. DebugAssert(!FVMSAllRevisions);
  2188. TAutoFlag VMSAllRevisionsFlag(FVMSAllRevisions);
  2189. if (FVMS && (NameOnly.Pos(L";") > 2))
  2190. {
  2191. FTerminal->LogEvent(L"VMS versioned file detected, asking for all revisions");
  2192. FVMSAllRevisions = true;
  2193. }
  2194. TRemoteFile * AFile = NULL;
  2195. // FZAPI does not have efficient way to read properties of one file.
  2196. // In case we need properties of set of files from the same directory,
  2197. // cache the file list for future
  2198. if ((FFileListCache != NULL) &&
  2199. UnixSamePath(Path, FFileListCache->Directory) &&
  2200. (UnixIsAbsolutePath(FFileListCache->Directory) ||
  2201. (FFileListCachePath == CurrentDirectory)))
  2202. {
  2203. AFile = FFileListCache->FindFile(NameOnly);
  2204. }
  2205. // if cache is invalid or file is not in cache, (re)read the directory
  2206. if (AFile == NULL)
  2207. {
  2208. TRemoteFileList * FileListCache = new TRemoteFileList();
  2209. FileListCache->Directory = Path;
  2210. try
  2211. {
  2212. ReadDirectory(FileListCache);
  2213. }
  2214. catch(...)
  2215. {
  2216. delete FileListCache;
  2217. throw;
  2218. }
  2219. // set only after we successfully read the directory,
  2220. // otherwise, when we reconnect from ReadDirectory,
  2221. // the FFileListCache is reset from ResetCache.
  2222. delete FFileListCache;
  2223. FFileListCache = FileListCache;
  2224. FFileListCachePath = GetCurrentDirectory();
  2225. AFile = FFileListCache->FindFile(NameOnly);
  2226. }
  2227. VMSAllRevisionsFlag.Release();
  2228. if (AFile != NULL)
  2229. {
  2230. File = AFile->Duplicate();
  2231. if (MVSPath)
  2232. {
  2233. File->FileName = FileName;
  2234. File->FullFileName = FileName;
  2235. }
  2236. if (File->IsSymLink)
  2237. {
  2238. TAutoFlag AutoFlag(FForceReadSymlink);
  2239. File->Complete();
  2240. }
  2241. }
  2242. }
  2243. }
  2244. if (File == NULL)
  2245. {
  2246. throw Exception(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  2247. }
  2248. }
  2249. //---------------------------------------------------------------------------
  2250. void __fastcall TFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  2251. TRemoteFile *& File)
  2252. {
  2253. if (FForceReadSymlink && DebugAlwaysTrue(!SymlinkFile->LinkTo.IsEmpty()) && DebugAlwaysTrue(SymlinkFile->HaveFullFileName))
  2254. {
  2255. // When we get here from TFTPFileSystem::ReadFile, it's likely the second time ReadSymlink has been called for the link.
  2256. // The first time getting to the later branch, so IsDirectory is true and hence FullFileName ends with a slash.
  2257. UnicodeString SymlinkDir = UnixExtractFileDir(UnixExcludeTrailingBackslash(SymlinkFile->FullFileName));
  2258. UnicodeString LinkTo = ::AbsolutePath(SymlinkDir, SymlinkFile->LinkTo);
  2259. ReadFile(LinkTo, File);
  2260. }
  2261. else
  2262. {
  2263. // Resolving symlinks over FTP is big overhead
  2264. // (involves opening TCPIP connection for retrieving "directory listing").
  2265. // Moreover FZAPI does not support that anyway.
  2266. // Though nowadays we could use MLST to read the symlink.
  2267. std::unique_ptr<TRemoteFile> AFile(new TRemoteFile(SymlinkFile));
  2268. AFile->Terminal = FTerminal;
  2269. AFile->FileName = UnixExtractFileName(SymlinkFile->LinkTo);
  2270. // FZAPI treats all symlink target as directories
  2271. AFile->Type = FILETYPE_DIRECTORY;
  2272. File = AFile.release();
  2273. }
  2274. }
  2275. //---------------------------------------------------------------------------
  2276. void __fastcall TFTPFileSystem::RenameFile(const UnicodeString AFileName, const TRemoteFile * /*File*/,
  2277. const UnicodeString ANewName)
  2278. {
  2279. UnicodeString FileName = AbsolutePath(AFileName, false);
  2280. UnicodeString NewName = AbsolutePath(ANewName, false);
  2281. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  2282. UnicodeString FilePathOnly = RemoteExtractFilePath(FileName);
  2283. UnicodeString NewNameOnly = UnixExtractFileName(NewName);
  2284. UnicodeString NewPathOnly = RemoteExtractFilePath(NewName);
  2285. {
  2286. // ignore file list
  2287. TFileListHelper Helper(this, NULL, true);
  2288. FFileZillaIntf->Rename(FileNameOnly.c_str(), NewNameOnly.c_str(),
  2289. FilePathOnly.c_str(), NewPathOnly.c_str());
  2290. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  2291. }
  2292. }
  2293. //---------------------------------------------------------------------------
  2294. void __fastcall TFTPFileSystem::CopyFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  2295. const UnicodeString NewName)
  2296. {
  2297. DebugAssert(SupportsSiteCommand(CopySiteCommand));
  2298. EnsureLocation();
  2299. UnicodeString Command;
  2300. Command = FORMAT(L"%s CPFR %s", (SiteCommand, FileName));
  2301. SendCommand(Command);
  2302. GotReply(WaitForCommandReply(), REPLY_3XX_CODE);
  2303. Command = FORMAT(L"%s CPTO %s", (SiteCommand, NewName));
  2304. SendCommand(Command);
  2305. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  2306. }
  2307. //---------------------------------------------------------------------------
  2308. TStrings * __fastcall TFTPFileSystem::GetFixedPaths()
  2309. {
  2310. return NULL;
  2311. }
  2312. //---------------------------------------------------------------------------
  2313. void __fastcall TFTPFileSystem::SpaceAvailable(const UnicodeString Path,
  2314. TSpaceAvailable & ASpaceAvailable)
  2315. {
  2316. if (FBytesAvailableSupported)
  2317. {
  2318. std::unique_ptr<TRemoteFileList> DummyFileList(new TRemoteFileList());
  2319. DummyFileList->Directory = Path;
  2320. ReadDirectory(DummyFileList.get());
  2321. ASpaceAvailable.UnusedBytesAvailableToUser = FBytesAvailable;
  2322. }
  2323. else if (SupportsCommand(XQuotaCommand))
  2324. {
  2325. // WS_FTP:
  2326. // XQUOTA
  2327. // 213-File and disk usage
  2328. // File count: 3
  2329. // File limit: 10000
  2330. // Disk usage: 1532791
  2331. // Disk limit: 2048000
  2332. // 213 File and disk usage end
  2333. // XQUOTA is global not path-specific
  2334. UnicodeString Command = XQuotaCommand;
  2335. SendCommand(Command);
  2336. TStrings * Response = NULL;
  2337. GotReply(WaitForCommandReply(), REPLY_2XX_CODE, L"", NULL, &Response);
  2338. std::unique_ptr<TStrings> ResponseOwner(Response);
  2339. __int64 UsedBytes = -1;
  2340. for (int Index = 0; Index < Response->Count; Index++)
  2341. {
  2342. // trimming padding
  2343. UnicodeString Line = Trim(Response->Strings[Index]);
  2344. UnicodeString Label = CutToChar(Line, L':', true);
  2345. if (SameText(Label, L"Disk usage"))
  2346. {
  2347. UsedBytes = StrToInt64(Line);
  2348. }
  2349. else if (SameText(Label, L"Disk limit") && !SameText(Line, L"unlimited"))
  2350. {
  2351. ASpaceAvailable.BytesAvailableToUser = StrToInt64(Line);
  2352. }
  2353. }
  2354. if ((UsedBytes >= 0) && (ASpaceAvailable.BytesAvailableToUser > 0))
  2355. {
  2356. ASpaceAvailable.UnusedBytesAvailableToUser = ASpaceAvailable.BytesAvailableToUser - UsedBytes;
  2357. }
  2358. }
  2359. else if (SupportsCommand(AvblCommand))
  2360. {
  2361. // draft-peterson-streamlined-ftp-command-extensions-10
  2362. // Implemented by Serv-U.
  2363. UnicodeString Command = FORMAT(L"%s %s", (AvblCommand, Path));
  2364. SendCommand(Command);
  2365. UnicodeString Response = GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_SINGLE_LINE);
  2366. ASpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(Response);
  2367. }
  2368. }
  2369. //---------------------------------------------------------------------------
  2370. const TSessionInfo & __fastcall TFTPFileSystem::GetSessionInfo()
  2371. {
  2372. return FSessionInfo;
  2373. }
  2374. //---------------------------------------------------------------------------
  2375. const TFileSystemInfo & __fastcall TFTPFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  2376. {
  2377. if (!FFileSystemInfoValid)
  2378. {
  2379. FFileSystemInfo.RemoteSystem = FSystem;
  2380. FFileSystemInfo.RemoteSystem.Unique();
  2381. if (FFeatures->Count == 0)
  2382. {
  2383. FFileSystemInfo.AdditionalInfo = LoadStr(FTP_NO_FEATURE_INFO);
  2384. }
  2385. else
  2386. {
  2387. FFileSystemInfo.AdditionalInfo =
  2388. FORMAT(L"%s\r\n", (LoadStr(FTP_FEATURE_INFO)));
  2389. for (int Index = 0; Index < FFeatures->Count; Index++)
  2390. {
  2391. // For TrimLeft, refer to HandleFeatReply
  2392. FFileSystemInfo.AdditionalInfo += FORMAT(L" %s\r\n", (TrimLeft(FFeatures->Strings[Index])));
  2393. }
  2394. }
  2395. FTerminal->SaveCapabilities(FFileSystemInfo);
  2396. FFileSystemInfoValid = true;
  2397. }
  2398. return FFileSystemInfo;
  2399. }
  2400. //---------------------------------------------------------------------------
  2401. bool __fastcall TFTPFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
  2402. {
  2403. return false;
  2404. }
  2405. //---------------------------------------------------------------------------
  2406. bool __fastcall TFTPFileSystem::GetStoredCredentialsTried()
  2407. {
  2408. return FStoredPasswordTried;
  2409. }
  2410. //---------------------------------------------------------------------------
  2411. UnicodeString __fastcall TFTPFileSystem::GetUserName()
  2412. {
  2413. return FUserName;
  2414. }
  2415. //---------------------------------------------------------------------------
  2416. UnicodeString __fastcall TFTPFileSystem::GetCurrentDirectory()
  2417. {
  2418. return FCurrentDirectory;
  2419. }
  2420. //---------------------------------------------------------------------------
  2421. const wchar_t * __fastcall TFTPFileSystem::GetOption(int OptionID) const
  2422. {
  2423. TSessionData * Data = FTerminal->SessionData;
  2424. switch (OptionID)
  2425. {
  2426. case OPTION_PROXYHOST:
  2427. case OPTION_FWHOST:
  2428. FOptionScratch = Data->ProxyHost;
  2429. break;
  2430. case OPTION_PROXYUSER:
  2431. case OPTION_FWUSER:
  2432. FOptionScratch = Data->ProxyUsername;
  2433. break;
  2434. case OPTION_PROXYPASS:
  2435. case OPTION_FWPASS:
  2436. FOptionScratch = Data->ProxyPassword;
  2437. break;
  2438. case OPTION_TRANSFERIP:
  2439. FOptionScratch = FTerminal->Configuration->ExternalIpAddress;
  2440. break;
  2441. case OPTION_ANONPWD:
  2442. case OPTION_TRANSFERIP6:
  2443. FOptionScratch = L"";
  2444. break;
  2445. case OPTION_MPEXT_CERT_STORAGE:
  2446. FOptionScratch = FTerminal->Configuration->CertificateStorageExpanded;
  2447. break;
  2448. default:
  2449. DebugFail();
  2450. FOptionScratch = L"";
  2451. }
  2452. return FOptionScratch.c_str();
  2453. }
  2454. //---------------------------------------------------------------------------
  2455. int __fastcall TFTPFileSystem::GetOptionVal(int OptionID) const
  2456. {
  2457. TSessionData * Data = FTerminal->SessionData;
  2458. int Result;
  2459. switch (OptionID)
  2460. {
  2461. case OPTION_PROXYTYPE:
  2462. switch (Data->ProxyMethod)
  2463. {
  2464. case ::pmNone:
  2465. Result = 0; // PROXYTYPE_NOPROXY;
  2466. break;
  2467. case pmSocks4:
  2468. Result = 2; // PROXYTYPE_SOCKS4A
  2469. break;
  2470. case pmSocks5:
  2471. Result = 3; // PROXYTYPE_SOCKS5
  2472. break;
  2473. case pmHTTP:
  2474. Result = 4; // PROXYTYPE_HTTP11
  2475. break;
  2476. case pmTelnet:
  2477. case pmCmd:
  2478. default:
  2479. DebugFail();
  2480. Result = 0; // PROXYTYPE_NOPROXY;
  2481. break;
  2482. }
  2483. break;
  2484. case OPTION_PROXYPORT:
  2485. case OPTION_FWPORT:
  2486. Result = Data->ProxyPort;
  2487. break;
  2488. case OPTION_PROXYUSELOGON:
  2489. Result = !Data->ProxyUsername.IsEmpty();
  2490. break;
  2491. case OPTION_LOGONTYPE:
  2492. Result = Data->FtpProxyLogonType;
  2493. break;
  2494. case OPTION_TIMEOUTLENGTH:
  2495. Result = Data->Timeout;
  2496. break;
  2497. case OPTION_DEBUGSHOWLISTING:
  2498. Result = (FTerminal->Configuration->ActualLogProtocol >= 0);
  2499. break;
  2500. case OPTION_PASV:
  2501. // should never get here t_server.nPasv being nonzero
  2502. DebugFail();
  2503. Result = FALSE;
  2504. break;
  2505. case OPTION_PRESERVEDOWNLOADFILETIME:
  2506. case OPTION_MPEXT_PRESERVEUPLOADFILETIME:
  2507. Result = FFileTransferPreserveTime ? TRUE : FALSE;
  2508. break;
  2509. case OPTION_LIMITPORTRANGE:
  2510. Result = !FTerminal->SessionData->FtpPasvMode && FTerminal->Configuration->HasLocalPortNumberLimits();
  2511. break;
  2512. case OPTION_PORTRANGELOW:
  2513. Result = FTerminal->Configuration->LocalPortNumberMin;
  2514. break;
  2515. case OPTION_PORTRANGEHIGH:
  2516. Result = FTerminal->Configuration->LocalPortNumberMax;
  2517. break;
  2518. case OPTION_ENABLE_IPV6:
  2519. Result = ((Data->AddressFamily != afIPv4) ? TRUE : FALSE);
  2520. break;
  2521. case OPTION_KEEPALIVE:
  2522. Result = ((Data->FtpPingType != ptOff) ? TRUE : FALSE);
  2523. break;
  2524. case OPTION_INTERVALLOW:
  2525. case OPTION_INTERVALHIGH:
  2526. Result = Data->FtpPingInterval;
  2527. break;
  2528. case OPTION_VMSALLREVISIONS:
  2529. Result = FVMSAllRevisions ? TRUE : FALSE;
  2530. break;
  2531. case OPTION_SPEEDLIMIT_DOWNLOAD_TYPE:
  2532. case OPTION_SPEEDLIMIT_UPLOAD_TYPE:
  2533. Result = (FFileTransferCPSLimit == 0 ? 0 : 1);
  2534. break;
  2535. case OPTION_SPEEDLIMIT_DOWNLOAD_VALUE:
  2536. case OPTION_SPEEDLIMIT_UPLOAD_VALUE:
  2537. Result = (FFileTransferCPSLimit / 1024); // FZAPI expects KB/s
  2538. break;
  2539. case OPTION_MPEXT_SHOWHIDDEN:
  2540. Result = (FDoListAll ? TRUE : FALSE);
  2541. break;
  2542. case OPTION_MPEXT_SSLSESSIONREUSE:
  2543. Result = (Data->SslSessionReuse ? TRUE : FALSE);
  2544. break;
  2545. case OPTION_MPEXT_SNDBUF:
  2546. Result = Data->SendBuf;
  2547. break;
  2548. case OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY:
  2549. Result = FTransferActiveImmediately;
  2550. break;
  2551. case OPTION_MPEXT_REMOVE_BOM:
  2552. Result = FFileTransferRemoveBOM ? TRUE : FALSE;
  2553. break;
  2554. case OPTION_MPEXT_LOG_SENSITIVE:
  2555. Result = FTerminal->Configuration->LogSensitive ? TRUE : FALSE;
  2556. break;
  2557. case OPTION_MPEXT_HOST:
  2558. Result = (Data->FtpHost == asOn);
  2559. break;
  2560. case OPTION_MPEXT_NODELAY:
  2561. Result = Data->TcpNoDelay;
  2562. break;
  2563. case OPTION_MPEXT_NOLIST:
  2564. Result = FFileTransferNoList ? TRUE : FALSE;
  2565. break;
  2566. case OPTION_MPEXT_COMPLETE_TLS_SHUTDOWN:
  2567. Result = FFileZilla ? FALSE : TRUE;
  2568. break;
  2569. case OPTION_MPEXT_WORK_FROM_CWD:
  2570. Result = (FWorkFromCwd == asOn);
  2571. break;
  2572. default:
  2573. DebugFail();
  2574. Result = FALSE;
  2575. break;
  2576. }
  2577. return Result;
  2578. }
  2579. //---------------------------------------------------------------------------
  2580. bool __fastcall TFTPFileSystem::PostMessage(unsigned int Type, WPARAM wParam, LPARAM lParam)
  2581. {
  2582. if (Type == TFileZillaIntf::MSG_TRANSFERSTATUS)
  2583. {
  2584. // Stop here if FileTransferProgress is proceeding,
  2585. // it makes "pause" in queue work.
  2586. // Paused queue item stops in some of the TFileOperationProgressType
  2587. // methods called from FileTransferProgress
  2588. TGuard Guard(FTransferStatusCriticalSection);
  2589. }
  2590. TGuard Guard(FQueueCriticalSection);
  2591. FQueue->push_back(TMessageQueue::value_type(wParam, lParam));
  2592. SetEvent(FQueueEvent);
  2593. return true;
  2594. }
  2595. //---------------------------------------------------------------------------
  2596. bool __fastcall TFTPFileSystem::ProcessMessage()
  2597. {
  2598. bool Result;
  2599. TMessageQueue::value_type Message;
  2600. {
  2601. TGuard Guard(FQueueCriticalSection);
  2602. Result = !FQueue->empty();
  2603. if (Result)
  2604. {
  2605. Message = FQueue->front();
  2606. FQueue->pop_front();
  2607. }
  2608. else
  2609. {
  2610. // now we are perfectly sure that the queue is empty as it is locked,
  2611. // so reset the event
  2612. ResetEvent(FQueueEvent);
  2613. }
  2614. }
  2615. if (Result)
  2616. {
  2617. FFileZillaIntf->HandleMessage(Message.first, Message.second);
  2618. }
  2619. return Result;
  2620. }
  2621. //---------------------------------------------------------------------------
  2622. void __fastcall TFTPFileSystem::DiscardMessages()
  2623. {
  2624. try
  2625. {
  2626. while (ProcessMessage());
  2627. }
  2628. __finally
  2629. {
  2630. FReply = 0;
  2631. FCommandReply = 0;
  2632. }
  2633. }
  2634. //---------------------------------------------------------------------------
  2635. void __fastcall TFTPFileSystem::WaitForMessages()
  2636. {
  2637. unsigned int Result;
  2638. do
  2639. {
  2640. Result = WaitForSingleObject(FQueueEvent, GUIUpdateInterval);
  2641. FTerminal->ProcessGUI();
  2642. } while (Result == WAIT_TIMEOUT);
  2643. if (Result != WAIT_OBJECT_0)
  2644. {
  2645. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, (L"ftp#1", IntToStr(int(Result)))));
  2646. }
  2647. }
  2648. //---------------------------------------------------------------------------
  2649. void __fastcall TFTPFileSystem::PoolForFatalNonCommandReply()
  2650. {
  2651. DebugAssert(FReply == 0);
  2652. DebugAssert(FCommandReply == 0);
  2653. DebugAssert(!FWaitingForReply);
  2654. FWaitingForReply = true;
  2655. unsigned int Reply;
  2656. try
  2657. {
  2658. // discard up to one reply
  2659. // (it should not happen here that two replies are posted anyway)
  2660. while (ProcessMessage() && (FReply == 0));
  2661. Reply = FReply;
  2662. }
  2663. __finally
  2664. {
  2665. FReply = 0;
  2666. DebugAssert(FCommandReply == 0);
  2667. FCommandReply = 0;
  2668. DebugAssert(FWaitingForReply);
  2669. FWaitingForReply = false;
  2670. }
  2671. if (Reply != 0)
  2672. {
  2673. // throws
  2674. GotNonCommandReply(Reply);
  2675. }
  2676. }
  2677. //---------------------------------------------------------------------------
  2678. bool __fastcall TFTPFileSystem::NoFinalLastCode()
  2679. {
  2680. return (FLastCodeClass == 0) || (FLastCodeClass == 1);
  2681. }
  2682. //---------------------------------------------------------------------------
  2683. bool __fastcall TFTPFileSystem::KeepWaitingForReply(unsigned int & ReplyToAwait, bool WantLastCode)
  2684. {
  2685. // To keep waiting,
  2686. // non-command reply must be unset,
  2687. // the reply we wait for must be unset or
  2688. // last code must be unset (if we wait for it).
  2689. // Though make sure that disconnect makes it through always. As for example when connection is closed already,
  2690. // when sending commands, we may get REPLY_DISCONNECTED as a command response and no other response after,
  2691. // what would cause a hang.
  2692. return
  2693. (FReply == 0) &&
  2694. ((ReplyToAwait == 0) ||
  2695. (WantLastCode && NoFinalLastCode() && FLAGCLEAR(ReplyToAwait, TFileZillaIntf::REPLY_DISCONNECTED)));
  2696. }
  2697. //---------------------------------------------------------------------------
  2698. void __fastcall TFTPFileSystem::DoWaitForReply(unsigned int & ReplyToAwait, bool WantLastCode)
  2699. {
  2700. try
  2701. {
  2702. while (KeepWaitingForReply(ReplyToAwait, WantLastCode))
  2703. {
  2704. WaitForMessages();
  2705. // wait for the first reply only,
  2706. // i.e. in case two replies are posted get the first only.
  2707. // e.g. when server closes the connection, but posts error message before,
  2708. // sometime it happens that command (like download) fails because of the error
  2709. // and does not catch the disconnection. then asynchronous "disconnect reply"
  2710. // is posted immediately afterwards. leave detection of that to Idle()
  2711. while (ProcessMessage() && KeepWaitingForReply(ReplyToAwait, WantLastCode));
  2712. }
  2713. if (FReply != 0)
  2714. {
  2715. // throws
  2716. GotNonCommandReply(FReply);
  2717. }
  2718. }
  2719. catch(...)
  2720. {
  2721. // even if non-fatal error happens, we must process pending message,
  2722. // so that we "eat" the reply message, so that it gets not mistakenly
  2723. // associated with future connect
  2724. if (FTerminal->Active)
  2725. {
  2726. DoWaitForReply(ReplyToAwait, WantLastCode);
  2727. }
  2728. throw;
  2729. }
  2730. }
  2731. //---------------------------------------------------------------------------
  2732. unsigned int __fastcall TFTPFileSystem::WaitForReply(bool Command, bool WantLastCode)
  2733. {
  2734. DebugAssert(FReply == 0);
  2735. DebugAssert(FCommandReply == 0);
  2736. DebugAssert(!FWaitingForReply);
  2737. ResetReply();
  2738. FWaitingForReply = true;
  2739. unsigned int Reply;
  2740. try
  2741. {
  2742. unsigned int & ReplyToAwait = (Command ? FCommandReply : FReply);
  2743. DoWaitForReply(ReplyToAwait, WantLastCode);
  2744. Reply = ReplyToAwait;
  2745. }
  2746. __finally
  2747. {
  2748. FReply = 0;
  2749. FCommandReply = 0;
  2750. DebugAssert(FWaitingForReply);
  2751. FWaitingForReply = false;
  2752. }
  2753. return Reply;
  2754. }
  2755. //---------------------------------------------------------------------------
  2756. unsigned int __fastcall TFTPFileSystem::WaitForCommandReply(bool WantLastCode)
  2757. {
  2758. return WaitForReply(true, WantLastCode);
  2759. }
  2760. //---------------------------------------------------------------------------
  2761. void __fastcall TFTPFileSystem::WaitForFatalNonCommandReply()
  2762. {
  2763. WaitForReply(false, false);
  2764. DebugFail();
  2765. }
  2766. //---------------------------------------------------------------------------
  2767. void __fastcall TFTPFileSystem::ResetReply()
  2768. {
  2769. FLastCode = 0;
  2770. FLastCodeClass = 0;
  2771. FMultiLineResponse = false;
  2772. DebugAssert(FLastResponse != NULL);
  2773. FLastResponse->Clear();
  2774. DebugAssert(FLastErrorResponse != NULL);
  2775. FLastErrorResponse->Clear();
  2776. DebugAssert(FLastError != NULL);
  2777. FLastError->Clear();
  2778. }
  2779. //---------------------------------------------------------------------------
  2780. void __fastcall TFTPFileSystem::GotNonCommandReply(unsigned int Reply)
  2781. {
  2782. DebugAssert(FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2783. GotReply(Reply);
  2784. // should never get here as GotReply should raise fatal exception
  2785. DebugFail();
  2786. }
  2787. //---------------------------------------------------------------------------
  2788. void __fastcall TFTPFileSystem::Disconnect()
  2789. {
  2790. Discard();
  2791. FTerminal->Closed();
  2792. }
  2793. //---------------------------------------------------------------------------
  2794. UnicodeString __fastcall TFTPFileSystem::GotReply(unsigned int Reply, unsigned int Flags,
  2795. UnicodeString Error, unsigned int * Code, TStrings ** Response)
  2796. {
  2797. UnicodeString Result;
  2798. try
  2799. {
  2800. if (FLAGSET(Reply, TFileZillaIntf::REPLY_OK))
  2801. {
  2802. DebugAssert(Reply == TFileZillaIntf::REPLY_OK);
  2803. // With REPLY_2XX_CODE treat "OK" non-2xx code like an error.
  2804. // REPLY_3XX_CODE has to be always used along with REPLY_2XX_CODE.
  2805. if ((FLAGSET(Flags, REPLY_2XX_CODE) && (FLastCodeClass != 2)) &&
  2806. ((FLAGCLEAR(Flags, REPLY_3XX_CODE) || (FLastCodeClass != 3))))
  2807. {
  2808. GotReply(TFileZillaIntf::REPLY_ERROR, Flags, Error);
  2809. }
  2810. }
  2811. else if (FLAGSET(Reply, TFileZillaIntf::REPLY_CANCEL) &&
  2812. FLAGSET(Flags, REPLY_ALLOW_CANCEL))
  2813. {
  2814. DebugAssert(
  2815. (Reply == (TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)) ||
  2816. (Reply == (TFileZillaIntf::REPLY_ABORTED | TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)));
  2817. // noop
  2818. }
  2819. // we do not expect these with our usage of FZ
  2820. else if (Reply &
  2821. (TFileZillaIntf::REPLY_WOULDBLOCK | TFileZillaIntf::REPLY_OWNERNOTSET |
  2822. TFileZillaIntf::REPLY_INVALIDPARAM | TFileZillaIntf::REPLY_ALREADYCONNECTED |
  2823. TFileZillaIntf::REPLY_IDLE | TFileZillaIntf::REPLY_NOTINITIALIZED |
  2824. TFileZillaIntf::REPLY_ALREADYINIZIALIZED))
  2825. {
  2826. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, (L"ftp#2", FORMAT(L"0x%x", (int(Reply))))));
  2827. }
  2828. else
  2829. {
  2830. // everything else must be an error or disconnect notification
  2831. DebugAssert(
  2832. FLAGSET(Reply, TFileZillaIntf::REPLY_ERROR) ||
  2833. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2834. // TODO: REPLY_CRITICALERROR ignored
  2835. // REPLY_NOTCONNECTED happens if connection is closed between moment
  2836. // when FZAPI interface method dispatches the command to FZAPI thread
  2837. // and moment when FZAPI thread receives the command
  2838. bool Disconnected =
  2839. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED) ||
  2840. FLAGSET(Reply, TFileZillaIntf::REPLY_NOTCONNECTED);
  2841. bool DoClose = false;
  2842. UnicodeString HelpKeyword;
  2843. TStrings * MoreMessages = new TStringList();
  2844. try
  2845. {
  2846. if (Disconnected)
  2847. {
  2848. if (FLAGCLEAR(Flags, REPLY_CONNECT))
  2849. {
  2850. MoreMessages->Add(LoadStr(LOST_CONNECTION));
  2851. Disconnect();
  2852. }
  2853. else
  2854. {
  2855. // For connection failure, do not report that connection was lost,
  2856. // its obvious.
  2857. // Also do not report to terminal that we are closed as
  2858. // that turns terminal into closed mode, but we want to
  2859. // pretend (at least with failed authentication) to retry
  2860. // with the same connection (as with SSH), so we explicitly
  2861. // close terminal in Open() only after we give up
  2862. Discard();
  2863. }
  2864. }
  2865. if (FLAGSET(Reply, TFileZillaIntf::REPLY_ABORTED))
  2866. {
  2867. MoreMessages->Add(LoadStr(USER_TERMINATED));
  2868. }
  2869. if (FLAGSET(Reply, TFileZillaIntf::REPLY_NOTSUPPORTED))
  2870. {
  2871. MoreMessages->Add(LoadStr(NOTSUPPORTED));
  2872. }
  2873. if (FLastCode == 530)
  2874. {
  2875. // Serv-U also uses this code in response to "SITE PSWD"
  2876. MoreMessages->Add(LoadStr(AUTHENTICATION_FAILED));
  2877. }
  2878. bool RetryTransfer = false;
  2879. if (FLastCode == 425)
  2880. {
  2881. if (FAnyTransferSucceeded)
  2882. {
  2883. FTerminal->LogEvent(FORMAT(L"Got %d after some previous data connections succeeded, retrying connection", (FLastCode)));
  2884. RetryTransfer = true;
  2885. }
  2886. else if (!FTerminal->SessionData->FtpPasvMode)
  2887. {
  2888. MoreMessages->Add(LoadStr(FTP_CANNOT_OPEN_ACTIVE_CONNECTION2));
  2889. HelpKeyword = HELP_FTP_CANNOT_OPEN_ACTIVE_CONNECTION;
  2890. }
  2891. }
  2892. if (FLastCode == DummyTimeoutCode)
  2893. {
  2894. HelpKeyword = HELP_ERRORMSG_TIMEOUT;
  2895. }
  2896. if (FLastCode == DummyDisconnectCode)
  2897. {
  2898. HelpKeyword = HELP_STATUSMSG_DISCONNECTED;
  2899. }
  2900. if (FAnyTransferSucceeded && (FLastError->Count > 0))
  2901. {
  2902. UnicodeString CantOpenTransferChannelMessage = LoadStr(IDS_ERRORMSG_CANTOPENTRANSFERCHANNEL);
  2903. int P = CantOpenTransferChannelMessage.Pos(L"%");
  2904. if (DebugAlwaysTrue(P > 0))
  2905. {
  2906. CantOpenTransferChannelMessage.SetLength(P - 1);
  2907. }
  2908. if (ContainsText(FLastError->Strings[0], CantOpenTransferChannelMessage))
  2909. {
  2910. FTerminal->LogEvent(L"Failed to connection data connection after some previous data connections succeeded, retrying connection");
  2911. RetryTransfer = true;
  2912. }
  2913. }
  2914. if (RetryTransfer)
  2915. {
  2916. Disconnected = true;
  2917. // Close only later, as we still need to use FLast* fields
  2918. DoClose = true;
  2919. }
  2920. MoreMessages->AddStrings(FLastError);
  2921. // already cleared from WaitForReply, but GotReply can be also called
  2922. // from Closed. then make sure that error from previous command not
  2923. // associated with session closure is not reused
  2924. FLastError->Clear();
  2925. MoreMessages->AddStrings(FLastErrorResponse);
  2926. // see comment for FLastError
  2927. FLastResponse->Clear();
  2928. FLastErrorResponse->Clear();
  2929. if (MoreMessages->Count == 0)
  2930. {
  2931. delete MoreMessages;
  2932. MoreMessages = NULL;
  2933. }
  2934. }
  2935. catch(...)
  2936. {
  2937. delete MoreMessages;
  2938. throw;
  2939. }
  2940. if (Error.IsEmpty() && (MoreMessages != NULL))
  2941. {
  2942. DebugAssert(MoreMessages->Count > 0);
  2943. // bit too generic assigning of main instructions, let's see how it works
  2944. Error = MainInstructions(MoreMessages->Strings[0]);
  2945. MoreMessages->Delete(0);
  2946. }
  2947. if (Disconnected)
  2948. {
  2949. if (DoClose)
  2950. {
  2951. Close();
  2952. }
  2953. // for fatal error, it is essential that there is some message
  2954. DebugAssert(!Error.IsEmpty());
  2955. ExtException * E = new ExtException(Error, MoreMessages, true, HelpKeyword);
  2956. try
  2957. {
  2958. FTerminal->FatalError(E, L"");
  2959. }
  2960. __finally
  2961. {
  2962. delete E;
  2963. }
  2964. }
  2965. else
  2966. {
  2967. throw ExtException(Error, MoreMessages, true, HelpKeyword);
  2968. }
  2969. }
  2970. if ((Code != NULL) && (FLastCodeClass != DummyCodeClass))
  2971. {
  2972. *Code = FLastCode;
  2973. }
  2974. if (FLAGSET(Flags, REPLY_SINGLE_LINE))
  2975. {
  2976. if (FLastResponse->Count != 1)
  2977. {
  2978. throw Exception(FMTLOAD(FTP_RESPONSE_ERROR, (FLastCommandSent, FLastResponse->Text)));
  2979. }
  2980. Result = FLastResponse->Strings[0];
  2981. }
  2982. if (Response != NULL)
  2983. {
  2984. *Response = FLastResponse;
  2985. FLastResponse = new TStringList();
  2986. // just to be consistent
  2987. delete FLastErrorResponse;
  2988. FLastErrorResponse = new TStringList();
  2989. }
  2990. }
  2991. __finally
  2992. {
  2993. ResetReply();
  2994. }
  2995. return Result;
  2996. }
  2997. //---------------------------------------------------------------------------
  2998. void __fastcall TFTPFileSystem::SendCommand(const UnicodeString & Command)
  2999. {
  3000. FFileZillaIntf->CustomCommand(Command.c_str());
  3001. FLastCommandSent = CopyToChar(Command, L' ', false);
  3002. }
  3003. //---------------------------------------------------------------------------
  3004. void __fastcall TFTPFileSystem::SetLastCode(int Code)
  3005. {
  3006. FLastCode = Code;
  3007. FLastCodeClass = (Code / 100);
  3008. }
  3009. //---------------------------------------------------------------------------
  3010. void __fastcall TFTPFileSystem::StoreLastResponse(const UnicodeString & Text)
  3011. {
  3012. FLastResponse->Add(Text);
  3013. if (FLastCodeClass >= 4)
  3014. {
  3015. FLastErrorResponse->Add(Text);
  3016. }
  3017. }
  3018. //---------------------------------------------------------------------------
  3019. void __fastcall TFTPFileSystem::HandleReplyStatus(UnicodeString Response)
  3020. {
  3021. int Code;
  3022. if (FOnCaptureOutput != NULL)
  3023. {
  3024. FOnCaptureOutput(Response, cotOutput);
  3025. }
  3026. if (FWelcomeMessage.IsEmpty() && StartsStr(L"SSH", Response))
  3027. {
  3028. FLastErrorResponse->Add(LoadStr(SFTP_AS_FTP_ERROR));
  3029. }
  3030. // Two forms of multiline responses were observed
  3031. // (the first is according to the RFC 959):
  3032. // 211-Features:
  3033. // MDTM
  3034. // REST STREAM
  3035. // SIZE
  3036. // 211 End
  3037. // This format is according to RFC 2228.
  3038. // Is used by ProFTPD when deprecated MultilineRFC2228 directive is enabled
  3039. // http://www.proftpd.org/docs/modules/mod_core.html#FileZillaNonASCII
  3040. // 211-Features:
  3041. // 211-MDTM
  3042. // 211-REST STREAM
  3043. // 211-SIZE
  3044. // 211-AUTH TLS
  3045. // 211-PBSZ
  3046. // 211-PROT
  3047. // 211 End
  3048. // IIS 2003:
  3049. // 211-FEAT
  3050. // SIZE
  3051. // MDTM
  3052. // 211 END
  3053. // Partially duplicated in CFtpControlSocket::OnReceive
  3054. bool HasCodePrefix =
  3055. (Response.Length() >= 3) &&
  3056. TryStrToInt(Response.SubString(1, 3), Code) &&
  3057. (Code >= 100) && (Code <= 599) &&
  3058. ((Response.Length() == 3) || (Response[4] == L' ') || (Response[4] == L'-'));
  3059. if (HasCodePrefix && !FMultiLineResponse)
  3060. {
  3061. FMultiLineResponse = (Response.Length() >= 4) && (Response[4] == L'-');
  3062. FLastResponse->Clear();
  3063. FLastErrorResponse->Clear();
  3064. SetLastCode(Code);
  3065. if (Response.Length() >= 5)
  3066. {
  3067. StoreLastResponse(Response.SubString(5, Response.Length() - 4));
  3068. }
  3069. }
  3070. else
  3071. {
  3072. int Start;
  3073. // response with code prefix
  3074. if (HasCodePrefix && (FLastCode == Code))
  3075. {
  3076. // End of multiline response?
  3077. if ((Response.Length() <= 3) || (Response[4] == L' '))
  3078. {
  3079. FMultiLineResponse = false;
  3080. }
  3081. Start = 5;
  3082. }
  3083. else
  3084. {
  3085. Start = (((Response.Length() >= 1) && (Response[1] == L' ')) ? 2 : 1);
  3086. }
  3087. // Intermediate empty lines are being added
  3088. if (FMultiLineResponse || (Response.Length() >= Start))
  3089. {
  3090. StoreLastResponse(Response.SubString(Start, Response.Length() - Start + 1));
  3091. }
  3092. }
  3093. if (StartsStr(DirectoryHasBytesPrefix, Response))
  3094. {
  3095. UnicodeString Buf = Response;
  3096. Buf.Delete(1, DirectoryHasBytesPrefix.Length());
  3097. Buf = Buf.TrimLeft();
  3098. UnicodeString BytesStr = CutToChar(Buf, L' ', true);
  3099. BytesStr = ReplaceStr(BytesStr, L",", L"");
  3100. FBytesAvailable = StrToInt64Def(BytesStr, -1);
  3101. if (FBytesAvailable >= 0)
  3102. {
  3103. FBytesAvailableSupported = true;
  3104. }
  3105. }
  3106. if (!FMultiLineResponse)
  3107. {
  3108. if (FLastCode == 220)
  3109. {
  3110. // HOST command also uses 220 response.
  3111. // Neither our use of welcome message is prepared for changing it
  3112. // during the session, so we keep the initial message only.
  3113. // Theoretically the welcome message can be host-specific,
  3114. // but IIS uses "220 Host accepted", and we are not interested in that anyway.
  3115. // Serv-U repeats the initial welcome message.
  3116. // WS_FTP uses "200 Command HOST succeed"
  3117. if (FWelcomeMessage.IsEmpty())
  3118. {
  3119. FWelcomeMessage = FLastResponse->Text;
  3120. if (FTerminal->Configuration->ShowFtpWelcomeMessage)
  3121. {
  3122. FTerminal->DisplayBanner(FWelcomeMessage);
  3123. }
  3124. // Idea FTP Server v0.80
  3125. if ((FTerminal->SessionData->FtpTransferActiveImmediately == asAuto) &&
  3126. FWelcomeMessage.Pos(L"Idea FTP Server") > 0)
  3127. {
  3128. FTerminal->LogEvent(L"The server requires TLS/SSL handshake on transfer connection before responding 1yz to STOR/APPE");
  3129. FTransferActiveImmediately = true;
  3130. }
  3131. }
  3132. }
  3133. else if (FLastCommand == PASS)
  3134. {
  3135. FStoredPasswordTried = true;
  3136. // 530 = "Not logged in."
  3137. if (FLastCode == 530)
  3138. {
  3139. FPasswordFailed = true;
  3140. }
  3141. }
  3142. else if (FLastCommand == SYST)
  3143. {
  3144. DebugAssert(FSystem.IsEmpty());
  3145. // Positive reply to "SYST" should be 215, see RFC 959.
  3146. // But "VMS VAX/VMS V6.1 on node nsrp14" uses plain 200.
  3147. if (FLastCodeClass == 2)
  3148. {
  3149. FSystem = FLastResponse->Text.TrimRight();
  3150. // FZAPI has own detection of MVS/VMS
  3151. // Full name is "MVS is the operating system of this server. FTP Server is running on ..."
  3152. // (the ... can be "z/OS")
  3153. // https://www.ibm.com/docs/en/zos/latest?topic=2rc-215-mvs-is-operating-system-this-server-ftp-server-is-running-name
  3154. // FZPI has a different incompatible detection.
  3155. // MVS FTP servers have two separate MVS and Unix file systems cooexisting in the same session.
  3156. FMVS = (FSystem.SubString(1, 3) == L"MVS");
  3157. if (FMVS)
  3158. {
  3159. FTerminal->LogEvent(L"MVS system detected.");
  3160. }
  3161. // The FWelcomeMessage usually contains "Microsoft FTP Service" but can be empty
  3162. if (ContainsText(FSystem, L"Windows_NT"))
  3163. {
  3164. FTerminal->LogEvent(L"The server is probably running Windows, assuming that directory listing timestamps are affected by DST.");
  3165. FWindowsServer = true;
  3166. }
  3167. // VMS system type. VMS V5.5-2.
  3168. // VMS VAX/VMS V6.1 on node nsrp14
  3169. if (FSystem.SubString(1, 4) == L"VMS ")
  3170. {
  3171. FTerminal->LogEvent(L"VMS system detected.");
  3172. FVMS = true;
  3173. }
  3174. if ((FListAll == asAuto) &&
  3175. // full name is "Personal FTP Server PRO K6.0"
  3176. ((FSystem.Pos(L"Personal FTP Server") > 0) ||
  3177. FMVS || FVMS))
  3178. {
  3179. FTerminal->LogEvent(L"Server is known not to support LIST -a");
  3180. FListAll = asOff;
  3181. }
  3182. if ((FWorkFromCwd == asAuto) && FVMS)
  3183. {
  3184. FTerminal->LogEvent(L"Server is known to require use of relative paths");
  3185. FWorkFromCwd = asOn;
  3186. }
  3187. // 220-FileZilla Server 1.0.1
  3188. // 220 Please visit https://filezilla-project.org/
  3189. // SYST
  3190. // 215 UNIX emulated by FileZilla
  3191. // (Welcome message is configurable)
  3192. if (ContainsText(FSystem, L"FileZilla"))
  3193. {
  3194. FTerminal->LogEvent(L"FileZilla server detected.");
  3195. FFileZilla = true;
  3196. }
  3197. }
  3198. else
  3199. {
  3200. FSystem = L"";
  3201. }
  3202. }
  3203. else if (FLastCommand == FEAT)
  3204. {
  3205. HandleFeatReply();
  3206. }
  3207. }
  3208. }
  3209. //---------------------------------------------------------------------------
  3210. void __fastcall TFTPFileSystem::ResetFeatures()
  3211. {
  3212. FFeatures->Clear();
  3213. FSupportedCommands->Clear();
  3214. FSupportedSiteCommands->Clear();
  3215. FHashAlgs->Clear();
  3216. FSupportsAnyChecksumFeature = false;
  3217. }
  3218. //---------------------------------------------------------------------------
  3219. UnicodeString TFTPFileSystem::CutFeature(UnicodeString & Buf)
  3220. {
  3221. UnicodeString Result;
  3222. if (Buf.SubString(1, 1) == L"\"")
  3223. {
  3224. Buf.Delete(1, 1);
  3225. int P = Buf.Pos(L"\",");
  3226. if (P == 0)
  3227. {
  3228. Result = Buf;
  3229. Buf = UnicodeString();
  3230. // there should be the ending quote, but if not, just do nothing
  3231. if (Result.SubString(Result.Length(), 1) == L"\"")
  3232. {
  3233. Result.SetLength(Result.Length() - 1);
  3234. }
  3235. }
  3236. else
  3237. {
  3238. Result = Buf.SubString(1, P - 1);
  3239. Buf.Delete(1, P + 1);
  3240. }
  3241. Buf = Buf.TrimLeft();
  3242. }
  3243. else
  3244. {
  3245. Result = CutToChar(Buf, L',', true);
  3246. }
  3247. return Result;
  3248. }
  3249. //---------------------------------------------------------------------------
  3250. void TFTPFileSystem::ProcessFeatures()
  3251. {
  3252. std::unique_ptr<TStrings> Features(new TStringList());
  3253. UnicodeString FeaturesOverride = FTerminal->SessionData->ProtocolFeatures.Trim();
  3254. if (FeaturesOverride.SubString(1, 1) == L"*")
  3255. {
  3256. FeaturesOverride.Delete(1, 1);
  3257. while (!FeaturesOverride.IsEmpty())
  3258. {
  3259. UnicodeString Feature = CutFeature(FeaturesOverride);
  3260. Features->Add(Feature);
  3261. }
  3262. }
  3263. else
  3264. {
  3265. std::unique_ptr<TStrings> DeleteFeatures(CreateSortedStringList());
  3266. std::unique_ptr<TStrings> AddFeatures(new TStringList());
  3267. while (!FeaturesOverride.IsEmpty())
  3268. {
  3269. UnicodeString Feature = CutFeature(FeaturesOverride);
  3270. if (Feature.SubString(1, 1) == L"-")
  3271. {
  3272. Feature.Delete(1, 1);
  3273. DeleteFeatures->Add(Feature.LowerCase());
  3274. }
  3275. else
  3276. {
  3277. if (Feature.SubString(1, 1) == L"+")
  3278. {
  3279. Feature.Delete(1, 1);
  3280. }
  3281. AddFeatures->Add(Feature);
  3282. }
  3283. }
  3284. for (int Index = 0; Index < FFeatures->Count; Index++)
  3285. {
  3286. // IIS 2003 indents response by 4 spaces, instead of one,
  3287. // see example in HandleReplyStatus
  3288. UnicodeString Feature = FFeatures->Strings[Index].Trim();
  3289. if (DeleteFeatures->IndexOf(Feature) < 0)
  3290. {
  3291. Features->Add(Feature);
  3292. }
  3293. }
  3294. Features->AddStrings(AddFeatures.get());
  3295. }
  3296. for (int Index = 0; Index < Features->Count; Index++)
  3297. {
  3298. UnicodeString Feature = Features->Strings[Index];
  3299. UnicodeString Args = Feature;
  3300. UnicodeString Command = CutToChar(Args, L' ', true);
  3301. // Serv-U lists Xalg commands like:
  3302. // XSHA1 filename;start;end
  3303. FSupportedCommands->Add(Command);
  3304. if (SameText(Command, SiteCommand))
  3305. {
  3306. // Serv-U lists all SITE commands in one line like:
  3307. // SITE PSWD;SET;ZONE;CHMOD;MSG;EXEC;HELP
  3308. // But ProFTPD lists them separatelly:
  3309. // SITE UTIME
  3310. // SITE RMDIR
  3311. // SITE COPY
  3312. // SITE MKDIR
  3313. // SITE SYMLINK
  3314. while (!Args.IsEmpty())
  3315. {
  3316. UnicodeString Arg = CutToChar(Args, L';', true);
  3317. FSupportedSiteCommands->Add(Arg);
  3318. }
  3319. }
  3320. else if (SameText(Command, HashCommand))
  3321. {
  3322. while (!Args.IsEmpty())
  3323. {
  3324. UnicodeString Alg = CutToChar(Args, L';', true);
  3325. if ((Alg.Length() > 0) && (Alg[Alg.Length()] == L'*'))
  3326. {
  3327. Alg.Delete(Alg.Length(), 1);
  3328. }
  3329. // FTP HASH alg names follow IANA as we do,
  3330. // but using uppercase and we use lowercase
  3331. FHashAlgs->Add(LowerCase(Alg));
  3332. FSupportsAnyChecksumFeature = true;
  3333. }
  3334. }
  3335. if (FChecksumCommands->IndexOf(Command) >= 0)
  3336. {
  3337. FSupportsAnyChecksumFeature = true;
  3338. }
  3339. }
  3340. }
  3341. //---------------------------------------------------------------------------
  3342. void __fastcall TFTPFileSystem::HandleFeatReply()
  3343. {
  3344. ResetFeatures();
  3345. // Response to FEAT must be multiline, where leading and trailing line
  3346. // is "meaningless". See RFC 2389.
  3347. if ((FLastCode == 211) && (FLastResponse->Count > 2))
  3348. {
  3349. FLastResponse->Delete(0);
  3350. FLastResponse->Delete(FLastResponse->Count - 1);
  3351. FFeatures->Assign(FLastResponse);
  3352. }
  3353. }
  3354. //---------------------------------------------------------------------------
  3355. bool __fastcall TFTPFileSystem::HandleStatus(const wchar_t * AStatus, int Type)
  3356. {
  3357. TLogLineType LogType = (TLogLineType)-1;
  3358. UnicodeString Status(AStatus);
  3359. switch (Type)
  3360. {
  3361. case TFileZillaIntf::LOG_STATUS:
  3362. FTerminal->Information(Status, true);
  3363. LogType = llMessage;
  3364. break;
  3365. case TFileZillaIntf::LOG_COMMAND:
  3366. if (Status == L"SYST")
  3367. {
  3368. // not to trigger the assert in HandleReplyStatus,
  3369. // when SYST command is used by the user
  3370. FSystem = "";
  3371. FLastCommand = SYST;
  3372. }
  3373. else if (Status == L"FEAT")
  3374. {
  3375. FLastCommand = FEAT;
  3376. }
  3377. else if (Status.SubString(1, 5) == L"PASS ")
  3378. {
  3379. FLastCommand = PASS;
  3380. }
  3381. else
  3382. {
  3383. FLastCommand = CMD_UNKNOWN;
  3384. }
  3385. if (!FLoggedIn || (FTerminal->Configuration->ActualLogProtocol >= 0))
  3386. {
  3387. LogType = llInput;
  3388. }
  3389. break;
  3390. case TFileZillaIntf::LOG_ERROR:
  3391. case TFileZillaIntf::LOG_APIERROR:
  3392. case TFileZillaIntf::LOG_WARNING:
  3393. // when timeout message occurs, break loop waiting for response code
  3394. // by setting dummy one
  3395. if (Type == TFileZillaIntf::LOG_ERROR)
  3396. {
  3397. if (StartsStr(FTimeoutStatus, Status))
  3398. {
  3399. if (NoFinalLastCode())
  3400. {
  3401. SetLastCode(DummyTimeoutCode);
  3402. }
  3403. }
  3404. else if (Status == FDisconnectStatus)
  3405. {
  3406. if (NoFinalLastCode())
  3407. {
  3408. SetLastCode(DummyDisconnectCode);
  3409. }
  3410. }
  3411. }
  3412. // there can be multiple error messages associated with single failure
  3413. // (such as "cannot open local file..." followed by "download failed")
  3414. FLastError->Add(Status);
  3415. LogType = llMessage;
  3416. break;
  3417. case TFileZillaIntf::LOG_PROGRESS:
  3418. LogType = llMessage;
  3419. break;
  3420. case TFileZillaIntf::LOG_REPLY:
  3421. HandleReplyStatus(AStatus);
  3422. if (!FLoggedIn || (FTerminal->Configuration->ActualLogProtocol >= 0))
  3423. {
  3424. LogType = llOutput;
  3425. }
  3426. break;
  3427. case TFileZillaIntf::LOG_INFO:
  3428. LogType = llMessage;
  3429. break;
  3430. case TFileZillaIntf::LOG_DEBUG:
  3431. LogType = llMessage;
  3432. break;
  3433. default:
  3434. DebugFail();
  3435. break;
  3436. }
  3437. if (FTerminal->Log->Logging && (LogType != (TLogLineType)-1))
  3438. {
  3439. FTerminal->Log->Add(LogType, Status);
  3440. }
  3441. return true;
  3442. }
  3443. //---------------------------------------------------------------------------
  3444. TDateTime __fastcall TFTPFileSystem::ConvertLocalTimestamp(time_t Time)
  3445. {
  3446. // This reverses how FZAPI converts FILETIME to time_t,
  3447. // before passing it to FZ_ASYNCREQUEST_OVERWRITE.
  3448. __int64 Timestamp;
  3449. tm * Tm = localtime(&Time);
  3450. if (Tm != NULL)
  3451. {
  3452. SYSTEMTIME SystemTime;
  3453. SystemTime.wYear = static_cast<WORD>(Tm->tm_year + 1900);
  3454. SystemTime.wMonth = static_cast<WORD>(Tm->tm_mon + 1);
  3455. SystemTime.wDayOfWeek = 0;
  3456. SystemTime.wDay = static_cast<WORD>(Tm->tm_mday);
  3457. SystemTime.wHour = static_cast<WORD>(Tm->tm_hour);
  3458. SystemTime.wMinute = static_cast<WORD>(Tm->tm_min);
  3459. SystemTime.wSecond = static_cast<WORD>(Tm->tm_sec);
  3460. SystemTime.wMilliseconds = 0;
  3461. FILETIME LocalTime;
  3462. SystemTimeToFileTime(&SystemTime, &LocalTime);
  3463. FILETIME FileTime;
  3464. LocalFileTimeToFileTime(&LocalTime, &FileTime);
  3465. Timestamp = ConvertTimestampToUnixSafe(FileTime, dstmUnix);
  3466. }
  3467. else
  3468. {
  3469. // incorrect, but at least something
  3470. Timestamp = Time;
  3471. }
  3472. return UnixToDateTime(Timestamp, dstmUnix);
  3473. }
  3474. //---------------------------------------------------------------------------
  3475. bool __fastcall TFTPFileSystem::HandleAsynchRequestOverwrite(
  3476. wchar_t * FileName1, size_t FileName1Len, const wchar_t * FileName2,
  3477. const wchar_t * Path1, const wchar_t * Path2,
  3478. __int64 Size1, __int64 Size2, time_t LocalTime,
  3479. bool /*HasLocalTime*/, const TRemoteFileTime & RemoteTime, void * AUserData, int & RequestResult)
  3480. {
  3481. if (!FActive)
  3482. {
  3483. return false;
  3484. }
  3485. else
  3486. {
  3487. TFileTransferData & UserData = *((TFileTransferData *)AUserData);
  3488. if (UserData.OverwriteResult >= 0)
  3489. {
  3490. // on retry, use the same answer as on the first attempt
  3491. RequestResult = UserData.OverwriteResult;
  3492. }
  3493. else if ((UserData.CopyParam->OnTransferOut != NULL) || (UserData.CopyParam->OnTransferIn != NULL))
  3494. {
  3495. DebugFail();
  3496. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  3497. }
  3498. else
  3499. {
  3500. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  3501. UnicodeString TargetFileName = FileName1;
  3502. DebugAssert(UserData.FileName == TargetFileName);
  3503. UnicodeString SourceFullFileName = Path2;
  3504. UnicodeString TargetFullFileName = Path1;
  3505. if (OperationProgress->Side == osLocal)
  3506. {
  3507. SourceFullFileName = IncludeTrailingBackslash(SourceFullFileName);
  3508. TargetFullFileName = UnixIncludeTrailingBackslash(TargetFullFileName);
  3509. }
  3510. else
  3511. {
  3512. SourceFullFileName = UnixIncludeTrailingBackslash(SourceFullFileName);
  3513. TargetFullFileName = IncludeTrailingBackslash(TargetFullFileName);
  3514. }
  3515. SourceFullFileName += FileName2;
  3516. TargetFullFileName += FileName1;
  3517. TOverwriteMode OverwriteMode = omOverwrite;
  3518. TOverwriteFileParams FileParams;
  3519. bool NoFileParams =
  3520. (Size1 < 0) || (LocalTime == 0) ||
  3521. (Size2 < 0) || !RemoteTime.HasDate;
  3522. if (!NoFileParams)
  3523. {
  3524. FileParams.SourceSize = Size2;
  3525. FileParams.DestSize = Size1;
  3526. // Time is coming from LIST (not from MLSD or MDTM)
  3527. bool NeedApplyTimeDifference = !RemoteTime.Utc && DebugAlwaysTrue(!FFileZillaIntf->UsingMlsd());
  3528. if (OperationProgress->Side == osLocal)
  3529. {
  3530. FileParams.SourceTimestamp = ConvertLocalTimestamp(LocalTime);
  3531. RemoteFileTimeToDateTimeAndPrecision(RemoteTime, FileParams.DestTimestamp, FileParams.DestPrecision);
  3532. if (NeedApplyTimeDifference)
  3533. {
  3534. ApplyTimeDifference(TargetFullFileName, FileParams.DestTimestamp, FileParams.DestPrecision);
  3535. }
  3536. }
  3537. else
  3538. {
  3539. FileParams.DestTimestamp = ConvertLocalTimestamp(LocalTime);
  3540. RemoteFileTimeToDateTimeAndPrecision(RemoteTime, FileParams.SourceTimestamp, FileParams.SourcePrecision);
  3541. if (NeedApplyTimeDifference)
  3542. {
  3543. ApplyTimeDifference(SourceFullFileName, FileParams.SourceTimestamp, FileParams.SourcePrecision);
  3544. }
  3545. }
  3546. }
  3547. bool AllowResume = UserData.CopyParam->AllowResume(FileParams.SourceSize, UnicodeString());
  3548. bool AutoResume = UserData.AutoResume && AllowResume;
  3549. if (ConfirmOverwrite(SourceFullFileName, TargetFileName, OverwriteMode, OperationProgress,
  3550. (NoFileParams ? NULL : &FileParams), UserData.CopyParam, UserData.Params, AutoResume))
  3551. {
  3552. switch (OverwriteMode)
  3553. {
  3554. case omOverwrite:
  3555. if (TargetFileName != FileName1)
  3556. {
  3557. wcsncpy(FileName1, TargetFileName.c_str(), FileName1Len);
  3558. FileName1[FileName1Len - 1] = L'\0';
  3559. UserData.FileName = FileName1;
  3560. RequestResult = TFileZillaIntf::FILEEXISTS_RENAME;
  3561. }
  3562. else
  3563. {
  3564. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  3565. }
  3566. break;
  3567. case omResume:
  3568. RequestResult = TFileZillaIntf::FILEEXISTS_RESUME;
  3569. break;
  3570. case omComplete:
  3571. FTerminal->LogEvent(L"File transfer was completed before disconnect");
  3572. RequestResult = TFileZillaIntf::FILEEXISTS_COMPLETE;
  3573. break;
  3574. default:
  3575. DebugFail();
  3576. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  3577. break;
  3578. }
  3579. }
  3580. else
  3581. {
  3582. RequestResult = TFileZillaIntf::FILEEXISTS_SKIP;
  3583. }
  3584. }
  3585. // remember the answer for the retries
  3586. UserData.OverwriteResult = RequestResult;
  3587. if (RequestResult == TFileZillaIntf::FILEEXISTS_SKIP)
  3588. {
  3589. // when user chooses not to overwrite, break loop waiting for response code
  3590. // by setting dummy one, as FZAPI won't do anything then
  3591. SetLastCode(DummyTimeoutCode);
  3592. }
  3593. return true;
  3594. }
  3595. }
  3596. //---------------------------------------------------------------------------
  3597. UnicodeString __fastcall FormatContactList(UnicodeString Entry1, UnicodeString Entry2)
  3598. {
  3599. if (!Entry1.IsEmpty() && !Entry2.IsEmpty())
  3600. {
  3601. return FORMAT(L"%s, %s", (Entry1, Entry2));
  3602. }
  3603. else
  3604. {
  3605. return Entry1 + Entry2;
  3606. }
  3607. }
  3608. //---------------------------------------------------------------------------
  3609. UnicodeString __fastcall FormatContact(const TFtpsCertificateData::TContact & Contact)
  3610. {
  3611. UnicodeString Result =
  3612. FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 1),
  3613. (FormatContactList(FormatContactList(FormatContactList(
  3614. Contact.Organization, Contact.Unit), Contact.CommonName), Contact.Mail)));
  3615. if ((wcslen(Contact.Country) > 0) ||
  3616. (wcslen(Contact.StateProvince) > 0) ||
  3617. (wcslen(Contact.Town) > 0))
  3618. {
  3619. Result +=
  3620. FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 2),
  3621. (FormatContactList(FormatContactList(
  3622. Contact.Country, Contact.StateProvince), Contact.Town)));
  3623. }
  3624. if (wcslen(Contact.Other) > 0)
  3625. {
  3626. Result += FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 3), (Contact.Other));
  3627. }
  3628. return Result;
  3629. }
  3630. //---------------------------------------------------------------------------
  3631. UnicodeString __fastcall FormatValidityTime(const TFtpsCertificateData::TValidityTime & ValidityTime)
  3632. {
  3633. return FormatDateTime(L"ddddd tt",
  3634. EncodeDateVerbose(
  3635. (unsigned short)ValidityTime.Year, (unsigned short)ValidityTime.Month,
  3636. (unsigned short)ValidityTime.Day) +
  3637. EncodeTimeVerbose(
  3638. (unsigned short)ValidityTime.Hour, (unsigned short)ValidityTime.Min,
  3639. (unsigned short)ValidityTime.Sec, 0));
  3640. }
  3641. //---------------------------------------------------------------------------
  3642. bool __fastcall VerifyNameMask(UnicodeString Name, UnicodeString Mask)
  3643. {
  3644. bool Result = true;
  3645. int Pos;
  3646. while (Result && (Pos = Mask.Pos(L"*")) > 0)
  3647. {
  3648. // Pos will typically be 1 here, so not actual comparison is done
  3649. Result = SameText(Mask.SubString(1, Pos - 1), Name.SubString(1, Pos - 1));
  3650. if (Result)
  3651. {
  3652. Mask.Delete(1, Pos); // including *
  3653. Name.Delete(1, Pos - 1);
  3654. // remove everything until the next dot
  3655. Pos = Name.Pos(L".");
  3656. if (Pos == 0)
  3657. {
  3658. Pos = Name.Length() + 1;
  3659. }
  3660. Name.Delete(1, Pos - 1);
  3661. }
  3662. }
  3663. if (Result)
  3664. {
  3665. Result = SameText(Mask, Name);
  3666. }
  3667. return Result;
  3668. }
  3669. //---------------------------------------------------------------------------
  3670. bool __fastcall TFTPFileSystem::VerifyCertificateHostName(const TFtpsCertificateData & Data)
  3671. {
  3672. UnicodeString HostName = FTerminal->SessionData->HostNameExpanded;
  3673. UnicodeString CommonName = Data.Subject.CommonName;
  3674. bool NoMask = CommonName.IsEmpty();
  3675. bool Result = !NoMask && VerifyNameMask(HostName, CommonName);
  3676. if (Result)
  3677. {
  3678. FTerminal->LogEvent(FORMAT(L"Certificate common name \"%s\" matches hostname", (CommonName)));
  3679. }
  3680. else
  3681. {
  3682. if (!NoMask && (FTerminal->Configuration->ActualLogProtocol >= 1))
  3683. {
  3684. FTerminal->LogEvent(FORMAT(L"Certificate common name \"%s\" does not match hostname", (CommonName)));
  3685. }
  3686. UnicodeString SubjectAltName = Data.SubjectAltName;
  3687. while (!Result && !SubjectAltName.IsEmpty())
  3688. {
  3689. UnicodeString Entry = CutToChar(SubjectAltName, L',', true);
  3690. UnicodeString EntryName = CutToChar(Entry, L':', true);
  3691. if (SameText(EntryName, L"DNS"))
  3692. {
  3693. NoMask = false;
  3694. Result = VerifyNameMask(HostName, Entry);
  3695. if (Result)
  3696. {
  3697. FTerminal->LogEvent(FORMAT(L"Certificate subject alternative name \"%s\" matches hostname", (Entry)));
  3698. }
  3699. else
  3700. {
  3701. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  3702. {
  3703. FTerminal->LogEvent(FORMAT(L"Certificate subject alternative name \"%s\" does not match hostname", (Entry)));
  3704. }
  3705. }
  3706. }
  3707. }
  3708. }
  3709. if (!Result && NoMask)
  3710. {
  3711. FTerminal->LogEvent(L"Certificate has no common name nor subject alternative name, not verifying hostname");
  3712. Result = true;
  3713. }
  3714. return Result;
  3715. }
  3716. //---------------------------------------------------------------------------
  3717. static bool __fastcall IsIPAddress(const UnicodeString & HostName)
  3718. {
  3719. bool IPv4 = true;
  3720. bool IPv6 = true;
  3721. bool AnyColon = false;
  3722. for (int Index = 1; Index <= HostName.Length(); Index++)
  3723. {
  3724. wchar_t C = HostName[Index];
  3725. if (!IsDigit(C) && (C != L'.'))
  3726. {
  3727. IPv4 = false;
  3728. }
  3729. if (!IsHex(C) && (C != L':'))
  3730. {
  3731. IPv6 = false;
  3732. }
  3733. if (C == L':')
  3734. {
  3735. AnyColon = true;
  3736. }
  3737. }
  3738. return IPv4 || (IPv6 && AnyColon);
  3739. }
  3740. //---------------------------------------------------------------------------
  3741. bool __fastcall TFTPFileSystem::HandleAsynchRequestVerifyCertificate(
  3742. const TFtpsCertificateData & Data, int & RequestResult)
  3743. {
  3744. if (!FActive)
  3745. {
  3746. return false;
  3747. }
  3748. else
  3749. {
  3750. FSessionInfo.CertificateFingerprintSHA1 =
  3751. BytesToHex(RawByteString((const char*)Data.HashSha1, Data.HashSha1Len), false, L':');
  3752. FSessionInfo.CertificateFingerprintSHA256 =
  3753. BytesToHex(RawByteString((const char*)Data.HashSha256, Data.HashSha256Len), false, L':');
  3754. if (FTerminal->SessionData->FingerprintScan)
  3755. {
  3756. RequestResult = 0;
  3757. }
  3758. else
  3759. {
  3760. UnicodeString CertificateSubject = Data.Subject.Organization;
  3761. FTerminal->LogEvent(FORMAT(L"Verifying certificate for \"%s\" with fingerprint %s and %d failures", (CertificateSubject, FSessionInfo.CertificateFingerprintSHA256, Data.VerificationResult)));
  3762. bool Trusted = false;
  3763. bool TryWindowsSystemCertificateStore = false;
  3764. UnicodeString VerificationResultStr;
  3765. switch (Data.VerificationResult)
  3766. {
  3767. case X509_V_OK:
  3768. Trusted = true;
  3769. break;
  3770. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
  3771. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_GET_ISSUER_CERT);
  3772. TryWindowsSystemCertificateStore = true;
  3773. break;
  3774. case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
  3775. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE);
  3776. break;
  3777. case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
  3778. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY);
  3779. break;
  3780. case X509_V_ERR_CERT_SIGNATURE_FAILURE:
  3781. VerificationResultStr = LoadStr(CERT_ERR_CERT_SIGNATURE_FAILURE);
  3782. break;
  3783. case X509_V_ERR_CERT_NOT_YET_VALID:
  3784. VerificationResultStr = LoadStr(CERT_ERR_CERT_NOT_YET_VALID);
  3785. break;
  3786. case X509_V_ERR_CERT_HAS_EXPIRED:
  3787. VerificationResultStr = LoadStr(CERT_ERR_CERT_HAS_EXPIRED);
  3788. break;
  3789. case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
  3790. VerificationResultStr = LoadStr(CERT_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD);
  3791. break;
  3792. case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
  3793. VerificationResultStr = LoadStr(CERT_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD);
  3794. break;
  3795. case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
  3796. VerificationResultStr = LoadStr(CERT_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
  3797. TryWindowsSystemCertificateStore = true;
  3798. break;
  3799. case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
  3800. VerificationResultStr = LoadStr(CERT_ERR_SELF_SIGNED_CERT_IN_CHAIN);
  3801. TryWindowsSystemCertificateStore = true;
  3802. break;
  3803. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
  3804. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY);
  3805. TryWindowsSystemCertificateStore = true;
  3806. break;
  3807. case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
  3808. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
  3809. TryWindowsSystemCertificateStore = true;
  3810. break;
  3811. case X509_V_ERR_INVALID_CA:
  3812. VerificationResultStr = LoadStr(CERT_ERR_INVALID_CA);
  3813. break;
  3814. case X509_V_ERR_PATH_LENGTH_EXCEEDED:
  3815. VerificationResultStr = LoadStr(CERT_ERR_PATH_LENGTH_EXCEEDED);
  3816. break;
  3817. case X509_V_ERR_INVALID_PURPOSE:
  3818. VerificationResultStr = LoadStr(CERT_ERR_INVALID_PURPOSE);
  3819. break;
  3820. case X509_V_ERR_CERT_UNTRUSTED:
  3821. VerificationResultStr = LoadStr(CERT_ERR_CERT_UNTRUSTED);
  3822. TryWindowsSystemCertificateStore = true;
  3823. break;
  3824. case X509_V_ERR_CERT_REJECTED:
  3825. VerificationResultStr = LoadStr(CERT_ERR_CERT_REJECTED);
  3826. break;
  3827. case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
  3828. VerificationResultStr = LoadStr(CERT_ERR_KEYUSAGE_NO_CERTSIGN);
  3829. break;
  3830. case X509_V_ERR_CERT_CHAIN_TOO_LONG:
  3831. VerificationResultStr = LoadStr(CERT_ERR_CERT_CHAIN_TOO_LONG);
  3832. break;
  3833. default:
  3834. VerificationResultStr =
  3835. FORMAT(L"%s (%s)",
  3836. (LoadStr(CERT_ERR_UNKNOWN), X509_verify_cert_error_string(Data.VerificationResult)));
  3837. break;
  3838. }
  3839. bool IsHostNameIPAddress = IsIPAddress(FTerminal->SessionData->HostNameExpanded);
  3840. bool CertificateHostNameVerified = !IsHostNameIPAddress && VerifyCertificateHostName(Data);
  3841. bool VerificationResult = Trusted;
  3842. if (IsHostNameIPAddress || !CertificateHostNameVerified)
  3843. {
  3844. VerificationResult = false;
  3845. TryWindowsSystemCertificateStore = false;
  3846. }
  3847. if (!VerificationResult)
  3848. {
  3849. if (FTerminal->VerifyCertificate(FtpsCertificateStorageKey, FTerminal->SessionData->SiteKey,
  3850. FSessionInfo.CertificateFingerprintSHA1, FSessionInfo.CertificateFingerprintSHA256,
  3851. CertificateSubject, Data.VerificationResult))
  3852. {
  3853. // certificate is trusted, but for not purposes of info dialog
  3854. VerificationResult = true;
  3855. FSessionInfo.CertificateVerifiedManually = true;
  3856. }
  3857. }
  3858. // TryWindowsSystemCertificateStore is set for the same set of failures
  3859. // as trigger NE_SSL_UNTRUSTED flag in ne_openssl.c's verify_callback().
  3860. // Use WindowsValidateCertificate only as a last resort (after checking the cached fiungerprint)
  3861. // as it can take a very long time (up to 1 minute).
  3862. if (!VerificationResult && TryWindowsSystemCertificateStore)
  3863. {
  3864. UnicodeString WindowsCertificateError;
  3865. if (WindowsValidateCertificate(Data.Certificate, Data.CertificateLen, WindowsCertificateError))
  3866. {
  3867. FTerminal->LogEvent(L"Certificate verified against Windows certificate store");
  3868. VerificationResult = true;
  3869. // certificate is trusted for all purposes
  3870. Trusted = true;
  3871. }
  3872. else
  3873. {
  3874. FTerminal->LogEvent(
  3875. FORMAT(L"Certificate failed to verify against Windows certificate store: %s", (DefaultStr(WindowsCertificateError, L"no details"))));
  3876. }
  3877. }
  3878. const UnicodeString SummarySeparator = L"\n\n";
  3879. UnicodeString Summary;
  3880. // even if the fingerprint is cached, the certificate is still not trusted for a purposes of the info dialog.
  3881. if (!Trusted)
  3882. {
  3883. AddToList(Summary, VerificationResultStr + L" " + FMTLOAD(CERT_ERRDEPTH, (Data.VerificationDepth + 1)), SummarySeparator);
  3884. }
  3885. if (IsHostNameIPAddress)
  3886. {
  3887. AddToList(Summary, FMTLOAD(CERT_IP_CANNOT_VERIFY, (FTerminal->SessionData->HostNameExpanded)), SummarySeparator);
  3888. }
  3889. else if (!CertificateHostNameVerified)
  3890. {
  3891. AddToList(Summary, FMTLOAD(CERT_NAME_MISMATCH, (FTerminal->SessionData->HostNameExpanded)), SummarySeparator);
  3892. }
  3893. if (Summary.IsEmpty())
  3894. {
  3895. Summary = LoadStr(CERT_OK);
  3896. }
  3897. FSessionInfo.Certificate =
  3898. FMTLOAD(CERT_TEXT2, (
  3899. FormatContact(Data.Issuer),
  3900. FormatContact(Data.Subject),
  3901. FormatValidityTime(Data.ValidFrom),
  3902. FormatValidityTime(Data.ValidUntil),
  3903. FSessionInfo.CertificateFingerprintSHA256,
  3904. FSessionInfo.CertificateFingerprintSHA1,
  3905. Summary));
  3906. RequestResult = VerificationResult ? 1 : 0;
  3907. if (RequestResult == 0)
  3908. {
  3909. if (FTerminal->ConfirmCertificate(FSessionInfo, Data.VerificationResult, FtpsCertificateStorageKey, true))
  3910. {
  3911. // FZ's VerifyCertDlg.cpp returns 2 for "cached", what we do nto distinguish here,
  3912. // however FZAPI takes all non-zero values equally.
  3913. RequestResult = 1;
  3914. FSessionInfo.CertificateVerifiedManually = true;
  3915. }
  3916. }
  3917. }
  3918. return true;
  3919. }
  3920. }
  3921. //---------------------------------------------------------------------------
  3922. bool __fastcall TFTPFileSystem::HandleAsynchRequestNeedPass(
  3923. struct TNeedPassRequestData & Data, int & RequestResult)
  3924. {
  3925. if (!FActive)
  3926. {
  3927. return false;
  3928. }
  3929. else
  3930. {
  3931. UnicodeString Password;
  3932. if (FCertificate != NULL)
  3933. {
  3934. FTerminal->LogEvent(L"Server asked for password, but we are using certificate, and no password was specified upfront, using fake password");
  3935. Password = L"USINGCERT";
  3936. RequestResult = TFileZillaIntf::REPLY_OK;
  3937. }
  3938. else
  3939. {
  3940. if (FTerminal->PromptUser(FTerminal->SessionData, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  3941. LoadStr(PASSWORD_PROMPT), false, 0, Password))
  3942. {
  3943. RequestResult = TFileZillaIntf::REPLY_OK;
  3944. }
  3945. else
  3946. {
  3947. RequestResult = TFileZillaIntf::REPLY_ABORTED;
  3948. }
  3949. }
  3950. // When returning REPLY_OK, we need to return an allocated password,
  3951. // even if we were returning and empty string we got on input.
  3952. if (RequestResult == TFileZillaIntf::REPLY_OK)
  3953. {
  3954. Data.Password = _wcsdup(Password.c_str());
  3955. }
  3956. return true;
  3957. }
  3958. }
  3959. //---------------------------------------------------------------------------
  3960. void __fastcall TFTPFileSystem::RemoteFileTimeToDateTimeAndPrecision(const TRemoteFileTime & Source, TDateTime & DateTime, TModificationFmt & ModificationFmt)
  3961. {
  3962. // ModificationFmt must be set after Modification
  3963. if (Source.HasDate)
  3964. {
  3965. DateTime =
  3966. EncodeDateVerbose((unsigned short)Source.Year, (unsigned short)Source.Month,
  3967. (unsigned short)Source.Day);
  3968. if (Source.HasTime)
  3969. {
  3970. DateTime = DateTime +
  3971. EncodeTimeVerbose((unsigned short)Source.Hour, (unsigned short)Source.Minute,
  3972. (unsigned short)Source.Second, 0);
  3973. ModificationFmt = Source.HasSeconds ? mfFull : (Source.HasYear ? mfYMDHM : mfMDHM);
  3974. // With IIS, the Utc should be false only for MDTM
  3975. if (FWindowsServer && !Source.Utc)
  3976. {
  3977. DateTime -= DSTDifferenceForTime(DateTime);
  3978. }
  3979. }
  3980. else
  3981. {
  3982. ModificationFmt = mfMDY;
  3983. }
  3984. if (Source.Utc)
  3985. {
  3986. DateTime = ConvertTimestampFromUTC(DateTime);
  3987. }
  3988. }
  3989. else
  3990. {
  3991. // With SCP we estimate date to be today, if we have at least time
  3992. DateTime = double(0);
  3993. ModificationFmt = mfNone;
  3994. }
  3995. }
  3996. //---------------------------------------------------------------------------
  3997. bool __fastcall TFTPFileSystem::HandleListData(const wchar_t * Path,
  3998. const TListDataEntry * Entries, unsigned int Count)
  3999. {
  4000. if (!FActive)
  4001. {
  4002. return false;
  4003. }
  4004. else if (FIgnoreFileList)
  4005. {
  4006. // directory listing provided implicitly by FZAPI during certain operations is ignored
  4007. DebugAssert(FFileList == NULL);
  4008. return false;
  4009. }
  4010. else
  4011. {
  4012. DebugAssert(FFileList != NULL);
  4013. DebugUsedParam(Path);
  4014. for (unsigned int Index = 0; Index < Count; Index++)
  4015. {
  4016. const TListDataEntry * Entry = &Entries[Index];
  4017. std::unique_ptr<TRemoteFile> File(new TRemoteFile());
  4018. try
  4019. {
  4020. File->Terminal = FTerminal;
  4021. File->FileName = Entry->Name;
  4022. try
  4023. {
  4024. int PermissionsLen = wcslen(Entry->Permissions);
  4025. if (PermissionsLen >= 10)
  4026. {
  4027. File->Rights->Text = Entry->Permissions + 1;
  4028. }
  4029. else if ((PermissionsLen == 3) || (PermissionsLen == 4))
  4030. {
  4031. File->Rights->Octal = Entry->Permissions;
  4032. }
  4033. }
  4034. catch(...)
  4035. {
  4036. // ignore permissions errors with FTP
  4037. }
  4038. File->HumanRights = Entry->HumanPerm;
  4039. // deprecated, to be replaced with Owner/Group
  4040. if (wcslen(Entry->OwnerGroup) > 0)
  4041. {
  4042. const wchar_t * Space = wcschr(Entry->OwnerGroup, L' ');
  4043. if (Space != NULL)
  4044. {
  4045. File->Owner.Name = UnicodeString(Entry->OwnerGroup, Space - Entry->OwnerGroup);
  4046. File->Group.Name = Space + 1;
  4047. }
  4048. else
  4049. {
  4050. File->Owner.Name = Entry->OwnerGroup;
  4051. }
  4052. }
  4053. else
  4054. {
  4055. File->Owner.Name = Entry->Owner;
  4056. File->Group.Name = Entry->Group;
  4057. }
  4058. File->Size = Entry->Size;
  4059. if (Entry->Link)
  4060. {
  4061. File->Type = FILETYPE_SYMLINK;
  4062. }
  4063. else if (Entry->Dir)
  4064. {
  4065. File->Type = FILETYPE_DIRECTORY;
  4066. }
  4067. else
  4068. {
  4069. File->Type = FILETYPE_DEFAULT;
  4070. }
  4071. TDateTime Modification;
  4072. TModificationFmt ModificationFmt;
  4073. RemoteFileTimeToDateTimeAndPrecision(Entry->Time, Modification, ModificationFmt);
  4074. File->Modification = Modification;
  4075. File->ModificationFmt = ModificationFmt;
  4076. File->LastAccess = File->Modification;
  4077. File->LinkTo = Entry->LinkTarget;
  4078. File->Complete();
  4079. }
  4080. catch (Exception & E)
  4081. {
  4082. UnicodeString EntryData =
  4083. FORMAT(L"%s/%s/%s/%s/%s/%s/%s/%d/%d/%d/%d/%d/%d/%d/%d/%d/%d/%d",
  4084. (Entry->Name, Entry->Permissions, Entry->HumanPerm, Entry->Owner, Entry->Group, Entry->OwnerGroup, IntToStr(Entry->Size),
  4085. int(Entry->Dir), int(Entry->Link), Entry->Time.Year, Entry->Time.Month, Entry->Time.Day,
  4086. Entry->Time.Hour, Entry->Time.Minute, int(Entry->Time.HasTime),
  4087. int(Entry->Time.HasYear), int(Entry->Time.HasSeconds), int(Entry->Time.HasDate)));
  4088. throw ETerminal(&E, FMTLOAD(LIST_LINE_ERROR, (EntryData)), HELP_LIST_LINE_ERROR);
  4089. }
  4090. if (FTerminal->IsValidFile(File.get()))
  4091. {
  4092. FFileList->AddFile(File.release());
  4093. }
  4094. }
  4095. return true;
  4096. }
  4097. }
  4098. //---------------------------------------------------------------------------
  4099. bool __fastcall TFTPFileSystem::HandleTransferStatus(bool Valid, __int64 TransferSize,
  4100. __int64 Bytes, bool FileTransfer)
  4101. {
  4102. if (!FActive)
  4103. {
  4104. return false;
  4105. }
  4106. else if (!Valid)
  4107. {
  4108. }
  4109. else if (FileTransfer)
  4110. {
  4111. FileTransferProgress(TransferSize, Bytes);
  4112. }
  4113. else
  4114. {
  4115. ReadDirectoryProgress(Bytes);
  4116. }
  4117. return true;
  4118. }
  4119. //---------------------------------------------------------------------------
  4120. bool __fastcall TFTPFileSystem::HandleReply(int Command, unsigned int Reply)
  4121. {
  4122. if (!FActive)
  4123. {
  4124. return false;
  4125. }
  4126. else
  4127. {
  4128. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  4129. {
  4130. FTerminal->LogEvent(FORMAT(L"Got reply %x to the command %d", (int(Reply), Command)));
  4131. }
  4132. // reply with Command 0 is not associated with current operation
  4133. // so do not treat is as a reply
  4134. // (it is typically used asynchronously to notify about disconnects)
  4135. if (Command != 0)
  4136. {
  4137. DebugAssert(FCommandReply == 0);
  4138. FCommandReply = Reply;
  4139. }
  4140. else
  4141. {
  4142. DebugAssert(FReply == 0);
  4143. FReply = Reply;
  4144. }
  4145. return true;
  4146. }
  4147. }
  4148. //---------------------------------------------------------------------------
  4149. bool __fastcall TFTPFileSystem::HandleCapabilities(
  4150. TFTPServerCapabilities * ServerCapabilities)
  4151. {
  4152. FServerCapabilities->Assign(ServerCapabilities);
  4153. FFileSystemInfoValid = false;
  4154. return true;
  4155. }
  4156. //---------------------------------------------------------------------------
  4157. bool __fastcall TFTPFileSystem::CheckError(int ReturnCode, const wchar_t * Context)
  4158. {
  4159. // we do not expect any FZAPI call to fail as it generally can fail only due to:
  4160. // - invalid parameters
  4161. // - busy FZAPI core
  4162. // the only exception is REPLY_NOTCONNECTED that can happen if
  4163. // connection is closed just between the last call to Idle()
  4164. // and call to any FZAPI command
  4165. // in such case reply without associated command is posted,
  4166. // which we are going to wait for unless we are already waiting
  4167. // on higher level (this typically happens if connection is lost while
  4168. // waiting for user interaction and is detected within call to
  4169. // SetAsyncRequestResult)
  4170. if (FLAGSET(ReturnCode, TFileZillaIntf::REPLY_NOTCONNECTED))
  4171. {
  4172. if (!FWaitingForReply)
  4173. {
  4174. // throws
  4175. WaitForFatalNonCommandReply();
  4176. }
  4177. }
  4178. else
  4179. {
  4180. FTerminal->FatalError(NULL,
  4181. FMTLOAD(INTERNAL_ERROR, (FORMAT(L"fz#%s", (Context)), IntToHex(ReturnCode, 4))));
  4182. DebugFail();
  4183. }
  4184. return false;
  4185. }
  4186. //---------------------------------------------------------------------------
  4187. bool __fastcall TFTPFileSystem::Unquote(UnicodeString & Str)
  4188. {
  4189. enum
  4190. {
  4191. INIT,
  4192. QUOTE,
  4193. QUOTED,
  4194. DONE
  4195. } State;
  4196. State = INIT;
  4197. DebugAssert((Str.Length() > 0) && ((Str[1] == L'"') || (Str[1] == L'\'')));
  4198. int Index = 1;
  4199. wchar_t Quote;
  4200. while (Index <= Str.Length())
  4201. {
  4202. switch (State)
  4203. {
  4204. case INIT:
  4205. if ((Str[Index] == L'"') || (Str[Index] == L'\''))
  4206. {
  4207. Quote = Str[Index];
  4208. State = QUOTED;
  4209. Str.Delete(Index, 1);
  4210. }
  4211. else
  4212. {
  4213. DebugFail();
  4214. // no quoted string
  4215. Str.SetLength(0);
  4216. }
  4217. break;
  4218. case QUOTED:
  4219. if (Str[Index] == Quote)
  4220. {
  4221. State = QUOTE;
  4222. Str.Delete(Index, 1);
  4223. }
  4224. else
  4225. {
  4226. Index++;
  4227. }
  4228. break;
  4229. case QUOTE:
  4230. if (Str[Index] == Quote)
  4231. {
  4232. Index++;
  4233. }
  4234. else
  4235. {
  4236. // end of quoted string, trim the rest
  4237. Str.SetLength(Index - 1);
  4238. State = DONE;
  4239. }
  4240. break;
  4241. }
  4242. }
  4243. return (State == DONE);
  4244. }
  4245. //---------------------------------------------------------------------------
  4246. void __fastcall TFTPFileSystem::PreserveDownloadFileTime(HANDLE Handle, void * UserData)
  4247. {
  4248. TFileTransferData * Data = static_cast<TFileTransferData *>(UserData);
  4249. DebugAssert(Data->CopyParam->OnTransferOut == NULL);
  4250. FTerminal->UpdateTargetTime(Handle, Data->Modification, dstmUnix);
  4251. }
  4252. //---------------------------------------------------------------------------
  4253. bool __fastcall TFTPFileSystem::GetFileModificationTimeInUtc(const wchar_t * FileName, struct tm & Time)
  4254. {
  4255. bool Result;
  4256. try
  4257. {
  4258. // error-handling-free and DST-mode-inaware copy of TTerminal::OpenLocalFile
  4259. HANDLE Handle = CreateFile(ApiPath(FileName).c_str(), GENERIC_READ,
  4260. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
  4261. if (Handle == INVALID_HANDLE_VALUE)
  4262. {
  4263. Result = false;
  4264. }
  4265. else
  4266. {
  4267. FILETIME MTime;
  4268. if (!GetFileTime(Handle, NULL, NULL, &MTime))
  4269. {
  4270. Result = false;
  4271. }
  4272. else
  4273. {
  4274. TDateTime Modification = ConvertTimestampToUTC(FileTimeToDateTime(MTime));
  4275. unsigned short Year;
  4276. unsigned short Month;
  4277. unsigned short Day;
  4278. Modification.DecodeDate(&Year, &Month, &Day);
  4279. Time.tm_year = Year - 1900;
  4280. Time.tm_mon = Month - 1;
  4281. Time.tm_mday = Day;
  4282. unsigned short Hour;
  4283. unsigned short Min;
  4284. unsigned short Sec;
  4285. unsigned short MSec;
  4286. Modification.DecodeTime(&Hour, &Min, &Sec, &MSec);
  4287. Time.tm_hour = Hour;
  4288. Time.tm_min = Min;
  4289. Time.tm_sec = Sec;
  4290. Result = true;
  4291. }
  4292. CloseHandle(Handle);
  4293. }
  4294. }
  4295. catch (...)
  4296. {
  4297. Result = false;
  4298. }
  4299. return Result;
  4300. }
  4301. //---------------------------------------------------------------------------
  4302. void __fastcall TFTPFileSystem::RegisterChecksumAlgCommand(const UnicodeString & Alg, const UnicodeString & Command)
  4303. {
  4304. FChecksumAlgs->Add(Alg);
  4305. FChecksumCommands->Add(Command);
  4306. }
  4307. //---------------------------------------------------------------------------
  4308. void __fastcall TFTPFileSystem::GetSupportedChecksumAlgs(TStrings * Algs)
  4309. {
  4310. for (int Index = 0; Index < FHashAlgs->Count; Index++)
  4311. {
  4312. Algs->Add(FHashAlgs->Strings[Index]);
  4313. }
  4314. for (int Index = 0; Index < FChecksumAlgs->Count; Index++)
  4315. {
  4316. UnicodeString Alg = FChecksumAlgs->Strings[Index];
  4317. UnicodeString Command = FChecksumCommands->Strings[Index];
  4318. if (SupportsCommand(Command) && (Algs->IndexOf(Alg) < 0))
  4319. {
  4320. Algs->Add(Alg);
  4321. }
  4322. }
  4323. }
  4324. //---------------------------------------------------------------------------
  4325. bool __fastcall TFTPFileSystem::SupportsSiteCommand(const UnicodeString & Command) const
  4326. {
  4327. return (FSupportedSiteCommands->IndexOf(Command) >= 0);
  4328. }
  4329. //---------------------------------------------------------------------------
  4330. bool __fastcall TFTPFileSystem::SupportsCommand(const UnicodeString & Command) const
  4331. {
  4332. return (FSupportedCommands->IndexOf(Command) >= 0);
  4333. }
  4334. //---------------------------------------------------------------------------
  4335. void __fastcall TFTPFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  4336. {
  4337. DebugFail();
  4338. }
  4339. //---------------------------------------------------------------------------
  4340. void __fastcall TFTPFileSystem::UnlockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  4341. {
  4342. DebugFail();
  4343. }
  4344. //---------------------------------------------------------------------------
  4345. void __fastcall TFTPFileSystem::UpdateFromMain(TCustomFileSystem * /*MainFileSystem*/)
  4346. {
  4347. // noop
  4348. }
  4349. //---------------------------------------------------------------------------
  4350. void __fastcall TFTPFileSystem::ClearCaches()
  4351. {
  4352. // noop
  4353. }
  4354. //---------------------------------------------------------------------------
  4355. UnicodeString __fastcall GetOpenSSLVersionText()
  4356. {
  4357. return OPENSSL_VERSION_TEXT;
  4358. }
  4359. //---------------------------------------------------------------------------