HttpListenerHost.cs 15 KB

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