HttpServer.cs 21 KB

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