HttpListenerHost.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. using Funq;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Controller.Net;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Server.Implementations.HttpServer.NetListener;
  8. using MediaBrowser.Server.Implementations.HttpServer.SocketSharp;
  9. using ServiceStack;
  10. using ServiceStack.Api.Swagger;
  11. using ServiceStack.Host;
  12. using ServiceStack.Host.Handlers;
  13. using ServiceStack.Host.HttpListener;
  14. using ServiceStack.Logging;
  15. using ServiceStack.Web;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Reflection;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. namespace MediaBrowser.Server.Implementations.HttpServer
  24. {
  25. public class HttpListenerHost : ServiceStackHost, IHttpServer
  26. {
  27. private string HandlerPath { get; set; }
  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. private readonly List<string> _localEndpoints = new List<string>();
  36. private readonly ReaderWriterLockSlim _localEndpointLock = new ReaderWriterLockSlim();
  37. /// <summary>
  38. /// Gets the local end points.
  39. /// </summary>
  40. /// <value>The local end points.</value>
  41. public IEnumerable<string> LocalEndPoints
  42. {
  43. get
  44. {
  45. _localEndpointLock.EnterReadLock();
  46. var list = _localEndpoints.ToList();
  47. _localEndpointLock.ExitReadLock();
  48. return list;
  49. }
  50. }
  51. public HttpListenerHost(IApplicationHost applicationHost, ILogManager logManager, string serviceName, string handlerPath, string defaultRedirectPath, params Assembly[] assembliesWithServices)
  52. : base(serviceName, assembliesWithServices)
  53. {
  54. DefaultRedirectPath = defaultRedirectPath;
  55. HandlerPath = handlerPath;
  56. _logger = logManager.GetLogger("HttpServer");
  57. _containerAdapter = new ContainerAdapter(applicationHost);
  58. }
  59. public override void Configure(Container container)
  60. {
  61. HostConfig.Instance.DefaultRedirectPath = DefaultRedirectPath;
  62. HostConfig.Instance.MapExceptionToStatusCode = new Dictionary<Type, int>
  63. {
  64. {typeof (InvalidOperationException), 422},
  65. {typeof (ResourceNotFoundException), 404},
  66. {typeof (FileNotFoundException), 404},
  67. {typeof (DirectoryNotFoundException), 404},
  68. {typeof (Implementations.Security.AuthenticationException), 401}
  69. };
  70. HostConfig.Instance.DebugMode = true;
  71. HostConfig.Instance.LogFactory = LogManager.LogFactory;
  72. // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
  73. // Custom format allows images
  74. HostConfig.Instance.EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat;
  75. container.Adapter = _containerAdapter;
  76. Plugins.Add(new SwaggerFeature());
  77. Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization, Range, X-MediaBrowser-Token"));
  78. //Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
  79. // new SessionAuthProvider(_containerAdapter.Resolve<ISessionContext>()),
  80. //}));
  81. PreRequestFilters.Add((httpReq, httpRes) =>
  82. {
  83. //Handles Request and closes Responses after emitting global HTTP Headers
  84. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  85. {
  86. httpRes.EndRequest(); //add a 'using ServiceStack;'
  87. }
  88. });
  89. HostContext.GlobalResponseFilters.Add(new ResponseFilter(_logger).FilterResponse);
  90. }
  91. public override void OnAfterInit()
  92. {
  93. SetAppDomainData();
  94. base.OnAfterInit();
  95. }
  96. public override void OnConfigLoad()
  97. {
  98. base.OnConfigLoad();
  99. Config.HandlerFactoryPath = string.IsNullOrEmpty(HandlerPath)
  100. ? null
  101. : HandlerPath;
  102. Config.MetadataRedirectPath = string.IsNullOrEmpty(HandlerPath)
  103. ? "metadata"
  104. : PathUtils.CombinePaths(HandlerPath, "metadata");
  105. }
  106. protected override ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
  107. {
  108. var types = _restServices.Select(r => r.GetType()).ToArray();
  109. return new ServiceController(this, () => types);
  110. }
  111. public virtual void SetAppDomainData()
  112. {
  113. //Required for Mono to resolve VirtualPathUtility and Url.Content urls
  114. var domain = Thread.GetDomain(); // or AppDomain.Current
  115. domain.SetData(".appDomain", "1");
  116. domain.SetData(".appVPath", "/");
  117. domain.SetData(".appPath", domain.BaseDirectory);
  118. if (string.IsNullOrEmpty(domain.GetData(".appId") as string))
  119. {
  120. domain.SetData(".appId", "1");
  121. }
  122. if (string.IsNullOrEmpty(domain.GetData(".domainId") as string))
  123. {
  124. domain.SetData(".domainId", "1");
  125. }
  126. }
  127. public override ServiceStackHost Start(string listeningAtUrlBase)
  128. {
  129. StartListener();
  130. return this;
  131. }
  132. private void OnRequestReceived(string localEndPoint)
  133. {
  134. var ignore = localEndPoint.IndexOf("::", StringComparison.OrdinalIgnoreCase) != -1 ||
  135. localEndPoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
  136. localEndPoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ||
  137. localEndPoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase);
  138. if (ignore)
  139. {
  140. return;
  141. }
  142. if (_localEndpointLock.TryEnterWriteLock(100))
  143. {
  144. var list = _localEndpoints.ToList();
  145. list.Remove(localEndPoint);
  146. list.Insert(0, localEndPoint);
  147. _localEndpointLock.ExitWriteLock();
  148. }
  149. }
  150. /// <summary>
  151. /// Starts the Web Service
  152. /// </summary>
  153. private void StartListener()
  154. {
  155. HostContext.Config.HandlerFactoryPath = ListenerRequest.GetHandlerPathIfAny(UrlPrefixes.First());
  156. _listener = NativeWebSocket.IsSupported
  157. ? _listener = new HttpListenerServer(_logger, OnRequestReceived)
  158. //? _listener = new WebSocketSharpListener(_logger, OnRequestReceived)
  159. : _listener = new WebSocketSharpListener(_logger, OnRequestReceived);
  160. _listener.WebSocketHandler = WebSocketHandler;
  161. _listener.ErrorHandler = ErrorHandler;
  162. _listener.RequestHandler = RequestHandler;
  163. _listener.Start(UrlPrefixes);
  164. }
  165. private void WebSocketHandler(WebSocketConnectEventArgs args)
  166. {
  167. if (WebSocketConnected != null)
  168. {
  169. WebSocketConnected(this, args);
  170. }
  171. }
  172. private void ErrorHandler(Exception ex, IRequest httpReq)
  173. {
  174. try
  175. {
  176. var httpRes = httpReq.Response;
  177. if (httpRes.IsClosed)
  178. {
  179. return;
  180. }
  181. var errorResponse = new ErrorResponse
  182. {
  183. ResponseStatus = new ResponseStatus
  184. {
  185. ErrorCode = ex.GetType().GetOperationName(),
  186. Message = ex.Message,
  187. StackTrace = ex.StackTrace,
  188. }
  189. };
  190. var contentType = httpReq.ResponseContentType;
  191. var serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  192. if (serializer == null)
  193. {
  194. contentType = HostContext.Config.DefaultContentType;
  195. serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  196. }
  197. var httpError = ex as IHttpError;
  198. if (httpError != null)
  199. {
  200. httpRes.StatusCode = httpError.Status;
  201. httpRes.StatusDescription = httpError.StatusDescription;
  202. }
  203. else
  204. {
  205. httpRes.StatusCode = 500;
  206. }
  207. httpRes.ContentType = contentType;
  208. serializer(httpReq, errorResponse, httpRes);
  209. httpRes.Close();
  210. }
  211. catch (Exception errorEx)
  212. {
  213. _logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  214. }
  215. }
  216. /// <summary>
  217. /// Shut down the Web Service
  218. /// </summary>
  219. public void Stop()
  220. {
  221. if (_listener != null)
  222. {
  223. _listener.Stop();
  224. }
  225. }
  226. /// <summary>
  227. /// Overridable method that can be used to implement a custom hnandler
  228. /// </summary>
  229. /// <param name="httpReq">The HTTP req.</param>
  230. /// <param name="url">The URL.</param>
  231. /// <returns>Task.</returns>
  232. protected Task RequestHandler(IHttpRequest httpReq, Uri url)
  233. {
  234. var date = DateTime.Now;
  235. var httpRes = httpReq.Response;
  236. var operationName = httpReq.OperationName;
  237. var localPath = url.LocalPath;
  238. if (string.Equals(localPath, "/" + HandlerPath + "/", StringComparison.OrdinalIgnoreCase))
  239. {
  240. httpRes.RedirectToUrl(DefaultRedirectPath);
  241. return Task.FromResult(true);
  242. }
  243. if (string.Equals(localPath, "/" + HandlerPath, StringComparison.OrdinalIgnoreCase))
  244. {
  245. httpRes.RedirectToUrl(HandlerPath + "/" + DefaultRedirectPath);
  246. return Task.FromResult(true);
  247. }
  248. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  249. {
  250. httpRes.RedirectToUrl(HandlerPath + "/" + DefaultRedirectPath);
  251. return Task.FromResult(true);
  252. }
  253. if (string.IsNullOrEmpty(localPath))
  254. {
  255. httpRes.RedirectToUrl("/" + HandlerPath + "/" + DefaultRedirectPath);
  256. return Task.FromResult(true);
  257. }
  258. var handler = HttpHandlerFactory.GetHandler(httpReq);
  259. var remoteIp = httpReq.RemoteIp;
  260. var serviceStackHandler = handler as IServiceStackHandler;
  261. if (serviceStackHandler != null)
  262. {
  263. var restHandler = serviceStackHandler as RestHandler;
  264. if (restHandler != null)
  265. {
  266. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
  267. }
  268. var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
  269. task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  270. //Matches Exceptions handled in HttpListenerBase.InitTask()
  271. var urlString = url.ToString();
  272. task.ContinueWith(x =>
  273. {
  274. var statusCode = httpRes.StatusCode;
  275. var duration = DateTime.Now - date;
  276. LoggerUtils.LogResponse(_logger, statusCode, urlString, remoteIp, duration);
  277. }, TaskContinuationOptions.None);
  278. return task;
  279. }
  280. return new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
  281. .AsTaskException();
  282. }
  283. /// <summary>
  284. /// Adds the rest handlers.
  285. /// </summary>
  286. /// <param name="services">The services.</param>
  287. public void Init(IEnumerable<IRestfulService> services)
  288. {
  289. _restServices.AddRange(services);
  290. ServiceController = CreateServiceController();
  291. _logger.Info("Calling ServiceStack AppHost.Init");
  292. base.Init();
  293. }
  294. //public override RouteAttribute[] GetRouteAttributes(System.Type requestType)
  295. //{
  296. // var routes = base.GetRouteAttributes(requestType);
  297. // routes.Each(x => x.Path = "/api" + x.Path);
  298. // return routes;
  299. //}
  300. /// <summary>
  301. /// Releases the specified instance.
  302. /// </summary>
  303. /// <param name="instance">The instance.</param>
  304. public override void Release(object instance)
  305. {
  306. // Leave this empty so SS doesn't try to dispose our objects
  307. }
  308. private bool _disposed;
  309. private readonly object _disposeLock = new object();
  310. protected virtual void Dispose(bool disposing)
  311. {
  312. if (_disposed) return;
  313. base.Dispose();
  314. lock (_disposeLock)
  315. {
  316. if (_disposed) return;
  317. if (disposing)
  318. {
  319. Stop();
  320. }
  321. //release unmanaged resources here...
  322. _disposed = true;
  323. }
  324. }
  325. public override void Dispose()
  326. {
  327. Dispose(true);
  328. GC.SuppressFinalize(this);
  329. }
  330. public void StartServer(IEnumerable<string> urlPrefixes)
  331. {
  332. UrlPrefixes = urlPrefixes.ToList();
  333. Start(UrlPrefixes.First());
  334. }
  335. }
  336. }