Cotton code
306 lines · 12.2 KB · RustRaw
//! The Wi-Fi door for one film playing on a TV (cinemas-airplay, 18 Nov//! 2026). A sealed film is opened on the phone and served at 127.0.0.1//! (`super::loopback`); an AirPlay receiver asks for the address it is handed//! itself, and cannot reach the phone's loopback. While the player's route is//! a TV, the film the phone's door offers is offered again here: on the//! phone's Wi-Fi address only, at a port of its own, under a path no one can//! guess (128 bits, new for each door), and nothing else at all.//!//! - Only this door's path answers; any other is 404, and every file it//!   answers is the one film's (its folder's files, by the same rules as the//!   phone's door).//! - It binds the Wi-Fi interface's address ([`wifi_address`]: `en0`, the//!   interface iOS gives Wi-Fi, IPv4), never every interface and never the//!   cellular one (`pdp_ip*`). With no Wi-Fi address there is no door, and//!   the film plays through the phone.//! - It lives while the film plays on the TV: [`LanDoor::close`] (and its//!   drop) stops every answer and lets the port go, and the player drops it//!   when the play ends or the route comes back to the phone.//! - [`LanDoor::fetched`] says whether the film's index has been asked for by//!   another device than the phone itself; [`LanDoor::asked`] names every//!   path another device asked, and [`LanDoor::media_taken_at`] when it last//!   took bytes of the film itself (a segment, or the whole file), not a//!   playlist (airplay-refused, 18 Nov 2026: a receiver that fetched the//!   index and then refused the film never asks for one). The player's//!   checks that the receiver reached the film and plays on.//!//! The opened bytes still go only to a device on the same Wi-Fi that holds//! the path: no key and no byte is sent to a server.use std::collections::BTreeMap;use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};use std::thread::JoinHandle;use std::time::{Duration, Instant};use super::loopback::{answer, Offer, Offered, PlainSource};/// The interface iOS gives Wi-Fi (`pdp_ip0` is cellular, `en2` a cable).pub const WIFI_INTERFACE: &str = "en0";/// How long closing waits for the listener to see it.const KNOCK: Duration = Duration::from_millis(400);/// A door on the Wi-Fi address for one film.pub struct LanDoor {    url: String,    addr: SocketAddr,    offers: Arc<Mutex<BTreeMap<String, Offer>>>,    closed: Arc<AtomicBool>,    heard: Arc<Heard>,    listening: Mutex<Option<JoinHandle<()>>>,}impl std::fmt::Debug for LanDoor {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("LanDoor").field("addr", &self.addr).finish_non_exhaustive()    }}impl LanDoor {    /// Offer `offered`, whose player starts at `index`, on `ip` alone    /// ([`super::loopback::Loopback::lend`] refuses any but a Wi-Fi address).    pub(super) fn open(ip: IpAddr, offered: Offered, index: &str) -> Result<LanDoor, String> {        let index = index.split(['?', '#']).next().unwrap_or_default().to_string();        if super::loopback::folder_path(&index).is_none() {            return Err("that address names no file".into());        }        let listener = TcpListener::bind((ip, 0)).map_err(|error| format!("the Wi-Fi door would not open ({error})"))?;        let addr = listener.local_addr().map_err(|error| error.to_string())?;        let mut token = [0u8; 16];        rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut token);        let token = hex::encode(token);        let offers: Arc<Mutex<BTreeMap<String, Offer>>> = Arc::default();        offers.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(token.clone(), Offer { offered, at: Instant::now() });        let closed = Arc::new(AtomicBool::new(false));        let heard: Arc<Heard> = Arc::default();        let (live, gone, ear, first) = (Arc::clone(&offers), Arc::clone(&closed), Arc::clone(&heard), index.clone());        let listening = std::thread::Builder::new()            .name("cotton-lan".into())            .spawn(move || {                for stream in listener.incoming() {                    if gone.load(Ordering::SeqCst) {                        break;                    }                    let Ok(stream) = stream else { continue };                    // The phone asking its own door is not the receiver.                    let foreign = stream.peer_addr().map(|peer| peer.ip() != ip).unwrap_or(false);                    let one = watched(&live, foreign, &ear, &first);                    let _ = std::thread::Builder::new().name("cotton-lan-answer".into()).spawn(move || answer(stream, &one));                }            })            .map_err(|error| error.to_string())?;        Ok(LanDoor {            url: format!("http://{addr}/{token}/{index}"),            addr,            offers,            closed,            heard,            listening: Mutex::new(Some(listening)),        })    }    /// The film's address on the Wi-Fi: what the receiver is handed.    pub fn url(&self) -> &str {        &self.url    }    /// Where the door listens.    pub fn addr(&self) -> SocketAddr {        self.addr    }    /// Whether a device other than this phone has asked for the film's index.    pub fn fetched(&self) -> bool {        self.heard.index.load(Ordering::SeqCst)    }    /// Every path within the film another device asked for, in the order    /// first asked (the index's name for a film that is one file).    pub fn asked(&self) -> Vec<String> {        self.heard.paths.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()    }    /// When another device last took bytes of the film itself (a segment or    /// the one file, never a playlist); None while it never has.    pub fn media_taken_at(&self) -> Option<Instant> {        *self.heard.media_at.lock().unwrap_or_else(std::sync::PoisonError::into_inner)    }    /// Shut the door: nothing is answered after, and the port is let go.    pub fn close(&self) {        self.offers.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clear();        if self.closed.swap(true, Ordering::SeqCst) {            return;        }        // The listener waits in accept: one knock lets it see it is closed.        let _ = TcpStream::connect_timeout(&self.addr, KNOCK);        if let Some(listening) = self.listening.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() {            let _ = listening.join();        }    }}impl Drop for LanDoor {    fn drop(&mut self) {        self.close();    }}/// What the door heard from devices other than the phone.#[derive(Debug, Default)]pub(super) struct Heard {    /// The film's index was asked for.    pub(super) index: AtomicBool,    /// Every path asked, in the order first asked.    pub(super) paths: Mutex<Vec<String>>,    /// When bytes of the film itself were last read out for one.    pub(super) media_at: Mutex<Option<Instant>>,}impl Heard {    fn asked(&self, path: &str, index: bool) {        if index {            self.index.store(true, Ordering::SeqCst);        }        let mut paths = self.paths.lock().unwrap_or_else(std::sync::PoisonError::into_inner);        if !paths.iter().any(|known| known == path) {            paths.push(path.to_string());        }    }    fn took(&self) {        *self.media_at.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Instant::now());    }}/// A file of the film itself read out to another device: each read is the/// receiver taking it (a long range streams on one request, so the request/// alone would go quiet while the receiver still plays).struct Taken {    inner: Box<dyn PlainSource>,    heard: Arc<Heard>,}impl std::io::Read for Taken {    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {        let read = self.inner.read(buf)?;        if read > 0 {            self.heard.took();        }        Ok(read)    }}impl std::io::Seek for Taken {    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {        self.inner.seek(pos)    }}impl PlainSource for Taken {    fn plain_len(&self) -> u64 {        self.inner.plain_len()    }}/// Whether `path` within a film is a playlist rather than the film itself.pub fn playlist(path: &str) -> bool {    path.split(['?', '#']).next().unwrap_or_default().to_ascii_lowercase().ends_with(".m3u8")}/// The door's one offer as one connection sees it: nothing once the door is/// shut; what another device asks is heard (its index marks the door/// fetched, the film's own bytes read out mark it taken).fn watched(live: &Mutex<BTreeMap<String, Offer>>, foreign: bool, heard: &Arc<Heard>, index: &str) -> Mutex<BTreeMap<String, Offer>> {    let live = live.lock().unwrap_or_else(std::sync::PoisonError::into_inner);    let mut one = BTreeMap::new();    for (token, offer) in live.iter() {        let heard = Arc::clone(heard);        let offered = match &offer.offered {            Offered::Folder(opener) => {                let (opener, index) = (Arc::clone(opener), index.to_string());                Offered::Folder(Arc::new(move |inner: &str| {                    let opened = opener(inner)?;                    if !foreign {                        return Ok(opened);                    }                    heard.asked(inner, inner == index);                    if playlist(inner) {                        return Ok(opened);                    }                    let (content_type, source) = opened;                    Ok((content_type, Box::new(Taken { inner: source, heard: Arc::clone(&heard) }) as Box<dyn PlainSource>))                }))            }            Offered::File { content_type, opener } => {                let (opener, index) = (Arc::clone(opener), index.to_string());                Offered::File {                    content_type: content_type.clone(),                    opener: Arc::new(move || {                        let source = opener()?;                        if !foreign {                            return Ok(source);                        }                        heard.asked(&index, true);                        Ok(Box::new(Taken { inner: source, heard: Arc::clone(&heard) }) as Box<dyn PlainSource>)                    }),                }            }        };        one.insert(token.clone(), Offer { offered, at: offer.at });    }    Mutex::new(one)}/// The Wi-Fi address among `interfaces` (name, address): `en0`'s IPv4 that/// is a real network's, none for loopback, unset or self-assigned (no/// network to reach a TV on). Never another interface: cellular is `pdp_ip*`.pub fn wifi_of(interfaces: &[(String, IpAddr)]) -> Option<IpAddr> {    interfaces        .iter()        .find(|(name, ip)| name == WIFI_INTERFACE && matches!(ip, IpAddr::V4(v4) if !v4.is_loopback() && !v4.is_unspecified() && !v4.is_link_local() && !v4.is_broadcast()))        .map(|(_, ip)| *ip)}/// This phone's Wi-Fi address now, if it has one.pub fn wifi_address() -> Option<IpAddr> {    wifi_of(&interfaces())}/// Every interface's IPv4 address, by name.#[cfg(unix)]pub fn interfaces() -> Vec<(String, IpAddr)> {    let mut out = Vec::new();    let mut head: *mut libc::ifaddrs = std::ptr::null_mut();    // SAFETY: getifaddrs fills `head` with a list we only read, walking    // `ifa_next` until null, and hand back to freeifaddrs once; each address    // is read as sockaddr_in only when its family says AF_INET.    unsafe {        if libc::getifaddrs(&mut head) != 0 {            return out;        }        let mut at = head;        while !at.is_null() {            let ifa = &*at;            if !ifa.ifa_addr.is_null() && !ifa.ifa_name.is_null() && i32::from((*ifa.ifa_addr).sa_family) == libc::AF_INET {                let name = std::ffi::CStr::from_ptr(ifa.ifa_name).to_string_lossy().into_owned();                let sin = &*(ifa.ifa_addr as *const libc::sockaddr_in);                out.push((name, IpAddr::V4(Ipv4Addr::from(u32::from_be(sin.sin_addr.s_addr)))));            }            at = ifa.ifa_next;        }        libc::freeifaddrs(head);    }    out}#[cfg(not(unix))]pub fn interfaces() -> Vec<(String, IpAddr)> {    Vec::new()}#[cfg(test)]#[path = "lan_tests.rs"]mod tests;