2
0

HttpListenerHost.cs 32 KB

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