HttpListenerHost.cs 19 KB

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