HttpListenerHost.cs 14 KB

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