LanFilteringMiddleware.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System.Net;
  2. using System.Threading.Tasks;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Controller.Configuration;
  6. using Microsoft.AspNetCore.Http;
  7. namespace Jellyfin.Api.Middleware;
  8. /// <summary>
  9. /// Validates the LAN host IP based on application configuration.
  10. /// </summary>
  11. public class LanFilteringMiddleware
  12. {
  13. private readonly RequestDelegate _next;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="LanFilteringMiddleware"/> class.
  16. /// </summary>
  17. /// <param name="next">The next delegate in the pipeline.</param>
  18. public LanFilteringMiddleware(RequestDelegate next)
  19. {
  20. _next = next;
  21. }
  22. /// <summary>
  23. /// Executes the middleware action.
  24. /// </summary>
  25. /// <param name="httpContext">The current HTTP context.</param>
  26. /// <param name="networkManager">The network manager.</param>
  27. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  28. /// <returns>The async task.</returns>
  29. public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager)
  30. {
  31. if (serverConfigurationManager.GetNetworkConfiguration().EnableRemoteAccess)
  32. {
  33. await _next(httpContext).ConfigureAwait(false);
  34. return;
  35. }
  36. var host = httpContext.GetNormalizedRemoteIP();
  37. if (!networkManager.IsInLocalNetwork(host))
  38. {
  39. // No access from network, respond with 503 instead of 200.
  40. httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
  41. return;
  42. }
  43. await _next(httpContext).ConfigureAwait(false);
  44. }
  45. }