LanFilteringMiddleware.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Threading.Tasks;
  5. using MediaBrowser.Common.Extensions;
  6. using MediaBrowser.Common.Net;
  7. using MediaBrowser.Controller.Configuration;
  8. using Microsoft.AspNetCore.Http;
  9. using NetworkCollection;
  10. namespace Jellyfin.Server.Middleware
  11. {
  12. /// <summary>
  13. /// Validates the LAN host IP based on application configuration.
  14. /// </summary>
  15. public class LanFilteringMiddleware
  16. {
  17. private readonly RequestDelegate _next;
  18. /// <summary>
  19. /// Initializes a new instance of the <see cref="LanFilteringMiddleware"/> class.
  20. /// </summary>
  21. /// <param name="next">The next delegate in the pipeline.</param>
  22. public LanFilteringMiddleware(RequestDelegate next)
  23. {
  24. _next = next;
  25. }
  26. /// <summary>
  27. /// Executes the middleware action.
  28. /// </summary>
  29. /// <param name="httpContext">The current HTTP context.</param>
  30. /// <param name="networkManager">The network manager.</param>
  31. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  32. /// <returns>The async task.</returns>
  33. public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager)
  34. {
  35. var host = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
  36. if (!networkManager.IsInLocalNetwork(host) && !serverConfigurationManager.Configuration.EnableRemoteAccess)
  37. {
  38. return;
  39. }
  40. await _next(httpContext).ConfigureAwait(false);
  41. }
  42. private static string NormalizeConfiguredLocalAddress(string address)
  43. {
  44. var add = address.AsSpan().Trim('/');
  45. int index = add.IndexOf('/');
  46. if (index != -1)
  47. {
  48. add = add.Slice(index + 1);
  49. }
  50. return add.TrimStart('/').ToString();
  51. }
  52. }
  53. }