Nacre/src/engine/host.rs

874 lines
45 KiB
Rust

//! The engine's per-profile state (network session, web context, settings, page scripts) and the web views made from
//! it. Each view's signals become `Event`s on the hub; the `ViewId ↔ WebView` map lives here.
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use gtk::glib;
use gtk::prelude::*;
use url::Url;
use webkit::prelude::*;
use super::{AuthRequest, CertError, ColorPicker, Control, Event, FilePicker, Hub, LoadState, NavigationRequest, Notification, PageAction, PageMenuRequest, PermissionAsk, SelectElement, SimpleDialog, UserStyle, View, ViewId, WebDownload};
use crate::store::permissions::Kind as Perm;
/// Settings the engine starts with.
pub struct Setup {
/// Persistent data and cache folders; `None` = ephemeral (incognito).
pub dirs: Option<(std::path::PathBuf, std::path::PathBuf)>,
/// Nacre's network bridge (`socks5://user:[email protected]:port`), if it runs.
pub proxy: Option<String>,
/// User agent override; empty = WebKit's own.
pub user_agent: String,
pub dark_background: bool,
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,
/// WebKit's SQLite cookie store (on tmpfs, sealed by `store::cookies`); `None` = cookies in memory only.
pub cookie_db: Option<std::path::PathBuf>,
}
pub struct Engine {
hub: Rc<Hub>,
session: webkit::NetworkSession,
context: webkit::WebContext,
settings: webkit::Settings,
/// The page scripts every new document gets (each view has its own content manager so page messages know
/// their view).
scripts: RefCell<Vec<String>>,
styles: RefCell<Vec<UserStyle>>,
views: RefCell<HashMap<ViewId, glib::WeakRef<webkit::WebView>>>,
background: RefCell<gtk::gdk::RGBA>,
/// 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 Images permission's filter (pictures blocked per site), on every view whatever the ad blocker does.
images_filter: Rc<RefCell<Option<webkit::UserContentFilter>>>,
}
/// Hosts that never go through the bridge.
const LOOPBACK: &[&str] = &["localhost", "*.localhost", "127.0.0.0/8", "::1"];
/// 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`; the Images filter always.
/// A navigation found to be the tab's own, for the browser to decide.
struct Navigation {
web: webkit::WebView,
hub: Rc<Hub>,
filters: Rc<RefCell<Vec<webkit::UserContentFilter>>>,
images: Rc<RefCell<Option<webkit::UserContentFilter>>>,
id: ViewId,
url: Url,
redirect: bool,
reloadable: bool,
decision: webkit::PolicyDecision,
}
impl Navigation {
fn decide(self) {
// The filter is set for the page's site before it loads (paused sites go without).
attach_filters(&self.web, &self.hub, &self.filters, &self.images, self.url.host_str().unwrap_or(""));
self.hub.push(Event::Navigation(self.id, NavigationRequest::new(self.url, self.redirect, self.reloadable, self.decision)));
}
}
fn attach_filters(web: &webkit::WebView, hub: &Hub, filters: &RefCell<Vec<webkit::UserContentFilter>>, images: &RefCell<Option<webkit::UserContentFilter>>, host: &str) {
let Some(ucm) = web.user_content_manager() else { return };
ucm.remove_all_filters();
if let Some(filter) = images.borrow().as_ref() {
ucm.add_filter(filter);
}
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> {
std::env::var(name).ok().filter(|v| !v.is_empty())
}
impl Engine {
pub fn new(hub: Rc<Hub>, setup: &Setup) -> Rc<Engine> {
if let Some(address) = &setup.remote_inspector {
// Read once when the first web context starts; nothing else in Nacre reads or writes it.
unsafe { std::env::set_var("WEBKIT_INSPECTOR_HTTP_SERVER", address) };
}
// D-040 tuning defaults, env overrides for tests.
let mem_limit: u32 = env("NACRE_WK_MEM_LIMIT").and_then(|v| v.parse().ok()).unwrap_or(500);
let mut pressure = None;
if mem_limit > 0 {
let mut p = webkit::MemoryPressureSettings::new();
p.set_memory_limit(mem_limit);
webkit::NetworkSession::set_memory_pressure_settings(&mut p.clone());
pressure = Some(p);
}
let session = match &setup.dirs {
Some((data, cache)) => {
let _ = std::fs::create_dir_all(data);
let _ = std::fs::create_dir_all(cache);
webkit::NetworkSession::new(Some(&data.to_string_lossy()), Some(&cache.to_string_lossy()))
},
None => webkit::NetworkSession::new_ephemeral(),
};
if let Some(manager) = session.website_data_manager() {
manager.set_favicons_enabled(true);
}
if let (Some(db), Some(cookies)) = (&setup.cookie_db, session.cookie_manager()) {
cookies.set_persistent_storage(&db.to_string_lossy(), webkit::CookiePersistentStorage::Sqlite);
let hub = hub.clone();
cookies.connect_changed(move |_| hub.push(Event::CookiesChanged));
}
// Everything goes through Nacre's bridge except this machine's own addresses (the bridge would only send
// them straight back). SOCKS5: its login is part of the handshake, so plain http works too (S050).
if let Some(proxy) = &setup.proxy {
let settings = webkit::NetworkProxySettings::new(Some(proxy), LOOPBACK);
session.set_proxy_settings(webkit::NetworkProxyMode::Custom, Some(&settings));
}
let context = match &pressure {
Some(p) => webkit::WebContext::builder().memory_pressure_settings(p).build(),
None => webkit::WebContext::new(),
};
// The web process sandbox has no /home: GStreamer there can't read a file:// video or song (D-043).
for dir in media_dirs(std::env::var_os("NACRE_SCRIPT").is_some()) {
context.add_path_to_sandbox(&dir, true);
}
context.set_cache_model(match env("NACRE_WK_CACHE_MODEL").as_deref() {
Some("browser") => webkit::CacheModel::WebBrowser,
Some("viewer") => webkit::CacheModel::DocumentViewer,
// DocumentViewer has no HTTP disk cache (D-040).
_ => webkit::CacheModel::DocumentBrowser,
});
let settings = webkit::Settings::new();
settings.set_enable_developer_extras(setup.developer_extras || env("NACRE_WK_INSPECTOR").is_some());
settings.set_enable_page_cache(env("NACRE_WK_PAGE_CACHE").as_deref() == Some("1"));
settings.set_javascript_can_open_windows_automatically(true);
settings.set_enable_back_forward_navigation_gestures(true);
// Camera and microphone (getUserMedia) and calls; each use still asks (`permission-request`).
settings.set_enable_media_stream(true);
settings.set_enable_webrtc(true);
match env("NACRE_WK_HW").as_deref() {
Some("never") => settings.set_hardware_acceleration_policy(webkit::HardwareAccelerationPolicy::Never),
Some("always") => settings.set_hardware_acceleration_policy(webkit::HardwareAccelerationPolicy::Always),
_ => {},
}
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();
context.connect_initialize_notification_permissions(move |context| {
let origins = |hosts: &[String]| -> Vec<webkit::SecurityOrigin> { hosts.iter().flat_map(|h| ["https", "http"].map(|s| webkit::SecurityOrigin::new(s, h, 0))).collect() };
let (allowed, blocked) = { let a = answers.borrow(); (origins(&a.0), origins(&a.1)) };
context.initialize_notification_permissions(&allowed.iter().collect::<Vec<_>>(), &blocked.iter().collect::<Vec<_>>());
});
let engine = Rc::new(Engine {
hub,
session,
context,
settings,
scripts: RefCell::new(Vec::new()),
styles: RefCell::new(Vec::new()),
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,
images_filter: Rc::default(),
});
engine.watch_downloads();
engine
}
/// Downloads WebKit starts itself (`<a download>`, a page's `blob:` file): web addresses go to Nacre's own
/// downloader like every other download (pause, resume, download managers); the rest only WebKit can fetch, so
/// it saves them where the app says.
fn watch_downloads(self: &Rc<Self>) {
let engine = Rc::downgrade(self);
self.session.connect_download_started(move |_, download| {
let Some(engine) = engine.upgrade() else { return };
let view = download.web_view().and_then(|w| engine.view_id(&w));
let url = download.request().and_then(|r| r.uri()).and_then(|u| Url::parse(&u).ok());
if let (Some(url), Some(view)) = (&url, view)
&& matches!(url.scheme(), "http" | "https")
{
download.cancel();
engine.hub.push(Event::Download(view, url.clone(), None));
return;
}
let hub = engine.hub.clone();
download.connect_decide_destination(move |d, suggested| {
hub.push(Event::WebDownload(view, WebDownload::new(d.clone(), suggested.to_owned())));
true
});
});
}
fn view_id(&self, web: &webkit::WebView) -> Option<ViewId> {
self.views.borrow().iter().find(|(_, w)| w.upgrade().as_ref() == Some(web)).map(|(id, _)| *id)
}
/// Third-party cookies: refused (`block`), or accepted like first-party ones. WebKit's no-third-party policy only
/// stops frames and pictures from storing cookies (and frames from reading them); its tracking prevention (ITP)
/// is what keeps their existing cookies off cross-site requests.
pub fn set_block_third_party_cookies(&self, block: bool) {
if let Some(cookies) = self.session.cookie_manager() {
cookies.set_accept_policy(if block { webkit::CookieAcceptPolicy::NoThirdParty } else { webkit::CookieAcceptPolicy::Always });
}
if self.session.is_itp_enabled() != block {
self.session.set_itp_enabled(block);
}
}
/// "Open anyway": trust this certificate for its host until Nacre quits.
pub fn allow_certificate(&self, error: &CertError) {
self.session.allow_tls_certificate_for_host(&error.certificate, &error.host);
}
/// The Images permission as one more content filter: pictures blocked on the listed sites (or everywhere but
/// the listed ones); `None` = no site blocks them. Compiled once per rule set, like the ad blocker's.
pub fn set_images_filter(self: &Rc<Self>, json: Option<String>) {
let Some(json) = json else {
*self.images_filter.borrow_mut() = None;
return self.refresh_filters();
};
let id = format!("nacre-images-{:016x}", crate::adblock::simple_hash(json.as_bytes()));
if self.images_filter.borrow().as_ref().is_some_and(|f| f.identifier().as_deref() == Some(id.as_str())) {
return;
}
let weak = Rc::downgrade(self);
self.filter_store.save(&id, &glib::Bytes::from_owned(json.into_bytes()), None::<&gtk::gio::Cancellable>, move |result| {
let Some(engine) = weak.upgrade() else { return };
match result {
Ok(filter) => {
*engine.images_filter.borrow_mut() = Some(filter);
engine.refresh_filters();
},
Err(e) => eprintln!("images: WebKit couldn't compile the filter: {e}"),
}
});
}
/// 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, &self.images_filter, &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);
}
/// The user agent pages see.
pub fn user_agent(&self) -> String {
self.settings.user_agent().map(|u| u.to_string()).unwrap_or_default()
}
pub fn set_user_agent(&self, ua: &str) {
self.settings.set_user_agent(if ua.trim().is_empty() { None } else { Some(ua.trim()) });
}
/// Accept-Language and `navigator.languages`.
pub fn set_languages(&self, languages: &[String]) {
let refs: Vec<&str> = languages.iter().map(String::as_str).collect();
self.context.set_preferred_languages(&refs);
}
/// A user agent for one view only (`None`: back to the shared settings). Google's sign-in refuses browsers it
/// doesn't know, so its pages get Firefox's (`HubConfig::wants_ua_quirk`). Whether the view's agent changed: a
/// navigation already on its way still carries the old one.
pub fn set_view_user_agent(&self, view: &View, ua: Option<&str>) -> bool {
let current = webkit::prelude::WebViewExt::settings(&view.web);
let own = current.as_ref() != Some(&self.settings);
match ua {
None if own => view.web.set_settings(&self.settings),
None => return false,
Some(ua) => {
if own && let Some(settings) = &current {
let changed = settings.user_agent().as_deref() != Some(ua);
settings.set_user_agent(Some(ua));
return changed;
}
// A copy of the shared settings with only the user agent (and its quirks) changed.
let copy = webkit::Settings::new();
for spec in self.settings.list_properties().iter() {
let flags = spec.flags();
if flags.contains(glib::ParamFlags::READWRITE) && !flags.intersects(glib::ParamFlags::CONSTRUCT_ONLY) {
copy.set_property_from_value(spec.name(), &self.settings.property_value(spec.name()));
}
}
// WebKit's own site quirks put a Safari user agent on Google's requests over any set one.
copy.set_enable_site_specific_quirks(false);
copy.set_user_agent(Some(ua));
view.web.set_settings(&copy);
},
}
true
}
/// The colour a page shows before it paints (no white flash in dark mode).
pub fn set_dark_background(&self, dark: bool) {
let shade = if dark { 0.1 } else { 1.0 };
*self.background.borrow_mut() = gtk::gdk::RGBA::new(shade, shade, shade, 1.0);
for web in self.live_views() {
web.set_background_color(&self.background.borrow());
}
}
/// Replace the page scripts and user style sheets; scripts apply to each page's next document, style sheets at once.
pub fn set_page_content(&self, scripts: Vec<String>, styles: Vec<UserStyle>) {
*self.scripts.borrow_mut() = scripts;
*self.styles.borrow_mut() = styles;
for web in self.live_views() {
if let Some(ucm) = web.user_content_manager() {
ucm.remove_all_scripts();
ucm.remove_all_style_sheets();
self.add_content(&ucm);
}
}
}
fn add_content(&self, ucm: &webkit::UserContentManager) {
for source in self.scripts.borrow().iter() {
let script = webkit::UserScript::new(source, webkit::UserContentInjectedFrames::AllFrames, webkit::UserScriptInjectionTime::Start, &[], &[]);
ucm.add_script(&script);
}
for style in self.styles.borrow().iter() {
let allow: Vec<&str> = style.allow.iter().map(String::as_str).collect();
let block: Vec<&str> = style.block.iter().map(String::as_str).collect();
let sheet = webkit::UserStyleSheet::new(&style.css, webkit::UserContentInjectedFrames::AllFrames, webkit::UserStyleLevel::Author, &allow, &block);
ucm.add_style_sheet(&sheet);
}
}
fn live_views(&self) -> Vec<webkit::WebView> {
self.views.borrow().values().filter_map(|w| w.upgrade()).collect()
}
/// Delete cookies and stored site data and/or the cache: changed since `since` (Unix seconds, 0 = all; cookies always
/// all), or every
/// item of `hosts` (and their subdomains) whatever its age.
pub fn clear_data(&self, cookies: bool, cache: bool, since: u64, hosts: Option<Vec<String>>) {
let Some(manager) = self.session.website_data_manager() else { return };
let mut types = webkit::WebsiteDataTypes::empty();
if cookies {
types |= webkit::WebsiteDataTypes::ALL & !(webkit::WebsiteDataTypes::MEMORY_CACHE | webkit::WebsiteDataTypes::DISK_CACHE);
}
if cache {
types |= webkit::WebsiteDataTypes::MEMORY_CACHE | webkit::WebsiteDataTypes::DISK_CACHE;
}
if types.is_empty() {
return;
}
match hosts {
None => {
// WebKit takes "modified in the last <span>"; 0 clears everything. Its libsoup cookie store keeps no
// dates and ignores a span, so cookies go whatever the range (the Clear data page says so).
let span = if since == 0 { 0 } else { crate::util::now().saturating_sub(since).max(1) as i64 };
if span != 0 && types.contains(webkit::WebsiteDataTypes::COOKIES) {
manager.clear(webkit::WebsiteDataTypes::COOKIES, glib::TimeSpan::from_seconds(0), None::<&gtk::gio::Cancellable>, |_| {});
types.remove(webkit::WebsiteDataTypes::COOKIES);
}
manager.clear(types, glib::TimeSpan::from_seconds(span), None::<&gtk::gio::Cancellable>, |_| {});
},
Some(hosts) => {
let m = manager.clone();
manager.fetch(types, None::<&gtk::gio::Cancellable>, move |result| {
let Ok(list) = result else { return };
let matching: Vec<webkit::WebsiteData> = list.into_iter().filter(|d| d.name().is_some_and(|n| hosts.iter().any(|h| crate::util::host_matches(&n, h) || crate::util::host_matches(h, &n)))).collect();
if !matching.is_empty() {
let refs: Vec<&webkit::WebsiteData> = matching.iter().collect();
m.remove(types, &refs, None::<&gtk::gio::Cancellable>, |_| {});
}
});
},
}
}
/// What `host` keeps (site info): the cookies sent to `url` and the kinds of stored data under the host's name.
/// Answers with `Event::SiteData`.
pub fn site_data(&self, host: String, url: &str) {
let (Some(manager), Some(cookies)) = (self.session.website_data_manager(), self.session.cookie_manager()) else { return };
let hub = self.hub.clone();
cookies.cookies(url, None::<&gtk::gio::Cancellable>, move |result| {
let count = result.map(|c| c.len()).unwrap_or(0);
let stored = webkit::WebsiteDataTypes::ALL & !(webkit::WebsiteDataTypes::MEMORY_CACHE | webkit::WebsiteDataTypes::DISK_CACHE | webkit::WebsiteDataTypes::COOKIES);
manager.fetch(stored, None::<&gtk::gio::Cancellable>, move |result| {
let mut kinds = webkit::WebsiteDataTypes::empty();
for d in result.unwrap_or_default() {
if d.name().is_some_and(|n| crate::util::host_matches(&host, &n)) {
kinds |= d.types();
}
}
let labels = [
(webkit::WebsiteDataTypes::LOCAL_STORAGE, "local storage"),
(webkit::WebsiteDataTypes::INDEXEDDB_DATABASES, "databases"),
(webkit::WebsiteDataTypes::SERVICE_WORKER_REGISTRATIONS, "service workers"),
(webkit::WebsiteDataTypes::DOM_CACHE, "offline files"),
];
let stored = labels.iter().filter(|(t, _)| kinds.contains(*t)).map(|(_, l)| *l).collect();
hub.push(Event::SiteData(host, super::SiteData { cookies: count, stored }));
});
});
}
/// A new web view for a tab (`related`: a pop-up sharing its opener's web process).
pub fn create_view(self: &Rc<Self>, id: ViewId, related: Option<&View>) -> View {
// The message handler is registered before the view exists, so the first document can already post.
let ucm = webkit::UserContentManager::new();
self.add_content(&ucm);
ucm.register_script_message_handler("nacre", None);
let hub = self.hub.clone();
ucm.connect_script_message_received(Some("nacre"), move |_, value| {
if let Some(msg) = crate::inject::parse_message(&hub.token, &value.to_str()) {
hub.push(Event::Page(id, msg));
}
});
let mut builder = webkit::WebView::builder().settings(&self.settings).user_content_manager(&ucm);
builder = match related.map(|r| &r.web) {
Some(r) => builder.related_view(r),
None => builder.network_session(&self.session).web_context(&self.context),
};
let web = builder.build();
web.set_background_color(&self.background.borrow());
attach_filters(&web, &self.hub, &self.filters, &self.images_filter, "");
self.views.borrow_mut().insert(id, web.downgrade());
let view = View::new(id, web);
self.wire(&view);
view
}
/// Forget a closed view.
pub fn forget(&self, id: ViewId) {
self.views.borrow_mut().remove(&id);
self.hub.forget(id);
}
fn wire(self: &Rc<Self>, view: &View) {
let id = view.id();
let web = &view.web;
let hub = self.hub.clone();
web.connect_uri_notify(move |w| {
if let Some(url) = w.uri().and_then(|u| Url::parse(&u).ok()) {
hub.push(Event::UrlChanged(id, url));
}
});
let hub = self.hub.clone();
web.connect_title_notify(move |w| hub.push(Event::TitleChanged(id, w.title().map(|t| t.to_string()))));
let hub = self.hub.clone();
web.connect_mouse_target_changed(move |_, hit, _| hub.push(Event::StatusText(id, hit.link_uri().map(|u| u.to_string()))));
let hub = self.hub.clone();
web.connect_estimated_load_progress_notify(move |w| hub.push(Event::Progress(id, w.estimated_load_progress())));
let hub = self.hub.clone();
web.connect_favicon_notify(move |_| hub.push(Event::Favicon(id)));
let hub = self.hub.clone();
web.connect_is_playing_audio_notify(move |w| hub.push(Event::Audio(id, w.is_playing_audio())));
let hub = self.hub.clone();
let provisional = Rc::new(std::cell::Cell::new(false));
let tab_loading = provisional.clone();
web.connect_load_changed(move |w, event| {
tab_loading.set(matches!(event, webkit::LoadEvent::Started | webkit::LoadEvent::Redirected));
let state = match event {
webkit::LoadEvent::Started => LoadState::Started,
webkit::LoadEvent::Committed => LoadState::Committed,
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();
hub.push(Event::History(id, entries, current));
}
});
let hub = self.hub.clone();
web.connect_load_failed(move |_, _, uri, error| {
// A load the browser stopped (a decision, a download, Stop) is not a failure.
if error.matches(webkit::NetworkError::Cancelled) || error.matches(webkit::PolicyError::FrameLoadInterruptedByPolicyChange) {
return false;
}
hub.push(Event::LoadFailed(id, uri.to_owned(), error.message().to_owned()));
true
});
let hub = self.hub.clone();
web.connect_close(move |_| hub.push(Event::Closed(id)));
if let Some(find) = web.find_controller() {
let hub = self.hub.clone();
find.connect_found_text(move |_, count| hub.push(Event::Find(id, count)));
let hub = self.hub.clone();
find.connect_failed_to_find_text(move |_| hub.push(Event::Find(id, 0)));
}
let hub = self.hub.clone();
web.connect_web_process_terminated(move |_, reason| {
let why = match reason {
webkit::WebProcessTerminationReason::ExceededMemoryLimit => "The page used more memory than allowed.",
webkit::WebProcessTerminationReason::TerminatedByApi => "The page was stopped.",
_ => "The page's web process crashed.",
};
hub.push(Event::Crashed(id, why.to_owned()));
});
let hub = self.hub.clone();
web.connect_enter_fullscreen(move |_| {
hub.push(Event::Fullscreen(id, true));
true
});
let hub = self.hub.clone();
web.connect_leave_fullscreen(move |_| {
hub.push(Event::Fullscreen(id, false));
true
});
let hub = self.hub.clone();
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();
web.connect_load_failed_with_tls_errors(move |_, uri, certificate, errors| {
let Ok(url) = Url::parse(uri) else { return false };
hub.push(Event::CertError(id, CertError::new(url, certificate.clone(), errors)));
true
});
let hub = self.hub.clone();
let filters = self.filters.clone();
let images = self.images_filter.clone();
web.connect_decide_policy(move |web, decision, kind| match kind {
webkit::PolicyDecisionType::NavigationAction | webkit::PolicyDecisionType::NewWindowAction => {
let Some(nav) = decision.downcast_ref::<webkit::NavigationPolicyDecision>() else { return false };
let Some(mut action) = nav.navigation_action() else { return false };
// A link clicked with the middle button or Ctrl opens in a new tab (Ctrl+Shift: in front), as in
// other browsers; WebKit would load it here.
let mods = gtk::gdk::ModifierType::from_bits_truncate(action.modifiers());
if action.navigation_type() == webkit::NavigationType::LinkClicked && (action.mouse_button() == 2 || mods.contains(gtk::gdk::ModifierType::CONTROL_MASK))
&& let Some(url) = action.request().and_then(|r| r.uri()).and_then(|u| Url::parse(&u).ok())
{
decision.ignore();
hub.push(Event::OpenLink(id, url, mods.contains(gtk::gdk::ModifierType::SHIFT_MASK)));
return true;
}
if kind == webkit::PolicyDecisionType::NewWindowAction {
return false;
}
// Only the top frame: frames load as the page asks.
if action.frame_name().is_some() {
return false;
}
let Some(request) = action.request() else { return false };
let Some(uri) = request.uri() else { return false };
let Ok(url) = Url::parse(&uri) else { return false };
let get = request.http_method().is_none_or(|m| m.eq_ignore_ascii_case("GET"));
let reloadable = get && action.navigation_type() != webkit::NavigationType::BackForward;
let redirect = action.is_redirect();
let tab = Navigation { web: web.clone(), hub: hub.clone(), filters: filters.clone(), images: images.clone(), id, url, redirect, reloadable, decision: decision.clone() };
// WebKit's GTK API doesn't say which frame a navigation is for, and the browser's decisions (HTTPS-only,
// the strip, the user agent reload) load the new URL in the tab: only the tab's own loads go to it.
// The browser's own loads come without headers; a redirect is the tab's while its load is provisional
// (frames load after the page commits); anything else is a frame's when a frame element has that
// URL. Not caught: a link followed inside a frame.
let from_browser = request.http_headers().is_none_or(|h| {
let mut any = false;
h.foreach(|_, _| any = true);
!any
});
if from_browser {
tab.decide();
} else if redirect {
if !provisional.get() {
return false;
}
tab.decide();
} else {
let script = format!("(() => {{ const u = {}; const has = d => [...d.querySelectorAll('iframe, frame')].some(f => {{ if (f.src === u) return true; try {{ return !!f.contentDocument && has(f.contentDocument); }} catch (e) {{ return false; }} }}); return has(document); }})()", serde_json::to_string(uri.as_str()).unwrap_or_default());
View::new(id, web.clone()).evaluate_javascript(script, move |frame| match frame {
Ok(serde_json::Value::Bool(true)) => tab.decision.use_(),
_ => tab.decide(),
});
}
true
},
webkit::PolicyDecisionType::Response => {
let Some(response) = decision.downcast_ref::<webkit::ResponsePolicyDecision>() else { return false };
if !response.is_main_frame_main_resource() {
return false;
}
let reply = response.response();
let attachment = reply.as_ref().and_then(|r| r.http_headers()).and_then(|h| h.one("Content-Disposition")).is_some_and(|v| v.trim_start().to_ascii_lowercase().starts_with("attachment"));
if response.is_mime_type_supported() && !attachment {
return false;
}
// Nacre's own downloader takes it (http and https; the rest WebKit saves itself).
let Some(url) = response.request().and_then(|r| r.uri()).and_then(|u| Url::parse(&u).ok()) else { return false };
if !matches!(url.scheme(), "http" | "https") {
decision.download();
return true;
}
decision.ignore();
let name = reply.and_then(|r| r.suggested_filename()).map(|n| n.to_string()).filter(|n| !n.is_empty());
hub.push(Event::Download(id, url, name));
true
},
_ => false,
});
let engine = Rc::downgrade(self);
let hub = self.hub.clone();
web.connect_create(move |w, action| {
let engine = engine.upgrade()?;
let url = action.request().and_then(|r| r.uri()).and_then(|u| Url::parse(&u).ok());
let popup = engine.create_view(ViewId(crate::app::next_id()), Some(&View::new(id, w.clone())));
let widget = popup.widget();
hub.push(Event::CreateNew(id, popup, url));
Some(widget)
});
let hub = self.hub.clone();
web.connect_permission_request(move |_, request| {
let kind = if request.is::<webkit::GeolocationPermissionRequest>() {
Perm::Location
} else if request.is::<webkit::NotificationPermissionRequest>() {
Perm::Notifications
} else if let Some(media) = request.downcast_ref::<webkit::UserMediaPermissionRequest>() {
if media.is_for_video_device() { Perm::Camera } else { Perm::Microphone }
} else if request.is::<webkit::DeviceInfoPermissionRequest>() {
Perm::DeviceInfo
} else if request.is::<webkit::ClipboardPermissionRequest>() {
Perm::Clipboard
} else if request.is::<webkit::WebsiteDataAccessPermissionRequest>() {
Perm::Storage
} else if request.is::<webkit::PointerLockPermissionRequest>() {
request.allow();
return true;
} else {
// Encrypted media (EME, later plan) and XR are not available.
request.deny();
return true;
};
hub.push(Event::Permission(id, kind, PermissionAsk::new(request.clone())));
true
});
let hub = self.hub.clone();
web.connect_authenticate(move |_, request| {
hub.push(Event::Auth(id, AuthRequest::new(request.clone())));
true
});
let hub = self.hub.clone();
web.connect_script_dialog(move |_, dialog| match SimpleDialog::new(dialog.clone()) {
Some(control) => {
hub.push(Event::Control(id, control));
true
},
None => false,
});
let hub = self.hub.clone();
web.connect_show_option_menu(move |_, menu, rect| {
let rect = egui::Rect::from_min_size(egui::pos2(rect.x() as f32, rect.y() as f32), egui::vec2(rect.width() as f32, rect.height() as f32));
hub.push(Event::Control(id, Control::Select(SelectElement::new(menu.clone(), rect))));
true
});
let hub = self.hub.clone();
web.connect_run_color_chooser(move |_, request| {
hub.push(Event::Control(id, Control::Color(ColorPicker::new(request.clone()))));
true
});
let hub = self.hub.clone();
web.connect_run_file_chooser(move |_, request| {
hub.push(Event::Control(id, Control::File(FilePicker::new(request.clone()))));
true
});
let hub = self.hub.clone();
web.connect_show_notification(move |_, n| {
let title = n.title().map(|t| t.to_string()).unwrap_or_default();
let body = n.body().map(|t| t.to_string()).unwrap_or_default();
hub.push(Event::Notification(Some(id), Notification { title, body }));
true
});
let hub = self.hub.clone();
web.connect_context_menu(move |w, menu, hit| {
// The event is in window coordinates (the view's surface is the window's).
let Some(position) = menu.event().and_then(|e| e.position()).map(|(x, y)| egui::pos2(x as f32, y as f32)) else { return false };
let editable = hit.context_is_editable();
let selection = hit.context_is_selection();
let mut items = vec![
("Back".to_owned(), PageAction::GoBack, w.can_go_back()),
("Forward".to_owned(), PageAction::GoForward, w.can_go_forward()),
("Reload".to_owned(), PageAction::Reload, true),
];
if editable || selection {
items.push((String::new(), PageAction::Reload, false));
if editable {
items.push(("Cut".to_owned(), PageAction::Cut, selection));
}
items.push(("Copy".to_owned(), PageAction::Copy, selection));
if editable {
items.push(("Paste".to_owned(), PageAction::Paste, true));
}
items.push(("Select all".to_owned(), PageAction::SelectAll, true));
}
let request = PageMenuRequest {
position,
link: hit.link_uri().map(|u| u.to_string()),
image: hit.image_uri().map(|u| u.to_string()),
media: hit.media_uri().map(|u| u.to_string()),
editable,
selection,
items,
view: View::new(id, w.clone()),
};
hub.push(Event::Control(id, Control::ContextMenu(request)));
true
});
}
}
/// Folders the web process may read (read only), so local media in them plays: the XDG user folders that exist (never
/// the home folder itself), plus the smoke test pages in scripted runs (D-043).
fn media_dirs(selftest: bool) -> Vec<std::path::PathBuf> {
let home = dirs::home_dir();
let mut found: Vec<std::path::PathBuf> = [dirs::download_dir(), dirs::video_dir(), dirs::audio_dir(), dirs::picture_dir(), dirs::desktop_dir(), dirs::document_dir()]
.into_iter()
.flatten()
.filter(|d| d.is_dir() && Some(d) != home.as_ref() && d.parent().is_some())
.collect();
if selftest {
found.push(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/smoke/pages"));
}
found.dedup();
found
}
#[cfg(test)]
mod tests {
use super::media_dirs;
#[test]
fn media_dirs_never_home() {
let home = dirs::home_dir();
let dirs = media_dirs(true);
assert!(dirs.iter().all(|d| Some(d) != home.as_ref() && d.as_os_str() != "/"));
assert!(dirs.iter().any(|d| d.ends_with("tests/smoke/pages")));
assert!(!media_dirs(false).iter().any(|d| d.ends_with("tests/smoke/pages")));
}
}