HttpListenerHost.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. using Funq;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Net;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Server.Implementations.HttpServer.SocketSharp;
  8. using ServiceStack;
  9. using ServiceStack.Api.Swagger;
  10. using ServiceStack.Host;
  11. using ServiceStack.Host.Handlers;
  12. using ServiceStack.Host.HttpListener;
  13. using ServiceStack.Logging;
  14. using ServiceStack.Web;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Reflection;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using MediaBrowser.Common.Net;
  23. using MediaBrowser.Common.Security;
  24. using MediaBrowser.Model.Extensions;
  25. namespace MediaBrowser.Server.Implementations.HttpServer
  26. {
  27. public class HttpListenerHost : ServiceStackHost, IHttpServer
  28. {
  29. private string DefaultRedirectPath { get; set; }
  30. private readonly ILogger _logger;
  31. public IEnumerable<string> UrlPrefixes { get; private set; }
  32. private readonly List<IRestfulService> _restServices = new List<IRestfulService>();
  33. private IHttpListener _listener;
  34. private readonly ContainerAdapter _containerAdapter;
  35. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  36. public event EventHandler<WebSocketConnectingEventArgs> WebSocketConnecting;
  37. public string CertificatePath { get; private set; }
  38. private readonly IServerConfigurationManager _config;
  39. private readonly INetworkManager _networkManager;
  40. public HttpListenerHost(IApplicationHost applicationHost,
  41. ILogManager logManager,
  42. IServerConfigurationManager config,
  43. string serviceName,
  44. string defaultRedirectPath, INetworkManager networkManager, params Assembly[] assembliesWithServices)
  45. : base(serviceName, assembliesWithServices)
  46. {
  47. DefaultRedirectPath = defaultRedirectPath;
  48. _networkManager = networkManager;
  49. _config = config;
  50. _logger = logManager.GetLogger("HttpServer");
  51. _containerAdapter = new ContainerAdapter(applicationHost);
  52. }
  53. public string GlobalResponse { get; set; }
  54. public override void Configure(Container container)
  55. {
  56. HostConfig.Instance.DefaultRedirectPath = DefaultRedirectPath;
  57. HostConfig.Instance.LogUnobservedTaskExceptions = false;
  58. HostConfig.Instance.MapExceptionToStatusCode = new Dictionary<Type, int>
  59. {
  60. {typeof (InvalidOperationException), 422},
  61. {typeof (ResourceNotFoundException), 404},
  62. {typeof (FileNotFoundException), 404},
  63. {typeof (DirectoryNotFoundException), 404},
  64. {typeof (SecurityException), 401},
  65. {typeof (PaymentRequiredException), 402},
  66. {typeof (UnauthorizedAccessException), 500},
  67. {typeof (ApplicationException), 500}
  68. };
  69. HostConfig.Instance.GlobalResponseHeaders = new Dictionary<string, string>();
  70. HostConfig.Instance.DebugMode = false;
  71. HostConfig.Instance.LogFactory = LogManager.LogFactory;
  72. // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
  73. // Custom format allows images
  74. HostConfig.Instance.EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat;
  75. container.Adapter = _containerAdapter;
  76. Plugins.Add(new SwaggerFeature());
  77. Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization"));
  78. //Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
  79. // new SessionAuthProvider(_containerAdapter.Resolve<ISessionContext>()),
  80. //}));
  81. PreRequestFilters.Add((httpReq, httpRes) =>
  82. {
  83. //Handles Request and closes Responses after emitting global HTTP Headers
  84. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  85. {
  86. httpRes.EndRequest(); //add a 'using ServiceStack;'
  87. }
  88. });
  89. HostContext.GlobalResponseFilters.Add(new ResponseFilter(_logger).FilterResponse);
  90. }
  91. public override void OnAfterInit()
  92. {
  93. SetAppDomainData();
  94. base.OnAfterInit();
  95. }
  96. public override void OnConfigLoad()
  97. {
  98. base.OnConfigLoad();
  99. Config.HandlerFactoryPath = null;
  100. Config.MetadataRedirectPath = "metadata";
  101. }
  102. protected override ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
  103. {
  104. var types = _restServices.Select(r => r.GetType()).ToArray();
  105. return new ServiceController(this, () => types);
  106. }
  107. public virtual void SetAppDomainData()
  108. {
  109. //Required for Mono to resolve VirtualPathUtility and Url.Content urls
  110. var domain = Thread.GetDomain(); // or AppDomain.Current
  111. domain.SetData(".appDomain", "1");
  112. domain.SetData(".appVPath", "/");
  113. domain.SetData(".appPath", domain.BaseDirectory);
  114. if (string.IsNullOrEmpty(domain.GetData(".appId") as string))
  115. {
  116. domain.SetData(".appId", "1");
  117. }
  118. if (string.IsNullOrEmpty(domain.GetData(".domainId") as string))
  119. {
  120. domain.SetData(".domainId", "1");
  121. }
  122. }
  123. public override ServiceStackHost Start(string listeningAtUrlBase)
  124. {
  125. StartListener();
  126. return this;
  127. }
  128. /// <summary>
  129. /// Starts the Web Service
  130. /// </summary>
  131. private void StartListener()
  132. {
  133. HostContext.Config.HandlerFactoryPath = ListenerRequest.GetHandlerPathIfAny(UrlPrefixes.First());
  134. _listener = GetListener();
  135. _listener.WebSocketConnected = OnWebSocketConnected;
  136. _listener.WebSocketConnecting = OnWebSocketConnecting;
  137. _listener.ErrorHandler = ErrorHandler;
  138. _listener.RequestHandler = RequestHandler;
  139. _listener.Start(UrlPrefixes);
  140. }
  141. private IHttpListener GetListener()
  142. {
  143. return new WebSocketSharpListener(_logger, CertificatePath);
  144. }
  145. private void OnWebSocketConnecting(WebSocketConnectingEventArgs args)
  146. {
  147. if (_disposed)
  148. {
  149. return;
  150. }
  151. if (WebSocketConnecting != null)
  152. {
  153. WebSocketConnecting(this, args);
  154. }
  155. }
  156. private void OnWebSocketConnected(WebSocketConnectEventArgs args)
  157. {
  158. if (_disposed)
  159. {
  160. return;
  161. }
  162. if (WebSocketConnected != null)
  163. {
  164. WebSocketConnected(this, args);
  165. }
  166. }
  167. private void ErrorHandler(Exception ex, IRequest httpReq)
  168. {
  169. try
  170. {
  171. var httpRes = httpReq.Response;
  172. if (httpRes.IsClosed)
  173. {
  174. return;
  175. }
  176. var errorResponse = new ErrorResponse
  177. {
  178. ResponseStatus = new ResponseStatus
  179. {
  180. ErrorCode = ex.GetType().GetOperationName(),
  181. Message = ex.Message,
  182. StackTrace = ex.StackTrace
  183. }
  184. };
  185. var contentType = httpReq.ResponseContentType;
  186. var serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  187. if (serializer == null)
  188. {
  189. contentType = HostContext.Config.DefaultContentType;
  190. serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  191. }
  192. var httpError = ex as IHttpError;
  193. if (httpError != null)
  194. {
  195. httpRes.StatusCode = httpError.Status;
  196. httpRes.StatusDescription = httpError.StatusDescription;
  197. }
  198. else
  199. {
  200. httpRes.StatusCode = 500;
  201. }
  202. httpRes.ContentType = contentType;
  203. serializer(httpReq, errorResponse, httpRes);
  204. httpRes.Close();
  205. }
  206. catch
  207. {
  208. //_logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  209. }
  210. }
  211. /// <summary>
  212. /// Shut down the Web Service
  213. /// </summary>
  214. public void Stop()
  215. {
  216. if (_listener != null)
  217. {
  218. _listener.Stop();
  219. }
  220. }
  221. private readonly Dictionary<string, int> _skipLogExtensions = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
  222. {
  223. {".js", 0},
  224. {".css", 0},
  225. {".woff", 0},
  226. {".woff2", 0},
  227. {".ttf", 0},
  228. {".html", 0}
  229. };
  230. private bool EnableLogging(string url, string localPath)
  231. {
  232. var extension = GetExtension(url);
  233. if (string.IsNullOrWhiteSpace(extension) || !_skipLogExtensions.ContainsKey(extension))
  234. {
  235. if (string.IsNullOrWhiteSpace(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  236. {
  237. return true;
  238. }
  239. }
  240. return false;
  241. }
  242. private string GetExtension(string url)
  243. {
  244. var parts = url.Split(new[] { '?' }, 2);
  245. return Path.GetExtension(parts[0]);
  246. }
  247. public static string RemoveQueryStringByKey(string url, string key)
  248. {
  249. var uri = new Uri(url);
  250. // this gets all the query string key value pairs as a collection
  251. var newQueryString = MyHttpUtility.ParseQueryString(uri.Query);
  252. if (newQueryString.Count == 0)
  253. {
  254. return url;
  255. }
  256. // this removes the key if exists
  257. newQueryString.Remove(key);
  258. // this gets the page path from root without QueryString
  259. string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path);
  260. return newQueryString.Count > 0
  261. ? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
  262. : pagePathWithoutQueryString;
  263. }
  264. private string GetUrlToLog(string url)
  265. {
  266. url = RemoveQueryStringByKey(url, "api_key");
  267. return url;
  268. }
  269. private string NormalizeConfiguredLocalAddress(string address)
  270. {
  271. var index = address.Trim('/').IndexOf('/');
  272. if (index != -1)
  273. {
  274. address = address.Substring(index + 1);
  275. }
  276. return address.Trim('/');
  277. }
  278. private bool ValidateHost(Uri url)
  279. {
  280. var hosts = _config
  281. .Configuration
  282. .LocalNetworkAddresses
  283. .Select(NormalizeConfiguredLocalAddress)
  284. .ToList();
  285. if (hosts.Count == 0)
  286. {
  287. return true;
  288. }
  289. var host = url.Host ?? string.Empty;
  290. _logger.Debug("Validating host {0}", host);
  291. if (_networkManager.IsInPrivateAddressSpace(host))
  292. {
  293. hosts.Add("localhost");
  294. hosts.Add("127.0.0.1");
  295. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  296. }
  297. return true;
  298. }
  299. /// <summary>
  300. /// Overridable method that can be used to implement a custom hnandler
  301. /// </summary>
  302. /// <param name="httpReq">The HTTP req.</param>
  303. /// <param name="url">The URL.</param>
  304. /// <returns>Task.</returns>
  305. protected async Task RequestHandler(IHttpRequest httpReq, Uri url)
  306. {
  307. var date = DateTime.Now;
  308. var httpRes = httpReq.Response;
  309. if (_disposed)
  310. {
  311. httpRes.StatusCode = 503;
  312. httpRes.Close();
  313. return ;
  314. }
  315. if (!ValidateHost(url))
  316. {
  317. httpRes.StatusCode = 400;
  318. httpRes.ContentType = "text/plain";
  319. httpRes.Write("Invalid host");
  320. httpRes.Close();
  321. return;
  322. }
  323. var operationName = httpReq.OperationName;
  324. var localPath = url.LocalPath;
  325. var urlString = url.OriginalString;
  326. var enableLog = EnableLogging(urlString, localPath);
  327. var urlToLog = urlString;
  328. if (enableLog)
  329. {
  330. urlToLog = GetUrlToLog(urlString);
  331. LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent);
  332. }
  333. if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) ||
  334. string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
  335. {
  336. httpRes.RedirectToUrl(DefaultRedirectPath);
  337. return;
  338. }
  339. if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) ||
  340. string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
  341. {
  342. httpRes.RedirectToUrl("emby/" + DefaultRedirectPath);
  343. return;
  344. }
  345. if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) ||
  346. string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) ||
  347. localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1)
  348. {
  349. httpRes.StatusCode = 200;
  350. httpRes.ContentType = "text/html";
  351. var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
  352. .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
  353. if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
  354. {
  355. httpRes.Write("<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>");
  356. httpRes.Close();
  357. return;
  358. }
  359. }
  360. if (localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1 &&
  361. localPath.IndexOf("web/dashboard", StringComparison.OrdinalIgnoreCase) == -1)
  362. {
  363. httpRes.StatusCode = 200;
  364. httpRes.ContentType = "text/html";
  365. var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
  366. .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
  367. if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
  368. {
  369. httpRes.Write("<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>");
  370. httpRes.Close();
  371. return;
  372. }
  373. }
  374. if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase))
  375. {
  376. httpRes.RedirectToUrl(DefaultRedirectPath);
  377. return;
  378. }
  379. if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase))
  380. {
  381. httpRes.RedirectToUrl("../" + DefaultRedirectPath);
  382. return;
  383. }
  384. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  385. {
  386. httpRes.RedirectToUrl(DefaultRedirectPath);
  387. return;
  388. }
  389. if (string.IsNullOrEmpty(localPath))
  390. {
  391. httpRes.RedirectToUrl("/" + DefaultRedirectPath);
  392. return;
  393. }
  394. if (string.Equals(localPath, "/emby/pin", StringComparison.OrdinalIgnoreCase))
  395. {
  396. httpRes.RedirectToUrl("web/pin.html");
  397. return;
  398. }
  399. if (!string.IsNullOrWhiteSpace(GlobalResponse))
  400. {
  401. httpRes.StatusCode = 503;
  402. httpRes.ContentType = "text/html";
  403. httpRes.Write(GlobalResponse);
  404. httpRes.Close();
  405. return;
  406. }
  407. var handler = HttpHandlerFactory.GetHandler(httpReq);
  408. var remoteIp = httpReq.RemoteIp;
  409. var serviceStackHandler = handler as IServiceStackHandler;
  410. if (serviceStackHandler != null)
  411. {
  412. var restHandler = serviceStackHandler as RestHandler;
  413. if (restHandler != null)
  414. {
  415. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
  416. }
  417. try
  418. {
  419. await serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName).ConfigureAwait(false);
  420. }
  421. finally
  422. {
  423. httpRes.Close();
  424. var statusCode = httpRes.StatusCode;
  425. var duration = DateTime.Now - date;
  426. if (enableLog)
  427. {
  428. LoggerUtils.LogResponse(_logger, statusCode, urlToLog, remoteIp, duration);
  429. }
  430. }
  431. }
  432. throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
  433. }
  434. /// <summary>
  435. /// Adds the rest handlers.
  436. /// </summary>
  437. /// <param name="services">The services.</param>
  438. public void Init(IEnumerable<IRestfulService> services)
  439. {
  440. _restServices.AddRange(services);
  441. ServiceController = CreateServiceController();
  442. _logger.Info("Calling ServiceStack AppHost.Init");
  443. base.Init();
  444. }
  445. public override RouteAttribute[] GetRouteAttributes(Type requestType)
  446. {
  447. var routes = base.GetRouteAttributes(requestType).ToList();
  448. var clone = routes.ToList();
  449. foreach (var route in clone)
  450. {
  451. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  452. {
  453. Notes = route.Notes,
  454. Priority = route.Priority,
  455. Summary = route.Summary
  456. });
  457. routes.Add(new RouteAttribute(NormalizeRoutePath(route.Path), route.Verbs)
  458. {
  459. Notes = route.Notes,
  460. Priority = route.Priority,
  461. Summary = route.Summary
  462. });
  463. routes.Add(new RouteAttribute(DoubleNormalizeEmbyRoutePath(route.Path), route.Verbs)
  464. {
  465. Notes = route.Notes,
  466. Priority = route.Priority,
  467. Summary = route.Summary
  468. });
  469. }
  470. return routes.ToArray();
  471. }
  472. private string NormalizeEmbyRoutePath(string path)
  473. {
  474. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  475. {
  476. return "/emby" + path;
  477. }
  478. return "emby/" + path;
  479. }
  480. private string DoubleNormalizeEmbyRoutePath(string path)
  481. {
  482. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  483. {
  484. return "/emby/emby" + path;
  485. }
  486. return "emby/emby/" + path;
  487. }
  488. private string NormalizeRoutePath(string path)
  489. {
  490. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  491. {
  492. return "/mediabrowser" + path;
  493. }
  494. return "mediabrowser/" + path;
  495. }
  496. /// <summary>
  497. /// Releases the specified instance.
  498. /// </summary>
  499. /// <param name="instance">The instance.</param>
  500. public override void Release(object instance)
  501. {
  502. // Leave this empty so SS doesn't try to dispose our objects
  503. }
  504. private bool _disposed;
  505. private readonly object _disposeLock = new object();
  506. protected virtual void Dispose(bool disposing)
  507. {
  508. if (_disposed) return;
  509. base.Dispose();
  510. lock (_disposeLock)
  511. {
  512. if (_disposed) return;
  513. if (disposing)
  514. {
  515. Stop();
  516. }
  517. //release unmanaged resources here...
  518. _disposed = true;
  519. }
  520. }
  521. public override void Dispose()
  522. {
  523. Dispose(true);
  524. GC.SuppressFinalize(this);
  525. }
  526. public void StartServer(IEnumerable<string> urlPrefixes, string certificatePath)
  527. {
  528. CertificatePath = certificatePath;
  529. UrlPrefixes = urlPrefixes.ToList();
  530. Start(UrlPrefixes.First());
  531. }
  532. }
  533. }