//! The relay's only outgoing request: a wake to a mailbox owner's push endpoint when a blob arrived //! (`docs/PROTOCOL.md` §6, `.agents/features/wake-up.md` §2.2). //! //! The body is a constant; nothing of the mailbox, the blob or its sender goes out. A mailbox is //! woken at most once a minute, remembered in memory only. The endpoint's host is resolved here and //! every address that is not global is dropped before connecting, so a mailbox owner cannot point //! the relay at its own network. Nothing about a wake is printed. use crate::store::Store; use std::collections::HashMap; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::sync::{Arc, Mutex}; use std::time::Duration; use tabellarius_protocol::{MailboxId, PushEndpoint, WAKE_BODY, WAKE_EVERY_SECS}; use tokio::sync::Semaphore; use ureq::config::Config; use ureq::http::Uri; use ureq::unversioned::resolver::{DefaultResolver, ResolvedSocketAddrs, Resolver}; use ureq::unversioned::transport::{DefaultConnector, NextTimeout}; /// At most this many wakes are on their way at once; beyond that a wake is dropped. pub const MAX_IN_FLIGHT: usize = 16; /// A wake gives up after this long. pub const WAKE_TIMEOUT: Duration = Duration::from_secs(10); /// The in-memory "woken lately" map is pruned when it reaches this size. const MAX_REMEMBERED: usize = 100_000; pub struct Waker { allow_loopback: bool, /// Mailbox → the second it was last woken. Memory only: `PROTOCOL.md` §5 does not change. woken: Mutex>, slots: Arc, agent: ureq::Agent, } /// What a wake came to; the tests read it, the relay only acts on `Gone`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Outcome { Delivered, /// 404 or 410: the endpoint no longer exists, so it is removed. Gone, /// Anything else: the network, a refused address, a timeout, another status. Failed, } impl Waker { /// `allow_loopback`: `http://` to a loopback host, and loopback addresses, for tests only /// (`--push-loopback`). A relay facing the internet never sets it. pub fn new(allow_loopback: bool) -> Self { let config = Config::builder() .timeout_global(Some(WAKE_TIMEOUT)) .max_redirects(0) .http_status_as_error(false) .proxy(None) .build(); let agent = ureq::Agent::with_parts( config, DefaultConnector::default(), GlobalOnly { allow_loopback }, ); Self { allow_loopback, woken: Mutex::new(HashMap::new()), slots: Arc::new(Semaphore::new(MAX_IN_FLIGHT)), agent, } } /// Whether this relay accepts the endpoint at all. pub fn accepts(&self, endpoint: &PushEndpoint) -> bool { !endpoint.is_loopback_http() || self.allow_loopback } /// After a blob was stored: wakes the mailbox's owner, unless it was woken in the last minute or /// too many wakes are on their way. Returns at once; the request runs in the background. pub fn wake(&self, store: Arc, id: MailboxId, endpoint: String, now: i64) -> bool { if !self.due(id, now) { return false; } let Ok(slot) = Arc::clone(&self.slots).try_acquire_owned() else { return false; }; let agent = self.agent.clone(); tokio::task::spawn_blocking(move || { let _slot = slot; if send(&agent, &endpoint) == Outcome::Gone { let _ = store.drop_push_if(&id, &endpoint); } }); true } /// Once a minute per mailbox. A clock that went back counts as due. fn due(&self, id: MailboxId, now: i64) -> bool { let mut woken = self.woken.lock().unwrap_or_else(|e| e.into_inner()); if let Some(&last) = woken.get(&id) { if (0..WAKE_EVERY_SECS).contains(&(now - last)) { return false; } } if woken.len() >= MAX_REMEMBERED { woken.retain(|_, last| now - *last < WAKE_EVERY_SECS); } woken.insert(id, now); true } } /// One wake: the constant body and nothing else of the relay's. pub fn send(agent: &ureq::Agent, endpoint: &str) -> Outcome { let sent = agent .post(endpoint) .header("TTL", "86400") .header("Urgency", "normal") .header("Content-Type", "application/octet-stream") .send(WAKE_BODY); match sent.map(|r| r.status().as_u16()) { Ok(200..=299) => Outcome::Delivered, Ok(404 | 410) => Outcome::Gone, _ => Outcome::Failed, } } /// The system's resolver, with every address that is not global dropped. #[derive(Debug)] struct GlobalOnly { allow_loopback: bool, } impl Resolver for GlobalOnly { fn resolve( &self, uri: &Uri, config: &Config, timeout: NextTimeout, ) -> Result { let all = DefaultResolver::default().resolve(uri, config, timeout)?; let mut kept = self.empty(); for addr in &all { if reachable(addr.ip(), self.allow_loopback) { kept.push(*addr); } } if kept.is_empty() { Err(ureq::Error::HostNotFound) } else { Ok(kept) } } } /// Whether the relay may connect to this address: global unicast only (loopback when allowed). pub fn reachable(ip: IpAddr, allow_loopback: bool) -> bool { match ip { IpAddr::V4(v4) => v4_reachable(v4, allow_loopback), IpAddr::V6(v6) => { // An IPv4 address in IPv6 clothing is judged as the IPv4 address. if let Some(v4) = v6.to_ipv4_mapped() { return v4_reachable(v4, allow_loopback); } let s = v6.segments(); // NAT64 (64:ff9b::/96) reaches the IPv4 address in its last 32 bits. if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] { let v4 = Ipv4Addr::new((s[6] >> 8) as u8, s[6] as u8, (s[7] >> 8) as u8, s[7] as u8); return v4_reachable(v4, allow_loopback); } v6_reachable(v6, allow_loopback) } } } fn v4_reachable(ip: Ipv4Addr, allow_loopback: bool) -> bool { if ip.is_loopback() { return allow_loopback; } let o = ip.octets(); !(o[0] == 0 // "this network" || ip.is_private() // 10/8, 172.16/12, 192.168/16 || ip.is_link_local() // 169.254/16 || (o[0] == 100 && (o[1] & 0xc0) == 64) // CGNAT 100.64/10 || (o[0] == 192 && o[1] == 0 && o[2] == 0) // IETF 192.0.0/24 || ip.is_documentation() || (o[0] == 198 && (o[1] & 0xfe) == 18) // benchmarking 198.18/15 || ip.is_multicast() || o[0] >= 240) // reserved and broadcast } fn v6_reachable(ip: Ipv6Addr, allow_loopback: bool) -> bool { if ip.is_loopback() { return allow_loopback; } let s = ip.segments(); !(ip.is_unspecified() || ip.is_multicast() || s[..6] == [0; 6] // IPv4-compatible ::/96 || (s[0] & 0xfe00) == 0xfc00 // unique local fc00::/7 || (s[0] & 0xffc0) == 0xfe80 // link-local fe80::/10 || (s[0] & 0xffc0) == 0xfec0 // site-local fec0::/10 || (s[0] == 0x2001 && s[1] == 0x0db8) // documentation || s[0] == 0x2002 // 6to4: an IPv4 address inside || (s[0] == 0x2001 && s[1] == 0) // Teredo || (s[0] == 0x0100 && s[1..4] == [0; 3])) // discard-only 100::/64 } #[cfg(test)] mod tests { use super::*; fn ok(text: &str) -> bool { reachable(text.parse().expect("an address"), false) } #[test] fn only_global_addresses_are_reachable() { for global in ["1.1.1.1", "159.69.10.20", "2a01:4f8::1", "64:ff9b::808:808"] { assert!(ok(global), "{global}"); } for not in [ "127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.1.1", "169.254.169.254", "100.64.0.1", "0.0.0.0", "192.0.0.8", "192.0.2.1", "198.18.0.1", "224.0.0.1", "255.255.255.255", "::1", "::", "fc00::1", "fd12::1", "fe80::1", "ff02::1", "2001:db8::1", "::ffff:10.0.0.1", "::ffff:127.0.0.1", "::10.0.0.1", "64:ff9b::a00:1", "2002:a00:1::", "2001:0:4136:e378::1", "100::1", ] { assert!(!ok(not), "{not}"); } } #[test] fn loopback_only_when_allowed() { assert!(reachable("127.0.0.1".parse().expect("v4"), true)); assert!(reachable("::1".parse().expect("v6"), true)); assert!(!reachable("10.0.0.1".parse().expect("v4"), true)); } }