HttpListenerHost.cs 13 KB

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