HttpListenerHost.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Sockets;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Emby.Server.Implementations.Net;
  13. using Emby.Server.Implementations.Services;
  14. using Emby.Server.Implementations.SocketSharp;
  15. using MediaBrowser.Common.Extensions;
  16. using MediaBrowser.Common.Net;
  17. using MediaBrowser.Controller;
  18. using MediaBrowser.Controller.Configuration;
  19. using MediaBrowser.Controller.Net;
  20. using MediaBrowser.Model.Events;
  21. using MediaBrowser.Model.Extensions;
  22. using MediaBrowser.Model.Serialization;
  23. using MediaBrowser.Model.Services;
  24. using Microsoft.AspNetCore.Http;
  25. using Microsoft.AspNetCore.Http.Internal;
  26. using Microsoft.AspNetCore.WebUtilities;
  27. using Microsoft.Extensions.Configuration;
  28. using Microsoft.Extensions.Logging;
  29. using ServiceStack.Text.Jsv;
  30. namespace Emby.Server.Implementations.HttpServer
  31. {
  32. public class HttpListenerHost : IHttpServer, IDisposable
  33. {
  34. private string DefaultRedirectPath { get; set; }
  35. private readonly ILogger _logger;
  36. public string[] UrlPrefixes { get; private set; }
  37. private IHttpListener _listener;
  38. public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
  39. private readonly IServerConfigurationManager _config;
  40. private readonly INetworkManager _networkManager;
  41. private readonly IServerApplicationHost _appHost;
  42. private readonly IJsonSerializer _jsonSerializer;
  43. private readonly IXmlSerializer _xmlSerializer;
  44. private readonly IHttpListener _socketListener;
  45. private readonly Func<Type, Func<string, object>> _funcParseFn;
  46. public Action<IRequest, IResponse, object>[] ResponseFilters { get; set; }
  47. private readonly Dictionary<Type, Type> ServiceOperationsMap = new Dictionary<Type, Type>();
  48. public static HttpListenerHost Instance { get; protected set; }
  49. private IWebSocketListener[] _webSocketListeners = Array.Empty<IWebSocketListener>();
  50. private readonly List<IWebSocketConnection> _webSocketConnections = new List<IWebSocketConnection>();
  51. public HttpListenerHost(
  52. IServerApplicationHost applicationHost,
  53. ILoggerFactory loggerFactory,
  54. IServerConfigurationManager config,
  55. IConfiguration configuration,
  56. INetworkManager networkManager,
  57. IJsonSerializer jsonSerializer,
  58. IXmlSerializer xmlSerializer,
  59. IHttpListener socketListener)
  60. {
  61. _appHost = applicationHost;
  62. _logger = loggerFactory.CreateLogger("HttpServer");
  63. _config = config;
  64. DefaultRedirectPath = configuration["HttpListenerHost:DefaultRedirectPath"];
  65. _networkManager = networkManager;
  66. _jsonSerializer = jsonSerializer;
  67. _xmlSerializer = xmlSerializer;
  68. _socketListener = socketListener;
  69. _socketListener.WebSocketConnected = OnWebSocketConnected;
  70. _funcParseFn = t => s => JsvReader.GetParseFn(t)(s);
  71. Instance = this;
  72. ResponseFilters = Array.Empty<Action<IRequest, IResponse, object>>();
  73. }
  74. public string GlobalResponse { get; set; }
  75. protected ILogger Logger => _logger;
  76. public object CreateInstance(Type type)
  77. {
  78. return _appHost.CreateInstance(type);
  79. }
  80. /// <summary>
  81. /// Applies the request filters. Returns whether or not the request has been handled
  82. /// and no more processing should be done.
  83. /// </summary>
  84. /// <returns></returns>
  85. public void ApplyRequestFilters(IRequest req, IResponse res, object requestDto)
  86. {
  87. //Exec all RequestFilter attributes with Priority < 0
  88. var attributes = GetRequestFilterAttributes(requestDto.GetType());
  89. int count = attributes.Count;
  90. int i = 0;
  91. for (; i < count && attributes[i].Priority < 0; i++)
  92. {
  93. var attribute = attributes[i];
  94. attribute.RequestFilter(req, res, requestDto);
  95. }
  96. //Exec remaining RequestFilter attributes with Priority >= 0
  97. for (; i < count && attributes[i].Priority >= 0; i++)
  98. {
  99. var attribute = attributes[i];
  100. attribute.RequestFilter(req, res, requestDto);
  101. }
  102. }
  103. public Type GetServiceTypeByRequest(Type requestType)
  104. {
  105. ServiceOperationsMap.TryGetValue(requestType, out var serviceType);
  106. return serviceType;
  107. }
  108. public void AddServiceInfo(Type serviceType, Type requestType)
  109. {
  110. ServiceOperationsMap[requestType] = serviceType;
  111. }
  112. private List<IHasRequestFilter> GetRequestFilterAttributes(Type requestDtoType)
  113. {
  114. var attributes = requestDtoType.GetTypeInfo().GetCustomAttributes(true).OfType<IHasRequestFilter>().ToList();
  115. var serviceType = GetServiceTypeByRequest(requestDtoType);
  116. if (serviceType != null)
  117. {
  118. attributes.AddRange(serviceType.GetTypeInfo().GetCustomAttributes(true).OfType<IHasRequestFilter>());
  119. }
  120. attributes.Sort((x, y) => x.Priority - y.Priority);
  121. return attributes;
  122. }
  123. private void OnWebSocketConnected(WebSocketConnectEventArgs e)
  124. {
  125. if (_disposed)
  126. {
  127. return;
  128. }
  129. var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger)
  130. {
  131. OnReceive = ProcessWebSocketMessageReceived,
  132. Url = e.Url,
  133. QueryString = e.QueryString ?? new QueryCollection()
  134. };
  135. connection.Closed += Connection_Closed;
  136. lock (_webSocketConnections)
  137. {
  138. _webSocketConnections.Add(connection);
  139. }
  140. WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));
  141. }
  142. private void Connection_Closed(object sender, EventArgs e)
  143. {
  144. lock (_webSocketConnections)
  145. {
  146. _webSocketConnections.Remove((IWebSocketConnection)sender);
  147. }
  148. }
  149. private static Exception GetActualException(Exception ex)
  150. {
  151. if (ex is AggregateException agg)
  152. {
  153. var inner = agg.InnerException;
  154. if (inner != null)
  155. {
  156. return GetActualException(inner);
  157. }
  158. else
  159. {
  160. var inners = agg.InnerExceptions;
  161. if (inners != null && inners.Count > 0)
  162. {
  163. return GetActualException(inners[0]);
  164. }
  165. }
  166. }
  167. return ex;
  168. }
  169. private int GetStatusCode(Exception ex)
  170. {
  171. switch (ex)
  172. {
  173. case ArgumentException _: return 400;
  174. case SecurityException _: return 401;
  175. case DirectoryNotFoundException _:
  176. case FileNotFoundException _:
  177. case ResourceNotFoundException _: return 404;
  178. case RemoteServiceUnavailableException _: return 502;
  179. default: return 500;
  180. }
  181. }
  182. private async Task ErrorHandler(Exception ex, IRequest httpReq, bool logExceptionStackTrace, bool logExceptionMessage)
  183. {
  184. try
  185. {
  186. ex = GetActualException(ex);
  187. if (logExceptionStackTrace)
  188. {
  189. _logger.LogError(ex, "Error processing request");
  190. }
  191. else if (logExceptionMessage)
  192. {
  193. _logger.LogError(ex.Message);
  194. }
  195. var httpRes = httpReq.Response;
  196. if (httpRes.IsClosed)
  197. {
  198. return;
  199. }
  200. var statusCode = GetStatusCode(ex);
  201. httpRes.StatusCode = statusCode;
  202. httpRes.ContentType = "text/html";
  203. await Write(httpRes, NormalizeExceptionMessage(ex.Message)).ConfigureAwait(false);
  204. }
  205. catch (Exception errorEx)
  206. {
  207. _logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)");
  208. }
  209. }
  210. private string NormalizeExceptionMessage(string msg)
  211. {
  212. if (msg == null)
  213. {
  214. return string.Empty;
  215. }
  216. // Strip any information we don't want to reveal
  217. msg = msg.Replace(_config.ApplicationPaths.ProgramSystemPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  218. msg = msg.Replace(_config.ApplicationPaths.ProgramDataPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  219. return msg;
  220. }
  221. /// <summary>
  222. /// Shut down the Web Service
  223. /// </summary>
  224. public void Stop()
  225. {
  226. List<IWebSocketConnection> connections;
  227. lock (_webSocketConnections)
  228. {
  229. connections = _webSocketConnections.ToList();
  230. _webSocketConnections.Clear();
  231. }
  232. foreach (var connection in connections)
  233. {
  234. try
  235. {
  236. connection.Dispose();
  237. }
  238. catch
  239. {
  240. }
  241. }
  242. if (_listener != null)
  243. {
  244. _logger.LogInformation("Stopping HttpListener...");
  245. var task = _listener.Stop();
  246. Task.WaitAll(task);
  247. _logger.LogInformation("HttpListener stopped");
  248. }
  249. }
  250. public static string RemoveQueryStringByKey(string url, string key)
  251. {
  252. var uri = new Uri(url);
  253. // this gets all the query string key value pairs as a collection
  254. var newQueryString = QueryHelpers.ParseQuery(uri.Query);
  255. var originalCount = newQueryString.Count;
  256. if (originalCount == 0)
  257. {
  258. return url;
  259. }
  260. // this removes the key if exists
  261. newQueryString.Remove(key);
  262. if (originalCount == newQueryString.Count)
  263. {
  264. return url;
  265. }
  266. // this gets the page path from root without QueryString
  267. string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
  268. return newQueryString.Count > 0
  269. ? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
  270. : pagePathWithoutQueryString;
  271. }
  272. private static string GetUrlToLog(string url)
  273. {
  274. url = RemoveQueryStringByKey(url, "api_key");
  275. return url;
  276. }
  277. private static string NormalizeConfiguredLocalAddress(string address)
  278. {
  279. var index = address.Trim('/').IndexOf('/');
  280. if (index != -1)
  281. {
  282. address = address.Substring(index + 1);
  283. }
  284. return address.Trim('/');
  285. }
  286. private bool ValidateHost(string host)
  287. {
  288. var hosts = _config
  289. .Configuration
  290. .LocalNetworkAddresses
  291. .Select(NormalizeConfiguredLocalAddress)
  292. .ToList();
  293. if (hosts.Count == 0)
  294. {
  295. return true;
  296. }
  297. host = host ?? string.Empty;
  298. if (_networkManager.IsInPrivateAddressSpace(host))
  299. {
  300. hosts.Add("localhost");
  301. hosts.Add("127.0.0.1");
  302. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  303. }
  304. return true;
  305. }
  306. private bool ValidateRequest(string remoteIp, bool isLocal)
  307. {
  308. if (isLocal)
  309. {
  310. return true;
  311. }
  312. if (_config.Configuration.EnableRemoteAccess)
  313. {
  314. var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  315. if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
  316. {
  317. if (_config.Configuration.IsRemoteIPFilterBlacklist)
  318. {
  319. return !_networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  320. }
  321. else
  322. {
  323. return _networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  324. }
  325. }
  326. }
  327. else
  328. {
  329. if (!_networkManager.IsInLocalNetwork(remoteIp))
  330. {
  331. return false;
  332. }
  333. }
  334. return true;
  335. }
  336. private bool ValidateSsl(string remoteIp, string urlString)
  337. {
  338. if (_config.Configuration.RequireHttps && _appHost.EnableHttps && !_config.Configuration.IsBehindProxy)
  339. {
  340. if (urlString.IndexOf("https://", StringComparison.OrdinalIgnoreCase) == -1)
  341. {
  342. // These are hacks, but if these ever occur on ipv6 in the local network they could be incorrectly redirected
  343. if (urlString.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) != -1 ||
  344. urlString.IndexOf("dlna/", StringComparison.OrdinalIgnoreCase) != -1)
  345. {
  346. return true;
  347. }
  348. if (!_networkManager.IsInLocalNetwork(remoteIp))
  349. {
  350. return false;
  351. }
  352. }
  353. }
  354. return true;
  355. }
  356. /// <summary>
  357. /// Overridable method that can be used to implement a custom hnandler
  358. /// </summary>
  359. public async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
  360. {
  361. var stopWatch = new Stopwatch();
  362. stopWatch.Start();
  363. var httpRes = httpReq.Response;
  364. string urlToLog = null;
  365. string remoteIp = httpReq.RemoteIp;
  366. try
  367. {
  368. if (_disposed)
  369. {
  370. httpRes.StatusCode = 503;
  371. httpRes.ContentType = "text/plain";
  372. await Write(httpRes, "Server shutting down").ConfigureAwait(false);
  373. return;
  374. }
  375. if (!ValidateHost(host))
  376. {
  377. httpRes.StatusCode = 400;
  378. httpRes.ContentType = "text/plain";
  379. await Write(httpRes, "Invalid host").ConfigureAwait(false);
  380. return;
  381. }
  382. if (!ValidateRequest(remoteIp, httpReq.IsLocal))
  383. {
  384. httpRes.StatusCode = 403;
  385. httpRes.ContentType = "text/plain";
  386. await Write(httpRes, "Forbidden").ConfigureAwait(false);
  387. return;
  388. }
  389. if (!ValidateSsl(httpReq.RemoteIp, urlString))
  390. {
  391. RedirectToSecureUrl(httpReq, httpRes, urlString);
  392. return;
  393. }
  394. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  395. {
  396. httpRes.StatusCode = 200;
  397. httpRes.AddHeader("Access-Control-Allow-Origin", "*");
  398. httpRes.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  399. httpRes.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
  400. httpRes.ContentType = "text/plain";
  401. await Write(httpRes, string.Empty).ConfigureAwait(false);
  402. return;
  403. }
  404. urlToLog = GetUrlToLog(urlString);
  405. Logger.LogDebug("HTTP {HttpMethod} {Url} UserAgent: {UserAgent} \nHeaders: {@Headers}", urlToLog, httpReq.UserAgent ?? string.Empty, httpReq.HttpMethod, httpReq.Headers);
  406. if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) ||
  407. string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
  408. {
  409. RedirectToUrl(httpRes, DefaultRedirectPath);
  410. return;
  411. }
  412. if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) ||
  413. string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
  414. {
  415. RedirectToUrl(httpRes, "emby/" + DefaultRedirectPath);
  416. return;
  417. }
  418. if (localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1)
  419. {
  420. httpRes.StatusCode = 200;
  421. httpRes.ContentType = "text/html";
  422. var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
  423. .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
  424. if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
  425. {
  426. await Write(httpRes,
  427. "<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" +
  428. newUrl + "\">" + newUrl + "</a></body></html>").ConfigureAwait(false);
  429. return;
  430. }
  431. }
  432. if (localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1 &&
  433. localPath.IndexOf("web/dashboard", StringComparison.OrdinalIgnoreCase) == -1)
  434. {
  435. httpRes.StatusCode = 200;
  436. httpRes.ContentType = "text/html";
  437. var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
  438. .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
  439. if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
  440. {
  441. await Write(httpRes,
  442. "<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" +
  443. newUrl + "\">" + newUrl + "</a></body></html>").ConfigureAwait(false);
  444. return;
  445. }
  446. }
  447. if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase))
  448. {
  449. RedirectToUrl(httpRes, DefaultRedirectPath);
  450. return;
  451. }
  452. if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase))
  453. {
  454. RedirectToUrl(httpRes, "../" + DefaultRedirectPath);
  455. return;
  456. }
  457. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  458. {
  459. RedirectToUrl(httpRes, DefaultRedirectPath);
  460. return;
  461. }
  462. if (string.IsNullOrEmpty(localPath))
  463. {
  464. RedirectToUrl(httpRes, "/" + DefaultRedirectPath);
  465. return;
  466. }
  467. if (!string.Equals(httpReq.QueryString["r"], "0", StringComparison.OrdinalIgnoreCase))
  468. {
  469. if (localPath.EndsWith("web/dashboard.html", StringComparison.OrdinalIgnoreCase))
  470. {
  471. RedirectToUrl(httpRes, "index.html#!/dashboard.html");
  472. }
  473. if (localPath.EndsWith("web/home.html", StringComparison.OrdinalIgnoreCase))
  474. {
  475. RedirectToUrl(httpRes, "index.html");
  476. }
  477. }
  478. if (!string.IsNullOrEmpty(GlobalResponse))
  479. {
  480. // We don't want the address pings in ApplicationHost to fail
  481. if (localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  482. {
  483. httpRes.StatusCode = 503;
  484. httpRes.ContentType = "text/html";
  485. await Write(httpRes, GlobalResponse).ConfigureAwait(false);
  486. return;
  487. }
  488. }
  489. var handler = GetServiceHandler(httpReq);
  490. if (handler != null)
  491. {
  492. await handler.ProcessRequestAsync(this, httpReq, httpRes, Logger, httpReq.OperationName, cancellationToken).ConfigureAwait(false);
  493. }
  494. else
  495. {
  496. await ErrorHandler(new FileNotFoundException(), httpReq, false, false).ConfigureAwait(false);
  497. }
  498. }
  499. catch (Exception ex) when (ex is SocketException || ex is IOException || ex is OperationCanceledException)
  500. {
  501. await ErrorHandler(ex, httpReq, false, false).ConfigureAwait(false);
  502. }
  503. catch (SecurityException ex)
  504. {
  505. await ErrorHandler(ex, httpReq, false, true).ConfigureAwait(false);
  506. }
  507. catch (Exception ex)
  508. {
  509. var logException = !string.Equals(ex.GetType().Name, "SocketException", StringComparison.OrdinalIgnoreCase);
  510. await ErrorHandler(ex, httpReq, logException, false).ConfigureAwait(false);
  511. }
  512. finally
  513. {
  514. // TODO
  515. httpRes.IsClosed = true;
  516. stopWatch.Stop();
  517. var elapsed = stopWatch.Elapsed;
  518. if (elapsed.TotalMilliseconds > 500)
  519. {
  520. _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  521. }
  522. else
  523. {
  524. _logger.LogDebug("HTTP Response {StatusCode} to {RemoteIp}. Time: {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  525. }
  526. }
  527. }
  528. // Entry point for HttpListener
  529. public ServiceHandler GetServiceHandler(IHttpRequest httpReq)
  530. {
  531. var pathInfo = httpReq.PathInfo;
  532. var pathParts = pathInfo.TrimStart('/').Split('/');
  533. if (pathParts.Length == 0)
  534. {
  535. _logger.LogError("Path parts empty for PathInfo: {PathInfo}, Url: {RawUrl}", pathInfo, httpReq.RawUrl);
  536. return null;
  537. }
  538. var restPath = ServiceHandler.FindMatchingRestPath(httpReq.HttpMethod, pathInfo, out string contentType);
  539. if (restPath != null)
  540. {
  541. return new ServiceHandler
  542. {
  543. RestPath = restPath,
  544. ResponseContentType = contentType
  545. };
  546. }
  547. _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
  548. return null;
  549. }
  550. private static Task Write(IResponse response, string text)
  551. {
  552. var bOutput = Encoding.UTF8.GetBytes(text);
  553. return response.OutputStream.WriteAsync(bOutput, 0, bOutput.Length);
  554. }
  555. private void RedirectToSecureUrl(IHttpRequest httpReq, IResponse httpRes, string url)
  556. {
  557. if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
  558. {
  559. var builder = new UriBuilder(uri)
  560. {
  561. Port = _config.Configuration.PublicHttpsPort,
  562. Scheme = "https"
  563. };
  564. url = builder.Uri.ToString();
  565. RedirectToUrl(httpRes, url);
  566. }
  567. else
  568. {
  569. // TODO what is this?
  570. var httpsUrl = url
  571. .Replace("http://", "https://", StringComparison.OrdinalIgnoreCase)
  572. .Replace(":" + _config.Configuration.PublicPort.ToString(CultureInfo.InvariantCulture), ":" + _config.Configuration.PublicHttpsPort.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase);
  573. RedirectToUrl(httpRes, url);
  574. }
  575. }
  576. public static void RedirectToUrl(IResponse httpRes, string url)
  577. {
  578. httpRes.StatusCode = 302;
  579. httpRes.AddHeader("Location", url);
  580. }
  581. public ServiceController ServiceController { get; private set; }
  582. /// <summary>
  583. /// Adds the rest handlers.
  584. /// </summary>
  585. /// <param name="services">The services.</param>
  586. public void Init(IEnumerable<IService> services, IEnumerable<IWebSocketListener> listeners)
  587. {
  588. _webSocketListeners = listeners.ToArray();
  589. ServiceController = new ServiceController();
  590. _logger.LogInformation("Calling ServiceStack AppHost.Init");
  591. var types = services.Select(r => r.GetType()).ToArray();
  592. ServiceController.Init(this, types);
  593. ResponseFilters = new Action<IRequest, IResponse, object>[]
  594. {
  595. new ResponseFilter(_logger).FilterResponse
  596. };
  597. }
  598. public RouteAttribute[] GetRouteAttributes(Type requestType)
  599. {
  600. var routes = requestType.GetTypeInfo().GetCustomAttributes<RouteAttribute>(true).ToList();
  601. var clone = routes.ToList();
  602. foreach (var route in clone)
  603. {
  604. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  605. {
  606. Notes = route.Notes,
  607. Priority = route.Priority,
  608. Summary = route.Summary
  609. });
  610. routes.Add(new RouteAttribute(NormalizeMediaBrowserRoutePath(route.Path), route.Verbs)
  611. {
  612. Notes = route.Notes,
  613. Priority = route.Priority,
  614. Summary = route.Summary
  615. });
  616. // needed because apps add /emby, and some users also add /emby, thereby double prefixing
  617. routes.Add(new RouteAttribute(DoubleNormalizeEmbyRoutePath(route.Path), route.Verbs)
  618. {
  619. Notes = route.Notes,
  620. Priority = route.Priority,
  621. Summary = route.Summary
  622. });
  623. }
  624. return routes.ToArray();
  625. }
  626. public Func<string, object> GetParseFn(Type propertyType)
  627. {
  628. return _funcParseFn(propertyType);
  629. }
  630. public void SerializeToJson(object o, Stream stream)
  631. {
  632. _jsonSerializer.SerializeToStream(o, stream);
  633. }
  634. public void SerializeToXml(object o, Stream stream)
  635. {
  636. _xmlSerializer.SerializeToStream(o, stream);
  637. }
  638. public Task<object> DeserializeXml(Type type, Stream stream)
  639. {
  640. return Task.FromResult(_xmlSerializer.DeserializeFromStream(type, stream));
  641. }
  642. public Task<object> DeserializeJson(Type type, Stream stream)
  643. {
  644. return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
  645. }
  646. public Task ProcessWebSocketRequest(HttpContext context)
  647. {
  648. // TODO
  649. return ((WebSocketSharpListener)_socketListener).ProcessWebSocketRequest(context);
  650. }
  651. //TODO Add Jellyfin Route Path Normalizer
  652. private static string NormalizeEmbyRoutePath(string path)
  653. {
  654. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  655. {
  656. return "/emby" + path;
  657. }
  658. return "emby/" + path;
  659. }
  660. private static string NormalizeMediaBrowserRoutePath(string path)
  661. {
  662. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  663. {
  664. return "/mediabrowser" + path;
  665. }
  666. return "mediabrowser/" + path;
  667. }
  668. private static string DoubleNormalizeEmbyRoutePath(string path)
  669. {
  670. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  671. {
  672. return "/emby/emby" + path;
  673. }
  674. return "emby/emby/" + path;
  675. }
  676. private bool _disposed;
  677. private readonly object _disposeLock = new object();
  678. protected virtual void Dispose(bool disposing)
  679. {
  680. if (_disposed) return;
  681. lock (_disposeLock)
  682. {
  683. if (_disposed) return;
  684. _disposed = true;
  685. if (disposing)
  686. {
  687. Stop();
  688. }
  689. }
  690. }
  691. /// <summary>
  692. /// Processes the web socket message received.
  693. /// </summary>
  694. /// <param name="result">The result.</param>
  695. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  696. {
  697. if (_disposed)
  698. {
  699. return Task.CompletedTask;
  700. }
  701. _logger.LogDebug("Websocket message received: {0}", result.MessageType);
  702. var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
  703. {
  704. try
  705. {
  706. await i.ProcessMessage(result).ConfigureAwait(false);
  707. }
  708. catch (Exception ex)
  709. {
  710. _logger.LogError(ex, "{0} failed processing WebSocket message {1}", i.GetType().Name, result.MessageType ?? string.Empty);
  711. }
  712. }));
  713. return Task.WhenAll(tasks);
  714. }
  715. public void Dispose()
  716. {
  717. Dispose(true);
  718. }
  719. }
  720. }