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.Host;
  9. using ServiceStack.Host.Handlers;
  10. using ServiceStack.Host.HttpListener;
  11. using ServiceStack.Logging;
  12. using ServiceStack.Web;
  13. using System;
  14. using System.Collections.Concurrent;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Net;
  19. using System.Reflection;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. namespace MediaBrowser.Server.Implementations.HttpServer
  23. {
  24. public delegate void DelReceiveWebRequest(HttpListenerContext context);
  25. public class HttpListenerHost : ServiceStackHost, IHttpServer
  26. {
  27. private string ServerName { get; set; }
  28. private string HandlerPath { get; set; }
  29. private string DefaultRedirectPath { get; set; }
  30. private readonly ILogger _logger;
  31. public string UrlPrefix { 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 List<AutoResetEvent> _autoResetEvents = new List<AutoResetEvent>();
  36. private readonly ContainerAdapter _containerAdapter;
  37. private readonly ConcurrentDictionary<string, string> _localEndPoints = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  38. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  39. /// <summary>
  40. /// Gets the local end points.
  41. /// </summary>
  42. /// <value>The local end points.</value>
  43. public IEnumerable<string> LocalEndPoints
  44. {
  45. get { return _localEndPoints.Keys.ToList(); }
  46. }
  47. public HttpListenerHost(IApplicationHost applicationHost, ILogManager logManager, string serviceName, string handlerPath, string defaultRedirectPath, params Assembly[] assembliesWithServices)
  48. : base(serviceName, assembliesWithServices)
  49. {
  50. DefaultRedirectPath = defaultRedirectPath;
  51. ServerName = serviceName;
  52. HandlerPath = handlerPath;
  53. _logger = logManager.GetLogger("HttpServer");
  54. _containerAdapter = new ContainerAdapter(applicationHost);
  55. for (var i = 0; i < 2; 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());
  78. HostContext.GlobalResponseFilters.Add(new ResponseFilter(_logger).FilterResponse);
  79. }
  80. public override void OnAfterInit()
  81. {
  82. SetAppDomainData();
  83. base.OnAfterInit();
  84. }
  85. public override void OnConfigLoad()
  86. {
  87. base.OnConfigLoad();
  88. Config.HandlerFactoryPath = string.IsNullOrEmpty(HandlerPath)
  89. ? null
  90. : HandlerPath;
  91. Config.MetadataRedirectPath = string.IsNullOrEmpty(HandlerPath)
  92. ? "metadata"
  93. : PathUtils.CombinePaths(HandlerPath, "metadata");
  94. }
  95. protected override ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
  96. {
  97. var types = _restServices.Select(r => r.GetType()).ToArray();
  98. return new ServiceController(this, () => types);
  99. }
  100. public virtual void SetAppDomainData()
  101. {
  102. //Required for Mono to resolve VirtualPathUtility and Url.Content urls
  103. var domain = Thread.GetDomain(); // or AppDomain.Current
  104. domain.SetData(".appDomain", "1");
  105. domain.SetData(".appVPath", "/");
  106. domain.SetData(".appPath", domain.BaseDirectory);
  107. if (string.IsNullOrEmpty(domain.GetData(".appId") as string))
  108. {
  109. domain.SetData(".appId", "1");
  110. }
  111. if (string.IsNullOrEmpty(domain.GetData(".domainId") as string))
  112. {
  113. domain.SetData(".domainId", "1");
  114. }
  115. }
  116. public override ServiceStackHost Start(string listeningAtUrlBase)
  117. {
  118. StartListener(listeningAtUrlBase);
  119. return this;
  120. }
  121. /// <summary>
  122. /// Starts the Web Service
  123. /// </summary>
  124. /// <param name="listeningAtUrlBase">
  125. /// A Uri that acts as the base that the server is listening on.
  126. /// Format should be: http://127.0.0.1:8080/ or http://127.0.0.1:8080/somevirtual/
  127. /// Note: the trailing slash is required! For more info see the
  128. /// HttpListener.Prefixes property on MSDN.
  129. /// </param>
  130. protected void StartListener(string listeningAtUrlBase)
  131. {
  132. // *** Already running - just leave it in place
  133. if (IsStarted)
  134. return;
  135. if (Listener == null)
  136. Listener = new HttpListener();
  137. HostContext.Config.HandlerFactoryPath = ListenerRequest.GetHandlerPathIfAny(listeningAtUrlBase);
  138. UrlPrefix = listeningAtUrlBase;
  139. Listener.Prefixes.Add(listeningAtUrlBase);
  140. _logger.Info("Adding HttpListener Prefixes");
  141. Listener.Prefixes.Add(listeningAtUrlBase);
  142. IsStarted = true;
  143. _logger.Info("Starting HttpListner");
  144. Listener.Start();
  145. for (var i = 0; i < _autoResetEvents.Count; i++)
  146. {
  147. var index = i;
  148. ThreadPool.QueueUserWorkItem(o => Listen(o, index));
  149. }
  150. }
  151. private bool IsListening
  152. {
  153. get { return this.IsStarted && this.Listener != null && this.Listener.IsListening; }
  154. }
  155. // Loop here to begin processing of new requests.
  156. private void Listen(object state, int index)
  157. {
  158. while (IsListening)
  159. {
  160. if (Listener == null) return;
  161. try
  162. {
  163. Listener.BeginGetContext(c => ListenerCallback(c, index), Listener);
  164. _autoResetEvents[index].WaitOne();
  165. }
  166. catch (Exception ex)
  167. {
  168. _logger.Error("Listen()", ex);
  169. return;
  170. }
  171. if (Listener == null) return;
  172. }
  173. }
  174. // Handle the processing of a request in here.
  175. private void ListenerCallback(IAsyncResult asyncResult, int index)
  176. {
  177. var listener = asyncResult.AsyncState as HttpListener;
  178. HttpListenerContext context = null;
  179. if (listener == null) return;
  180. try
  181. {
  182. if (!IsListening)
  183. {
  184. _logger.Debug("Ignoring ListenerCallback() as HttpListener is no longer listening");
  185. return;
  186. }
  187. // The EndGetContext() method, as with all Begin/End asynchronous methods in the .NET Framework,
  188. // blocks until there is a request to be processed or some type of data is available.
  189. context = listener.EndGetContext(asyncResult);
  190. }
  191. catch (Exception ex)
  192. {
  193. // You will get an exception when httpListener.Stop() is called
  194. // because there will be a thread stopped waiting on the .EndGetContext()
  195. // method, and again, that is just the way most Begin/End asynchronous
  196. // methods of the .NET Framework work.
  197. var errMsg = ex + ": " + IsListening;
  198. _logger.Warn(errMsg);
  199. return;
  200. }
  201. finally
  202. {
  203. // Once we know we have a request (or exception), we signal the other thread
  204. // so that it calls the BeginGetContext() (or possibly exits if we're not
  205. // listening any more) method to start handling the next incoming request
  206. // while we continue to process this request on a different thread.
  207. _autoResetEvents[index].Set();
  208. }
  209. if (context == null) return;
  210. var date = DateTime.Now;
  211. Task.Factory.StartNew(async () =>
  212. {
  213. try
  214. {
  215. LogHttpRequest(context, index);
  216. if (context.Request.IsWebSocketRequest)
  217. {
  218. ProcessWebSocketRequest(context);
  219. return;
  220. }
  221. var localPath = context.Request.Url.LocalPath;
  222. if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
  223. {
  224. context.Response.Redirect(DefaultRedirectPath);
  225. context.Response.Close();
  226. return;
  227. }
  228. if (string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
  229. {
  230. context.Response.Redirect("mediabrowser/" + DefaultRedirectPath);
  231. context.Response.Close();
  232. return;
  233. }
  234. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  235. {
  236. context.Response.Redirect("mediabrowser/" + DefaultRedirectPath);
  237. context.Response.Close();
  238. return;
  239. }
  240. if (string.IsNullOrEmpty(localPath))
  241. {
  242. context.Response.Redirect("/mediabrowser/" + DefaultRedirectPath);
  243. context.Response.Close();
  244. return;
  245. }
  246. var url = context.Request.Url.ToString();
  247. var endPoint = context.Request.RemoteEndPoint;
  248. await ProcessRequestAsync(context).ConfigureAwait(false);
  249. var duration = DateTime.Now - date;
  250. if (EnableHttpRequestLogging)
  251. {
  252. LoggerUtils.LogResponse(_logger, context, url, endPoint, duration);
  253. }
  254. }
  255. catch (Exception ex)
  256. {
  257. _logger.ErrorException("ProcessRequest failure", ex);
  258. HandleError(ex, context, _logger);
  259. }
  260. });
  261. }
  262. /// <summary>
  263. /// Logs the HTTP request.
  264. /// </summary>
  265. /// <param name="ctx">The CTX.</param>
  266. private void LogHttpRequest(HttpListenerContext ctx, int index)
  267. {
  268. var endpoint = ctx.Request.LocalEndPoint;
  269. if (endpoint != null)
  270. {
  271. var address = endpoint.ToString();
  272. _localEndPoints.GetOrAdd(address, address);
  273. }
  274. if (EnableHttpRequestLogging)
  275. {
  276. LoggerUtils.LogRequest(_logger, ctx, index);
  277. }
  278. }
  279. /// <summary>
  280. /// Processes the web socket request.
  281. /// </summary>
  282. /// <param name="ctx">The CTX.</param>
  283. /// <returns>Task.</returns>
  284. private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
  285. {
  286. #if !__MonoCS__
  287. try
  288. {
  289. var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
  290. if (WebSocketConnected != null)
  291. {
  292. WebSocketConnected(this, new WebSocketConnectEventArgs { WebSocket = new NativeWebSocket(webSocketContext.WebSocket, _logger), Endpoint = ctx.Request.RemoteEndPoint.ToString() });
  293. }
  294. }
  295. catch (Exception ex)
  296. {
  297. _logger.ErrorException("AcceptWebSocketAsync error", ex);
  298. ctx.Response.StatusCode = 500;
  299. ctx.Response.Close();
  300. }
  301. #endif
  302. }
  303. public static void HandleError(Exception ex, HttpListenerContext context, ILogger logger)
  304. {
  305. try
  306. {
  307. var errorResponse = new ErrorResponse
  308. {
  309. ResponseStatus = new ResponseStatus
  310. {
  311. ErrorCode = ex.GetType().GetOperationName(),
  312. Message = ex.Message,
  313. StackTrace = ex.StackTrace,
  314. }
  315. };
  316. var operationName = context.Request.GetOperationName();
  317. var httpReq = context.ToRequest(operationName);
  318. var httpRes = httpReq.Response;
  319. var contentType = httpReq.ResponseContentType;
  320. var serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  321. if (serializer == null)
  322. {
  323. contentType = HostContext.Config.DefaultContentType;
  324. serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  325. }
  326. var httpError = ex as IHttpError;
  327. if (httpError != null)
  328. {
  329. httpRes.StatusCode = httpError.Status;
  330. httpRes.StatusDescription = httpError.StatusDescription;
  331. }
  332. else
  333. {
  334. httpRes.StatusCode = 500;
  335. }
  336. httpRes.ContentType = contentType;
  337. serializer(httpReq, errorResponse, httpRes);
  338. httpRes.Close();
  339. }
  340. catch (Exception errorEx)
  341. {
  342. logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  343. }
  344. }
  345. /// <summary>
  346. /// Shut down the Web Service
  347. /// </summary>
  348. public void Stop()
  349. {
  350. if (Listener != null)
  351. {
  352. Listener.Prefixes.Remove(UrlPrefix);
  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(string urlPrefix)
  430. {
  431. Start(urlPrefix);
  432. }
  433. public bool SupportsWebSockets
  434. {
  435. get { return NativeWebSocket.IsSupported; }
  436. }
  437. }
  438. }