WebDAVFileSystem.cpp 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231
  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;
  258. DebugAssert(FSessionContext == NULL);
  259. FSessionContext = NeonOpen(Url, Path);
  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. SetNeonTlsInit(Session, InitSslSession);
  287. // When the CA certificate or server certificate has
  288. // verification problems, neon will call our verify function before
  289. // outright rejection of the connection.
  290. ne_ssl_verify_fn Callback = Aux ? NeonServerSSLCallbackAux : NeonServerSSLCallbackMain;
  291. ne_ssl_set_verify(Session, Callback, SessionContext);
  292. ne_ssl_trust_default_ca(Session);
  293. }
  294. //---------------------------------------------------------------------------
  295. void __fastcall TWebDAVFileSystem::InitSession(TSessionContext * SessionContext, ne_session_s * Session)
  296. {
  297. TSessionData * Data = FTerminal->SessionData;
  298. InitNeonSession(
  299. Session, Data->ProxyMethod, Data->ProxyHost, Data->ProxyPort,
  300. Data->ProxyUsername, Data->ProxyPassword, FTerminal);
  301. ne_set_read_timeout(Session, Data->Timeout);
  302. ne_set_connect_timeout(Session, Data->Timeout);
  303. ne_set_session_private(Session, SESSION_CONTEXT_KEY, SessionContext);
  304. // Allow ^-escaping in OneDrive
  305. ne_set_session_flag(Session, NE_SESSFLAG_LIBERAL_ESCAPING, Data->WebDavLiberalEscaping || FOneDrive);
  306. }
  307. //---------------------------------------------------------------------------
  308. TWebDAVFileSystem::TSessionContext * TWebDAVFileSystem::NeonOpen(const UnicodeString & Url, UTF8String & Path)
  309. {
  310. ne_uri uri;
  311. NeonParseUrl(Url, uri);
  312. std::unique_ptr<TSessionContext> Result(new TSessionContext());
  313. Result->FileSystem = this;
  314. Result->HostName = StrFromNeon(uri.host);
  315. Result->PortNumber = uri.port;
  316. Result->NtlmAuthenticationFailed = false;
  317. Result->NeonSession = CreateNeonSession(uri);
  318. InitSession(Result.get(), Result->NeonSession);
  319. Path = uri.path;
  320. bool Ssl = IsTlsUri(uri);
  321. ne_uri_free(&uri);
  322. ne_set_aux_request_init(Result->NeonSession, NeonAuxRequestInit, Result.get());
  323. UpdateNeonDebugMask();
  324. NeonAddAuthentiation(Result.get(), Ssl);
  325. if (Ssl)
  326. {
  327. SetSessionTls(Result.get(), Result->NeonSession, false);
  328. ne_ssl_provide_clicert(Result->NeonSession, NeonProvideClientCert, Result.get());
  329. }
  330. ne_set_notifier(Result->NeonSession, NeonNotifier, Result.get());
  331. ne_hook_create_request(Result->NeonSession, NeonCreateRequest, Result.get());
  332. ne_hook_pre_send(Result->NeonSession, NeonPreSend, Result.get());
  333. ne_hook_post_send(Result->NeonSession, NeonPostSend, Result.get());
  334. ne_hook_post_headers(Result->NeonSession, NeonPostHeaders, Result.get());
  335. return Result.release();
  336. }
  337. //---------------------------------------------------------------------------
  338. bool TWebDAVFileSystem::IsTlsSession(ne_session * Session)
  339. {
  340. ne_uri uri = {0};
  341. ne_fill_server_uri(Session, &uri);
  342. bool Result = IsTlsUri(uri);
  343. ne_uri_free(&uri);
  344. return Result;
  345. }
  346. //---------------------------------------------------------------------------
  347. void TWebDAVFileSystem::NeonAuxRequestInit(ne_session * Session, ne_request * /*Request*/, void * UserData)
  348. {
  349. TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
  350. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  351. FileSystem->InitSession(SessionContext, Session);
  352. if (FileSystem->IsTlsSession(Session))
  353. {
  354. FileSystem->SetSessionTls(SessionContext, Session, true);
  355. }
  356. }
  357. //---------------------------------------------------------------------------
  358. void __fastcall TWebDAVFileSystem::NeonAddAuthentiation(TSessionContext * SessionContext, bool UseNegotiate)
  359. {
  360. unsigned int NeonAuthTypes = NE_AUTH_BASIC | NE_AUTH_DIGEST | NE_AUTH_PASSPORT;
  361. if (UseNegotiate)
  362. {
  363. NeonAuthTypes |= NE_AUTH_NEGOTIATE;
  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. UnicodeString RemoteSystem = FFileSystemInfo.RemoteSystem;
  466. if (ContainsText(RemoteSystem, L"Microsoft-IIS"))
  467. {
  468. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVIIS");
  469. }
  470. else if (ContainsText(RemoteSystem, L"IT Hit WebDAV Server"))
  471. {
  472. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVITHit");
  473. }
  474. // e.g. brickftp.com
  475. else if (ContainsText(RemoteSystem, L"nginx"))
  476. {
  477. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVNginx");
  478. }
  479. else
  480. {
  481. // We also know OpenDrive, Yandex, iFiles (iOS), Swapper (iOS), SafeSync
  482. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVOther");
  483. }
  484. }
  485. //---------------------------------------------------------------------------
  486. const TSessionInfo & __fastcall TWebDAVFileSystem::GetSessionInfo()
  487. {
  488. return FSessionInfo;
  489. }
  490. //---------------------------------------------------------------------------
  491. const TFileSystemInfo & __fastcall TWebDAVFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  492. {
  493. return FFileSystemInfo;
  494. }
  495. //---------------------------------------------------------------------------
  496. bool __fastcall TWebDAVFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
  497. {
  498. return false;
  499. }
  500. //---------------------------------------------------------------------------
  501. bool __fastcall TWebDAVFileSystem::GetStoredCredentialsTried()
  502. {
  503. return FStoredPasswordTried;
  504. }
  505. //---------------------------------------------------------------------------
  506. UnicodeString __fastcall TWebDAVFileSystem::GetUserName()
  507. {
  508. return FUserName;
  509. }
  510. //---------------------------------------------------------------------------
  511. void __fastcall TWebDAVFileSystem::Idle()
  512. {
  513. // noop
  514. }
  515. //---------------------------------------------------------------------------
  516. UnicodeString __fastcall TWebDAVFileSystem::AbsolutePath(const UnicodeString Path, bool /*Local*/)
  517. {
  518. bool AddTrailingBackslash;
  519. if (Path == L"/")
  520. {
  521. // does not really matter as path "/" is still "/" when absolute,
  522. // no slash needed
  523. AddTrailingBackslash = FHasTrailingSlash;
  524. }
  525. else
  526. {
  527. AddTrailingBackslash = (Path[Path.Length()] == L'/');
  528. }
  529. UnicodeString Result = ::AbsolutePath(GetCurrentDirectory(), Path);
  530. // We must preserve trailing slash, because particularly for mod_dav,
  531. // it really matters if the slash in there or not
  532. if (AddTrailingBackslash)
  533. {
  534. Result = UnixIncludeTrailingBackslash(Result);
  535. }
  536. return Result;
  537. }
  538. //---------------------------------------------------------------------------
  539. bool __fastcall TWebDAVFileSystem::IsCapable(int Capability) const
  540. {
  541. DebugAssert(FTerminal);
  542. switch (Capability)
  543. {
  544. case fcRename:
  545. case fcRemoteMove:
  546. case fcMoveToQueue:
  547. case fcPreservingTimestampUpload:
  548. case fcCheckingSpaceAvailable:
  549. // Only to make double-click on file edit/open the file,
  550. // instead of trying to open it as directory
  551. case fcResolveSymlink:
  552. case fcSkipTransfer:
  553. case fcParallelTransfers:
  554. case fcRemoteCopy:
  555. return true;
  556. case fcUserGroupListing:
  557. case fcModeChanging:
  558. case fcModeChangingUpload:
  559. case fcAclChangingFiles:
  560. case fcGroupChanging:
  561. case fcOwnerChanging:
  562. case fcAnyCommand:
  563. case fcShellAnyCommand:
  564. case fcHardLink:
  565. case fcSymbolicLink:
  566. case fcTextMode:
  567. case fcNativeTextMode:
  568. case fcNewerOnlyUpload:
  569. case fcTimestampChanging:
  570. case fcLoadingAdditionalProperties:
  571. case fcIgnorePermErrors:
  572. case fcCalculatingChecksum:
  573. case fcSecondaryShell:
  574. case fcGroupOwnerChangingByID:
  575. case fcRemoveCtrlZUpload:
  576. case fcRemoveBOMUpload:
  577. case fcPreservingTimestampDirs:
  578. case fcResumeSupport:
  579. case fcChangePassword:
  580. case fcTransferOut:
  581. case fcTransferIn:
  582. return false;
  583. case fcLocking:
  584. return FLAGSET(FCapabilities, NE_CAP_DAV_CLASS2);
  585. default:
  586. DebugFail();
  587. return false;
  588. }
  589. }
  590. //---------------------------------------------------------------------------
  591. UnicodeString __fastcall TWebDAVFileSystem::GetCurrentDirectory()
  592. {
  593. return FCurrentDirectory;
  594. }
  595. //---------------------------------------------------------------------------
  596. void __fastcall TWebDAVFileSystem::DoStartup()
  597. {
  598. FTerminal->SetExceptionOnFail(true);
  599. // retrieve initialize working directory to save it as home directory
  600. ReadCurrentDirectory();
  601. FTerminal->SetExceptionOnFail(false);
  602. }
  603. //---------------------------------------------------------------------------
  604. void __fastcall TWebDAVFileSystem::ClearNeonError()
  605. {
  606. FCancelled = false;
  607. FSkipped = false;
  608. FAuthenticationRequested = false;
  609. ne_set_error(FSessionContext->NeonSession, "");
  610. }
  611. //---------------------------------------------------------------------------
  612. UnicodeString __fastcall TWebDAVFileSystem::GetNeonError()
  613. {
  614. return ::GetNeonError(FSessionContext->NeonSession);
  615. }
  616. //---------------------------------------------------------------------------
  617. void TWebDAVFileSystem::CheckStatus(int NeonStatus)
  618. {
  619. CheckStatus(FSessionContext, NeonStatus);
  620. }
  621. //---------------------------------------------------------------------------
  622. void TWebDAVFileSystem::CheckStatus(TSessionContext * SessionContext, int NeonStatus)
  623. {
  624. if ((NeonStatus == NE_ERROR) && (FCancelled || FSkipped))
  625. {
  626. if (FCancelled)
  627. {
  628. FCancelled = false;
  629. FSkipped = false; // just in case
  630. Abort();
  631. }
  632. else
  633. {
  634. DebugAssert(FSkipped);
  635. FSkipped = false;
  636. throw ESkipFile();
  637. }
  638. }
  639. else
  640. {
  641. CheckNeonStatus(SessionContext->NeonSession, NeonStatus, SessionContext->HostName);
  642. }
  643. }
  644. //---------------------------------------------------------------------------
  645. void __fastcall TWebDAVFileSystem::LookupUsersGroups()
  646. {
  647. DebugFail();
  648. }
  649. //---------------------------------------------------------------------------
  650. void __fastcall TWebDAVFileSystem::ReadCurrentDirectory()
  651. {
  652. if (FCachedDirectoryChange.IsEmpty())
  653. {
  654. FCurrentDirectory = FCurrentDirectory.IsEmpty() ? UnicodeString(L"/") : FCurrentDirectory;
  655. }
  656. else
  657. {
  658. FCurrentDirectory = FCachedDirectoryChange;
  659. FCachedDirectoryChange = L"";
  660. }
  661. }
  662. //---------------------------------------------------------------------------
  663. void __fastcall TWebDAVFileSystem::HomeDirectory()
  664. {
  665. ChangeDirectory(L"/");
  666. }
  667. //---------------------------------------------------------------------------
  668. UnicodeString __fastcall TWebDAVFileSystem::DirectoryPath(UnicodeString Path)
  669. {
  670. if (FHasTrailingSlash)
  671. {
  672. Path = ::UnixIncludeTrailingBackslash(Path);
  673. }
  674. return Path;
  675. }
  676. //---------------------------------------------------------------------------
  677. UnicodeString __fastcall TWebDAVFileSystem::FilePath(const TRemoteFile * File)
  678. {
  679. UnicodeString Result = File->FullFileName;
  680. if (File->IsDirectory)
  681. {
  682. Result = DirectoryPath(Result);
  683. }
  684. return Result;
  685. }
  686. //---------------------------------------------------------------------------
  687. void __fastcall TWebDAVFileSystem::TryOpenDirectory(UnicodeString Directory)
  688. {
  689. Directory = DirectoryPath(Directory);
  690. FTerminal->LogEvent(FORMAT(L"Trying to open directory \"%s\".", (Directory)));
  691. TRemoteFile * File;
  692. ReadFile(Directory, File);
  693. delete File;
  694. }
  695. //---------------------------------------------------------------------------
  696. void __fastcall TWebDAVFileSystem::AnnounceFileListOperation()
  697. {
  698. // noop
  699. }
  700. //---------------------------------------------------------------------------
  701. void __fastcall TWebDAVFileSystem::ChangeDirectory(const UnicodeString ADirectory)
  702. {
  703. UnicodeString Path = AbsolutePath(ADirectory, false);
  704. // to verify existence of directory try to open it
  705. TryOpenDirectory(Path);
  706. // if open dir did not fail, directory exists -> success.
  707. FCachedDirectoryChange = Path;
  708. }
  709. //---------------------------------------------------------------------------
  710. void __fastcall TWebDAVFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  711. {
  712. FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
  713. }
  714. //---------------------------------------------------------------------------
  715. struct TReadFileData
  716. {
  717. TWebDAVFileSystem * FileSystem;
  718. TRemoteFile * File;
  719. TRemoteFileList * FileList;
  720. };
  721. //---------------------------------------------------------------------------
  722. int __fastcall TWebDAVFileSystem::ReadDirectoryInternal(
  723. const UnicodeString & Path, TRemoteFileList * FileList)
  724. {
  725. TReadFileData Data;
  726. Data.FileSystem = this;
  727. Data.File = NULL;
  728. Data.FileList = FileList;
  729. ClearNeonError();
  730. ne_propfind_handler * PropFindHandler = ne_propfind_create(FSessionContext->NeonSession, PathToNeon(Path), NE_DEPTH_ONE);
  731. void * DiscoveryContext = ne_lock_register_discovery(PropFindHandler);
  732. int Result;
  733. try
  734. {
  735. Result = ne_propfind_allprop(PropFindHandler, NeonPropsResult, &Data);
  736. }
  737. __finally
  738. {
  739. ne_lock_discovery_free(DiscoveryContext);
  740. ne_propfind_destroy(PropFindHandler);
  741. }
  742. return Result;
  743. }
  744. //---------------------------------------------------------------------------
  745. bool __fastcall TWebDAVFileSystem::IsValidRedirect(int NeonStatus, UnicodeString & Path)
  746. {
  747. bool Result = (NeonStatus == NE_REDIRECT);
  748. if (Result)
  749. {
  750. // What PathToNeon does
  751. UnicodeString OriginalPath = AbsolutePath(Path, false);
  752. // Handle one-step redirect
  753. // (for more steps we would have to implement loop detection).
  754. // This is mainly to handle "folder" => "folder/" redirects of Apache/mod_dav.
  755. UnicodeString RedirectUrl = GetRedirectUrl();
  756. // We should test if the redirect is not for another server,
  757. // though not sure how to do this reliably (domain aliases, IP vs. domain, etc.)
  758. // If this ever gets implemented, beware of use from Sink(), where we support redirects to another server.
  759. UnicodeString RedirectPath = ParsePathFromUrl(RedirectUrl);
  760. Result =
  761. !RedirectPath.IsEmpty() &&
  762. (RedirectPath != OriginalPath);
  763. if (Result)
  764. {
  765. Path = RedirectPath;
  766. }
  767. }
  768. return Result;
  769. }
  770. //---------------------------------------------------------------------------
  771. void __fastcall TWebDAVFileSystem::ReadDirectory(TRemoteFileList * FileList)
  772. {
  773. UnicodeString Path = DirectoryPath(FileList->Directory);
  774. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  775. int NeonStatus = ReadDirectoryInternal(Path, FileList);
  776. if (IsValidRedirect(NeonStatus, Path))
  777. {
  778. NeonStatus = ReadDirectoryInternal(Path, FileList);
  779. }
  780. CheckStatus(NeonStatus);
  781. }
  782. //---------------------------------------------------------------------------
  783. void __fastcall TWebDAVFileSystem::ReadSymlink(TRemoteFile * /*SymlinkFile*/,
  784. TRemoteFile *& /*File*/)
  785. {
  786. // we never set SymLink flag, so we should never get here
  787. DebugFail();
  788. }
  789. //---------------------------------------------------------------------------
  790. void __fastcall TWebDAVFileSystem::ReadFile(const UnicodeString FileName,
  791. TRemoteFile *& File)
  792. {
  793. CustomReadFile(FileName, File, NULL);
  794. }
  795. //---------------------------------------------------------------------------
  796. void TWebDAVFileSystem::NeonPropsResult(
  797. void * UserData, const ne_uri * Uri, const ne_prop_result_set * Results)
  798. {
  799. UnicodeString Path = PathUnescape(Uri->path);
  800. TReadFileData & Data = *static_cast<TReadFileData *>(UserData);
  801. if (Data.FileList != NULL)
  802. {
  803. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  804. File->Terminal = Data.FileSystem->FTerminal;
  805. Data.FileSystem->ParsePropResultSet(File.get(), Path, Results);
  806. UnicodeString FileListPath = Data.FileSystem->AbsolutePath(Data.FileList->Directory, false);
  807. if (UnixSamePath(File->FullFileName, FileListPath))
  808. {
  809. File->FileName = PARENTDIRECTORY;
  810. File->FullFileName = UnixCombinePaths(Path, PARENTDIRECTORY);
  811. }
  812. Data.FileList->AddFile(File.release());
  813. }
  814. else
  815. {
  816. Data.FileSystem->ParsePropResultSet(Data.File, Path, Results);
  817. }
  818. }
  819. //---------------------------------------------------------------------------
  820. const char * __fastcall TWebDAVFileSystem::GetProp(
  821. const ne_prop_result_set * Results, const char * Name, const char * NameSpace)
  822. {
  823. ne_propname Prop;
  824. Prop.nspace = (NameSpace == NULL) ? DAV_PROP_NAMESPACE : NameSpace;
  825. Prop.name = Name;
  826. return ne_propset_value(Results, &Prop);
  827. }
  828. //---------------------------------------------------------------------------
  829. void __fastcall TWebDAVFileSystem::ParsePropResultSet(TRemoteFile * File,
  830. const UnicodeString & Path, const ne_prop_result_set * Results)
  831. {
  832. File->FullFileName = UnixExcludeTrailingBackslash(Path);
  833. // Some servers do not use DAV:collection tag, but indicate the folder by trailing slash only.
  834. // But not all, for example OneDrive does not (it did in the past).
  835. bool Collection = (File->FullFileName != Path);
  836. File->FileName = UnixExtractFileName(File->FullFileName);
  837. const char * ContentLength = GetProp(Results, PROP_CONTENT_LENGTH);
  838. // some servers, for example iFiles, do not provide "getcontentlength" for folders
  839. if (ContentLength != NULL)
  840. {
  841. File->Size = StrToInt64Def(ContentLength, 0);
  842. }
  843. const char * LastModified = GetProp(Results, PROP_LAST_MODIFIED);
  844. // We've seen a server (t=24891) that does not set "getlastmodified" for the "this" folder entry.
  845. if (LastModified != NULL)
  846. {
  847. char WeekDay[4] = { L'\0' };
  848. int Year = 0;
  849. char MonthStr[4] = { L'\0' };
  850. int Day = 0;
  851. int Hour = 0;
  852. int Min = 0;
  853. int Sec = 0;
  854. #define RFC1123_FORMAT "%3s, %02d %3s %4d %02d:%02d:%02d GMT"
  855. // Keep is sync with S3
  856. int Filled =
  857. sscanf(LastModified, RFC1123_FORMAT, WeekDay, &Day, MonthStr, &Year, &Hour, &Min, &Sec);
  858. // we need at least a complete date
  859. if (Filled >= 4)
  860. {
  861. int Month = ParseShortEngMonthName(MonthStr);
  862. if (Month >= 1)
  863. {
  864. TDateTime Modification =
  865. EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) +
  866. EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0);
  867. File->Modification = ConvertTimestampFromUTC(Modification);
  868. // Should use mfYMDHM or mfMDY when appropriate according to Filled
  869. File->ModificationFmt = mfFull;
  870. }
  871. else
  872. {
  873. File->ModificationFmt = mfNone;
  874. }
  875. }
  876. else
  877. {
  878. File->ModificationFmt = mfNone;
  879. }
  880. }
  881. // optimization
  882. if (!Collection)
  883. {
  884. // See a comment at the Collection declaration.
  885. const char * ResourceType = GetProp(Results, PROP_RESOURCE_TYPE);
  886. if (ResourceType != NULL)
  887. {
  888. // property has XML value
  889. UnicodeString AResourceType = ResourceType;
  890. // this is very poor parsing
  891. if (ContainsText(ResourceType, L"<DAV:collection"))
  892. {
  893. Collection = true;
  894. }
  895. }
  896. }
  897. File->Type = Collection ? FILETYPE_DIRECTORY : FILETYPE_DEFAULT;
  898. // this is MS extension (draft-hopmann-collection-props-00)
  899. const char * IsHidden = GetProp(Results, PROP_HIDDEN);
  900. if (IsHidden != NULL)
  901. {
  902. File->IsHidden = (StrToIntDef(IsHidden, 0) != 0);
  903. }
  904. const char * Owner = GetProp(Results, PROP_OWNER);
  905. if (Owner != NULL)
  906. {
  907. File->Owner.Name = Owner;
  908. }
  909. const char * DisplayName = GetProp(Results, PROP_DISPLAY_NAME);
  910. if (DisplayName != NULL)
  911. {
  912. File->DisplayName = StrFromNeon(DisplayName);
  913. // OneDrive caret escaping (we could do this for all files, but let's limit the scope for now).
  914. // In *file* PROPFIND response, the # (and other symbols like comma or plus) is not escaped at all
  915. // (while in directory listing, they are caret-escaped),
  916. // so if we see one in the display name, take the name from there.
  917. // * and % won't help, as OneDrive seem to have bug with % at the end of the filename,
  918. // and the * (and others) is removed from file names.
  919. // Filenames with commas (,) get as many additional characters at the end of the filename as there are commas.
  920. if (FOneDrive &&
  921. (ContainsText(File->FileName, L"^") || ContainsText(File->FileName, L",") || (wcspbrk(File->DisplayName.c_str(), L"&,+#[]%*") != NULL)))
  922. {
  923. File->FileName = File->DisplayName;
  924. File->FullFileName = UnixCombinePaths(UnixExtractFileDir(File->FullFileName), File->FileName);
  925. }
  926. }
  927. const UnicodeString RightsDelimiter(L", ");
  928. UnicodeString HumanRights;
  929. // Proprietary property of mod_dav
  930. // http://www.webdav.org/mod_dav/#imp
  931. const char * Executable = GetProp(Results, PROP_EXECUTABLE, MODDAV_PROP_NAMESPACE);
  932. if (Executable != NULL)
  933. {
  934. if (strcmp(Executable, "T") == NULL)
  935. {
  936. UnicodeString ExecutableRights;
  937. // The "gear" character is supported since Windows 8
  938. if (IsWin8())
  939. {
  940. ExecutableRights = L"\u2699";
  941. }
  942. else
  943. {
  944. ExecutableRights = LoadStr(EXECUTABLE);
  945. }
  946. AddToList(HumanRights, ExecutableRights, RightsDelimiter);
  947. }
  948. }
  949. struct ne_lock * Lock = static_cast<struct ne_lock *>(ne_propset_private(Results));
  950. if ((Lock != NULL) && (Lock->token != NULL))
  951. {
  952. UnicodeString Owner;
  953. if (Lock->owner != NULL)
  954. {
  955. Owner = StrFromNeon(Lock->owner).Trim();
  956. }
  957. UnicodeString LockRights;
  958. if (IsWin8())
  959. {
  960. // The "lock" character is supported since Windows 8
  961. LockRights = L"\uD83D\uDD12" + Owner;
  962. }
  963. else
  964. {
  965. LockRights = LoadStr(LOCKED);
  966. if (!Owner.IsEmpty())
  967. {
  968. LockRights = FORMAT(L"%s (%s)", (LockRights, Owner));
  969. }
  970. }
  971. AddToList(HumanRights, LockRights, RightsDelimiter);
  972. }
  973. File->HumanRights = HumanRights;
  974. }
  975. //---------------------------------------------------------------------------
  976. int __fastcall TWebDAVFileSystem::CustomReadFileInternal(const UnicodeString FileName,
  977. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  978. {
  979. std::unique_ptr<TRemoteFile> AFile(new TRemoteFile(ALinkedByFile));
  980. TReadFileData Data;
  981. Data.FileSystem = this;
  982. Data.File = AFile.get();
  983. Data.FileList = NULL;
  984. ClearNeonError();
  985. int Result =
  986. ne_simple_propfind(FSessionContext->NeonSession, PathToNeon(FileName), NE_DEPTH_ZERO, NULL,
  987. NeonPropsResult, &Data);
  988. if (Result == NE_OK)
  989. {
  990. File = AFile.release();
  991. }
  992. return Result;
  993. }
  994. //---------------------------------------------------------------------------
  995. void __fastcall TWebDAVFileSystem::CustomReadFile(UnicodeString FileName,
  996. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  997. {
  998. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  999. int NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  1000. if (IsValidRedirect(NeonStatus, FileName))
  1001. {
  1002. NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  1003. }
  1004. CheckStatus(NeonStatus);
  1005. }
  1006. //---------------------------------------------------------------------------
  1007. void __fastcall TWebDAVFileSystem::DeleteFile(const UnicodeString FileName,
  1008. const TRemoteFile * File, int /*Params*/, TRmSessionAction & Action)
  1009. {
  1010. Action.Recursive();
  1011. ClearNeonError();
  1012. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1013. RawByteString Path = PathToNeon(FilePath(File));
  1014. // WebDAV does not allow non-recursive delete:
  1015. // RFC 4918, section 9.6.1:
  1016. // "A client MUST NOT submit a Depth header with a DELETE on a collection with any value but infinity."
  1017. // We should check that folder is empty when called with FLAGSET(Params, dfNoRecursive)
  1018. CheckStatus(ne_delete(FSessionContext->NeonSession, Path.c_str()));
  1019. // The lock is removed with the file, but if a file with the same name gets created,
  1020. // we would try to use obsoleted lock token with it, what the server would reject
  1021. // (mod_dav returns "412 Precondition Failed")
  1022. DiscardLock(Path);
  1023. }
  1024. //---------------------------------------------------------------------------
  1025. int __fastcall TWebDAVFileSystem::RenameFileInternal(const UnicodeString & FileName,
  1026. const UnicodeString & NewName)
  1027. {
  1028. // 0 = no overwrite
  1029. return ne_move(FSessionContext->NeonSession, 0, PathToNeon(FileName), PathToNeon(NewName));
  1030. }
  1031. //---------------------------------------------------------------------------
  1032. void __fastcall TWebDAVFileSystem::RenameFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  1033. const UnicodeString NewName)
  1034. {
  1035. ClearNeonError();
  1036. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1037. UnicodeString Path = FileName;
  1038. int NeonStatus = RenameFileInternal(Path, NewName);
  1039. if (IsValidRedirect(NeonStatus, Path))
  1040. {
  1041. NeonStatus = RenameFileInternal(Path, NewName);
  1042. }
  1043. CheckStatus(NeonStatus);
  1044. // See a comment in DeleteFile
  1045. DiscardLock(PathToNeon(Path));
  1046. }
  1047. //---------------------------------------------------------------------------
  1048. int __fastcall TWebDAVFileSystem::CopyFileInternal(const UnicodeString & FileName,
  1049. const UnicodeString & NewName)
  1050. {
  1051. // 0 = no overwrite
  1052. return ne_copy(FSessionContext->NeonSession, 0, NE_DEPTH_INFINITE, PathToNeon(FileName), PathToNeon(NewName));
  1053. }
  1054. //---------------------------------------------------------------------------
  1055. void __fastcall TWebDAVFileSystem::CopyFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  1056. const UnicodeString NewName)
  1057. {
  1058. ClearNeonError();
  1059. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1060. UnicodeString Path = FileName;
  1061. int NeonStatus = CopyFileInternal(Path, NewName);
  1062. if (IsValidRedirect(NeonStatus, Path))
  1063. {
  1064. NeonStatus = CopyFileInternal(Path, NewName);
  1065. }
  1066. CheckStatus(NeonStatus);
  1067. }
  1068. //---------------------------------------------------------------------------
  1069. void __fastcall TWebDAVFileSystem::CreateDirectory(const UnicodeString & DirName, bool /*Encrypt*/)
  1070. {
  1071. ClearNeonError();
  1072. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1073. CheckStatus(ne_mkcol(FSessionContext->NeonSession, PathToNeon(DirName)));
  1074. }
  1075. //---------------------------------------------------------------------------
  1076. void __fastcall TWebDAVFileSystem::CreateLink(const UnicodeString FileName,
  1077. const UnicodeString PointTo, bool /*Symbolic*/)
  1078. {
  1079. DebugFail();
  1080. }
  1081. //---------------------------------------------------------------------------
  1082. void __fastcall TWebDAVFileSystem::ChangeFileProperties(const UnicodeString FileName,
  1083. const TRemoteFile * /*File*/, const TRemoteProperties * /*Properties*/,
  1084. TChmodSessionAction & /*Action*/)
  1085. {
  1086. DebugFail();
  1087. }
  1088. //---------------------------------------------------------------------------
  1089. bool __fastcall TWebDAVFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  1090. {
  1091. DebugFail();
  1092. return false;
  1093. }
  1094. //---------------------------------------------------------------------------
  1095. void __fastcall TWebDAVFileSystem::CalculateFilesChecksum(
  1096. const UnicodeString & DebugUsedArg(Alg), TStrings * DebugUsedArg(FileList), TCalculatedChecksumEvent,
  1097. TFileOperationProgressType *, bool DebugUsedArg(FirstLevel))
  1098. {
  1099. DebugFail();
  1100. }
  1101. //---------------------------------------------------------------------------
  1102. void __fastcall TWebDAVFileSystem::ConfirmOverwrite(
  1103. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1104. TFileOperationProgressType * OperationProgress,
  1105. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1106. int Params)
  1107. {
  1108. // all = "yes to newer"
  1109. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll;
  1110. TQueryButtonAlias Aliases[3];
  1111. Aliases[0] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
  1112. Aliases[1] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
  1113. Aliases[2] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
  1114. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1115. QueryParams.Aliases = Aliases;
  1116. QueryParams.AliasesCount = LENOF(Aliases);
  1117. unsigned int Answer;
  1118. {
  1119. TSuspendFileOperationProgress Suspend(OperationProgress);
  1120. Answer =
  1121. FTerminal->ConfirmFileOverwrite(
  1122. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1123. ReverseOperationSide(OperationProgress->Side),
  1124. CopyParam, Params, OperationProgress);
  1125. }
  1126. switch (Answer)
  1127. {
  1128. case qaYes:
  1129. // noop
  1130. break;
  1131. case qaNo:
  1132. throw ESkipFile();
  1133. default:
  1134. DebugFail();
  1135. case qaCancel:
  1136. OperationProgress->SetCancelAtLeast(csCancel);
  1137. Abort();
  1138. break;
  1139. }
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. void __fastcall TWebDAVFileSystem::CustomCommandOnFile(const UnicodeString FileName,
  1143. const TRemoteFile * /*File*/, UnicodeString Command, int /*Params*/, TCaptureOutputEvent /*OutputEvent*/)
  1144. {
  1145. DebugFail();
  1146. }
  1147. //---------------------------------------------------------------------------
  1148. void __fastcall TWebDAVFileSystem::AnyCommand(const UnicodeString Command,
  1149. TCaptureOutputEvent /*OutputEvent*/)
  1150. {
  1151. DebugFail();
  1152. }
  1153. //---------------------------------------------------------------------------
  1154. TStrings * __fastcall TWebDAVFileSystem::GetFixedPaths()
  1155. {
  1156. return NULL;
  1157. }
  1158. //---------------------------------------------------------------------------
  1159. void TWebDAVFileSystem::NeonQuotaResult(
  1160. void * UserData, const ne_uri * /*Uri*/, const ne_prop_result_set * Results)
  1161. {
  1162. TSpaceAvailable & SpaceAvailable = *static_cast<TSpaceAvailable *>(UserData);
  1163. const char * Value = GetProp(Results, PROP_QUOTA_AVAILABLE);
  1164. if (Value != NULL)
  1165. {
  1166. SpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(StrFromNeon(Value));
  1167. const char * Value = GetProp(Results, PROP_QUOTA_USED);
  1168. if (Value != NULL)
  1169. {
  1170. SpaceAvailable.BytesAvailableToUser =
  1171. StrToInt64(StrFromNeon(Value)) + SpaceAvailable.UnusedBytesAvailableToUser;
  1172. }
  1173. }
  1174. }
  1175. //---------------------------------------------------------------------------
  1176. void __fastcall TWebDAVFileSystem::SpaceAvailable(const UnicodeString Path,
  1177. TSpaceAvailable & ASpaceAvailable)
  1178. {
  1179. // RFC4331: https://datatracker.ietf.org/doc/html/rfc4331
  1180. // This is known to be supported by:
  1181. // OpenDrive: for a root drive only (and contrary to the spec, it sends the properties
  1182. // unconditionally, even when not explicitly requested)
  1183. // Server: Apache/2.2.17 (Fedora)
  1184. // X-Powered-By: PHP/5.5.7
  1185. // X-DAV-Powered-By: OpenDrive
  1186. // WWW-Authenticate: Basic realm="PHP WebDAV"
  1187. // IT Hit WebDAV Server:
  1188. // Server: Microsoft-HTTPAPI/1.0
  1189. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1190. // Yandex disk:
  1191. // WWW-Authenticate: Basic realm="Yandex.Disk"
  1192. // Server: MochiWeb/1.0
  1193. // OneDrive:
  1194. // it sends the properties unconditionally, even when not explicitly requested
  1195. UnicodeString APath = DirectoryPath(Path);
  1196. ne_propname QuotaProps[3];
  1197. memset(QuotaProps, 0, sizeof(QuotaProps));
  1198. QuotaProps[0].nspace = DAV_PROP_NAMESPACE;
  1199. QuotaProps[0].name = PROP_QUOTA_AVAILABLE;
  1200. QuotaProps[1].nspace = DAV_PROP_NAMESPACE;
  1201. QuotaProps[1].name = PROP_QUOTA_USED;
  1202. QuotaProps[2].nspace = NULL;
  1203. QuotaProps[2].name = NULL;
  1204. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1205. CheckStatus(
  1206. ne_simple_propfind(FSessionContext->NeonSession, PathToNeon(APath), NE_DEPTH_ZERO, QuotaProps,
  1207. NeonQuotaResult, &ASpaceAvailable));
  1208. }
  1209. //---------------------------------------------------------------------------
  1210. void __fastcall TWebDAVFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1211. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1212. int Params, TFileOperationProgressType * OperationProgress,
  1213. TOnceDoneOperation & OnceDoneOperation)
  1214. {
  1215. Params &= ~cpAppend;
  1216. FTerminal->DoCopyToRemote(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfPreCreateDir, OnceDoneOperation);
  1217. }
  1218. //---------------------------------------------------------------------------
  1219. void __fastcall TWebDAVFileSystem::Source(
  1220. TLocalFileHandle & Handle, const UnicodeString & TargetDir, UnicodeString & DestFileName,
  1221. const TCopyParamType * CopyParam, int Params,
  1222. TFileOperationProgressType * OperationProgress, unsigned int /*Flags*/,
  1223. TUploadSessionAction & Action, bool & ChildError)
  1224. {
  1225. int FD = -1;
  1226. try
  1227. {
  1228. UnicodeString DestFullName = TargetDir + DestFileName;
  1229. TRemoteFile * RemoteFile = NULL;
  1230. try
  1231. {
  1232. TValueRestorer<TIgnoreAuthenticationFailure> IgnoreAuthenticationFailureRestorer(FIgnoreAuthenticationFailure);
  1233. FIgnoreAuthenticationFailure = iafWaiting;
  1234. // this should not throw
  1235. CustomReadFileInternal(DestFullName, RemoteFile, NULL);
  1236. }
  1237. catch (...)
  1238. {
  1239. if (!FTerminal->Active)
  1240. {
  1241. throw;
  1242. }
  1243. }
  1244. if (RemoteFile != NULL)
  1245. {
  1246. TOverwriteFileParams FileParams;
  1247. FileParams.SourceSize = Handle.Size;
  1248. FileParams.SourceTimestamp = Handle.Modification;
  1249. FileParams.DestSize = RemoteFile->Size;
  1250. FileParams.DestTimestamp = RemoteFile->Modification;
  1251. delete RemoteFile;
  1252. ConfirmOverwrite(Handle.FileName, DestFileName, OperationProgress,
  1253. &FileParams, CopyParam, Params);
  1254. }
  1255. DestFullName = TargetDir + DestFileName;
  1256. // only now, we know the final destination
  1257. // (not really true as we do not support changing file name on overwrite dialog)
  1258. Action.Destination(DestFullName);
  1259. FUploadMimeType = Configuration->GetFileMimeType(DestFileName);
  1260. FILE_OPERATION_LOOP_BEGIN
  1261. {
  1262. SetFilePointer(Handle.Handle, 0, NULL, FILE_BEGIN);
  1263. FD = _open_osfhandle((intptr_t)Handle.Handle, O_BINARY);
  1264. if (FD < 0)
  1265. {
  1266. throw ESkipFile();
  1267. }
  1268. TAutoFlag UploadingFlag(FUploading);
  1269. ClearNeonError();
  1270. CheckStatus(ne_put(FSessionContext->NeonSession, PathToNeon(DestFullName), FD));
  1271. }
  1272. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (Handle.FileName)));
  1273. if (CopyParam->PreserveTime)
  1274. {
  1275. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1276. (StandardTimestamp(Handle.Modification))));
  1277. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Handle.Modification);
  1278. try
  1279. {
  1280. TDateTime ModificationUTC = ConvertTimestampToUTC(Handle.Modification);
  1281. TFormatSettings FormatSettings = GetEngFormatSettings();
  1282. UnicodeString LastModified =
  1283. FormatDateTime(L"ddd, d mmm yyyy hh:nn:ss 'GMT'", ModificationUTC, FormatSettings);
  1284. UTF8String NeonLastModified(LastModified);
  1285. // second element is "NULL-terminating"
  1286. ne_proppatch_operation Operations[2];
  1287. memset(Operations, 0, sizeof(Operations));
  1288. ne_propname LastModifiedProp;
  1289. LastModifiedProp.nspace = DAV_PROP_NAMESPACE;
  1290. LastModifiedProp.name = PROP_LAST_MODIFIED;
  1291. Operations[0].name = &LastModifiedProp;
  1292. Operations[0].type = ne_propset;
  1293. Operations[0].value = NeonLastModified.c_str();
  1294. int Status = ne_proppatch(FSessionContext->NeonSession, PathToNeon(DestFullName), Operations);
  1295. if (Status == NE_ERROR)
  1296. {
  1297. FTerminal->LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s",
  1298. (GetNeonError())));
  1299. // Ignore errors as major WebDAV servers (like IIS), do not support
  1300. // changing getlastmodified.
  1301. // The only server we found that supports this is TradeMicro SafeSync.
  1302. // But it announces itself as "Server: Apache",
  1303. // so it's not reliable to autodetect the support.
  1304. // Microsoft Office alegedly uses <Win32LastModifiedTime>
  1305. // https://sabre.io/dav/clients/msoffice/
  1306. // Carot DAV does that too. But we do not know what server does support this.
  1307. TouchAction.Cancel();
  1308. }
  1309. else
  1310. {
  1311. CheckStatus(Status);
  1312. }
  1313. }
  1314. catch (Exception & E)
  1315. {
  1316. TouchAction.Rollback(&E);
  1317. ChildError = true;
  1318. throw;
  1319. }
  1320. }
  1321. }
  1322. __finally
  1323. {
  1324. if (FD >= 0)
  1325. {
  1326. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1327. // but it crashes code guard
  1328. _close(FD);
  1329. Handle.Dismiss();
  1330. }
  1331. }
  1332. }
  1333. //---------------------------------------------------------------------------
  1334. void __fastcall TWebDAVFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1335. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1336. int Params, TFileOperationProgressType * OperationProgress,
  1337. TOnceDoneOperation & OnceDoneOperation)
  1338. {
  1339. Params &= ~cpAppend;
  1340. FTerminal->DoCopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfNone, OnceDoneOperation);
  1341. }
  1342. //---------------------------------------------------------------------------
  1343. void TWebDAVFileSystem::NeonCreateRequest(
  1344. ne_request * Request, void * UserData, const char * /*Method*/, const char * /*Uri*/)
  1345. {
  1346. TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
  1347. ne_set_request_private(Request, SESSION_CONTEXT_KEY, SessionContext);
  1348. ne_add_response_body_reader(Request, NeonBodyAccepter, NeonBodyReader, Request);
  1349. SessionContext->NtlmAuthenticationFailed = false;
  1350. }
  1351. //---------------------------------------------------------------------------
  1352. void TWebDAVFileSystem::NeonPreSend(
  1353. ne_request * Request, void * UserData, ne_buffer * Header)
  1354. {
  1355. TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
  1356. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1357. SessionContext->AuthorizationProtocol = EmptyStr;
  1358. UnicodeString HeaderBuf(StrFromNeon(AnsiString(Header->data, Header->used)));
  1359. const UnicodeString AuthorizationHeaderName(L"Authorization:");
  1360. int P = HeaderBuf.Pos(AuthorizationHeaderName);
  1361. if (P > 0)
  1362. {
  1363. P += AuthorizationHeaderName.Length();
  1364. int P2 = PosEx(L"\n", HeaderBuf, P);
  1365. if (DebugAlwaysTrue(P2 > 0))
  1366. {
  1367. UnicodeString AuthorizationHeader = HeaderBuf.SubString(P, P2 - P).Trim();
  1368. SessionContext->AuthorizationProtocol = CutToChar(AuthorizationHeader, L' ', false);
  1369. if (SessionContext == FileSystem->FSessionContext)
  1370. {
  1371. FileSystem->FLastAuthorizationProtocol = SessionContext->AuthorizationProtocol;
  1372. }
  1373. }
  1374. }
  1375. if (FileSystem->FDownloading)
  1376. {
  1377. // Needed by IIS server to make it download source code, not code output,
  1378. // and mainly to even allow downloading file with unregistered extensions.
  1379. // Without it files like .001 return 404 (Not found) HTTP code.
  1380. // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wdv/e37a9543-9290-4843-8c04-66457c60fa0a
  1381. // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wdvse/501879f9-3875-4d7a-ab88-3cecab440034
  1382. // http://lists.manyfish.co.uk/pipermail/neon/2012-April/000582.html
  1383. // It's also supported by Oracle server:
  1384. // https://docs.oracle.com/cd/E19146-01/821-1828/gczya/index.html
  1385. // We do not know yet of any server that fails when the header is used,
  1386. // so it's added unconditionally.
  1387. ne_buffer_zappend(Header, "Translate: f\r\n");
  1388. }
  1389. const UnicodeString ContentTypeHeaderPrefix(L"Content-Type: ");
  1390. if (FileSystem->FTerminal->Log->Logging)
  1391. {
  1392. const char * Buffer;
  1393. size_t Size;
  1394. if (ne_get_request_body_buffer(Request, &Buffer, &Size))
  1395. {
  1396. // all neon request types that use ne_add_request_header
  1397. // use XML content-type, so it's text-based
  1398. DebugAssert(ContainsStr(HeaderBuf, ContentTypeHeaderPrefix + NE_XML_MEDIA_TYPE));
  1399. FileSystem->FTerminal->Log->Add(llInput, UnicodeString(UTF8String(Buffer, Size)));
  1400. }
  1401. }
  1402. if (FileSystem->FUploading)
  1403. {
  1404. ne_set_request_body_provider_pre(Request, FileSystem->NeonUploadBodyProvider, SessionContext);
  1405. if (!FileSystem->FUploadMimeType.IsEmpty())
  1406. {
  1407. UnicodeString ContentTypeHeader = ContentTypeHeaderPrefix + FileSystem->FUploadMimeType + L"\r\n";
  1408. ne_buffer_zappend(Header, AnsiString(ContentTypeHeader).c_str());
  1409. }
  1410. }
  1411. FileSystem->FResponse = L"";
  1412. }
  1413. //---------------------------------------------------------------------------
  1414. int TWebDAVFileSystem::NeonPostSend(ne_request * /*Req*/, void * UserData,
  1415. const ne_status * /*Status*/)
  1416. {
  1417. TWebDAVFileSystem * FileSystem = static_cast<TSessionContext *>(UserData)->FileSystem;
  1418. if (!FileSystem->FResponse.IsEmpty())
  1419. {
  1420. FileSystem->FTerminal->Log->Add(llOutput, FileSystem->FResponse);
  1421. }
  1422. return NE_OK;
  1423. }
  1424. //---------------------------------------------------------------------------
  1425. bool __fastcall TWebDAVFileSystem::IsNtlmAuthentication(TSessionContext * SessionContext)
  1426. {
  1427. return
  1428. SameText(SessionContext->AuthorizationProtocol, L"NTLM") ||
  1429. SameText(SessionContext->AuthorizationProtocol, L"Negotiate");
  1430. }
  1431. //---------------------------------------------------------------------------
  1432. void __fastcall TWebDAVFileSystem::HttpAuthenticationFailed(TSessionContext * SessionContext)
  1433. {
  1434. // NTLM/GSSAPI failed
  1435. if (IsNtlmAuthentication(SessionContext))
  1436. {
  1437. if (SessionContext->NtlmAuthenticationFailed)
  1438. {
  1439. // Next time do not try Negotiate (NTLM/GSSAPI),
  1440. // otherwise we end up in an endless loop.
  1441. // If the server returns all other challenges in the response, removing the Negotiate
  1442. // protocol will itself ensure that other protocols are tried (we haven't seen this behaviour).
  1443. // IIS will return only Negotiate response if the request was Negotiate, so there's no fallback.
  1444. // We have to retry with a fresh request. That's what FAuthenticationRetry does.
  1445. FTerminal->LogEvent(FORMAT(L"%s challenge failed, will try different challenge", (SessionContext->AuthorizationProtocol)));
  1446. ne_remove_server_auth(SessionContext->NeonSession);
  1447. NeonAddAuthentiation(SessionContext, false);
  1448. FAuthenticationRetry = true;
  1449. }
  1450. else
  1451. {
  1452. // The first 401 is expected, the server is using it to send WWW-Authenticate header with data.
  1453. SessionContext->NtlmAuthenticationFailed = true;
  1454. }
  1455. }
  1456. }
  1457. //---------------------------------------------------------------------------
  1458. void TWebDAVFileSystem::NeonPostHeaders(ne_request * /*Req*/, void * UserData, const ne_status * Status)
  1459. {
  1460. TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
  1461. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1462. if (Status->code == HttpUnauthorized)
  1463. {
  1464. FileSystem->HttpAuthenticationFailed(SessionContext);
  1465. }
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. ssize_t TWebDAVFileSystem::NeonUploadBodyProvider(void * UserData, char * /*Buffer*/, size_t /*BufLen*/)
  1469. {
  1470. TWebDAVFileSystem * FileSystem = static_cast<TSessionContext *>(UserData)->FileSystem;
  1471. ssize_t Result;
  1472. if (FileSystem->CancelTransfer())
  1473. {
  1474. Result = -1;
  1475. }
  1476. else
  1477. {
  1478. Result = 1;
  1479. }
  1480. return Result;
  1481. }
  1482. //---------------------------------------------------------------------------
  1483. static void __fastcall AddHeaderValueToList(UnicodeString & List, ne_request * Request, const char * Name)
  1484. {
  1485. const char * Value = ne_get_response_header(Request, Name);
  1486. if (Value != NULL)
  1487. {
  1488. AddToList(List, StrFromNeon(Value), L"; ");
  1489. }
  1490. }
  1491. //---------------------------------------------------------------------------
  1492. int TWebDAVFileSystem::NeonBodyAccepter(void * UserData, ne_request * Request, const ne_status * Status)
  1493. {
  1494. DebugAssert(UserData == Request);
  1495. TSessionContext * SessionContext = static_cast<TSessionContext *>(ne_get_request_private(Request, SESSION_CONTEXT_KEY));
  1496. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1497. bool AuthenticationFailureCode = (Status->code == HttpUnauthorized);
  1498. bool PasswordAuthenticationFailed = AuthenticationFailureCode && FileSystem->FAuthenticationRequested;
  1499. bool AuthenticationFailed = PasswordAuthenticationFailed || (AuthenticationFailureCode && FileSystem->IsNtlmAuthentication(SessionContext));
  1500. bool AuthenticationNeeded = AuthenticationFailureCode && !AuthenticationFailed;
  1501. if (FileSystem->FInitialHandshake)
  1502. {
  1503. UnicodeString Line;
  1504. if (AuthenticationNeeded)
  1505. {
  1506. Line = LoadStr(STATUS_AUTHENTICATE);
  1507. }
  1508. else if (AuthenticationFailed)
  1509. {
  1510. Line = LoadStr(FTP_ACCESS_DENIED);
  1511. }
  1512. else if (Status->klass == 2)
  1513. {
  1514. Line = LoadStr(STATUS_AUTHENTICATED);
  1515. }
  1516. if (!Line.IsEmpty())
  1517. {
  1518. FileSystem->FTerminal->Information(Line, true);
  1519. }
  1520. UnicodeString RemoteSystem;
  1521. // Used by IT Hit WebDAV Server:
  1522. // Server: Microsoft-HTTPAPI/1.0
  1523. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1524. AddHeaderValueToList(RemoteSystem, Request, "X-Engine");
  1525. // Used by OpenDrive:
  1526. // Server: Apache/2.2.17 (Fedora)
  1527. // X-Powered-By: PHP/5.5.7
  1528. // X-DAV-Powered-By: OpenDrive
  1529. AddHeaderValueToList(RemoteSystem, Request, "X-DAV-Powered-By");
  1530. // Used by IIS:
  1531. // Server: Microsoft-IIS/8.5
  1532. AddHeaderValueToList(RemoteSystem, Request, "Server");
  1533. // Not really useful.
  1534. // Can be e.g. "PleskLin"
  1535. AddHeaderValueToList(RemoteSystem, Request, "X-Powered-By");
  1536. FileSystem->FFileSystemInfo.RemoteSystem = RemoteSystem;
  1537. }
  1538. // When we explicitly fail authentication of request
  1539. // with FIgnoreAuthenticationFailure flag (after it failed with password),
  1540. // neon resets its internal password store and tries the next request
  1541. // without calling our authentication hook first
  1542. // (note AuthenticationFailed vs. AuthenticationNeeded)
  1543. // what likely fails, but we do not want to reset out password
  1544. // (as it was not even tried yet for this request).
  1545. if (PasswordAuthenticationFailed)
  1546. {
  1547. if (FileSystem->FIgnoreAuthenticationFailure == iafNo)
  1548. {
  1549. FileSystem->FPassword = RawByteString();
  1550. }
  1551. else
  1552. {
  1553. FileSystem->FIgnoreAuthenticationFailure = iafPasswordFailed;
  1554. }
  1555. }
  1556. return ne_accept_2xx(UserData, Request, Status);
  1557. }
  1558. //---------------------------------------------------------------------------
  1559. bool __fastcall TWebDAVFileSystem::CancelTransfer()
  1560. {
  1561. bool Result = false;
  1562. if ((FUploading || FDownloading) &&
  1563. (FTerminal->OperationProgress != NULL) &&
  1564. (FTerminal->OperationProgress->Cancel != csContinue))
  1565. {
  1566. if (FTerminal->OperationProgress->ClearCancelFile())
  1567. {
  1568. FSkipped = true;
  1569. }
  1570. else
  1571. {
  1572. FCancelled = true;
  1573. }
  1574. Result = true;
  1575. }
  1576. return Result;
  1577. }
  1578. //---------------------------------------------------------------------------
  1579. int TWebDAVFileSystem::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  1580. {
  1581. ne_request * Request = static_cast<ne_request *>(UserData);
  1582. TSessionContext * SessionContext = static_cast<TSessionContext *>(ne_get_request_private(Request, SESSION_CONTEXT_KEY));
  1583. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1584. if (FileSystem->FTerminal->Log->Logging)
  1585. {
  1586. ne_content_type ContentType;
  1587. if (ne_get_content_type(Request, &ContentType) == 0)
  1588. {
  1589. // The main point of the content-type check was to exclude
  1590. // GET responses (with file contents).
  1591. // But this won't work when downloading text files that have text
  1592. // content type on their own, hence the additional not-downloading test.
  1593. if (!FileSystem->FDownloading &&
  1594. ((ne_strcasecmp(ContentType.type, "text") == 0) ||
  1595. media_type_is_xml(&ContentType)))
  1596. {
  1597. UnicodeString Content = UnicodeString(UTF8String(Buf, Len)).Trim();
  1598. FileSystem->FResponse += Content;
  1599. }
  1600. ne_free(ContentType.value);
  1601. }
  1602. }
  1603. int Result = FileSystem->CancelTransfer() ? 1 : 0;
  1604. return Result;
  1605. }
  1606. //---------------------------------------------------------------------------
  1607. void __fastcall TWebDAVFileSystem::Sink(
  1608. const UnicodeString & FileName, const TRemoteFile * File,
  1609. const UnicodeString & TargetDir, UnicodeString & DestFileName, int Attrs,
  1610. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  1611. unsigned int /*Flags*/, TDownloadSessionAction & Action)
  1612. {
  1613. UnicodeString DestFullName = TargetDir + DestFileName;
  1614. if (FileExists(ApiPath(DestFullName)))
  1615. {
  1616. __int64 Size;
  1617. __int64 MTime;
  1618. FTerminal->OpenLocalFile(DestFullName, GENERIC_READ, NULL, NULL, NULL, &MTime, NULL, &Size);
  1619. TOverwriteFileParams FileParams;
  1620. FileParams.SourceSize = File->Size;
  1621. FileParams.SourceTimestamp = File->Modification;
  1622. FileParams.DestSize = Size;
  1623. FileParams.DestTimestamp = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  1624. ConfirmOverwrite(FileName, DestFileName, OperationProgress, &FileParams, CopyParam, Params);
  1625. }
  1626. UnicodeString ExpandedDestFullName = ExpandUNCFileName(DestFullName);
  1627. Action.Destination(ExpandedDestFullName);
  1628. FILE_OPERATION_LOOP_BEGIN
  1629. {
  1630. HANDLE LocalHandle;
  1631. if (!FTerminal->CreateLocalFile(DestFullName, OperationProgress, &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  1632. {
  1633. throw ESkipFile();
  1634. }
  1635. bool DeleteLocalFile = true;
  1636. int FD = -1;
  1637. try
  1638. {
  1639. FD = _open_osfhandle((intptr_t)LocalHandle, O_BINARY);
  1640. if (FD < 0)
  1641. {
  1642. throw ESkipFile();
  1643. }
  1644. TAutoFlag DownloadingFlag(FDownloading);
  1645. ClearNeonError();
  1646. int NeonStatus = ne_get(FSessionContext->NeonSession, PathToNeon(FileName), FD);
  1647. UnicodeString DiscardPath = FileName;
  1648. if (IsValidRedirect(NeonStatus, DiscardPath))
  1649. {
  1650. UnicodeString CorrectedUrl = GetRedirectUrl();
  1651. UTF8String CorrectedFileName;
  1652. std::unique_ptr<TSessionContext> CorrectedSessionContext(NeonOpen(CorrectedUrl, CorrectedFileName));
  1653. NeonStatus = ne_get(CorrectedSessionContext->NeonSession, CorrectedFileName.c_str(), FD);
  1654. CheckStatus(CorrectedSessionContext.get(), NeonStatus);
  1655. }
  1656. else
  1657. {
  1658. CheckStatus(NeonStatus);
  1659. }
  1660. DeleteLocalFile = false;
  1661. if (CopyParam->PreserveTime)
  1662. {
  1663. FTerminal->UpdateTargetTime(LocalHandle, File->Modification, FTerminal->SessionData->DSTMode);
  1664. }
  1665. }
  1666. __finally
  1667. {
  1668. if (FD >= 0)
  1669. {
  1670. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1671. // but it crashes code guard
  1672. _close(FD);
  1673. }
  1674. else
  1675. {
  1676. CloseHandle(LocalHandle);
  1677. }
  1678. if (DeleteLocalFile)
  1679. {
  1680. FILE_OPERATION_LOOP_BEGIN
  1681. {
  1682. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestFullName)));
  1683. }
  1684. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestFullName)));
  1685. }
  1686. }
  1687. }
  1688. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1689. FTerminal->UpdateTargetAttrs(DestFullName, File, CopyParam, Attrs);
  1690. }
  1691. //---------------------------------------------------------------------------
  1692. // Similar to TS3FileSystem::VerifyCertificate
  1693. bool TWebDAVFileSystem::VerifyCertificate(TSessionContext * SessionContext, TNeonCertificateData Data, bool Aux)
  1694. {
  1695. FSessionInfo.CertificateFingerprintSHA1 = Data.FingerprintSHA1;
  1696. FSessionInfo.CertificateFingerprintSHA256 = Data.FingerprintSHA256;
  1697. bool Result;
  1698. if (FTerminal->SessionData->FingerprintScan)
  1699. {
  1700. Result = false;
  1701. }
  1702. else
  1703. {
  1704. FTerminal->LogEvent(0, CertificateVerificationMessage(Data));
  1705. UnicodeString SiteKey = TSessionData::FormatSiteKey(SessionContext->HostName, SessionContext->PortNumber);
  1706. Result =
  1707. FTerminal->VerifyCertificate(
  1708. HttpsCertificateStorageKey, SiteKey, Data.FingerprintSHA1, Data.FingerprintSHA256, Data.Subject, Data.Failures);
  1709. if (Result)
  1710. {
  1711. FSessionInfo.CertificateVerifiedManually = true;
  1712. }
  1713. else
  1714. {
  1715. UnicodeString Message;
  1716. Result = NeonWindowsValidateCertificateWithMessage(Data, Message);
  1717. FTerminal->LogEvent(0, Message);
  1718. }
  1719. FSessionInfo.Certificate = CertificateSummary(Data, SessionContext->HostName);
  1720. if (!Result)
  1721. {
  1722. if (FTerminal->ConfirmCertificate(FSessionInfo, Data.Failures, HttpsCertificateStorageKey, !Aux))
  1723. {
  1724. Result = true;
  1725. FSessionInfo.CertificateVerifiedManually = true;
  1726. }
  1727. }
  1728. if (Result && !Aux && (SessionContext == FSessionContext))
  1729. {
  1730. CollectTLSSessionInfo();
  1731. }
  1732. }
  1733. return Result;
  1734. }
  1735. //------------------------------------------------------------------------------
  1736. void __fastcall TWebDAVFileSystem::CollectTLSSessionInfo()
  1737. {
  1738. // See also TFTPFileSystem::Open().
  1739. // Have to cache the value as the connection (the neon HTTP session, not "our" session)
  1740. // can be closed at the time we need it in CollectUsage().
  1741. UnicodeString Message = NeonTlsSessionInfo(FSessionContext->NeonSession, FSessionInfo, FTlsVersionStr);
  1742. FTerminal->LogEvent(0, Message);
  1743. }
  1744. //------------------------------------------------------------------------------
  1745. // A neon-session callback to validate the SSL certificate when the CA
  1746. // is unknown (e.g. a self-signed cert), or there are other SSL
  1747. // certificate problems.
  1748. int TWebDAVFileSystem::DoNeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate, bool Aux)
  1749. {
  1750. TNeonCertificateData Data;
  1751. RetrieveNeonCertificateData(Failures, Certificate, Data);
  1752. TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
  1753. TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
  1754. return FileSystem->VerifyCertificate(SessionContext, Data, Aux) ? NE_OK : NE_ERROR;
  1755. }
  1756. //------------------------------------------------------------------------------
  1757. int TWebDAVFileSystem::NeonServerSSLCallbackMain(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  1758. {
  1759. return DoNeonServerSSLCallback(UserData, Failures, Certificate, false);
  1760. }
  1761. //------------------------------------------------------------------------------
  1762. int TWebDAVFileSystem::NeonServerSSLCallbackAux(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  1763. {
  1764. return DoNeonServerSSLCallback(UserData, Failures, Certificate, true);
  1765. }
  1766. //------------------------------------------------------------------------------
  1767. void TWebDAVFileSystem::NeonProvideClientCert(void * UserData, ne_session * Sess,
  1768. const ne_ssl_dname * const * /*DNames*/, int /*DNCount*/)
  1769. {
  1770. TWebDAVFileSystem * FileSystem = static_cast<TSessionContext *>(UserData)->FileSystem;
  1771. FileSystem->FTerminal->LogEvent(LoadStr(NEED_CLIENT_CERTIFICATE));
  1772. X509 * Certificate;
  1773. EVP_PKEY * PrivateKey;
  1774. if (FileSystem->FTerminal->LoadTlsCertificate(Certificate, PrivateKey))
  1775. {
  1776. ne_ssl_client_cert * NeonCertificate = ne_ssl_clicert_create(Certificate, PrivateKey);
  1777. ne_ssl_set_clicert(Sess, NeonCertificate);
  1778. ne_ssl_clicert_free(NeonCertificate);
  1779. }
  1780. }
  1781. //------------------------------------------------------------------------------
  1782. int TWebDAVFileSystem::NeonRequestAuth(
  1783. void * UserData, const char * Realm, int Attempt, char * UserName, char * Password)
  1784. {
  1785. DebugUsedParam(Realm);
  1786. DebugUsedParam(Attempt);
  1787. TWebDAVFileSystem * FileSystem = static_cast<TSessionContext *>(UserData)->FileSystem;
  1788. TTerminal * Terminal = FileSystem->FTerminal;
  1789. TSessionData * SessionData = Terminal->SessionData;
  1790. bool Result = true;
  1791. // will ask for username only once
  1792. if (FileSystem->FUserName.IsEmpty())
  1793. {
  1794. if (!SessionData->UserName.IsEmpty())
  1795. {
  1796. FileSystem->FUserName = SessionData->UserNameExpanded;
  1797. }
  1798. else
  1799. {
  1800. Terminal->LogEvent(L"Username prompt");
  1801. if (!Terminal->PromptUser(SessionData, pkUserName, LoadStr(USERNAME_TITLE), L"",
  1802. LoadStr(USERNAME_PROMPT2), true, NE_ABUFSIZ, FileSystem->FUserName))
  1803. {
  1804. // note that we never get here actually
  1805. Result = false;
  1806. }
  1807. }
  1808. }
  1809. UnicodeString APassword;
  1810. if (Result)
  1811. {
  1812. // Some servers (Gallery2 on discontinued g2.pixi.me)
  1813. // return authentication error (401) on PROPFIND request for
  1814. // non-existing files.
  1815. // When we already tried password before, do not try anymore.
  1816. // When we did not try password before (possible only when
  1817. // server does not require authentication for any previous request,
  1818. // such as when read access is not authenticated), try it now,
  1819. // but use special flag for the try, because when it fails
  1820. // we still want to try password for future requests (such as PUT).
  1821. if (!FileSystem->FPassword.IsEmpty())
  1822. {
  1823. if (FileSystem->FIgnoreAuthenticationFailure == iafPasswordFailed)
  1824. {
  1825. // Fail PROPFIND /nonexising request...
  1826. Result = false;
  1827. }
  1828. else
  1829. {
  1830. APassword = Terminal->DecryptPassword(FileSystem->FPassword);
  1831. }
  1832. }
  1833. else
  1834. {
  1835. if (!SessionData->Password.IsEmpty() && !FileSystem->FStoredPasswordTried)
  1836. {
  1837. APassword = NormalizeString(SessionData->Password);
  1838. FileSystem->FStoredPasswordTried = true;
  1839. }
  1840. else
  1841. {
  1842. // Asking for password (or using configured password) the first time,
  1843. // and asking for password.
  1844. // Note that we never get false here actually
  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. //---------------------------------------------------------------------------