HttpListenerHost.cs 17 KB

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