1
0

WebDAVFileSystem.cpp 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <io.h>
  5. #include <fcntl.h>
  6. #include <wincrypt.h>
  7. #define NE_LFS
  8. #define WINSCP
  9. #include <ne_basic.h>
  10. #include <ne_auth.h>
  11. #include <ne_props.h>
  12. #include <ne_uri.h>
  13. #include <ne_session.h>
  14. #include <ne_request.h>
  15. #include <ne_xml.h>
  16. #include <ne_redirect.h>
  17. #include <ne_xmlreq.h>
  18. #include <expat.h>
  19. #include "WebDAVFileSystem.h"
  20. #include "Interface.h"
  21. #include "Common.h"
  22. #include "Exceptions.h"
  23. #include "Terminal.h"
  24. #include "TextsCore.h"
  25. #include "SecureShell.h"
  26. #include "HelpCore.h"
  27. #include "CoreMain.h"
  28. #include "Security.h"
  29. #include <StrUtils.hpp>
  30. #include <openssl/ssl.h>
  31. //---------------------------------------------------------------------------
  32. #pragma package(smart_init)
  33. //---------------------------------------------------------------------------
  34. #define FILE_OPERATION_LOOP_TERMINAL FTerminal
  35. //---------------------------------------------------------------------------
  36. const int tfFirstLevel = 0x01;
  37. //---------------------------------------------------------------------------
  38. struct TSinkFileParams
  39. {
  40. UnicodeString TargetDir;
  41. const TCopyParamType * CopyParam;
  42. int Params;
  43. TFileOperationProgressType * OperationProgress;
  44. bool Skipped;
  45. unsigned int Flags;
  46. };
  47. //---------------------------------------------------------------------------
  48. struct TWebDAVCertificateData
  49. {
  50. UnicodeString Subject;
  51. UnicodeString Issuer;
  52. TDateTime ValidFrom;
  53. TDateTime ValidUntil;
  54. UnicodeString Fingerprint;
  55. AnsiString AsciiCert;
  56. int Failures;
  57. };
  58. //---------------------------------------------------------------------------
  59. #define SESSION_FS_KEY "filesystem"
  60. #define MAX_REDIRECT_ATTEMPTS 3
  61. static const char CertificateStorageKey[] = "HttpsCertificates";
  62. static const UnicodeString CONST_WEBDAV_PROTOCOL_BASE_NAME = L"WebDAV";
  63. //---------------------------------------------------------------------------
  64. #define DAV_PROP_NAMESPACE "DAV:"
  65. #define PROP_CONTENT_LENGTH "getcontentlength"
  66. #define PROP_LAST_MODIFIED "getlastmodified"
  67. #define PROP_RESOURCE_TYPE "resourcetype"
  68. #define PROP_HIDDEN "ishidden"
  69. #define PROP_QUOTA_AVAILABLE "quota-available-bytes"
  70. #define PROP_QUOTA_USED "quota-used-bytes"
  71. //---------------------------------------------------------------------------
  72. static std::unique_ptr<TCriticalSection> DebugSection(new TCriticalSection);
  73. static std::set<TWebDAVFileSystem *> FileSystems;
  74. //---------------------------------------------------------------------------
  75. extern "C"
  76. {
  77. void ne_debug(void * Context, int Channel, const char * Format, ...)
  78. {
  79. bool DoLog;
  80. if (FLAGSET(Channel, NE_DBG_SOCKET) ||
  81. FLAGSET(Channel, NE_DBG_HTTP) ||
  82. FLAGSET(Channel, NE_DBG_HTTPAUTH) ||
  83. FLAGSET(Channel, NE_DBG_SSL))
  84. {
  85. DoLog = true;
  86. }
  87. else if (FLAGSET(Channel, NE_DBG_XML) ||
  88. FLAGSET(Channel, NE_DBG_WINSCP_HTTP_DETAIL))
  89. {
  90. DoLog = (Configuration->ActualLogProtocol >= 1);
  91. }
  92. else if (FLAGSET(Channel, NE_DBG_LOCKS) ||
  93. FLAGSET(Channel, NE_DBG_XMLPARSE) ||
  94. FLAGSET(Channel, NE_DBG_HTTPBODY))
  95. {
  96. DoLog = (Configuration->ActualLogProtocol >= 2);
  97. }
  98. else
  99. {
  100. DoLog = false;
  101. FAIL;
  102. }
  103. if (DoLog)
  104. {
  105. TWebDAVFileSystem * FileSystem = NULL;
  106. if (Context != NULL)
  107. {
  108. ne_session * Session = static_cast<ne_session *>(Context);
  109. FileSystem =
  110. static_cast<TWebDAVFileSystem *>(ne_get_session_private(Session, SESSION_FS_KEY));
  111. }
  112. else
  113. {
  114. TGuard Guard(DebugSection.get());
  115. if (FileSystems.size() == 1)
  116. {
  117. FileSystem = *FileSystems.begin();
  118. }
  119. }
  120. if (FileSystem != NULL)
  121. {
  122. va_list Args;
  123. va_start(Args, Format);
  124. UTF8String Message;
  125. Message.vprintf(Format, Args);
  126. FileSystem->NeonDebug(UnicodeString(Message));
  127. va_end(Args);
  128. }
  129. }
  130. }
  131. void ne_init_ssl_session(struct ssl_st * Ssl, ne_session * Session)
  132. {
  133. TWebDAVFileSystem * FileSystem =
  134. static_cast<TWebDAVFileSystem *>(ne_get_session_private(Session, SESSION_FS_KEY));
  135. FileSystem->InitSslSession(Ssl);
  136. }
  137. } // extern "C"
  138. //------------------------------------------------------------------------------
  139. //---------------------------------------------------------------------------
  140. // ne_path_escape returns 7-bit string, so it does not really matter if we use
  141. // AnsiString or UTF8String here, though UTF8String might be more safe
  142. static AnsiString PathEscape(const char * Path)
  143. {
  144. char * EscapedPath = ne_path_escape(Path);
  145. AnsiString Result = EscapedPath;
  146. ne_free(EscapedPath);
  147. return Result;
  148. }
  149. //---------------------------------------------------------------------------
  150. static UTF8String PathUnescape(const char * Path)
  151. {
  152. char * UnescapedPath = ne_path_unescape(Path);
  153. UTF8String Result = UnescapedPath;
  154. ne_free(UnescapedPath);
  155. return Result;
  156. }
  157. //---------------------------------------------------------------------------
  158. #define StrToNeon(S) UTF8String(S).c_str()
  159. #define StrFromNeon(S) UnicodeString(UTF8String(S))
  160. #define AbsolutePathToNeon(P) PathEscape(StrToNeon(P)).c_str()
  161. #define PathToNeonStatic(THIS, P) AbsolutePathToNeon((THIS)->AbsolutePath(P, false))
  162. #define PathToNeon(P) PathToNeonStatic(this, P)
  163. //---------------------------------------------------------------------------
  164. //---------------------------------------------------------------------------
  165. void __fastcall NeonInitialize()
  166. {
  167. // Even if this fails, we do not want to interrupt WinSCP starting for that.
  168. // We may possibly remember that and fail opening session later.
  169. // Anyway, it can hardly fail.
  170. // Though it fails on Wine on Debian VM.
  171. // Probably because of ne_sspi_init() as we get this message on stderr:
  172. // p11-kit: couldn't load module: /usr/lib/i386-linux-gnu/pkcs11/gnome-keyring-pkcs11.so: /usr/lib/i386-linux-gnu/pkcs11/gnome-keyring-pkcs11.so: cannot open shared object file: No such file or directory
  173. // err:winediag:SECUR32_initNTLMSP ntlm_auth was not found or is outdated. Make sure that ntlm_auth >= 3.0.25 is in your path. Usually, you can find it in the winbind package of your distribution.
  174. ALWAYS_TRUE(ne_sock_init() == 0);
  175. }
  176. //---------------------------------------------------------------------------
  177. void __fastcall NeonFinalize()
  178. {
  179. ne_sock_exit();
  180. }
  181. //---------------------------------------------------------------------------
  182. UnicodeString __fastcall NeonVersion()
  183. {
  184. UnicodeString Str = StrFromNeon(ne_version_string());
  185. CutToChar(Str, L' ', true); // "neon"
  186. UnicodeString Result = CutToChar(Str, L':', true);
  187. return Result;
  188. }
  189. //---------------------------------------------------------------------------
  190. UnicodeString __fastcall ExpatVersion()
  191. {
  192. return FORMAT(L"%d.%d.%d", (XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION));
  193. }
  194. //---------------------------------------------------------------------------
  195. //---------------------------------------------------------------------------
  196. TWebDAVFileSystem::TWebDAVFileSystem(TTerminal * ATerminal) :
  197. TCustomFileSystem(ATerminal),
  198. FActive(false),
  199. FHasTrailingSlash(false),
  200. FNeonSession(NULL),
  201. FUploading(false),
  202. FDownloading(false),
  203. FInitialHandshake(false),
  204. FIgnoreAuthenticationFailure(iafNo)
  205. {
  206. FFileSystemInfo.ProtocolBaseName = CONST_WEBDAV_PROTOCOL_BASE_NAME;
  207. FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
  208. }
  209. //---------------------------------------------------------------------------
  210. __fastcall TWebDAVFileSystem::~TWebDAVFileSystem()
  211. {
  212. UnregisterFromDebug();
  213. }
  214. //---------------------------------------------------------------------------
  215. void __fastcall TWebDAVFileSystem::Open()
  216. {
  217. RegisterForDebug();
  218. FCurrentDirectory = L"";
  219. FHasTrailingSlash = true;
  220. FStoredPasswordTried = false;
  221. FTlsVersionStr = L"";
  222. TSessionData * Data = FTerminal->SessionData;
  223. FSessionInfo.LoginTime = Now();
  224. bool Ssl = (FTerminal->SessionData->Ftps != ftpsNone);
  225. if (Ssl)
  226. {
  227. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_IMPLICIT);
  228. }
  229. UnicodeString HostName = Data->HostNameExpanded;
  230. size_t Port = Data->PortNumber;
  231. UnicodeString ProtocolName = !Ssl ? WebDAVProtocol : WebDAVSProtocol;
  232. UnicodeString Path = Data->RemoteDirectory;
  233. // PathToNeon is not used as we cannot call AbsolutePath here
  234. UnicodeString EscapedPath = UnicodeString(UTF8String(PathEscape(StrToNeon(Path)).c_str()));
  235. UnicodeString Url = FORMAT(L"%s://%s:%d%s", (ProtocolName, HostName, Port, EscapedPath));
  236. FTerminal->Information(LoadStr(STATUS_CONNECT), true);
  237. FActive = false;
  238. try
  239. {
  240. OpenUrl(Url);
  241. }
  242. catch (Exception & E)
  243. {
  244. CloseNeonSession();
  245. FTerminal->Closed();
  246. FTerminal->FatalError(&E, LoadStr(CONNECTION_FAILED));
  247. }
  248. FActive = true;
  249. }
  250. //---------------------------------------------------------------------------
  251. UnicodeString __fastcall TWebDAVFileSystem::ParsePathFromUrl(const UnicodeString & Url)
  252. {
  253. UnicodeString Result;
  254. ne_uri ParsedUri;
  255. if (ne_uri_parse(StrToNeon(Url), &ParsedUri) == 0)
  256. {
  257. Result = StrFromNeon(PathUnescape(ParsedUri.path));
  258. ne_uri_free(&ParsedUri);
  259. }
  260. return Result;
  261. }
  262. //---------------------------------------------------------------------------
  263. void TWebDAVFileSystem::OpenUrl(const UnicodeString & Url)
  264. {
  265. UnicodeString CorrectedUrl;
  266. NeonClientOpenSessionInternal(CorrectedUrl, Url);
  267. if (CorrectedUrl.IsEmpty())
  268. {
  269. CorrectedUrl = Url;
  270. }
  271. AnsiString ParsedPath = ParsePathFromUrl(CorrectedUrl);
  272. if (!ParsedPath.IsEmpty())
  273. {
  274. // this is most likely pointless as it get overwritten by
  275. // call to ChangeDirectory() from TTerminal::DoStartup
  276. FCurrentDirectory = ParsedPath;
  277. }
  278. }
  279. //---------------------------------------------------------------------------
  280. void TWebDAVFileSystem::NeonClientOpenSessionInternal(UnicodeString & CorrectedUrl, UnicodeString Url)
  281. {
  282. std::unique_ptr<TStringList> AttemptedUrls(CreateSortedStringList());
  283. int AttemptsLeft = MAX_REDIRECT_ATTEMPTS;
  284. while (true)
  285. {
  286. CorrectedUrl = L"";
  287. NeonOpen(CorrectedUrl, Url);
  288. // No error and no corrected URL? We're done here.
  289. if (CorrectedUrl.IsEmpty())
  290. {
  291. break;
  292. }
  293. if (AttemptsLeft == 0)
  294. {
  295. throw Exception(LoadStr(TOO_MANY_REDIRECTS));
  296. }
  297. else
  298. {
  299. CloseNeonSession();
  300. AttemptsLeft--;
  301. // Our caller will want to know what our final corrected URL was.
  302. // Make sure we've not attempted this URL before.
  303. if (AttemptedUrls->IndexOf(CorrectedUrl) >= 0)
  304. {
  305. throw Exception(LoadStr(REDIRECT_LOOP));
  306. }
  307. AttemptedUrls->Add(CorrectedUrl);
  308. Url = CorrectedUrl;
  309. }
  310. }
  311. CorrectedUrl = Url;
  312. }
  313. //---------------------------------------------------------------------------
  314. void TWebDAVFileSystem::NeonOpen(UnicodeString & CorrectedUrl, const UnicodeString & Url)
  315. {
  316. ne_uri uri;
  317. if (ne_uri_parse(StrToNeon(Url), &uri) != 0)
  318. {
  319. // should never happen
  320. throw Exception(FMTLOAD(INVALID_URL, (Url)));
  321. }
  322. // Will never happen for initial URL, but may happen for redirect URLs
  323. if (uri.port == 0)
  324. {
  325. uri.port = ne_uri_defaultport(uri.scheme);
  326. }
  327. TSessionData * Data = FTerminal->SessionData;
  328. assert(FNeonSession == NULL);
  329. FNeonSession = ne_session_create(uri.scheme, uri.host, uri.port);
  330. UTF8String Path = uri.path;
  331. ne_uri_free(&uri);
  332. ne_set_session_private(FNeonSession, SESSION_FS_KEY, this);
  333. // Other flags:
  334. // NE_DBG_FLUSH - used only in native implementation of ne_debug
  335. // NE_DBG_HTTPPLAIN - log credentials in HTTP authentication
  336. ne_debug_mask =
  337. NE_DBG_SOCKET |
  338. NE_DBG_HTTP |
  339. NE_DBG_XML | // detail
  340. NE_DBG_HTTPAUTH |
  341. NE_DBG_LOCKS | // very details
  342. NE_DBG_XMLPARSE | // very details
  343. NE_DBG_HTTPBODY | // very details
  344. NE_DBG_SSL;
  345. if (Data->ProxyMethod != ::pmNone)
  346. {
  347. if ((Data->ProxyMethod == pmSocks4) || (Data->ProxyMethod == pmSocks5))
  348. {
  349. enum ne_sock_sversion vers = (Data->ProxyMethod == pmSocks4) ? NE_SOCK_SOCKSV4A : NE_SOCK_SOCKSV5;
  350. ne_session_socks_proxy(FNeonSession, vers, StrToNeon(Data->ProxyHost), Data->ProxyPort, StrToNeon(Data->ProxyUsername), StrToNeon(Data->ProxyPassword));
  351. }
  352. else if (!Data->ProxyHost.IsEmpty())
  353. {
  354. ne_session_proxy(FNeonSession, StrToNeon(Data->ProxyHost), Data->ProxyPort);
  355. if (!Data->ProxyUsername.IsEmpty())
  356. {
  357. ne_set_proxy_auth(FNeonSession, NeonProxyAuth, this);
  358. }
  359. else
  360. {
  361. // Enable (only) the Negotiate scheme for proxy
  362. // authentication, if no username/password is
  363. // configured.
  364. ne_add_proxy_auth(FNeonSession, NE_AUTH_NEGOTIATE, NULL, NULL);
  365. }
  366. }
  367. }
  368. ne_set_read_timeout(FNeonSession, Data->Timeout);
  369. ne_set_connect_timeout(FNeonSession, Data->Timeout);
  370. ne_redirect_register(FNeonSession);
  371. ne_set_useragent(FNeonSession, StrToNeon(FORMAT(L"%s/%s", (AppNameString(), Configuration->Version))));
  372. unsigned int NeonAuthTypes = NE_AUTH_BASIC | NE_AUTH_DIGEST;
  373. if (Data->Ftps != ftpsNone)
  374. {
  375. NeonAuthTypes |= NE_AUTH_NEGOTIATE;
  376. }
  377. ne_add_server_auth(FNeonSession, NeonAuthTypes, NeonRequestAuth, this);
  378. if (Data->Ftps != ftpsNone)
  379. {
  380. // When the CA certificate or server certificate has
  381. // verification problems, neon will call our verify function before
  382. // outright rejection of the connection.
  383. ne_ssl_set_verify(FNeonSession, NeonServerSSLCallback, this);
  384. ne_ssl_trust_default_ca(FNeonSession);
  385. }
  386. ne_set_notifier(FNeonSession, NeonNotifier, this);
  387. ne_hook_create_request(FNeonSession, NeonCreateRequest, this);
  388. ne_hook_pre_send(FNeonSession, NeonPreSend, this);
  389. ne_hook_post_send(FNeonSession, NeonPostSend, this);
  390. TAutoFlag Flag(FInitialHandshake);
  391. ExchangeCapabilities(Path.c_str(), CorrectedUrl);
  392. }
  393. //---------------------------------------------------------------------------
  394. UnicodeString __fastcall TWebDAVFileSystem::GetRedirectUrl()
  395. {
  396. const ne_uri * RedirectUri = ne_redirect_location(FNeonSession);
  397. char * RedirectUriStr = ne_uri_unparse(RedirectUri);
  398. UnicodeString Result = StrFromNeon(RedirectUriStr);
  399. ne_free(RedirectUriStr);
  400. FTerminal->LogEvent(FORMAT(L"Redirected to \"%s\".", (Result)));
  401. return Result;
  402. }
  403. //---------------------------------------------------------------------------
  404. void TWebDAVFileSystem::ExchangeCapabilities(const char * Path, UnicodeString & CorrectedUrl)
  405. {
  406. unsigned int Capabilities = 0;
  407. ClearNeonError();
  408. int NeonStatus = ne_options2(FNeonSession, Path, &Capabilities);
  409. if (NeonStatus == NE_REDIRECT)
  410. {
  411. CorrectedUrl = GetRedirectUrl();
  412. }
  413. else if (NeonStatus == NE_OK)
  414. {
  415. if (Capabilities > 0)
  416. {
  417. UnicodeString Str;
  418. unsigned int Capability = 0x01;
  419. while (Capabilities > 0)
  420. {
  421. if (FLAGSET(Capabilities, Capability))
  422. {
  423. AddToList(Str, StrFromNeon(ne_capability_name(Capability)), L", ");
  424. Capabilities -= Capability;
  425. }
  426. Capability <<= 1;
  427. }
  428. FTerminal->LogEvent(FORMAT(L"Server capabilities: %s", (Str)));
  429. FFileSystemInfo.AdditionalInfo +=
  430. LoadStr(WEBDAV_EXTENSION_INFO) + sLineBreak +
  431. L" " + Str + sLineBreak;
  432. }
  433. }
  434. else
  435. {
  436. CheckStatus(NeonStatus);
  437. }
  438. FTerminal->SaveCapabilities(FFileSystemInfo);
  439. }
  440. //---------------------------------------------------------------------------
  441. void __fastcall TWebDAVFileSystem::CloseNeonSession()
  442. {
  443. if (FNeonSession != NULL)
  444. {
  445. ne_session_destroy(FNeonSession);
  446. FNeonSession = NULL;
  447. }
  448. }
  449. //---------------------------------------------------------------------------
  450. void __fastcall TWebDAVFileSystem::Close()
  451. {
  452. assert(FActive);
  453. CloseNeonSession();
  454. FTerminal->Closed();
  455. FActive = false;
  456. UnregisterFromDebug();
  457. }
  458. //---------------------------------------------------------------------------
  459. void __fastcall TWebDAVFileSystem::RegisterForDebug()
  460. {
  461. TGuard Guard(DebugSection.get());
  462. FileSystems.insert(this);
  463. }
  464. //---------------------------------------------------------------------------
  465. void __fastcall TWebDAVFileSystem::UnregisterFromDebug()
  466. {
  467. TGuard Guard(DebugSection.get());
  468. FileSystems.erase(this);
  469. }
  470. //---------------------------------------------------------------------------
  471. bool __fastcall TWebDAVFileSystem::GetActive()
  472. {
  473. return FActive;
  474. }
  475. //---------------------------------------------------------------------------
  476. void __fastcall TWebDAVFileSystem::CollectUsage()
  477. {
  478. if (!FTlsVersionStr.IsEmpty())
  479. {
  480. FTerminal->CollectTlsUsage(FTlsVersionStr);
  481. }
  482. UnicodeString RemoteSystem = FFileSystemInfo.RemoteSystem;
  483. if (ContainsText(RemoteSystem, L"Microsoft-IIS"))
  484. {
  485. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVIIS");
  486. }
  487. else if (ContainsText(RemoteSystem, L"IT Hit WebDAV Server"))
  488. {
  489. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVITHit");
  490. }
  491. // e.g. brickftp.com
  492. else if (ContainsText(RemoteSystem, L"nginx"))
  493. {
  494. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVNginx");
  495. }
  496. else
  497. {
  498. // We also know OpenDrive, Yandex, iFiles (iOS), Swapper (iOS), SafeSync
  499. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVOther");
  500. }
  501. }
  502. //---------------------------------------------------------------------------
  503. const TSessionInfo & __fastcall TWebDAVFileSystem::GetSessionInfo()
  504. {
  505. return FSessionInfo;
  506. }
  507. //---------------------------------------------------------------------------
  508. const TFileSystemInfo & __fastcall TWebDAVFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  509. {
  510. return FFileSystemInfo;
  511. }
  512. //---------------------------------------------------------------------------
  513. bool __fastcall TWebDAVFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
  514. {
  515. return false;
  516. }
  517. //---------------------------------------------------------------------------
  518. bool __fastcall TWebDAVFileSystem::GetStoredCredentialsTried()
  519. {
  520. return FStoredPasswordTried;
  521. }
  522. //---------------------------------------------------------------------------
  523. UnicodeString __fastcall TWebDAVFileSystem::GetUserName()
  524. {
  525. return FUserName;
  526. }
  527. //---------------------------------------------------------------------------
  528. void __fastcall TWebDAVFileSystem::Idle()
  529. {
  530. // noop
  531. }
  532. //---------------------------------------------------------------------------
  533. UnicodeString __fastcall TWebDAVFileSystem::AbsolutePath(const UnicodeString Path, bool /*Local*/)
  534. {
  535. bool AddTrailingBackslash;
  536. if (Path == L"/")
  537. {
  538. // does not really matter as path "/" is still "/" when absolute,
  539. // no slash needed
  540. AddTrailingBackslash = FHasTrailingSlash;
  541. }
  542. else
  543. {
  544. AddTrailingBackslash = (Path[Path.Length()] == L'/');
  545. }
  546. UnicodeString Result = ::AbsolutePath(GetCurrentDirectory(), Path);
  547. // We must preserve trailing slash, because particularly for mod_dav,
  548. // it really matters if the slash in there or not
  549. if (AddTrailingBackslash)
  550. {
  551. Result = UnixIncludeTrailingBackslash(Result);
  552. }
  553. return Result;
  554. }
  555. //---------------------------------------------------------------------------
  556. bool __fastcall TWebDAVFileSystem::IsCapable(int Capability) const
  557. {
  558. assert(FTerminal);
  559. switch (Capability)
  560. {
  561. case fcRename:
  562. case fcRemoteMove:
  563. case fcMoveToQueue:
  564. case fcPreservingTimestampUpload:
  565. case fcCheckingSpaceAvailable:
  566. // Only to make double-click on file edit/open the file,
  567. // instead of trying to open it as directory
  568. case fcResolveSymlink:
  569. return true;
  570. case fcUserGroupListing:
  571. case fcModeChanging:
  572. case fcModeChangingUpload:
  573. case fcGroupChanging:
  574. case fcOwnerChanging:
  575. case fcAnyCommand:
  576. case fcShellAnyCommand:
  577. case fcHardLink:
  578. case fcSymbolicLink:
  579. case fcTextMode:
  580. case fcNativeTextMode:
  581. case fcNewerOnlyUpload:
  582. case fcTimestampChanging:
  583. case fcLoadingAdditionalProperties:
  584. case fcIgnorePermErrors:
  585. case fcCalculatingChecksum:
  586. case fcSecondaryShell:
  587. case fcGroupOwnerChangingByID:
  588. case fcRemoveCtrlZUpload:
  589. case fcRemoveBOMUpload:
  590. case fcRemoteCopy:
  591. return false;
  592. default:
  593. FAIL;
  594. return false;
  595. }
  596. }
  597. //---------------------------------------------------------------------------
  598. UnicodeString __fastcall TWebDAVFileSystem::GetCurrentDirectory()
  599. {
  600. return FCurrentDirectory;
  601. }
  602. //---------------------------------------------------------------------------
  603. void __fastcall TWebDAVFileSystem::DoStartup()
  604. {
  605. FTerminal->SetExceptionOnFail(true);
  606. // retrieve initialize working directory to save it as home directory
  607. ReadCurrentDirectory();
  608. FTerminal->SetExceptionOnFail(false);
  609. }
  610. //---------------------------------------------------------------------------
  611. void __fastcall TWebDAVFileSystem::ClearNeonError()
  612. {
  613. FCancelled = false;
  614. FAuthenticationRequested = false;
  615. ne_set_error(FNeonSession, "");
  616. }
  617. //---------------------------------------------------------------------------
  618. UnicodeString __fastcall TWebDAVFileSystem::GetNeonError()
  619. {
  620. return StrFromNeon(ne_get_error(FNeonSession));
  621. }
  622. //---------------------------------------------------------------------------
  623. void __fastcall TWebDAVFileSystem::CheckStatus(int NeonStatus)
  624. {
  625. if (NeonStatus == NE_OK)
  626. {
  627. // noop
  628. }
  629. else if ((NeonStatus == NE_ERROR) && FCancelled)
  630. {
  631. FCancelled = false;
  632. Abort();
  633. }
  634. else
  635. {
  636. UnicodeString NeonError = GetNeonError();
  637. UnicodeString Error;
  638. switch (NeonStatus)
  639. {
  640. case NE_ERROR:
  641. // noop
  642. assert(!NeonError.IsEmpty());
  643. Error = NeonError;
  644. NeonError = L"";
  645. break;
  646. case NE_LOOKUP:
  647. Error = ReplaceStr(LoadStr(NET_TRANSL_HOST_NOT_EXIST2), L"%HOST%", FTerminal->SessionData->HostNameExpanded);
  648. break;
  649. case NE_AUTH:
  650. Error = LoadStr(AUTHENTICATION_FAILED);
  651. break;
  652. case NE_PROXYAUTH:
  653. Error = LoadStr(PROXY_AUTHENTICATION_FAILED);
  654. break;
  655. case NE_CONNECT:
  656. Error = LoadStr(CONNECTION_FAILED);
  657. break;
  658. case NE_TIMEOUT:
  659. Error = ReplaceStr(LoadStr(NET_TRANSL_TIMEOUT2), L"%HOST%", FTerminal->SessionData->HostNameExpanded);
  660. break;
  661. case NE_REDIRECT:
  662. {
  663. char * Uri = ne_uri_unparse(ne_redirect_location(FNeonSession));
  664. Error = FMTLOAD(REQUEST_REDIRECTED, (Uri));
  665. ne_free(Uri);
  666. }
  667. break;
  668. case NE_FAILED: // never used by neon as of 0.30.0
  669. case NE_RETRY: // not sure if this is a public API
  670. default:
  671. FAIL;
  672. Error = FORMAT(L"Unexpected neon error %d", (NeonStatus));
  673. break;
  674. }
  675. throw ExtException(Error, NeonError);
  676. }
  677. }
  678. //---------------------------------------------------------------------------
  679. void __fastcall TWebDAVFileSystem::LookupUsersGroups()
  680. {
  681. FAIL;
  682. }
  683. //---------------------------------------------------------------------------
  684. void __fastcall TWebDAVFileSystem::ReadCurrentDirectory()
  685. {
  686. if (FCachedDirectoryChange.IsEmpty())
  687. {
  688. FCurrentDirectory = FCurrentDirectory.IsEmpty() ? UnicodeString(L"/") : FCurrentDirectory;
  689. }
  690. else
  691. {
  692. FCurrentDirectory = FCachedDirectoryChange;
  693. FCachedDirectoryChange = L"";
  694. }
  695. }
  696. //---------------------------------------------------------------------------
  697. void __fastcall TWebDAVFileSystem::HomeDirectory()
  698. {
  699. ChangeDirectory(L"/");
  700. }
  701. //---------------------------------------------------------------------------
  702. UnicodeString __fastcall TWebDAVFileSystem::DirectoryPath(UnicodeString Path)
  703. {
  704. if (FHasTrailingSlash)
  705. {
  706. Path = ::UnixIncludeTrailingBackslash(Path);
  707. }
  708. return Path;
  709. }
  710. //---------------------------------------------------------------------------
  711. void __fastcall TWebDAVFileSystem::TryOpenDirectory(UnicodeString Directory)
  712. {
  713. Directory = DirectoryPath(Directory);
  714. FTerminal->LogEvent(FORMAT(L"Trying to open directory \"%s\".", (Directory)));
  715. TRemoteFile * File;
  716. ReadFile(Directory, File);
  717. delete File;
  718. }
  719. //---------------------------------------------------------------------------
  720. void __fastcall TWebDAVFileSystem::AnnounceFileListOperation()
  721. {
  722. // noop
  723. }
  724. //---------------------------------------------------------------------------
  725. void __fastcall TWebDAVFileSystem::ChangeDirectory(const UnicodeString ADirectory)
  726. {
  727. UnicodeString Path = AbsolutePath(ADirectory, false);
  728. // to verify existence of directory try to open it
  729. TryOpenDirectory(Path);
  730. // if open dir did not fail, directory exists -> success.
  731. FCachedDirectoryChange = Path;
  732. }
  733. //---------------------------------------------------------------------------
  734. void __fastcall TWebDAVFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  735. {
  736. FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
  737. }
  738. //---------------------------------------------------------------------------
  739. struct TReadFileData
  740. {
  741. TWebDAVFileSystem * FileSystem;
  742. TRemoteFile * File;
  743. TRemoteFileList * FileList;
  744. };
  745. //---------------------------------------------------------------------------
  746. int __fastcall TWebDAVFileSystem::ReadDirectoryInternal(
  747. const UnicodeString & Path, TRemoteFileList * FileList)
  748. {
  749. TReadFileData Data;
  750. Data.FileSystem = this;
  751. Data.File = NULL;
  752. Data.FileList = FileList;
  753. ClearNeonError();
  754. return
  755. ne_simple_propfind(FNeonSession, PathToNeon(Path), NE_DEPTH_ONE, NULL,
  756. NeonPropsResult, &Data);
  757. }
  758. //---------------------------------------------------------------------------
  759. bool __fastcall TWebDAVFileSystem::IsValidRedirect(int NeonStatus, UnicodeString & Path)
  760. {
  761. bool Result = (NeonStatus == NE_REDIRECT);
  762. if (Result)
  763. {
  764. // What PathToNeon does
  765. UnicodeString OriginalPath = AbsolutePath(Path, false);
  766. // Handle one-step redirect
  767. // (for more steps we would have to implement loop detection).
  768. // This is mainly to handle "folder" => "folder/" redirects of Apache/mod_dav.
  769. UnicodeString RedirectUrl = GetRedirectUrl();
  770. // We should test if the redirect is not for another server,
  771. // though not sure how to do this reliably (domain aliases, IP vs. domain, etc.)
  772. UnicodeString RedirectPath = ParsePathFromUrl(RedirectUrl);
  773. Result =
  774. !RedirectPath.IsEmpty() &&
  775. (RedirectPath != OriginalPath);
  776. if (Result)
  777. {
  778. Path = RedirectPath;
  779. }
  780. }
  781. return Result;
  782. }
  783. //---------------------------------------------------------------------------
  784. void __fastcall TWebDAVFileSystem::ReadDirectory(TRemoteFileList * FileList)
  785. {
  786. UnicodeString Path = DirectoryPath(FileList->Directory);
  787. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  788. int NeonStatus = ReadDirectoryInternal(Path, FileList);
  789. if (IsValidRedirect(NeonStatus, Path))
  790. {
  791. NeonStatus = ReadDirectoryInternal(Path, FileList);
  792. }
  793. CheckStatus(NeonStatus);
  794. }
  795. //---------------------------------------------------------------------------
  796. void __fastcall TWebDAVFileSystem::ReadSymlink(TRemoteFile * /*SymlinkFile*/,
  797. TRemoteFile *& /*File*/)
  798. {
  799. // we never set SymLink flag, so we should never get here
  800. FAIL;
  801. }
  802. //---------------------------------------------------------------------------
  803. void __fastcall TWebDAVFileSystem::ReadFile(const UnicodeString FileName,
  804. TRemoteFile *& File)
  805. {
  806. CustomReadFile(FileName, File, NULL);
  807. }
  808. //---------------------------------------------------------------------------
  809. void TWebDAVFileSystem::NeonPropsResult(
  810. void * UserData, const ne_uri * Uri, const ne_prop_result_set * Results)
  811. {
  812. UTF8String UnescapedUri = PathUnescape(Uri->path).c_str();
  813. UnicodeString Path = StrFromNeon(UnescapedUri);
  814. Path = UnixExcludeTrailingBackslash(Path);
  815. TReadFileData & Data = *static_cast<TReadFileData *>(UserData);
  816. if (Data.FileList != NULL)
  817. {
  818. UnicodeString FileListPath = PathToNeonStatic(Data.FileSystem, Data.FileList->Directory);
  819. if (UnixSamePath(Path, FileListPath))
  820. {
  821. Path = UnixIncludeTrailingBackslash(Path) + L"..";
  822. }
  823. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  824. File->Terminal = Data.FileSystem->FTerminal;
  825. Data.FileSystem->ParsePropResultSet(File.get(), Path, Results);
  826. Data.FileList->AddFile(File.release());
  827. }
  828. else
  829. {
  830. Data.FileSystem->ParsePropResultSet(Data.File, Path, Results);
  831. }
  832. }
  833. //---------------------------------------------------------------------------
  834. const char * __fastcall TWebDAVFileSystem::GetProp(const ne_prop_result_set * Results, const char * Name)
  835. {
  836. ne_propname Prop;
  837. Prop.nspace = DAV_PROP_NAMESPACE;
  838. Prop.name = Name;
  839. return ne_propset_value(Results, &Prop);
  840. }
  841. //---------------------------------------------------------------------------
  842. void __fastcall TWebDAVFileSystem::ParsePropResultSet(TRemoteFile * File,
  843. const UnicodeString & Path, const ne_prop_result_set * Results)
  844. {
  845. File->FullFileName = Path;
  846. File->FileName = UnixExtractFileName(File->FullFileName);
  847. const char * ContentLength = GetProp(Results, PROP_CONTENT_LENGTH);
  848. // some servers, for example iFiles, do not provide "getcontentlength" for folders
  849. if (ContentLength != NULL)
  850. {
  851. File->Size = StrToInt64Def(ContentLength, 0);
  852. }
  853. const char * LastModified = GetProp(Results, PROP_LAST_MODIFIED);
  854. if (ALWAYS_TRUE(LastModified != NULL))
  855. {
  856. char WeekDay[4] = { L'\0' };
  857. int Year = 0;
  858. char MonthStr[4] = { L'\0' };
  859. int Day = 0;
  860. int Hour = 0;
  861. int Min = 0;
  862. int Sec = 0;
  863. #define RFC1123_FORMAT "%3s, %02d %3s %4d %02d:%02d:%02d GMT"
  864. int Filled =
  865. sscanf(LastModified, RFC1123_FORMAT, WeekDay, &Day, MonthStr, &Year, &Hour, &Min, &Sec);
  866. // we need at least a complete date
  867. if (Filled >= 4)
  868. {
  869. int Month = ParseShortEngMonthName(MonthStr);
  870. if (Month >= 1)
  871. {
  872. TDateTime Modification =
  873. EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) +
  874. EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0);
  875. File->Modification = ConvertTimestampFromUTC(Modification);
  876. File->ModificationFmt = mfFull;
  877. }
  878. }
  879. }
  880. bool Collection = false;
  881. const char * ResourceType = GetProp(Results, PROP_RESOURCE_TYPE);
  882. if (ResourceType != NULL)
  883. {
  884. // property has XML value
  885. UnicodeString AResourceType = ResourceType;
  886. // this is very poor parsing
  887. if (ContainsText(ResourceType, L"<DAV:collection"))
  888. {
  889. Collection = true;
  890. }
  891. }
  892. File->Type = Collection ? FILETYPE_DIRECTORY : FILETYPE_DEFAULT;
  893. // this is MS extension (draft-hopmann-collection-props-00)
  894. const char * IsHidden = GetProp(Results, PROP_HIDDEN);
  895. if (IsHidden != NULL)
  896. {
  897. File->IsHidden = (StrToIntDef(IsHidden, 0) != 0);
  898. }
  899. }
  900. //---------------------------------------------------------------------------
  901. int __fastcall TWebDAVFileSystem::CustomReadFileInternal(const UnicodeString FileName,
  902. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  903. {
  904. std::unique_ptr<TRemoteFile> AFile(new TRemoteFile(ALinkedByFile));
  905. TReadFileData Data;
  906. Data.FileSystem = this;
  907. Data.File = AFile.get();
  908. Data.FileList = NULL;
  909. ClearNeonError();
  910. int Result =
  911. ne_simple_propfind(FNeonSession, PathToNeon(FileName), NE_DEPTH_ZERO, NULL,
  912. NeonPropsResult, &Data);
  913. if (Result == NE_OK)
  914. {
  915. File = AFile.release();
  916. }
  917. return Result;
  918. }
  919. //---------------------------------------------------------------------------
  920. void __fastcall TWebDAVFileSystem::CustomReadFile(UnicodeString FileName,
  921. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  922. {
  923. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  924. int NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  925. if (IsValidRedirect(NeonStatus, FileName))
  926. {
  927. NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  928. }
  929. CheckStatus(NeonStatus);
  930. }
  931. //---------------------------------------------------------------------------
  932. void __fastcall TWebDAVFileSystem::DeleteFile(const UnicodeString FileName,
  933. const TRemoteFile * File, int /*Params*/, TRmSessionAction & Action)
  934. {
  935. Action.Recursive();
  936. ClearNeonError();
  937. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  938. UnicodeString Path = File->FullFileName;
  939. if (File->IsDirectory)
  940. {
  941. Path = DirectoryPath(Path);
  942. }
  943. // WebDAV does not allow non-recursive delete:
  944. // RFC 4918, section 9.6.1:
  945. // "A client MUST NOT submit a Depth header with a DELETE on a collection with any value but infinity."
  946. // We should check that folder is empty when called with FLAGSET(Params, dfNoRecursive)
  947. CheckStatus(ne_delete(FNeonSession, PathToNeon(Path)));
  948. }
  949. //---------------------------------------------------------------------------
  950. int __fastcall TWebDAVFileSystem::RenameFileInternal(const UnicodeString & FileName,
  951. const UnicodeString & NewName)
  952. {
  953. // 0 = no overwrite
  954. return ne_move(FNeonSession, 0, PathToNeon(FileName), PathToNeon(NewName));
  955. }
  956. //---------------------------------------------------------------------------
  957. void __fastcall TWebDAVFileSystem::RenameFile(const UnicodeString FileName,
  958. const UnicodeString NewName)
  959. {
  960. ClearNeonError();
  961. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  962. UnicodeString Path = FileName;
  963. int NeonStatus = RenameFileInternal(Path, NewName);
  964. if (IsValidRedirect(NeonStatus, Path))
  965. {
  966. NeonStatus = RenameFileInternal(Path, NewName);
  967. }
  968. CheckStatus(NeonStatus);
  969. }
  970. //---------------------------------------------------------------------------
  971. void __fastcall TWebDAVFileSystem::CopyFile(const UnicodeString FileName,
  972. const UnicodeString NewName)
  973. {
  974. FAIL;
  975. }
  976. //---------------------------------------------------------------------------
  977. void __fastcall TWebDAVFileSystem::CreateDirectory(const UnicodeString DirName)
  978. {
  979. ClearNeonError();
  980. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  981. CheckStatus(ne_mkcol(FNeonSession, PathToNeon(DirName)));
  982. }
  983. //---------------------------------------------------------------------------
  984. void __fastcall TWebDAVFileSystem::CreateLink(const UnicodeString FileName,
  985. const UnicodeString PointTo, bool /*Symbolic*/)
  986. {
  987. FAIL;
  988. }
  989. //---------------------------------------------------------------------------
  990. void __fastcall TWebDAVFileSystem::ChangeFileProperties(const UnicodeString FileName,
  991. const TRemoteFile * /*File*/, const TRemoteProperties * /*Properties*/,
  992. TChmodSessionAction & /*Action*/)
  993. {
  994. FAIL;
  995. }
  996. //---------------------------------------------------------------------------
  997. bool __fastcall TWebDAVFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  998. {
  999. FAIL;
  1000. return false;
  1001. }
  1002. //---------------------------------------------------------------------------
  1003. void __fastcall TWebDAVFileSystem::CalculateFilesChecksum(const UnicodeString & /*Alg*/,
  1004. TStrings * /*FileList*/, TStrings * /*Checksums*/,
  1005. TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
  1006. {
  1007. FAIL;
  1008. }
  1009. //---------------------------------------------------------------------------
  1010. void __fastcall TWebDAVFileSystem::ConfirmOverwrite(
  1011. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1012. TFileOperationProgressType * OperationProgress,
  1013. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1014. int Params)
  1015. {
  1016. // all = "yes to newer"
  1017. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll;
  1018. TQueryButtonAlias Aliases[3];
  1019. Aliases[0].Button = qaAll;
  1020. Aliases[0].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  1021. Aliases[0].GroupWith = qaYes;
  1022. Aliases[0].GrouppedShiftState = TShiftState() << ssCtrl;
  1023. Aliases[1].Button = qaYesToAll;
  1024. Aliases[1].GroupWith = qaYes;
  1025. Aliases[1].GrouppedShiftState = TShiftState() << ssShift;
  1026. Aliases[2].Button = qaNoToAll;
  1027. Aliases[2].GroupWith = qaNo;
  1028. Aliases[2].GrouppedShiftState = TShiftState() << ssShift;
  1029. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1030. QueryParams.Aliases = Aliases;
  1031. QueryParams.AliasesCount = LENOF(Aliases);
  1032. unsigned int Answer;
  1033. {
  1034. TSuspendFileOperationProgress Suspend(OperationProgress);
  1035. Answer =
  1036. FTerminal->ConfirmFileOverwrite(
  1037. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1038. (OperationProgress->Side == osLocal) ? osRemote : osLocal,
  1039. CopyParam, Params, OperationProgress);
  1040. }
  1041. switch (Answer)
  1042. {
  1043. case qaYes:
  1044. // noop
  1045. break;
  1046. case qaNo:
  1047. THROW_SKIP_FILE_NULL;
  1048. default:
  1049. FAIL;
  1050. case qaCancel:
  1051. if (!OperationProgress->Cancel)
  1052. {
  1053. OperationProgress->Cancel = csCancel;
  1054. }
  1055. Abort();
  1056. break;
  1057. }
  1058. }
  1059. //---------------------------------------------------------------------------
  1060. void __fastcall TWebDAVFileSystem::CustomCommandOnFile(const UnicodeString FileName,
  1061. const TRemoteFile * /*File*/, UnicodeString Command, int /*Params*/, TCaptureOutputEvent /*OutputEvent*/)
  1062. {
  1063. FAIL;
  1064. }
  1065. //---------------------------------------------------------------------------
  1066. void __fastcall TWebDAVFileSystem::AnyCommand(const UnicodeString Command,
  1067. TCaptureOutputEvent /*OutputEvent*/)
  1068. {
  1069. FAIL;
  1070. }
  1071. //---------------------------------------------------------------------------
  1072. TStrings * __fastcall TWebDAVFileSystem::GetFixedPaths()
  1073. {
  1074. return NULL;
  1075. }
  1076. //---------------------------------------------------------------------------
  1077. void TWebDAVFileSystem::NeonQuotaResult(
  1078. void * UserData, const ne_uri * /*Uri*/, const ne_prop_result_set * Results)
  1079. {
  1080. TSpaceAvailable & SpaceAvailable = *static_cast<TSpaceAvailable *>(UserData);
  1081. const char * Value = GetProp(Results, PROP_QUOTA_AVAILABLE);
  1082. if (Value != NULL)
  1083. {
  1084. SpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(StrFromNeon(Value));
  1085. const char * Value = GetProp(Results, PROP_QUOTA_USED);
  1086. if (Value != NULL)
  1087. {
  1088. SpaceAvailable.BytesAvailableToUser =
  1089. StrToInt64(StrFromNeon(Value)) + SpaceAvailable.UnusedBytesAvailableToUser;
  1090. }
  1091. }
  1092. }
  1093. //---------------------------------------------------------------------------
  1094. void __fastcall TWebDAVFileSystem::SpaceAvailable(const UnicodeString Path,
  1095. TSpaceAvailable & ASpaceAvailable)
  1096. {
  1097. // RFC4331: http://tools.ietf.org/html/rfc4331
  1098. // This is known to be supported by:
  1099. // OpenDrive: for a root drive only (and contrary to the spec, it sends the properties
  1100. // unconditionally, even when not explicitly requested)
  1101. // Server: Apache/2.2.17 (Fedora)
  1102. // X-Powered-By: PHP/5.5.7
  1103. // X-DAV-Powered-By: OpenDrive
  1104. // WWW-Authenticate: Basic realm="PHP WebDAV"
  1105. // IT Hit WebDAV Server:
  1106. // Server: Microsoft-HTTPAPI/1.0
  1107. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1108. // Yandex disk:
  1109. // WWW-Authenticate: Basic realm="Yandex.Disk"
  1110. // Server: MochiWeb/1.0
  1111. UnicodeString APath = DirectoryPath(Path);
  1112. ne_propname QuotaProps[3];
  1113. memset(QuotaProps, 0, sizeof(QuotaProps));
  1114. QuotaProps[0].nspace = DAV_PROP_NAMESPACE;
  1115. QuotaProps[0].name = PROP_QUOTA_AVAILABLE;
  1116. QuotaProps[1].nspace = DAV_PROP_NAMESPACE;
  1117. QuotaProps[1].name = PROP_QUOTA_USED;
  1118. QuotaProps[2].nspace = NULL;
  1119. QuotaProps[2].name = NULL;
  1120. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1121. CheckStatus(
  1122. ne_simple_propfind(FNeonSession, PathToNeon(APath), NE_DEPTH_ZERO, QuotaProps,
  1123. NeonQuotaResult, &ASpaceAvailable));
  1124. }
  1125. //---------------------------------------------------------------------------
  1126. void __fastcall TWebDAVFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1127. const UnicodeString ATargetDir, const TCopyParamType * CopyParam,
  1128. int Params, TFileOperationProgressType * OperationProgress,
  1129. TOnceDoneOperation & OnceDoneOperation)
  1130. {
  1131. assert((FilesToCopy != NULL) && (OperationProgress != NULL));
  1132. Params &= ~cpAppend;
  1133. UnicodeString FileName, FileNameOnly;
  1134. UnicodeString TargetDir = AbsolutePath(ATargetDir, false);
  1135. UnicodeString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  1136. intptr_t Index = 0;
  1137. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  1138. {
  1139. bool Success = false;
  1140. FileName = FilesToCopy->Strings[Index];
  1141. FileNameOnly = ExtractFileName(FileName, false);
  1142. try
  1143. {
  1144. try
  1145. {
  1146. if (FTerminal->SessionData->CacheDirectories)
  1147. {
  1148. FTerminal->DirectoryModified(TargetDir, false);
  1149. if (::DirectoryExists(ApiPath(::ExtractFilePath(FileName))))
  1150. {
  1151. FTerminal->DirectoryModified(FullTargetDir + FileNameOnly, true);
  1152. }
  1153. }
  1154. SourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  1155. tfFirstLevel);
  1156. Success = true;
  1157. }
  1158. catch (EScpSkipFile & E)
  1159. {
  1160. TSuspendFileOperationProgress Suspend(OperationProgress);
  1161. if (!FTerminal->HandleException(&E))
  1162. {
  1163. throw;
  1164. }
  1165. }
  1166. }
  1167. __finally
  1168. {
  1169. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1170. }
  1171. Index++;
  1172. }
  1173. }
  1174. //---------------------------------------------------------------------------
  1175. void __fastcall TWebDAVFileSystem::SourceRobust(const UnicodeString FileName,
  1176. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  1177. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1178. {
  1179. // the same in TSFTPFileSystem
  1180. TUploadSessionAction Action(FTerminal->ActionLog);
  1181. TRobustOperationLoop RobustLoop(FTerminal, OperationProgress);
  1182. do
  1183. {
  1184. bool ChildError = false;
  1185. try
  1186. {
  1187. Source(FileName, TargetDir, CopyParam, Params, OperationProgress,
  1188. Flags, Action, ChildError);
  1189. }
  1190. catch (Exception & E)
  1191. {
  1192. if (!RobustLoop.TryReopen(E))
  1193. {
  1194. if (!ChildError)
  1195. {
  1196. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1197. }
  1198. throw;
  1199. }
  1200. }
  1201. if (RobustLoop.ShouldRetry())
  1202. {
  1203. OperationProgress->RollbackTransfer();
  1204. Action.Restart();
  1205. // prevent overwrite confirmations
  1206. // (should not be set for directories!)
  1207. Params |= cpNoConfirmation;
  1208. }
  1209. }
  1210. while (RobustLoop.Retry());
  1211. }
  1212. //---------------------------------------------------------------------------
  1213. void __fastcall TWebDAVFileSystem::Source(const UnicodeString FileName,
  1214. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  1215. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1216. TUploadSessionAction & Action, bool & ChildError)
  1217. {
  1218. Action.FileName(ExpandUNCFileName(FileName));
  1219. OperationProgress->SetFile(FileName, false);
  1220. if (!FTerminal->AllowLocalFileTransfer(FileName, CopyParam, OperationProgress))
  1221. {
  1222. THROW_SKIP_FILE_NULL;
  1223. }
  1224. HANDLE File;
  1225. __int64 MTime;
  1226. __int64 Size;
  1227. int Attrs;
  1228. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &Attrs,
  1229. &File, NULL, &MTime, NULL, &Size);
  1230. bool Dir = FLAGSET(Attrs, faDirectory);
  1231. int FD = -1;
  1232. try
  1233. {
  1234. OperationProgress->SetFileInProgress();
  1235. if (Dir)
  1236. {
  1237. Action.Cancel();
  1238. DirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  1239. Attrs, CopyParam, Params, OperationProgress, Flags);
  1240. }
  1241. else
  1242. {
  1243. UnicodeString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
  1244. osLocal, FLAGSET(Flags, tfFirstLevel));
  1245. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  1246. OperationProgress->SetLocalSize(Size);
  1247. // Suppose same data size to transfer as to read
  1248. // (not true with ASCII transfer)
  1249. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1250. OperationProgress->TransferingFile = false;
  1251. UnicodeString DestFullName = TargetDir + DestFileName;
  1252. TRemoteFile * RemoteFile = NULL;
  1253. try
  1254. {
  1255. TValueRestorer<TIgnoreAuthenticationFailure> IgnoreAuthenticationFailureRestorer(FIgnoreAuthenticationFailure);
  1256. FIgnoreAuthenticationFailure = iafWaiting;
  1257. // this should not throw
  1258. CustomReadFileInternal(DestFullName, RemoteFile, NULL);
  1259. }
  1260. catch (...)
  1261. {
  1262. if (!FTerminal->Active)
  1263. {
  1264. throw;
  1265. }
  1266. }
  1267. TDateTime Modification = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  1268. if (RemoteFile != NULL)
  1269. {
  1270. TOverwriteFileParams FileParams;
  1271. FileParams.SourceSize = Size;
  1272. FileParams.SourceTimestamp = Modification;
  1273. FileParams.DestSize = RemoteFile->Size;
  1274. FileParams.DestTimestamp = RemoteFile->Modification;
  1275. delete RemoteFile;
  1276. ConfirmOverwrite(FileName, DestFileName, OperationProgress,
  1277. &FileParams, CopyParam, Params);
  1278. }
  1279. DestFullName = TargetDir + DestFileName;
  1280. // only now, we know the final destination
  1281. // (not really true as we do not support changing file name on overwrite dialog)
  1282. Action.Destination(DestFullName);
  1283. FILE_OPERATION_LOOP_BEGIN
  1284. {
  1285. SetFilePointer(File, 0, NULL, FILE_BEGIN);
  1286. FD = _open_osfhandle((intptr_t)File, O_BINARY);
  1287. if (FD < 0)
  1288. {
  1289. THROW_SKIP_FILE_NULL;
  1290. }
  1291. TAutoFlag UploadingFlag(FUploading);
  1292. ClearNeonError();
  1293. CheckStatus(ne_put(FNeonSession, PathToNeon(DestFullName), FD));
  1294. }
  1295. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1296. if (CopyParam->PreserveTime)
  1297. {
  1298. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1299. (StandardTimestamp(Modification))));
  1300. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Modification);
  1301. try
  1302. {
  1303. TDateTime ModificationUTC = ConvertTimestampToUTC(Modification);
  1304. TFormatSettings FormatSettings = GetEngFormatSettings();
  1305. UnicodeString LastModified =
  1306. FormatDateTime(L"ddd, d mmm yyyy hh:nn:ss 'GMT'", ModificationUTC, FormatSettings);
  1307. UTF8String NeonLastModified(LastModified);
  1308. // second element is "NULL-terminating"
  1309. ne_proppatch_operation Operations[2];
  1310. memset(Operations, 0, sizeof(Operations));
  1311. ne_propname LastModifiedProp;
  1312. LastModifiedProp.nspace = DAV_PROP_NAMESPACE;
  1313. LastModifiedProp.name = PROP_LAST_MODIFIED;
  1314. Operations[0].name = &LastModifiedProp;
  1315. Operations[0].type = ne_propset;
  1316. Operations[0].value = NeonLastModified.c_str();
  1317. int Status = ne_proppatch(FNeonSession, PathToNeon(DestFullName), Operations);
  1318. if (Status == NE_ERROR)
  1319. {
  1320. FTerminal->LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s",
  1321. (GetNeonError())));
  1322. // Ignore errors as major WebDAV servers (like IIS), do not support
  1323. // changing getlastmodified.
  1324. // The only server we found that supports this is TradeMicro SafeSync.
  1325. // But it announces itself as "Server: Apache",
  1326. // so it's not reliably autodetect the support.
  1327. TouchAction.Cancel();
  1328. }
  1329. else
  1330. {
  1331. CheckStatus(Status);
  1332. }
  1333. }
  1334. catch (Exception & E)
  1335. {
  1336. TouchAction.Rollback(&E);
  1337. ChildError = true;
  1338. throw;
  1339. }
  1340. }
  1341. FTerminal->LogFileDone(OperationProgress);
  1342. }
  1343. }
  1344. __finally
  1345. {
  1346. if (FD >= 0)
  1347. {
  1348. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1349. // but it crashes code guard
  1350. _close(FD);
  1351. }
  1352. else if (File != NULL)
  1353. {
  1354. CloseHandle(File);
  1355. }
  1356. }
  1357. // TODO : Delete also read-only files.
  1358. if (FLAGSET(Params, cpDelete))
  1359. {
  1360. if (!Dir)
  1361. {
  1362. FILE_OPERATION_LOOP_BEGIN
  1363. {
  1364. THROWOSIFFALSE(::DeleteFile(ApiPath(FileName).c_str()));
  1365. }
  1366. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  1367. }
  1368. }
  1369. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1370. {
  1371. FILE_OPERATION_LOOP_BEGIN
  1372. {
  1373. THROWOSIFFALSE(FileSetAttr(ApiPath(FileName), Attrs & ~faArchive) == 0);
  1374. }
  1375. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  1376. }
  1377. }
  1378. //---------------------------------------------------------------------------
  1379. void __fastcall TWebDAVFileSystem::DirectorySource(const UnicodeString DirectoryName,
  1380. const UnicodeString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  1381. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1382. {
  1383. UnicodeString DestDirectoryName = CopyParam->ChangeFileName(
  1384. ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal,
  1385. FLAGSET(Flags, tfFirstLevel));
  1386. UnicodeString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  1387. // create DestFullName if it does not exist
  1388. if (!FTerminal->FileExists(DestFullName))
  1389. {
  1390. TRemoteProperties Properties;
  1391. if (CopyParam->PreserveRights)
  1392. {
  1393. Properties.Valid = TValidProperties() << vpRights;
  1394. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  1395. }
  1396. FTerminal->CreateDirectory(DestFullName, &Properties);
  1397. }
  1398. OperationProgress->SetFile(DirectoryName);
  1399. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1400. TSearchRecChecked SearchRec;
  1401. bool FindOK;
  1402. FILE_OPERATION_LOOP_BEGIN
  1403. {
  1404. FindOK =
  1405. (FindFirstChecked(DirectoryName + L"*.*", FindAttrs, SearchRec) == 0);
  1406. }
  1407. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  1408. try
  1409. {
  1410. while (FindOK && !OperationProgress->Cancel)
  1411. {
  1412. UnicodeString FileName = DirectoryName + SearchRec.Name;
  1413. try
  1414. {
  1415. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  1416. {
  1417. SourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  1418. Flags & ~(tfFirstLevel));
  1419. }
  1420. }
  1421. catch (EScpSkipFile & E)
  1422. {
  1423. // If ESkipFile occurs, just log it and continue with next file
  1424. TSuspendFileOperationProgress Suspend(OperationProgress);
  1425. // here a message to user was displayed, which was not appropriate
  1426. // when user refused to overwrite the file in subdirectory.
  1427. // hopefully it won't be missing in other situations.
  1428. if (!FTerminal->HandleException(&E))
  1429. {
  1430. throw;
  1431. }
  1432. }
  1433. FILE_OPERATION_LOOP_BEGIN
  1434. {
  1435. FindOK = (FindNextChecked(SearchRec) == 0);
  1436. }
  1437. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  1438. }
  1439. }
  1440. __finally
  1441. {
  1442. FindClose(SearchRec);
  1443. }
  1444. // TODO : Delete also read-only directories.
  1445. // TODO : Show error message on failure.
  1446. if (!OperationProgress->Cancel)
  1447. {
  1448. if (FLAGSET(Params, cpDelete))
  1449. {
  1450. RemoveDir(ApiPath(DirectoryName));
  1451. }
  1452. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1453. {
  1454. FILE_OPERATION_LOOP_BEGIN
  1455. {
  1456. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  1457. }
  1458. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  1459. }
  1460. }
  1461. }
  1462. //---------------------------------------------------------------------------
  1463. void __fastcall TWebDAVFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1464. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1465. int Params, TFileOperationProgressType * OperationProgress,
  1466. TOnceDoneOperation & OnceDoneOperation)
  1467. {
  1468. Params &= ~cpAppend;
  1469. UnicodeString FullTargetDir = ::IncludeTrailingBackslash(TargetDir);
  1470. int Index = 0;
  1471. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  1472. {
  1473. UnicodeString FileName = FilesToCopy->Strings[Index];
  1474. const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
  1475. bool Success = false;
  1476. try
  1477. {
  1478. try
  1479. {
  1480. SinkRobust(AbsolutePath(FileName, false), File, FullTargetDir, CopyParam, Params,
  1481. OperationProgress, tfFirstLevel);
  1482. Success = true;
  1483. }
  1484. catch (EScpSkipFile & E)
  1485. {
  1486. TSuspendFileOperationProgress Suspend(OperationProgress);
  1487. if (!FTerminal->HandleException(&E))
  1488. {
  1489. throw;
  1490. }
  1491. }
  1492. }
  1493. __finally
  1494. {
  1495. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1496. }
  1497. Index++;
  1498. }
  1499. }
  1500. //---------------------------------------------------------------------------
  1501. void __fastcall TWebDAVFileSystem::SinkRobust(const UnicodeString FileName,
  1502. const TRemoteFile * File, const UnicodeString TargetDir,
  1503. const TCopyParamType * CopyParam, int Params,
  1504. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1505. {
  1506. // the same in TSFTPFileSystem
  1507. TDownloadSessionAction Action(FTerminal->ActionLog);
  1508. TRobustOperationLoop RobustLoop(FTerminal, OperationProgress);
  1509. do
  1510. {
  1511. bool ChildError = false;
  1512. try
  1513. {
  1514. Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress,
  1515. Flags, Action, ChildError);
  1516. }
  1517. catch (Exception & E)
  1518. {
  1519. if (!RobustLoop.TryReopen(E))
  1520. {
  1521. if (!ChildError)
  1522. {
  1523. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1524. }
  1525. throw;
  1526. }
  1527. }
  1528. if (RobustLoop.ShouldRetry())
  1529. {
  1530. OperationProgress->RollbackTransfer();
  1531. Action.Restart();
  1532. assert(File != NULL);
  1533. if (!File->IsDirectory)
  1534. {
  1535. // prevent overwrite confirmations
  1536. Params |= cpNoConfirmation;
  1537. }
  1538. }
  1539. }
  1540. while (RobustLoop.Retry());
  1541. }
  1542. //---------------------------------------------------------------------------
  1543. void TWebDAVFileSystem::NeonCreateRequest(
  1544. ne_request * Request, void * UserData, const char * /*Method*/, const char * /*Uri*/)
  1545. {
  1546. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1547. ne_set_request_private(Request, SESSION_FS_KEY, FileSystem);
  1548. ne_add_response_body_reader(Request, NeonBodyAccepter, NeonBodyReader, Request);
  1549. }
  1550. //---------------------------------------------------------------------------
  1551. void TWebDAVFileSystem::NeonPreSend(
  1552. ne_request * Request, void * UserData, ne_buffer * Header)
  1553. {
  1554. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1555. if (FileSystem->FDownloading)
  1556. {
  1557. // Needed by IIS server to make it download source code, not code output,
  1558. // and mainly to even allow downloading file with unregistered extensions.
  1559. // Without it files like .001 return 404 (Not found) HTTP code.
  1560. // http://msdn.microsoft.com/en-us/library/cc250098.aspx
  1561. // http://msdn.microsoft.com/en-us/library/cc250216.aspx
  1562. // http://lists.manyfish.co.uk/pipermail/neon/2012-April/001452.html
  1563. // It's also supported by Oracle server:
  1564. // https://docs.oracle.com/cd/E19146-01/821-1828/gczya/index.html
  1565. // We do not know yet of any server that fails when the header is used,
  1566. // so it's added unconditionally.
  1567. ne_buffer_zappend(Header, "Translate: f\r\n");
  1568. }
  1569. if (FileSystem->FTerminal->Log->Logging)
  1570. {
  1571. const char * Buffer;
  1572. size_t Size;
  1573. if (ne_get_request_body_buffer(Request, &Buffer, &Size))
  1574. {
  1575. // all neon request types that use ne_add_request_header
  1576. // use XML content-type, so it's text-based
  1577. assert(ContainsStr(AnsiString(Header->data, Header->used), "Content-Type: " NE_XML_MEDIA_TYPE));
  1578. FileSystem->FTerminal->Log->Add(llInput, UnicodeString(UTF8String(Buffer, Size)));
  1579. }
  1580. }
  1581. if (FileSystem->FUploading)
  1582. {
  1583. ne_set_request_body_provider_pre(Request,
  1584. FileSystem->NeonUploadBodyProvider, FileSystem);
  1585. }
  1586. FileSystem->FResponse = L"";
  1587. }
  1588. //---------------------------------------------------------------------------
  1589. int TWebDAVFileSystem::NeonPostSend(ne_request * /*Req*/, void * UserData,
  1590. const ne_status * /*Status*/)
  1591. {
  1592. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1593. if (!FileSystem->FResponse.IsEmpty())
  1594. {
  1595. FileSystem->FTerminal->Log->Add(llOutput, FileSystem->FResponse);
  1596. }
  1597. return NE_OK;
  1598. }
  1599. //---------------------------------------------------------------------------
  1600. ssize_t TWebDAVFileSystem::NeonUploadBodyProvider(void * UserData, char * /*Buffer*/, size_t /*BufLen*/)
  1601. {
  1602. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1603. ssize_t Result;
  1604. if (FileSystem->CancelTransfer())
  1605. {
  1606. Result = -1;
  1607. }
  1608. else
  1609. {
  1610. Result = 1;
  1611. }
  1612. return Result;
  1613. }
  1614. //---------------------------------------------------------------------------
  1615. static void __fastcall AddHeaderValueToList(UnicodeString & List, ne_request * Request, const char * Name)
  1616. {
  1617. const char * Value;
  1618. Value = ne_get_response_header(Request, Name);
  1619. if (Value != NULL)
  1620. {
  1621. AddToList(List, StrFromNeon(Value), L"; ");
  1622. }
  1623. }
  1624. //---------------------------------------------------------------------------
  1625. int TWebDAVFileSystem::NeonBodyAccepter(void * UserData, ne_request * Request, const ne_status * Status)
  1626. {
  1627. assert(UserData == Request);
  1628. TWebDAVFileSystem * FileSystem =
  1629. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1630. bool AuthenticationFailed = (Status->code == 401) && FileSystem->FAuthenticationRequested;
  1631. bool AuthenticationNeeded = (Status->code == 401) && !FileSystem->FAuthenticationRequested;
  1632. if (FileSystem->FInitialHandshake)
  1633. {
  1634. UnicodeString Line;
  1635. if (AuthenticationNeeded)
  1636. {
  1637. Line = LoadStr(STATUS_AUTHENTICATE);
  1638. }
  1639. else if (AuthenticationFailed)
  1640. {
  1641. Line = LoadStr(FTP_ACCESS_DENIED);
  1642. }
  1643. else if (Status->klass == 2)
  1644. {
  1645. Line = LoadStr(STATUS_AUTHENTICATED);
  1646. }
  1647. if (!Line.IsEmpty())
  1648. {
  1649. FileSystem->FTerminal->Information(Line, true);
  1650. }
  1651. UnicodeString RemoteSystem;
  1652. // Used by IT Hit WebDAV Server:
  1653. // Server: Microsoft-HTTPAPI/1.0
  1654. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1655. AddHeaderValueToList(RemoteSystem, Request, "X-Engine");
  1656. // Used by OpenDrive:
  1657. // Server: Apache/2.2.17 (Fedora)
  1658. // X-Powered-By: PHP/5.5.7
  1659. // X-DAV-Powered-By: OpenDrive
  1660. AddHeaderValueToList(RemoteSystem, Request, "X-DAV-Powered-By");
  1661. // Used by IIS:
  1662. // Server: Microsoft-IIS/8.5
  1663. AddHeaderValueToList(RemoteSystem, Request, "Server");
  1664. // Not really useful.
  1665. // Can be e.g. "PleskLin"
  1666. AddHeaderValueToList(RemoteSystem, Request, "X-Powered-By");
  1667. FileSystem->FFileSystemInfo.RemoteSystem = RemoteSystem;
  1668. }
  1669. // When we explicitly fail authentication of request
  1670. // with FIgnoreAuthenticationFailure flag (after it failed with password),
  1671. // neon resets its internal password store and tries the next request
  1672. // without calling our authentication hook first
  1673. // (note AuthenticationFailed vs. AuthenticationNeeded)
  1674. // what likely fails, but we do not want to reset out password
  1675. // (as it was not even tried yet for this request).
  1676. if (AuthenticationFailed)
  1677. {
  1678. if (FileSystem->FIgnoreAuthenticationFailure == iafNo)
  1679. {
  1680. FileSystem->FPassword = RawByteString();
  1681. }
  1682. else
  1683. {
  1684. FileSystem->FIgnoreAuthenticationFailure = iafPasswordFailed;
  1685. }
  1686. }
  1687. return ne_accept_2xx(UserData, Request, Status);
  1688. }
  1689. //---------------------------------------------------------------------------
  1690. bool __fastcall TWebDAVFileSystem::CancelTransfer()
  1691. {
  1692. bool Result = false;
  1693. if ((FUploading || FDownloading) &&
  1694. (FTerminal->OperationProgress != NULL) &&
  1695. (FTerminal->OperationProgress->Cancel != csContinue))
  1696. {
  1697. FCancelled = true;
  1698. Result = true;
  1699. }
  1700. return Result;
  1701. }
  1702. //---------------------------------------------------------------------------
  1703. int TWebDAVFileSystem::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  1704. {
  1705. ne_request * Request = static_cast<ne_request *>(UserData);
  1706. TWebDAVFileSystem * FileSystem =
  1707. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1708. if (FileSystem->FTerminal->Log->Logging)
  1709. {
  1710. ne_content_type ContentType;
  1711. if (ne_get_content_type(Request, &ContentType) == 0)
  1712. {
  1713. // The main point of the content-type check was to exclude
  1714. // GET responses (with file contents).
  1715. // But this won't work when downloading text files that have text
  1716. // content type on their own, hence the additional not-downloading test.
  1717. if (!FileSystem->FDownloading &&
  1718. ((ne_strcasecmp(ContentType.type, "text") == 0) ||
  1719. media_type_is_xml(&ContentType)))
  1720. {
  1721. UnicodeString Content = UnicodeString(UTF8String(Buf, Len)).Trim();
  1722. FileSystem->FResponse += Content;
  1723. }
  1724. ne_free(ContentType.value);
  1725. }
  1726. }
  1727. int Result = FileSystem->CancelTransfer() ? 1 : 0;
  1728. return Result;
  1729. }
  1730. //---------------------------------------------------------------------------
  1731. void __fastcall TWebDAVFileSystem::Sink(const UnicodeString FileName,
  1732. const TRemoteFile * File, const UnicodeString TargetDir,
  1733. const TCopyParamType * CopyParam, int Params,
  1734. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1735. TDownloadSessionAction & Action, bool & ChildError)
  1736. {
  1737. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  1738. Action.FileName(FileName);
  1739. assert(File);
  1740. TFileMasks::TParams MaskParams;
  1741. MaskParams.Size = File->Size;
  1742. if (!CopyParam->AllowTransfer(FileName, osRemote, File->IsDirectory, MaskParams))
  1743. {
  1744. FTerminal->LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  1745. THROW_SKIP_FILE_NULL;
  1746. }
  1747. if (CopyParam->SkipTransfer(FileName, File->IsDirectory))
  1748. {
  1749. OperationProgress->AddSkippedFileSize(File->Size);
  1750. THROW_SKIP_FILE_NULL;
  1751. }
  1752. FTerminal->LogFileDetails(FileName, TDateTime(), File->Size);
  1753. OperationProgress->SetFile(FileName);
  1754. UnicodeString DestFileName = CopyParam->ChangeFileName(FileNameOnly,
  1755. osRemote, FLAGSET(Flags, tfFirstLevel));
  1756. UnicodeString DestFullName = TargetDir + DestFileName;
  1757. if (File->IsDirectory)
  1758. {
  1759. Action.Cancel();
  1760. if (ALWAYS_TRUE(!File->IsSymLink))
  1761. {
  1762. FILE_OPERATION_LOOP_BEGIN
  1763. {
  1764. int Attrs = FileGetAttr(ApiPath(DestFullName));
  1765. if (FLAGCLEAR(Attrs, faDirectory)) { EXCEPTION; }
  1766. }
  1767. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)));
  1768. FILE_OPERATION_LOOP_BEGIN
  1769. {
  1770. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFullName)));
  1771. }
  1772. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFullName)));
  1773. TSinkFileParams SinkFileParams;
  1774. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  1775. SinkFileParams.CopyParam = CopyParam;
  1776. SinkFileParams.Params = Params;
  1777. SinkFileParams.OperationProgress = OperationProgress;
  1778. SinkFileParams.Skipped = false;
  1779. SinkFileParams.Flags = Flags & ~tfFirstLevel;
  1780. FTerminal->ProcessDirectory(FileName, SinkFile, &SinkFileParams);
  1781. // Do not delete directory if some of its files were skip.
  1782. // Throw "skip file" for the directory to avoid attempt to deletion
  1783. // of any parent directory
  1784. if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
  1785. {
  1786. THROW_SKIP_FILE_NULL;
  1787. }
  1788. }
  1789. else
  1790. {
  1791. // file is symlink to directory, currently do nothing, but it should be
  1792. // reported to user
  1793. }
  1794. }
  1795. else
  1796. {
  1797. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to local directory started.", (FileName)));
  1798. if (FileExists(ApiPath(DestFullName)))
  1799. {
  1800. __int64 Size;
  1801. __int64 MTime;
  1802. FTerminal->OpenLocalFile(DestFullName, GENERIC_READ, NULL,
  1803. NULL, NULL, &MTime, NULL, &Size);
  1804. TOverwriteFileParams FileParams;
  1805. FileParams.SourceSize = File->Size;
  1806. FileParams.SourceTimestamp = File->Modification;
  1807. FileParams.DestSize = Size;
  1808. FileParams.DestTimestamp = UnixToDateTime(MTime,
  1809. FTerminal->SessionData->DSTMode);
  1810. ConfirmOverwrite(FileName, DestFileName, OperationProgress,
  1811. &FileParams, CopyParam, Params);
  1812. }
  1813. // Suppose same data size to transfer as to write
  1814. OperationProgress->SetTransferSize(File->Size);
  1815. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  1816. int Attrs = -1;
  1817. FILE_OPERATION_LOOP_BEGIN
  1818. {
  1819. Attrs = FileGetAttr(ApiPath(DestFullName));
  1820. if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory)) { EXCEPTION; }
  1821. }
  1822. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_FILE_ERROR, (DestFullName)));
  1823. OperationProgress->TransferingFile = false; // not set with WebDAV protocol
  1824. UnicodeString FilePath = ::UnixExtractFilePath(FileName);
  1825. if (FilePath.IsEmpty())
  1826. {
  1827. FilePath = L"/";
  1828. }
  1829. Action.Destination(ExpandUNCFileName(DestFullName));
  1830. FILE_OPERATION_LOOP_BEGIN
  1831. {
  1832. HANDLE LocalHandle;
  1833. if (!FTerminal->CreateLocalFile(DestFullName, OperationProgress,
  1834. &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  1835. {
  1836. THROW_SKIP_FILE_NULL;
  1837. }
  1838. bool DeleteLocalFile = true;
  1839. int FD = -1;
  1840. try
  1841. {
  1842. FD = _open_osfhandle((intptr_t)LocalHandle, O_BINARY);
  1843. if (FD < 0)
  1844. {
  1845. THROW_SKIP_FILE_NULL;
  1846. }
  1847. TAutoFlag DownloadingFlag(FDownloading);
  1848. ClearNeonError();
  1849. CheckStatus(ne_get(FNeonSession, PathToNeon(FileName), FD));
  1850. DeleteLocalFile = false;
  1851. if (CopyParam->PreserveTime)
  1852. {
  1853. TDateTime Modification = File->Modification;
  1854. FILETIME WrTime = DateTimeToFileTime(Modification, FTerminal->SessionData->DSTMode);
  1855. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1856. (StandardTimestamp(Modification))));
  1857. SetFileTime(LocalHandle, NULL, NULL, &WrTime);
  1858. }
  1859. }
  1860. __finally
  1861. {
  1862. if (FD >= 0)
  1863. {
  1864. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1865. // but it crashes code guard
  1866. _close(FD);
  1867. }
  1868. else
  1869. {
  1870. CloseHandle(LocalHandle);
  1871. }
  1872. if (DeleteLocalFile)
  1873. {
  1874. FILE_OPERATION_LOOP_BEGIN
  1875. {
  1876. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestFullName)));
  1877. }
  1878. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestFullName)));
  1879. }
  1880. }
  1881. }
  1882. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1883. if (Attrs == -1)
  1884. {
  1885. Attrs = faArchive;
  1886. }
  1887. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  1888. if ((NewAttrs & Attrs) != NewAttrs)
  1889. {
  1890. FILE_OPERATION_LOOP_BEGIN
  1891. {
  1892. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFullName), Attrs | NewAttrs) == 0);
  1893. }
  1894. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFullName)));
  1895. }
  1896. FTerminal->LogFileDone(OperationProgress);
  1897. }
  1898. if (FLAGSET(Params, cpDelete))
  1899. {
  1900. ChildError = true;
  1901. // If file is directory, do not delete it recursively, because it should be
  1902. // empty already. If not, it should not be deleted (some files were
  1903. // skipped or some new files were copied to it, while we were downloading)
  1904. int Params = dfNoRecursive;
  1905. FTerminal->DeleteFile(FileName, File, &Params);
  1906. ChildError = false;
  1907. }
  1908. }
  1909. //---------------------------------------------------------------------------
  1910. void __fastcall TWebDAVFileSystem::SinkFile(const UnicodeString FileName,
  1911. const TRemoteFile * File, void * Param)
  1912. {
  1913. TSinkFileParams * Params = static_cast<TSinkFileParams *>(Param);
  1914. assert(Params->OperationProgress);
  1915. try
  1916. {
  1917. SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  1918. Params->Params, Params->OperationProgress, Params->Flags);
  1919. }
  1920. catch (EScpSkipFile & E)
  1921. {
  1922. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  1923. Params->Skipped = true;
  1924. {
  1925. TSuspendFileOperationProgress Suspend(OperationProgress);
  1926. if (!FTerminal->HandleException(&E))
  1927. {
  1928. throw;
  1929. }
  1930. }
  1931. if (OperationProgress->Cancel)
  1932. {
  1933. Abort();
  1934. }
  1935. }
  1936. }
  1937. //---------------------------------------------------------------------------
  1938. bool TWebDAVFileSystem::VerifyCertificate(const TWebDAVCertificateData & Data)
  1939. {
  1940. FTerminal->LogEvent(
  1941. FORMAT(L"Verifying certificate for \"%s\" with fingerprint %s and %2.2X failures",
  1942. (Data.Subject, Data.Fingerprint, Data.Failures)));
  1943. int Failures = Data.Failures;
  1944. // We can accept only unknown certificate authority.
  1945. if (FLAGSET(Data.Failures, NE_SSL_UNTRUSTED))
  1946. {
  1947. unsigned char * Certificate;
  1948. size_t CertificateLen = ne_unbase64(Data.AsciiCert.c_str(), &Certificate);
  1949. if (CertificateLen > 0)
  1950. {
  1951. if (WindowsValidateCertificate(Certificate, CertificateLen))
  1952. {
  1953. FTerminal->LogEvent(L"Certificate verified against Windows certificate store");
  1954. Failures &= ~NE_SSL_UNTRUSTED;
  1955. }
  1956. ne_free(Certificate);
  1957. }
  1958. }
  1959. UnicodeString Summary;
  1960. if (Failures == 0)
  1961. {
  1962. Summary = LoadStr(CERT_OK);
  1963. }
  1964. else
  1965. {
  1966. int FailuresToList = Failures;
  1967. if (FLAGSET(FailuresToList, NE_SSL_NOTYETVALID))
  1968. {
  1969. AddToList(Summary, LoadStr(CERT_ERR_CERT_NOT_YET_VALID), L" ");
  1970. FailuresToList &= ~NE_SSL_NOTYETVALID;
  1971. }
  1972. if (FLAGSET(FailuresToList, NE_SSL_EXPIRED))
  1973. {
  1974. AddToList(Summary, LoadStr(CERT_ERR_CERT_HAS_EXPIRED), L" ");
  1975. FailuresToList &= ~NE_SSL_EXPIRED;
  1976. }
  1977. // NEON checks certificate host name on its own
  1978. if (FLAGSET(FailuresToList, NE_SSL_IDMISMATCH))
  1979. {
  1980. AddToList(Summary, FMTLOAD(CERT_NAME_MISMATCH, (FTerminal->SessionData->HostNameExpanded)), L" ");
  1981. FailuresToList &= ~NE_SSL_IDMISMATCH;
  1982. }
  1983. if (FLAGSET(FailuresToList, NE_SSL_UNTRUSTED))
  1984. {
  1985. AddToList(Summary, LoadStr(CERT_ERR_CERT_UNTRUSTED), L" ");
  1986. FailuresToList &= ~NE_SSL_UNTRUSTED;
  1987. }
  1988. if (FLAGSET(FailuresToList, NE_SSL_BADCHAIN))
  1989. {
  1990. AddToList(Summary, LoadStr(CERT_ERR_BAD_CHAIN), L" ");
  1991. FailuresToList &= ~NE_SSL_BADCHAIN;
  1992. }
  1993. // nb, NE_SSL_REVOKED is never used by OpenSSL implementation
  1994. if (FailuresToList != 0)
  1995. {
  1996. AddToList(Summary, LoadStr(CERT_ERR_UNKNOWN), L" ");
  1997. }
  1998. }
  1999. UnicodeString ValidityTimeFormat = L"ddddd tt";
  2000. FSessionInfo.CertificateFingerprint = Data.Fingerprint;
  2001. FSessionInfo.Certificate =
  2002. FMTLOAD(CERT_TEXT, (
  2003. Data.Issuer + L"\n",
  2004. Data.Subject + L"\n",
  2005. FormatDateTime(ValidityTimeFormat, Data.ValidFrom),
  2006. FormatDateTime(ValidityTimeFormat, Data.ValidUntil),
  2007. Data.Fingerprint,
  2008. Summary));
  2009. bool Result = (Failures == 0);
  2010. if (!Result)
  2011. {
  2012. if (!Result)
  2013. {
  2014. Result = FTerminal->VerifyCertificate(
  2015. CertificateStorageKey, Data.Fingerprint, Data.Subject, Failures);
  2016. }
  2017. if (!Result)
  2018. {
  2019. TClipboardHandler ClipboardHandler;
  2020. ClipboardHandler.Text = Data.Fingerprint;
  2021. TQueryButtonAlias Aliases[1];
  2022. Aliases[0].Button = qaRetry;
  2023. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  2024. Aliases[0].OnClick = &ClipboardHandler.Copy;
  2025. TQueryParams Params;
  2026. Params.HelpKeyword = HELP_VERIFY_CERTIFICATE;
  2027. Params.NoBatchAnswers = qaYes | qaRetry;
  2028. Params.Aliases = Aliases;
  2029. Params.AliasesCount = LENOF(Aliases);
  2030. unsigned int Answer = FTerminal->QueryUser(
  2031. FMTLOAD(VERIFY_CERT_PROMPT3, (FSessionInfo.Certificate)),
  2032. NULL, qaYes | qaNo | qaCancel | qaRetry, &Params, qtWarning);
  2033. switch (Answer)
  2034. {
  2035. case qaYes:
  2036. FTerminal->CacheCertificate(CertificateStorageKey, Data.Fingerprint, Failures);
  2037. Result = true;
  2038. break;
  2039. case qaNo:
  2040. Result = true;
  2041. break;
  2042. default:
  2043. FAIL;
  2044. case qaCancel:
  2045. FTerminal->Configuration->Usage->Inc(L"HostNotVerified");
  2046. Result = false;
  2047. break;
  2048. }
  2049. }
  2050. }
  2051. if (Result)
  2052. {
  2053. CollectTLSSessionInfo();
  2054. }
  2055. return Result;
  2056. }
  2057. //------------------------------------------------------------------------------
  2058. void __fastcall TWebDAVFileSystem::CollectTLSSessionInfo()
  2059. {
  2060. // See also TFTPFileSystem::Open().
  2061. // Have to cache the value as the connection (the neon HTTP session, not "our" session)
  2062. // can be closed as the time we need it in CollectUsage().
  2063. FTlsVersionStr = StrFromNeon(ne_ssl_get_version(FNeonSession));
  2064. AddToList(FSessionInfo.SecurityProtocolName, FTlsVersionStr, L", ");
  2065. UnicodeString Cipher = StrFromNeon(ne_ssl_get_cipher(FNeonSession));
  2066. FSessionInfo.CSCipher = Cipher;
  2067. FSessionInfo.SCCipher = Cipher;
  2068. // see CAsyncSslSocketLayer::PrintSessionInfo()
  2069. FTerminal->LogEvent(FORMAT(L"Using %s, cipher %s", (FTlsVersionStr, Cipher)));
  2070. }
  2071. //------------------------------------------------------------------------------
  2072. // A neon-session callback to validate the SSL certificate when the CA
  2073. // is unknown (e.g. a self-signed cert), or there are other SSL
  2074. // certificate problems.
  2075. int TWebDAVFileSystem::NeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  2076. {
  2077. TWebDAVCertificateData Data;
  2078. char Fingerprint[NE_SSL_DIGESTLEN] = {0};
  2079. if (ne_ssl_cert_digest(Certificate, Fingerprint) != 0)
  2080. {
  2081. strcpy(Fingerprint, "<unknown>");
  2082. }
  2083. Data.Fingerprint = StrFromNeon(Fingerprint);
  2084. char * AsciiCert = ne_ssl_cert_export(Certificate);
  2085. Data.AsciiCert = StrFromNeon(AsciiCert);
  2086. ne_free(AsciiCert);
  2087. char * Subject = ne_ssl_readable_dname(ne_ssl_cert_subject(Certificate));
  2088. Data.Subject = StrFromNeon(Subject);
  2089. ne_free(Subject);
  2090. char * Issuer = ne_ssl_readable_dname(ne_ssl_cert_issuer(Certificate));
  2091. Data.Issuer = StrFromNeon(Issuer);
  2092. ne_free(Issuer);
  2093. Data.Failures = Failures;
  2094. time_t ValidFrom;
  2095. time_t ValidUntil;
  2096. ne_ssl_cert_validity_time(Certificate, &ValidFrom, &ValidUntil);
  2097. Data.ValidFrom = UnixToDateTime(ValidFrom, dstmWin);
  2098. Data.ValidUntil = UnixToDateTime(ValidUntil, dstmWin);
  2099. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2100. return FileSystem->VerifyCertificate(Data) ? NE_OK : NE_ERROR;
  2101. }
  2102. //------------------------------------------------------------------------------
  2103. int TWebDAVFileSystem::NeonRequestAuth(
  2104. void * UserData, const char * /*Realm*/, int /*Attempt*/, char * UserName, char * Password)
  2105. {
  2106. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2107. TTerminal * Terminal = FileSystem->FTerminal;
  2108. TSessionData * SessionData = Terminal->SessionData;
  2109. bool Result = true;
  2110. // will ask for username only once
  2111. if (FileSystem->FUserName.IsEmpty())
  2112. {
  2113. if (!SessionData->UserName.IsEmpty())
  2114. {
  2115. FileSystem->FUserName = SessionData->UserNameExpanded;
  2116. }
  2117. else
  2118. {
  2119. if (!Terminal->PromptUser(SessionData, pkUserName, LoadStr(USERNAME_TITLE), L"",
  2120. LoadStr(USERNAME_PROMPT2), true, NE_ABUFSIZ, FileSystem->FUserName))
  2121. {
  2122. // note that we never get here actually
  2123. Result = false;
  2124. }
  2125. }
  2126. }
  2127. UnicodeString APassword;
  2128. if (Result)
  2129. {
  2130. // Some servers (Gallery2 on https://g2.pixi.me/w/webdav/)
  2131. // return authentication error (401) on PROPFIND request for
  2132. // non-existing files.
  2133. // When we already tried password before, do not try anymore.
  2134. // When we did not try password before (possible only when
  2135. // server does not require authentication for any previous request,
  2136. // such as when read access is not authenticated), try it now,
  2137. // but use special flag for the try, because when it fails
  2138. // we still want to try password for future requests (such as PUT).
  2139. if (!FileSystem->FPassword.IsEmpty())
  2140. {
  2141. if (FileSystem->FIgnoreAuthenticationFailure == iafPasswordFailed)
  2142. {
  2143. // Fail PROPFIND /nonexising request...
  2144. Result = false;
  2145. }
  2146. else
  2147. {
  2148. APassword = Terminal->DecryptPassword(FileSystem->FPassword);
  2149. }
  2150. }
  2151. else
  2152. {
  2153. if (!SessionData->Password.IsEmpty() && !FileSystem->FStoredPasswordTried)
  2154. {
  2155. APassword = SessionData->Password;
  2156. FileSystem->FStoredPasswordTried = true;
  2157. }
  2158. else
  2159. {
  2160. // Asking for password (or using configured password) the first time,
  2161. // and asking for password.
  2162. // Note that we never get false here actually
  2163. Result =
  2164. Terminal->PromptUser(
  2165. SessionData, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  2166. LoadStr(PASSWORD_PROMPT), false, NE_ABUFSIZ, APassword);
  2167. }
  2168. if (Result)
  2169. {
  2170. // While neon remembers the password on its own,
  2171. // we need to keep a copy in case neon store gets reset by
  2172. // 401 response to PROPFIND /nonexisting on G2, see above.
  2173. // Possibly we can do this for G2 servers only.
  2174. FileSystem->FPassword = Terminal->EncryptPassword(APassword);
  2175. }
  2176. }
  2177. }
  2178. if (Result)
  2179. {
  2180. strncpy(UserName, StrToNeon(FileSystem->FUserName), NE_ABUFSIZ);
  2181. strncpy(Password, StrToNeon(APassword), NE_ABUFSIZ);
  2182. }
  2183. FileSystem->FAuthenticationRequested = true;
  2184. return Result ? 0 : -1;
  2185. }
  2186. //------------------------------------------------------------------------------
  2187. int TWebDAVFileSystem::NeonProxyAuth(
  2188. void * UserData, const char * /*Realm*/, int Attempt, char * UserName, char * Password)
  2189. {
  2190. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2191. TSessionData * SessionData = FileSystem->FTerminal->SessionData;
  2192. int Result;
  2193. // no point trying too many times as we always return the same credentials
  2194. // (maybe just one would be enough)
  2195. if (Attempt >= 2)
  2196. {
  2197. Result = 1;
  2198. }
  2199. else
  2200. {
  2201. strncpy(UserName, StrToNeon(SessionData->ProxyUsername), NE_ABUFSIZ);
  2202. strncpy(Password, StrToNeon(SessionData->ProxyPassword), NE_ABUFSIZ);
  2203. Result = 0;
  2204. }
  2205. return Result;
  2206. }
  2207. //------------------------------------------------------------------------------
  2208. void TWebDAVFileSystem::NeonNotifier(void * UserData, ne_session_status Status, const ne_session_status_info * StatusInfo)
  2209. {
  2210. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2211. TFileOperationProgressType * OperationProgress = FileSystem->FTerminal->OperationProgress;
  2212. // We particularly have to filter out response to "put" request,
  2213. // handling that would reset the upload progress back to low number (response is small).
  2214. if (((FileSystem->FUploading && (Status == ne_status_sending)) ||
  2215. (FileSystem->FDownloading && (Status == ne_status_recving))) &&
  2216. ALWAYS_TRUE(OperationProgress != NULL))
  2217. {
  2218. __int64 Progress = StatusInfo->sr.progress;
  2219. __int64 Diff = Progress - OperationProgress->TransferedSize;
  2220. if (Diff > 0)
  2221. {
  2222. OperationProgress->ThrottleToCPSLimit(static_cast<unsigned long>(Diff));
  2223. }
  2224. __int64 Total = StatusInfo->sr.total;
  2225. // Total size unknown
  2226. if (Total < 0)
  2227. {
  2228. if (Diff >= 0)
  2229. {
  2230. OperationProgress->AddTransfered(Diff);
  2231. }
  2232. else
  2233. {
  2234. // Session total has been reset. A new stream started
  2235. OperationProgress->AddTransfered(Progress);
  2236. }
  2237. }
  2238. else
  2239. {
  2240. OperationProgress->SetTransferSize(Total);
  2241. OperationProgress->AddTransfered(Diff);
  2242. }
  2243. }
  2244. }
  2245. //------------------------------------------------------------------------------
  2246. void __fastcall TWebDAVFileSystem::NeonDebug(const UnicodeString & Message)
  2247. {
  2248. FTerminal->LogEvent(Message);
  2249. }
  2250. //------------------------------------------------------------------------------
  2251. void __fastcall TWebDAVFileSystem::InitSslSession(ssl_st * Ssl)
  2252. {
  2253. // See also CAsyncSslSocketLayer::InitSSLConnection
  2254. TSessionData * Data = FTerminal->SessionData;
  2255. #define MASK_TLS_VERSION(VERSION, FLAG) ((Data->MinTlsVersion > VERSION) || (Data->MaxTlsVersion < VERSION) ? FLAG : 0)
  2256. int Options =
  2257. MASK_TLS_VERSION(ssl2, SSL_OP_NO_SSLv2) |
  2258. MASK_TLS_VERSION(ssl3, SSL_OP_NO_SSLv3) |
  2259. MASK_TLS_VERSION(tls10, SSL_OP_NO_TLSv1) |
  2260. MASK_TLS_VERSION(tls11, SSL_OP_NO_TLSv1_1) |
  2261. MASK_TLS_VERSION(tls12, SSL_OP_NO_TLSv1_2);
  2262. // SSL_ctrl() with SSL_CTRL_OPTIONS adds flags (not sets)
  2263. SSL_ctrl(Ssl, SSL_CTRL_OPTIONS, Options, NULL);
  2264. }
  2265. //---------------------------------------------------------------------------
  2266. void __fastcall TWebDAVFileSystem::GetSupportedChecksumAlgs(TStrings * /*Algs*/)
  2267. {
  2268. // NOOP
  2269. }
  2270. //------------------------------------------------------------------------------