HttpListenerHost.cs 32 KB

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