Nacre/src/adblock.rs
astar76 f63ddf8da1 S050 (WIP): WebKit through the bridge over SOCKS5, navigation policy, certificate warning, downloads, cookie policy
- Bridge speaks SOCKS5 on its port; WebKit uses it (plain http through the HTTP proxy lost the login and looped);
  loopback skips the proxy.
- decide-policy: HTTPS-only upgrade with redirect guard, tracking strip, Content-Disposition downloads; Images
  permission as a WebKit content filter (net::policy::images_filter).
- load-failed-with-tls-errors -> Nacre's certificate page (assets/pages/badcert.html), "Open anyway" via
  nacre://allowcert for that tab only.
- download-started: web links to Nacre's downloader, blob:/data: saved by WebKit and tracked in the downloads list.
- Third-party cookies: NoThirdParty + ITP; privacy mode Accept-Language through the extension.
- selftest js/assert/save wait for the page's answer (unanswered asserts used to pass).
- Smokes: net-privacy (+localhost, TLS, images), net-downloads (+<a download>, blob:), privacy-net on https.
Open: main-frame detection for navigations, Google UA quirk, privacy-mode/cache smokes (see plan "Resume").

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 15:27:36 -06:00

512 lines
28 KiB
Rust

//! 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};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::Duration;
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;
pub struct FilterList {
pub key: &'static str,
pub group: &'static str,
pub name: &'static str,
pub url: &'static str,
pub description: &'static str,
}
macro_rules! list {
($key:literal, $group:literal, $name:literal, $url:expr, $desc:literal) => {
FilterList { key: $key, group: $group, name: $name, url: $url, description: $desc }
};
}
pub const LISTS: &[FilterList] = &[
list!("easylist", "Ads", "EasyList", "https://easylist.to/easylist/easylist.txt", "The main ad list"),
list!("ublock", "Ads", "uBlock filters", "https://ublockorigin.github.io/uAssets/filters/filters.txt", "uBlock Origin's own ad rules"),
list!("adguard_base", "Ads", "AdGuard Base", "https://filters.adtidy.org/extension/ublock/filters/2_without_easylist.txt", "AdGuard ads, minus EasyList overlap"),
list!("adguard_mobile", "Ads", "AdGuard Mobile Ads", "https://filters.adtidy.org/extension/ublock/filters/11.txt", "Ads on mobile-style sites"),
list!("pgl", "Ads", "Peter Lowe's list", "https://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&mimetype=plaintext", "Small, fast ad and tracker host list"),
list!("easyprivacy", "Privacy", "EasyPrivacy", "https://easylist.to/easylist/easyprivacy.txt", "Trackers and analytics"),
list!("ublock_privacy", "Privacy", "uBlock Privacy", "https://ublockorigin.github.io/uAssets/filters/privacy.txt", "Extra tracking protection"),
list!("adguard_tracking", "Privacy", "AdGuard Tracking Protection", "https://filters.adtidy.org/extension/ublock/filters/3.txt", "Thorough tracker blocking"),
list!("adguard_url", "Privacy", "AdGuard URL Tracking", "https://filters.adtidy.org/extension/ublock/filters/17.txt", "Tracking parameters and endpoints"),
list!("ublock_badware", "Security", "uBlock Badware risks", "https://ublockorigin.github.io/uAssets/filters/badware.txt", "Scam and fake-download sites"),
list!("urlhaus", "Security", "URLhaus Malicious URLs", "https://malware-filter.gitlab.io/malware-filter/urlhaus-filter-ag-online.txt", "Active malware hosts"),
list!("phishing", "Security", "Phishing URL Blocklist", "https://malware-filter.gitlab.io/malware-filter/phishing-filter-ag.txt", "Known phishing pages"),
list!("annoyances", "Annoyances", "uBlock Annoyances", "https://ublockorigin.github.io/uAssets/filters/annoyances.txt", "Pop-ups, overlays, nags"),
list!("cookies", "Annoyances", "EasyList Cookie List", "https://secure.fanboy.co.nz/fanboy-cookiemonster.txt", "Hides cookie banners"),
list!("fanboy_annoyance", "Annoyances", "Fanboy Annoyances", "https://secure.fanboy.co.nz/fanboy-annoyance.txt", "Social widgets, newsletters"),
list!("adguard_annoyances", "Annoyances", "AdGuard Annoyances", "https://filters.adtidy.org/extension/ublock/filters/14.txt", "AdGuard's annoyance collection"),
list!("stevenblack", "Hosts & DNS lists", "StevenBlack hosts", "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts", "Unified ad and malware hosts"),
list!("oisd", "Hosts & DNS lists", "OISD small", "https://small.oisd.nl/", "Low false-positive DNS list"),
list!("hagezi", "Hosts & DNS lists", "HaGeZi Pro", "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/adblock/pro.txt", "Aggressive but well maintained"),
list!("onehosts", "Hosts & DNS lists", "1Hosts Lite", "https://o0.pages.dev/Lite/adblock.txt", "Light, balanced host list"),
list!("ublock_quick", "Fixes", "uBlock Quick fixes", "https://ublockorigin.github.io/uAssets/filters/quick-fixes.txt", "Fast-moving fixes (YouTube, Twitch…)"),
list!("ublock_unbreak", "Fixes", "uBlock Unbreak", "https://ublockorigin.github.io/uAssets/filters/unbreak.txt", "Exceptions that un-break sites"),
];
pub fn list_by_key(key: &str) -> Option<&'static FilterList> {
LISTS.iter().find(|l| l.key == key)
}
/// CSS selectors removed on YouTube in addition to the lists.
pub const YT_AD_SELECTORS: &[&str] = &[
"ytd-ad-slot-renderer", "ytd-in-feed-ad-layout-renderer", "ytd-display-ad-renderer", "ytd-promoted-sparkles-web-renderer",
"ytd-promoted-video-renderer", "ytd-compact-promoted-video-renderer", "ytd-search-pyv-renderer", "ytd-banner-promo-renderer",
"ytd-statement-banner-renderer", "ytd-video-masthead-ad-v3-renderer", "#masthead-ad", "#player-ads",
"ytd-engagement-panel-section-list-renderer[target-id='engagement-panel-ads']", "ytd-merch-shelf-renderer",
"ytd-ads-engagement-panel-content-renderer", "ytd-player-legacy-desktop-watch-ads-renderer",
".ytd-mealbar-promo-renderer", "ytmusic-mealbar-promo-renderer", "ytm-promoted-sparkles-web-renderer",
];
/// Removes ads from YouTube's player data and skips video ads that still play.
pub const YOUTUBE_JS: &str = r#"(() => { const h = location.hostname; if (!/(^|\.)youtube(-nocookie)?\.com$/.test(h)) return;
const KEYS = ['adPlacements', 'adSlots', 'playerAds', 'adBreakHeartbeatParams'];
const prune = o => { try { if (o && typeof o === 'object') { for (const k of KEYS) if (k in o) delete o[k];
if (o.playerResponse) prune(o.playerResponse); if (o.response) prune(o.response); } } catch (e) {} return o; };
const jp = JSON.parse; JSON.parse = function () { return prune(jp.apply(this, arguments)); };
const rj = Response.prototype.json; Response.prototype.json = function () { return rj.apply(this, arguments).then(prune); };
for (const name of ['ytInitialPlayerResponse', 'ytInitialData']) { let v;
try { Object.defineProperty(window, name, { configurable: true, get: () => v, set: x => { v = prune(x); } }); } catch (e) {} }
const skip = () => { const p = document.querySelector('#movie_player.ad-showing, ytmusic-player .ad-showing');
if (p) { const v = p.querySelector('video'); if (v && isFinite(v.duration)) { v.muted = true; v.currentTime = v.duration; } }
const b = document.querySelector('.ytp-skip-ad-button, .ytp-ad-skip-button, .ytp-ad-skip-button-modern');
if (b) b.click(); };
const start = () => new MutationObserver(skip).observe(document.documentElement, { subtree: true, attributes: true, attributeFilter: ['class'], childList: true });
if (document.documentElement) start(); else document.addEventListener('readystatechange', start, { once: true });
})();"#;
/// 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,
})
}
/// 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 {
built: RwLock<Option<Built>>,
/// Lists that failed to download last time: key -> reason.
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).
fn seed_dir() -> Option<PathBuf> {
let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_owned));
let candidates = [exe_dir.as_ref().map(|d| d.join("filters")), exe_dir.as_ref().map(|d| d.join("../share/nacre/filters")), Some(PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/assets/filters")))];
candidates.into_iter().flatten().find(|d| d.is_dir())
}
fn list_path(dir: &Path, key: &str) -> PathBuf {
dir.join(format!("{}.txt", util::safe_file_name(key)))
}
fn custom_key(url: &str) -> String {
format!("custom-{}", &util::hex(url.as_bytes())[..url.len().min(24) * 2])
}
impl Default for AdBlocker {
fn default() -> Self {
Self::new()
}
}
impl AdBlocker {
pub fn new() -> AdBlocker {
AdBlocker { built: RwLock::new(None), failures: RwLock::new(HashMap::new()), updating: false.into(), building: false.into(), pending: Default::default() }
}
pub fn ready(&self) -> bool {
self.built.read().map(|b| b.is_some()).unwrap_or(false)
}
pub fn rule_count(&self) -> usize {
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 };
let _ = std::fs::create_dir_all(dir);
for list in LISTS {
let target = list_path(dir, list.key);
let source = list_path(&seed, list.key);
if !target.exists() && source.exists() {
let _ = std::fs::copy(&source, &target);
}
}
}
/// Age of a downloaded list in seconds, or None if it isn't there.
pub fn list_age(dir: &Path, key: &str) -> Option<u64> {
let modified = std::fs::metadata(list_path(dir, key)).ok()?.modified().ok()?;
Some(modified.elapsed().map(|d| d.as_secs()).unwrap_or(0))
}
/// 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 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)));
// Fingerprint: list names, sizes, change times and the user's own rules.
let mut fingerprint = String::new();
for key in &keys {
if let Ok(meta) = std::fs::metadata(list_path(dir, key)) {
let modified = meta.modified().ok().and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0);
fingerprint.push_str(&format!("{key}:{}:{modified};", meta.len()));
}
}
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, filter: filter_of(&converted) });
}
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);
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(), 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, filter });
}
}
/// Download enabled lists that are older than `max_age` seconds (0 = all). Blocking.
/// Returns how many were refreshed.
pub fn update_lists(&self, settings: &AdBlockSettings, dir: &Path, max_age: u64) -> usize {
use std::sync::atomic::Ordering;
if self.updating.swap(true, Ordering::SeqCst) {
return 0;
}
let _ = std::fs::create_dir_all(dir);
let mut wanted: Vec<(String, String)> = settings.lists.iter().filter_map(|k| list_by_key(k).map(|l| (k.clone(), l.url.to_owned()))).collect();
wanted.extend(settings.custom.iter().map(|u| (custom_key(u), u.clone())));
let mut refreshed = 0;
for (key, url) in wanted {
if max_age > 0 && Self::list_age(dir, &key).is_some_and(|age| age < max_age) {
continue;
}
match fetch::get(&url, &[], 32 * 1024 * 1024, Duration::from_secs(120)) {
Ok(fetched) if fetched.ok() && fetched.body.len() > 64 => {
if util::write_atomic(&list_path(dir, &key), &fetched.body, false).is_ok() {
refreshed += 1;
if let Ok(mut failures) = self.failures.write() {
failures.remove(&key);
}
}
},
Ok(fetched) => {
if let Ok(mut failures) = self.failures.write() {
failures.insert(key, format!("the server answered {}", fetched.status));
}
},
Err(error) => {
if let Ok(mut failures) = self.failures.write() {
failures.insert(key, error);
}
},
}
}
self.updating.store(false, Ordering::SeqCst);
refreshed
}
/// 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) };
let Some(built) = built.as_ref() else { return (Vec::new(), HashSet::new(), false) };
let resources = built.engine.url_cosmetic_resources(url);
let mut selectors: Vec<String> = resources.hide_selectors.into_iter().collect();
let host = util::host_of_str(url);
if util::host_matches(&host, "youtube.com") {
selectors.extend(YT_AD_SELECTORS.iter().map(|s| (*s).to_owned()));
}
(selectors, resources.exceptions, resources.generichide)
}
/// Generic hiding: selectors for the classes and ids found on a page.
pub fn generic_selectors(&self, classes: &[String], ids: &[String], exceptions: &HashSet<String>) -> Vec<String> {
let Ok(built) = self.built.read() else { return Vec::new() };
let Some(built) = built.as_ref() else { return Vec::new() };
built.engine.hidden_class_id_selectors(classes, ids, exceptions)
}
}
/// Rule lines in a list (comments and headers left out); shown in settings.
fn count_rules(text: &str) -> usize {
text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('!') && !l.starts_with('[') && (!l.starts_with('#') || l.starts_with("##") || l.starts_with("#@#") || l.starts_with("#?#"))).count()
}
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
}
/// FNV-1a; only used to notice that the lists changed.
pub(crate) fn simple_hash(data: &[u8]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325u64;
for b in data {
hash ^= *b as u64;
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
hash
}
/// Shared handle.
pub type SharedAdBlocker = Arc<AdBlocker>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn urls_are_joined() {
assert_eq!(list_by_key("ublock").unwrap().url, "https://ublockorigin.github.io/uAssets/filters/filters.txt");
}
#[test]
fn blocks_with_own_rules() {
let dir = std::env::temp_dir().join(format!("nacre-adblock-test-{}", util::random_hex(6)));
std::fs::create_dir_all(&dir).unwrap();
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!(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)));
}
}