1use std::fs;
16use std::io::{ErrorKind, Write};
17use std::os::unix::net::UnixListener;
18use std::sync::atomic::{AtomicBool, Ordering};
19use std::sync::mpsc::{SyncSender, TrySendError, sync_channel};
20use std::sync::{Arc, Mutex};
21use std::thread;
22use std::time::Duration;
23
24const WRITE_TIMEOUT: Duration = Duration::from_millis(100);
25const ACCEPT_POLL_INTERVAL: Duration = Duration::from_millis(50);
26const CLIENT_QUEUE_CAP: usize = 100;
28const MAX_CONSUMERS: usize = 16;
30const CRC_POLY: u32 = 0x04c1_1db7;
32
33pub struct OpusHead {
36 pub channels: u8,
37 pub pre_skip: u16,
38 pub input_sample_rate: u32,
39 pub mapping: Option<(u8, u8, Vec<u8>)>,
40}
41
42fn peer_is_session_user(stream: &std::os::unix::net::UnixStream) -> bool {
45 use std::os::fd::AsRawFd;
46 let mut cred: libc::ucred = unsafe { std::mem::zeroed() };
47 let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
48 let r = unsafe {
49 libc::getsockopt(
50 stream.as_raw_fd(),
51 libc::SOL_SOCKET,
52 libc::SO_PEERCRED,
53 (&mut cred as *mut libc::ucred).cast(),
54 &mut len,
55 )
56 };
57 r == 0 && (cred.uid == unsafe { libc::geteuid() } || cred.uid == 0)
58}
59
60struct Client {
61 #[expect(
62 clippy::rc_buffer,
63 reason = "a page is built as a `Vec`; an `Arc<[u8]>` would copy each one"
64 )]
65 tx: SyncSender<Arc<Vec<u8>>>,
66 stop: Arc<AtomicBool>,
67}
68
69pub struct OggSink {
71 path: String,
72 clients: Arc<Mutex<Vec<Client>>>,
73 shutdown: Arc<AtomicBool>,
74 serial: u32,
75 seq: u32,
76}
77
78const CRC_TABLE: [u32; 256] = {
80 let mut table = [0u32; 256];
81 let mut i = 0;
82 while i < 256 {
83 let mut crc = (i as u32) << 24;
84 let mut bit = 0;
85 while bit < 8 {
86 crc = if crc & 0x8000_0000 != 0 {
87 (crc << 1) ^ CRC_POLY
88 } else {
89 crc << 1
90 };
91 bit += 1;
92 }
93 table[i] = crc;
94 i += 1;
95 }
96 table
97};
98
99fn crc32(data: &[u8]) -> u32 {
100 data.iter().fold(0u32, |crc, &b| {
101 (crc << 8) ^ CRC_TABLE[((crc >> 24) ^ u32::from(b)) as usize]
102 })
103}
104
105fn page(serial: u32, seq: u32, granule: u64, header_type: u8, packet: &[u8]) -> Vec<u8> {
108 let mut lacing: Vec<u8> = vec![255; packet.len() / 255];
109 lacing.push((packet.len() % 255) as u8);
110 let mut out = Vec::with_capacity(27 + lacing.len() + packet.len());
111 out.extend_from_slice(b"OggS");
112 out.push(0);
113 out.push(header_type);
114 out.extend_from_slice(&granule.to_le_bytes());
115 out.extend_from_slice(&serial.to_le_bytes());
116 out.extend_from_slice(&seq.to_le_bytes());
117 out.extend_from_slice(&[0u8; 4]);
118 out.push(lacing.len() as u8);
119 out.extend_from_slice(&lacing);
120 out.extend_from_slice(packet);
121 let crc = crc32(&out).to_le_bytes();
122 out[22..26].copy_from_slice(&crc);
123 out
124}
125
126fn header_pages(serial: u32, head: &OpusHead) -> Vec<u8> {
128 let mut id = b"OpusHead".to_vec();
129 id.push(1);
130 id.push(head.channels);
131 id.extend_from_slice(&head.pre_skip.to_le_bytes());
132 id.extend_from_slice(&head.input_sample_rate.to_le_bytes());
133 id.extend_from_slice(&0i16.to_le_bytes());
134 match &head.mapping {
135 None => id.push(0),
136 Some((streams, coupled, table)) => {
137 id.push(1);
138 id.push(*streams);
139 id.push(*coupled);
140 id.extend_from_slice(table);
141 }
142 }
143 let mut tags = b"OpusTags".to_vec();
144 tags.extend_from_slice(&(b"pcmflux".len() as u32).to_le_bytes());
145 tags.extend_from_slice(b"pcmflux");
146 tags.extend_from_slice(&0u32.to_le_bytes());
147 let mut out = page(serial, 0, 0, 0x02, &id);
148 out.extend_from_slice(&page(serial, 1, 0, 0, &tags));
149 out
150}
151
152impl OggSink {
153 pub fn bind(path: &str, head: &OpusHead) -> Result<Self, String> {
158 use std::os::unix::fs::{FileTypeExt, MetadataExt};
159 let stale = match fs::symlink_metadata(path) {
160 Ok(meta) if meta.uid() != unsafe { libc::geteuid() } => {
161 Err("another account owns it".to_string())
162 }
163 Ok(meta) if !meta.file_type().is_socket() => Err("it is not a socket".to_string()),
164 Ok(_) => fs::remove_file(path).map_err(|e| e.to_string()),
165 Err(_) => Ok(()),
166 };
167 let listener = stale
168 .and_then(|_| {
169 UnixListener::bind(path)
170 .and_then(|l| {
171 use std::os::unix::fs::PermissionsExt;
172 fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
174 l.set_nonblocking(true).map(|_| l)
175 })
176 .map_err(|e| e.to_string())
177 })
178 .map_err(|e| format!("output_socket {path} cannot be bound: {e}"))?;
179 let serial = std::process::id()
180 ^ (std::time::SystemTime::now()
181 .duration_since(std::time::UNIX_EPOCH)
182 .map(|d| d.subsec_nanos())
183 .unwrap_or(0));
184 let headers = Arc::new(header_pages(serial, head));
185 let clients: Arc<Mutex<Vec<Client>>> = Arc::new(Mutex::new(Vec::new()));
186 let shutdown = Arc::new(AtomicBool::new(false));
187 let (clients_acc, shutdown_acc, path_log) =
188 (clients.clone(), shutdown.clone(), path.to_string());
189 thread::spawn(move || {
190 while !shutdown_acc.load(Ordering::Relaxed) {
191 match listener.accept() {
192 Ok((stream, _)) => {
193 if !peer_is_session_user(&stream)
194 || clients_acc.lock().unwrap().len() >= MAX_CONSUMERS
195 {
196 continue;
197 }
198 let _ = stream.set_write_timeout(Some(WRITE_TIMEOUT));
199 let (tx, rx) = sync_channel::<Arc<Vec<u8>>>(CLIENT_QUEUE_CAP);
200 let stop = Arc::new(AtomicBool::new(false));
201 let stop_writer = stop.clone();
202 let _ = tx.try_send(headers.clone());
203 thread::spawn(move || {
204 let mut stream = stream;
205 for bytes in rx.iter() {
206 if stop_writer.load(Ordering::Relaxed)
207 || stream.write_all(&bytes).is_err()
208 {
209 break;
210 }
211 }
212 });
213 clients_acc.lock().unwrap().push(Client { tx, stop });
214 eprintln!("[pcmflux] ogg sink consumer connected on {path_log}");
215 }
216 Err(e) if e.kind() == ErrorKind::WouldBlock => {
217 thread::sleep(ACCEPT_POLL_INTERVAL)
218 }
219 Err(e) => {
220 eprintln!("[pcmflux] ogg sink accept error: {e}");
221 thread::sleep(Duration::from_millis(500));
222 }
223 }
224 }
225 });
226 Ok(Self {
227 path: path.to_string(),
228 clients,
229 shutdown,
230 serial,
231 seq: 2,
232 })
233 }
234
235 pub fn write_packet(&mut self, packet: &[u8], granule: u64) {
237 let bytes = Arc::new(page(self.serial, self.seq, granule, 0, packet));
238 self.seq = self.seq.wrapping_add(1);
239 let mut clients = self.clients.lock().unwrap();
240 clients.retain(|c| match c.tx.try_send(bytes.clone()) {
241 Ok(()) => true,
242 Err(TrySendError::Full(_)) | Err(TrySendError::Disconnected(_)) => {
243 c.stop.store(true, Ordering::Relaxed);
244 eprintln!("[pcmflux] ogg sink dropping a consumer that stopped reading");
245 false
246 }
247 });
248 }
249}
250
251impl Drop for OggSink {
252 fn drop(&mut self) {
253 self.shutdown.store(true, Ordering::Relaxed);
254 for c in self.clients.lock().unwrap().drain(..) {
255 c.stop.store(true, Ordering::Relaxed);
256 }
257 let _ = fs::remove_file(&self.path);
258 }
259}
260
261#[cfg(test)]
262mod tests {
263 use super::*;
264 use std::io::Read;
265 use std::os::unix::net::UnixStream;
266
267 #[test]
270 fn a_stale_socket_of_this_session_is_replaced() {
271 let path = format!("/tmp/pcmflux-ogg-stale-{}.sock", std::process::id());
272 let _ = fs::remove_file(&path);
273 drop(std::os::unix::net::UnixListener::bind(&path).unwrap());
275 let head = OpusHead {
276 channels: 2,
277 pre_skip: 312,
278 input_sample_rate: 48000,
279 mapping: None,
280 };
281 let sink = OggSink::bind(&path, &head);
282 assert!(
283 sink.is_ok(),
284 "an own leftover is removed and the socket bound"
285 );
286 drop(sink);
287 assert!(
288 fs::symlink_metadata(&path).is_err(),
289 "the socket is removed with the sink"
290 );
291 }
292
293 #[test]
296 fn the_socket_is_its_users_alone() {
297 use std::os::unix::fs::PermissionsExt;
298 let dir = tempfile::Builder::new()
299 .prefix("pcmflux-ogg-mode-")
300 .tempdir()
301 .unwrap();
302 let path = dir.path().join("out.sock").to_string_lossy().into_owned();
303 let head = OpusHead {
304 channels: 2,
305 pre_skip: 312,
306 input_sample_rate: 48000,
307 mapping: None,
308 };
309 let old = unsafe { libc::umask(0) };
310 let sink = OggSink::bind(&path, &head);
311 unsafe { libc::umask(old) };
312 let sink = sink.expect("bind");
313 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
314 assert_eq!(mode, 0o600);
315 let peer = UnixStream::connect(&path).unwrap();
316 assert!(peer_is_session_user(&peer));
317 drop(sink);
318 }
319
320 #[test]
323 fn the_checksum_table_agrees_with_the_polynomial() {
324 fn bitwise(data: &[u8]) -> u32 {
325 let mut crc = 0u32;
326 for &b in data {
327 crc ^= u32::from(b) << 24;
328 for _ in 0..8 {
329 crc = if crc & 0x8000_0000 != 0 {
330 (crc << 1) ^ CRC_POLY
331 } else {
332 crc << 1
333 };
334 }
335 }
336 crc
337 }
338 assert_eq!(crc32(&[]), 0);
339 assert_eq!(crc32(&[0; 64]), 0);
340 assert_eq!(crc32(b"123456789"), 0x89a1_897f);
341 let every: Vec<u8> = (0..=255u8).cycle().take(4096).collect();
342 for data in [&every[..], &every[..255], &every[1..256], &[0xff; 300][..]] {
343 assert_eq!(crc32(data), bitwise(data));
344 }
345 }
346
347 #[test]
349 fn a_file_that_is_not_a_socket_is_left_alone() {
350 let path = format!("/tmp/pcmflux-ogg-file-{}", std::process::id());
351 fs::write(&path, b"kept").unwrap();
352 let head = OpusHead {
353 channels: 2,
354 pre_skip: 312,
355 input_sample_rate: 48000,
356 mapping: None,
357 };
358 let err = OggSink::bind(&path, &head)
359 .err()
360 .expect("a regular file is refused");
361 assert!(err.contains("not a socket"), "{err}");
362 assert_eq!(fs::read(&path).unwrap(), b"kept");
363 let _ = fs::remove_file(&path);
364 }
365
366 #[test]
367 fn an_unbindable_path_is_an_error() {
368 let path = format!("/tmp/pcmflux-ogg-missing-{}/rec.sock", std::process::id());
369 let head = OpusHead {
370 channels: 2,
371 pre_skip: 312,
372 input_sample_rate: 48000,
373 mapping: None,
374 };
375 let err = OggSink::bind(&path, &head)
376 .err()
377 .expect("a missing directory is refused");
378 assert!(err.contains(&path), "{err}");
379 }
380
381 #[test]
387 fn stream_pages_are_well_formed() {
388 assert_eq!(crc32(b"123456789"), 0x89a1_897f);
389 let path = format!("/tmp/pcmflux-ogg-test-{}.sock", std::process::id());
390 let head = OpusHead {
391 channels: 2,
392 pre_skip: 312,
393 input_sample_rate: 48000,
394 mapping: None,
395 };
396 let mut sink = OggSink::bind(&path, &head).expect("bind");
397 let mut consumer = UnixStream::connect(&path).expect("connect");
398 consumer
399 .set_read_timeout(Some(Duration::from_secs(2)))
400 .unwrap();
401 thread::sleep(Duration::from_millis(150));
402 sink.write_packet(&[0xfc, 1, 2, 3], 960);
403 sink.write_packet(&vec![0xfc; 255], 1920);
404 thread::sleep(Duration::from_millis(150));
405 let mut buf = vec![0u8; 4096];
406 let mut got = Vec::new();
407 while let Ok(n) = consumer.read(&mut buf) {
408 if n == 0 {
409 break;
410 }
411 got.extend_from_slice(&buf[..n]);
412 if got.len() >= 27 * 4 + 19 + 27 + 4 + 259 {
413 break;
414 }
415 }
416 let mut pages = Vec::new();
417 let mut laces = Vec::new();
418 let mut at = 0;
419 while at + 27 <= got.len() {
420 assert_eq!(&got[at..at + 4], b"OggS");
421 let segments = got[at + 26] as usize;
422 let body: usize = got[at + 27..at + 27 + segments]
423 .iter()
424 .map(|&l| l as usize)
425 .sum();
426 let end = at + 27 + segments + body;
427 let mut copy = got[at..end].to_vec();
428 let stored = u32::from_le_bytes(copy[22..26].try_into().unwrap());
429 copy[22..26].copy_from_slice(&[0; 4]);
430 assert_eq!(crc32(©), stored, "page {} checksum", pages.len());
431 let granule = u64::from_le_bytes(copy[6..14].try_into().unwrap());
432 laces.push(copy[27..27 + segments].to_vec());
433 pages.push((granule, copy[27 + segments..].to_vec()));
434 at = end;
435 }
436 assert_eq!(pages.len(), 4);
437 assert!(pages[0].1.starts_with(b"OpusHead"));
438 assert_eq!(pages[0].1[9], 2);
439 assert!(pages[1].1.starts_with(b"OpusTags"));
440 assert_eq!(pages[2], (960, vec![0xfc, 1, 2, 3]));
441 assert_eq!(pages[3].0, 1920);
442 assert_eq!(pages[3].1.len(), 255);
443 assert_eq!(laces[3], vec![255, 0]);
444 drop(sink);
445 assert!(!std::path::Path::new(&path).exists());
446 }
447}