60 lines
1.7 KiB
C#
60 lines
1.7 KiB
C#
using Microsoft.Extensions.Options;
|
|
|
|
namespace Flypaper.Http;
|
|
|
|
public sealed class TrapMatcher
|
|
{
|
|
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 TrapMatcher(IOptions<HttpTrapOptions> options)
|
|
{
|
|
foreach (var host in options.Value.KnownHosts)
|
|
{
|
|
if (host.StartsWith("*.", StringComparison.Ordinal))
|
|
{
|
|
_hostSuffixes.Add(host[1..]);
|
|
}
|
|
else
|
|
{
|
|
_hosts.Add(host);
|
|
}
|
|
}
|
|
|
|
foreach (var path in options.Value.TrapPaths)
|
|
{
|
|
if (path.EndsWith('*'))
|
|
{
|
|
_pathPrefixes.Add(path[..^1]);
|
|
}
|
|
else
|
|
{
|
|
_paths.Add(TrimTrailingSlash(path));
|
|
}
|
|
}
|
|
}
|
|
|
|
public TrapMatch Match(string? host, string? path)
|
|
{
|
|
if (!IsKnownHost(host))
|
|
{
|
|
return TrapMatch.UnknownHost;
|
|
}
|
|
|
|
return IsTrapPath(path ?? "/") ? TrapMatch.TrapPath : TrapMatch.None;
|
|
}
|
|
|
|
private bool IsKnownHost(string? host) =>
|
|
!string.IsNullOrEmpty(host)
|
|
&& (_hosts.Contains(host)
|
|
|| _hostSuffixes.Any(suffix => host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)));
|
|
|
|
private 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;
|
|
}
|