Import Anubis v1.28.2

Replace the tree with upstream TecharoHQ/anubis v1.28.2 (a1384fbf42e3).
Masyunis customizations are re-applied in the following commits.
This commit is contained in:
sol_bot Bot committed 2026-11-28 14:52:26 +03:00
1 parent eb3e46d8d0
commit e07de898cd
573 files changed
+35846 -6807

No files matched your search

+95
View File
@@ -0,0 +1,95 @@
package geoip
import (
"fmt"
"net/http"
"net/netip"
"strings"
"github.com/TecharoHQ/anubis/internal"
"github.com/TecharoHQ/anubis/lib/policy/checker"
)
// ASNCheckerFor matches requests from any of the given autonomous systems.
func (db *DB) ASNCheckerFor(asns []uint32) checker.Impl {
asnMap := map[uint32]struct{}{}
var sb strings.Builder
fmt.Fprintln(&sb, "ASNChecker")
for _, asn := range asns {
asnMap[asn] = struct{}{}
fmt.Fprintln(&sb, "AS", asn)
}
return &ASNChecker{
db: db,
asns: asnMap,
hash: internal.FastHash(sb.String()),
}
}
type ASNChecker struct {
db *DB
asns map[uint32]struct{}
hash string
}
func (asnc *ASNChecker) Check(r *http.Request) (bool, error) {
addr, err := netip.ParseAddr(r.Header.Get("X-Real-IP"))
if err != nil {
return false, nil
}
asn, _, ok := asnc.db.LookupASN(addr)
if !ok {
return false, nil
}
_, ok = asnc.asns[asn]
return ok, nil
}
func (asnc *ASNChecker) Hash() string {
return asnc.hash
}
// GeoIPCheckerFor matches requests from any of the given countries.
func (db *DB) GeoIPCheckerFor(countries []string) checker.Impl {
countryMap := map[string]struct{}{}
var sb strings.Builder
fmt.Fprintln(&sb, "GeoIPChecker")
for _, cc := range countries {
countryMap[strings.ToLower(cc)] = struct{}{}
fmt.Fprintln(&sb, cc)
}
return &GeoIPChecker{
db: db,
countries: countryMap,
hash: sb.String(),
}
}
type GeoIPChecker struct {
db *DB
countries map[string]struct{}
hash string
}
func (gipc *GeoIPChecker) Check(r *http.Request) (bool, error) {
addr, err := netip.ParseAddr(r.Header.Get("X-Real-IP"))
if err != nil {
return false, nil
}
cc, ok := gipc.db.LookupCountry(addr)
if !ok {
return false, nil
}
_, ok = gipc.countries[cc]
return ok, nil
}
func (gipc *GeoIPChecker) Hash() string {
return gipc.hash
}
+236
View File
@@ -0,0 +1,236 @@
package geoip_test
import (
"bytes"
"net"
"net/netip"
"os"
"path/filepath"
"testing"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/TecharoHQ/anubis/lib/geoip"
"github.com/maxmind/mmdbwriter"
"github.com/maxmind/mmdbwriter/mmdbtype"
"github.com/oschwald/maxminddb-golang/v2"
)
func TestAdditionalMaxMindEditions(t *testing.T) {
for _, tt := range []struct {
name string
dbType string
kind string
record mmdbtype.Map
}{
{
name: "ISP for ASN",
dbType: "GeoIP2-ISP",
kind: "asn",
record: mmdbtype.Map{
"autonomous_system_number": mmdbtype.Uint32(13335),
"autonomous_system_organization": mmdbtype.String("Cloudflare"),
"isp": mmdbtype.String("Cloudflare"),
},
},
{
name: "City for Country",
dbType: "GeoLite2-City",
kind: "country",
record: mmdbtype.Map{
"country": mmdbtype.Map{
"iso_code": mmdbtype.String("US"),
},
},
},
} {
t.Run(tt.name, func(t *testing.T) {
tree, err := mmdbwriter.New(mmdbwriter.Options{
DatabaseType: tt.dbType,
RecordSize: 24,
})
if err != nil {
t.Fatal(err)
}
_, network, _ := net.ParseCIDR("1.1.1.0/24")
if err := tree.Insert(network, tt.record); err != nil {
t.Fatal(err)
}
var data bytes.Buffer
if _, err := tree.WriteTo(&data); err != nil {
t.Fatal(err)
}
path := filepath.Join(t.TempDir(), "test.mmdb")
if err := os.WriteFile(path, data.Bytes(), 0600); err != nil {
t.Fatal(err)
}
cfg := &config.GeoIPDatabases{}
if tt.kind == "asn" {
cfg.ASN = &config.GeoIPDatabase{Path: path}
} else {
cfg.Country = &config.GeoIPDatabase{Path: path}
}
// Verify that the normal Anubis loader accepts this edition.
db, err := geoip.New(t.Context(), discardLogger(), cfg)
if err != nil {
t.Fatalf("failed to load %s: %v", tt.dbType, err)
}
ip := netip.MustParseAddr("1.1.1.1")
if tt.kind == "asn" {
asn, org, ok := db.LookupASN(ip)
if !ok || asn != 13335 || org != "Cloudflare" {
t.Fatalf("ASN lookup failed: %d %q %v", asn, org, ok)
}
} else {
country, ok := db.LookupCountry(ip)
if !ok || country != "us" {
t.Fatalf("country lookup failed: %q %v", country, ok)
}
}
t.Logf("PASS: %s loaded and lookup succeeded", tt.dbType)
})
}
}
// TestAdditionalMaxMindEdgeCases verifies that the existing lookup
// functions handle compatible database records correctly.
func TestAdditionalMaxMindEdgeCases(t *testing.T) {
for _, tt := range []struct {
name string
ip string
asn uint32
org string
country string
asnOK bool
countryOK bool
}{
{
name: "IPv4 lookup",
ip: "1.1.1.1",
asn: 13335,
org: "Cloudflare",
country: "us",
asnOK: true,
countryOK: true,
},
{
name: "IPv6 lookup",
ip: "2606:4700::1111",
asn: 13335,
org: "Cloudflare",
country: "us",
asnOK: true,
countryOK: true,
},
{
name: "IP not in database",
ip: "8.8.8.8",
},
{
name: "private IP",
ip: "10.0.0.1",
},
} {
t.Run(tt.name, func(t *testing.T) {
asnDB := createCompatibilityDB(t, "GeoIP2-ISP", true)
countryDB := createCompatibilityDB(t, "GeoLite2-City", false)
db := geoip.FromReaders(
asnDB,
countryDB,
config.DefaultGeoIPCountryField,
)
ip := netip.MustParseAddr(tt.ip)
asn, org, asnOK := db.LookupASN(ip)
country, countryOK := db.LookupCountry(ip)
if asn != tt.asn || org != tt.org || asnOK != tt.asnOK {
t.Errorf(
"ASN: wanted (%d, %q, %v), got (%d, %q, %v)",
tt.asn, tt.org, tt.asnOK,
asn, org, asnOK,
)
}
if country != tt.country || countryOK != tt.countryOK {
t.Errorf(
"Country: wanted (%q, %v), got (%q, %v)",
tt.country, tt.countryOK,
country, countryOK,
)
}
})
}
}
func createCompatibilityDB(
t *testing.T,
dbType string,
isASN bool,
) *maxminddb.Reader {
t.Helper()
tree, err := mmdbwriter.New(mmdbwriter.Options{
DatabaseType: dbType,
RecordSize: 24,
})
if err != nil {
t.Fatal(err)
}
var record mmdbtype.Map
if isASN {
record = mmdbtype.Map{
"autonomous_system_number": mmdbtype.Uint32(13335),
"autonomous_system_organization": mmdbtype.String("Cloudflare"),
}
} else {
record = mmdbtype.Map{
"country": mmdbtype.Map{
"iso_code": mmdbtype.String("US"),
},
}
}
for _, cidr := range []string{
"1.1.1.0/24",
"2606:4700::/32",
} {
_, network, err := net.ParseCIDR(cidr)
if err != nil {
t.Fatal(err)
}
if err := tree.Insert(network, record); err != nil {
t.Fatal(err)
}
}
var buf bytes.Buffer
if _, err := tree.WriteTo(&buf); err != nil {
t.Fatal(err)
}
reader, err := maxminddb.OpenBytes(buf.Bytes())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := reader.Close(); err != nil {
t.Error(err)
}
})
return reader
}
+16
View File
@@ -0,0 +1,16 @@
package geoip
import "context"
type ctxKey struct{}
// With attaches db to ctx. A geoip block in the policy file takes precedence
// over a DB passed this way.
func With(ctx context.Context, db *DB) context.Context {
return context.WithValue(ctx, ctxKey{}, db)
}
func FromContext(ctx context.Context) (*DB, bool) {
db, ok := ctx.Value(ctxKey{}).(*DB)
return db, ok && db != nil
}
+23
View File
@@ -0,0 +1,23 @@
package geoip
import (
"context"
"log/slog"
"github.com/TecharoHQ/anubis/lib/config"
)
// Test hooks. These let geoip_test drive the update loop one step at a time.
func (db *DB) CheckASNFile(ctx context.Context, lg *slog.Logger) {
db.checkFile(ctx, lg, db.asn)
}
func (db *DB) UpdateASN(ctx context.Context, cfg *config.GeoIPAutoUpdate) (bool, error) {
up, err := newUpdater(cfg)
if err != nil {
return false, err
}
return up.update(ctx, db.asn)
}
+315
View File
@@ -0,0 +1,315 @@
// Package geoip looks up the autonomous system and country of IP addresses
// with MaxMind databases. It powers the asns and geoip bot rules and ASN
// logging.
package geoip
import (
"context"
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"net/netip"
"os"
"strings"
"sync/atomic"
"time"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/oschwald/maxminddb-golang/v2"
)
var (
ErrWrongDatabaseType = errors.New("geoip: database is the wrong type")
ErrCantOpenDatabase = errors.New("geoip: can't open database")
)
// Kind is the kind of data a database holds.
type Kind string
const (
KindASN Kind = "ASN"
KindCountry Kind = "Country"
)
// DB holds the ASN and country databases. Either may be absent. A nil *DB is
// valid and reports that nothing is loaded.
type DB struct {
asn *source
country *source
countryField config.CountryField
}
// source is one database file. The reader is swapped atomically when the file
// is updated, so lookups never lock.
type source struct {
kind Kind
path string
edition string
reader atomic.Pointer[maxminddb.Reader]
// versioned is true when automatic updates manage this database. Each
// download is then kept in its own timestamped file next to path.
versioned bool
// current, md5, and modTime are only touched during New and by the update
// goroutine. current is the file backing the active reader.
current string
md5 string
modTime time.Time
}
type asnRecord struct {
Number uint32 `maxminddb:"autonomous_system_number"`
Organization string `maxminddb:"autonomous_system_organization"`
}
type countryRecord struct {
Country struct {
ISOCode string `maxminddb:"iso_code"`
} `maxminddb:"country"`
RegisteredCountry struct {
ISOCode string `maxminddb:"iso_code"`
} `maxminddb:"registered_country"`
}
// New opens the databases in cfg. When auto_update is set, missing databases
// are downloaded before New returns. A background goroutine keeps the
// databases fresh until ctx is canceled.
func New(ctx context.Context, lg *slog.Logger, cfg *config.GeoIPDatabases) (*DB, error) {
lg = lg.With("at", "geoip")
db := &DB{
countryField: cfg.Country.GetCountryField(),
}
var up *updater
if cfg.AutoUpdate != nil {
var err error
up, err = newUpdater(cfg.AutoUpdate)
if err != nil {
return nil, err
}
}
var errs []error
if cfg.ASN != nil {
db.asn = &source{kind: KindASN, path: cfg.ASN.Path, edition: cfg.ASNEditionID(), versioned: up != nil}
}
if cfg.Country != nil {
db.country = &source{kind: KindCountry, path: cfg.Country.Path, edition: cfg.CountryEditionID(), versioned: up != nil}
}
for _, src := range db.sources() {
err := src.load()
if errors.Is(err, fs.ErrNotExist) && up != nil {
lg.InfoContext(ctx, "database not found on disk, downloading it", "edition", src.edition, "path", src.path)
_, err = up.update(ctx, src)
}
if err != nil {
errs = append(errs, err)
continue
}
if src.versioned {
if err := src.cleanup(); err != nil {
lg.DebugContext(ctx, "can't clean up old geoip databases yet", "edition", src.edition, "err", err)
}
}
}
if len(errs) != 0 {
return nil, errors.Join(errs...)
}
go db.run(ctx, lg, up)
return db, nil
}
// FromReaders builds a DB from already opened readers. It does not watch
// or update anything. It is meant for tests and embedders.
func FromReaders(asn, country *maxminddb.Reader, countryField config.CountryField) *DB {
db := &DB{countryField: countryField}
if asn != nil {
db.asn = &source{kind: KindASN}
db.asn.reader.Store(asn)
}
if country != nil {
db.country = &source{kind: KindCountry}
db.country.reader.Store(country)
}
return db
}
func (db *DB) sources() []*source {
var result []*source
for _, src := range []*source{db.asn, db.country} {
if src != nil {
result = append(result, src)
}
}
return result
}
// HasASN reports whether an ASN database is configured.
func (db *DB) HasASN() bool {
return db != nil && db.asn != nil
}
// HasCountry reports whether a country database is configured.
func (db *DB) HasCountry() bool {
return db != nil && db.country != nil
}
// LookupASN returns the autonomous system for addr. ok is false when the
// address is not publicly announced (such as private or reserved ranges) or
// no ASN database is loaded.
func (db *DB) LookupASN(addr netip.Addr) (asn uint32, org string, ok bool) {
if !db.HasASN() {
return 0, "", false
}
rdr := db.asn.reader.Load()
if rdr == nil {
return 0, "", false
}
var rec asnRecord
res := rdr.Lookup(addr.Unmap())
if !res.Found() {
return 0, "", false
}
if err := res.Decode(&rec); err != nil || rec.Number == 0 {
return 0, "", false
}
return rec.Number, rec.Organization, true
}
// LookupCountry returns the lowercase ISO 3166-1 alpha-2 country code for
// addr. ok is false when the address has no country or no country database is
// loaded.
func (db *DB) LookupCountry(addr netip.Addr) (cc string, ok bool) {
if !db.HasCountry() {
return "", false
}
rdr := db.country.reader.Load()
if rdr == nil {
return "", false
}
var rec countryRecord
res := rdr.Lookup(addr.Unmap())
if !res.Found() {
return "", false
}
if err := res.Decode(&rec); err != nil {
return "", false
}
primary, fallback := rec.Country.ISOCode, rec.RegisteredCountry.ISOCode
if db.countryField == config.CountryFieldRegisteredCountry {
primary, fallback = fallback, primary
}
switch {
case primary != "":
return strings.ToLower(primary), true
case fallback != "":
return strings.ToLower(fallback), true
default:
return "", false
}
}
// load maps the database file and swaps it in. Versioned sources load their
// newest download, falling back to path so an existing file can seed them.
func (src *source) load() error {
fname := src.path
if src.versioned {
if latest, ok := src.latest(); ok {
fname = latest
}
}
fi, err := os.Stat(fname)
if err != nil {
return fmt.Errorf("%w %s: %w", ErrCantOpenDatabase, fname, err)
}
sum, err := fileMD5(fname)
if err != nil {
return fmt.Errorf("%w %s: %w", ErrCantOpenDatabase, fname, err)
}
rdr, err := src.open(fname)
if err != nil {
return fmt.Errorf("%w %s: %w", ErrCantOpenDatabase, fname, err)
}
src.install(rdr, fname, sum)
src.modTime = fi.ModTime()
return nil
}
// open mmaps the database at path and checks that it is the right kind.
func (src *source) open(path string) (*maxminddb.Reader, error) {
rdr, err := maxminddb.Open(path)
if err != nil {
return nil, err
}
dbType := rdr.Metadata.DatabaseType
validType := strings.Contains(dbType, string(src.kind)) ||
(src.kind == "ASN" && dbType == "GeoIP2-ISP") ||
(src.kind == "Country" && dbType == "GeoLite2-City")
if !validType {
rdr.Close() //nolint:errcheck
return nil, fmt.Errorf("%w: wanted a %s database, got %q", ErrWrongDatabaseType, src.kind, rdr.Metadata.DatabaseType)
}
return rdr, nil
}
// install makes rdr the active reader.
//
// The old reader is not closed here because a lookup may still be using it.
// maxminddb unmaps a reader's file when the reader is garbage collected, and
// every lookup result keeps its reader reachable, so the old mapping lives
// exactly as long as something needs it.
func (src *source) install(rdr *maxminddb.Reader, fname, sum string) {
src.reader.Store(rdr)
src.current = fname
src.md5 = sum
databaseBuildTime.WithLabelValues(string(src.kind)).Set(float64(rdr.Metadata.BuildEpoch))
}
func fileMD5(path string) (string, error) {
fin, err := os.Open(path)
if err != nil {
return "", err
}
defer fin.Close() //nolint:errcheck
h := md5.New()
if _, err := io.Copy(h, fin); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
+609
View File
@@ -0,0 +1,609 @@
package geoip_test
import (
"archive/tar"
"bytes"
"compress/gzip"
"crypto/md5"
"encoding/hex"
"encoding/json"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"net/netip"
"os"
"path/filepath"
"testing"
"time"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/TecharoHQ/anubis/lib/geoip"
"github.com/TecharoHQ/anubis/lib/geoip/geoiptest"
"github.com/maxmind/geoipupdate/v8/client"
"github.com/oschwald/maxminddb-golang/v2"
)
func discardLogger() *slog.Logger {
return slog.New(slog.DiscardHandler)
}
func TestLookup(t *testing.T) {
db := geoiptest.DB(t)
for _, tt := range []struct {
name string
ip string
asn uint32
org string
asnOK bool
country string
ccOK bool
}{
{name: "cloudflare v4", ip: "1.1.1.1", asn: 13335, org: "Cloudflare, Inc.", asnOK: true, country: "us", ccOK: true},
{name: "cloudflare v6", ip: "2606:4700::1111", asn: 13335, org: "Cloudflare, Inc.", asnOK: true, country: "us", ccOK: true},
{name: "ipv4 mapped ipv6", ip: "::ffff:1.1.1.1", asn: 13335, org: "Cloudflare, Inc.", asnOK: true, country: "us", ccOK: true},
{name: "registered country fallback", ip: "1.0.0.1", asn: 13335, org: "Cloudflare, Inc.", asnOK: true, country: "au", ccOK: true},
{name: "canada", ip: "2.2.2.2", asn: 420, org: "test canada", asnOK: true, country: "ca", ccOK: true},
{name: "not in database", ip: "8.8.8.8"},
{name: "private", ip: "10.0.0.1"},
{name: "loopback", ip: "127.0.0.1"},
{name: "ipv6 loopback", ip: "::1"},
} {
t.Run(tt.name, func(t *testing.T) {
addr := netip.MustParseAddr(tt.ip)
asn, org, ok := db.LookupASN(addr)
if ok != tt.asnOK || asn != tt.asn || org != tt.org {
t.Errorf("LookupASN: want (%d, %q, %v), got (%d, %q, %v)", tt.asn, tt.org, tt.asnOK, asn, org, ok)
}
cc, ok := db.LookupCountry(addr)
if ok != tt.ccOK || cc != tt.country {
t.Errorf("LookupCountry: want (%q, %v), got (%q, %v)", tt.country, tt.ccOK, cc, ok)
}
})
}
}
func TestLookupCountryField(t *testing.T) {
country, err := maxminddb.OpenBytes(geoiptest.CountryDatabase(t, geoiptest.DefaultRecords))
if err != nil {
t.Fatal(err)
}
for _, tt := range []struct {
name string
field config.CountryField
ip string
want string
}{
{name: "country", field: config.CountryFieldCountry, ip: "57.141.0.1", want: "us"},
{name: "registered country", field: config.CountryFieldRegisteredCountry, ip: "57.141.0.1", want: "ie"},
{name: "registered country falls back to country", field: config.CountryFieldRegisteredCountry, ip: "1.1.1.1", want: "us"},
{name: "country falls back to registered country", field: config.CountryFieldCountry, ip: "1.0.0.1", want: "au"},
} {
t.Run(tt.name, func(t *testing.T) {
db := geoip.FromReaders(nil, country, tt.field)
got, ok := db.LookupCountry(netip.MustParseAddr(tt.ip))
if !ok || got != tt.want {
t.Errorf("want %q, got %q (ok: %v)", tt.want, got, ok)
}
})
}
}
func TestNilDB(t *testing.T) {
var db *geoip.DB
if db.HasASN() || db.HasCountry() {
t.Error("nil DB should have no databases")
}
if _, _, ok := db.LookupASN(netip.MustParseAddr("1.1.1.1")); ok {
t.Error("nil DB LookupASN should not find anything")
}
if _, ok := db.LookupCountry(netip.MustParseAddr("1.1.1.1")); ok {
t.Error("nil DB LookupCountry should not find anything")
}
}
func TestCheckers(t *testing.T) {
db := geoiptest.DB(t)
asnc := db.ASNCheckerFor([]uint32{13335})
gipc := db.GeoIPCheckerFor([]string{"CA"})
for _, tt := range []struct {
name string
ip string
wantASN bool
wantGeoIP bool
}{
{name: "cloudflare", ip: "1.1.1.1", wantASN: true},
{name: "canada", ip: "2.2.2.2", wantGeoIP: true},
{name: "not in database", ip: "8.8.8.8"},
{name: "private", ip: "10.0.0.1"},
{name: "not an IP", ip: "taco"},
{name: "empty", ip: ""},
} {
t.Run(tt.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.Header.Set("X-Real-IP", tt.ip)
got, err := asnc.Check(r)
if err != nil {
t.Fatal(err)
}
if got != tt.wantASN {
t.Errorf("ASNChecker: want %v, got %v", tt.wantASN, got)
}
got, err = gipc.Check(r)
if err != nil {
t.Fatal(err)
}
if got != tt.wantGeoIP {
t.Errorf("GeoIPChecker: want %v, got %v", tt.wantGeoIP, got)
}
})
}
if asnc.Hash() == db.ASNCheckerFor([]uint32{420}).Hash() {
t.Error("ASN checkers for different ASNs have the same hash")
}
if gipc.Hash() == db.GeoIPCheckerFor([]string{"US"}).Hash() {
t.Error("GeoIP checkers for different countries have the same hash")
}
}
func TestNew(t *testing.T) {
asnPath, countryPath := geoiptest.WriteFixtures(t)
for _, tt := range []struct {
name string
cfg *config.GeoIPDatabases
err error
}{
{
name: "both",
cfg: &config.GeoIPDatabases{
ASN: &config.GeoIPDatabase{Path: asnPath},
Country: &config.GeoIPDatabase{Path: countryPath},
},
},
{
name: "asn only",
cfg: &config.GeoIPDatabases{
ASN: &config.GeoIPDatabase{Path: asnPath},
},
},
{
name: "missing file",
cfg: &config.GeoIPDatabases{
ASN: &config.GeoIPDatabase{Path: filepath.Join(t.TempDir(), "nope.mmdb")},
},
err: os.ErrNotExist,
},
{
name: "swapped paths",
cfg: &config.GeoIPDatabases{
ASN: &config.GeoIPDatabase{Path: countryPath},
Country: &config.GeoIPDatabase{Path: asnPath},
},
err: geoip.ErrWrongDatabaseType,
},
} {
t.Run(tt.name, func(t *testing.T) {
db, err := geoip.New(t.Context(), discardLogger(), tt.cfg)
if tt.err != nil {
if !errors.Is(err, tt.err) {
t.Logf("want: %v", tt.err)
t.Logf("got: %v", err)
t.Fatal("got wrong error")
}
return
}
if err != nil {
t.Fatal(err)
}
if _, _, ok := db.LookupASN(netip.MustParseAddr("1.1.1.1")); !ok {
t.Error("wanted ASN lookup to succeed")
}
if got := db.HasCountry(); got != (tt.cfg.Country != nil) {
t.Errorf("HasCountry: want %v, got %v", tt.cfg.Country != nil, got)
}
})
}
}
var updatedRecords = append([]geoiptest.Record{
{CIDR: "3.3.3.0/24", ASN: 999, Organization: "new network"},
}, geoiptest.DefaultRecords...)
// replaceFile swaps in new contents at path with a rename, the way
// geoipupdate does. Writing a mapped database in place would change the
// memory of the reader that is already loaded.
func replaceFile(t *testing.T, path string, data []byte) {
t.Helper()
tmp := path + ".new"
if err := os.WriteFile(tmp, data, 0o644); err != nil {
t.Fatal(err)
}
if err := os.Rename(tmp, path); err != nil {
t.Fatal(err)
}
}
func TestReloadFromDisk(t *testing.T) {
asnPath, _ := geoiptest.WriteFixtures(t)
db, err := geoip.New(t.Context(), discardLogger(), &config.GeoIPDatabases{
ASN: &config.GeoIPDatabase{Path: asnPath},
})
if err != nil {
t.Fatal(err)
}
addr := netip.MustParseAddr("3.3.3.3")
if _, _, ok := db.LookupASN(addr); ok {
t.Fatal("3.3.3.3 should not be in the first database")
}
// Unchanged file: nothing happens.
db.CheckASNFile(t.Context(), discardLogger())
replaceFile(t, asnPath, geoiptest.ASNDatabase(t, updatedRecords))
future := time.Now().Add(time.Hour)
if err := os.Chtimes(asnPath, future, future); err != nil {
t.Fatal(err)
}
db.CheckASNFile(t.Context(), discardLogger())
if asn, _, ok := db.LookupASN(addr); !ok || asn != 999 {
t.Fatalf("wanted reloaded database to find AS999, got %d (ok: %v)", asn, ok)
}
// A corrupt file must not replace the loaded database.
replaceFile(t, asnPath, []byte("not a database"))
future = future.Add(time.Hour)
if err := os.Chtimes(asnPath, future, future); err != nil {
t.Fatal(err)
}
db.CheckASNFile(t.Context(), discardLogger())
if asn, _, ok := db.LookupASN(addr); !ok || asn != 999 {
t.Fatalf("corrupt file replaced the loaded database, got %d (ok: %v)", asn, ok)
}
}
// fakeMaxMind serves the parts of the MaxMind update API that geoipupdate's
// client uses.
type fakeMaxMind struct {
db []byte
md5 string
status int
requests int
}
func newFakeMaxMind(t *testing.T, db []byte) (*fakeMaxMind, *httptest.Server) {
t.Helper()
sum := md5.Sum(db)
f := &fakeMaxMind{db: db, md5: hex.EncodeToString(sum[:]), status: http.StatusOK}
mux := http.NewServeMux()
mux.HandleFunc("GET /geoip/updates/metadata", func(w http.ResponseWriter, r *http.Request) {
f.requests++
user, pass, ok := r.BasicAuth()
if !ok || user != "1234" || pass != "hunter2" || f.status != http.StatusOK {
status := f.status
if status == http.StatusOK {
status = http.StatusUnauthorized
}
http.Error(w, `{"code":"INVALID_LICENSE_KEY"}`, status)
return
}
json.NewEncoder(w).Encode(map[string]any{ //nolint:errcheck
"databases": []map[string]string{{
"date": "2026-09-27",
"edition_id": r.URL.Query().Get("edition_id"),
"md5": f.md5,
}},
})
})
mux.HandleFunc("GET /geoip/databases/{edition}/download", func(w http.ResponseWriter, r *http.Request) {
edition := r.PathValue("edition")
var buf bytes.Buffer
gw := gzip.NewWriter(&buf)
tw := tar.NewWriter(gw)
name := edition + "_20260927/" + edition + ".mmdb"
tw.WriteHeader(&tar.Header{Name: name, Mode: 0o644, Size: int64(len(f.db))}) //nolint:errcheck
tw.Write(f.db) //nolint:errcheck
tw.Close() //nolint:errcheck
gw.Close() //nolint:errcheck
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Write(buf.Bytes()) //nolint:errcheck
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return f, srv
}
func autoUpdateConfig(t *testing.T, endpoint string) *config.GeoIPAutoUpdate {
t.Helper()
t.Setenv("ANUBIS_TEST_MAXMIND_LICENSE_KEY", "hunter2")
return &config.GeoIPAutoUpdate{
AccountID: 1234,
LicenseKeyEnv: "ANUBIS_TEST_MAXMIND_LICENSE_KEY",
Endpoint: &endpoint,
}
}
func TestNewDownloadsMissingDatabase(t *testing.T) {
_, srv := newFakeMaxMind(t, geoiptest.ASNDatabase(t, geoiptest.DefaultRecords))
asnPath := filepath.Join(t.TempDir(), "sub", "GeoLite2-ASN.mmdb")
db, err := geoip.New(t.Context(), discardLogger(), &config.GeoIPDatabases{
ASN: &config.GeoIPDatabase{Path: asnPath},
AutoUpdate: autoUpdateConfig(t, srv.URL),
})
if err != nil {
t.Fatal(err)
}
if _, _, ok := db.LookupASN(netip.MustParseAddr("1.1.1.1")); !ok {
t.Error("wanted downloaded database to be loaded")
}
if _, err := os.Stat(asnPath); !errors.Is(err, os.ErrNotExist) {
t.Errorf("the configured path should not be written, stat: %v", err)
}
versions := versionFiles(t, asnPath)
if len(versions) != 1 {
t.Fatalf("wanted one timestamped download, got %v", versions)
}
}
// versionFiles lists the timestamped downloads and staging files next to path.
func versionFiles(t *testing.T, path string) []string {
t.Helper()
matches, err := filepath.Glob(path + ".*")
if err != nil {
t.Fatal(err)
}
return matches
}
func TestUpdate(t *testing.T) {
for _, tt := range []struct {
name string
serve func(t *testing.T) []byte
badMD5 bool
status int
wantUpdated bool
wantAS999 bool
wantErr bool
wantHTTP int
}{
{
name: "no update available",
serve: func(t *testing.T) []byte { return geoiptest.ASNDatabase(t, geoiptest.DefaultRecords) },
},
{
name: "update available",
serve: func(t *testing.T) []byte { return geoiptest.ASNDatabase(t, updatedRecords) },
wantUpdated: true,
wantAS999: true,
},
{
name: "corrupt download",
serve: func(t *testing.T) []byte { return []byte("not a database") },
wantErr: true,
},
{
name: "wrong database type",
serve: func(t *testing.T) []byte { return geoiptest.CountryDatabase(t, updatedRecords) },
wantErr: true,
},
{
name: "checksum mismatch",
serve: func(t *testing.T) []byte { return geoiptest.ASNDatabase(t, updatedRecords) },
badMD5: true,
wantErr: true,
},
{
name: "bad license key",
serve: func(t *testing.T) []byte { return geoiptest.ASNDatabase(t, updatedRecords) },
status: http.StatusUnauthorized,
wantErr: true,
wantHTTP: http.StatusUnauthorized,
},
} {
t.Run(tt.name, func(t *testing.T) {
asnPath, _ := geoiptest.WriteFixtures(t)
original, err := os.ReadFile(asnPath)
if err != nil {
t.Fatal(err)
}
fake, srv := newFakeMaxMind(t, tt.serve(t))
if tt.badMD5 {
fake.md5 = "00000000000000000000000000000000"
}
if tt.status != 0 {
fake.status = tt.status
}
cfg := autoUpdateConfig(t, srv.URL)
db, err := geoip.New(t.Context(), discardLogger(), &config.GeoIPDatabases{
ASN: &config.GeoIPDatabase{Path: asnPath},
AutoUpdate: cfg,
})
if err != nil {
t.Fatal(err)
}
updated, err := db.UpdateASN(t.Context(), cfg)
if (err != nil) != tt.wantErr {
t.Fatalf("wantErr: %v, got: %v", tt.wantErr, err)
}
if tt.wantHTTP != 0 {
var httpErr client.HTTPError
if !errors.As(err, &httpErr) || httpErr.StatusCode != tt.wantHTTP {
t.Errorf("wanted HTTP %d error, got: %v", tt.wantHTTP, err)
}
}
if updated != tt.wantUpdated {
t.Errorf("updated: want %v, got %v", tt.wantUpdated, updated)
}
_, _, found := db.LookupASN(netip.MustParseAddr("3.3.3.3"))
if found != tt.wantAS999 {
t.Errorf("AS999 lookup: want %v, got %v", tt.wantAS999, found)
}
if _, _, ok := db.LookupASN(netip.MustParseAddr("1.1.1.1")); !ok {
t.Error("existing data should still be served")
}
onDisk, err := os.ReadFile(asnPath)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(onDisk, original) {
t.Error("the configured path was modified, updates must go to new files")
}
versions := versionFiles(t, asnPath)
wantVersions := 0
if tt.wantUpdated {
wantVersions = 1
}
if len(versions) != wantVersions {
t.Errorf("timestamped files: want %d, got %v", wantVersions, versions)
}
})
}
}
func TestContext(t *testing.T) {
if _, ok := geoip.FromContext(t.Context()); ok {
t.Error("empty context should not have a DB")
}
db := geoiptest.DB(t)
got, ok := geoip.FromContext(geoip.With(t.Context(), db))
if !ok || got != db {
t.Error("wanted DB back from context")
}
if _, ok := geoip.FromContext(geoip.With(t.Context(), nil)); ok {
t.Error("nil DB in context should not count")
}
}
func TestVersionedStartupAndCleanup(t *testing.T) {
asnPath, _ := geoiptest.WriteFixtures(t)
older := asnPath + ".1700000000"
newer := asnPath + ".1800000000"
for fname, records := range map[string][]geoiptest.Record{
older: geoiptest.DefaultRecords,
newer: updatedRecords,
} {
if err := os.WriteFile(fname, geoiptest.ASNDatabase(t, records), 0o644); err != nil {
t.Fatal(err)
}
}
// Files that must be ignored when picking the newest version.
for _, fname := range []string{asnPath + ".1900000000.tmp", asnPath + ".bak", asnPath + ".1900000000x"} {
if err := os.WriteFile(fname, []byte("junk"), 0o644); err != nil {
t.Fatal(err)
}
}
_, srv := newFakeMaxMind(t, geoiptest.ASNDatabase(t, updatedRecords))
cfg := autoUpdateConfig(t, srv.URL)
db, err := geoip.New(t.Context(), discardLogger(), &config.GeoIPDatabases{
ASN: &config.GeoIPDatabase{Path: asnPath},
AutoUpdate: cfg,
})
if err != nil {
t.Fatal(err)
}
if asn, _, ok := db.LookupASN(netip.MustParseAddr("3.3.3.3")); !ok || asn != 999 {
t.Fatalf("wanted newest version to be loaded, got AS%d (ok: %v)", asn, ok)
}
for fname, want := range map[string]bool{
asnPath: true,
newer: true,
older: false,
asnPath + ".1900000000.tmp": false,
asnPath + ".bak": true,
asnPath + ".1900000000x": true,
} {
_, err := os.Stat(fname)
if got := err == nil; got != want {
t.Errorf("%s exists: want %v, got %v", filepath.Base(fname), want, got)
}
}
// The server has the same database, so no new file appears.
updated, err := db.UpdateASN(t.Context(), cfg)
if err != nil || updated {
t.Fatalf("wanted no update, got updated=%v err=%v", updated, err)
}
}
func TestVersionAfterClockStep(t *testing.T) {
asnPath, _ := geoiptest.WriteFixtures(t)
// A version from the future, as if the clock stepped backwards since.
future := asnPath + ".9999999999"
if err := os.WriteFile(future, geoiptest.ASNDatabase(t, geoiptest.DefaultRecords), 0o644); err != nil {
t.Fatal(err)
}
_, srv := newFakeMaxMind(t, geoiptest.ASNDatabase(t, updatedRecords))
cfg := autoUpdateConfig(t, srv.URL)
db, err := geoip.New(t.Context(), discardLogger(), &config.GeoIPDatabases{
ASN: &config.GeoIPDatabase{Path: asnPath},
AutoUpdate: cfg,
})
if err != nil {
t.Fatal(err)
}
if updated, err := db.UpdateASN(t.Context(), cfg); err != nil || !updated {
t.Fatalf("wanted an update, got updated=%v err=%v", updated, err)
}
if _, err := os.Stat(asnPath + ".10000000000"); err != nil {
t.Errorf("wanted the new version to sort after the future one: %v", err)
}
}
+138
View File
@@ -0,0 +1,138 @@
// Package geoiptest builds small MaxMind databases for tests.
package geoiptest
import (
"bytes"
"context"
"net"
"os"
"path/filepath"
"testing"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/TecharoHQ/anubis/lib/geoip"
"github.com/maxmind/mmdbwriter"
"github.com/maxmind/mmdbwriter/mmdbtype"
"github.com/oschwald/maxminddb-golang/v2"
)
// Record is one network in a fixture database.
type Record struct {
CIDR string
ASN uint32
Organization string
Country string
RegisteredCountry string
}
// DefaultRecords are the networks in the default fixtures. 10.0.0.0/8 and
// other reserved ranges are left out, like in the real databases.
var DefaultRecords = []Record{
{CIDR: "1.1.1.0/24", ASN: 13335, Organization: "Cloudflare, Inc.", Country: "US", RegisteredCountry: "US"},
{CIDR: "1.0.0.0/24", ASN: 13335, Organization: "Cloudflare, Inc.", RegisteredCountry: "AU"},
{CIDR: "2.2.2.0/24", ASN: 420, Organization: "test canada", Country: "CA", RegisteredCountry: "CA"},
{CIDR: "57.141.0.0/24", ASN: 32934, Organization: "Facebook, Inc.", Country: "US", RegisteredCountry: "IE"},
{CIDR: "2606:4700::/32", ASN: 13335, Organization: "Cloudflare, Inc.", Country: "US", RegisteredCountry: "US"},
}
// ASNDatabase returns the bytes of an ASN database holding records.
func ASNDatabase(t testing.TB, records []Record) []byte {
t.Helper()
return build(t, "GeoLite2-ASN", records, func(r Record) mmdbtype.Map {
return mmdbtype.Map{
"autonomous_system_number": mmdbtype.Uint32(r.ASN),
"autonomous_system_organization": mmdbtype.String(r.Organization),
}
})
}
// CountryDatabase returns the bytes of a country database holding records.
func CountryDatabase(t testing.TB, records []Record) []byte {
t.Helper()
return build(t, "GeoLite2-Country", records, func(r Record) mmdbtype.Map {
result := mmdbtype.Map{}
if r.Country != "" {
result["country"] = mmdbtype.Map{"iso_code": mmdbtype.String(r.Country)}
}
if r.RegisteredCountry != "" {
result["registered_country"] = mmdbtype.Map{"iso_code": mmdbtype.String(r.RegisteredCountry)}
}
return result
})
}
// WriteFixtures writes the default ASN and country databases into a temporary
// directory and returns their paths.
func WriteFixtures(t testing.TB) (asnPath, countryPath string) {
t.Helper()
dir := t.TempDir()
asnPath = filepath.Join(dir, "GeoLite2-ASN.mmdb")
countryPath = filepath.Join(dir, "GeoLite2-Country.mmdb")
if err := os.WriteFile(asnPath, ASNDatabase(t, DefaultRecords), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(countryPath, CountryDatabase(t, DefaultRecords), 0o644); err != nil {
t.Fatal(err)
}
return asnPath, countryPath
}
// DB returns a DB backed by the default fixtures.
func DB(t testing.TB) *geoip.DB {
t.Helper()
asn, err := maxminddb.OpenBytes(ASNDatabase(t, DefaultRecords))
if err != nil {
t.Fatal(err)
}
country, err := maxminddb.OpenBytes(CountryDatabase(t, DefaultRecords))
if err != nil {
t.Fatal(err)
}
return geoip.FromReaders(asn, country, config.DefaultGeoIPCountryField)
}
// WithMockGeoIP returns a context carrying a DB backed by the default fixtures.
func WithMockGeoIP(t testing.TB) context.Context {
t.Helper()
return geoip.With(t.Context(), DB(t))
}
func build(t testing.TB, dbType string, records []Record, value func(Record) mmdbtype.Map) []byte {
t.Helper()
tree, err := mmdbwriter.New(mmdbwriter.Options{
DatabaseType: dbType,
RecordSize: 24,
})
if err != nil {
t.Fatal(err)
}
for _, r := range records {
_, network, err := net.ParseCIDR(r.CIDR)
if err != nil {
t.Fatal(err)
}
if err := tree.Insert(network, value(r)); err != nil {
t.Fatal(err)
}
}
var buf bytes.Buffer
if _, err := tree.WriteTo(&buf); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
+18
View File
@@ -0,0 +1,18 @@
package geoip
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
var (
databaseBuildTime = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "anubis_geoip_database_build_timestamp_seconds",
Help: "Build time of the loaded geoip database as a Unix timestamp",
}, []string{"kind"})
updateErrors = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "anubis_geoip_update_errors_total",
Help: "Number of failed geoip database updates or reloads",
}, []string{"kind"})
)
+237
View File
@@ -0,0 +1,237 @@
package geoip
import (
"context"
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"time"
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/maxmind/geoipupdate/v8/client"
)
var (
ErrChecksumMismatch = errors.New("geoip: downloaded database checksum does not match")
ErrDatabaseTooLarge = errors.New("geoip: downloaded database is too large")
)
const (
// maxDatabaseSize caps how much of a download is written to disk.
// GeoIP2-City, the largest common edition, is well under this.
maxDatabaseSize = 512 << 20
// fileCheckInterval is how often database files are checked for changes
// when automatic updates are off.
fileCheckInterval = 5 * time.Minute
)
type updater struct {
cli client.Client
interval time.Duration
}
func newUpdater(cfg *config.GeoIPAutoUpdate) (*updater, error) {
opts := []client.Option{
client.WithHTTPClient(&http.Client{
Timeout: 5 * time.Minute,
Transport: userAgentTransport{next: http.DefaultTransport},
}),
}
if cfg.Endpoint != nil {
opts = append(opts, client.WithEndpoint(*cfg.Endpoint))
}
cli, err := client.New(cfg.AccountID, cfg.LicenseKey(), opts...)
if err != nil {
return nil, fmt.Errorf("geoip: can't create MaxMind update client: %w", err)
}
return &updater{
cli: cli,
interval: cfg.GetInterval(),
}, nil
}
// update checks MaxMind for a newer copy of src. When there is one, it saves
// the download as a new file named after the Unix timestamp of the update,
// verifies it, and swaps it in. It never renames over or rewrites a file that
// is mapped. It reports whether a new database was installed.
func (u *updater) update(ctx context.Context, src *source) (bool, error) {
resp, err := u.cli.Download(ctx, src.edition, src.md5)
if err != nil {
return false, fmt.Errorf("geoip: can't download %s: %w", src.edition, err)
}
defer resp.Reader.Close() //nolint:errcheck
if !resp.UpdateAvailable {
return false, nil
}
fname := src.nextVersionPath(time.Now().Unix())
gotMD5, err := writeVersion(fname, resp.Reader)
if err != nil {
return false, fmt.Errorf("geoip: can't save %s download: %w", src.edition, err)
}
if gotMD5 != resp.MD5 {
os.Remove(fname) //nolint:errcheck
return false, fmt.Errorf("%w: %s: want %s, got %s", ErrChecksumMismatch, src.edition, resp.MD5, gotMD5)
}
rdr, err := src.open(fname)
if err != nil {
os.Remove(fname) //nolint:errcheck
return false, fmt.Errorf("geoip: downloaded %s is not valid: %w", src.edition, err)
}
src.install(rdr, fname, gotMD5)
return true, nil
}
// nextVersionPath returns the file name for a download made at ts. If that
// name is taken, such as after the clock steps backwards, it moves forward to
// the next free second so the new file still sorts as the newest.
func (src *source) nextVersionPath(ts int64) string {
if latest, ok := src.latest(); ok {
if lts, ok := parseVersion(filepath.Base(latest), filepath.Base(src.path)+"."); ok && lts >= ts {
ts = lts + 1
}
}
return src.versionPath(ts)
}
// writeVersion streams r into a staging file, syncs it, and renames it to
// fname. Nothing maps fname yet, so the rename is safe on every platform. It
// returns the MD5 checksum of what was written.
func writeVersion(fname string, r io.Reader) (string, error) {
if err := os.MkdirAll(filepath.Dir(fname), 0o755); err != nil {
return "", err
}
tmpName := fname + tmpSuffix
tmp, err := os.OpenFile(tmpName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
if err != nil {
return "", err
}
h := md5.New()
n, err := io.Copy(io.MultiWriter(tmp, h), io.LimitReader(r, maxDatabaseSize+1))
if err == nil && n > maxDatabaseSize {
err = fmt.Errorf("%w: larger than %d bytes", ErrDatabaseTooLarge, maxDatabaseSize)
}
if err == nil {
err = tmp.Sync()
}
if cerr := tmp.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Rename(tmpName, fname)
}
if err != nil {
os.Remove(tmpName) //nolint:errcheck
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// run keeps the databases fresh until ctx is canceled. With an updater it
// polls MaxMind. Without one it reloads files that change on disk, such as
// when an external geoipupdate job replaces them.
func (db *DB) run(ctx context.Context, lg *slog.Logger, up *updater) {
interval := fileCheckInterval
if up != nil {
interval = up.interval
}
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
for _, src := range db.sources() {
if up != nil {
db.checkUpdate(ctx, lg, up, src)
} else {
db.checkFile(ctx, lg, src)
}
}
}
}
func (db *DB) checkUpdate(ctx context.Context, lg *slog.Logger, up *updater, src *source) {
lg = lg.With("edition", src.edition, "path", src.path)
updated, err := up.update(ctx, src)
if err != nil {
updateErrors.WithLabelValues(string(src.kind)).Inc()
var httpErr client.HTTPError
if errors.As(err, &httpErr) && (httpErr.StatusCode == http.StatusUnauthorized || httpErr.StatusCode == http.StatusForbidden) {
lg.ErrorContext(ctx, "MaxMind rejected the account ID or license key, please check the geoip auto_update settings", "err", err, "actionable", true)
return
}
lg.WarnContext(ctx, "can't update geoip database, keeping the current one", "err", err)
return
}
if updated {
lg.InfoContext(ctx, "updated geoip database", "file", src.current)
}
if err := src.cleanup(); err != nil {
lg.DebugContext(ctx, "can't clean up old geoip databases yet", "err", err)
}
}
func (db *DB) checkFile(ctx context.Context, lg *slog.Logger, src *source) {
lg = lg.With("path", src.path)
fi, err := os.Stat(src.path)
if err != nil {
updateErrors.WithLabelValues(string(src.kind)).Inc()
lg.WarnContext(ctx, "can't stat geoip database, keeping the current one", "err", err)
return
}
if fi.ModTime().Equal(src.modTime) {
return
}
if err := src.load(); err != nil {
updateErrors.WithLabelValues(string(src.kind)).Inc()
lg.WarnContext(ctx, "can't reload geoip database, keeping the current one", "err", err)
return
}
lg.InfoContext(ctx, "reloaded geoip database from disk")
}
type userAgentTransport struct {
next http.RoundTripper
}
func (u userAgentTransport) RoundTrip(r *http.Request) (*http.Response, error) {
r = r.Clone(r.Context())
r.Header.Set("User-Agent", fmt.Sprint("Techaro/anubis:", anubis.Version, " ", r.Header.Get("User-Agent")))
return u.next.RoundTrip(r)
}
+125
View File
@@ -0,0 +1,125 @@
package geoip
import (
"cmp"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
)
// Automatic updates never rename over or rewrite a database that is mapped.
// Each download is saved as its own file named after the configured path with
// the Unix timestamp of the update appended, such as
// GeoLite2-ASN.mmdb.1790496947. The newest one is loaded at startup, and older
// ones are removed once nothing should be using them.
const tmpSuffix = ".tmp"
// versionPath returns the file name for a download made at ts.
func (src *source) versionPath(ts int64) string {
return src.path + "." + strconv.FormatInt(ts, 10)
}
// versions lists the downloaded copies of src, oldest first, and any staging
// files left behind by interrupted downloads.
func (src *source) versions() (versions, staging []string, err error) {
dir := filepath.Dir(src.path)
entries, err := os.ReadDir(dir)
if err != nil {
return nil, nil, err
}
type version struct {
ts int64
path string
}
prefix := filepath.Base(src.path) + "."
var found []version
for _, e := range entries {
if e.IsDir() {
continue
}
if strings.HasPrefix(e.Name(), prefix) && strings.HasSuffix(e.Name(), tmpSuffix) {
staging = append(staging, filepath.Join(dir, e.Name()))
continue
}
if ts, ok := parseVersion(e.Name(), prefix); ok {
found = append(found, version{ts: ts, path: filepath.Join(dir, e.Name())})
}
}
slices.SortFunc(found, func(a, b version) int {
return cmp.Compare(a.ts, b.ts)
})
for _, v := range found {
versions = append(versions, v.path)
}
return versions, staging, nil
}
func parseVersion(name, prefix string) (int64, bool) {
suffix, ok := strings.CutPrefix(name, prefix)
if !ok || suffix == "" {
return 0, false
}
for _, r := range suffix {
if r < '0' || r > '9' {
return 0, false
}
}
ts, err := strconv.ParseInt(suffix, 10, 64)
return ts, err == nil
}
// latest returns the newest downloaded copy of src, if any.
func (src *source) latest() (string, bool) {
vs, _, err := src.versions()
if err != nil || len(vs) == 0 {
return "", false
}
return vs[len(vs)-1], true
}
// cleanup removes downloaded copies of src other than the one in use, and
// staging files left behind by interrupted downloads. Only the goroutine that
// owns updates may call it.
//
// On Windows a file cannot be removed while a reader still maps it. Those
// removals fail and are tried again after the next update check.
func (src *source) cleanup() error {
vs, staging, err := src.versions()
if err != nil {
return err
}
var errs []error
for _, f := range append(vs, staging...) {
if f == src.current {
continue
}
if err := os.Remove(f); err != nil && !errors.Is(err, os.ErrNotExist) {
errs = append(errs, err)
}
}
if len(errs) != 0 {
return fmt.Errorf("geoip: can't remove old %s databases: %w", src.edition, errors.Join(errs...))
}
return nil
}