WebDAVFileSystem.cpp 79 KB

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