HttpServer.cs 15 KB

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