FtpFileSystem.cpp 100 KB

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