Clearwake / app · clearwake.ai / crates / clearwake-app / src / net.rs
| 1 | //! Loading pages and pictures. Every address, including each redirect, is |
| 2 | //! checked against the filter before anything is requested. |
| 3 | //! |
| 4 | //! On computers and phones Clearwake talks to sites directly. In a web |
| 5 | //! browser it can't (sites don't allow other pages to read them), so the web |
| 6 | //! version asks clearwake.ai/fetch, which applies the same filter. |
| 7 | |
| 8 | use clearwake_core::{Filter, Url}; |
| 9 | use std::sync::{Arc, Mutex}; |
| 10 | |
| 11 | #[allow(dead_code)] |
| 12 | pub const MAX_PAGE: u64 = 12 * 1024 * 1024; |
| 13 | #[allow(dead_code)] |
| 14 | pub const MAX_IMAGE: u64 = 8 * 1024 * 1024; |
| 15 | #[allow(dead_code)] |
| 16 | pub const USER_AGENT: &str = "Mozilla/5.0 (compatible; Clearwake/0.1; +https://clearwake.ai)"; |
| 17 | |
| 18 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 19 | pub enum Kind { |
| 20 | Page, |
| 21 | Image, |
| 22 | } |
| 23 | |
| 24 | #[derive(Clone, Debug)] |
| 25 | pub struct Job { |
| 26 | pub generation: u64, |
| 27 | pub kind: Kind, |
| 28 | pub url: String, |
| 29 | } |
| 30 | |
| 31 | pub enum Body { |
| 32 | /// A page or text, with its final address after redirects. |
| 33 | Page { url: String, content_type: String, bytes: Vec<u8> }, |
| 34 | /// A decoded picture, RGBA. |
| 35 | Image { width: usize, height: usize, rgba: Vec<u8> }, |
| 36 | } |
| 37 | |
| 38 | pub struct Done { |
| 39 | pub job: Job, |
| 40 | pub result: Result<Body, String>, |
| 41 | } |
| 42 | |
| 43 | pub type Inbox = Arc<Mutex<Vec<Done>>>; |
| 44 | |
| 45 | /// Decode a picture and shrink it to at most `max` pixels wide. |
| 46 | pub fn decode_image(bytes: &[u8], max: u32) -> Result<Body, String> { |
| 47 | let img = image::load_from_memory(bytes).map_err(|_| String::from("This picture could not be read."))?; |
| 48 | let img = if img.width() > max { |
| 49 | let h = (img.height() as u64 * max as u64 / img.width() as u64).max(1) as u32; |
| 50 | img.resize_exact(max, h, image::imageops::FilterType::Triangle) |
| 51 | } else { |
| 52 | img |
| 53 | }; |
| 54 | let mut rgba = img.to_rgba8(); |
| 55 | lay_on_paper(&mut rgba); |
| 56 | Ok(Body::Image { width: rgba.width() as usize, height: rgba.height() as usize, rgba: rgba.into_raw() }) |
| 57 | } |
| 58 | |
| 59 | /// Web pictures with see-through parts (logos, diagrams) are drawn for a white page. On |
| 60 | /// Clearwake's dark page their dark lines would vanish, so pictures bigger than an icon get |
| 61 | /// a white backing, the way every page author expects them to be seen. |
| 62 | fn lay_on_paper(rgba: &mut image::RgbaImage) { |
| 63 | if rgba.width() <= 32 || rgba.height() <= 32 || rgba.pixels().all(|p| p[3] == 255) { |
| 64 | return; |
| 65 | } |
| 66 | for p in rgba.pixels_mut() { |
| 67 | let a = p[3] as u32; |
| 68 | for c in 0..3 { |
| 69 | p[c] = ((p[c] as u32 * a + 255 * (255 - a)) / 255) as u8; |
| 70 | } |
| 71 | p[3] = 255; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | fn blocked_message() -> String { |
| 76 | String::from("Clearwake blocked this address because it serves ads or tracking.") |
| 77 | } |
| 78 | |
| 79 | #[cfg(not(target_arch = "wasm32"))] |
| 80 | mod native { |
| 81 | use super::*; |
| 82 | use std::collections::VecDeque; |
| 83 | use std::io::Read; |
| 84 | use std::sync::Condvar; |
| 85 | |
| 86 | pub struct Loader { |
| 87 | queue: Arc<(Mutex<VecDeque<Job>>, Condvar)>, |
| 88 | } |
| 89 | |
| 90 | impl Loader { |
| 91 | pub fn new(inbox: Inbox, ctx: egui::Context, filter: Arc<Filter>) -> Loader { |
| 92 | let queue: Arc<(Mutex<VecDeque<Job>>, Condvar)> = Arc::new((Mutex::new(VecDeque::new()), Condvar::new())); |
| 93 | #[allow(unused_mut)] |
| 94 | let mut config = ureq::Agent::config_builder(); |
| 95 | #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))] |
| 96 | { |
| 97 | // Trust the same certificates the computer itself trusts. |
| 98 | config = config.tls_config(ureq::tls::TlsConfig::builder().root_certs(ureq::tls::RootCerts::PlatformVerifier).build()); |
| 99 | } |
| 100 | let agent: ureq::Agent = config |
| 101 | .max_redirects(0) |
| 102 | .http_status_as_error(false) |
| 103 | .timeout_global(Some(std::time::Duration::from_secs(30))) |
| 104 | .user_agent(USER_AGENT) |
| 105 | .build() |
| 106 | .into(); |
| 107 | for _ in 0..6 { |
| 108 | let queue = queue.clone(); |
| 109 | let inbox = inbox.clone(); |
| 110 | let ctx = ctx.clone(); |
| 111 | let filter = filter.clone(); |
| 112 | let agent = agent.clone(); |
| 113 | std::thread::spawn(move || loop { |
| 114 | let job = { |
| 115 | let (lock, cv) = &*queue; |
| 116 | let mut q = lock.lock().unwrap(); |
| 117 | loop { |
| 118 | if let Some(j) = q.pop_front() { |
| 119 | break j; |
| 120 | } |
| 121 | q = cv.wait(q).unwrap(); |
| 122 | } |
| 123 | }; |
| 124 | let result = fetch(&agent, &filter, &job); |
| 125 | inbox.lock().unwrap().push(Done { job, result }); |
| 126 | ctx.request_repaint(); |
| 127 | }); |
| 128 | } |
| 129 | Loader { queue } |
| 130 | } |
| 131 | |
| 132 | pub fn load(&self, job: Job) { |
| 133 | let (lock, cv) = &*self.queue; |
| 134 | let mut q = lock.lock().unwrap(); |
| 135 | if job.kind == Kind::Page { |
| 136 | // A new page makes every queued job for older pages pointless. |
| 137 | q.retain(|j| j.generation >= job.generation); |
| 138 | q.push_front(job); |
| 139 | } else { |
| 140 | q.push_back(job); |
| 141 | } |
| 142 | cv.notify_one(); |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | fn fetch(agent: &ureq::Agent, filter: &Filter, job: &Job) -> Result<Body, String> { |
| 147 | let mut url = Url::parse(&job.url).ok_or_else(|| String::from("That address doesn't look right."))?; |
| 148 | for _ in 0..10 { |
| 149 | if filter.blocks(&url) { |
| 150 | return Err(blocked_message()); |
| 151 | } |
| 152 | let accept = match job.kind { |
| 153 | Kind::Page => "text/html,application/xhtml+xml,text/plain;q=0.9,image/*;q=0.8", |
| 154 | Kind::Image => "image/png,image/jpeg,image/gif,image/webp,image/*;q=0.8", |
| 155 | }; |
| 156 | let mut resp = agent |
| 157 | .get(url.to_string()) |
| 158 | .header("Accept", accept) |
| 159 | .header("Accept-Language", "en-US,en;q=0.8") |
| 160 | .call() |
| 161 | .map_err(|e| friendly(&e.to_string()))?; |
| 162 | let status = resp.status().as_u16(); |
| 163 | if (300..400).contains(&status) { |
| 164 | let loc = resp.headers().get("location").and_then(|v| v.to_str().ok()).unwrap_or(""); |
| 165 | url = url.join(loc).ok_or_else(|| String::from("The site sent Clearwake somewhere it won't go."))?; |
| 166 | continue; |
| 167 | } |
| 168 | if status >= 400 { |
| 169 | return Err(format!("The site answered with an error ({status}).")); |
| 170 | } |
| 171 | let content_type = resp.headers().get("content-type").and_then(|v| v.to_str().ok()).unwrap_or("").to_string(); |
| 172 | let limit = if job.kind == Kind::Page { MAX_PAGE } else { MAX_IMAGE }; |
| 173 | let mut bytes = Vec::new(); |
| 174 | resp.body_mut() |
| 175 | .as_reader() |
| 176 | .take(limit) |
| 177 | .read_to_end(&mut bytes) |
| 178 | .map_err(|e| friendly(&e.to_string()))?; |
| 179 | return match job.kind { |
| 180 | Kind::Image => decode_image(&bytes, 1600), |
| 181 | Kind::Page => Ok(Body::Page { url: url.to_string(), content_type, bytes }), |
| 182 | }; |
| 183 | } |
| 184 | Err(String::from("The site redirected too many times.")) |
| 185 | } |
| 186 | |
| 187 | fn friendly(e: &str) -> String { |
| 188 | let l = e.to_ascii_lowercase(); |
| 189 | if l.contains("dns") || l.contains("resolve") || l.contains("lookup") { |
| 190 | String::from("Clearwake couldn't find that site. Check the address and your connection.") |
| 191 | } else if l.contains("timed out") || l.contains("timeout") { |
| 192 | String::from("The site took too long to answer.") |
| 193 | } else if l.contains("certificate") || l.contains("tls") { |
| 194 | String::from("This site's security certificate isn't valid, so Clearwake won't open it.") |
| 195 | } else { |
| 196 | format!("The page couldn't be loaded. ({e})") |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | #[cfg(not(target_arch = "wasm32"))] |
| 202 | pub use native::Loader; |
| 203 | |
| 204 | #[cfg(target_arch = "wasm32")] |
| 205 | mod web { |
| 206 | use super::*; |
| 207 | |
| 208 | pub struct Loader { |
| 209 | inbox: Inbox, |
| 210 | ctx: egui::Context, |
| 211 | filter: Arc<Filter>, |
| 212 | } |
| 213 | |
| 214 | impl Loader { |
| 215 | pub fn new(inbox: Inbox, ctx: egui::Context, filter: Arc<Filter>) -> Loader { |
| 216 | Loader { inbox, ctx, filter } |
| 217 | } |
| 218 | |
| 219 | pub fn load(&self, job: Job) { |
| 220 | let inbox = self.inbox.clone(); |
| 221 | let ctx = self.ctx.clone(); |
| 222 | if let Some(u) = Url::parse(&job.url) { |
| 223 | if self.filter.blocks(&u) { |
| 224 | inbox.lock().unwrap().push(Done { job, result: Err(blocked_message()) }); |
| 225 | ctx.request_repaint(); |
| 226 | return; |
| 227 | } |
| 228 | } |
| 229 | let proxied = format!("/fetch?url={}", clearwake_core::url::encode_component(&job.url)); |
| 230 | let req = ehttp::Request::get(proxied); |
| 231 | ehttp::fetch(req, move |res| { |
| 232 | let result = match res { |
| 233 | Err(e) => Err(format!("The page couldn't be loaded. ({e})")), |
| 234 | Ok(r) if !r.ok => { |
| 235 | let msg = String::from_utf8_lossy(&r.bytes).to_string(); |
| 236 | Err(if msg.trim().is_empty() || msg.len() > 300 { format!("The site answered with an error ({}).", r.status) } else { msg }) |
| 237 | } |
| 238 | Ok(r) => match job.kind { |
| 239 | Kind::Image => decode_image(&r.bytes, 1200), |
| 240 | Kind::Page => Ok(Body::Page { |
| 241 | url: r.headers.get("x-clearwake-url").map(|s| s.to_string()).unwrap_or_else(|| job.url.clone()), |
| 242 | content_type: r.headers.get("content-type").unwrap_or("").to_string(), |
| 243 | bytes: r.bytes, |
| 244 | }), |
| 245 | }, |
| 246 | }; |
| 247 | inbox.lock().unwrap().push(Done { job, result }); |
| 248 | ctx.request_repaint(); |
| 249 | }); |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | #[cfg(target_arch = "wasm32")] |
| 255 | pub use web::Loader; |