1
0
mirror of https://github.com/gorhill/uBlock.git synced 2024-11-05 18:32:30 +01:00
uBlock/src/js/background.js

216 lines
7.3 KiB
JavaScript
Raw Normal View History

2014-06-24 00:42:43 +02:00
/*******************************************************************************
uBlock Origin - a browser extension to block requests.
2018-08-06 18:34:41 +02:00
Copyright (C) 2014-present Raymond Hill
2014-06-24 00:42:43 +02:00
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';
2014-08-21 05:19:27 +02:00
/******************************************************************************/
// Not all platforms may have properly declared vAPI.webextFlavor.
if ( vAPI.webextFlavor === undefined ) {
vAPI.webextFlavor = { major: 0, soup: new Set([ 'ublock' ]) };
}
/******************************************************************************/
const µBlock = (( ) => { // jshint ignore:line
Squashed commit of the following: commit 7c6cacc59b27660fabacb55d668ef099b222a9e6 Author: Raymond Hill <rhill@raymondhill.net> Date: Sat Nov 3 08:52:51 2018 -0300 code review: finalize support for wasm-based hntrie commit 8596ed80e3bdac2c36e3c860b51e7189f6bc8487 Merge: cbe1f2e 000eb82 Author: Raymond Hill <rhill@raymondhill.net> Date: Sat Nov 3 08:41:40 2018 -0300 Merge branch 'master' of github.com:gorhill/uBlock into trie-wasm commit cbe1f2e2f38484d42af3204ec7f1b5decd30f99e Merge: 270fc7f dbb7e80 Author: Raymond Hill <rhill@raymondhill.net> Date: Fri Nov 2 17:43:20 2018 -0300 Merge branch 'master' of github.com:gorhill/uBlock into trie-wasm commit 270fc7f9b3b73d79e6355522c1a42ce782fe7e5c Merge: d2a89cf d693d4f Author: Raymond Hill <rhill@raymondhill.net> Date: Fri Nov 2 16:21:08 2018 -0300 Merge branch 'master' of github.com:gorhill/uBlock into trie-wasm commit d2a89cf28f0816ffd4617c2c7b4ccfcdcc30e1b4 Merge: d7afc78 649f82f Author: Raymond Hill <rhill@raymondhill.net> Date: Fri Nov 2 14:54:58 2018 -0300 Merge branch 'master' of github.com:gorhill/uBlock into trie-wasm commit d7afc78b5f5675d7d34c5a1d0ec3099a77caef49 Author: Raymond Hill <rhill@raymondhill.net> Date: Fri Nov 2 13:56:11 2018 -0300 finalize wasm-based hntrie implementation commit e7b9e043cf36ad055791713e34eb0322dec84627 Author: Raymond Hill <rhill@raymondhill.net> Date: Fri Nov 2 08:14:02 2018 -0300 add first-pass implementation of wasm version of hntrie commit 1015cb34624f3ef73ace58b58fe4e03dfc59897f Author: Raymond Hill <rhill@raymondhill.net> Date: Wed Oct 31 17:16:47 2018 -0300 back up draft work toward experimenting with wasm hntries
2018-11-03 12:58:46 +01:00
const hiddenSettingsDefault = {
allowGenericProceduralFilters: false,
assetFetchTimeout: 30,
autoCommentFilterTemplate: '{{date}} {{origin}}',
autoUpdateAssetFetchPeriod: 120,
autoUpdateDelayAfterLaunch: 180,
autoUpdatePeriod: 7,
benchmarkDatasetURL: 'unset',
blockingProfiles: '11111/#F00 11011/#C0F 11001/#00F 00001',
cacheStorageAPI: 'unset',
cacheStorageCompression: true,
cacheControlForFirefox1376932: 'no-cache, no-store, must-revalidate',
cloudStorageCompression: false,
Add ability to uncloak CNAME records Related issue: - https://github.com/uBlockOrigin/uBlock-issues/issues/780 New webext permission added: `dns`, which purpose is to allow an extension to fetch the DNS record of specific hostnames, reference documentation: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/dns The webext API `dns` is available in Firefox 60+ only. The new API will enable uBO to "uncloak" the actual hostname used in network requests. The ability is currently disabled by default for now -- this is only a first commit related to the above issue to allow advanced users to immediately use the new ability. Four advanced settings have been created to control the uncloaking of actual hostnames: cnameAliasList: a space-separated list of hostnames. Default value: unset => empty list. Special value: * => all hostnames. A space-separated list of hostnames => this tells uBO to "uncloak" the hostnames in the list will. cnameIgnoreList: a space-separated list of hostnames. Default value: unset => empty list. Special value: * => all hostnames. A space-separated list of hostnames => this tells uBO to NOT re-run the network request through uBO's filtering engine with the CNAME hostname. This is useful to exclude commonly used actual hostnames from being re-run through uBO's filtering engine, so as to avoid pointless overhead. cnameIgnore1stParty: boolean. Default value: true. Whether uBO should ignore to re-run a network request through the filtering engine when the CNAME hostname is 1st-party to the alias hostname. cnameMaxTTL: number of minutes. Default value: 120. This tells uBO to clear its CNAME cache after the specified time. For efficiency purpose, uBO will cache alias=>CNAME associations for reuse so as to reduce calls to `browser.dns.resolve`. All the associations will be cleared after the specified time to ensure the map does not grow too large and too ensure uBO uses up to date CNAME information.
2019-11-19 18:05:33 +01:00
cnameIgnoreList: 'unset',
cnameIgnore1stParty: true,
cnameIgnoreExceptions: true,
cnameIgnoreRootDocument: true,
cnameMaxTTL: 120,
cnameReplayFullURL: false,
cnameUncloak: true,
cnameUncloakProxied: false,
Refactor selfie generation into a more flexible persistence mechanism The motivation is to address the higher peak memory usage at launch time with 3rd-gen HNTrie when a selfie was present. The selfie generation prior to this change was to collect all filtering data into a single data structure, and then to serialize that whole structure at once into storage (using JSON.stringify). However, HNTrie serialization requires that a large UintArray32 be converted into a plain JS array, which itslef would be indirectly converted into a JSON string. This was the main reason why peak memory usage would be higher at launch from selfie, since the JSON string would need to be wholly unserialized into JS objects, which themselves would need to be converted into more specialized data structures (like that Uint32Array one). The solution to lower peak memory usage at launch is to refactor selfie generation to allow a more piecemeal approach: each filtering component is given the ability to serialize itself rather than to be forced to be embedded in the master selfie. With this approach, the HNTrie buffer can now serialize to its own storage by converting the buffer data directly into a string which can be directly sent to storage. This avoiding expensive intermediate steps such as converting into a JS array and then to a JSON string. As part of the refactoring, there was also opportunistic code upgrade to ES6 and Promise (eventually all of uBO's code will be proper ES6). Additionally, the polyfill to bring getBytesInUse() to Firefox has been revisited to replace the rather expensive previous implementation with an implementation with virtually no overhead.
2019-02-14 19:33:55 +01:00
consoleLogLevel: 'unset',
debugScriptlets: false,
debugScriptletInjector: false,
disableWebAssembly: false,
extensionUpdateForceReload: false,
ignoreRedirectFilters: false,
ignoreScriptInjectFilters: false,
filterAuthorMode: false,
loggerPopupType: 'popup',
manualUpdateAssetFetchPeriod: 500,
popupFontSize: 'unset',
popupPanelDisabledSections: 0,
popupPanelLockedSections: 0,
popupPanelHeightMode: 0,
requestJournalProcessPeriod: 1000,
selfieAfter: 3,
strictBlockingBypassDuration: 120,
suspendTabsUntilReady: 'unset',
uiPopupConfig: 'undocumented',
uiFlavor: 'unset',
uiStyles: 'unset',
uiTheme: 'unset',
updateAssetBypassBrowserCache: false,
userResourcesLocation: 'unset',
};
return {
userSettings: {
advancedUserEnabled: false,
alwaysDetachLogger: true,
autoUpdate: true,
cloudStorageEnabled: false,
collapseBlocked: true,
colorBlindFriendly: false,
contextMenuEnabled: true,
dynamicFilteringEnabled: false,
externalLists: [],
firewallPaneMinimized: true,
hyperlinkAuditingDisabled: true,
ignoreGenericCosmeticFilters: vAPI.webextFlavor.soup.has('mobile'),
largeMediaSize: 50,
parseAllABPHideFilters: true,
popupPanelSections: 0b111,
prefetchingDisabled: true,
requestLogMaxEntries: 1000,
showIconBadge: true,
tooltipsDisabled: false,
webrtcIPAddressHidden: false,
},
hiddenSettingsDefault: hiddenSettingsDefault,
hiddenSettings: Object.assign({}, hiddenSettingsDefault),
// Features detection.
privacySettingsSupported: vAPI.browserSettings instanceof Object,
cloudStorageSupported: vAPI.cloud instanceof Object,
canFilterResponseData: typeof browser.webRequest.filterResponseData === 'function',
canInjectScriptletsNow: vAPI.webextFlavor.soup.has('chromium'),
// https://github.com/chrisaljoudi/uBlock/issues/180
// Whitelist directives need to be loaded once the PSL is available
netWhitelist: new Map(),
netWhitelistModifyTime: 0,
netWhitelistDefault: [
'about-scheme',
'chrome-extension-scheme',
'chrome-scheme',
'edge-scheme',
'moz-extension-scheme',
'opera-scheme',
'vivaldi-scheme',
'wyciwyg-scheme', // Firefox's "What-You-Cache-Is-What-You-Get"
],
localSettings: {
blockedRequestCount: 0,
allowedRequestCount: 0,
},
localSettingsLastModified: 0,
localSettingsLastSaved: 0,
// Read-only
systemSettings: {
Add new filter option `queryprune=` Related issue: - https://github.com/uBlockOrigin/uBlock-issues/issues/760 The purpose of this new network filter option is to remove query parameters form the URL of network requests. The name `queryprune` has been picked over `querystrip` since the purpose of the option is to remove some parameters from the URL rather than all parameters. `queryprune` is a modifier option (like `csp`) in that it does not cause a network request to be blocked but rather modified before being emitted. `queryprune` must be assigned a value, which value will determine which parameters from a query string will be removed. The syntax for the value is that of regular expression *except* for the following rules: - do not wrap the regex directive between `/` - do not use regex special values `^` and `$` - do not use literal comma character in the value, though you can use hex-encoded version, `\x2c` - to match the start of a query parameter, prepend `|` - to match the end of a query parameter, append `|` `queryprune` regex-like values will be tested against each key-value parameter pair as `[key]=[value]` string. This way you can prune according to either the key, the value, or both. This commit introduces the concept of modifier filter options, which as of now are: - `csp=` - `queryprune=` They both work in similar way when used with `important` option or when used in exception filters. Modifier options can apply to any network requests, hence the logger reports the type of the network requests, and no longer use the modifier as the type, i.e. `csp` filters are no longer reported as requests of type `csp`. Though modifier options can apply to any network requests, for the time being the `csp=` modifier option still apply only to top or embedded (frame) documents, just as before. In some future we may want to apply `csp=` directives to network requests of type script, to control the behavior of service workers for example. A new built-in filter expression has been added to the logger: "modified", which allow to see all the network requests which were modified before being emitted. The translation work for this new option will be available in a future commit.
2020-10-31 15:42:53 +01:00
compiledMagic: 30, // Increase when compiled format changes
selfieMagic: 30, // Increase when selfie format changes
},
// https://github.com/uBlockOrigin/uBlock-issues/issues/759#issuecomment-546654501
// The assumption is that cache storage state reflects whether
// compiled or selfie assets are available or not. The properties
// below is to no longer rely on this assumption -- though it's still
// not clear how the assumption could be wrong, and it's still not
// clear whether relying on those properties will really solve the
// issue. It's just an attempt at hardening.
compiledFormatChanged: false,
selfieIsInvalid: false,
restoreBackupSettings: {
lastRestoreFile: '',
lastRestoreTime: 0,
lastBackupFile: '',
lastBackupTime: 0,
},
commandShortcuts: new Map(),
// Allows to fully customize uBO's assets, typically set through admin
// settings. The content of 'assets.json' will also tell which filter
// lists to enable by default when uBO is first installed.
assetsBootstrapLocation: undefined,
userFiltersPath: 'user-filters',
pslAssetKey: 'public_suffix_list.dat',
selectedFilterLists: [],
availableFilterLists: {},
badLists: new Map(),
// https://github.com/uBlockOrigin/uBlock-issues/issues/974
// This can be used to defer filtering decision-making.
readyToFilter: false,
2018-02-26 19:59:16 +01:00
pageStores: new Map(),
pageStoresToken: 0,
storageQuota: vAPI.storage.QUOTA_BYTES,
storageUsed: 0,
noopFunc: function(){},
apiErrorCount: 0,
2017-09-06 01:49:48 +02:00
maybeGoodPopup: {
tabId: 0,
url: '',
2017-09-06 01:49:48 +02:00
},
epickerArgs: {
eprom: null,
mouse: false,
target: '',
zap: false,
},
scriptlets: {},
cspNoInlineScript: "script-src 'unsafe-eval' * blob: data:",
cspNoScripting: 'script-src http: https:',
cspNoInlineFont: 'font-src *',
liveBlockingProfiles: [],
blockingProfileColorCache: new Map(),
};
2014-06-24 00:42:43 +02:00
})();
/******************************************************************************/