2
0

HttpListenerHost.cs 31 KB

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