WebDAVFileSystem.cpp 74 KB

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