HttpServer.cs 19 KB

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