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