HttpListenerHost.cs 14 KB

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