HttpListenerHost.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. using Funq;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Controller.Net;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Server.Implementations.HttpServer.NetListener;
  7. using MediaBrowser.Server.Implementations.HttpServer.SocketSharp;
  8. using ServiceStack;
  9. using ServiceStack.Api.Swagger;
  10. using ServiceStack.Host;
  11. using ServiceStack.Host.Handlers;
  12. using ServiceStack.Host.HttpListener;
  13. using ServiceStack.Logging;
  14. using ServiceStack.Web;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Reflection;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. namespace MediaBrowser.Server.Implementations.HttpServer
  23. {
  24. public class HttpListenerHost : ServiceStackHost, IHttpServer
  25. {
  26. private string DefaultRedirectPath { get; set; }
  27. private readonly ILogger _logger;
  28. public IEnumerable<string> UrlPrefixes { get; private set; }
  29. private readonly List<IRestfulService> _restServices = new List<IRestfulService>();
  30. private IHttpListener _listener;
  31. private readonly ContainerAdapter _containerAdapter;
  32. public event EventHandler<WebSocketConnectEventArgs> WebSocketConnected;
  33. private readonly List<string> _localEndpoints = new List<string>();
  34. private readonly ReaderWriterLockSlim _localEndpointLock = new ReaderWriterLockSlim();
  35. private readonly bool _supportsNativeWebSocket;
  36. private string _certificatePath;
  37. /// <summary>
  38. /// Gets the local end points.
  39. /// </summary>
  40. /// <value>The local end points.</value>
  41. public IEnumerable<string> LocalEndPoints
  42. {
  43. get
  44. {
  45. _localEndpointLock.EnterReadLock();
  46. var list = _localEndpoints.ToList();
  47. _localEndpointLock.ExitReadLock();
  48. return list;
  49. }
  50. }
  51. public HttpListenerHost(IApplicationHost applicationHost,
  52. ILogManager logManager,
  53. string serviceName,
  54. string defaultRedirectPath,
  55. bool supportsNativeWebSocket,
  56. params Assembly[] assembliesWithServices)
  57. : base(serviceName, assembliesWithServices)
  58. {
  59. DefaultRedirectPath = defaultRedirectPath;
  60. _supportsNativeWebSocket = supportsNativeWebSocket;
  61. _logger = logManager.GetLogger("HttpServer");
  62. _containerAdapter = new ContainerAdapter(applicationHost);
  63. }
  64. public override void Configure(Container container)
  65. {
  66. HostConfig.Instance.DefaultRedirectPath = DefaultRedirectPath;
  67. HostConfig.Instance.MapExceptionToStatusCode = new Dictionary<Type, int>
  68. {
  69. {typeof (InvalidOperationException), 422},
  70. {typeof (ResourceNotFoundException), 404},
  71. {typeof (FileNotFoundException), 404},
  72. {typeof (DirectoryNotFoundException), 404},
  73. {typeof (SecurityException), 401},
  74. {typeof (UnauthorizedAccessException), 401}
  75. };
  76. HostConfig.Instance.DebugMode = true;
  77. HostConfig.Instance.LogFactory = LogManager.LogFactory;
  78. // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
  79. // Custom format allows images
  80. HostConfig.Instance.EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat;
  81. container.Adapter = _containerAdapter;
  82. Plugins.Add(new SwaggerFeature());
  83. Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization, Range, X-MediaBrowser-Token"));
  84. //Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
  85. // new SessionAuthProvider(_containerAdapter.Resolve<ISessionContext>()),
  86. //}));
  87. PreRequestFilters.Add((httpReq, httpRes) =>
  88. {
  89. //Handles Request and closes Responses after emitting global HTTP Headers
  90. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  91. {
  92. httpRes.EndRequest(); //add a 'using ServiceStack;'
  93. }
  94. });
  95. HostContext.GlobalResponseFilters.Add(new ResponseFilter(_logger).FilterResponse);
  96. }
  97. public override void OnAfterInit()
  98. {
  99. SetAppDomainData();
  100. base.OnAfterInit();
  101. }
  102. public override void OnConfigLoad()
  103. {
  104. base.OnConfigLoad();
  105. Config.HandlerFactoryPath = null;
  106. Config.MetadataRedirectPath = "metadata";
  107. }
  108. protected override ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
  109. {
  110. var types = _restServices.Select(r => r.GetType()).ToArray();
  111. return new ServiceController(this, () => types);
  112. }
  113. public virtual void SetAppDomainData()
  114. {
  115. //Required for Mono to resolve VirtualPathUtility and Url.Content urls
  116. var domain = Thread.GetDomain(); // or AppDomain.Current
  117. domain.SetData(".appDomain", "1");
  118. domain.SetData(".appVPath", "/");
  119. domain.SetData(".appPath", domain.BaseDirectory);
  120. if (string.IsNullOrEmpty(domain.GetData(".appId") as string))
  121. {
  122. domain.SetData(".appId", "1");
  123. }
  124. if (string.IsNullOrEmpty(domain.GetData(".domainId") as string))
  125. {
  126. domain.SetData(".domainId", "1");
  127. }
  128. }
  129. public override ServiceStackHost Start(string listeningAtUrlBase)
  130. {
  131. StartListener();
  132. return this;
  133. }
  134. private void OnRequestReceived(string localEndPoint)
  135. {
  136. var ignore = localEndPoint.IndexOf("::", StringComparison.OrdinalIgnoreCase) != -1 ||
  137. localEndPoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
  138. localEndPoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ||
  139. localEndPoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase);
  140. if (ignore)
  141. {
  142. return;
  143. }
  144. if (_localEndpointLock.TryEnterWriteLock(100))
  145. {
  146. var list = _localEndpoints.ToList();
  147. list.Remove(localEndPoint);
  148. list.Insert(0, localEndPoint);
  149. _localEndpointLock.ExitWriteLock();
  150. }
  151. }
  152. /// <summary>
  153. /// Starts the Web Service
  154. /// </summary>
  155. private void StartListener()
  156. {
  157. HostContext.Config.HandlerFactoryPath = ListenerRequest.GetHandlerPathIfAny(UrlPrefixes.First());
  158. _listener = GetListener();
  159. _listener.WebSocketHandler = WebSocketHandler;
  160. _listener.ErrorHandler = ErrorHandler;
  161. _listener.RequestHandler = RequestHandler;
  162. _listener.Start(UrlPrefixes);
  163. }
  164. private IHttpListener GetListener()
  165. {
  166. if (_supportsNativeWebSocket && NativeWebSocket.IsSupported)
  167. {
  168. // Certificate location is ignored here. You need to use netsh
  169. // to assign the certificate to the proper port.
  170. return new HttpListenerServer(_logger, OnRequestReceived);
  171. }
  172. return new WebSocketSharpListener(_logger, OnRequestReceived, _certificatePath);
  173. }
  174. private void WebSocketHandler(WebSocketConnectEventArgs args)
  175. {
  176. if (WebSocketConnected != null)
  177. {
  178. WebSocketConnected(this, args);
  179. }
  180. }
  181. private void ErrorHandler(Exception ex, IRequest httpReq)
  182. {
  183. try
  184. {
  185. var httpRes = httpReq.Response;
  186. if (httpRes.IsClosed)
  187. {
  188. return;
  189. }
  190. var errorResponse = new ErrorResponse
  191. {
  192. ResponseStatus = new ResponseStatus
  193. {
  194. ErrorCode = ex.GetType().GetOperationName(),
  195. Message = ex.Message,
  196. StackTrace = ex.StackTrace
  197. }
  198. };
  199. var contentType = httpReq.ResponseContentType;
  200. var serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  201. if (serializer == null)
  202. {
  203. contentType = HostContext.Config.DefaultContentType;
  204. serializer = HostContext.ContentTypes.GetResponseSerializer(contentType);
  205. }
  206. var httpError = ex as IHttpError;
  207. if (httpError != null)
  208. {
  209. httpRes.StatusCode = httpError.Status;
  210. httpRes.StatusDescription = httpError.StatusDescription;
  211. }
  212. else
  213. {
  214. httpRes.StatusCode = 500;
  215. }
  216. httpRes.ContentType = contentType;
  217. serializer(httpReq, errorResponse, httpRes);
  218. httpRes.Close();
  219. }
  220. catch (Exception errorEx)
  221. {
  222. _logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx);
  223. }
  224. }
  225. /// <summary>
  226. /// Shut down the Web Service
  227. /// </summary>
  228. public void Stop()
  229. {
  230. if (_listener != null)
  231. {
  232. _listener.Stop();
  233. }
  234. }
  235. /// <summary>
  236. /// Overridable method that can be used to implement a custom hnandler
  237. /// </summary>
  238. /// <param name="httpReq">The HTTP req.</param>
  239. /// <param name="url">The URL.</param>
  240. /// <returns>Task.</returns>
  241. protected Task RequestHandler(IHttpRequest httpReq, Uri url)
  242. {
  243. var date = DateTime.Now;
  244. var httpRes = httpReq.Response;
  245. var operationName = httpReq.OperationName;
  246. var localPath = url.LocalPath;
  247. if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
  248. {
  249. httpRes.RedirectToUrl("/../" + DefaultRedirectPath);
  250. return Task.FromResult(true);
  251. }
  252. if (string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
  253. {
  254. httpRes.RedirectToUrl("../" + DefaultRedirectPath);
  255. return Task.FromResult(true);
  256. }
  257. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  258. {
  259. httpRes.RedirectToUrl(DefaultRedirectPath);
  260. return Task.FromResult(true);
  261. }
  262. if (string.IsNullOrEmpty(localPath))
  263. {
  264. httpRes.RedirectToUrl("/" + DefaultRedirectPath);
  265. return Task.FromResult(true);
  266. }
  267. var handler = HttpHandlerFactory.GetHandler(httpReq);
  268. var remoteIp = httpReq.RemoteIp;
  269. var serviceStackHandler = handler as IServiceStackHandler;
  270. if (serviceStackHandler != null)
  271. {
  272. var restHandler = serviceStackHandler as RestHandler;
  273. if (restHandler != null)
  274. {
  275. httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
  276. }
  277. var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
  278. task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  279. //Matches Exceptions handled in HttpListenerBase.InitTask()
  280. var urlString = url.ToString();
  281. task.ContinueWith(x =>
  282. {
  283. var statusCode = httpRes.StatusCode;
  284. var duration = DateTime.Now - date;
  285. LoggerUtils.LogResponse(_logger, statusCode, urlString, remoteIp, duration);
  286. }, TaskContinuationOptions.None);
  287. return task;
  288. }
  289. return new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
  290. .AsTaskException();
  291. }
  292. /// <summary>
  293. /// Adds the rest handlers.
  294. /// </summary>
  295. /// <param name="services">The services.</param>
  296. public void Init(IEnumerable<IRestfulService> services)
  297. {
  298. _restServices.AddRange(services);
  299. ServiceController = CreateServiceController();
  300. _logger.Info("Calling ServiceStack AppHost.Init");
  301. base.Init();
  302. }
  303. public override RouteAttribute[] GetRouteAttributes(Type requestType)
  304. {
  305. var routes = base.GetRouteAttributes(requestType).ToList();
  306. var clone = routes.ToList();
  307. foreach (var route in clone)
  308. {
  309. routes.Add(new RouteAttribute(NormalizeRoutePath(route.Path), route.Verbs)
  310. {
  311. Notes = route.Notes,
  312. Priority = route.Priority,
  313. Summary = route.Summary
  314. });
  315. }
  316. return routes.ToArray();
  317. }
  318. private string NormalizeRoutePath(string path)
  319. {
  320. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  321. {
  322. return "/mediabrowser" + path;
  323. }
  324. return "mediabrowser/" + path;
  325. }
  326. /// <summary>
  327. /// Releases the specified instance.
  328. /// </summary>
  329. /// <param name="instance">The instance.</param>
  330. public override void Release(object instance)
  331. {
  332. // Leave this empty so SS doesn't try to dispose our objects
  333. }
  334. private bool _disposed;
  335. private readonly object _disposeLock = new object();
  336. protected virtual void Dispose(bool disposing)
  337. {
  338. if (_disposed) return;
  339. base.Dispose();
  340. lock (_disposeLock)
  341. {
  342. if (_disposed) return;
  343. if (disposing)
  344. {
  345. Stop();
  346. }
  347. //release unmanaged resources here...
  348. _disposed = true;
  349. }
  350. }
  351. public override void Dispose()
  352. {
  353. Dispose(true);
  354. GC.SuppressFinalize(this);
  355. }
  356. public void StartServer(IEnumerable<string> urlPrefixes, string certificatePath)
  357. {
  358. _certificatePath = certificatePath;
  359. UrlPrefixes = urlPrefixes.ToList();
  360. Start(UrlPrefixes.First());
  361. }
  362. }
  363. }