Cotton code
196 lines · 11.2 KB · RustRaw
use std::io::{Read, Write};use std::net::{IpAddr, Ipv4Addr};use std::sync::Arc;use super::*;use crate::media::loopback::{hls_type, Loopback, PlainSource};/// One folder's files in the clear: the door's rules, not the seal, are under test here.fn folder(files: &[(&'static str, &'static [u8])]) -> crate::media::loopback::FolderOpener {    let files: BTreeMap<&'static str, Vec<u8>> = files.iter().map(|(name, bytes)| (*name, bytes.to_vec())).collect();    Arc::new(move |inner: &str| {        let bytes = files.get(inner).ok_or("no such file")?.clone();        Ok((hls_type(inner).to_string(), Box::new(std::io::Cursor::new(bytes)) as Box<dyn PlainSource>))    })}fn get(url: &str) -> Result<(String, Vec<u8>), std::io::Error> {    let rest = url.strip_prefix("http://").unwrap();    let (host, path) = rest.split_once('/').unwrap();    let mut stream = std::net::TcpStream::connect(host)?;    write!(stream, "GET /{path} HTTP/1.1\r\nHost: {host}\r\n\r\n")?;    let mut all = Vec::new();    stream.read_to_end(&mut all)?;    let split = all.windows(4).position(|w| w == b"\r\n\r\n").unwrap_or(all.len());    Ok((String::from_utf8_lossy(&all[..split]).to_string(), all.get(split + 4..).unwrap_or_default().to_vec()))}fn status(url: &str) -> String {    get(url).map(|(head, _)| head.lines().next().unwrap_or_default().to_string()).unwrap_or_else(|error| format!("refused ({error})"))}const FILM: &[(&str, &[u8])] = &[("master.m3u8", b"#EXTM3U\nvideo/index.m3u8\n"), ("video/index.m3u8", b"#EXTM3U\nseg.m4s\n"), ("video/seg.m4s", b"segment"), ("sub-en.vtt", b"WEBVTT\n")];const OTHER: &[(&str, &[u8])] = &[("master.m3u8", b"#EXTM3U\nother\n"), ("video/seg.m4s", b"other film")];/// A non-loopback IPv4 this machine holds, to bind as a phone binds its Wi-Fi address.fn a_real_address() -> Option<IpAddr> {    interfaces().into_iter().map(|(_, ip)| ip).find(|ip| matches!(ip, IpAddr::V4(v4) if !v4.is_loopback() && !v4.is_link_local() && !v4.is_unspecified()))}/// RULE (cinemas-airplay, 18 Nov 2026): the Wi-Fi door answers only under its own path, new for each door and 128/// bits; a wrong path, the phone's own door's path, another film's path and a path out of the folder answer 404; the/// film's playlists, segments and subtitles answer under it.#[test]fn the_wifi_door_answers_only_its_own_films_path() {    let phone = Loopback::start().unwrap();    let film = phone.offer_folder("master.m3u8", folder(FILM));    let other = phone.offer_folder("master.m3u8", folder(OTHER));    let lan = LanDoor::open(IpAddr::V4(Ipv4Addr::LOCALHOST), offered_at(&phone, &film), "master.m3u8").unwrap();    let url = lan.url().to_string();    let token = url.split('/').nth(3).unwrap();    assert_eq!(token.len(), 32, "128 bits of path: {url}");    assert!(token.chars().all(|c| c.is_ascii_hexdigit()), "{url}");    assert!(!film.contains(token), "the Wi-Fi door's path is not the phone door's");    let again = LanDoor::open(IpAddr::V4(Ipv4Addr::LOCALHOST), offered_at(&phone, &film), "master.m3u8").unwrap();    assert_ne!(again.url().split('/').nth(3), Some(token), "a new door is a new path");    let base = url.strip_suffix("master.m3u8").unwrap();    let (head, body) = get(&url).unwrap();    assert!(head.starts_with("HTTP/1.1 200") && head.contains("application/vnd.apple.mpegurl"), "{head}");    assert_eq!(body, FILM[0].1);    assert_eq!(get(&format!("{base}video/seg.m4s")).unwrap().1, b"segment");    assert_eq!(get(&format!("{base}sub-en.vtt")).unwrap().1, b"WEBVTT\n", "subtitles travel the same way");    let port = lan.addr().port();    let other_token = other.split('/').nth(3).unwrap();    let phone_token = film.split('/').nth(3).unwrap();    for wrong in [        format!("http://127.0.0.1:{port}/{}/master.m3u8", "0".repeat(32)),        format!("http://127.0.0.1:{port}/{other_token}/master.m3u8"),        format!("http://127.0.0.1:{port}/{other_token}/video/seg.m4s"),        format!("http://127.0.0.1:{port}/{phone_token}/master.m3u8"),        format!("http://127.0.0.1:{port}/master.m3u8"),        format!("http://127.0.0.1:{port}/"),        format!("{base}../{other_token}/master.m3u8"),    ] {        assert!(status(&wrong).starts_with("HTTP/1.1 404"), "{wrong}: {}", status(&wrong));    }}/// RULE (cinemas-airplay): closed, the Wi-Fi door answers nothing and lets its port go; the phone's own door plays on.#[test]fn a_closed_wifi_door_refuses_every_request() {    let phone = Loopback::start().unwrap();    let film = phone.offer_folder("master.m3u8", folder(FILM));    let lan = LanDoor::open(IpAddr::V4(Ipv4Addr::LOCALHOST), offered_at(&phone, &film), "master.m3u8").unwrap();    let url = lan.url().to_string();    assert!(status(&url).starts_with("HTTP/1.1 200"));    lan.close();    assert!(!status(&url).starts_with("HTTP/1.1 200"), "closed, it answers nothing: {}", status(&url));    assert!(std::net::TcpStream::connect(lan.addr()).is_err(), "closed, its port is let go");    lan.close();    assert!(status(&film).starts_with("HTTP/1.1 200"), "the phone's own door is untouched");    let dropped = LanDoor::open(IpAddr::V4(Ipv4Addr::LOCALHOST), offered_at(&phone, &film), "master.m3u8").unwrap();    let (addr, url) = (dropped.addr(), dropped.url().to_string());    drop(dropped);    assert!(std::net::TcpStream::connect(addr).is_err(), "dropped, it is closed: {}", status(&url));}/// RULE (cinemas-airplay; airplay-refused, 18 Nov 2026): the door is fetched only when another device asks for the/// film's index, and taken only when another device reads bytes of the film itself (a segment, not a playlist); every/// path another device asked is named once, in order. The phone asking its own door is none of it.#[test]fn fetched_is_the_index_and_taken_is_the_film_asked_by_another_device() {    let phone = Loopback::start().unwrap();    let film = phone.offer_folder("master.m3u8", folder(FILM));    let lan = LanDoor::open(IpAddr::V4(Ipv4Addr::LOCALHOST), offered_at(&phone, &film), "master.m3u8").unwrap();    assert!(!lan.fetched());    assert!(status(lan.url()).starts_with("HTTP/1.1 200"));    assert!(!lan.fetched(), "the phone's own request is not the receiver's");    assert!(lan.asked().is_empty() && lan.media_taken_at().is_none());    let token = lan.url().split('/').nth(3).unwrap().to_string();    let read = |foreign: bool, inner: &str| {        let one = watched(&lan.offers, foreign, &lan.heard, "master.m3u8");        let map = one.lock().unwrap();        let Offered::Folder(opener) = &map[&token].offered else { panic!("a folder") };        let (_, mut source) = opener(inner).unwrap();        let mut bytes = Vec::new();        source.read_to_end(&mut bytes).unwrap();    };    read(false, "master.m3u8");    read(false, "video/seg.m4s");    assert!(!lan.fetched() && lan.asked().is_empty() && lan.media_taken_at().is_none(), "the phone asking is not the receiver");    read(true, "master.m3u8");    read(true, "video/index.m3u8");    assert!(lan.fetched(), "another device asked for the index");    assert_eq!(lan.media_taken_at(), None, "playlists alone: the film itself never taken");    read(true, "video/seg.m4s");    let taken = lan.media_taken_at().expect("a segment read out to another device");    read(true, "master.m3u8");    assert_eq!(lan.asked(), ["master.m3u8", "video/index.m3u8", "video/seg.m4s"], "each path once, in order");    assert_eq!(lan.media_taken_at(), Some(taken), "a playlist again is not the film taken");    assert!(playlist("video/INDEX.m3u8?x=1") && !playlist("video/seg.m4s") && !playlist("film.mp4"));    lan.close();    assert!(watched(&lan.offers, true, &lan.heard, "master.m3u8").lock().unwrap().is_empty(), "closed, a connection sees nothing offered");}/// RULE (airplay-refused): a film that is one file is taken whenever another device reads it, and its index is that file.#[test]fn a_one_file_film_is_taken_as_it_is_read() {    let phone = Loopback::start().unwrap();    let opener: crate::media::loopback::Opener = Arc::new(|| Ok(Box::new(std::io::Cursor::new(b"the whole film".to_vec())) as Box<dyn PlainSource>));    let film = phone.offer("film.mp4", "video/mp4", opener);    let lan = LanDoor::open(IpAddr::V4(Ipv4Addr::LOCALHOST), offered_at(&phone, &film), "film.mp4").unwrap();    let token = lan.url().split('/').nth(3).unwrap().to_string();    let one = watched(&lan.offers, true, &lan.heard, "film.mp4");    let map = one.lock().unwrap();    let Offered::File { opener, .. } = &map[&token].offered else { panic!("a file") };    let mut source = opener().unwrap();    assert!(lan.fetched(), "asked for: its index is the file");    assert_eq!(lan.media_taken_at(), None, "opened, nothing read yet");    let mut bytes = [0u8; 4];    source.read_exact(&mut bytes).unwrap();    assert!(lan.media_taken_at().is_some());    assert_eq!(lan.asked(), ["film.mp4"]);}/// RULE (cinemas-airplay): the door binds the Wi-Fi address alone: `en0`'s IPv4, never cellular (`pdp_ip*`), a cable,/// loopback or a self-assigned address; with none there is no door. Lent on a real address, it answers there and not/// on 127.0.0.1; it is never lent on loopback or on every interface.#[test]fn the_wifi_door_binds_the_wifi_address_alone() {    let v4 = |a, b, c, d| IpAddr::V4(Ipv4Addr::new(a, b, c, d));    let named = |list: &[(&str, IpAddr)]| list.iter().map(|(name, ip)| (name.to_string(), *ip)).collect::<Vec<_>>();    let phone = named(&[("lo0", v4(127, 0, 0, 1)), ("pdp_ip0", v4(10, 52, 3, 9)), ("en2", v4(169, 254, 4, 4)), ("en0", v4(192, 168, 1, 23))]);    assert_eq!(wifi_of(&phone), Some(v4(192, 168, 1, 23)));    assert_eq!(wifi_of(&named(&[("pdp_ip0", v4(10, 52, 3, 9)), ("lo0", v4(127, 0, 0, 1))])), None, "cellular alone: no Wi-Fi door");    assert_eq!(wifi_of(&named(&[("en0", v4(169, 254, 7, 7))])), None, "self-assigned: no network to reach a TV on");    assert_eq!(wifi_of(&named(&[("en1", v4(192, 168, 1, 5))])), None, "only the Wi-Fi interface");    assert_eq!(wifi_of(&[]), None);    let door = Loopback::start().unwrap();    let film = door.offer_folder("master.m3u8", folder(FILM));    assert!(door.lend(&film, IpAddr::V4(Ipv4Addr::LOCALHOST)).is_err(), "never on loopback");    assert!(door.lend(&film, IpAddr::V4(Ipv4Addr::UNSPECIFIED)).is_err(), "never on every interface");    let Some(ip) = a_real_address() else {        // A machine with no network address cannot show the bind; the rules above still hold.        return eprintln!("no non-loopback IPv4 here: the bind itself is not shown");    };    assert!(door.lend(&format!("http://127.0.0.1:{}/{}/master.m3u8", door.port(), "0".repeat(32)), ip).is_err(), "only a film this door offers is lent");    let lan = door.lend(&film, ip).unwrap();    assert_eq!(lan.addr().ip(), ip, "bound to the Wi-Fi address itself");    assert!(lan.url().starts_with(&format!("http://{ip}:")), "{}", lan.url());    assert!(status(lan.url()).starts_with("HTTP/1.1 200"), "{}", status(lan.url()));    let loopback = format!("http://127.0.0.1:{}/{}", lan.addr().port(), lan.url().splitn(4, '/').nth(3).unwrap());    assert!(!status(&loopback).starts_with("HTTP/1.1 200"), "not on loopback: {}", status(&loopback));}/// The offer the phone's door holds at `url`.fn offered_at(door: &Loopback, url: &str) -> Offered {    let token = url.split('/').nth(3).unwrap();    door.offered(token).expect("offered")}