2
0

HttpListenerHost.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. using Amib.Threading;
  2. using Funq;
  3. using MediaBrowser.Common;
  4. using MediaBrowser.Common.Extensions;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Controller.Net;
  7. using MediaBrowser.Model.Logging;
  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.Concurrent;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Net;
  21. using System.Reflection;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. namespace MediaBrowser.Server.Implementations.HttpServer
  25. {
  26. public class HttpListenerHost : ServiceStackHost, IHttpServer
  27. {
  28. private string HandlerPath { get; set; }
  29. private string DefaultRedirectPath { get; set; }
  30. private readonly ILogger _logger;
  31. public IEnumerable<string> UrlPrefixes { get; private set; }
  32. private readonly List<IRestfulService> _restServices = new List<IRestfulService>();
  33. private HttpListener Listener { get; set; }
  34. protected bool IsStarted = false;
  35. private readonly AutoResetEvent _listenForNextRequest = new AutoResetEvent(false);
  36. private readonly SmartThreadPool _threadPoolManager;
  37. private const int IdleTimeout = 300;
  38. private readonly ContainerAdapter _containerAdapter;
  39. private readonly ConcurrentDictionary<string, string> _localEndPoints = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  40. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  41. /// <summary>
  42. /// Gets the local end points.
  43. /// </summary>
  44. /// <value>The local end points.</value>
  45. public IEnumerable<string> LocalEndPoints
  46. {
  47. get { return _localEndPoints.Keys.ToList(); }
  48. }
  49. public HttpListenerHost(IApplicationHost applicationHost, ILogManager logManager, string serviceName, string handlerPath, string defaultRedirectPath, params Assembly[] assembliesWithServices)
  50. : base(serviceName, assembliesWithServices)
  51. {
  52. DefaultRedirectPath = defaultRedirectPath;
  53. HandlerPath = handlerPath;
  54. _logger = logManager.GetLogger("HttpServer");
  55. _containerAdapter = new ContainerAdapter(applicationHost);
  56. _threadPoolManager = new SmartThreadPool(IdleTimeout,
  57. maxWorkerThreads: Math.Max(16, Environment.ProcessorCount * 2));
  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. };
  69. HostConfig.Instance.DebugMode = true;
  70. HostConfig.Instance.LogFactory = LogManager.LogFactory;
  71. // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
  72. // Custom format allows images
  73. HostConfig.Instance.EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat;
  74. container.Adapter = _containerAdapter;
  75. Plugins.Add(new SwaggerFeature());
  76. Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization"));
  77. //Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
  78. // new SessionAuthProvider(_containerAdapter.Resolve<ISessionContext>()),
  79. //}));
  80. HostContext.GlobalResponseFilters.Add(new ResponseFilter(_logger).FilterResponse);
  81. }
  82. public override void OnAfterInit()
  83. {
  84. SetAppDomainData();
  85. base.OnAfterInit();
  86. }
  87. public override void OnConfigLoad()
  88. {
  89. base.OnConfigLoad();
  90. Config.HandlerFactoryPath = string.IsNullOrEmpty(HandlerPath)
  91. ? null
  92. : HandlerPath;
  93. Config.MetadataRedirectPath = string.IsNullOrEmpty(HandlerPath)
  94. ? "metadata"
  95. : PathUtils.CombinePaths(HandlerPath, "metadata");
  96. }
  97. protected override ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
  98. {
  99. var types = _restServices.Select(r => r.GetType()).ToArray();
  100. return new ServiceController(this, () => types);
  101. }
  102. public virtual void SetAppDomainData()
  103. {
  104. //Required for Mono to resolve VirtualPathUtility and Url.Content urls
  105. var domain = Thread.GetDomain(); // or AppDomain.Current
  106. domain.SetData(".appDomain", "1");
  107. domain.SetData(".appVPath", "/");
  108. domain.SetData(".appPath", domain.BaseDirectory);
  109. if (string.IsNullOrEmpty(domain.GetData(".appId") as string))
  110. {
  111. domain.SetData(".appId", "1");
  112. }
  113. if (string.IsNullOrEmpty(domain.GetData(".domainId") as string))
  114. {
  115. domain.SetData(".domainId", "1");
  116. }
  117. }
  118. public override ServiceStackHost Start(string listeningAtUrlBase)
  119. {
  120. StartListener(Listen);
  121. return this;
  122. }
  123. /// <summary>
  124. /// Starts the Web Service
  125. /// </summary>
  126. private void StartListener(WaitCallback listenCallback)
  127. {
  128. // *** Already running - just leave it in place
  129. if (IsStarted)
  130. return;
  131. if (Listener == null)
  132. Listener = new HttpListener();
  133. HostContext.Config.HandlerFactoryPath = ListenerRequest.GetHandlerPathIfAny(UrlPrefixes.First());
  134. foreach (var prefix in UrlPrefixes)
  135. {
  136. _logger.Info("Adding HttpListener prefix " + prefix);
  137. Listener.Prefixes.Add(prefix);
  138. }
  139. IsStarted = true;
  140. _logger.Info("Starting HttpListner");
  141. Listener.Start();
  142. _logger.Info("HttpListener started");
  143. ThreadPool.QueueUserWorkItem(listenCallback);
  144. }
  145. private bool IsListening
  146. {
  147. get { return this.IsStarted && this.Listener != null && this.Listener.IsListening; }
  148. }
  149. // Loop here to begin processing of new requests.
  150. private void Listen(object state)
  151. {
  152. while (IsListening)
  153. {
  154. if (Listener == null) return;
  155. try
  156. {
  157. Listener.BeginGetContext(ListenerCallback, Listener);
  158. _listenForNextRequest.WaitOne();
  159. }
  160. catch (Exception ex)
  161. {
  162. _logger.Error("Listen()", ex);
  163. return;
  164. }
  165. if (Listener == null) return;
  166. }
  167. }
  168. // Handle the processing of a request in here.
  169. private void ListenerCallback(IAsyncResult asyncResult)
  170. {
  171. var listener = asyncResult.AsyncState as HttpListener;
  172. HttpListenerContext context;
  173. if (listener == null) return;
  174. var isListening = listener.IsListening;
  175. try
  176. {
  177. if (!isListening)
  178. {
  179. _logger.Debug("Ignoring ListenerCallback() as HttpListener is no longer listening"); return;
  180. }
  181. // The EndGetContext() method, as with all Begin/End asynchronous methods in the .NET Framework,
  182. // blocks until there is a request to be processed or some type of data is available.
  183. context = listener.EndGetContext(asyncResult);
  184. }
  185. catch (Exception ex)
  186. {
  187. // You will get an exception when httpListener.Stop() is called
  188. // because there will be a thread stopped waiting on the .EndGetContext()
  189. // method, and again, that is just the way most Begin/End asynchronous
  190. // methods of the .NET Framework work.
  191. var errMsg = ex + ": " + IsListening;
  192. _logger.Warn(errMsg);
  193. return;
  194. }
  195. finally
  196. {
  197. // Once we know we have a request (or exception), we signal the other thread
  198. // so that it calls the BeginGetContext() (or possibly exits if we're not
  199. // listening any more) method to start handling the next incoming request
  200. // while we continue to process this request on a different thread.
  201. _listenForNextRequest.Set();
  202. }
  203. _threadPoolManager.QueueWorkItem(() => InitTask(context));
  204. }
  205. public virtual void InitTask(HttpListenerContext context)
  206. {
  207. try
  208. {
  209. var task = this.ProcessRequestAsync(context);
  210. task.ContinueWith(x => HandleError(x.Exception, context), TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.AttachedToParent);
  211. if (task.Status == TaskStatus.Created)
  212. {
  213. task.RunSynchronously();
  214. }
  215. }
  216. catch (Exception ex)
  217. {
  218. HandleError(ex, context);
  219. }
  220. }
  221. /// <summary>
  222. /// Logs the HTTP request.
  223. /// </summary>
  224. /// <param name="request">The request.</param>
  225. private void LogHttpRequest(HttpListenerRequest request)
  226. {
  227. var endpoint = request.LocalEndPoint;
  228. if (endpoint != null)
  229. {
  230. var address = endpoint.ToString();
  231. _localEndPoints.GetOrAdd(address, address);
  232. }
  233. if (EnableHttpRequestLogging)
  234. {
  235. LoggerUtils.LogRequest(_logger, request);
  236. }
  237. }
  238. /// <summary>
  239. /// Processes the web socket request.
  240. /// </summary>
  241. /// <param name="ctx">The CTX.</param>
  242. /// <returns>Task.</returns>
  243. private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
  244. {
  245. #if !__MonoCS__
  246. try
  247. {
  248. var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
  249. if (WebSocketConnected != null)
  250. {
  251. WebSocketConnected(this, new WebSocketConnectEventArgs { WebSocket = new NativeWebSocket(webSocketContext.WebSocket, _logger), Endpoint = ctx.Request.RemoteEndPoint.ToString() });
  252. }
  253. }
  254. catch (Exception ex)
  255. {
  256. _logger.ErrorException("AcceptWebSocketAsync error", ex);
  257. ctx.Response.StatusCode = 500;
  258. ctx.Response.Close();
  259. }
  260. #endif
  261. }
  262. private void HandleError(Exception ex, HttpListenerContext context)
  263. {
  264. try
  265. {
  266. var operationName = context.Request.GetOperationName();
  267. var httpReq = GetRequest(context, operationName);
  268. var httpRes = httpReq.Response;
  269. if (httpRes.IsClosed)
  270. {
  271. return;
  272. }
  273. var errorResponse = new ErrorResponse
  274. {
  275. ResponseStatus = new ResponseStatus
  276. {
  277. ErrorCode = ex.GetType().GetOperationName(),
  278. Message = ex.Message,
  279. StackTrace = ex.StackTrace,
  280. }
  281. };
  282. var contentType = httpReq.ResponseContentType;
  283. var serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  284. if (serializer == null)
  285. {
  286. contentType = HostContext.Config.DefaultContentType;
  287. serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  288. }
  289. var httpError = ex as IHttpError;
  290. if (httpError != null)
  291. {
  292. httpRes.StatusCode = httpError.Status;
  293. httpRes.StatusDescription = httpError.StatusDescription;
  294. }
  295. else
  296. {
  297. httpRes.StatusCode = 500;
  298. }
  299. httpRes.ContentType = contentType;
  300. serializer(httpReq, errorResponse, httpRes);
  301. httpRes.Close();
  302. }
  303. catch (Exception errorEx)
  304. {
  305. _logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  306. }
  307. }
  308. private static ListenerRequest GetRequest(HttpListenerContext httpContext, string operationName)
  309. {
  310. var req = new ListenerRequest(httpContext, operationName, RequestAttributes.None);
  311. req.RequestAttributes = req.GetAttributes();
  312. return req;
  313. }
  314. /// <summary>
  315. /// Shut down the Web Service
  316. /// </summary>
  317. public void Stop()
  318. {
  319. if (Listener != null)
  320. {
  321. foreach (var prefix in UrlPrefixes)
  322. {
  323. Listener.Prefixes.Remove(prefix);
  324. }
  325. Listener.Close();
  326. }
  327. }
  328. /// <summary>
  329. /// Overridable method that can be used to implement a custom hnandler
  330. /// </summary>
  331. /// <param name="context"></param>
  332. protected Task ProcessRequestAsync(HttpListenerContext context)
  333. {
  334. var request = context.Request;
  335. LogHttpRequest(request);
  336. if (request.IsWebSocketRequest)
  337. {
  338. return ProcessWebSocketRequest(context);
  339. }
  340. var localPath = request.Url.LocalPath;
  341. if (string.Equals(localPath, "/" + HandlerPath + "/", StringComparison.OrdinalIgnoreCase))
  342. {
  343. context.Response.Redirect(DefaultRedirectPath);
  344. context.Response.Close();
  345. return Task.FromResult(true);
  346. }
  347. if (string.Equals(localPath, "/" + HandlerPath, StringComparison.OrdinalIgnoreCase))
  348. {
  349. context.Response.Redirect(HandlerPath + "/" + DefaultRedirectPath);
  350. context.Response.Close();
  351. return Task.FromResult(true);
  352. }
  353. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  354. {
  355. context.Response.Redirect(HandlerPath + "/" + DefaultRedirectPath);
  356. context.Response.Close();
  357. return Task.FromResult(true);
  358. }
  359. if (string.IsNullOrEmpty(localPath))
  360. {
  361. context.Response.Redirect("/" + HandlerPath + "/" + DefaultRedirectPath);
  362. context.Response.Close();
  363. return Task.FromResult(true);
  364. }
  365. var date = DateTime.Now;
  366. if (string.IsNullOrEmpty(context.Request.RawUrl))
  367. return ((object)null).AsTaskResult();
  368. var operationName = context.Request.GetOperationName();
  369. var httpReq = GetRequest(context, operationName);
  370. var httpRes = httpReq.Response;
  371. var handler = HttpHandlerFactory.GetHandler(httpReq);
  372. var url = request.Url.ToString();
  373. var remoteIp = httpReq.RemoteIp;
  374. var serviceStackHandler = handler as IServiceStackHandler;
  375. if (serviceStackHandler != null)
  376. {
  377. var restHandler = serviceStackHandler as RestHandler;
  378. if (restHandler != null)
  379. {
  380. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
  381. }
  382. var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
  383. task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  384. //Matches Exceptions handled in HttpListenerBase.InitTask()
  385. var statusCode = httpRes.StatusCode;
  386. task.ContinueWith(x =>
  387. {
  388. var duration = DateTime.Now - date;
  389. if (EnableHttpRequestLogging)
  390. {
  391. LoggerUtils.LogResponse(_logger, statusCode, url, remoteIp, duration);
  392. }
  393. }, TaskContinuationOptions.None);
  394. return task;
  395. }
  396. return new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
  397. .AsTaskException();
  398. }
  399. /// <summary>
  400. /// Gets or sets a value indicating whether [enable HTTP request logging].
  401. /// </summary>
  402. /// <value><c>true</c> if [enable HTTP request logging]; otherwise, <c>false</c>.</value>
  403. public bool EnableHttpRequestLogging { get; set; }
  404. /// <summary>
  405. /// Adds the rest handlers.
  406. /// </summary>
  407. /// <param name="services">The services.</param>
  408. public void Init(IEnumerable<IRestfulService> services)
  409. {
  410. _restServices.AddRange(services);
  411. ServiceController = CreateServiceController();
  412. _logger.Info("Calling ServiceStack AppHost.Init");
  413. base.Init();
  414. }
  415. //public override RouteAttribute[] GetRouteAttributes(System.Type requestType)
  416. //{
  417. // var routes = base.GetRouteAttributes(requestType);
  418. // routes.Each(x => x.Path = "/api" + x.Path);
  419. // return routes;
  420. //}
  421. /// <summary>
  422. /// Releases the specified instance.
  423. /// </summary>
  424. /// <param name="instance">The instance.</param>
  425. public override void Release(object instance)
  426. {
  427. // Leave this empty so SS doesn't try to dispose our objects
  428. }
  429. private bool _disposed;
  430. private readonly object _disposeLock = new object();
  431. protected virtual void Dispose(bool disposing)
  432. {
  433. if (_disposed) return;
  434. base.Dispose();
  435. lock (_disposeLock)
  436. {
  437. if (_disposed) return;
  438. if (disposing)
  439. {
  440. _threadPoolManager.Dispose();
  441. Stop();
  442. }
  443. //release unmanaged resources here...
  444. _disposed = true;
  445. }
  446. }
  447. public override void Dispose()
  448. {
  449. Dispose(true);
  450. GC.SuppressFinalize(this);
  451. }
  452. public void StartServer(IEnumerable<string> urlPrefixes)
  453. {
  454. UrlPrefixes = urlPrefixes.ToList();
  455. Start(UrlPrefixes.First());
  456. }
  457. public bool SupportsWebSockets
  458. {
  459. get { return NativeWebSocket.IsSupported; }
  460. }
  461. }
  462. }