-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathipdb.go
239 lines (213 loc) · 5.08 KB
/
ipdb.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
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
package main
import (
"encoding/csv"
"fmt"
"io"
"net/netip"
"os"
"strconv"
"strings"
"go4.org/netipx"
)
type Company struct {
Code string `json:"code"`
Name string `json:"name"`
Document string `json:"document"`
}
type IPRange struct {
Prefix netip.Prefix
Company *Company
}
type IPStruct struct {
Key int64
Separator string
Children map[uint64]*IPStruct
Ranges []IPRange
}
type IPDatabase struct {
Companies map[string]*Company
Ipv4 *IPStruct
Ipv6 *IPStruct
}
// func main() {
// db := NewDatabase()
// db.LoadFromFile("data/nicbr-asn-blk-latest.txt")
// // check some addresses
// company, err := db.Search("45.180.216.1")
// if err != nil {
// fmt.Printf("err: %v\n", err)
// return
// }
// fmt.Println("The Company was found!:", company)
// }
func NewDatabase() *IPDatabase {
return &IPDatabase{
Companies: make(map[string]*Company, 0),
Ipv4: CreateIPStruct("."),
Ipv6: CreateIPStruct(":"),
}
}
func (d *IPDatabase) LoadFromFile(filePath string) error {
f, err := os.Open(filePath)
if err != nil {
return err
}
defer f.Close()
return d.LoadFromReader(f)
}
func (d *IPDatabase) LoadFromReader(reader io.Reader) error {
csvReader := csv.NewReader(reader)
csvReader.Comma = '|'
csvReader.FieldsPerRecord = -1
records, err := csvReader.ReadAll()
if err != nil {
return err
}
for _, fields := range records {
d.processLine(fields)
}
return nil
}
func (d *IPDatabase) processLine(fields []string) {
//Field 0: Company code
//Field 1: Company name
//Field 2: Company cnpj
//Field 3..: IP Ranges
var (
code string = fields[0]
company *Company
found bool
)
if company, found = d.Companies[code]; !found {
//company need to be created
company = &Company{
Code: code,
Name: fields[1],
Document: fields[2],
}
d.Companies[code] = company
}
// percorre os campos e processa
for _, ipRange := range fields[3:] {
d.processRange(company, ipRange)
}
}
func (d *IPDatabase) Search(address string) (*Company, error) {
//convert ip address to object
ipAddr, err := netip.ParseAddr(address)
if err != nil {
return nil, fmt.Errorf("invalid ip address")
}
// now make the search
var ipStruct *IPStruct
if ipAddr.Is4() {
ipStruct = d.Ipv4
} else {
ipStruct = d.Ipv6
}
// now use struct to process thing
return ipStruct.Search(ipAddr)
}
func (d *IPDatabase) processRange(company *Company, ipRange string) {
ipPrefix, err := netip.ParsePrefix(ipRange)
if err != nil {
fmt.Println("Invalid IP Prefix", ipRange)
return
}
var ipStruct *IPStruct
if ipPrefix.Addr().Is4() {
ipStruct = d.Ipv4
} else {
ipStruct = d.Ipv6
}
// now use struct to process thing
ipStruct.Add(ipPrefix, company)
}
func CreateIPStruct(Separator string) *IPStruct {
return &IPStruct{
Separator: Separator,
Children: make(map[uint64]*IPStruct, 0),
Ranges: make([]IPRange, 0, 10),
}
}
func (st *IPStruct) Search(ipAddr netip.Addr) (*Company, error) {
// nao achou, tenta navegar
parts := strings.Split(ipAddr.String(), st.Separator)
return st.traverse(ipAddr, parts)
}
func (st *IPStruct) traverse(ipAddr netip.Addr, parts []string) (*Company, error) {
// check the current ranges
for _, ipRange := range st.Ranges {
if ipRange.Prefix.Contains(ipAddr) {
return ipRange.Company, nil
}
}
// go deep one step
if len(parts) > 1 {
//acessa
ip_id, err := strconv.ParseUint(parts[0], 16, 64)
if err != nil {
return nil, fmt.Errorf("cannot convert ip address to number")
}
v, found := st.Children[ip_id]
if found {
return v.traverse(ipAddr, parts[1:])
}
}
return nil, fmt.Errorf("IP address not found in this database")
}
func (st *IPStruct) Add(prefix netip.Prefix, company *Company) {
rng := netipx.RangeOfPrefix(prefix)
from := strings.Split(rng.From().String(), st.Separator)
to := strings.Split(rng.To().String(), st.Separator)
st.parsePrefix(prefix, company, from, to)
}
func (st *IPStruct) parsePrefix(prefix netip.Prefix, company *Company, from []string, to []string) {
if len(from) == 0 {
return
}
if from[0] != to[0] || from[0] == "0" || to[0] == "" || from[0] == "" || to[0] == "" {
//fim da linha/adiciona aqui
st.Ranges = append(st.Ranges, IPRange{
Company: company,
Prefix: prefix,
})
return
}
// navega na estrutura
ip_id, err := strconv.ParseUint(to[0], 16, 64)
if err != nil {
panic("Cannot convert string to uint number!")
}
pStruct, exists := st.Children[ip_id]
if !exists {
//cria a estrutura
pStruct = CreateIPStruct(st.Separator)
pStruct.Key = int64(ip_id)
st.Children[ip_id] = pStruct
}
pStruct.parsePrefix(prefix, company, from[1:], to[1:])
}
func (c *Company) String() string {
return fmt.Sprintf("{Code:%s, Name:%s, Document:%s}", c.Code, c.Name, c.Document)
}
/*
func main() {
cogen := &Company{ // pb == &Student{"Bob", 8}
Code: "AS174",
Name: "COGENT BRASIL TELECOMUNICAÇÕES LTDA.",
Cnpj: "29.484.413/0001-70",
}
ipv6 := &IPStruct{
Key: "",
}
range1 := &IPRange{
Prefix: netip.MustParsePrefix("2804:5330::/32"),
Company: cogen,
}
part1, err := strconv.ParseInt("2804", 16, 64)
if err != nil {
panic(err)
}
}
*/