HttpListenerHost.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. using Funq;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Controller.Net;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Server.Implementations.HttpServer.NetListener;
  7. using MediaBrowser.Server.Implementations.HttpServer.SocketSharp;
  8. using ServiceStack;
  9. using ServiceStack.Api.Swagger;
  10. using ServiceStack.Host;
  11. using ServiceStack.Host.Handlers;
  12. using ServiceStack.Host.HttpListener;
  13. using ServiceStack.Logging;
  14. using ServiceStack.Web;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Reflection;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. namespace MediaBrowser.Server.Implementations.HttpServer
  23. {
  24. public class HttpListenerHost : ServiceStackHost, IHttpServer
  25. {
  26. private string HandlerPath { get; set; }
  27. private string DefaultRedirectPath { get; set; }
  28. private readonly ILogger _logger;
  29. public IEnumerable<string> UrlPrefixes { get; private set; }
  30. private readonly List<IRestfulService> _restServices = new List<IRestfulService>();
  31. private IHttpListener _listener;
  32. private readonly ContainerAdapter _containerAdapter;
  33. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  34. private readonly List<string> _localEndpoints = new List<string>();
  35. private readonly ReaderWriterLockSlim _localEndpointLock = new ReaderWriterLockSlim();
  36. private readonly bool _supportsNativeWebSocket;
  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,
  52. ILogManager logManager,
  53. string serviceName,
  54. string handlerPath,
  55. string defaultRedirectPath,
  56. bool supportsNativeWebSocket,
  57. params Assembly[] assembliesWithServices)
  58. : base(serviceName, assembliesWithServices)
  59. {
  60. DefaultRedirectPath = defaultRedirectPath;
  61. _supportsNativeWebSocket = supportsNativeWebSocket;
  62. HandlerPath = handlerPath;
  63. _logger = logManager.GetLogger("HttpServer");
  64. _containerAdapter = new ContainerAdapter(applicationHost);
  65. }
  66. public override void Configure(Container container)
  67. {
  68. HostConfig.Instance.DefaultRedirectPath = DefaultRedirectPath;
  69. HostConfig.Instance.MapExceptionToStatusCode = new Dictionary<Type, int>
  70. {
  71. {typeof (InvalidOperationException), 422},
  72. {typeof (ResourceNotFoundException), 404},
  73. {typeof (FileNotFoundException), 404},
  74. {typeof (DirectoryNotFoundException), 404},
  75. {typeof (SecurityException), 401},
  76. {typeof (UnauthorizedAccessException), 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 = GetListener();
  165. _listener.WebSocketHandler = WebSocketHandler;
  166. _listener.ErrorHandler = ErrorHandler;
  167. _listener.RequestHandler = RequestHandler;
  168. _listener.Start(UrlPrefixes);
  169. }
  170. private IHttpListener GetListener()
  171. {
  172. if (_supportsNativeWebSocket && NativeWebSocket.IsSupported)
  173. {
  174. return new HttpListenerServer(_logger, OnRequestReceived);
  175. }
  176. return new WebSocketSharpListener(_logger, OnRequestReceived);
  177. }
  178. private void WebSocketHandler(WebSocketConnectEventArgs args)
  179. {
  180. if (WebSocketConnected != null)
  181. {
  182. WebSocketConnected(this, args);
  183. }
  184. }
  185. private void ErrorHandler(Exception ex, IRequest httpReq)
  186. {
  187. try
  188. {
  189. var httpRes = httpReq.Response;
  190. if (httpRes.IsClosed)
  191. {
  192. return;
  193. }
  194. var errorResponse = new ErrorResponse
  195. {
  196. ResponseStatus = new ResponseStatus
  197. {
  198. ErrorCode = ex.GetType().GetOperationName(),
  199. Message = ex.Message,
  200. StackTrace = ex.StackTrace
  201. }
  202. };
  203. var contentType = httpReq.ResponseContentType;
  204. var serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  205. if (serializer == null)
  206. {
  207. contentType = HostContext.Config.DefaultContentType;
  208. serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  209. }
  210. var httpError = ex as IHttpError;
  211. if (httpError != null)
  212. {
  213. httpRes.StatusCode = httpError.Status;
  214. httpRes.StatusDescription = httpError.StatusDescription;
  215. }
  216. else
  217. {
  218. httpRes.StatusCode = 500;
  219. }
  220. httpRes.ContentType = contentType;
  221. serializer(httpReq, errorResponse, httpRes);
  222. httpRes.Close();
  223. }
  224. catch (Exception errorEx)
  225. {
  226. _logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  227. }
  228. }
  229. /// <summary>
  230. /// Shut down the Web Service
  231. /// </summary>
  232. public void Stop()
  233. {
  234. if (_listener != null)
  235. {
  236. _listener.Stop();
  237. }
  238. }
  239. /// <summary>
  240. /// Overridable method that can be used to implement a custom hnandler
  241. /// </summary>
  242. /// <param name="httpReq">The HTTP req.</param>
  243. /// <param name="url">The URL.</param>
  244. /// <returns>Task.</returns>
  245. protected Task RequestHandler(IHttpRequest httpReq, Uri url)
  246. {
  247. var date = DateTime.Now;
  248. var httpRes = httpReq.Response;
  249. var operationName = httpReq.OperationName;
  250. var localPath = url.LocalPath;
  251. if (string.Equals(localPath, "/" + HandlerPath + "/", StringComparison.OrdinalIgnoreCase))
  252. {
  253. httpRes.RedirectToUrl(DefaultRedirectPath);
  254. return Task.FromResult(true);
  255. }
  256. if (string.Equals(localPath, "/" + HandlerPath, StringComparison.OrdinalIgnoreCase))
  257. {
  258. httpRes.RedirectToUrl(HandlerPath + "/" + DefaultRedirectPath);
  259. return Task.FromResult(true);
  260. }
  261. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  262. {
  263. httpRes.RedirectToUrl(HandlerPath + "/" + DefaultRedirectPath);
  264. return Task.FromResult(true);
  265. }
  266. if (string.IsNullOrEmpty(localPath))
  267. {
  268. httpRes.RedirectToUrl("/" + HandlerPath + "/" + DefaultRedirectPath);
  269. return Task.FromResult(true);
  270. }
  271. var handler = HttpHandlerFactory.GetHandler(httpReq);
  272. var remoteIp = httpReq.RemoteIp;
  273. var serviceStackHandler = handler as IServiceStackHandler;
  274. if (serviceStackHandler != null)
  275. {
  276. var restHandler = serviceStackHandler as RestHandler;
  277. if (restHandler != null)
  278. {
  279. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
  280. }
  281. var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
  282. task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  283. //Matches Exceptions handled in HttpListenerBase.InitTask()
  284. var urlString = url.ToString();
  285. task.ContinueWith(x =>
  286. {
  287. var statusCode = httpRes.StatusCode;
  288. var duration = DateTime.Now - date;
  289. LoggerUtils.LogResponse(_logger, statusCode, urlString, remoteIp, duration);
  290. }, TaskContinuationOptions.None);
  291. return task;
  292. }
  293. return new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
  294. .AsTaskException();
  295. }
  296. /// <summary>
  297. /// Adds the rest handlers.
  298. /// </summary>
  299. /// <param name="services">The services.</param>
  300. public void Init(IEnumerable<IRestfulService> services)
  301. {
  302. _restServices.AddRange(services);
  303. ServiceController = CreateServiceController();
  304. _logger.Info("Calling ServiceStack AppHost.Init");
  305. base.Init();
  306. }
  307. //public override RouteAttribute[] GetRouteAttributes(System.Type requestType)
  308. //{
  309. // var routes = base.GetRouteAttributes(requestType);
  310. // routes.Each(x => x.Path = "/api" + x.Path);
  311. // return routes;
  312. //}
  313. /// <summary>
  314. /// Releases the specified instance.
  315. /// </summary>
  316. /// <param name="instance">The instance.</param>
  317. public override void Release(object instance)
  318. {
  319. // Leave this empty so SS doesn't try to dispose our objects
  320. }
  321. private bool _disposed;
  322. private readonly object _disposeLock = new object();
  323. protected virtual void Dispose(bool disposing)
  324. {
  325. if (_disposed) return;
  326. base.Dispose();
  327. lock (_disposeLock)
  328. {
  329. if (_disposed) return;
  330. if (disposing)
  331. {
  332. Stop();
  333. }
  334. //release unmanaged resources here...
  335. _disposed = true;
  336. }
  337. }
  338. public override void Dispose()
  339. {
  340. Dispose(true);
  341. GC.SuppressFinalize(this);
  342. }
  343. public void StartServer(IEnumerable<string> urlPrefixes)
  344. {
  345. UrlPrefixes = urlPrefixes.ToList();
  346. Start(UrlPrefixes.First());
  347. }
  348. }
  349. }