2
0

HttpListenerHost.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. using System.Net.Sockets;
  2. using System.Runtime.Serialization;
  3. using Funq;
  4. using MediaBrowser.Common;
  5. using MediaBrowser.Common.Extensions;
  6. using MediaBrowser.Common.Net;
  7. using MediaBrowser.Controller.Net;
  8. using MediaBrowser.Model.Logging;
  9. using ServiceStack;
  10. using ServiceStack.Api.Swagger;
  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 ServerName { get; set; }
  30. private string HandlerPath { get; set; }
  31. private string DefaultRedirectPath { get; set; }
  32. private readonly ILogger _logger;
  33. public IEnumerable<string> UrlPrefixes { get; private set; }
  34. private readonly List<IRestfulService> _restServices = new List<IRestfulService>();
  35. private HttpListener Listener { get; set; }
  36. protected bool IsStarted = false;
  37. private readonly List<AutoResetEvent> _autoResetEvents = new List<AutoResetEvent>();
  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. ServerName = serviceName;
  54. HandlerPath = handlerPath;
  55. _logger = logManager.GetLogger("HttpServer");
  56. _containerAdapter = new ContainerAdapter(applicationHost);
  57. for (var i = 0; i < 1; i++)
  58. {
  59. _autoResetEvents.Add(new AutoResetEvent(false));
  60. }
  61. }
  62. public override void Configure(Container container)
  63. {
  64. HostConfig.Instance.DefaultRedirectPath = DefaultRedirectPath;
  65. HostConfig.Instance.MapExceptionToStatusCode = new Dictionary<Type, int>
  66. {
  67. {typeof (InvalidOperationException), 422},
  68. {typeof (ResourceNotFoundException), 404},
  69. {typeof (FileNotFoundException), 404},
  70. {typeof (DirectoryNotFoundException), 404}
  71. };
  72. HostConfig.Instance.DebugMode = true;
  73. HostConfig.Instance.LogFactory = LogManager.LogFactory;
  74. // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
  75. // Custom format allows images
  76. HostConfig.Instance.EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat;
  77. container.Adapter = _containerAdapter;
  78. Plugins.Add(new SwaggerFeature());
  79. Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization"));
  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();
  121. return this;
  122. }
  123. /// <summary>
  124. /// Starts the Web Service
  125. /// </summary>
  126. private void StartListener()
  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. for (var i = 0; i < _autoResetEvents.Count; i++)
  143. {
  144. var index = i;
  145. ThreadPool.QueueUserWorkItem(o => Listen(o, index));
  146. }
  147. }
  148. private bool IsListening
  149. {
  150. get { return this.IsStarted && this.Listener != null && this.Listener.IsListening; }
  151. }
  152. // Loop here to begin processing of new requests.
  153. private void Listen(object state, int index)
  154. {
  155. while (IsListening)
  156. {
  157. if (Listener == null) return;
  158. try
  159. {
  160. Listener.BeginGetContext(c => ListenerCallback(c, index), Listener);
  161. _autoResetEvents[index].WaitOne();
  162. }
  163. catch (Exception ex)
  164. {
  165. _logger.Error("Listen()", ex);
  166. return;
  167. }
  168. if (Listener == null) return;
  169. }
  170. }
  171. // Handle the processing of a request in here.
  172. private void ListenerCallback(IAsyncResult asyncResult, int index)
  173. {
  174. var listener = asyncResult.AsyncState as HttpListener;
  175. HttpListenerContext context = null;
  176. if (listener == null) return;
  177. try
  178. {
  179. if (!IsListening)
  180. {
  181. _logger.Debug("Ignoring ListenerCallback() as HttpListener is no longer listening");
  182. return;
  183. }
  184. // The EndGetContext() method, as with all Begin/End asynchronous methods in the .NET Framework,
  185. // blocks until there is a request to be processed or some type of data is available.
  186. context = listener.EndGetContext(asyncResult);
  187. }
  188. catch (Exception ex)
  189. {
  190. // You will get an exception when httpListener.Stop() is called
  191. // because there will be a thread stopped waiting on the .EndGetContext()
  192. // method, and again, that is just the way most Begin/End asynchronous
  193. // methods of the .NET Framework work.
  194. var errMsg = ex + ": " + IsListening;
  195. _logger.Warn(errMsg);
  196. return;
  197. }
  198. finally
  199. {
  200. // Once we know we have a request (or exception), we signal the other thread
  201. // so that it calls the BeginGetContext() (or possibly exits if we're not
  202. // listening any more) method to start handling the next incoming request
  203. // while we continue to process this request on a different thread.
  204. _autoResetEvents[index].Set();
  205. }
  206. var date = DateTime.Now;
  207. Task.Factory.StartNew(async () =>
  208. {
  209. try
  210. {
  211. var request = context.Request;
  212. LogHttpRequest(request, index);
  213. if (request.IsWebSocketRequest)
  214. {
  215. await ProcessWebSocketRequest(context).ConfigureAwait(false);
  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.Response, 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="request">The request.</param>
  263. /// <param name="index">The index.</param>
  264. private void LogHttpRequest(HttpListenerRequest request, int index)
  265. {
  266. var endpoint = request.LocalEndPoint;
  267. if (endpoint != null)
  268. {
  269. var address = endpoint.ToString();
  270. _localEndPoints.GetOrAdd(address, address);
  271. }
  272. if (EnableHttpRequestLogging)
  273. {
  274. LoggerUtils.LogRequest(_logger, request, index);
  275. }
  276. }
  277. /// <summary>
  278. /// Processes the web socket request.
  279. /// </summary>
  280. /// <param name="ctx">The CTX.</param>
  281. /// <returns>Task.</returns>
  282. private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
  283. {
  284. #if !__MonoCS__
  285. try
  286. {
  287. var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
  288. if (WebSocketConnected != null)
  289. {
  290. WebSocketConnected(this, new WebSocketConnectEventArgs { WebSocket = new NativeWebSocket(webSocketContext.WebSocket, _logger), Endpoint = ctx.Request.RemoteEndPoint.ToString() });
  291. }
  292. }
  293. catch (Exception ex)
  294. {
  295. _logger.ErrorException("AcceptWebSocketAsync error", ex);
  296. ctx.Response.StatusCode = 500;
  297. ctx.Response.Close();
  298. }
  299. #endif
  300. }
  301. public static void HandleError(Exception ex, HttpListenerContext context, ILogger logger)
  302. {
  303. try
  304. {
  305. var errorResponse = new ErrorResponse
  306. {
  307. ResponseStatus = new ResponseStatus
  308. {
  309. ErrorCode = ex.GetType().GetOperationName(),
  310. Message = ex.Message,
  311. StackTrace = ex.StackTrace,
  312. }
  313. };
  314. var operationName = context.Request.GetOperationName();
  315. var httpReq = GetRequest(context, operationName);
  316. var httpRes = httpReq.Response;
  317. var contentType = httpReq.ResponseContentType;
  318. var serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  319. if (serializer == null)
  320. {
  321. contentType = HostContext.Config.DefaultContentType;
  322. serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  323. }
  324. var httpError = ex as IHttpError;
  325. if (httpError != null)
  326. {
  327. httpRes.StatusCode = httpError.Status;
  328. httpRes.StatusDescription = httpError.StatusDescription;
  329. }
  330. else
  331. {
  332. httpRes.StatusCode = 500;
  333. }
  334. httpRes.ContentType = contentType;
  335. serializer(httpReq, errorResponse, httpRes);
  336. httpRes.Close();
  337. }
  338. catch (Exception errorEx)
  339. {
  340. logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  341. }
  342. }
  343. private static ListenerRequest GetRequest(HttpListenerContext httpContext, string operationName)
  344. {
  345. var req = new ListenerRequest(httpContext, operationName, RequestAttributes.None);
  346. req.RequestAttributes = req.GetAttributes();
  347. return req;
  348. }
  349. /// <summary>
  350. /// Shut down the Web Service
  351. /// </summary>
  352. public void Stop()
  353. {
  354. if (Listener != null)
  355. {
  356. foreach (var prefix in UrlPrefixes)
  357. {
  358. Listener.Prefixes.Remove(prefix);
  359. }
  360. Listener.Close();
  361. }
  362. }
  363. /// <summary>
  364. /// Overridable method that can be used to implement a custom hnandler
  365. /// </summary>
  366. /// <param name="context"></param>
  367. protected Task ProcessRequestAsync(HttpListenerContext context)
  368. {
  369. if (string.IsNullOrEmpty(context.Request.RawUrl))
  370. return ((object)null).AsTaskResult();
  371. var operationName = context.Request.GetOperationName();
  372. var httpReq = GetRequest(context, operationName);
  373. var httpRes = httpReq.Response;
  374. var handler = HttpHandlerFactory.GetHandler(httpReq);
  375. var serviceStackHandler = handler as IServiceStackHandler;
  376. if (serviceStackHandler != null)
  377. {
  378. var restHandler = serviceStackHandler as RestHandler;
  379. if (restHandler != null)
  380. {
  381. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
  382. }
  383. var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
  384. task.ContinueWith(x => httpRes.Close());
  385. return task;
  386. }
  387. return new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
  388. .AsTaskException();
  389. }
  390. /// <summary>
  391. /// Gets or sets a value indicating whether [enable HTTP request logging].
  392. /// </summary>
  393. /// <value><c>true</c> if [enable HTTP request logging]; otherwise, <c>false</c>.</value>
  394. public bool EnableHttpRequestLogging { get; set; }
  395. /// <summary>
  396. /// Adds the rest handlers.
  397. /// </summary>
  398. /// <param name="services">The services.</param>
  399. public void Init(IEnumerable<IRestfulService> services)
  400. {
  401. _restServices.AddRange(services);
  402. ServiceController = CreateServiceController();
  403. _logger.Info("Calling ServiceStack AppHost.Init");
  404. base.Init();
  405. }
  406. /// <summary>
  407. /// Releases the specified instance.
  408. /// </summary>
  409. /// <param name="instance">The instance.</param>
  410. public override void Release(object instance)
  411. {
  412. // Leave this empty so SS doesn't try to dispose our objects
  413. }
  414. private bool _disposed;
  415. private readonly object _disposeLock = new object();
  416. protected virtual void Dispose(bool disposing)
  417. {
  418. if (_disposed) return;
  419. base.Dispose();
  420. lock (_disposeLock)
  421. {
  422. if (_disposed) return;
  423. if (disposing)
  424. {
  425. Stop();
  426. }
  427. //release unmanaged resources here...
  428. _disposed = true;
  429. }
  430. }
  431. public override void Dispose()
  432. {
  433. Dispose(true);
  434. GC.SuppressFinalize(this);
  435. }
  436. public void StartServer(IEnumerable<string> urlPrefixes)
  437. {
  438. UrlPrefixes = urlPrefixes.ToList();
  439. Start(UrlPrefixes.First());
  440. }
  441. public bool SupportsWebSockets
  442. {
  443. get { return NativeWebSocket.IsSupported; }
  444. }
  445. }
  446. }