HttpServer.cs 22 KB

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