Skip to main content

radio_cli/
process.rs

1use crate::error::{DomainError, ErrorCode};
2use anyhow::{Context, Result, bail};
3use fs2::FileExt;
4use std::{
5    fs::{File, OpenOptions},
6    io::Read,
7    path::Path,
8    process::{Child, Command, ExitStatus, Stdio},
9    sync::{
10        Arc,
11        atomic::{AtomicBool, Ordering},
12    },
13    thread,
14    time::{Duration, Instant},
15};
16
17pub struct MediaLock {
18    _file: File,
19}
20
21/// Linux must also reap media when the owning frontend is killed abruptly.
22pub fn owned_child(command: &mut Command) -> &mut Command {
23    #[cfg(target_os = "linux")]
24    {
25        use std::os::unix::process::CommandExt;
26        let parent = std::process::id();
27        // Only async-signal-safe operations run between fork and exec.
28        unsafe {
29            command.pre_exec(move || {
30                if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) < 0 {
31                    return Err(std::io::Error::last_os_error());
32                }
33                if libc::getppid() != parent as libc::pid_t {
34                    libc::_exit(1);
35                }
36                Ok(())
37            });
38        }
39    }
40    command
41}
42// Linux ties PDEATHSIG to the spawning thread. Spawn through a persistent
43// supervisor so returning a child from a short-lived task does not kill it.
44pub fn spawn_owned(command: Command) -> std::io::Result<Child> {
45    type Request = (Command, std::sync::mpsc::SyncSender<std::io::Result<Child>>);
46    static SPAWNER: std::sync::OnceLock<std::sync::mpsc::Sender<Request>> =
47        std::sync::OnceLock::new();
48    let sender = SPAWNER.get_or_init(|| {
49        let (sender, receiver) = std::sync::mpsc::channel::<Request>();
50        thread::Builder::new()
51            .name("radio-process-spawner".into())
52            .spawn(move || {
53                for (mut command, reply) in receiver {
54                    let child = owned_child(&mut command).spawn();
55                    if let Err(error) = reply.send(child)
56                        && let Ok(mut child) = error.0
57                    {
58                        let _ = child.kill();
59                        let _ = child.wait();
60                    }
61                }
62            })
63            .expect("cannot start process supervisor");
64        sender
65    });
66    let (reply, result) = std::sync::mpsc::sync_channel(1);
67    sender
68        .send((command, reply))
69        .map_err(|_| std::io::Error::other("process supervisor stopped"))?;
70    result
71        .recv()
72        .map_err(|_| std::io::Error::other("process supervisor stopped"))?
73}
74
75impl MediaLock {
76    pub fn acquire(dir: &Path) -> Result<Self> {
77        let file = OpenOptions::new()
78            .create(true)
79            .truncate(false)
80            .read(true)
81            .write(true)
82            .open(dir.join("media.lock"))?;
83        file.try_lock_exclusive()
84            .context(DomainError::new(ErrorCode::MediaBusy))?;
85        Ok(Self { _file: file })
86    }
87}
88
89impl Drop for MediaLock {
90    fn drop(&mut self) {
91        // A concurrent fork may briefly inherit the open description before
92        // exec closes it. Explicitly unlock when the last owner finishes;
93        // unrelated children must not prolong the media-session lifetime.
94        let _ = fs2::FileExt::unlock(&self._file);
95    }
96}
97
98pub fn drain(mut reader: impl Read + Send + 'static, cap: usize) -> thread::JoinHandle<Vec<u8>> {
99    thread::spawn(move || {
100        let mut result = Vec::new();
101        let mut buf = [0u8; 4096];
102        while let Ok(n) = reader.read(&mut buf) {
103            if n == 0 {
104                break;
105            }
106            let room = cap.saturating_sub(result.len());
107            result.extend_from_slice(&buf[..n.min(room)]);
108        }
109        result
110    })
111}
112
113pub fn wait_until(child: &mut Child, timeout: Duration, stop: &AtomicBool) -> Result<ExitStatus> {
114    let deadline = Instant::now() + timeout;
115    loop {
116        if let Some(status) = child.try_wait()? {
117            return Ok(status);
118        }
119        let cancelled = stop.load(Ordering::Relaxed);
120        if cancelled || Instant::now() >= deadline {
121            let _ = child.kill();
122            let _ = child.wait();
123            let code = if cancelled {
124                ErrorCode::Cancelled
125            } else {
126                ErrorCode::ProcessTimeout
127            };
128            bail!(DomainError::new(code));
129        }
130        thread::sleep(Duration::from_millis(30));
131    }
132}
133
134pub fn output(command: &mut Command, timeout: Duration, stop: &Arc<AtomicBool>) -> Result<Vec<u8>> {
135    use std::os::fd::OwnedFd;
136    use std::os::unix::{net::UnixStream, process::CommandExt};
137
138    // Separate read endpoints let us drain output without ever waiting for
139    // EOF from an orphaned descendant that inherited a write endpoint.
140    let (mut stdout, out) = UnixStream::pair()?;
141    let (mut stderr, err) = UnixStream::pair()?;
142    stdout.set_nonblocking(true)?;
143    stderr.set_nonblocking(true)?;
144    command
145        .process_group(0)
146        .stdin(Stdio::null())
147        .stdout(Stdio::from(OwnedFd::from(out)))
148        .stderr(Stdio::from(OwnedFd::from(err)));
149    let configured = std::mem::replace(command, Command::new("unused"));
150    let program = configured.get_program().to_string_lossy().into_owned();
151    let mut child = spawn_owned(configured)
152        .context(DomainError::new(ErrorCode::MissingDependency).with("program", program))?;
153    let deadline = Instant::now() + timeout;
154    let mut data = Vec::new();
155    let mut error = Vec::new();
156    let result = (|| -> Result<ExitStatus> {
157        loop {
158            let (out_eof, out_read) = read_available(&mut stdout, &mut data, 256 * 1024)?;
159            let (err_eof, err_read) = read_available(&mut stderr, &mut error, 16 * 1024)?;
160            if out_eof
161                && err_eof
162                && let Some(status) = child.try_wait()?
163            {
164                return Ok(status);
165            }
166            if stop.load(Ordering::Relaxed) {
167                bail!(DomainError::new(ErrorCode::Cancelled));
168            }
169            if Instant::now() >= deadline {
170                bail!(DomainError::new(ErrorCode::ProcessTimeout));
171            }
172            if !out_read && !err_read {
173                thread::sleep(Duration::from_millis(10));
174            }
175        }
176    })();
177    if result.is_err() {
178        // We have not reaped the group leader, so its ID cannot be reused.
179        unsafe {
180            libc::kill(-(child.id() as i32), libc::SIGKILL);
181        }
182        // A wrapper may have moved itself out of the original process group.
183        let _ = child.kill();
184        let _ = child.wait();
185    }
186    let status = result?;
187    if !status.success() {
188        bail!(DomainError::new(ErrorCode::ProcessFailed).with(
189            "reason",
190            crate::clean_text(&String::from_utf8_lossy(&error))
191        ));
192    }
193    Ok(data)
194}
195
196fn read_available(
197    reader: &mut impl Read,
198    result: &mut Vec<u8>,
199    cap: usize,
200) -> std::io::Result<(bool, bool)> {
201    let mut buf = [0; 8192];
202    match reader.read(&mut buf) {
203        Ok(0) => Ok((true, false)),
204        Ok(n) => {
205            result.extend_from_slice(&buf[..n.min(cap.saturating_sub(result.len()))]);
206            Ok((false, true))
207        }
208        Err(e)
209            if matches!(
210                e.kind(),
211                std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
212            ) =>
213        {
214            Ok((false, false))
215        }
216        Err(e) => Err(e),
217    }
218}
219
220/// Desktop applications launched by the opener may outlive the radio process.
221pub(crate) fn open_directory(
222    mut command: Command,
223    timeout: Duration,
224    stop: &AtomicBool,
225) -> Result<()> {
226    command
227        .stdin(Stdio::null())
228        .stdout(Stdio::null())
229        .stderr(Stdio::null());
230    let program = command.get_program().to_string_lossy().into_owned();
231    let mut child = spawn_owned(command)
232        .context(DomainError::new(ErrorCode::MissingDependency).with("program", program))?;
233    let status = wait_until(&mut child, timeout, stop)?;
234    if !status.success() {
235        bail!(DomainError::new(ErrorCode::ProcessFailed).with("reason", status.to_string()));
236    }
237    Ok(())
238}
239
240/// A cancellable task whose blocking I/O never holds up the media owner.
241/// Dropping it cancels subprocesses and ignores any late network result.
242pub struct Background<T> {
243    cancel: Arc<AtomicBool>,
244    result: std::sync::mpsc::Receiver<Result<T>>,
245}
246impl<T: Send + 'static> Background<T> {
247    pub fn start(
248        name: &str,
249        work: impl FnOnce(Arc<AtomicBool>) -> Result<T> + Send + 'static,
250    ) -> Result<Self> {
251        let cancel = Arc::new(AtomicBool::new(false));
252        let flag = cancel.clone();
253        let (sender, result) = std::sync::mpsc::sync_channel(1);
254        thread::Builder::new().name(name.into()).spawn(move || {
255            let _ = sender.send(work(flag));
256        })?;
257        Ok(Self { cancel, result })
258    }
259    pub fn poll(&self) -> Option<Result<T>> {
260        match self.result.try_recv() {
261            Ok(value) => Some(value),
262            Err(std::sync::mpsc::TryRecvError::Empty) => None,
263            Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(Err(anyhow::anyhow!(
264                DomainError::new(ErrorCode::BackgroundFailed)
265            ))),
266        }
267    }
268
269    pub(crate) fn cancel(&self) {
270        self.cancel.store(true, Ordering::Relaxed);
271    }
272}
273impl<T> Drop for Background<T> {
274    fn drop(&mut self) {
275        self.cancel.store(true, Ordering::Relaxed);
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    #[test]
284    fn inherited_output_is_bounded_for_probes_and_detached_for_openers() {
285        let stop = Arc::default();
286        let timeout = Duration::from_millis(150);
287        let command = || {
288            let mut cmd = Command::new("sh");
289            cmd.args(["-c", "sleep 2 & exit 0"]);
290            cmd
291        };
292        let start = Instant::now();
293        let err = output(&mut command(), timeout, &stop).unwrap_err();
294        assert_eq!(
295            err.downcast_ref::<DomainError>().unwrap().code,
296            ErrorCode::ProcessTimeout
297        );
298        open_directory(command(), timeout, &stop).unwrap();
299        assert!(start.elapsed() < Duration::from_secs(1));
300    }
301
302    #[test]
303    fn stopping_a_running_child_reports_cancellation() {
304        let mut child = Command::new("sleep").arg("30").spawn().unwrap();
305        let error =
306            wait_until(&mut child, Duration::from_secs(10), &AtomicBool::new(true)).unwrap_err();
307        assert_eq!(
308            error.downcast_ref::<DomainError>().unwrap().code,
309            ErrorCode::Cancelled
310        );
311        assert!(child.try_wait().unwrap().is_some());
312    }
313}