-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathprune.go
308 lines (262 loc) · 7.28 KB
/
prune.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
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"net/url"
"os"
"strconv"
"strings"
"github.com/andybalholm/cascadia"
"golang.org/x/net/html"
"golang.org/x/net/html/charset"
"golang.org/x/text/transform"
)
// Functions for content pruning (removing specific HTML elements from the page)
var metaCharsetSelector selector
func init() {
var err error
metaCharsetSelector, err = newSelector(`meta[charset], meta[http-equiv="Content-Type"]`)
if err != nil {
panic(err)
}
}
// A filteredPruningRule represents an HTML element that should be removed from
// the page if its score in a blocked category exceeds Threshold.
type filteredPruningRule struct {
Threshold int
Selector selector
}
// A selector is a CSS selector that remembers the original text it was parsed
// from.
type selector struct {
cascadia.Selector
s string
}
func newSelector(s string) (selector, error) {
cs, err := cascadia.Compile(s)
if err != nil {
return selector{}, err
}
return selector{
Selector: cs,
s: s,
}, nil
}
func (s selector) String() string {
return s.s
}
// combineSelectors returns a selector that will match wherever a or b matches.
func combineSelectors(a, b selector) selector {
s := selector{
Selector: func(n *html.Node) bool { return a.Selector(n) || b.Selector(n) },
s: a.s + ", " + b.s,
}
// :contains selectors don't work in browser CSS, just in jQuery and Cascadia.
// So leave those out of the string version.
if strings.Contains(a.s, ":contains") {
s.s = b.s
} else if strings.Contains(b.s, ":contains") {
s.s = a.s
}
return s
}
func (c *config) loadPruningConfig(filename string) error {
f, err := os.Open(filename)
if err != nil {
return fmt.Errorf("could not open %s: %s\n", filename, err)
}
defer f.Close()
r := bufio.NewReader(f)
for {
line, err := r.ReadString('\n')
if line == "" {
if err != io.EOF {
log.Printf("Error reading %s: %s", filename, err)
}
break
}
line = strings.TrimSpace(line)
if line == "" || line[0] == '#' {
continue
}
r, line, err := parseSimpleRule(line)
if err != nil {
log.Printf("Syntax error in %s: %s", filename, err)
continue
}
if r.t == defaultRule || r.t == contentPhrase {
log.Printf("Wrong rule type in %s: %s", filename, r)
continue
}
// See if there is a threshold value between the rule and the selector.
threshold := 0
line = strings.TrimSpace(line)
if space := strings.Index(line, " "); space != -1 {
if t, err := strconv.Atoi(line[:space]); err == nil {
threshold = t
line = line[space+1:]
}
}
sel, err := newSelector(line)
if err != nil {
log.Printf("Invalid CSS selector %q in %s: %s", line, filename, err)
continue
}
if threshold == 0 {
if oldAction, ok := c.PruneActions[r]; ok {
c.PruneActions[r] = combineSelectors(oldAction, sel)
} else {
c.PruneActions[r] = sel
}
c.PruneMatcher.AddRule(r)
} else {
c.FilteredPruning[r] = append(c.FilteredPruning[r], filteredPruningRule{threshold, sel})
c.FilteredPruneMatcher.AddRule(r)
}
}
c.PruneMatcher.finalize()
c.FilteredPruneMatcher.finalize()
return nil
}
func parseHTML(content []byte, cs string) (*html.Node, error) {
var r io.Reader = bytes.NewReader(content)
if cs != "utf-8" {
e, _ := charset.Lookup(cs)
r = transform.NewReader(r, e.NewDecoder())
}
return html.Parse(r)
}
var headSelector = cascadia.MustCompile("head")
// pruneContent checks the URL to see if it is a site that is calling for
// content pruning. If so, it parses the HTML, removes the specified tags, and
// re-renders the HTML. It returns true if the content was changed. The content
// may be pre-parsed and passed in as tree; the final parse tree will be stored
// in tree.
func (c *config) pruneContent(URL *url.URL, content *[]byte, cs string, tree **html.Node) bool {
URLMatches := c.PruneMatcher.MatchingRules(URL)
if len(URLMatches) == 0 {
return false
}
if *tree == nil {
doc, err := parseHTML(*content, cs)
if err != nil {
log.Printf("Error parsing html from %s: %s", URL, err)
return false
}
*tree = doc
}
toDelete := map[*html.Node]bool{}
var selectors []selector
for urlRule := range URLMatches {
if sel, ok := c.PruneActions[urlRule]; ok {
prune(*tree, sel, toDelete)
selectors = append(selectors, sel)
}
}
if len(toDelete) == 0 {
return false
}
// Remove any meta tag that indicated the charset, since it will be
// re-rendered as UTF-8.
prune(*tree, metaCharsetSelector, toDelete)
// Actually delete the nodes that are to be removed.
for n := range toDelete {
n.Parent.RemoveChild(n)
}
// Add a style element to hide nodes that match the pruned selectors, in case they
// get added by Ajax.
css := new(bytes.Buffer)
for _, sel := range selectors {
fmt.Fprintf(css, "%s { display: none !important }\n", sel)
}
style := &html.Node{
Type: html.ElementNode,
Data: "style",
}
style.AppendChild(&html.Node{
Type: html.TextNode,
Data: string(css.Bytes()),
})
head := headSelector.MatchFirst(*tree)
if head != nil {
head.AppendChild(style)
}
b := new(bytes.Buffer)
err := html.Render(b, *tree)
if err != nil {
log.Printf("Error rendering modified content from %s: %s", URL, err)
return false
}
*content = b.Bytes()
return true
}
func (c *config) doFilteredPruning(URL *url.URL, content []byte, cs string, acls map[string]bool, tree **html.Node) bool {
URLMatches := c.FilteredPruneMatcher.MatchingRules(URL)
if len(URLMatches) == 0 {
return false
}
if *tree == nil {
doc, err := parseHTML(content, cs)
if err != nil {
log.Printf("Error parsing html from %s: %s", URL, err)
return false
}
*tree = doc
}
toDelete := map[*html.Node]bool{}
for urlRule := range URLMatches {
for _, fpr := range c.FilteredPruning[urlRule] {
c.pruneFiltered(*tree, fpr, acls, toDelete)
}
}
if len(toDelete) == 0 {
return false
}
// Mark the new content as having a charset of UTF-8.
prune(*tree, metaCharsetSelector, toDelete)
// Actually delete the nodes that are to be removed.
for n := range toDelete {
n.Parent.RemoveChild(n)
}
return true
}
// prune finds children of n that match sel, and adds them to toDelete.
func prune(n *html.Node, sel selector, toDelete map[*html.Node]bool) {
for child := n.FirstChild; child != nil; child = child.NextSibling {
switch {
case toDelete[child]:
// Ignore it.
case sel.Selector(child):
toDelete[child] = true
default:
prune(child, sel, toDelete)
}
}
}
// pruneFiltered phrase-scans children of n that match fpr.Selector, and adds
// to toDelete those that should be removed according to fpr.Threshold and acls.
func (c *config) pruneFiltered(n *html.Node, fpr filteredPruningRule, acls map[string]bool, toDelete map[*html.Node]bool) {
for child := n.FirstChild; child != nil; child = child.NextSibling {
if toDelete[child] {
continue
}
remove := false
if fpr.Selector.Selector(child) {
buf := new(bytes.Buffer)
html.Render(buf, child)
tally := make(map[rule]int)
c.scanContent(buf.Bytes(), "text/html", "utf-8", tally)
scores := c.categoryScores(tally)
rule, _ := c.ChooseACLCategoryAction(acls, scores, fpr.Threshold, "allow", "block", "block-invisible")
remove = rule.Action == "block" || rule.Action == "block-invisible"
}
if remove {
toDelete[child] = true
} else {
c.pruneFiltered(child, fpr, acls, toDelete)
}
}
}