FtpFileSystem.cpp 140 KB

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