-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
storage.js
1363 lines (1184 loc) · 45.8 KB
/
storage.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
*/
/* global punycode, publicSuffixList */
'use strict';
/******************************************************************************/
µBlock.getBytesInUse = async function() {
const promises = [];
let bytesInUse;
// Not all platforms implement this method.
promises.push(
vAPI.storage.getBytesInUse instanceof Function
? vAPI.storage.getBytesInUse(null)
: undefined
);
if (
navigator.storage instanceof Object &&
navigator.storage.estimate instanceof Function
) {
promises.push(navigator.storage.estimate());
}
const results = await Promise.all(promises);
const processCount = count => {
if ( typeof count !== 'number' ) { return; }
if ( bytesInUse === undefined ) { bytesInUse = 0; }
bytesInUse += count;
return bytesInUse;
};
processCount(results[0]);
if ( results.length > 1 && results[1] instanceof Object ) {
processCount(results[1].usage);
}
µBlock.storageUsed = bytesInUse;
return bytesInUse;
};
/******************************************************************************/
µBlock.saveLocalSettings = (( ) => {
const saveAfter = 4 * 60 * 1000;
const onTimeout = ( ) => {
const µb = µBlock;
if ( µb.localSettingsLastModified > µb.localSettingsLastSaved ) {
µb.saveLocalSettings();
}
vAPI.setTimeout(onTimeout, saveAfter);
};
vAPI.setTimeout(onTimeout, saveAfter);
return function() {
this.localSettingsLastSaved = Date.now();
return vAPI.storage.set(this.localSettings);
};
})();
/******************************************************************************/
µBlock.saveUserSettings = function() {
vAPI.storage.set(this.userSettings);
};
/******************************************************************************/
µBlock.loadHiddenSettings = async function() {
const bin = await vAPI.storage.get('hiddenSettings');
if ( bin instanceof Object === false ) { return; }
const hs = bin.hiddenSettings;
if ( hs instanceof Object ) {
const hsDefault = this.hiddenSettingsDefault;
for ( const key in hsDefault ) {
if (
hsDefault.hasOwnProperty(key) &&
hs.hasOwnProperty(key) &&
typeof hs[key] === typeof hsDefault[key]
) {
this.hiddenSettings[key] = hs[key];
}
}
if ( typeof this.hiddenSettings.suspendTabsUntilReady === 'boolean' ) {
this.hiddenSettings.suspendTabsUntilReady =
this.hiddenSettings.suspendTabsUntilReady
? 'yes'
: 'unset';
}
}
this.fireDOMEvent('hiddenSettingsChanged');
};
// Note: Save only the settings which values differ from the default ones.
// This way the new default values in the future will properly apply for those
// which were not modified by the user.
µBlock.saveHiddenSettings = function() {
const bin = { hiddenSettings: {} };
for ( const prop in this.hiddenSettings ) {
if (
this.hiddenSettings.hasOwnProperty(prop) &&
this.hiddenSettings[prop] !== this.hiddenSettingsDefault[prop]
) {
bin.hiddenSettings[prop] = this.hiddenSettings[prop];
}
}
vAPI.storage.set(bin);
};
self.addEventListener('hiddenSettingsChanged', ( ) => {
const µbhs = µBlock.hiddenSettings;
self.log.verbosity = µbhs.consoleLogLevel;
vAPI.net.setOptions({
cnameIgnoreList: µbhs.cnameIgnoreList,
cnameIgnore1stParty: µbhs.cnameIgnore1stParty,
cnameIgnoreExceptions: µbhs.cnameIgnoreExceptions,
cnameIgnoreRootDocument: µbhs.cnameIgnoreRootDocument,
cnameMaxTTL: µbhs.cnameMaxTTL,
cnameReplayFullURL: µbhs.cnameReplayFullURL,
cnameUncloak: µbhs.cnameUncloak,
cnameUncloakProxied: µbhs.cnameUncloakProxied,
});
});
/******************************************************************************/
µBlock.hiddenSettingsFromString = function(raw) {
const out = Object.assign({}, this.hiddenSettingsDefault);
const lineIter = new this.LineIterator(raw);
while ( lineIter.eot() === false ) {
const line = lineIter.next();
const matches = /^\s*(\S+)\s+(.+)$/.exec(line);
if ( matches === null || matches.length !== 3 ) { continue; }
const name = matches[1];
if ( out.hasOwnProperty(name) === false ) { continue; }
const value = matches[2];
switch ( typeof out[name] ) {
case 'boolean':
if ( value === 'true' ) {
out[name] = true;
} else if ( value === 'false' ) {
out[name] = false;
}
break;
case 'string':
out[name] = value.trim();
break;
case 'number':
out[name] = parseInt(value, 10);
if ( isNaN(out[name]) ) {
out[name] = this.hiddenSettingsDefault[name];
}
break;
default:
break;
}
}
return out;
};
µBlock.stringFromHiddenSettings = function() {
const out = [];
for ( const key of Object.keys(this.hiddenSettings).sort() ) {
out.push(key + ' ' + this.hiddenSettings[key]);
}
return out.join('\n');
};
/******************************************************************************/
µBlock.savePermanentFirewallRules = function() {
vAPI.storage.set({
dynamicFilteringString: this.permanentFirewall.toString()
});
};
/******************************************************************************/
µBlock.savePermanentURLFilteringRules = function() {
vAPI.storage.set({
urlFilteringString: this.permanentURLFiltering.toString()
});
};
/******************************************************************************/
µBlock.saveHostnameSwitches = function() {
vAPI.storage.set({
hostnameSwitchesString: this.permanentSwitches.toString()
});
};
/******************************************************************************/
µBlock.saveWhitelist = function() {
vAPI.storage.set({
netWhitelist: this.arrayFromWhitelist(this.netWhitelist)
});
this.netWhitelistModifyTime = Date.now();
};
/*******************************************************************************
TODO(seamless migration):
The code related to 'remoteBlacklist' can be removed when I am confident
all users have moved to a version of uBO which no longer depends on
the property 'remoteBlacklists, i.e. v1.11 and beyond.
**/
µBlock.loadSelectedFilterLists = async function() {
const bin = await vAPI.storage.get('selectedFilterLists');
if ( bin instanceof Object && Array.isArray(bin.selectedFilterLists) ) {
this.selectedFilterLists = bin.selectedFilterLists;
return;
}
// https://github.com/gorhill/uBlock/issues/747
// Select default filter lists if first-time launch.
const lists = await this.assets.metadata();
this.saveSelectedFilterLists(this.autoSelectRegionalFilterLists(lists));
};
µBlock.saveSelectedFilterLists = function(newKeys, append = false) {
const oldKeys = this.selectedFilterLists.slice();
if ( append ) {
newKeys = newKeys.concat(oldKeys);
}
const newSet = new Set(newKeys);
// Purge unused filter lists from cache.
for ( const oldKey of oldKeys ) {
if ( newSet.has(oldKey) === false ) {
this.removeFilterList(oldKey);
}
}
newKeys = Array.from(newSet);
this.selectedFilterLists = newKeys;
return vAPI.storage.set({ selectedFilterLists: newKeys });
};
/******************************************************************************/
µBlock.applyFilterListSelection = function(details) {
let selectedListKeySet = new Set(this.selectedFilterLists);
let externalLists = this.userSettings.externalLists;
// Filter lists to select
if ( Array.isArray(details.toSelect) ) {
if ( details.merge ) {
for ( let i = 0, n = details.toSelect.length; i < n; i++ ) {
selectedListKeySet.add(details.toSelect[i]);
}
} else {
selectedListKeySet = new Set(details.toSelect);
}
}
// Imported filter lists to remove
if ( Array.isArray(details.toRemove) ) {
const removeURLFromHaystack = (haystack, needle) => {
return haystack.replace(
new RegExp(
'(^|\\n)' +
this.escapeRegex(needle) +
'(\\n|$)', 'g'),
'\n'
).trim();
};
for ( let i = 0, n = details.toRemove.length; i < n; i++ ) {
const assetKey = details.toRemove[i];
selectedListKeySet.delete(assetKey);
externalLists = removeURLFromHaystack(externalLists, assetKey);
this.removeFilterList(assetKey);
}
}
// Filter lists to import
if ( typeof details.toImport === 'string' ) {
// https://github.com/gorhill/uBlock/issues/1181
// Try mapping the URL of an imported filter list to the assetKey
// of an existing stock list.
const assetKeyFromURL = url => {
const needle = url.replace(/^https?:/, '');
const assets = this.availableFilterLists;
for ( const assetKey in assets ) {
const asset = assets[assetKey];
if ( asset.content !== 'filters' ) { continue; }
if ( typeof asset.contentURL === 'string' ) {
if ( asset.contentURL.endsWith(needle) ) { return assetKey; }
continue;
}
if ( Array.isArray(asset.contentURL) === false ) { continue; }
for ( let i = 0, n = asset.contentURL.length; i < n; i++ ) {
if ( asset.contentURL[i].endsWith(needle) ) {
return assetKey;
}
}
}
return url;
};
const importedSet = new Set(this.listKeysFromCustomFilterLists(externalLists));
const toImportSet = new Set(this.listKeysFromCustomFilterLists(details.toImport));
for ( const urlKey of toImportSet ) {
if ( importedSet.has(urlKey) ) { continue; }
const assetKey = assetKeyFromURL(urlKey);
if ( assetKey === urlKey ) {
importedSet.add(urlKey);
}
selectedListKeySet.add(assetKey);
}
externalLists = Array.from(importedSet).sort().join('\n');
}
const result = Array.from(selectedListKeySet);
if ( externalLists !== this.userSettings.externalLists ) {
this.userSettings.externalLists = externalLists;
vAPI.storage.set({ externalLists: externalLists });
}
this.saveSelectedFilterLists(result);
};
/******************************************************************************/
µBlock.listKeysFromCustomFilterLists = function(raw) {
const out = new Set();
const reIgnore = /^[!#]/;
const reValid = /^[a-z-]+:\/\/\S+/;
const lineIter = new this.LineIterator(raw);
while ( lineIter.eot() === false ) {
const location = lineIter.next().trim();
if ( reIgnore.test(location) || !reValid.test(location) ) { continue; }
out.add(location);
}
return Array.from(out);
};
/******************************************************************************/
µBlock.saveUserFilters = function(content) {
// https://github.com/gorhill/uBlock/issues/1022
// Be sure to end with an empty line.
content = content.trim();
if ( content !== '' ) { content += '\n'; }
this.removeCompiledFilterList(this.userFiltersPath);
return this.assets.put(this.userFiltersPath, content);
};
µBlock.loadUserFilters = function() {
return this.assets.get(this.userFiltersPath);
};
µBlock.appendUserFilters = async function(filters, options) {
filters = filters.trim();
if ( filters.length === 0 ) { return; }
// https://github.com/uBlockOrigin/uBlock-issues/issues/372
// Auto comment using user-defined template.
let comment = '';
if (
options instanceof Object &&
options.autoComment === true &&
this.hiddenSettings.autoCommentFilterTemplate.indexOf('{{') !== -1
) {
const d = new Date();
comment =
'! ' +
this.hiddenSettings.autoCommentFilterTemplate
.replace('{{date}}', d.toLocaleDateString())
.replace('{{time}}', d.toLocaleTimeString())
.replace('{{origin}}', options.origin);
}
const details = await this.loadUserFilters();
if ( details.error ) { return; }
// The comment, if any, will be applied if and only if it is different
// from the last comment found in the user filter list.
if ( comment !== '' ) {
const pos = details.content.lastIndexOf(comment);
if (
pos === -1 ||
details.content.indexOf('\n!', pos + 1) !== -1
) {
filters = '\n' + comment + '\n' + filters;
}
}
// https://github.com/chrisaljoudi/uBlock/issues/976
// If we reached this point, the filter quite probably needs to be
// added for sure: do not try to be too smart, trying to avoid
// duplicates at this point may lead to more issues.
await this.saveUserFilters(details.content.trim() + '\n' + filters);
const compiledFilters = this.compileFilters(
filters,
{ assetKey: this.userFiltersPath }
);
const snfe = this.staticNetFilteringEngine;
const cfe = this.cosmeticFilteringEngine;
const acceptedCount = snfe.acceptedCount + cfe.acceptedCount;
const discardedCount = snfe.discardedCount + cfe.discardedCount;
this.applyCompiledFilters(compiledFilters, true);
const entry = this.availableFilterLists[this.userFiltersPath];
const deltaEntryCount =
snfe.acceptedCount +
cfe.acceptedCount - acceptedCount;
const deltaEntryUsedCount =
deltaEntryCount -
(snfe.discardedCount + cfe.discardedCount - discardedCount);
entry.entryCount += deltaEntryCount;
entry.entryUsedCount += deltaEntryUsedCount;
vAPI.storage.set({ 'availableFilterLists': this.availableFilterLists });
this.staticNetFilteringEngine.freeze();
this.redirectEngine.freeze();
this.staticExtFilteringEngine.freeze();
this.selfieManager.destroy();
// https://www.reddit.com/r/uBlockOrigin/comments/cj7g7m/
// https://www.reddit.com/r/uBlockOrigin/comments/cnq0bi/
if ( options.killCache ) {
browser.webRequest.handlerBehaviorChanged();
}
};
µBlock.createUserFilters = function(details) {
this.appendUserFilters(details.filters, details);
// https://github.com/gorhill/uBlock/issues/1786
this.cosmeticFilteringEngine.removeFromSelectorCache(details.pageDomain);
};
/******************************************************************************/
µBlock.autoSelectRegionalFilterLists = function(lists) {
const selectedListKeys = [ this.userFiltersPath ];
for ( const key in lists ) {
if ( lists.hasOwnProperty(key) === false ) { continue; }
const list = lists[key];
if ( list.off !== true ) {
selectedListKeys.push(key);
continue;
}
if ( this.listMatchesEnvironment(list) ) {
selectedListKeys.push(key);
list.off = false;
}
}
return selectedListKeys;
};
/******************************************************************************/
µBlock.getAvailableLists = async function() {
let oldAvailableLists = {},
newAvailableLists = {};
// User filter list.
newAvailableLists[this.userFiltersPath] = {
group: 'user',
title: vAPI.i18n('1pPageName')
};
// Custom filter lists.
const importedListKeys = this.listKeysFromCustomFilterLists(
this.userSettings.externalLists
);
for ( const listKey of importedListKeys ) {
const entry = {
content: 'filters',
contentURL: listKey,
external: true,
group: 'custom',
submitter: 'user',
title: ''
};
newAvailableLists[listKey] = entry;
this.assets.registerAssetSource(listKey, entry);
}
// Convert a no longer existing stock list into an imported list.
const customListFromStockList = assetKey => {
const oldEntry = oldAvailableLists[assetKey];
if ( oldEntry === undefined || oldEntry.off === true ) { return; }
let listURL = oldEntry.contentURL;
if ( Array.isArray(listURL) ) {
listURL = listURL[0];
}
const newEntry = {
content: 'filters',
contentURL: listURL,
external: true,
group: 'custom',
submitter: 'user',
title: oldEntry.title || ''
};
newAvailableLists[listURL] = newEntry;
this.assets.registerAssetSource(listURL, newEntry);
importedListKeys.push(listURL);
this.userSettings.externalLists += '\n' + listURL;
this.userSettings.externalLists = this.userSettings.externalLists.trim();
vAPI.storage.set({ externalLists: this.userSettings.externalLists });
this.saveSelectedFilterLists([ listURL ], true);
};
// Load previously saved available lists -- these contains data
// computed at run-time, we will reuse this data if possible.
const [ bin, entries ] = await Promise.all([
vAPI.storage.get('availableFilterLists'),
this.assets.metadata(),
]);
oldAvailableLists = bin && bin.availableFilterLists || {};
for ( const assetKey in entries ) {
if ( entries.hasOwnProperty(assetKey) === false ) { continue; }
const entry = entries[assetKey];
if ( entry.content !== 'filters' ) { continue; }
newAvailableLists[assetKey] = Object.assign({}, entry);
}
// Load set of currently selected filter lists.
const listKeySet = new Set(this.selectedFilterLists);
for ( const listKey in newAvailableLists ) {
if ( newAvailableLists.hasOwnProperty(listKey) ) {
newAvailableLists[listKey].off = !listKeySet.has(listKey);
}
}
//finalize();
// Final steps:
// - reuse existing list metadata if any;
// - unregister unreferenced imported filter lists if any.
// Reuse existing metadata.
for ( const assetKey in oldAvailableLists ) {
const oldEntry = oldAvailableLists[assetKey];
const newEntry = newAvailableLists[assetKey];
// List no longer exists. If a stock list, try to convert to
// imported list if it was selected.
if ( newEntry === undefined ) {
this.removeFilterList(assetKey);
if ( assetKey.indexOf('://') === -1 ) {
customListFromStockList(assetKey);
}
continue;
}
if ( oldEntry.entryCount !== undefined ) {
newEntry.entryCount = oldEntry.entryCount;
}
if ( oldEntry.entryUsedCount !== undefined ) {
newEntry.entryUsedCount = oldEntry.entryUsedCount;
}
// This may happen if the list name was pulled from the list
// content.
// https://github.com/chrisaljoudi/uBlock/issues/982
// There is no guarantee the title was successfully extracted from
// the list content.
if (
newEntry.title === '' &&
typeof oldEntry.title === 'string' &&
oldEntry.title !== ''
) {
newEntry.title = oldEntry.title;
}
}
// Remove unreferenced imported filter lists.
for ( const assetKey in newAvailableLists ) {
const newEntry = newAvailableLists[assetKey];
if ( newEntry.submitter !== 'user' ) { continue; }
if ( importedListKeys.indexOf(assetKey) !== -1 ) { continue; }
delete newAvailableLists[assetKey];
this.assets.unregisterAssetSource(assetKey);
this.removeFilterList(assetKey);
}
return newAvailableLists;
};
/******************************************************************************/
µBlock.loadFilterLists = (( ) => {
const loadedListKeys = [];
let loadingPromise;
let t0 = 0;
const onDone = function() {
log.info(`loadFilterLists() took ${Date.now()-t0} ms`);
this.staticNetFilteringEngine.freeze();
this.staticExtFilteringEngine.freeze();
this.redirectEngine.freeze();
vAPI.net.unsuspend();
vAPI.storage.set({ 'availableFilterLists': this.availableFilterLists });
vAPI.messaging.broadcast({
what: 'staticFilteringDataChanged',
parseCosmeticFilters: this.userSettings.parseAllABPHideFilters,
ignoreGenericCosmeticFilters: this.userSettings.ignoreGenericCosmeticFilters,
listKeys: loadedListKeys
});
this.selfieManager.destroy();
this.lz4Codec.relinquish();
this.compiledFormatChanged = false;
loadingPromise = undefined;
};
const applyCompiledFilters = function(assetKey, compiled) {
const snfe = this.staticNetFilteringEngine;
const sxfe = this.staticExtFilteringEngine;
let acceptedCount = snfe.acceptedCount + sxfe.acceptedCount,
discardedCount = snfe.discardedCount + sxfe.discardedCount;
this.applyCompiledFilters(compiled, assetKey === this.userFiltersPath);
if ( this.availableFilterLists.hasOwnProperty(assetKey) ) {
const entry = this.availableFilterLists[assetKey];
entry.entryCount = snfe.acceptedCount + sxfe.acceptedCount -
acceptedCount;
entry.entryUsedCount = entry.entryCount -
(snfe.discardedCount + sxfe.discardedCount - discardedCount);
}
loadedListKeys.push(assetKey);
};
const onFilterListsReady = function(lists) {
this.availableFilterLists = lists;
vAPI.net.suspend();
this.redirectEngine.reset();
this.staticExtFilteringEngine.reset();
this.staticNetFilteringEngine.reset();
this.selfieManager.destroy();
this.staticFilteringReverseLookup.resetLists();
// We need to build a complete list of assets to pull first: this is
// because it *may* happens that some load operations are synchronous:
// This happens for assets which do not exist, ot assets with no
// content.
const toLoad = [];
for ( const assetKey in lists ) {
if ( lists.hasOwnProperty(assetKey) === false ) { continue; }
if ( lists[assetKey].off ) { continue; }
toLoad.push(
this.getCompiledFilterList(assetKey).then(details => {
applyCompiledFilters.call(
this,
details.assetKey,
details.content
);
})
);
}
return Promise.all(toLoad);
};
return function() {
if ( loadingPromise instanceof Promise === false ) {
t0 = Date.now();
loadedListKeys.length = 0;
loadingPromise = Promise.all([
this.getAvailableLists().then(lists =>
onFilterListsReady.call(this, lists)
),
this.loadRedirectResources(),
]).then(( ) => {
onDone.call(this);
});
}
return loadingPromise;
};
})();
/******************************************************************************/
µBlock.getCompiledFilterList = async function(assetKey) {
const compiledPath = 'compiled/' + assetKey;
if ( this.compiledFormatChanged === false ) {
let compiledDetails = await this.assets.get(compiledPath);
if ( compiledDetails.content !== '' ) {
compiledDetails.assetKey = assetKey;
return compiledDetails;
}
}
const rawDetails = await this.assets.get(assetKey);
// Compiling an empty string results in an empty string.
if ( rawDetails.content === '' ) {
rawDetails.assetKey = assetKey;
return rawDetails;
}
this.extractFilterListMetadata(assetKey, rawDetails.content);
// Fetching the raw content may cause the compiled content to be
// generated somewhere else in uBO, hence we try one last time to
// fetch the compiled content in case it has become available.
const compiledDetails = await this.assets.get(compiledPath);
if ( compiledDetails.content === '' ) {
compiledDetails.content = this.compileFilters(
rawDetails.content,
{ assetKey: assetKey }
);
this.assets.put(compiledPath, compiledDetails.content);
}
compiledDetails.assetKey = assetKey;
return compiledDetails;
};
/******************************************************************************/
// https://github.com/gorhill/uBlock/issues/3406
// Lower minimum update period to 1 day.
µBlock.extractFilterListMetadata = function(assetKey, raw) {
const listEntry = this.availableFilterLists[assetKey];
if ( listEntry === undefined ) { return; }
// Metadata expected to be found at the top of content.
const head = raw.slice(0, 1024);
// https://github.com/gorhill/uBlock/issues/313
// Always try to fetch the name if this is an external filter list.
if ( listEntry.title === '' || listEntry.group === 'custom' ) {
const matches = head.match(/(?:^|\n)(?:!|# )[\t ]*Title[\t ]*:([^\n]+)/i);
if ( matches !== null ) {
// https://bugs.chromium.org/p/v8/issues/detail?id=2869
// orphanizeString is to work around String.slice()
// potentially causing the whole raw filter list to be held in
// memory just because we cut out the title as a substring.
listEntry.title = this.orphanizeString(matches[1].trim());
}
}
// Extract update frequency information
const matches = head.match(/(?:^|\n)(?:!|# )[\t ]*Expires[\t ]*:[\t ]*(\d+)[\t ]*(h)?/i);
if ( matches !== null ) {
let v = Math.max(parseInt(matches[1], 10), 1);
if ( matches[2] !== undefined ) {
v = Math.ceil(v / 24);
}
if ( v !== listEntry.updateAfter ) {
this.assets.registerAssetSource(assetKey, { updateAfter: v });
}
}
};
/******************************************************************************/
µBlock.removeCompiledFilterList = function(assetKey) {
this.assets.remove('compiled/' + assetKey);
};
µBlock.removeFilterList = function(assetKey) {
this.removeCompiledFilterList(assetKey);
this.assets.remove(assetKey);
};
/******************************************************************************/
µBlock.compileFilters = function(rawText, details) {
const writer = new this.CompiledLineIO.Writer();
// Populate the writer with information potentially useful to the
// client compilers.
if ( details ) {
if ( details.assetKey ) {
writer.properties.set('assetKey', details.assetKey);
}
}
// Useful references:
// https://adblockplus.org/en/filter-cheatsheet
// https://adblockplus.org/en/filters
const staticNetFilteringEngine = this.staticNetFilteringEngine;
const staticExtFilteringEngine = this.staticExtFilteringEngine;
const lineIter = new this.LineIterator(this.processDirectives(rawText));
const parser = new vAPI.StaticFilteringParser();
parser.setMaxTokenLength(this.urlTokenizer.MAX_TOKEN_LENGTH);
while ( lineIter.eot() === false ) {
let line = lineIter.next();
while ( line.endsWith(' \\') ) {
if ( lineIter.peek(4) !== ' ' ) { break; }
line = line.slice(0, -2).trim() + lineIter.next().trim();
}
parser.analyze(line);
if ( parser.shouldIgnore() ) { continue; }
if ( parser.category === parser.CATStaticExtFilter ) {
staticExtFilteringEngine.compile(parser, writer);
continue;
}
if ( parser.category !== parser.CATStaticNetFilter ) { continue; }
// https://github.com/gorhill/uBlock/issues/2599
// convert hostname to punycode if needed
if ( parser.patternHasUnicode() && parser.toPunycode() === false ) {
continue;
}
staticNetFilteringEngine.compile(parser, writer);
}
return writer.toString();
};
/******************************************************************************/
// https://github.com/gorhill/uBlock/issues/1395
// Added `firstparty` argument: to avoid discarding cosmetic filters when
// applying 1st-party filters.
µBlock.applyCompiledFilters = function(rawText, firstparty) {
if ( rawText === '' ) { return; }
let reader = new this.CompiledLineIO.Reader(rawText);
this.staticNetFilteringEngine.fromCompiledContent(reader);
this.staticExtFilteringEngine.fromCompiledContent(reader, {
skipGenericCosmetic: this.userSettings.ignoreGenericCosmeticFilters,
skipCosmetic: !firstparty && !this.userSettings.parseAllABPHideFilters
});
};
/******************************************************************************/
// https://github.com/AdguardTeam/AdguardBrowserExtension/issues/917
µBlock.processDirectives = function(content) {
const reIf = /^!#(if|endif)\b([^\n]*)/gm;
const stack = [];
const shouldDiscard = ( ) => stack.some(v => v);
const parts = [];
let beg = 0, discard = false;
while ( beg < content.length ) {
const match = reIf.exec(content);
if ( match === null ) { break; }
switch ( match[1] ) {
case 'if':
let expr = match[2].trim();
const target = expr.charCodeAt(0) === 0x21 /* '!' */;
if ( target ) { expr = expr.slice(1); }
const token = this.processDirectives.tokens.get(expr);
const startDiscard =
token === 'false' &&
target === false ||
token !== undefined &&
vAPI.webextFlavor.soup.has(token) === target;
if ( discard === false && startDiscard ) {
parts.push(content.slice(beg, match.index));
discard = true;
}
stack.push(startDiscard);
break;
case 'endif':
stack.pop();
const stopDiscard = shouldDiscard() === false;
if ( discard && stopDiscard ) {
beg = match.index + match[0].length + 1;
discard = false;
}
break;
default:
break;
}
}
if ( stack.length === 0 && parts.length !== 0 ) {
parts.push(content.slice(beg));
content = parts.join('\n');
}
return content.trim();
};
µBlock.processDirectives.tokens = new Map([
[ 'ext_ublock', 'ublock' ],
[ 'env_chromium', 'chromium' ],
[ 'env_edge', 'edge' ],
[ 'env_firefox', 'firefox' ],
[ 'env_legacy', 'legacy' ],
[ 'env_mobile', 'mobile' ],
[ 'env_safari', 'safari' ],
[ 'cap_html_filtering', 'html_filtering' ],
[ 'cap_user_stylesheet', 'user_stylesheet' ],
[ 'false', 'false' ],
]);
/******************************************************************************/
µBlock.loadRedirectResources = async function() {
try {
const success = await this.redirectEngine.resourcesFromSelfie();
if ( success === true ) { return true; }
const fetchPromises = [
this.redirectEngine.loadBuiltinResources()
];
const userResourcesLocation = this.hiddenSettings.userResourcesLocation;
if ( userResourcesLocation !== 'unset' ) {
for ( const url of userResourcesLocation.split(/\s+/) ) {
fetchPromises.push(this.assets.fetchText(url));
}
}
const results = await Promise.all(fetchPromises);
if ( Array.isArray(results) === false ) { return results; }
let content = '';
for ( let i = 1; i < results.length; i++ ) {
const result = results[i];
if (
result instanceof Object === false ||
typeof result.content !== 'string' ||
result.content === ''
) {
continue;
}
content += '\n\n' + result.content;
}
this.redirectEngine.resourcesFromString(content);
this.redirectEngine.selfieFromResources();
} catch(ex) {
log.info(ex);
return false;
}
return true;
};
/******************************************************************************/
µBlock.loadPublicSuffixList = async function() {
if ( this.hiddenSettings.disableWebAssembly !== true ) {
publicSuffixList.enableWASM();
}
try {
const result = await this.assets.get(`compiled/${this.pslAssetKey}`);
if ( publicSuffixList.fromSelfie(result.content, this.base64) ) {
return;
}
} catch (ex) {
log.info(ex);
}
const result = await this.assets.get(this.pslAssetKey);
if ( result.content !== '' ) {
this.compilePublicSuffixList(result.content);
}
};
µBlock.compilePublicSuffixList = function(content) {
publicSuffixList.parse(content, punycode.toASCII);
this.assets.put(
'compiled/' + this.pslAssetKey,
publicSuffixList.toSelfie(µBlock.base64)
);
};
/******************************************************************************/
// This is to be sure the selfie is generated in a sane manner: the selfie will
// be generated if the user doesn't change his filter lists selection for
// some set time.
µBlock.selfieManager = (( ) => {
const µb = µBlock;