WebDAVFileSystem.cpp 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133
  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 <ne_locks.h>
  19. #include <expat.h>
  20. #include "WebDAVFileSystem.h"
  21. #include "Interface.h"
  22. #include "Common.h"
  23. #include "Exceptions.h"
  24. #include "Terminal.h"
  25. #include "TextsCore.h"
  26. #include "SecureShell.h"
  27. #include "HelpCore.h"
  28. #include "CoreMain.h"
  29. #include "Security.h"
  30. #include <StrUtils.hpp>
  31. #include <NeonIntf.h>
  32. //---------------------------------------------------------------------------
  33. #pragma package(smart_init)
  34. //---------------------------------------------------------------------------
  35. #define FILE_OPERATION_LOOP_TERMINAL FTerminal
  36. //---------------------------------------------------------------------------
  37. #define SESSION_FS_KEY "filesystem"
  38. static const UnicodeString CONST_WEBDAV_PROTOCOL_BASE_NAME = L"WebDAV";
  39. static const int HttpUnauthorized = 401;
  40. //---------------------------------------------------------------------------
  41. #define DAV_PROP_NAMESPACE "DAV:"
  42. #define MODDAV_PROP_NAMESPACE "http://apache.org/dav/props/"
  43. #define PROP_CONTENT_LENGTH "getcontentlength"
  44. #define PROP_LAST_MODIFIED "getlastmodified"
  45. #define PROP_RESOURCE_TYPE "resourcetype"
  46. #define PROP_HIDDEN "ishidden"
  47. #define PROP_QUOTA_AVAILABLE "quota-available-bytes"
  48. #define PROP_QUOTA_USED "quota-used-bytes"
  49. #define PROP_EXECUTABLE "executable"
  50. #define PROP_OWNER "owner"
  51. #define PROP_DISPLAY_NAME "displayname"
  52. //------------------------------------------------------------------------------
  53. //---------------------------------------------------------------------------
  54. // ne_path_escape returns 7-bit string, so it does not really matter if we use
  55. // AnsiString or UTF8String here, though UTF8String might be more safe
  56. static AnsiString PathEscape(const char * Path)
  57. {
  58. char * EscapedPath = ne_path_escape(Path);
  59. AnsiString Result = EscapedPath;
  60. ne_free(EscapedPath);
  61. return Result;
  62. }
  63. //---------------------------------------------------------------------------
  64. static UTF8String PathUnescape(const char * Path)
  65. {
  66. char * UnescapedPath = ne_path_unescape(Path);
  67. UTF8String Result = UnescapedPath;
  68. ne_free(UnescapedPath);
  69. return Result;
  70. }
  71. //---------------------------------------------------------------------------
  72. #define AbsolutePathToNeon(P) PathEscape(StrToNeon(P)).c_str()
  73. #define PathToNeonStatic(THIS, P) AbsolutePathToNeon((THIS)->AbsolutePath(P, false))
  74. #define PathToNeon(P) PathToNeonStatic(this, P)
  75. //---------------------------------------------------------------------------
  76. //---------------------------------------------------------------------------
  77. static bool NeonInitialized = false;
  78. static bool NeonSspiInitialized = false;
  79. //---------------------------------------------------------------------------
  80. void __fastcall NeonInitialize()
  81. {
  82. // Even if this fails, we do not want to interrupt WinSCP starting for that.
  83. // Anyway, it can hardly fail.
  84. // Though it fails on Wine on Debian VM, because of ne_sspi_init():
  85. // sspi: QuerySecurityPackageInfo [failed] [80090305].
  86. // sspi: Unable to get negotiate maximum packet size
  87. int NeonResult = ne_sock_init();
  88. if (NeonResult == 0)
  89. {
  90. NeonInitialized = true;
  91. NeonSspiInitialized = true;
  92. }
  93. else if (NeonResult == -2)
  94. {
  95. NeonInitialized = true;
  96. NeonSspiInitialized = false;
  97. }
  98. else
  99. {
  100. NeonInitialized = false;
  101. NeonSspiInitialized = false;
  102. }
  103. }
  104. //---------------------------------------------------------------------------
  105. void __fastcall NeonFinalize()
  106. {
  107. if (NeonInitialized)
  108. {
  109. ne_sock_exit();
  110. NeonInitialized = false;
  111. }
  112. }
  113. //---------------------------------------------------------------------------
  114. void __fastcall RequireNeon(TTerminal * Terminal)
  115. {
  116. if (!NeonInitialized)
  117. {
  118. throw Exception(LoadStr(NEON_INIT_FAILED2));
  119. }
  120. if (!NeonSspiInitialized)
  121. {
  122. Terminal->LogEvent(L"Warning: SSPI initialization failed.");
  123. }
  124. }
  125. //---------------------------------------------------------------------------
  126. UnicodeString __fastcall NeonVersion()
  127. {
  128. UnicodeString Str = StrFromNeon(ne_version_string());
  129. CutToChar(Str, L' ', true); // "neon"
  130. UnicodeString Result = CutToChar(Str, L':', true);
  131. return Result;
  132. }
  133. //---------------------------------------------------------------------------
  134. UnicodeString __fastcall ExpatVersion()
  135. {
  136. return FORMAT(L"%d.%d.%d", (XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION));
  137. }
  138. //---------------------------------------------------------------------------
  139. //---------------------------------------------------------------------------
  140. TWebDAVFileSystem::TWebDAVFileSystem(TTerminal * ATerminal) :
  141. TCustomFileSystem(ATerminal),
  142. FActive(false),
  143. FHasTrailingSlash(false),
  144. FNeonSession(NULL),
  145. FNeonLockStore(NULL),
  146. FNeonLockStoreSection(new TCriticalSection()),
  147. FUploading(false),
  148. FDownloading(false),
  149. FInitialHandshake(false),
  150. FIgnoreAuthenticationFailure(iafNo)
  151. {
  152. FFileSystemInfo.ProtocolBaseName = CONST_WEBDAV_PROTOCOL_BASE_NAME;
  153. FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
  154. }
  155. //---------------------------------------------------------------------------
  156. __fastcall TWebDAVFileSystem::~TWebDAVFileSystem()
  157. {
  158. UnregisterFromNeonDebug(FTerminal);
  159. {
  160. TGuard Guard(FNeonLockStoreSection);
  161. if (FNeonLockStore != NULL)
  162. {
  163. ne_lockstore_destroy(FNeonLockStore);
  164. FNeonLockStore = NULL;
  165. }
  166. }
  167. delete FNeonLockStoreSection;
  168. }
  169. //---------------------------------------------------------------------------
  170. void __fastcall TWebDAVFileSystem::Open()
  171. {
  172. RequireNeon(FTerminal);
  173. RegisterForNeonDebug(FTerminal);
  174. FCurrentDirectory = L"";
  175. FHasTrailingSlash = true;
  176. FStoredPasswordTried = false;
  177. FTlsVersionStr = L"";
  178. FCapabilities = 0;
  179. TSessionData * Data = FTerminal->SessionData;
  180. FSessionInfo.LoginTime = Now();
  181. FSessionInfo.CertificateVerifiedManually = false;
  182. UnicodeString HostName = Data->HostNameExpanded;
  183. size_t Port = Data->PortNumber;
  184. UnicodeString ProtocolName = (FTerminal->SessionData->Ftps == ftpsNone) ? HttpProtocol : HttpsProtocol;
  185. UnicodeString Path = Data->RemoteDirectory;
  186. // PathToNeon is not used as we cannot call AbsolutePath here
  187. UnicodeString EscapedPath = StrFromNeon(PathEscape(StrToNeon(Path)).c_str());
  188. UnicodeString Url = FORMAT(L"%s://%s:%d%s", (ProtocolName, HostName, Port, EscapedPath));
  189. FTerminal->Information(LoadStr(STATUS_CONNECT), true);
  190. FActive = false;
  191. try
  192. {
  193. OpenUrl(Url);
  194. }
  195. catch (Exception & E)
  196. {
  197. CloseNeonSession();
  198. FTerminal->Closed();
  199. FTerminal->FatalError(&E, LoadStr(CONNECTION_FAILED));
  200. }
  201. FActive = true;
  202. }
  203. //---------------------------------------------------------------------------
  204. UnicodeString __fastcall TWebDAVFileSystem::ParsePathFromUrl(const UnicodeString & Url)
  205. {
  206. UnicodeString Result;
  207. ne_uri ParsedUri;
  208. if (ne_uri_parse(StrToNeon(Url), &ParsedUri) == 0)
  209. {
  210. Result = StrFromNeon(PathUnescape(ParsedUri.path));
  211. ne_uri_free(&ParsedUri);
  212. }
  213. return Result;
  214. }
  215. //---------------------------------------------------------------------------
  216. void TWebDAVFileSystem::OpenUrl(const UnicodeString & Url)
  217. {
  218. UnicodeString CorrectedUrl;
  219. NeonClientOpenSessionInternal(CorrectedUrl, Url);
  220. if (CorrectedUrl.IsEmpty())
  221. {
  222. CorrectedUrl = Url;
  223. }
  224. UnicodeString ParsedPath = ParsePathFromUrl(CorrectedUrl);
  225. if (!ParsedPath.IsEmpty())
  226. {
  227. // this is most likely pointless as it get overwritten by
  228. // call to ChangeDirectory() from TTerminal::DoStartup
  229. FCurrentDirectory = ParsedPath;
  230. }
  231. }
  232. //---------------------------------------------------------------------------
  233. void TWebDAVFileSystem::NeonClientOpenSessionInternal(UnicodeString & CorrectedUrl, UnicodeString Url)
  234. {
  235. std::unique_ptr<TStringList> AttemptedUrls(CreateSortedStringList());
  236. AttemptedUrls->Add(Url);
  237. while (true)
  238. {
  239. CorrectedUrl = L"";
  240. NeonOpen(CorrectedUrl, Url);
  241. // No error and no corrected URL? We're done here.
  242. if (CorrectedUrl.IsEmpty())
  243. {
  244. break;
  245. }
  246. CloseNeonSession();
  247. CheckRedirectLoop(CorrectedUrl, AttemptedUrls.get());
  248. // Our caller will want to know what our final corrected URL was.
  249. Url = CorrectedUrl;
  250. }
  251. CorrectedUrl = Url;
  252. }
  253. //---------------------------------------------------------------------------
  254. void __fastcall TWebDAVFileSystem::SetSessionTls(ne_session_s * Session, bool Aux)
  255. {
  256. SetNeonTlsInit(Session, InitSslSession);
  257. // When the CA certificate or server certificate has
  258. // verification problems, neon will call our verify function before
  259. // outright rejection of the connection.
  260. ne_ssl_verify_fn Callback = Aux ? NeonServerSSLCallbackAux : NeonServerSSLCallbackMain;
  261. ne_ssl_set_verify(Session, Callback, this);
  262. ne_ssl_trust_default_ca(Session);
  263. }
  264. //---------------------------------------------------------------------------
  265. void __fastcall TWebDAVFileSystem::InitSession(ne_session_s * Session)
  266. {
  267. TSessionData * Data = FTerminal->SessionData;
  268. InitNeonSession(
  269. Session, Data->ProxyMethod, Data->ProxyHost, Data->ProxyPort,
  270. Data->ProxyUsername, Data->ProxyPassword, FTerminal);
  271. ne_set_read_timeout(Session, Data->Timeout);
  272. ne_set_connect_timeout(Session, Data->Timeout);
  273. ne_set_session_private(Session, SESSION_FS_KEY, this);
  274. }
  275. //---------------------------------------------------------------------------
  276. void TWebDAVFileSystem::NeonOpen(UnicodeString & CorrectedUrl, const UnicodeString & Url)
  277. {
  278. ne_uri uri;
  279. NeonParseUrl(Url, uri);
  280. FHostName = StrFromNeon(uri.host);
  281. FPortNumber = uri.port;
  282. FSessionInfo.CSCipher = UnicodeString();
  283. FSessionInfo.SCCipher = UnicodeString();
  284. bool Ssl = IsTlsUri(uri);
  285. FSessionInfo.SecurityProtocolName = Ssl ? LoadStr(FTPS_IMPLICIT) : UnicodeString();
  286. if (Ssl != (FTerminal->SessionData->Ftps != ftpsNone))
  287. {
  288. FTerminal->LogEvent(FORMAT(L"Warning: %s", (LoadStr(UNENCRYPTED_REDIRECT))));
  289. }
  290. DebugAssert(FNeonSession == NULL);
  291. FNeonSession = CreateNeonSession(uri);
  292. InitSession(FNeonSession);
  293. UTF8String Path = uri.path;
  294. ne_uri_free(&uri);
  295. ne_set_aux_request_init(FNeonSession, NeonAuxRequestInit, this);
  296. UpdateNeonDebugMask();
  297. NeonAddAuthentiation(Ssl);
  298. if (Ssl)
  299. {
  300. SetSessionTls(FNeonSession, false);
  301. ne_ssl_provide_clicert(FNeonSession, NeonProvideClientCert, this);
  302. }
  303. ne_set_notifier(FNeonSession, NeonNotifier, this);
  304. ne_hook_create_request(FNeonSession, NeonCreateRequest, this);
  305. ne_hook_pre_send(FNeonSession, NeonPreSend, this);
  306. ne_hook_post_send(FNeonSession, NeonPostSend, this);
  307. ne_hook_post_headers(FNeonSession, NeonPostHeaders, this);
  308. TAutoFlag Flag(FInitialHandshake);
  309. ExchangeCapabilities(Path.c_str(), CorrectedUrl);
  310. }
  311. //---------------------------------------------------------------------------
  312. void TWebDAVFileSystem::NeonAuxRequestInit(ne_session * Session, ne_request * /*Request*/, void * UserData)
  313. {
  314. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  315. FileSystem->InitSession(Session);
  316. ne_uri uri = {0};
  317. ne_fill_server_uri(Session, &uri);
  318. bool Tls = IsTlsUri(uri);
  319. ne_uri_free(&uri);
  320. if (Tls)
  321. {
  322. FileSystem->SetSessionTls(Session, true);
  323. }
  324. }
  325. //---------------------------------------------------------------------------
  326. void __fastcall TWebDAVFileSystem::NeonAddAuthentiation(bool UseNegotiate)
  327. {
  328. unsigned int NeonAuthTypes = NE_AUTH_BASIC | NE_AUTH_DIGEST | NE_AUTH_PASSPORT;
  329. if (UseNegotiate)
  330. {
  331. NeonAuthTypes |= NE_AUTH_NEGOTIATE;
  332. }
  333. ne_add_server_auth(FNeonSession, NeonAuthTypes, NeonRequestAuth, this);
  334. }
  335. //---------------------------------------------------------------------------
  336. UnicodeString __fastcall TWebDAVFileSystem::GetRedirectUrl()
  337. {
  338. UnicodeString Result = GetNeonRedirectUrl(FNeonSession);
  339. FTerminal->LogEvent(FORMAT(L"Redirected to \"%s\".", (Result)));
  340. return Result;
  341. }
  342. //---------------------------------------------------------------------------
  343. void TWebDAVFileSystem::ExchangeCapabilities(const char * Path, UnicodeString & CorrectedUrl)
  344. {
  345. ClearNeonError();
  346. int NeonStatus;
  347. FAuthenticationRetry = false;
  348. do
  349. {
  350. NeonStatus = ne_options2(FNeonSession, Path, &FCapabilities);
  351. }
  352. while ((NeonStatus == NE_AUTH) && FAuthenticationRetry);
  353. if (NeonStatus == NE_REDIRECT)
  354. {
  355. CorrectedUrl = GetRedirectUrl();
  356. }
  357. else if (NeonStatus == NE_OK)
  358. {
  359. if (FCapabilities > 0)
  360. {
  361. UnicodeString Str;
  362. unsigned int Capability = 0x01;
  363. unsigned int Capabilities = FCapabilities;
  364. while (Capabilities > 0)
  365. {
  366. if (FLAGSET(Capabilities, Capability))
  367. {
  368. AddToList(Str, StrFromNeon(ne_capability_name(Capability)), L", ");
  369. Capabilities -= Capability;
  370. }
  371. Capability <<= 1;
  372. }
  373. FTerminal->LogEvent(FORMAT(L"Server capabilities: %s", (Str)));
  374. FFileSystemInfo.AdditionalInfo +=
  375. LoadStr(WEBDAV_EXTENSION_INFO) + sLineBreak +
  376. L" " + Str + sLineBreak;
  377. }
  378. }
  379. else
  380. {
  381. CheckStatus(NeonStatus);
  382. }
  383. FTerminal->SaveCapabilities(FFileSystemInfo);
  384. }
  385. //---------------------------------------------------------------------------
  386. void __fastcall TWebDAVFileSystem::CloseNeonSession()
  387. {
  388. if (FNeonSession != NULL)
  389. {
  390. DestroyNeonSession(FNeonSession);
  391. FNeonSession = NULL;
  392. }
  393. }
  394. //---------------------------------------------------------------------------
  395. void __fastcall TWebDAVFileSystem::Close()
  396. {
  397. DebugAssert(FActive);
  398. CloseNeonSession();
  399. FTerminal->Closed();
  400. FActive = false;
  401. UnregisterFromNeonDebug(FTerminal);
  402. }
  403. //---------------------------------------------------------------------------
  404. bool __fastcall TWebDAVFileSystem::GetActive()
  405. {
  406. return FActive;
  407. }
  408. //---------------------------------------------------------------------------
  409. void __fastcall TWebDAVFileSystem::CollectUsage()
  410. {
  411. if (!FTlsVersionStr.IsEmpty())
  412. {
  413. FTerminal->CollectTlsUsage(FTlsVersionStr);
  414. }
  415. if (!FTerminal->SessionData->TlsCertificateFile.IsEmpty())
  416. {
  417. Configuration->Usage->Inc(L"OpenedSessionsWebDAVSCertificate");
  418. }
  419. // The Authorization header for passport method is included only in the first request,
  420. // so we have to use FLastAuthorizationProtocol
  421. if (SameText(FLastAuthorizationProtocol, L"Passport1.4"))
  422. {
  423. Configuration->Usage->Inc(L"OpenedSessionsWebDAVSPassport");
  424. }
  425. UnicodeString RemoteSystem = FFileSystemInfo.RemoteSystem;
  426. if (ContainsText(RemoteSystem, L"Microsoft-IIS"))
  427. {
  428. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVIIS");
  429. }
  430. else if (ContainsText(RemoteSystem, L"IT Hit WebDAV Server"))
  431. {
  432. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVITHit");
  433. }
  434. // e.g. brickftp.com
  435. else if (ContainsText(RemoteSystem, L"nginx"))
  436. {
  437. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVNginx");
  438. }
  439. else
  440. {
  441. // We also know OpenDrive, Yandex, iFiles (iOS), Swapper (iOS), SafeSync
  442. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVOther");
  443. }
  444. }
  445. //---------------------------------------------------------------------------
  446. const TSessionInfo & __fastcall TWebDAVFileSystem::GetSessionInfo()
  447. {
  448. return FSessionInfo;
  449. }
  450. //---------------------------------------------------------------------------
  451. const TFileSystemInfo & __fastcall TWebDAVFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  452. {
  453. return FFileSystemInfo;
  454. }
  455. //---------------------------------------------------------------------------
  456. bool __fastcall TWebDAVFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
  457. {
  458. return false;
  459. }
  460. //---------------------------------------------------------------------------
  461. bool __fastcall TWebDAVFileSystem::GetStoredCredentialsTried()
  462. {
  463. return FStoredPasswordTried;
  464. }
  465. //---------------------------------------------------------------------------
  466. UnicodeString __fastcall TWebDAVFileSystem::GetUserName()
  467. {
  468. return FUserName;
  469. }
  470. //---------------------------------------------------------------------------
  471. void __fastcall TWebDAVFileSystem::Idle()
  472. {
  473. // noop
  474. }
  475. //---------------------------------------------------------------------------
  476. UnicodeString __fastcall TWebDAVFileSystem::AbsolutePath(const UnicodeString Path, bool /*Local*/)
  477. {
  478. bool AddTrailingBackslash;
  479. if (Path == L"/")
  480. {
  481. // does not really matter as path "/" is still "/" when absolute,
  482. // no slash needed
  483. AddTrailingBackslash = FHasTrailingSlash;
  484. }
  485. else
  486. {
  487. AddTrailingBackslash = (Path[Path.Length()] == L'/');
  488. }
  489. UnicodeString Result = ::AbsolutePath(GetCurrentDirectory(), Path);
  490. // We must preserve trailing slash, because particularly for mod_dav,
  491. // it really matters if the slash in there or not
  492. if (AddTrailingBackslash)
  493. {
  494. Result = UnixIncludeTrailingBackslash(Result);
  495. }
  496. return Result;
  497. }
  498. //---------------------------------------------------------------------------
  499. bool __fastcall TWebDAVFileSystem::IsCapable(int Capability) const
  500. {
  501. DebugAssert(FTerminal);
  502. switch (Capability)
  503. {
  504. case fcRename:
  505. case fcRemoteMove:
  506. case fcMoveToQueue:
  507. case fcPreservingTimestampUpload:
  508. case fcCheckingSpaceAvailable:
  509. // Only to make double-click on file edit/open the file,
  510. // instead of trying to open it as directory
  511. case fcResolveSymlink:
  512. case fsSkipTransfer:
  513. case fsParallelTransfers:
  514. case fcRemoteCopy:
  515. return true;
  516. case fcUserGroupListing:
  517. case fcModeChanging:
  518. case fcModeChangingUpload:
  519. case fcGroupChanging:
  520. case fcOwnerChanging:
  521. case fcAnyCommand:
  522. case fcShellAnyCommand:
  523. case fcHardLink:
  524. case fcSymbolicLink:
  525. case fcTextMode:
  526. case fcNativeTextMode:
  527. case fcNewerOnlyUpload:
  528. case fcTimestampChanging:
  529. case fcLoadingAdditionalProperties:
  530. case fcIgnorePermErrors:
  531. case fcCalculatingChecksum:
  532. case fcSecondaryShell:
  533. case fcGroupOwnerChangingByID:
  534. case fcRemoveCtrlZUpload:
  535. case fcRemoveBOMUpload:
  536. case fcPreservingTimestampDirs:
  537. case fcResumeSupport:
  538. case fcChangePassword:
  539. return false;
  540. case fcLocking:
  541. return FLAGSET(FCapabilities, NE_CAP_DAV_CLASS2);
  542. default:
  543. DebugFail();
  544. return false;
  545. }
  546. }
  547. //---------------------------------------------------------------------------
  548. UnicodeString __fastcall TWebDAVFileSystem::GetCurrentDirectory()
  549. {
  550. return FCurrentDirectory;
  551. }
  552. //---------------------------------------------------------------------------
  553. void __fastcall TWebDAVFileSystem::DoStartup()
  554. {
  555. FTerminal->SetExceptionOnFail(true);
  556. // retrieve initialize working directory to save it as home directory
  557. ReadCurrentDirectory();
  558. FTerminal->SetExceptionOnFail(false);
  559. }
  560. //---------------------------------------------------------------------------
  561. void __fastcall TWebDAVFileSystem::ClearNeonError()
  562. {
  563. FCancelled = false;
  564. FSkipped = false;
  565. FAuthenticationRequested = false;
  566. ne_set_error(FNeonSession, "");
  567. }
  568. //---------------------------------------------------------------------------
  569. UnicodeString __fastcall TWebDAVFileSystem::GetNeonError()
  570. {
  571. return ::GetNeonError(FNeonSession);
  572. }
  573. //---------------------------------------------------------------------------
  574. void __fastcall TWebDAVFileSystem::CheckStatus(int NeonStatus)
  575. {
  576. if ((NeonStatus == NE_ERROR) && (FCancelled || FSkipped))
  577. {
  578. if (FCancelled)
  579. {
  580. FCancelled = false;
  581. FSkipped = false; // just in case
  582. Abort();
  583. }
  584. else
  585. {
  586. DebugAssert(FSkipped);
  587. FSkipped = false;
  588. throw ESkipFile();
  589. }
  590. }
  591. else
  592. {
  593. CheckNeonStatus(FNeonSession, NeonStatus, FHostName);
  594. }
  595. }
  596. //---------------------------------------------------------------------------
  597. void __fastcall TWebDAVFileSystem::LookupUsersGroups()
  598. {
  599. DebugFail();
  600. }
  601. //---------------------------------------------------------------------------
  602. void __fastcall TWebDAVFileSystem::ReadCurrentDirectory()
  603. {
  604. if (FCachedDirectoryChange.IsEmpty())
  605. {
  606. FCurrentDirectory = FCurrentDirectory.IsEmpty() ? UnicodeString(L"/") : FCurrentDirectory;
  607. }
  608. else
  609. {
  610. FCurrentDirectory = FCachedDirectoryChange;
  611. FCachedDirectoryChange = L"";
  612. }
  613. }
  614. //---------------------------------------------------------------------------
  615. void __fastcall TWebDAVFileSystem::HomeDirectory()
  616. {
  617. ChangeDirectory(L"/");
  618. }
  619. //---------------------------------------------------------------------------
  620. UnicodeString __fastcall TWebDAVFileSystem::DirectoryPath(UnicodeString Path)
  621. {
  622. if (FHasTrailingSlash)
  623. {
  624. Path = ::UnixIncludeTrailingBackslash(Path);
  625. }
  626. return Path;
  627. }
  628. //---------------------------------------------------------------------------
  629. UnicodeString __fastcall TWebDAVFileSystem::FilePath(const TRemoteFile * File)
  630. {
  631. UnicodeString Result = File->FullFileName;
  632. if (File->IsDirectory)
  633. {
  634. Result = DirectoryPath(Result);
  635. }
  636. return Result;
  637. }
  638. //---------------------------------------------------------------------------
  639. void __fastcall TWebDAVFileSystem::TryOpenDirectory(UnicodeString Directory)
  640. {
  641. Directory = DirectoryPath(Directory);
  642. FTerminal->LogEvent(FORMAT(L"Trying to open directory \"%s\".", (Directory)));
  643. TRemoteFile * File;
  644. ReadFile(Directory, File);
  645. delete File;
  646. }
  647. //---------------------------------------------------------------------------
  648. void __fastcall TWebDAVFileSystem::AnnounceFileListOperation()
  649. {
  650. // noop
  651. }
  652. //---------------------------------------------------------------------------
  653. void __fastcall TWebDAVFileSystem::ChangeDirectory(const UnicodeString ADirectory)
  654. {
  655. UnicodeString Path = AbsolutePath(ADirectory, false);
  656. // to verify existence of directory try to open it
  657. TryOpenDirectory(Path);
  658. // if open dir did not fail, directory exists -> success.
  659. FCachedDirectoryChange = Path;
  660. }
  661. //---------------------------------------------------------------------------
  662. void __fastcall TWebDAVFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  663. {
  664. FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
  665. }
  666. //---------------------------------------------------------------------------
  667. struct TReadFileData
  668. {
  669. TWebDAVFileSystem * FileSystem;
  670. TRemoteFile * File;
  671. TRemoteFileList * FileList;
  672. };
  673. //---------------------------------------------------------------------------
  674. int __fastcall TWebDAVFileSystem::ReadDirectoryInternal(
  675. const UnicodeString & Path, TRemoteFileList * FileList)
  676. {
  677. TReadFileData Data;
  678. Data.FileSystem = this;
  679. Data.File = NULL;
  680. Data.FileList = FileList;
  681. ClearNeonError();
  682. ne_propfind_handler * PropFindHandler = ne_propfind_create(FNeonSession, PathToNeon(Path), NE_DEPTH_ONE);
  683. void * DiscoveryContext = ne_lock_register_discovery(PropFindHandler);
  684. int Result;
  685. try
  686. {
  687. Result = ne_propfind_allprop(PropFindHandler, NeonPropsResult, &Data);
  688. }
  689. __finally
  690. {
  691. ne_lock_discovery_free(DiscoveryContext);
  692. ne_propfind_destroy(PropFindHandler);
  693. }
  694. return Result;
  695. }
  696. //---------------------------------------------------------------------------
  697. bool __fastcall TWebDAVFileSystem::IsValidRedirect(int NeonStatus, UnicodeString & Path)
  698. {
  699. bool Result = (NeonStatus == NE_REDIRECT);
  700. if (Result)
  701. {
  702. // What PathToNeon does
  703. UnicodeString OriginalPath = AbsolutePath(Path, false);
  704. // Handle one-step redirect
  705. // (for more steps we would have to implement loop detection).
  706. // This is mainly to handle "folder" => "folder/" redirects of Apache/mod_dav.
  707. UnicodeString RedirectUrl = GetRedirectUrl();
  708. // We should test if the redirect is not for another server,
  709. // though not sure how to do this reliably (domain aliases, IP vs. domain, etc.)
  710. UnicodeString RedirectPath = ParsePathFromUrl(RedirectUrl);
  711. Result =
  712. !RedirectPath.IsEmpty() &&
  713. (RedirectPath != OriginalPath);
  714. if (Result)
  715. {
  716. Path = RedirectPath;
  717. }
  718. }
  719. return Result;
  720. }
  721. //---------------------------------------------------------------------------
  722. void __fastcall TWebDAVFileSystem::ReadDirectory(TRemoteFileList * FileList)
  723. {
  724. UnicodeString Path = DirectoryPath(FileList->Directory);
  725. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  726. int NeonStatus = ReadDirectoryInternal(Path, FileList);
  727. if (IsValidRedirect(NeonStatus, Path))
  728. {
  729. NeonStatus = ReadDirectoryInternal(Path, FileList);
  730. }
  731. CheckStatus(NeonStatus);
  732. }
  733. //---------------------------------------------------------------------------
  734. void __fastcall TWebDAVFileSystem::ReadSymlink(TRemoteFile * /*SymlinkFile*/,
  735. TRemoteFile *& /*File*/)
  736. {
  737. // we never set SymLink flag, so we should never get here
  738. DebugFail();
  739. }
  740. //---------------------------------------------------------------------------
  741. void __fastcall TWebDAVFileSystem::ReadFile(const UnicodeString FileName,
  742. TRemoteFile *& File)
  743. {
  744. CustomReadFile(FileName, File, NULL);
  745. }
  746. //---------------------------------------------------------------------------
  747. void TWebDAVFileSystem::NeonPropsResult(
  748. void * UserData, const ne_uri * Uri, const ne_prop_result_set * Results)
  749. {
  750. UnicodeString Path = StrFromNeon(PathUnescape(Uri->path).c_str());
  751. TReadFileData & Data = *static_cast<TReadFileData *>(UserData);
  752. if (Data.FileList != NULL)
  753. {
  754. UnicodeString FileListPath = Data.FileSystem->AbsolutePath(Data.FileList->Directory, false);
  755. if (UnixSamePath(Path, FileListPath))
  756. {
  757. Path = UnixIncludeTrailingBackslash(UnixIncludeTrailingBackslash(Path) + PARENTDIRECTORY);
  758. }
  759. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  760. File->Terminal = Data.FileSystem->FTerminal;
  761. Data.FileSystem->ParsePropResultSet(File.get(), Path, Results);
  762. Data.FileList->AddFile(File.release());
  763. }
  764. else
  765. {
  766. Data.FileSystem->ParsePropResultSet(Data.File, Path, Results);
  767. }
  768. }
  769. //---------------------------------------------------------------------------
  770. const char * __fastcall TWebDAVFileSystem::GetProp(
  771. const ne_prop_result_set * Results, const char * Name, const char * NameSpace)
  772. {
  773. ne_propname Prop;
  774. Prop.nspace = (NameSpace == NULL) ? DAV_PROP_NAMESPACE : NameSpace;
  775. Prop.name = Name;
  776. return ne_propset_value(Results, &Prop);
  777. }
  778. //---------------------------------------------------------------------------
  779. void __fastcall TWebDAVFileSystem::ParsePropResultSet(TRemoteFile * File,
  780. const UnicodeString & Path, const ne_prop_result_set * Results)
  781. {
  782. File->FullFileName = UnixExcludeTrailingBackslash(Path);
  783. // Some servers do not use DAV:collection tag, but indicate the folder by trailing slash only.
  784. // It seems that all servers actually use the trailing slash, including IIS, mod_Dav, IT Hit, OpenDrive, etc.
  785. bool Collection = (File->FullFileName != Path);
  786. File->FileName = UnixExtractFileName(File->FullFileName);
  787. const char * ContentLength = GetProp(Results, PROP_CONTENT_LENGTH);
  788. // some servers, for example iFiles, do not provide "getcontentlength" for folders
  789. if (ContentLength != NULL)
  790. {
  791. File->Size = StrToInt64Def(ContentLength, 0);
  792. }
  793. const char * LastModified = GetProp(Results, PROP_LAST_MODIFIED);
  794. // We've seen a server (t=24891) that does not set "getlastmodified" for the "this" folder entry.
  795. if (LastModified != NULL)
  796. {
  797. char WeekDay[4] = { L'\0' };
  798. int Year = 0;
  799. char MonthStr[4] = { L'\0' };
  800. int Day = 0;
  801. int Hour = 0;
  802. int Min = 0;
  803. int Sec = 0;
  804. #define RFC1123_FORMAT "%3s, %02d %3s %4d %02d:%02d:%02d GMT"
  805. int Filled =
  806. sscanf(LastModified, RFC1123_FORMAT, WeekDay, &Day, MonthStr, &Year, &Hour, &Min, &Sec);
  807. // we need at least a complete date
  808. if (Filled >= 4)
  809. {
  810. int Month = ParseShortEngMonthName(MonthStr);
  811. if (Month >= 1)
  812. {
  813. TDateTime Modification =
  814. EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) +
  815. EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0);
  816. File->Modification = ConvertTimestampFromUTC(Modification);
  817. File->ModificationFmt = mfFull;
  818. }
  819. }
  820. }
  821. // optimization
  822. if (!Collection)
  823. {
  824. // This is possibly redundant code as all servers we know (see a comment above)
  825. // indicate the folder by trailing slash too
  826. const char * ResourceType = GetProp(Results, PROP_RESOURCE_TYPE);
  827. if (ResourceType != NULL)
  828. {
  829. // property has XML value
  830. UnicodeString AResourceType = ResourceType;
  831. // this is very poor parsing
  832. if (ContainsText(ResourceType, L"<DAV:collection"))
  833. {
  834. Collection = true;
  835. }
  836. }
  837. }
  838. File->Type = Collection ? FILETYPE_DIRECTORY : FILETYPE_DEFAULT;
  839. // this is MS extension (draft-hopmann-collection-props-00)
  840. const char * IsHidden = GetProp(Results, PROP_HIDDEN);
  841. if (IsHidden != NULL)
  842. {
  843. File->IsHidden = (StrToIntDef(IsHidden, 0) != 0);
  844. }
  845. const char * Owner = GetProp(Results, PROP_OWNER);
  846. if (Owner != NULL)
  847. {
  848. File->Owner.Name = Owner;
  849. }
  850. const char * DisplayName = GetProp(Results, PROP_DISPLAY_NAME);
  851. if (DisplayName != NULL)
  852. {
  853. File->DisplayName = StrFromNeon(DisplayName);
  854. }
  855. const UnicodeString RightsDelimiter(L", ");
  856. UnicodeString HumanRights;
  857. // Proprietary property of mod_dav
  858. // http://www.webdav.org/mod_dav/#imp
  859. const char * Executable = GetProp(Results, PROP_EXECUTABLE, MODDAV_PROP_NAMESPACE);
  860. if (Executable != NULL)
  861. {
  862. if (strcmp(Executable, "T") == NULL)
  863. {
  864. UnicodeString ExecutableRights;
  865. // The "gear" character is supported since Windows 8
  866. if (IsWin8())
  867. {
  868. ExecutableRights = L"\u2699";
  869. }
  870. else
  871. {
  872. ExecutableRights = LoadStr(EXECUTABLE);
  873. }
  874. AddToList(HumanRights, ExecutableRights, RightsDelimiter);
  875. }
  876. }
  877. struct ne_lock * Lock = static_cast<struct ne_lock *>(ne_propset_private(Results));
  878. if ((Lock != NULL) && (Lock->token != NULL))
  879. {
  880. UnicodeString Owner;
  881. if (Lock->owner != NULL)
  882. {
  883. Owner = StrFromNeon(Lock->owner).Trim();
  884. }
  885. UnicodeString LockRights;
  886. if (IsWin8())
  887. {
  888. // The "lock" character is supported since Windows 8
  889. LockRights = L"\uD83D\uDD12" + Owner;
  890. }
  891. else
  892. {
  893. LockRights = LoadStr(LOCKED);
  894. if (!Owner.IsEmpty())
  895. {
  896. LockRights = FORMAT(L"%s (%s)", (LockRights, Owner));
  897. }
  898. }
  899. AddToList(HumanRights, LockRights, RightsDelimiter);
  900. }
  901. File->HumanRights = HumanRights;
  902. }
  903. //---------------------------------------------------------------------------
  904. int __fastcall TWebDAVFileSystem::CustomReadFileInternal(const UnicodeString FileName,
  905. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  906. {
  907. std::unique_ptr<TRemoteFile> AFile(new TRemoteFile(ALinkedByFile));
  908. TReadFileData Data;
  909. Data.FileSystem = this;
  910. Data.File = AFile.get();
  911. Data.FileList = NULL;
  912. ClearNeonError();
  913. int Result =
  914. ne_simple_propfind(FNeonSession, PathToNeon(FileName), NE_DEPTH_ZERO, NULL,
  915. NeonPropsResult, &Data);
  916. if (Result == NE_OK)
  917. {
  918. File = AFile.release();
  919. }
  920. return Result;
  921. }
  922. //---------------------------------------------------------------------------
  923. void __fastcall TWebDAVFileSystem::CustomReadFile(UnicodeString FileName,
  924. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  925. {
  926. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  927. int NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  928. if (IsValidRedirect(NeonStatus, FileName))
  929. {
  930. NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  931. }
  932. CheckStatus(NeonStatus);
  933. }
  934. //---------------------------------------------------------------------------
  935. void __fastcall TWebDAVFileSystem::DeleteFile(const UnicodeString FileName,
  936. const TRemoteFile * File, int /*Params*/, TRmSessionAction & Action)
  937. {
  938. Action.Recursive();
  939. ClearNeonError();
  940. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  941. RawByteString Path = PathToNeon(FilePath(File));
  942. // WebDAV does not allow non-recursive delete:
  943. // RFC 4918, section 9.6.1:
  944. // "A client MUST NOT submit a Depth header with a DELETE on a collection with any value but infinity."
  945. // We should check that folder is empty when called with FLAGSET(Params, dfNoRecursive)
  946. CheckStatus(ne_delete(FNeonSession, Path.c_str()));
  947. // The lock is removed with the file, but if a file with the same name gets created,
  948. // we would try to use obsoleted lock token with it, what the server would reject
  949. // (mod_dav returns "412 Precondition Failed")
  950. DiscardLock(Path);
  951. }
  952. //---------------------------------------------------------------------------
  953. int __fastcall TWebDAVFileSystem::RenameFileInternal(const UnicodeString & FileName,
  954. const UnicodeString & NewName)
  955. {
  956. // 0 = no overwrite
  957. return ne_move(FNeonSession, 0, PathToNeon(FileName), PathToNeon(NewName));
  958. }
  959. //---------------------------------------------------------------------------
  960. void __fastcall TWebDAVFileSystem::RenameFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  961. const UnicodeString NewName)
  962. {
  963. ClearNeonError();
  964. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  965. UnicodeString Path = FileName;
  966. int NeonStatus = RenameFileInternal(Path, NewName);
  967. if (IsValidRedirect(NeonStatus, Path))
  968. {
  969. NeonStatus = RenameFileInternal(Path, NewName);
  970. }
  971. CheckStatus(NeonStatus);
  972. // See a comment in DeleteFile
  973. DiscardLock(PathToNeon(Path));
  974. }
  975. //---------------------------------------------------------------------------
  976. int __fastcall TWebDAVFileSystem::CopyFileInternal(const UnicodeString & FileName,
  977. const UnicodeString & NewName)
  978. {
  979. // 0 = no overwrite
  980. return ne_copy(FNeonSession, 0, NE_DEPTH_INFINITE, PathToNeon(FileName), PathToNeon(NewName));
  981. }
  982. //---------------------------------------------------------------------------
  983. void __fastcall TWebDAVFileSystem::CopyFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  984. const UnicodeString NewName)
  985. {
  986. ClearNeonError();
  987. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  988. UnicodeString Path = FileName;
  989. int NeonStatus = CopyFileInternal(Path, NewName);
  990. if (IsValidRedirect(NeonStatus, Path))
  991. {
  992. NeonStatus = CopyFileInternal(Path, NewName);
  993. }
  994. CheckStatus(NeonStatus);
  995. }
  996. //---------------------------------------------------------------------------
  997. void __fastcall TWebDAVFileSystem::CreateDirectory(const UnicodeString & DirName, bool /*Encrypt*/)
  998. {
  999. ClearNeonError();
  1000. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1001. CheckStatus(ne_mkcol(FNeonSession, PathToNeon(DirName)));
  1002. }
  1003. //---------------------------------------------------------------------------
  1004. void __fastcall TWebDAVFileSystem::CreateLink(const UnicodeString FileName,
  1005. const UnicodeString PointTo, bool /*Symbolic*/)
  1006. {
  1007. DebugFail();
  1008. }
  1009. //---------------------------------------------------------------------------
  1010. void __fastcall TWebDAVFileSystem::ChangeFileProperties(const UnicodeString FileName,
  1011. const TRemoteFile * /*File*/, const TRemoteProperties * /*Properties*/,
  1012. TChmodSessionAction & /*Action*/)
  1013. {
  1014. DebugFail();
  1015. }
  1016. //---------------------------------------------------------------------------
  1017. bool __fastcall TWebDAVFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  1018. {
  1019. DebugFail();
  1020. return false;
  1021. }
  1022. //---------------------------------------------------------------------------
  1023. void __fastcall TWebDAVFileSystem::CalculateFilesChecksum(const UnicodeString & /*Alg*/,
  1024. TStrings * /*FileList*/, TStrings * /*Checksums*/,
  1025. TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
  1026. {
  1027. DebugFail();
  1028. }
  1029. //---------------------------------------------------------------------------
  1030. void __fastcall TWebDAVFileSystem::ConfirmOverwrite(
  1031. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1032. TFileOperationProgressType * OperationProgress,
  1033. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1034. int Params)
  1035. {
  1036. // all = "yes to newer"
  1037. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll;
  1038. TQueryButtonAlias Aliases[3];
  1039. Aliases[0] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
  1040. Aliases[1] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
  1041. Aliases[2] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
  1042. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1043. QueryParams.Aliases = Aliases;
  1044. QueryParams.AliasesCount = LENOF(Aliases);
  1045. unsigned int Answer;
  1046. {
  1047. TSuspendFileOperationProgress Suspend(OperationProgress);
  1048. Answer =
  1049. FTerminal->ConfirmFileOverwrite(
  1050. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1051. ReverseOperationSide(OperationProgress->Side),
  1052. CopyParam, Params, OperationProgress);
  1053. }
  1054. switch (Answer)
  1055. {
  1056. case qaYes:
  1057. // noop
  1058. break;
  1059. case qaNo:
  1060. throw ESkipFile();
  1061. default:
  1062. DebugFail();
  1063. case qaCancel:
  1064. OperationProgress->SetCancelAtLeast(csCancel);
  1065. Abort();
  1066. break;
  1067. }
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. void __fastcall TWebDAVFileSystem::CustomCommandOnFile(const UnicodeString FileName,
  1071. const TRemoteFile * /*File*/, UnicodeString Command, int /*Params*/, TCaptureOutputEvent /*OutputEvent*/)
  1072. {
  1073. DebugFail();
  1074. }
  1075. //---------------------------------------------------------------------------
  1076. void __fastcall TWebDAVFileSystem::AnyCommand(const UnicodeString Command,
  1077. TCaptureOutputEvent /*OutputEvent*/)
  1078. {
  1079. DebugFail();
  1080. }
  1081. //---------------------------------------------------------------------------
  1082. TStrings * __fastcall TWebDAVFileSystem::GetFixedPaths()
  1083. {
  1084. return NULL;
  1085. }
  1086. //---------------------------------------------------------------------------
  1087. void TWebDAVFileSystem::NeonQuotaResult(
  1088. void * UserData, const ne_uri * /*Uri*/, const ne_prop_result_set * Results)
  1089. {
  1090. TSpaceAvailable & SpaceAvailable = *static_cast<TSpaceAvailable *>(UserData);
  1091. const char * Value = GetProp(Results, PROP_QUOTA_AVAILABLE);
  1092. if (Value != NULL)
  1093. {
  1094. SpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(StrFromNeon(Value));
  1095. const char * Value = GetProp(Results, PROP_QUOTA_USED);
  1096. if (Value != NULL)
  1097. {
  1098. SpaceAvailable.BytesAvailableToUser =
  1099. StrToInt64(StrFromNeon(Value)) + SpaceAvailable.UnusedBytesAvailableToUser;
  1100. }
  1101. }
  1102. }
  1103. //---------------------------------------------------------------------------
  1104. void __fastcall TWebDAVFileSystem::SpaceAvailable(const UnicodeString Path,
  1105. TSpaceAvailable & ASpaceAvailable)
  1106. {
  1107. // RFC4331: https://tools.ietf.org/html/rfc4331
  1108. // This is known to be supported by:
  1109. // OpenDrive: for a root drive only (and contrary to the spec, it sends the properties
  1110. // unconditionally, even when not explicitly requested)
  1111. // Server: Apache/2.2.17 (Fedora)
  1112. // X-Powered-By: PHP/5.5.7
  1113. // X-DAV-Powered-By: OpenDrive
  1114. // WWW-Authenticate: Basic realm="PHP WebDAV"
  1115. // IT Hit WebDAV Server:
  1116. // Server: Microsoft-HTTPAPI/1.0
  1117. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1118. // Yandex disk:
  1119. // WWW-Authenticate: Basic realm="Yandex.Disk"
  1120. // Server: MochiWeb/1.0
  1121. // OneDrive:
  1122. // it sends the properties unconditionally, even when not explicitly requested
  1123. UnicodeString APath = DirectoryPath(Path);
  1124. ne_propname QuotaProps[3];
  1125. memset(QuotaProps, 0, sizeof(QuotaProps));
  1126. QuotaProps[0].nspace = DAV_PROP_NAMESPACE;
  1127. QuotaProps[0].name = PROP_QUOTA_AVAILABLE;
  1128. QuotaProps[1].nspace = DAV_PROP_NAMESPACE;
  1129. QuotaProps[1].name = PROP_QUOTA_USED;
  1130. QuotaProps[2].nspace = NULL;
  1131. QuotaProps[2].name = NULL;
  1132. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1133. CheckStatus(
  1134. ne_simple_propfind(FNeonSession, PathToNeon(APath), NE_DEPTH_ZERO, QuotaProps,
  1135. NeonQuotaResult, &ASpaceAvailable));
  1136. }
  1137. //---------------------------------------------------------------------------
  1138. void __fastcall TWebDAVFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1139. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1140. int Params, TFileOperationProgressType * OperationProgress,
  1141. TOnceDoneOperation & OnceDoneOperation)
  1142. {
  1143. Params &= ~cpAppend;
  1144. FTerminal->DoCopyToRemote(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfPreCreateDir, OnceDoneOperation);
  1145. }
  1146. //---------------------------------------------------------------------------
  1147. void __fastcall TWebDAVFileSystem::Source(
  1148. TLocalFileHandle & Handle, const UnicodeString & TargetDir, UnicodeString & DestFileName,
  1149. const TCopyParamType * CopyParam, int Params,
  1150. TFileOperationProgressType * OperationProgress, unsigned int /*Flags*/,
  1151. TUploadSessionAction & Action, bool & ChildError)
  1152. {
  1153. int FD = -1;
  1154. try
  1155. {
  1156. UnicodeString DestFullName = TargetDir + DestFileName;
  1157. TRemoteFile * RemoteFile = NULL;
  1158. try
  1159. {
  1160. TValueRestorer<TIgnoreAuthenticationFailure> IgnoreAuthenticationFailureRestorer(FIgnoreAuthenticationFailure);
  1161. FIgnoreAuthenticationFailure = iafWaiting;
  1162. // this should not throw
  1163. CustomReadFileInternal(DestFullName, RemoteFile, NULL);
  1164. }
  1165. catch (...)
  1166. {
  1167. if (!FTerminal->Active)
  1168. {
  1169. throw;
  1170. }
  1171. }
  1172. if (RemoteFile != NULL)
  1173. {
  1174. TOverwriteFileParams FileParams;
  1175. FileParams.SourceSize = Handle.Size;
  1176. FileParams.SourceTimestamp = Handle.Modification;
  1177. FileParams.DestSize = RemoteFile->Size;
  1178. FileParams.DestTimestamp = RemoteFile->Modification;
  1179. delete RemoteFile;
  1180. ConfirmOverwrite(Handle.FileName, DestFileName, OperationProgress,
  1181. &FileParams, CopyParam, Params);
  1182. }
  1183. DestFullName = TargetDir + DestFileName;
  1184. // only now, we know the final destination
  1185. // (not really true as we do not support changing file name on overwrite dialog)
  1186. Action.Destination(DestFullName);
  1187. FUploadMimeType = Configuration->GetFileMimeType(DestFileName);
  1188. FILE_OPERATION_LOOP_BEGIN
  1189. {
  1190. SetFilePointer(Handle.Handle, 0, NULL, FILE_BEGIN);
  1191. FD = _open_osfhandle((intptr_t)Handle.Handle, O_BINARY);
  1192. if (FD < 0)
  1193. {
  1194. throw ESkipFile();
  1195. }
  1196. TAutoFlag UploadingFlag(FUploading);
  1197. ClearNeonError();
  1198. CheckStatus(ne_put(FNeonSession, PathToNeon(DestFullName), FD));
  1199. }
  1200. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (Handle.FileName)));
  1201. if (CopyParam->PreserveTime)
  1202. {
  1203. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1204. (StandardTimestamp(Handle.Modification))));
  1205. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Handle.Modification);
  1206. try
  1207. {
  1208. TDateTime ModificationUTC = ConvertTimestampToUTC(Handle.Modification);
  1209. TFormatSettings FormatSettings = GetEngFormatSettings();
  1210. UnicodeString LastModified =
  1211. FormatDateTime(L"ddd, d mmm yyyy hh:nn:ss 'GMT'", ModificationUTC, FormatSettings);
  1212. UTF8String NeonLastModified(LastModified);
  1213. // second element is "NULL-terminating"
  1214. ne_proppatch_operation Operations[2];
  1215. memset(Operations, 0, sizeof(Operations));
  1216. ne_propname LastModifiedProp;
  1217. LastModifiedProp.nspace = DAV_PROP_NAMESPACE;
  1218. LastModifiedProp.name = PROP_LAST_MODIFIED;
  1219. Operations[0].name = &LastModifiedProp;
  1220. Operations[0].type = ne_propset;
  1221. Operations[0].value = NeonLastModified.c_str();
  1222. int Status = ne_proppatch(FNeonSession, PathToNeon(DestFullName), Operations);
  1223. if (Status == NE_ERROR)
  1224. {
  1225. FTerminal->LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s",
  1226. (GetNeonError())));
  1227. // Ignore errors as major WebDAV servers (like IIS), do not support
  1228. // changing getlastmodified.
  1229. // The only server we found that supports this is TradeMicro SafeSync.
  1230. // But it announces itself as "Server: Apache",
  1231. // so it's not reliable to autodetect the support.
  1232. // Microsoft Office alegedly uses <Win32LastModifiedTime>
  1233. // https://sabre.io/dav/clients/msoffice/
  1234. // Carot DAV does that too. But we do not know what server does support this.
  1235. TouchAction.Cancel();
  1236. }
  1237. else
  1238. {
  1239. CheckStatus(Status);
  1240. }
  1241. }
  1242. catch (Exception & E)
  1243. {
  1244. TouchAction.Rollback(&E);
  1245. ChildError = true;
  1246. throw;
  1247. }
  1248. }
  1249. }
  1250. __finally
  1251. {
  1252. if (FD >= 0)
  1253. {
  1254. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1255. // but it crashes code guard
  1256. _close(FD);
  1257. Handle.Dismiss();
  1258. }
  1259. }
  1260. }
  1261. //---------------------------------------------------------------------------
  1262. void __fastcall TWebDAVFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1263. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1264. int Params, TFileOperationProgressType * OperationProgress,
  1265. TOnceDoneOperation & OnceDoneOperation)
  1266. {
  1267. Params &= ~cpAppend;
  1268. FTerminal->DoCopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfNone, OnceDoneOperation);
  1269. }
  1270. //---------------------------------------------------------------------------
  1271. void TWebDAVFileSystem::NeonCreateRequest(
  1272. ne_request * Request, void * UserData, const char * /*Method*/, const char * /*Uri*/)
  1273. {
  1274. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1275. ne_set_request_private(Request, SESSION_FS_KEY, FileSystem);
  1276. ne_add_response_body_reader(Request, NeonBodyAccepter, NeonBodyReader, Request);
  1277. FileSystem->FNtlmAuthenticationFailed = false;
  1278. }
  1279. //---------------------------------------------------------------------------
  1280. void TWebDAVFileSystem::NeonPreSend(
  1281. ne_request * Request, void * UserData, ne_buffer * Header)
  1282. {
  1283. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1284. FileSystem->FAuthorizationProtocol = L"";
  1285. UnicodeString HeaderBuf(StrFromNeon(AnsiString(Header->data, Header->used)));
  1286. const UnicodeString AuthorizationHeaderName(L"Authorization:");
  1287. int P = HeaderBuf.Pos(AuthorizationHeaderName);
  1288. if (P > 0)
  1289. {
  1290. P += AuthorizationHeaderName.Length();
  1291. int P2 = PosEx(L"\n", HeaderBuf, P);
  1292. if (DebugAlwaysTrue(P2 > 0))
  1293. {
  1294. UnicodeString AuthorizationHeader = HeaderBuf.SubString(P, P2 - P).Trim();
  1295. FileSystem->FAuthorizationProtocol = CutToChar(AuthorizationHeader, L' ', false);
  1296. FileSystem->FLastAuthorizationProtocol = FileSystem->FAuthorizationProtocol;
  1297. }
  1298. }
  1299. if (FileSystem->FDownloading)
  1300. {
  1301. // Needed by IIS server to make it download source code, not code output,
  1302. // and mainly to even allow downloading file with unregistered extensions.
  1303. // Without it files like .001 return 404 (Not found) HTTP code.
  1304. // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wdv/e37a9543-9290-4843-8c04-66457c60fa0a
  1305. // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wdvse/501879f9-3875-4d7a-ab88-3cecab440034
  1306. // http://lists.manyfish.co.uk/pipermail/neon/2012-April/000582.html
  1307. // It's also supported by Oracle server:
  1308. // https://docs.oracle.com/cd/E19146-01/821-1828/gczya/index.html
  1309. // We do not know yet of any server that fails when the header is used,
  1310. // so it's added unconditionally.
  1311. ne_buffer_zappend(Header, "Translate: f\r\n");
  1312. }
  1313. const UnicodeString ContentTypeHeaderPrefix(L"Content-Type: ");
  1314. if (FileSystem->FTerminal->Log->Logging)
  1315. {
  1316. const char * Buffer;
  1317. size_t Size;
  1318. if (ne_get_request_body_buffer(Request, &Buffer, &Size))
  1319. {
  1320. // all neon request types that use ne_add_request_header
  1321. // use XML content-type, so it's text-based
  1322. DebugAssert(ContainsStr(HeaderBuf, ContentTypeHeaderPrefix + NE_XML_MEDIA_TYPE));
  1323. FileSystem->FTerminal->Log->Add(llInput, UnicodeString(UTF8String(Buffer, Size)));
  1324. }
  1325. }
  1326. if (FileSystem->FUploading)
  1327. {
  1328. ne_set_request_body_provider_pre(Request,
  1329. FileSystem->NeonUploadBodyProvider, FileSystem);
  1330. if (!FileSystem->FUploadMimeType.IsEmpty())
  1331. {
  1332. UnicodeString ContentTypeHeader = ContentTypeHeaderPrefix + FileSystem->FUploadMimeType + L"\r\n";
  1333. ne_buffer_zappend(Header, AnsiString(ContentTypeHeader).c_str());
  1334. }
  1335. }
  1336. FileSystem->FResponse = L"";
  1337. }
  1338. //---------------------------------------------------------------------------
  1339. int TWebDAVFileSystem::NeonPostSend(ne_request * /*Req*/, void * UserData,
  1340. const ne_status * /*Status*/)
  1341. {
  1342. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1343. if (!FileSystem->FResponse.IsEmpty())
  1344. {
  1345. FileSystem->FTerminal->Log->Add(llOutput, FileSystem->FResponse);
  1346. }
  1347. return NE_OK;
  1348. }
  1349. //---------------------------------------------------------------------------
  1350. bool __fastcall TWebDAVFileSystem::IsNtlmAuthentication()
  1351. {
  1352. return
  1353. SameText(FAuthorizationProtocol, L"NTLM") ||
  1354. SameText(FAuthorizationProtocol, L"Negotiate");
  1355. }
  1356. //---------------------------------------------------------------------------
  1357. void __fastcall TWebDAVFileSystem::HttpAuthenticationFailed()
  1358. {
  1359. // NTLM/GSSAPI failed
  1360. if (IsNtlmAuthentication())
  1361. {
  1362. if (FNtlmAuthenticationFailed)
  1363. {
  1364. // Next time do not try Negotiate (NTLM/GSSAPI),
  1365. // otherwise we end up in an endless loop.
  1366. // If the server returns all other challenges in the response, removing the Negotiate
  1367. // protocol will itself ensure that other protocols are tried (we haven't seen this behaviour).
  1368. // IIS will return only Negotiate response if the request was Negotiate, so there's no fallback.
  1369. // We have to retry with a fresh request. That's what FAuthenticationRetry does.
  1370. FTerminal->LogEvent(FORMAT(L"%s challenge failed, will try different challenge", (FAuthorizationProtocol)));
  1371. ne_remove_server_auth(FNeonSession);
  1372. NeonAddAuthentiation(false);
  1373. FAuthenticationRetry = true;
  1374. }
  1375. else
  1376. {
  1377. // The first 401 is expected, the server is using it to send WWW-Authenticate header with data.
  1378. FNtlmAuthenticationFailed = true;
  1379. }
  1380. }
  1381. }
  1382. //---------------------------------------------------------------------------
  1383. void TWebDAVFileSystem::NeonPostHeaders(ne_request * /*Req*/, void * UserData, const ne_status * Status)
  1384. {
  1385. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1386. if (Status->code == HttpUnauthorized)
  1387. {
  1388. FileSystem->HttpAuthenticationFailed();
  1389. }
  1390. }
  1391. //---------------------------------------------------------------------------
  1392. ssize_t TWebDAVFileSystem::NeonUploadBodyProvider(void * UserData, char * /*Buffer*/, size_t /*BufLen*/)
  1393. {
  1394. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1395. ssize_t Result;
  1396. if (FileSystem->CancelTransfer())
  1397. {
  1398. Result = -1;
  1399. }
  1400. else
  1401. {
  1402. Result = 1;
  1403. }
  1404. return Result;
  1405. }
  1406. //---------------------------------------------------------------------------
  1407. static void __fastcall AddHeaderValueToList(UnicodeString & List, ne_request * Request, const char * Name)
  1408. {
  1409. const char * Value = ne_get_response_header(Request, Name);
  1410. if (Value != NULL)
  1411. {
  1412. AddToList(List, StrFromNeon(Value), L"; ");
  1413. }
  1414. }
  1415. //---------------------------------------------------------------------------
  1416. int TWebDAVFileSystem::NeonBodyAccepter(void * UserData, ne_request * Request, const ne_status * Status)
  1417. {
  1418. DebugAssert(UserData == Request);
  1419. TWebDAVFileSystem * FileSystem =
  1420. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1421. bool AuthenticationFailureCode = (Status->code == HttpUnauthorized);
  1422. bool PasswordAuthenticationFailed = AuthenticationFailureCode && FileSystem->FAuthenticationRequested;
  1423. bool AuthenticationFailed = PasswordAuthenticationFailed || (AuthenticationFailureCode && FileSystem->IsNtlmAuthentication());
  1424. bool AuthenticationNeeded = AuthenticationFailureCode && !AuthenticationFailed;
  1425. if (FileSystem->FInitialHandshake)
  1426. {
  1427. UnicodeString Line;
  1428. if (AuthenticationNeeded)
  1429. {
  1430. Line = LoadStr(STATUS_AUTHENTICATE);
  1431. }
  1432. else if (AuthenticationFailed)
  1433. {
  1434. Line = LoadStr(FTP_ACCESS_DENIED);
  1435. }
  1436. else if (Status->klass == 2)
  1437. {
  1438. Line = LoadStr(STATUS_AUTHENTICATED);
  1439. }
  1440. if (!Line.IsEmpty())
  1441. {
  1442. FileSystem->FTerminal->Information(Line, true);
  1443. }
  1444. UnicodeString RemoteSystem;
  1445. // Used by IT Hit WebDAV Server:
  1446. // Server: Microsoft-HTTPAPI/1.0
  1447. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1448. AddHeaderValueToList(RemoteSystem, Request, "X-Engine");
  1449. // Used by OpenDrive:
  1450. // Server: Apache/2.2.17 (Fedora)
  1451. // X-Powered-By: PHP/5.5.7
  1452. // X-DAV-Powered-By: OpenDrive
  1453. AddHeaderValueToList(RemoteSystem, Request, "X-DAV-Powered-By");
  1454. // Used by IIS:
  1455. // Server: Microsoft-IIS/8.5
  1456. AddHeaderValueToList(RemoteSystem, Request, "Server");
  1457. // Not really useful.
  1458. // Can be e.g. "PleskLin"
  1459. AddHeaderValueToList(RemoteSystem, Request, "X-Powered-By");
  1460. FileSystem->FFileSystemInfo.RemoteSystem = RemoteSystem;
  1461. }
  1462. // When we explicitly fail authentication of request
  1463. // with FIgnoreAuthenticationFailure flag (after it failed with password),
  1464. // neon resets its internal password store and tries the next request
  1465. // without calling our authentication hook first
  1466. // (note AuthenticationFailed vs. AuthenticationNeeded)
  1467. // what likely fails, but we do not want to reset out password
  1468. // (as it was not even tried yet for this request).
  1469. if (PasswordAuthenticationFailed)
  1470. {
  1471. if (FileSystem->FIgnoreAuthenticationFailure == iafNo)
  1472. {
  1473. FileSystem->FPassword = RawByteString();
  1474. }
  1475. else
  1476. {
  1477. FileSystem->FIgnoreAuthenticationFailure = iafPasswordFailed;
  1478. }
  1479. }
  1480. return ne_accept_2xx(UserData, Request, Status);
  1481. }
  1482. //---------------------------------------------------------------------------
  1483. bool __fastcall TWebDAVFileSystem::CancelTransfer()
  1484. {
  1485. bool Result = false;
  1486. if ((FUploading || FDownloading) &&
  1487. (FTerminal->OperationProgress != NULL) &&
  1488. (FTerminal->OperationProgress->Cancel != csContinue))
  1489. {
  1490. if (FTerminal->OperationProgress->ClearCancelFile())
  1491. {
  1492. FSkipped = true;
  1493. }
  1494. else
  1495. {
  1496. FCancelled = true;
  1497. }
  1498. Result = true;
  1499. }
  1500. return Result;
  1501. }
  1502. //---------------------------------------------------------------------------
  1503. int TWebDAVFileSystem::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  1504. {
  1505. ne_request * Request = static_cast<ne_request *>(UserData);
  1506. TWebDAVFileSystem * FileSystem =
  1507. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1508. if (FileSystem->FTerminal->Log->Logging)
  1509. {
  1510. ne_content_type ContentType;
  1511. if (ne_get_content_type(Request, &ContentType) == 0)
  1512. {
  1513. // The main point of the content-type check was to exclude
  1514. // GET responses (with file contents).
  1515. // But this won't work when downloading text files that have text
  1516. // content type on their own, hence the additional not-downloading test.
  1517. if (!FileSystem->FDownloading &&
  1518. ((ne_strcasecmp(ContentType.type, "text") == 0) ||
  1519. media_type_is_xml(&ContentType)))
  1520. {
  1521. UnicodeString Content = UnicodeString(UTF8String(Buf, Len)).Trim();
  1522. FileSystem->FResponse += Content;
  1523. }
  1524. ne_free(ContentType.value);
  1525. }
  1526. }
  1527. int Result = FileSystem->CancelTransfer() ? 1 : 0;
  1528. return Result;
  1529. }
  1530. //---------------------------------------------------------------------------
  1531. void __fastcall TWebDAVFileSystem::Sink(
  1532. const UnicodeString & FileName, const TRemoteFile * File,
  1533. const UnicodeString & TargetDir, UnicodeString & DestFileName, int Attrs,
  1534. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  1535. unsigned int /*Flags*/, TDownloadSessionAction & Action)
  1536. {
  1537. UnicodeString DestFullName = TargetDir + DestFileName;
  1538. if (FileExists(ApiPath(DestFullName)))
  1539. {
  1540. __int64 Size;
  1541. __int64 MTime;
  1542. FTerminal->OpenLocalFile(DestFullName, GENERIC_READ, NULL, NULL, NULL, &MTime, NULL, &Size);
  1543. TOverwriteFileParams FileParams;
  1544. FileParams.SourceSize = File->Size;
  1545. FileParams.SourceTimestamp = File->Modification;
  1546. FileParams.DestSize = Size;
  1547. FileParams.DestTimestamp = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  1548. ConfirmOverwrite(FileName, DestFileName, OperationProgress, &FileParams, CopyParam, Params);
  1549. }
  1550. UnicodeString ExpandedDestFullName = ExpandUNCFileName(DestFullName);
  1551. Action.Destination(ExpandedDestFullName);
  1552. FILE_OPERATION_LOOP_BEGIN
  1553. {
  1554. HANDLE LocalHandle;
  1555. if (!FTerminal->CreateLocalFile(DestFullName, OperationProgress, &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  1556. {
  1557. throw ESkipFile();
  1558. }
  1559. bool DeleteLocalFile = true;
  1560. int FD = -1;
  1561. try
  1562. {
  1563. FD = _open_osfhandle((intptr_t)LocalHandle, O_BINARY);
  1564. if (FD < 0)
  1565. {
  1566. throw ESkipFile();
  1567. }
  1568. TAutoFlag DownloadingFlag(FDownloading);
  1569. ClearNeonError();
  1570. CheckStatus(ne_get(FNeonSession, PathToNeon(FileName), FD));
  1571. DeleteLocalFile = false;
  1572. if (CopyParam->PreserveTime)
  1573. {
  1574. FTerminal->UpdateTargetTime(LocalHandle, File->Modification, FTerminal->SessionData->DSTMode);
  1575. }
  1576. }
  1577. __finally
  1578. {
  1579. if (FD >= 0)
  1580. {
  1581. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1582. // but it crashes code guard
  1583. _close(FD);
  1584. }
  1585. else
  1586. {
  1587. CloseHandle(LocalHandle);
  1588. }
  1589. if (DeleteLocalFile)
  1590. {
  1591. FILE_OPERATION_LOOP_BEGIN
  1592. {
  1593. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestFullName)));
  1594. }
  1595. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestFullName)));
  1596. }
  1597. }
  1598. }
  1599. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1600. FTerminal->UpdateTargetAttrs(DestFullName, File, CopyParam, Attrs);
  1601. }
  1602. //---------------------------------------------------------------------------
  1603. // Similar to TS3FileSystem::VerifyCertificate
  1604. bool TWebDAVFileSystem::VerifyCertificate(TNeonCertificateData Data, bool Aux)
  1605. {
  1606. FSessionInfo.CertificateFingerprintSHA1 = Data.FingerprintSHA1;
  1607. FSessionInfo.CertificateFingerprintSHA256 = Data.FingerprintSHA256;
  1608. bool Result;
  1609. if (FTerminal->SessionData->FingerprintScan)
  1610. {
  1611. Result = false;
  1612. }
  1613. else
  1614. {
  1615. FTerminal->LogEvent(0, CertificateVerificationMessage(Data));
  1616. UnicodeString SiteKey = TSessionData::FormatSiteKey(FHostName, FPortNumber);
  1617. Result =
  1618. FTerminal->VerifyCertificate(
  1619. HttpsCertificateStorageKey, SiteKey, Data.FingerprintSHA1, Data.FingerprintSHA256, Data.Subject, Data.Failures);
  1620. if (Result)
  1621. {
  1622. FSessionInfo.CertificateVerifiedManually = true;
  1623. }
  1624. else
  1625. {
  1626. UnicodeString Message;
  1627. Result = NeonWindowsValidateCertificateWithMessage(Data, Message);
  1628. FTerminal->LogEvent(0, Message);
  1629. }
  1630. FSessionInfo.Certificate = CertificateSummary(Data, FHostName);
  1631. if (!Result)
  1632. {
  1633. if (FTerminal->ConfirmCertificate(FSessionInfo, Data.Failures, HttpsCertificateStorageKey, !Aux))
  1634. {
  1635. Result = true;
  1636. FSessionInfo.CertificateVerifiedManually = true;
  1637. }
  1638. }
  1639. if (Result && !Aux)
  1640. {
  1641. CollectTLSSessionInfo();
  1642. }
  1643. }
  1644. return Result;
  1645. }
  1646. //------------------------------------------------------------------------------
  1647. void __fastcall TWebDAVFileSystem::CollectTLSSessionInfo()
  1648. {
  1649. // See also TFTPFileSystem::Open().
  1650. // Have to cache the value as the connection (the neon HTTP session, not "our" session)
  1651. // can be closed at the time we need it in CollectUsage().
  1652. UnicodeString Message = NeonTlsSessionInfo(FNeonSession, FSessionInfo, FTlsVersionStr);
  1653. FTerminal->LogEvent(0, Message);
  1654. }
  1655. //------------------------------------------------------------------------------
  1656. // A neon-session callback to validate the SSL certificate when the CA
  1657. // is unknown (e.g. a self-signed cert), or there are other SSL
  1658. // certificate problems.
  1659. int TWebDAVFileSystem::DoNeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate, bool Aux)
  1660. {
  1661. TNeonCertificateData Data;
  1662. RetrieveNeonCertificateData(Failures, Certificate, Data);
  1663. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1664. return FileSystem->VerifyCertificate(Data, Aux) ? NE_OK : NE_ERROR;
  1665. }
  1666. //------------------------------------------------------------------------------
  1667. int TWebDAVFileSystem::NeonServerSSLCallbackMain(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  1668. {
  1669. return DoNeonServerSSLCallback(UserData, Failures, Certificate, false);
  1670. }
  1671. //------------------------------------------------------------------------------
  1672. int TWebDAVFileSystem::NeonServerSSLCallbackAux(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  1673. {
  1674. return DoNeonServerSSLCallback(UserData, Failures, Certificate, true);
  1675. }
  1676. //------------------------------------------------------------------------------
  1677. void TWebDAVFileSystem::NeonProvideClientCert(void * UserData, ne_session * Sess,
  1678. const ne_ssl_dname * const * /*DNames*/, int /*DNCount*/)
  1679. {
  1680. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1681. FileSystem->FTerminal->LogEvent(LoadStr(NEED_CLIENT_CERTIFICATE));
  1682. X509 * Certificate;
  1683. EVP_PKEY * PrivateKey;
  1684. if (FileSystem->FTerminal->LoadTlsCertificate(Certificate, PrivateKey))
  1685. {
  1686. ne_ssl_client_cert * NeonCertificate = ne_ssl_clicert_create(Certificate, PrivateKey);
  1687. ne_ssl_set_clicert(Sess, NeonCertificate);
  1688. ne_ssl_clicert_free(NeonCertificate);
  1689. }
  1690. }
  1691. //------------------------------------------------------------------------------
  1692. int TWebDAVFileSystem::NeonRequestAuth(
  1693. void * UserData, const char * Realm, int Attempt, char * UserName, char * Password)
  1694. {
  1695. DebugUsedParam(Realm);
  1696. DebugUsedParam(Attempt);
  1697. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1698. TTerminal * Terminal = FileSystem->FTerminal;
  1699. TSessionData * SessionData = Terminal->SessionData;
  1700. bool Result = true;
  1701. // will ask for username only once
  1702. if (FileSystem->FUserName.IsEmpty())
  1703. {
  1704. if (!SessionData->UserName.IsEmpty())
  1705. {
  1706. FileSystem->FUserName = SessionData->UserNameExpanded;
  1707. }
  1708. else
  1709. {
  1710. Terminal->LogEvent(L"Username prompt");
  1711. if (!Terminal->PromptUser(SessionData, pkUserName, LoadStr(USERNAME_TITLE), L"",
  1712. LoadStr(USERNAME_PROMPT2), true, NE_ABUFSIZ, FileSystem->FUserName))
  1713. {
  1714. // note that we never get here actually
  1715. Result = false;
  1716. }
  1717. }
  1718. }
  1719. UnicodeString APassword;
  1720. if (Result)
  1721. {
  1722. // Some servers (Gallery2 on discontinued g2.pixi.me)
  1723. // return authentication error (401) on PROPFIND request for
  1724. // non-existing files.
  1725. // When we already tried password before, do not try anymore.
  1726. // When we did not try password before (possible only when
  1727. // server does not require authentication for any previous request,
  1728. // such as when read access is not authenticated), try it now,
  1729. // but use special flag for the try, because when it fails
  1730. // we still want to try password for future requests (such as PUT).
  1731. if (!FileSystem->FPassword.IsEmpty())
  1732. {
  1733. if (FileSystem->FIgnoreAuthenticationFailure == iafPasswordFailed)
  1734. {
  1735. // Fail PROPFIND /nonexising request...
  1736. Result = false;
  1737. }
  1738. else
  1739. {
  1740. APassword = Terminal->DecryptPassword(FileSystem->FPassword);
  1741. }
  1742. }
  1743. else
  1744. {
  1745. if (!SessionData->Password.IsEmpty() && !FileSystem->FStoredPasswordTried)
  1746. {
  1747. APassword = NormalizeString(SessionData->Password);
  1748. FileSystem->FStoredPasswordTried = true;
  1749. }
  1750. else
  1751. {
  1752. // Asking for password (or using configured password) the first time,
  1753. // and asking for password.
  1754. // Note that we never get false here actually
  1755. Terminal->LogEvent(L"Password prompt");
  1756. Result =
  1757. Terminal->PromptUser(
  1758. SessionData, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  1759. LoadStr(PASSWORD_PROMPT), false, NE_ABUFSIZ, APassword);
  1760. }
  1761. if (Result)
  1762. {
  1763. // While neon remembers the password on its own,
  1764. // we need to keep a copy in case neon store gets reset by
  1765. // 401 response to PROPFIND /nonexisting on G2, see above.
  1766. // Possibly we can do this for G2 servers only.
  1767. FileSystem->FPassword = Terminal->EncryptPassword(APassword);
  1768. }
  1769. }
  1770. }
  1771. if (Result)
  1772. {
  1773. strncpy(UserName, StrToNeon(FileSystem->FUserName), NE_ABUFSIZ);
  1774. strncpy(Password, StrToNeon(APassword), NE_ABUFSIZ);
  1775. }
  1776. FileSystem->FAuthenticationRequested = true;
  1777. return Result ? 0 : -1;
  1778. }
  1779. //------------------------------------------------------------------------------
  1780. void TWebDAVFileSystem::NeonNotifier(void * UserData, ne_session_status Status, const ne_session_status_info * StatusInfo)
  1781. {
  1782. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1783. TFileOperationProgressType * OperationProgress = FileSystem->FTerminal->OperationProgress;
  1784. // We particularly have to filter out response to "put" request,
  1785. // handling that would reset the upload progress back to low number (response is small).
  1786. if (((FileSystem->FUploading && (Status == ne_status_sending)) ||
  1787. (FileSystem->FDownloading && (Status == ne_status_recving))) &&
  1788. DebugAlwaysTrue(OperationProgress != NULL))
  1789. {
  1790. __int64 Progress = StatusInfo->sr.progress;
  1791. __int64 Diff = Progress - OperationProgress->TransferredSize;
  1792. if (Diff > 0)
  1793. {
  1794. OperationProgress->ThrottleToCPSLimit(static_cast<unsigned long>(Diff));
  1795. }
  1796. __int64 Total = StatusInfo->sr.total;
  1797. // Total size unknown
  1798. if (Total < 0)
  1799. {
  1800. if (Diff >= 0)
  1801. {
  1802. OperationProgress->AddTransferred(Diff);
  1803. }
  1804. else
  1805. {
  1806. // Session total has been reset. A new stream started
  1807. OperationProgress->AddTransferred(Progress);
  1808. }
  1809. }
  1810. else
  1811. {
  1812. OperationProgress->SetTransferSize(Total);
  1813. OperationProgress->AddTransferred(Diff);
  1814. }
  1815. }
  1816. }
  1817. //------------------------------------------------------------------------------
  1818. void TWebDAVFileSystem::InitSslSession(ssl_st * Ssl, ne_session * /*Session*/)
  1819. {
  1820. SetupSsl(Ssl, FTerminal->SessionData->MinTlsVersion, FTerminal->SessionData->MaxTlsVersion);
  1821. }
  1822. //---------------------------------------------------------------------------
  1823. void __fastcall TWebDAVFileSystem::GetSupportedChecksumAlgs(TStrings * /*Algs*/)
  1824. {
  1825. // NOOP
  1826. }
  1827. //---------------------------------------------------------------------------
  1828. void __fastcall TWebDAVFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * File)
  1829. {
  1830. ClearNeonError();
  1831. struct ne_lock * Lock = ne_lock_create();
  1832. try
  1833. {
  1834. Lock->uri.path = ne_strdup(PathToNeon(FilePath(File)));
  1835. Lock->depth = NE_DEPTH_INFINITE;
  1836. Lock->timeout = NE_TIMEOUT_INFINITE;
  1837. Lock->owner = ne_strdup(StrToNeon(FTerminal->UserName));
  1838. CheckStatus(ne_lock(FNeonSession, Lock));
  1839. {
  1840. TGuard Guard(FNeonLockStoreSection);
  1841. RequireLockStore();
  1842. ne_lockstore_add(FNeonLockStore, Lock);
  1843. }
  1844. // ownership passed
  1845. Lock = NULL;
  1846. }
  1847. __finally
  1848. {
  1849. if (Lock != NULL)
  1850. {
  1851. ne_lock_destroy(Lock);
  1852. }
  1853. }
  1854. }
  1855. //---------------------------------------------------------------------------
  1856. void __fastcall TWebDAVFileSystem::RequireLockStore()
  1857. {
  1858. // Create store only when needed,
  1859. // to limit the use of cross-thread code in UpdateFromMain
  1860. if (FNeonLockStore == NULL)
  1861. {
  1862. FNeonLockStore = ne_lockstore_create();
  1863. ne_lockstore_register(FNeonLockStore, FNeonSession);
  1864. }
  1865. }
  1866. //---------------------------------------------------------------------------
  1867. void TWebDAVFileSystem::LockResult(void * UserData, const struct ne_lock * Lock,
  1868. const ne_uri * /*Uri*/, const ne_status * /*Status*/)
  1869. {
  1870. // Is NULL on failure (Status is not NULL then)
  1871. if (Lock != NULL)
  1872. {
  1873. RawByteString & LockToken = *static_cast<RawByteString *>(UserData);
  1874. LockToken = Lock->token;
  1875. }
  1876. }
  1877. //---------------------------------------------------------------------------
  1878. struct ne_lock * __fastcall TWebDAVFileSystem::FindLock(const RawByteString & Path)
  1879. {
  1880. ne_uri Uri = {0};
  1881. Uri.path = Path.c_str();
  1882. return ne_lockstore_findbyuri(FNeonLockStore, &Uri);
  1883. }
  1884. //---------------------------------------------------------------------------
  1885. void __fastcall TWebDAVFileSystem::DiscardLock(const RawByteString & Path)
  1886. {
  1887. TGuard Guard(FNeonLockStoreSection);
  1888. if (FNeonLockStore != NULL)
  1889. {
  1890. struct ne_lock * Lock = FindLock(Path);
  1891. if (Lock != NULL)
  1892. {
  1893. ne_lockstore_remove(FNeonLockStore, Lock);
  1894. }
  1895. }
  1896. }
  1897. //---------------------------------------------------------------------------
  1898. void __fastcall TWebDAVFileSystem::UnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  1899. {
  1900. ClearNeonError();
  1901. struct ne_lock * Lock = ne_lock_create();
  1902. try
  1903. {
  1904. RawByteString Path = PathToNeon(FilePath(File));
  1905. RawByteString LockToken;
  1906. struct ne_lock * Lock = NULL;
  1907. {
  1908. TGuard Guard(FNeonLockStoreSection);
  1909. if (FNeonLockStore != NULL)
  1910. {
  1911. Lock = FindLock(Path);
  1912. }
  1913. }
  1914. // we are not aware of the file being locked,
  1915. // though it can be locked from another (previous and already closed)
  1916. // session, so query the server.
  1917. if (Lock == NULL)
  1918. {
  1919. CheckStatus(ne_lock_discover(FNeonSession, Path.c_str(), LockResult, &LockToken));
  1920. }
  1921. if ((Lock == NULL) && (LockToken.IsEmpty()))
  1922. {
  1923. throw Exception(FMTLOAD(NOT_LOCKED, (FileName)));
  1924. }
  1925. else
  1926. {
  1927. struct ne_lock * Unlock;
  1928. if (Lock == NULL)
  1929. {
  1930. DebugAssert(!LockToken.IsEmpty());
  1931. Unlock = ne_lock_create();
  1932. Unlock->uri.path = ne_strdup(Path.c_str());
  1933. Unlock->token = ne_strdup(LockToken.c_str());
  1934. }
  1935. else
  1936. {
  1937. Unlock = Lock;
  1938. }
  1939. CheckStatus(ne_unlock(FNeonSession, Unlock));
  1940. DiscardLock(Path);
  1941. }
  1942. }
  1943. __finally
  1944. {
  1945. ne_lock_destroy(Lock);
  1946. }
  1947. }
  1948. //---------------------------------------------------------------------------
  1949. void __fastcall TWebDAVFileSystem::UpdateFromMain(TCustomFileSystem * AMainFileSystem)
  1950. {
  1951. TWebDAVFileSystem * MainFileSystem = dynamic_cast<TWebDAVFileSystem *>(AMainFileSystem);
  1952. if (DebugAlwaysTrue(MainFileSystem != NULL))
  1953. {
  1954. TGuard Guard(FNeonLockStoreSection);
  1955. TGuard MainGuard(MainFileSystem->FNeonLockStoreSection);
  1956. if (FNeonLockStore != NULL)
  1957. {
  1958. struct ne_lock * Lock;
  1959. while ((Lock = ne_lockstore_first(FNeonLockStore)) != NULL)
  1960. {
  1961. ne_lockstore_remove(FNeonLockStore, Lock);
  1962. }
  1963. }
  1964. if (MainFileSystem->FNeonLockStore != NULL)
  1965. {
  1966. RequireLockStore();
  1967. struct ne_lock * Lock = ne_lockstore_first(MainFileSystem->FNeonLockStore);
  1968. while (Lock != NULL)
  1969. {
  1970. ne_lockstore_add(FNeonLockStore, ne_lock_copy(Lock));
  1971. Lock = ne_lockstore_next(MainFileSystem->FNeonLockStore);
  1972. }
  1973. }
  1974. }
  1975. }
  1976. //------------------------------------------------------------------------------
  1977. void __fastcall TWebDAVFileSystem::ClearCaches()
  1978. {
  1979. // noop
  1980. }
  1981. //---------------------------------------------------------------------------