-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathparental_categories.go
More file actions
381 lines (336 loc) · 9.08 KB
/
parental_categories.go
File metadata and controls
381 lines (336 loc) · 9.08 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
File: parental_categories.go
Version: 2.9.0 (Split)
Updated: 11-May-2026 08:37 CEST
Description:
Category data management and lookups for the sdproxy parental subsystem.
Extracted parsing, tree consolidation, and data loading into:
- parental_loader.go
- parental_parser.go
- parental_consolidation.go
Changes:
2.9.0 - [LOGGING] Safely governed startup diagnostic outputs natively through the
`logParental` parameter loop.
2.8.0 - [SECURITY/FIX] Resolved a severe structural regression. Exported the fields
of `wildcardCatEntry` (`Pattern`, `Cat`) to ensure Go's `encoding/json`
correctly persists wildcard filters into the local disk caches natively.
Wildcard categories are no longer irreversibly corrupted upon process restart.
2.7.0 - [PERF/FIX] Re-enforced strict prefix length descending arrays natively
during `loadCatCache()` deserialization. Ensures `CIDR` category lookups
maintain maximum specificity organically without manual reloads.
*/
package main
import (
"encoding/json"
"log"
"net/netip"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"sync/atomic"
)
// ---------------------------------------------------------------------------
// Category data structures
// ---------------------------------------------------------------------------
type wildcardCatEntry struct {
Pattern string `json:"pattern"`
Cat string `json:"cat"`
}
type compiledWildcard struct {
pattern string
cat string
minLen int
literalLen int
prefix string
suffix string
}
type cidrCatEntry struct {
prefix netip.Prefix
cat string
}
type categoryData struct {
apex map[string]string
compiledPatterns []compiledWildcard
ips map[netip.Addr]string
cidrs []cidrCatEntry
}
var catMap atomic.Pointer[categoryData]
var (
catMinLabels atomic.Int32
catMaxLabels atomic.Int32
)
func init() {
catMinLabels.Store(1)
catMaxLabels.Store(128)
}
// ---------------------------------------------------------------------------
// Wildcard helpers & Compilation
// ---------------------------------------------------------------------------
func isWildcard(s string) bool {
return strings.ContainsAny(s, "*?")
}
func matchGlob(p, s string) bool {
starP, starS := -1, 0
pi, si := 0, 0
for si < len(s) {
switch {
case pi < len(p) && p[pi] == '*':
starP = pi
starS = si
pi++
case pi < len(p) && (p[pi] == '?' || p[pi] == s[si]):
pi++
si++
case starP >= 0:
starS++
si = starS
pi = starP + 1
default:
return false
}
}
for pi < len(p) && p[pi] == '*' {
pi++
}
return pi == len(p)
}
func CompileWildcards(raw []wildcardCatEntry) []compiledWildcard {
compiled := make([]compiledWildcard, len(raw))
for i, r := range raw {
stars := strings.Count(r.Pattern, "*")
qs := strings.Count(r.Pattern, "?")
cw := compiledWildcard{
pattern: r.Pattern,
cat: r.Cat,
minLen: len(r.Pattern) - stars,
literalLen: len(r.Pattern) - stars - qs,
}
firstWild := strings.IndexAny(r.Pattern, "*?")
if firstWild < 0 {
cw.prefix = r.Pattern
cw.suffix = r.Pattern
} else {
cw.prefix = r.Pattern[:firstWild]
lastWild := strings.LastIndexAny(r.Pattern, "*?")
cw.suffix = r.Pattern[lastWild+1:]
}
compiled[i] = cw
}
slices.SortFunc(compiled, func(a, b compiledWildcard) int {
if a.literalLen > b.literalLen {
return -1
} else if a.literalLen < b.literalLen {
return 1
}
return 0
})
return compiled
}
// ---------------------------------------------------------------------------
// Category lookup (hot path)
// ---------------------------------------------------------------------------
func categoryOf(qname string, targetAddr netip.Addr) (string, string) {
data := catMap.Load()
if data == nil {
return "", ""
}
// 1. Directly short circuit for IP lookups (Filter IPs Support)
// Zero-allocation fallback for hot-path IP mapping
if targetAddr.IsValid() {
ip := targetAddr.Unmap()
if cat, ok := data.ips[ip]; ok {
return cat, ip.String() // Allocated only strictly on match
}
for _, c := range data.cidrs {
if c.prefix.Contains(ip) {
return c.cat, c.prefix.String() // Allocated only strictly on match
}
}
// Allow logic to cascade downward to execute domain constraints natively
// when physical IP array evaluations register zero active blocks.
}
if qname == "" {
return "", ""
}
// [PERF] Fast-path heuristic: only invoke netip.ParseAddr if the string starts
// with a digit or IPv6 colon. Radically reduces heap allocations for alphabetical
// domain queries escaping the error interface natively.
if (qname[0] >= '0' && qname[0] <= '9') || qname[0] == ':' {
if ip, err := netip.ParseAddr(qname); err == nil {
ip = ip.Unmap()
if cat, ok := data.ips[ip]; ok {
return cat, ip.String()
}
for _, c := range data.cidrs {
if c.prefix.Contains(ip) {
return c.cat, c.prefix.String()
}
}
return "", ""
}
}
// 2. High-Performance Wildcard Evaluation
for _, e := range data.compiledPatterns {
if len(qname) < e.minLen {
continue
}
if e.prefix != "" && !strings.HasPrefix(qname, e.prefix) {
continue
}
if e.suffix != "" && !strings.HasSuffix(qname, e.suffix) {
continue
}
if matchGlob(e.pattern, qname) {
return e.cat, e.pattern
}
}
// 3. Apex Resolution
labels := countDomainLabels(qname)
ceiling := int(catMaxLabels.Load())
if ceiling > labels {
ceiling = labels
}
search := qname
for labels > ceiling {
idx := strings.IndexByte(search, '.')
if idx < 0 {
break
}
search = search[idx+1:]
labels--
}
for {
if cat, ok := data.apex[search]; ok {
return cat, search
}
idx := strings.IndexByte(search, '.')
if idx < 0 || labels <= int(catMinLabels.Load()) {
break
}
search = search[idx+1:]
labels--
}
return "", ""
}
func computeCatLabelBounds(apex map[string]string) {
if len(apex) == 0 {
catMinLabels.Store(1)
catMaxLabels.Store(128)
return
}
minL, maxL := int(^uint(0)>>1), 0
for k := range apex {
n := countDomainLabels(k)
if n < minL {
minL = n
}
if n > maxL {
maxL = n
}
}
catMinLabels.Store(int32(minL))
catMaxLabels.Store(int32(maxL))
if logParental {
log.Printf("[PARENTAL] Category walk bounds: [%d..%d] labels (%d apex entries)", catMinLabels.Load(), catMaxLabels.Load(), len(apex))
}
}
// ---------------------------------------------------------------------------
// Disk Cache Persistence
// ---------------------------------------------------------------------------
type catCacheData struct {
Apex map[string]string `json:"apex"`
Patterns []wildcardCatEntry `json:"patterns"`
IPs map[string]string `json:"ips"`
CIDRs []cidrCatEntryStr `json:"cidrs"`
}
type cidrCatEntryStr struct {
Prefix string `json:"prefix"`
Cat string `json:"cat"`
}
func loadCatCache() {
path := filepath.Join(snapshotDir(), catCacheFile)
b, err := os.ReadFile(path)
if err != nil {
return
}
var data catCacheData
if err := json.Unmarshal(b, &data); err != nil {
var apex map[string]string
if err := json.Unmarshal(b, &apex); err != nil {
if logParental {
log.Printf("[PARENTAL] Cat-cache parse error: %v", err)
}
return
}
data.Apex = apex
}
var patterns []wildcardCatEntry
if len(data.Patterns) == 0 {
for cat, cc := range cfg.Parental.Categories {
for _, d := range cc.Add {
d = strings.ToLower(strings.TrimSuffix(d, "."))
if isWildcard(d) {
patterns = append(patterns, wildcardCatEntry{Pattern: d, Cat: cat})
}
}
}
} else {
patterns = data.Patterns
}
ips := make(map[netip.Addr]string, len(data.IPs))
for k, v := range data.IPs {
if ip, err := netip.ParseAddr(k); err == nil {
ips[ip] = v
}
}
var cidrs []cidrCatEntry
for _, c := range data.CIDRs {
if prefix, err := netip.ParsePrefix(c.Prefix); err == nil {
cidrs = append(cidrs, cidrCatEntry{prefix: prefix, cat: c.Cat})
}
}
if len(cidrs) > 0 {
sort.SliceStable(cidrs, func(i, j int) bool {
return cidrs[i].prefix.Bits() > cidrs[j].prefix.Bits()
})
}
catMap.Store(&categoryData{
apex: data.Apex,
compiledPatterns: CompileWildcards(patterns),
ips: ips,
cidrs: cidrs,
})
catMapInitialized.Store(true) // Release startup guard
computeCatLabelBounds(data.Apex)
if logParental {
log.Printf("[PARENTAL] Category cache loaded: %d apex, %d patterns, %d IPs, %d CIDRs", len(data.Apex), len(patterns), len(ips), len(cidrs))
}
}
func saveCatCache(apex map[string]string, patterns []wildcardCatEntry, ips map[netip.Addr]string, cidrs []cidrCatEntry) {
path := filepath.Join(snapshotDir(), catCacheFile)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return
}
data := catCacheData{
Apex: apex,
Patterns: patterns,
IPs: make(map[string]string, len(ips)),
CIDRs: make([]cidrCatEntryStr, len(cidrs)),
}
for k, v := range ips {
data.IPs[k.String()] = v
}
for i, c := range cidrs {
data.CIDRs[i] = cidrCatEntryStr{Prefix: c.prefix.String(), Cat: c.cat}
}
b, err := json.Marshal(data)
if err != nil {
return
}
tmp := path + ".tmp"
if os.WriteFile(tmp, b, 0644) == nil {
os.Rename(tmp, path)
}
}