-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser_zi.go
127 lines (115 loc) · 2.78 KB
/
parser_zi.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
package main
import (
"net"
"encoding/binary"
"github.com/amkulikov/ipv4range"
"io"
"bufio"
"strings"
"regexp"
"os"
)
var (
regexpCIDR = regexp.MustCompile(`(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}`)
regexpIP = regexp.MustCompile(`(?:\d{1,3}\.){3}\d{1,3}`)
)
// Парсер для блоклиста от https://github.com/zapret-info/z-i
type ZapretInfoParser struct {
AllowedDomains []string // Разрешенные домены для выборки в blocklist
AllowEmptyDomain bool // Использование правил с пустыми доменами
AllDomains bool // Использование любых доменов (в т.ч. пустых)
}
// Загрузка списка разрешенных доменов из файла
func (zi *ZapretInfoParser) LoadAllowedDomains(src string) error {
f, err := os.Open(src)
if err != nil {
return err
}
defer f.Close()
br := bufio.NewReader(f)
for {
line, err := br.ReadString('\n')
if err != nil {
if err == io.EOF {
break
} else {
return err
}
}
zi.AllowedDomains = append(zi.AllowedDomains, strings.TrimSpace(line))
}
return nil
}
// Разбор содержимого блоклиста
func (zi *ZapretInfoParser) Parse(r io.Reader) (ips map[ipv4range.IPv4]struct{}, nets []*net.IPNet, e error) {
ips = make(map[ipv4range.IPv4]struct{})
br := bufio.NewReader(r)
for {
line, err := br.ReadString('\n')
if err != nil {
if err == io.EOF {
break
} else {
e = err
return
}
}
ipPart := line[:]
if sep := strings.Index(ipPart, ";"); sep >= 0 {
ipPart = ipPart[:sep]
} else {
continue
}
if !zi.AllDomains {
domainPart := line[len(ipPart)+1:]
if sep := strings.Index(domainPart, ";"); sep >= 0 {
domainPart = strings.TrimSpace(domainPart[:sep])
} else {
continue
}
if len(domainPart) == 0 {
if !zi.AllowEmptyDomain {
continue
}
} else if len(zi.AllowedDomains) > 0 {
skipLine := true
for _, d := range zi.AllowedDomains {
if strings.HasSuffix(domainPart, d) {
skipLine = false
break
}
}
if skipLine {
continue
}
}
}
matchesCIDR := regexpCIDR.FindAllStringSubmatch(ipPart, -1)
for _, match := range matchesCIDR {
if len(match) == 0 {
continue
}
_, ipNet, err := net.ParseCIDR(match[0])
if err != nil {
continue
}
nets = append(nets, ipNet)
}
var ipBuf uint32
matchesIP := regexpIP.FindAllStringSubmatch(ipPart, -1)
for _, match := range matchesIP {
if len(match) == 0 {
continue
}
ipAddr := net.ParseIP(match[0])
if ipAddr == nil {
continue
}
ipBuf = binary.BigEndian.Uint32(ipAddr.To4()[:4])
if _, ok := ips[ipv4range.IPv4(ipBuf)]; !ok {
ips[ipv4range.IPv4(ipBuf)] = struct{}{}
}
}
}
return
}