2
0

HttpListenerHost.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Net;
  4. using Microsoft.Extensions.Logging;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using Emby.Server.Implementations.Services;
  15. using MediaBrowser.Common.Net;
  16. using MediaBrowser.Controller;
  17. using MediaBrowser.Model.Extensions;
  18. using MediaBrowser.Model.Serialization;
  19. using MediaBrowser.Model.Services;
  20. using MediaBrowser.Model.Text;
  21. using System.Net.Sockets;
  22. using Emby.Server.Implementations.Net;
  23. using MediaBrowser.Model.Events;
  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. Type serviceType;
  103. ServiceOperationsMap.TryGetValue(requestType, out 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, _textEncoding)
  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. if (WebSocketConnected != null)
  139. {
  140. WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));
  141. }
  142. }
  143. private void Connection_Closed(object sender, EventArgs e)
  144. {
  145. lock (_webSocketConnections)
  146. {
  147. _webSocketConnections.Remove((IWebSocketConnection)sender);
  148. }
  149. }
  150. private static Exception GetActualException(Exception ex)
  151. {
  152. if (ex is AggregateException agg)
  153. {
  154. var inner = agg.InnerException;
  155. if (inner != null)
  156. {
  157. return GetActualException(inner);
  158. }
  159. else
  160. {
  161. var inners = agg.InnerExceptions;
  162. if (inners != null && inners.Count > 0)
  163. {
  164. return GetActualException(inners[0]);
  165. }
  166. }
  167. }
  168. return ex;
  169. }
  170. private int GetStatusCode(Exception ex)
  171. {
  172. if (ex is ArgumentException)
  173. {
  174. return 400;
  175. }
  176. var exceptionType = ex.GetType();
  177. int statusCode;
  178. if (!_mapExceptionToStatusCode.TryGetValue(exceptionType, out 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. string contentType;
  587. var restPath = ServiceHandler.FindMatchingRestPath(httpReq.HttpMethod, pathInfo, out contentType);
  588. if (restPath != null)
  589. {
  590. return new ServiceHandler
  591. {
  592. RestPath = restPath,
  593. ResponseContentType = contentType
  594. };
  595. }
  596. _logger.LogError("Could not find handler for {pathInfo}", pathInfo);
  597. return null;
  598. }
  599. private static Task Write(IResponse response, string text)
  600. {
  601. var bOutput = Encoding.UTF8.GetBytes(text);
  602. response.SetContentLength(bOutput.Length);
  603. return response.OutputStream.WriteAsync(bOutput, 0, bOutput.Length);
  604. }
  605. private void RedirectToSecureUrl(IHttpRequest httpReq, IResponse httpRes, string url)
  606. {
  607. int currentPort;
  608. Uri uri;
  609. if (Uri.TryCreate(url, UriKind.Absolute, out uri))
  610. {
  611. currentPort = uri.Port;
  612. var builder = new UriBuilder(uri);
  613. builder.Port = _config.Configuration.PublicHttpsPort;
  614. builder.Scheme = "https";
  615. url = builder.Uri.ToString();
  616. RedirectToUrl(httpRes, url);
  617. }
  618. else
  619. {
  620. var httpsUrl = url
  621. .Replace("http://", "https://", StringComparison.OrdinalIgnoreCase)
  622. .Replace(":" + _config.Configuration.PublicPort.ToString(CultureInfo.InvariantCulture), ":" + _config.Configuration.PublicHttpsPort.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase);
  623. RedirectToUrl(httpRes, url);
  624. }
  625. }
  626. public static void RedirectToUrl(IResponse httpRes, string url)
  627. {
  628. httpRes.StatusCode = 302;
  629. httpRes.AddHeader("Location", url);
  630. }
  631. public ServiceController ServiceController { get; private set; }
  632. /// <summary>
  633. /// Adds the rest handlers.
  634. /// </summary>
  635. /// <param name="services">The services.</param>
  636. public void Init(IEnumerable<IService> services, IEnumerable<IWebSocketListener> listeners)
  637. {
  638. _webSocketListeners = listeners.ToArray();
  639. ServiceController = new ServiceController();
  640. _logger.LogInformation("Calling ServiceStack AppHost.Init");
  641. var types = services.Select(r => r.GetType()).ToArray();
  642. ServiceController.Init(this, types);
  643. ResponseFilters = new Action<IRequest, IResponse, object>[]
  644. {
  645. new ResponseFilter(_logger).FilterResponse
  646. };
  647. }
  648. public RouteAttribute[] GetRouteAttributes(Type requestType)
  649. {
  650. var routes = requestType.GetTypeInfo().GetCustomAttributes<RouteAttribute>(true).ToList();
  651. var clone = routes.ToList();
  652. foreach (var route in clone)
  653. {
  654. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  655. {
  656. Notes = route.Notes,
  657. Priority = route.Priority,
  658. Summary = route.Summary
  659. });
  660. routes.Add(new RouteAttribute(NormalizeMediaBrowserRoutePath(route.Path), route.Verbs)
  661. {
  662. Notes = route.Notes,
  663. Priority = route.Priority,
  664. Summary = route.Summary
  665. });
  666. // needed because apps add /emby, and some users also add /emby, thereby double prefixing
  667. routes.Add(new RouteAttribute(DoubleNormalizeEmbyRoutePath(route.Path), route.Verbs)
  668. {
  669. Notes = route.Notes,
  670. Priority = route.Priority,
  671. Summary = route.Summary
  672. });
  673. }
  674. return routes.ToArray();
  675. }
  676. public Func<string, object> GetParseFn(Type propertyType)
  677. {
  678. return _funcParseFn(propertyType);
  679. }
  680. public void SerializeToJson(object o, Stream stream)
  681. {
  682. _jsonSerializer.SerializeToStream(o, stream);
  683. }
  684. public void SerializeToXml(object o, Stream stream)
  685. {
  686. _xmlSerializer.SerializeToStream(o, stream);
  687. }
  688. public Task<object> DeserializeXml(Type type, Stream stream)
  689. {
  690. return Task.FromResult(_xmlSerializer.DeserializeFromStream(type, stream));
  691. }
  692. public Task<object> DeserializeJson(Type type, Stream stream)
  693. {
  694. //using (var reader = new StreamReader(stream))
  695. //{
  696. // var json = reader.ReadToEnd();
  697. // logger.LogInformation(json);
  698. // return _jsonSerializer.DeserializeFromString(json, type);
  699. //}
  700. return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
  701. }
  702. //TODO Add Jellyfin Route Path Normalizer
  703. private static string NormalizeEmbyRoutePath(string path)
  704. {
  705. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  706. {
  707. return "/emby" + path;
  708. }
  709. return "emby/" + path;
  710. }
  711. private static string NormalizeMediaBrowserRoutePath(string path)
  712. {
  713. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  714. {
  715. return "/mediabrowser" + path;
  716. }
  717. return "mediabrowser/" + path;
  718. }
  719. private static string DoubleNormalizeEmbyRoutePath(string path)
  720. {
  721. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  722. {
  723. return "/emby/emby" + path;
  724. }
  725. return "emby/emby/" + path;
  726. }
  727. private bool _disposed;
  728. private readonly object _disposeLock = new object();
  729. protected virtual void Dispose(bool disposing)
  730. {
  731. if (_disposed) return;
  732. lock (_disposeLock)
  733. {
  734. if (_disposed) return;
  735. _disposed = true;
  736. if (disposing)
  737. {
  738. Stop();
  739. }
  740. }
  741. }
  742. /// <summary>
  743. /// Processes the web socket message received.
  744. /// </summary>
  745. /// <param name="result">The result.</param>
  746. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  747. {
  748. if (_disposed)
  749. {
  750. return Task.CompletedTask;
  751. }
  752. _logger.LogDebug("Websocket message received: {0}", result.MessageType);
  753. var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
  754. {
  755. try
  756. {
  757. await i.ProcessMessage(result).ConfigureAwait(false);
  758. }
  759. catch (Exception ex)
  760. {
  761. _logger.LogError(ex, "{0} failed processing WebSocket message {1}", i.GetType().Name, result.MessageType ?? string.Empty);
  762. }
  763. }));
  764. return Task.WhenAll(tasks);
  765. }
  766. public void Dispose()
  767. {
  768. Dispose(true);
  769. }
  770. public void StartServer(string[] urlPrefixes, IHttpListener httpListener)
  771. {
  772. UrlPrefixes = urlPrefixes;
  773. _listener = httpListener;
  774. _listener.WebSocketConnected = OnWebSocketConnected;
  775. _listener.ErrorHandler = ErrorHandler;
  776. _listener.RequestHandler = RequestHandler;
  777. _listener.Start(UrlPrefixes);
  778. }
  779. }
  780. }