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