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. ne_add_server_auth(SessionContext->NeonSession, NeonAuthTypes, NeonRequestAuth, SessionContext);
  362. }
  363. //---------------------------------------------------------------------------
  364. UnicodeString __fastcall TWebDAVFileSystem::GetRedirectUrl()
  365. {
  366. UnicodeString Result = GetNeonRedirectUrl(FSessionContext->NeonSession);
  367. FTerminal->LogEvent(FORMAT(L"Redirected to \"%s\".", (Result)));
  368. return Result;
  369. }
  370. //---------------------------------------------------------------------------
  371. void TWebDAVFileSystem::ExchangeCapabilities(const char * Path, UnicodeString & CorrectedUrl)
  372. {
  373. ClearNeonError();
  374. int NeonStatus;
  375. FAuthenticationRetry = false;
  376. do
  377. {
  378. NeonStatus = ne_options2(FSessionContext->NeonSession, Path, &FCapabilities);
  379. }
  380. while ((NeonStatus == NE_AUTH) && FAuthenticationRetry);
  381. if (NeonStatus == NE_REDIRECT)
  382. {
  383. CorrectedUrl = GetRedirectUrl();
  384. }
  385. else if (NeonStatus == NE_OK)
  386. {
  387. if (FCapabilities > 0)
  388. {
  389. UnicodeString Str;
  390. unsigned int Capability = 0x01;
  391. unsigned int Capabilities = FCapabilities;
  392. while (Capabilities > 0)
  393. {
  394. if (FLAGSET(Capabilities, Capability))
  395. {
  396. AddToList(Str, StrFromNeon(ne_capability_name(Capability)), L", ");
  397. Capabilities -= Capability;
  398. }
  399. Capability <<= 1;
  400. }
  401. FTerminal->LogEvent(FORMAT(L"Server capabilities: %s", (Str)));
  402. FFileSystemInfo.AdditionalInfo +=
  403. LoadStr(WEBDAV_EXTENSION_INFO) + sLineBreak +
  404. L" " + Str + sLineBreak;
  405. }
  406. }
  407. else
  408. {
  409. CheckStatus(NeonStatus);
  410. }
  411. FTerminal->SaveCapabilities(FFileSystemInfo);
  412. }
  413. //---------------------------------------------------------------------------
  414. TWebDAVFileSystem::TSessionContext::~TSessionContext()
  415. {
  416. if (NeonSession != NULL)
  417. {
  418. DestroyNeonSession(NeonSession);
  419. }
  420. }
  421. //---------------------------------------------------------------------------
  422. void __fastcall TWebDAVFileSystem::CloseNeonSession()
  423. {
  424. if (FSessionContext != NULL)
  425. {
  426. delete FSessionContext;
  427. FSessionContext = NULL;
  428. }
  429. }
  430. //---------------------------------------------------------------------------
  431. void __fastcall TWebDAVFileSystem::Close()
  432. {
  433. DebugAssert(FActive);
  434. CloseNeonSession();
  435. FTerminal->Closed();
  436. FActive = false;
  437. UnregisterFromNeonDebug(FTerminal);
  438. }
  439. //---------------------------------------------------------------------------
  440. bool __fastcall TWebDAVFileSystem::GetActive()
  441. {
  442. return FActive;
  443. }
  444. //---------------------------------------------------------------------------
  445. void __fastcall TWebDAVFileSystem::CollectUsage()
  446. {
  447. if (!FTlsVersionStr.IsEmpty())
  448. {
  449. FTerminal->CollectTlsUsage(FTlsVersionStr);
  450. }
  451. if (!FTerminal->SessionData->TlsCertificateFile.IsEmpty())
  452. {
  453. Configuration->Usage->Inc(L"OpenedSessionsWebDAVSCertificate");
  454. }
  455. // The Authorization header for passport method is included only in the first request,
  456. // so we have to use FLastAuthorizationProtocol
  457. if (SameText(FLastAuthorizationProtocol, L"Passport1.4"))
  458. {
  459. Configuration->Usage->Inc(L"OpenedSessionsWebDAVSPassport");
  460. }
  461. else if (SameText(FLastAuthorizationProtocol, L"Basic"))
  462. {
  463. Configuration->Usage->Inc(L"OpenedSessionsWebDAVAuthBasic");
  464. }
  465. UnicodeString RemoteSystem = FFileSystemInfo.RemoteSystem;
  466. if (ContainsText(RemoteSystem, L"Microsoft-IIS"))
  467. {
  468. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVIIS");
  469. }
  470. else if (ContainsText(RemoteSystem, L"IT Hit WebDAV Server"))
  471. {
  472. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVITHit");
  473. }
  474. // e.g. brickftp.com
  475. else if (ContainsText(RemoteSystem, L"nginx"))
  476. {
  477. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVNginx");
  478. }
  479. else
  480. {
  481. // We also know OpenDrive, Yandex, iFiles (iOS), Swapper (iOS), SafeSync
  482. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVOther");
  483. }
  484. }
  485. //---------------------------------------------------------------------------
  486. const TSessionInfo & __fastcall TWebDAVFileSystem::GetSessionInfo()
  487. {
  488. return FSessionInfo;
  489. }
  490. //---------------------------------------------------------------------------
  491. const TFileSystemInfo & __fastcall TWebDAVFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  492. {
  493. return FFileSystemInfo;
  494. }
  495. //---------------------------------------------------------------------------
  496. bool __fastcall TWebDAVFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
  497. {
  498. return false;
  499. }
  500. //---------------------------------------------------------------------------
  501. bool __fastcall TWebDAVFileSystem::GetStoredCredentialsTried()
  502. {
  503. return FStoredPasswordTried;
  504. }
  505. //---------------------------------------------------------------------------
  506. UnicodeString __fastcall TWebDAVFileSystem::GetUserName()
  507. {
  508. return FUserName;
  509. }
  510. //---------------------------------------------------------------------------
  511. void __fastcall TWebDAVFileSystem::Idle()
  512. {
  513. // noop
  514. }
  515. //---------------------------------------------------------------------------
  516. UnicodeString __fastcall TWebDAVFileSystem::AbsolutePath(const UnicodeString Path, bool /*Local*/)
  517. {
  518. bool AddTrailingBackslash;
  519. if (Path == L"/")
  520. {
  521. // does not really matter as path "/" is still "/" when absolute,
  522. // no slash needed
  523. AddTrailingBackslash = FHasTrailingSlash;
  524. }
  525. else
  526. {
  527. AddTrailingBackslash = (Path[Path.Length()] == L'/');
  528. }
  529. UnicodeString Result = ::AbsolutePath(GetCurrentDirectory(), Path);
  530. // We must preserve trailing slash, because particularly for mod_dav,
  531. // it really matters if the slash in there or not
  532. if (AddTrailingBackslash)
  533. {
  534. Result = UnixIncludeTrailingBackslash(Result);
  535. }
  536. return Result;
  537. }
  538. //---------------------------------------------------------------------------
  539. bool __fastcall TWebDAVFileSystem::IsCapable(int Capability) const
  540. {
  541. DebugAssert(FTerminal);
  542. switch (Capability)
  543. {
  544. case fcRename:
  545. case fcRemoteMove:
  546. case fcMoveToQueue:
  547. case fcPreservingTimestampUpload:
  548. case fcCheckingSpaceAvailable:
  549. // Only to make double-click on file edit/open the file,
  550. // instead of trying to open it as directory
  551. case fcResolveSymlink:
  552. case fcSkipTransfer:
  553. case fcParallelTransfers:
  554. case fcRemoteCopy:
  555. case fcMoveOverExistingFile:
  556. return true;
  557. case fcUserGroupListing:
  558. case fcModeChanging:
  559. case fcModeChangingUpload:
  560. case fcAclChangingFiles:
  561. case fcGroupChanging:
  562. case fcOwnerChanging:
  563. case fcAnyCommand:
  564. case fcShellAnyCommand:
  565. case fcHardLink:
  566. case fcSymbolicLink:
  567. case fcTextMode:
  568. case fcNativeTextMode:
  569. case fcNewerOnlyUpload:
  570. case fcTimestampChanging:
  571. case fcLoadingAdditionalProperties:
  572. case fcIgnorePermErrors:
  573. case fcCalculatingChecksum:
  574. case fcSecondaryShell:
  575. case fcGroupOwnerChangingByID:
  576. case fcRemoveCtrlZUpload:
  577. case fcRemoveBOMUpload:
  578. case fcPreservingTimestampDirs:
  579. case fcResumeSupport:
  580. case fcChangePassword:
  581. case fcTransferOut:
  582. case fcTransferIn:
  583. case fcParallelFileTransfers:
  584. return false;
  585. case fcLocking:
  586. return FLAGSET(FCapabilities, NE_CAP_DAV_CLASS2);
  587. default:
  588. DebugFail();
  589. return false;
  590. }
  591. }
  592. //---------------------------------------------------------------------------
  593. UnicodeString __fastcall TWebDAVFileSystem::GetCurrentDirectory()
  594. {
  595. return FCurrentDirectory;
  596. }
  597. //---------------------------------------------------------------------------
  598. void __fastcall TWebDAVFileSystem::DoStartup()
  599. {
  600. FTerminal->SetExceptionOnFail(true);
  601. // retrieve initialize working directory to save it as home directory
  602. ReadCurrentDirectory();
  603. FTerminal->SetExceptionOnFail(false);
  604. }
  605. //---------------------------------------------------------------------------
  606. void __fastcall TWebDAVFileSystem::ClearNeonError()
  607. {
  608. FCancelled = false;
  609. FSkipped = false;
  610. FAuthenticationRequested = false;
  611. ne_set_error(FSessionContext->NeonSession, "");
  612. }
  613. //---------------------------------------------------------------------------
  614. UnicodeString __fastcall TWebDAVFileSystem::GetNeonError()
  615. {
  616. return ::GetNeonError(FSessionContext->NeonSession);
  617. }
  618. //---------------------------------------------------------------------------
  619. void TWebDAVFileSystem::CheckStatus(int NeonStatus)
  620. {
  621. CheckStatus(FSessionContext, NeonStatus);
  622. }
  623. //---------------------------------------------------------------------------
  624. void TWebDAVFileSystem::CheckStatus(TSessionContext * SessionContext, int NeonStatus)
  625. {
  626. if ((NeonStatus == NE_ERROR) && (FCancelled || FSkipped))
  627. {
  628. if (FCancelled)
  629. {
  630. FCancelled = false;
  631. FSkipped = false; // just in case
  632. Abort();
  633. }
  634. else
  635. {
  636. DebugAssert(FSkipped);
  637. FSkipped = false;
  638. throw ESkipFile();
  639. }
  640. }
  641. else
  642. {
  643. CheckNeonStatus(SessionContext->NeonSession, NeonStatus, SessionContext->HostName);
  644. }
  645. }
  646. //---------------------------------------------------------------------------
  647. void __fastcall TWebDAVFileSystem::LookupUsersGroups()
  648. {
  649. DebugFail();
  650. }
  651. //---------------------------------------------------------------------------
  652. void __fastcall TWebDAVFileSystem::ReadCurrentDirectory()
  653. {
  654. if (FCachedDirectoryChange.IsEmpty())
  655. {
  656. FCurrentDirectory = FCurrentDirectory.IsEmpty() ? UnicodeString(L"/") : FCurrentDirectory;
  657. }
  658. else
  659. {
  660. FCurrentDirectory = FCachedDirectoryChange;
  661. FCachedDirectoryChange = L"";
  662. }
  663. }
  664. //---------------------------------------------------------------------------
  665. void __fastcall TWebDAVFileSystem::HomeDirectory()
  666. {
  667. ChangeDirectory(L"/");
  668. }
  669. //---------------------------------------------------------------------------
  670. UnicodeString __fastcall TWebDAVFileSystem::DirectoryPath(UnicodeString Path)
  671. {
  672. if (FHasTrailingSlash)
  673. {
  674. Path = ::UnixIncludeTrailingBackslash(Path);
  675. }
  676. return Path;
  677. }
  678. //---------------------------------------------------------------------------
  679. UnicodeString __fastcall TWebDAVFileSystem::FilePath(const TRemoteFile * File)
  680. {
  681. UnicodeString Result = File->FullFileName;
  682. if (File->IsDirectory)
  683. {
  684. Result = DirectoryPath(Result);
  685. }
  686. return Result;
  687. }
  688. //---------------------------------------------------------------------------
  689. void __fastcall TWebDAVFileSystem::TryOpenDirectory(UnicodeString Directory)
  690. {
  691. Directory = DirectoryPath(Directory);
  692. FTerminal->LogEvent(FORMAT(L"Trying to open directory \"%s\".", (Directory)));
  693. TRemoteFile * File;
  694. ReadFile(Directory, File);
  695. delete File;
  696. }
  697. //---------------------------------------------------------------------------
  698. void __fastcall TWebDAVFileSystem::AnnounceFileListOperation()
  699. {
  700. // noop
  701. }
  702. //---------------------------------------------------------------------------
  703. void __fastcall TWebDAVFileSystem::ChangeDirectory(const UnicodeString ADirectory)
  704. {
  705. UnicodeString Path = AbsolutePath(ADirectory, false);
  706. // to verify existence of directory try to open it
  707. TryOpenDirectory(Path);
  708. // if open dir did not fail, directory exists -> success.
  709. FCachedDirectoryChange = Path;
  710. }
  711. //---------------------------------------------------------------------------
  712. void __fastcall TWebDAVFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  713. {
  714. FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
  715. }
  716. //---------------------------------------------------------------------------
  717. struct TReadFileData
  718. {
  719. TWebDAVFileSystem * FileSystem;
  720. TRemoteFile * File;
  721. TRemoteFileList * FileList;
  722. };
  723. //---------------------------------------------------------------------------
  724. int __fastcall TWebDAVFileSystem::ReadDirectoryInternal(
  725. const UnicodeString & Path, TRemoteFileList * FileList)
  726. {
  727. TReadFileData Data;
  728. Data.FileSystem = this;
  729. Data.File = NULL;
  730. Data.FileList = FileList;
  731. ClearNeonError();
  732. ne_propfind_handler * PropFindHandler = ne_propfind_create(FSessionContext->NeonSession, PathToNeon(Path), NE_DEPTH_ONE);
  733. void * DiscoveryContext = ne_lock_register_discovery(PropFindHandler);
  734. int Result;
  735. try
  736. {
  737. Result = ne_propfind_allprop(PropFindHandler, NeonPropsResult, &Data);
  738. }
  739. __finally
  740. {
  741. ne_lock_discovery_free(DiscoveryContext);
  742. ne_propfind_destroy(PropFindHandler);
  743. }
  744. return Result;
  745. }
  746. //---------------------------------------------------------------------------
  747. bool __fastcall TWebDAVFileSystem::IsValidRedirect(int NeonStatus, UnicodeString & Path)
  748. {
  749. bool Result = (NeonStatus == NE_REDIRECT);
  750. if (Result)
  751. {
  752. // What PathToNeon does
  753. UnicodeString OriginalPath = AbsolutePath(Path, false);
  754. // Handle one-step redirect
  755. // (for more steps we would have to implement loop detection).
  756. // This is mainly to handle "folder" => "folder/" redirects of Apache/mod_dav.
  757. UnicodeString RedirectUrl = GetRedirectUrl();
  758. // We should test if the redirect is not for another server,
  759. // though not sure how to do this reliably (domain aliases, IP vs. domain, etc.)
  760. // If this ever gets implemented, beware of use from Sink(), where we support redirects to another server.
  761. UnicodeString RedirectPath = ParsePathFromUrl(RedirectUrl);
  762. Result =
  763. !RedirectPath.IsEmpty() &&
  764. (RedirectPath != OriginalPath);
  765. if (Result)
  766. {
  767. Path = RedirectPath;
  768. }
  769. }
  770. return Result;
  771. }
  772. //---------------------------------------------------------------------------
  773. void __fastcall TWebDAVFileSystem::ReadDirectory(TRemoteFileList * FileList)
  774. {
  775. UnicodeString Path = DirectoryPath(FileList->Directory);
  776. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  777. int NeonStatus = ReadDirectoryInternal(Path, FileList);
  778. if (IsValidRedirect(NeonStatus, Path))
  779. {
  780. NeonStatus = ReadDirectoryInternal(Path, FileList);
  781. }
  782. CheckStatus(NeonStatus);
  783. }
  784. //---------------------------------------------------------------------------
  785. void __fastcall TWebDAVFileSystem::ReadSymlink(TRemoteFile * /*SymlinkFile*/,
  786. TRemoteFile *& /*File*/)
  787. {
  788. // we never set SymLink flag, so we should never get here
  789. DebugFail();
  790. }
  791. //---------------------------------------------------------------------------
  792. void __fastcall TWebDAVFileSystem::ReadFile(const UnicodeString FileName,
  793. TRemoteFile *& File)
  794. {
  795. CustomReadFile(FileName, File, NULL);
  796. }
  797. //---------------------------------------------------------------------------
  798. void TWebDAVFileSystem::NeonPropsResult(
  799. void * UserData, const ne_uri * Uri, const ne_prop_result_set * Results)
  800. {
  801. UnicodeString Path = PathUnescape(Uri->path);
  802. TReadFileData & Data = *static_cast<TReadFileData *>(UserData);
  803. if (Data.FileList != NULL)
  804. {
  805. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  806. File->Terminal = Data.FileSystem->FTerminal;
  807. Data.FileSystem->ParsePropResultSet(File.get(), Path, Results);
  808. UnicodeString FileListPath = Data.FileSystem->AbsolutePath(Data.FileList->Directory, false);
  809. if (UnixSamePath(File->FullFileName, FileListPath))
  810. {
  811. File->FileName = PARENTDIRECTORY;
  812. File->FullFileName = UnixCombinePaths(Path, PARENTDIRECTORY);
  813. }
  814. Data.FileList->AddFile(File.release());
  815. }
  816. else
  817. {
  818. Data.FileSystem->ParsePropResultSet(Data.File, Path, Results);
  819. }
  820. }
  821. //---------------------------------------------------------------------------
  822. const char * __fastcall TWebDAVFileSystem::GetProp(
  823. const ne_prop_result_set * Results, const char * Name, const char * NameSpace)
  824. {
  825. ne_propname Prop;
  826. Prop.nspace = (NameSpace == NULL) ? DAV_PROP_NAMESPACE : NameSpace;
  827. Prop.name = Name;
  828. return ne_propset_value(Results, &Prop);
  829. }
  830. //---------------------------------------------------------------------------
  831. void __fastcall TWebDAVFileSystem::ParsePropResultSet(TRemoteFile * File,
  832. const UnicodeString & Path, const ne_prop_result_set * Results)
  833. {
  834. File->FullFileName = UnixExcludeTrailingBackslash(Path);
  835. // Some servers do not use DAV:collection tag, but indicate the folder by trailing slash only.
  836. // But not all, for example OneDrive does not (it did in the past).
  837. bool Collection = (File->FullFileName != Path);
  838. File->FileName = UnixExtractFileName(File->FullFileName);
  839. const char * ContentLength = GetProp(Results, PROP_CONTENT_LENGTH);
  840. // some servers, for example iFiles, do not provide "getcontentlength" for folders
  841. if (ContentLength != NULL)
  842. {
  843. File->Size = StrToInt64Def(ContentLength, 0);
  844. }
  845. const char * LastModified = GetProp(Results, PROP_LAST_MODIFIED);
  846. // We've seen a server (t=24891) that does not set "getlastmodified" for the "this" folder entry.
  847. if (LastModified != NULL)
  848. {
  849. char WeekDay[4] = { L'\0' };
  850. int Year = 0;
  851. char MonthStr[4] = { L'\0' };
  852. int Day = 0;
  853. int Hour = 0;
  854. int Min = 0;
  855. int Sec = 0;
  856. #define RFC1123_FORMAT "%3s, %02d %3s %4d %02d:%02d:%02d GMT"
  857. // Keep is sync with S3
  858. int Filled =
  859. sscanf(LastModified, RFC1123_FORMAT, WeekDay, &Day, MonthStr, &Year, &Hour, &Min, &Sec);
  860. // we need at least a complete date
  861. if (Filled >= 4)
  862. {
  863. int Month = ParseShortEngMonthName(MonthStr);
  864. if (Month >= 1)
  865. {
  866. TDateTime Modification =
  867. EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) +
  868. EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0);
  869. File->Modification = ConvertTimestampFromUTC(Modification);
  870. // Should use mfYMDHM or mfMDY when appropriate according to Filled
  871. File->ModificationFmt = mfFull;
  872. }
  873. else
  874. {
  875. File->ModificationFmt = mfNone;
  876. }
  877. }
  878. else
  879. {
  880. File->ModificationFmt = mfNone;
  881. }
  882. }
  883. // optimization
  884. if (!Collection)
  885. {
  886. // See a comment at the Collection declaration.
  887. const char * ResourceType = GetProp(Results, PROP_RESOURCE_TYPE);
  888. if (ResourceType != NULL)
  889. {
  890. // property has XML value
  891. UnicodeString AResourceType = ResourceType;
  892. // this is very poor parsing
  893. if (ContainsText(ResourceType, L"<DAV:collection"))
  894. {
  895. Collection = true;
  896. }
  897. }
  898. }
  899. File->Type = Collection ? FILETYPE_DIRECTORY : FILETYPE_DEFAULT;
  900. // this is MS extension (draft-hopmann-collection-props-00)
  901. const char * IsHidden = GetProp(Results, PROP_HIDDEN);
  902. if (IsHidden != NULL)
  903. {
  904. File->IsHidden = (StrToIntDef(IsHidden, 0) != 0);
  905. }
  906. const char * Owner = GetProp(Results, PROP_OWNER);
  907. if (Owner != NULL)
  908. {
  909. File->Owner.Name = Owner;
  910. }
  911. const char * DisplayName = GetProp(Results, PROP_DISPLAY_NAME);
  912. if (DisplayName != NULL)
  913. {
  914. File->DisplayName = StrFromNeon(DisplayName);
  915. // OneDrive caret escaping (we could do this for all files, but let's limit the scope for now).
  916. // In *file* PROPFIND response, the # (and other symbols like comma or plus) is not escaped at all
  917. // (while in directory listing, they are caret-escaped),
  918. // so if we see one in the display name, take the name from there.
  919. // * and % won't help, as OneDrive seem to have bug with % at the end of the filename,
  920. // and the * (and others) is removed from file names.
  921. // Filenames with commas (,) get as many additional characters at the end of the filename as there are commas.
  922. if (FOneDrive &&
  923. (ContainsText(File->FileName, L"^") || ContainsText(File->FileName, L",") || (wcspbrk(File->DisplayName.c_str(), L"&,+#[]%*") != NULL)))
  924. {
  925. File->FileName = File->DisplayName;
  926. File->FullFileName = UnixCombinePaths(UnixExtractFileDir(File->FullFileName), File->FileName);
  927. }
  928. }
  929. const UnicodeString RightsDelimiter(L", ");
  930. UnicodeString HumanRights;
  931. // Proprietary property of mod_dav
  932. // http://www.webdav.org/mod_dav/#imp
  933. const char * Executable = GetProp(Results, PROP_EXECUTABLE, MODDAV_PROP_NAMESPACE);
  934. if (Executable != NULL)
  935. {
  936. if (strcmp(Executable, "T") == NULL)
  937. {
  938. UnicodeString ExecutableRights;
  939. // The "gear" character is supported since Windows 8
  940. if (IsWin8())
  941. {
  942. ExecutableRights = L"\u2699";
  943. }
  944. else
  945. {
  946. ExecutableRights = LoadStr(EXECUTABLE);
  947. }
  948. AddToList(HumanRights, ExecutableRights, RightsDelimiter);
  949. }
  950. }
  951. struct ne_lock * Lock = static_cast<struct ne_lock *>(ne_propset_private(Results));
  952. if ((Lock != NULL) && (Lock->token != NULL))
  953. {
  954. UnicodeString Owner;
  955. if (Lock->owner != NULL)
  956. {
  957. Owner = StrFromNeon(Lock->owner).Trim();
  958. }
  959. UnicodeString LockRights;
  960. if (IsWin8())
  961. {
  962. // The "lock" character is supported since Windows 8
  963. LockRights = L"\uD83D\uDD12" + Owner;
  964. }
  965. else
  966. {
  967. LockRights = LoadStr(LOCKED);
  968. if (!Owner.IsEmpty())
  969. {
  970. LockRights = FORMAT(L"%s (%s)", (LockRights, Owner));
  971. }
  972. }
  973. AddToList(HumanRights, LockRights, RightsDelimiter);
  974. }
  975. File->HumanRights = HumanRights;
  976. }
  977. //---------------------------------------------------------------------------
  978. int __fastcall TWebDAVFileSystem::CustomReadFileInternal(const UnicodeString FileName,
  979. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  980. {
  981. std::unique_ptr<TRemoteFile> AFile(new TRemoteFile(ALinkedByFile));
  982. TReadFileData Data;
  983. Data.FileSystem = this;
  984. Data.File = AFile.get();
  985. Data.FileList = NULL;
  986. ClearNeonError();
  987. int Result =
  988. ne_simple_propfind(FSessionContext->NeonSession, PathToNeon(FileName), NE_DEPTH_ZERO, NULL,
  989. NeonPropsResult, &Data);
  990. if (Result == NE_OK)
  991. {
  992. File = AFile.release();
  993. }
  994. return Result;
  995. }
  996. //---------------------------------------------------------------------------
  997. void __fastcall TWebDAVFileSystem::CustomReadFile(UnicodeString FileName,
  998. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  999. {
  1000. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1001. int NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  1002. if (IsValidRedirect(NeonStatus, FileName))
  1003. {
  1004. NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  1005. }
  1006. CheckStatus(NeonStatus);
  1007. }
  1008. //---------------------------------------------------------------------------
  1009. void __fastcall TWebDAVFileSystem::DeleteFile(const UnicodeString FileName,
  1010. const TRemoteFile * File, int /*Params*/, TRmSessionAction & Action)
  1011. {
  1012. Action.Recursive();
  1013. ClearNeonError();
  1014. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1015. RawByteString Path = PathToNeon(FilePath(File));
  1016. // WebDAV does not allow non-recursive delete:
  1017. // RFC 4918, section 9.6.1:
  1018. // "A client MUST NOT submit a Depth header with a DELETE on a collection with any value but infinity."
  1019. // We should check that folder is empty when called with FLAGSET(Params, dfNoRecursive)
  1020. CheckStatus(ne_delete(FSessionContext->NeonSession, Path.c_str()));
  1021. // The lock is removed with the file, but if a file with the same name gets created,
  1022. // we would try to use obsoleted lock token with it, what the server would reject
  1023. // (mod_dav returns "412 Precondition Failed")
  1024. DiscardLock(Path);
  1025. }
  1026. //---------------------------------------------------------------------------
  1027. int __fastcall TWebDAVFileSystem::RenameFileInternal(const UnicodeString & FileName,
  1028. const UnicodeString & NewName)
  1029. {
  1030. const int Overwrite = 1;
  1031. return ne_move(FSessionContext->NeonSession, Overwrite, PathToNeon(FileName), PathToNeon(NewName));
  1032. }
  1033. //---------------------------------------------------------------------------
  1034. void __fastcall TWebDAVFileSystem::RenameFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  1035. const UnicodeString NewName)
  1036. {
  1037. ClearNeonError();
  1038. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1039. UnicodeString Path = FileName;
  1040. int NeonStatus = RenameFileInternal(Path, NewName);
  1041. if (IsValidRedirect(NeonStatus, Path))
  1042. {
  1043. NeonStatus = RenameFileInternal(Path, NewName);
  1044. }
  1045. CheckStatus(NeonStatus);
  1046. // See a comment in DeleteFile
  1047. DiscardLock(PathToNeon(Path));
  1048. }
  1049. //---------------------------------------------------------------------------
  1050. int __fastcall TWebDAVFileSystem::CopyFileInternal(const UnicodeString & FileName,
  1051. const UnicodeString & NewName)
  1052. {
  1053. // 0 = no overwrite
  1054. return ne_copy(FSessionContext->NeonSession, 0, NE_DEPTH_INFINITE, PathToNeon(FileName), PathToNeon(NewName));
  1055. }
  1056. //---------------------------------------------------------------------------
  1057. void __fastcall TWebDAVFileSystem::CopyFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  1058. const UnicodeString NewName)
  1059. {
  1060. ClearNeonError();
  1061. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1062. UnicodeString Path = FileName;
  1063. int NeonStatus = CopyFileInternal(Path, NewName);
  1064. if (IsValidRedirect(NeonStatus, Path))
  1065. {
  1066. NeonStatus = CopyFileInternal(Path, NewName);
  1067. }
  1068. CheckStatus(NeonStatus);
  1069. }
  1070. //---------------------------------------------------------------------------
  1071. void __fastcall TWebDAVFileSystem::CreateDirectory(const UnicodeString & DirName, bool /*Encrypt*/)
  1072. {
  1073. ClearNeonError();
  1074. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1075. CheckStatus(ne_mkcol(FSessionContext->NeonSession, PathToNeon(DirName)));
  1076. }
  1077. //---------------------------------------------------------------------------
  1078. void __fastcall TWebDAVFileSystem::CreateLink(const UnicodeString FileName,
  1079. const UnicodeString PointTo, bool /*Symbolic*/)
  1080. {
  1081. DebugFail();
  1082. }
  1083. //---------------------------------------------------------------------------
  1084. void __fastcall TWebDAVFileSystem::ChangeFileProperties(const UnicodeString FileName,
  1085. const TRemoteFile * /*File*/, const TRemoteProperties * /*Properties*/,
  1086. TChmodSessionAction & /*Action*/)
  1087. {
  1088. DebugFail();
  1089. }
  1090. //---------------------------------------------------------------------------
  1091. bool __fastcall TWebDAVFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  1092. {
  1093. DebugFail();
  1094. return false;
  1095. }
  1096. //---------------------------------------------------------------------------
  1097. void __fastcall TWebDAVFileSystem::CalculateFilesChecksum(
  1098. const UnicodeString & DebugUsedArg(Alg), TStrings * DebugUsedArg(FileList), TCalculatedChecksumEvent,
  1099. TFileOperationProgressType *, bool DebugUsedArg(FirstLevel))
  1100. {
  1101. DebugFail();
  1102. }
  1103. //---------------------------------------------------------------------------
  1104. void __fastcall TWebDAVFileSystem::ConfirmOverwrite(
  1105. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1106. TFileOperationProgressType * OperationProgress,
  1107. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1108. int Params)
  1109. {
  1110. // all = "yes to newer"
  1111. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll;
  1112. TQueryButtonAlias Aliases[3];
  1113. Aliases[0] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
  1114. Aliases[1] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
  1115. Aliases[2] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
  1116. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1117. QueryParams.Aliases = Aliases;
  1118. QueryParams.AliasesCount = LENOF(Aliases);
  1119. unsigned int Answer;
  1120. {
  1121. TSuspendFileOperationProgress Suspend(OperationProgress);
  1122. Answer =
  1123. FTerminal->ConfirmFileOverwrite(
  1124. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1125. ReverseOperationSide(OperationProgress->Side),
  1126. CopyParam, Params, OperationProgress);
  1127. }
  1128. switch (Answer)
  1129. {
  1130. case qaYes:
  1131. // Can happen when moving to background (and the server manages to commit the interrupeted foreground transfer).
  1132. // WebDAV does not support resumable uploads.
  1133. // Resumable downloads are not implemented.
  1134. case qaRetry:
  1135. // noop
  1136. break;
  1137. case qaNo:
  1138. throw ESkipFile();
  1139. default:
  1140. DebugFail();
  1141. case qaCancel:
  1142. OperationProgress->SetCancelAtLeast(csCancel);
  1143. Abort();
  1144. break;
  1145. }
  1146. }
  1147. //---------------------------------------------------------------------------
  1148. void __fastcall TWebDAVFileSystem::CustomCommandOnFile(const UnicodeString FileName,
  1149. const TRemoteFile * /*File*/, UnicodeString Command, int /*Params*/, TCaptureOutputEvent /*OutputEvent*/)
  1150. {
  1151. DebugFail();
  1152. }
  1153. //---------------------------------------------------------------------------
  1154. void __fastcall TWebDAVFileSystem::AnyCommand(const UnicodeString Command,
  1155. TCaptureOutputEvent /*OutputEvent*/)
  1156. {
  1157. DebugFail();
  1158. }
  1159. //---------------------------------------------------------------------------
  1160. TStrings * __fastcall TWebDAVFileSystem::GetFixedPaths()
  1161. {
  1162. return NULL;
  1163. }
  1164. //---------------------------------------------------------------------------
  1165. void TWebDAVFileSystem::NeonQuotaResult(
  1166. void * UserData, const ne_uri * /*Uri*/, const ne_prop_result_set * Results)
  1167. {
  1168. TSpaceAvailable & SpaceAvailable = *static_cast<TSpaceAvailable *>(UserData);
  1169. const char * Value = GetProp(Results, PROP_QUOTA_AVAILABLE);
  1170. if (Value != NULL)
  1171. {
  1172. SpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(StrFromNeon(Value));
  1173. const char * Value = GetProp(Results, PROP_QUOTA_USED);
  1174. if (Value != NULL)
  1175. {
  1176. SpaceAvailable.BytesAvailableToUser =
  1177. StrToInt64(StrFromNeon(Value)) + SpaceAvailable.UnusedBytesAvailableToUser;
  1178. }
  1179. }
  1180. }
  1181. //---------------------------------------------------------------------------
  1182. void __fastcall TWebDAVFileSystem::SpaceAvailable(const UnicodeString Path,
  1183. TSpaceAvailable & ASpaceAvailable)
  1184. {
  1185. // RFC4331: https://datatracker.ietf.org/doc/html/rfc4331
  1186. // This is known to be supported by:
  1187. // OpenDrive: for a root drive only (and contrary to the spec, it sends the properties
  1188. // unconditionally, even when not explicitly requested)
  1189. // Server: Apache/2.2.17 (Fedora)
  1190. // X-Powered-By: PHP/5.5.7
  1191. // X-DAV-Powered-By: OpenDrive
  1192. // WWW-Authenticate: Basic realm="PHP WebDAV"
  1193. // IT Hit WebDAV Server:
  1194. // Server: Microsoft-HTTPAPI/1.0
  1195. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1196. // Yandex disk:
  1197. // WWW-Authenticate: Basic realm="Yandex.Disk"
  1198. // Server: MochiWeb/1.0
  1199. // OneDrive:
  1200. // it sends the properties unconditionally, even when not explicitly requested
  1201. UnicodeString APath = DirectoryPath(Path);
  1202. ne_propname QuotaProps[3];
  1203. memset(QuotaProps, 0, sizeof(QuotaProps));
  1204. QuotaProps[0].nspace = DAV_PROP_NAMESPACE;
  1205. QuotaProps[0].name = PROP_QUOTA_AVAILABLE;
  1206. QuotaProps[1].nspace = DAV_PROP_NAMESPACE;
  1207. QuotaProps[1].name = PROP_QUOTA_USED;
  1208. QuotaProps[2].nspace = NULL;
  1209. QuotaProps[2].name = NULL;
  1210. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1211. CheckStatus(
  1212. ne_simple_propfind(FSessionContext->NeonSession, PathToNeon(APath), NE_DEPTH_ZERO, QuotaProps,
  1213. NeonQuotaResult, &ASpaceAvailable));
  1214. }
  1215. //---------------------------------------------------------------------------
  1216. void __fastcall TWebDAVFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1217. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1218. int Params, TFileOperationProgressType * OperationProgress,
  1219. TOnceDoneOperation & OnceDoneOperation)
  1220. {
  1221. Params &= ~cpAppend;
  1222. FTerminal->DoCopyToRemote(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfPreCreateDir, OnceDoneOperation);
  1223. }
  1224. //---------------------------------------------------------------------------
  1225. void __fastcall TWebDAVFileSystem::Source(
  1226. TLocalFileHandle & Handle, const UnicodeString & TargetDir, UnicodeString & DestFileName,
  1227. const TCopyParamType * CopyParam, int Params,
  1228. TFileOperationProgressType * OperationProgress, unsigned int /*Flags*/,
  1229. TUploadSessionAction & Action, bool & ChildError)
  1230. {
  1231. int FD = -1;
  1232. try
  1233. {
  1234. UnicodeString DestFullName = TargetDir + DestFileName;
  1235. TRemoteFile * RemoteFile = NULL;
  1236. try
  1237. {
  1238. TValueRestorer<TIgnoreAuthenticationFailure> IgnoreAuthenticationFailureRestorer(FIgnoreAuthenticationFailure);
  1239. FIgnoreAuthenticationFailure = iafWaiting;
  1240. // this should not throw
  1241. CustomReadFileInternal(DestFullName, RemoteFile, NULL);
  1242. }
  1243. catch (...)
  1244. {
  1245. if (!FTerminal->Active)
  1246. {
  1247. throw;
  1248. }
  1249. }
  1250. if (RemoteFile != NULL)
  1251. {
  1252. TOverwriteFileParams FileParams;
  1253. FileParams.SourceSize = Handle.Size;
  1254. FileParams.SourceTimestamp = Handle.Modification;
  1255. FileParams.DestSize = RemoteFile->Size;
  1256. FileParams.DestTimestamp = RemoteFile->Modification;
  1257. delete RemoteFile;
  1258. ConfirmOverwrite(Handle.FileName, DestFileName, OperationProgress,
  1259. &FileParams, CopyParam, Params);
  1260. }
  1261. DestFullName = TargetDir + DestFileName;
  1262. // only now, we know the final destination
  1263. // (not really true as we do not support changing file name on overwrite dialog)
  1264. Action.Destination(DestFullName);
  1265. FUploadMimeType = Configuration->GetFileMimeType(DestFileName);
  1266. FILE_OPERATION_LOOP_BEGIN
  1267. {
  1268. SetFilePointer(Handle.Handle, 0, NULL, FILE_BEGIN);
  1269. FD = _open_osfhandle((intptr_t)Handle.Handle, O_BINARY);
  1270. if (FD < 0) // can happen only if there are no free slots in handle-FD table
  1271. {
  1272. throw ESkipFile();
  1273. }
  1274. TAutoFlag UploadingFlag(FUploading);
  1275. ClearNeonError();
  1276. CheckStatus(ne_put(FSessionContext->NeonSession, PathToNeon(DestFullName), FD));
  1277. }
  1278. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (Handle.FileName)));
  1279. if (CopyParam->PreserveTime)
  1280. {
  1281. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1282. (StandardTimestamp(Handle.Modification))));
  1283. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Handle.Modification);
  1284. try
  1285. {
  1286. TDateTime ModificationUTC = ConvertTimestampToUTC(Handle.Modification);
  1287. TFormatSettings FormatSettings = GetEngFormatSettings();
  1288. UnicodeString LastModified =
  1289. FormatDateTime(L"ddd, d mmm yyyy hh:nn:ss 'GMT'", ModificationUTC, FormatSettings);
  1290. UTF8String NeonLastModified(LastModified);
  1291. // second element is "NULL-terminating"
  1292. ne_proppatch_operation Operations[2];
  1293. memset(Operations, 0, sizeof(Operations));
  1294. ne_propname LastModifiedProp;
  1295. LastModifiedProp.nspace = DAV_PROP_NAMESPACE;
  1296. LastModifiedProp.name = PROP_LAST_MODIFIED;
  1297. Operations[0].name = &LastModifiedProp;
  1298. Operations[0].type = ne_propset;
  1299. Operations[0].value = NeonLastModified.c_str();
  1300. int Status = ne_proppatch(FSessionContext->NeonSession, PathToNeon(DestFullName), Operations);
  1301. if (Status == NE_ERROR)
  1302. {
  1303. FTerminal->LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s",
  1304. (GetNeonError())));
  1305. // Ignore errors as major WebDAV servers (like IIS), do not support
  1306. // changing getlastmodified.
  1307. // The only server we found that supports this is TradeMicro SafeSync.
  1308. // But it announces itself as "Server: Apache",
  1309. // so it's not reliable to autodetect the support.
  1310. // Microsoft Office alegedly uses <Win32LastModifiedTime>
  1311. // https://sabre.io/dav/clients/msoffice/
  1312. // Carot DAV does that too. But we do not know what server does support this.
  1313. TouchAction.Cancel();
  1314. }
  1315. else
  1316. {
  1317. CheckStatus(Status);
  1318. }
  1319. }
  1320. catch (Exception & E)
  1321. {
  1322. TouchAction.Rollback(&E);
  1323. ChildError = true;
  1324. throw;
  1325. }
  1326. }
  1327. }
  1328. __finally
  1329. {
  1330. if (FD >= 0)
  1331. {
  1332. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1333. // but it crashes code guard
  1334. _close(FD);
  1335. Handle.Dismiss();
  1336. }
  1337. }
  1338. }
  1339. //---------------------------------------------------------------------------
  1340. void __fastcall TWebDAVFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1341. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1342. int Params, TFileOperationProgressType * OperationProgress,
  1343. TOnceDoneOperation & OnceDoneOperation)
  1344. {
  1345. Params &= ~cpAppend;
  1346. FTerminal->DoCopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfNone, OnceDoneOperation);
  1347. }
  1348. //---------------------------------------------------------------------------
  1349. void TWebDAVFileSystem::NeonCreateRequest(
  1350. ne_request * Request, void * UserData, const char * /*Method*/, const char * /*Uri*/)
  1351. {
  1352. TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
  1353. ne_set_request_private(Request, SESSION_CONTEXT_KEY, SessionContext);
  1354. ne_add_response_body_reader(Request, NeonBodyAccepter, NeonBodyReader, Request);
  1355. SessionContext->NtlmAuthenticationFailed = false;
  1356. }
  1357. //---------------------------------------------------------------------------
  1358. void TWebDAVFileSystem::NeonPreSend(
  1359. ne_request * Request, void * UserData, ne_buffer * Header)
  1360. {
  1361. TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
  1362. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1363. SessionContext->AuthorizationProtocol = EmptyStr;
  1364. UnicodeString HeaderBuf(StrFromNeon(AnsiString(Header->data, Header->used)));
  1365. const UnicodeString AuthorizationHeaderName(L"Authorization:");
  1366. int P = HeaderBuf.Pos(AuthorizationHeaderName);
  1367. if (P > 0)
  1368. {
  1369. P += AuthorizationHeaderName.Length();
  1370. int P2 = PosEx(L"\n", HeaderBuf, P);
  1371. if (DebugAlwaysTrue(P2 > 0))
  1372. {
  1373. UnicodeString AuthorizationHeader = HeaderBuf.SubString(P, P2 - P).Trim();
  1374. SessionContext->AuthorizationProtocol = CutToChar(AuthorizationHeader, L' ', false);
  1375. if (SessionContext == FileSystem->FSessionContext)
  1376. {
  1377. FileSystem->FLastAuthorizationProtocol = SessionContext->AuthorizationProtocol;
  1378. }
  1379. }
  1380. }
  1381. if (FileSystem->FDownloading)
  1382. {
  1383. // Needed by IIS server to make it download source code, not code output,
  1384. // and mainly to even allow downloading file with unregistered extensions.
  1385. // Without it files like .001 return 404 (Not found) HTTP code.
  1386. // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wdv/e37a9543-9290-4843-8c04-66457c60fa0a
  1387. // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wdvse/501879f9-3875-4d7a-ab88-3cecab440034
  1388. // It's also supported by Oracle server:
  1389. // https://docs.oracle.com/cd/E19146-01/821-1828/gczya/index.html
  1390. // We do not know yet of any server that fails when the header is used,
  1391. // so it's added unconditionally.
  1392. ne_buffer_zappend(Header, "Translate: f\r\n");
  1393. }
  1394. const UnicodeString ContentTypeHeaderPrefix(L"Content-Type: ");
  1395. if (FileSystem->FTerminal->Log->Logging)
  1396. {
  1397. const char * Buffer;
  1398. size_t Size;
  1399. if (ne_get_request_body_buffer(Request, &Buffer, &Size))
  1400. {
  1401. // all neon request types that use ne_add_request_header
  1402. // use XML content-type, so it's text-based
  1403. DebugAssert(ContainsStr(HeaderBuf, ContentTypeHeaderPrefix + NE_XML_MEDIA_TYPE));
  1404. FileSystem->FTerminal->Log->Add(llInput, UnicodeString(UTF8String(Buffer, Size)));
  1405. }
  1406. }
  1407. if (FileSystem->FUploading)
  1408. {
  1409. ne_set_request_body_provider_pre(Request, FileSystem->NeonUploadBodyProvider, SessionContext);
  1410. if (!FileSystem->FUploadMimeType.IsEmpty())
  1411. {
  1412. UnicodeString ContentTypeHeader = ContentTypeHeaderPrefix + FileSystem->FUploadMimeType + L"\r\n";
  1413. ne_buffer_zappend(Header, AnsiString(ContentTypeHeader).c_str());
  1414. }
  1415. }
  1416. FileSystem->FResponse = L"";
  1417. }
  1418. //---------------------------------------------------------------------------
  1419. int TWebDAVFileSystem::NeonPostSend(ne_request * /*Req*/, void * UserData,
  1420. const ne_status * /*Status*/)
  1421. {
  1422. TWebDAVFileSystem * FileSystem = static_cast<TSessionContext *>(UserData)->FileSystem;
  1423. if (!FileSystem->FResponse.IsEmpty())
  1424. {
  1425. FileSystem->FTerminal->Log->Add(llOutput, FileSystem->FResponse);
  1426. }
  1427. return NE_OK;
  1428. }
  1429. //---------------------------------------------------------------------------
  1430. bool __fastcall TWebDAVFileSystem::IsNtlmAuthentication(TSessionContext * SessionContext)
  1431. {
  1432. return
  1433. SameText(SessionContext->AuthorizationProtocol, L"NTLM") ||
  1434. SameText(SessionContext->AuthorizationProtocol, L"Negotiate");
  1435. }
  1436. //---------------------------------------------------------------------------
  1437. void __fastcall TWebDAVFileSystem::HttpAuthenticationFailed(TSessionContext * SessionContext)
  1438. {
  1439. // NTLM/GSSAPI failed
  1440. if (IsNtlmAuthentication(SessionContext))
  1441. {
  1442. if (SessionContext->NtlmAuthenticationFailed)
  1443. {
  1444. // Next time do not try Negotiate (NTLM/GSSAPI),
  1445. // otherwise we end up in an endless loop.
  1446. // If the server returns all other challenges in the response, removing the Negotiate
  1447. // protocol will itself ensure that other protocols are tried (we haven't seen this behaviour).
  1448. // IIS will return only Negotiate response if the request was Negotiate, so there's no fallback.
  1449. // We have to retry with a fresh request. That's what FAuthenticationRetry does.
  1450. FTerminal->LogEvent(FORMAT(L"%s challenge failed, will try different challenge", (SessionContext->AuthorizationProtocol)));
  1451. ne_remove_server_auth(SessionContext->NeonSession);
  1452. NeonAddAuthentiation(SessionContext, false);
  1453. FAuthenticationRetry = true;
  1454. }
  1455. else
  1456. {
  1457. // The first 401 is expected, the server is using it to send WWW-Authenticate header with data.
  1458. SessionContext->NtlmAuthenticationFailed = true;
  1459. }
  1460. }
  1461. }
  1462. //---------------------------------------------------------------------------
  1463. void TWebDAVFileSystem::NeonPostHeaders(ne_request * /*Req*/, void * UserData, const ne_status * Status)
  1464. {
  1465. TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
  1466. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1467. if (Status->code == HttpUnauthorized)
  1468. {
  1469. FileSystem->HttpAuthenticationFailed(SessionContext);
  1470. }
  1471. }
  1472. //---------------------------------------------------------------------------
  1473. ssize_t TWebDAVFileSystem::NeonUploadBodyProvider(void * UserData, char * /*Buffer*/, size_t /*BufLen*/)
  1474. {
  1475. TWebDAVFileSystem * FileSystem = static_cast<TSessionContext *>(UserData)->FileSystem;
  1476. ssize_t Result;
  1477. if (FileSystem->CancelTransfer())
  1478. {
  1479. Result = -1;
  1480. }
  1481. else
  1482. {
  1483. Result = 1;
  1484. }
  1485. return Result;
  1486. }
  1487. //---------------------------------------------------------------------------
  1488. static void __fastcall AddHeaderValueToList(UnicodeString & List, ne_request * Request, const char * Name)
  1489. {
  1490. const char * Value = ne_get_response_header(Request, Name);
  1491. if (Value != NULL)
  1492. {
  1493. AddToList(List, StrFromNeon(Value), L"; ");
  1494. }
  1495. }
  1496. //---------------------------------------------------------------------------
  1497. int TWebDAVFileSystem::NeonBodyAccepter(void * UserData, ne_request * Request, const ne_status * Status)
  1498. {
  1499. DebugAssert(UserData == Request);
  1500. TSessionContext * SessionContext = static_cast<TSessionContext *>(ne_get_request_private(Request, SESSION_CONTEXT_KEY));
  1501. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1502. bool AuthenticationFailureCode = (Status->code == HttpUnauthorized);
  1503. bool PasswordAuthenticationFailed = AuthenticationFailureCode && FileSystem->FAuthenticationRequested;
  1504. bool AuthenticationFailed = PasswordAuthenticationFailed || (AuthenticationFailureCode && FileSystem->IsNtlmAuthentication(SessionContext));
  1505. bool AuthenticationNeeded = AuthenticationFailureCode && !AuthenticationFailed;
  1506. if (FileSystem->FInitialHandshake)
  1507. {
  1508. UnicodeString Line;
  1509. if (AuthenticationNeeded)
  1510. {
  1511. Line = LoadStr(STATUS_AUTHENTICATE);
  1512. }
  1513. else if (AuthenticationFailed)
  1514. {
  1515. Line = LoadStr(FTP_ACCESS_DENIED);
  1516. }
  1517. else if (Status->klass == 2)
  1518. {
  1519. Line = LoadStr(STATUS_AUTHENTICATED);
  1520. }
  1521. if (!Line.IsEmpty())
  1522. {
  1523. FileSystem->FTerminal->Information(Line, true);
  1524. }
  1525. UnicodeString RemoteSystem;
  1526. // Used by IT Hit WebDAV Server:
  1527. // Server: Microsoft-HTTPAPI/1.0
  1528. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1529. AddHeaderValueToList(RemoteSystem, Request, "X-Engine");
  1530. // Used by OpenDrive:
  1531. // Server: Apache/2.2.17 (Fedora)
  1532. // X-Powered-By: PHP/5.5.7
  1533. // X-DAV-Powered-By: OpenDrive
  1534. AddHeaderValueToList(RemoteSystem, Request, "X-DAV-Powered-By");
  1535. // Used by IIS:
  1536. // Server: Microsoft-IIS/8.5
  1537. AddHeaderValueToList(RemoteSystem, Request, "Server");
  1538. // Not really useful.
  1539. // Can be e.g. "PleskLin"
  1540. AddHeaderValueToList(RemoteSystem, Request, "X-Powered-By");
  1541. FileSystem->FFileSystemInfo.RemoteSystem = RemoteSystem;
  1542. }
  1543. // When we explicitly fail authentication of request
  1544. // with FIgnoreAuthenticationFailure flag (after it failed with password),
  1545. // neon resets its internal password store and tries the next request
  1546. // without calling our authentication hook first
  1547. // (note AuthenticationFailed vs. AuthenticationNeeded)
  1548. // what likely fails, but we do not want to reset out password
  1549. // (as it was not even tried yet for this request).
  1550. if (PasswordAuthenticationFailed)
  1551. {
  1552. if (FileSystem->FIgnoreAuthenticationFailure == iafNo)
  1553. {
  1554. FileSystem->FPassword = RawByteString();
  1555. }
  1556. else
  1557. {
  1558. FileSystem->FIgnoreAuthenticationFailure = iafPasswordFailed;
  1559. }
  1560. }
  1561. return ne_accept_2xx(UserData, Request, Status);
  1562. }
  1563. //---------------------------------------------------------------------------
  1564. bool __fastcall TWebDAVFileSystem::CancelTransfer()
  1565. {
  1566. bool Result = false;
  1567. if ((FUploading || FDownloading) &&
  1568. (FTerminal->OperationProgress != NULL) &&
  1569. (FTerminal->OperationProgress->Cancel != csContinue))
  1570. {
  1571. if (FTerminal->OperationProgress->ClearCancelFile())
  1572. {
  1573. FSkipped = true;
  1574. }
  1575. else
  1576. {
  1577. FCancelled = true;
  1578. }
  1579. Result = true;
  1580. }
  1581. return Result;
  1582. }
  1583. //---------------------------------------------------------------------------
  1584. int TWebDAVFileSystem::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  1585. {
  1586. ne_request * Request = static_cast<ne_request *>(UserData);
  1587. TSessionContext * SessionContext = static_cast<TSessionContext *>(ne_get_request_private(Request, SESSION_CONTEXT_KEY));
  1588. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1589. if (FileSystem->FTerminal->Log->Logging)
  1590. {
  1591. ne_content_type ContentType;
  1592. if (ne_get_content_type(Request, &ContentType) == 0)
  1593. {
  1594. // The main point of the content-type check was to exclude
  1595. // GET responses (with file contents).
  1596. // But this won't work when downloading text files that have text
  1597. // content type on their own, hence the additional not-downloading test.
  1598. if (!FileSystem->FDownloading &&
  1599. ((ne_strcasecmp(ContentType.type, "text") == 0) ||
  1600. media_type_is_xml(&ContentType)))
  1601. {
  1602. UnicodeString Content = UnicodeString(UTF8String(Buf, Len)).Trim();
  1603. FileSystem->FResponse += Content;
  1604. }
  1605. ne_free(ContentType.value);
  1606. }
  1607. }
  1608. int Result = FileSystem->CancelTransfer() ? 1 : 0;
  1609. return Result;
  1610. }
  1611. //---------------------------------------------------------------------------
  1612. void __fastcall TWebDAVFileSystem::Sink(
  1613. const UnicodeString & FileName, const TRemoteFile * File,
  1614. const UnicodeString & TargetDir, UnicodeString & DestFileName, int Attrs,
  1615. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  1616. unsigned int /*Flags*/, TDownloadSessionAction & Action)
  1617. {
  1618. UnicodeString DestFullName = TargetDir + DestFileName;
  1619. if (FileExists(ApiPath(DestFullName)))
  1620. {
  1621. __int64 Size;
  1622. __int64 MTime;
  1623. FTerminal->OpenLocalFile(DestFullName, GENERIC_READ, NULL, NULL, NULL, &MTime, NULL, &Size);
  1624. TOverwriteFileParams FileParams;
  1625. FileParams.SourceSize = File->Size;
  1626. FileParams.SourceTimestamp = File->Modification;
  1627. FileParams.DestSize = Size;
  1628. FileParams.DestTimestamp = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  1629. ConfirmOverwrite(FileName, DestFileName, OperationProgress, &FileParams, CopyParam, Params);
  1630. }
  1631. UnicodeString ExpandedDestFullName = ExpandUNCFileName(DestFullName);
  1632. Action.Destination(ExpandedDestFullName);
  1633. FILE_OPERATION_LOOP_BEGIN
  1634. {
  1635. HANDLE LocalHandle;
  1636. if (!FTerminal->CreateLocalFile(DestFullName, OperationProgress, &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  1637. {
  1638. throw ESkipFile();
  1639. }
  1640. bool DeleteLocalFile = true;
  1641. int FD = -1;
  1642. try
  1643. {
  1644. FD = _open_osfhandle((intptr_t)LocalHandle, O_BINARY);
  1645. if (FD < 0)
  1646. {
  1647. throw ESkipFile();
  1648. }
  1649. TAutoFlag DownloadingFlag(FDownloading);
  1650. ClearNeonError();
  1651. int NeonStatus = ne_get(FSessionContext->NeonSession, PathToNeon(FileName), FD);
  1652. UnicodeString DiscardPath = FileName;
  1653. if (IsValidRedirect(NeonStatus, DiscardPath))
  1654. {
  1655. UnicodeString CorrectedUrl = GetRedirectUrl();
  1656. UTF8String CorrectedFileName, Query;
  1657. std::unique_ptr<TSessionContext> CorrectedSessionContext(NeonOpen(CorrectedUrl, CorrectedFileName, Query));
  1658. UTF8String RedirectUrl = CorrectedFileName;
  1659. if (!Query.IsEmpty())
  1660. {
  1661. RedirectUrl += L"?" + Query;
  1662. }
  1663. NeonStatus = ne_get(CorrectedSessionContext->NeonSession, RedirectUrl.c_str(), FD);
  1664. CheckStatus(CorrectedSessionContext.get(), NeonStatus);
  1665. }
  1666. else
  1667. {
  1668. CheckStatus(NeonStatus);
  1669. }
  1670. DeleteLocalFile = false;
  1671. if (CopyParam->PreserveTime)
  1672. {
  1673. FTerminal->UpdateTargetTime(LocalHandle, File->Modification, 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 /nonexising 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. //---------------------------------------------------------------------------