CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 20s
CI / Tests (Linux, race detector) (push) Successful in 18s
CI / Dependency audit (push) Successful in 14s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 14s
Release / Gitea release (push) Successful in 3s
lookupRaw loaded the database pointer and then acquired it. A hot swap could close the old database in between, so the lookup returned an empty answer (and cached it). The swap stores the new database before closing the old one, so reload the pointer and retry when acquire fails. Seen once in 377k lookups on the arm64 runner. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
369 lines
8.7 KiB
Go
369 lines
8.7 KiB
Go
// Package geo resolve geolocalização e ASN offline a partir de bases MMDB
|
|
// (DB-IP Lite), com leitor MMDB próprio, mmap somente leitura e troca a
|
|
// quente da base em uso.
|
|
package geo
|
|
|
|
import (
|
|
"container/list"
|
|
"net/netip"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
)
|
|
|
|
// Attribution deve ser exibida onde os dados forem apresentados (CC BY 4.0).
|
|
const Attribution = "IP geolocation by DB-IP (https://db-ip.com), CC BY 4.0"
|
|
|
|
// Info é o resultado de uma consulta; campos ausentes ficam zerados.
|
|
type Info struct {
|
|
CountryCode string `json:"cc,omitempty"`
|
|
Country string `json:"country,omitempty"` // nome em inglês
|
|
CountryPT string `json:"country_pt,omitempty"` // nome em pt-BR quando houver
|
|
Continent string `json:"continent,omitempty"`
|
|
Region string `json:"region,omitempty"`
|
|
City string `json:"city,omitempty"`
|
|
Lat float64 `json:"lat,omitempty"`
|
|
Lon float64 `json:"lon,omitempty"`
|
|
ASN uint32 `json:"asn,omitempty"`
|
|
ASOrg string `json:"as_org,omitempty"`
|
|
}
|
|
|
|
// FileStatus descreve uma base carregada.
|
|
type FileStatus struct {
|
|
File string `json:"file,omitempty"`
|
|
Type string `json:"type,omitempty"`
|
|
Build time.Time `json:"build,omitempty"` // build_epoch dos metadados
|
|
Loaded bool `json:"loaded"`
|
|
}
|
|
|
|
// Status resume o estado do resolvedor.
|
|
type Status struct {
|
|
City FileStatus `json:"city"`
|
|
ASN FileStatus `json:"asn"`
|
|
LastUpdate time.Time `json:"last_update,omitempty"` // última troca bem-sucedida
|
|
LastCheck time.Time `json:"last_check,omitempty"`
|
|
LastError string `json:"last_error,omitempty"`
|
|
}
|
|
|
|
type kind struct {
|
|
name string // "city" | "asn"
|
|
prefix string // dbip-city-lite-
|
|
}
|
|
|
|
var (
|
|
kindCity = kind{"city", "dbip-city-lite-"}
|
|
kindASN = kind{"asn", "dbip-asn-lite-"}
|
|
)
|
|
|
|
type db struct {
|
|
r *reader
|
|
file string
|
|
}
|
|
|
|
// Resolver é seguro para uso concorrente.
|
|
type Resolver struct {
|
|
dir string
|
|
city atomic.Pointer[db]
|
|
asn atomic.Pointer[db]
|
|
|
|
cache *lru
|
|
|
|
mu sync.Mutex // status e instalação
|
|
lastUpdate time.Time
|
|
lastCheck time.Time
|
|
lastErr string
|
|
updating atomic.Bool
|
|
}
|
|
|
|
// Open carrega as bases que existirem em dir (criando-o se preciso). Sem
|
|
// bases, Lookup devolve Info{} até que o updater baixe alguma.
|
|
func Open(dir string) (*Resolver, error) {
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return nil, err
|
|
}
|
|
r := &Resolver{dir: dir, cache: newLRU(8192)}
|
|
for _, k := range []kind{kindCity, kindASN} {
|
|
files := r.listFiles(k)
|
|
// da mais nova para a mais antiga: usa a primeira que abrir.
|
|
for i := len(files) - 1; i >= 0; i-- {
|
|
rd, err := openReader(files[i])
|
|
if err != nil {
|
|
r.setErr(k.name + ": " + err.Error())
|
|
continue
|
|
}
|
|
if err := rd.sanity(); err != nil {
|
|
rd.close()
|
|
r.setErr(k.name + ": " + err.Error())
|
|
continue
|
|
}
|
|
r.slot(k).Store(&db{r: rd, file: files[i]})
|
|
break
|
|
}
|
|
}
|
|
return r, nil
|
|
}
|
|
|
|
func (r *Resolver) slot(k kind) *atomic.Pointer[db] {
|
|
if k.name == "city" {
|
|
return &r.city
|
|
}
|
|
return &r.asn
|
|
}
|
|
|
|
// listFiles devolve os .mmdb do tipo, em ordem crescente (YYYY-MM).
|
|
func (r *Resolver) listFiles(k kind) []string {
|
|
m, _ := filepath.Glob(filepath.Join(r.dir, k.prefix+"*.mmdb"))
|
|
sort.Strings(m)
|
|
return m
|
|
}
|
|
|
|
func (r *Resolver) setErr(s string) {
|
|
r.mu.Lock()
|
|
r.lastErr = s
|
|
r.mu.Unlock()
|
|
}
|
|
|
|
// Close libera as bases. Lookups posteriores devolvem Info{}.
|
|
func (r *Resolver) Close() error {
|
|
var first error
|
|
for _, s := range []*atomic.Pointer[db]{&r.city, &r.asn} {
|
|
if d := s.Swap(nil); d != nil {
|
|
if err := d.r.close(); err != nil && first == nil {
|
|
first = err
|
|
}
|
|
}
|
|
}
|
|
r.cache.clear()
|
|
return first
|
|
}
|
|
|
|
// Status devolve um retrato do estado atual.
|
|
func (r *Resolver) Status() Status {
|
|
st := Status{}
|
|
fill := func(fs *FileStatus, d *db) {
|
|
if d == nil {
|
|
return
|
|
}
|
|
fs.File, fs.Type, fs.Loaded = filepath.Base(d.file), d.r.DatabaseType, true
|
|
fs.Build = time.Unix(int64(d.r.BuildEpoch), 0).UTC()
|
|
}
|
|
fill(&st.City, r.city.Load())
|
|
fill(&st.ASN, r.asn.Load())
|
|
r.mu.Lock()
|
|
st.LastUpdate, st.LastCheck, st.LastError = r.lastUpdate, r.lastCheck, r.lastErr
|
|
r.mu.Unlock()
|
|
return st
|
|
}
|
|
|
|
func skipAddr(ip netip.Addr) bool {
|
|
return !ip.IsValid() || ip.IsPrivate() || ip.IsLoopback() || ip.IsUnspecified() ||
|
|
ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsMulticast()
|
|
}
|
|
|
|
// Lookup consulta cidade e ASN do IP. IPs privados/loopback/etc. devolvem Info{}.
|
|
func (r *Resolver) Lookup(ip netip.Addr) Info {
|
|
ip = ip.Unmap()
|
|
if skipAddr(ip) {
|
|
return Info{}
|
|
}
|
|
if in, ok := r.cache.get(ip); ok {
|
|
return in
|
|
}
|
|
in := r.lookupRaw(ip)
|
|
r.cache.put(ip, in)
|
|
return in
|
|
}
|
|
|
|
func (r *Resolver) lookupRaw(ip netip.Addr) Info {
|
|
var in Info
|
|
withDB(r.city.Load, func(rd *reader) {
|
|
if off, ok := rd.find(ip); ok {
|
|
fillCity(rd.dec, off, &in)
|
|
}
|
|
})
|
|
withDB(r.asn.Load, func(rd *reader) {
|
|
if off, ok := rd.find(ip); ok {
|
|
fillASN(rd.dec, off, &in)
|
|
}
|
|
})
|
|
return in
|
|
}
|
|
|
|
// withDB runs fn on the current database of a slot. A hot swap stores the new
|
|
// database before closing the old one, so when acquire fails (the pointer we
|
|
// loaded was closed in between) the slot already holds its replacement: load
|
|
// it again instead of returning an empty answer. Bounded, in case the slot is
|
|
// being closed for good (Close).
|
|
func withDB(load func() *db, fn func(*reader)) {
|
|
for attempt := 0; attempt < 8; attempt++ {
|
|
d := load()
|
|
if d == nil {
|
|
return
|
|
}
|
|
if d.r.acquire() {
|
|
fn(d.r)
|
|
d.r.release()
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// fillCity extrai campos no layout GeoIP2-City; erros de decodificação
|
|
// deixam o que já foi lido.
|
|
func fillCity(d decoder, off uint, in *Info) {
|
|
_ = d.mapEntries(off, func(key []byte, v uint) error {
|
|
switch string(key) {
|
|
case "country":
|
|
_ = d.mapEntries(v, func(k []byte, v uint) error {
|
|
switch string(k) {
|
|
case "iso_code":
|
|
if s, err := d.str(v); err == nil {
|
|
in.CountryCode = string(s)
|
|
}
|
|
case "names":
|
|
readNames(d, v, &in.Country, &in.CountryPT)
|
|
}
|
|
return nil
|
|
})
|
|
case "continent":
|
|
_ = d.mapEntries(v, func(k []byte, v uint) error {
|
|
if string(k) == "code" {
|
|
if s, err := d.str(v); err == nil {
|
|
in.Continent = string(s)
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
case "subdivisions":
|
|
if first, ok := firstElem(d, v); ok {
|
|
_ = d.mapEntries(first, func(k []byte, v uint) error {
|
|
if string(k) == "names" {
|
|
var pt string
|
|
readNames(d, v, &in.Region, &pt)
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
case "city":
|
|
_ = d.mapEntries(v, func(k []byte, v uint) error {
|
|
if string(k) == "names" {
|
|
var pt string
|
|
readNames(d, v, &in.City, &pt)
|
|
}
|
|
return nil
|
|
})
|
|
case "location":
|
|
_ = d.mapEntries(v, func(k []byte, v uint) error {
|
|
switch string(k) {
|
|
case "latitude":
|
|
in.Lat, _ = d.floatAt(v)
|
|
case "longitude":
|
|
in.Lon, _ = d.floatAt(v)
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
func fillASN(d decoder, off uint, in *Info) {
|
|
_ = d.mapEntries(off, func(key []byte, v uint) error {
|
|
switch string(key) {
|
|
case "autonomous_system_number":
|
|
if n, err := d.uintAt(v); err == nil {
|
|
in.ASN = uint32(n)
|
|
}
|
|
case "autonomous_system_organization":
|
|
if s, err := d.str(v); err == nil {
|
|
in.ASOrg = string(s)
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// readNames lê "en" em en e "pt-BR" em pt (pt pode ser nil-equivalente).
|
|
func readNames(d decoder, off uint, en, pt *string) {
|
|
_ = d.mapEntries(off, func(k []byte, v uint) error {
|
|
switch string(k) {
|
|
case "en":
|
|
if s, err := d.str(v); err == nil {
|
|
*en = string(s)
|
|
}
|
|
case "pt-BR":
|
|
if s, err := d.str(v); err == nil {
|
|
*pt = string(s)
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// firstElem devolve o offset do primeiro elemento de um array.
|
|
func firstElem(d decoder, off uint) (uint, bool) {
|
|
v, err := d.resolve(off)
|
|
if err != nil {
|
|
return 0, false
|
|
}
|
|
typ, size, p, err := d.header(v)
|
|
if err != nil || typ != tArray || size == 0 {
|
|
return 0, false
|
|
}
|
|
return p, true
|
|
}
|
|
|
|
// ---- cache LRU ----
|
|
|
|
type lruEntry struct {
|
|
ip netip.Addr
|
|
info Info
|
|
}
|
|
|
|
type lru struct {
|
|
mu sync.Mutex
|
|
cap int
|
|
m map[netip.Addr]*list.Element
|
|
l *list.List
|
|
}
|
|
|
|
func newLRU(n int) *lru {
|
|
return &lru{cap: n, m: make(map[netip.Addr]*list.Element, n), l: list.New()}
|
|
}
|
|
|
|
func (c *lru) get(ip netip.Addr) (Info, bool) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if e, ok := c.m[ip]; ok {
|
|
c.l.MoveToFront(e)
|
|
return e.Value.(*lruEntry).info, true
|
|
}
|
|
return Info{}, false
|
|
}
|
|
|
|
func (c *lru) put(ip netip.Addr, in Info) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if e, ok := c.m[ip]; ok {
|
|
e.Value.(*lruEntry).info = in
|
|
c.l.MoveToFront(e)
|
|
return
|
|
}
|
|
c.m[ip] = c.l.PushFront(&lruEntry{ip, in})
|
|
if c.l.Len() > c.cap {
|
|
old := c.l.Back()
|
|
c.l.Remove(old)
|
|
delete(c.m, old.Value.(*lruEntry).ip)
|
|
}
|
|
}
|
|
|
|
func (c *lru) clear() {
|
|
c.mu.Lock()
|
|
c.m = make(map[netip.Addr]*list.Element, c.cap)
|
|
c.l.Init()
|
|
c.mu.Unlock()
|
|
}
|