1
0
mirror of https://github.com/gorhill/uBlock.git synced 2024-09-29 22:27:12 +02:00
uBlock/src/js/messaging.js

1780 lines
52 KiB
JavaScript
Raw Normal View History

2014-06-24 00:42:43 +02:00
/*******************************************************************************
uBlock Origin - a browser extension to block requests.
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
*/
/******************************************************************************/
/******************************************************************************/
2016-08-06 18:05:01 +02:00
'use strict';
// https://github.com/uBlockOrigin/uBlock-issues/issues/710
// Listeners have a name and a "privileged" status.
// The nameless default handler is always deemed "privileged".
// Messages from privileged ports must never relayed to listeners
// which are not privileged.
/******************************************************************************/
/******************************************************************************/
// Default handler
// priviledged
{
// >>>>> start of local scope
const µb = µBlock;
const clickToLoad = function(request, sender) {
const { tabId, frameId } = sender;
if ( tabId === undefined || frameId === undefined ) { return false; }
const pageStore = µb.pageStoreFromTabId(tabId);
if ( pageStore === null ) { return false; }
pageStore.clickToLoad(frameId, request.frameURL);
return true;
};
const getDomainNames = function(targets) {
const µburi = µb.URI;
return targets.map(target => {
if ( typeof target !== 'string' ) { return ''; }
return target.indexOf('/') !== -1
? µburi.domainFromURI(target) || ''
: µburi.domainFromHostname(target) || target;
});
};
const onMessage = function(request, sender, callback) {
// Async
switch ( request.what ) {
case 'getAssetContent':
// https://github.com/chrisaljoudi/uBlock/issues/417
µb.assets.get(request.url, {
dontCache: true,
needSourceURL: true,
}).then(result => {
callback(result);
});
return;
case 'listsFromNetFilter':
µb.staticFilteringReverseLookup.fromNetFilter(
Expand bidi-trie usage in static network filtering engine Related issues: - https://github.com/uBlockOrigin/uBlock-issues/issues/761 - https://github.com/uBlockOrigin/uBlock-issues/issues/528 The previous bidi-trie code could only hold filters which are plain pattern, i.e. no wildcard characters, and which had no origin option (`domain=`), right and/or left anchor, and no `csp=` option. Example of filters that could be moved into a bidi-trie data structure: &ad_box_ /w/d/capu.php?z=$script,third-party ||liveonlinetv247.com/images/muvixx-150x50-watch-now-in-hd-play-btn.gif Examples of filters that could NOT be moved to a bidi-trie: -adap.$domain=~l-adap.org /tsc.php?*&ses= ||ibsrv.net/*forumsponsor$domain=[...] @@||imgspice.com/jquery.cookie.js|$script ||view.atdmt.com^*/iview/$third-party ||postimg.cc/image/$csp=[...] Ideally the filters above should be able to be moved to a bidi-trie since they are basically plain patterns, or at least partially moved to a bidi-trie when there is only a single wildcard (i.e. made of two plain patterns). Also, there were two distinct bidi-tries in which plain-pattern filters can be moved to: one for patterns without hostname anchoring and another one for patterns with hostname-anchoring. This was required because the hostname-anchored patterns have an extra condition which is outside the bidi-trie knowledge. This commit expands the number of filters which can be stored in the bidi-trie, and also remove the need to use two distinct bidi-tries. - Added ability to associate a pattern with an integer in the bidi-trie [1]. - The bidi-trie match code passes this externally provided integer when calling an externally provided method used for testing extra conditions that may be present for a plain pattern found to be matching in the bidi-trie. - Decomposed existing filters into smaller logical units: - FilterPlainLeftAnchored => FilterPatternPlain + FilterAnchorLeft - FilterPlainRightAnchored => FilterPatternPlain + FilterAnchorRight - FilterExactMatch => FilterPatternPlain + FilterAnchorLeft + FilterAnchorRight - FilterPlainHnAnchored => FilterPatternPlain + FilterAnchorHn - FilterWildcard1 => FilterPatternPlain + [ FilterPatternLeft or FilterPatternRight ] - FilterWildcard1HnAnchored => FilterPatternPlain + [ FilterPatternLeft or FilterPatternRight ] + FilterAnchorHn - FilterGenericHnAnchored => FilterPatternGeneric + FilterAnchorHn - FilterGenericHnAndRightAnchored => FilterPatternGeneric + FilterAnchorRight + FilterAnchorHn - FilterOriginMixedSet => FilterOriginMissSet + FilterOriginHitSet - Instances of FilterOrigin[...], FilterDataHolder can also be added to a composite filter to represent `domain=` and `csp=` options. - Added a new filter class, FilterComposite, for filters which are a combination of two or more logical units. A FilterComposite instance is a match when *all* filters composing it are a match. Since filters are now encoded into combination of smaller units, it becomes possible to extract the FilterPatternPlain component and store it in the bidi-trie, and use the integer as a handle for the remaining extra conditions, if any. Since a single pattern in the bidi-trie may be a component for different filters, the associated integer points to a sequence of extra conditions, and a match occurs as soon as one of the extra conditions (which may itself be a sequence of conditions) is fulfilled. Decomposing filters which are currently single instance into sequences of smaller logical filters means increasing the storage and CPU overhead when evaluating such filters. The CPU overhead is compensated by the fact that more filters can now moved into the bidi-trie, where the first match is efficiently evaluated. The extra conditions have to be evaluated if and only if there is a match in the bidi-trie. The storage overhead is compensated by the bidi-trie's intrinsic nature of merging similar patterns. Furthermore, the storage overhead is reduced by no longer using JavaScript array to store collection of filters (which is what FilterComposite is): the same technique used in [2] is imported to store sequences of filters. A sequence of filters is a sequence of integer pairs where the first integer is an index to an actual filter instance stored in a global array of filters (`filterUnits`), while the second integer is an index to the next pair in the sequence -- which means all sequences of filters are encoded in one single array of integers (`filterSequences` => Uint32Array). As a result, a sequence of filters can be represented by one single integer -- an index to the first pair -- regardless of the number of filters in the sequence. This representation is further leveraged to replace the use of JavaScript array in FilterBucket [3], which used a JavaScript array to store collection of filters. Doing so means there is no more need for FilterPair [4], which purpose was to be a lightweight representation when there was only two filters in a collection. As a result of the above changes, the map of `token` (integer) => filter instance (object) used to associate tokens to filters or collections of filters is replaced with a more efficient map of `token` (integer) to filter unit index (integer) to lookup a filter object from the global `filterUnits` array. Another consequence of using one single global array to store all filter instances means we can reuse existing instances when a logical filter instance is parameter-less, which is the case for FilterAnchorLeft, FilterAnchorRight, FilterAnchorHn, the index to these single instances is reused where needed. `urlTokenizer` now stores the character codes of the scanned URL into a bidi-trie buffer, for reuse when string matching methods are called. New method: `tokenHistogram()`, used to generate histograms of occurrences of token extracted from URLs in built-in benchmark. The top results of the "miss" histogram are used as "bad tokens", i.e. tokens to avoid if possible when compiling filter lists. All plain pattern strings are now stored in the bidi-trie memory buffer, regardless of whether they will be used in the trie proper or not. Three methods have been added to the bidi-trie to test stored string against the URL which is also stored in then bidi-trie. FilterParser is now instanciated on demand and released when no longer used. *** [1] https://github.com/gorhill/uBlock/blob/135a45a878f5b93bc538f822981e3a42b1e9073f/src/js/strie.js#L120 [2] https://github.com/gorhill/uBlock/commit/e94024d350b066e4e04a772b0a3dbc69daab3fb7 [3] https://github.com/gorhill/uBlock/blob/135a45a878f5b93bc538f822981e3a42b1e9073f/src/js/static-net-filtering.js#L1630 [4] https://github.com/gorhill/uBlock/blob/135a45a878f5b93bc538f822981e3a42b1e9073f/src/js/static-net-filtering.js#L1566
2019-10-21 14:15:58 +02:00
request.rawFilter
).then(response => {
callback(response);
});
return;
case 'listsFromCosmeticFilter':
Expand bidi-trie usage in static network filtering engine Related issues: - https://github.com/uBlockOrigin/uBlock-issues/issues/761 - https://github.com/uBlockOrigin/uBlock-issues/issues/528 The previous bidi-trie code could only hold filters which are plain pattern, i.e. no wildcard characters, and which had no origin option (`domain=`), right and/or left anchor, and no `csp=` option. Example of filters that could be moved into a bidi-trie data structure: &ad_box_ /w/d/capu.php?z=$script,third-party ||liveonlinetv247.com/images/muvixx-150x50-watch-now-in-hd-play-btn.gif Examples of filters that could NOT be moved to a bidi-trie: -adap.$domain=~l-adap.org /tsc.php?*&ses= ||ibsrv.net/*forumsponsor$domain=[...] @@||imgspice.com/jquery.cookie.js|$script ||view.atdmt.com^*/iview/$third-party ||postimg.cc/image/$csp=[...] Ideally the filters above should be able to be moved to a bidi-trie since they are basically plain patterns, or at least partially moved to a bidi-trie when there is only a single wildcard (i.e. made of two plain patterns). Also, there were two distinct bidi-tries in which plain-pattern filters can be moved to: one for patterns without hostname anchoring and another one for patterns with hostname-anchoring. This was required because the hostname-anchored patterns have an extra condition which is outside the bidi-trie knowledge. This commit expands the number of filters which can be stored in the bidi-trie, and also remove the need to use two distinct bidi-tries. - Added ability to associate a pattern with an integer in the bidi-trie [1]. - The bidi-trie match code passes this externally provided integer when calling an externally provided method used for testing extra conditions that may be present for a plain pattern found to be matching in the bidi-trie. - Decomposed existing filters into smaller logical units: - FilterPlainLeftAnchored => FilterPatternPlain + FilterAnchorLeft - FilterPlainRightAnchored => FilterPatternPlain + FilterAnchorRight - FilterExactMatch => FilterPatternPlain + FilterAnchorLeft + FilterAnchorRight - FilterPlainHnAnchored => FilterPatternPlain + FilterAnchorHn - FilterWildcard1 => FilterPatternPlain + [ FilterPatternLeft or FilterPatternRight ] - FilterWildcard1HnAnchored => FilterPatternPlain + [ FilterPatternLeft or FilterPatternRight ] + FilterAnchorHn - FilterGenericHnAnchored => FilterPatternGeneric + FilterAnchorHn - FilterGenericHnAndRightAnchored => FilterPatternGeneric + FilterAnchorRight + FilterAnchorHn - FilterOriginMixedSet => FilterOriginMissSet + FilterOriginHitSet - Instances of FilterOrigin[...], FilterDataHolder can also be added to a composite filter to represent `domain=` and `csp=` options. - Added a new filter class, FilterComposite, for filters which are a combination of two or more logical units. A FilterComposite instance is a match when *all* filters composing it are a match. Since filters are now encoded into combination of smaller units, it becomes possible to extract the FilterPatternPlain component and store it in the bidi-trie, and use the integer as a handle for the remaining extra conditions, if any. Since a single pattern in the bidi-trie may be a component for different filters, the associated integer points to a sequence of extra conditions, and a match occurs as soon as one of the extra conditions (which may itself be a sequence of conditions) is fulfilled. Decomposing filters which are currently single instance into sequences of smaller logical filters means increasing the storage and CPU overhead when evaluating such filters. The CPU overhead is compensated by the fact that more filters can now moved into the bidi-trie, where the first match is efficiently evaluated. The extra conditions have to be evaluated if and only if there is a match in the bidi-trie. The storage overhead is compensated by the bidi-trie's intrinsic nature of merging similar patterns. Furthermore, the storage overhead is reduced by no longer using JavaScript array to store collection of filters (which is what FilterComposite is): the same technique used in [2] is imported to store sequences of filters. A sequence of filters is a sequence of integer pairs where the first integer is an index to an actual filter instance stored in a global array of filters (`filterUnits`), while the second integer is an index to the next pair in the sequence -- which means all sequences of filters are encoded in one single array of integers (`filterSequences` => Uint32Array). As a result, a sequence of filters can be represented by one single integer -- an index to the first pair -- regardless of the number of filters in the sequence. This representation is further leveraged to replace the use of JavaScript array in FilterBucket [3], which used a JavaScript array to store collection of filters. Doing so means there is no more need for FilterPair [4], which purpose was to be a lightweight representation when there was only two filters in a collection. As a result of the above changes, the map of `token` (integer) => filter instance (object) used to associate tokens to filters or collections of filters is replaced with a more efficient map of `token` (integer) to filter unit index (integer) to lookup a filter object from the global `filterUnits` array. Another consequence of using one single global array to store all filter instances means we can reuse existing instances when a logical filter instance is parameter-less, which is the case for FilterAnchorLeft, FilterAnchorRight, FilterAnchorHn, the index to these single instances is reused where needed. `urlTokenizer` now stores the character codes of the scanned URL into a bidi-trie buffer, for reuse when string matching methods are called. New method: `tokenHistogram()`, used to generate histograms of occurrences of token extracted from URLs in built-in benchmark. The top results of the "miss" histogram are used as "bad tokens", i.e. tokens to avoid if possible when compiling filter lists. All plain pattern strings are now stored in the bidi-trie memory buffer, regardless of whether they will be used in the trie proper or not. Three methods have been added to the bidi-trie to test stored string against the URL which is also stored in then bidi-trie. FilterParser is now instanciated on demand and released when no longer used. *** [1] https://github.com/gorhill/uBlock/blob/135a45a878f5b93bc538f822981e3a42b1e9073f/src/js/strie.js#L120 [2] https://github.com/gorhill/uBlock/commit/e94024d350b066e4e04a772b0a3dbc69daab3fb7 [3] https://github.com/gorhill/uBlock/blob/135a45a878f5b93bc538f822981e3a42b1e9073f/src/js/static-net-filtering.js#L1630 [4] https://github.com/gorhill/uBlock/blob/135a45a878f5b93bc538f822981e3a42b1e9073f/src/js/static-net-filtering.js#L1566
2019-10-21 14:15:58 +02:00
µb.staticFilteringReverseLookup.fromCosmeticFilter(
request
).then(response => {
callback(response);
});
return;
2015-06-26 06:08:41 +02:00
case 'reloadAllFilters':
µb.loadFilterLists().then(( ) => { callback(); });
2015-06-26 06:08:41 +02:00
return;
case 'scriptlet':
µb.scriptlets.inject(request.tabId, request.scriptlet, callback);
return;
case 'sfneBenchmark':
µb.staticNetFilteringEngine.benchmark().then(result => {
callback(result);
});
return;
default:
break;
}
// Sync
let response;
switch ( request.what ) {
2017-01-22 22:05:16 +01:00
case 'applyFilterListSelection':
response = µb.applyFilterListSelection(request);
break;
case 'clickToLoad':
response = clickToLoad(request, sender);
break;
case 'createUserFilter':
µb.createUserFilters(request);
break;
case 'forceUpdateAssets':
µb.scheduleAssetUpdater(0);
2017-12-30 23:38:07 +01:00
µb.assets.updateStart({
delay: µb.hiddenSettings.manualUpdateAssetFetchPeriod
});
break;
2014-12-01 17:25:33 +01:00
case 'getAppData':
2018-05-17 18:45:57 +02:00
response = {
name: browser.runtime.getManifest().name,
version: vAPI.app.version,
canBenchmark: µb.hiddenSettings.benchmarkDatasetURL !== 'unset',
2018-05-17 18:45:57 +02:00
};
break;
case 'getDomainNames':
response = getDomainNames(request.targets);
break;
2016-03-06 16:51:06 +01:00
case 'getWhitelist':
response = {
whitelist: µb.arrayFromWhitelist(µb.netWhitelist),
whitelistDefault: µb.netWhitelistDefault,
reBadHostname: µb.reWhitelistBadHostname.source,
reHostnameExtractor: µb.reWhitelistHostnameExtractor.source
};
2016-03-06 16:51:06 +01:00
break;
case 'launchElementPicker':
// Launched from some auxiliary pages, clear context menu coords.
µb.epickerArgs.mouse = false;
µb.elementPickerExec(request.tabId, 0, request.targetURL, request.zap);
break;
case 'gotoURL':
2016-09-16 23:41:17 +02:00
µb.openNewTab(request.details);
break;
case 'reloadTab':
if ( vAPI.isBehindTheSceneTabId(request.tabId) === false ) {
2018-01-07 23:53:33 +01:00
vAPI.tabs.reload(request.tabId, request.bypassCache === true);
if ( request.select && vAPI.tabs.select ) {
vAPI.tabs.select(request.tabId);
}
}
break;
2016-03-06 16:51:06 +01:00
case 'setWhitelist':
µb.netWhitelist = µb.whitelistFromString(request.whitelist);
µb.saveWhitelist();
break;
case 'toggleHostnameSwitch':
µb.toggleHostnameSwitch(request);
break;
2015-03-27 18:00:55 +01:00
case 'uiStyles':
response = {
uiStyles: µb.hiddenSettings.uiStyles,
uiTheme: vAPI.webextFlavor.soup.has('devbuild')
? µb.hiddenSettings.uiTheme
: 'unset',
};
break;
case 'userSettings':
response = µb.changeUserSettings(request.name, request.value);
if (
vAPI.net.canUncloakCnames !== true &&
response instanceof Object
) {
response.cnameUncloakEnabled = undefined;
}
break;
default:
return vAPI.messaging.UNHANDLED;
}
callback(response);
};
vAPI.messaging.setup(onMessage);
// <<<<< end of local scope
}
2014-09-14 22:20:40 +02:00
/******************************************************************************/
2014-06-24 00:42:43 +02:00
/******************************************************************************/
// Channel:
// popupPanel
// privileged
2014-09-28 18:05:46 +02:00
{
// >>>>> start of local scope
2014-06-24 00:42:43 +02:00
const µb = µBlock;
2014-06-24 00:42:43 +02:00
const createCounts = ( ) => {
return {
blocked: { any: 0, frame: 0, script: 0 },
allowed: { any: 0, frame: 0, script: 0 },
};
};
const getHostnameDict = function(hostnameDetailsMap, out) {
const hnDict = Object.create(null);
const cnMap = [];
const createDictEntry = (domain, hostname, details) => {
const cname = vAPI.net.canonicalNameFromHostname(hostname);
if ( cname !== undefined ) {
cnMap.push([ cname, hostname ]);
}
hnDict[hostname] = { domain, counts: details.counts };
};
for ( const hnDetails of hostnameDetailsMap.values() ) {
const hostname = hnDetails.hostname;
if ( hnDict[hostname] !== undefined ) { continue; }
const domain = vAPI.domainFromHostname(hostname) || hostname;
const dnDetails =
hostnameDetailsMap.get(domain) || { counts: createCounts() };
if ( hnDict[domain] === undefined ) {
createDictEntry(domain, domain, dnDetails);
2015-02-17 03:15:09 +01:00
}
if ( hostname === domain ) { continue; }
createDictEntry(domain, hostname, hnDetails);
2014-12-30 22:36:29 +01:00
}
out.hostnameDict = hnDict;
out.cnameMap = cnMap;
2014-12-30 22:36:29 +01:00
};
const firewallRuleTypes = [
'*',
'image',
'3p',
'inline-script',
'1p-script',
'3p-script',
'3p-frame',
];
const getFirewallRules = function(src, out) {
const ruleset = out.firewallRules = {};
const df = µb.sessionFirewall;
for ( const type of firewallRuleTypes ) {
const r = df.lookupRuleData('*', '*', type);
if ( r === undefined ) { continue; }
ruleset[`/ * ${type}`] = r;
2014-12-30 22:36:29 +01:00
}
if ( typeof src !== 'string' ) { return; }
for ( const type of firewallRuleTypes ) {
const r = df.lookupRuleData(src, '*', type);
if ( r === undefined ) { continue; }
ruleset[`. * ${type}`] = r;
}
const { hostnameDict } = out;
for ( const des in hostnameDict ) {
let r = df.lookupRuleData('*', des, '*');
if ( r !== undefined ) { ruleset[`/ ${des} *`] = r; }
r = df.lookupRuleData(src, des, '*');
if ( r !== undefined ) { ruleset[`. ${des} *`] = r; }
}
2014-10-06 20:02:44 +02:00
};
const popupDataFromTabId = function(tabId, tabTitle) {
const tabContext = µb.tabContextManager.mustLookup(tabId);
const rootHostname = tabContext.rootHostname;
const µbus = µb.userSettings;
const µbhs = µb.hiddenSettings;
const r = {
advancedUserEnabled: µbus.advancedUserEnabled,
2014-12-01 17:25:33 +01:00
appName: vAPI.app.name,
appVersion: vAPI.app.version,
colorBlindFriendly: µbus.colorBlindFriendly,
cosmeticFilteringSwitch: false,
firewallPaneMinimized: µbus.firewallPaneMinimized,
2014-06-24 00:42:43 +02:00
globalAllowedRequestCount: µb.localSettings.allowedRequestCount,
globalBlockedRequestCount: µb.localSettings.blockedRequestCount,
fontSize: µbhs.popupFontSize,
godMode: µbhs.filterAuthorMode,
netFilteringSwitch: false,
2015-04-09 00:46:08 +02:00
rawURL: tabContext.rawURL,
pageURL: tabContext.normalURL,
pageHostname: rootHostname,
2015-04-09 00:46:08 +02:00
pageDomain: tabContext.rootDomain,
2016-01-04 16:48:28 +01:00
popupBlockedCount: 0,
popupPanelSections: µbus.popupPanelSections,
popupPanelDisabledSections: µbhs.popupPanelDisabledSections,
popupPanelLockedSections: µbhs.popupPanelLockedSections,
popupPanelHeightMode: µbhs.popupPanelHeightMode,
2015-03-02 19:49:34 +01:00
tabId: tabId,
tabTitle: tabTitle,
tooltipsDisabled: µbus.tooltipsDisabled
2014-06-24 00:42:43 +02:00
};
2015-04-09 00:46:08 +02:00
if ( µbhs.uiPopupConfig !== 'undocumented' ) {
r.uiPopupConfig = µbhs.uiPopupConfig;
}
const pageStore = µb.pageStoreFromTabId(tabId);
2014-06-24 00:42:43 +02:00
if ( pageStore ) {
r.pageCounts = pageStore.counts;
2014-08-02 17:40:27 +02:00
r.netFilteringSwitch = pageStore.getNetFilteringSwitch();
getHostnameDict(pageStore.getAllHostnameDetails(), r);
2015-01-10 17:23:28 +01:00
r.contentLastModified = pageStore.contentLastModified;
getFirewallRules(rootHostname, r);
2018-09-07 16:52:10 +02:00
r.canElementPicker = µb.URI.isNetworkURI(r.rawURL);
r.noPopups = µb.sessionSwitches.evaluateZ(
'no-popups',
rootHostname
);
2016-01-04 16:48:28 +01:00
r.popupBlockedCount = pageStore.popupBlockedCount;
r.noCosmeticFiltering = µb.sessionSwitches.evaluateZ(
'no-cosmetic-filtering',
rootHostname
);
r.noLargeMedia = µb.sessionSwitches.evaluateZ(
'no-large-media',
rootHostname
);
r.largeMediaCount = pageStore.largeMediaCount;
r.noRemoteFonts = µb.sessionSwitches.evaluateZ(
'no-remote-fonts',
rootHostname
);
r.remoteFontCount = pageStore.remoteFontCount;
r.noScripting = µb.sessionSwitches.evaluateZ(
'no-scripting',
rootHostname
);
2014-12-30 22:36:29 +01:00
} else {
r.hostnameDict = {};
getFirewallRules(undefined, r);
}
2018-09-03 20:06:49 +02:00
r.matrixIsDirty = µb.sessionFirewall.hasSameRules(
2015-04-09 00:46:08 +02:00
µb.permanentFirewall,
rootHostname,
2015-04-09 00:46:08 +02:00
r.hostnameDict
2018-09-03 20:06:49 +02:00
) === false;
if ( r.matrixIsDirty === false ) {
r.matrixIsDirty = µb.sessionSwitches.hasSameRules(
µb.permanentSwitches,
rootHostname
) === false;
}
2014-06-24 00:42:43 +02:00
return r;
};
const popupDataFromRequest = async function(request) {
2015-05-18 16:39:20 +02:00
if ( request.tabId ) {
return popupDataFromTabId(request.tabId, '');
}
2015-01-21 17:13:32 +01:00
2015-05-18 16:39:20 +02:00
// Still no target tab id? Use currently selected tab.
const tab = await vAPI.tabs.getCurrent();
let tabId = '';
let tabTitle = '';
if ( tab instanceof Object ) {
tabId = tab.id;
tabTitle = tab.title || '';
}
return popupDataFromTabId(tabId, tabTitle);
};
const getElementCount = async function(tabId, what) {
const results = await vAPI.tabs.executeScript(tabId, {
allFrames: true,
file: `/js/scriptlets/dom-survey-${what}.js`,
runAt: 'document_end',
});
let total = 0;
for ( const count of results ) {
if ( typeof count !== 'number' ) { continue; }
if ( count === -1 ) { return -1; }
total += count;
}
return total;
};
const onMessage = function(request, sender, callback) {
2014-06-24 00:42:43 +02:00
// Async
switch ( request.what ) {
case 'getHiddenElementCount':
getElementCount(request.tabId, 'elements').then(count => {
callback(count);
});
return;
case 'getScriptCount':
getElementCount(request.tabId, 'scripts').then(count => {
callback(count);
});
return;
2015-04-24 14:36:19 +02:00
case 'getPopupData':
popupDataFromRequest(request).then(popupData => {
callback(popupData);
});
2015-04-24 14:36:19 +02:00
return;
2015-04-24 14:36:19 +02:00
default:
break;
2014-06-24 00:42:43 +02:00
}
// Sync
let response;
let pageStore;
2014-06-24 00:42:43 +02:00
switch ( request.what ) {
2015-04-24 14:36:19 +02:00
case 'hasPopupContentChanged':
pageStore = µb.pageStoreFromTabId(request.tabId);
var lastModified = pageStore ? pageStore.contentLastModified : 0;
response = lastModified !== request.contentLastModified;
break;
case 'revertFirewallRules':
µb.sessionFirewall.copyRules(
µb.permanentFirewall,
request.srcHostname,
request.desHostnames
);
2018-09-03 20:06:49 +02:00
µb.sessionSwitches.copyRules(
µb.permanentSwitches,
request.srcHostname
);
2015-05-09 14:25:05 +02:00
// https://github.com/gorhill/uBlock/issues/188
2018-09-03 20:06:49 +02:00
µb.cosmeticFilteringEngine.removeFromSelectorCache(
request.srcHostname,
'net'
);
µb.updateToolbarIcon(request.tabId, 0b100);
2015-05-18 16:39:20 +02:00
response = popupDataFromTabId(request.tabId);
2015-04-24 14:36:19 +02:00
break;
case 'saveFirewallRules':
2018-09-03 20:06:49 +02:00
if (
µb.permanentFirewall.copyRules(
µb.sessionFirewall,
request.srcHostname,
request.desHostnames
)
) {
µb.savePermanentFirewallRules();
}
if (
µb.permanentSwitches.copyRules(
µb.sessionSwitches,
request.srcHostname
)
) {
µb.saveHostnameSwitches();
}
break;
case 'toggleHostnameSwitch':
µb.toggleHostnameSwitch(request);
response = popupDataFromTabId(request.tabId);
2015-04-24 14:36:19 +02:00
break;
case 'toggleFirewallRule':
µb.toggleFirewallRule(request);
2015-05-18 16:39:20 +02:00
response = popupDataFromTabId(request.tabId);
2015-04-24 14:36:19 +02:00
break;
case 'toggleNetFiltering':
pageStore = µb.pageStoreFromTabId(request.tabId);
if ( pageStore ) {
pageStore.toggleNetFilteringSwitch(
request.url,
request.scope,
request.state
);
µb.updateToolbarIcon(request.tabId, 0b111);
2015-04-24 14:36:19 +02:00
}
break;
2014-06-24 00:42:43 +02:00
2015-04-24 14:36:19 +02:00
default:
return vAPI.messaging.UNHANDLED;
2014-06-24 00:42:43 +02:00
}
callback(response);
};
vAPI.messaging.listen({
name: 'popupPanel',
listener: onMessage,
privileged: true,
});
2014-06-24 00:42:43 +02:00
// <<<<< end of local scope
}
2014-06-24 00:42:43 +02:00
2014-09-14 22:20:40 +02:00
/******************************************************************************/
2014-06-24 00:42:43 +02:00
/******************************************************************************/
// Channel:
// contentscript
// unprivileged
2014-06-27 23:06:42 +02:00
{
// >>>>> start of local scope
2014-06-27 23:06:42 +02:00
const µb = µBlock;
2014-09-28 18:05:46 +02:00
const retrieveContentScriptParameters = async function(sender, request) {
if ( µb.readyToFilter !== true ) { return; }
const { tabId, frameId } = sender;
if ( tabId === undefined || frameId === undefined ) { return; }
const pageStore = µb.pageStoreFromTabId(tabId);
if ( pageStore === null || pageStore.getNetFilteringSwitch() === false ) {
return;
}
// A content script may not always be able to successfully look up the
// effective context, hence in such case we try again to look up here
// using cached information about embedded frames.
if ( frameId !== 0 && request.url.startsWith('about:') ) {
request.url = pageStore.getEffectiveFrameURL(sender);
}
const loggerEnabled = µb.logger.enabled;
const noCosmeticFiltering = pageStore.noCosmeticFiltering === true;
const response = {
collapseBlocked: µb.userSettings.collapseBlocked,
noCosmeticFiltering,
noGenericCosmeticFiltering: noCosmeticFiltering,
noSpecificCosmeticFiltering: noCosmeticFiltering,
};
// https://github.com/uBlockOrigin/uAssets/issues/5704
// `generichide` must be evaluated in the frame context.
if ( noCosmeticFiltering === false ) {
const genericHide =
Add support for `cname` type and `denyallow` option This concerns the static network filtering engine. Related issue: - https://github.com/uBlockOrigin/uBlock-issues/issues/943 * * * New static network filter type: `cname` By default, network requests which are result of resolving a canonical name are subject to filtering. This filtering can be bypassed by creating exception filters using the `cname` option. For example: @@*$cname The filter above tells the network filtering engine to except network requests which fulfill all the following conditions: - network request is blocked - network request is that of an unaliased hostname Filter list authors are discouraged from using exception filters of `cname` type, unless there no other practical solution such that maintenance burden become the greater issue. Of course, such exception filters should be as narrow as possible, i.e. apply to specific domain, etc. * * * New static network filter option: `denyallow` The purpose of `denyallow` is bring default-deny/allow-exceptionally ability into static network filtering arsenal. Example of usage: *$3p,script, \ denyallow=x.com|y.com \ domain=a.com|b.com The above filter tells the network filtering engine that when the context is `a.com` or `b.com`, block all 3rd-party scripts except those from `x.com` and `y.com`. Essentially, the new `denyallow` option makes it easier to implement default-deny/allow-exceptionally in static filter lists, whereas before this had to be done with unwieldy regular expressions[1], or through the mix of broadly blocking filters along with exception filters[2]. [1] https://hg.adblockplus.org/ruadlist/rev/f362910bc9a0 [2] Typically filters which pattern are of the form `|http*://`
2020-03-15 17:23:25 +01:00
µb.staticNetFilteringEngine.matchStringReverse(
'generichide',
request.url
);
response.noGenericCosmeticFiltering = genericHide === 2;
if ( loggerEnabled && genericHide !== 0 ) {
µBlock.filteringContext
.duplicate()
.fromTabId(tabId)
.setURL(request.url)
.setRealm('network')
.setType('generichide')
.setFilter(µb.staticNetFilteringEngine.toLogData())
.toLogger();
}
}
request.tabId = tabId;
request.frameId = frameId;
request.hostname = µb.URI.hostnameFromURI(request.url);
request.domain = µb.URI.domainFromHostname(request.hostname);
request.entity = µb.URI.entityFromDomain(request.domain);
// https://www.reddit.com/r/uBlockOrigin/comments/d6vxzj/
// Add support for `specifichide`.
if ( noCosmeticFiltering === false ) {
const specificHide =
Add support for `cname` type and `denyallow` option This concerns the static network filtering engine. Related issue: - https://github.com/uBlockOrigin/uBlock-issues/issues/943 * * * New static network filter type: `cname` By default, network requests which are result of resolving a canonical name are subject to filtering. This filtering can be bypassed by creating exception filters using the `cname` option. For example: @@*$cname The filter above tells the network filtering engine to except network requests which fulfill all the following conditions: - network request is blocked - network request is that of an unaliased hostname Filter list authors are discouraged from using exception filters of `cname` type, unless there no other practical solution such that maintenance burden become the greater issue. Of course, such exception filters should be as narrow as possible, i.e. apply to specific domain, etc. * * * New static network filter option: `denyallow` The purpose of `denyallow` is bring default-deny/allow-exceptionally ability into static network filtering arsenal. Example of usage: *$3p,script, \ denyallow=x.com|y.com \ domain=a.com|b.com The above filter tells the network filtering engine that when the context is `a.com` or `b.com`, block all 3rd-party scripts except those from `x.com` and `y.com`. Essentially, the new `denyallow` option makes it easier to implement default-deny/allow-exceptionally in static filter lists, whereas before this had to be done with unwieldy regular expressions[1], or through the mix of broadly blocking filters along with exception filters[2]. [1] https://hg.adblockplus.org/ruadlist/rev/f362910bc9a0 [2] Typically filters which pattern are of the form `|http*://`
2020-03-15 17:23:25 +01:00
µb.staticNetFilteringEngine.matchStringReverse(
'specifichide',
request.url
);
response.noSpecificCosmeticFiltering = specificHide === 2;
if ( loggerEnabled && specificHide !== 0 ) {
µBlock.filteringContext
.duplicate()
.fromTabId(tabId)
.setURL(request.url)
.setRealm('network')
.setType('specifichide')
.setFilter(µb.staticNetFilteringEngine.toLogData())
.toLogger();
}
}
// Cosmetic filtering can be effectively disabled when both specific and
// generic cosmetic filtering are disabled.
if (
noCosmeticFiltering === false &&
response.noGenericCosmeticFiltering &&
response.noSpecificCosmeticFiltering
) {
response.noCosmeticFiltering = true;
}
response.specificCosmeticFilters =
µb.cosmeticFilteringEngine.retrieveSpecificSelectors(request, response);
// The procedural filterer's code is loaded only when needed and must be
// present before returning response to caller.
if (
Array.isArray(response.specificCosmeticFilters.proceduralFilters) || (
loggerEnabled &&
response.specificCosmeticFilters.exceptedFilters.length !== 0
)
) {
await vAPI.tabs.executeScript(tabId, {
allFrames: false,
file: '/js/contentscript-extra.js',
frameId,
matchAboutBlank: true,
runAt: 'document_start',
});
}
// https://github.com/uBlockOrigin/uBlock-issues/issues/688#issuecomment-748179731
// For non-network URIs, scriptlet injection is deferred to here. The
// effective URL is available here in `request.url`.
if (
µb.canInjectScriptletsNow === false ||
µb.URI.isNetworkURI(sender.frameURL) === false
) {
response.scriptlets = µb.scriptletFilteringEngine.retrieve(request);
}
// https://github.com/NanoMeow/QuickReports/issues/6#issuecomment-414516623
// Inject as early as possible to make the cosmetic logger code less
// sensitive to the removal of DOM nodes which may match injected
// cosmetic filters.
if ( loggerEnabled && response.noCosmeticFiltering !== true ) {
vAPI.tabs.executeScript(tabId, {
allFrames: false,
file: '/js/scriptlets/cosmetic-logger.js',
frameId,
matchAboutBlank: true,
runAt: 'document_start',
});
}
return response;
};
const onMessage = function(request, sender, callback) {
2014-06-27 23:06:42 +02:00
// Async
switch ( request.what ) {
case 'retrieveContentScriptParameters':
return retrieveContentScriptParameters(
sender,
request
).then(response => {
callback(response);
});
default:
break;
2014-06-27 23:06:42 +02:00
}
const pageStore = µb.pageStoreFromTabId(sender.tabId);
2014-06-27 23:06:42 +02:00
// Sync
let response;
2014-06-27 23:06:42 +02:00
switch ( request.what ) {
case 'cosmeticFiltersInjected':
µb.cosmeticFilteringEngine.addToSelectorCache(request);
break;
2017-08-03 16:18:05 +02:00
case 'getCollapsibleBlockedRequests':
response = {
id: request.id,
hash: request.hash,
2017-10-21 19:43:46 +02:00
netSelectorCacheCountMax:
µb.cosmeticFilteringEngine.netSelectorCacheCountMax,
2017-08-03 16:18:05 +02:00
};
if (
µb.userSettings.collapseBlocked &&
pageStore && pageStore.getNetFilteringSwitch()
2017-08-03 16:18:05 +02:00
) {
pageStore.getBlockedResources(request, response);
}
break;
case 'maybeGoodPopup':
µb.maybeGoodPopup.tabId = sender.tabId;
µb.maybeGoodPopup.url = request.url;
break;
case 'shouldRenderNoscriptTags':
if ( pageStore === null ) { break; }
const fctxt = µb.filteringContext.fromTabId(sender.tabId);
if ( pageStore.filterScripting(fctxt, undefined) ) {
vAPI.tabs.executeScript(sender.tabId, {
file: '/js/scriptlets/noscript-spoof.js',
frameId: sender.frameId,
runAt: 'document_end',
});
}
break;
case 'retrieveGenericCosmeticSelectors':
request.tabId = sender.tabId;
request.frameId = sender.frameId;
response = {
result: µb.cosmeticFilteringEngine.retrieveGenericSelectors(request),
};
break;
2014-06-27 23:06:42 +02:00
default:
return vAPI.messaging.UNHANDLED;
}
2014-06-24 00:42:43 +02:00
callback(response);
};
vAPI.messaging.listen({
name: 'contentscript',
listener: onMessage,
});
// <<<<< end of local scope
}
/******************************************************************************/
/******************************************************************************/
// Channel:
// elementPicker
// unprivileged
{
// >>>>> start of local scope
2014-09-28 18:05:46 +02:00
const onMessage = function(request, sender, callback) {
const µb = µBlock;
// Async
switch ( request.what ) {
// The procedural filterer must be present in case the user wants to
// type-in custom filters.
case 'elementPickerArguments':
return vAPI.tabs.executeScript(sender.tabId, {
allFrames: false,
file: '/js/contentscript-extra.js',
frameId: sender.frameId,
matchAboutBlank: true,
runAt: 'document_start',
}).then(( ) => {
callback({
target: µb.epickerArgs.target,
mouse: µb.epickerArgs.mouse,
zap: µb.epickerArgs.zap,
eprom: µb.epickerArgs.eprom,
pickerURL: vAPI.getURL(`/web_accessible_resources/epicker-ui.html?secret=${vAPI.warSecret()}`),
});
µb.epickerArgs.target = '';
});
2015-05-19 19:59:53 +02:00
default:
break;
}
2014-07-13 02:32:44 +02:00
// Sync
let response;
switch ( request.what ) {
2015-05-19 19:59:53 +02:00
case 'elementPickerEprom':
µb.epickerArgs.eprom = request;
2015-05-19 19:59:53 +02:00
break;
2015-05-19 19:59:53 +02:00
default:
return vAPI.messaging.UNHANDLED;
2014-07-13 02:32:44 +02:00
}
callback(response);
};
vAPI.messaging.listen({
name: 'elementPicker',
listener: onMessage,
});
2014-09-28 18:05:46 +02:00
// <<<<< end of local scope
}
2014-06-24 00:42:43 +02:00
2014-09-14 22:20:40 +02:00
/******************************************************************************/
2014-06-24 00:42:43 +02:00
/******************************************************************************/
2015-08-11 21:29:14 +02:00
// Channel:
// cloudWidget
// privileged
2015-08-11 21:29:14 +02:00
{
// >>>>> start of local scope
2015-08-11 21:29:14 +02:00
const fromBase64 = function(encoded) {
if ( typeof encoded !== 'string' ) {
return Promise.resolve(encoded);
}
let u8array;
try {
u8array = µBlock.denseBase64.decode(encoded);
} catch(ex) {
}
return Promise.resolve(u8array !== undefined ? u8array : encoded);
};
const toBase64 = function(data) {
const value = data instanceof Uint8Array
? µBlock.denseBase64.encode(data)
: data;
return Promise.resolve(value);
};
const compress = function(json) {
return µBlock.lz4Codec.encode(json, toBase64);
};
const decompress = function(encoded) {
return µBlock.lz4Codec.decode(encoded, fromBase64);
};
const onMessage = function(request, sender, callback) {
// Cloud storage support is optional.
if ( µBlock.cloudStorageSupported !== true ) {
callback();
return;
}
2015-08-11 21:29:14 +02:00
// Async
switch ( request.what ) {
case 'cloudGetOptions':
vAPI.cloud.getOptions(function(options) {
options.enabled = µBlock.userSettings.cloudStorageEnabled === true;
2015-08-11 21:29:14 +02:00
callback(options);
});
return;
case 'cloudSetOptions':
vAPI.cloud.setOptions(request.options, callback);
return;
case 'cloudPull':
request.decode = decompress;
return vAPI.cloud.pull(request).then(result => {
callback(result);
});
2015-08-11 21:29:14 +02:00
case 'cloudPush':
if ( µBlock.hiddenSettings.cloudStorageCompression ) {
request.encode = compress;
}
return vAPI.cloud.push(request).then(result => {
callback(result);
});
2015-08-11 21:29:14 +02:00
case 'cloudUsed':
return vAPI.cloud.used(request.datakey).then(result => {
callback(result);
});
2015-08-11 21:29:14 +02:00
default:
break;
}
// Sync
let response;
2015-08-11 21:29:14 +02:00
switch ( request.what ) {
// For when cloud storage is disabled.
case 'cloudPull':
// fallthrough
case 'cloudPush':
break;
default:
return vAPI.messaging.UNHANDLED;
}
callback(response);
};
vAPI.messaging.listen({
name: 'cloudWidget',
listener: onMessage,
privileged: true,
});
// <<<<< end of local scope
}
/******************************************************************************/
/******************************************************************************/
// Channel:
// dashboard
// privileged
2014-07-17 16:52:43 +02:00
{
// >>>>> start of local scope
2014-07-17 16:52:43 +02:00
const µb = µBlock;
2014-09-28 18:05:46 +02:00
2016-03-06 16:51:06 +01:00
// Settings
const getLocalData = async function() {
const data = Object.assign({}, µb.restoreBackupSettings);
data.storageUsed = await µb.getBytesInUse();
data.cloudStorageSupported = µb.cloudStorageSupported;
data.privacySettingsSupported = µb.privacySettingsSupported;
return data;
2015-03-07 05:36:09 +01:00
};
const backupUserData = async function() {
const userFilters = await µb.loadUserFilters();
const userData = {
2015-04-16 18:14:43 +02:00
timeStamp: Date.now(),
version: vAPI.app.version,
userSettings:
µb.getModifiedSettings(µb.userSettings, µb.userSettingsDefault),
2017-01-26 16:17:38 +01:00
selectedFilterLists: µb.selectedFilterLists,
hiddenSettings:
µb.getModifiedSettings(µb.hiddenSettings, µb.hiddenSettingsDefault),
whitelist: µb.arrayFromWhitelist(µb.netWhitelist),
2015-04-16 18:14:43 +02:00
dynamicFilteringString: µb.permanentFirewall.toString(),
2015-05-21 20:15:17 +02:00
urlFilteringString: µb.permanentURLFiltering.toString(),
2018-09-03 20:06:49 +02:00
hostnameSwitchesString: µb.permanentSwitches.toString(),
userFilters: userFilters.content,
2017-01-26 16:17:38 +01:00
};
2015-04-16 18:14:43 +02:00
const filename = vAPI.i18n('aboutBackupFilename')
.replace('{{datetime}}', µb.dateNowToSensibleString())
.replace(/ +/g, '_');
µb.restoreBackupSettings.lastBackupFile = filename;
µb.restoreBackupSettings.lastBackupTime = Date.now();
vAPI.storage.set(µb.restoreBackupSettings);
2015-03-07 05:36:09 +01:00
const localData = await getLocalData();
return { localData, userData };
2014-10-07 14:59:35 +02:00
};
const restoreUserData = async function(request) {
const userData = request.userData;
2014-10-11 22:44:56 +02:00
// https://github.com/LiCybora/NanoDefenderFirefox/issues/196
// Backup data could be from Chromium platform or from an older
// Firefox version.
if (
vAPI.webextFlavor.soup.has('firefox') &&
vAPI.app.intFromVersion(userData.version) <= 1031003011
) {
userData.hostnameSwitchesString += '\nno-csp-reports: * true';
}
// List of external lists is meant to be a string.
if ( Array.isArray(userData.externalLists) ) {
userData.externalLists = userData.externalLists.join('\n');
}
2015-04-07 03:26:05 +02:00
// https://github.com/chrisaljoudi/uBlock/issues/1102
// Ensure all currently cached assets are flushed from storage AND memory.
2015-03-27 14:50:31 +01:00
µb.assets.rmrf();
2014-10-07 16:46:10 +02:00
// If we are going to restore all, might as well wipe out clean local
// storages
await Promise.all([
µb.cacheStorage.clear(),
vAPI.storage.clear(),
]);
// Restore block stats
µBlock.saveLocalSettings();
// Restore user data
vAPI.storage.set(userData.userSettings);
// Restore advanced settings.
let hiddenSettings = userData.hiddenSettings;
if ( hiddenSettings instanceof Object === false ) {
hiddenSettings = µBlock.hiddenSettingsFromString(
userData.hiddenSettingsString || ''
);
}
// Discard unknown setting or setting with default value.
for ( const key in hiddenSettings ) {
if (
µb.hiddenSettingsDefault.hasOwnProperty(key) === false ||
hiddenSettings[key] === µb.hiddenSettingsDefault[key]
) {
delete hiddenSettings[key];
}
}
// Whitelist directives can be represented as an array or as a
// (eventually to be deprecated) string.
let whitelist = userData.whitelist;
if (
Array.isArray(whitelist) === false &&
typeof userData.netWhitelist === 'string' &&
userData.netWhitelist !== ''
) {
whitelist = userData.netWhitelist.split('\n');
}
vAPI.storage.set({
hiddenSettings,
netWhitelist: whitelist || [],
dynamicFilteringString: userData.dynamicFilteringString || '',
urlFilteringString: userData.urlFilteringString || '',
hostnameSwitchesString: userData.hostnameSwitchesString || '',
lastRestoreFile: request.file || '',
lastRestoreTime: Date.now(),
lastBackupFile: '',
lastBackupTime: 0
});
µb.saveUserFilters(userData.userFilters);
if ( Array.isArray(userData.selectedFilterLists) ) {
await µb.saveSelectedFilterLists(userData.selectedFilterLists);
}
vAPI.app.restart();
2014-10-07 14:59:35 +02:00
};
// Remove all stored data but keep global counts, people can become
// quite attached to numbers
const resetUserData = async function() {
await Promise.all([
µb.cacheStorage.clear(),
vAPI.storage.clear(),
]);
await µb.saveLocalSettings();
vAPI.app.restart();
2014-10-07 14:59:35 +02:00
};
// Filter lists
const prepListEntries = function(entries) {
const µburi = µb.URI;
for ( const k in entries ) {
if ( entries.hasOwnProperty(k) === false ) { continue; }
const entry = entries[k];
2016-03-06 16:51:06 +01:00
if ( typeof entry.supportURL === 'string' && entry.supportURL !== '' ) {
entry.supportName = µburi.hostnameFromURI(entry.supportURL);
} else if ( typeof entry.homeURL === 'string' && entry.homeURL !== '' ) {
const hn = µburi.hostnameFromURI(entry.homeURL);
entry.supportURL = `http://${hn}/`;
2016-03-06 16:51:06 +01:00
entry.supportName = µburi.domainFromHostname(hn);
}
}
};
const getLists = async function(callback) {
const r = {
2016-03-06 16:51:06 +01:00
autoUpdate: µb.userSettings.autoUpdate,
available: null,
cache: null,
cosmeticFilterCount: µb.cosmeticFilteringEngine.getFilterCount(),
current: µb.availableFilterLists,
2016-08-13 22:42:58 +02:00
ignoreGenericCosmeticFilters: µb.userSettings.ignoreGenericCosmeticFilters,
isUpdating: µb.assets.isUpdating(),
2016-03-06 16:51:06 +01:00
netFilterCount: µb.staticNetFilteringEngine.getFilterCount(),
2017-01-22 22:05:16 +01:00
parseCosmeticFilters: µb.userSettings.parseAllABPHideFilters,
2017-12-14 22:42:54 +01:00
userFiltersPath: µb.userFiltersPath
2016-03-06 16:51:06 +01:00
};
const [ lists, metadata ] = await Promise.all([
µb.getAvailableLists(),
µb.assets.metadata(),
]);
r.available = lists;
prepListEntries(r.available);
r.cache = metadata;
prepListEntries(r.cache);
callback(r);
2016-03-06 16:51:06 +01:00
};
// My filters
// TODO: also return origin of embedded frames?
const getOriginHints = function() {
const punycode = self.punycode;
const out = new Set();
for ( const tabId of µb.pageStores.keys() ) {
if ( tabId === -1 ) { continue; }
const tabContext = µb.tabContextManager.lookup(tabId);
if ( tabContext === null ) { continue; }
let { rootDomain, rootHostname } = tabContext;
if ( rootDomain.endsWith('-scheme') ) { continue; }
const isPunycode = rootHostname.includes('xn--');
out.add(isPunycode ? punycode.toUnicode(rootDomain) : rootDomain);
if ( rootHostname === rootDomain ) { continue; }
out.add(isPunycode ? punycode.toUnicode(rootHostname) : rootHostname);
}
return Array.from(out);
};
2016-03-06 16:51:06 +01:00
// My rules
const getRules = function() {
2016-03-06 16:51:06 +01:00
return {
2018-09-03 20:06:49 +02:00
permanentRules:
µb.permanentFirewall.toArray().concat(
µb.permanentSwitches.toArray(),
µb.permanentURLFiltering.toArray()
),
sessionRules:
µb.sessionFirewall.toArray().concat(
µb.sessionSwitches.toArray(),
µb.sessionURLFiltering.toArray()
),
pslSelfie: self.publicSuffixList.toSelfie(),
2016-03-06 16:51:06 +01:00
};
};
const modifyRuleset = function(details) {
2018-09-03 20:06:49 +02:00
let swRuleset, hnRuleset, urlRuleset;
if ( details.permanent ) {
2018-09-03 20:06:49 +02:00
swRuleset = µb.permanentSwitches;
hnRuleset = µb.permanentFirewall;
urlRuleset = µb.permanentURLFiltering;
} else {
2018-09-03 20:06:49 +02:00
swRuleset = µb.sessionSwitches;
hnRuleset = µb.sessionFirewall;
urlRuleset = µb.sessionURLFiltering;
}
2018-09-03 20:06:49 +02:00
let toRemove = new Set(details.toRemove.trim().split(/\s*[\n\r]+\s*/));
for ( let rule of toRemove ) {
if ( rule === '' ) { continue; }
2018-09-03 20:06:49 +02:00
let parts = rule.split(/\s+/);
if ( hnRuleset.removeFromRuleParts(parts) === false ) {
if ( swRuleset.removeFromRuleParts(parts) === false ) {
urlRuleset.removeFromRuleParts(parts);
}
}
}
2018-09-03 20:06:49 +02:00
let toAdd = new Set(details.toAdd.trim().split(/\s*[\n\r]+\s*/));
for ( let rule of toAdd ) {
if ( rule === '' ) { continue; }
2018-09-03 20:06:49 +02:00
let parts = rule.split(/\s+/);
if ( hnRuleset.addFromRuleParts(parts) === false ) {
if ( swRuleset.addFromRuleParts(parts) === false ) {
urlRuleset.addFromRuleParts(parts);
}
}
}
if ( details.permanent ) {
2018-09-03 20:06:49 +02:00
if ( swRuleset.changed ) {
µb.saveHostnameSwitches();
swRuleset.changed = false;
}
if ( hnRuleset.changed ) {
µb.savePermanentFirewallRules();
hnRuleset.changed = false;
2016-03-06 16:51:06 +01:00
}
if ( urlRuleset.changed ) {
µb.savePermanentURLFilteringRules();
urlRuleset.changed = false;
2016-03-06 16:51:06 +01:00
}
}
};
// Shortcuts pane
const getShortcuts = function(callback) {
if ( µb.canUseShortcuts === false ) {
return callback([]);
}
vAPI.commands.getAll(commands => {
let response = [];
for ( let command of commands ) {
let desc = command.description;
let match = /^__MSG_(.+?)__$/.exec(desc);
if ( match !== null ) {
desc = vAPI.i18n(match[1]);
}
if ( desc === '' ) { continue; }
command.description = desc;
response.push(command);
}
callback(response);
});
};
const setShortcut = function(details) {
if ( µb.canUpdateShortcuts === false ) { return; }
if ( details.shortcut === undefined ) {
vAPI.commands.reset(details.name);
µb.commandShortcuts.delete(details.name);
} else {
vAPI.commands.update({ name: details.name, shortcut: details.shortcut });
µb.commandShortcuts.set(details.name, details.shortcut);
}
vAPI.storage.set({ commandShortcuts: Array.from(µb.commandShortcuts) });
};
const onMessage = function(request, sender, callback) {
2014-06-24 00:42:43 +02:00
// Async
switch ( request.what ) {
2015-05-19 19:59:53 +02:00
case 'backupUserData':
return backupUserData().then(data => {
callback(data);
});
2015-03-07 05:36:09 +01:00
2016-03-06 16:51:06 +01:00
case 'getLists':
return getLists(callback);
2015-05-19 19:59:53 +02:00
case 'getLocalData':
return getLocalData().then(localData => {
callback(localData);
});
2014-06-24 00:42:43 +02:00
case 'getShortcuts':
return getShortcuts(callback);
2016-03-06 16:51:06 +01:00
case 'readUserFilters':
return µb.loadUserFilters().then(result => {
callback(result);
});
2016-03-06 16:51:06 +01:00
case 'writeUserFilters':
return µb.saveUserFilters(request.content).then(result => {
callback(result);
});
2016-03-06 16:51:06 +01:00
2015-05-19 19:59:53 +02:00
default:
break;
2014-06-24 00:42:43 +02:00
}
// Sync
let response;
2014-06-24 00:42:43 +02:00
switch ( request.what ) {
case 'dashboardConfig':
response = {
canUpdateShortcuts: µb.canUpdateShortcuts,
noDashboard: µb.noDashboard,
};
break;
case 'getAutoCompleteDetails':
response = {};
if ( (request.hintUpdateToken || 0) === 0 ) {
response.redirectResources = µb.redirectEngine.getResourceDetails();
response.preparseDirectiveTokens = µb.preparseDirectives.getTokens();
response.preparseDirectiveHints = µb.preparseDirectives.getHints();
response.expertMode = µb.hiddenSettings.filterAuthorMode;
}
if ( request.hintUpdateToken !== µb.pageStoresToken ) {
response.originHints = getOriginHints();
response.hintUpdateToken = µb.pageStoresToken;
}
break;
2016-03-06 16:51:06 +01:00
case 'getRules':
response = getRules();
break;
case 'modifyRuleset':
// https://github.com/chrisaljoudi/uBlock/issues/772
µb.cosmeticFilteringEngine.removeFromSelectorCache('*');
modifyRuleset(request);
response = getRules();
break;
case 'purgeAllCaches':
if ( request.hard ) {
µb.assets.remove(/./);
} else {
µb.assets.purge(/./, 'public_suffix_list.dat');
}
break;
2016-03-06 16:51:06 +01:00
case 'purgeCache':
µb.assets.purge(request.assetKey);
µb.assets.remove('compiled/' + request.assetKey);
2016-03-06 16:51:06 +01:00
break;
case 'readHiddenSettings':
response = {
'default': µb.hiddenSettingsDefault,
'admin': µb.hiddenSettingsAdmin,
'current': µb.hiddenSettings,
};
break;
2015-05-19 19:59:53 +02:00
case 'restoreUserData':
restoreUserData(request);
break;
2014-10-07 14:59:35 +02:00
2015-05-19 19:59:53 +02:00
case 'resetUserData':
resetUserData();
break;
2016-03-06 16:51:06 +01:00
case 'setShortcut':
setShortcut(request);
break;
case 'writeHiddenSettings':
µb.changeHiddenSettings(µb.hiddenSettingsFromString(request.content));
break;
2015-05-19 19:59:53 +02:00
default:
return vAPI.messaging.UNHANDLED;
2014-06-24 00:42:43 +02:00
}
callback(response);
};
vAPI.messaging.listen({
name: 'dashboard',
listener: onMessage,
privileged: true,
});
2014-06-24 00:42:43 +02:00
// <<<<< end of local scope
}
2014-06-24 00:42:43 +02:00
/******************************************************************************/
/******************************************************************************/
// Channel:
// loggerUI
// privileged
{
// >>>>> start of local scope
const µb = µBlock;
const extensionOriginURL = vAPI.getURL('');
const documentBlockedURL = vAPI.getURL('document-blocked.html');
const getLoggerData = async function(details, activeTabId, callback) {
const response = {
activeTabId,
colorBlind: µb.userSettings.colorBlindFriendly,
entries: µb.logger.readAll(details.ownerId),
filterAuthorMode: µb.hiddenSettings.filterAuthorMode,
tabIdsToken: µb.pageStoresToken,
tooltips: µb.userSettings.tooltipsDisabled === false
};
if ( µb.pageStoresToken !== details.tabIdsToken ) {
const tabIds = new Map();
for ( const [ tabId, pageStore ] of µb.pageStores ) {
const { rawURL } = pageStore;
if (
rawURL.startsWith(extensionOriginURL) === false ||
rawURL.startsWith(documentBlockedURL)
) {
tabIds.set(tabId, pageStore.title);
}
}
response.tabIds = Array.from(tabIds);
}
if ( activeTabId ) {
const pageStore = µb.pageStoreFromTabId(activeTabId);
const rawURL = pageStore && pageStore.rawURL;
if (
rawURL === null ||
rawURL.startsWith(extensionOriginURL) &&
rawURL.startsWith(documentBlockedURL) === false
) {
response.activeTabId = undefined;
}
}
if ( details.popupLoggerBoxChanged && vAPI.windows instanceof Object ) {
const tabs = await vAPI.tabs.query({
url: vAPI.getURL('/logger-ui.html?popup=1')
});
if ( tabs.length !== 0 ) {
const win = await vAPI.windows.get(tabs[0].windowId);
if ( win === null ) { return; }
vAPI.localStorage.setItem('popupLoggerBox', JSON.stringify({
left: win.left,
top: win.top,
width: win.width,
height: win.height,
}));
}
}
callback(response);
};
const getURLFilteringData = function(details) {
const colors = {};
const response = {
2015-05-21 20:15:17 +02:00
dirty: false,
colors: colors
};
const suf = µb.sessionURLFiltering;
const puf = µb.permanentURLFiltering;
const urls = details.urls;
const context = details.context;
const type = details.type;
for ( const url of urls ) {
const colorEntry = colors[url] = { r: 0, own: false };
2015-05-21 20:15:17 +02:00
if ( suf.evaluateZ(context, url, type).r !== 0 ) {
colorEntry.r = suf.r;
colorEntry.own = suf.r !== 0 &&
suf.context === context &&
suf.url === url &&
suf.type === type;
2015-05-21 20:15:17 +02:00
}
if ( response.dirty ) { continue; }
2015-05-21 20:15:17 +02:00
puf.evaluateZ(context, url, type);
response.dirty = colorEntry.own !== (
puf.r !== 0 &&
puf.context === context &&
puf.url === url &&
puf.type === type
);
2015-05-21 20:15:17 +02:00
}
return response;
};
const compileTemporaryException = function(filter) {
const parser = new vAPI.StaticFilteringParser();
parser.analyze(filter);
if ( parser.shouldDiscard() ) { return {}; }
let selector = parser.result.compiled;
let session;
if ( (parser.flavorBits & parser.BITFlavorExtScriptlet) !== 0 ) {
session = µb.scriptletFilteringEngine.getSession();
} else if ( (parser.flavorBits & parser.BITFlavorExtHTML) !== 0 ) {
session = µb.htmlFilteringEngine.getSession();
} else {
session = µb.cosmeticFilteringEngine.getSession();
}
return { session, selector };
};
const toggleTemporaryException = function(details) {
const { session, selector } = compileTemporaryException(details.filter);
if ( session.has(1, selector) ) {
session.remove(1, selector);
return false;
}
session.add(1, selector);
return true;
};
const hasTemporaryException = function(details) {
const { session, selector } = compileTemporaryException(details.filter);
return session && session.has(1, selector);
};
const onMessage = function(request, sender, callback) {
// Async
switch ( request.what ) {
2015-05-19 19:59:53 +02:00
case 'readAll':
2018-01-08 20:29:39 +01:00
if (
µb.logger.ownerId !== undefined &&
µb.logger.ownerId !== request.ownerId
) {
return callback({ unavailable: true });
2018-01-08 20:29:39 +01:00
}
vAPI.tabs.getCurrent().then(tab => {
getLoggerData(request, tab && tab.id, callback);
});
return;
default:
2015-05-19 19:59:53 +02:00
break;
}
// Sync
let response;
switch ( request.what ) {
case 'hasTemporaryException':
response = hasTemporaryException(request);
break;
2018-01-08 20:29:39 +01:00
case 'releaseView':
if ( request.ownerId === µb.logger.ownerId ) {
µb.logger.ownerId = undefined;
}
break;
2015-05-21 20:15:17 +02:00
case 'saveURLFilteringRules':
2015-05-22 14:05:55 +02:00
response = µb.permanentURLFiltering.copyRules(
µb.sessionURLFiltering,
request.context,
request.urls,
request.type
);
if ( response ) {
2015-05-21 20:15:17 +02:00
µb.savePermanentURLFilteringRules();
}
break;
case 'setURLFilteringRule':
µb.toggleURLFilteringRule(request);
break;
case 'getURLFilteringData':
response = getURLFilteringData(request);
break;
case 'toggleTemporaryException':
response = toggleTemporaryException(request);
break;
2015-05-19 19:59:53 +02:00
default:
return vAPI.messaging.UNHANDLED;
}
callback(response);
};
vAPI.messaging.listen({
name: 'loggerUI',
listener: onMessage,
privileged: true,
});
// <<<<< end of local scope
}
2014-06-24 00:42:43 +02:00
/******************************************************************************/
2015-03-09 17:57:52 +01:00
/******************************************************************************/
// Channel:
// documentBlocked
// privileged
2015-03-26 00:28:22 +01:00
{
// >>>>> start of local scope
2015-03-26 00:28:22 +01:00
const onMessage = function(request, sender, callback) {
const tabId = sender.tabId || 0;
2015-03-26 00:28:22 +01:00
// Async
switch ( request.what ) {
2015-05-19 19:59:53 +02:00
default:
break;
2015-03-26 00:28:22 +01:00
}
// Sync
let response;
2015-03-26 00:28:22 +01:00
switch ( request.what ) {
case 'closeThisTab':
vAPI.tabs.remove(tabId);
break;
2015-05-19 19:59:53 +02:00
case 'temporarilyWhitelistDocument':
µBlock.webRequest.strictBlockBypass(request.hostname);
2015-05-19 19:59:53 +02:00
break;
2015-03-26 00:28:22 +01:00
2015-05-19 19:59:53 +02:00
default:
return vAPI.messaging.UNHANDLED;
2015-03-26 00:28:22 +01:00
}
callback(response);
};
vAPI.messaging.listen({
name: 'documentBlocked',
listener: onMessage,
privileged: true,
});
2015-03-26 00:28:22 +01:00
// <<<<< end of local scope
}
2015-03-09 17:57:52 +01:00
/******************************************************************************/
/******************************************************************************/
// Channel:
// scriptlets
// unprivileged
{
// >>>>> start of local scope
const µb = µBlock;
const logCosmeticFilters = function(tabId, details) {
if ( µb.logger.enabled === false ) { return; }
const filter = { source: 'cosmetic', raw: '' };
const fctxt = µb.filteringContext.duplicate();
fctxt.fromTabId(tabId)
.setRealm('cosmetic')
.setType('dom')
.setURL(details.frameURL)
.setDocOriginFromURL(details.frameURL)
.setFilter(filter);
for ( const selector of details.matchedSelectors.sort() ) {
filter.raw = selector;
fctxt.toLogger();
}
};
const logCSPViolations = function(pageStore, request) {
if ( µb.logger.enabled === false || pageStore === null ) {
return false;
}
if ( request.violations.length === 0 ) {
return true;
}
const fctxt = µb.filteringContext.duplicate();
fctxt.fromTabId(pageStore.tabId)
.setRealm('network')
.setDocOriginFromURL(request.docURL)
.setURL(request.docURL);
let cspData = pageStore.extraData.get('cspData');
if ( cspData === undefined ) {
cspData = new Map();
const staticDirectives =
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
µb.staticNetFilteringEngine.matchAndFetchModifiers(fctxt, 'csp');
if ( staticDirectives !== undefined ) {
for ( const directive of staticDirectives ) {
if ( directive.result !== 1 ) { continue; }
cspData.set(directive.value, directive.logData());
}
}
fctxt.type = 'inline-script';
fctxt.filter = undefined;
if ( pageStore.filterRequest(fctxt) === 1 ) {
cspData.set(µb.cspNoInlineScript, fctxt.filter);
}
fctxt.type = 'script';
fctxt.filter = undefined;
if ( pageStore.filterScripting(fctxt, true) === 1 ) {
cspData.set(µb.cspNoScripting, fctxt.filter);
}
fctxt.type = 'inline-font';
fctxt.filter = undefined;
if ( pageStore.filterRequest(fctxt) === 1 ) {
cspData.set(µb.cspNoInlineFont, fctxt.filter);
}
if ( cspData.size === 0 ) { return false; }
pageStore.extraData.set('cspData', cspData);
}
const typeMap = logCSPViolations.policyDirectiveToTypeMap;
for ( const json of request.violations ) {
const violation = JSON.parse(json);
let type = typeMap.get(violation.directive);
if ( type === undefined ) { continue; }
const logData = cspData.get(violation.policy);
if ( logData === undefined ) { continue; }
if ( /^[\w.+-]+:\/\//.test(violation.url) === false ) {
violation.url = request.docURL;
if ( type === 'script' ) { type = 'inline-script'; }
else if ( type === 'font' ) { type = 'inline-font'; }
}
// The resource was blocked as a result of applying a CSP directive
// elsewhere rather than to the resource itself.
logData.modifier = undefined;
fctxt.setURL(violation.url)
.setType(type)
.setFilter(logData)
.toLogger();
}
return true;
};
logCSPViolations.policyDirectiveToTypeMap = new Map([
[ 'img-src', 'image' ],
[ 'connect-src', 'xmlhttprequest' ],
[ 'font-src', 'font' ],
[ 'frame-src', 'sub_frame' ],
[ 'media-src', 'media' ],
[ 'object-src', 'object' ],
[ 'script-src', 'script' ],
[ 'script-src-attr', 'script' ],
[ 'script-src-elem', 'script' ],
[ 'style-src', 'stylesheet' ],
[ 'style-src-attr', 'stylesheet' ],
[ 'style-src-elem', 'stylesheet' ],
]);
const onMessage = function(request, sender, callback) {
const tabId = sender.tabId || 0;
const pageStore = µb.pageStoreFromTabId(tabId);
2015-06-26 06:08:41 +02:00
// Async
switch ( request.what ) {
default:
break;
}
// Sync
let response;
switch ( request.what ) {
case 'inlinescriptFound':
if ( µb.logger.enabled && pageStore !== null ) {
const fctxt = µb.filteringContext.duplicate();
fctxt.fromTabId(tabId)
.setType('inline-script')
.setURL(request.docURL)
.setDocOriginFromURL(request.docURL);
if ( pageStore.filterRequest(fctxt) === 0 ) {
fctxt.setRealm('network').toLogger();
}
}
break;
case 'logCosmeticFilteringData':
logCosmeticFilters(tabId, request);
break;
case 'securityPolicyViolation':
response = logCSPViolations(pageStore, request);
break;
case 'temporarilyAllowLargeMediaElement':
if ( pageStore !== null ) {
pageStore.allowLargeMediaElementsUntil = Date.now() + 5000;
}
break;
case 'subscribeTo':
const url = encodeURIComponent(request.location);
const title = encodeURIComponent(request.title);
const hash = µb.selectedFilterLists.indexOf(request.location) !== -1
? '#subscribed'
: '';
vAPI.tabs.open({
url: `/asset-viewer.html?url=${url}&title=${title}&subscribe=1${hash}`,
select: true,
});
break;
default:
return vAPI.messaging.UNHANDLED;
}
callback(response);
};
vAPI.messaging.listen({
name: 'scriptlets',
listener: onMessage,
});
// <<<<< end of local scope
}
2015-06-26 06:08:41 +02:00
/******************************************************************************/
/******************************************************************************/