HttpServer.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. }
  305. finally
  306. {
  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. // This could fail, but try to add the stack trace as the body content
  335. try
  336. {
  337. response.StatusCode = statusCode;
  338. response.Headers.Add("Status", statusCode.ToString(new CultureInfo("en-US")));
  339. response.Headers.Remove("Age");
  340. response.Headers.Remove("Expires");
  341. response.Headers.Remove("Cache-Control");
  342. response.Headers.Remove("Etag");
  343. response.Headers.Remove("Last-Modified");
  344. response.ContentType = "text/plain";
  345. if (!string.IsNullOrEmpty(ex.Message))
  346. {
  347. response.AddHeader("X-Application-Error-Code", ex.Message);
  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.ContentType = ContentType.Json;
  358. var sbBytes = sb.ToString().ToUtf8Bytes();
  359. response.OutputStream.Write(sbBytes, 0, sbBytes.Length);
  360. }
  361. catch (Exception errorEx)
  362. {
  363. _logger.ErrorException("Error processing failed request", errorEx);
  364. }
  365. }
  366. /// <summary>
  367. /// Overridable method that can be used to implement a custom hnandler
  368. /// </summary>
  369. /// <param name="context">The context.</param>
  370. /// <exception cref="System.NotImplementedException">Cannot execute handler: + handler + at PathInfo: + httpReq.PathInfo</exception>
  371. protected override void ProcessRequest(HttpListenerContext context)
  372. {
  373. if (string.IsNullOrEmpty(context.Request.RawUrl)) return;
  374. var operationName = context.Request.GetOperationName();
  375. var httpReq = new HttpListenerRequestWrapper(operationName, context.Request);
  376. var httpRes = new HttpListenerResponseWrapper(context.Response);
  377. var handler = ServiceStackHttpHandlerFactory.GetHandler(httpReq);
  378. var url = context.Request.Url.ToString();
  379. var endPoint = context.Request.RemoteEndPoint;
  380. var serviceStackHandler = handler as IServiceStackHttpHandler;
  381. if (serviceStackHandler != null)
  382. {
  383. var restHandler = serviceStackHandler as RestHandler;
  384. if (restHandler != null)
  385. {
  386. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.Name;
  387. }
  388. serviceStackHandler.ProcessRequest(httpReq, httpRes, operationName);
  389. LogResponse(context, url, endPoint);
  390. return;
  391. }
  392. throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
  393. }
  394. /// <summary>
  395. /// Logs the response.
  396. /// </summary>
  397. /// <param name="ctx">The CTX.</param>
  398. /// <param name="url">The URL.</param>
  399. /// <param name="endPoint">The end point.</param>
  400. private void LogResponse(HttpListenerContext ctx, string url, IPEndPoint endPoint)
  401. {
  402. if (!EnableHttpRequestLogging)
  403. {
  404. return;
  405. }
  406. var statusode = ctx.Response.StatusCode;
  407. var log = new StringBuilder();
  408. log.AppendLine(string.Format("Url: {0}", url));
  409. log.AppendLine("Headers: " + string.Join(",", ctx.Response.Headers.AllKeys.Select(k => k + "=" + ctx.Response.Headers[k])));
  410. var msg = "Http Response Sent (" + statusode + ") to " + endPoint;
  411. _logger.LogMultiline(msg, LogSeverity.Debug, log);
  412. }
  413. /// <summary>
  414. /// Creates the service manager.
  415. /// </summary>
  416. /// <param name="assembliesWithServices">The assemblies with services.</param>
  417. /// <returns>ServiceManager.</returns>
  418. protected override ServiceManager CreateServiceManager(params Assembly[] assembliesWithServices)
  419. {
  420. var types = _restServices.Select(r => r.GetType()).ToArray();
  421. return new ServiceManager(new Container(), new ServiceController(() => types));
  422. }
  423. /// <summary>
  424. /// Shut down the Web Service
  425. /// </summary>
  426. public override void Stop()
  427. {
  428. if (HttpListener != null)
  429. {
  430. HttpListener.Dispose();
  431. HttpListener = null;
  432. }
  433. if (Listener != null)
  434. {
  435. Listener.Prefixes.Remove(UrlPrefix);
  436. }
  437. base.Stop();
  438. }
  439. /// <summary>
  440. /// The _supports native web socket
  441. /// </summary>
  442. private bool? _supportsNativeWebSocket;
  443. /// <summary>
  444. /// Gets a value indicating whether [supports web sockets].
  445. /// </summary>
  446. /// <value><c>true</c> if [supports web sockets]; otherwise, <c>false</c>.</value>
  447. public bool SupportsWebSockets
  448. {
  449. get
  450. {
  451. if (!_supportsNativeWebSocket.HasValue)
  452. {
  453. try
  454. {
  455. new ClientWebSocket();
  456. _supportsNativeWebSocket = true;
  457. }
  458. catch (PlatformNotSupportedException)
  459. {
  460. _supportsNativeWebSocket = false;
  461. }
  462. }
  463. return _supportsNativeWebSocket.Value;
  464. }
  465. }
  466. /// <summary>
  467. /// Gets or sets a value indicating whether [enable HTTP request logging].
  468. /// </summary>
  469. /// <value><c>true</c> if [enable HTTP request logging]; otherwise, <c>false</c>.</value>
  470. public bool EnableHttpRequestLogging { get; set; }
  471. /// <summary>
  472. /// Adds the rest handlers.
  473. /// </summary>
  474. /// <param name="services">The services.</param>
  475. public void Init(IEnumerable<IRestfulService> services)
  476. {
  477. _restServices.AddRange(services);
  478. _logger.Info("Calling EndpointHost.ConfigureHost");
  479. EndpointHost.ConfigureHost(this, ServerName, CreateServiceManager());
  480. _logger.Info("Calling ServiceStack AppHost.Init");
  481. Init();
  482. }
  483. }
  484. /// <summary>
  485. /// Class ContainerAdapter
  486. /// </summary>
  487. class ContainerAdapter : IContainerAdapter, IRelease
  488. {
  489. /// <summary>
  490. /// The _app host
  491. /// </summary>
  492. private readonly IApplicationHost _appHost;
  493. /// <summary>
  494. /// Initializes a new instance of the <see cref="ContainerAdapter" /> class.
  495. /// </summary>
  496. /// <param name="appHost">The app host.</param>
  497. public ContainerAdapter(IApplicationHost appHost)
  498. {
  499. _appHost = appHost;
  500. }
  501. /// <summary>
  502. /// Resolves this instance.
  503. /// </summary>
  504. /// <typeparam name="T"></typeparam>
  505. /// <returns>``0.</returns>
  506. public T Resolve<T>()
  507. {
  508. return _appHost.Resolve<T>();
  509. }
  510. /// <summary>
  511. /// Tries the resolve.
  512. /// </summary>
  513. /// <typeparam name="T"></typeparam>
  514. /// <returns>``0.</returns>
  515. public T TryResolve<T>()
  516. {
  517. return _appHost.TryResolve<T>();
  518. }
  519. /// <summary>
  520. /// Releases the specified instance.
  521. /// </summary>
  522. /// <param name="instance">The instance.</param>
  523. public void Release(object instance)
  524. {
  525. // Leave this empty so SS doesn't try to dispose our objects
  526. }
  527. }
  528. }