75 lines
2.4 KiB
C#
75 lines
2.4 KiB
C#
using Microsoft.Extensions.Options;
|
|
|
|
namespace Flypaper.Http.Matching;
|
|
|
|
public sealed class TrapMatcher : IDisposable
|
|
{
|
|
private readonly IDisposable? _subscription;
|
|
private volatile Snapshot _snapshot;
|
|
|
|
public TrapMatcher(IOptionsMonitor<HttpTrapOptions> options)
|
|
{
|
|
_snapshot = new Snapshot(options.CurrentValue);
|
|
_subscription = options.OnChange(updated => _snapshot = new Snapshot(updated));
|
|
}
|
|
|
|
public TrapMatch Match(string? host, string? path)
|
|
{
|
|
var snapshot = _snapshot;
|
|
if (!snapshot.IsKnownHost(host))
|
|
{
|
|
return TrapMatch.UnknownHost;
|
|
}
|
|
|
|
return snapshot.IsTrapPath(path ?? "/") ? TrapMatch.TrapPath : TrapMatch.None;
|
|
}
|
|
|
|
public void Dispose() => _subscription?.Dispose();
|
|
|
|
private sealed class Snapshot
|
|
{
|
|
private readonly HashSet<string> _hosts = new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly List<string> _hostSuffixes = [];
|
|
private readonly HashSet<string> _paths = new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly List<string> _pathPrefixes = [];
|
|
|
|
public Snapshot(HttpTrapOptions options)
|
|
{
|
|
foreach (var host in options.KnownHosts.Where(h => !string.IsNullOrWhiteSpace(h)))
|
|
{
|
|
if (host.StartsWith("*.", StringComparison.Ordinal))
|
|
{
|
|
_hostSuffixes.Add(host[1..]);
|
|
}
|
|
else
|
|
{
|
|
_hosts.Add(host);
|
|
}
|
|
}
|
|
|
|
foreach (var path in options.TrapPaths.Where(p => !string.IsNullOrWhiteSpace(p)))
|
|
{
|
|
if (path.EndsWith('*'))
|
|
{
|
|
_pathPrefixes.Add(path[..^1]);
|
|
}
|
|
else
|
|
{
|
|
_paths.Add(TrimTrailingSlash(path));
|
|
}
|
|
}
|
|
}
|
|
|
|
public bool IsKnownHost(string? host) =>
|
|
!string.IsNullOrEmpty(host)
|
|
&& (_hosts.Contains(host)
|
|
|| _hostSuffixes.Any(suffix => host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)));
|
|
|
|
public bool IsTrapPath(string path) =>
|
|
_paths.Contains(TrimTrailingSlash(path))
|
|
|| _pathPrefixes.Any(prefix => path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
|
|
|
|
private static string TrimTrailingSlash(string path) => path.Length > 1 ? path.TrimEnd('/') : path;
|
|
}
|
|
}
|