HttpListenerHost.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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.Security;
  23. namespace MediaBrowser.Server.Implementations.HttpServer
  24. {
  25. public class HttpListenerHost : ServiceStackHost, IHttpServer
  26. {
  27. private string DefaultRedirectPath { get; set; }
  28. private readonly ILogger _logger;
  29. public IEnumerable<string> UrlPrefixes { get; private set; }
  30. private readonly List<IRestfulService> _restServices = new List<IRestfulService>();
  31. private IHttpListener _listener;
  32. private readonly ContainerAdapter _containerAdapter;
  33. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  34. public event EventHandler<WebSocketConnectingEventArgs> WebSocketConnecting;
  35. private readonly List<string> _localEndpoints = new List<string>();
  36. private readonly ReaderWriterLockSlim _localEndpointLock = new ReaderWriterLockSlim();
  37. public string CertificatePath { get; private set; }
  38. private readonly IServerConfigurationManager _config;
  39. /// <summary>
  40. /// Gets the local end points.
  41. /// </summary>
  42. /// <value>The local end points.</value>
  43. public IEnumerable<string> LocalEndPoints
  44. {
  45. get
  46. {
  47. _localEndpointLock.EnterReadLock();
  48. var list = _localEndpoints.ToList();
  49. _localEndpointLock.ExitReadLock();
  50. return list;
  51. }
  52. }
  53. public HttpListenerHost(IApplicationHost applicationHost,
  54. ILogManager logManager,
  55. IServerConfigurationManager config,
  56. string serviceName,
  57. string defaultRedirectPath, params Assembly[] assembliesWithServices)
  58. : base(serviceName, assembliesWithServices)
  59. {
  60. DefaultRedirectPath = defaultRedirectPath;
  61. _config = config;
  62. _logger = logManager.GetLogger("HttpServer");
  63. _containerAdapter = new ContainerAdapter(applicationHost);
  64. }
  65. public string GlobalResponse { get; set; }
  66. public override void Configure(Container container)
  67. {
  68. HostConfig.Instance.DefaultRedirectPath = DefaultRedirectPath;
  69. HostConfig.Instance.MapExceptionToStatusCode = new Dictionary<Type, int>
  70. {
  71. {typeof (InvalidOperationException), 422},
  72. {typeof (ResourceNotFoundException), 404},
  73. {typeof (FileNotFoundException), 404},
  74. {typeof (DirectoryNotFoundException), 404},
  75. {typeof (SecurityException), 401},
  76. {typeof (PaymentRequiredException), 402},
  77. {typeof (UnauthorizedAccessException), 500},
  78. {typeof (ApplicationException), 500}
  79. };
  80. HostConfig.Instance.DebugMode = true;
  81. HostConfig.Instance.LogFactory = LogManager.LogFactory;
  82. // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
  83. // Custom format allows images
  84. HostConfig.Instance.EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat;
  85. container.Adapter = _containerAdapter;
  86. Plugins.Add(new SwaggerFeature());
  87. Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization"));
  88. //Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
  89. // new SessionAuthProvider(_containerAdapter.Resolve<ISessionContext>()),
  90. //}));
  91. PreRequestFilters.Add((httpReq, httpRes) =>
  92. {
  93. //Handles Request and closes Responses after emitting global HTTP Headers
  94. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  95. {
  96. httpRes.EndRequest(); //add a 'using ServiceStack;'
  97. }
  98. });
  99. HostContext.GlobalResponseFilters.Add(new ResponseFilter(_logger, () => _config.Configuration.DenyIFrameEmbedding).FilterResponse);
  100. }
  101. public override void OnAfterInit()
  102. {
  103. SetAppDomainData();
  104. base.OnAfterInit();
  105. }
  106. public override void OnConfigLoad()
  107. {
  108. base.OnConfigLoad();
  109. Config.HandlerFactoryPath = null;
  110. Config.MetadataRedirectPath = "metadata";
  111. }
  112. protected override ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
  113. {
  114. var types = _restServices.Select(r => r.GetType()).ToArray();
  115. return new ServiceController(this, () => types);
  116. }
  117. public virtual void SetAppDomainData()
  118. {
  119. //Required for Mono to resolve VirtualPathUtility and Url.Content urls
  120. var domain = Thread.GetDomain(); // or AppDomain.Current
  121. domain.SetData(".appDomain", "1");
  122. domain.SetData(".appVPath", "/");
  123. domain.SetData(".appPath", domain.BaseDirectory);
  124. if (string.IsNullOrEmpty(domain.GetData(".appId") as string))
  125. {
  126. domain.SetData(".appId", "1");
  127. }
  128. if (string.IsNullOrEmpty(domain.GetData(".domainId") as string))
  129. {
  130. domain.SetData(".domainId", "1");
  131. }
  132. }
  133. public override ServiceStackHost Start(string listeningAtUrlBase)
  134. {
  135. StartListener();
  136. return this;
  137. }
  138. private void OnRequestReceived(string localEndPoint)
  139. {
  140. var ignore = localEndPoint.IndexOf("::", StringComparison.OrdinalIgnoreCase) != -1 ||
  141. localEndPoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
  142. localEndPoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ||
  143. localEndPoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase);
  144. if (ignore)
  145. {
  146. return;
  147. }
  148. if (_localEndpointLock.TryEnterWriteLock(100))
  149. {
  150. var list = _localEndpoints.ToList();
  151. list.Remove(localEndPoint);
  152. list.Insert(0, localEndPoint);
  153. _localEndpointLock.ExitWriteLock();
  154. }
  155. }
  156. /// <summary>
  157. /// Starts the Web Service
  158. /// </summary>
  159. private void StartListener()
  160. {
  161. HostContext.Config.HandlerFactoryPath = ListenerRequest.GetHandlerPathIfAny(UrlPrefixes.First());
  162. _listener = GetListener();
  163. _listener.WebSocketConnected = OnWebSocketConnected;
  164. _listener.WebSocketConnecting = OnWebSocketConnecting;
  165. _listener.ErrorHandler = ErrorHandler;
  166. _listener.RequestHandler = RequestHandler;
  167. _listener.Start(UrlPrefixes);
  168. }
  169. private IHttpListener GetListener()
  170. {
  171. return new WebSocketSharpListener(_logger, OnRequestReceived, CertificatePath);
  172. }
  173. private void OnWebSocketConnecting(WebSocketConnectingEventArgs args)
  174. {
  175. if (WebSocketConnecting != null)
  176. {
  177. WebSocketConnecting(this, args);
  178. }
  179. }
  180. private void OnWebSocketConnected(WebSocketConnectEventArgs args)
  181. {
  182. if (WebSocketConnected != null)
  183. {
  184. WebSocketConnected(this, args);
  185. }
  186. }
  187. private void ErrorHandler(Exception ex, IRequest httpReq)
  188. {
  189. try
  190. {
  191. var httpRes = httpReq.Response;
  192. if (httpRes.IsClosed)
  193. {
  194. return;
  195. }
  196. var errorResponse = new ErrorResponse
  197. {
  198. ResponseStatus = new ResponseStatus
  199. {
  200. ErrorCode = ex.GetType().GetOperationName(),
  201. Message = ex.Message,
  202. StackTrace = ex.StackTrace
  203. }
  204. };
  205. var contentType = httpReq.ResponseContentType;
  206. var serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  207. if (serializer == null)
  208. {
  209. contentType = HostContext.Config.DefaultContentType;
  210. serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  211. }
  212. var httpError = ex as IHttpError;
  213. if (httpError != null)
  214. {
  215. httpRes.StatusCode = httpError.Status;
  216. httpRes.StatusDescription = httpError.StatusDescription;
  217. }
  218. else
  219. {
  220. httpRes.StatusCode = 500;
  221. }
  222. httpRes.ContentType = contentType;
  223. serializer(httpReq, errorResponse, httpRes);
  224. httpRes.Close();
  225. }
  226. catch (Exception errorEx)
  227. {
  228. _logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  229. }
  230. }
  231. /// <summary>
  232. /// Shut down the Web Service
  233. /// </summary>
  234. public void Stop()
  235. {
  236. if (_listener != null)
  237. {
  238. _listener.Stop();
  239. }
  240. }
  241. /// <summary>
  242. /// Overridable method that can be used to implement a custom hnandler
  243. /// </summary>
  244. /// <param name="httpReq">The HTTP req.</param>
  245. /// <param name="url">The URL.</param>
  246. /// <returns>Task.</returns>
  247. protected Task RequestHandler(IHttpRequest httpReq, Uri url)
  248. {
  249. var date = DateTime.Now;
  250. var httpRes = httpReq.Response;
  251. var operationName = httpReq.OperationName;
  252. var localPath = url.LocalPath;
  253. if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) ||
  254. string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase))
  255. {
  256. httpRes.RedirectToUrl(DefaultRedirectPath);
  257. return Task.FromResult(true);
  258. }
  259. if (string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
  260. {
  261. httpRes.RedirectToUrl("mediabrowser/" + DefaultRedirectPath);
  262. return Task.FromResult(true);
  263. }
  264. if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase))
  265. {
  266. httpRes.RedirectToUrl("emby/" + DefaultRedirectPath);
  267. return Task.FromResult(true);
  268. }
  269. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  270. {
  271. httpRes.RedirectToUrl(DefaultRedirectPath);
  272. return Task.FromResult(true);
  273. }
  274. if (string.IsNullOrEmpty(localPath))
  275. {
  276. httpRes.RedirectToUrl("/" + DefaultRedirectPath);
  277. return Task.FromResult(true);
  278. }
  279. if (!string.IsNullOrWhiteSpace(GlobalResponse))
  280. {
  281. httpRes.Write(GlobalResponse);
  282. httpRes.ContentType = "text/plain";
  283. return Task.FromResult(true);
  284. }
  285. var handler = HttpHandlerFactory.GetHandler(httpReq);
  286. var remoteIp = httpReq.RemoteIp;
  287. var serviceStackHandler = handler as IServiceStackHandler;
  288. if (serviceStackHandler != null)
  289. {
  290. var restHandler = serviceStackHandler as RestHandler;
  291. if (restHandler != null)
  292. {
  293. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
  294. }
  295. var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
  296. task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  297. //Matches Exceptions handled in HttpListenerBase.InitTask()
  298. var urlString = url.ToString();
  299. task.ContinueWith(x =>
  300. {
  301. var statusCode = httpRes.StatusCode;
  302. var duration = DateTime.Now - date;
  303. LoggerUtils.LogResponse(_logger, statusCode, urlString, remoteIp, duration);
  304. }, TaskContinuationOptions.None);
  305. return task;
  306. }
  307. return new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
  308. .AsTaskException();
  309. }
  310. /// <summary>
  311. /// Adds the rest handlers.
  312. /// </summary>
  313. /// <param name="services">The services.</param>
  314. public void Init(IEnumerable<IRestfulService> services)
  315. {
  316. _restServices.AddRange(services);
  317. ServiceController = CreateServiceController();
  318. _logger.Info("Calling ServiceStack AppHost.Init");
  319. base.Init();
  320. }
  321. public override RouteAttribute[] GetRouteAttributes(Type requestType)
  322. {
  323. var routes = base.GetRouteAttributes(requestType).ToList();
  324. var clone = routes.ToList();
  325. foreach (var route in clone)
  326. {
  327. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  328. {
  329. Notes = route.Notes,
  330. Priority = route.Priority,
  331. Summary = route.Summary
  332. });
  333. routes.Add(new RouteAttribute(NormalizeRoutePath(route.Path), route.Verbs)
  334. {
  335. Notes = route.Notes,
  336. Priority = route.Priority,
  337. Summary = route.Summary
  338. });
  339. // TODO: This is a hack for iOS. Remove it asap.
  340. routes.Add(new RouteAttribute(DoubleNormalizeRoutePath(route.Path), route.Verbs)
  341. {
  342. Notes = route.Notes,
  343. Priority = route.Priority,
  344. Summary = route.Summary
  345. });
  346. routes.Add(new RouteAttribute(DoubleNormalizeEmbyRoutePath(route.Path), route.Verbs)
  347. {
  348. Notes = route.Notes,
  349. Priority = route.Priority,
  350. Summary = route.Summary
  351. });
  352. }
  353. return routes.ToArray();
  354. }
  355. private string NormalizeEmbyRoutePath(string path)
  356. {
  357. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  358. {
  359. return "/emby" + path;
  360. }
  361. return "emby/" + path;
  362. }
  363. private string DoubleNormalizeEmbyRoutePath(string path)
  364. {
  365. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  366. {
  367. return "/emby/emby" + path;
  368. }
  369. return "emby/emby/" + path;
  370. }
  371. private string NormalizeRoutePath(string path)
  372. {
  373. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  374. {
  375. return "/mediabrowser" + path;
  376. }
  377. return "mediabrowser/" + path;
  378. }
  379. private string DoubleNormalizeRoutePath(string path)
  380. {
  381. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  382. {
  383. return "/mediabrowser/mediabrowser" + path;
  384. }
  385. return "mediabrowser/mediabrowser/" + path;
  386. }
  387. /// <summary>
  388. /// Releases the specified instance.
  389. /// </summary>
  390. /// <param name="instance">The instance.</param>
  391. public override void Release(object instance)
  392. {
  393. // Leave this empty so SS doesn't try to dispose our objects
  394. }
  395. private bool _disposed;
  396. private readonly object _disposeLock = new object();
  397. protected virtual void Dispose(bool disposing)
  398. {
  399. if (_disposed) return;
  400. base.Dispose();
  401. lock (_disposeLock)
  402. {
  403. if (_disposed) return;
  404. if (disposing)
  405. {
  406. Stop();
  407. }
  408. //release unmanaged resources here...
  409. _disposed = true;
  410. }
  411. }
  412. public override void Dispose()
  413. {
  414. Dispose(true);
  415. GC.SuppressFinalize(this);
  416. }
  417. public void StartServer(IEnumerable<string> urlPrefixes, string certificatePath)
  418. {
  419. CertificatePath = certificatePath;
  420. UrlPrefixes = urlPrefixes.ToList();
  421. Start(UrlPrefixes.First());
  422. }
  423. }
  424. }