HttpListenerHost.cs 30 KB

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