HttpListenerHost.cs 33 KB

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