HttpServer.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. using System.Net.WebSockets;
  2. using Funq;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.Kernel;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Model.Logging;
  7. using ServiceStack.Api.Swagger;
  8. using ServiceStack.Common.Web;
  9. using ServiceStack.Configuration;
  10. using ServiceStack.Logging.NLogger;
  11. using ServiceStack.ServiceHost;
  12. using ServiceStack.ServiceInterface.Cors;
  13. using ServiceStack.Text;
  14. using ServiceStack.WebHost.Endpoints;
  15. using ServiceStack.WebHost.Endpoints.Extensions;
  16. using ServiceStack.WebHost.Endpoints.Support;
  17. using System;
  18. using System.Globalization;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Net;
  22. using System.Reactive.Linq;
  23. using System.Reflection;
  24. using System.Text;
  25. using System.Threading.Tasks;
  26. namespace MediaBrowser.Networking.Web
  27. {
  28. /// <summary>
  29. /// Class HttpServer
  30. /// </summary>
  31. public class HttpServer : HttpListenerBase, IHttpServer
  32. {
  33. /// <summary>
  34. /// The logger
  35. /// </summary>
  36. private readonly ILogger _logger;
  37. /// <summary>
  38. /// Gets the URL prefix.
  39. /// </summary>
  40. /// <value>The URL prefix.</value>
  41. public string UrlPrefix { get; private set; }
  42. /// <summary>
  43. /// Gets or sets the kernel.
  44. /// </summary>
  45. /// <value>The kernel.</value>
  46. private IKernel Kernel { get; set; }
  47. /// <summary>
  48. /// Gets or sets the application host.
  49. /// </summary>
  50. /// <value>The application host.</value>
  51. private IApplicationHost ApplicationHost { get; set; }
  52. /// <summary>
  53. /// This subscribes to HttpListener requests and finds the appropriate BaseHandler to process it
  54. /// </summary>
  55. /// <value>The HTTP listener.</value>
  56. private IDisposable HttpListener { get; set; }
  57. /// <summary>
  58. /// Occurs when [web socket connected].
  59. /// </summary>
  60. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  61. /// <summary>
  62. /// Gets the default redirect path.
  63. /// </summary>
  64. /// <value>The default redirect path.</value>
  65. private string DefaultRedirectPath { get; set; }
  66. /// <summary>
  67. /// Gets or sets the name of the server.
  68. /// </summary>
  69. /// <value>The name of the server.</value>
  70. private string ServerName { get; set; }
  71. /// <summary>
  72. /// Initializes a new instance of the <see cref="HttpServer" /> class.
  73. /// </summary>
  74. /// <param name="applicationHost">The application host.</param>
  75. /// <param name="kernel">The kernel.</param>
  76. /// <param name="logger">The logger.</param>
  77. /// <param name="serverName">Name of the server.</param>
  78. /// <param name="defaultRedirectpath">The default redirectpath.</param>
  79. /// <exception cref="System.ArgumentNullException">urlPrefix</exception>
  80. public HttpServer(IApplicationHost applicationHost, IKernel kernel, ILogger logger, string serverName, string defaultRedirectpath)
  81. : base()
  82. {
  83. if (kernel == null)
  84. {
  85. throw new ArgumentNullException("kernel");
  86. }
  87. if (logger == null)
  88. {
  89. throw new ArgumentNullException("logger");
  90. }
  91. if (applicationHost == null)
  92. {
  93. throw new ArgumentNullException("applicationHost");
  94. }
  95. if (string.IsNullOrEmpty(serverName))
  96. {
  97. throw new ArgumentNullException("serverName");
  98. }
  99. if (string.IsNullOrEmpty(defaultRedirectpath))
  100. {
  101. throw new ArgumentNullException("defaultRedirectpath");
  102. }
  103. ServerName = serverName;
  104. DefaultRedirectPath = defaultRedirectpath;
  105. _logger = logger;
  106. ApplicationHost = applicationHost;
  107. EndpointHostConfig.Instance.ServiceStackHandlerFactoryPath = null;
  108. EndpointHostConfig.Instance.MetadataRedirectPath = "metadata";
  109. Kernel = kernel;
  110. EndpointHost.ConfigureHost(this, ServerName, CreateServiceManager());
  111. ContentTypeFilters.Register(ContentType.ProtoBuf, (reqCtx, res, stream) => Kernel.ProtobufSerializer.SerializeToStream(res, stream), (type, stream) => Kernel.ProtobufSerializer.DeserializeFromStream(stream, type));
  112. Init();
  113. }
  114. /// <summary>
  115. /// Configures the specified container.
  116. /// </summary>
  117. /// <param name="container">The container.</param>
  118. public override void Configure(Container container)
  119. {
  120. SetConfig(new EndpointHostConfig
  121. {
  122. DefaultRedirectPath = DefaultRedirectPath,
  123. // Tell SS to bubble exceptions up to here
  124. WriteErrorsToResponse = false,
  125. DebugMode = true
  126. });
  127. container.Adapter = new ContainerAdapter(ApplicationHost);
  128. foreach (var service in Kernel.RestServices)
  129. {
  130. service.Configure(this);
  131. }
  132. Plugins.Add(new SwaggerFeature());
  133. Plugins.Add(new CorsFeature());
  134. ServiceStack.Logging.LogManager.LogFactory = new NLogFactory();
  135. }
  136. /// <summary>
  137. /// Starts the Web Service
  138. /// </summary>
  139. /// <param name="urlBase">A Uri that acts as the base that the server is listening on.
  140. /// Format should be: http://127.0.0.1:8080/ or http://127.0.0.1:8080/somevirtual/
  141. /// Note: the trailing slash is required! For more info see the
  142. /// HttpListener.Prefixes property on MSDN.</param>
  143. public override void Start(string urlBase)
  144. {
  145. if (string.IsNullOrEmpty(urlBase))
  146. {
  147. throw new ArgumentNullException("urlBase");
  148. }
  149. // *** Already running - just leave it in place
  150. if (IsStarted)
  151. {
  152. return;
  153. }
  154. if (Listener == null)
  155. {
  156. Listener = new HttpListener();
  157. }
  158. EndpointHost.Config.ServiceStackHandlerFactoryPath = HttpListenerRequestWrapper.GetHandlerPathIfAny(urlBase);
  159. UrlPrefix = urlBase;
  160. Listener.Prefixes.Add(urlBase);
  161. IsStarted = true;
  162. Listener.Start();
  163. HttpListener = CreateObservableStream().Subscribe(ProcessHttpRequestAsync);
  164. }
  165. /// <summary>
  166. /// Creates the observable stream.
  167. /// </summary>
  168. /// <returns>IObservable{HttpListenerContext}.</returns>
  169. private IObservable<HttpListenerContext> CreateObservableStream()
  170. {
  171. return Observable.Create<HttpListenerContext>(obs =>
  172. Observable.FromAsync(() => Listener.GetContextAsync())
  173. .Subscribe(obs))
  174. .Repeat()
  175. .Retry()
  176. .Publish()
  177. .RefCount();
  178. }
  179. /// <summary>
  180. /// Processes incoming http requests by routing them to the appropiate handler
  181. /// </summary>
  182. /// <param name="context">The CTX.</param>
  183. private async void ProcessHttpRequestAsync(HttpListenerContext context)
  184. {
  185. LogHttpRequest(context);
  186. if (context.Request.IsWebSocketRequest)
  187. {
  188. await ProcessWebSocketRequest(context).ConfigureAwait(false);
  189. return;
  190. }
  191. Task.Run(() =>
  192. {
  193. RaiseReceiveWebRequest(context);
  194. try
  195. {
  196. ProcessRequest(context);
  197. }
  198. catch (InvalidOperationException ex)
  199. {
  200. HandleException(context.Response, ex, 422);
  201. throw;
  202. }
  203. catch (ResourceNotFoundException ex)
  204. {
  205. HandleException(context.Response, ex, 404);
  206. throw;
  207. }
  208. catch (FileNotFoundException ex)
  209. {
  210. HandleException(context.Response, ex, 404);
  211. throw;
  212. }
  213. catch (DirectoryNotFoundException ex)
  214. {
  215. HandleException(context.Response, ex, 404);
  216. throw;
  217. }
  218. catch (UnauthorizedAccessException ex)
  219. {
  220. HandleException(context.Response, ex, 401);
  221. throw;
  222. }
  223. catch (ArgumentException ex)
  224. {
  225. HandleException(context.Response, ex, 400);
  226. throw;
  227. }
  228. catch (Exception ex)
  229. {
  230. HandleException(context.Response, ex, 500);
  231. throw;
  232. }
  233. });
  234. }
  235. /// <summary>
  236. /// Processes the web socket request.
  237. /// </summary>
  238. /// <param name="ctx">The CTX.</param>
  239. /// <returns>Task.</returns>
  240. private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
  241. {
  242. try
  243. {
  244. var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
  245. if (WebSocketConnected != null)
  246. {
  247. WebSocketConnected(this, new WebSocketConnectEventArgs { WebSocket = new NativeWebSocket(webSocketContext.WebSocket, _logger), Endpoint = ctx.Request.RemoteEndPoint.ToString() });
  248. }
  249. }
  250. catch (Exception ex)
  251. {
  252. _logger.ErrorException("AcceptWebSocketAsync error", ex);
  253. ctx.Response.StatusCode = 500;
  254. ctx.Response.Close();
  255. }
  256. }
  257. /// <summary>
  258. /// Logs the HTTP request.
  259. /// </summary>
  260. /// <param name="ctx">The CTX.</param>
  261. private void LogHttpRequest(HttpListenerContext ctx)
  262. {
  263. var log = new StringBuilder();
  264. log.AppendLine("Url: " + ctx.Request.Url);
  265. log.AppendLine("Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));
  266. var type = ctx.Request.IsWebSocketRequest ? "Web Socket" : "HTTP " + ctx.Request.HttpMethod;
  267. if (EnableHttpRequestLogging)
  268. {
  269. _logger.LogMultiline(type + " request received from " + ctx.Request.RemoteEndPoint, LogSeverity.Debug, log);
  270. }
  271. }
  272. /// <summary>
  273. /// Appends the error message.
  274. /// </summary>
  275. /// <param name="response">The response.</param>
  276. /// <param name="ex">The ex.</param>
  277. /// <param name="statusCode">The status code.</param>
  278. private void HandleException(HttpListenerResponse response, Exception ex, int statusCode)
  279. {
  280. _logger.ErrorException("Error processing request", ex);
  281. response.StatusCode = statusCode;
  282. response.Headers.Add("Status", statusCode.ToString(new CultureInfo("en-US")));
  283. response.Headers.Remove("Age");
  284. response.Headers.Remove("Expires");
  285. response.Headers.Remove("Cache-Control");
  286. response.Headers.Remove("Etag");
  287. response.Headers.Remove("Last-Modified");
  288. response.ContentType = "text/plain";
  289. if (!string.IsNullOrEmpty(ex.Message))
  290. {
  291. response.AddHeader("X-Application-Error-Code", ex.Message);
  292. }
  293. // This could fail, but try to add the stack trace as the body content
  294. try
  295. {
  296. var sb = new StringBuilder();
  297. sb.AppendLine("{");
  298. sb.AppendLine("\"ResponseStatus\":{");
  299. sb.AppendFormat(" \"ErrorCode\":{0},\n", ex.GetType().Name.EncodeJson());
  300. sb.AppendFormat(" \"Message\":{0},\n", ex.Message.EncodeJson());
  301. sb.AppendFormat(" \"StackTrace\":{0}\n", ex.StackTrace.EncodeJson());
  302. sb.AppendLine("}");
  303. sb.AppendLine("}");
  304. response.StatusCode = 500;
  305. response.ContentType = ContentType.Json;
  306. var sbBytes = sb.ToString().ToUtf8Bytes();
  307. response.OutputStream.Write(sbBytes, 0, sbBytes.Length);
  308. response.Close();
  309. }
  310. catch (Exception errorEx)
  311. {
  312. _logger.ErrorException("Error processing failed request", errorEx);
  313. }
  314. }
  315. /// <summary>
  316. /// Overridable method that can be used to implement a custom hnandler
  317. /// </summary>
  318. /// <param name="context">The context.</param>
  319. /// <exception cref="System.NotImplementedException">Cannot execute handler: + handler + at PathInfo: + httpReq.PathInfo</exception>
  320. protected override void ProcessRequest(HttpListenerContext context)
  321. {
  322. if (string.IsNullOrEmpty(context.Request.RawUrl)) return;
  323. var operationName = context.Request.GetOperationName();
  324. var httpReq = new HttpListenerRequestWrapper(operationName, context.Request);
  325. var httpRes = new HttpListenerResponseWrapper(context.Response);
  326. var handler = ServiceStackHttpHandlerFactory.GetHandler(httpReq);
  327. var serviceStackHandler = handler as IServiceStackHttpHandler;
  328. if (serviceStackHandler != null)
  329. {
  330. var restHandler = serviceStackHandler as RestHandler;
  331. if (restHandler != null)
  332. {
  333. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.Name;
  334. }
  335. serviceStackHandler.ProcessRequest(httpReq, httpRes, operationName);
  336. LogResponse(context);
  337. httpRes.Close();
  338. return;
  339. }
  340. throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
  341. }
  342. /// <summary>
  343. /// Logs the response.
  344. /// </summary>
  345. /// <param name="ctx">The CTX.</param>
  346. private void LogResponse(HttpListenerContext ctx)
  347. {
  348. var statusode = ctx.Response.StatusCode;
  349. var log = new StringBuilder();
  350. log.AppendLine(string.Format("Url: {0}", ctx.Request.Url));
  351. log.AppendLine("Headers: " + string.Join(",", ctx.Response.Headers.AllKeys.Select(k => k + "=" + ctx.Response.Headers[k])));
  352. var msg = "Http Response Sent (" + statusode + ") to " + ctx.Request.RemoteEndPoint;
  353. if (EnableHttpRequestLogging)
  354. {
  355. _logger.LogMultiline(msg, LogSeverity.Debug, log);
  356. }
  357. }
  358. /// <summary>
  359. /// Creates the service manager.
  360. /// </summary>
  361. /// <param name="assembliesWithServices">The assemblies with services.</param>
  362. /// <returns>ServiceManager.</returns>
  363. protected override ServiceManager CreateServiceManager(params Assembly[] assembliesWithServices)
  364. {
  365. var types = Kernel.RestServices.Select(r => r.GetType()).ToArray();
  366. return new ServiceManager(new Container(), new ServiceController(() => types));
  367. }
  368. /// <summary>
  369. /// Shut down the Web Service
  370. /// </summary>
  371. public override void Stop()
  372. {
  373. if (HttpListener != null)
  374. {
  375. HttpListener.Dispose();
  376. HttpListener = null;
  377. }
  378. if (Listener != null)
  379. {
  380. Listener.Prefixes.Remove(UrlPrefix);
  381. }
  382. base.Stop();
  383. }
  384. /// <summary>
  385. /// The _supports native web socket
  386. /// </summary>
  387. private bool? _supportsNativeWebSocket;
  388. /// <summary>
  389. /// Gets a value indicating whether [supports web sockets].
  390. /// </summary>
  391. /// <value><c>true</c> if [supports web sockets]; otherwise, <c>false</c>.</value>
  392. public bool SupportsWebSockets
  393. {
  394. get
  395. {
  396. if (!_supportsNativeWebSocket.HasValue)
  397. {
  398. try
  399. {
  400. new ClientWebSocket();
  401. _supportsNativeWebSocket = true;
  402. }
  403. catch (PlatformNotSupportedException)
  404. {
  405. _supportsNativeWebSocket = false;
  406. }
  407. }
  408. return _supportsNativeWebSocket.Value;
  409. }
  410. }
  411. /// <summary>
  412. /// Gets or sets a value indicating whether [enable HTTP request logging].
  413. /// </summary>
  414. /// <value><c>true</c> if [enable HTTP request logging]; otherwise, <c>false</c>.</value>
  415. public bool EnableHttpRequestLogging { get; set; }
  416. }
  417. /// <summary>
  418. /// Class ContainerAdapter
  419. /// </summary>
  420. class ContainerAdapter : IContainerAdapter
  421. {
  422. /// <summary>
  423. /// The _app host
  424. /// </summary>
  425. private readonly IApplicationHost _appHost;
  426. /// <summary>
  427. /// Initializes a new instance of the <see cref="ContainerAdapter" /> class.
  428. /// </summary>
  429. /// <param name="appHost">The app host.</param>
  430. public ContainerAdapter(IApplicationHost appHost)
  431. {
  432. _appHost = appHost;
  433. }
  434. /// <summary>
  435. /// Resolves this instance.
  436. /// </summary>
  437. /// <typeparam name="T"></typeparam>
  438. /// <returns>``0.</returns>
  439. public T Resolve<T>()
  440. {
  441. return _appHost.Resolve<T>();
  442. }
  443. /// <summary>
  444. /// Tries the resolve.
  445. /// </summary>
  446. /// <typeparam name="T"></typeparam>
  447. /// <returns>``0.</returns>
  448. public T TryResolve<T>()
  449. {
  450. return _appHost.TryResolve<T>();
  451. }
  452. }
  453. }