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

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
},