Branchwell

Clearwake / app · clearwake.ai / crates / clearwake-fetch / src / lib.rs

Raw 3.1 KB on 85fd7484362aeeaf8dbc19b2d6ddb6a3999a141b
1//! The filter behind clearwake.ai/fetch, the page loader for Clearwake on
2//! the web (a web page can't read other sites directly).
3//!
4//! Built as a WebAssembly module with no imports. The loader writes an
5//! address into memory from `cw_alloc` and asks `cw_check` before every
6//! request and every redirect:
7//! 0 = may load, 1 = ad or tracker (blocked), 2 = not a web address,
8//! 3 = a private or local address.
9
10#![no_std]
11
12extern crate alloc;
13
14use alloc::vec::Vec;
15use clearwake_core::{Filter, Url};
16use core::cell::UnsafeCell;
17
18struct Bump;
19
20/// A small allocator: WebAssembly memory only grows, and each request
21/// runs in a fresh instance, so freeing is a no-op.
22unsafe impl core::alloc::GlobalAlloc for Bump {
23 unsafe fn alloc(&self, layout: core::alloc::Layout) -> *mut u8 {
24 static mut NEXT: usize = 0;
25 static mut END: usize = 0;
26 unsafe {
27 let align = layout.align();
28 let mut start = (NEXT + align - 1) & !(align - 1);
29 if start == 0 || start + layout.size() > END {
30 let pages = layout.size() / 65536 + 1;
31 let old = core::arch::wasm32::memory_grow(0, pages);
32 if old == usize::MAX {
33 return core::ptr::null_mut();
34 }
35 if start == 0 || old * 65536 != END {
36 start = (old * 65536 + align - 1) & !(align - 1);
37 }
38 END = (old + pages) * 65536;
39 }
40 NEXT = start + layout.size();
41 start as *mut u8
42 }
43 }
44 unsafe fn dealloc(&self, _: *mut u8, _: core::alloc::Layout) {}
45}
46
47#[global_allocator]
48static ALLOC: Bump = Bump;
49
50#[panic_handler]
51fn panic(_: &core::panic::PanicInfo) -> ! {
52 core::arch::wasm32::unreachable()
53}
54
55struct Once(UnsafeCell<Option<Filter>>);
56unsafe impl Sync for Once {}
57static FILTER: Once = Once(UnsafeCell::new(None));
58
59fn filter() -> &'static Filter {
60 // Single-threaded WebAssembly.
61 unsafe { (*FILTER.0.get()).get_or_insert_with(Filter::new) }
62}
63
64#[unsafe(no_mangle)]
65pub extern "C" fn cw_alloc(len: usize) -> *mut u8 {
66 let mut v: Vec<u8> = Vec::with_capacity(len.max(1));
67 let p = v.as_mut_ptr();
68 core::mem::forget(v);
69 p
70}
71
72fn private_host(h: &str) -> bool {
73 h == "localhost"
74 || h.ends_with(".localhost")
75 || h.ends_with(".local")
76 || h.ends_with(".internal")
77 || h.starts_with('[')
78 || h.starts_with("127.")
79 || h.starts_with("10.")
80 || h.starts_with("192.168.")
81 || h.starts_with("169.254.")
82 || h.starts_with("0.")
83 || h.starts_with("100.64.")
84 || (h.starts_with("172.") && h.split('.').nth(1).and_then(|s| s.parse::<u8>().ok()).is_some_and(|n| (16..=31).contains(&n)))
85}
86
87#[unsafe(no_mangle)]
88pub extern "C" fn cw_check(ptr: *const u8, len: usize) -> i32 {
89 let bytes = unsafe { core::slice::from_raw_parts(ptr, len) };
90 let Ok(s) = core::str::from_utf8(bytes) else { return 2 };
91 let Some(u) = Url::parse(s) else { return 2 };
92 if u.is_about() {
93 return 2;
94 }
95 if private_host(&u.host) {
96 return 3;
97 }
98 if filter().blocks(&u) {
99 return 1;
100 }
101 0
102}