From 876dcc58d16402d05b06c737fc5b1b3f887b0ecf Mon Sep 17 00:00:00 2001 From: abdelrahman fahmy <104788132+Apdelrahman1911@users.noreply.github.com> Date: Sun, 6 Dec 2026 07:43:57 +0000 Subject: [PATCH] feat(simaudio): publish SO_PEERCRED stream-to-PID map in simaudio-streams.json --- tools/launcher/core/src/services/simaudio.rs | 107 ++++++++++++++++++- 1 file changed, 105 insertions(+), 2 deletions(-) diff --git a/tools/launcher/core/src/services/simaudio.rs b/tools/launcher/core/src/services/simaudio.rs index 8a4de436..90b372de 100644 --- a/tools/launcher/core/src/services/simaudio.rs +++ b/tools/launcher/core/src/services/simaudio.rs @@ -8,8 +8,11 @@ //! length, payload. Out: 1 open (u32 rate, u32 channels), 2 data, 3 close; in: 4 microphone (f32 mono 48 kHz, replaces //! the input streams' source while it arrives), 5 microphone off. A slow tap loses data, never slows a stream. //! /simaudio-out/ marks a process with an output stream open (jetsam keeps audio apps that play). +//! /simaudio-streams.json maps active output stream IDs (matching simaudio-tap.sock) to their SO_PEERCRED +//! host_pid, rate, and channels without changing the 8-byte OPEN tap wire format. //! env: X86SIM_AUDIO_VOLUME (0..1, 0.5), X86SIM_AUDIO_PLAYER (pw-cat | pacat) use super::wait_timeout; +use serde::Serialize; use std::collections::{BTreeMap, HashMap}; use std::io::{BufRead, BufReader, Read, Write}; use std::os::unix::fs::PermissionsExt; @@ -243,6 +246,60 @@ impl Taps { } } +/// Active output stream attribution for a tap stream id (from kernel SO_PEERCRED). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct OutputStreamInfo { + pub host_pid: i32, + pub rate: u32, + pub channels: u32, +} + +#[derive(Serialize)] +struct StreamsSnapshot<'a> { + schema: u32, + streams: &'a BTreeMap, +} + +struct StreamRegistry { + path: Option, + streams: Mutex>, +} + +impl StreamRegistry { + fn new(path: Option) -> Self { + let reg = Self { path, streams: Mutex::default() }; + let empty = BTreeMap::new(); + reg.flush_locked(&empty); + reg + } + + fn insert(&self, sid: u32, info: OutputStreamInfo) { + let mut streams = self.streams.lock().unwrap(); + streams.insert(sid, info); + self.flush_locked(&streams); + } + + fn remove(&self, sid: u32) { + let mut streams = self.streams.lock().unwrap(); + if streams.remove(&sid).is_some() { + self.flush_locked(&streams); + } + } + + fn flush_locked(&self, streams: &BTreeMap) { + let Some(path) = self.path.as_ref() else { return }; + let keyed: BTreeMap = streams.iter().map(|(sid, info)| (sid.to_string(), *info)).collect(); + let Ok(bytes) = serde_json::to_vec(&StreamsSnapshot { schema: 1, streams: &keyed }) else { return }; + let tmp = path.with_extension("json.tmp"); + if std::fs::write(&tmp, &bytes).is_ok() { + let _ = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)); + if std::fs::rename(&tmp, path).is_err() { + let _ = std::fs::remove_file(&tmp); + } + } + } +} + struct Service { playback: bool, mic: bool, @@ -253,6 +310,7 @@ struct Service { micfeed: Mutex, out_dir: Option, out_n: Mutex>, + streams: StreamRegistry, } /// a player that stopped while its stream still ran (once a connection): its exit status, if it ends within 1 s @@ -345,7 +403,9 @@ impl Service { if direction == 0 { let pid = peer_pid(&conn); self.out_mark(pid, 1); + self.streams.insert(n as u32, OutputStreamInfo { host_pid: pid, rate, channels: ch }); self.output(&conn, n, rate, ch); + self.streams.remove(n as u32); self.out_mark(pid, -1); } else { self.input(&conn, n, rate, ch); @@ -478,10 +538,12 @@ pub fn run(path: &Path) -> std::io::Result<()> { let tap_path = abs_dir(path).join("simaudio-tap.sock"); let t = listen(&tap_path, 0o700)?; // the marks, a previous boot's removed - let out = abs_dir(path).join("simaudio-out"); + let state_dir = abs_dir(path); + let out = state_dir.join("simaudio-out"); let _ = std::fs::remove_dir_all(&out); let out_dir = std::fs::create_dir_all(&out).is_ok().then_some(out); - let svc = Arc::new(Service { playback, mic, player, volume: volume.clone(), gain, taps: Taps::default(), micfeed: Mutex::default(), out_dir, out_n: Mutex::default() }); + let streams = StreamRegistry::new(Some(state_dir.join("simaudio-streams.json"))); + let svc = Arc::new(Service { playback, mic, player, volume: volume.clone(), gain, taps: Taps::default(), micfeed: Mutex::default(), out_dir, out_n: Mutex::default(), streams }); { let svc = svc.clone(); std::thread::spawn(move || { @@ -535,4 +597,45 @@ mod tests { f.off(); assert!(!f.active()); } + + #[test] + fn stream_registry_tracks_open_and_close_atomically() { + let path = std::env::temp_dir().join(format!("x86sim-simaudio-streams-{}.json", std::process::id())); + let tmp = path.with_extension("json.tmp"); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(&tmp); + + let reg = StreamRegistry::new(Some(path.clone())); + let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(v["schema"], 1); + assert_eq!(v["streams"].as_object().unwrap().len(), 0); + assert!(!tmp.exists()); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + + reg.insert(1, OutputStreamInfo { host_pid: 4242, rate: 48000, channels: 2 }); + reg.insert(2, OutputStreamInfo { host_pid: 5151, rate: 44100, channels: 1 }); + let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(v["streams"]["1"]["host_pid"], 4242); + assert_eq!(v["streams"]["1"]["rate"], 48000); + assert_eq!(v["streams"]["1"]["channels"], 2); + assert_eq!(v["streams"]["2"]["host_pid"], 5151); + + reg.remove(1); + let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert!(v["streams"].get("1").is_none()); + assert_eq!(v["streams"]["2"]["host_pid"], 5151); + + reg.remove(2); + let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(v["streams"].as_object().unwrap().len(), 0); + assert!(!tmp.exists()); + + let _ = std::fs::remove_file(&path); + } + + #[test] + fn peer_pid_on_unix_socketpair() { + let (a, _b) = UnixStream::pair().unwrap(); + assert_eq!(peer_pid(&a), std::process::id() as i32); + } }