HttpListenerHost.cs 32 KB

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