HttpListenerHost.cs 21 KB

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