WebDAVFileSystem.cpp 79 KB

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