/
static-net-filtering.js
4696 lines (4102 loc) · 144 KB
/
static-net-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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
uBlock Origin - a browser extension to block requests.
Copyright (C) 2014-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
*/
/* globals vAPI */
'use strict';
/******************************************************************************/
import { queueTask, dropTask } from './tasks.js';
import BidiTrieContainer from './biditrie.js';
import HNTrieContainer from './hntrie.js';
import { sparseBase64 } from './base64-custom.js';
import { StaticFilteringParser } from './static-filtering-parser.js';
import { CompiledListReader } from './static-filtering-io.js';
import {
domainFromHostname,
hostnameFromNetworkURL,
} from './uri-utils.js';
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#browser_compatibility
//
// This import would be best done dynamically, but since dynamic imports are
// not supported by older browsers, for now a static import is necessary.
import { FilteringContext } from './filtering-context.js';
/******************************************************************************/
// Access to a key-val store is optional and useful only for optimal
// initialization at module load time. Probably could re-arrange code
// to export an init() function with optimization parameters which would
// need to be called by module clients. For now, I want modularizing with
// minimal amount of changes.
const keyvalStore = typeof vAPI !== 'undefined'
? vAPI.localStorage
: { getItem() { return null; }, setItem() {}, removeItem() {} };
/******************************************************************************/
// fedcba9876543210
// || | || |
// || | || |
// || | || |
// || | || |
// || | || +---- bit 0- 1: block=0, allow=1, block important=2
// || | |+------ bit 2: modifier
// || | +------- bit 3- 4: party [0-3]
// || +--------- bit 5- 9: type [0-31]
// |+-------------- bit 10: headers-based filters
// +--------------- bit 11-15: unused
const CategoryCount = 1 << 0xb; // shift left to first unused bit
const RealmBitsMask = 0b00000000111;
const ActionBitsMask = 0b00000000011;
const TypeBitsMask = 0b01111100000;
const TypeBitsOffset = 5;
const BlockAction = 0b00000000000;
const AllowAction = 0b00000000001;
const Important = 0b00000000010;
const BlockImportant = BlockAction | Important;
const ModifyAction = 0b00000000100;
const AnyParty = 0b00000000000;
const FirstParty = 0b00000001000;
const ThirdParty = 0b00000010000;
const AllParties = 0b00000011000;
const HEADERS = 0b10000000000;
const typeNameToTypeValue = {
'no_type': 0 << TypeBitsOffset,
'stylesheet': 1 << TypeBitsOffset,
'image': 2 << TypeBitsOffset,
'object': 3 << TypeBitsOffset,
'object_subrequest': 3 << TypeBitsOffset,
'script': 4 << TypeBitsOffset,
'fetch': 5 << TypeBitsOffset,
'xmlhttprequest': 5 << TypeBitsOffset,
'sub_frame': 6 << TypeBitsOffset,
'font': 7 << TypeBitsOffset,
'media': 8 << TypeBitsOffset,
'websocket': 9 << TypeBitsOffset,
'beacon': 10 << TypeBitsOffset,
'ping': 10 << TypeBitsOffset,
'other': 11 << TypeBitsOffset,
'popup': 12 << TypeBitsOffset, // start of behavorial filtering
'popunder': 13 << TypeBitsOffset,
'main_frame': 14 << TypeBitsOffset, // start of 1p behavorial filtering
'generichide': 15 << TypeBitsOffset,
'specifichide': 16 << TypeBitsOffset,
'inline-font': 17 << TypeBitsOffset,
'inline-script': 18 << TypeBitsOffset,
'cname': 19 << TypeBitsOffset,
'webrtc': 20 << TypeBitsOffset,
'unsupported': 21 << TypeBitsOffset,
};
const otherTypeBitValue = typeNameToTypeValue.other;
const bitFromType = type =>
1 << ((typeNameToTypeValue[type] >>> TypeBitsOffset) - 1);
// All network request types to bitmap
// bring origin to 0 (from TypeBitsOffset -- see typeNameToTypeValue)
// left-shift 1 by the above-calculated value
// subtract 1 to set all type bits
const allNetworkTypesBits =
(1 << (otherTypeBitValue >>> TypeBitsOffset)) - 1;
const allTypesBits =
allNetworkTypesBits |
1 << (typeNameToTypeValue['popup'] >>> TypeBitsOffset) - 1 |
1 << (typeNameToTypeValue['main_frame'] >>> TypeBitsOffset) - 1 |
1 << (typeNameToTypeValue['inline-font'] >>> TypeBitsOffset) - 1 |
1 << (typeNameToTypeValue['inline-script'] >>> TypeBitsOffset) - 1;
const unsupportedTypeBit =
1 << (typeNameToTypeValue['unsupported'] >>> TypeBitsOffset) - 1;
const typeValueToTypeName = [
'',
'stylesheet',
'image',
'object',
'script',
'xmlhttprequest',
'subdocument',
'font',
'media',
'websocket',
'ping',
'other',
'popup',
'popunder',
'document',
'generichide',
'specifichide',
'inline-font',
'inline-script',
'cname',
'',
'',
'webrtc',
'unsupported',
];
//const typeValueFromCatBits = catBits => (catBits >>> TypeBitsOffset) & 0b11111;
const MAX_TOKEN_LENGTH = 7;
// Four upper bits of token hash are reserved for built-in predefined
// token hashes, which should never end up being used when tokenizing
// any arbitrary string.
const NO_TOKEN_HASH = 0x50000000;
const DOT_TOKEN_HASH = 0x10000000;
const ANY_TOKEN_HASH = 0x20000000;
const ANY_HTTPS_TOKEN_HASH = 0x30000000;
const ANY_HTTP_TOKEN_HASH = 0x40000000;
const EMPTY_TOKEN_HASH = 0xF0000000;
/******************************************************************************/
// See the following as short-lived registers, used during evaluation. They are
// valid until the next evaluation.
let $requestTypeValue = 0;
let $requestURL = '';
let $requestURLRaw = '';
let $requestHostname = '';
let $docHostname = '';
let $docDomain = '';
let $tokenBeg = 0;
let $patternMatchLeft = 0;
let $patternMatchRight = 0;
let $isBlockImportant = false;
const $docEntity = {
entity: '',
last: '',
compute() {
if ( this.last !== $docHostname ) {
this.last = $docHostname;
const pos = $docDomain.indexOf('.');
this.entity = pos !== -1
? `${$docHostname.slice(0, pos - $docDomain.length)}.*`
: '';
}
return this.entity;
},
};
const $httpHeaders = {
init(headers) {
this.headers = headers;
this.parsed.clear();
},
reset() {
this.headers = [];
this.parsed.clear();
},
lookup(name) {
if ( this.parsed.size === 0 ) {
for ( let i = 0, n = this.headers.length; i < n; i++ ) {
const { name, value } = this.headers[i];
this.parsed.set(name, value);
}
}
return this.parsed.get(name);
},
headers: [],
parsed: new Map(),
};
/******************************************************************************/
// Local helpers
const restrSeparator = '(?:[^%.0-9a-z_-]|$)';
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
const reEscape = /[.*+?^${}()|[\]\\]/g;
// Convert a plain string (devoid of special characters) into a regex.
const restrFromPlainPattern = s => s.replace(reEscape, '\\$&');
const restrFromGenericPattern = function(s, anchor = 0) {
let reStr = s.replace(restrFromGenericPattern.rePlainChars, '\\$&')
.replace(restrFromGenericPattern.reSeparators, restrSeparator)
.replace(restrFromGenericPattern.reDanglingAsterisks, '')
.replace(restrFromGenericPattern.reAsterisks, '\\S*?');
if ( anchor & 0b100 ) {
reStr = (
reStr.startsWith('\\.') ?
restrFromGenericPattern.restrHostnameAnchor2 :
restrFromGenericPattern.restrHostnameAnchor1
) + reStr;
} else if ( anchor & 0b010 ) {
reStr = '^' + reStr;
}
if ( anchor & 0b001 ) {
reStr += '$';
}
return reStr;
};
restrFromGenericPattern.rePlainChars = /[.+?${}()|[\]\\]/g;
restrFromGenericPattern.reSeparators = /\^/g;
restrFromGenericPattern.reDanglingAsterisks = /^\*+|\*+$/g;
restrFromGenericPattern.reAsterisks = /\*+/g;
restrFromGenericPattern.restrHostnameAnchor1 = '^[a-z-]+://(?:[^/?#]+\\.)?';
restrFromGenericPattern.restrHostnameAnchor2 = '^[a-z-]+://(?:[^/?#]+)?';
/******************************************************************************/
class LogData {
constructor(categoryBits, tokenHash, iunit) {
this.result = 0;
this.source = 'static';
this.tokenHash = tokenHash;
if ( iunit === 0 ) {
this.raw = this.regex = '';
return;
}
this.result = (categoryBits & AllowAction) === 0 ? 1 : 2;
const pattern = [];
const regex = [];
const options = [];
const denyallow = [];
const domains = [];
const logData = {
pattern,
regex,
denyallow,
domains,
options,
isRegex: false,
};
filterLogData(iunit, logData);
if ( (categoryBits & ThirdParty) !== 0 ) {
logData.options.unshift('3p');
} else if ( (categoryBits & FirstParty) !== 0 ) {
logData.options.unshift('1p');
}
const type = categoryBits & TypeBitsMask;
if ( type !== 0 ) {
logData.options.unshift(typeValueToTypeName[type >>> TypeBitsOffset]);
}
let raw = logData.pattern.join('');
if (
logData.isRegex === false &&
raw.charCodeAt(0) === 0x2F /* '/' */ &&
raw.charCodeAt(raw.length - 1) === 0x2F /* '/' */
) {
raw += '*';
}
if ( (categoryBits & AllowAction) !== 0 ) {
raw = '@@' + raw;
}
if ( denyallow.length !== 0 ) {
options.push(`denyallow=${denyallow.join('|')}`);
}
if ( domains.length !== 0 ) {
options.push(`domain=${domains.join('|')}`);
}
if ( options.length !== 0 ) {
raw += '$' + options.join(',');
}
this.raw = raw;
this.regex = logData.regex.join('');
}
isUntokenized() {
return this.tokenHash === NO_TOKEN_HASH;
}
isPureHostname() {
return this.tokenHash === DOT_TOKEN_HASH;
}
}
/******************************************************************************/
const charClassMap = new Uint32Array(128);
const CHAR_CLASS_SEPARATOR = 0b00000001;
{
const reSeparators = /[^\w%.-]/;
for ( let i = 0; i < 128; i++ ) {
if ( reSeparators.test(String.fromCharCode(i)) ) {
charClassMap[i] |= CHAR_CLASS_SEPARATOR;
}
}
}
const isSeparatorChar = c => (charClassMap[c] & CHAR_CLASS_SEPARATOR) !== 0;
/******************************************************************************/
const FILTER_DATA_PAGE_SIZE = 65536;
const roundToFilterDataPageSize =
len => (len + FILTER_DATA_PAGE_SIZE-1) & ~(FILTER_DATA_PAGE_SIZE-1);
let filterData = new Int32Array(FILTER_DATA_PAGE_SIZE * 5);
let filterDataWritePtr = 2;
function filterDataGrow(len) {
if ( len <= filterData.length ) { return; }
const newLen = roundToFilterDataPageSize(len);
const newBuf = new Int32Array(newLen);
newBuf.set(filterData);
filterData = newBuf;
}
function filterDataShrink() {
const newLen = Math.max(
roundToFilterDataPageSize(filterDataWritePtr),
FILTER_DATA_PAGE_SIZE
);
if ( newLen >= filterData.length ) { return; }
const newBuf = new Int32Array(newLen);
newBuf.set(filterData.subarray(0, filterDataWritePtr));
filterData = newBuf;
}
function filterDataAlloc(...args) {
const len = args.length;
const idata = filterDataAllocLen(len);
for ( let i = 0; i < len; i++ ) {
filterData[idata+i] = args[i];
}
return idata;
}
function filterDataAllocLen(len) {
const idata = filterDataWritePtr;
filterDataWritePtr += len;
if ( filterDataWritePtr > filterData.length ) {
filterDataGrow(filterDataWritePtr);
}
return idata;
}
const filterSequenceAdd = (a, b) => {
const iseq = filterDataAllocLen(2);
filterData[iseq+0] = a;
filterData[iseq+1] = b;
return iseq;
};
function filterDataReset() {
filterData.fill(0);
filterDataWritePtr = 2;
}
function filterDataToSelfie() {
return JSON.stringify(Array.from(filterData.subarray(0, filterDataWritePtr)));
}
function filterDataFromSelfie(selfie) {
if ( typeof selfie !== 'string' || selfie === '' ) { return false; }
const data = JSON.parse(selfie);
if ( Array.isArray(data) === false ) { return false; }
filterDataGrow(data.length);
filterDataWritePtr = data.length;
filterData.set(data);
filterDataShrink();
return true;
}
const filterRefs = [ null ];
let filterRefsWritePtr = 1;
const filterRefAdd = function(ref) {
const i = filterRefsWritePtr;
filterRefs[i] = ref;
filterRefsWritePtr += 1;
return i;
};
function filterRefsReset() {
filterRefs.fill(null);
filterRefsWritePtr = 1;
}
function filterRefsToSelfie() {
const refs = [];
for ( let i = 0; i < filterRefsWritePtr; i++ ) {
const v = filterRefs[i];
if ( v instanceof RegExp ) {
refs.push({ t: 1, s: v.source, f: v.flags });
continue;
}
if ( Array.isArray(v) ) {
refs.push({ t: 2, v });
continue;
}
if ( typeof v !== 'object' || v === null ) {
refs.push({ t: 0, v });
continue;
}
const out = Object.create(null);
for ( const prop of Object.keys(v) ) {
const value = v[prop];
out[prop] = prop.startsWith('$')
? (typeof value === 'string' ? '' : null)
: value;
}
refs.push({ t: 3, v: out });
}
return JSON.stringify(refs);
}
function filterRefsFromSelfie(selfie) {
if ( typeof selfie !== 'string' || selfie === '' ) { return false; }
const refs = JSON.parse(selfie);
if ( Array.isArray(refs) === false ) { return false; }
for ( let i = 0; i < refs.length; i++ ) {
const v = refs[i];
switch ( v.t ) {
case 0:
case 2:
case 3:
filterRefs[i] = v.v;
break;
case 1:
filterRefs[i] = new RegExp(v.s, v.f);
break;
default:
throw new Error('Unknown filter reference!');
}
}
filterRefsWritePtr = refs.length;
return true;
}
/******************************************************************************/
const origHNTrieContainer = new HNTrieContainer();
const destHNTrieContainer = new HNTrieContainer();
/******************************************************************************/
const bidiTrieMatchExtra = function(l, r, ix) {
for (;;) {
$patternMatchLeft = l;
$patternMatchRight = r;
const iu = filterData[ix+0];
if ( filterMatch(iu) ) { return iu; }
ix = filterData[ix+1];
if ( ix === 0 ) { break; }
}
return 0;
};
const bidiTrie = new BidiTrieContainer(bidiTrieMatchExtra);
const bidiTriePrime = function() {
bidiTrie.reset(keyvalStore.getItem('SNFE.bidiTrie'));
};
const bidiTrieOptimize = function(shrink = false) {
keyvalStore.setItem('SNFE.bidiTrie', bidiTrie.optimize(shrink));
};
/*******************************************************************************
Each filter class will register itself in the map.
IMPORTANT: any change which modifies the mapping will have to be
reflected with µBlock.systemSettings.compiledMagic.
*/
const filterClasses = [];
const filterArgsToUnit = new Map();
let filterClassIdGenerator = 0;
const registerFilterClass = function(fc) {
const fid = filterClassIdGenerator++;
fc.fid = fid;
fc.fidstr = `${fid}`;
filterClasses[fid] = fc;
};
const filterFromCompiled = args => {
const fc = filterClasses[args[0]];
const keygen = fc.keyFromArgs;
if ( keygen === undefined ) {
return fc.fromCompiled(args);
}
const key = `${fc.fidstr} ${(keygen(args) || '')}`;
let idata = filterArgsToUnit.get(key);
if ( idata !== undefined ) { return idata; }
idata = fc.fromCompiled(args);
filterArgsToUnit.set(key, idata);
return idata;
};
const filterGetClass = idata => {
return filterClasses[filterData[idata+0]];
};
const filterMatch = idata => filterClasses[filterData[idata+0]].match(idata);
const filterHasOriginHit = idata => {
const fc = filterClasses[filterData[idata+0]];
return fc.hasOriginHit !== undefined && fc.hasOriginHit(idata);
};
const filterGetDomainOpt = (idata, out) => {
const fc = filterClasses[filterData[idata+0]];
if ( fc.getDomainOpt === undefined ) { return; }
const domainOpt = fc.getDomainOpt(idata);
if ( out === undefined ) { return domainOpt; }
out.push(domainOpt);
};
const filterGetRegexPattern = (idata, out) => {
const fc = filterClasses[filterData[idata+0]];
if ( fc.hasRegexPattern === undefined ) { return; }
const reStr = fc.getRegexPattern(idata);
if ( out === undefined ) { return reStr; }
out.push(reStr);
};
const filterIsBidiTrieable = idata => {
const fc = filterClasses[filterData[idata+0]];
if ( fc.isBidiTrieable === undefined ) { return false; }
return fc.isBidiTrieable(idata) === true;
};
const filterToBidiTrie = idata => {
const fc = filterClasses[filterData[idata+0]];
if ( fc.toBidiTrie === undefined ) { return; }
return fc.toBidiTrie(idata);
};
const filterMatchAndFetchModifiers = (idata, env) => {
const fc = filterClasses[filterData[idata+0]];
if ( fc.matchAndFetchModifiers === undefined ) { return; }
return fc.matchAndFetchModifiers(idata, env);
};
const filterGetModifierType = idata => {
const fc = filterClasses[filterData[idata+0]];
if ( fc.getModifierType === undefined ) { return; }
return fc.getModifierType(idata);
};
const filterLogData = (idata, details) => {
const fc = filterClasses[filterData[idata+0]];
if ( fc.logData === undefined ) { return; }
fc.logData(idata, details);
};
const filterDumpInfo = (idata) => {
const fc = filterGetClass(idata);
if ( fc.dumpInfo === undefined ) { return; }
return fc.dumpInfo(idata);
};
/*******************************************************************************
Filter classes
Pattern:
FilterPatternAny
FilterPatternPlain
FilterPatternPlain1
FilterPatternPlainX
FilterPatternGeneric
FilterRegex
FilterPlainTrie
FilterHostnameDict
Pattern modifiers:
FilterAnchorHnLeft
FilterAnchorHn
FilterAnchorRight
FilterAnchorLeft
FilterTrailingSeparator
Context, immediate:
FilterOriginHit
FilterOriginMiss
FilterOriginEntityMiss
FilterOriginEntityHit
FilterOriginHitSet
FilterOriginMissSet
FilterJustOrigin
FilterHTTPJustOrigin
FilterHTTPSJustOrigin
Other options:
FilterDenyAllow
FilterImportant
FilterNotType
FilterStrictParty
FilterModifier
Collection:
FilterCollection
FilterCompositeAll
FilterBucket
FilterBucketIf
FilterBucketIfOriginHits
FilterBucketIfRegexHits
FilterOriginHitAny
A single filter can be made of many parts, in which case FilterCompositeAll
is used to hold all the parts, and where all the parts must be a match in
order for the filter to be a match.
**/
/******************************************************************************/
const FilterPatternAny = class {
static match() {
return true;
}
static compile() {
return [ FilterPatternAny.fid ];
}
static fromCompiled(args) {
return filterDataAlloc(args[0]);
}
static keyFromArgs() {
}
static logData(idata, details) {
details.pattern.push('*');
details.regex.push('^');
}
};
registerFilterClass(FilterPatternAny);
/******************************************************************************/
const FilterImportant = class {
static match() {
return ($isBlockImportant = true);
}
static compile() {
return [ FilterImportant.fid ];
}
static fromCompiled(args) {
return filterDataAlloc(args[0]);
}
static keyFromArgs() {
}
static logData(idata, details) {
details.options.unshift('important');
}
};
registerFilterClass(FilterImportant);
/******************************************************************************/
const FilterPatternPlain = class {
static isBidiTrieable(idata) {
return filterData[idata+2] <= 255;
}
static toBidiTrie(idata) {
return {
i: filterData[idata+1],
n: filterData[idata+2],
itok: filterData[idata+3],
};
}
static match(idata) {
const left = $tokenBeg;
const n = filterData[idata+2];
if (
bidiTrie.startsWith(
left,
bidiTrie.haystackLen,
filterData[idata+1],
n
) === 0
) {
return false;
}
$patternMatchLeft = left;
$patternMatchRight = left + n;
return true;
}
static compile(details) {
const { tokenBeg } = details;
if ( tokenBeg === 0 ) {
return [ FilterPatternPlain.fid, details.pattern, 0 ];
}
if ( tokenBeg === 1 ) {
return [ FilterPatternPlain1.fid, details.pattern, 1 ];
}
return [ FilterPatternPlainX.fid, details.pattern, tokenBeg ];
}
static fromCompiled(args) {
const idata = filterDataAllocLen(4);
filterData[idata+0] = args[0]; // fid
filterData[idata+1] = bidiTrie.storeString(args[1]); // i
filterData[idata+2] = args[1].length; // n
filterData[idata+3] = args[2]; // tokenBeg
return idata;
}
static logData(idata, details) {
const s = bidiTrie.extractString(
filterData[idata+1],
filterData[idata+2]
);
details.pattern.push(s);
details.regex.push(restrFromPlainPattern(s));
// https://github.com/gorhill/uBlock/issues/3037
// Make sure the logger reflects accurately internal match, taking
// into account MAX_TOKEN_LENGTH.
if ( /^[0-9a-z%]{1,6}$/i.exec(s.slice(filterData[idata+3])) !== null ) {
details.regex.push('(?![0-9A-Za-z%])');
}
}
static dumpInfo(idata) {
const pattern = bidiTrie.extractString(
filterData[idata+1],
filterData[idata+2]
);
return `${pattern} ${filterData[idata+3]}`;
}
};
FilterPatternPlain.isPatternPlain = true;
registerFilterClass(FilterPatternPlain);
const FilterPatternPlain1 = class extends FilterPatternPlain {
static match(idata) {
const left = $tokenBeg - 1;
const n = filterData[idata+2];
if (
bidiTrie.startsWith(
left,
bidiTrie.haystackLen,
filterData[idata+1],
n
) === 0
) {
return false;
}
$patternMatchLeft = left;
$patternMatchRight = left + n;
return true;
}
};
registerFilterClass(FilterPatternPlain1);
const FilterPatternPlainX = class extends FilterPatternPlain {
static match(idata) {
const left = $tokenBeg - filterData[idata+3];
const n = filterData[idata+2];
if (
bidiTrie.startsWith(
left,
bidiTrie.haystackLen,
filterData[idata+1],
n
) === 0
) {
return false;
}
$patternMatchLeft = left;
$patternMatchRight = left + n;
return true;
}
};
registerFilterClass(FilterPatternPlainX);
/******************************************************************************/
const FilterPatternGeneric = class {
static hasRegexPattern() {
return true;
}
static getRegexPattern(idata) {
return restrFromGenericPattern(
bidiTrie.extractString(
filterData[idata+1],
filterData[idata+2]
),
filterData[idata+3]
);
}
static match(idata) {
const refs = filterRefs[filterData[idata+4]];
if ( refs.$re === null ) {
refs.$re = new RegExp(this.getRegexPattern(idata));
}
return refs.$re.test($requestURL);
}
static compile(details) {
const out = [
FilterPatternGeneric.fid,
details.pattern,
details.anchor,
];
details.anchor = 0;
return out;
}
static fromCompiled(args) {
const idata = filterDataAllocLen(5);
filterData[idata+0] = args[0]; // fid
filterData[idata+1] = bidiTrie.storeString(args[1]); // i
filterData[idata+2] = args[1].length; // n
filterData[idata+3] = args[2]; // anchor
filterData[idata+4] = filterRefAdd({ $re: null });
return idata;
}
static keyFromArgs(args) {
return `${args[1]}\t${args[2]}`;
}
static logData(idata, details) {
details.pattern.length = 0;
const anchor = filterData[idata+3];
if ( (anchor & 0b100) !== 0 ) {
details.pattern.push('||');
} else if ( (anchor & 0b010) !== 0 ) {
details.pattern.push('|');
}
const s = bidiTrie.extractString(
filterData[idata+1],
filterData[idata+2]
);
details.pattern.push(s);
if ( (anchor & 0b001) !== 0 ) {
details.pattern.push('|');
}
details.regex.length = 0;
details.regex.push(restrFromGenericPattern(s, anchor & ~0b100));
}
static dumpInfo(idata) {
return bidiTrie.extractString(
filterData[idata+1],
filterData[idata+2]
);
}
};
FilterPatternGeneric.isSlow = true;
registerFilterClass(FilterPatternGeneric);
/******************************************************************************/
const FilterAnchorHnLeft = class {
static match(idata) {
const len = $requestHostname.length;
const haystackCodes = bidiTrie.haystack;
let lastBeg = filterData[idata+2];
let lastEnd = filterData[idata+3];
if (
len !== filterData[idata+1] ||
lastBeg === -1 ||
haystackCodes[lastBeg-3] !== 0x3A /* ':' */ ||
haystackCodes[lastBeg-2] !== 0x2F /* '/' */ ||
haystackCodes[lastBeg-1] !== 0x2F /* '/' */
) {
lastBeg = len !== 0 ? haystackCodes.indexOf(0x3A) : -1;
if ( lastBeg !== -1 ) {
if (
lastBeg >= bidiTrie.haystackLen ||
haystackCodes[lastBeg+1] !== 0x2F ||
haystackCodes[lastBeg+2] !== 0x2F
) {
lastBeg = -1;
}
}
if ( lastBeg !== -1 ) {
lastBeg += 3;
lastEnd = lastBeg + len;
} else {
lastEnd = -1;
}
filterData[idata+1] = len;
filterData[idata+2] = lastBeg;
filterData[idata+3] = lastEnd;
}
const left = $patternMatchLeft;
return left < lastEnd && (
left === lastBeg ||
left > lastBeg && haystackCodes[left-1] === 0x2E /* '.' */
);
}
static compile() {
return [ FilterAnchorHnLeft.fid ];
}
static fromCompiled(args) {
const idata = filterDataAllocLen(4);
filterData[idata+0] = args[0]; // fid
filterData[idata+1] = 0; // lastLen
filterData[idata+2] = -1; // lastBeg
filterData[idata+3] = -1; // lastEnd
return idata;
}
static keyFromArgs() {
}
static logData(idata, details) {
details.pattern.unshift('||');
}
};
registerFilterClass(FilterAnchorHnLeft);
/******************************************************************************/
const FilterAnchorHn = class extends FilterAnchorHnLeft {
static match(idata) {
return super.match(idata) && filterData[idata+3] === $patternMatchRight;
}
static compile() {
return [ FilterAnchorHn.fid ];
}
static keyFromArgs() {
}
static logData(idata, details) {