HttpListenerHost.cs 31 KB

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