-
Notifications
You must be signed in to change notification settings - Fork 0
/
geoip.go
59 lines (53 loc) · 1.27 KB
/
geoip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package geodata
import (
"github.com/clashdev/geodata/internal"
"google.golang.org/protobuf/proto"
"io"
"net"
"strings"
"sync/atomic"
)
type GeoIPSeeker struct {
entries atomic.Pointer[map[string][]*net.IPNet]
}
func (s *GeoIPSeeker) ReadFrom(r io.Reader) (n int64, err error) {
var data []byte
if data, err = io.ReadAll(r); err == nil {
err = s.UnmarshalBinary(data)
}
return
}
func (s *GeoIPSeeker) UnmarshalBinary(data []byte) (err error) {
ipset := new(internal.GeoIPList)
entries := make(map[string][]*net.IPNet)
if err = proto.Unmarshal(data, ipset); err == nil {
for _, entry := range ipset.Entry {
networks := make([]*net.IPNet, len(entry.Cidr))
for index, cidr := range entry.Cidr {
networks[index] = &net.IPNet{
IP: cidr.Ip,
Mask: net.CIDRMask(int(cidr.Prefix), len(cidr.Ip)*8),
}
}
entries[strings.ToLower(entry.CountryCode)] = networks
}
}
s.entries.Store(&entries)
return
}
func (s *GeoIPSeeker) IsZero() bool {
if s == nil {
return true
}
entries := s.entries.Load()
return entries == nil || *entries == nil
}
func (s *GeoIPSeeker) Query(name string) []*net.IPNet {
if s.IsZero() {
return nil
}
name = strings.TrimPrefix(name, "geoip:")
entries := *s.entries.Load()
networks, _ := entries[name]
return networks
}