HttpListenerHost.cs 14 KB

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