WebDAVFileSystem.cpp 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224
  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. TWebDAVFileSystem * FileSystem = Data.FileSystem;
  812. if (Data.FileList != NULL)
  813. {
  814. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  815. TTerminal * Terminal = FileSystem->FTerminal;
  816. File->Terminal = Terminal;
  817. FileSystem->ParsePropResultSet(File.get(), Path, Results);
  818. UnicodeString FileListPath = UnixIncludeTrailingBackslash(FileSystem->AbsolutePath(Data.FileList->Directory, false));
  819. if (UnixSamePath(File->FullFileName, FileListPath))
  820. {
  821. File->FileName = PARENTDIRECTORY;
  822. File->FullFileName = UnixCombinePaths(Path, PARENTDIRECTORY);
  823. }
  824. else
  825. {
  826. // Quick and dirty hack. The following tests do not work on OneDrive, as the directory path may be escaped,
  827. // and we do not correctly unescape full `Path`, only its filename (so path in FullFileName may not be not correct).
  828. // Until it's real problem somewhere else, we skip this test, as we otherwise trust OneDrive not to return nonsense contents.
  829. if (!FileSystem->FOneDrive)
  830. {
  831. if (!StartsStr(FileListPath, File->FullFileName))
  832. {
  833. Terminal->LogEvent(FORMAT(L"Discarding entry \"%s\" with absolute path \"%s\" because it is not descendant of directory \"%s\".", (Path, File->FullFileName, FileListPath)));
  834. File.reset(NULL);
  835. }
  836. else
  837. {
  838. UnicodeString FileName = MidStr(File->FullFileName, FileListPath.Length() + 1);
  839. if (!UnixExtractFileDir(FileName).IsEmpty())
  840. {
  841. Terminal->LogEvent(FORMAT(L"Discarding entry \"%s\" with absolute path \"%s\" because it is not direct child of directory \"%s\".", (Path, File->FullFileName, FileListPath)));
  842. File.reset(NULL);
  843. }
  844. }
  845. }
  846. }
  847. if (File.get() != NULL)
  848. {
  849. Data.FileList->AddFile(File.release());
  850. }
  851. }
  852. else
  853. {
  854. FileSystem->ParsePropResultSet(Data.File, Path, Results);
  855. }
  856. }
  857. //---------------------------------------------------------------------------
  858. const char * __fastcall TWebDAVFileSystem::GetProp(
  859. const ne_prop_result_set * Results, const char * Name, const char * NameSpace)
  860. {
  861. ne_propname Prop;
  862. Prop.nspace = (NameSpace == NULL) ? DAV_PROP_NAMESPACE : NameSpace;
  863. Prop.name = Name;
  864. return ne_propset_value(Results, &Prop);
  865. }
  866. //---------------------------------------------------------------------------
  867. void __fastcall TWebDAVFileSystem::ParsePropResultSet(TRemoteFile * File,
  868. const UnicodeString & Path, const ne_prop_result_set * Results)
  869. {
  870. File->FullFileName = UnixExcludeTrailingBackslash(Path);
  871. // Some servers do not use DAV:collection tag, but indicate the folder by trailing slash only.
  872. // But not all, for example OneDrive does not (it did in the past).
  873. bool Collection = (File->FullFileName != Path);
  874. File->FileName = UnixExtractFileName(File->FullFileName);
  875. const char * ContentLength = GetProp(Results, PROP_CONTENT_LENGTH);
  876. // some servers, for example iFiles, do not provide "getcontentlength" for folders
  877. if (ContentLength != NULL)
  878. {
  879. File->Size = StrToInt64Def(ContentLength, 0);
  880. }
  881. const char * LastModified = GetProp(Results, PROP_LAST_MODIFIED);
  882. // We've seen a server (t=24891) that does not set "getlastmodified" for the "this" folder entry.
  883. File->ModificationFmt = mfNone; // fallback
  884. if (LastModified != NULL)
  885. {
  886. char WeekDay[4] = { L'\0' };
  887. int Year = 0;
  888. char MonthStr[4] = { L'\0' };
  889. int Day = 0;
  890. int Hour = 0;
  891. int Min = 0;
  892. int Sec = 0;
  893. #define RFC1123_FORMAT "%3s, %02d %3s %4d %02d:%02d:%02d GMT"
  894. // Keep is sync with S3
  895. int Filled =
  896. sscanf(LastModified, RFC1123_FORMAT, WeekDay, &Day, MonthStr, &Year, &Hour, &Min, &Sec);
  897. // we need at least a complete date
  898. if (Filled >= 4)
  899. {
  900. int Month = ParseShortEngMonthName(MonthStr);
  901. if (Month >= 1)
  902. {
  903. TDateTime Modification =
  904. EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) +
  905. EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0);
  906. File->Modification = ConvertTimestampFromUTC(Modification);
  907. // Should use mfYMDHM or mfMDY when appropriate according to Filled
  908. File->ModificationFmt = mfFull;
  909. }
  910. }
  911. }
  912. // optimization
  913. if (!Collection)
  914. {
  915. // See a comment at the Collection declaration.
  916. const char * ResourceType = GetProp(Results, PROP_RESOURCE_TYPE);
  917. if (ResourceType != NULL)
  918. {
  919. // property has XML value
  920. UnicodeString AResourceType = ResourceType;
  921. // this is very poor parsing
  922. if (ContainsText(ResourceType, L"<DAV:collection"))
  923. {
  924. Collection = true;
  925. }
  926. }
  927. }
  928. File->Type = Collection ? FILETYPE_DIRECTORY : FILETYPE_DEFAULT;
  929. // this is MS extension (draft-hopmann-collection-props-00)
  930. const char * IsHidden = GetProp(Results, PROP_HIDDEN);
  931. if (IsHidden != NULL)
  932. {
  933. File->IsHidden = (StrToIntDef(IsHidden, 0) != 0);
  934. }
  935. const char * Owner = GetProp(Results, PROP_OWNER);
  936. if (Owner != NULL)
  937. {
  938. File->Owner.Name = Owner;
  939. }
  940. const char * DisplayName = GetProp(Results, PROP_DISPLAY_NAME);
  941. if (DisplayName != NULL)
  942. {
  943. File->DisplayName = StrFromNeon(DisplayName);
  944. // OneDrive caret escaping (we could do this for all files, but let's limit the scope for now).
  945. // In *file* PROPFIND response, the # (and other symbols like comma or plus) is not escaped at all
  946. // (while in directory listing, they are caret-escaped),
  947. // so if we see one in the display name, take the name from there.
  948. // * and % won't help, as OneDrive seem to have bug with % at the end of the filename,
  949. // and the * (and others) is removed from file names.
  950. // Filenames with commas (,) get as many additional characters at the end of the filename as there are commas.
  951. if (FOneDrive &&
  952. (ContainsText(File->FileName, L"^") || ContainsText(File->FileName, L",") || (wcspbrk(File->DisplayName.c_str(), L"&,+#[]%*") != NULL)))
  953. {
  954. File->FileName = File->DisplayName;
  955. File->FullFileName = UnixCombinePaths(UnixExtractFileDir(File->FullFileName), File->FileName);
  956. }
  957. }
  958. const UnicodeString RightsDelimiter(L", ");
  959. UnicodeString HumanRights;
  960. // Proprietary property of mod_dav
  961. // http://www.webdav.org/mod_dav/#imp
  962. const char * Executable = GetProp(Results, PROP_EXECUTABLE, MODDAV_PROP_NAMESPACE);
  963. if (Executable != NULL)
  964. {
  965. if (strcmp(Executable, "T") == NULL)
  966. {
  967. UnicodeString ExecutableRights;
  968. // The "gear" character is supported since Windows 8
  969. if (IsWin8())
  970. {
  971. ExecutableRights = L"\u2699";
  972. }
  973. else
  974. {
  975. ExecutableRights = LoadStr(EXECUTABLE);
  976. }
  977. AddToList(HumanRights, ExecutableRights, RightsDelimiter);
  978. }
  979. }
  980. struct ne_lock * Lock = static_cast<struct ne_lock *>(ne_propset_private(Results));
  981. if ((Lock != NULL) && (Lock->token != NULL))
  982. {
  983. UnicodeString Owner;
  984. if (Lock->owner != NULL)
  985. {
  986. Owner = StrFromNeon(Lock->owner).Trim();
  987. }
  988. UnicodeString LockRights;
  989. if (IsWin8())
  990. {
  991. // The "lock" character is supported since Windows 8
  992. LockRights = L"\uD83D\uDD12" + Owner;
  993. }
  994. else
  995. {
  996. LockRights = LoadStr(LOCKED);
  997. if (!Owner.IsEmpty())
  998. {
  999. LockRights = FORMAT(L"%s (%s)", (LockRights, Owner));
  1000. }
  1001. }
  1002. AddToList(HumanRights, LockRights, RightsDelimiter);
  1003. }
  1004. File->HumanRights = HumanRights;
  1005. }
  1006. //---------------------------------------------------------------------------
  1007. int __fastcall TWebDAVFileSystem::CustomReadFileInternal(const UnicodeString FileName,
  1008. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  1009. {
  1010. std::unique_ptr<TRemoteFile> AFile(new TRemoteFile(ALinkedByFile));
  1011. TReadFileData Data;
  1012. Data.FileSystem = this;
  1013. Data.File = AFile.get();
  1014. Data.FileList = NULL;
  1015. ClearNeonError();
  1016. int Result =
  1017. ne_simple_propfind(FSessionContext->NeonSession, PathToNeon(FileName), NE_DEPTH_ZERO, NULL,
  1018. NeonPropsResult, &Data);
  1019. if (Result == NE_OK)
  1020. {
  1021. File = AFile.release();
  1022. }
  1023. return Result;
  1024. }
  1025. //---------------------------------------------------------------------------
  1026. void __fastcall TWebDAVFileSystem::CustomReadFile(UnicodeString FileName,
  1027. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  1028. {
  1029. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1030. int NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  1031. if (IsValidRedirect(NeonStatus, FileName))
  1032. {
  1033. NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  1034. }
  1035. CheckStatus(NeonStatus);
  1036. }
  1037. //---------------------------------------------------------------------------
  1038. void __fastcall TWebDAVFileSystem::DeleteFile(const UnicodeString FileName,
  1039. const TRemoteFile * File, int /*Params*/, TRmSessionAction & Action)
  1040. {
  1041. Action.Recursive();
  1042. ClearNeonError();
  1043. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1044. RawByteString Path = PathToNeon(FilePath(File));
  1045. // WebDAV does not allow non-recursive delete:
  1046. // RFC 4918, section 9.6.1:
  1047. // "A client MUST NOT submit a Depth header with a DELETE on a collection with any value but infinity."
  1048. // We should check that folder is empty when called with FLAGSET(Params, dfNoRecursive)
  1049. CheckStatus(ne_delete(FSessionContext->NeonSession, Path.c_str()));
  1050. // The lock is removed with the file, but if a file with the same name gets created,
  1051. // we would try to use obsoleted lock token with it, what the server would reject
  1052. // (mod_dav returns "412 Precondition Failed")
  1053. DiscardLock(Path);
  1054. }
  1055. //---------------------------------------------------------------------------
  1056. int __fastcall TWebDAVFileSystem::RenameFileInternal(
  1057. const UnicodeString & FileName, const UnicodeString & NewName, bool Overwrite)
  1058. {
  1059. return ne_move(FSessionContext->NeonSession, Overwrite, PathToNeon(FileName), PathToNeon(NewName));
  1060. }
  1061. //---------------------------------------------------------------------------
  1062. void __fastcall TWebDAVFileSystem::RenameFile(
  1063. const UnicodeString & FileName, const TRemoteFile *, const UnicodeString & NewName, bool Overwrite)
  1064. {
  1065. ClearNeonError();
  1066. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1067. UnicodeString Path = FileName;
  1068. int NeonStatus = RenameFileInternal(Path, NewName, Overwrite);
  1069. if (IsValidRedirect(NeonStatus, Path))
  1070. {
  1071. NeonStatus = RenameFileInternal(Path, NewName, Overwrite);
  1072. }
  1073. CheckStatus(NeonStatus);
  1074. // See a comment in DeleteFile
  1075. DiscardLock(PathToNeon(Path));
  1076. }
  1077. //---------------------------------------------------------------------------
  1078. int __fastcall TWebDAVFileSystem::CopyFileInternal(
  1079. const UnicodeString & FileName, const UnicodeString & NewName, bool Overwrite)
  1080. {
  1081. return ne_copy(FSessionContext->NeonSession, Overwrite, NE_DEPTH_INFINITE, PathToNeon(FileName), PathToNeon(NewName));
  1082. }
  1083. //---------------------------------------------------------------------------
  1084. void __fastcall TWebDAVFileSystem::CopyFile(
  1085. const UnicodeString & FileName, const TRemoteFile *, const UnicodeString & NewName, bool Overwrite)
  1086. {
  1087. ClearNeonError();
  1088. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1089. UnicodeString Path = FileName;
  1090. int NeonStatus = CopyFileInternal(Path, NewName, Overwrite);
  1091. if (IsValidRedirect(NeonStatus, Path))
  1092. {
  1093. NeonStatus = CopyFileInternal(Path, NewName, Overwrite);
  1094. }
  1095. CheckStatus(NeonStatus);
  1096. }
  1097. //---------------------------------------------------------------------------
  1098. void __fastcall TWebDAVFileSystem::CreateDirectory(const UnicodeString & DirName, bool /*Encrypt*/)
  1099. {
  1100. ClearNeonError();
  1101. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1102. CheckStatus(ne_mkcol(FSessionContext->NeonSession, PathToNeon(DirName)));
  1103. }
  1104. //---------------------------------------------------------------------------
  1105. void __fastcall TWebDAVFileSystem::CreateLink(const UnicodeString FileName,
  1106. const UnicodeString PointTo, bool /*Symbolic*/)
  1107. {
  1108. DebugFail();
  1109. }
  1110. //---------------------------------------------------------------------------
  1111. void __fastcall TWebDAVFileSystem::ChangeFileProperties(const UnicodeString FileName,
  1112. const TRemoteFile * /*File*/, const TRemoteProperties * /*Properties*/,
  1113. TChmodSessionAction & /*Action*/)
  1114. {
  1115. DebugFail();
  1116. }
  1117. //---------------------------------------------------------------------------
  1118. bool __fastcall TWebDAVFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  1119. {
  1120. DebugFail();
  1121. return false;
  1122. }
  1123. //---------------------------------------------------------------------------
  1124. void __fastcall TWebDAVFileSystem::CalculateFilesChecksum(
  1125. const UnicodeString & DebugUsedArg(Alg), TStrings * DebugUsedArg(FileList), TCalculatedChecksumEvent,
  1126. TFileOperationProgressType *, bool DebugUsedArg(FirstLevel))
  1127. {
  1128. DebugFail();
  1129. }
  1130. //---------------------------------------------------------------------------
  1131. void __fastcall TWebDAVFileSystem::ConfirmOverwrite(
  1132. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1133. TFileOperationProgressType * OperationProgress,
  1134. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1135. int Params)
  1136. {
  1137. // all = "yes to newer"
  1138. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll;
  1139. TQueryButtonAlias Aliases[3];
  1140. Aliases[0] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
  1141. Aliases[1] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
  1142. Aliases[2] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
  1143. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1144. QueryParams.Aliases = Aliases;
  1145. QueryParams.AliasesCount = LENOF(Aliases);
  1146. unsigned int Answer;
  1147. {
  1148. TSuspendFileOperationProgress Suspend(OperationProgress);
  1149. Answer =
  1150. FTerminal->ConfirmFileOverwrite(
  1151. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1152. ReverseOperationSide(OperationProgress->Side),
  1153. CopyParam, Params, OperationProgress);
  1154. }
  1155. switch (Answer)
  1156. {
  1157. case qaYes:
  1158. // Can happen when moving to background (and the server manages to commit the interrupted foreground transfer).
  1159. // WebDAV does not support resumable uploads.
  1160. // Resumable downloads are not implemented.
  1161. case qaRetry:
  1162. // noop
  1163. break;
  1164. case qaNo:
  1165. throw ESkipFile();
  1166. default:
  1167. DebugFail();
  1168. case qaCancel:
  1169. OperationProgress->SetCancelAtLeast(csCancel);
  1170. Abort();
  1171. break;
  1172. }
  1173. }
  1174. //---------------------------------------------------------------------------
  1175. void __fastcall TWebDAVFileSystem::CustomCommandOnFile(const UnicodeString FileName,
  1176. const TRemoteFile * /*File*/, UnicodeString Command, int /*Params*/, TCaptureOutputEvent /*OutputEvent*/)
  1177. {
  1178. DebugFail();
  1179. }
  1180. //---------------------------------------------------------------------------
  1181. void __fastcall TWebDAVFileSystem::AnyCommand(const UnicodeString Command,
  1182. TCaptureOutputEvent /*OutputEvent*/)
  1183. {
  1184. DebugFail();
  1185. }
  1186. //---------------------------------------------------------------------------
  1187. TStrings * __fastcall TWebDAVFileSystem::GetFixedPaths()
  1188. {
  1189. return NULL;
  1190. }
  1191. //---------------------------------------------------------------------------
  1192. void TWebDAVFileSystem::NeonQuotaResult(
  1193. void * UserData, const ne_uri * /*Uri*/, const ne_prop_result_set * Results)
  1194. {
  1195. TSpaceAvailable & SpaceAvailable = *static_cast<TSpaceAvailable *>(UserData);
  1196. const char * Value = GetProp(Results, PROP_QUOTA_AVAILABLE);
  1197. if (Value != NULL)
  1198. {
  1199. SpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(StrFromNeon(Value));
  1200. const char * Value = GetProp(Results, PROP_QUOTA_USED);
  1201. if (Value != NULL)
  1202. {
  1203. SpaceAvailable.BytesAvailableToUser =
  1204. StrToInt64(StrFromNeon(Value)) + SpaceAvailable.UnusedBytesAvailableToUser;
  1205. }
  1206. }
  1207. }
  1208. //---------------------------------------------------------------------------
  1209. void __fastcall TWebDAVFileSystem::SpaceAvailable(const UnicodeString Path,
  1210. TSpaceAvailable & ASpaceAvailable)
  1211. {
  1212. // RFC4331: https://datatracker.ietf.org/doc/html/rfc4331
  1213. // This is known to be supported by:
  1214. // OpenDrive: for a root drive only (and contrary to the spec, it sends the properties
  1215. // unconditionally, even when not explicitly requested)
  1216. // Server: Apache/2.2.17 (Fedora)
  1217. // X-Powered-By: PHP/5.5.7
  1218. // X-DAV-Powered-By: OpenDrive
  1219. // WWW-Authenticate: Basic realm="PHP WebDAV"
  1220. // IT Hit WebDAV Server:
  1221. // Server: Microsoft-HTTPAPI/1.0
  1222. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1223. // Yandex disk:
  1224. // WWW-Authenticate: Basic realm="Yandex.Disk"
  1225. // Server: MochiWeb/1.0
  1226. // OneDrive:
  1227. // it sends the properties unconditionally, even when not explicitly requested
  1228. UnicodeString APath = DirectoryPath(Path);
  1229. ne_propname QuotaProps[3];
  1230. memset(QuotaProps, 0, sizeof(QuotaProps));
  1231. QuotaProps[0].nspace = DAV_PROP_NAMESPACE;
  1232. QuotaProps[0].name = PROP_QUOTA_AVAILABLE;
  1233. QuotaProps[1].nspace = DAV_PROP_NAMESPACE;
  1234. QuotaProps[1].name = PROP_QUOTA_USED;
  1235. QuotaProps[2].nspace = NULL;
  1236. QuotaProps[2].name = NULL;
  1237. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1238. CheckStatus(
  1239. ne_simple_propfind(FSessionContext->NeonSession, PathToNeon(APath), NE_DEPTH_ZERO, QuotaProps,
  1240. NeonQuotaResult, &ASpaceAvailable));
  1241. }
  1242. //---------------------------------------------------------------------------
  1243. void __fastcall TWebDAVFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1244. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1245. int Params, TFileOperationProgressType * OperationProgress,
  1246. TOnceDoneOperation & OnceDoneOperation)
  1247. {
  1248. Params &= ~cpAppend;
  1249. FTerminal->DoCopyToRemote(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfPreCreateDir, OnceDoneOperation);
  1250. }
  1251. //---------------------------------------------------------------------------
  1252. void __fastcall TWebDAVFileSystem::Source(
  1253. TLocalFileHandle & Handle, const UnicodeString & TargetDir, UnicodeString & DestFileName,
  1254. const TCopyParamType * CopyParam, int Params,
  1255. TFileOperationProgressType * OperationProgress, unsigned int /*Flags*/,
  1256. TUploadSessionAction & Action, bool & ChildError)
  1257. {
  1258. int FD = -1;
  1259. try
  1260. {
  1261. UnicodeString DestFullName = TargetDir + DestFileName;
  1262. TRemoteFile * RemoteFile = NULL;
  1263. try
  1264. {
  1265. TValueRestorer<TIgnoreAuthenticationFailure> IgnoreAuthenticationFailureRestorer(FIgnoreAuthenticationFailure);
  1266. FIgnoreAuthenticationFailure = iafWaiting;
  1267. // this should not throw
  1268. CustomReadFileInternal(DestFullName, RemoteFile, NULL);
  1269. }
  1270. catch (...)
  1271. {
  1272. if (!FTerminal->Active)
  1273. {
  1274. throw;
  1275. }
  1276. }
  1277. if (RemoteFile != NULL)
  1278. {
  1279. TOverwriteFileParams FileParams;
  1280. FileParams.SourceSize = Handle.Size;
  1281. FileParams.SourceTimestamp = Handle.Modification;
  1282. FileParams.DestSize = RemoteFile->Size;
  1283. FileParams.DestTimestamp = RemoteFile->Modification;
  1284. delete RemoteFile;
  1285. ConfirmOverwrite(Handle.FileName, DestFileName, OperationProgress,
  1286. &FileParams, CopyParam, Params);
  1287. }
  1288. DestFullName = TargetDir + DestFileName;
  1289. // only now, we know the final destination
  1290. // (not really true as we do not support changing file name on overwrite dialog)
  1291. Action.Destination(DestFullName);
  1292. FUploadMimeType = Configuration->GetFileMimeType(DestFileName);
  1293. FILE_OPERATION_LOOP_BEGIN
  1294. {
  1295. SetFilePointer(Handle.Handle, 0, NULL, FILE_BEGIN);
  1296. FD = _open_osfhandle((intptr_t)Handle.Handle, O_BINARY);
  1297. if (FD < 0) // can happen only if there are no free slots in handle-FD table
  1298. {
  1299. throw ESkipFile();
  1300. }
  1301. TAutoFlag UploadingFlag(FUploading);
  1302. ClearNeonError();
  1303. CheckStatus(ne_put(FSessionContext->NeonSession, PathToNeon(DestFullName), FD));
  1304. }
  1305. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (Handle.FileName)));
  1306. if (CopyParam->PreserveTime)
  1307. {
  1308. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1309. (StandardTimestamp(Handle.Modification))));
  1310. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Handle.Modification);
  1311. try
  1312. {
  1313. TDateTime ModificationUTC = ConvertTimestampToUTC(Handle.Modification);
  1314. TFormatSettings FormatSettings = GetEngFormatSettings();
  1315. UnicodeString LastModified =
  1316. FormatDateTime(L"ddd, d mmm yyyy hh:nn:ss 'GMT'", ModificationUTC, FormatSettings);
  1317. UTF8String NeonLastModified(LastModified);
  1318. // second element is "NULL-terminating"
  1319. ne_proppatch_operation Operations[2];
  1320. memset(Operations, 0, sizeof(Operations));
  1321. ne_propname LastModifiedProp;
  1322. LastModifiedProp.nspace = DAV_PROP_NAMESPACE;
  1323. LastModifiedProp.name = PROP_LAST_MODIFIED;
  1324. Operations[0].name = &LastModifiedProp;
  1325. Operations[0].type = ne_propset;
  1326. Operations[0].value = NeonLastModified.c_str();
  1327. int Status = ne_proppatch(FSessionContext->NeonSession, PathToNeon(DestFullName), Operations);
  1328. if (Status == NE_ERROR)
  1329. {
  1330. FTerminal->LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s",
  1331. (GetNeonError())));
  1332. // Ignore errors as major WebDAV servers (like IIS), do not support
  1333. // changing getlastmodified.
  1334. // The only server we found that supports this is TradeMicro SafeSync.
  1335. // But it announces itself as "Server: Apache",
  1336. // so it's not reliable to autodetect the support.
  1337. // Microsoft Office alegedly uses <Win32LastModifiedTime>
  1338. // https://sabre.io/dav/clients/msoffice/
  1339. // Carot DAV does that too. But we do not know what server does support this.
  1340. TouchAction.Cancel();
  1341. }
  1342. else
  1343. {
  1344. CheckStatus(Status);
  1345. }
  1346. }
  1347. catch (Exception & E)
  1348. {
  1349. TouchAction.Rollback(&E);
  1350. ChildError = true;
  1351. throw;
  1352. }
  1353. }
  1354. }
  1355. __finally
  1356. {
  1357. if (FD >= 0)
  1358. {
  1359. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1360. // but it crashes code guard
  1361. _close(FD);
  1362. Handle.Dismiss();
  1363. }
  1364. }
  1365. }
  1366. //---------------------------------------------------------------------------
  1367. void __fastcall TWebDAVFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1368. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1369. int Params, TFileOperationProgressType * OperationProgress,
  1370. TOnceDoneOperation & OnceDoneOperation)
  1371. {
  1372. Params &= ~cpAppend;
  1373. FTerminal->DoCopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfNone, OnceDoneOperation);
  1374. }
  1375. //---------------------------------------------------------------------------
  1376. void TWebDAVFileSystem::NeonCreateRequest(
  1377. ne_request * Request, void * UserData, const char * /*Method*/, const char * /*Uri*/)
  1378. {
  1379. TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
  1380. ne_set_request_private(Request, SESSION_CONTEXT_KEY, SessionContext);
  1381. ne_add_response_body_reader(Request, NeonBodyAccepter, NeonBodyReader, Request);
  1382. SessionContext->NtlmAuthenticationFailed = false;
  1383. }
  1384. //---------------------------------------------------------------------------
  1385. void TWebDAVFileSystem::NeonPreSend(
  1386. ne_request * Request, void * UserData, ne_buffer * Header)
  1387. {
  1388. TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
  1389. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1390. SessionContext->AuthorizationProtocol = EmptyStr;
  1391. UnicodeString HeaderBuf(StrFromNeon(AnsiString(Header->data, Header->used)));
  1392. const UnicodeString AuthorizationHeaderName(L"Authorization:");
  1393. int P = HeaderBuf.Pos(AuthorizationHeaderName);
  1394. if (P > 0)
  1395. {
  1396. P += AuthorizationHeaderName.Length();
  1397. int P2 = PosEx(L"\n", HeaderBuf, P);
  1398. if (DebugAlwaysTrue(P2 > 0))
  1399. {
  1400. UnicodeString AuthorizationHeader = HeaderBuf.SubString(P, P2 - P).Trim();
  1401. SessionContext->AuthorizationProtocol = CutToChar(AuthorizationHeader, L' ', false);
  1402. if (SessionContext == FileSystem->FSessionContext)
  1403. {
  1404. FileSystem->FLastAuthorizationProtocol = SessionContext->AuthorizationProtocol;
  1405. }
  1406. }
  1407. }
  1408. if (FileSystem->FDownloading)
  1409. {
  1410. // Needed by IIS server to make it download source code, not code output,
  1411. // and mainly to even allow downloading file with unregistered extensions.
  1412. // Without it files like .001 return 404 (Not found) HTTP code.
  1413. // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wdv/e37a9543-9290-4843-8c04-66457c60fa0a
  1414. // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wdvse/501879f9-3875-4d7a-ab88-3cecab440034
  1415. // It's also supported by Oracle server:
  1416. // https://docs.oracle.com/cd/E19146-01/821-1828/gczya/index.html
  1417. // We do not know yet of any server that fails when the header is used,
  1418. // so it's added unconditionally.
  1419. ne_buffer_zappend(Header, "Translate: f\r\n");
  1420. }
  1421. const UnicodeString ContentTypeHeaderPrefix(L"Content-Type: ");
  1422. if (FileSystem->FTerminal->Log->Logging)
  1423. {
  1424. const char * Buffer;
  1425. size_t Size;
  1426. if (ne_get_request_body_buffer(Request, &Buffer, &Size))
  1427. {
  1428. // all neon request types that use ne_add_request_header
  1429. // use XML content-type, so it's text-based
  1430. DebugAssert(ContainsStr(HeaderBuf, ContentTypeHeaderPrefix + NE_XML_MEDIA_TYPE));
  1431. FileSystem->FTerminal->Log->Add(llInput, UnicodeString(UTF8String(Buffer, Size)));
  1432. }
  1433. }
  1434. if (FileSystem->FUploading)
  1435. {
  1436. ne_set_request_body_provider_pre(Request, FileSystem->NeonUploadBodyProvider, SessionContext);
  1437. if (!FileSystem->FUploadMimeType.IsEmpty())
  1438. {
  1439. UnicodeString ContentTypeHeader = ContentTypeHeaderPrefix + FileSystem->FUploadMimeType + L"\r\n";
  1440. ne_buffer_zappend(Header, AnsiString(ContentTypeHeader).c_str());
  1441. }
  1442. }
  1443. FileSystem->FResponse = L"";
  1444. }
  1445. //---------------------------------------------------------------------------
  1446. int TWebDAVFileSystem::NeonPostSend(ne_request * /*Req*/, void * UserData,
  1447. const ne_status * /*Status*/)
  1448. {
  1449. TWebDAVFileSystem * FileSystem = static_cast<TSessionContext *>(UserData)->FileSystem;
  1450. if (!FileSystem->FResponse.IsEmpty())
  1451. {
  1452. FileSystem->FTerminal->Log->Add(llOutput, FileSystem->FResponse);
  1453. }
  1454. return NE_OK;
  1455. }
  1456. //---------------------------------------------------------------------------
  1457. bool __fastcall TWebDAVFileSystem::IsNtlmAuthentication(TSessionContext * SessionContext)
  1458. {
  1459. return
  1460. SameText(SessionContext->AuthorizationProtocol, L"NTLM") ||
  1461. SameText(SessionContext->AuthorizationProtocol, L"Negotiate");
  1462. }
  1463. //---------------------------------------------------------------------------
  1464. void __fastcall TWebDAVFileSystem::HttpAuthenticationFailed(TSessionContext * SessionContext)
  1465. {
  1466. // NTLM/GSSAPI failed
  1467. if (IsNtlmAuthentication(SessionContext))
  1468. {
  1469. if (SessionContext->NtlmAuthenticationFailed)
  1470. {
  1471. // Next time do not try Negotiate (NTLM/GSSAPI),
  1472. // otherwise we end up in an endless loop.
  1473. // If the server returns all other challenges in the response, removing the Negotiate
  1474. // protocol will itself ensure that other protocols are tried (we haven't seen this behaviour).
  1475. // IIS will return only Negotiate response if the request was Negotiate, so there's no fallback.
  1476. // We have to retry with a fresh request. That's what FAuthenticationRetry does.
  1477. FTerminal->LogEvent(FORMAT(L"%s challenge failed, will try different challenge", (SessionContext->AuthorizationProtocol)));
  1478. ne_remove_server_auth(SessionContext->NeonSession);
  1479. NeonAddAuthentiation(SessionContext, false);
  1480. FAuthenticationRetry = true;
  1481. }
  1482. else
  1483. {
  1484. // The first 401 is expected, the server is using it to send WWW-Authenticate header with data.
  1485. SessionContext->NtlmAuthenticationFailed = true;
  1486. }
  1487. }
  1488. }
  1489. //---------------------------------------------------------------------------
  1490. void TWebDAVFileSystem::NeonPostHeaders(ne_request * /*Req*/, void * UserData, const ne_status * Status)
  1491. {
  1492. TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
  1493. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1494. if (Status->code == HttpUnauthorized)
  1495. {
  1496. FileSystem->HttpAuthenticationFailed(SessionContext);
  1497. }
  1498. }
  1499. //---------------------------------------------------------------------------
  1500. ssize_t TWebDAVFileSystem::NeonUploadBodyProvider(void * UserData, char * /*Buffer*/, size_t /*BufLen*/)
  1501. {
  1502. TWebDAVFileSystem * FileSystem = static_cast<TSessionContext *>(UserData)->FileSystem;
  1503. ssize_t Result;
  1504. if (FileSystem->CancelTransfer())
  1505. {
  1506. Result = -1;
  1507. }
  1508. else
  1509. {
  1510. Result = 1;
  1511. }
  1512. return Result;
  1513. }
  1514. //---------------------------------------------------------------------------
  1515. static void __fastcall AddHeaderValueToList(UnicodeString & List, ne_request * Request, const char * Name)
  1516. {
  1517. const char * Value = ne_get_response_header(Request, Name);
  1518. if (Value != NULL)
  1519. {
  1520. AddToList(List, StrFromNeon(Value), L"; ");
  1521. }
  1522. }
  1523. //---------------------------------------------------------------------------
  1524. int TWebDAVFileSystem::NeonBodyAccepter(void * UserData, ne_request * Request, const ne_status * Status)
  1525. {
  1526. DebugAssert(UserData == Request);
  1527. TSessionContext * SessionContext = static_cast<TSessionContext *>(ne_get_request_private(Request, SESSION_CONTEXT_KEY));
  1528. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1529. bool AuthenticationFailureCode = (Status->code == HttpUnauthorized);
  1530. bool PasswordAuthenticationFailed = AuthenticationFailureCode && FileSystem->FAuthenticationRequested;
  1531. bool AuthenticationFailed = PasswordAuthenticationFailed || (AuthenticationFailureCode && FileSystem->IsNtlmAuthentication(SessionContext));
  1532. bool AuthenticationNeeded = AuthenticationFailureCode && !AuthenticationFailed;
  1533. if (FileSystem->FInitialHandshake)
  1534. {
  1535. UnicodeString Line;
  1536. if (AuthenticationNeeded)
  1537. {
  1538. Line = LoadStr(STATUS_AUTHENTICATE);
  1539. }
  1540. else if (AuthenticationFailed)
  1541. {
  1542. Line = LoadStr(FTP_ACCESS_DENIED);
  1543. }
  1544. else if (Status->klass == 2)
  1545. {
  1546. Line = LoadStr(STATUS_AUTHENTICATED);
  1547. }
  1548. if (!Line.IsEmpty())
  1549. {
  1550. FileSystem->FTerminal->Information(Line, true);
  1551. }
  1552. UnicodeString RemoteSystem;
  1553. // Used by IT Hit WebDAV Server:
  1554. // Server: Microsoft-HTTPAPI/1.0
  1555. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1556. AddHeaderValueToList(RemoteSystem, Request, "X-Engine");
  1557. // Used by OpenDrive:
  1558. // Server: Apache/2.2.17 (Fedora)
  1559. // X-Powered-By: PHP/5.5.7
  1560. // X-DAV-Powered-By: OpenDrive
  1561. AddHeaderValueToList(RemoteSystem, Request, "X-DAV-Powered-By");
  1562. // Used by IIS:
  1563. // Server: Microsoft-IIS/8.5
  1564. AddHeaderValueToList(RemoteSystem, Request, "Server");
  1565. // Not really useful.
  1566. // Can be e.g. "PleskLin"
  1567. AddHeaderValueToList(RemoteSystem, Request, "X-Powered-By");
  1568. FileSystem->FFileSystemInfo.RemoteSystem = RemoteSystem;
  1569. }
  1570. // When we explicitly fail authentication of request
  1571. // with FIgnoreAuthenticationFailure flag (after it failed with password),
  1572. // neon resets its internal password store and tries the next request
  1573. // without calling our authentication hook first
  1574. // (note AuthenticationFailed vs. AuthenticationNeeded)
  1575. // what likely fails, but we do not want to reset out password
  1576. // (as it was not even tried yet for this request).
  1577. if (PasswordAuthenticationFailed)
  1578. {
  1579. if (FileSystem->FIgnoreAuthenticationFailure == iafNo)
  1580. {
  1581. FileSystem->FPassword = RawByteString();
  1582. }
  1583. else
  1584. {
  1585. FileSystem->FIgnoreAuthenticationFailure = iafPasswordFailed;
  1586. }
  1587. }
  1588. return ne_accept_2xx(UserData, Request, Status);
  1589. }
  1590. //---------------------------------------------------------------------------
  1591. bool __fastcall TWebDAVFileSystem::CancelTransfer()
  1592. {
  1593. bool Result = false;
  1594. if ((FUploading || FDownloading) &&
  1595. (FTerminal->OperationProgress != NULL) &&
  1596. (FTerminal->OperationProgress->Cancel != csContinue))
  1597. {
  1598. if (FTerminal->OperationProgress->ClearCancelFile())
  1599. {
  1600. FSkipped = true;
  1601. }
  1602. else
  1603. {
  1604. FCancelled = true;
  1605. }
  1606. Result = true;
  1607. }
  1608. return Result;
  1609. }
  1610. //---------------------------------------------------------------------------
  1611. int TWebDAVFileSystem::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  1612. {
  1613. ne_request * Request = static_cast<ne_request *>(UserData);
  1614. TSessionContext * SessionContext = static_cast<TSessionContext *>(ne_get_request_private(Request, SESSION_CONTEXT_KEY));
  1615. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1616. if (FileSystem->FTerminal->Log->Logging)
  1617. {
  1618. ne_content_type ContentType;
  1619. if (ne_get_content_type(Request, &ContentType) == 0)
  1620. {
  1621. // The main point of the content-type check was to exclude
  1622. // GET responses (with file contents).
  1623. // But this won't work when downloading text files that have text
  1624. // content type on their own, hence the additional not-downloading test.
  1625. if (!FileSystem->FDownloading &&
  1626. ((ne_strcasecmp(ContentType.type, "text") == 0) ||
  1627. media_type_is_xml(&ContentType)))
  1628. {
  1629. UnicodeString Content = UnicodeString(UTF8String(Buf, Len)).Trim();
  1630. FileSystem->FResponse += Content;
  1631. }
  1632. ne_free(ContentType.value);
  1633. }
  1634. }
  1635. int Result = FileSystem->CancelTransfer() ? 1 : 0;
  1636. return Result;
  1637. }
  1638. //---------------------------------------------------------------------------
  1639. void __fastcall TWebDAVFileSystem::Sink(
  1640. const UnicodeString & FileName, const TRemoteFile * File,
  1641. const UnicodeString & TargetDir, UnicodeString & DestFileName, int Attrs,
  1642. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  1643. unsigned int /*Flags*/, TDownloadSessionAction & Action)
  1644. {
  1645. UnicodeString DestFullName = TargetDir + DestFileName;
  1646. if (FileExists(ApiPath(DestFullName)))
  1647. {
  1648. __int64 Size;
  1649. __int64 MTime;
  1650. FTerminal->OpenLocalFile(DestFullName, GENERIC_READ, NULL, NULL, NULL, &MTime, NULL, &Size);
  1651. TOverwriteFileParams FileParams;
  1652. FileParams.SourceSize = File->Size;
  1653. FileParams.SourceTimestamp = File->Modification;
  1654. FileParams.DestSize = Size;
  1655. FileParams.DestTimestamp = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  1656. ConfirmOverwrite(FileName, DestFileName, OperationProgress, &FileParams, CopyParam, Params);
  1657. }
  1658. UnicodeString ExpandedDestFullName = ExpandUNCFileName(DestFullName);
  1659. Action.Destination(ExpandedDestFullName);
  1660. FILE_OPERATION_LOOP_BEGIN
  1661. {
  1662. HANDLE LocalHandle;
  1663. if (!FTerminal->CreateLocalFile(DestFullName, OperationProgress, &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  1664. {
  1665. throw ESkipFile();
  1666. }
  1667. bool DeleteLocalFile = true;
  1668. int FD = -1;
  1669. try
  1670. {
  1671. FD = _open_osfhandle((intptr_t)LocalHandle, O_BINARY);
  1672. if (FD < 0)
  1673. {
  1674. throw ESkipFile();
  1675. }
  1676. TAutoFlag DownloadingFlag(FDownloading);
  1677. ClearNeonError();
  1678. int NeonStatus = ne_get(FSessionContext->NeonSession, PathToNeon(FileName), FD);
  1679. // Contrary to other actions, for "GET" we support any redirect
  1680. if (IsRedirect(NeonStatus))
  1681. {
  1682. UnicodeString CorrectedUrl = GetRedirectUrl();
  1683. UTF8String CorrectedFileName, Query;
  1684. std::unique_ptr<TSessionContext> CorrectedSessionContext(NeonOpen(CorrectedUrl, CorrectedFileName, Query));
  1685. UTF8String RedirectUrl = CorrectedFileName;
  1686. if (!Query.IsEmpty())
  1687. {
  1688. RedirectUrl += L"?" + Query;
  1689. }
  1690. NeonStatus = ne_get(CorrectedSessionContext->NeonSession, RedirectUrl.c_str(), FD);
  1691. CheckStatus(CorrectedSessionContext.get(), NeonStatus);
  1692. }
  1693. else
  1694. {
  1695. CheckStatus(NeonStatus);
  1696. }
  1697. DeleteLocalFile = false;
  1698. if (CopyParam->PreserveTime)
  1699. {
  1700. FTerminal->UpdateTargetTime(
  1701. LocalHandle, File->Modification, File->ModificationFmt, FTerminal->SessionData->DSTMode);
  1702. }
  1703. }
  1704. __finally
  1705. {
  1706. if (FD >= 0)
  1707. {
  1708. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1709. // but it crashes code guard
  1710. _close(FD);
  1711. }
  1712. else
  1713. {
  1714. CloseHandle(LocalHandle);
  1715. }
  1716. if (DeleteLocalFile)
  1717. {
  1718. FTerminal->DoDeleteLocalFile(DestFullName);
  1719. }
  1720. }
  1721. }
  1722. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1723. FTerminal->UpdateTargetAttrs(DestFullName, File, CopyParam, Attrs);
  1724. }
  1725. //---------------------------------------------------------------------------
  1726. bool TWebDAVFileSystem::VerifyCertificate(TSessionContext * SessionContext, TNeonCertificateData Data, bool Aux)
  1727. {
  1728. bool Result =
  1729. FTerminal->VerifyOrConfirmHttpCertificate(
  1730. SessionContext->HostName, SessionContext->PortNumber, Data, !Aux, FSessionInfo);
  1731. if (Result && !Aux && (SessionContext == FSessionContext))
  1732. {
  1733. CollectTLSSessionInfo();
  1734. }
  1735. return Result;
  1736. }
  1737. //------------------------------------------------------------------------------
  1738. void __fastcall TWebDAVFileSystem::CollectTLSSessionInfo()
  1739. {
  1740. // See also TFTPFileSystem::Open().
  1741. // Have to cache the value as the connection (the neon HTTP session, not "our" session)
  1742. // can be closed at the time we need it in CollectUsage().
  1743. UnicodeString Message = NeonTlsSessionInfo(FSessionContext->NeonSession, FSessionInfo, FTlsVersionStr);
  1744. FTerminal->LogEvent(0, Message);
  1745. }
  1746. //------------------------------------------------------------------------------
  1747. // A neon-session callback to validate the SSL certificate when the CA
  1748. // is unknown (e.g. a self-signed cert), or there are other SSL
  1749. // certificate problems.
  1750. int TWebDAVFileSystem::DoNeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate, bool Aux)
  1751. {
  1752. TNeonCertificateData Data;
  1753. RetrieveNeonCertificateData(Failures, Certificate, Data);
  1754. TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
  1755. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1756. return FileSystem->VerifyCertificate(SessionContext, Data, Aux) ? NE_OK : NE_ERROR;
  1757. }
  1758. //------------------------------------------------------------------------------
  1759. int TWebDAVFileSystem::NeonServerSSLCallbackMain(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  1760. {
  1761. return DoNeonServerSSLCallback(UserData, Failures, Certificate, false);
  1762. }
  1763. //------------------------------------------------------------------------------
  1764. int TWebDAVFileSystem::NeonServerSSLCallbackAux(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  1765. {
  1766. return DoNeonServerSSLCallback(UserData, Failures, Certificate, true);
  1767. }
  1768. //------------------------------------------------------------------------------
  1769. void TWebDAVFileSystem::NeonProvideClientCert(void * UserData, ne_session * Sess,
  1770. const ne_ssl_dname * const * /*DNames*/, int /*DNCount*/)
  1771. {
  1772. TWebDAVFileSystem * FileSystem = static_cast<TSessionContext *>(UserData)->FileSystem;
  1773. FileSystem->FTerminal->LogEvent(LoadStr(NEED_CLIENT_CERTIFICATE));
  1774. X509 * Certificate;
  1775. EVP_PKEY * PrivateKey;
  1776. if (FileSystem->FTerminal->LoadTlsCertificate(Certificate, PrivateKey))
  1777. {
  1778. ne_ssl_client_cert * NeonCertificate = ne_ssl_clicert_create(Certificate, PrivateKey);
  1779. ne_ssl_set_clicert(Sess, NeonCertificate);
  1780. ne_ssl_clicert_free(NeonCertificate);
  1781. }
  1782. }
  1783. //------------------------------------------------------------------------------
  1784. int TWebDAVFileSystem::NeonRequestAuth(
  1785. void * UserData, const char * Realm, int Attempt, char * UserName, char * Password)
  1786. {
  1787. DebugUsedParam(Realm);
  1788. DebugUsedParam(Attempt);
  1789. TWebDAVFileSystem * FileSystem = static_cast<TSessionContext *>(UserData)->FileSystem;
  1790. TTerminal * Terminal = FileSystem->FTerminal;
  1791. TSessionData * SessionData = Terminal->SessionData;
  1792. bool Result = true;
  1793. // will ask for username only once
  1794. if (FileSystem->FUserName.IsEmpty())
  1795. {
  1796. if (!SessionData->UserName.IsEmpty())
  1797. {
  1798. FileSystem->FUserName = SessionData->UserNameExpanded;
  1799. }
  1800. else
  1801. {
  1802. Terminal->LogEvent(L"Username prompt");
  1803. if (!Terminal->PromptUser(SessionData, pkUserName, LoadStr(USERNAME_TITLE), L"",
  1804. LoadStr(USERNAME_PROMPT2), true, NE_ABUFSIZ, FileSystem->FUserName))
  1805. {
  1806. Result = false;
  1807. }
  1808. }
  1809. }
  1810. UnicodeString APassword;
  1811. if (Result)
  1812. {
  1813. // Some servers (Gallery2 on discontinued g2.pixi.me)
  1814. // return authentication error (401) on PROPFIND request for
  1815. // non-existing files.
  1816. // When we already tried password before, do not try anymore.
  1817. // When we did not try password before (possible only when
  1818. // server does not require authentication for any previous request,
  1819. // such as when read access is not authenticated), try it now,
  1820. // but use special flag for the try, because when it fails
  1821. // we still want to try password for future requests (such as PUT).
  1822. if (!FileSystem->FPassword.IsEmpty())
  1823. {
  1824. if (FileSystem->FIgnoreAuthenticationFailure == iafPasswordFailed)
  1825. {
  1826. // Fail PROPFIND /nonexisting request...
  1827. Result = false;
  1828. }
  1829. else
  1830. {
  1831. APassword = Terminal->DecryptPassword(FileSystem->FPassword);
  1832. }
  1833. }
  1834. else
  1835. {
  1836. if (!SessionData->Password.IsEmpty() && !FileSystem->FStoredPasswordTried)
  1837. {
  1838. APassword = NormalizeString(SessionData->Password);
  1839. FileSystem->FStoredPasswordTried = true;
  1840. }
  1841. else
  1842. {
  1843. // Asking for password (or using configured password) the first time,
  1844. // and asking for password.
  1845. Terminal->LogEvent(L"Password prompt");
  1846. Result =
  1847. Terminal->PromptUser(
  1848. SessionData, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  1849. LoadStr(PASSWORD_PROMPT), false, NE_ABUFSIZ, APassword);
  1850. }
  1851. if (Result)
  1852. {
  1853. // While neon remembers the password on its own,
  1854. // we need to keep a copy in case neon store gets reset by
  1855. // 401 response to PROPFIND /nonexisting on G2, see above.
  1856. // Possibly we can do this for G2 servers only.
  1857. FileSystem->FPassword = Terminal->EncryptPassword(APassword);
  1858. }
  1859. }
  1860. }
  1861. if (Result)
  1862. {
  1863. strncpy(UserName, StrToNeon(FileSystem->FUserName), NE_ABUFSIZ);
  1864. strncpy(Password, StrToNeon(APassword), NE_ABUFSIZ);
  1865. }
  1866. FileSystem->FAuthenticationRequested = true;
  1867. return Result ? 0 : -1;
  1868. }
  1869. //------------------------------------------------------------------------------
  1870. void TWebDAVFileSystem::NeonNotifier(void * UserData, ne_session_status Status, const ne_session_status_info * StatusInfo)
  1871. {
  1872. TWebDAVFileSystem * FileSystem = static_cast<TSessionContext *>(UserData)->FileSystem;
  1873. TFileOperationProgressType * OperationProgress = FileSystem->FTerminal->OperationProgress;
  1874. // We particularly have to filter out response to "put" request,
  1875. // handling that would reset the upload progress back to low number (response is small).
  1876. if (((FileSystem->FUploading && (Status == ne_status_sending)) ||
  1877. (FileSystem->FDownloading && (Status == ne_status_recving))) &&
  1878. DebugAlwaysTrue(OperationProgress != NULL))
  1879. {
  1880. __int64 Progress = StatusInfo->sr.progress;
  1881. __int64 Diff = Progress - OperationProgress->TransferredSize;
  1882. if (Diff > 0)
  1883. {
  1884. OperationProgress->ThrottleToCPSLimit(static_cast<unsigned long>(Diff));
  1885. }
  1886. __int64 Total = StatusInfo->sr.total;
  1887. // Total size unknown
  1888. if (Total < 0)
  1889. {
  1890. if (Diff >= 0)
  1891. {
  1892. OperationProgress->AddTransferred(Diff);
  1893. }
  1894. else
  1895. {
  1896. // Session total has been reset. A new stream started
  1897. OperationProgress->AddTransferred(Progress);
  1898. }
  1899. }
  1900. else
  1901. {
  1902. OperationProgress->SetTransferSize(Total);
  1903. OperationProgress->AddTransferred(Diff);
  1904. }
  1905. }
  1906. }
  1907. //------------------------------------------------------------------------------
  1908. void TWebDAVFileSystem::InitSslSession(ssl_st * Ssl, ne_session * /*Session*/)
  1909. {
  1910. SetupSsl(Ssl, FTerminal->SessionData->MinTlsVersion, FTerminal->SessionData->MaxTlsVersion);
  1911. }
  1912. //---------------------------------------------------------------------------
  1913. void __fastcall TWebDAVFileSystem::GetSupportedChecksumAlgs(TStrings * /*Algs*/)
  1914. {
  1915. // NOOP
  1916. }
  1917. //---------------------------------------------------------------------------
  1918. void __fastcall TWebDAVFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * File)
  1919. {
  1920. ClearNeonError();
  1921. struct ne_lock * Lock = ne_lock_create();
  1922. try
  1923. {
  1924. Lock->uri.path = ne_strdup(PathToNeon(FilePath(File)));
  1925. Lock->depth = NE_DEPTH_INFINITE;
  1926. Lock->timeout = NE_TIMEOUT_INFINITE;
  1927. Lock->owner = ne_strdup(StrToNeon(FTerminal->UserName));
  1928. CheckStatus(ne_lock(FSessionContext->NeonSession, Lock));
  1929. {
  1930. TGuard Guard(FNeonLockStoreSection);
  1931. RequireLockStore();
  1932. ne_lockstore_add(FNeonLockStore, Lock);
  1933. }
  1934. // ownership passed
  1935. Lock = NULL;
  1936. }
  1937. __finally
  1938. {
  1939. if (Lock != NULL)
  1940. {
  1941. ne_lock_destroy(Lock);
  1942. }
  1943. }
  1944. }
  1945. //---------------------------------------------------------------------------
  1946. void __fastcall TWebDAVFileSystem::RequireLockStore()
  1947. {
  1948. // Create store only when needed,
  1949. // to limit the use of cross-thread code in UpdateFromMain
  1950. if (FNeonLockStore == NULL)
  1951. {
  1952. FNeonLockStore = ne_lockstore_create();
  1953. ne_lockstore_register(FNeonLockStore, FSessionContext->NeonSession);
  1954. }
  1955. }
  1956. //---------------------------------------------------------------------------
  1957. void TWebDAVFileSystem::LockResult(void * UserData, const struct ne_lock * Lock,
  1958. const ne_uri * /*Uri*/, const ne_status * /*Status*/)
  1959. {
  1960. // Is NULL on failure (Status is not NULL then)
  1961. if (Lock != NULL)
  1962. {
  1963. RawByteString & LockToken = *static_cast<RawByteString *>(UserData);
  1964. LockToken = Lock->token;
  1965. }
  1966. }
  1967. //---------------------------------------------------------------------------
  1968. struct ne_lock * __fastcall TWebDAVFileSystem::FindLock(const RawByteString & Path)
  1969. {
  1970. ne_uri Uri = {0};
  1971. Uri.path = Path.c_str();
  1972. return ne_lockstore_findbyuri(FNeonLockStore, &Uri);
  1973. }
  1974. //---------------------------------------------------------------------------
  1975. void __fastcall TWebDAVFileSystem::DiscardLock(const RawByteString & Path)
  1976. {
  1977. TGuard Guard(FNeonLockStoreSection);
  1978. if (FNeonLockStore != NULL)
  1979. {
  1980. struct ne_lock * Lock = FindLock(Path);
  1981. if (Lock != NULL)
  1982. {
  1983. ne_lockstore_remove(FNeonLockStore, Lock);
  1984. }
  1985. }
  1986. }
  1987. //---------------------------------------------------------------------------
  1988. void __fastcall TWebDAVFileSystem::UnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  1989. {
  1990. ClearNeonError();
  1991. struct ne_lock * Lock = ne_lock_create();
  1992. try
  1993. {
  1994. RawByteString Path = PathToNeon(FilePath(File));
  1995. RawByteString LockToken;
  1996. struct ne_lock * Lock = NULL;
  1997. {
  1998. TGuard Guard(FNeonLockStoreSection);
  1999. if (FNeonLockStore != NULL)
  2000. {
  2001. Lock = FindLock(Path);
  2002. }
  2003. }
  2004. // we are not aware of the file being locked,
  2005. // though it can be locked from another (previous and already closed)
  2006. // session, so query the server.
  2007. if (Lock == NULL)
  2008. {
  2009. CheckStatus(ne_lock_discover(FSessionContext->NeonSession, Path.c_str(), LockResult, &LockToken));
  2010. }
  2011. if ((Lock == NULL) && (LockToken.IsEmpty()))
  2012. {
  2013. throw Exception(FMTLOAD(NOT_LOCKED, (FileName)));
  2014. }
  2015. else
  2016. {
  2017. struct ne_lock * Unlock;
  2018. if (Lock == NULL)
  2019. {
  2020. DebugAssert(!LockToken.IsEmpty());
  2021. Unlock = ne_lock_create();
  2022. Unlock->uri.path = ne_strdup(Path.c_str());
  2023. Unlock->token = ne_strdup(LockToken.c_str());
  2024. }
  2025. else
  2026. {
  2027. Unlock = Lock;
  2028. }
  2029. CheckStatus(ne_unlock(FSessionContext->NeonSession, Unlock));
  2030. DiscardLock(Path);
  2031. }
  2032. }
  2033. __finally
  2034. {
  2035. ne_lock_destroy(Lock);
  2036. }
  2037. }
  2038. //---------------------------------------------------------------------------
  2039. void __fastcall TWebDAVFileSystem::UpdateFromMain(TCustomFileSystem * AMainFileSystem)
  2040. {
  2041. TWebDAVFileSystem * MainFileSystem = dynamic_cast<TWebDAVFileSystem *>(AMainFileSystem);
  2042. if (DebugAlwaysTrue(MainFileSystem != NULL))
  2043. {
  2044. TGuard Guard(FNeonLockStoreSection);
  2045. TGuard MainGuard(MainFileSystem->FNeonLockStoreSection);
  2046. if (FNeonLockStore != NULL)
  2047. {
  2048. struct ne_lock * Lock;
  2049. while ((Lock = ne_lockstore_first(FNeonLockStore)) != NULL)
  2050. {
  2051. ne_lockstore_remove(FNeonLockStore, Lock);
  2052. }
  2053. }
  2054. if (MainFileSystem->FNeonLockStore != NULL)
  2055. {
  2056. RequireLockStore();
  2057. struct ne_lock * Lock = ne_lockstore_first(MainFileSystem->FNeonLockStore);
  2058. while (Lock != NULL)
  2059. {
  2060. ne_lockstore_add(FNeonLockStore, ne_lock_copy(Lock));
  2061. Lock = ne_lockstore_next(MainFileSystem->FNeonLockStore);
  2062. }
  2063. }
  2064. }
  2065. }
  2066. //------------------------------------------------------------------------------
  2067. void __fastcall TWebDAVFileSystem::ClearCaches()
  2068. {
  2069. // noop
  2070. }
  2071. //---------------------------------------------------------------------------