HttpServer.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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;
  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.Concurrent;
  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. /// This subscribes to HttpListener requests and finds the appropriate BaseHandler to process it
  50. /// </summary>
  51. /// <value>The HTTP listener.</value>
  52. private IDisposable HttpListener { get; set; }
  53. /// <summary>
  54. /// Occurs when [web socket connected].
  55. /// </summary>
  56. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  57. /// <summary>
  58. /// Gets the default redirect path.
  59. /// </summary>
  60. /// <value>The default redirect path.</value>
  61. private string DefaultRedirectPath { get; set; }
  62. /// <summary>
  63. /// Gets or sets the name of the server.
  64. /// </summary>
  65. /// <value>The name of the server.</value>
  66. private string ServerName { get; set; }
  67. /// <summary>
  68. /// The _container adapter
  69. /// </summary>
  70. private readonly ContainerAdapter _containerAdapter;
  71. private readonly ConcurrentDictionary<string, string> _localEndPoints = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  72. /// <summary>
  73. /// Gets the local end points.
  74. /// </summary>
  75. /// <value>The local end points.</value>
  76. public IEnumerable<string> LocalEndPoints
  77. {
  78. get { return _localEndPoints.Keys.ToList(); }
  79. }
  80. /// <summary>
  81. /// Initializes a new instance of the <see cref="HttpServer" /> class.
  82. /// </summary>
  83. /// <param name="applicationHost">The application host.</param>
  84. /// <param name="logManager">The log manager.</param>
  85. /// <param name="serverName">Name of the server.</param>
  86. /// <param name="defaultRedirectpath">The default redirectpath.</param>
  87. /// <exception cref="System.ArgumentNullException">urlPrefix</exception>
  88. public HttpServer(IApplicationHost applicationHost, ILogManager logManager, string serverName, string defaultRedirectpath)
  89. : base()
  90. {
  91. if (logManager == null)
  92. {
  93. throw new ArgumentNullException("logManager");
  94. }
  95. if (applicationHost == null)
  96. {
  97. throw new ArgumentNullException("applicationHost");
  98. }
  99. if (string.IsNullOrEmpty(serverName))
  100. {
  101. throw new ArgumentNullException("serverName");
  102. }
  103. if (string.IsNullOrEmpty(defaultRedirectpath))
  104. {
  105. throw new ArgumentNullException("defaultRedirectpath");
  106. }
  107. ServerName = serverName;
  108. DefaultRedirectPath = defaultRedirectpath;
  109. _logger = logManager.GetLogger("HttpServer");
  110. LogManager.LogFactory = new ServerLogFactory(logManager);
  111. EndpointHostConfig.Instance.ServiceStackHandlerFactoryPath = null;
  112. EndpointHostConfig.Instance.MetadataRedirectPath = "metadata";
  113. _containerAdapter = new ContainerAdapter(applicationHost);
  114. }
  115. /// <summary>
  116. /// The us culture
  117. /// </summary>
  118. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  119. /// <summary>
  120. /// Configures the specified container.
  121. /// </summary>
  122. /// <param name="container">The container.</param>
  123. public override void Configure(Container container)
  124. {
  125. JsConfig.DateHandler = JsonDateHandler.ISO8601;
  126. JsConfig.ExcludeTypeInfo = true;
  127. JsConfig.IncludeNullValues = false;
  128. SetConfig(new EndpointHostConfig
  129. {
  130. DefaultRedirectPath = DefaultRedirectPath,
  131. MapExceptionToStatusCode = {
  132. { typeof(InvalidOperationException), 422 },
  133. { typeof(ResourceNotFoundException), 404 },
  134. { typeof(FileNotFoundException), 404 },
  135. { typeof(DirectoryNotFoundException), 404 }
  136. },
  137. DebugMode = true,
  138. ServiceName = ServerName,
  139. LogFactory = LogManager.LogFactory,
  140. // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
  141. // Custom format allows images
  142. EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat
  143. });
  144. container.Adapter = _containerAdapter;
  145. Plugins.Add(new SwaggerFeature());
  146. Plugins.Add(new CorsFeature());
  147. ResponseFilters.Add(FilterResponse);
  148. }
  149. /// <summary>
  150. /// Filters the response.
  151. /// </summary>
  152. /// <param name="req">The req.</param>
  153. /// <param name="res">The res.</param>
  154. /// <param name="dto">The dto.</param>
  155. private void FilterResponse(IHttpRequest req, IHttpResponse res, object dto)
  156. {
  157. var exception = dto as Exception;
  158. if (exception != null)
  159. {
  160. _logger.ErrorException("Error processing request for {0}", exception, req.RawUrl);
  161. if (!string.IsNullOrEmpty(exception.Message))
  162. {
  163. var error = exception.Message.Replace(Environment.NewLine, " ");
  164. error = RemoveControlCharacters(error);
  165. res.AddHeader("X-Application-Error-Code", error);
  166. }
  167. }
  168. if (dto is CompressedResult)
  169. {
  170. // Per Google PageSpeed
  171. // This instructs the proxies to cache two versions of the resource: one compressed, and one uncompressed.
  172. // The correct version of the resource is delivered based on the client request header.
  173. // This is a good choice for applications that are singly homed and depend on public proxies for user locality.
  174. res.AddHeader("Vary", "Accept-Encoding");
  175. }
  176. var hasOptions = dto as IHasOptions;
  177. if (hasOptions != null)
  178. {
  179. // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy
  180. string contentLength;
  181. if (hasOptions.Options.TryGetValue("Content-Length", out contentLength) && !string.IsNullOrEmpty(contentLength))
  182. {
  183. var length = long.Parse(contentLength, UsCulture);
  184. if (length > 0)
  185. {
  186. var response = (HttpListenerResponse)res.OriginalResponse;
  187. response.ContentLength64 = length;
  188. // Disable chunked encoding. Technically this is only needed when using Content-Range, but
  189. // anytime we know the content length there's no need for it
  190. response.SendChunked = false;
  191. }
  192. }
  193. }
  194. }
  195. /// <summary>
  196. /// Removes the control characters.
  197. /// </summary>
  198. /// <param name="inString">The in string.</param>
  199. /// <returns>System.String.</returns>
  200. private static string RemoveControlCharacters(string inString)
  201. {
  202. if (inString == null) return null;
  203. var newString = new StringBuilder();
  204. foreach (var ch in inString)
  205. {
  206. if (!char.IsControl(ch))
  207. {
  208. newString.Append(ch);
  209. }
  210. }
  211. return newString.ToString();
  212. }
  213. /// <summary>
  214. /// Starts the Web Service
  215. /// </summary>
  216. /// <param name="urlBase">A Uri that acts as the base that the server is listening on.
  217. /// Format should be: http://127.0.0.1:8080/ or http://127.0.0.1:8080/somevirtual/
  218. /// Note: the trailing slash is required! For more info see the
  219. /// HttpListener.Prefixes property on MSDN.</param>
  220. /// <exception cref="System.ArgumentNullException">urlBase</exception>
  221. public override void Start(string urlBase)
  222. {
  223. if (string.IsNullOrEmpty(urlBase))
  224. {
  225. throw new ArgumentNullException("urlBase");
  226. }
  227. // *** Already running - just leave it in place
  228. if (IsStarted)
  229. {
  230. return;
  231. }
  232. if (Listener == null)
  233. {
  234. _logger.Info("Creating HttpListner");
  235. Listener = new HttpListener();
  236. }
  237. EndpointHost.Config.ServiceStackHandlerFactoryPath = HttpListenerRequestWrapper.GetHandlerPathIfAny(urlBase);
  238. UrlPrefix = urlBase;
  239. _logger.Info("Adding HttpListener Prefixes");
  240. Listener.Prefixes.Add(urlBase);
  241. IsStarted = true;
  242. _logger.Info("Starting HttpListner");
  243. Listener.Start();
  244. _logger.Info("Creating HttpListner observable stream");
  245. HttpListener = CreateObservableStream().Subscribe(ProcessHttpRequestAsync);
  246. }
  247. /// <summary>
  248. /// Creates the observable stream.
  249. /// </summary>
  250. /// <returns>IObservable{HttpListenerContext}.</returns>
  251. private IObservable<HttpListenerContext> CreateObservableStream()
  252. {
  253. return Observable.Create<HttpListenerContext>(obs =>
  254. Observable.FromAsync(() => Listener.GetContextAsync())
  255. .Subscribe(obs))
  256. .Repeat()
  257. .Retry()
  258. .Publish()
  259. .RefCount();
  260. }
  261. /// <summary>
  262. /// Processes incoming http requests by routing them to the appropiate handler
  263. /// </summary>
  264. /// <param name="context">The CTX.</param>
  265. private async void ProcessHttpRequestAsync(HttpListenerContext context)
  266. {
  267. var date = DateTime.Now;
  268. LogHttpRequest(context);
  269. if (context.Request.IsWebSocketRequest)
  270. {
  271. await ProcessWebSocketRequest(context).ConfigureAwait(false);
  272. return;
  273. }
  274. var localPath = context.Request.Url.LocalPath;
  275. if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
  276. {
  277. context.Response.Redirect(DefaultRedirectPath);
  278. context.Response.Close();
  279. return;
  280. }
  281. if (string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
  282. {
  283. context.Response.Redirect("mediabrowser/" + DefaultRedirectPath);
  284. context.Response.Close();
  285. return;
  286. }
  287. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  288. {
  289. context.Response.Redirect("mediabrowser/" + DefaultRedirectPath);
  290. context.Response.Close();
  291. return;
  292. }
  293. if (string.IsNullOrEmpty(localPath))
  294. {
  295. context.Response.Redirect("/mediabrowser/" + DefaultRedirectPath);
  296. context.Response.Close();
  297. return;
  298. }
  299. RaiseReceiveWebRequest(context);
  300. await Task.Factory.StartNew(() =>
  301. {
  302. try
  303. {
  304. var url = context.Request.Url.ToString();
  305. var endPoint = context.Request.RemoteEndPoint;
  306. ProcessRequest(context);
  307. var duration = DateTime.Now - date;
  308. LogResponse(context, url, endPoint, duration);
  309. }
  310. catch (Exception ex)
  311. {
  312. _logger.ErrorException("ProcessRequest failure", ex);
  313. }
  314. }).ConfigureAwait(false);
  315. }
  316. /// <summary>
  317. /// Processes the web socket request.
  318. /// </summary>
  319. /// <param name="ctx">The CTX.</param>
  320. /// <returns>Task.</returns>
  321. private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
  322. {
  323. #if __MonoCS__
  324. #else
  325. try
  326. {
  327. var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
  328. if (WebSocketConnected != null)
  329. {
  330. WebSocketConnected(this, new WebSocketConnectEventArgs { WebSocket = new NativeWebSocket(webSocketContext.WebSocket, _logger), Endpoint = ctx.Request.RemoteEndPoint.ToString() });
  331. }
  332. }
  333. catch (Exception ex)
  334. {
  335. _logger.ErrorException("AcceptWebSocketAsync error", ex);
  336. ctx.Response.StatusCode = 500;
  337. ctx.Response.Close();
  338. }
  339. #endif
  340. }
  341. /// <summary>
  342. /// Logs the HTTP request.
  343. /// </summary>
  344. /// <param name="ctx">The CTX.</param>
  345. private void LogHttpRequest(HttpListenerContext ctx)
  346. {
  347. var endpoint = ctx.Request.LocalEndPoint;
  348. if (endpoint != null)
  349. {
  350. var address = endpoint.ToString();
  351. _localEndPoints.GetOrAdd(address, address);
  352. }
  353. if (EnableHttpRequestLogging)
  354. {
  355. var log = new StringBuilder();
  356. log.AppendLine("Url: " + ctx.Request.Url);
  357. log.AppendLine("Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));
  358. var type = ctx.Request.IsWebSocketRequest ? "Web Socket" : "HTTP " + ctx.Request.HttpMethod;
  359. _logger.LogMultiline(type + " request received from " + ctx.Request.RemoteEndPoint, LogSeverity.Debug, log);
  360. }
  361. }
  362. /// <summary>
  363. /// Overridable method that can be used to implement a custom hnandler
  364. /// </summary>
  365. /// <param name="context">The context.</param>
  366. /// <exception cref="System.NotImplementedException">Cannot execute handler: + handler + at PathInfo: + httpReq.PathInfo</exception>
  367. protected override void ProcessRequest(HttpListenerContext context)
  368. {
  369. if (string.IsNullOrEmpty(context.Request.RawUrl)) return;
  370. var operationName = context.Request.GetOperationName();
  371. var httpReq = new HttpListenerRequestWrapper(operationName, context.Request);
  372. var httpRes = new HttpListenerResponseWrapper(context.Response);
  373. var handler = ServiceStackHttpHandlerFactory.GetHandler(httpReq);
  374. var serviceStackHandler = handler as IServiceStackHttpHandler;
  375. if (serviceStackHandler != null)
  376. {
  377. var restHandler = serviceStackHandler as RestHandler;
  378. if (restHandler != null)
  379. {
  380. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.Name;
  381. }
  382. serviceStackHandler.ProcessRequest(httpReq, httpRes, operationName);
  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. /// <param name="duration">The duration.</param>
  394. private void LogResponse(HttpListenerContext ctx, string url, IPEndPoint endPoint, TimeSpan duration)
  395. {
  396. if (!EnableHttpRequestLogging)
  397. {
  398. return;
  399. }
  400. var statusCode = ctx.Response.StatusCode;
  401. var log = new StringBuilder();
  402. log.AppendLine(string.Format("Url: {0}", url));
  403. log.AppendLine("Headers: " + string.Join(",", ctx.Response.Headers.AllKeys.Select(k => k + "=" + ctx.Response.Headers[k])));
  404. var responseTime = string.Format(". Response time: {0} ms", duration.TotalMilliseconds);
  405. var msg = "Response code " + statusCode + " sent to " + endPoint + responseTime;
  406. _logger.LogMultiline(msg, LogSeverity.Debug, log);
  407. }
  408. /// <summary>
  409. /// Creates the service manager.
  410. /// </summary>
  411. /// <param name="assembliesWithServices">The assemblies with services.</param>
  412. /// <returns>ServiceManager.</returns>
  413. protected override ServiceManager CreateServiceManager(params Assembly[] assembliesWithServices)
  414. {
  415. var types = _restServices.Select(r => r.GetType()).ToArray();
  416. return new ServiceManager(new Container(), new ServiceController(() => types));
  417. }
  418. /// <summary>
  419. /// Shut down the Web Service
  420. /// </summary>
  421. public override void Stop()
  422. {
  423. if (HttpListener != null)
  424. {
  425. HttpListener.Dispose();
  426. HttpListener = null;
  427. }
  428. if (Listener != null)
  429. {
  430. Listener.Prefixes.Remove(UrlPrefix);
  431. }
  432. base.Stop();
  433. }
  434. /// <summary>
  435. /// The _supports native web socket
  436. /// </summary>
  437. private bool? _supportsNativeWebSocket;
  438. /// <summary>
  439. /// Gets a value indicating whether [supports web sockets].
  440. /// </summary>
  441. /// <value><c>true</c> if [supports web sockets]; otherwise, <c>false</c>.</value>
  442. public bool SupportsWebSockets
  443. {
  444. get
  445. {
  446. #if __MonoCS__
  447. return false;
  448. #else
  449. #endif
  450. if (!_supportsNativeWebSocket.HasValue)
  451. {
  452. try
  453. {
  454. new ClientWebSocket();
  455. _supportsNativeWebSocket = true;
  456. }
  457. catch (PlatformNotSupportedException)
  458. {
  459. _supportsNativeWebSocket = false;
  460. }
  461. }
  462. return _supportsNativeWebSocket.Value;
  463. }
  464. }
  465. /// <summary>
  466. /// Gets or sets a value indicating whether [enable HTTP request logging].
  467. /// </summary>
  468. /// <value><c>true</c> if [enable HTTP request logging]; otherwise, <c>false</c>.</value>
  469. public bool EnableHttpRequestLogging { get; set; }
  470. /// <summary>
  471. /// Adds the rest handlers.
  472. /// </summary>
  473. /// <param name="services">The services.</param>
  474. public void Init(IEnumerable<IRestfulService> services)
  475. {
  476. _restServices.AddRange(services);
  477. _logger.Info("Calling EndpointHost.ConfigureHost");
  478. EndpointHost.ConfigureHost(this, ServerName, CreateServiceManager());
  479. _logger.Info("Calling ServiceStack AppHost.Init");
  480. Init();
  481. }
  482. /// <summary>
  483. /// Releases the specified instance.
  484. /// </summary>
  485. /// <param name="instance">The instance.</param>
  486. public override void Release(object instance)
  487. {
  488. // Leave this empty so SS doesn't try to dispose our objects
  489. }
  490. }
  491. /// <summary>
  492. /// Class ContainerAdapter
  493. /// </summary>
  494. class ContainerAdapter : IContainerAdapter, IRelease
  495. {
  496. /// <summary>
  497. /// The _app host
  498. /// </summary>
  499. private readonly IApplicationHost _appHost;
  500. /// <summary>
  501. /// Initializes a new instance of the <see cref="ContainerAdapter" /> class.
  502. /// </summary>
  503. /// <param name="appHost">The app host.</param>
  504. public ContainerAdapter(IApplicationHost appHost)
  505. {
  506. _appHost = appHost;
  507. }
  508. /// <summary>
  509. /// Resolves this instance.
  510. /// </summary>
  511. /// <typeparam name="T"></typeparam>
  512. /// <returns>``0.</returns>
  513. public T Resolve<T>()
  514. {
  515. return _appHost.Resolve<T>();
  516. }
  517. /// <summary>
  518. /// Tries the resolve.
  519. /// </summary>
  520. /// <typeparam name="T"></typeparam>
  521. /// <returns>``0.</returns>
  522. public T TryResolve<T>()
  523. {
  524. return _appHost.TryResolve<T>();
  525. }
  526. /// <summary>
  527. /// Releases the specified instance.
  528. /// </summary>
  529. /// <param name="instance">The instance.</param>
  530. public void Release(object instance)
  531. {
  532. // Leave this empty so SS doesn't try to dispose our objects
  533. }
  534. }
  535. }