HttpServer.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. using System.IO;
  2. using Funq;
  3. using MediaBrowser.Common;
  4. using MediaBrowser.Common.Extensions;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Model.Logging;
  7. using ServiceStack.Api.Swagger;
  8. using ServiceStack.Common.Web;
  9. using ServiceStack.Configuration;
  10. using ServiceStack.Logging;
  11. using ServiceStack.ServiceHost;
  12. using ServiceStack.ServiceInterface.Cors;
  13. using ServiceStack.Text;
  14. using ServiceStack.WebHost.Endpoints;
  15. using ServiceStack.WebHost.Endpoints.Extensions;
  16. using ServiceStack.WebHost.Endpoints.Support;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Globalization;
  20. using System.Linq;
  21. using System.Net;
  22. using System.Net.WebSockets;
  23. using System.Reactive.Linq;
  24. using System.Reflection;
  25. using System.Text;
  26. using System.Threading.Tasks;
  27. namespace MediaBrowser.Server.Implementations.HttpServer
  28. {
  29. /// <summary>
  30. /// Class HttpServer
  31. /// </summary>
  32. public class HttpServer : HttpListenerBase, IHttpServer
  33. {
  34. /// <summary>
  35. /// The logger
  36. /// </summary>
  37. private readonly ILogger _logger;
  38. /// <summary>
  39. /// Gets the URL prefix.
  40. /// </summary>
  41. /// <value>The URL prefix.</value>
  42. public string UrlPrefix { get; private set; }
  43. /// <summary>
  44. /// The _rest services
  45. /// </summary>
  46. private readonly List<IRestfulService> _restServices = new List<IRestfulService>();
  47. /// <summary>
  48. /// This subscribes to HttpListener requests and finds the appropriate BaseHandler to process it
  49. /// </summary>
  50. /// <value>The HTTP listener.</value>
  51. private IDisposable HttpListener { get; set; }
  52. /// <summary>
  53. /// Occurs when [web socket connected].
  54. /// </summary>
  55. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  56. /// <summary>
  57. /// Gets the default redirect path.
  58. /// </summary>
  59. /// <value>The default redirect path.</value>
  60. private string DefaultRedirectPath { get; set; }
  61. /// <summary>
  62. /// Gets or sets the name of the server.
  63. /// </summary>
  64. /// <value>The name of the server.</value>
  65. private string ServerName { get; set; }
  66. /// <summary>
  67. /// The _container adapter
  68. /// </summary>
  69. private readonly ContainerAdapter _containerAdapter;
  70. /// <summary>
  71. /// Initializes a new instance of the <see cref="HttpServer" /> class.
  72. /// </summary>
  73. /// <param name="applicationHost">The application host.</param>
  74. /// <param name="logManager">The log manager.</param>
  75. /// <param name="serverName">Name of the server.</param>
  76. /// <param name="defaultRedirectpath">The default redirectpath.</param>
  77. /// <exception cref="System.ArgumentNullException">urlPrefix</exception>
  78. public HttpServer(IApplicationHost applicationHost, ILogManager logManager, string serverName, string defaultRedirectpath)
  79. : base()
  80. {
  81. if (logManager == null)
  82. {
  83. throw new ArgumentNullException("logManager");
  84. }
  85. if (applicationHost == null)
  86. {
  87. throw new ArgumentNullException("applicationHost");
  88. }
  89. if (string.IsNullOrEmpty(serverName))
  90. {
  91. throw new ArgumentNullException("serverName");
  92. }
  93. if (string.IsNullOrEmpty(defaultRedirectpath))
  94. {
  95. throw new ArgumentNullException("defaultRedirectpath");
  96. }
  97. ServerName = serverName;
  98. DefaultRedirectPath = defaultRedirectpath;
  99. _logger = logManager.GetLogger("HttpServer");
  100. LogManager.LogFactory = new ServerLogFactory(logManager);
  101. EndpointHostConfig.Instance.ServiceStackHandlerFactoryPath = null;
  102. EndpointHostConfig.Instance.MetadataRedirectPath = "metadata";
  103. _containerAdapter = new ContainerAdapter(applicationHost);
  104. }
  105. /// <summary>
  106. /// The us culture
  107. /// </summary>
  108. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  109. /// <summary>
  110. /// Configures the specified container.
  111. /// </summary>
  112. /// <param name="container">The container.</param>
  113. public override void Configure(Container container)
  114. {
  115. JsConfig.DateHandler = JsonDateHandler.ISO8601;
  116. JsConfig.ExcludeTypeInfo = true;
  117. JsConfig.IncludeNullValues = false;
  118. SetConfig(new EndpointHostConfig
  119. {
  120. DefaultRedirectPath = DefaultRedirectPath,
  121. MapExceptionToStatusCode = {
  122. { typeof(InvalidOperationException), 422 },
  123. { typeof(ResourceNotFoundException), 404 },
  124. { typeof(FileNotFoundException), 404 },
  125. { typeof(DirectoryNotFoundException), 404 }
  126. },
  127. DebugMode = true
  128. });
  129. container.Adapter = _containerAdapter;
  130. Plugins.Add(new SwaggerFeature());
  131. Plugins.Add(new CorsFeature());
  132. ResponseFilters.Add((req, res, dto) =>
  133. {
  134. var exception = dto as Exception;
  135. if (exception != null)
  136. {
  137. _logger.ErrorException("Error processing request for {0}", exception, req.RawUrl);
  138. if (!string.IsNullOrEmpty(exception.Message))
  139. {
  140. var error = exception.Message.Replace(Environment.NewLine, " ");
  141. error = RemoveControlCharacters(error);
  142. res.AddHeader("X-Application-Error-Code", error);
  143. }
  144. }
  145. if (dto is CompressedResult)
  146. {
  147. // Per Google PageSpeed
  148. // This instructs the proxies to cache two versions of the resource: one compressed, and one uncompressed.
  149. // The correct version of the resource is delivered based on the client request header.
  150. // This is a good choice for applications that are singly homed and depend on public proxies for user locality.
  151. res.AddHeader("Vary", "Accept-Encoding");
  152. }
  153. var hasOptions = dto as IHasOptions;
  154. if (hasOptions != null)
  155. {
  156. // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy
  157. string contentLength;
  158. if (hasOptions.Options.TryGetValue("Content-Length", out contentLength) && !string.IsNullOrEmpty(contentLength))
  159. {
  160. var length = long.Parse(contentLength, UsCulture);
  161. if (length > 0)
  162. {
  163. var response = (HttpListenerResponse)res.OriginalResponse;
  164. response.ContentLength64 = length;
  165. // Disable chunked encoding. Technically this is only needed when using Content-Range, but
  166. // anytime we know the content length there's no need for it
  167. response.SendChunked = false;
  168. }
  169. }
  170. }
  171. });
  172. }
  173. /// <summary>
  174. /// Removes the control characters.
  175. /// </summary>
  176. /// <param name="inString">The in string.</param>
  177. /// <returns>System.String.</returns>
  178. private static string RemoveControlCharacters(string inString)
  179. {
  180. if (inString == null) return null;
  181. var newString = new StringBuilder();
  182. foreach (var ch in inString)
  183. {
  184. if (!char.IsControl(ch))
  185. {
  186. newString.Append(ch);
  187. }
  188. }
  189. return newString.ToString();
  190. }
  191. /// <summary>
  192. /// Starts the Web Service
  193. /// </summary>
  194. /// <param name="urlBase">A Uri that acts as the base that the server is listening on.
  195. /// Format should be: http://127.0.0.1:8080/ or http://127.0.0.1:8080/somevirtual/
  196. /// Note: the trailing slash is required! For more info see the
  197. /// HttpListener.Prefixes property on MSDN.</param>
  198. /// <exception cref="System.ArgumentNullException">urlBase</exception>
  199. public override void Start(string urlBase)
  200. {
  201. if (string.IsNullOrEmpty(urlBase))
  202. {
  203. throw new ArgumentNullException("urlBase");
  204. }
  205. // *** Already running - just leave it in place
  206. if (IsStarted)
  207. {
  208. return;
  209. }
  210. if (Listener == null)
  211. {
  212. _logger.Info("Creating HttpListner");
  213. Listener = new HttpListener();
  214. }
  215. EndpointHost.Config.ServiceStackHandlerFactoryPath = HttpListenerRequestWrapper.GetHandlerPathIfAny(urlBase);
  216. UrlPrefix = urlBase;
  217. _logger.Info("Adding HttpListener Prefixes");
  218. Listener.Prefixes.Add(urlBase);
  219. IsStarted = true;
  220. _logger.Info("Starting HttpListner");
  221. Listener.Start();
  222. _logger.Info("Creating HttpListner observable stream");
  223. HttpListener = CreateObservableStream().Subscribe(ProcessHttpRequestAsync);
  224. }
  225. /// <summary>
  226. /// Creates the observable stream.
  227. /// </summary>
  228. /// <returns>IObservable{HttpListenerContext}.</returns>
  229. private IObservable<HttpListenerContext> CreateObservableStream()
  230. {
  231. return Observable.Create<HttpListenerContext>(obs =>
  232. Observable.FromAsync(() => Listener.GetContextAsync())
  233. .Subscribe(obs))
  234. .Repeat()
  235. .Retry()
  236. .Publish()
  237. .RefCount();
  238. }
  239. /// <summary>
  240. /// Processes incoming http requests by routing them to the appropiate handler
  241. /// </summary>
  242. /// <param name="context">The CTX.</param>
  243. private async void ProcessHttpRequestAsync(HttpListenerContext context)
  244. {
  245. LogHttpRequest(context);
  246. if (context.Request.IsWebSocketRequest)
  247. {
  248. await ProcessWebSocketRequest(context).ConfigureAwait(false);
  249. return;
  250. }
  251. RaiseReceiveWebRequest(context);
  252. await Task.Run(() => ProcessRequest(context)).ConfigureAwait(false);
  253. }
  254. /// <summary>
  255. /// Processes the web socket request.
  256. /// </summary>
  257. /// <param name="ctx">The CTX.</param>
  258. /// <returns>Task.</returns>
  259. private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
  260. {
  261. try
  262. {
  263. var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
  264. if (WebSocketConnected != null)
  265. {
  266. WebSocketConnected(this, new WebSocketConnectEventArgs { WebSocket = new NativeWebSocket(webSocketContext.WebSocket, _logger), Endpoint = ctx.Request.RemoteEndPoint.ToString() });
  267. }
  268. }
  269. catch (Exception ex)
  270. {
  271. _logger.ErrorException("AcceptWebSocketAsync error", ex);
  272. ctx.Response.StatusCode = 500;
  273. ctx.Response.Close();
  274. }
  275. }
  276. /// <summary>
  277. /// Logs the HTTP request.
  278. /// </summary>
  279. /// <param name="ctx">The CTX.</param>
  280. private void LogHttpRequest(HttpListenerContext ctx)
  281. {
  282. var log = new StringBuilder();
  283. log.AppendLine("Url: " + ctx.Request.Url);
  284. log.AppendLine("Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));
  285. var type = ctx.Request.IsWebSocketRequest ? "Web Socket" : "HTTP " + ctx.Request.HttpMethod;
  286. if (EnableHttpRequestLogging)
  287. {
  288. _logger.LogMultiline(type + " request received from " + ctx.Request.RemoteEndPoint, LogSeverity.Debug, log);
  289. }
  290. }
  291. /// <summary>
  292. /// Overridable method that can be used to implement a custom hnandler
  293. /// </summary>
  294. /// <param name="context">The context.</param>
  295. /// <exception cref="System.NotImplementedException">Cannot execute handler: + handler + at PathInfo: + httpReq.PathInfo</exception>
  296. protected override void ProcessRequest(HttpListenerContext context)
  297. {
  298. if (string.IsNullOrEmpty(context.Request.RawUrl)) return;
  299. var operationName = context.Request.GetOperationName();
  300. var httpReq = new HttpListenerRequestWrapper(operationName, context.Request);
  301. var httpRes = new HttpListenerResponseWrapper(context.Response);
  302. var handler = ServiceStackHttpHandlerFactory.GetHandler(httpReq);
  303. var url = context.Request.Url.ToString();
  304. var endPoint = context.Request.RemoteEndPoint;
  305. var serviceStackHandler = handler as IServiceStackHttpHandler;
  306. if (serviceStackHandler != null)
  307. {
  308. var restHandler = serviceStackHandler as RestHandler;
  309. if (restHandler != null)
  310. {
  311. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.Name;
  312. }
  313. serviceStackHandler.ProcessRequest(httpReq, httpRes, operationName);
  314. LogResponse(context, url, endPoint);
  315. return;
  316. }
  317. throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
  318. }
  319. /// <summary>
  320. /// Logs the response.
  321. /// </summary>
  322. /// <param name="ctx">The CTX.</param>
  323. /// <param name="url">The URL.</param>
  324. /// <param name="endPoint">The end point.</param>
  325. private void LogResponse(HttpListenerContext ctx, string url, IPEndPoint endPoint)
  326. {
  327. if (!EnableHttpRequestLogging)
  328. {
  329. return;
  330. }
  331. var statusode = ctx.Response.StatusCode;
  332. var log = new StringBuilder();
  333. log.AppendLine(string.Format("Url: {0}", url));
  334. log.AppendLine("Headers: " + string.Join(",", ctx.Response.Headers.AllKeys.Select(k => k + "=" + ctx.Response.Headers[k])));
  335. var msg = "Http Response Sent (" + statusode + ") to " + endPoint;
  336. _logger.LogMultiline(msg, LogSeverity.Debug, log);
  337. }
  338. /// <summary>
  339. /// Creates the service manager.
  340. /// </summary>
  341. /// <param name="assembliesWithServices">The assemblies with services.</param>
  342. /// <returns>ServiceManager.</returns>
  343. protected override ServiceManager CreateServiceManager(params Assembly[] assembliesWithServices)
  344. {
  345. var types = _restServices.Select(r => r.GetType()).ToArray();
  346. return new ServiceManager(new Container(), new ServiceController(() => types));
  347. }
  348. /// <summary>
  349. /// Shut down the Web Service
  350. /// </summary>
  351. public override void Stop()
  352. {
  353. if (HttpListener != null)
  354. {
  355. HttpListener.Dispose();
  356. HttpListener = null;
  357. }
  358. if (Listener != null)
  359. {
  360. Listener.Prefixes.Remove(UrlPrefix);
  361. }
  362. base.Stop();
  363. }
  364. /// <summary>
  365. /// The _supports native web socket
  366. /// </summary>
  367. private bool? _supportsNativeWebSocket;
  368. /// <summary>
  369. /// Gets a value indicating whether [supports web sockets].
  370. /// </summary>
  371. /// <value><c>true</c> if [supports web sockets]; otherwise, <c>false</c>.</value>
  372. public bool SupportsWebSockets
  373. {
  374. get
  375. {
  376. if (!_supportsNativeWebSocket.HasValue)
  377. {
  378. try
  379. {
  380. new ClientWebSocket();
  381. _supportsNativeWebSocket = true;
  382. }
  383. catch (PlatformNotSupportedException)
  384. {
  385. _supportsNativeWebSocket = false;
  386. }
  387. }
  388. return _supportsNativeWebSocket.Value;
  389. }
  390. }
  391. /// <summary>
  392. /// Gets or sets a value indicating whether [enable HTTP request logging].
  393. /// </summary>
  394. /// <value><c>true</c> if [enable HTTP request logging]; otherwise, <c>false</c>.</value>
  395. public bool EnableHttpRequestLogging { get; set; }
  396. /// <summary>
  397. /// Adds the rest handlers.
  398. /// </summary>
  399. /// <param name="services">The services.</param>
  400. public void Init(IEnumerable<IRestfulService> services)
  401. {
  402. _restServices.AddRange(services);
  403. _logger.Info("Calling EndpointHost.ConfigureHost");
  404. EndpointHost.ConfigureHost(this, ServerName, CreateServiceManager());
  405. _logger.Info("Calling ServiceStack AppHost.Init");
  406. Init();
  407. }
  408. }
  409. /// <summary>
  410. /// Class ContainerAdapter
  411. /// </summary>
  412. class ContainerAdapter : IContainerAdapter, IRelease
  413. {
  414. /// <summary>
  415. /// The _app host
  416. /// </summary>
  417. private readonly IApplicationHost _appHost;
  418. /// <summary>
  419. /// Initializes a new instance of the <see cref="ContainerAdapter" /> class.
  420. /// </summary>
  421. /// <param name="appHost">The app host.</param>
  422. public ContainerAdapter(IApplicationHost appHost)
  423. {
  424. _appHost = appHost;
  425. }
  426. /// <summary>
  427. /// Resolves this instance.
  428. /// </summary>
  429. /// <typeparam name="T"></typeparam>
  430. /// <returns>``0.</returns>
  431. public T Resolve<T>()
  432. {
  433. return _appHost.Resolve<T>();
  434. }
  435. /// <summary>
  436. /// Tries the resolve.
  437. /// </summary>
  438. /// <typeparam name="T"></typeparam>
  439. /// <returns>``0.</returns>
  440. public T TryResolve<T>()
  441. {
  442. return _appHost.TryResolve<T>();
  443. }
  444. /// <summary>
  445. /// Releases the specified instance.
  446. /// </summary>
  447. /// <param name="instance">The instance.</param>
  448. public void Release(object instance)
  449. {
  450. // Leave this empty so SS doesn't try to dispose our objects
  451. }
  452. }
  453. }