FtpFileSystem.cpp 156 KB

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