FtpFileSystem.cpp 110 KB

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