FtpFileSystem.cpp 149 KB

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