HttpListenerHost.cs 13 KB

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