HttpServer.cs 19 KB

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