2
0

HttpServer.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. Task.Run(() =>
  177. {
  178. RaiseReceiveWebRequest(context);
  179. try
  180. {
  181. ProcessRequest(context);
  182. }
  183. catch (InvalidOperationException ex)
  184. {
  185. HandleException(context.Response, ex, 422);
  186. throw;
  187. }
  188. catch (ResourceNotFoundException ex)
  189. {
  190. HandleException(context.Response, ex, 404);
  191. throw;
  192. }
  193. catch (FileNotFoundException ex)
  194. {
  195. HandleException(context.Response, ex, 404);
  196. throw;
  197. }
  198. catch (DirectoryNotFoundException ex)
  199. {
  200. HandleException(context.Response, ex, 404);
  201. throw;
  202. }
  203. catch (UnauthorizedAccessException ex)
  204. {
  205. HandleException(context.Response, ex, 401);
  206. throw;
  207. }
  208. catch (ArgumentException ex)
  209. {
  210. HandleException(context.Response, ex, 400);
  211. throw;
  212. }
  213. catch (Exception ex)
  214. {
  215. HandleException(context.Response, ex, 500);
  216. throw;
  217. }
  218. });
  219. }
  220. /// <summary>
  221. /// Processes the web socket request.
  222. /// </summary>
  223. /// <param name="ctx">The CTX.</param>
  224. /// <returns>Task.</returns>
  225. private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
  226. {
  227. try
  228. {
  229. var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
  230. if (WebSocketConnected != null)
  231. {
  232. WebSocketConnected(this, new WebSocketConnectEventArgs { WebSocket = new NativeWebSocket(webSocketContext.WebSocket), Endpoint = ctx.Request.RemoteEndPoint });
  233. }
  234. }
  235. catch (Exception ex)
  236. {
  237. Logger.ErrorException("AcceptWebSocketAsync error", ex);
  238. ctx.Response.StatusCode = 500;
  239. ctx.Response.Close();
  240. }
  241. }
  242. /// <summary>
  243. /// Logs the HTTP request.
  244. /// </summary>
  245. /// <param name="ctx">The CTX.</param>
  246. private void LogHttpRequest(HttpListenerContext ctx)
  247. {
  248. var log = new StringBuilder();
  249. log.AppendLine("Url: " + ctx.Request.Url);
  250. log.AppendLine("Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));
  251. var type = ctx.Request.IsWebSocketRequest ? "Web Socket" : "HTTP " + ctx.Request.HttpMethod;
  252. if (Kernel.Configuration.EnableHttpLevelLogging)
  253. {
  254. Logger.LogMultiline(type + " request received from " + ctx.Request.RemoteEndPoint, LogSeverity.Debug, log);
  255. }
  256. }
  257. /// <summary>
  258. /// Appends the error message.
  259. /// </summary>
  260. /// <param name="response">The response.</param>
  261. /// <param name="ex">The ex.</param>
  262. /// <param name="statusCode">The status code.</param>
  263. private void HandleException(HttpListenerResponse response, Exception ex, int statusCode)
  264. {
  265. Logger.ErrorException("Error processing request", ex);
  266. response.StatusCode = statusCode;
  267. response.Headers.Add("Status", statusCode.ToString(new CultureInfo("en-US")));
  268. response.Headers.Remove("Age");
  269. response.Headers.Remove("Expires");
  270. response.Headers.Remove("Cache-Control");
  271. response.Headers.Remove("Etag");
  272. response.Headers.Remove("Last-Modified");
  273. response.ContentType = "text/plain";
  274. if (!string.IsNullOrEmpty(ex.Message))
  275. {
  276. response.AddHeader("X-Application-Error-Code", ex.Message);
  277. }
  278. // This could fail, but try to add the stack trace as the body content
  279. try
  280. {
  281. var sb = new StringBuilder();
  282. sb.AppendLine("{");
  283. sb.AppendLine("\"ResponseStatus\":{");
  284. sb.AppendFormat(" \"ErrorCode\":{0},\n", ex.GetType().Name.EncodeJson());
  285. sb.AppendFormat(" \"Message\":{0},\n", ex.Message.EncodeJson());
  286. sb.AppendFormat(" \"StackTrace\":{0}\n", ex.StackTrace.EncodeJson());
  287. sb.AppendLine("}");
  288. sb.AppendLine("}");
  289. response.StatusCode = 500;
  290. response.ContentType = ContentType.Json;
  291. var sbBytes = sb.ToString().ToUtf8Bytes();
  292. response.OutputStream.Write(sbBytes, 0, sbBytes.Length);
  293. response.Close();
  294. }
  295. catch (Exception errorEx)
  296. {
  297. Logger.ErrorException("Error processing failed request", errorEx);
  298. }
  299. }
  300. /// <summary>
  301. /// Overridable method that can be used to implement a custom hnandler
  302. /// </summary>
  303. /// <param name="context">The context.</param>
  304. /// <exception cref="System.NotImplementedException">Cannot execute handler: + handler + at PathInfo: + httpReq.PathInfo</exception>
  305. protected override void ProcessRequest(HttpListenerContext context)
  306. {
  307. if (string.IsNullOrEmpty(context.Request.RawUrl)) return;
  308. var operationName = context.Request.GetOperationName();
  309. var httpReq = new HttpListenerRequestWrapper(operationName, context.Request);
  310. var httpRes = new HttpListenerResponseWrapper(context.Response);
  311. var handler = ServiceStackHttpHandlerFactory.GetHandler(httpReq);
  312. var serviceStackHandler = handler as IServiceStackHttpHandler;
  313. if (serviceStackHandler != null)
  314. {
  315. var restHandler = serviceStackHandler as RestHandler;
  316. if (restHandler != null)
  317. {
  318. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.Name;
  319. }
  320. serviceStackHandler.ProcessRequest(httpReq, httpRes, operationName);
  321. LogResponse(context);
  322. httpRes.Close();
  323. return;
  324. }
  325. throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
  326. }
  327. /// <summary>
  328. /// Logs the response.
  329. /// </summary>
  330. /// <param name="ctx">The CTX.</param>
  331. private void LogResponse(HttpListenerContext ctx)
  332. {
  333. var statusode = ctx.Response.StatusCode;
  334. var log = new StringBuilder();
  335. log.AppendLine(string.Format("Url: {0}", ctx.Request.Url));
  336. log.AppendLine("Headers: " + string.Join(",", ctx.Response.Headers.AllKeys.Select(k => k + "=" + ctx.Response.Headers[k])));
  337. var msg = "Http Response Sent (" + statusode + ") to " + ctx.Request.RemoteEndPoint;
  338. if (Kernel.Configuration.EnableHttpLevelLogging)
  339. {
  340. Logger.LogMultiline(msg, LogSeverity.Debug, log);
  341. }
  342. }
  343. /// <summary>
  344. /// Creates the service manager.
  345. /// </summary>
  346. /// <param name="assembliesWithServices">The assemblies with services.</param>
  347. /// <returns>ServiceManager.</returns>
  348. protected override ServiceManager CreateServiceManager(params Assembly[] assembliesWithServices)
  349. {
  350. var types = Kernel.RestServices.Select(r => r.GetType()).ToArray();
  351. return new ServiceManager(new Container(), new ServiceController(() => types));
  352. }
  353. }
  354. /// <summary>
  355. /// Class WebSocketConnectEventArgs
  356. /// </summary>
  357. public class WebSocketConnectEventArgs : EventArgs
  358. {
  359. /// <summary>
  360. /// Gets or sets the web socket.
  361. /// </summary>
  362. /// <value>The web socket.</value>
  363. public IWebSocket WebSocket { get; set; }
  364. /// <summary>
  365. /// Gets or sets the endpoint.
  366. /// </summary>
  367. /// <value>The endpoint.</value>
  368. public IPEndPoint Endpoint { get; set; }
  369. }
  370. }