2
0

HttpListenerHost.cs 17 KB

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