-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathhtml-filtering.js
458 lines (407 loc) · 12.6 KB
/
html-filtering.js
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/*******************************************************************************
uBlock Origin - a browser extension to block requests.
Copyright (C) 2017-present Raymond Hill
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
Home: https://github.com/gorhill/uBlock
*/
'use strict';
/******************************************************************************/
import logger from './logger.js';
import µb from './background.js';
import { sessionFirewall } from './filtering-engines.js';
import { StaticExtFilteringHostnameDB } from './static-ext-filtering-db.js';
/******************************************************************************/
const pselectors = new Map();
const duplicates = new Set();
const filterDB = new StaticExtFilteringHostnameDB(2);
let acceptedCount = 0;
let discardedCount = 0;
let docRegister;
const htmlFilteringEngine = {
get acceptedCount() {
return acceptedCount;
},
get discardedCount() {
return discardedCount;
},
getFilterCount() {
return filterDB.size;
},
};
const regexFromString = (s, exact = false) => {
if ( s === '' ) { return /^/; }
const match = /^\/(.+)\/([i]?)$/.exec(s);
if ( match !== null ) {
return new RegExp(match[1], match[2] || undefined);
}
const reStr = s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return new RegExp(exact ? `^${reStr}$` : reStr, 'i');
};
class PSelectorVoidTask {
constructor(task) {
console.info(`[uBO] HTML filtering: :${task[0]}() operator is not supported`);
}
transpose() {
}
}
class PSelectorHasTextTask {
constructor(task) {
this.needle = regexFromString(task[1]);
}
transpose(node, output) {
if ( this.needle.test(node.textContent) ) {
output.push(node);
}
}
}
const PSelectorIfTask = class {
constructor(task) {
this.pselector = new PSelector(task[1]);
}
transpose(node, output) {
if ( this.pselector.test(node) === this.target ) {
output.push(node);
}
}
};
PSelectorIfTask.prototype.target = true;
class PSelectorIfNotTask extends PSelectorIfTask {
}
PSelectorIfNotTask.prototype.target = false;
class PSelectorMinTextLengthTask {
constructor(task) {
this.min = task[1];
}
transpose(node, output) {
if ( node.textContent.length >= this.min ) {
output.push(node);
}
}
}
class PSelectorSpathTask {
constructor(task) {
this.spath = task[1];
this.nth = /^(?:\s*[+~]|:)/.test(this.spath);
if ( this.nth ) { return; }
if ( /^\s*>/.test(this.spath) ) {
this.spath = `:scope ${this.spath.trim()}`;
}
}
transpose(node, output) {
const nodes = this.nth
? PSelectorSpathTask.qsa(node, this.spath)
: node.querySelectorAll(this.spath);
for ( const node of nodes ) {
output.push(node);
}
}
// Helper method for other operators.
static qsa(node, selector) {
const parent = node.parentElement;
if ( parent === null ) { return []; }
let pos = 1;
for (;;) {
node = node.previousElementSibling;
if ( node === null ) { break; }
pos += 1;
}
return parent.querySelectorAll(
`:scope > :nth-child(${pos})${selector}`
);
}
}
class PSelectorUpwardTask {
constructor(task) {
const arg = task[1];
if ( typeof arg === 'number' ) {
this.i = arg;
} else {
this.s = arg;
}
}
transpose(node, output) {
if ( this.s !== '' ) {
const parent = node.parentElement;
if ( parent === null ) { return; }
node = parent.closest(this.s);
if ( node === null ) { return; }
} else {
let nth = this.i;
for (;;) {
node = node.parentElement;
if ( node === null ) { return; }
nth -= 1;
if ( nth === 0 ) { break; }
}
}
output.push(node);
}
}
PSelectorUpwardTask.prototype.i = 0;
PSelectorUpwardTask.prototype.s = '';
class PSelectorXpathTask {
constructor(task) {
this.xpe = task[1];
}
transpose(node, output) {
const xpr = docRegister.evaluate(
this.xpe,
node,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null
);
let j = xpr.snapshotLength;
while ( j-- ) {
const node = xpr.snapshotItem(j);
if ( node.nodeType === 1 ) {
output.push(node);
}
}
}
}
class PSelector {
constructor(o) {
this.raw = o.raw;
this.selector = o.selector;
this.tasks = [];
if ( !o.tasks ) { return; }
for ( const task of o.tasks ) {
const ctor = this.operatorToTaskMap.get(task[0]) || PSelectorVoidTask;
const pselector = new ctor(task);
this.tasks.push(pselector);
}
}
prime(input) {
const root = input || docRegister;
if ( this.selector === '' ) { return [ root ]; }
if ( input !== docRegister && /^ ?[>+~]/.test(this.selector) ) {
return Array.from(PSelectorSpathTask.qsa(input, this.selector));
}
return Array.from(root.querySelectorAll(this.selector));
}
exec(input) {
let nodes = this.prime(input);
for ( const task of this.tasks ) {
if ( nodes.length === 0 ) { break; }
const transposed = [];
for ( const node of nodes ) {
task.transpose(node, transposed);
}
nodes = transposed;
}
return nodes;
}
test(input) {
const nodes = this.prime(input);
for ( const node of nodes ) {
let output = [ node ];
for ( const task of this.tasks ) {
const transposed = [];
for ( const node of output ) {
task.transpose(node, transposed);
}
output = transposed;
if ( output.length === 0 ) { break; }
}
if ( output.length !== 0 ) { return true; }
}
return false;
}
}
PSelector.prototype.operatorToTaskMap = new Map([
[ 'has', PSelectorIfTask ],
[ 'has-text', PSelectorHasTextTask ],
[ 'if', PSelectorIfTask ],
[ 'if-not', PSelectorIfNotTask ],
[ 'min-text-length', PSelectorMinTextLengthTask ],
[ 'not', PSelectorIfNotTask ],
[ 'nth-ancestor', PSelectorUpwardTask ],
[ 'spath', PSelectorSpathTask ],
[ 'upward', PSelectorUpwardTask ],
[ 'xpath', PSelectorXpathTask ],
]);
function logOne(details, exception, selector) {
µb.filteringContext
.duplicate()
.fromTabId(details.tabId)
.setRealm('extended')
.setType('dom')
.setURL(details.url)
.setDocOriginFromURL(details.url)
.setFilter({
source: 'extended',
raw: `${exception === 0 ? '##' : '#@#'}^${selector}`
})
.toLogger();
}
function applyProceduralSelector(details, selector) {
let pselector = pselectors.get(selector);
if ( pselector === undefined ) {
pselector = new PSelector(JSON.parse(selector));
pselectors.set(selector, pselector);
}
const nodes = pselector.exec();
let modified = false;
for ( const node of nodes ) {
node.remove();
modified = true;
}
if ( modified && logger.enabled ) {
logOne(details, 0, pselector.raw);
}
return modified;
}
function applyCSSSelector(details, selector) {
const nodes = docRegister.querySelectorAll(selector);
let modified = false;
for ( const node of nodes ) {
node.remove();
modified = true;
}
if ( modified && logger.enabled ) {
logOne(details, 0, selector);
}
return modified;
}
htmlFilteringEngine.reset = function() {
filterDB.clear();
pselectors.clear();
duplicates.clear();
acceptedCount = 0;
discardedCount = 0;
};
htmlFilteringEngine.freeze = function() {
duplicates.clear();
filterDB.collectGarbage();
};
htmlFilteringEngine.compile = function(parser, writer) {
const { raw, compiled, exception } = parser.result;
if ( compiled === undefined ) {
const who = writer.properties.get('name') || '?';
logger.writeOne({
realm: 'message',
type: 'error',
text: `Invalid HTML filter in ${who}: ##${raw}`
});
return;
}
writer.select('HTML_FILTERS');
// Only exception filters are allowed to be global.
if ( parser.hasOptions() === false ) {
if ( exception ) {
writer.push([ 64, '', 1, compiled ]);
}
return;
}
// TODO: Mind negated hostnames, they are currently discarded.
for ( const { hn, not, bad } of parser.extOptions() ) {
if ( bad ) { continue; }
let kind = 0;
if ( exception ) {
if ( not ) { continue; }
kind |= 0b01;
}
if ( compiled.charCodeAt(0) === 0x7B /* '{' */ ) {
kind |= 0b10;
}
writer.push([ 64, hn, kind, compiled ]);
}
};
htmlFilteringEngine.fromCompiledContent = function(reader) {
// Don't bother loading filters if stream filtering is not supported.
if ( µb.canFilterResponseData === false ) { return; }
reader.select('HTML_FILTERS');
while ( reader.next() ) {
acceptedCount += 1;
const fingerprint = reader.fingerprint();
if ( duplicates.has(fingerprint) ) {
discardedCount += 1;
continue;
}
duplicates.add(fingerprint);
const args = reader.args();
filterDB.store(args[1], args[2], args[3]);
}
};
htmlFilteringEngine.retrieve = function(details) {
const hostname = details.hostname;
const plains = new Set();
const procedurals = new Set();
const exceptions = new Set();
filterDB.retrieve(
hostname,
[ plains, exceptions, procedurals, exceptions ]
);
const entity = details.entity !== ''
? `${hostname.slice(0, -details.domain.length)}${details.entity}`
: '*';
filterDB.retrieve(
entity,
[ plains, exceptions, procedurals, exceptions ],
1
);
if ( plains.size === 0 && procedurals.size === 0 ) { return; }
// https://github.com/gorhill/uBlock/issues/2835
// Do not filter if the site is under an `allow` rule.
if (
µb.userSettings.advancedUserEnabled &&
sessionFirewall.evaluateCellZY(hostname, hostname, '*') === 2
) {
return;
}
const out = { plains, procedurals };
if ( exceptions.size === 0 ) {
return out;
}
for ( const selector of exceptions ) {
if ( plains.has(selector) ) {
plains.delete(selector);
logOne(details, 1, selector);
continue;
}
if ( procedurals.has(selector) ) {
procedurals.delete(selector);
logOne(details, 1, JSON.parse(selector).raw);
continue;
}
}
if ( plains.size !== 0 || procedurals.size !== 0 ) {
return out;
}
};
htmlFilteringEngine.apply = function(doc, details) {
docRegister = doc;
let modified = false;
for ( const selector of details.selectors.plains ) {
if ( applyCSSSelector(details, selector) ) {
modified = true;
}
}
for ( const selector of details.selectors.procedurals ) {
if ( applyProceduralSelector(details, selector) ) {
modified = true;
}
}
docRegister = undefined;
return modified;
};
htmlFilteringEngine.toSelfie = function() {
return filterDB.toSelfie();
};
htmlFilteringEngine.fromSelfie = function(selfie) {
filterDB.fromSelfie(selfie);
pselectors.clear();
};
/******************************************************************************/
export default htmlFilteringEngine;
/******************************************************************************/