diff --git a/Cargo.lock b/Cargo.lock index b70bf80..b9def73 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index 144f712..6762a04 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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"] } diff --git a/Plans/08 WebKit engine/S049-adblock-webext.md b/Plans/08 WebKit engine/S049-adblock-webext.md index 5492c1f..0eb28ad 100644 --- a/Plans/08 WebKit engine/S049-adblock-webext.md +++ b/Plans/08 WebKit engine/S049-adblock-webext.md @@ -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. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index b5c766b..212b0aa 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -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 `/adblock-engine.webkit.json`, compiled by + `UserContentFilterStore` (`/content-filters`, id `nacre-adblock--`); 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=`): 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:` (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 `/../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 from loading a resource from "); 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. diff --git a/src/actions.rs b/src/actions.rs index c1e4e17..cafbffe 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -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(); diff --git a/src/adblock.rs b/src/adblock.rs index 691829d..5a55b89 100644 --- a/src/adblock.rs +++ b/src/adblock.rs @@ -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), +/// 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""), + "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>, + /// How many lists (kept in the build cache). + pub parts: usize, + /// Rules the extension serves a stand-in for. + pub redirects: Vec, + /// 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 = 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> { + 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, } struct Built { engine: Engine, rules: usize, + filter: ContentFilter, } pub struct AdBlocker { @@ -122,6 +221,8 @@ pub struct AdBlocker { pub failures: RwLock>, 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>, } /// 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 { + 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 = 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::(&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::>()); + 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::(), 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, HashSet, 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)> { - 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 = 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 = out.lists[0].iter().filter(|r| r.action.typ == CbType::Block).cloned().collect(); + let exceptions: Vec = 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::>(), [4, 3]); + assert!(lists.iter().all(|l| l.ends_with(&exceptions))); + } } diff --git a/src/app.rs b/src/app.rs index 2c99d9c..b6e4d6a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -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); diff --git a/src/engine/host.rs b/src/engine/host.rs index f1ffd44..2cb1a7e 100644 --- a/src/engine/host.rs +++ b/src/engine/host.rs @@ -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, + /// 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, Vec)>>, + 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>>, + /// Counts `set_content_filter` calls, so a slow compile of older lists never replaces newer ones. + filter_generation: Rc>, + /// The web process extension's config JSON (`net::rules::Config`), also given to new web processes. + webext_config: Rc>, +} + +/// 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 { + 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>, 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 { @@ -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> = 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, Vec)>> = 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, 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>> = Rc::default(); + let ids: Vec = 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| { + 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(¤t).unwrap_or_default().lines().filter(|old| !ids.iter().any(|id| id == old)) { + engine.filter_store.remove(old, None::<>k::gio::Cancellable>, |_| {}); + } + let _ = std::fs::write(¤t, ids.join("\n")); + }; + let key = id.clone(); + self.filter_store.load(&key, None::<>k::gio::Cancellable>, move |loaded| match loaded { + Ok(compiled) => done(Ok(compiled)), + Err(_) => store.save_from_file(&id, >k::gio::File::for_path(&json), None::<>k::gio::Cancellable>, done), + }); + } + } + + /// The ad blocker filters in use (their store names). + pub fn filter_ids(&self) -> Vec { + 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, blocked: Vec) { *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::() 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 }, diff --git a/src/net/mod.rs b/src/net/mod.rs index 88d8a3d..ce4e05d 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -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}; diff --git a/src/net/policy.rs b/src/net/policy.rs index dbfae90..5226f54 100644 --- a/src/net/policy.rs +++ b/src/net/policy.rs @@ -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), + /// 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] diff --git a/src/net/privacy.rs b/src/net/privacy.rs index 8d8f54e..3eb8475 100644 --- a/src/net/privacy.rs +++ b/src/net/privacy.rs @@ -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.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() { diff --git a/src/selftest.rs b/src/selftest.rs index 024aa02..9b37b69 100644 --- a/src/selftest.rs +++ b/src/selftest.rs @@ -30,6 +30,7 @@ //! js