WebDAVFileSystem.cpp 77 KB

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