HttpListenerHost.cs 14 KB

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