//! The filter behind clearwake.ai/fetch, the page loader for Clearwake on //! the web (a web page can't read other sites directly). //! //! Built as a WebAssembly module with no imports. The loader writes an //! address into memory from `cw_alloc` and asks `cw_check` before every //! request and every redirect: //! 0 = may load, 1 = ad or tracker (blocked), 2 = not a web address, //! 3 = a private or local address. #![no_std] extern crate alloc; use alloc::vec::Vec; use clearwake_core::{Filter, Url}; use core::cell::UnsafeCell; struct Bump; /// A small allocator: WebAssembly memory only grows, and each request /// runs in a fresh instance, so freeing is a no-op. unsafe impl core::alloc::GlobalAlloc for Bump { unsafe fn alloc(&self, layout: core::alloc::Layout) -> *mut u8 { static mut NEXT: usize = 0; static mut END: usize = 0; unsafe { let align = layout.align(); let mut start = (NEXT + align - 1) & !(align - 1); if start == 0 || start + layout.size() > END { let pages = layout.size() / 65536 + 1; let old = core::arch::wasm32::memory_grow(0, pages); if old == usize::MAX { return core::ptr::null_mut(); } if start == 0 || old * 65536 != END { start = (old * 65536 + align - 1) & !(align - 1); } END = (old + pages) * 65536; } NEXT = start + layout.size(); start as *mut u8 } } unsafe fn dealloc(&self, _: *mut u8, _: core::alloc::Layout) {} } #[global_allocator] static ALLOC: Bump = Bump; #[panic_handler] fn panic(_: &core::panic::PanicInfo) -> ! { core::arch::wasm32::unreachable() } struct Once(UnsafeCell>); unsafe impl Sync for Once {} static FILTER: Once = Once(UnsafeCell::new(None)); fn filter() -> &'static Filter { // Single-threaded WebAssembly. unsafe { (*FILTER.0.get()).get_or_insert_with(Filter::new) } } #[unsafe(no_mangle)] pub extern "C" fn cw_alloc(len: usize) -> *mut u8 { let mut v: Vec = Vec::with_capacity(len.max(1)); let p = v.as_mut_ptr(); core::mem::forget(v); p } fn private_host(h: &str) -> bool { h == "localhost" || h.ends_with(".localhost") || h.ends_with(".local") || h.ends_with(".internal") || h.starts_with('[') || h.starts_with("127.") || h.starts_with("10.") || h.starts_with("192.168.") || h.starts_with("169.254.") || h.starts_with("0.") || h.starts_with("100.64.") || (h.starts_with("172.") && h.split('.').nth(1).and_then(|s| s.parse::().ok()).is_some_and(|n| (16..=31).contains(&n))) } #[unsafe(no_mangle)] pub extern "C" fn cw_check(ptr: *const u8, len: usize) -> i32 { let bytes = unsafe { core::slice::from_raw_parts(ptr, len) }; let Ok(s) = core::str::from_utf8(bytes) else { return 2 }; let Some(u) = Url::parse(s) else { return 2 }; if u.is_about() { return 2; } if private_host(&u.host) { return 3; } if filter().blocks(&u) { return 1; } 0 }