FtpFileSystem.cpp 152 KB

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