diff --git a/README.md b/README.md index 57d3598..f7e5b9a 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,13 @@ A jailed player: the app's `main` calls `helper::run(args, &options, SANDBOX_COD lock_down)` when started with its helper argument, and starts one with `helper::start(jail::command(HELPER_ARG, sound)?, file, size, sound)`. +A jailed GPU player (`gpu_helper`) is started with `jail::gpu_arguments(exe, vendor, +jail::sound_socket().as_deref())` and plays sound with `Audio::Pulse`. That binds the +session's PulseAudio socket read-only, as the CPU helper does, and never PipeWire's own +socket. Once a file has loaded, it says the file's title, artist and album, if it has them, +as `meta` messages, cleaned by `gpu_helper::clean_meta`. Control characters, bidirectional +overrides, isolates and marks are taken out, and each tag is cut to 160 bytes. + ## Checks ```sh diff --git a/examples/colour-gpu.rs b/examples/colour-gpu.rs index 87eaadd..7052bf3 100644 --- a/examples/colour-gpu.rs +++ b/examples/colour-gpu.rs @@ -214,7 +214,7 @@ fn play_helper(reader: &alias_playback::gpu::Gpu, clip: &Path, vendor: alias_pla use alias_playback::gpu_helper::{self, Said}; let exe = alias_playback::jail::own_exe().map_err(|e| e.to_string())?; let mut command = std::process::Command::new("bwrap"); - command.args(alias_playback::jail::gpu_arguments(&exe, vendor)).arg(HELPER_ARG).arg(if hwdec { format!("{vendor:?}") } else { "software".into() }); + command.args(alias_playback::jail::gpu_arguments(&exe, vendor, None)).arg(HELPER_ARG).arg(if hwdec { format!("{vendor:?}") } else { "software".into() }); let node = alias_playback::gpu::first_render_node()?; let file = std::fs::File::open(clip).map_err(|e| e.to_string())?; let mut started = gpu_helper::start(command, file, node, (WIDTH as u32, HEIGHT as u32), false).map_err(|e| e.to_string())?; diff --git a/examples/gpu-play.rs b/examples/gpu-play.rs index 688d190..ec53ec9 100644 --- a/examples/gpu-play.rs +++ b/examples/gpu-play.rs @@ -49,7 +49,7 @@ fn main() { let exe = jail::own_exe().expect("own path"); let mut command = if flag("--jail") { let mut command = Command::new("bwrap"); - command.args(jail::gpu_arguments(&exe, vendor)).arg(HELPER_ARG); + command.args(jail::gpu_arguments(&exe, vendor, None)).arg(HELPER_ARG); command } else { let mut command = Command::new(&exe); diff --git a/examples/gpu-show.rs b/examples/gpu-show.rs index 39113b9..fc547ab 100644 --- a/examples/gpu-show.rs +++ b/examples/gpu-show.rs @@ -74,7 +74,7 @@ fn main() { let exe = jail::own_exe().expect("own path"); let mut command = if flag("--jail") { let mut command = Command::new("bwrap"); - command.args(jail::gpu_arguments(&exe, vendor)).arg(HELPER_ARG); + command.args(jail::gpu_arguments(&exe, vendor, None)).arg(HELPER_ARG); command } else { let mut command = Command::new(&exe); diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index 9e2806b..25e53a4 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -69,10 +69,105 @@ pub enum Said { Decoder(String), NoVideo, CantPlay, + /// A tag from the file, once it's loaded: its title, artist or album, cleaned by + /// [`clean_meta`]. Only tags the file has are said. + Meta(MetaField, String), +} + +/// The tags a player says, for an app's music view. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MetaField { + Title, + Artist, + Album, +} + +impl MetaField { + pub const ALL: [MetaField; 3] = [MetaField::Title, MetaField::Artist, MetaField::Album]; + + /// The word in a `meta` message. + pub fn word(self) -> &'static str { + match self { + MetaField::Title => "title", + MetaField::Artist => "artist", + MetaField::Album => "album", + } + } + + fn from_word(word: &str) -> Option { + Self::ALL.into_iter().find(|f| f.word() == word) + } + + /// The id its `Player::ask` goes by. + fn ask_id(self) -> u32 { + match self { + MetaField::Title => 1, + MetaField::Artist => 2, + MetaField::Album => 3, + } + } + + fn from_ask_id(id: u32) -> Option { + Self::ALL.into_iter().find(|f| f.ask_id() == id) + } + + /// libmpv's property for the tag. Tag names are matched without regard to case, so + /// Vorbis's `TITLE` and ID3's `title` both answer. + fn property(self) -> &'static std::ffi::CStr { + match self { + MetaField::Title => c"metadata/by-key/title", + MetaField::Artist => c"metadata/by-key/artist", + MetaField::Album => c"metadata/by-key/album", + } + } +} + +/// The `Player::ask` id for the video track, which confirms a file has no picture. Apart +/// from the tags' ids (1 to 3). +const VID_ASK: u32 = 4; + +/// The most of a tag that's kept, in bytes (cut at a character's edge). With `meta album ` +/// before it, a message stays well inside a packet. +pub const META_MAX: usize = 160; + +/// A tag as an app may show and speak it: control characters, bidirectional overrides, +/// isolates and marks, and line and paragraph separators taken out, runs of white space made +/// one space, trimmed, and cut to [`META_MAX`] bytes. A tag is the file's own text, so +/// nothing in it may reorder or break the line it's drawn on. +pub fn clean_meta(text: &str) -> String { + let unwanted = |c: char| c.is_control() || matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{2028}' | '\u{2029}' | '\u{FEFF}'); + let mut out = String::new(); + for word in text.split(|c: char| c.is_whitespace()).map(|w| w.chars().filter(|c| !unwanted(*c)).collect::()).filter(|w| !w.is_empty()) { + let gap = usize::from(!out.is_empty()); + if out.len() + gap + word.len() > META_MAX { + if out.len() + gap < META_MAX { + if gap == 1 { + out.push(' '); + } + for c in word.chars() { + if out.len() + c.len_utf8() > META_MAX { + break; + } + out.push(c); + } + } + break; + } + if gap == 1 { + out.push(' '); + } + out.push_str(&word); + } + out.trim_end().to_owned() } /// A message from the player, or `None` if it isn't a sensible one. pub fn parse_said(line: &str) -> Option { + if let Some(rest) = line.strip_prefix("meta ") { + let (word, text) = rest.split_once(' ')?; + let text = clean_meta(text); + return (!text.is_empty()).then_some(Said::Meta(MetaField::from_word(word)?, text)); + } let words: Vec<&str> = line.split_ascii_whitespace().collect(); let n = |i: usize| words.get(i)?.parse::().ok(); let small = |i: usize| u32::try_from(n(i)?).ok(); @@ -466,12 +561,39 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp match event { Event::Shutdown => std::process::exit(0), Event::Loaded { video } => { + // The file's tags, asked for without waiting on libmpv's core (a wait here + // stalled a song's cover): each is said when its answer comes. + for field in MetaField::ALL { + let _ = player.ask(field.property(), field.ask_id()); + } + // No picture: confirmed by asking the file now loading, as a late Loaded + // about the previous file can still arrive (its answer would be this + // file's). Only that answer starts sound alone. if !video { - say("novideo"); + let _ = player.ask(c"vid", VID_ASK); } } Event::Failed | Event::Refused(Request::Load) => say("cantplay"), - Event::Refused(_) | Event::Answered(_) => {} + Event::Answered(VID_ASK) => { + let none = player.answer(VID_ASK).is_some_and(|v| v == "no"); + if none && !first_drawn { + say("novideo"); + // Sound alone has no first frame to wait for: it starts now, if asked to. + first_drawn = true; + if !wanted_paused { + let _ = player.set_paused(false); + } + } + } + Event::Answered(id) => { + if let Some(field) = MetaField::from_ask_id(id) { + let text = player.answer(id).map(|t| clean_meta(&t)).unwrap_or_default(); + if !text.is_empty() { + say(&format!("meta {} {text}", field.word())); + } + } + } + Event::Refused(_) => {} Event::VideoChanged => {} // Width and height come one at a time: the size is settled after the batch. Event::Width(w) => shown_size.0 = w, @@ -654,6 +776,49 @@ mod tests { assert!(matches!(parse_said("state 1 2 0 100 0 0"), Some(Said::State(_)))); } + #[test] + fn each_tag_has_its_own_ask_id() { + for f in MetaField::ALL { + assert_eq!(MetaField::from_ask_id(f.ask_id()), Some(f)); + assert_ne!(f.ask_id(), VID_ASK); + } + assert_eq!(MetaField::from_ask_id(0), None); + } + + #[test] + fn tags_are_said_cleaned() { + assert_eq!(parse_said("meta title Night Drive"), Some(Said::Meta(MetaField::Title, "Night Drive".into()))); + assert_eq!(parse_said("meta artist The\tTest Signals "), Some(Said::Meta(MetaField::Artist, "The Test Signals".into()))); + assert_eq!(parse_said("meta album Calibration"), Some(Said::Meta(MetaField::Album, "Calibration".into()))); + assert_eq!(parse_said("meta genre Rock"), None, "only the three tags"); + assert_eq!(parse_said("meta title \u{202E}\u{0007}"), None, "nothing left to show"); + assert_eq!(parse_said("meta title"), None); + } + + #[test] + fn control_and_bidi_characters_are_stripped() { + assert_eq!(clean_meta("a\u{0}b\u{1b}[31mc\u{7f}d"), "ab[31mcd"); + assert_eq!(clean_meta("line\none\r\ntwo\u{2028}three\u{2029}four"), "line one two three four"); + for bidi in ['\u{061C}', '\u{200E}', '\u{200F}', '\u{202A}', '\u{202B}', '\u{202C}', '\u{202D}', '\u{202E}', '\u{2066}', '\u{2067}', '\u{2068}', '\u{2069}', '\u{FEFF}'] { + assert_eq!(clean_meta(&format!("evil{bidi}gpj.exe")), "evilgpj.exe", "U+{:04X}", bidi as u32); + } + assert_eq!(clean_meta(" Ünïcödé 名前 "), "Ünïcödé 名前", "other text is kept"); + } + + #[test] + fn tags_are_capped_at_a_character_edge() { + let long = "é".repeat(200); + let cut = clean_meta(&long); + assert!(cut.len() <= META_MAX && cut.len() >= META_MAX - 1); + assert!(cut.chars().all(|c| c == 'é')); + let words = "word ".repeat(100); + let cut = clean_meta(&words); + assert!(cut.len() <= META_MAX && !cut.ends_with(' ')); + assert!(format!("meta album {}", clean_meta(&"x".repeat(1000))).len() < MAX_MESSAGE); + let line = format!("meta title {}", "y".repeat(400)); + assert_eq!(parse_said(&line), Some(Said::Meta(MetaField::Title, "y".repeat(META_MAX)))); + } + #[test] fn nonsense_is_refused() { let xr24 = crate::gpu::FOURCC_XRGB8888; diff --git a/src/jail.rs b/src/jail.rs index a02d22c..345579b 100644 --- a/src/jail.rs +++ b/src/jail.rs @@ -72,8 +72,12 @@ pub fn arguments(executable: &Path, sound_socket: Option<&Path>) -> Vec /// gets, plus that card's device files, which drawing and decoding on it need, and nothing /// for any other maker. That's the drivers' attack surface too, which Mike accepted for this /// (2026-12-02). -pub fn gpu_arguments(executable: &Path, vendor: crate::options::Vendor) -> Vec { - let mut args = arguments(executable, None); +/// +/// With `sound_socket` (see [`sound_socket`]), the session's PulseAudio socket goes in +/// read-only, as for the CPU helper, and the player should use `Audio::Pulse`. PipeWire's own +/// socket is never bound: its clients reach every stream, screen casts and cameras included. +pub fn gpu_arguments(executable: &Path, vendor: crate::options::Vendor, sound_socket: Option<&Path>) -> Vec { + let mut args = arguments(executable, sound_socket); let run = args.len() - 2; // A user namespace of the jail's own. The helper's seccomp filter (`forbid_memory_writes`) // keeps it from making another inside: one would give back the privileges the jail drops, @@ -320,7 +324,7 @@ mod tests { fn only_nvidia_gets_proc_and_its_devices() { use crate::options::Vendor; for vendor in [Vendor::Nvidia, Vendor::Amd, Vendor::Intel, Vendor::Apple, Vendor::Other] { - let text = gpu_arguments(Path::new("/opt/app"), vendor).join(" "); + let text = gpu_arguments(Path::new("/opt/app"), vendor, None).join(" "); let nvidia = vendor == Vendor::Nvidia; assert_eq!(text.contains("--proc /proc"), nvidia, "{vendor:?}"); assert_eq!(text.contains("/dev/nvidia"), nvidia, "{vendor:?}"); @@ -328,6 +332,16 @@ mod tests { assert!(text.contains("--unshare-user") && !text.contains("--disable-userns"), "--disable-userns can't start in an LXC container"); assert!(!text.contains("/dev/video"), "no camera or other V4L2 devices"); assert!(text.ends_with("-- /playback-helper"), "{vendor:?}"); + assert!(!text.contains("PULSE_SERVER") && !text.contains("pipewire"), "no socket, no sound"); + let with_sound = gpu_arguments(Path::new("/opt/app"), vendor, Some(Path::new("/run/user/1000/pulse/native"))).join(" "); + assert!(with_sound.contains("--ro-bind /run/user/1000/pulse/native /sound-server") && with_sound.contains("--setenv PULSE_SERVER unix:/sound-server"), "{vendor:?}"); + assert!(with_sound.contains("--unshare-user") && with_sound.ends_with("-- /playback-helper"), "sound loosens nothing else: {vendor:?}"); + assert_eq!( + with_sound.replace(" --ro-bind /run/user/1000/pulse/native /sound-server --setenv PULSE_SERVER unix:/sound-server", ""), + text, + "sound adds the socket and nothing else: {vendor:?}" + ); + assert!(!with_sound.contains("pipewire-0"), "PipeWire's own socket is never bound"); } } @@ -342,10 +356,17 @@ mod tests { eprintln!("skipped: no bubblewrap with user namespaces, or no /dev/dri, here"); return; } - let args = gpu_arguments(&std::env::current_exe().expect("own path"), crate::options::Vendor::Other); - let inside = Command::new("bwrap").args(&args).args(["--ignored", "--exact", "jail::tests::in_the_gpu_jail", "--test-threads=1", "--nocapture"]).output().expect("bubblewrap"); - let said = String::from_utf8_lossy(&inside.stdout); - assert!(inside.status.success() && said.contains("1 passed"), "inside the jail:\n{said}{}", String::from_utf8_lossy(&inside.stderr)); + // With sound too: the sound socket's bind loosens nothing. A plain file stands in for + // the socket, as bubblewrap binds any file. + let socket = std::env::temp_dir().join(format!("alias-playback-sound-{}", std::process::id())); + std::fs::write(&socket, b"").unwrap(); + for sound in [None, Some(socket.as_path())] { + let args = gpu_arguments(&std::env::current_exe().expect("own path"), crate::options::Vendor::Other, sound); + let inside = Command::new("bwrap").args(&args).args(["--ignored", "--exact", "jail::tests::in_the_gpu_jail", "--test-threads=1", "--nocapture"]).output().expect("bubblewrap"); + let said = String::from_utf8_lossy(&inside.stdout); + assert!(inside.status.success() && said.contains("1 passed"), "inside the jail, sound {sound:?}:\n{said}{}", String::from_utf8_lossy(&inside.stderr)); + } + std::fs::remove_file(socket).unwrap(); } /// Run inside the GPU jail by `the_gpu_jail_cant_make_a_user_namespace`. The jail alone lets