HttpListenerHost.cs 31 KB

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