FtpFileSystem.cpp 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #ifndef NO_FILEZILLA
  5. //---------------------------------------------------------------------------
  6. #include <list>
  7. #include "FtpFileSystem.h"
  8. #include "FileZillaIntf.h"
  9. #include "Common.h"
  10. #include "Exceptions.h"
  11. #include "Terminal.h"
  12. #include "TextsCore.h"
  13. #include "TextsFileZilla.h"
  14. #include "HelpCore.h"
  15. #define OPENSSL_NO_EC
  16. #define OPENSSL_NO_ECDSA
  17. #define OPENSSL_NO_ECDH
  18. #include <openssl/x509_vfy.h>
  19. //---------------------------------------------------------------------------
  20. #pragma package(smart_init)
  21. //---------------------------------------------------------------------------
  22. #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
  23. FILE_OPERATION_LOOP_CUSTOM(FTerminal, ALLOW_SKIP, MESSAGE, OPERATION)
  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 char * __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 char * Status, int Type);
  39. virtual bool __fastcall HandleAsynchRequestOverwrite(
  40. char * FileName1, size_t FileName1Len, const char * FileName2,
  41. const char * Path1, const char * Path2,
  42. __int64 Size1, __int64 Size2, time_t Time1, time_t Time2,
  43. bool HasTime1, bool HasTime2, void * UserData, int & RequestResult);
  44. virtual bool __fastcall HandleAsynchRequestVerifyCertificate(
  45. const TFtpsCertificateData & Data, int & RequestResult);
  46. virtual bool __fastcall HandleListData(const char * Path, const TListDataEntry * Entries,
  47. unsigned int Count);
  48. virtual bool __fastcall HandleTransferStatus(bool Valid, __int64 TransferSize,
  49. __int64 Bytes, int Percent, int TimeElapsed, int TimeLeft, int TransferRate,
  50. bool FileTransfer);
  51. virtual bool __fastcall HandleReply(int Command, unsigned int Reply);
  52. virtual bool __fastcall HandleCapabilities(bool Mfmt);
  53. virtual bool __fastcall CheckError(int ReturnCode, const char * Context);
  54. private:
  55. TFTPFileSystem * FFileSystem;
  56. };
  57. //---------------------------------------------------------------------------
  58. __fastcall TFileZillaImpl::TFileZillaImpl(TFTPFileSystem * FileSystem) :
  59. TFileZillaIntf(),
  60. FFileSystem(FileSystem)
  61. {
  62. }
  63. //---------------------------------------------------------------------------
  64. const char * __fastcall TFileZillaImpl::Option(int OptionID) const
  65. {
  66. return FFileSystem->GetOption(OptionID);
  67. }
  68. //---------------------------------------------------------------------------
  69. int __fastcall TFileZillaImpl::OptionVal(int OptionID) const
  70. {
  71. return FFileSystem->GetOptionVal(OptionID);
  72. }
  73. //---------------------------------------------------------------------------
  74. bool __fastcall TFileZillaImpl::DoPostMessage(TMessageType Type, WPARAM wParam, LPARAM lParam)
  75. {
  76. return FFileSystem->PostMessage(Type, wParam, lParam);
  77. }
  78. //---------------------------------------------------------------------------
  79. bool __fastcall TFileZillaImpl::HandleStatus(const char * Status, int Type)
  80. {
  81. return FFileSystem->HandleStatus(Status, Type);
  82. }
  83. //---------------------------------------------------------------------------
  84. bool __fastcall TFileZillaImpl::HandleAsynchRequestOverwrite(
  85. char * FileName1, size_t FileName1Len, const char * FileName2,
  86. const char * Path1, const char * Path2,
  87. __int64 Size1, __int64 Size2, time_t Time1, time_t Time2,
  88. bool HasTime1, bool HasTime2, void * UserData, int & RequestResult)
  89. {
  90. return FFileSystem->HandleAsynchRequestOverwrite(
  91. FileName1, FileName1Len, FileName2, Path1, Path2, Size1, Size2, Time1, Time2,
  92. HasTime1, HasTime2, UserData, RequestResult);
  93. }
  94. //---------------------------------------------------------------------------
  95. bool __fastcall TFileZillaImpl::HandleAsynchRequestVerifyCertificate(
  96. const TFtpsCertificateData & Data, int & RequestResult)
  97. {
  98. return FFileSystem->HandleAsynchRequestVerifyCertificate(Data, RequestResult);
  99. }
  100. //---------------------------------------------------------------------------
  101. bool __fastcall TFileZillaImpl::HandleListData(const char * Path,
  102. const TListDataEntry * Entries, unsigned int Count)
  103. {
  104. return FFileSystem->HandleListData(Path, Entries, Count);
  105. }
  106. //---------------------------------------------------------------------------
  107. bool __fastcall TFileZillaImpl::HandleTransferStatus(bool Valid, __int64 TransferSize,
  108. __int64 Bytes, int Percent, int TimeElapsed, int TimeLeft, int TransferRate,
  109. bool FileTransfer)
  110. {
  111. return FFileSystem->HandleTransferStatus(Valid, TransferSize, Bytes, Percent,
  112. TimeElapsed, TimeLeft, TransferRate, FileTransfer);
  113. }
  114. //---------------------------------------------------------------------------
  115. bool __fastcall TFileZillaImpl::HandleReply(int Command, unsigned int Reply)
  116. {
  117. return FFileSystem->HandleReply(Command, Reply);
  118. }
  119. //---------------------------------------------------------------------------
  120. bool __fastcall TFileZillaImpl::HandleCapabilities(bool Mfmt)
  121. {
  122. return FFileSystem->HandleCapabilities(Mfmt);
  123. }
  124. //---------------------------------------------------------------------------
  125. bool __fastcall TFileZillaImpl::CheckError(int ReturnCode, const char * Context)
  126. {
  127. return FFileSystem->CheckError(ReturnCode, Context);
  128. }
  129. //---------------------------------------------------------------------------
  130. //---------------------------------------------------------------------------
  131. class TMessageQueue : public std::list<std::pair<WPARAM, LPARAM> >
  132. {
  133. };
  134. //---------------------------------------------------------------------------
  135. //---------------------------------------------------------------------------
  136. struct TFileTransferData
  137. {
  138. TFileTransferData()
  139. {
  140. Params = 0;
  141. AutoResume = false;
  142. OverwriteResult = -1;
  143. CopyParam = NULL;
  144. }
  145. AnsiString FileName;
  146. int Params;
  147. bool AutoResume;
  148. int OverwriteResult;
  149. const TCopyParamType * CopyParam;
  150. };
  151. //---------------------------------------------------------------------------
  152. const int tfFirstLevel = 0x01;
  153. const int tfAutoResume = 0x02;
  154. const char CertificateStorageKey[] = "FtpsCertificates";
  155. //---------------------------------------------------------------------------
  156. struct TSinkFileParams
  157. {
  158. AnsiString TargetDir;
  159. const TCopyParamType * CopyParam;
  160. int Params;
  161. TFileOperationProgressType * OperationProgress;
  162. bool Skipped;
  163. unsigned int Flags;
  164. };
  165. //---------------------------------------------------------------------------
  166. class TFileListHelper
  167. {
  168. public:
  169. TFileListHelper(TFTPFileSystem * FileSystem, TRemoteFileList * FileList,
  170. bool IgnoreFileList) :
  171. FFileSystem(FileSystem),
  172. FFileList(FFileSystem->FFileList),
  173. FIgnoreFileList(FFileSystem->FIgnoreFileList)
  174. {
  175. FFileSystem->FFileList = FileList;
  176. FFileSystem->FIgnoreFileList = IgnoreFileList;
  177. }
  178. ~TFileListHelper()
  179. {
  180. FFileSystem->FFileList = FFileList;
  181. FFileSystem->FIgnoreFileList = FIgnoreFileList;
  182. }
  183. private:
  184. TFTPFileSystem * FFileSystem;
  185. TRemoteFileList * FFileList;
  186. bool FIgnoreFileList;
  187. };
  188. //---------------------------------------------------------------------------
  189. __fastcall TFTPFileSystem::TFTPFileSystem(TTerminal * ATerminal):
  190. TCustomFileSystem(ATerminal),
  191. FFileZillaIntf(NULL),
  192. FQueueCriticalSection(new TCriticalSection),
  193. FTransferStatusCriticalSection(new TCriticalSection),
  194. FQueueEvent(CreateEvent(NULL, true, false, NULL)),
  195. FQueue(new TMessageQueue),
  196. FReply(0),
  197. FCommandReply(0),
  198. FLastCommand(CMD_UNKNOWN),
  199. FLastResponse(new TStringList()),
  200. FLastError(new TStringList()),
  201. FFeatures(new TStringList()),
  202. FFileList(NULL),
  203. FFileListCache(NULL),
  204. FActive(false),
  205. FWaitingForReply(false),
  206. FIgnoreFileList(false),
  207. FOnCaptureOutput(NULL),
  208. FFileSystemInfoValid(false),
  209. FDoListAll(false),
  210. FMfmt(false)
  211. {
  212. ResetReply();
  213. FListAll = FTerminal->SessionData->FtpListAll;
  214. FFileSystemInfo.ProtocolBaseName = "FTP";
  215. FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
  216. FTimeoutStatus = LoadStr(IDS_ERRORMSG_TIMEOUT);
  217. FDisconnectStatus = LoadStr(IDS_STATUSMSG_DISCONNECTED);
  218. }
  219. //---------------------------------------------------------------------------
  220. __fastcall TFTPFileSystem::~TFTPFileSystem()
  221. {
  222. assert(FFileList == NULL);
  223. FFileZillaIntf->Destroying();
  224. // to release memory associated with the messages
  225. DiscardMessages();
  226. delete FFileZillaIntf;
  227. FFileZillaIntf = NULL;
  228. delete FQueue;
  229. FQueue = NULL;
  230. CloseHandle(FQueueEvent);
  231. delete FQueueCriticalSection;
  232. FQueueCriticalSection = NULL;
  233. delete FTransferStatusCriticalSection;
  234. FTransferStatusCriticalSection = NULL;
  235. delete FLastResponse;
  236. FLastResponse = NULL;
  237. delete FLastError;
  238. FLastError = NULL;
  239. delete FFeatures;
  240. FFeatures = NULL;
  241. ResetCaches();
  242. }
  243. //---------------------------------------------------------------------------
  244. void __fastcall TFTPFileSystem::Open()
  245. {
  246. // on reconnect, typically there may be pending status messages from previous session
  247. DiscardMessages();
  248. ResetCaches();
  249. FCurrentDirectory = "";
  250. FHomeDirectory = "";
  251. TSessionData * Data = FTerminal->SessionData;
  252. FSessionInfo.LoginTime = Now();
  253. FSessionInfo.ProtocolBaseName = "FTP";
  254. FSessionInfo.ProtocolName = FSessionInfo.ProtocolBaseName;
  255. switch (Data->Ftps)
  256. {
  257. case ftpsImplicit:
  258. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_IMPLICIT);
  259. break;
  260. case ftpsExplicitSsl:
  261. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_EXPLICIT_SSL);
  262. break;
  263. case ftpsExplicitTls:
  264. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_EXPLICIT_TLS);
  265. break;
  266. }
  267. FLastDataSent = Now();
  268. FMultineResponse = false;
  269. // initialize FZAPI on the first connect only
  270. if (FFileZillaIntf == NULL)
  271. {
  272. FFileZillaIntf = new TFileZillaImpl(this);
  273. try
  274. {
  275. TFileZillaIntf::TLogLevel LogLevel;
  276. switch (FTerminal->Configuration->ActualLogProtocol)
  277. {
  278. default:
  279. case 0:
  280. case 1:
  281. LogLevel = TFileZillaIntf::LOG_WARNING;
  282. break;
  283. case 2:
  284. LogLevel = TFileZillaIntf::LOG_INFO;
  285. break;
  286. }
  287. FFileZillaIntf->SetDebugLevel(LogLevel);
  288. FFileZillaIntf->Init();
  289. }
  290. catch(...)
  291. {
  292. delete FFileZillaIntf;
  293. FFileZillaIntf = NULL;
  294. throw;
  295. }
  296. }
  297. AnsiString HostName = Data->HostName;
  298. AnsiString UserName = Data->UserName;
  299. AnsiString Password = Data->Password;
  300. AnsiString Account = Data->FtpAccount;
  301. AnsiString Path = Data->RemoteDirectory;
  302. int ServerType;
  303. switch (Data->Ftps)
  304. {
  305. case ftpsImplicit:
  306. ServerType = TFileZillaIntf::SERVER_FTP_SSL_IMPLICIT;
  307. break;
  308. case ftpsExplicitSsl:
  309. ServerType = TFileZillaIntf::SERVER_FTP_SSL_EXPLICIT;
  310. break;
  311. case ftpsExplicitTls:
  312. ServerType = TFileZillaIntf::SERVER_FTP_TLS_EXPLICIT;
  313. break;
  314. default:
  315. assert(Data->Ftps == ftpsNone);
  316. ServerType = TFileZillaIntf::SERVER_FTP;
  317. break;
  318. }
  319. int Pasv = (Data->FtpPasvMode ? 1 : 2);
  320. int TimeZoneOffset = int(Round(double(Data->TimeDifference) * 24 * 60));
  321. int UTF8 = 0;
  322. switch (Data->NotUtf)
  323. {
  324. case asOn:
  325. UTF8 = 2;
  326. break;
  327. case asOff:
  328. UTF8 = 1;
  329. break;
  330. case asAuto:
  331. UTF8 = 0;
  332. break;
  333. };
  334. FPasswordFailed = false;
  335. bool PromptedForCredentials = false;
  336. do
  337. {
  338. FSystem = "";
  339. FFeatures->Clear();
  340. FFileSystemInfoValid = false;
  341. // TODO: the same for account? it ever used?
  342. // ask for username if it was not specified in advance, even on retry,
  343. // but keep previous one as default,
  344. if (Data->UserName.IsEmpty())
  345. {
  346. FTerminal->LogEvent("Username prompt (no username provided)");
  347. if (!FPasswordFailed && !PromptedForCredentials)
  348. {
  349. FTerminal->Information(LoadStr(FTP_CREDENTIAL_PROMPT), false);
  350. PromptedForCredentials = true;
  351. }
  352. if (!FTerminal->PromptUser(Data, pkUserName, LoadStr(USERNAME_TITLE), "",
  353. LoadStr(USERNAME_PROMPT2), true, 0, UserName))
  354. {
  355. FTerminal->FatalError(NULL, LoadStr(AUTHENTICATION_FAILED));
  356. }
  357. else
  358. {
  359. FUserName = UserName;
  360. }
  361. }
  362. // ask for password if it was not specified in advance,
  363. // on retry ask always
  364. if ((Data->Password.IsEmpty() && !Data->Passwordless) || FPasswordFailed)
  365. {
  366. FTerminal->LogEvent("Password prompt (no password provided or last login attempt failed)");
  367. if (!FPasswordFailed && !PromptedForCredentials)
  368. {
  369. FTerminal->Information(LoadStr(FTP_CREDENTIAL_PROMPT), false);
  370. PromptedForCredentials = true;
  371. }
  372. // on retry ask for new password
  373. Password = "";
  374. if (!FTerminal->PromptUser(Data, pkPassword, LoadStr(PASSWORD_TITLE), "",
  375. LoadStr(PASSWORD_PROMPT), false, 0, Password))
  376. {
  377. FTerminal->FatalError(NULL, LoadStr(AUTHENTICATION_FAILED));
  378. }
  379. }
  380. FActive = FFileZillaIntf->Connect(
  381. HostName.c_str(), Data->PortNumber, UserName.c_str(),
  382. Password.c_str(), Account.c_str(), false, Path.c_str(),
  383. ServerType, Pasv, TimeZoneOffset, UTF8, Data->FtpForcePasvIp);
  384. assert(FActive);
  385. FPasswordFailed = false;
  386. try
  387. {
  388. // do not wait for FTP response code as Connect is complex operation
  389. GotReply(WaitForCommandReply(false), REPLY_CONNECT, LoadStr(CONNECTION_FAILED));
  390. // we have passed, even if we got 530 on the way (if it is possible at all),
  391. // ignore it
  392. assert(!FPasswordFailed);
  393. FPasswordFailed = false;
  394. }
  395. catch(...)
  396. {
  397. if (FPasswordFailed)
  398. {
  399. FTerminal->Information(LoadStr(FTP_ACCESS_DENIED), false);
  400. }
  401. else
  402. {
  403. // see handling of REPLY_CONNECT in GotReply
  404. FTerminal->Closed();
  405. throw;
  406. }
  407. }
  408. }
  409. while (FPasswordFailed);
  410. }
  411. //---------------------------------------------------------------------------
  412. void __fastcall TFTPFileSystem::Close()
  413. {
  414. assert(FActive);
  415. if (FFileZillaIntf->Close())
  416. {
  417. CHECK(FLAGSET(WaitForCommandReply(false), TFileZillaIntf::REPLY_DISCONNECTED));
  418. assert(FActive);
  419. Discard();
  420. FTerminal->Closed();
  421. }
  422. else
  423. {
  424. assert(false);
  425. }
  426. }
  427. //---------------------------------------------------------------------------
  428. bool __fastcall TFTPFileSystem::GetActive()
  429. {
  430. return FActive;
  431. }
  432. //---------------------------------------------------------------------------
  433. void __fastcall TFTPFileSystem::Idle()
  434. {
  435. if (FActive && !FWaitingForReply)
  436. {
  437. PoolForFatalNonCommandReply();
  438. // Keep session alive
  439. if ((FTerminal->SessionData->FtpPingType != ptOff) &&
  440. (double(Now() - FLastDataSent) > double(FTerminal->SessionData->FtpPingIntervalDT) * 4))
  441. {
  442. FLastDataSent = Now();
  443. TRemoteDirectory * Files = new TRemoteDirectory(FTerminal);
  444. try
  445. {
  446. try
  447. {
  448. Files->Directory = CurrentDirectory;
  449. DoReadDirectory(Files);
  450. }
  451. catch(...)
  452. {
  453. // ignore non-fatal errors
  454. // (i.e. current directory may not exist anymore)
  455. if (!FTerminal->Active)
  456. {
  457. throw;
  458. }
  459. }
  460. }
  461. __finally
  462. {
  463. delete Files;
  464. }
  465. }
  466. }
  467. }
  468. //---------------------------------------------------------------------------
  469. void __fastcall TFTPFileSystem::Discard()
  470. {
  471. // remove all pending messages, to get complete log
  472. // note that we need to retry discard on reconnect, as there still may be another
  473. // "disconnect/timeout/..." status messages coming
  474. DiscardMessages();
  475. assert(FActive);
  476. FActive = false;
  477. }
  478. //---------------------------------------------------------------------------
  479. AnsiString __fastcall TFTPFileSystem::AbsolutePath(AnsiString Path, bool /*Local*/)
  480. {
  481. // TODO: improve (handle .. etc.)
  482. if (TTerminal::IsAbsolutePath(Path))
  483. {
  484. return Path;
  485. }
  486. else
  487. {
  488. return ::AbsolutePath(FCurrentDirectory, Path);
  489. }
  490. }
  491. //---------------------------------------------------------------------------
  492. AnsiString __fastcall TFTPFileSystem::ActualCurrentDirectory()
  493. {
  494. char CurrentPath[1024];
  495. FFileZillaIntf->GetCurrentPath(CurrentPath, sizeof(CurrentPath));
  496. return UnixExcludeTrailingBackslash(AnsiString(CurrentPath));
  497. }
  498. //---------------------------------------------------------------------------
  499. void __fastcall TFTPFileSystem::EnsureLocation()
  500. {
  501. // if we do not know what's the current directory, do nothing
  502. if (!FCurrentDirectory.IsEmpty())
  503. {
  504. // Make sure that the FZAPI current working directory,
  505. // is actually our working directory.
  506. // It may not be because:
  507. // 1) We did cached directory change
  508. // 2) Listing was requested for non-current directory, which
  509. // makes FAPI change its current directory (and not restoring it back afterwards)
  510. if (!UnixComparePaths(ActualCurrentDirectory(), FCurrentDirectory))
  511. {
  512. FTerminal->LogEvent(FORMAT("Synchronizing current directory \"%s\".",
  513. (FCurrentDirectory)));
  514. DoChangeDirectory(FCurrentDirectory);
  515. }
  516. }
  517. }
  518. //---------------------------------------------------------------------------
  519. void __fastcall TFTPFileSystem::AnyCommand(const AnsiString Command,
  520. TCaptureOutputEvent OutputEvent)
  521. {
  522. // end-user has right to expect that client current directory is really
  523. // current directory for the server
  524. EnsureLocation();
  525. assert(FOnCaptureOutput == NULL);
  526. FOnCaptureOutput = OutputEvent;
  527. try
  528. {
  529. FFileZillaIntf->CustomCommand(Command.c_str());
  530. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  531. }
  532. __finally
  533. {
  534. FOnCaptureOutput = NULL;
  535. }
  536. }
  537. //---------------------------------------------------------------------------
  538. void __fastcall TFTPFileSystem::ResetCaches()
  539. {
  540. delete FFileListCache;
  541. FFileListCache = NULL;
  542. }
  543. //---------------------------------------------------------------------------
  544. void __fastcall TFTPFileSystem::AnnounceFileListOperation()
  545. {
  546. ResetCaches();
  547. }
  548. //---------------------------------------------------------------------------
  549. void __fastcall TFTPFileSystem::DoChangeDirectory(const AnsiString & Directory)
  550. {
  551. AnsiString Command = FORMAT("CWD %s", (Directory));
  552. FFileZillaIntf->CustomCommand(Command.c_str());
  553. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  554. }
  555. //---------------------------------------------------------------------------
  556. void __fastcall TFTPFileSystem::ChangeDirectory(const AnsiString ADirectory)
  557. {
  558. AnsiString Directory = ADirectory;
  559. try
  560. {
  561. // For changing directory, we do not make paths absolute, instead we
  562. // delegate this to the server, hence we sychronize current working
  563. // directory with the server and only then we ask for the change with
  564. // relative path.
  565. // But if synchronization fails, typically because current working directory
  566. // no longer exists, we fall back to out own resolution, to give
  567. // user chance to leave the non-existing directory.
  568. EnsureLocation();
  569. }
  570. catch(...)
  571. {
  572. if (FTerminal->Active)
  573. {
  574. Directory = AbsolutePath(Directory, false);
  575. }
  576. else
  577. {
  578. throw;
  579. }
  580. }
  581. DoChangeDirectory(Directory);
  582. // make next ReadCurrentDirectory retrieve actual server-side current directory
  583. FCurrentDirectory = "";
  584. }
  585. //---------------------------------------------------------------------------
  586. void __fastcall TFTPFileSystem::CachedChangeDirectory(const AnsiString Directory)
  587. {
  588. FCurrentDirectory = UnixExcludeTrailingBackslash(Directory);
  589. }
  590. //---------------------------------------------------------------------------
  591. void __fastcall TFTPFileSystem::ChangeFileProperties(const AnsiString AFileName,
  592. const TRemoteFile * File, const TRemoteProperties * Properties,
  593. TChmodSessionAction & Action)
  594. {
  595. assert(!Properties->Valid.Contains(vpGroup));
  596. assert(!Properties->Valid.Contains(vpOwner));
  597. assert(!Properties->Valid.Contains(vpLastAccess));
  598. assert(!Properties->Valid.Contains(vpModification));
  599. if (Properties->Valid.Contains(vpRights))
  600. {
  601. assert(Properties);
  602. TRemoteFile * OwnedFile = NULL;
  603. try
  604. {
  605. AnsiString FileName = AbsolutePath(AFileName, false);
  606. if (File == NULL)
  607. {
  608. ReadFile(FileName, OwnedFile);
  609. File = OwnedFile;
  610. }
  611. if ((File != NULL) && File->IsDirectory && !File->IsSymLink && Properties->Recursive)
  612. {
  613. try
  614. {
  615. FTerminal->ProcessDirectory(AFileName, FTerminal->ChangeFileProperties,
  616. (void*)Properties);
  617. }
  618. catch(...)
  619. {
  620. Action.Cancel();
  621. throw;
  622. }
  623. }
  624. TRights Rights;
  625. if (File != NULL)
  626. {
  627. Rights = *File->Rights;
  628. }
  629. Rights |= Properties->Rights.NumberSet;
  630. Rights &= (unsigned short)~Properties->Rights.NumberUnset;
  631. if ((File != NULL) && File->IsDirectory && Properties->AddXToDirectories)
  632. {
  633. Rights.AddExecute();
  634. }
  635. Action.Rights(Rights);
  636. AnsiString FileNameOnly = UnixExtractFileName(FileName);
  637. AnsiString FilePath = UnixExtractFilePath(FileName);
  638. // FZAPI wants octal number represented as decadic
  639. FFileZillaIntf->Chmod(Rights.NumberDecadic, FileNameOnly.c_str(), FilePath.c_str());
  640. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  641. }
  642. __finally
  643. {
  644. delete OwnedFile;
  645. }
  646. }
  647. else
  648. {
  649. Action.Cancel();
  650. }
  651. }
  652. //---------------------------------------------------------------------------
  653. bool __fastcall TFTPFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  654. {
  655. assert(false);
  656. return false;
  657. }
  658. //---------------------------------------------------------------------------
  659. void __fastcall TFTPFileSystem::CalculateFilesChecksum(const AnsiString & /*Alg*/,
  660. TStrings * /*FileList*/, TStrings * /*Checksums*/,
  661. TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
  662. {
  663. assert(false);
  664. }
  665. //---------------------------------------------------------------------------
  666. bool __fastcall TFTPFileSystem::ConfirmOverwrite(AnsiString & FileName,
  667. TOverwriteMode & OverwriteMode, TFileOperationProgressType * OperationProgress,
  668. const TOverwriteFileParams * FileParams, int Params, bool AutoResume)
  669. {
  670. bool Result;
  671. bool CanAutoResume = FLAGSET(Params, cpNoConfirmation) && AutoResume;
  672. // when resuming transfer after interrupted connection,
  673. // do nothing (dummy resume) when the files has the same size.
  674. // this is workaround for servers that strangely fails just after successful
  675. // upload.
  676. bool CanResume =
  677. (FileParams != NULL) &&
  678. (((FileParams->DestSize < FileParams->SourceSize)) ||
  679. ((FileParams->DestSize == FileParams->SourceSize) && CanAutoResume));
  680. int Answer;
  681. if (CanAutoResume && CanResume)
  682. {
  683. Answer = qaRetry;
  684. }
  685. else
  686. {
  687. // retry = "resume"
  688. // all = "yes to newer"
  689. // ignore = "rename"
  690. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  691. if (CanResume)
  692. {
  693. Answers |= qaRetry;
  694. }
  695. TQueryButtonAlias Aliases[3];
  696. Aliases[0].Button = qaRetry;
  697. Aliases[0].Alias = LoadStr(RESUME_BUTTON);
  698. Aliases[1].Button = qaAll;
  699. Aliases[1].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  700. Aliases[2].Button = qaIgnore;
  701. Aliases[2].Alias = LoadStr(RENAME_BUTTON);
  702. TQueryParams QueryParams(qpNeverAskAgainCheck);
  703. QueryParams.Aliases = Aliases;
  704. QueryParams.AliasesCount = LENOF(Aliases);
  705. SUSPEND_OPERATION
  706. (
  707. Answer = FTerminal->ConfirmFileOverwrite(FileName, FileParams,
  708. Answers, &QueryParams,
  709. OperationProgress->Side == osLocal ? osRemote : osLocal,
  710. Params, OperationProgress);
  711. )
  712. }
  713. Result = true;
  714. switch (Answer)
  715. {
  716. // resume
  717. case qaRetry:
  718. OverwriteMode = omResume;
  719. assert(FileParams != NULL);
  720. assert(CanResume);
  721. FFileTransferResumed = FileParams->DestSize;
  722. break;
  723. // rename
  724. case qaIgnore:
  725. if (FTerminal->PromptUser(FTerminal->SessionData, pkFileName,
  726. LoadStr(RENAME_TITLE), "", LoadStr(RENAME_PROMPT2), true, 0, FileName))
  727. {
  728. OverwriteMode = omOverwrite;
  729. }
  730. else
  731. {
  732. if (!OperationProgress->Cancel)
  733. {
  734. OperationProgress->Cancel = csCancel;
  735. }
  736. FFileTransferAbort = ftaCancel;
  737. Result = false;
  738. }
  739. break;
  740. case qaYes:
  741. OverwriteMode = omOverwrite;
  742. break;
  743. case qaCancel:
  744. if (!OperationProgress->Cancel)
  745. {
  746. OperationProgress->Cancel = csCancel;
  747. }
  748. FFileTransferAbort = ftaCancel;
  749. Result = false;
  750. break;
  751. case qaNo:
  752. FFileTransferAbort = ftaSkip;
  753. Result = false;
  754. break;
  755. default:
  756. assert(false);
  757. Result = false;
  758. break;
  759. }
  760. return Result;
  761. }
  762. //---------------------------------------------------------------------------
  763. void __fastcall TFTPFileSystem::ResetFileTransfer()
  764. {
  765. FFileTransferAbort = ftaNone;
  766. FFileTransferCancelled = false;
  767. FFileTransferResumed = 0;
  768. }
  769. //---------------------------------------------------------------------------
  770. void __fastcall TFTPFileSystem::ReadDirectoryProgress(__int64 Bytes)
  771. {
  772. // with FTP we do not know exactly how many entries we have received,
  773. // instead we know number of bytes received only.
  774. // so we report approximation based on average size of entry.
  775. int Progress = int(Bytes / 80);
  776. if (Progress - FLastReadDirectoryProgress >= 10)
  777. {
  778. bool Cancel = false;
  779. FLastReadDirectoryProgress = Progress;
  780. FTerminal->DoReadDirectoryProgress(Progress, Cancel);
  781. if (Cancel)
  782. {
  783. FTerminal->DoReadDirectoryProgress(-2, Cancel);
  784. FFileZillaIntf->Cancel();
  785. }
  786. }
  787. }
  788. //---------------------------------------------------------------------------
  789. void __fastcall TFTPFileSystem::DoFileTransferProgress(__int64 TransferSize,
  790. __int64 Bytes)
  791. {
  792. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  793. OperationProgress->SetTransferSize(TransferSize);
  794. if (FFileTransferResumed > 0)
  795. {
  796. OperationProgress->AddResumed(FFileTransferResumed);
  797. FFileTransferResumed = 0;
  798. }
  799. __int64 Diff = Bytes - OperationProgress->TransferedSize;
  800. assert(Diff >= 0);
  801. if (Diff >= 0)
  802. {
  803. OperationProgress->AddTransfered(Diff);
  804. }
  805. if (OperationProgress->Cancel == csCancel)
  806. {
  807. FFileTransferCancelled = true;
  808. FFileTransferAbort = ftaCancel;
  809. FFileZillaIntf->Cancel();
  810. }
  811. if (FFileTransferCPSLimit != OperationProgress->CPSLimit)
  812. {
  813. FFileTransferCPSLimit = OperationProgress->CPSLimit;
  814. }
  815. }
  816. //---------------------------------------------------------------------------
  817. void __fastcall TFTPFileSystem::FileTransferProgress(__int64 TransferSize,
  818. __int64 Bytes)
  819. {
  820. TGuard Guard(FTransferStatusCriticalSection);
  821. DoFileTransferProgress(TransferSize, Bytes);
  822. }
  823. //---------------------------------------------------------------------------
  824. void __fastcall TFTPFileSystem::FileTransfer(const AnsiString & FileName,
  825. const AnsiString & LocalFile, const AnsiString & RemoteFile,
  826. const AnsiString & RemotePath, bool Get, __int64 Size, int Type,
  827. TFileTransferData & UserData, TFileOperationProgressType * OperationProgress)
  828. {
  829. FILE_OPERATION_LOOP(FMTLOAD(TRANSFER_ERROR, (FileName)),
  830. FFileZillaIntf->FileTransfer(LocalFile.c_str(), RemoteFile.c_str(),
  831. RemotePath.c_str(), Get, Size, Type, &UserData);
  832. // we may actually catch reponse code of the listing
  833. // command (when checking for existence of the remote file)
  834. unsigned int Reply = WaitForCommandReply();
  835. GotReply(Reply, FLAGMASK(FFileTransferCancelled, REPLY_ALLOW_CANCEL));
  836. );
  837. switch (FFileTransferAbort)
  838. {
  839. case ftaSkip:
  840. THROW_SKIP_FILE_NULL;
  841. case ftaCancel:
  842. Abort();
  843. break;
  844. }
  845. if (!FFileTransferCancelled)
  846. {
  847. // show completion of transfer
  848. // call non-guarded variant to avoid deadlock with keepalives
  849. // (we are not waiting for reply anymore so keepalives are free to proceed)
  850. DoFileTransferProgress(OperationProgress->TransferSize, OperationProgress->TransferSize);
  851. }
  852. }
  853. //---------------------------------------------------------------------------
  854. void __fastcall TFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  855. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  856. int Params, TFileOperationProgressType * OperationProgress,
  857. TOnceDoneOperation & OnceDoneOperation)
  858. {
  859. Params &= ~cpAppend;
  860. AnsiString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  861. int Index = 0;
  862. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  863. {
  864. AnsiString FileName = FilesToCopy->Strings[Index];
  865. const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
  866. bool Success = false;
  867. try
  868. {
  869. try
  870. {
  871. SinkRobust(AbsolutePath(FileName, false), File, FullTargetDir, CopyParam, Params,
  872. OperationProgress, tfFirstLevel);
  873. Success = true;
  874. FLastDataSent = Now();
  875. }
  876. catch(EScpSkipFile & E)
  877. {
  878. SUSPEND_OPERATION (
  879. if (!FTerminal->HandleException(&E)) throw;
  880. );
  881. }
  882. }
  883. __finally
  884. {
  885. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  886. }
  887. Index++;
  888. }
  889. }
  890. //---------------------------------------------------------------------------
  891. void __fastcall TFTPFileSystem::SinkRobust(const AnsiString FileName,
  892. const TRemoteFile * File, const AnsiString TargetDir,
  893. const TCopyParamType * CopyParam, int Params,
  894. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  895. {
  896. // the same in TSFTPFileSystem
  897. bool Retry;
  898. TDownloadSessionAction Action(FTerminal->Log);
  899. do
  900. {
  901. Retry = false;
  902. try
  903. {
  904. Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress,
  905. Flags, Action);
  906. }
  907. catch(Exception & E)
  908. {
  909. Retry = true;
  910. if (FTerminal->Active ||
  911. !FTerminal->QueryReopen(&E, ropNoReadDirectory, OperationProgress))
  912. {
  913. FTerminal->RollbackAction(Action, OperationProgress, &E);
  914. throw;
  915. }
  916. }
  917. if (Retry)
  918. {
  919. OperationProgress->RollbackTransfer();
  920. Action.Restart();
  921. assert(File != NULL);
  922. if (!File->IsDirectory)
  923. {
  924. // prevent overwrite confirmations
  925. Params |= cpNoConfirmation;
  926. Flags |= tfAutoResume;
  927. }
  928. }
  929. }
  930. while (Retry);
  931. }
  932. //---------------------------------------------------------------------------
  933. void __fastcall TFTPFileSystem::Sink(const AnsiString FileName,
  934. const TRemoteFile * File, const AnsiString TargetDir,
  935. const TCopyParamType * CopyParam, int Params,
  936. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  937. TDownloadSessionAction & Action)
  938. {
  939. AnsiString OnlyFileName = UnixExtractFileName(FileName);
  940. Action.FileName(FileName);
  941. TFileMasks::TParams MaskParams;
  942. MaskParams.Size = File->Size;
  943. if (!CopyParam->AllowTransfer(FileName, osRemote, File->IsDirectory, MaskParams))
  944. {
  945. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  946. THROW_SKIP_FILE_NULL;
  947. }
  948. assert(File);
  949. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  950. OperationProgress->SetFile(OnlyFileName);
  951. AnsiString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
  952. osRemote, FLAGSET(Flags, tfFirstLevel));
  953. AnsiString DestFullName = TargetDir + DestFileName;
  954. if (File->IsDirectory)
  955. {
  956. Action.Cancel();
  957. if (!File->IsSymLink)
  958. {
  959. FILE_OPERATION_LOOP (FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)),
  960. int Attrs = FileGetAttr(DestFullName);
  961. if (FLAGCLEAR(Attrs, faDirectory))
  962. {
  963. EXCEPTION;
  964. }
  965. );
  966. FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFullName)),
  967. if (!ForceDirectories(DestFullName))
  968. {
  969. RaiseLastOSError();
  970. }
  971. );
  972. TSinkFileParams SinkFileParams;
  973. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  974. SinkFileParams.CopyParam = CopyParam;
  975. SinkFileParams.Params = Params;
  976. SinkFileParams.OperationProgress = OperationProgress;
  977. SinkFileParams.Skipped = false;
  978. SinkFileParams.Flags = Flags & ~(tfFirstLevel | tfAutoResume);
  979. FTerminal->ProcessDirectory(FileName, SinkFile, &SinkFileParams);
  980. // Do not delete directory if some of its files were skip.
  981. // Throw "skip file" for the directory to avoid attempt to deletion
  982. // of any parent directory
  983. if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
  984. {
  985. THROW_SKIP_FILE_NULL;
  986. }
  987. }
  988. else
  989. {
  990. // file is symlink to directory, currently do nothing, but it should be
  991. // reported to user
  992. }
  993. }
  994. else
  995. {
  996. FTerminal->LogEvent(FORMAT("Copying \"%s\" to local directory started.", (FileName)));
  997. // Will we use ASCII of BINARY file tranfer?
  998. OperationProgress->SetAsciiTransfer(
  999. CopyParam->UseAsciiTransfer(FileName, osRemote, MaskParams));
  1000. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  1001. " transfer mode selected.");
  1002. // Suppose same data size to transfer as to write
  1003. OperationProgress->SetTransferSize(File->Size);
  1004. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  1005. int Attrs;
  1006. FILE_OPERATION_LOOP (FMTLOAD(NOT_FILE_ERROR, (DestFullName)),
  1007. Attrs = FileGetAttr(DestFullName);
  1008. if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory))
  1009. {
  1010. EXCEPTION;
  1011. }
  1012. );
  1013. OperationProgress->TransferingFile = false; // not set with FTP protocol
  1014. ResetFileTransfer();
  1015. TFileTransferData UserData;
  1016. AnsiString FilePath = UnixExtractFilePath(FileName);
  1017. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1018. {
  1019. // ignore file list
  1020. TFileListHelper Helper(this, NULL, true);
  1021. FFileTransferCPSLimit = OperationProgress->CPSLimit;
  1022. FFileTransferPreserveTime = CopyParam->PreserveTime;
  1023. UserData.FileName = DestFileName;
  1024. UserData.Params = Params;
  1025. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1026. UserData.CopyParam = CopyParam;
  1027. FileTransfer(FileName, DestFullName, OnlyFileName,
  1028. FilePath, true, File->Size, TransferType, UserData, OperationProgress);
  1029. }
  1030. // in case dest filename is changed from overwrite dialog
  1031. if (DestFileName != UserData.FileName)
  1032. {
  1033. DestFullName = TargetDir + UserData.FileName;
  1034. Attrs = FileGetAttr(DestFullName);
  1035. }
  1036. Action.Destination(ExpandUNCFileName(DestFullName));
  1037. if (Attrs == -1)
  1038. {
  1039. Attrs = faArchive;
  1040. }
  1041. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  1042. if ((NewAttrs & Attrs) != NewAttrs)
  1043. {
  1044. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFullName)),
  1045. THROWOSIFFALSE(FileSetAttr(DestFullName, Attrs | NewAttrs) == 0);
  1046. );
  1047. }
  1048. }
  1049. if (FLAGSET(Params, cpDelete))
  1050. {
  1051. // If file is directory, do not delete it recursively, because it should be
  1052. // empty already. If not, it should not be deleted (some files were
  1053. // skipped or some new files were copied to it, while we were downloading)
  1054. int Params = dfNoRecursive;
  1055. FTerminal->DeleteFile(FileName, File, &Params);
  1056. }
  1057. }
  1058. //---------------------------------------------------------------------------
  1059. void __fastcall TFTPFileSystem::SinkFile(AnsiString FileName,
  1060. const TRemoteFile * File, void * Param)
  1061. {
  1062. TSinkFileParams * Params = (TSinkFileParams *)Param;
  1063. assert(Params->OperationProgress);
  1064. try
  1065. {
  1066. SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  1067. Params->Params, Params->OperationProgress, Params->Flags);
  1068. }
  1069. catch(EScpSkipFile & E)
  1070. {
  1071. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  1072. Params->Skipped = true;
  1073. SUSPEND_OPERATION (
  1074. if (!FTerminal->HandleException(&E))
  1075. {
  1076. throw;
  1077. }
  1078. );
  1079. if (OperationProgress->Cancel)
  1080. {
  1081. Abort();
  1082. }
  1083. }
  1084. }
  1085. //---------------------------------------------------------------------------
  1086. void __fastcall TFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1087. const AnsiString ATargetDir, const TCopyParamType * CopyParam,
  1088. int Params, TFileOperationProgressType * OperationProgress,
  1089. TOnceDoneOperation & OnceDoneOperation)
  1090. {
  1091. assert((FilesToCopy != NULL) && (OperationProgress != NULL));
  1092. Params &= ~cpAppend;
  1093. AnsiString FileName, FileNameOnly;
  1094. AnsiString TargetDir = AbsolutePath(ATargetDir, false);
  1095. AnsiString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  1096. int Index = 0;
  1097. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  1098. {
  1099. bool Success = false;
  1100. FileName = FilesToCopy->Strings[Index];
  1101. FileNameOnly = ExtractFileName(FileName);
  1102. try
  1103. {
  1104. try
  1105. {
  1106. if (FTerminal->SessionData->CacheDirectories)
  1107. {
  1108. FTerminal->DirectoryModified(TargetDir, false);
  1109. if (DirectoryExists(FileName))
  1110. {
  1111. FTerminal->DirectoryModified(FullTargetDir + FileNameOnly, true);
  1112. }
  1113. }
  1114. SourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  1115. tfFirstLevel);
  1116. Success = true;
  1117. FLastDataSent = Now();
  1118. }
  1119. catch(EScpSkipFile & E)
  1120. {
  1121. SUSPEND_OPERATION (
  1122. if (!FTerminal->HandleException(&E)) throw;
  1123. );
  1124. }
  1125. }
  1126. __finally
  1127. {
  1128. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1129. }
  1130. Index++;
  1131. }
  1132. }
  1133. //---------------------------------------------------------------------------
  1134. void __fastcall TFTPFileSystem::SourceRobust(const AnsiString FileName,
  1135. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  1136. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1137. {
  1138. // the same in TSFTPFileSystem
  1139. bool Retry;
  1140. TUploadSessionAction Action(FTerminal->Log);
  1141. do
  1142. {
  1143. Retry = false;
  1144. try
  1145. {
  1146. Source(FileName, TargetDir, CopyParam, Params, OperationProgress,
  1147. Flags, Action);
  1148. }
  1149. catch(Exception & E)
  1150. {
  1151. Retry = true;
  1152. if (FTerminal->Active ||
  1153. !FTerminal->QueryReopen(&E, ropNoReadDirectory, OperationProgress))
  1154. {
  1155. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1156. throw;
  1157. }
  1158. }
  1159. if (Retry)
  1160. {
  1161. OperationProgress->RollbackTransfer();
  1162. Action.Restart();
  1163. // prevent overwrite confirmations
  1164. // (should not be set for directories!)
  1165. Params |= cpNoConfirmation;
  1166. Flags |= tfAutoResume;
  1167. }
  1168. }
  1169. while (Retry);
  1170. }
  1171. //---------------------------------------------------------------------------
  1172. void __fastcall TFTPFileSystem::Source(const AnsiString FileName,
  1173. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  1174. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1175. TUploadSessionAction & Action)
  1176. {
  1177. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  1178. Action.FileName(ExpandUNCFileName(FileName));
  1179. OperationProgress->SetFile(FileName, false);
  1180. if (!FTerminal->AllowLocalFileTransfer(FileName, CopyParam))
  1181. {
  1182. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  1183. THROW_SKIP_FILE_NULL;
  1184. }
  1185. __int64 Size;
  1186. int Attrs;
  1187. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &Attrs,
  1188. NULL, NULL, NULL, NULL, &Size);
  1189. OperationProgress->SetFileInProgress();
  1190. bool Dir = FLAGSET(Attrs, faDirectory);
  1191. if (Dir)
  1192. {
  1193. Action.Cancel();
  1194. DirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  1195. Attrs, CopyParam, Params, OperationProgress, Flags);
  1196. }
  1197. else
  1198. {
  1199. AnsiString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
  1200. osLocal, FLAGSET(Flags, tfFirstLevel));
  1201. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  1202. OperationProgress->SetLocalSize(Size);
  1203. // Suppose same data size to transfer as to read
  1204. // (not true with ASCII transfer)
  1205. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1206. OperationProgress->TransferingFile = false;
  1207. // Will we use ASCII of BINARY file tranfer?
  1208. TFileMasks::TParams MaskParams;
  1209. MaskParams.Size = Size;
  1210. OperationProgress->SetAsciiTransfer(
  1211. CopyParam->UseAsciiTransfer(FileName, osLocal, MaskParams));
  1212. FTerminal->LogEvent(
  1213. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  1214. " transfer mode selected.");
  1215. ResetFileTransfer();
  1216. TFileTransferData UserData;
  1217. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1218. {
  1219. // ignore file list
  1220. TFileListHelper Helper(this, NULL, true);
  1221. FFileTransferCPSLimit = OperationProgress->CPSLimit;
  1222. // not used for uploads anyway
  1223. FFileTransferPreserveTime = CopyParam->PreserveTime;
  1224. // not used for uploads, but we get new name (if any) back in this field
  1225. UserData.FileName = DestFileName;
  1226. UserData.Params = Params;
  1227. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1228. UserData.CopyParam = CopyParam;
  1229. FileTransfer(FileName, FileName, DestFileName,
  1230. TargetDir, false, Size, TransferType, UserData, OperationProgress);
  1231. }
  1232. AnsiString DestFullName = TargetDir + UserData.FileName;
  1233. // only now, we know the final destination
  1234. Action.Destination(DestFullName);
  1235. // we are not able to tell if setting timestamp succeeded,
  1236. // so we log it always (if supported)
  1237. if (FFileTransferPreserveTime && FMfmt)
  1238. {
  1239. // Inspired by SysUtils::FileAge
  1240. WIN32_FIND_DATA FindData;
  1241. HANDLE Handle = FindFirstFile(FileName.c_str(), &FindData);
  1242. if (Handle != INVALID_HANDLE_VALUE)
  1243. {
  1244. TTouchSessionAction TouchAction(FTerminal->Log, DestFullName,
  1245. UnixToDateTime(
  1246. ConvertTimestampToUnixSafe(FindData.ftLastWriteTime, dstmUnix),
  1247. dstmUnix));
  1248. FindClose(Handle);
  1249. }
  1250. }
  1251. }
  1252. /* TODO : Delete also read-only files. */
  1253. if (FLAGSET(Params, cpDelete))
  1254. {
  1255. if (!Dir)
  1256. {
  1257. FILE_OPERATION_LOOP (FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)),
  1258. THROWOSIFFALSE(Sysutils::DeleteFile(FileName));
  1259. )
  1260. }
  1261. }
  1262. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1263. {
  1264. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  1265. THROWOSIFFALSE(FileSetAttr(FileName, Attrs & ~faArchive) == 0);
  1266. )
  1267. }
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. void __fastcall TFTPFileSystem::DirectorySource(const AnsiString DirectoryName,
  1271. const AnsiString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  1272. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1273. {
  1274. AnsiString DestDirectoryName = CopyParam->ChangeFileName(
  1275. ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal,
  1276. FLAGSET(Flags, tfFirstLevel));
  1277. AnsiString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  1278. OperationProgress->SetFile(DirectoryName);
  1279. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1280. TSearchRec SearchRec;
  1281. bool FindOK;
  1282. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1283. FindOK = (bool)(FindFirst(DirectoryName + "*.*",
  1284. FindAttrs, SearchRec) == 0);
  1285. );
  1286. bool CreateDir = true;
  1287. try
  1288. {
  1289. while (FindOK && !OperationProgress->Cancel)
  1290. {
  1291. AnsiString FileName = DirectoryName + SearchRec.Name;
  1292. try
  1293. {
  1294. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  1295. {
  1296. SourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  1297. Flags & ~(tfFirstLevel | tfAutoResume));
  1298. // if any file got uploaded (i.e. there were any file in the
  1299. // directory and at least one was not skipped),
  1300. // do not try to create the directory,
  1301. // as it should be already created by FZAPI during upload
  1302. CreateDir = false;
  1303. }
  1304. }
  1305. catch (EScpSkipFile &E)
  1306. {
  1307. // If ESkipFile occurs, just log it and continue with next file
  1308. SUSPEND_OPERATION (
  1309. // here a message to user was displayed, which was not appropriate
  1310. // when user refused to overwrite the file in subdirectory.
  1311. // hopefuly it won't be missing in other situations.
  1312. if (!FTerminal->HandleException(&E)) throw;
  1313. );
  1314. }
  1315. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1316. FindOK = (FindNext(SearchRec) == 0);
  1317. );
  1318. };
  1319. }
  1320. __finally
  1321. {
  1322. FindClose(SearchRec);
  1323. }
  1324. if (CreateDir)
  1325. {
  1326. TRemoteProperties Properties;
  1327. if (CopyParam->PreserveRights)
  1328. {
  1329. Properties.Valid = TValidProperties() << vpRights;
  1330. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  1331. }
  1332. try
  1333. {
  1334. FTerminal->ExceptionOnFail = true;
  1335. try
  1336. {
  1337. FTerminal->CreateDirectory(DestFullName, &Properties);
  1338. }
  1339. __finally
  1340. {
  1341. FTerminal->ExceptionOnFail = false;
  1342. }
  1343. }
  1344. catch(...)
  1345. {
  1346. TRemoteFile * File = NULL;
  1347. // ignore non-fatal error when the directory already exists
  1348. bool Rethrow =
  1349. !FTerminal->Active ||
  1350. !FTerminal->FileExists(UnixExcludeTrailingBackslash(DestFullName), &File) ||
  1351. !File->IsDirectory;
  1352. delete File;
  1353. if (Rethrow)
  1354. {
  1355. throw;
  1356. }
  1357. }
  1358. }
  1359. /* TODO : Delete also read-only directories. */
  1360. /* TODO : Show error message on failure. */
  1361. if (!OperationProgress->Cancel)
  1362. {
  1363. if (FLAGSET(Params, cpDelete))
  1364. {
  1365. RemoveDir(DirectoryName);
  1366. }
  1367. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1368. {
  1369. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DirectoryName)),
  1370. THROWOSIFFALSE(FileSetAttr(DirectoryName, Attrs & ~faArchive) == 0);
  1371. )
  1372. }
  1373. }
  1374. }
  1375. //---------------------------------------------------------------------------
  1376. void __fastcall TFTPFileSystem::CreateDirectory(const AnsiString ADirName)
  1377. {
  1378. AnsiString DirName = AbsolutePath(ADirName, false);
  1379. {
  1380. // ignore file list
  1381. TFileListHelper Helper(this, NULL, true);
  1382. FFileZillaIntf->MakeDir(DirName.c_str());
  1383. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1384. }
  1385. }
  1386. //---------------------------------------------------------------------------
  1387. void __fastcall TFTPFileSystem::CreateLink(const AnsiString /*FileName*/,
  1388. const AnsiString /*PointTo*/, bool /*Symbolic*/)
  1389. {
  1390. assert(false);
  1391. }
  1392. //---------------------------------------------------------------------------
  1393. void __fastcall TFTPFileSystem::DeleteFile(const AnsiString AFileName,
  1394. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  1395. {
  1396. AnsiString FileName = AbsolutePath(AFileName, false);
  1397. AnsiString FileNameOnly = UnixExtractFileName(FileName);
  1398. AnsiString FilePath = UnixExtractFilePath(FileName);
  1399. bool Dir = (File != NULL) && File->IsDirectory && !File->IsSymLink;
  1400. if (Dir && FLAGCLEAR(Params, dfNoRecursive))
  1401. {
  1402. try
  1403. {
  1404. FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Params);
  1405. }
  1406. catch(...)
  1407. {
  1408. Action.Cancel();
  1409. throw;
  1410. }
  1411. }
  1412. {
  1413. // ignore file list
  1414. TFileListHelper Helper(this, NULL, true);
  1415. if (Dir)
  1416. {
  1417. // If current remote directory is in the directory being removed,
  1418. // some servers may refuse to delete it
  1419. // This is common as ProcessDirectory above would CWD to
  1420. // the directory to LIST it.
  1421. // EnsureLocation should reset actual current directory to user's working directory.
  1422. // If user's working directory is still below deleted directory, it is
  1423. // perfectly correct to report an error.
  1424. if (UnixIsChildPath(ActualCurrentDirectory(), FileName))
  1425. {
  1426. EnsureLocation();
  1427. }
  1428. FFileZillaIntf->RemoveDir(FileNameOnly.c_str(), FilePath.c_str());
  1429. }
  1430. else
  1431. {
  1432. FFileZillaIntf->Delete(FileNameOnly.c_str(), FilePath.c_str());
  1433. }
  1434. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1435. }
  1436. }
  1437. //---------------------------------------------------------------------------
  1438. void __fastcall TFTPFileSystem::CustomCommandOnFile(const AnsiString /*FileName*/,
  1439. const TRemoteFile * /*File*/, AnsiString /*Command*/, int /*Params*/,
  1440. TCaptureOutputEvent /*OutputEvent*/)
  1441. {
  1442. // if ever implemented, do not forget to add EnsureLocation,
  1443. // see AnyCommand for a reason why
  1444. assert(false);
  1445. }
  1446. //---------------------------------------------------------------------------
  1447. void __fastcall TFTPFileSystem::DoStartup()
  1448. {
  1449. TStrings * PostLoginCommands = new TStringList();
  1450. try
  1451. {
  1452. PostLoginCommands->Text = FTerminal->SessionData->PostLoginCommands;
  1453. for (int Index = 0; Index < PostLoginCommands->Count; Index++)
  1454. {
  1455. AnsiString Command = PostLoginCommands->Strings[Index];
  1456. if (!Command.IsEmpty())
  1457. {
  1458. FFileZillaIntf->CustomCommand(Command.c_str());
  1459. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1460. }
  1461. }
  1462. }
  1463. __finally
  1464. {
  1465. delete PostLoginCommands;
  1466. }
  1467. // retrieve initialize working directory to save it as home directory
  1468. ReadCurrentDirectory();
  1469. FHomeDirectory = FCurrentDirectory;
  1470. }
  1471. //---------------------------------------------------------------------------
  1472. void __fastcall TFTPFileSystem::HomeDirectory()
  1473. {
  1474. // FHomeDirectory is an absolute path, so avoid unnecessary overhead
  1475. // of ChangeDirectory, such as EnsureLocation
  1476. DoChangeDirectory(FHomeDirectory);
  1477. FCurrentDirectory = FHomeDirectory;
  1478. }
  1479. //---------------------------------------------------------------------------
  1480. bool __fastcall TFTPFileSystem::IsCapable(int Capability) const
  1481. {
  1482. assert(FTerminal);
  1483. switch (Capability)
  1484. {
  1485. case fcResolveSymlink: // sic
  1486. case fcTextMode:
  1487. case fcModeChanging: // but not fcModeChangingUpload
  1488. case fcNewerOnlyUpload:
  1489. case fcAnyCommand: // but not fcShellAnyCommand
  1490. case fcRename:
  1491. case fcRemoteMove:
  1492. return true;
  1493. case fcPreservingTimestampUpload:
  1494. return FMfmt;
  1495. case fcModeChangingUpload:
  1496. case fcLoadingAdditionalProperties:
  1497. case fcShellAnyCommand:
  1498. case fcCalculatingChecksum:
  1499. case fcHardLink:
  1500. case fcSymbolicLink:
  1501. case fcCheckingSpaceAvailable:
  1502. case fcUserGroupListing:
  1503. case fcGroupChanging:
  1504. case fcOwnerChanging:
  1505. case fcGroupOwnerChangingByID:
  1506. case fcSecondaryShell:
  1507. case fcRemoteCopy:
  1508. case fcNativeTextMode:
  1509. case fcTimestampChanging:
  1510. case fcIgnorePermErrors:
  1511. return false;
  1512. default:
  1513. assert(false);
  1514. return false;
  1515. }
  1516. }
  1517. //---------------------------------------------------------------------------
  1518. void __fastcall TFTPFileSystem::LookupUsersGroups()
  1519. {
  1520. assert(false);
  1521. }
  1522. //---------------------------------------------------------------------------
  1523. void __fastcall TFTPFileSystem::ReadCurrentDirectory()
  1524. {
  1525. // ask the server for current directory on startup only
  1526. // and immediatelly after call to CWD,
  1527. // later our current directory may be not synchronized with FZAPI current
  1528. // directory anyway, see comments in EnsureLocation
  1529. if (FCurrentDirectory.IsEmpty())
  1530. {
  1531. FFileZillaIntf->CustomCommand("PWD");
  1532. unsigned int Code;
  1533. TStrings * Response = NULL;
  1534. GotReply(WaitForCommandReply(), REPLY_2XX_CODE, "", &Code, &Response);
  1535. try
  1536. {
  1537. assert(Response != NULL);
  1538. bool Result = false;
  1539. // the only allowed 2XX code to "PWD"
  1540. if ((Code == 257) &&
  1541. (Response->Count == 1))
  1542. {
  1543. AnsiString Path = Response->Text;
  1544. int P = Path.Pos("\"");
  1545. if (P == 0)
  1546. {
  1547. // some systems use single quotes, be tolerant
  1548. P = Path.Pos("'");
  1549. }
  1550. if (P != 0)
  1551. {
  1552. Path.Delete(1, P - 1);
  1553. if (Unquote(Path))
  1554. {
  1555. FCurrentDirectory = UnixExcludeTrailingBackslash(Path);
  1556. Result = true;
  1557. }
  1558. }
  1559. }
  1560. if (Result)
  1561. {
  1562. FFileZillaIntf->SetCurrentPath(FCurrentDirectory.c_str());
  1563. }
  1564. else
  1565. {
  1566. throw Exception(FMTLOAD(FTP_PWD_RESPONSE_ERROR, (Response->Text)));
  1567. }
  1568. }
  1569. __finally
  1570. {
  1571. delete Response;
  1572. }
  1573. }
  1574. }
  1575. //---------------------------------------------------------------------------
  1576. void __fastcall TFTPFileSystem::DoReadDirectory(TRemoteFileList * FileList)
  1577. {
  1578. FileList->Clear();
  1579. // FZAPI does not list parent directory, add it
  1580. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  1581. FLastReadDirectoryProgress = 0;
  1582. TFileListHelper Helper(this, FileList, false);
  1583. // always specify path to list, do not attempt to list "current" dir as:
  1584. // 1) List() lists again the last listed directory, not the current working directory
  1585. // 2) we handle this way the cached directory change
  1586. AnsiString Directory = AbsolutePath(FileList->Directory, false);
  1587. FFileZillaIntf->List(Directory.c_str());
  1588. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_ALLOW_CANCEL);
  1589. FLastDataSent = Now();
  1590. }
  1591. //---------------------------------------------------------------------------
  1592. void __fastcall TFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  1593. {
  1594. bool GotNoFilesForAll = false;
  1595. bool Repeat;
  1596. do
  1597. {
  1598. Repeat = false;
  1599. try
  1600. {
  1601. FDoListAll = (FListAll == asAuto) || (FListAll == asOn);
  1602. DoReadDirectory(FileList);
  1603. // We got no files with "-a", but again no files w/o "-a",
  1604. // so it was not "-a"'s problem, revert to auto and let it decide the next time
  1605. if (GotNoFilesForAll && (FileList->Count == 0))
  1606. {
  1607. assert(FListAll == asOff);
  1608. FListAll = asAuto;
  1609. }
  1610. else if (FListAll == asAuto)
  1611. {
  1612. // some servers take "-a" as a mask and return empty directory listing
  1613. // (note that it's actually never empty here, there's always at least parent directory,
  1614. // added explicitly by DoReadDirectory)
  1615. if ((FileList->Count == 0) ||
  1616. ((FileList->Count == 1) && FileList->Files[0]->IsParentDirectory))
  1617. {
  1618. Repeat = true;
  1619. FListAll = asOff;
  1620. GotNoFilesForAll = true;
  1621. }
  1622. else
  1623. {
  1624. // reading first directory has succeeded, always use "-a"
  1625. FListAll = asOn;
  1626. }
  1627. }
  1628. // use "-a" even for implicit directory reading by FZAPI?
  1629. // (e.g. before file transfer)
  1630. FDoListAll = (FListAll == asOn);
  1631. }
  1632. catch(Exception & E)
  1633. {
  1634. FDoListAll = false;
  1635. // reading the first directory has failed,
  1636. // further try without "-a" only as the server may not support it
  1637. if ((FListAll == asAuto) &&
  1638. (FTerminal->Active ||
  1639. FTerminal->QueryReopen(&E, ropNoReadDirectory, NULL)))
  1640. {
  1641. FListAll = asOff;
  1642. Repeat = true;
  1643. }
  1644. else
  1645. {
  1646. throw;
  1647. }
  1648. }
  1649. }
  1650. while (Repeat);
  1651. }
  1652. //---------------------------------------------------------------------------
  1653. void __fastcall TFTPFileSystem::ReadFile(const AnsiString FileName,
  1654. TRemoteFile *& File)
  1655. {
  1656. AnsiString Path = UnixExtractFilePath(FileName);
  1657. AnsiString NameOnly = UnixExtractFileName(FileName);
  1658. // FZAPI does not have efficient way to read properties of one file.
  1659. // If case we need properties of set of files from the same directory,
  1660. // cache the file list for future
  1661. TRemoteFile * AFile = NULL;
  1662. if ((FFileListCache != NULL) &&
  1663. UnixComparePaths(Path, FFileListCache->Directory) &&
  1664. (TTerminal::IsAbsolutePath(FFileListCache->Directory) ||
  1665. (FFileListCachePath == CurrentDirectory)))
  1666. {
  1667. AFile = FFileListCache->FindFile(NameOnly);
  1668. }
  1669. // if cache is invalid or file is not in cache, (re)read the directory
  1670. if (AFile == NULL)
  1671. {
  1672. delete FFileListCache;
  1673. FFileListCache = NULL;
  1674. FFileListCache = new TRemoteFileList();
  1675. FFileListCache->Directory = Path;
  1676. ReadDirectory(FFileListCache);
  1677. FFileListCachePath = CurrentDirectory;
  1678. AFile = FFileListCache->FindFile(NameOnly);
  1679. if (AFile == NULL)
  1680. {
  1681. File = NULL;
  1682. throw Exception(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  1683. }
  1684. }
  1685. assert(AFile != NULL);
  1686. File = AFile->Duplicate();
  1687. }
  1688. //---------------------------------------------------------------------------
  1689. void __fastcall TFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  1690. TRemoteFile *& File)
  1691. {
  1692. // Resolving symlinks over FTP is big overhead
  1693. // (involves opening TCPIP connection for retrieving "directory listing").
  1694. // Moreover FZAPI does not support that anyway.
  1695. File = new TRemoteFile(SymlinkFile);
  1696. try
  1697. {
  1698. File->Terminal = FTerminal;
  1699. File->FileName = UnixExtractFileName(SymlinkFile->LinkTo);
  1700. // FZAPI treats all symlink target as directories
  1701. File->Type = FILETYPE_DIRECTORY;
  1702. }
  1703. catch(...)
  1704. {
  1705. delete File;
  1706. File = NULL;
  1707. throw;
  1708. }
  1709. }
  1710. //---------------------------------------------------------------------------
  1711. void __fastcall TFTPFileSystem::RenameFile(const AnsiString AFileName,
  1712. const AnsiString ANewName)
  1713. {
  1714. AnsiString FileName = AbsolutePath(AFileName, false);
  1715. AnsiString NewName = AbsolutePath(ANewName, false);
  1716. AnsiString FileNameOnly = UnixExtractFileName(FileName);
  1717. AnsiString FilePathOnly = UnixExtractFilePath(FileName);
  1718. AnsiString NewNameOnly = UnixExtractFileName(NewName);
  1719. AnsiString NewPathOnly = UnixExtractFilePath(NewName);
  1720. {
  1721. // ignore file list
  1722. TFileListHelper Helper(this, NULL, true);
  1723. FFileZillaIntf->Rename(FileNameOnly.c_str(), NewNameOnly.c_str(),
  1724. FilePathOnly.c_str(), NewPathOnly.c_str());
  1725. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1726. }
  1727. }
  1728. //---------------------------------------------------------------------------
  1729. void __fastcall TFTPFileSystem::CopyFile(const AnsiString FileName,
  1730. const AnsiString NewName)
  1731. {
  1732. assert(false);
  1733. }
  1734. //---------------------------------------------------------------------------
  1735. AnsiString __fastcall TFTPFileSystem::FileUrl(const AnsiString FileName)
  1736. {
  1737. return FTerminal->FileUrl("ftp", FileName);
  1738. }
  1739. //---------------------------------------------------------------------------
  1740. TStrings * __fastcall TFTPFileSystem::GetFixedPaths()
  1741. {
  1742. return NULL;
  1743. }
  1744. //---------------------------------------------------------------------------
  1745. void __fastcall TFTPFileSystem::SpaceAvailable(const AnsiString /*Path*/,
  1746. TSpaceAvailable & /*ASpaceAvailable*/)
  1747. {
  1748. assert(false);
  1749. }
  1750. //---------------------------------------------------------------------------
  1751. const TSessionInfo & __fastcall TFTPFileSystem::GetSessionInfo()
  1752. {
  1753. return FSessionInfo;
  1754. }
  1755. //---------------------------------------------------------------------------
  1756. const TFileSystemInfo & __fastcall TFTPFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  1757. {
  1758. if (!FFileSystemInfoValid)
  1759. {
  1760. FFileSystemInfo.RemoteSystem = FSystem;
  1761. FFileSystemInfo.RemoteSystem.Unique();
  1762. if (FFeatures->Count == 0)
  1763. {
  1764. FFileSystemInfo.AdditionalInfo = LoadStr(FTP_NO_FEATURE_INFO);
  1765. }
  1766. else
  1767. {
  1768. FFileSystemInfo.AdditionalInfo =
  1769. FORMAT("%s\r\n", (LoadStr(FTP_FEATURE_INFO)));
  1770. for (int Index = 0; Index < FFeatures->Count; Index++)
  1771. {
  1772. FFileSystemInfo.AdditionalInfo += FORMAT(" %s\r\n", (FFeatures->Strings[Index]));
  1773. }
  1774. }
  1775. for (int Index = 0; Index < fcCount; Index++)
  1776. {
  1777. FFileSystemInfo.IsCapable[Index] = IsCapable((TFSCapability)Index);
  1778. }
  1779. FFileSystemInfoValid = true;
  1780. }
  1781. return FFileSystemInfo;
  1782. }
  1783. //---------------------------------------------------------------------------
  1784. bool __fastcall TFTPFileSystem::TemporaryTransferFile(const AnsiString & /*FileName*/)
  1785. {
  1786. return false;
  1787. }
  1788. //---------------------------------------------------------------------------
  1789. bool __fastcall TFTPFileSystem::GetStoredCredentialsTried()
  1790. {
  1791. return !FTerminal->SessionData->Password.IsEmpty();
  1792. }
  1793. //---------------------------------------------------------------------------
  1794. AnsiString __fastcall TFTPFileSystem::GetUserName()
  1795. {
  1796. return FUserName;
  1797. }
  1798. //---------------------------------------------------------------------------
  1799. AnsiString __fastcall TFTPFileSystem::GetCurrentDirectory()
  1800. {
  1801. return FCurrentDirectory;
  1802. }
  1803. //---------------------------------------------------------------------------
  1804. const char * __fastcall TFTPFileSystem::GetOption(int OptionID) const
  1805. {
  1806. TSessionData * Data = FTerminal->SessionData;
  1807. switch (OptionID)
  1808. {
  1809. case OPTION_PROXYHOST:
  1810. case OPTION_FWHOST:
  1811. FOptionScratch = Data->ProxyHost;
  1812. break;
  1813. case OPTION_PROXYUSER:
  1814. case OPTION_FWUSER:
  1815. FOptionScratch = Data->ProxyUsername;
  1816. break;
  1817. case OPTION_PROXYPASS:
  1818. case OPTION_FWPASS:
  1819. FOptionScratch = Data->ProxyPassword;
  1820. break;
  1821. case OPTION_ANONPWD:
  1822. case OPTION_TRANSFERIP:
  1823. case OPTION_TRANSFERIP6:
  1824. FOptionScratch = "";
  1825. break;
  1826. default:
  1827. assert(false);
  1828. FOptionScratch = "";
  1829. }
  1830. return FOptionScratch.c_str();
  1831. }
  1832. //---------------------------------------------------------------------------
  1833. int __fastcall TFTPFileSystem::GetOptionVal(int OptionID) const
  1834. {
  1835. TSessionData * Data = FTerminal->SessionData;
  1836. int Result;
  1837. switch (OptionID)
  1838. {
  1839. case OPTION_PROXYTYPE:
  1840. switch (Data->ProxyMethod)
  1841. {
  1842. case pmNone:
  1843. Result = 0; // PROXYTYPE_NOPROXY;
  1844. break;
  1845. case pmSocks4:
  1846. Result = 2; // PROXYTYPE_SOCKS4A
  1847. break;
  1848. case pmSocks5:
  1849. Result = 3; // PROXYTYPE_SOCKS5
  1850. break;
  1851. case pmHTTP:
  1852. Result = 4; // PROXYTYPE_HTTP11
  1853. break;
  1854. case pmTelnet:
  1855. case pmCmd:
  1856. default:
  1857. assert(false);
  1858. Result = 0; // PROXYTYPE_NOPROXY;
  1859. break;
  1860. }
  1861. break;
  1862. case OPTION_PROXYPORT:
  1863. case OPTION_FWPORT:
  1864. Result = Data->ProxyPort;
  1865. break;
  1866. case OPTION_PROXYUSELOGON:
  1867. Result = !Data->ProxyUsername.IsEmpty();
  1868. break;
  1869. case OPTION_LOGONTYPE:
  1870. Result = Data->FtpProxyLogonType;
  1871. break;
  1872. case OPTION_TIMEOUTLENGTH:
  1873. Result = Data->Timeout;
  1874. break;
  1875. case OPTION_DEBUGSHOWLISTING:
  1876. // Listing is logged on FZAPI level 5 (what is strangely LOG_APIERROR)
  1877. Result = (FTerminal->Configuration->ActualLogProtocol >= 1);
  1878. break;
  1879. case OPTION_PASV:
  1880. // should never get here t_server.nPasv being nonzero
  1881. assert(false);
  1882. Result = FALSE;
  1883. break;
  1884. case OPTION_PRESERVEDOWNLOADFILETIME:
  1885. case OPTION_MPEXT_PRESERVEUPLOADFILETIME:
  1886. Result = FFileTransferPreserveTime ? TRUE : FALSE;
  1887. break;
  1888. case OPTION_LIMITPORTRANGE:
  1889. Result = FALSE;
  1890. break;
  1891. case OPTION_PORTRANGELOW:
  1892. case OPTION_PORTRANGEHIGH:
  1893. // should never get here OPTION_LIMITPORTRANGE being zero
  1894. assert(false);
  1895. Result = 0;
  1896. break;
  1897. case OPTION_ENABLE_IPV6:
  1898. Result = ((Data->AddressFamily == afIPv6) ? TRUE : FALSE);
  1899. break;
  1900. case OPTION_KEEPALIVE:
  1901. Result = ((Data->FtpPingType != ptOff) ? TRUE : FALSE);
  1902. break;
  1903. case OPTION_INTERVALLOW:
  1904. case OPTION_INTERVALHIGH:
  1905. Result = Data->FtpPingInterval;
  1906. break;
  1907. case OPTION_VMSALLREVISIONS:
  1908. Result = FALSE;
  1909. break;
  1910. case OPTION_SPEEDLIMIT_DOWNLOAD_TYPE:
  1911. case OPTION_SPEEDLIMIT_UPLOAD_TYPE:
  1912. Result = (FFileTransferCPSLimit == 0 ? 0 : 1);
  1913. break;
  1914. case OPTION_SPEEDLIMIT_DOWNLOAD_VALUE:
  1915. case OPTION_SPEEDLIMIT_UPLOAD_VALUE:
  1916. Result = (FFileTransferCPSLimit / 1024); // FZAPI expects KiB/s
  1917. break;
  1918. case OPTION_MPEXT_SHOWHIDDEN:
  1919. Result = (FDoListAll ? TRUE : FALSE);
  1920. break;
  1921. default:
  1922. assert(false);
  1923. Result = FALSE;
  1924. break;
  1925. }
  1926. return Result;
  1927. }
  1928. //---------------------------------------------------------------------------
  1929. bool __fastcall TFTPFileSystem::PostMessage(unsigned int Type, WPARAM wParam, LPARAM lParam)
  1930. {
  1931. if (Type == TFileZillaIntf::MSG_TRANSFERSTATUS)
  1932. {
  1933. // Stop here if FileTransferProgress is proceeding,
  1934. // it makes "pause" in queue work.
  1935. // Paused queue item stops in some of the TFileOperationProgressType
  1936. // methods called from FileTransferProgress
  1937. TGuard Guard(FTransferStatusCriticalSection);
  1938. }
  1939. TGuard Guard(FQueueCriticalSection);
  1940. FQueue->push_back(TMessageQueue::value_type(wParam, lParam));
  1941. SetEvent(FQueueEvent);
  1942. return true;
  1943. }
  1944. //---------------------------------------------------------------------------
  1945. bool __fastcall TFTPFileSystem::ProcessMessage()
  1946. {
  1947. bool Result;
  1948. TMessageQueue::value_type Message;
  1949. {
  1950. TGuard Guard(FQueueCriticalSection);
  1951. Result = !FQueue->empty();
  1952. if (Result)
  1953. {
  1954. Message = FQueue->front();
  1955. FQueue->pop_front();
  1956. }
  1957. else
  1958. {
  1959. // now we are perfecly sure that the queue is empty as it is locked,
  1960. // so reset the event
  1961. ResetEvent(FQueueEvent);
  1962. }
  1963. }
  1964. if (Result)
  1965. {
  1966. FFileZillaIntf->HandleMessage(Message.first, Message.second);
  1967. }
  1968. return Result;
  1969. }
  1970. //---------------------------------------------------------------------------
  1971. void __fastcall TFTPFileSystem::DiscardMessages()
  1972. {
  1973. while (ProcessMessage());
  1974. }
  1975. //---------------------------------------------------------------------------
  1976. void __fastcall TFTPFileSystem::WaitForMessages()
  1977. {
  1978. unsigned int Result = WaitForSingleObject(FQueueEvent, INFINITE);
  1979. if (Result != WAIT_OBJECT_0)
  1980. {
  1981. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, ("ftp#1", IntToStr(Result))));
  1982. }
  1983. }
  1984. //---------------------------------------------------------------------------
  1985. void __fastcall TFTPFileSystem::PoolForFatalNonCommandReply()
  1986. {
  1987. assert(FReply == 0);
  1988. assert(FCommandReply == 0);
  1989. assert(!FWaitingForReply);
  1990. FWaitingForReply = true;
  1991. unsigned int Reply;
  1992. try
  1993. {
  1994. // discard up to one reply
  1995. // (it should not happen here that two replies are posted anyway)
  1996. while (ProcessMessage() && (FReply == 0));
  1997. Reply = FReply;
  1998. }
  1999. __finally
  2000. {
  2001. FReply = 0;
  2002. assert(FCommandReply == 0);
  2003. FCommandReply = 0;
  2004. assert(FWaitingForReply);
  2005. FWaitingForReply = false;
  2006. }
  2007. if (Reply != 0)
  2008. {
  2009. // throws
  2010. GotNonCommandReply(Reply);
  2011. }
  2012. }
  2013. //---------------------------------------------------------------------------
  2014. bool __fastcall TFTPFileSystem::NoFinalLastCode()
  2015. {
  2016. return (FLastCodeClass == 0) || (FLastCodeClass == 1);
  2017. }
  2018. //---------------------------------------------------------------------------
  2019. bool __fastcall TFTPFileSystem::KeepWaitingForReply(unsigned int & ReplyToAwait, bool WantLastCode)
  2020. {
  2021. // to keep waiting,
  2022. // non-command reply must be unset,
  2023. // the reply we wait for must be unset or
  2024. // last code must be unset (if we wait for it)
  2025. return
  2026. (FReply == 0) &&
  2027. ((ReplyToAwait == 0) ||
  2028. (WantLastCode && NoFinalLastCode()));
  2029. }
  2030. //---------------------------------------------------------------------------
  2031. void __fastcall TFTPFileSystem::DoWaitForReply(unsigned int & ReplyToAwait, bool WantLastCode)
  2032. {
  2033. try
  2034. {
  2035. while (KeepWaitingForReply(ReplyToAwait, WantLastCode))
  2036. {
  2037. WaitForMessages();
  2038. // wait for the first reply only,
  2039. // i.e. in case two replies are posted get the first only.
  2040. // e.g. when server closes the connection, but posts error message before,
  2041. // sometime it happens that command (like download) fails because of the error
  2042. // and does not catch the disconnection. then asynchronous "disconnect reply"
  2043. // is posted immediately afterwards. leave detection of that to Idle()
  2044. while (ProcessMessage() && KeepWaitingForReply(ReplyToAwait, WantLastCode));
  2045. }
  2046. if (FReply != 0)
  2047. {
  2048. // throws
  2049. GotNonCommandReply(FReply);
  2050. }
  2051. }
  2052. catch(...)
  2053. {
  2054. // even if non-fatal error happens, we must process pending message,
  2055. // so that we "eat" the reply message, so that it gets not mistakenly
  2056. // associated with future connect
  2057. if (FTerminal->Active)
  2058. {
  2059. DoWaitForReply(ReplyToAwait, WantLastCode);
  2060. }
  2061. throw;
  2062. }
  2063. }
  2064. //---------------------------------------------------------------------------
  2065. unsigned int __fastcall TFTPFileSystem::WaitForReply(bool Command, bool WantLastCode)
  2066. {
  2067. assert(FReply == 0);
  2068. assert(FCommandReply == 0);
  2069. assert(!FWaitingForReply);
  2070. assert(!FTransferStatusCriticalSection->Acquired);
  2071. ResetReply();
  2072. FWaitingForReply = true;
  2073. unsigned int Reply;
  2074. try
  2075. {
  2076. unsigned int & ReplyToAwait = (Command ? FCommandReply : FReply);
  2077. DoWaitForReply(ReplyToAwait, WantLastCode);
  2078. Reply = ReplyToAwait;
  2079. }
  2080. __finally
  2081. {
  2082. FReply = 0;
  2083. FCommandReply = 0;
  2084. assert(FWaitingForReply);
  2085. FWaitingForReply = false;
  2086. }
  2087. return Reply;
  2088. }
  2089. //---------------------------------------------------------------------------
  2090. unsigned int __fastcall TFTPFileSystem::WaitForCommandReply(bool WantLastCode)
  2091. {
  2092. return WaitForReply(true, WantLastCode);
  2093. }
  2094. //---------------------------------------------------------------------------
  2095. void __fastcall TFTPFileSystem::WaitForFatalNonCommandReply()
  2096. {
  2097. WaitForReply(false, false);
  2098. assert(false);
  2099. }
  2100. //---------------------------------------------------------------------------
  2101. void __fastcall TFTPFileSystem::ResetReply()
  2102. {
  2103. FLastCode = 0;
  2104. FLastCodeClass = 0;
  2105. assert(FLastResponse != NULL);
  2106. FLastResponse->Clear();
  2107. assert(FLastError != NULL);
  2108. FLastError->Clear();
  2109. }
  2110. //---------------------------------------------------------------------------
  2111. void __fastcall TFTPFileSystem::GotNonCommandReply(unsigned int Reply)
  2112. {
  2113. assert(FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2114. GotReply(Reply);
  2115. // should never get here as GotReply should raise fatal exception
  2116. assert(false);
  2117. }
  2118. //---------------------------------------------------------------------------
  2119. void __fastcall TFTPFileSystem::GotReply(unsigned int Reply, unsigned int Flags,
  2120. AnsiString Error, unsigned int * Code, TStrings ** Response)
  2121. {
  2122. try
  2123. {
  2124. if (FLAGSET(Reply, TFileZillaIntf::REPLY_OK))
  2125. {
  2126. assert(Reply == TFileZillaIntf::REPLY_OK);
  2127. // With REPLY_2XX_CODE treat "OK" non-2xx code like an error
  2128. if (FLAGSET(Flags, REPLY_2XX_CODE) && (FLastCodeClass != 2))
  2129. {
  2130. GotReply(TFileZillaIntf::REPLY_ERROR, Flags, Error);
  2131. }
  2132. }
  2133. else if (FLAGSET(Reply, TFileZillaIntf::REPLY_CANCEL) &&
  2134. FLAGSET(Flags, REPLY_ALLOW_CANCEL))
  2135. {
  2136. assert(
  2137. (Reply == (TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)) ||
  2138. (Reply == (TFileZillaIntf::REPLY_ABORTED | TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)));
  2139. // noop
  2140. }
  2141. // we do not expect these with our usage of FZ
  2142. else if (Reply &
  2143. (TFileZillaIntf::REPLY_WOULDBLOCK | TFileZillaIntf::REPLY_OWNERNOTSET |
  2144. TFileZillaIntf::REPLY_INVALIDPARAM | TFileZillaIntf::REPLY_ALREADYCONNECTED |
  2145. TFileZillaIntf::REPLY_IDLE | TFileZillaIntf::REPLY_NOTINITIALIZED |
  2146. TFileZillaIntf::REPLY_ALREADYINIZIALIZED))
  2147. {
  2148. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, ("ftp#2", FORMAT("0x%x", (int(Reply))))));
  2149. }
  2150. else
  2151. {
  2152. // everything else must be an error or disconnect notification
  2153. assert(
  2154. FLAGSET(Reply, TFileZillaIntf::REPLY_ERROR) ||
  2155. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2156. // TODO: REPLY_CRITICALERROR ignored
  2157. // REPLY_NOTCONNECTED happens if connection is closed between moment
  2158. // when FZAPI interface method dispatches the command to FZAPI thread
  2159. // and moment when FZAPI thread receives the command
  2160. bool Disconnected =
  2161. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED) ||
  2162. FLAGSET(Reply, TFileZillaIntf::REPLY_NOTCONNECTED);
  2163. TStrings * MoreMessages = new TStringList();
  2164. try
  2165. {
  2166. if (Disconnected)
  2167. {
  2168. if (FLAGCLEAR(Flags, REPLY_CONNECT))
  2169. {
  2170. MoreMessages->Add(LoadStr(LOST_CONNECTION));
  2171. Discard();
  2172. FTerminal->Closed();
  2173. }
  2174. else
  2175. {
  2176. // For connection failure, do not report that connection was lost,
  2177. // its obvious.
  2178. // Also do not report to terminal that we are closed as
  2179. // that turns terminal into closed mode, but we want to
  2180. // pretend (at least with failed authentication) to retry
  2181. // with the same connection (as with SSH), so we explicitly
  2182. // close terminal in Open() only after we give up
  2183. Discard();
  2184. }
  2185. }
  2186. if (FLAGSET(Reply, TFileZillaIntf::REPLY_ABORTED))
  2187. {
  2188. MoreMessages->Add(LoadStr(USER_TERMINATED));
  2189. }
  2190. if (FLAGSET(Reply, TFileZillaIntf::REPLY_NOTSUPPORTED))
  2191. {
  2192. MoreMessages->Add(LoadStr(FZ_NOTSUPPORTED));
  2193. }
  2194. if (FLastCode == 530)
  2195. {
  2196. MoreMessages->Add(LoadStr(AUTHENTICATION_FAILED));
  2197. }
  2198. if (FLastCode == 425)
  2199. {
  2200. if (!FTerminal->SessionData->FtpPasvMode)
  2201. {
  2202. MoreMessages->Add(LoadStr(FTP_CANNOT_OPEN_ACTIVE_CONNECTION));
  2203. }
  2204. }
  2205. MoreMessages->AddStrings(FLastError);
  2206. // already cleared from WaitForReply, but GotReply can be also called
  2207. // from Closed. then make sure that error from previous command not
  2208. // associated with session closure is not reused
  2209. FLastError->Clear();
  2210. MoreMessages->AddStrings(FLastResponse);
  2211. // see comment for FLastError
  2212. FLastResponse->Clear();
  2213. if (MoreMessages->Count == 0)
  2214. {
  2215. delete MoreMessages;
  2216. MoreMessages = NULL;
  2217. }
  2218. }
  2219. catch(...)
  2220. {
  2221. delete MoreMessages;
  2222. throw;
  2223. }
  2224. if (Error.IsEmpty() && (MoreMessages != NULL))
  2225. {
  2226. assert(MoreMessages->Count > 0);
  2227. Error = MoreMessages->Strings[0];
  2228. MoreMessages->Delete(0);
  2229. }
  2230. if (Disconnected)
  2231. {
  2232. // for fatal error, it is essential that there is some message
  2233. assert(!Error.IsEmpty());
  2234. ExtException * E = new ExtException(Error, MoreMessages, true);
  2235. try
  2236. {
  2237. FTerminal->FatalError(E, "");
  2238. }
  2239. __finally
  2240. {
  2241. delete E;
  2242. }
  2243. }
  2244. else
  2245. {
  2246. throw ExtException(Error, MoreMessages, true);
  2247. }
  2248. }
  2249. if ((Code != NULL) && (FLastCodeClass != DummyCodeClass))
  2250. {
  2251. *Code = FLastCode;
  2252. }
  2253. if (Response != NULL)
  2254. {
  2255. *Response = FLastResponse;
  2256. FLastResponse = new TStringList();
  2257. }
  2258. }
  2259. __finally
  2260. {
  2261. ResetReply();
  2262. }
  2263. }
  2264. //---------------------------------------------------------------------------
  2265. void __fastcall TFTPFileSystem::SetLastCode(int Code)
  2266. {
  2267. FLastCode = Code;
  2268. FLastCodeClass = (Code / 100);
  2269. }
  2270. //---------------------------------------------------------------------------
  2271. void __fastcall TFTPFileSystem::HandleReplyStatus(AnsiString Response)
  2272. {
  2273. int Code;
  2274. if (FOnCaptureOutput != NULL)
  2275. {
  2276. FOnCaptureOutput(Response, false);
  2277. }
  2278. // Two forms of multiline responses were observed
  2279. // (the first is according to the RFC 959):
  2280. // 211-Features:
  2281. // MDTM
  2282. // REST STREAM
  2283. // SIZE
  2284. // 211 End
  2285. // 211-Features:
  2286. // 211-MDTM
  2287. // 211-REST STREAM
  2288. // 211-SIZE
  2289. // 211-AUTH TLS
  2290. // 211-PBSZ
  2291. // 211-PROT
  2292. // 211 End
  2293. bool HasCodePrefix =
  2294. (Response.Length() >= 3) &&
  2295. TryStrToInt(Response.SubString(1, 3), Code) &&
  2296. (Code >= 100) && (Code <= 599) &&
  2297. ((Response.Length() == 3) || (Response[4] == ' ') || (Response[4] == '-'));
  2298. if (HasCodePrefix && !FMultineResponse)
  2299. {
  2300. FMultineResponse = (Response.Length() >= 4) && (Response[4] == '-');
  2301. FLastResponse->Clear();
  2302. if (Response.Length() >= 5)
  2303. {
  2304. FLastResponse->Add(Response.SubString(5, Response.Length() - 4));
  2305. }
  2306. SetLastCode(Code);
  2307. }
  2308. else
  2309. {
  2310. int Start;
  2311. // response with code prefix
  2312. if (HasCodePrefix && (FLastCode == Code))
  2313. {
  2314. // End of multiline response?
  2315. if ((Response.Length() <= 3) || (Response[4] == ' '))
  2316. {
  2317. FMultineResponse = false;
  2318. }
  2319. Start = 5;
  2320. }
  2321. else
  2322. {
  2323. Start = (((Response.Length() >= 1) && (Response[1] == ' ')) ? 2 : 1);
  2324. }
  2325. // Intermediate empty lines are being added
  2326. if (FMultineResponse || (Response.Length() >= Start))
  2327. {
  2328. FLastResponse->Add(Response.SubString(Start, Response.Length() - Start + 1));
  2329. }
  2330. }
  2331. if (!FMultineResponse)
  2332. {
  2333. if (FLastCode == 220)
  2334. {
  2335. if (FTerminal->Configuration->ShowFtpWelcomeMessage)
  2336. {
  2337. FTerminal->DisplayBanner(FLastResponse->Text);
  2338. }
  2339. }
  2340. else if (FLastCommand == PASS)
  2341. {
  2342. // 530 = "Not logged in."
  2343. if (FLastCode == 530)
  2344. {
  2345. FPasswordFailed = true;
  2346. };
  2347. }
  2348. else if (FLastCommand == SYST)
  2349. {
  2350. assert(FSystem.IsEmpty());
  2351. // Possitive reply to "SYST" must be 215, see RFC 959
  2352. if (FLastCode == 215)
  2353. {
  2354. FSystem = FLastResponse->Text.TrimRight();
  2355. // full name is "Personal FTP Server PRO K6.0"
  2356. if ((FListAll == asAuto) &&
  2357. (FSystem.Pos("Personal FTP Server") > 0))
  2358. {
  2359. FTerminal->LogEvent("Server is known not to support LIST -a");
  2360. FListAll = asOff;
  2361. }
  2362. }
  2363. else
  2364. {
  2365. FSystem = "";
  2366. }
  2367. }
  2368. else if (FLastCommand == FEAT)
  2369. {
  2370. // Response to FEAT must be multiline, where leading and trailing line
  2371. // is "meaningless". See RFC 2389.
  2372. if ((FLastCode == 211) && (FLastResponse->Count > 2))
  2373. {
  2374. FLastResponse->Delete(0);
  2375. FLastResponse->Delete(FLastResponse->Count - 1);
  2376. FFeatures->Assign(FLastResponse);
  2377. }
  2378. else
  2379. {
  2380. FFeatures->Clear();
  2381. }
  2382. }
  2383. }
  2384. }
  2385. //---------------------------------------------------------------------------
  2386. AnsiString __fastcall TFTPFileSystem::ExtractStatusMessage(AnsiString Status)
  2387. {
  2388. // CApiLog::LogMessage
  2389. // (note that the formatting may not be present when LogMessageRaw is used)
  2390. int P1 = Status.Pos("): ");
  2391. if (P1 > 0)
  2392. {
  2393. int P2 = Status.Pos(".cpp(");
  2394. if ((P2 > 0) && (P2 < P1))
  2395. {
  2396. int P3 = Status.Pos(" caller=0x");
  2397. if ((P3 > 0) && (P3 > P1))
  2398. {
  2399. Status = Status.SubString(P1 + 3, P3 - P1 - 3);
  2400. }
  2401. }
  2402. }
  2403. return Status;
  2404. }
  2405. //---------------------------------------------------------------------------
  2406. bool __fastcall TFTPFileSystem::HandleStatus(const char * AStatus, int Type)
  2407. {
  2408. TLogLineType LogType = (TLogLineType)-1;
  2409. AnsiString Status(AStatus);
  2410. switch (Type)
  2411. {
  2412. case TFileZillaIntf::LOG_STATUS:
  2413. FTerminal->Information(Status, true);
  2414. LogType = llMessage;
  2415. break;
  2416. case TFileZillaIntf::LOG_COMMAND:
  2417. if (Status == "SYST")
  2418. {
  2419. FLastCommand = SYST;
  2420. }
  2421. else if (Status == "FEAT")
  2422. {
  2423. FLastCommand = FEAT;
  2424. }
  2425. else if (Status.SubString(1, 5) == "PASS ")
  2426. {
  2427. FLastCommand = PASS;
  2428. }
  2429. else
  2430. {
  2431. FLastCommand = CMD_UNKNOWN;
  2432. }
  2433. LogType = llInput;
  2434. break;
  2435. case TFileZillaIntf::LOG_ERROR:
  2436. case TFileZillaIntf::LOG_APIERROR:
  2437. case TFileZillaIntf::LOG_WARNING:
  2438. // when timeout message occurs, break loop waiting for response code
  2439. // by setting dummy one
  2440. if (Type == TFileZillaIntf::LOG_ERROR)
  2441. {
  2442. if (Status == FTimeoutStatus)
  2443. {
  2444. if (NoFinalLastCode())
  2445. {
  2446. SetLastCode(DummyTimeoutCode);
  2447. }
  2448. }
  2449. else if (Status == FDisconnectStatus)
  2450. {
  2451. if (NoFinalLastCode())
  2452. {
  2453. SetLastCode(DummyDisconnectCode);
  2454. }
  2455. }
  2456. }
  2457. // there can be multiple error messages associated with single failure
  2458. // (such as "cannot open local file..." followed by "download failed")
  2459. Status = ExtractStatusMessage(Status);
  2460. FLastError->Add(Status);
  2461. LogType = llMessage;
  2462. break;
  2463. case TFileZillaIntf::LOG_REPLY:
  2464. HandleReplyStatus(AStatus);
  2465. LogType = llOutput;
  2466. break;
  2467. case TFileZillaIntf::LOG_INFO:
  2468. Status = ExtractStatusMessage(Status);
  2469. LogType = llMessage;
  2470. break;
  2471. case TFileZillaIntf::LOG_DEBUG:
  2472. // used for directory listing only
  2473. LogType = llMessage;
  2474. break;
  2475. default:
  2476. assert(false);
  2477. break;
  2478. }
  2479. if (FTerminal->Log->Logging && (LogType != (TLogLineType)-1))
  2480. {
  2481. FTerminal->Log->Add(LogType, Status);
  2482. }
  2483. return true;
  2484. }
  2485. //---------------------------------------------------------------------------
  2486. TDateTime __fastcall TFTPFileSystem::ConvertLocalTimestamp(time_t Time)
  2487. {
  2488. // This reverses how FZAPI converts FILETIME to time_t,
  2489. // before passing it to FZ_ASYNCREQUEST_OVERWRITE.
  2490. __int64 Timestamp;
  2491. tm * Tm = localtime(&Time);
  2492. if (Tm != NULL)
  2493. {
  2494. SYSTEMTIME SystemTime;
  2495. SystemTime.wYear = static_cast<WORD>(Tm->tm_year + 1900);
  2496. SystemTime.wMonth = static_cast<WORD>(Tm->tm_mon + 1);
  2497. SystemTime.wDayOfWeek = 0;
  2498. SystemTime.wDay = static_cast<WORD>(Tm->tm_mday);
  2499. SystemTime.wHour = static_cast<WORD>(Tm->tm_hour);
  2500. SystemTime.wMinute = static_cast<WORD>(Tm->tm_min);
  2501. SystemTime.wSecond = static_cast<WORD>(Tm->tm_sec);
  2502. SystemTime.wMilliseconds = 0;
  2503. FILETIME LocalTime;
  2504. SystemTimeToFileTime(&SystemTime, &LocalTime);
  2505. FILETIME FileTime;
  2506. LocalFileTimeToFileTime(&LocalTime, &FileTime);
  2507. Timestamp = ConvertTimestampToUnixSafe(FileTime, dstmUnix);
  2508. }
  2509. else
  2510. {
  2511. // incorrect, but at least something
  2512. Timestamp = Time;
  2513. }
  2514. return UnixToDateTime(Timestamp, dstmUnix);
  2515. }
  2516. //---------------------------------------------------------------------------
  2517. TDateTime __fastcall TFTPFileSystem::ConvertRemoteTimestamp(time_t Time, bool HasTime)
  2518. {
  2519. TDateTime Result;
  2520. tm * Tm = localtime(&Time);
  2521. if (Tm != NULL)
  2522. {
  2523. // should be the same as HandleListData
  2524. Result = EncodeDateVerbose(
  2525. static_cast<unsigned short>(Tm->tm_year + 1900),
  2526. static_cast<unsigned short>(Tm->tm_mon + 1),
  2527. static_cast<unsigned short>(Tm->tm_mday));
  2528. if (HasTime)
  2529. {
  2530. Result += EncodeTimeVerbose(
  2531. static_cast<unsigned short>(Tm->tm_hour),
  2532. static_cast<unsigned short>(Tm->tm_min),
  2533. static_cast<unsigned short>(Tm->tm_sec), 0);
  2534. }
  2535. }
  2536. else
  2537. {
  2538. // incorrect, but at least something
  2539. Result = UnixToDateTime(Time, dstmUnix);
  2540. }
  2541. return Result;
  2542. }
  2543. //---------------------------------------------------------------------------
  2544. bool __fastcall TFTPFileSystem::HandleAsynchRequestOverwrite(
  2545. char * FileName1, size_t FileName1Len, const char * /*FileName2*/,
  2546. const char * /*Path1*/, const char * /*Path2*/,
  2547. __int64 Size1, __int64 Size2, time_t Time1, time_t Time2,
  2548. bool HasTime1, bool HasTime2, void * AUserData, int & RequestResult)
  2549. {
  2550. if (!FActive)
  2551. {
  2552. return false;
  2553. }
  2554. else
  2555. {
  2556. TFileTransferData & UserData = *((TFileTransferData *)AUserData);
  2557. if (UserData.OverwriteResult >= 0)
  2558. {
  2559. // on retry, use the same answer as on the first attempt
  2560. RequestResult = UserData.OverwriteResult;
  2561. }
  2562. else
  2563. {
  2564. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  2565. AnsiString FileName = FileName1;
  2566. assert(UserData.FileName == FileName);
  2567. TOverwriteMode OverwriteMode = omOverwrite;
  2568. TOverwriteFileParams FileParams;
  2569. bool NoFileParams =
  2570. (Size1 < 0) || (Time1 == 0) ||
  2571. (Size2 < 0) || (Time2 == 0);
  2572. if (!NoFileParams)
  2573. {
  2574. FileParams.SourceSize = Size2;
  2575. FileParams.DestSize = Size1;
  2576. if (OperationProgress->Side == osLocal)
  2577. {
  2578. FileParams.SourceTimestamp = ConvertLocalTimestamp(Time2);
  2579. FileParams.DestTimestamp = ConvertRemoteTimestamp(Time1, HasTime1);
  2580. FileParams.DestPrecision = (HasTime1 ? mfMDHM : mfMDY);
  2581. }
  2582. else
  2583. {
  2584. FileParams.SourceTimestamp = ConvertRemoteTimestamp(Time2, HasTime2);
  2585. FileParams.SourcePrecision = (HasTime2 ? mfMDHM : mfMDY);
  2586. FileParams.DestTimestamp = ConvertLocalTimestamp(Time1);
  2587. }
  2588. }
  2589. if (ConfirmOverwrite(FileName, OverwriteMode, OperationProgress,
  2590. (NoFileParams ? NULL : &FileParams), UserData.Params,
  2591. UserData.AutoResume && UserData.CopyParam->AllowResume(FileParams.SourceSize)))
  2592. {
  2593. switch (OverwriteMode)
  2594. {
  2595. case omOverwrite:
  2596. if (FileName != FileName1)
  2597. {
  2598. strncpy(FileName1, FileName.c_str(), FileName1Len);
  2599. FileName1[FileName1Len - 1] = '\0';
  2600. UserData.FileName = FileName1;
  2601. RequestResult = TFileZillaIntf::FILEEXISTS_RENAME;
  2602. }
  2603. else
  2604. {
  2605. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  2606. }
  2607. break;
  2608. case omResume:
  2609. RequestResult = TFileZillaIntf::FILEEXISTS_RESUME;
  2610. break;
  2611. default:
  2612. assert(false);
  2613. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  2614. break;
  2615. }
  2616. }
  2617. else
  2618. {
  2619. RequestResult = TFileZillaIntf::FILEEXISTS_SKIP;
  2620. }
  2621. }
  2622. // remember the answer for the retries
  2623. UserData.OverwriteResult = RequestResult;
  2624. if (RequestResult == TFileZillaIntf::FILEEXISTS_SKIP)
  2625. {
  2626. // when user chosses not to overwrite, break loop waiting for response code
  2627. // by setting dummy one, az FZAPI won't do anything then
  2628. SetLastCode(DummyTimeoutCode);
  2629. }
  2630. return true;
  2631. }
  2632. }
  2633. //---------------------------------------------------------------------------
  2634. struct TClipboardHandler
  2635. {
  2636. AnsiString Text;
  2637. void __fastcall Copy(TObject * /*Sender*/)
  2638. {
  2639. CopyToClipboard(Text);
  2640. }
  2641. };
  2642. //---------------------------------------------------------------------------
  2643. AnsiString __fastcall FormatContactList(AnsiString Entry1, AnsiString Entry2)
  2644. {
  2645. if (!Entry1.IsEmpty() && !Entry2.IsEmpty())
  2646. {
  2647. return FORMAT("%s, %s", (Entry1, Entry2));
  2648. }
  2649. else
  2650. {
  2651. return Entry1 + Entry2;
  2652. }
  2653. }
  2654. //---------------------------------------------------------------------------
  2655. AnsiString __fastcall FormatContact(const TFtpsCertificateData::TContact & Contact)
  2656. {
  2657. AnsiString Result =
  2658. FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 1),
  2659. (FormatContactList(FormatContactList(FormatContactList(
  2660. Contact.Organization, Contact.Unit), Contact.CommonName), Contact.Mail)));
  2661. if ((strlen(Contact.Country) > 0) ||
  2662. (strlen(Contact.StateProvince) > 0) ||
  2663. (strlen(Contact.Town) > 0))
  2664. {
  2665. Result +=
  2666. FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 2),
  2667. (FormatContactList(FormatContactList(
  2668. Contact.Country, Contact.StateProvince), Contact.Town)));
  2669. }
  2670. if (strlen(Contact.Other) > 0)
  2671. {
  2672. Result += FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 3), (Contact.Other));
  2673. }
  2674. return Result;
  2675. }
  2676. //---------------------------------------------------------------------------
  2677. AnsiString __fastcall FormatValidityTime(const TFtpsCertificateData::TValidityTime & ValidityTime)
  2678. {
  2679. return FormatDateTime("ddddd tt",
  2680. EncodeDateVerbose(
  2681. (unsigned short)ValidityTime.Year, (unsigned short)ValidityTime.Month,
  2682. (unsigned short)ValidityTime.Day) +
  2683. EncodeTimeVerbose(
  2684. (unsigned short)ValidityTime.Hour, (unsigned short)ValidityTime.Min,
  2685. (unsigned short)ValidityTime.Sec, 0));
  2686. }
  2687. //---------------------------------------------------------------------------
  2688. bool __fastcall TFTPFileSystem::HandleAsynchRequestVerifyCertificate(
  2689. const TFtpsCertificateData & Data, int & RequestResult)
  2690. {
  2691. if (!FActive)
  2692. {
  2693. return false;
  2694. }
  2695. else
  2696. {
  2697. FSessionInfo.CertificateFingerprint =
  2698. StrToHex(AnsiString((const char*)Data.Hash, Data.HashLen), false, ':');
  2699. int VerificationResultStr;
  2700. switch (Data.VerificationResult)
  2701. {
  2702. case X509_V_OK:
  2703. VerificationResultStr = CERT_OK;
  2704. break;
  2705. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
  2706. VerificationResultStr = CERT_ERR_UNABLE_TO_GET_ISSUER_CERT;
  2707. break;
  2708. case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
  2709. VerificationResultStr = CERT_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE;
  2710. break;
  2711. case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
  2712. VerificationResultStr = CERT_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
  2713. break;
  2714. case X509_V_ERR_CERT_SIGNATURE_FAILURE:
  2715. VerificationResultStr = CERT_ERR_CERT_SIGNATURE_FAILURE;
  2716. break;
  2717. case X509_V_ERR_CERT_NOT_YET_VALID:
  2718. VerificationResultStr = CERT_ERR_CERT_NOT_YET_VALID;
  2719. break;
  2720. case X509_V_ERR_CERT_HAS_EXPIRED:
  2721. VerificationResultStr = CERT_ERR_CERT_HAS_EXPIRED;
  2722. break;
  2723. case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
  2724. VerificationResultStr = CERT_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
  2725. break;
  2726. case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
  2727. VerificationResultStr = CERT_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
  2728. break;
  2729. case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
  2730. VerificationResultStr = CERT_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
  2731. break;
  2732. case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
  2733. VerificationResultStr = CERT_ERR_SELF_SIGNED_CERT_IN_CHAIN;
  2734. break;
  2735. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
  2736. VerificationResultStr = CERT_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
  2737. break;
  2738. case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
  2739. VerificationResultStr = CERT_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
  2740. break;
  2741. case X509_V_ERR_INVALID_CA:
  2742. VerificationResultStr = CERT_ERR_INVALID_CA;
  2743. break;
  2744. case X509_V_ERR_PATH_LENGTH_EXCEEDED:
  2745. VerificationResultStr = CERT_ERR_PATH_LENGTH_EXCEEDED;
  2746. break;
  2747. case X509_V_ERR_INVALID_PURPOSE:
  2748. VerificationResultStr = CERT_ERR_INVALID_PURPOSE;
  2749. break;
  2750. case X509_V_ERR_CERT_UNTRUSTED:
  2751. VerificationResultStr = CERT_ERR_CERT_UNTRUSTED;
  2752. break;
  2753. case X509_V_ERR_CERT_REJECTED:
  2754. VerificationResultStr = CERT_ERR_CERT_REJECTED;
  2755. break;
  2756. case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
  2757. VerificationResultStr = CERT_ERR_KEYUSAGE_NO_CERTSIGN;
  2758. break;
  2759. case X509_V_ERR_CERT_CHAIN_TOO_LONG:
  2760. VerificationResultStr = CERT_ERR_CERT_CHAIN_TOO_LONG;
  2761. break;
  2762. default:
  2763. VerificationResultStr = CERT_ERR_UNKNOWN;
  2764. break;
  2765. }
  2766. AnsiString Summary = LoadStr(VerificationResultStr);
  2767. if (Data.VerificationResult != X509_V_OK)
  2768. {
  2769. Summary += " " + FMTLOAD(CERT_ERRDEPTH, (Data.VerificationDepth + 1));
  2770. }
  2771. FSessionInfo.Certificate =
  2772. FMTLOAD(CERT_TEXT, (
  2773. FormatContact(Data.Subject),
  2774. FormatContact(Data.Issuer),
  2775. FormatValidityTime(Data.ValidFrom),
  2776. FormatValidityTime(Data.ValidUntil),
  2777. FSessionInfo.CertificateFingerprint,
  2778. Summary));
  2779. RequestResult = 0;
  2780. THierarchicalStorage * Storage =
  2781. FTerminal->Configuration->CreateScpStorage(false);
  2782. try
  2783. {
  2784. Storage->AccessMode = smRead;
  2785. if (Storage->OpenSubKey(CertificateStorageKey, false) &&
  2786. Storage->ValueExists(FSessionInfo.CertificateFingerprint))
  2787. {
  2788. RequestResult = 1;
  2789. }
  2790. }
  2791. __finally
  2792. {
  2793. delete Storage;
  2794. }
  2795. if (RequestResult == 0)
  2796. {
  2797. AnsiString Buf = FTerminal->SessionData->HostKey;
  2798. while ((RequestResult == 0) && !Buf.IsEmpty())
  2799. {
  2800. AnsiString ExpectedKey = CutToChar(Buf, ';', false);
  2801. if (ExpectedKey == FSessionInfo.CertificateFingerprint)
  2802. {
  2803. RequestResult = 1;
  2804. }
  2805. }
  2806. }
  2807. if (RequestResult == 0)
  2808. {
  2809. TClipboardHandler ClipboardHandler;
  2810. ClipboardHandler.Text = FSessionInfo.CertificateFingerprint;
  2811. TQueryButtonAlias Aliases[1];
  2812. Aliases[0].Button = qaRetry;
  2813. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  2814. Aliases[0].OnClick = &ClipboardHandler.Copy;
  2815. TQueryParams Params;
  2816. Params.HelpKeyword = HELP_VERIFY_CERTIFICATE;
  2817. Params.NoBatchAnswers = qaYes | qaRetry;
  2818. Params.Aliases = Aliases;
  2819. Params.AliasesCount = LENOF(Aliases);
  2820. int Answer = FTerminal->QueryUser(
  2821. FMTLOAD(VERIFY_CERT_PROMPT2, (FSessionInfo.Certificate)),
  2822. NULL, qaYes | qaNo | qaCancel | qaRetry, &Params, qtWarning);
  2823. switch (Answer)
  2824. {
  2825. case qaYes:
  2826. // 2 = always, as used by FZ's VerifyCertDlg.cpp,
  2827. // however FZAPI takes all non-zero values equally
  2828. RequestResult = 2;
  2829. break;
  2830. case qaNo:
  2831. RequestResult = 1;
  2832. break;
  2833. case qaCancel:
  2834. RequestResult = 0;
  2835. break;
  2836. default:
  2837. assert(false);
  2838. RequestResult = 0;
  2839. break;
  2840. }
  2841. if (RequestResult == 2)
  2842. {
  2843. THierarchicalStorage * Storage =
  2844. FTerminal->Configuration->CreateScpStorage(false);
  2845. try
  2846. {
  2847. Storage->AccessMode = smReadWrite;
  2848. if (Storage->OpenSubKey(CertificateStorageKey, true))
  2849. {
  2850. Storage->WriteString(FSessionInfo.CertificateFingerprint, "");
  2851. }
  2852. }
  2853. __finally
  2854. {
  2855. delete Storage;
  2856. }
  2857. }
  2858. }
  2859. return true;
  2860. }
  2861. }
  2862. //---------------------------------------------------------------------------
  2863. bool __fastcall TFTPFileSystem::HandleListData(const char * Path,
  2864. const TListDataEntry * Entries, unsigned int Count)
  2865. {
  2866. if (!FActive)
  2867. {
  2868. return false;
  2869. }
  2870. else if (FIgnoreFileList)
  2871. {
  2872. // directory listing provided implicitly by FZAPI during certain operations is ignored
  2873. assert(FFileList == NULL);
  2874. return false;
  2875. }
  2876. else
  2877. {
  2878. assert(FFileList != NULL);
  2879. // this can actually fail in real life,
  2880. // when connected to server with case insensitive paths
  2881. assert(UnixComparePaths(AbsolutePath(FFileList->Directory, false), Path));
  2882. USEDPARAM(Path);
  2883. for (unsigned int Index = 0; Index < Count; Index++)
  2884. {
  2885. const TListDataEntry * Entry = &Entries[Index];
  2886. TRemoteFile * File = new TRemoteFile();
  2887. try
  2888. {
  2889. File->Terminal = FTerminal;
  2890. File->FileName = Entry->Name;
  2891. if (strlen(Entry->Permissions) >= 10)
  2892. {
  2893. try
  2894. {
  2895. File->Rights->Text = Entry->Permissions + 1;
  2896. }
  2897. catch(...)
  2898. {
  2899. // ignore permissions errors with FTP
  2900. }
  2901. }
  2902. const char * Space = strchr(Entry->OwnerGroup, ' ');
  2903. if (Space != NULL)
  2904. {
  2905. File->Owner.Name = AnsiString(Entry->OwnerGroup, Space - Entry->OwnerGroup);
  2906. File->Group.Name = Space + 1;
  2907. }
  2908. else
  2909. {
  2910. File->Owner.Name = Entry->OwnerGroup;
  2911. }
  2912. File->Size = Entry->Size;
  2913. if (Entry->Link)
  2914. {
  2915. File->Type = FILETYPE_SYMLINK;
  2916. }
  2917. else if (Entry->Dir)
  2918. {
  2919. File->Type = FILETYPE_DIRECTORY;
  2920. }
  2921. else
  2922. {
  2923. File->Type = '-';
  2924. }
  2925. // ModificationFmt must be set after Modification
  2926. if (Entry->HasDate)
  2927. {
  2928. // should be the same as ConvertRemoteTimestamp
  2929. TDateTime Modification =
  2930. EncodeDateVerbose((unsigned short)Entry->Year, (unsigned short)Entry->Month,
  2931. (unsigned short)Entry->Day);
  2932. if (Entry->HasTime)
  2933. {
  2934. File->Modification = Modification +
  2935. EncodeTimeVerbose((unsigned short)Entry->Hour, (unsigned short)Entry->Minute, 0, 0);
  2936. // not exact as we got year as well, but it is most probably
  2937. // guessed by FZAPI anyway
  2938. File->ModificationFmt = mfMDHM;
  2939. }
  2940. else
  2941. {
  2942. File->Modification = Modification;
  2943. File->ModificationFmt = mfMDY;
  2944. }
  2945. }
  2946. else
  2947. {
  2948. // With SCP we estimate date to be today, if we have at least time
  2949. File->Modification = double(0);
  2950. File->ModificationFmt = mfNone;
  2951. }
  2952. File->LastAccess = File->Modification;
  2953. File->LinkTo = Entry->LinkTarget;
  2954. File->Complete();
  2955. }
  2956. catch (Exception & E)
  2957. {
  2958. delete File;
  2959. AnsiString EntryData =
  2960. FORMAT("%s/%s/%s/%s/%d/%d/%d/%d/%d/%d/%d/%d/%d",
  2961. (Entry->Name, Entry->Permissions, Entry->OwnerGroup, IntToStr(Entry->Size),
  2962. int(Entry->Dir), int(Entry->Link), Entry->Year, Entry->Month, Entry->Day,
  2963. Entry->Hour, Entry->Minute, int(Entry->HasTime), int(Entry->HasDate)));
  2964. throw ETerminal(&E, FMTLOAD(LIST_LINE_ERROR, (EntryData)));
  2965. }
  2966. FFileList->AddFile(File);
  2967. }
  2968. return true;
  2969. }
  2970. }
  2971. //---------------------------------------------------------------------------
  2972. bool __fastcall TFTPFileSystem::HandleTransferStatus(bool Valid, __int64 TransferSize,
  2973. __int64 Bytes, int /*Percent*/, int /*TimeElapsed*/, int /*TimeLeft*/, int /*TransferRate*/,
  2974. bool FileTransfer)
  2975. {
  2976. if (!FActive)
  2977. {
  2978. return false;
  2979. }
  2980. else if (!Valid)
  2981. {
  2982. }
  2983. else if (FileTransfer)
  2984. {
  2985. FileTransferProgress(TransferSize, Bytes);
  2986. }
  2987. else
  2988. {
  2989. ReadDirectoryProgress(Bytes);
  2990. }
  2991. return true;
  2992. }
  2993. //---------------------------------------------------------------------------
  2994. bool __fastcall TFTPFileSystem::HandleReply(int Command, unsigned int Reply)
  2995. {
  2996. if (!FActive)
  2997. {
  2998. return false;
  2999. }
  3000. else
  3001. {
  3002. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  3003. {
  3004. FTerminal->LogEvent(FORMAT("Got reply %x to the command %d", (int(Reply), Command)));
  3005. }
  3006. // reply with Command 0 is not associated with current operation
  3007. // so do not treat is as a reply
  3008. // (it is typically used asynchronously to notify about disconnects)
  3009. if (Command != 0)
  3010. {
  3011. assert(FCommandReply == 0);
  3012. FCommandReply = Reply;
  3013. }
  3014. else
  3015. {
  3016. assert(FReply == 0);
  3017. FReply = Reply;
  3018. }
  3019. return true;
  3020. }
  3021. }
  3022. //---------------------------------------------------------------------------
  3023. bool __fastcall TFTPFileSystem::HandleCapabilities(bool Mfmt)
  3024. {
  3025. FMfmt = Mfmt;
  3026. FFileSystemInfoValid = false;
  3027. return true;
  3028. }
  3029. //---------------------------------------------------------------------------
  3030. bool __fastcall TFTPFileSystem::CheckError(int ReturnCode, const char * Context)
  3031. {
  3032. // we do not expect any FZAPI call to fail as it generally can fail only due to:
  3033. // - invalid paramerers
  3034. // - busy FZAPI core
  3035. // the only exception is REPLY_NOTCONNECTED that can happen if
  3036. // connection is closed just between the last call to Idle()
  3037. // and call to any FZAPI command
  3038. // in such case reply without associated command is posted,
  3039. // which we are going to wait for unless we are already waiting
  3040. // on higher level (this typically happens if connection is lost while
  3041. // waiting for user interaction and is detected within call to
  3042. // SetAsyncRequestResult)
  3043. if (FLAGSET(ReturnCode, TFileZillaIntf::REPLY_NOTCONNECTED))
  3044. {
  3045. if (!FWaitingForReply)
  3046. {
  3047. // throws
  3048. WaitForFatalNonCommandReply();
  3049. }
  3050. }
  3051. else
  3052. {
  3053. FTerminal->FatalError(NULL,
  3054. FMTLOAD(INTERNAL_ERROR, (FORMAT("fz#%s", (Context)), IntToHex(ReturnCode, 4))));
  3055. assert(false);
  3056. }
  3057. return false;
  3058. }
  3059. //---------------------------------------------------------------------------
  3060. bool __fastcall TFTPFileSystem::Unquote(AnsiString & Str)
  3061. {
  3062. enum
  3063. {
  3064. INIT,
  3065. QUOTE,
  3066. QUOTED,
  3067. DONE
  3068. } State;
  3069. State = INIT;
  3070. assert((Str.Length() > 0) && ((Str[1] == '"') || (Str[1] == '\'')));
  3071. int Index = 1;
  3072. char Quote;
  3073. while (Index <= Str.Length())
  3074. {
  3075. switch (State)
  3076. {
  3077. case INIT:
  3078. if ((Str[Index] == '"') || (Str[Index] == '\''))
  3079. {
  3080. Quote = Str[Index];
  3081. State = QUOTED;
  3082. Str.Delete(Index, 1);
  3083. }
  3084. else
  3085. {
  3086. assert(false);
  3087. // no quoted string
  3088. Str.SetLength(0);
  3089. }
  3090. break;
  3091. case QUOTED:
  3092. if (Str[Index] == Quote)
  3093. {
  3094. State = QUOTE;
  3095. Str.Delete(Index, 1);
  3096. }
  3097. else
  3098. {
  3099. Index++;
  3100. }
  3101. break;
  3102. case QUOTE:
  3103. if (Str[Index] == Quote)
  3104. {
  3105. Index++;
  3106. }
  3107. else
  3108. {
  3109. // end of quoted string, trim the rest
  3110. Str.SetLength(Index - 1);
  3111. State = DONE;
  3112. }
  3113. break;
  3114. }
  3115. }
  3116. return (State == DONE);
  3117. }
  3118. //---------------------------------------------------------------------------
  3119. #endif NO_FILEZILLA