WebDAVFileSystem.cpp 76 KB

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