HttpListenerHost.cs 32 KB

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