HttpServer.cs 21 KB

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