Debian Codegraph @

cmd/atomdns/handlers/geoip/geoip.go

raw
1 package geoip
2
3 import (
4 "context"
5 "log/slog"
6 "net/netip"
7
8 "codeberg.org/miekg/dns"
9 "codeberg.org/miekg/dns/cmd/atomdns/internal/dnsctx"
10 "codeberg.org/miekg/dns/dnsutil"
11 "github.com/oschwald/geoip2-golang/v2"
12 )
13
14 // Geoip adds location data to the context.
15 type Geoip struct {
16 City *geoip2.Reader
17 City6 *geoip2.Reader
18 Asn *geoip2.Reader
19 Asn6 *geoip2.Reader
20 }
21
22 func (g *Geoip) HandlerFunc(next dns.HandlerFunc) dns.HandlerFunc {
23 return dns.HandlerFunc(func(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) {
24 ip, _ := netip.ParseAddr(dnsutil.RemoteIP(w))
25 if x := dnsctx.Addr(ctx, "etc/address"); x.IsValid() {
26 log().Debug("Using 'ecs/address'", slog.String("address", x.String()))
27 ip = x
28 }
29
30 var (
31 city *geoip2.City
32 asn *geoip2.ASN
33 err error
34 )
35 switch ip.Is4() {
36 case true:
37 if g.City != nil {
38 if city, err = g.City.City(ip); err != nil {
39 log().Debug("Lookup failed", Err(err))
40 }
41 }
42 if g.Asn != nil {
43 if asn, err = g.Asn.ASN(ip); err != nil {
44 log().Debug("Lookup failed", Err(err))
45 }
46 }
47
48 case false:
49 if g.City6 != nil {
50 if city, err = g.City6.City(ip); err != nil {
51 log().Debug("Lookup failed", Err(err))
52 }
53 }
54 if g.Asn6 != nil {
55 if asn, err = g.Asn6.ASN(ip); err != nil {
56 log().Debug("Lookup failed", Err(err))
57 }
58 }
59 }
60 if city.HasData() {
61 dnsctx.WithValue(ctx, dnsctx.Key(g, "city"), city.City.Names.English)
62 regions := make([]string, len(city.Subdivisions))
63 for i, region := range city.Subdivisions {
64 regions[i] = region.ISOCode
65 }
66 dnsctx.WithValue(ctx, dnsctx.Key(g, "city/region"), regions)
67 dnsctx.WithValue(ctx, dnsctx.Key(g, "country"), city.Country.ISOCode)
68 dnsctx.WithValue(ctx, dnsctx.Key(g, "country/eu"), city.Country.IsInEuropeanUnion)
69 dnsctx.WithValue(ctx, dnsctx.Key(g, "continent"), city.Continent.Code)
70 dnsctx.WithValue(ctx, dnsctx.Key(g, "timezone"), city.Location.TimeZone)
71 if city.Location.HasCoordinates() {
72 dnsctx.WithValue(ctx, dnsctx.Key(g, "latitude"), *city.Location.Latitude)
73 dnsctx.WithValue(ctx, dnsctx.Key(g, "longitude"), *city.Location.Longitude)
74 }
75 }
76 if asn.HasData() {
77 dnsctx.WithValue(ctx, dnsctx.Key(g, "asn"), asn.AutonomousSystemNumber)
78 dnsctx.WithValue(ctx, dnsctx.Key(g, "asn/organization"), asn.AutonomousSystemOrganization)
79 }
80 next.ServeDNS(ctx, w, r)
81 })
82 }