HttpListenerHost.cs 18 KB

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