HttpServer.cs 21 KB

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