HttpListenerHost.cs 19 KB

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