HttpServer.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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. await Task.Run(() =>
  242. {
  243. try
  244. {
  245. ProcessRequest(context);
  246. }
  247. catch (InvalidOperationException ex)
  248. {
  249. HandleException(context.Response, ex, 422);
  250. }
  251. catch (ResourceNotFoundException ex)
  252. {
  253. HandleException(context.Response, ex, 404);
  254. }
  255. catch (FileNotFoundException ex)
  256. {
  257. HandleException(context.Response, ex, 404);
  258. }
  259. catch (DirectoryNotFoundException ex)
  260. {
  261. HandleException(context.Response, ex, 404);
  262. }
  263. catch (UnauthorizedAccessException ex)
  264. {
  265. HandleException(context.Response, ex, 401);
  266. }
  267. catch (ArgumentException ex)
  268. {
  269. HandleException(context.Response, ex, 400);
  270. }
  271. catch (Exception ex)
  272. {
  273. HandleException(context.Response, ex, 500);
  274. }
  275. finally
  276. {
  277. context.Response.Close();
  278. }
  279. }).ConfigureAwait(false);
  280. }
  281. /// <summary>
  282. /// Processes the web socket request.
  283. /// </summary>
  284. /// <param name="ctx">The CTX.</param>
  285. /// <returns>Task.</returns>
  286. private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
  287. {
  288. try
  289. {
  290. var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
  291. if (WebSocketConnected != null)
  292. {
  293. WebSocketConnected(this, new WebSocketConnectEventArgs { WebSocket = new NativeWebSocket(webSocketContext.WebSocket, _logger), Endpoint = ctx.Request.RemoteEndPoint.ToString() });
  294. }
  295. }
  296. catch (Exception ex)
  297. {
  298. _logger.ErrorException("AcceptWebSocketAsync error", ex);
  299. ctx.Response.StatusCode = 500;
  300. ctx.Response.Close();
  301. }
  302. }
  303. /// <summary>
  304. /// Logs the HTTP request.
  305. /// </summary>
  306. /// <param name="ctx">The CTX.</param>
  307. private void LogHttpRequest(HttpListenerContext ctx)
  308. {
  309. var log = new StringBuilder();
  310. log.AppendLine("Url: " + ctx.Request.Url);
  311. log.AppendLine("Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));
  312. var type = ctx.Request.IsWebSocketRequest ? "Web Socket" : "HTTP " + ctx.Request.HttpMethod;
  313. if (EnableHttpRequestLogging)
  314. {
  315. _logger.LogMultiline(type + " request received from " + ctx.Request.RemoteEndPoint, LogSeverity.Debug, log);
  316. }
  317. }
  318. /// <summary>
  319. /// Appends the error message.
  320. /// </summary>
  321. /// <param name="response">The response.</param>
  322. /// <param name="ex">The ex.</param>
  323. /// <param name="statusCode">The status code.</param>
  324. private void HandleException(HttpListenerResponse response, Exception ex, int statusCode)
  325. {
  326. _logger.ErrorException("Error processing request", ex);
  327. // This could fail, but try to add the stack trace as the body content
  328. try
  329. {
  330. response.StatusCode = statusCode;
  331. response.Headers.Add("Status", statusCode.ToString(new CultureInfo("en-US")));
  332. response.Headers.Remove("Age");
  333. response.Headers.Remove("Expires");
  334. response.Headers.Remove("Cache-Control");
  335. response.Headers.Remove("Etag");
  336. response.Headers.Remove("Last-Modified");
  337. response.ContentType = "text/plain";
  338. if (!string.IsNullOrEmpty(ex.Message))
  339. {
  340. response.AddHeader("X-Application-Error-Code", ex.Message);
  341. }
  342. var sb = new StringBuilder();
  343. sb.AppendLine("{");
  344. sb.AppendLine("\"ResponseStatus\":{");
  345. sb.AppendFormat(" \"ErrorCode\":{0},\n", ex.GetType().Name.EncodeJson());
  346. sb.AppendFormat(" \"Message\":{0},\n", ex.Message.EncodeJson());
  347. sb.AppendFormat(" \"StackTrace\":{0}\n", ex.StackTrace.EncodeJson());
  348. sb.AppendLine("}");
  349. sb.AppendLine("}");
  350. response.ContentType = ContentType.Json;
  351. var sbBytes = sb.ToString().ToUtf8Bytes();
  352. response.OutputStream.Write(sbBytes, 0, sbBytes.Length);
  353. }
  354. catch (Exception errorEx)
  355. {
  356. _logger.ErrorException("Error processing failed request", errorEx);
  357. }
  358. }
  359. /// <summary>
  360. /// Overridable method that can be used to implement a custom hnandler
  361. /// </summary>
  362. /// <param name="context">The context.</param>
  363. /// <exception cref="System.NotImplementedException">Cannot execute handler: + handler + at PathInfo: + httpReq.PathInfo</exception>
  364. protected override void ProcessRequest(HttpListenerContext context)
  365. {
  366. if (string.IsNullOrEmpty(context.Request.RawUrl)) return;
  367. var operationName = context.Request.GetOperationName();
  368. var httpReq = new HttpListenerRequestWrapper(operationName, context.Request);
  369. var httpRes = new HttpListenerResponseWrapper(context.Response);
  370. var handler = ServiceStackHttpHandlerFactory.GetHandler(httpReq);
  371. var url = context.Request.Url.ToString();
  372. var endPoint = context.Request.RemoteEndPoint;
  373. var serviceStackHandler = handler as IServiceStackHttpHandler;
  374. if (serviceStackHandler != null)
  375. {
  376. var restHandler = serviceStackHandler as RestHandler;
  377. if (restHandler != null)
  378. {
  379. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.Name;
  380. }
  381. serviceStackHandler.ProcessRequest(httpReq, httpRes, operationName);
  382. LogResponse(context, url, endPoint);
  383. return;
  384. }
  385. throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
  386. }
  387. /// <summary>
  388. /// Logs the response.
  389. /// </summary>
  390. /// <param name="ctx">The CTX.</param>
  391. /// <param name="url">The URL.</param>
  392. /// <param name="endPoint">The end point.</param>
  393. private void LogResponse(HttpListenerContext ctx, string url, IPEndPoint endPoint)
  394. {
  395. if (!EnableHttpRequestLogging)
  396. {
  397. return;
  398. }
  399. var statusode = ctx.Response.StatusCode;
  400. var log = new StringBuilder();
  401. log.AppendLine(string.Format("Url: {0}", url));
  402. log.AppendLine("Headers: " + string.Join(",", ctx.Response.Headers.AllKeys.Select(k => k + "=" + ctx.Response.Headers[k])));
  403. var msg = "Http Response Sent (" + statusode + ") to " + endPoint;
  404. _logger.LogMultiline(msg, LogSeverity.Debug, log);
  405. }
  406. /// <summary>
  407. /// Creates the service manager.
  408. /// </summary>
  409. /// <param name="assembliesWithServices">The assemblies with services.</param>
  410. /// <returns>ServiceManager.</returns>
  411. protected override ServiceManager CreateServiceManager(params Assembly[] assembliesWithServices)
  412. {
  413. var types = _restServices.Select(r => r.GetType()).ToArray();
  414. return new ServiceManager(new Container(), new ServiceController(() => types));
  415. }
  416. /// <summary>
  417. /// Shut down the Web Service
  418. /// </summary>
  419. public override void Stop()
  420. {
  421. if (HttpListener != null)
  422. {
  423. HttpListener.Dispose();
  424. HttpListener = null;
  425. }
  426. if (Listener != null)
  427. {
  428. Listener.Prefixes.Remove(UrlPrefix);
  429. }
  430. base.Stop();
  431. }
  432. /// <summary>
  433. /// The _supports native web socket
  434. /// </summary>
  435. private bool? _supportsNativeWebSocket;
  436. /// <summary>
  437. /// Gets a value indicating whether [supports web sockets].
  438. /// </summary>
  439. /// <value><c>true</c> if [supports web sockets]; otherwise, <c>false</c>.</value>
  440. public bool SupportsWebSockets
  441. {
  442. get
  443. {
  444. if (!_supportsNativeWebSocket.HasValue)
  445. {
  446. try
  447. {
  448. new ClientWebSocket();
  449. _supportsNativeWebSocket = true;
  450. }
  451. catch (PlatformNotSupportedException)
  452. {
  453. _supportsNativeWebSocket = false;
  454. }
  455. }
  456. return _supportsNativeWebSocket.Value;
  457. }
  458. }
  459. /// <summary>
  460. /// Gets or sets a value indicating whether [enable HTTP request logging].
  461. /// </summary>
  462. /// <value><c>true</c> if [enable HTTP request logging]; otherwise, <c>false</c>.</value>
  463. public bool EnableHttpRequestLogging { get; set; }
  464. /// <summary>
  465. /// Adds the rest handlers.
  466. /// </summary>
  467. /// <param name="services">The services.</param>
  468. public void Init(IEnumerable<IRestfulService> services)
  469. {
  470. _restServices.AddRange(services);
  471. _logger.Info("Calling EndpointHost.ConfigureHost");
  472. EndpointHost.ConfigureHost(this, ServerName, CreateServiceManager());
  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. }