-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathcategories.go
422 lines (374 loc) · 9.47 KB
/
categories.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
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package main
// storage and loading of categories
import (
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"github.com/andybalholm/dhash"
"gopkg.in/yaml.v3"
)
// A weight contains the point values assigned to a rule+category combination.
type weight struct {
points int // points per occurrence
maxPoints int // maximum points per page
}
// An action is the action assigned to a category.
type action int
const (
BLOCK action = -1
IGNORE action = 0
ALLOW action = 1
ACL action = 2
)
func (a action) String() string {
switch a {
case BLOCK:
return "block"
case IGNORE:
return "ignore"
case ALLOW:
return "allow"
case ACL:
return "acl"
}
return "<invalid action>"
}
// A category represents one of the categories of filtering rules.
type category struct {
name string // the directory name
description string // the name presented to users
action action // the action to be taken with a page in this category
weights map[rule]weight // the weight for each rule
urlLists map[string]*CuckooFilter // a cuckoo filter for each URL list in the category
invisible bool // use invisible GIF instead of block page
}
// LoadCategories loads the category configuration files
func (cf *config) LoadCategories(dirName string) error {
if cf.Categories == nil {
cf.Categories = map[string]*category{}
}
return cf.loadCategories(dirName, nil, dirName)
}
func (cf *config) loadCategories(dirName string, parent *category, rootDir string) error {
dir, err := os.Open(dirName)
if err != nil {
return fmt.Errorf("Could not open category directory: %v", err)
}
defer dir.Close()
info, err := dir.Readdir(0)
if err != nil {
return fmt.Errorf("Could not read category directory: %v", err)
}
for _, fi := range info {
if name := fi.Name(); fi.IsDir() && name[0] != '.' {
categoryPath := filepath.Join(dirName, name)
c, err := loadCategory(categoryPath, parent, rootDir)
if err != nil {
log.Printf("Error loading category %s: %v", name, err)
continue
}
cf.Categories[c.name] = c
// Load child categories.
err = cf.loadCategories(categoryPath, c, rootDir)
if err != nil {
log.Printf("Error loading child categories of %s: %v", c.name, err)
}
}
}
return nil
}
// loadCategory loads the configuration for one category
func loadCategory(dirname string, parent *category, rootDir string) (c *category, err error) {
c = new(category)
c.weights = make(map[rule]weight)
c.name = filepath.Base(dirname)
if parent != nil {
c.name = parent.name + "/" + c.name
}
c.description = c.name
confFile := filepath.Join(dirname, "category.conf")
confData, err := os.ReadFile(confFile)
if err != nil {
return nil, err
}
var conf struct {
Description string
Action string
Invisible bool
ParentMultiplier float64 `yaml:"parent_multiplier"`
Includes map[string]float64
}
err = yaml.Unmarshal(confData, &conf)
if err != nil {
return nil, err
}
c.description = conf.Description
s := conf.Action
s = strings.TrimSpace(strings.ToLower(s))
switch s {
case "allow":
c.action = ALLOW
case "ignore":
c.action = IGNORE
case "block":
c.action = BLOCK
case "acl":
c.action = ACL
case "":
// No-op.
default:
return nil, fmt.Errorf("unrecognized action %s in %s", s, confFile)
}
c.invisible = conf.Invisible
parentMultiplier := 1.0
if conf.ParentMultiplier != 0 {
parentMultiplier = conf.ParentMultiplier
if parentMultiplier < 0 || parentMultiplier > 1 {
log.Printf("Value (%f) out of range for 'parent_multiplier' in %s (must be between 0 and 1)", parentMultiplier, confFile)
parentMultiplier = 1.0
}
}
if parent != nil {
// Copy rules from parent category.
for r, w := range parent.weights {
c.weights[r] = weight{
points: int(float64(w.points) * parentMultiplier),
maxPoints: int(float64(w.maxPoints) * parentMultiplier),
}
}
}
includes := make([]string, 0, len(conf.Includes))
for includedFile := range conf.Includes {
includes = append(includes, includedFile)
}
sort.Strings(includes)
for _, includedFile := range includes {
multiplier := conf.Includes[includedFile]
if !filepath.IsAbs(includedFile) {
includedFile = filepath.Join(rootDir, includedFile)
}
switch strings.ToLower(filepath.Ext(includedFile)) {
case ".list":
loadRuleFile(c, includedFile, multiplier)
case ".urllist":
loadURLList(c, includedFile, multiplier)
default:
log.Printf("Included file (%s) has unsupported extension in %s", includedFile, confFile)
}
}
ruleFiles, err := filepath.Glob(filepath.Join(dirname, "*.list"))
if err != nil {
return nil, fmt.Errorf("error listing rule files: %v", err)
}
sort.Strings(ruleFiles)
for _, list := range ruleFiles {
loadRuleFile(c, list, 1)
}
urlLists, err := filepath.Glob(filepath.Join(dirname, "*.urllist"))
if err != nil {
return nil, fmt.Errorf("error listing URL list files: %v", err)
}
sort.Strings(urlLists)
for _, list := range urlLists {
loadURLList(c, list, 1)
}
return c, nil
}
func loadRuleFile(c *category, filename string, multiplier float64) {
r, err := os.Open(filename)
if err != nil {
log.Println(err)
return
}
defer r.Close()
cr := newConfigReader(r)
defaultWeight := 0
for {
line, err := cr.ReadLine()
if err != nil {
break
}
r, line, err := parseCompoundRule(line)
if err != nil {
log.Printf("Error in line %d of %s: %s", cr.LineNo, filename, err)
continue
}
var w weight
n, _ := fmt.Sscan(line, &w.points, &w.maxPoints)
if n == 0 {
w.points = defaultWeight
} else if multiplier != 1 {
w.points = int(float64(w.points) * multiplier)
w.maxPoints = int(float64(w.maxPoints) * multiplier)
}
if sr, ok := r.(simpleRule); ok && sr.t == defaultRule {
defaultWeight = w.points
} else {
c.weights[r] = w
}
}
}
func loadURLList(c *category, filename string, multiplier float64) {
r, err := os.Open(filename)
if err != nil {
log.Println(err)
return
}
defer r.Close()
cr := newConfigReader(r)
var urls []string
score := 1
for {
line, err := cr.ReadLine()
if err != nil {
break
}
if len(urls) == 0 {
n, _ := fmt.Sscanf(line, "score %d", &score)
if n == 1 {
continue
}
}
u := line
if strings.HasSuffix(u, "/") {
u = strings.TrimSuffix(u, "/")
}
u = strings.ToLower(u)
urls = append(urls, u)
}
f := NewCuckooFilter(len(urls))
for _, u := range urls {
f.Insert(u)
}
if c.urlLists == nil {
c.urlLists = make(map[string]*CuckooFilter)
}
c.urlLists[filename] = f
c.weights[simpleRule{
t: urlList,
content: filename,
}] = weight{points: int(float64(score) * multiplier)}
}
func (cf *config) addRule(r rule) {
switch r := r.(type) {
case simpleRule:
switch r.t {
case contentPhrase:
cf.ContentPhraseList.addPhrase(r.content)
case imageHash:
content := r.content
threshold := -1
if dash := strings.Index(content, "-"); dash != -1 {
t, err := strconv.Atoi(content[dash+1:])
if err != nil {
log.Printf("%v: %v", r, err)
return
}
threshold = t
content = content[:dash]
}
h, err := dhash.Parse(content)
if err != nil {
log.Printf("%v: %v", r, err)
return
}
cf.ImageHashes = append(cf.ImageHashes, dhashWithThreshold{h, threshold})
default:
cf.URLRules.AddRule(r)
}
case compoundRule:
cf.addRule(r.left)
cf.addRule(r.right)
cf.CompoundRules = append(cf.CompoundRules, r)
}
}
// collectRules collects the rules from all the categories and adds
// them to URLRules and phraseRules.
func (cf *config) collectRules() {
for _, c := range cf.Categories {
for r, _ := range c.weights {
cf.addRule(r)
}
for filename, filter := range c.urlLists {
cf.URLRules.urlLists[filename] = filter
}
c.urlLists = nil // to allow duplicates to be garbage-collected
}
cf.ContentPhraseList.findFallbackNodes(0, nil)
cf.URLRules.finalize()
}
type ruleScore struct {
Count int
Score int
}
// score returns c's score for a page that matched
// the rules in tally. The keys are the rule names, and the values
// are the counts of how many times each rule was matched.
//
// If ruleScores is not nil, it will get an entry for each rule that contributes
// to the score for the category.
func (c *category) score(tally map[rule]int, conf *config, ruleScores map[string]ruleScore) int {
total := 0
weights := c.weights
for r, count := range tally {
w := weights[r]
if w.points == 0 {
continue
}
p := w.points * count
if conf.CountOnce {
p = w.points
}
if w.maxPoints != 0 && (p > 0 && p > w.maxPoints || p < 0 && p < w.maxPoints) {
p = w.maxPoints
}
total += p
if ruleScores != nil {
ruleScores[r.String()] = ruleScore{count, p}
}
}
return total
}
func (cf *config) applyCompoundRules(tally map[rule]int) {
for _, cr := range cf.CompoundRules {
left := tally[cr.left]
right := tally[cr.right]
combined := left
switch cr.op {
case "&":
if right < left {
combined = right
}
case "|":
if right > left {
combined = right
}
case "&!":
if right != 0 {
combined = 0
}
}
if combined != 0 {
tally[cr] = combined
}
}
}
// categoryScores returns a map containing a page's score for each category.
func (cf *config) categoryScores(tally map[rule]int) map[string]int {
if len(tally) == 0 {
return nil
}
cf.applyCompoundRules(tally)
scores := make(map[string]int)
for _, c := range cf.Categories {
s := c.score(tally, cf, nil)
if s != 0 {
scores[c.name] = s
}
}
return scores
}