HttpListenerHost.cs 31 KB

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