HttpListenerHost.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. private string _certificatePath;
  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 (SecurityException), 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 = GetListener();
  166. _listener.WebSocketHandler = WebSocketHandler;
  167. _listener.ErrorHandler = ErrorHandler;
  168. _listener.RequestHandler = RequestHandler;
  169. _listener.Start(UrlPrefixes);
  170. }
  171. private IHttpListener GetListener()
  172. {
  173. if (_supportsNativeWebSocket && NativeWebSocket.IsSupported)
  174. {
  175. // Certificate location is ignored here. You need to use netsh
  176. // to assign the certificate to the proper port.
  177. return new HttpListenerServer(_logger, OnRequestReceived);
  178. }
  179. return new WebSocketSharpListener(_logger, OnRequestReceived, _certificatePath);
  180. }
  181. private void WebSocketHandler(WebSocketConnectEventArgs args)
  182. {
  183. if (WebSocketConnected != null)
  184. {
  185. WebSocketConnected(this, args);
  186. }
  187. }
  188. private void ErrorHandler(Exception ex, IRequest httpReq)
  189. {
  190. try
  191. {
  192. var httpRes = httpReq.Response;
  193. if (httpRes.IsClosed)
  194. {
  195. return;
  196. }
  197. var errorResponse = new ErrorResponse
  198. {
  199. ResponseStatus = new ResponseStatus
  200. {
  201. ErrorCode = ex.GetType().GetOperationName(),
  202. Message = ex.Message,
  203. StackTrace = ex.StackTrace
  204. }
  205. };
  206. var contentType = httpReq.ResponseContentType;
  207. var serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  208. if (serializer == null)
  209. {
  210. contentType = HostContext.Config.DefaultContentType;
  211. serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  212. }
  213. var httpError = ex as IHttpError;
  214. if (httpError != null)
  215. {
  216. httpRes.StatusCode = httpError.Status;
  217. httpRes.StatusDescription = httpError.StatusDescription;
  218. }
  219. else
  220. {
  221. httpRes.StatusCode = 500;
  222. }
  223. httpRes.ContentType = contentType;
  224. serializer(httpReq, errorResponse, httpRes);
  225. httpRes.Close();
  226. }
  227. catch (Exception errorEx)
  228. {
  229. _logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  230. }
  231. }
  232. /// <summary>
  233. /// Shut down the Web Service
  234. /// </summary>
  235. public void Stop()
  236. {
  237. if (_listener != null)
  238. {
  239. _listener.Stop();
  240. }
  241. }
  242. /// <summary>
  243. /// Overridable method that can be used to implement a custom hnandler
  244. /// </summary>
  245. /// <param name="httpReq">The HTTP req.</param>
  246. /// <param name="url">The URL.</param>
  247. /// <returns>Task.</returns>
  248. protected Task RequestHandler(IHttpRequest httpReq, Uri url)
  249. {
  250. var date = DateTime.Now;
  251. var httpRes = httpReq.Response;
  252. var operationName = httpReq.OperationName;
  253. var localPath = url.LocalPath;
  254. if (string.Equals(localPath, "/" + HandlerPath + "/", StringComparison.OrdinalIgnoreCase))
  255. {
  256. httpRes.RedirectToUrl(DefaultRedirectPath);
  257. return Task.FromResult(true);
  258. }
  259. if (string.Equals(localPath, "/" + HandlerPath, StringComparison.OrdinalIgnoreCase))
  260. {
  261. httpRes.RedirectToUrl(HandlerPath + "/" + DefaultRedirectPath);
  262. return Task.FromResult(true);
  263. }
  264. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  265. {
  266. httpRes.RedirectToUrl(HandlerPath + "/" + DefaultRedirectPath);
  267. return Task.FromResult(true);
  268. }
  269. if (string.IsNullOrEmpty(localPath))
  270. {
  271. httpRes.RedirectToUrl("/" + HandlerPath + "/" + DefaultRedirectPath);
  272. return Task.FromResult(true);
  273. }
  274. var handler = HttpHandlerFactory.GetHandler(httpReq);
  275. var remoteIp = httpReq.RemoteIp;
  276. var serviceStackHandler = handler as IServiceStackHandler;
  277. if (serviceStackHandler != null)
  278. {
  279. var restHandler = serviceStackHandler as RestHandler;
  280. if (restHandler != null)
  281. {
  282. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
  283. }
  284. var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
  285. task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  286. //Matches Exceptions handled in HttpListenerBase.InitTask()
  287. var urlString = url.ToString();
  288. task.ContinueWith(x =>
  289. {
  290. var statusCode = httpRes.StatusCode;
  291. var duration = DateTime.Now - date;
  292. LoggerUtils.LogResponse(_logger, statusCode, urlString, remoteIp, duration);
  293. }, TaskContinuationOptions.None);
  294. return task;
  295. }
  296. return new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
  297. .AsTaskException();
  298. }
  299. /// <summary>
  300. /// Adds the rest handlers.
  301. /// </summary>
  302. /// <param name="services">The services.</param>
  303. public void Init(IEnumerable<IRestfulService> services)
  304. {
  305. _restServices.AddRange(services);
  306. ServiceController = CreateServiceController();
  307. _logger.Info("Calling ServiceStack AppHost.Init");
  308. base.Init();
  309. }
  310. //public override RouteAttribute[] GetRouteAttributes(System.Type requestType)
  311. //{
  312. // var routes = base.GetRouteAttributes(requestType);
  313. // routes.Each(x => x.Path = "/api" + x.Path);
  314. // return routes;
  315. //}
  316. /// <summary>
  317. /// Releases the specified instance.
  318. /// </summary>
  319. /// <param name="instance">The instance.</param>
  320. public override void Release(object instance)
  321. {
  322. // Leave this empty so SS doesn't try to dispose our objects
  323. }
  324. private bool _disposed;
  325. private readonly object _disposeLock = new object();
  326. protected virtual void Dispose(bool disposing)
  327. {
  328. if (_disposed) return;
  329. base.Dispose();
  330. lock (_disposeLock)
  331. {
  332. if (_disposed) return;
  333. if (disposing)
  334. {
  335. Stop();
  336. }
  337. //release unmanaged resources here...
  338. _disposed = true;
  339. }
  340. }
  341. public override void Dispose()
  342. {
  343. Dispose(true);
  344. GC.SuppressFinalize(this);
  345. }
  346. public void StartServer(IEnumerable<string> urlPrefixes, string certificatePath)
  347. {
  348. _certificatePath = certificatePath;
  349. UrlPrefixes = urlPrefixes.ToList();
  350. Start(UrlPrefixes.First());
  351. }
  352. }
  353. }