FtpFileSystem.cpp 124 KB

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