WebDAVFileSystem.cpp 79 KB

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