HttpServer.cs 21 KB

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