FtpFileSystem.cpp 149 KB

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