2
0

HttpListenerHost.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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.Reflection;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Emby.Server.Implementations.Services;
  13. using Emby.Server.Implementations.SocketSharp;
  14. using MediaBrowser.Common.Extensions;
  15. using MediaBrowser.Common.Net;
  16. using MediaBrowser.Controller;
  17. using MediaBrowser.Controller.Authentication;
  18. using MediaBrowser.Controller.Configuration;
  19. using MediaBrowser.Controller.Net;
  20. using MediaBrowser.Model.Events;
  21. using MediaBrowser.Model.Globalization;
  22. using MediaBrowser.Model.Serialization;
  23. using MediaBrowser.Model.Services;
  24. using Microsoft.AspNetCore.Http;
  25. using Microsoft.AspNetCore.Http.Extensions;
  26. using Microsoft.AspNetCore.WebUtilities;
  27. using Microsoft.Extensions.Configuration;
  28. using Microsoft.Extensions.Hosting;
  29. using Microsoft.Extensions.Logging;
  30. using Microsoft.Extensions.Primitives;
  31. using ServiceStack.Text.Jsv;
  32. namespace Emby.Server.Implementations.HttpServer
  33. {
  34. public class HttpListenerHost : IHttpServer
  35. {
  36. /// <summary>
  37. /// The key for a setting that specifies the default redirect path
  38. /// to use for requests where the URL base prefix is invalid or missing.
  39. /// </summary>
  40. public const string DefaultRedirectKey = "HttpListenerHost:DefaultRedirectPath";
  41. private readonly ILogger _logger;
  42. private readonly ILoggerFactory _loggerFactory;
  43. private readonly IServerConfigurationManager _config;
  44. private readonly INetworkManager _networkManager;
  45. private readonly IServerApplicationHost _appHost;
  46. private readonly IJsonSerializer _jsonSerializer;
  47. private readonly IXmlSerializer _xmlSerializer;
  48. private readonly Func<Type, Func<string, object>> _funcParseFn;
  49. private readonly string _defaultRedirectPath;
  50. private readonly string _baseUrlPrefix;
  51. private readonly Dictionary<Type, Type> _serviceOperationsMap = new Dictionary<Type, Type>();
  52. private readonly IHostEnvironment _hostEnvironment;
  53. private IWebSocketListener[] _webSocketListeners = Array.Empty<IWebSocketListener>();
  54. private bool _disposed = false;
  55. public HttpListenerHost(
  56. IServerApplicationHost applicationHost,
  57. ILogger<HttpListenerHost> logger,
  58. IServerConfigurationManager config,
  59. IConfiguration configuration,
  60. INetworkManager networkManager,
  61. IJsonSerializer jsonSerializer,
  62. IXmlSerializer xmlSerializer,
  63. ILocalizationManager localizationManager,
  64. ServiceController serviceController,
  65. IHostEnvironment hostEnvironment,
  66. ILoggerFactory loggerFactory)
  67. {
  68. _appHost = applicationHost;
  69. _logger = logger;
  70. _config = config;
  71. _defaultRedirectPath = configuration[DefaultRedirectKey];
  72. _baseUrlPrefix = _config.Configuration.BaseUrl;
  73. _networkManager = networkManager;
  74. _jsonSerializer = jsonSerializer;
  75. _xmlSerializer = xmlSerializer;
  76. ServiceController = serviceController;
  77. _hostEnvironment = hostEnvironment;
  78. _loggerFactory = loggerFactory;
  79. _funcParseFn = t => s => JsvReader.GetParseFn(t)(s);
  80. Instance = this;
  81. ResponseFilters = Array.Empty<Action<IRequest, HttpResponse, object>>();
  82. GlobalResponse = localizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
  83. }
  84. public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
  85. public Action<IRequest, HttpResponse, object>[] ResponseFilters { get; set; }
  86. public static HttpListenerHost Instance { get; protected set; }
  87. public string[] UrlPrefixes { get; private set; }
  88. public string GlobalResponse { get; set; }
  89. public ServiceController ServiceController { get; }
  90. public object CreateInstance(Type type)
  91. {
  92. return _appHost.CreateInstance(type);
  93. }
  94. private static string NormalizeUrlPath(string path)
  95. {
  96. if (path.Length > 0 && path[0] == '/')
  97. {
  98. // If the path begins with a leading slash, just return it as-is
  99. return path;
  100. }
  101. else
  102. {
  103. // If the path does not begin with a leading slash, append one for consistency
  104. return "/" + path;
  105. }
  106. }
  107. /// <summary>
  108. /// Applies the request filters. Returns whether or not the request has been handled
  109. /// and no more processing should be done.
  110. /// </summary>
  111. /// <returns></returns>
  112. public void ApplyRequestFilters(IRequest req, HttpResponse res, object requestDto)
  113. {
  114. // Exec all RequestFilter attributes with Priority < 0
  115. var attributes = GetRequestFilterAttributes(requestDto.GetType());
  116. int count = attributes.Count;
  117. int i = 0;
  118. for (; i < count && attributes[i].Priority < 0; i++)
  119. {
  120. var attribute = attributes[i];
  121. attribute.RequestFilter(req, res, requestDto);
  122. }
  123. // Exec remaining RequestFilter attributes with Priority >= 0
  124. for (; i < count && attributes[i].Priority >= 0; i++)
  125. {
  126. var attribute = attributes[i];
  127. attribute.RequestFilter(req, res, requestDto);
  128. }
  129. }
  130. public Type GetServiceTypeByRequest(Type requestType)
  131. {
  132. _serviceOperationsMap.TryGetValue(requestType, out var serviceType);
  133. return serviceType;
  134. }
  135. public void AddServiceInfo(Type serviceType, Type requestType)
  136. {
  137. _serviceOperationsMap[requestType] = serviceType;
  138. }
  139. private List<IHasRequestFilter> GetRequestFilterAttributes(Type requestDtoType)
  140. {
  141. var attributes = requestDtoType.GetCustomAttributes(true).OfType<IHasRequestFilter>().ToList();
  142. var serviceType = GetServiceTypeByRequest(requestDtoType);
  143. if (serviceType != null)
  144. {
  145. attributes.AddRange(serviceType.GetCustomAttributes(true).OfType<IHasRequestFilter>());
  146. }
  147. attributes.Sort((x, y) => x.Priority - y.Priority);
  148. return attributes;
  149. }
  150. private static Exception GetActualException(Exception ex)
  151. {
  152. if (ex is AggregateException agg)
  153. {
  154. var inner = agg.InnerException;
  155. if (inner != null)
  156. {
  157. return GetActualException(inner);
  158. }
  159. else
  160. {
  161. var inners = agg.InnerExceptions;
  162. if (inners.Count > 0)
  163. {
  164. return GetActualException(inners[0]);
  165. }
  166. }
  167. }
  168. return ex;
  169. }
  170. private int GetStatusCode(Exception ex)
  171. {
  172. switch (ex)
  173. {
  174. case ArgumentException _: return 400;
  175. case AuthenticationException _: return 401;
  176. case SecurityException _: return 403;
  177. case DirectoryNotFoundException _:
  178. case FileNotFoundException _:
  179. case ResourceNotFoundException _: return 404;
  180. case MethodNotAllowedException _: return 405;
  181. default: return 500;
  182. }
  183. }
  184. private async Task ErrorHandler(Exception ex, IRequest httpReq, int statusCode, string urlToLog, bool ignoreStackTrace)
  185. {
  186. if (ignoreStackTrace)
  187. {
  188. _logger.LogError("Error processing request: {Message}. URL: {Url}", ex.Message.TrimEnd('.'), urlToLog);
  189. }
  190. else
  191. {
  192. _logger.LogError(ex, "Error processing request. URL: {Url}", urlToLog);
  193. }
  194. var httpRes = httpReq.Response;
  195. if (httpRes.HasStarted)
  196. {
  197. return;
  198. }
  199. httpRes.StatusCode = statusCode;
  200. if (!_hostEnvironment.IsDevelopment())
  201. {
  202. await httpRes.WriteAsync("Error processing request.").ConfigureAwait(false);
  203. return;
  204. }
  205. var errContent = NormalizeExceptionMessage(ex) ?? string.Empty;
  206. httpRes.ContentType = "text/plain";
  207. httpRes.ContentLength = errContent.Length;
  208. await httpRes.WriteAsync(errContent).ConfigureAwait(false);
  209. }
  210. private string NormalizeExceptionMessage(Exception ex)
  211. {
  212. // Do not expose the exception message for AuthenticationException
  213. if (ex is AuthenticationException)
  214. {
  215. return null;
  216. }
  217. // Strip any information we don't want to reveal
  218. return ex.Message
  219. ?.Replace(_config.ApplicationPaths.ProgramSystemPath, string.Empty, StringComparison.OrdinalIgnoreCase)
  220. .Replace(_config.ApplicationPaths.ProgramDataPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  221. }
  222. public static string RemoveQueryStringByKey(string url, string key)
  223. {
  224. var uri = new Uri(url);
  225. // this gets all the query string key value pairs as a collection
  226. var newQueryString = QueryHelpers.ParseQuery(uri.Query);
  227. var originalCount = newQueryString.Count;
  228. if (originalCount == 0)
  229. {
  230. return url;
  231. }
  232. // this removes the key if exists
  233. newQueryString.Remove(key);
  234. if (originalCount == newQueryString.Count)
  235. {
  236. return url;
  237. }
  238. // this gets the page path from root without QueryString
  239. string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
  240. return newQueryString.Count > 0
  241. ? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
  242. : pagePathWithoutQueryString;
  243. }
  244. private static string GetUrlToLog(string url)
  245. {
  246. url = RemoveQueryStringByKey(url, "api_key");
  247. return url;
  248. }
  249. private static string NormalizeConfiguredLocalAddress(string address)
  250. {
  251. var add = address.AsSpan().Trim('/');
  252. int index = add.IndexOf('/');
  253. if (index != -1)
  254. {
  255. add = add.Slice(index + 1);
  256. }
  257. return add.TrimStart('/').ToString();
  258. }
  259. private bool ValidateHost(string host)
  260. {
  261. var hosts = _config
  262. .Configuration
  263. .LocalNetworkAddresses
  264. .Select(NormalizeConfiguredLocalAddress)
  265. .ToList();
  266. if (hosts.Count == 0)
  267. {
  268. return true;
  269. }
  270. host ??= string.Empty;
  271. if (_networkManager.IsInPrivateAddressSpace(host))
  272. {
  273. hosts.Add("localhost");
  274. hosts.Add("127.0.0.1");
  275. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  276. }
  277. return true;
  278. }
  279. private bool ValidateRequest(string remoteIp, bool isLocal)
  280. {
  281. if (isLocal)
  282. {
  283. return true;
  284. }
  285. if (_config.Configuration.EnableRemoteAccess)
  286. {
  287. var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  288. if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
  289. {
  290. if (_config.Configuration.IsRemoteIPFilterBlacklist)
  291. {
  292. return !_networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  293. }
  294. else
  295. {
  296. return _networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  297. }
  298. }
  299. }
  300. else
  301. {
  302. if (!_networkManager.IsInLocalNetwork(remoteIp))
  303. {
  304. return false;
  305. }
  306. }
  307. return true;
  308. }
  309. /// <summary>
  310. /// Validate a connection from a remote IP address to a URL to see if a redirection to HTTPS is required.
  311. /// </summary>
  312. /// <returns>True if the request is valid, or false if the request is not valid and an HTTPS redirect is required.</returns>
  313. private bool ValidateSsl(string remoteIp, string urlString)
  314. {
  315. if (_config.Configuration.RequireHttps
  316. && _appHost.ListenWithHttps
  317. && !urlString.Contains("https://", StringComparison.OrdinalIgnoreCase))
  318. {
  319. // These are hacks, but if these ever occur on ipv6 in the local network they could be incorrectly redirected
  320. if (urlString.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) != -1
  321. || urlString.IndexOf("dlna/", StringComparison.OrdinalIgnoreCase) != -1)
  322. {
  323. return true;
  324. }
  325. if (!_networkManager.IsInLocalNetwork(remoteIp))
  326. {
  327. return false;
  328. }
  329. }
  330. return true;
  331. }
  332. /// <inheritdoc />
  333. public Task RequestHandler(HttpContext context)
  334. {
  335. if (context.WebSockets.IsWebSocketRequest)
  336. {
  337. return WebSocketRequestHandler(context);
  338. }
  339. var request = context.Request;
  340. var response = context.Response;
  341. var localPath = context.Request.Path.ToString();
  342. var req = new WebSocketSharpRequest(request, response, request.Path, _logger);
  343. return RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, context.RequestAborted);
  344. }
  345. /// <summary>
  346. /// Overridable method that can be used to implement a custom handler.
  347. /// </summary>
  348. private async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
  349. {
  350. var stopWatch = new Stopwatch();
  351. stopWatch.Start();
  352. var httpRes = httpReq.Response;
  353. string urlToLog = GetUrlToLog(urlString);
  354. string remoteIp = httpReq.RemoteIp;
  355. try
  356. {
  357. if (_disposed)
  358. {
  359. httpRes.StatusCode = 503;
  360. httpRes.ContentType = "text/plain";
  361. await httpRes.WriteAsync("Server shutting down", cancellationToken).ConfigureAwait(false);
  362. return;
  363. }
  364. if (!ValidateHost(host))
  365. {
  366. httpRes.StatusCode = 400;
  367. httpRes.ContentType = "text/plain";
  368. await httpRes.WriteAsync("Invalid host", cancellationToken).ConfigureAwait(false);
  369. return;
  370. }
  371. if (!ValidateRequest(remoteIp, httpReq.IsLocal))
  372. {
  373. httpRes.StatusCode = 403;
  374. httpRes.ContentType = "text/plain";
  375. await httpRes.WriteAsync("Forbidden", cancellationToken).ConfigureAwait(false);
  376. return;
  377. }
  378. if (!ValidateSsl(httpReq.RemoteIp, urlString))
  379. {
  380. RedirectToSecureUrl(httpReq, httpRes, urlString);
  381. return;
  382. }
  383. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  384. {
  385. httpRes.StatusCode = 200;
  386. foreach(var (key, value) in GetDefaultCorsHeaders(httpReq))
  387. {
  388. httpRes.Headers.Add(key, value);
  389. }
  390. httpRes.ContentType = "text/plain";
  391. await httpRes.WriteAsync(string.Empty, cancellationToken).ConfigureAwait(false);
  392. return;
  393. }
  394. if (string.Equals(localPath, _baseUrlPrefix + "/", StringComparison.OrdinalIgnoreCase)
  395. || string.Equals(localPath, _baseUrlPrefix, StringComparison.OrdinalIgnoreCase)
  396. || string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase)
  397. || string.IsNullOrEmpty(localPath)
  398. || !localPath.StartsWith(_baseUrlPrefix, StringComparison.OrdinalIgnoreCase))
  399. {
  400. // Always redirect back to the default path if the base prefix is invalid or missing
  401. _logger.LogDebug("Normalizing a URL at {0}", localPath);
  402. httpRes.Redirect(_baseUrlPrefix + "/" + _defaultRedirectPath);
  403. return;
  404. }
  405. if (!string.IsNullOrEmpty(GlobalResponse))
  406. {
  407. // We don't want the address pings in ApplicationHost to fail
  408. if (localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  409. {
  410. httpRes.StatusCode = 503;
  411. httpRes.ContentType = "text/html";
  412. await httpRes.WriteAsync(GlobalResponse, cancellationToken).ConfigureAwait(false);
  413. return;
  414. }
  415. }
  416. var handler = GetServiceHandler(httpReq);
  417. if (handler != null)
  418. {
  419. await handler.ProcessRequestAsync(this, httpReq, httpRes, _logger, cancellationToken).ConfigureAwait(false);
  420. }
  421. else
  422. {
  423. throw new FileNotFoundException();
  424. }
  425. }
  426. catch (Exception requestEx)
  427. {
  428. try
  429. {
  430. var requestInnerEx = GetActualException(requestEx);
  431. var statusCode = GetStatusCode(requestInnerEx);
  432. foreach (var (key, value) in GetDefaultCorsHeaders(httpReq))
  433. {
  434. if (!httpRes.Headers.ContainsKey(key))
  435. {
  436. httpRes.Headers.Add(key, value);
  437. }
  438. }
  439. bool ignoreStackTrace =
  440. requestInnerEx is SocketException
  441. || requestInnerEx is IOException
  442. || requestInnerEx is OperationCanceledException
  443. || requestInnerEx is SecurityException
  444. || requestInnerEx is AuthenticationException
  445. || requestInnerEx is FileNotFoundException;
  446. // Do not handle 500 server exceptions manually when in development mode.
  447. // Instead, re-throw the exception so it can be handled by the DeveloperExceptionPageMiddleware.
  448. // However, do not use the DeveloperExceptionPageMiddleware when the stack trace should be ignored,
  449. // because it will log the stack trace when it handles the exception.
  450. if (statusCode == 500 && !ignoreStackTrace && _hostEnvironment.IsDevelopment())
  451. {
  452. throw;
  453. }
  454. await ErrorHandler(requestInnerEx, httpReq, statusCode, urlToLog, ignoreStackTrace).ConfigureAwait(false);
  455. }
  456. catch (Exception handlerException)
  457. {
  458. var aggregateEx = new AggregateException("Error while handling request exception", requestEx, handlerException);
  459. _logger.LogError(aggregateEx, "Error while handling exception in response to {Url}", urlToLog);
  460. if (_hostEnvironment.IsDevelopment())
  461. {
  462. throw aggregateEx;
  463. }
  464. }
  465. }
  466. finally
  467. {
  468. if (httpRes.StatusCode >= 500)
  469. {
  470. _logger.LogDebug("Sending HTTP Response 500 in response to {Url}", urlToLog);
  471. }
  472. stopWatch.Stop();
  473. var elapsed = stopWatch.Elapsed;
  474. if (elapsed.TotalMilliseconds > 500)
  475. {
  476. _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  477. }
  478. }
  479. }
  480. private async Task WebSocketRequestHandler(HttpContext context)
  481. {
  482. if (_disposed)
  483. {
  484. return;
  485. }
  486. try
  487. {
  488. _logger.LogInformation("WS {IP} request", context.Connection.RemoteIpAddress);
  489. WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
  490. var connection = new WebSocketConnection(
  491. _loggerFactory.CreateLogger<WebSocketConnection>(),
  492. webSocket,
  493. context.Connection.RemoteIpAddress,
  494. context.Request.Query)
  495. {
  496. OnReceive = ProcessWebSocketMessageReceived
  497. };
  498. WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));
  499. await connection.ProcessAsync().ConfigureAwait(false);
  500. _logger.LogInformation("WS {IP} closed", context.Connection.RemoteIpAddress);
  501. }
  502. catch (Exception ex) // Otherwise ASP.Net will ignore the exception
  503. {
  504. _logger.LogError(ex, "WS {IP} WebSocketRequestHandler error", context.Connection.RemoteIpAddress);
  505. if (!context.Response.HasStarted)
  506. {
  507. context.Response.StatusCode = 500;
  508. }
  509. }
  510. }
  511. /// <summary>
  512. /// Get the default CORS headers
  513. /// </summary>
  514. /// <param name="req"></param>
  515. /// <returns></returns>
  516. public IDictionary<string, string> GetDefaultCorsHeaders(IRequest req)
  517. {
  518. var origin = req.Headers["Origin"];
  519. if (origin == StringValues.Empty)
  520. {
  521. origin = req.Headers["Host"];
  522. if (origin == StringValues.Empty)
  523. {
  524. origin = "*";
  525. }
  526. }
  527. var headers = new Dictionary<string, string>();
  528. headers.Add("Access-Control-Allow-Origin", origin);
  529. headers.Add("Access-Control-Allow-Credentials", "true");
  530. headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  531. headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization, Cookie");
  532. return headers;
  533. }
  534. // Entry point for HttpListener
  535. public ServiceHandler GetServiceHandler(IHttpRequest httpReq)
  536. {
  537. var pathInfo = httpReq.PathInfo;
  538. pathInfo = ServiceHandler.GetSanitizedPathInfo(pathInfo, out string contentType);
  539. var restPath = ServiceController.GetRestPathForRequest(httpReq.HttpMethod, pathInfo);
  540. if (restPath != null)
  541. {
  542. return new ServiceHandler(restPath, contentType);
  543. }
  544. _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
  545. return null;
  546. }
  547. private void RedirectToSecureUrl(IHttpRequest httpReq, HttpResponse httpRes, string url)
  548. {
  549. if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
  550. {
  551. var builder = new UriBuilder(uri)
  552. {
  553. Port = _config.Configuration.PublicHttpsPort,
  554. Scheme = "https"
  555. };
  556. url = builder.Uri.ToString();
  557. }
  558. httpRes.Redirect(url);
  559. }
  560. /// <summary>
  561. /// Adds the rest handlers.
  562. /// </summary>
  563. /// <param name="serviceTypes">The service types to register with the <see cref="ServiceController"/>.</param>
  564. /// <param name="listeners">The web socket listeners.</param>
  565. /// <param name="urlPrefixes">The URL prefixes. See <see cref="UrlPrefixes"/>.</param>
  566. public void Init(IEnumerable<Type> serviceTypes, IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
  567. {
  568. _webSocketListeners = listeners.ToArray();
  569. UrlPrefixes = urlPrefixes.ToArray();
  570. ServiceController.Init(this, serviceTypes);
  571. ResponseFilters = new Action<IRequest, HttpResponse, object>[]
  572. {
  573. new ResponseFilter(this, _logger).FilterResponse
  574. };
  575. }
  576. public RouteAttribute[] GetRouteAttributes(Type requestType)
  577. {
  578. var routes = requestType.GetTypeInfo().GetCustomAttributes<RouteAttribute>(true).ToList();
  579. var clone = routes.ToList();
  580. foreach (var route in clone)
  581. {
  582. routes.Add(new RouteAttribute(NormalizeCustomRoutePath(route.Path), route.Verbs)
  583. {
  584. Notes = route.Notes,
  585. Priority = route.Priority,
  586. Summary = route.Summary
  587. });
  588. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  589. {
  590. Notes = route.Notes,
  591. Priority = route.Priority,
  592. Summary = route.Summary
  593. });
  594. routes.Add(new RouteAttribute(NormalizeMediaBrowserRoutePath(route.Path), route.Verbs)
  595. {
  596. Notes = route.Notes,
  597. Priority = route.Priority,
  598. Summary = route.Summary
  599. });
  600. }
  601. return routes.ToArray();
  602. }
  603. public Func<string, object> GetParseFn(Type propertyType)
  604. {
  605. return _funcParseFn(propertyType);
  606. }
  607. public void SerializeToJson(object o, Stream stream)
  608. {
  609. _jsonSerializer.SerializeToStream(o, stream);
  610. }
  611. public void SerializeToXml(object o, Stream stream)
  612. {
  613. _xmlSerializer.SerializeToStream(o, stream);
  614. }
  615. public Task<object> DeserializeXml(Type type, Stream stream)
  616. {
  617. return Task.FromResult(_xmlSerializer.DeserializeFromStream(type, stream));
  618. }
  619. public Task<object> DeserializeJson(Type type, Stream stream)
  620. {
  621. return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
  622. }
  623. private string NormalizeEmbyRoutePath(string path)
  624. {
  625. _logger.LogDebug("Normalizing /emby route");
  626. return _baseUrlPrefix + "/emby" + NormalizeUrlPath(path);
  627. }
  628. private string NormalizeMediaBrowserRoutePath(string path)
  629. {
  630. _logger.LogDebug("Normalizing /mediabrowser route");
  631. return _baseUrlPrefix + "/mediabrowser" + NormalizeUrlPath(path);
  632. }
  633. private string NormalizeCustomRoutePath(string path)
  634. {
  635. _logger.LogDebug("Normalizing custom route {0}", path);
  636. return _baseUrlPrefix + NormalizeUrlPath(path);
  637. }
  638. /// <summary>
  639. /// Processes the web socket message received.
  640. /// </summary>
  641. /// <param name="result">The result.</param>
  642. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  643. {
  644. if (_disposed)
  645. {
  646. return Task.CompletedTask;
  647. }
  648. IEnumerable<Task> GetTasks()
  649. {
  650. foreach (var x in _webSocketListeners)
  651. {
  652. yield return x.ProcessMessageAsync(result);
  653. }
  654. }
  655. return Task.WhenAll(GetTasks());
  656. }
  657. }
  658. }