-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathidentity_asn.go
More file actions
431 lines (375 loc) · 10.3 KB
/
identity_asn.go
File metadata and controls
431 lines (375 loc) · 10.3 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
File: identity_asn.go
Version: 1.9.0
Updated: 21-Apr-2026 14:42 CEST
Description:
Autonomous System Number (ASN) Identity Resolution and Database fetching.
Retrieves and parses remote/local IPinfo JSON/GZ databases.
Changes:
1.9.0 - [FEAT] Integrated `ipVersionSupport` check into `parseASNStream`
to selectively discard ASN ranges matching the filtered IP version
to minimize resource footprint.
1.8.0 - [PERF] Refactored `LookupASNDetails` to natively consume pre-parsed
`netip.Addr` structures.
...
*/
package main
import (
"bufio"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"io"
"log"
"net/http"
"net/netip"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
)
type asnRange struct {
start netip.Addr
end netip.Addr
asn string
name string
country string
}
type asnLookupTable struct {
ranges []asnRange
}
var asnSnap atomic.Pointer[asnLookupTable]
func LookupASNDetails(addr netip.Addr) (asn, name, country string) {
if !addr.IsValid() {
return "", "", ""
}
table := asnSnap.Load()
if table == nil || len(table.ranges) == 0 {
return "", "", ""
}
idx := sort.Search(len(table.ranges), func(i int) bool {
return table.ranges[i].end.Compare(addr) >= 0
})
if idx < len(table.ranges) {
r := table.ranges[idx]
if r.start.Compare(addr) <= 0 {
return r.asn, r.name, r.country
}
}
return "", "", ""
}
func LookupASNDetailsByIP(ipStr string) (asn, name, country string) {
if ipStr == "" {
return "", "", ""
}
addr, err := netip.ParseAddr(ipStr)
if err != nil {
return "", "", ""
}
return LookupASNDetails(addr.Unmap())
}
func LookupASNByIP(ipStr string) string {
asn, _, _ := LookupASNDetailsByIP(ipStr)
return asn
}
var (
asnHTTPMeta = make(map[string]catListHeaders)
asnFileMeta = make(map[string]int64)
asnFileRanges = make(map[string][]asnRange)
asnMu sync.Mutex
)
func loadASNMeta() map[string]catListHeaders {
meta := make(map[string]catListHeaders)
if cfg.Identity.ASNCacheDir == "" {
return meta
}
b, err := os.ReadFile(filepath.Join(cfg.Identity.ASNCacheDir, "asn-meta.json"))
if err == nil {
json.Unmarshal(b, &meta)
}
return meta
}
func saveASNMeta(meta map[string]catListHeaders) {
if cfg.Identity.ASNCacheDir == "" {
return
}
os.MkdirAll(cfg.Identity.ASNCacheDir, 0755)
b, err := json.Marshal(meta)
if err == nil {
os.WriteFile(filepath.Join(cfg.Identity.ASNCacheDir, "asn-meta.json"), b, 0644)
}
}
func InitASN() {
if len(cfg.Identity.IPInfoASN) == 0 {
return
}
log.Printf("[IDENTITY-ASN] Initialising ASN databases from %d source(s)", len(cfg.Identity.IPInfoASN))
if cfg.Identity.ASNFastStart {
log.Printf("[IDENTITY-ASN] Fast start enabled. ASN databases will load in the background.")
go pollASN(forceRefreshStartup)
} else {
pollASN(forceRefreshStartup)
}
pollStr := cfg.Identity.ASNPollInterval
if pollStr == "" {
pollStr = "6h"
}
if pollStr != "0s" && pollStr != "0" {
if interval, err := time.ParseDuration(pollStr); err == nil && interval > 0 {
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for range ticker.C {
pollASN(false)
}
}()
} else {
log.Printf("[IDENTITY-ASN] Invalid asn_poll_interval %q: %v", pollStr, err)
}
}
}
func pollASN(force bool) {
asnMu.Lock()
defer asnMu.Unlock()
changed := false
if force {
log.Printf("[IDENTITY-ASN] Force-refresh enabled. Bypassing metadata caches.")
asnHTTPMeta = make(map[string]catListHeaders)
} else if len(asnHTTPMeta) == 0 && cfg.Identity.ASNCacheDir != "" {
asnHTTPMeta = loadASNMeta()
}
for _, src := range cfg.Identity.IPInfoASN {
var reader io.ReadCloser
if strings.HasPrefix(src, "http://") || strings.HasPrefix(src, "https://") {
req, err := http.NewRequest(http.MethodGet, src, nil)
if err != nil {
log.Printf("[IDENTITY-ASN] Bad URL %s: %v", src, err)
continue
}
var cachePath string
hasCacheFile := false
if cfg.Identity.ASNCacheDir != "" {
os.MkdirAll(cfg.Identity.ASNCacheDir, 0755)
h := sha256.Sum256([]byte(src))
cachePath = filepath.Join(cfg.Identity.ASNCacheDir, "asn-"+hex.EncodeToString(h[:8])+".raw")
if _, err := os.Stat(cachePath); err == nil {
hasCacheFile = true
}
}
if !force {
if m, ok := asnHTTPMeta[src]; ok && hasCacheFile {
if m.LastModified != "" {
req.Header.Set("If-Modified-Since", m.LastModified)
}
if m.ETag != "" {
req.Header.Set("If-None-Match", m.ETag)
}
}
}
resp, err := catHTTPClient.Do(req)
if err != nil {
if len(asnFileRanges[src]) == 0 && hasCacheFile {
reader, _ = os.Open(cachePath)
changed = true
log.Printf("[IDENTITY-ASN] Fetch failed for %s: %v — falling back to local cache (%s)", src, err, filepath.Base(cachePath))
} else {
log.Printf("[IDENTITY-ASN] Fetch failed for %s: %v", src, err)
}
} else if resp.StatusCode == http.StatusNotModified {
resp.Body.Close()
if len(asnFileRanges[src]) == 0 && hasCacheFile {
reader, _ = os.Open(cachePath)
changed = true
log.Printf("[IDENTITY-ASN] Not modified (304), loading local cache (%s) for %s", filepath.Base(cachePath), src)
} else {
continue
}
} else if resp.StatusCode == http.StatusOK {
asnHTTPMeta[src] = catListHeaders{
LastModified: resp.Header.Get("Last-Modified"),
ETag: resp.Header.Get("ETag"),
}
if cachePath != "" {
f, err := os.Create(cachePath + ".tmp")
if err == nil {
io.Copy(f, resp.Body)
f.Close()
os.Rename(cachePath+".tmp", cachePath)
log.Printf("[IDENTITY-ASN] Saved remote database to local cache (%s) for %s", filepath.Base(cachePath), src)
}
resp.Body.Close()
reader, _ = os.Open(cachePath)
} else {
reader = resp.Body
}
changed = true
} else {
resp.Body.Close()
if len(asnFileRanges[src]) == 0 && hasCacheFile {
reader, _ = os.Open(cachePath)
changed = true
log.Printf("[IDENTITY-ASN] Failed to fetch. HTTP %d for %s — falling back to local cache (%s)", resp.StatusCode, src, filepath.Base(cachePath))
} else {
log.Printf("[IDENTITY-ASN] Failed to fetch. HTTP %d for %s", resp.StatusCode, src)
}
}
} else {
info, err := os.Stat(src)
if err != nil {
log.Printf("[IDENTITY-ASN] Cannot stat %s: %v", src, err)
continue
}
mtime := info.ModTime().UnixNano()
if lastMtime, ok := asnFileMeta[src]; ok && lastMtime == mtime && !force {
if len(asnFileRanges[src]) > 0 {
continue
}
}
f, err := os.Open(src)
if err != nil {
log.Printf("[IDENTITY-ASN] Cannot open %s: %v", src, err)
continue
}
asnFileMeta[src] = mtime
reader = f
changed = true
}
if reader != nil {
func() {
defer reader.Close()
header := make([]byte, 2)
n, _ := io.ReadFull(reader, header)
var decodeReader io.Reader
if n == 2 && header[0] == 0x1f && header[1] == 0x8b {
mr := io.MultiReader(bytes.NewReader(header[:n]), reader)
gzr, err := gzip.NewReader(mr)
if err != nil {
log.Printf("[IDENTITY-ASN] Gzip initialization error for %s: %v", src, err)
return
}
defer gzr.Close()
decodeReader = gzr
} else {
decodeReader = io.MultiReader(bytes.NewReader(header[:n]), reader)
}
parsed := parseASNStream(decodeReader)
asnFileRanges[src] = parsed
}()
}
}
if !changed {
return
}
saveASNMeta(asnHTTPMeta)
var allRanges []asnRange
for _, r := range asnFileRanges {
allRanges = append(allRanges, r...)
}
if len(allRanges) > 0 {
sort.Slice(allRanges, func(i, j int) bool {
return allRanges[i].start.Compare(allRanges[j].start) < 0
})
asnSnap.Store(&asnLookupTable{ranges: allRanges})
log.Printf("[IDENTITY-ASN] Rebuilt routing arrays. Loaded %d IP/ASN boundaries globally.", len(allRanges))
}
}
type ipinfoRow struct {
StartIP string `json:"start_ip,omitempty"`
EndIP string `json:"end_ip,omitempty"`
Name string `json:"name,omitempty"`
Country string `json:"country,omitempty"`
Network string `json:"network,omitempty"`
ASName string `json:"as_name,omitempty"`
CountryCode string `json:"country_code,omitempty"`
ASN string `json:"asn"`
}
func parseASNStream(r io.Reader) []asnRange {
var ranges []asnRange
scanner := bufio.NewScanner(r)
buf := make([]byte, 64*1024)
scanner.Buffer(buf, 2*1024*1024)
for scanner.Scan() {
line := bytes.TrimSpace(scanner.Bytes())
if len(line) == 0 || line[0] == '[' || line[0] == ']' {
continue
}
if line[len(line)-1] == ',' {
line = line[:len(line)-1]
}
var row ipinfoRow
if err := json.Unmarshal(line, &row); err == nil {
var start, end netip.Addr
var err1, err2 error
if row.Network != "" {
if prefix, err := netip.ParsePrefix(row.Network); err == nil {
start = prefix.Masked().Addr()
end = lastAddr(prefix)
} else {
err1 = err
}
} else {
start, err1 = netip.ParseAddr(row.StartIP)
end, err2 = netip.ParseAddr(row.EndIP)
}
if err1 == nil && err2 == nil && row.ASN != "" {
// [PERF] Filter entry based on global SupportIPVersion setting to save memory.
if ipVersionSupport != "both" {
if ipVersionSupport == "ipv4" && !start.Is4() {
continue
}
if ipVersionSupport == "ipv6" && !start.Is6() {
continue
}
}
asn := strings.ToUpper(row.ASN)
if !strings.HasPrefix(asn, "AS") {
asn = "AS" + asn
}
ownerName := row.ASName
if ownerName == "" {
ownerName = row.Name
}
countryCode := row.CountryCode
if countryCode == "" {
countryCode = row.Country
}
ranges = append(ranges, asnRange{
start: start.Unmap(),
end: end.Unmap(),
asn: asn,
name: ownerName,
country: countryCode,
})
}
}
}
return ranges
}
func lastAddr(p netip.Prefix) netip.Addr {
addr := p.Masked().Addr()
if addr.Is4() {
b := addr.As4()
mask := uint32(0xffffffff) >> p.Bits()
ip := binary.BigEndian.Uint32(b[:]) | mask
binary.BigEndian.PutUint32(b[:], ip)
return netip.AddrFrom4(b)
}
b := addr.As16()
rem := 128 - p.Bits()
for i := 15; i >= 0 && rem > 0; i-- {
if rem >= 8 {
b[i] = 0xff
rem -= 8
} else {
b[i] |= byte((1 << rem) - 1)
rem = 0
}
}
return netip.AddrFrom16(b)
}