2
0

HttpListenerHost.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. };
  67. HostConfig.Instance.DebugMode = true;
  68. HostConfig.Instance.LogFactory = LogManager.LogFactory;
  69. // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
  70. // Custom format allows images
  71. HostConfig.Instance.EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat;
  72. container.Adapter = _containerAdapter;
  73. Plugins.Add(new SwaggerFeature());
  74. Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization"));
  75. //Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
  76. // new SessionAuthProvider(_containerAdapter.Resolve<ISessionContext>()),
  77. //}));
  78. HostContext.GlobalResponseFilters.Add(new ResponseFilter(_logger).FilterResponse);
  79. }
  80. public override void OnAfterInit()
  81. {
  82. SetAppDomainData();
  83. base.OnAfterInit();
  84. }
  85. public override void OnConfigLoad()
  86. {
  87. base.OnConfigLoad();
  88. Config.HandlerFactoryPath = string.IsNullOrEmpty(HandlerPath)
  89. ? null
  90. : HandlerPath;
  91. Config.MetadataRedirectPath = string.IsNullOrEmpty(HandlerPath)
  92. ? "metadata"
  93. : PathUtils.CombinePaths(HandlerPath, "metadata");
  94. }
  95. protected override ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
  96. {
  97. var types = _restServices.Select(r => r.GetType()).ToArray();
  98. return new ServiceController(this, () => types);
  99. }
  100. public virtual void SetAppDomainData()
  101. {
  102. //Required for Mono to resolve VirtualPathUtility and Url.Content urls
  103. var domain = Thread.GetDomain(); // or AppDomain.Current
  104. domain.SetData(".appDomain", "1");
  105. domain.SetData(".appVPath", "/");
  106. domain.SetData(".appPath", domain.BaseDirectory);
  107. if (string.IsNullOrEmpty(domain.GetData(".appId") as string))
  108. {
  109. domain.SetData(".appId", "1");
  110. }
  111. if (string.IsNullOrEmpty(domain.GetData(".domainId") as string))
  112. {
  113. domain.SetData(".domainId", "1");
  114. }
  115. }
  116. public override ServiceStackHost Start(string listeningAtUrlBase)
  117. {
  118. StartListener();
  119. return this;
  120. }
  121. /// <summary>
  122. /// Starts the Web Service
  123. /// </summary>
  124. private void StartListener()
  125. {
  126. HostContext.Config.HandlerFactoryPath = ListenerRequest.GetHandlerPathIfAny(UrlPrefixes.First());
  127. _listener = NativeWebSocket.IsSupported
  128. ? _listener = new HttpListenerServer(_logger, _threadPoolManager)
  129. : _listener = new WebSocketSharpListener(_logger, _threadPoolManager);
  130. _listener.WebSocketHandler = WebSocketHandler;
  131. _listener.ErrorHandler = ErrorHandler;
  132. _listener.RequestHandler = RequestHandler;
  133. _listener.Start(UrlPrefixes);
  134. }
  135. private void WebSocketHandler(WebSocketConnectEventArgs args)
  136. {
  137. if (WebSocketConnected != null)
  138. {
  139. WebSocketConnected(this, args);
  140. }
  141. }
  142. private void ErrorHandler(Exception ex, IRequest httpReq)
  143. {
  144. try
  145. {
  146. var httpRes = httpReq.Response;
  147. if (httpRes.IsClosed)
  148. {
  149. return;
  150. }
  151. var errorResponse = new ErrorResponse
  152. {
  153. ResponseStatus = new ResponseStatus
  154. {
  155. ErrorCode = ex.GetType().GetOperationName(),
  156. Message = ex.Message,
  157. StackTrace = ex.StackTrace,
  158. }
  159. };
  160. var contentType = httpReq.ResponseContentType;
  161. var serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  162. if (serializer == null)
  163. {
  164. contentType = HostContext.Config.DefaultContentType;
  165. serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  166. }
  167. var httpError = ex as IHttpError;
  168. if (httpError != null)
  169. {
  170. httpRes.StatusCode = httpError.Status;
  171. httpRes.StatusDescription = httpError.StatusDescription;
  172. }
  173. else
  174. {
  175. httpRes.StatusCode = 500;
  176. }
  177. httpRes.ContentType = contentType;
  178. serializer(httpReq, errorResponse, httpRes);
  179. httpRes.Close();
  180. }
  181. catch (Exception errorEx)
  182. {
  183. _logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  184. }
  185. }
  186. /// <summary>
  187. /// Shut down the Web Service
  188. /// </summary>
  189. public void Stop()
  190. {
  191. if (_listener != null)
  192. {
  193. _listener.Stop();
  194. }
  195. }
  196. /// <summary>
  197. /// Overridable method that can be used to implement a custom hnandler
  198. /// </summary>
  199. /// <param name="httpReq">The HTTP req.</param>
  200. /// <param name="url">The URL.</param>
  201. /// <returns>Task.</returns>
  202. protected Task RequestHandler(IHttpRequest httpReq, Uri url)
  203. {
  204. var date = DateTime.Now;
  205. var httpRes = httpReq.Response;
  206. var operationName = httpReq.OperationName;
  207. var localPath = url.LocalPath;
  208. if (string.Equals(localPath, "/" + HandlerPath + "/", StringComparison.OrdinalIgnoreCase))
  209. {
  210. httpRes.RedirectToUrl(DefaultRedirectPath);
  211. return Task.FromResult(true);
  212. }
  213. if (string.Equals(localPath, "/" + HandlerPath, StringComparison.OrdinalIgnoreCase))
  214. {
  215. httpRes.RedirectToUrl(HandlerPath + "/" + DefaultRedirectPath);
  216. return Task.FromResult(true);
  217. }
  218. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  219. {
  220. httpRes.RedirectToUrl(HandlerPath + "/" + DefaultRedirectPath);
  221. return Task.FromResult(true);
  222. }
  223. if (string.IsNullOrEmpty(localPath))
  224. {
  225. httpRes.RedirectToUrl("/" + HandlerPath + "/" + DefaultRedirectPath);
  226. return Task.FromResult(true);
  227. }
  228. var handler = HttpHandlerFactory.GetHandler(httpReq);
  229. var remoteIp = httpReq.RemoteIp;
  230. var serviceStackHandler = handler as IServiceStackHandler;
  231. if (serviceStackHandler != null)
  232. {
  233. var restHandler = serviceStackHandler as RestHandler;
  234. if (restHandler != null)
  235. {
  236. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
  237. }
  238. var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
  239. task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  240. //Matches Exceptions handled in HttpListenerBase.InitTask()
  241. var urlString = url.ToString();
  242. task.ContinueWith(x =>
  243. {
  244. var statusCode = httpRes.StatusCode;
  245. var duration = DateTime.Now - date;
  246. LoggerUtils.LogResponse(_logger, statusCode, urlString, remoteIp, duration);
  247. }, TaskContinuationOptions.None);
  248. return task;
  249. }
  250. return new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
  251. .AsTaskException();
  252. }
  253. /// <summary>
  254. /// Adds the rest handlers.
  255. /// </summary>
  256. /// <param name="services">The services.</param>
  257. public void Init(IEnumerable<IRestfulService> services)
  258. {
  259. _restServices.AddRange(services);
  260. ServiceController = CreateServiceController();
  261. _logger.Info("Calling ServiceStack AppHost.Init");
  262. base.Init();
  263. }
  264. //public override RouteAttribute[] GetRouteAttributes(System.Type requestType)
  265. //{
  266. // var routes = base.GetRouteAttributes(requestType);
  267. // routes.Each(x => x.Path = "/api" + x.Path);
  268. // return routes;
  269. //}
  270. /// <summary>
  271. /// Releases the specified instance.
  272. /// </summary>
  273. /// <param name="instance">The instance.</param>
  274. public override void Release(object instance)
  275. {
  276. // Leave this empty so SS doesn't try to dispose our objects
  277. }
  278. private bool _disposed;
  279. private readonly object _disposeLock = new object();
  280. protected virtual void Dispose(bool disposing)
  281. {
  282. if (_disposed) return;
  283. base.Dispose();
  284. lock (_disposeLock)
  285. {
  286. if (_disposed) return;
  287. if (disposing)
  288. {
  289. _threadPoolManager.Dispose();
  290. Stop();
  291. }
  292. //release unmanaged resources here...
  293. _disposed = true;
  294. }
  295. }
  296. public override void Dispose()
  297. {
  298. Dispose(true);
  299. GC.SuppressFinalize(this);
  300. }
  301. public void StartServer(IEnumerable<string> urlPrefixes)
  302. {
  303. UrlPrefixes = urlPrefixes.ToList();
  304. Start(UrlPrefixes.First());
  305. }
  306. }
  307. }