HttpListenerHost.cs 28 KB

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