HttpListenerHost.cs 12 KB

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