HttpServer.cs 22 KB

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