forked from MetaCubeX/geo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeta.go
64 lines (59 loc) · 1.39 KB
/
meta.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
package convert
import (
"io"
"net"
"strings"
"github.com/maxmind/mmdbwriter"
"github.com/maxmind/mmdbwriter/inserter"
"github.com/maxmind/mmdbwriter/mmdbtype"
"github.com/oschwald/maxminddb-golang"
"github.com/sagernet/sing/common"
)
func MetaV0ToSing(binary []byte, output io.Writer) error {
database, err := maxminddb.FromBytes(binary)
if err != nil {
return err
}
writer, err := mmdbwriter.New(mmdbwriter.Options{
DatabaseType: "sing-geoip",
IPVersion: 6,
RecordSize: 24,
Inserter: inserter.ReplaceWith,
DisableIPv4Aliasing: true,
IncludeReservedNetworks: true,
})
if err != nil {
return err
}
networks := database.Networks(maxminddb.SkipAliasedNetworks)
var codes any
var ipNet *net.IPNet
for networks.Next() {
ipNet, err = networks.Network(&codes)
if err != nil {
return err
}
switch codes := codes.(type) {
case nil:
continue
case string:
if codes != "" {
err = writer.Insert(ipNet, mmdbtype.String(strings.ToLower(codes)))
}
case []any: // network returned type of slice is []any
err = writer.Insert(ipNet, mmdbtype.String(
strings.ToLower(
common.MaxBy(codes, func(it any) int {
return len(it.(string))
}).(string))))
}
if err != nil {
return err
}
}
err = networks.Err()
if err != nil {
return err
}
return common.Error(writer.WriteTo(output))
}