FtpFileSystem.cpp 153 KB

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