FtpFileSystem.cpp 149 KB

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