HttpListenerHost.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Sockets;
  8. using System.Net.WebSockets;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Jellyfin.Data.Events;
  12. using MediaBrowser.Common.Extensions;
  13. using MediaBrowser.Common.Net;
  14. using MediaBrowser.Controller;
  15. using MediaBrowser.Controller.Authentication;
  16. using MediaBrowser.Controller.Configuration;
  17. using MediaBrowser.Controller.Net;
  18. using MediaBrowser.Model.Globalization;
  19. using Microsoft.AspNetCore.Http;
  20. using Microsoft.AspNetCore.Http.Extensions;
  21. using Microsoft.AspNetCore.WebUtilities;
  22. using Microsoft.Extensions.Configuration;
  23. using Microsoft.Extensions.Hosting;
  24. using Microsoft.Extensions.Logging;
  25. using Microsoft.Extensions.Primitives;
  26. namespace Emby.Server.Implementations.HttpServer
  27. {
  28. public class HttpListenerHost : IHttpServer
  29. {
  30. /// <summary>
  31. /// The key for a setting that specifies the default redirect path
  32. /// to use for requests where the URL base prefix is invalid or missing.
  33. /// </summary>
  34. public const string DefaultRedirectKey = "HttpListenerHost:DefaultRedirectPath";
  35. private readonly ILogger<HttpListenerHost> _logger;
  36. private readonly ILoggerFactory _loggerFactory;
  37. private readonly IServerConfigurationManager _config;
  38. private readonly INetworkManager _networkManager;
  39. private readonly IServerApplicationHost _appHost;
  40. private readonly string _defaultRedirectPath;
  41. private readonly string _baseUrlPrefix;
  42. private readonly IHostEnvironment _hostEnvironment;
  43. private IWebSocketListener[] _webSocketListeners = Array.Empty<IWebSocketListener>();
  44. private bool _disposed = false;
  45. public HttpListenerHost(
  46. IServerApplicationHost applicationHost,
  47. ILogger<HttpListenerHost> logger,
  48. IServerConfigurationManager config,
  49. IConfiguration configuration,
  50. INetworkManager networkManager,
  51. ILocalizationManager localizationManager,
  52. IHostEnvironment hostEnvironment,
  53. ILoggerFactory loggerFactory)
  54. {
  55. _appHost = applicationHost;
  56. _logger = logger;
  57. _config = config;
  58. _defaultRedirectPath = configuration[DefaultRedirectKey];
  59. _baseUrlPrefix = _config.Configuration.BaseUrl;
  60. _networkManager = networkManager;
  61. _hostEnvironment = hostEnvironment;
  62. _loggerFactory = loggerFactory;
  63. Instance = this;
  64. GlobalResponse = localizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
  65. }
  66. public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
  67. public static HttpListenerHost Instance { get; protected set; }
  68. public string[] UrlPrefixes { get; private set; }
  69. public string GlobalResponse { get; set; }
  70. private static string NormalizeUrlPath(string path)
  71. {
  72. if (path.Length > 0 && path[0] == '/')
  73. {
  74. // If the path begins with a leading slash, just return it as-is
  75. return path;
  76. }
  77. else
  78. {
  79. // If the path does not begin with a leading slash, append one for consistency
  80. return "/" + path;
  81. }
  82. }
  83. private static Exception GetActualException(Exception ex)
  84. {
  85. if (ex is AggregateException agg)
  86. {
  87. var inner = agg.InnerException;
  88. if (inner != null)
  89. {
  90. return GetActualException(inner);
  91. }
  92. else
  93. {
  94. var inners = agg.InnerExceptions;
  95. if (inners.Count > 0)
  96. {
  97. return GetActualException(inners[0]);
  98. }
  99. }
  100. }
  101. return ex;
  102. }
  103. private int GetStatusCode(Exception ex)
  104. {
  105. switch (ex)
  106. {
  107. case ArgumentException _: return 400;
  108. case AuthenticationException _: return 401;
  109. case SecurityException _: return 403;
  110. case DirectoryNotFoundException _:
  111. case FileNotFoundException _:
  112. case ResourceNotFoundException _: return 404;
  113. case MethodNotAllowedException _: return 405;
  114. default: return 500;
  115. }
  116. }
  117. private async Task ErrorHandler(Exception ex, HttpContext httpContext, int statusCode, string urlToLog, bool ignoreStackTrace)
  118. {
  119. if (ignoreStackTrace)
  120. {
  121. _logger.LogError("Error processing request: {Message}. URL: {Url}", ex.Message.TrimEnd('.'), urlToLog);
  122. }
  123. else
  124. {
  125. _logger.LogError(ex, "Error processing request. URL: {Url}", urlToLog);
  126. }
  127. var httpRes = httpContext.Response;
  128. if (httpRes.HasStarted)
  129. {
  130. return;
  131. }
  132. httpRes.StatusCode = statusCode;
  133. var errContent = _hostEnvironment.IsDevelopment()
  134. ? (NormalizeExceptionMessage(ex) ?? string.Empty)
  135. : "Error processing request.";
  136. httpRes.ContentType = "text/plain";
  137. httpRes.ContentLength = errContent.Length;
  138. await httpRes.WriteAsync(errContent).ConfigureAwait(false);
  139. }
  140. private string NormalizeExceptionMessage(Exception ex)
  141. {
  142. // Do not expose the exception message for AuthenticationException
  143. if (ex is AuthenticationException)
  144. {
  145. return null;
  146. }
  147. // Strip any information we don't want to reveal
  148. return ex.Message
  149. ?.Replace(_config.ApplicationPaths.ProgramSystemPath, string.Empty, StringComparison.OrdinalIgnoreCase)
  150. .Replace(_config.ApplicationPaths.ProgramDataPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  151. }
  152. public static string RemoveQueryStringByKey(string url, string key)
  153. {
  154. var uri = new Uri(url);
  155. // this gets all the query string key value pairs as a collection
  156. var newQueryString = QueryHelpers.ParseQuery(uri.Query);
  157. var originalCount = newQueryString.Count;
  158. if (originalCount == 0)
  159. {
  160. return url;
  161. }
  162. // this removes the key if exists
  163. newQueryString.Remove(key);
  164. if (originalCount == newQueryString.Count)
  165. {
  166. return url;
  167. }
  168. // this gets the page path from root without QueryString
  169. string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
  170. return newQueryString.Count > 0
  171. ? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
  172. : pagePathWithoutQueryString;
  173. }
  174. private static string GetUrlToLog(string url)
  175. {
  176. url = RemoveQueryStringByKey(url, "api_key");
  177. return url;
  178. }
  179. private static string NormalizeConfiguredLocalAddress(string address)
  180. {
  181. var add = address.AsSpan().Trim('/');
  182. int index = add.IndexOf('/');
  183. if (index != -1)
  184. {
  185. add = add.Slice(index + 1);
  186. }
  187. return add.TrimStart('/').ToString();
  188. }
  189. private bool ValidateHost(string host)
  190. {
  191. var hosts = _config
  192. .Configuration
  193. .LocalNetworkAddresses
  194. .Select(NormalizeConfiguredLocalAddress)
  195. .ToList();
  196. if (hosts.Count == 0)
  197. {
  198. return true;
  199. }
  200. host ??= string.Empty;
  201. if (_networkManager.IsInPrivateAddressSpace(host))
  202. {
  203. hosts.Add("localhost");
  204. hosts.Add("127.0.0.1");
  205. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  206. }
  207. return true;
  208. }
  209. private bool ValidateRequest(string remoteIp, bool isLocal)
  210. {
  211. if (isLocal)
  212. {
  213. return true;
  214. }
  215. if (_config.Configuration.EnableRemoteAccess)
  216. {
  217. var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  218. if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
  219. {
  220. if (_config.Configuration.IsRemoteIPFilterBlacklist)
  221. {
  222. return !_networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  223. }
  224. else
  225. {
  226. return _networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  227. }
  228. }
  229. }
  230. else
  231. {
  232. if (!_networkManager.IsInLocalNetwork(remoteIp))
  233. {
  234. return false;
  235. }
  236. }
  237. return true;
  238. }
  239. /// <summary>
  240. /// Validate a connection from a remote IP address to a URL to see if a redirection to HTTPS is required.
  241. /// </summary>
  242. /// <returns>True if the request is valid, or false if the request is not valid and an HTTPS redirect is required.</returns>
  243. private bool ValidateSsl(string remoteIp, string urlString)
  244. {
  245. if (_config.Configuration.RequireHttps
  246. && _appHost.ListenWithHttps
  247. && !urlString.Contains("https://", StringComparison.OrdinalIgnoreCase))
  248. {
  249. // These are hacks, but if these ever occur on ipv6 in the local network they could be incorrectly redirected
  250. if (urlString.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) != -1
  251. || urlString.IndexOf("dlna/", StringComparison.OrdinalIgnoreCase) != -1)
  252. {
  253. return true;
  254. }
  255. if (!_networkManager.IsInLocalNetwork(remoteIp))
  256. {
  257. return false;
  258. }
  259. }
  260. return true;
  261. }
  262. /// <inheritdoc />
  263. public Task RequestHandler(HttpContext context)
  264. {
  265. if (context.WebSockets.IsWebSocketRequest)
  266. {
  267. return WebSocketRequestHandler(context);
  268. }
  269. return RequestHandler(context, context.RequestAborted);
  270. }
  271. /// <summary>
  272. /// Overridable method that can be used to implement a custom handler.
  273. /// </summary>
  274. private async Task RequestHandler(HttpContext httpContext, CancellationToken cancellationToken)
  275. {
  276. var stopWatch = new Stopwatch();
  277. stopWatch.Start();
  278. var httpRes = httpContext.Response;
  279. var host = httpContext.Request.Host.ToString();
  280. var localPath = httpContext.Request.Path.ToString();
  281. var urlString = httpContext.Request.GetDisplayUrl();
  282. string urlToLog = GetUrlToLog(urlString);
  283. string remoteIp = httpContext.Request.RemoteIp();
  284. try
  285. {
  286. if (_disposed)
  287. {
  288. httpRes.StatusCode = 503;
  289. httpRes.ContentType = "text/plain";
  290. await httpRes.WriteAsync("Server shutting down", cancellationToken).ConfigureAwait(false);
  291. return;
  292. }
  293. if (!ValidateHost(host))
  294. {
  295. httpRes.StatusCode = 400;
  296. httpRes.ContentType = "text/plain";
  297. await httpRes.WriteAsync("Invalid host", cancellationToken).ConfigureAwait(false);
  298. return;
  299. }
  300. if (!ValidateRequest(remoteIp, httpContext.Request.IsLocal()))
  301. {
  302. httpRes.StatusCode = 403;
  303. httpRes.ContentType = "text/plain";
  304. await httpRes.WriteAsync("Forbidden", cancellationToken).ConfigureAwait(false);
  305. return;
  306. }
  307. if (!ValidateSsl(httpContext.Request.RemoteIp(), urlString))
  308. {
  309. RedirectToSecureUrl(httpRes, urlString);
  310. return;
  311. }
  312. if (string.Equals(httpContext.Request.Method, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  313. {
  314. httpRes.StatusCode = 200;
  315. foreach (var (key, value) in GetDefaultCorsHeaders(httpContext))
  316. {
  317. httpRes.Headers.Add(key, value);
  318. }
  319. httpRes.ContentType = "text/plain";
  320. await httpRes.WriteAsync(string.Empty, cancellationToken).ConfigureAwait(false);
  321. return;
  322. }
  323. if (string.Equals(localPath, _baseUrlPrefix + "/", StringComparison.OrdinalIgnoreCase)
  324. || string.Equals(localPath, _baseUrlPrefix, StringComparison.OrdinalIgnoreCase)
  325. || string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase)
  326. || string.IsNullOrEmpty(localPath)
  327. || !localPath.StartsWith(_baseUrlPrefix, StringComparison.OrdinalIgnoreCase))
  328. {
  329. // Always redirect back to the default path if the base prefix is invalid or missing
  330. _logger.LogDebug("Normalizing a URL at {0}", localPath);
  331. httpRes.Redirect(_baseUrlPrefix + "/" + _defaultRedirectPath);
  332. return;
  333. }
  334. if (!string.IsNullOrEmpty(GlobalResponse))
  335. {
  336. // We don't want the address pings in ApplicationHost to fail
  337. if (localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  338. {
  339. httpRes.StatusCode = 503;
  340. httpRes.ContentType = "text/html";
  341. await httpRes.WriteAsync(GlobalResponse, cancellationToken).ConfigureAwait(false);
  342. return;
  343. }
  344. }
  345. throw new FileNotFoundException();
  346. }
  347. catch (Exception requestEx)
  348. {
  349. try
  350. {
  351. var requestInnerEx = GetActualException(requestEx);
  352. var statusCode = GetStatusCode(requestInnerEx);
  353. foreach (var (key, value) in GetDefaultCorsHeaders(httpContext))
  354. {
  355. if (!httpRes.Headers.ContainsKey(key))
  356. {
  357. httpRes.Headers.Add(key, value);
  358. }
  359. }
  360. bool ignoreStackTrace =
  361. requestInnerEx is SocketException
  362. || requestInnerEx is IOException
  363. || requestInnerEx is OperationCanceledException
  364. || requestInnerEx is SecurityException
  365. || requestInnerEx is AuthenticationException
  366. || requestInnerEx is FileNotFoundException;
  367. // Do not handle 500 server exceptions manually when in development mode.
  368. // Instead, re-throw the exception so it can be handled by the DeveloperExceptionPageMiddleware.
  369. // However, do not use the DeveloperExceptionPageMiddleware when the stack trace should be ignored,
  370. // because it will log the stack trace when it handles the exception.
  371. if (statusCode == 500 && !ignoreStackTrace && _hostEnvironment.IsDevelopment())
  372. {
  373. throw;
  374. }
  375. await ErrorHandler(requestInnerEx, httpContext, statusCode, urlToLog, ignoreStackTrace).ConfigureAwait(false);
  376. }
  377. catch (Exception handlerException)
  378. {
  379. var aggregateEx = new AggregateException("Error while handling request exception", requestEx, handlerException);
  380. _logger.LogError(aggregateEx, "Error while handling exception in response to {Url}", urlToLog);
  381. if (_hostEnvironment.IsDevelopment())
  382. {
  383. throw aggregateEx;
  384. }
  385. }
  386. }
  387. finally
  388. {
  389. if (httpRes.StatusCode >= 500)
  390. {
  391. _logger.LogDebug("Sending HTTP Response 500 in response to {Url}", urlToLog);
  392. }
  393. stopWatch.Stop();
  394. var elapsed = stopWatch.Elapsed;
  395. if (elapsed.TotalMilliseconds > 500)
  396. {
  397. _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  398. }
  399. }
  400. }
  401. private async Task WebSocketRequestHandler(HttpContext context)
  402. {
  403. if (_disposed)
  404. {
  405. return;
  406. }
  407. try
  408. {
  409. _logger.LogInformation("WS {IP} request", context.Connection.RemoteIpAddress);
  410. WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
  411. using var connection = new WebSocketConnection(
  412. _loggerFactory.CreateLogger<WebSocketConnection>(),
  413. webSocket,
  414. context.Connection.RemoteIpAddress,
  415. context.Request.Query)
  416. {
  417. OnReceive = ProcessWebSocketMessageReceived
  418. };
  419. WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));
  420. await connection.ProcessAsync().ConfigureAwait(false);
  421. _logger.LogInformation("WS {IP} closed", context.Connection.RemoteIpAddress);
  422. }
  423. catch (Exception ex) // Otherwise ASP.Net will ignore the exception
  424. {
  425. _logger.LogError(ex, "WS {IP} WebSocketRequestHandler error", context.Connection.RemoteIpAddress);
  426. if (!context.Response.HasStarted)
  427. {
  428. context.Response.StatusCode = 500;
  429. }
  430. }
  431. }
  432. /// <summary>
  433. /// Get the default CORS headers.
  434. /// </summary>
  435. /// <param name="req"></param>
  436. /// <returns></returns>
  437. public IDictionary<string, string> GetDefaultCorsHeaders(HttpContext httpContext)
  438. {
  439. var origin = httpContext.Request.Headers["Origin"];
  440. if (origin == StringValues.Empty)
  441. {
  442. origin = httpContext.Request.Headers["Host"];
  443. if (origin == StringValues.Empty)
  444. {
  445. origin = "*";
  446. }
  447. }
  448. var headers = new Dictionary<string, string>();
  449. headers.Add("Access-Control-Allow-Origin", origin);
  450. headers.Add("Access-Control-Allow-Credentials", "true");
  451. headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  452. headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization, Cookie");
  453. return headers;
  454. }
  455. private void RedirectToSecureUrl(HttpResponse httpRes, string url)
  456. {
  457. if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
  458. {
  459. var builder = new UriBuilder(uri)
  460. {
  461. Port = _config.Configuration.PublicHttpsPort,
  462. Scheme = "https"
  463. };
  464. url = builder.Uri.ToString();
  465. }
  466. httpRes.Redirect(url);
  467. }
  468. /// <summary>
  469. /// Adds the rest handlers.
  470. /// </summary>
  471. /// <param name="listeners">The web socket listeners.</param>
  472. /// <param name="urlPrefixes">The URL prefixes. See <see cref="UrlPrefixes"/>.</param>
  473. public void Init(IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
  474. {
  475. _webSocketListeners = listeners.ToArray();
  476. UrlPrefixes = urlPrefixes.ToArray();
  477. }
  478. /// <summary>
  479. /// Processes the web socket message received.
  480. /// </summary>
  481. /// <param name="result">The result.</param>
  482. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  483. {
  484. if (_disposed)
  485. {
  486. return Task.CompletedTask;
  487. }
  488. IEnumerable<Task> GetTasks()
  489. {
  490. foreach (var x in _webSocketListeners)
  491. {
  492. yield return x.ProcessMessageAsync(result);
  493. }
  494. }
  495. return Task.WhenAll(GetTasks());
  496. }
  497. }
  498. }