HttpListenerHost.cs 19 KB

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