forked from IncSW/geoip2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader_asn.go
71 lines (66 loc) · 1.53 KB
/
reader_asn.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
60
61
62
63
64
65
66
67
68
69
70
71
package geoip2
import (
"errors"
"io/ioutil"
"net"
"strconv"
)
type ASNReader struct {
*reader
}
func (r *ASNReader) Lookup(ip net.IP) (*ASN, error) {
offset, err := r.getOffset(ip)
if err != nil {
return nil, err
}
dataType, size, offset, err := readControl(r.decoderBuffer, offset)
if err != nil {
return nil, err
}
result := &ASN{}
switch dataType {
case dataTypeMap:
_, err = readASNMap(result, r.decoderBuffer, size, offset)
if err != nil {
return nil, err
}
case dataTypePointer:
pointer, _, err := readPointer(r.decoderBuffer, size, offset)
if err != nil {
return nil, err
}
dataType, size, offset, err := readControl(r.decoderBuffer, pointer)
if err != nil {
return nil, err
}
if dataType != dataTypeMap {
return nil, errors.New("invalid ASN pointer type: " + strconv.Itoa(int(dataType)))
}
_, err = readASNMap(result, r.decoderBuffer, size, offset)
if err != nil {
return nil, err
}
default:
return nil, errors.New("invalid ASN type: " + strconv.Itoa(int(dataType)))
}
return result, nil
}
func NewASNReader(buffer []byte) (*ASNReader, error) {
reader, err := newReader(buffer)
if err != nil {
return nil, err
}
if reader.metadata.DatabaseType != "GeoLite2-ASN" {
return nil, errors.New("wrong MaxMind DB ASN type: " + reader.metadata.DatabaseType)
}
return &ASNReader{
reader: reader,
}, nil
}
func NewASNReaderFromFile(filename string) (*ASNReader, error) {
buffer, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return NewASNReader(buffer)
}