FtpFileSystem.cpp 102 KB

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