1
0

WebDAVFileSystem.cpp 79 KB

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