HttpListenerHost.cs 13 KB

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