HttpServer.cs 16 KB

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