-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
219 lines (207 loc) · 5.09 KB
/
Copy pathparser.go
File metadata and controls
219 lines (207 loc) · 5.09 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
package ipcheck
import (
"context"
"fmt"
"net"
"net/netip"
"slices"
"strconv"
"strings"
"sync"
"time"
)
type parseMetrics struct {
ResolveSeconds float64
GeoSeconds float64
TotalSeconds float64
}
func parseSources(ctx context.Context, cfg *Config, geoSvc *geoService, enableGeo bool) ([]IPInfo, parseMetrics, error) {
startTotal := time.Now()
var raw []string
for _, src := range cfg.Runtime.IPSources {
lines, err := sourceLines(src)
if err != nil {
return nil, parseMetrics{}, err
}
raw = append(raw, lines...)
}
startResolve := time.Now()
var direct []IPInfo
var hosts []string
seen := map[string]struct{}{}
for _, item := range raw {
if ctx.Err() != nil {
return nil, parseMetrics{}, ctx.Err()
}
parsed := parseIPExpr(item, cfg)
if len(parsed) > 0 {
for _, ip := range parsed {
key := fmt.Sprintf("%s|%d", ip.IP, ip.Port)
if _, ok := seen[key]; ok {
continue
}
seen[key] = struct{}{}
direct = append(direct, ip)
}
continue
}
if isHostname(item) {
hosts = append(hosts, item)
}
}
resolved, err := resolveHostnames(ctx, uniqueStrings(hosts), cfg)
if err != nil {
return nil, parseMetrics{}, err
}
for _, ip := range resolved {
key := fmt.Sprintf("%s|%d", ip.IP, ip.Port)
if _, ok := seen[key]; ok {
continue
}
seen[key] = struct{}{}
direct = append(direct, ip)
}
resolveSeconds := round2(time.Since(startResolve).Seconds())
startGeo := time.Now()
if enableGeo && geoSvc != nil {
direct = geoSvc.fill(ctx, direct)
}
geoSeconds := round2(time.Since(startGeo).Seconds())
return direct, parseMetrics{
ResolveSeconds: resolveSeconds,
GeoSeconds: geoSeconds,
TotalSeconds: round2(time.Since(startTotal).Seconds()),
}, nil
}
func parseIPExpr(arg string, cfg *Config) []IPInfo {
if ips := parseBareIP(arg, cfg); len(ips) > 0 {
return ips
}
if ips := parseCIDR(arg, cfg); len(ips) > 0 {
return ips
}
if ips := parseIPPort(arg, cfg); len(ips) > 0 {
return ips
}
return nil
}
func parseBareIP(arg string, cfg *Config) []IPInfo {
ip := strings.TrimPrefix(strings.TrimSuffix(arg, "]"), "[")
if !isIPAddress(ip) || !addrAllowedByWhiteBlock(ip, cfg) || !addrAllowedByFamily(ip, cfg) {
return nil
}
return []IPInfo{newIPInfo(ip, cfg.IPPort)}
}
func parseCIDR(arg string, cfg *Config) []IPInfo {
prefix, err := netip.ParsePrefix(arg)
if err != nil || !addrAllowedByFamily(prefix.Addr().String(), cfg) {
return nil
}
sampleSize := cfg.CIDRSampleIPNum
if cfg.Mode == ModeGeoInfo {
sampleSize = 1
}
ips := samplePrefix(prefix, sampleSize)
out := make([]IPInfo, 0, len(ips))
for _, ip := range ips {
if addrAllowedByWhiteBlock(ip, cfg) {
out = append(out, newIPInfo(ip, cfg.IPPort))
}
}
return out
}
func parseIPPort(arg string, cfg *Config) []IPInfo {
host, portStr, err := net.SplitHostPort(arg)
if err != nil {
if strings.Count(arg, ":") == 1 && !strings.Contains(arg, "]") {
parts := strings.Split(arg, ":")
host, portStr = parts[0], parts[1]
} else {
return nil
}
}
host = strings.TrimPrefix(strings.TrimSuffix(host, "]"), "[")
port, err := strconv.Atoi(portStr)
if err != nil || !portAllowed(port, cfg) || !isIPAddress(host) || !addrAllowedByWhiteBlock(host, cfg) || !addrAllowedByFamily(host, cfg) {
return nil
}
return []IPInfo{newIPInfo(host, port)}
}
func resolveHostnames(ctx context.Context, hosts []string, cfg *Config) ([]IPInfo, error) {
if len(hosts) == 0 {
return nil, nil
}
workerCount := minInt(max(1, cfg.Runtime.ResolveThreadNum), len(hosts))
jobs := make(chan string)
var wg sync.WaitGroup
var mu sync.Mutex
var out []IPInfo
for i := 0; i < workerCount; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case host, ok := <-jobs:
if !ok {
return
}
var ips []netip.Addr
var err error
// 对标 Windows nslookup 行为模式:初始 timeout 2s,重试 1 次 (超时 4s),共 2 次尝试
timeouts := [...]time.Duration{2 * time.Second, 4 * time.Second}
for _, timeout := range timeouts {
if ctx.Err() != nil {
break
}
resolveCtx, cancel := context.WithTimeout(ctx, timeout)
ips, err = net.DefaultResolver.LookupNetIP(resolveCtx, "ip", host)
cancel()
if err == nil {
break
}
}
if err != nil {
continue
}
resolved := make([]IPInfo, 0, len(ips))
for _, ip := range ips {
ipStr := ip.String()
if !addrAllowedByWhiteBlock(ipStr, cfg) || !addrAllowedByFamily(ipStr, cfg) {
continue
}
info := newIPInfo(ipStr, cfg.IPPort)
info.Hostname = host
resolved = append(resolved, info)
}
if len(resolved) == 0 {
continue
}
mu.Lock()
out = append(out, resolved...)
mu.Unlock()
}
}
}()
}
go func() {
defer close(jobs)
for _, host := range hosts {
select {
case <-ctx.Done():
return
case jobs <- host:
}
}
}()
wg.Wait()
slices.SortFunc(out, func(a, b IPInfo) int {
if a.IP == b.IP {
return strings.Compare(a.Hostname, b.Hostname)
}
return strings.Compare(a.IP, b.IP)
})
return out, nil
}