FtpFileSystem.cpp 153 KB

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