2
0

HttpListenerHost.cs 31 KB

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