Add IP origin enrichment with DB-IP and world map
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
536aee1f31
commit
3671019e60
47 files changed
+1389
-12
No files matched your search
@@ -0,0 +1,66 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Core.Networking;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
public sealed partial class DbIpEnricher : IIpEnricher, IDisposable
|
||||
{
|
||||
private static readonly TimeSpan DisposeDelay = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly IGeoIpDatabaseFactory _factory;
|
||||
private readonly ILogger<DbIpEnricher> _logger;
|
||||
private IGeoIpDatabase? _database;
|
||||
|
||||
public DbIpEnricher(IGeoIpDatabaseFactory factory, ILogger<DbIpEnricher> logger)
|
||||
{
|
||||
_factory = factory;
|
||||
_logger = logger;
|
||||
_database = factory.Open();
|
||||
}
|
||||
|
||||
public bool IsAvailable => Volatile.Read(ref _database) is not null;
|
||||
|
||||
public event EventHandler? Updated;
|
||||
|
||||
public IpOrigin? Lookup(IPAddress address)
|
||||
{
|
||||
if (PrivateNetworks.Contains(address) || Volatile.Read(ref _database) is not { } database)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return database.Find(address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
LogLookupFailed(ex, address);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void Reload()
|
||||
{
|
||||
if (_factory.Open() is not { } next)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var previous = Interlocked.Exchange(ref _database, next);
|
||||
if (previous is not null)
|
||||
{
|
||||
_ = Task.Delay(DisposeDelay).ContinueWith(_ => previous.Dispose(), TaskScheduler.Default);
|
||||
}
|
||||
|
||||
Updated?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public void Dispose() => Interlocked.Exchange(ref _database, null)?.Dispose();
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Debug, Message = "GeoIP lookup failed for {Address}")]
|
||||
private partial void LogLookupFailed(Exception exception, IPAddress address);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
internal static class DbIpFiles
|
||||
{
|
||||
public const string City = "city";
|
||||
public const string Asn = "asn";
|
||||
|
||||
public static readonly string[] Kinds = [City, Asn];
|
||||
|
||||
public static string DatabasePath(string directory, string kind) => Path.Combine(directory, $"dbip-{kind}-lite.mmdb");
|
||||
|
||||
public static string VersionPath(string directory, string kind) => DatabasePath(directory, kind) + ".version";
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MaxMind.GeoIP2" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Flypaper.Core\Flypaper.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Flypaper.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,28 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
public static class FlypaperGeoIpExtensions
|
||||
{
|
||||
public static IServiceCollection AddFlypaperGeoIp(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.Configure<GeoIpOptions>(configuration.GetSection(GeoIpOptions.SectionName));
|
||||
services.AddHttpClient(GeoIpUpdater.HttpClientName, client =>
|
||||
{
|
||||
client.Timeout = TimeSpan.FromMinutes(10);
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("Flypaper");
|
||||
});
|
||||
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
services.TryAddSingleton<IGeoIpDatabaseFactory, MaxMindGeoIpDatabaseFactory>();
|
||||
services.TryAddSingleton<DbIpEnricher>();
|
||||
services.RemoveAll<IIpEnricher>();
|
||||
services.AddSingleton<IIpEnricher>(sp => sp.GetRequiredService<DbIpEnricher>());
|
||||
services.AddHostedService<GeoIpUpdater>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
public sealed class GeoIpOptions
|
||||
{
|
||||
public const string SectionName = "Flypaper:GeoIp";
|
||||
|
||||
public string? Directory { get; set; }
|
||||
|
||||
public string BaseUrl { get; set; } = "https://download.db-ip.com/free/";
|
||||
|
||||
public TimeSpan CheckInterval { get; set; } = TimeSpan.FromDays(1);
|
||||
|
||||
public TimeSpan RetryInterval { get; set; } = TimeSpan.FromHours(1);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
internal sealed partial class GeoIpUpdater(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
IOptions<GeoIpOptions> options,
|
||||
DbIpEnricher enricher,
|
||||
TimeProvider timeProvider,
|
||||
ILogger<GeoIpUpdater> logger) : BackgroundService
|
||||
{
|
||||
public const string HttpClientName = "Flypaper.GeoIp";
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (options.Value.Directory is not { Length: > 0 })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
while (true)
|
||||
{
|
||||
var delay = options.Value.CheckInterval;
|
||||
try
|
||||
{
|
||||
if (await UpdateAsync(stoppingToken))
|
||||
{
|
||||
enricher.Reload();
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LogUpdateFailed(ex);
|
||||
delay = options.Value.RetryInterval;
|
||||
}
|
||||
|
||||
await Task.Delay(delay, timeProvider, stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task<bool> UpdateAsync(CancellationToken ct)
|
||||
{
|
||||
var directory = options.Value.Directory!;
|
||||
Directory.CreateDirectory(directory);
|
||||
|
||||
var changed = false;
|
||||
foreach (var kind in DbIpFiles.Kinds)
|
||||
{
|
||||
changed |= await UpdateDatabaseAsync(directory, kind, ct);
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
private async Task<bool> UpdateDatabaseAsync(string directory, string kind, CancellationToken ct)
|
||||
{
|
||||
var target = DbIpFiles.DatabasePath(directory, kind);
|
||||
var versionFile = DbIpFiles.VersionPath(directory, kind);
|
||||
var installed = File.Exists(target) && File.Exists(versionFile)
|
||||
? (await File.ReadAllTextAsync(versionFile, ct)).Trim()
|
||||
: null;
|
||||
|
||||
var now = timeProvider.GetUtcNow();
|
||||
foreach (var month in new[] { now, now.AddMonths(-1) }.Select(m => m.ToString("yyyy-MM", CultureInfo.InvariantCulture)))
|
||||
{
|
||||
if (month == installed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (await TryDownloadAsync(kind, month, target, ct))
|
||||
{
|
||||
await File.WriteAllTextAsync(versionFile, month, ct);
|
||||
LogDownloaded(kind, month);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (installed is null)
|
||||
{
|
||||
throw new InvalidOperationException($"No DB-IP {kind} database available for the current or previous month.");
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private async Task<bool> TryDownloadAsync(string kind, string month, string target, CancellationToken ct)
|
||||
{
|
||||
var url = $"{options.Value.BaseUrl.TrimEnd('/')}/dbip-{kind}-lite-{month}.mmdb.gz";
|
||||
using var client = httpClientFactory.CreateClient(HttpClientName);
|
||||
using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var temporary = target + ".download";
|
||||
await using (var source = await response.Content.ReadAsStreamAsync(ct))
|
||||
await using (var gzip = new GZipStream(source, CompressionMode.Decompress))
|
||||
await using (var file = File.Create(temporary))
|
||||
{
|
||||
await gzip.CopyToAsync(file, ct);
|
||||
}
|
||||
|
||||
File.Move(temporary, target, overwrite: true);
|
||||
return true;
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Downloaded DB-IP {Kind} database for {Month}")]
|
||||
private partial void LogDownloaded(string kind, string month);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "GeoIP database update failed; trap events stay without origin until the next attempt")]
|
||||
private partial void LogUpdateFailed(Exception exception);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Models;
|
||||
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
public interface IGeoIpDatabase : IDisposable
|
||||
{
|
||||
IpOrigin? Find(IPAddress address);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
public interface IGeoIpDatabaseFactory
|
||||
{
|
||||
IGeoIpDatabase? Open();
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Models;
|
||||
using MaxMind.GeoIP2;
|
||||
using MaxMind.GeoIP2.Responses;
|
||||
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
internal sealed class MaxMindGeoIpDatabase(DatabaseReader? city, DatabaseReader? asn) : IGeoIpDatabase
|
||||
{
|
||||
public IpOrigin? Find(IPAddress address)
|
||||
{
|
||||
CityResponse? cityResponse = null;
|
||||
AsnResponse? asnResponse = null;
|
||||
city?.TryCity(address, out cityResponse);
|
||||
asn?.TryAsn(address, out asnResponse);
|
||||
|
||||
if (cityResponse is null && asnResponse is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new IpOrigin(
|
||||
cityResponse?.Country.IsoCode,
|
||||
cityResponse?.Country.Name,
|
||||
cityResponse?.City.Name,
|
||||
asnResponse?.AutonomousSystemNumber,
|
||||
asnResponse?.AutonomousSystemOrganization);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
city?.Dispose();
|
||||
asn?.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using MaxMind.Db;
|
||||
using MaxMind.GeoIP2;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.GeoIp;
|
||||
|
||||
internal sealed partial class MaxMindGeoIpDatabaseFactory(
|
||||
IOptions<GeoIpOptions> options,
|
||||
ILogger<MaxMindGeoIpDatabaseFactory> logger) : IGeoIpDatabaseFactory
|
||||
{
|
||||
private static readonly string[] Locales = ["de", "en"];
|
||||
|
||||
public IGeoIpDatabase? Open()
|
||||
{
|
||||
if (options.Value.Directory is not { Length: > 0 } directory)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var city = TryOpen(DbIpFiles.DatabasePath(directory, DbIpFiles.City));
|
||||
var asn = TryOpen(DbIpFiles.DatabasePath(directory, DbIpFiles.Asn));
|
||||
return city is null && asn is null ? null : new MaxMindGeoIpDatabase(city, asn);
|
||||
}
|
||||
|
||||
private DatabaseReader? TryOpen(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return new DatabaseReader(path, Locales, FileAccessMode.MemoryMapped);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDatabaseException or IOException)
|
||||
{
|
||||
LogOpenFailed(ex, path);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not open GeoIP database {Path}")]
|
||||
private partial void LogOpenFailed(Exception exception, string path);
|
||||
}
|
||||
Reference in new issue
Block a user