S049 (WIP): ad blocker in WebKit content filters, web process extension for headers, stand-ins and blocked counts

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-13 14:33:18 -06:00
commit bb1c1a5ed7
17 changed files with 879 additions and 133 deletions

19
Cargo.lock generated
View file

@ -1918,6 +1918,7 @@ dependencies = [
"log",
"material-colors",
"qrcode",
"regex-lite",
"rfd",
"rusqlite",
"rustls",
@ -1929,6 +1930,18 @@ dependencies = [
"webkit6",
]
[[package]]
name = "nacre-webext"
version = "0.4.0"
dependencies = [
"glib-sys",
"gobject-sys",
"regex-lite",
"serde",
"serde_json",
"url",
]
[[package]]
name = "nix"
version = "0.29.0"
@ -2508,6 +2521,12 @@ dependencies = [
"regex-syntax",
]
[[package]]
name = "regex-lite"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"
[[package]]
name = "regex-syntax"
version = "0.8.11"

View file

@ -7,6 +7,11 @@ description = "Nacre, a web browser built on WebKitGTK"
license = "MPL-2.0"
publish = false
# webext/: the web process extension (D-036), built with the browser.
[workspace]
members = [".", "webext"]
default-members = [".", "webext"]
[[bin]]
name = "nacre"
path = "src/main.rs"
@ -22,12 +27,14 @@ libloading = "0.8"
# Material You colour schemes (HCT, tonal palettes). 0.4.2: 0.5 needs Rust 1.97 (D-009).
material-colors = { version = "=0.4.2", default-features = false, features = ["std"] }
url = "2.5"
# Redirect rules (net::rules, shared with webext/)
regex-lite = "0.1"
http = "1.4"
rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs", "std"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "ico", "webp", "gif", "bmp"] }
log = "0.4"
# Ad blocking
adblock = { version = "0.13.5", default-features = false, features = ["embedded-domain-resolver", "full-regex-handling"] }
adblock = { version = "0.13.5", default-features = false, features = ["embedded-domain-resolver", "full-regex-handling", "content-blocking"] }
# Nacre's own HTTP (downloads, filter lists, updates, DoH)
ureq = { version = "3.5", default-features = false, features = ["rustls-no-provider", "rustls-webpki-roots", "gzip", "brotli"] }

View file

@ -14,12 +14,12 @@ shield counts and the per-site pause keep working.
- `src/adblock.rs` (whole), the adblock parts of `src/app.rs`/`src/actions.rs` (grep `adblock`), `tests/smoke/net-adblock.txt`.
## Steps
- [ ] Convert lists with adblock-rust's content-blocking feature; measure rule count and compile time for the default lists; write the JSON, compile with `UserContentFilterStore::save`, load and attach per `UserContentManager`; rebuild on list update; per-site pause = an `ignore-previous-rules` rule for that domain (or detach filters for that view).
- [ ] Rules the conversion can't express: list them with counts in DESIGN.md; redirect rules → extension.
- [ ] `webext/`: cdylib web process extension (check crates.io for maintained `webkit6` web-process-extension bindings first; else minimal FFI to `webkit_web_page` `send-request`); gets its config (headers on/off, redirect map, tracking params) from the UI process via `WebContext` initialization user data + messages; `send-request` adds DNT/Sec-GPC/Save-Data, rewrites tracking params, redirects to `nacre-resource:` (URI scheme handler in the UI process serving adblock resources), reports blocked/redirected counts.
- [ ] Blocked counts: content-filter blocks are invisible to the embedder — count them from the extension (`send-request` sees the request? verify) or from `resource-load-started` vs. finished; document the method and its limits.
- [ ] Ship/locate the extension: `WebContext::set_web_process_extensions_directory` to the build dir in dev and `$APPDIR/lib/nacre` in packages.
- [ ] Smoke: `python3 tests/smoke/net/server.py &` + `net-adblock.txt`, `crash-adblock.txt` (as a blocking stress test) green hidden; `privacy-net.txt` header checks green.
- [x] Convert lists with adblock-rust's content-blocking feature; measure rule count and compile time for the default lists; write the JSON, compile with `UserContentFilterStore::save`, load and attach per `UserContentManager`; rebuild on list update; per-site pause = an `ignore-previous-rules` rule for that domain (or detach filters for that view).
- [x] Rules the conversion can't express: list them with counts in DESIGN.md; redirect rules → extension.
- [x] `webext/`: cdylib web process extension (check crates.io for maintained `webkit6` web-process-extension bindings first; else minimal FFI to `webkit_web_page` `send-request`); gets its config (headers on/off, redirect map, tracking params) from the UI process via `WebContext` initialization user data + messages; `send-request` adds DNT/Sec-GPC/Save-Data, rewrites tracking params, redirects to `nacre-resource:` (URI scheme handler in the UI process serving adblock resources), reports blocked/redirected counts.
- [x] Blocked counts: content-filter blocks are invisible to the embedder — count them from the extension (`send-request` sees the request? verify) or from `resource-load-started` vs. finished; document the method and its limits.
- [x] Ship/locate the extension: `WebContext::set_web_process_extensions_directory` to the build dir in dev and `$APPDIR/lib/nacre` in packages.
- [x] Smoke: `python3 tests/smoke/net/server.py &` + `net-adblock.txt`, `crash-adblock.txt` (as a blocking stress test) green hidden; `privacy-net.txt` header checks green.
- [ ] RAM check: web process PSS with and without filters on 3 sites (`tools/engine-test/sample.py`), in PROGRESS.
- [ ] PROGRESS entry, INDEX line, tracker, commit `S049: …`, push.

View file

@ -24,7 +24,8 @@ src/hub.rs Servo delegates; everything Servo tells us becomes an Event i
src/tabs.rs Tab (one WebView or an internal page), per-window tab list
src/keys.rs winit -> Servo key conversion, shortcut table (rebindable)
src/inject.rs JavaScript injected into pages (bridge, autofill, find, media, PiP, cosmetic filters)
src/adblock.rs adblock-rust engine, lists, updates, counters
src/adblock.rs adblock-rust: lists, updates, cosmetic engine, conversion to WebKit content filters
webext/ web process extension (cdylib): headers, stand-ins, blocked counts (D-036)
src/discord.rs Discord Rich Presence over the local IPC socket
src/media.rs media state gathered from pages; feeds the media button, Discord, MPRIS later
src/importer.rs import from Chromium- and Firefox-family browsers
@ -399,3 +400,49 @@ full-window `default_size` it centres itself in the whole height and stretches t
## Feature checklist
See `docs/FEATURES.md`; every row names the file that implements it and its review state.
## Ad blocker on WebKit (D-036, S049)
- **Network rules** → WebKit content filters. `adblock::convert` parses every enabled list (network rules only) with
adblock-rust's `content-blocking` conversion; blocks first, then exceptions (`ignore-previous-rules`), then the
"first-party documents pass" rule; identical rules are dropped. WebKit refuses a filter of more than 150 000 rules,
so blocks are shared out over several filters and **each filter repeats every exception** (an exception only
reaches rules of its own filter). JSON at `<cache>/adblock-engine.webkit<N>.json`, compiled by
`UserContentFilterStore` (`<cache>/content-filters`, id `nacre-adblock-<list fingerprint>-<N>`); a restart with the
same lists loads the compiled filter (ms). First compile of the seed lists: ~7–15 s inside WebKit, off the main
thread; pages loaded meanwhile aren't network-blocked (cosmetic hiding still runs). `Engine::set_content_filter`
installs a build only when all its filters are ready and drops stale builds.
- **Cosmetic rules** stay in the adblock-rust engine (now built cosmetic-only) and page scripts, as before.
- **Per-site pause / ad blocker off**: the view's filters are detached in `decide-policy` before a main-frame load
of a paused host (`attach_filters`), and re-checked on every settings change.
- **Coverage, seed lists (10 lists, 2026-11-13)**: 152 610 network rules, 151 179 converted (99.1 %) into 149 902
WebKit rules (1 filter) and 268 redirects. Left out:
| Reason | Rules | What it means |
|---|---|---|
| `NetworkGenerichideUnsupported` | 590 | `$generichide` (the cosmetic engine still honours it) |
| `FullRegexUnsupported` | 248 | `/regex/` rules beyond WebKit's regex dialect |
| `NetworkRemoveparamUnsupported` | 215 | `$removeparam` (Nacre's own tracking-param strip covers the common ones) |
| `RedirectRuleOnly` | 151 | `$redirect-rule=`: a stand-in only for what another rule blocks; the filter's block wins |
| `FromNotSupported` | 121 | `$from=` / `$to=` domain options |
| `NoSupportedNetworkOptions` | 77 | only types WebKit has no name for (`$ping`, `$websocket`, …) |
| `NetworkCspUnsupported` | 28 | `$csp=` header injection |
| `UnlessAndIfDomainTogetherUnsupported` | 1 | `$domain=a.com\|~b.a.com` |
- **Redirect rules** (`$redirect=<name>`): when Nacre has the stand-in (`adblock::resource`: noopjs, noop.txt,
noop.css, noopjson, noopframe, transparent images) the rule goes to the extension, which rewrites the request to
`nacre-resource:<name>` (URI scheme served by the browser, registered secure + CORS); stand-ins Nacre lacks
(google-ima.js, media files, …) become plain blocks, as before with Servo. Limits: an exception (`@@`) doesn't stop
an extension redirect; the extension can't see the resource type; third-party is "last two host labels differ".
- **Web process extension** (`webext/`, `libnacre_webext.so`, ~0.8 MB, minimal FFI — no maintained Rust bindings
for WebKit's web process extension API exist): config JSON (`net::rules::Config`: headers, strip, ad blocker
on, paused hosts, redirects) as initialization user data and `nacre-config` user messages. `send-request` sets
DNT/Sec-GPC/Save-Data, applies redirects, strips tracking parameters from sub-resources (`net::rules`, the one
copy, shared with the browser by `#[path]`). Loaded from `NACRE_WEBEXT_DIR`, else `<exe>/../lib/nacre` (packages:
`$APPDIR/usr/lib/nacre`), else the exe's folder (cargo builds it next to `target/release/nacre`).
- **Blocked counts**: a content-filter block never reaches `send-request` or the UI process. WebKit logs each one to
the page console ("Content blocker prevented frame displaying <page> from loading a resource from <url>"); the
extension's `console-message-sent` handler sends a `nacre-blocked` message to the page's view, and the UI adds it
to `Hub::blocked` (reset in the `load-changed` Started handler). Limits: depends on WebKit's console wording;
WebKit may not log blocks for every load type (checked: script, image, fetch, module, async/defer, dynamic import);
a block logged just after a new page starts may count for the new page.

View file

@ -1895,10 +1895,19 @@ impl App {
blocker.rule_count()
}, |app, rules| {
*app.shared.adblock_status.borrow_mut() = format!("{} rules", fmt_count(rules));
app.use_content_filter();
app.redraw_all();
});
}
/// Hand the ad blocker's latest build to WebKit (content filter) and the web process extension (redirects).
fn use_content_filter(&mut self) {
if let (Some(engine), Some(filter)) = (&self.engine, self.shared.adblock.content_filter()) {
engine.set_content_filter(filter);
}
self.refresh_hub_config();
}
pub fn update_filter_lists(&mut self, max_age: u64) {
let settings = self.shared.settings.borrow().adblock.clone();
let blocker = self.shared.adblock.clone();
@ -1908,11 +1917,11 @@ impl App {
self.redraw_all();
self.spawn("adblock-update", move || {
let refreshed = blocker.update_lists(&settings, &dir, max_age);
if refreshed > 0 {
blocker.build(&settings, &dir, &cache);
}
// Also when nothing was downloaded: own rules may have changed (unchanged lists load from the cache).
blocker.build(&settings, &dir, &cache);
(refreshed, blocker.rule_count())
}, |app, (refreshed, rules)| {
app.use_content_filter();
app.shared.settings.borrow_mut().adblock.last_update = util::now();
app.applied.adblock.last_update = app.shared.settings.borrow().adblock.last_update;
app.save_settings();

View file

@ -1,6 +1,6 @@
//! Ad and tracker blocking with adblock-rust (the engine Brave uses): network rules decide each
//! request in `load_web_resource`, cosmetic rules hide elements on the page, and a YouTube script
//! removes video ads. Lists are downloaded to the cache and refreshed every `update_days`; seed
//! Ad and tracker blocking with adblock-rust (the engine Brave uses). Network rules are converted to WebKit content
//! filters (D-036, `convert`) that WebKit runs itself; redirect rules go to the web process extension
//! (`net::rules`); cosmetic rules hide elements on the page, and a YouTube script removes video ads. Lists are downloaded to the cache and refreshed every `update_days`; seed
//! copies ship with Nacre so blocking works offline on the first start.
use std::collections::{HashMap, HashSet};
@ -8,11 +8,14 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::Duration;
use adblock::lists::{FilterFormat, FilterSet, ParseOptions};
use adblock::request::Request;
use adblock::content_blocking::{CbLoadType, CbRule, CbRuleEquivalent, CbType, ignore_previous_fp_documents};
use adblock::filters::network::NetworkFilterFeaturesMask;
use adblock::lists::{FilterFormat, FilterSet, ParseOptions, ParsedLine, RuleTypes, parse_filter};
use adblock::Engine;
use serde::{Deserialize, Serialize};
use crate::net::fetch;
use crate::net::rules::Redirect;
use crate::store::settings::AdBlock as AdBlockSettings;
use crate::util;
@ -86,34 +89,130 @@ pub const YOUTUBE_JS: &str = r#"(() => { const h = location.hostname; if (!/(^|\
if (document.documentElement) start(); else document.addEventListener('readystatechange', start, { once: true });
})();"#;
/// What to do with a request.
pub enum Verdict {
Allow,
Block,
/// Serve this body instead (a harmless stand-in from a `redirect` rule): (mime, body).
Replace(String, Vec<u8>),
/// The stand-ins redirect rules may serve (uBlock Origin's names): (mime, body). Rules naming another resource
/// block instead.
pub fn resource(name: &str) -> Option<(&'static str, &'static [u8])> {
const GIF: &[u8] = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;";
Some(match name {
"noopjs" | "noop.js" => ("application/javascript", b"(function() {})();"),
"nooptext" | "noop.txt" => ("text/plain", b""),
"noopcss" | "noop.css" => ("text/css", b""),
"noopjson" | "noop.json" => ("application/json", b"{}"),
"noopframe" | "noop.html" => ("text/html", b"<!DOCTYPE html>"),
"1x1.gif" | "1x1-transparent.gif" | "2x2.png" | "2x2-transparent.png" | "3x2.png" | "3x2-transparent.png" | "32x32.png" | "32x32-transparent.png" => ("image/gif", GIF),
_ => return None,
})
}
/// Map a fetch destination to an adblock request type.
pub fn request_type(destination: &str) -> &'static str {
match destination {
"document" => "document",
"iframe" | "frame" => "subdocument",
"script" | "worker" | "sharedworker" | "serviceworker" | "audioworklet" | "paintworklet" => "script",
"style" | "xslt" => "stylesheet",
"image" => "image",
"font" => "font",
"audio" | "video" | "track" => "media",
"object" | "embed" => "object",
"report" => "ping",
"json" | "none" | "" => "xmlhttprequest",
_ => "other",
/// WebKit refuses a content filter with more rules than this ("Too many rules in JSON array").
const MAX_WEBKIT_RULES: usize = 150_000;
/// The network rules in WebKit's terms (D-036).
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Converted {
/// Content-blocker rule lists, each at most `MAX_WEBKIT_RULES`: a share of the blocks, then every exception
/// (`ignore-previous-rules` only reaches rules of its own list).
#[serde(skip)]
pub lists: Vec<Vec<CbRule>>,
/// How many lists (kept in the build cache).
pub parts: usize,
/// Rules the extension serves a stand-in for.
pub redirects: Vec<Redirect>,
/// Network rules read and converted (into one or more WebKit rules, or a redirect).
pub network: usize,
pub converted: usize,
/// Rules left out, by reason (adblock-rust's names, plus "RedirectRuleOnly").
pub dropped: Vec<(String, usize)>,
}
/// Convert the network rules of these lists. Cosmetic rules stay with the engine (page scripts).
pub fn convert(lists: &[(&str, FilterFormat)]) -> Converted {
let mut filters = Vec::new();
for (text, format) in lists {
let options = ParseOptions { format: *format, rule_types: RuleTypes::NetworkOnly, ..ParseOptions::default() };
filters.extend(text.lines().filter_map(|line| match parse_filter(line, true, options) {
Ok(ParsedLine::Network(f)) => Some(f),
_ => None,
}));
}
let bad: HashSet<_> = filters.iter().filter(|f| f.is_badfilter()).map(|f| f.get_id()).collect();
let mut out = Converted::default();
let mut dropped: HashMap<String, usize> = HashMap::new();
let (mut blocks, mut exceptions) = (Vec::new(), Vec::new());
for mut f in filters {
if f.is_badfilter() || bad.contains(&f.get_id()) {
continue;
}
out.network += 1;
let mut stand_in = None;
if f.is_redirect() {
// `$redirect=` blocks and serves a stand-in; `$redirect-rule=` only replaces what another rule blocks,
// which a content filter's block never lets the extension see.
if !f.also_block_redirect() {
*dropped.entry("RedirectRuleOnly".into()).or_default() += 1;
continue;
}
let name = f.modifier_option.unwrap_or("").split(':').next().unwrap_or("").to_owned();
stand_in = resource(&name).map(|_| name);
f.features_mask.remove(NetworkFilterFeaturesMask::IS_REDIRECT | NetworkFilterFeaturesMask::ALSO_BLOCK_REDIRECT);
f.modifier_option = None;
}
match CbRuleEquivalent::try_from(f) {
Err(e) => {
let reason = format!("{e:?}");
*dropped.entry(reason.split('(').next().unwrap_or("").to_owned()).or_default() += 1;
},
Ok(equivalent) => {
out.converted += 1;
for rule in equivalent {
match (&rule.action.typ, &stand_in) {
(CbType::IgnorePreviousRules, _) => exceptions.push(rule),
(CbType::Block, Some(name)) => out.redirects.push(Redirect {
url: rule.trigger.url_filter,
case: rule.trigger.url_filter_is_case_sensitive.unwrap_or(false),
if_domain: rule.trigger.if_domain.unwrap_or_default(),
unless_domain: rule.trigger.unless_domain.unwrap_or_default(),
third_party: rule.trigger.load_type.first().map(|t| matches!(t, CbLoadType::ThirdParty)),
resource: name.clone(),
}),
_ => blocks.push(rule),
}
}
},
}
}
// Lists repeat each other (hosts lists especially).
let mut seen = HashSet::new();
blocks.retain(|r| seen.insert(serde_json::to_string(r).unwrap_or_default()));
exceptions.retain(|r| seen.insert(serde_json::to_string(r).unwrap_or_default()));
exceptions.push(ignore_previous_fp_documents());
out.lists = split(&blocks, &exceptions, MAX_WEBKIT_RULES);
out.parts = out.lists.len();
let mut dropped: Vec<(String, usize)> = dropped.into_iter().collect();
dropped.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
out.dropped = dropped;
out
}
/// Rule lists of at most `max` rules: the blocks shared out, every list ending with all the exceptions.
fn split(blocks: &[CbRule], exceptions: &[CbRule], max: usize) -> Vec<Vec<CbRule>> {
let share = max.saturating_sub(exceptions.len()).max(1);
blocks.chunks(share).map(|c| c.iter().chain(exceptions).cloned().collect()).collect()
}
/// The compiled-filter side of a build: what the engine loads into WebKit.
#[derive(Clone, Debug)]
pub struct ContentFilter {
/// Each filter's name in WebKit's store (changes whenever the lists do) and the content-blocker JSON WebKit
/// compiles it from (only read when the store has no filter by that name).
pub parts: Vec<(String, PathBuf)>,
pub redirects: Vec<Redirect>,
}
struct Built {
engine: Engine,
rules: usize,
filter: ContentFilter,
}
pub struct AdBlocker {
@ -122,6 +221,8 @@ pub struct AdBlocker {
pub failures: RwLock<HashMap<String, String>>,
pub updating: std::sync::atomic::AtomicBool,
pub building: std::sync::atomic::AtomicBool,
/// A build asked for while another ran: done by that one when it finishes.
pending: std::sync::Mutex<Option<(AdBlockSettings, PathBuf, PathBuf)>>,
}
/// The seed copies shipped with Nacre (next to the program, or in the source tree when developing).
@ -147,7 +248,7 @@ impl Default for AdBlocker {
impl AdBlocker {
pub fn new() -> AdBlocker {
AdBlocker { built: RwLock::new(None), failures: RwLock::new(HashMap::new()), updating: false.into(), building: false.into() }
AdBlocker { built: RwLock::new(None), failures: RwLock::new(HashMap::new()), updating: false.into(), building: false.into(), pending: Default::default() }
}
pub fn ready(&self) -> bool {
@ -158,6 +259,11 @@ impl AdBlocker {
self.built.read().ok().and_then(|b| b.as_ref().map(|b| b.rules)).unwrap_or(0)
}
/// The WebKit content filter of the last build.
pub fn content_filter(&self) -> Option<ContentFilter> {
self.built.read().ok().and_then(|b| b.as_ref().map(|b| b.filter.clone()))
}
/// Copy seed lists into the cache for any enabled list that has never been downloaded.
pub fn seed(dir: &Path) {
let Some(seed) = seed_dir() else { return };
@ -179,11 +285,23 @@ impl AdBlocker {
/// Build the engine from the enabled lists. Blocking (a second or two); call from a worker.
/// Uses the cached compiled engine when the lists haven't changed.
/// A build asked for while one runs is done right after it, by the running one (latest settings win).
pub fn build(&self, settings: &AdBlockSettings, dir: &Path, cache: &Path) {
use std::sync::atomic::Ordering;
if self.building.swap(true, Ordering::SeqCst) {
return;
if let Ok(mut pending) = self.pending.lock() {
*pending = Some((settings.clone(), dir.to_owned(), cache.to_owned()));
}
let pending = || self.pending.lock().map(|p| p.is_some()).unwrap_or(false);
// A request that lands between the last take and letting go of `building` is picked up by the re-check.
while pending() && !self.building.swap(true, Ordering::SeqCst) {
while let Some((settings, dir, cache)) = self.pending.lock().ok().and_then(|mut p| p.take()) {
self.build_once(&settings, &dir, &cache);
}
self.building.store(false, Ordering::SeqCst);
}
}
fn build_once(&self, settings: &AdBlockSettings, dir: &Path, cache: &Path) {
Self::seed(dir);
let mut keys: Vec<String> = settings.lists.iter().filter(|k| list_by_key(k).is_some()).cloned().collect();
keys.extend(settings.custom.iter().map(|u| custom_key(u)));
@ -198,39 +316,57 @@ impl AdBlocker {
fingerprint.push_str(&settings.own_rules);
let fingerprint = util::hex(&simple_hash(fingerprint.as_bytes()).to_le_bytes());
let stamp_path = cache.with_extension("stamp");
let json = |i: usize| cache.with_extension(format!("webkit{i}.json"));
let converted_path = cache.with_extension("converted.json");
let filter_of = |converted: &Converted| ContentFilter { parts: (0..converted.parts).map(|i| (format!("nacre-adblock-{fingerprint}-{i}"), json(i))).collect(), redirects: converted.redirects.clone() };
let cached_stamp = std::fs::read_to_string(&stamp_path).unwrap_or_default();
if cached_stamp.trim_start().starts_with(&fingerprint)
&& let Ok(bytes) = std::fs::read(cache)
&& let Some(converted) = std::fs::read(&converted_path).ok().and_then(|b| serde_json::from_slice::<Converted>(&b).ok())
&& (0..converted.parts).all(|i| json(i).exists())
{
let mut engine = Engine::default();
if engine.deserialize(&bytes).is_ok() {
let rules = cached_stamp.split_whitespace().nth(1).and_then(|n| n.parse().ok()).unwrap_or(0);
if let Ok(mut built) = self.built.write() {
*built = Some(Built { engine, rules });
*built = Some(Built { engine, rules, filter: filter_of(&converted) });
}
self.building.store(false, Ordering::SeqCst);
return;
}
}
// The engine keeps only cosmetic rules (network rules run in WebKit's content filter).
let cosmetic = ParseOptions { rule_types: RuleTypes::CosmeticOnly, ..ParseOptions::default() };
let mut set = FilterSet::new(false);
let mut texts = Vec::new();
let mut rules = 0usize;
for key in &keys {
let Ok(text) = std::fs::read_to_string(list_path(dir, key)) else { continue };
let format = if looks_like_hosts(&text) { FilterFormat::Hosts } else { FilterFormat::Standard };
rules += count_rules(&text);
set.add_filter_list(text, ParseOptions { format, ..ParseOptions::default() });
if matches!(format, FilterFormat::Standard) {
set.add_filter_list(text.clone(), cosmetic);
}
texts.push((text, format));
}
if !settings.own_rules.trim().is_empty() {
rules += count_rules(&settings.own_rules);
set.add_filter_list(settings.own_rules.clone(), ParseOptions::default());
set.add_filter_list(settings.own_rules.clone(), cosmetic);
texts.push((settings.own_rules.clone(), FilterFormat::Standard));
}
let engine = Engine::new_with_filter_set(set);
let started = std::time::Instant::now();
let converted = convert(&texts.iter().map(|(t, f)| (t.as_str(), *f)).collect::<Vec<_>>());
eprintln!("adblock: {} network rules, {} converted into {} WebKit rules in {} lists and {} redirects in {} ms; dropped {:?}", converted.network, converted.converted, converted.lists.iter().map(Vec::len).sum::<usize>(), converted.parts, converted.redirects.len(), started.elapsed().as_millis(), converted.dropped);
for (i, list) in converted.lists.iter().enumerate() {
let _ = util::write_atomic(&json(i), &serde_json::to_vec(list).unwrap_or_default(), false);
}
let _ = util::write_atomic(&converted_path, &serde_json::to_vec(&converted).unwrap_or_default(), false);
let _ = util::write_atomic(cache, &engine.serialize(), false);
let _ = std::fs::write(&stamp_path, format!("{fingerprint} {rules}"));
let filter = filter_of(&converted);
if let Ok(mut built) = self.built.write() {
*built = Some(Built { engine, rules });
*built = Some(Built { engine, rules, filter });
}
self.building.store(false, Ordering::SeqCst);
}
/// Download enabled lists that are older than `max_age` seconds (0 = all). Blocking.
@ -273,21 +409,6 @@ impl AdBlocker {
refreshed
}
/// Decide a network request. `page_url` is the page that made it ("" for top-level loads).
pub fn check(&self, url: &str, page_url: &str, destination: &str) -> Verdict {
let Ok(built) = self.built.read() else { return Verdict::Allow };
let Some(built) = built.as_ref() else { return Verdict::Allow };
let source = if page_url.is_empty() { url } else { page_url };
let Ok(request) = Request::new(url, source, request_type(destination), "GET") else { return Verdict::Allow };
let result = built.engine.check_network_request(&request);
if let Some(redirect) = result.redirect.as_deref()
&& let Some((mime, body)) = decode_data_url(redirect)
{
return Verdict::Replace(mime, body);
}
if result.should_block() { Verdict::Block } else { Verdict::Allow }
}
/// Selectors to hide on this page and whether generic hiding is off for it.
pub fn page_selectors(&self, url: &str) -> (Vec<String>, HashSet<String>, bool) {
let Ok(built) = self.built.read() else { return (Vec::new(), HashSet::new(), false) };
@ -318,15 +439,6 @@ fn looks_like_hosts(text: &str) -> bool {
text.lines().filter(|l| !l.trim().is_empty() && !l.starts_with('#') && !l.starts_with('!')).take(20).filter(|l| l.starts_with("0.0.0.0 ") || l.starts_with("127.0.0.1 ")).count() >= 10
}
fn decode_data_url(url: &str) -> Option<(String, Vec<u8>)> {
use base64::Engine as _;
let rest = url.strip_prefix("data:")?;
let (meta, data) = rest.split_once(',')?;
let mime = meta.split(';').next().unwrap_or("text/plain").to_owned();
let body = if meta.ends_with(";base64") { base64::engine::general_purpose::STANDARD.decode(data).ok()? } else { util::percent_decode(data).into_bytes() };
Some((mime, body))
}
/// FNV-1a; only used to notice that the lists changed.
fn simple_hash(data: &[u8]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325u64;
@ -347,7 +459,6 @@ mod tests {
#[test]
fn urls_are_joined() {
assert_eq!(list_by_key("ublock").unwrap().url, "https://ublockorigin.github.io/uAssets/filters/filters.txt");
assert_eq!(request_type("iframe"), "subdocument");
}
#[test]
@ -357,9 +468,45 @@ mod tests {
let settings = AdBlockSettings { lists: Vec::new(), own_rules: "||ads.example^\nexample.org##.banner".into(), ..AdBlockSettings::default() };
let blocker = AdBlocker::new();
blocker.build(&settings, &dir.join("lists"), &dir.join("engine.bin"));
assert!(matches!(blocker.check("https://ads.example/x.js", "https://news.example/", "script"), Verdict::Block));
assert!(matches!(blocker.check("https://news.example/app.js", "https://news.example/", "script"), Verdict::Allow));
assert!(blocker.page_selectors("https://example.org/").0.contains(&".banner".to_owned()));
let filter = blocker.content_filter().unwrap();
let rules: serde_json::Value = serde_json::from_slice(&std::fs::read(&filter.parts[0].1).unwrap()).unwrap();
assert!(rules.as_array().unwrap().iter().any(|r| r["action"]["type"] == "block" && r["trigger"]["url-filter"].as_str().unwrap().contains("ads\\.example")));
// A second build with the same lists reads the cache and names the same filter.
let again = AdBlocker::new();
again.build(&settings, &dir.join("lists"), &dir.join("engine.bin"));
assert_eq!(again.content_filter().unwrap().parts, filter.parts);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn conversion_keeps_blocks_exceptions_and_stand_ins() {
let list = "||ads.example^\n@@||ads.example/ok.js\n||t.example/gtm.js$script,redirect=noopjs\n||t.example/x.js$redirect=unknown.js\n||t.example/y.js$redirect-rule=noopjs\n||x.example^$csp=script-src 'none'\n/ad[0-9]{2}/\n||bad.example^\n||bad.example^$badfilter\nexample.org##.banner";
let out = convert(&[(list, FilterFormat::Standard)]);
assert_eq!(out.parts, 1);
let types: Vec<String> = out.lists[0].iter().map(|r| format!("{:?}", r.action.typ)).collect();
// Block ads.example, block x.js (unknown stand-in), then the exception, then first-party documents.
assert_eq!(types, ["Block", "Block", "IgnorePreviousRules", "IgnorePreviousRules"]);
assert_eq!(out.redirects.len(), 1);
assert_eq!(out.redirects[0].resource, "noopjs");
assert_eq!((out.network, out.converted), (7, 4));
let reasons: Vec<&str> = out.dropped.iter().map(|(r, _)| r.as_str()).collect();
assert!(reasons.contains(&"RedirectRuleOnly") && reasons.contains(&"NetworkCspUnsupported") && reasons.contains(&"FullRegexUnsupported"));
let r = crate::net::rules::Redirects::new(&out.redirects);
assert_eq!(r.find("https://t.example/gtm.js?id=1", "t.example", "news.example"), Some("noopjs"));
assert_eq!(r.find("https://t.example/other.js", "t.example", "news.example"), None);
assert_eq!(resource("noopjs").unwrap().0, "application/javascript");
}
#[test]
fn big_filters_split_and_keep_their_exceptions() {
let out = convert(&[("||a.example^\n||b.example^\n||c.example^\n||a.example^\n@@||a.example/ok^", FilterFormat::Standard)]);
let blocks: Vec<CbRule> = out.lists[0].iter().filter(|r| r.action.typ == CbType::Block).cloned().collect();
let exceptions: Vec<CbRule> = out.lists[0].iter().filter(|r| r.action.typ != CbType::Block).cloned().collect();
// The repeated a.example rule is kept once.
assert_eq!((blocks.len(), exceptions.len()), (3, 2));
let lists = split(&blocks, &exceptions, 4);
assert_eq!(lists.iter().map(Vec::len).collect::<Vec<_>>(), [4, 3]);
assert!(lists.iter().all(|l| l.ends_with(&exceptions)));
}
}

View file

@ -393,6 +393,7 @@ impl App {
dark_background: dark,
developer_extras: true,
remote_inspector: settings.web.remote_debugging.then(|| "127.0.0.1:6080".to_owned()),
filter_store: paths.cache.join("content-filters"),
};
// Cookies stay in WebKit's memory for the run until S051 seals them (D-037); never plain on disk.
crate::store::cookies::start(&self.shared.paths.data, &self.shared.paths.engine(), self.shared.incognito);
@ -409,16 +410,28 @@ impl App {
self.engine = Some(engine);
self.apply_web_scheme();
self.refresh_hub_config();
if let (Some(engine), Some(filter)) = (&self.engine, self.shared.adblock.content_filter()) {
engine.set_content_filter(filter);
}
self.install_page_scripts();
}
pub fn refresh_hub_config(&self) {
let settings = self.shared.settings.borrow();
*self.hub.config.borrow_mut() = HubConfig::from_settings(&settings, &self.shared.permissions.borrow(), &self.shared.user_agent.borrow(), self.shared.http_allowed.borrow().clone());
// Request headers, third-party cookies and the ad blocker move to WebKit in S049/S050; the language list is
// the engine's own setting.
// Third-party cookies move to WebKit in S050; the language list is the engine's own setting; headers,
// tracking parameters on sub-resources and ad blocker stand-ins are the web process extension's (D-036).
if let Some(engine) = &self.engine {
engine.set_languages(&crate::net::privacy::languages(&crate::net::privacy::locale()));
let config = crate::net::rules::Config {
headers: crate::net::privacy::privacy_headers(&settings).into_iter().map(|(k, v)| (k.to_owned(), v.to_owned())).collect(),
strip: settings.privacy.strip_params,
adblock: settings.adblock.enabled,
paused: settings.adblock.allow.clone(),
redirects: self.shared.adblock.content_filter().map(|f| f.redirects).unwrap_or_default(),
};
engine.set_extension_config(serde_json::to_string(&config).unwrap_or_default());
engine.refresh_filters();
}
}
@ -746,7 +759,6 @@ impl App {
let Some((w, i)) = self.find_webview(id) else { return };
match status {
LoadState::Started => {
self.hub.blocked.borrow_mut().insert(id, 0);
let win = self.windows.get_mut(&w).expect("found");
let tab = &mut win.tabs[i];
tab.load_status = Some(status);

View file

@ -25,6 +25,8 @@ pub struct Setup {
pub developer_extras: bool,
/// Serve the Web Inspector to other browsers on this address (`127.0.0.1:6080`).
pub remote_inspector: Option<String>,
/// Where WebKit keeps the compiled ad blocker filters.
pub filter_store: std::path::PathBuf,
}
pub struct Engine {
@ -41,6 +43,37 @@ pub struct Engine {
/// Hosts whose notifications the user allowed / blocked, told to WebKit when it starts a web process (so
/// `Notification.permission` reads "granted"/"denied" without asking again).
notifications: Rc<RefCell<(Vec<String>, Vec<String>)>>,
filter_store: webkit::UserContentFilterStore,
filter_dir: std::path::PathBuf,
/// The ad blocker's compiled content filters, attached to every view except on paused sites.
filters: Rc<RefCell<Vec<webkit::UserContentFilter>>>,
/// Counts `set_content_filter` calls, so a slow compile of older lists never replaces newer ones.
filter_generation: Rc<std::cell::Cell<u64>>,
/// The web process extension's config JSON (`net::rules::Config`), also given to new web processes.
webext_config: Rc<RefCell<String>>,
}
/// The folder WebKit loads Nacre's web process extension from: `NACRE_WEBEXT_DIR`, the package's `lib/nacre`
/// beside `bin/`, or the build folder (cargo puts `libnacre_webext.so` next to the program).
fn webext_dir() -> Option<std::path::PathBuf> {
if let Some(dir) = env("NACRE_WEBEXT_DIR") {
return Some(dir.into());
}
let exe_dir = std::env::current_exe().ok()?.parent()?.to_owned();
[exe_dir.join("../lib/nacre"), exe_dir].into_iter().find(|d| d.join("libnacre_webext.so").is_file())
}
/// Attach or detach the ad blocker filter for a view about to show a page of `host`.
fn attach_filters(web: &webkit::WebView, hub: &Hub, filters: &RefCell<Vec<webkit::UserContentFilter>>, host: &str) {
let Some(ucm) = web.user_content_manager() else { return };
ucm.remove_all_filters();
let config = hub.config.borrow();
let paused = !config.adblock_enabled || config.adblock_allow.iter().any(|h| crate::util::host_matches(host, h));
if !paused {
for filter in filters.borrow().iter() {
ucm.add_filter(filter);
}
}
}
fn env(name: &str) -> Option<String> {
@ -106,6 +139,33 @@ impl Engine {
if !setup.user_agent.trim().is_empty() {
settings.set_user_agent(Some(setup.user_agent.trim()));
}
// The web process extension (D-036): headers, ad blocker stand-ins, blocked counts.
let webext_config: Rc<RefCell<String>> = Rc::new(RefCell::new("{}".into()));
match webext_dir() {
Some(dir) => {
log::info!("web process extension from {}", dir.display());
context.set_web_process_extensions_directory(&dir.to_string_lossy());
let config = webext_config.clone();
context.connect_initialize_web_process_extensions(move |context| context.set_web_process_extensions_initialization_user_data(&config.borrow().to_variant()));
},
None => eprintln!("no web process extension (libnacre_webext.so): no privacy headers, stand-ins or blocked counts"),
}
context.register_uri_scheme(crate::net::rules::RESOURCE_SCHEME, |request| {
let name = request.path().map(|p| p.to_string()).unwrap_or_default();
match crate::adblock::resource(&name) {
Some((mime, body)) => {
let stream = gtk::gio::MemoryInputStream::from_bytes(&glib::Bytes::from_static(body));
request.finish(&stream, body.len() as i64, Some(mime));
},
None => request.finish_error(&mut glib::Error::new(gtk::gio::IOErrorEnum::NotFound, "no such stand-in")),
}
});
if let Some(security) = context.security_manager() {
security.register_uri_scheme_as_secure(crate::net::rules::RESOURCE_SCHEME);
security.register_uri_scheme_as_cors_enabled(crate::net::rules::RESOURCE_SCHEME);
}
let _ = std::fs::create_dir_all(&setup.filter_store);
let filter_store = webkit::UserContentFilterStore::new(&setup.filter_store.to_string_lossy());
let shade = if setup.dark_background { 0.1 } else { 1.0 };
let notifications: Rc<RefCell<(Vec<String>, Vec<String>)>> = Rc::default();
let answers = notifications.clone();
@ -124,9 +184,82 @@ impl Engine {
views: RefCell::new(HashMap::new()),
background: RefCell::new(gtk::gdk::RGBA::new(shade, shade, shade, 1.0)),
notifications,
filter_store,
filter_dir: setup.filter_store.clone(),
filters: Rc::default(),
filter_generation: Rc::default(),
webext_config,
})
}
/// Use the ad blocker's content filters (D-036): each loaded from WebKit's store when it was compiled before,
/// else compiled from its JSON (seconds for big lists, off the main thread inside WebKit); once all are ready they
/// replace the old ones on every view not on a paused site, and the previous build's are removed from the store.
pub fn set_content_filter(self: &Rc<Self>, filter: crate::adblock::ContentFilter) {
let started = std::time::Instant::now();
let generation = self.filter_generation.get() + 1;
self.filter_generation.set(generation);
let total = filter.parts.len();
let ready: Rc<RefCell<Vec<webkit::UserContentFilter>>> = Rc::default();
let ids: Vec<String> = filter.parts.iter().map(|(id, _)| id.clone()).collect();
for (id, json) in filter.parts {
let weak = Rc::downgrade(self);
let store = self.filter_store.clone();
let (ready, ids) = (ready.clone(), ids.clone());
let done = move |result: Result<webkit::UserContentFilter, glib::Error>| {
let Some(engine) = weak.upgrade() else { return };
if engine.filter_generation.get() != generation {
return;
}
let compiled = match result {
Ok(compiled) => compiled,
Err(e) => return eprintln!("adblock: WebKit couldn't compile a content filter: {e}"),
};
ready.borrow_mut().push(compiled);
if ready.borrow().len() < total {
return;
}
eprintln!("adblock: {total} content filters ready in {} ms", started.elapsed().as_millis());
*engine.filters.borrow_mut() = std::mem::take(&mut *ready.borrow_mut());
engine.refresh_filters();
let current = engine.filter_dir.join("current");
for old in std::fs::read_to_string(&current).unwrap_or_default().lines().filter(|old| !ids.iter().any(|id| id == old)) {
engine.filter_store.remove(old, None::<&gtk::gio::Cancellable>, |_| {});
}
let _ = std::fs::write(&current, ids.join("\n"));
};
let key = id.clone();
self.filter_store.load(&key, None::<&gtk::gio::Cancellable>, move |loaded| match loaded {
Ok(compiled) => done(Ok(compiled)),
Err(_) => store.save_from_file(&id, &gtk::gio::File::for_path(&json), None::<&gtk::gio::Cancellable>, done),
});
}
}
/// The ad blocker filters in use (their store names).
pub fn filter_ids(&self) -> Vec<String> {
self.filters.borrow().iter().filter_map(|f| f.identifier().map(|i| i.to_string())).collect()
}
/// Attach or detach the ad blocker filter on every view after the ad blocker settings changed.
pub fn refresh_filters(&self) {
for web in self.live_views() {
let host = web.uri().and_then(|u| Url::parse(&u).ok()).and_then(|u| u.host_str().map(str::to_owned)).unwrap_or_default();
attach_filters(&web, &self.hub, &self.filters, &host);
}
}
/// The web process extension's settings (`net::rules::Config` JSON): sent to running web processes, and given to
/// new ones when they start.
pub fn set_extension_config(&self, json: String) {
if *self.webext_config.borrow() == json {
return;
}
let message = webkit::UserMessage::new(crate::net::rules::CONFIG_MESSAGE, Some(&json.to_variant()));
*self.webext_config.borrow_mut() = json;
self.context.send_message_to_all_extensions(&message);
}
/// The saved notification answers (hosts allowed, hosts blocked); read when WebKit starts a web process.
pub fn set_notification_answers(&self, allowed: Vec<String>, blocked: Vec<String>) {
*self.notifications.borrow_mut() = (allowed, blocked);
@ -234,6 +367,7 @@ impl Engine {
};
let web = builder.build();
web.set_background_color(&self.background.borrow());
attach_filters(&web, &self.hub, &self.filters, "");
self.views.borrow_mut().insert(id, web.downgrade());
let view = View::new(id, web);
self.wire(&view);
@ -271,6 +405,11 @@ impl Engine {
webkit::LoadEvent::Finished => LoadState::Complete,
_ => return,
};
if state == LoadState::Started {
// Here, not in the app's event handling: the extension's blocked counts for the new page may arrive
// before the app handles this event.
hub.blocked.borrow_mut().insert(id, 0);
}
hub.push(Event::Load(id, state));
if state != LoadState::Started {
let (entries, current) = View::new(id, w.clone()).back_forward();
@ -314,7 +453,18 @@ impl Engine {
true
});
let hub = self.hub.clone();
web.connect_decide_policy(move |_, decision, kind| match kind {
web.connect_user_message_received(move |_, message| {
if message.name().as_deref() != Some(crate::net::rules::BLOCKED_MESSAGE) {
return false;
}
// A request the content filter blocked (the extension read WebKit's console line).
*hub.blocked.borrow_mut().entry(id).or_default() += 1;
*hub.blocked_total.borrow_mut() += 1;
true
});
let hub = self.hub.clone();
let filters = self.filters.clone();
web.connect_decide_policy(move |web, decision, kind| match kind {
webkit::PolicyDecisionType::NavigationAction => {
let Some(nav) = decision.downcast_ref::<webkit::NavigationPolicyDecision>() else { return false };
let Some(mut action) = nav.navigation_action() else { return false };
@ -323,6 +473,8 @@ impl Engine {
return false;
}
let Some(url) = action.request().and_then(|r| r.uri()).and_then(|u| Url::parse(&u).ok()) else { return false };
// The filter is set for the page's site before it loads (paused sites go without).
attach_filters(web, &hub, &filters, url.host_str().unwrap_or(""));
hub.push(Event::Navigation(id, NavigationRequest::new(url, decision.clone())));
true
},

View file

@ -8,6 +8,9 @@ pub mod download;
pub mod fetch;
pub mod policy;
pub mod privacy;
/// Shared with the web process extension (D-036).
#[path = "../../webext/src/rules.rs"]
pub mod rules;
pub mod tor;
use crate::net::bridge::{Route, Upstream};

View file

@ -1,10 +1,9 @@
//! The decision for one request the engine is about to make: HTTPS-only upgrade and tracking-parameter strip for
//! pages, the Images permission and the ad blocker for sub-resources. Pure: the engine glue applies the outcome
//! (serve a redirect page, cancel, replace the body) and keeps the counts.
//! pages, the Images permission for sub-resources. Pure: the engine glue applies the outcome. The ad blocker runs
//! inside WebKit (content filters and the web process extension, D-036), not here.
use url::Url;
use crate::adblock::{AdBlocker, Verdict};
use crate::net::privacy::strip_tracking;
use crate::store::permissions::{Answer, Decision, Kind, Permissions};
use crate::store::settings::Settings;
@ -75,13 +74,11 @@ pub enum Outcome {
Upgrade(Url),
/// Open this URL instead (tracking parameters removed).
Strip(Url),
/// Cancel it. `counted`: the ad blocker blocked it (the shield counts it); not counted for the Images permission.
Block { counted: bool },
/// Serve this body instead (ad blocker redirect resource): (mime, body). Counted as blocked.
Replace(String, Vec<u8>),
/// Cancel it (Images permission; not counted by the shield).
Block,
}
pub fn decide(config: &HubConfig, adblock: &AdBlocker, req: &Request) -> Outcome {
pub fn decide(config: &HubConfig, req: &Request) -> Outcome {
let url = req.url;
if req.main_frame && matches!(url.scheme(), "http" | "https") {
// HTTPS-only: upgrade plain http documents (not local addresses, not exceptions).
@ -104,20 +101,12 @@ pub fn decide(config: &HubConfig, adblock: &AdBlocker, req: &Request) -> Outcome
return Outcome::NewPage;
}
// Sub-resources: the Images permission, then the ad blocker.
// Sub-resources: the Images permission.
let page_host = util::host_of_str(req.page_url);
if req.kind == "image" && matches!(url.scheme(), "http" | "https") && !page_host.is_empty() && config.images_blocked(&page_host) {
return Outcome::Block { counted: false };
}
let paused = !config.adblock_enabled || config.adblock_allow.iter().any(|h| util::host_matches(&page_host, h));
if paused || !matches!(url.scheme(), "http" | "https" | "ws" | "wss") {
return Outcome::Allow;
}
match adblock.check(url.as_str(), req.page_url, req.kind) {
Verdict::Allow => Outcome::Allow,
Verdict::Block => Outcome::Block { counted: true },
Verdict::Replace(mime, body) => Outcome::Replace(mime, body),
return Outcome::Block;
}
Outcome::Allow
}
#[cfg(test)]
@ -144,30 +133,28 @@ mod tests {
#[test]
fn pages_are_upgraded_then_stripped() {
let adblock = AdBlocker::new();
let mut config = HubConfig { https_only: true, strip_params: true, https_exceptions: vec!["old.example".into()], ..Default::default() };
let u = Url::parse("http://a.example:80/p?utm_source=x").unwrap();
assert_eq!(decide(&config, &adblock, &req(&u, "document", true, "")), Outcome::Upgrade(Url::parse("https://a.example/p?utm_source=x").unwrap()));
assert_eq!(decide(&config, &req(&u, "document", true, "")), Outcome::Upgrade(Url::parse("https://a.example/p?utm_source=x").unwrap()));
let u = Url::parse("https://a.example/p?utm_source=x").unwrap();
assert_eq!(decide(&config, &adblock, &req(&u, "document", true, "")), Outcome::Strip(Url::parse("https://a.example/p").unwrap()));
assert_eq!(decide(&config, &req(&u, "document", true, "")), Outcome::Strip(Url::parse("https://a.example/p").unwrap()));
let u = Url::parse("http://old.example/").unwrap();
assert_eq!(decide(&config, &adblock, &req(&u, "document", true, "")), Outcome::NewPage);
assert_eq!(decide(&config, &req(&u, "document", true, "")), Outcome::NewPage);
let u = Url::parse("http://127.0.0.1:8000/").unwrap();
assert_eq!(decide(&config, &adblock, &req(&u, "document", true, "")), Outcome::NewPage);
assert_eq!(decide(&config, &req(&u, "document", true, "")), Outcome::NewPage);
config.http_allowed.push("a.example".into());
let u = Url::parse("http://a.example/").unwrap();
assert_eq!(decide(&config, &adblock, &req(&u, "document", true, "")), Outcome::NewPage);
assert_eq!(decide(&config, &req(&u, "document", true, "")), Outcome::NewPage);
}
#[test]
fn blocked_images_are_not_counted_and_paused_sites_pass() {
let adblock = AdBlocker::new();
fn blocked_images_follow_the_site() {
let config = HubConfig { images_sites: vec![("a.example".into(), true)], adblock_enabled: true, adblock_allow: vec!["b.example".into()], ..Default::default() };
let img = Url::parse("https://cdn.example/x.png").unwrap();
assert_eq!(decide(&config, &adblock, &req(&img, "image", false, "https://a.example/")), Outcome::Block { counted: false });
assert_eq!(decide(&config, &adblock, &req(&img, "image", false, "https://b.example/")), Outcome::Allow);
assert_eq!(decide(&config, &req(&img, "image", false, "https://a.example/")), Outcome::Block);
assert_eq!(decide(&config, &req(&img, "image", false, "https://b.example/")), Outcome::Allow);
let data = Url::parse("data:image/png;base64,AA").unwrap();
assert_eq!(decide(&config, &adblock, &req(&data, "image", false, "https://c.example/")), Outcome::Allow);
assert_eq!(decide(&config, &req(&data, "image", false, "https://c.example/")), Outcome::Allow);
}
#[test]

View file

@ -1,16 +1,8 @@
//! Privacy rules that don't depend on the engine: the extra request headers, tracking parameters and the
//! Firefox-style language list. The engine glue applies them (S023, S024).
use url::Url;
use crate::store::settings::Settings;
/// Tracking parameters removed from links when "strip tracking parameters" is on.
const TRACKING_PARAMS: &[&str] = &[
"fbclid", "gclid", "dclid", "gbraid", "wbraid", "msclkid", "mc_eid", "mc_cid", "igshid", "yclid", "_hsenc", "_hsmi", "twclid", "ttclid", "li_fat_id", "oly_enc_id", "oly_anon_id", "vero_id", "wickedid", "_openstat", "mkt_tok", "s_cid", "srsltid", "rb_clickid", "epik", "ga_source",
];
const TRACKING_PREFIXES: &[&str] = &["utm_", "pk_", "mtm_", "hsa_"];
/// Headers every request carries for the privacy settings: Do Not Track with Global Privacy Control, and
/// Save-Data.
pub fn privacy_headers(settings: &Settings) -> Vec<(&'static str, &'static str)> {
@ -24,22 +16,7 @@ pub fn privacy_headers(settings: &Settings) -> Vec<(&'static str, &'static str)>
headers
}
/// The URL without tracking parameters, if it had any.
pub fn strip_tracking(url: &Url) -> Option<Url> {
url.query()?;
let pairs: Vec<(String, String)> = url.query_pairs().map(|(k, v)| (k.into_owned(), v.into_owned())).collect();
let keep: Vec<&(String, String)> = pairs.iter().filter(|(k, _)| { let k = k.to_ascii_lowercase(); !TRACKING_PARAMS.contains(&k.as_str()) && !TRACKING_PREFIXES.iter().any(|p| k.starts_with(p)) }).collect();
if keep.len() == pairs.len() {
return None;
}
let mut clean = url.clone();
if keep.is_empty() {
clean.set_query(None);
} else {
clean.query_pairs_mut().clear().extend_pairs(keep.iter().map(|(k, v)| (k.as_str(), v.as_str())));
}
Some(clean)
}
pub use super::rules::strip_tracking;
/// The languages pages are told about, Firefox-style: the locale and its bare language (`["en-US", "en"]`), or
/// the locale alone when it has no region.
@ -75,6 +52,7 @@ pub fn accept_language(languages: &[String]) -> String {
#[cfg(test)]
mod tests {
use super::*;
use url::Url;
#[test]
fn privacy_language_list_is_firefox_style() {

View file

@ -30,6 +30,7 @@
//! js <script> run JavaScript in the current tab; the result goes to the log
//! save <name> <js> run JavaScript in the current tab and write its string result to <name>.json
//! assert <js expression> the expression must give true, else `ASSERT FAILED` in the log fails the smoke run
//! waitstatus <s> <pointer> <json> poll a `status` value until it equals json, at most s seconds (timeout fails)
//! expect <pointer> <json> a value of the `status` JSON must equal json (e.g. `expect /tabs/1/pinned true`;
//! `/active/...` is the active tab, `/tab_count` the number of tabs; `> n` a number above n)
//! click <x> <y> click in the page at CSS pixel x,y (from the page's top left); `rclick` the same with
@ -87,6 +88,8 @@ pub struct SelfTest {
located: std::sync::Arc<std::sync::Mutex<Option<(f64, f64)>>>,
/// `waitfor`: the expression and when to give up.
wait_js: Option<(String, Instant)>,
/// `waitstatus`: when to give up.
wait_status_until: Option<Instant>,
/// (an evaluation is in flight, the last one gave true)
js_poll: std::sync::Arc<std::sync::Mutex<(bool, bool)>>,
/// A real input helper (wl-input, wtype) still sending; the script goes on once it exits.
@ -99,7 +102,7 @@ impl SelfTest {
let text = std::fs::read_to_string(&path).ok()?;
let dir = path.parent().map(|p| p.to_owned()).unwrap_or_else(|| PathBuf::from("."));
let lines = text.lines().map(|l| l.trim().to_owned()).filter(|l| !l.is_empty() && !l.starts_with('#')).collect();
Some(SelfTest { lines, next: 0, wait_until: None, wait_load_until: None, dir, pending_shot: false, pending_release: None, held: None, located: Default::default(), wait_js: None, js_poll: Default::default(), input: None })
Some(SelfTest { lines, next: 0, wait_until: None, wait_load_until: None, dir, pending_shot: false, pending_release: None, held: None, located: Default::default(), wait_js: None, wait_status_until: None, js_poll: Default::default(), input: None })
}
fn log(&self, text: &str) {
@ -271,6 +274,23 @@ impl App {
let text = serde_json::to_string_pretty(&self.selftest_status(window)).unwrap_or_default();
let _ = std::fs::write(dir.join(format!("{rest}.json")), text);
},
"waitstatus" => {
let mut parts = rest.splitn(3, char::is_whitespace);
let secs: f64 = parts.next().and_then(|s| s.parse().ok()).unwrap_or(30.0);
let pointer = parts.next().unwrap_or("");
let want: serde_json::Value = parts.next().and_then(|w| serde_json::from_str(w.trim()).ok()).unwrap_or(serde_json::Value::Null);
let got = self.selftest_status(window).pointer(pointer).cloned().unwrap_or(serde_json::Value::Null);
let Some(t) = self.selftest.as_mut() else { return };
let until = *t.wait_status_until.get_or_insert(Instant::now() + Duration::from_secs_f64(secs));
if got == want || Instant::now() >= until {
t.wait_status_until = None;
t.log(&if got == want { format!("waitstatus ok: {pointer} = {got}") } else { format!("ASSERT FAILED (waitstatus timed out): {pointer} is {got}") });
} else {
// Run this line again shortly.
t.next -= 1;
t.wait_until = Some(Instant::now() + Duration::from_millis(250));
}
},
"expect" => {
// Compare one value of the `status` JSON, e.g. `expect /tabs/1/pinned true`; a mismatch fails the run.
let (pointer, want) = rest.split_once(char::is_whitespace).unwrap_or((rest, "null"));
@ -842,7 +862,7 @@ impl App {
"vpn": format!("{:?}", self.shared.vpn_status.borrow()),
"route": self.shared.bridge.as_ref().map(|b| format!("{:?}", b.route())),
"bridge_bytes": self.shared.bridge.as_ref().map(|b| b.bytes.load(std::sync::atomic::Ordering::Relaxed)),
"adblock": {"ready": self.shared.adblock.ready(), "rules": self.shared.adblock.rule_count(), "status": self.shared.adblock_status.borrow().clone(), "total": settings.adblock.total},
"adblock": {"ready": self.shared.adblock.ready(), "filters_ready": self.shared.adblock.content_filter().is_some_and(|f| self.engine.as_ref().is_some_and(|e| e.filter_ids() == f.parts.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>())), "rules": self.shared.adblock.rule_count(), "status": self.shared.adblock_status.borrow().clone(), "total": settings.adblock.total},
"permissions": self.shared.permissions.borrow().all().iter().fold(serde_json::Map::new(), |mut m, (host, kind, decision)| {
m.entry(host.clone()).or_insert_with(|| serde_json::json!({})).as_object_mut().expect("object").insert(kind.key().to_owned(), serde_json::json!(format!("{decision:?}").to_lowercase()));
m

View file

@ -10,6 +10,8 @@ set /adblock/lists []
set /adblock/custom ["http://127.0.0.1:8766/list.txt"]
wait 5
expect /adblock/rules 4
# WebKit compiles the content filter (queued behind the seed lists' first compile, S049).
waitstatus 90 /adblock/filters_ready true
open @PAGES@/crash-adblock.html?rounds=20
waitfor 120 window.crash && window.crash.done && document.readyState === "complete"
status pass1

View file

@ -1,7 +1,9 @@
# Network pass (S007): the ad blocker on a local page. The shipped seed lists build offline; then only a local list
# (tests/smoke/net/server.py /list.txt, a custom list URL) blocks a script and an image, and hides one element by a
# site rule and one by a generic rule; pausing for the site lets everything through; a list that can't be fetched
# is reported and the engine keeps the rules it has. Offline. Never Tor or proxies. Start the server first:
# is reported and the engine keeps the rules it has. Blocking runs in WebKit content filters, counted through the web
# process extension (S049); `waitstatus` waits for WebKit to compile a filter (the seed lists take ~15 s the first
# time). Offline. Never Tor or proxies. Start the server first:
# python3 tests/smoke/net/server.py & then tools/smoke.sh tests/smoke/net-adblock.txt
wait 3
set /adblock/update_days 0
@ -9,11 +11,13 @@ wait 5
status seed
expect /adblock/ready true
expect /adblock/rules > 10000
waitstatus 90 /adblock/filters_ready true
set /adblock/lists []
set /adblock/custom ["http://127.0.0.1:8766/list.txt"]
wait 5
status local
expect /adblock/rules 4
waitstatus 30 /adblock/filters_ready true
open http://127.0.0.1:8766/ads.html
waitfor 20 document.title === "Ads" && window.pixelLoaded !== null
wait 2
@ -36,6 +40,17 @@ assert getComputedStyle(document.querySelector(".nacre-ad")).display !== "none"
status paused
expect /active/blocked 0
set /adblock/allow []
# A redirect rule (S049): the web process extension serves the noopjs stand-in from nacre-resource: instead.
set /adblock/own_rules "||127.0.0.1:8766/standin.js$xmlhttprequest,redirect=noopjs"
wait 3
waitstatus 30 /adblock/filters_ready true
open http://127.0.0.1:8766/ads.html
waitfor 20 document.title === "Ads"
js fetch("/standin.js").then(r => r.text()).then(t => { window.standin = t; }, e => { window.standin = "error " + e; })
waitfor 10 window.standin !== undefined
assert window.standin === "(function() {})();"
set /adblock/own_rules ""
wait 3
# A list that can't be fetched: the failure is reported, the local list's rules stay.
set /adblock/custom ["http://127.0.0.1:8766/list.txt","http://127.0.0.1:8767/missing.txt"]
wait 5

21
webext/Cargo.toml Normal file
View file

@ -0,0 +1,21 @@
[package]
name = "nacre-webext"
version = "0.4.0"
edition = "2024"
rust-version = "1.88"
description = "Nacre's WebKit web process extension: request headers, ad blocker stand-ins, blocked counts (D-036)"
license = "MPL-2.0"
publish = false
[lib]
name = "nacre_webext"
crate-type = ["cdylib"]
path = "src/lib.rs"
[dependencies]
glib-sys = "0.22"
gobject-sys = "0.22"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
url = "2.5"
regex-lite = "0.1"

175
webext/src/lib.rs Normal file
View file

@ -0,0 +1,175 @@
//! Nacre's web process extension (D-036). WebKit loads it into every web process, so it stays small: no ad block
//! engine here, only what WebKit's content filters can't do. On `send-request` it adds the privacy headers, serves
//! redirect rules' stand-ins (`nacre-resource:`) and strips tracking parameters from sub-resources; on
//! `console-message-sent` it tells the page's view about each request the content filter blocked (WebKit reports
//! those only on the console). The config comes from the browser at start and in `nacre-config` messages.
#![allow(clippy::missing_safety_doc)]
pub mod rules;
use std::ffi::{CStr, CString, c_char, c_void};
use std::sync::Mutex;
use glib_sys::{GVariant, gboolean, gpointer};
use rules::{BLOCKED_MESSAGE, CONFIG_MESSAGE, Config, Redirects};
#[repr(C)]
pub struct Opaque {
_private: [u8; 0],
}
#[link(name = "webkitgtk-6.0")]
unsafe extern "C" {
fn webkit_web_page_get_uri(page: *mut Opaque) -> *const c_char;
fn webkit_web_page_send_message_to_view(page: *mut Opaque, message: *mut Opaque, cancellable: *mut c_void, callback: *mut c_void, data: gpointer);
fn webkit_uri_request_get_uri(request: *mut Opaque) -> *const c_char;
fn webkit_uri_request_set_uri(request: *mut Opaque, uri: *const c_char);
fn webkit_uri_request_get_http_headers(request: *mut Opaque) -> *mut Opaque;
fn webkit_console_message_get_text(message: *mut Opaque) -> *const c_char;
fn webkit_user_message_new(name: *const c_char, parameters: *mut GVariant) -> *mut Opaque;
fn webkit_user_message_get_name(message: *mut Opaque) -> *const c_char;
fn webkit_user_message_get_parameters(message: *mut Opaque) -> *mut GVariant;
}
#[link(name = "soup-3.0")]
unsafe extern "C" {
fn soup_message_headers_replace(headers: *mut Opaque, name: *const c_char, value: *const c_char);
}
struct State {
config: Config,
redirects: Redirects,
/// The headers as C strings, made once per config.
headers: Vec<(CString, CString)>,
}
static STATE: Mutex<Option<State>> = Mutex::new(None);
fn debug() -> bool {
std::env::var_os("NACRE_WEBEXT_DEBUG").is_some()
}
fn set_config(json: &str) {
let config: Config = match serde_json::from_str(json) {
Ok(c) => c,
Err(e) => {
eprintln!("nacre-webext: bad config: {e}");
return;
},
};
let redirects = Redirects::new(&config.redirects);
let headers = config.headers.iter().filter_map(|(k, v)| Some((CString::new(k.as_str()).ok()?, CString::new(v.as_str()).ok()?))).collect();
if debug() {
eprintln!("nacre-webext: config: {} headers, {} redirects, strip {}", config.headers.len(), redirects.len(), config.strip);
}
*STATE.lock().unwrap_or_else(|e| e.into_inner()) = Some(State { config, redirects, headers });
}
unsafe fn str_of<'a>(p: *const c_char) -> Option<&'a str> {
if p.is_null() { None } else { unsafe { CStr::from_ptr(p) }.to_str().ok() }
}
unsafe fn variant_str<'a>(v: *mut GVariant) -> Option<&'a str> {
if v.is_null() || unsafe { glib_sys::g_variant_is_of_type(v, c"s".as_ptr() as *const _) } == 0 {
return None;
}
unsafe { str_of(glib_sys::g_variant_get_string(v, std::ptr::null_mut())) }
}
unsafe fn connect(instance: *mut Opaque, signal: &CStr, handler: *const ()) {
unsafe {
gobject_sys::g_signal_connect_data(instance as *mut _, signal.as_ptr(), Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(handler)), std::ptr::null_mut(), None, 0);
}
}
unsafe extern "C" fn send_request(page: *mut Opaque, request: *mut Opaque, _redirected: *mut Opaque, _: gpointer) -> gboolean {
let guard = STATE.lock().unwrap_or_else(|e| e.into_inner());
let Some(state) = guard.as_ref() else { return 0 };
let Some(url) = (unsafe { str_of(webkit_uri_request_get_uri(request)) }) else { return 0 };
if !(url.starts_with("http:") || url.starts_with("https:")) {
return 0;
}
let page_url = unsafe { str_of(webkit_web_page_get_uri(page)) }.unwrap_or("");
let headers = unsafe { webkit_uri_request_get_http_headers(request) };
if !headers.is_null() {
for (k, v) in &state.headers {
unsafe { soup_message_headers_replace(headers, k.as_ptr(), v.as_ptr()) };
}
}
// The page's own document load keeps its URL (the browser decides main-frame navigations).
if url == page_url {
return 0;
}
if let Some(new) = rules::rewrite(&state.config, &state.redirects, url, page_url)
&& let Ok(c) = CString::new(new.as_str())
{
if debug() {
eprintln!("nacre-webext: {url} -> {new}");
}
unsafe { webkit_uri_request_set_uri(request, c.as_ptr()) };
}
0
}
/// WebKit's console line for a content-filter block ends with the blocked URL:
/// "Content blocker prevented frame displaying <page> from loading a resource from <url>".
fn blocked_url(text: &str) -> Option<&str> {
text.starts_with("Content blocker prevented").then(|| text.rsplit_once(" from ").map(|(_, u)| u.trim())).flatten()
}
unsafe extern "C" fn console_message(page: *mut Opaque, message: *mut Opaque, _: gpointer) {
let Some(text) = (unsafe { str_of(webkit_console_message_get_text(message)) }) else { return };
if debug() {
eprintln!("nacre-webext: console: {text}");
}
let Some(url) = blocked_url(text) else { return };
let Ok(url) = CString::new(url) else { return };
unsafe {
let param = glib_sys::g_variant_new_string(url.as_ptr());
let msg = webkit_user_message_new(BLOCKED_MESSAGE_C.as_ptr(), param);
webkit_web_page_send_message_to_view(page, msg, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut());
}
}
const BLOCKED_MESSAGE_C: &CStr = c"nacre-blocked";
unsafe extern "C" fn page_created(_extension: *mut Opaque, page: *mut Opaque, _: gpointer) {
unsafe {
connect(page, c"send-request", send_request as *const ());
connect(page, c"console-message-sent", console_message as *const ());
}
}
unsafe extern "C" fn user_message(_extension: *mut Opaque, message: *mut Opaque, _: gpointer) -> gboolean {
let name = unsafe { str_of(webkit_user_message_get_name(message)) };
if name != Some(CONFIG_MESSAGE) {
return 0;
}
if let Some(json) = unsafe { variant_str(webkit_user_message_get_parameters(message)) } {
set_config(json);
}
1
}
/// WebKit's entry point: the user data is the config JSON as a string variant.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn webkit_web_process_extension_initialize_with_user_data(extension: *mut Opaque, user_data: *const GVariant) {
debug_assert_eq!(BLOCKED_MESSAGE_C.to_str(), Ok(BLOCKED_MESSAGE));
if let Some(json) = unsafe { variant_str(user_data as *mut _) } {
set_config(json);
}
unsafe {
connect(extension, c"page-created", page_created as *const ());
connect(extension, c"user-message-received", user_message as *const ());
}
}
#[cfg(test)]
mod tests {
#[test]
fn blocked_url_reads_webkit_console_line() {
assert_eq!(super::blocked_url("Content blocker prevented frame displaying http://a.test/ from loading a resource from http://ads.test/x.js"), Some("http://ads.test/x.js"));
assert_eq!(super::blocked_url("Uncaught TypeError"), None);
}
}

152
webext/src/rules.rs Normal file
View file

@ -0,0 +1,152 @@
//! What the web process extension does to each request, without any WebKit: the config the browser sends it, the
//! ad blocker's redirect rules and the tracking-parameter strip. Shared by the extension (`webext/`) and the
//! browser (`nacre::net::rules`, which builds the config and tests these).
use serde::{Deserialize, Serialize};
use url::Url;
/// Tracking parameters removed from links when "strip tracking parameters" is on.
pub const TRACKING_PARAMS: &[&str] = &[
"fbclid", "gclid", "dclid", "gbraid", "wbraid", "msclkid", "mc_eid", "mc_cid", "igshid", "yclid", "_hsenc", "_hsmi", "twclid", "ttclid", "li_fat_id", "oly_enc_id", "oly_anon_id", "vero_id", "wickedid", "_openstat", "mkt_tok", "s_cid", "srsltid", "rb_clickid", "epik", "ga_source",
];
pub const TRACKING_PREFIXES: &[&str] = &["utm_", "pk_", "mtm_", "hsa_"];
/// The URI scheme redirect rules point at; the browser serves the stand-ins (`adblock::resource`).
pub const RESOURCE_SCHEME: &str = "nacre-resource";
/// The user message the extension sends its page's view for each request the content filter blocked
/// (parameter: the blocked URL).
pub const BLOCKED_MESSAGE: &str = "nacre-blocked";
/// The user message that carries a new `Config` (parameter: its JSON) to every extension.
pub const CONFIG_MESSAGE: &str = "nacre-config";
/// The extension's settings, sent as JSON at web process start and on every change.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Config {
/// Added to every request (DNT, Sec-GPC, Save-Data).
#[serde(default)]
pub headers: Vec<(String, String)>,
/// Remove tracking parameters from sub-resource URLs.
#[serde(default)]
pub strip: bool,
/// The ad blocker is on (redirect rules apply).
#[serde(default)]
pub adblock: bool,
/// Sites the ad blocker is paused on (host suffixes).
#[serde(default)]
pub paused: Vec<String>,
#[serde(default)]
pub redirects: Vec<Redirect>,
}
/// An ad blocker rule that serves a harmless stand-in instead of blocking (`$redirect=noopjs`), in WebKit's
/// content-blocker terms (the trigger of the converted rule).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Redirect {
/// WebKit's url-filter regex (its small dialect, which `regex_lite` reads too).
pub url: String,
#[serde(default)]
pub case: bool,
/// Page hosts it applies to / not to; "*host" also covers subdomains.
#[serde(default)]
pub if_domain: Vec<String>,
#[serde(default)]
pub unless_domain: Vec<String>,
/// Some(true): only third-party requests; Some(false): only first-party.
#[serde(default)]
pub third_party: Option<bool>,
/// The stand-in's name (`noopjs`, `1x1.gif`, …).
pub resource: String,
}
/// Whether `host` is `domain` or below it.
pub fn host_matches(host: &str, domain: &str) -> bool {
host == domain || (host.len() > domain.len() && host.ends_with(domain) && host.as_bytes()[host.len() - domain.len() - 1] == b'.')
}
/// The last two labels of a host: a rough site for the third-party test (the extension has no public suffix list).
fn site(host: &str) -> &str {
let mut dots = host.rmatch_indices('.');
match (dots.next(), dots.next()) {
(Some(_), Some((i, _))) => &host[i + 1..],
_ => host,
}
}
fn domain_listed(list: &[String], host: &str) -> bool {
list.iter().any(|d| match d.strip_prefix('*') {
Some(d) => host_matches(host, d),
None => host == d,
})
}
/// Redirect rules with their regexes compiled once.
pub struct Redirects {
rules: Vec<(Redirect, regex_lite::Regex)>,
}
impl Redirects {
pub fn new(rules: &[Redirect]) -> Redirects {
let rules = rules
.iter()
.filter_map(|r| regex_lite::RegexBuilder::new(&r.url).case_insensitive(!r.case).build().ok().map(|re| (r.clone(), re)))
.collect();
Redirects { rules }
}
pub fn len(&self) -> usize {
self.rules.len()
}
/// The stand-in for this request on a page of `page_host`, if a rule takes it.
pub fn find(&self, url: &str, host: &str, page_host: &str) -> Option<&str> {
let third = site(host) != site(page_host);
self.rules
.iter()
.find(|(r, re)| {
r.third_party.is_none_or(|t| t == third)
&& (r.if_domain.is_empty() || domain_listed(&r.if_domain, page_host))
&& !domain_listed(&r.unless_domain, page_host)
&& re.is_match(url)
})
.map(|(r, _)| r.resource.as_str())
}
}
/// The URL without tracking parameters, if it had any.
pub fn strip_tracking(url: &Url) -> Option<Url> {
url.query()?;
let pairs: Vec<(String, String)> = url.query_pairs().map(|(k, v)| (k.into_owned(), v.into_owned())).collect();
let keep: Vec<&(String, String)> = pairs.iter().filter(|(k, _)| { let k = k.to_ascii_lowercase(); !TRACKING_PARAMS.contains(&k.as_str()) && !TRACKING_PREFIXES.iter().any(|p| k.starts_with(p)) }).collect();
if keep.len() == pairs.len() {
return None;
}
let mut clean = url.clone();
if keep.is_empty() {
clean.set_query(None);
} else {
clean.query_pairs_mut().clear().extend_pairs(keep.iter().map(|(k, v)| (k.as_str(), v.as_str())));
}
Some(clean)
}
/// What the extension does with one request: the URL to load instead, if any.
pub fn rewrite(config: &Config, redirects: &Redirects, url: &str, page_url: &str) -> Option<String> {
let parsed = Url::parse(url).ok()?;
if !matches!(parsed.scheme(), "http" | "https") {
return None;
}
let host = parsed.host_str().unwrap_or("");
let page_host = Url::parse(page_url).ok().and_then(|u| u.host_str().map(str::to_owned)).unwrap_or_default();
if config.adblock
&& !page_host.is_empty()
&& !config.paused.iter().any(|p| host_matches(&page_host, p))
&& let Some(resource) = redirects.find(url, host, &page_host)
{
return Some(format!("{RESOURCE_SCHEME}:{resource}"));
}
if config.strip {
return strip_tracking(&parsed).map(String::from);
}
None
}