HttpListenerHost.cs 17 KB

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