HttpListenerHost.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. namespace MediaBrowser.Server.Implementations.HttpServer
  25. {
  26. public class HttpListenerHost : ServiceStackHost, IHttpServer
  27. {
  28. private string DefaultRedirectPath { get; set; }
  29. private readonly ILogger _logger;
  30. public IEnumerable<string> UrlPrefixes { get; private set; }
  31. private readonly List<IRestfulService> _restServices = new List<IRestfulService>();
  32. private IHttpListener _listener;
  33. private readonly ContainerAdapter _containerAdapter;
  34. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  35. public event EventHandler<WebSocketConnectingEventArgs> WebSocketConnecting;
  36. private readonly List<string> _localEndpoints = new List<string>();
  37. private readonly ReaderWriterLockSlim _localEndpointLock = new ReaderWriterLockSlim();
  38. public string CertificatePath { get; private set; }
  39. private readonly IServerConfigurationManager _config;
  40. private readonly INetworkManager _networkManager;
  41. /// <summary>
  42. /// Gets the local end points.
  43. /// </summary>
  44. /// <value>The local end points.</value>
  45. public IEnumerable<string> LocalEndPoints
  46. {
  47. get
  48. {
  49. _localEndpointLock.EnterReadLock();
  50. var list = _localEndpoints.ToList();
  51. _localEndpointLock.ExitReadLock();
  52. return list;
  53. }
  54. }
  55. public HttpListenerHost(IApplicationHost applicationHost,
  56. ILogManager logManager,
  57. IServerConfigurationManager config,
  58. string serviceName,
  59. string defaultRedirectPath, INetworkManager networkManager, params Assembly[] assembliesWithServices)
  60. : base(serviceName, assembliesWithServices)
  61. {
  62. DefaultRedirectPath = defaultRedirectPath;
  63. _networkManager = networkManager;
  64. _config = config;
  65. _logger = logManager.GetLogger("HttpServer");
  66. _containerAdapter = new ContainerAdapter(applicationHost);
  67. }
  68. public string GlobalResponse { get; set; }
  69. public override void Configure(Container container)
  70. {
  71. HostConfig.Instance.DefaultRedirectPath = DefaultRedirectPath;
  72. HostConfig.Instance.MapExceptionToStatusCode = new Dictionary<Type, int>
  73. {
  74. {typeof (InvalidOperationException), 422},
  75. {typeof (ResourceNotFoundException), 404},
  76. {typeof (FileNotFoundException), 404},
  77. {typeof (DirectoryNotFoundException), 404},
  78. {typeof (SecurityException), 401},
  79. {typeof (PaymentRequiredException), 402},
  80. {typeof (UnauthorizedAccessException), 500},
  81. {typeof (ApplicationException), 500}
  82. };
  83. HostConfig.Instance.DebugMode = true;
  84. HostConfig.Instance.LogFactory = LogManager.LogFactory;
  85. // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
  86. // Custom format allows images
  87. HostConfig.Instance.EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat;
  88. container.Adapter = _containerAdapter;
  89. Plugins.Add(new SwaggerFeature());
  90. Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization"));
  91. //Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
  92. // new SessionAuthProvider(_containerAdapter.Resolve<ISessionContext>()),
  93. //}));
  94. PreRequestFilters.Add((httpReq, httpRes) =>
  95. {
  96. //Handles Request and closes Responses after emitting global HTTP Headers
  97. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  98. {
  99. httpRes.EndRequest(); //add a 'using ServiceStack;'
  100. }
  101. });
  102. HostContext.GlobalResponseFilters.Add(new ResponseFilter(_logger, () => _config.Configuration.DenyIFrameEmbedding).FilterResponse);
  103. }
  104. public override void OnAfterInit()
  105. {
  106. SetAppDomainData();
  107. base.OnAfterInit();
  108. }
  109. public override void OnConfigLoad()
  110. {
  111. base.OnConfigLoad();
  112. Config.HandlerFactoryPath = null;
  113. Config.MetadataRedirectPath = "metadata";
  114. }
  115. protected override ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
  116. {
  117. var types = _restServices.Select(r => r.GetType()).ToArray();
  118. return new ServiceController(this, () => types);
  119. }
  120. public virtual void SetAppDomainData()
  121. {
  122. //Required for Mono to resolve VirtualPathUtility and Url.Content urls
  123. var domain = Thread.GetDomain(); // or AppDomain.Current
  124. domain.SetData(".appDomain", "1");
  125. domain.SetData(".appVPath", "/");
  126. domain.SetData(".appPath", domain.BaseDirectory);
  127. if (string.IsNullOrEmpty(domain.GetData(".appId") as string))
  128. {
  129. domain.SetData(".appId", "1");
  130. }
  131. if (string.IsNullOrEmpty(domain.GetData(".domainId") as string))
  132. {
  133. domain.SetData(".domainId", "1");
  134. }
  135. }
  136. public override ServiceStackHost Start(string listeningAtUrlBase)
  137. {
  138. StartListener();
  139. return this;
  140. }
  141. private void OnRequestReceived(string localEndPoint)
  142. {
  143. var ignore = _networkManager.IsInPrivateAddressSpace(localEndPoint);
  144. if (ignore)
  145. {
  146. return;
  147. }
  148. if (_localEndpointLock.TryEnterWriteLock(100))
  149. {
  150. var list = _localEndpoints;
  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, "/web", StringComparison.OrdinalIgnoreCase))
  270. {
  271. httpRes.RedirectToUrl(DefaultRedirectPath);
  272. return Task.FromResult(true);
  273. }
  274. if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase))
  275. {
  276. httpRes.RedirectToUrl("../" + DefaultRedirectPath);
  277. return Task.FromResult(true);
  278. }
  279. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  280. {
  281. httpRes.RedirectToUrl(DefaultRedirectPath);
  282. return Task.FromResult(true);
  283. }
  284. if (string.IsNullOrEmpty(localPath))
  285. {
  286. httpRes.RedirectToUrl("/" + DefaultRedirectPath);
  287. return Task.FromResult(true);
  288. }
  289. if (!string.IsNullOrWhiteSpace(GlobalResponse))
  290. {
  291. httpRes.Write(GlobalResponse);
  292. httpRes.ContentType = "text/plain";
  293. return Task.FromResult(true);
  294. }
  295. var handler = HttpHandlerFactory.GetHandler(httpReq);
  296. var remoteIp = httpReq.RemoteIp;
  297. var serviceStackHandler = handler as IServiceStackHandler;
  298. if (serviceStackHandler != null)
  299. {
  300. var restHandler = serviceStackHandler as RestHandler;
  301. if (restHandler != null)
  302. {
  303. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
  304. }
  305. var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
  306. task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  307. //Matches Exceptions handled in HttpListenerBase.InitTask()
  308. var urlString = url.ToString();
  309. task.ContinueWith(x =>
  310. {
  311. var statusCode = httpRes.StatusCode;
  312. var duration = DateTime.Now - date;
  313. LoggerUtils.LogResponse(_logger, statusCode, urlString, remoteIp, duration);
  314. }, TaskContinuationOptions.None);
  315. return task;
  316. }
  317. return new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
  318. .AsTaskException();
  319. }
  320. /// <summary>
  321. /// Adds the rest handlers.
  322. /// </summary>
  323. /// <param name="services">The services.</param>
  324. public void Init(IEnumerable<IRestfulService> services)
  325. {
  326. _restServices.AddRange(services);
  327. ServiceController = CreateServiceController();
  328. _logger.Info("Calling ServiceStack AppHost.Init");
  329. base.Init();
  330. }
  331. public override RouteAttribute[] GetRouteAttributes(Type requestType)
  332. {
  333. var routes = base.GetRouteAttributes(requestType).ToList();
  334. var clone = routes.ToList();
  335. foreach (var route in clone)
  336. {
  337. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  338. {
  339. Notes = route.Notes,
  340. Priority = route.Priority,
  341. Summary = route.Summary
  342. });
  343. routes.Add(new RouteAttribute(NormalizeRoutePath(route.Path), route.Verbs)
  344. {
  345. Notes = route.Notes,
  346. Priority = route.Priority,
  347. Summary = route.Summary
  348. });
  349. // TODO: This is a hack for iOS. Remove it asap.
  350. routes.Add(new RouteAttribute(DoubleNormalizeRoutePath(route.Path), route.Verbs)
  351. {
  352. Notes = route.Notes,
  353. Priority = route.Priority,
  354. Summary = route.Summary
  355. });
  356. routes.Add(new RouteAttribute(DoubleNormalizeEmbyRoutePath(route.Path), route.Verbs)
  357. {
  358. Notes = route.Notes,
  359. Priority = route.Priority,
  360. Summary = route.Summary
  361. });
  362. }
  363. return routes.ToArray();
  364. }
  365. private string NormalizeEmbyRoutePath(string path)
  366. {
  367. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  368. {
  369. return "/emby" + path;
  370. }
  371. return "emby/" + path;
  372. }
  373. private string DoubleNormalizeEmbyRoutePath(string path)
  374. {
  375. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  376. {
  377. return "/emby/emby" + path;
  378. }
  379. return "emby/emby/" + path;
  380. }
  381. private string NormalizeRoutePath(string path)
  382. {
  383. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  384. {
  385. return "/mediabrowser" + path;
  386. }
  387. return "mediabrowser/" + path;
  388. }
  389. private string DoubleNormalizeRoutePath(string path)
  390. {
  391. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  392. {
  393. return "/mediabrowser/mediabrowser" + path;
  394. }
  395. return "mediabrowser/mediabrowser/" + path;
  396. }
  397. /// <summary>
  398. /// Releases the specified instance.
  399. /// </summary>
  400. /// <param name="instance">The instance.</param>
  401. public override void Release(object instance)
  402. {
  403. // Leave this empty so SS doesn't try to dispose our objects
  404. }
  405. private bool _disposed;
  406. private readonly object _disposeLock = new object();
  407. protected virtual void Dispose(bool disposing)
  408. {
  409. if (_disposed) return;
  410. base.Dispose();
  411. lock (_disposeLock)
  412. {
  413. if (_disposed) return;
  414. if (disposing)
  415. {
  416. Stop();
  417. }
  418. //release unmanaged resources here...
  419. _disposed = true;
  420. }
  421. }
  422. public override void Dispose()
  423. {
  424. Dispose(true);
  425. GC.SuppressFinalize(this);
  426. }
  427. public void StartServer(IEnumerable<string> urlPrefixes, string certificatePath)
  428. {
  429. CertificatePath = certificatePath;
  430. UrlPrefixes = urlPrefixes.ToList();
  431. Start(UrlPrefixes.First());
  432. }
  433. }
  434. }