ctb_workspace_ipc/process_manager/
unix.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT
2// SPDX-License-Identifier for parts derived from pid1-rs: MIT
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// Process reaping is based partly on <https://github.com/fpco/pid1-rs>:
22
23// Copyright (c) 2023 FP Complete
24
25// See additional licensing details at end of file.
26
27//! Unix-specific `ProcessManager` implementation.
28//!
29//! - Each child is started in its own process group via setpgid(0, 0).
30//! - On Linux, `PR_SET_PDEATHSIG` is set to SIGTERM.
31//! - Tree termination uses kill on the process group id.
32//!
33
34#![cfg(unix)]
35
36#[allow(
37    unused_imports,
38    clippy::wildcard_imports,
39    reason = "Standard workspace module prelude"
40)]
41use crate::utilities::*;
42
43use std::collections::HashMap;
44use std::process::Stdio;
45use std::sync::Arc;
46
47use anyhow::{Context, Result, anyhow};
48use async_trait::async_trait;
49use nix::errno::Errno;
50use nix::libc;
51use nix::sys::signal::{Signal, kill};
52use nix::unistd::Pid;
53use process_wrap::tokio::{CommandWrap, ProcessGroup};
54use tokio::io::AsyncWriteExt;
55use tokio::sync::Mutex;
56use tokio::time::{Duration, sleep};
57
58use crate::error::Error;
59use crate::types::{ConnectionId, ProcessId};
60
61use super::{ChildHandle, ProcessManager, SpawnParams};
62
63/// Unix-specific process supervision primitives (to be implemented with nix):
64/// - setpgid to create process groups
65/// - `prctl(PR_SET_PDEATHSIG)`
66/// - killpg for tree termination
67pub struct UnixProcessSupervisor;
68
69/// Unix shared memory helpers (memfd, `SCM_RIGHTS`) should be implemented here as needed.
70pub struct UnixSharedMemory;
71
72#[derive(Debug)]
73struct ChildEntry {
74    // child handle is now managed by a background reaper task
75    handle: ChildHandle,
76    // On Unix, the process group id equals pid when setpgid(0, 0) is used.
77    pgid: libc::pid_t,
78}
79
80#[derive(Debug)]
81struct Inner {
82    children: HashMap<ProcessId, ChildEntry>,
83}
84
85/// Tokio-based Unix process manager.
86#[derive(Debug)]
87pub struct TokioProcessManager {
88    inner: Arc<Mutex<Inner>>,
89}
90
91impl TokioProcessManager {
92    /// Create a new manager instance.
93    pub fn new() -> Arc<Self> {
94        Arc::new(Self {
95            inner: Arc::new(Mutex::new(Inner {
96                children: HashMap::new(),
97            })),
98        })
99    }
100
101    fn to_err(e: anyhow::Error) -> Error {
102        // Map anyhow::Error to crate error. Assumes Error: From<anyhow::Error>.
103        Error::from(e)
104    }
105
106    /// Send a signal to the given process group id, using nix.
107    fn signal_pgid(
108        pgid: libc::pid_t,
109        sig: libc::c_int,
110    ) -> Result<(), anyhow::Error> {
111        // Use kill with negative pgid to signal the whole process group.
112        // nix::unistd::Pid supports negative values for process groups.
113        let res = kill(Pid::from_raw(pgid), Signal::try_from(sig)?);
114        match res {
115            Ok(()) | Err(Errno::EPERM) => Ok(()),
116            Err(e) => {
117                Err(anyhow::anyhow!("failed to signal process group: {e}"))
118            }
119        }
120    }
121
122    /// Check whether a process group with the given pgid exists, using nix.
123    /// We send signal 0 to -pgid to test for any member of that group.
124    fn pid_exists(pid: libc::pid_t) -> bool {
125        // NOTE: treat `pid` as a process group id (pgid) and test the group.
126        let e = kill(Pid::from_raw(pid), None);
127        match e {
128            Ok(()) | Err(Errno::EPERM) => true,
129            Err(_) => false,
130        }
131    }
132}
133
134#[async_trait]
135impl ProcessManager for TokioProcessManager {
136    async fn spawn_child(
137        &self,
138        params: SpawnParams,
139    ) -> Result<ChildHandle, Error> {
140        // Use process-wrap's CommandWrap for safe process group setup
141        let program = if let Some(p) = params.program {
142            p
143        } else {
144            if params.kind == ipc::ChildKind::External {
145                return Err(Error::from(anyhow!(
146                    "No program specified for child process"
147                )));
148            }
149            std::env::current_exe()?.into_os_string().into_string()?
150        };
151        let mut cmd = CommandWrap::with_new(&program, |command| {
152            command.args(&params.args);
153            command.stdin(Stdio::piped());
154            for (k, v) in &params.env {
155                command.env(k, v);
156            }
157            if let Some(cwd) = &params.cwd {
158                command.current_dir(cwd);
159            }
160        });
161        // Apply the ProcessGroup wrapper to safely handle setpgid and PR_SET_PDEATHSIG (on Linux)
162        cmd.wrap(ProcessGroup::leader());
163
164        // Spawn the child using the wrapped command
165        let mut child = cmd.spawn().context("failed to spawn child")?;
166
167        // Pipe the capability token via stdin to avoid exposing it in argv.
168        // The child is expected to read a single line token from stdin.
169        let token = params.capabilities.token.0.clone();
170        if !token.is_empty() {
171            if let Some(stdin) = child.stdin() {
172                stdin
173                    .write_all(token.as_bytes())
174                    .await
175                    .map_err(|e: std::io::Error| Error::from(e))?;
176                stdin
177                    .write_all(b"\n")
178                    .await
179                    .map_err(|e: std::io::Error| Error::from(e))?;
180            }
181        }
182        let os_pid = child.id().ok_or_else(|| anyhow!("child has no pid"))?;
183        let process_id = ProcessId::new();
184        let handle = ChildHandle {
185            pid: process_id,
186            kind: params.kind,
187            parent: params.parent,
188            connection: None,
189        };
190
191        // Compute process group id value we use for signaling (negative value to target group)
192        let pgid = i32::try_from(os_pid)
193            .map_err(|e| Self::to_err(anyhow!("pid conversion error: {e}")))?
194            .checked_neg()
195            .ok_or_else(|| Self::to_err(anyhow!("pid negation overflow")))?;
196
197        // Spawn a background reaper task that waits on the child and cleans up
198        let inner_for_reaper = Arc::clone(&self.inner);
199        let pid_for_reaper = process_id;
200        tokio::spawn(async move {
201            // Wait for the child to exit and be reaped
202            let _ = child.wait().await;
203            // Best-effort cleanup of the manager's registry (in case terminate_tree wasn't called)
204            let mut inner = inner_for_reaper.lock().await;
205            let _ = inner.children.remove(&pid_for_reaper);
206        });
207
208        let entry = ChildEntry {
209            handle: handle.clone(),
210            pgid,
211        };
212        let mut inner = self.inner.lock().await;
213        inner.children.insert(process_id, entry);
214        Ok(handle)
215    }
216
217    async fn attach_connection(
218        &self,
219        pid: ProcessId,
220        conn: ConnectionId,
221    ) -> Result<(), Error> {
222        let mut inner = self.inner.lock().await;
223        let entry = inner.children.get_mut(&pid).ok_or_else(|| {
224            Self::to_err(anyhow!("child with pid {pid:?} not found"))
225        })?;
226        entry.handle.connection = Some(conn);
227        Ok(())
228    }
229
230    async fn list_children(&self) -> Result<Vec<ChildHandle>, Error> {
231        let inner = self.inner.lock().await;
232        Ok(inner.children.values().map(|e| e.handle.clone()).collect())
233    }
234
235    async fn terminate_tree(
236        &self,
237        pid: ProcessId,
238        force: bool,
239    ) -> Result<(), Error> {
240        // Determine subtree pids and their process groups.
241        let targets = {
242            let inner = self.inner.lock().await;
243
244            let mut targets: Vec<(ProcessId, libc::pid_t)> = Vec::new();
245
246            // Build a parent index.
247            let mut stack = vec![pid];
248            while let Some(cur) = stack.pop() {
249                if let Some(entry) = inner.children.get(&cur) {
250                    targets.push((cur, entry.pgid));
251                    // Note: we cannot clone a oneshot receiver, so we only
252                    // best-effort reap via `wait_for_exit`.
253                    // Keep the receiver only for the direct pid if present.
254                }
255
256                for (child_pid, entry) in &inner.children {
257                    if entry.handle.parent == Some(cur) {
258                        stack.push(*child_pid);
259                    }
260                }
261            }
262
263            targets
264        };
265
266        if targets.is_empty() {
267            return Ok(());
268        }
269
270        let sig = if force { libc::SIGKILL } else { libc::SIGTERM };
271        for (_pid, pgid) in &targets {
272            let _ = Self::signal_pgid(*pgid, sig);
273        }
274
275        Ok(())
276    }
277
278    async fn wait_for_exit(
279        &self,
280        pid: ProcessId,
281        timeout: Duration,
282    ) -> Result<bool, Error> {
283        // Snapshot subtree process groups.
284        let pgids: Vec<libc::pid_t> = {
285            let inner = self.inner.lock().await;
286            let mut pgids = Vec::new();
287            let mut stack = vec![pid];
288            while let Some(cur) = stack.pop() {
289                if let Some(entry) = inner.children.get(&cur) {
290                    pgids.push(entry.pgid);
291                }
292                for (child_pid, entry) in &inner.children {
293                    if entry.handle.parent == Some(cur) {
294                        stack.push(*child_pid);
295                    }
296                }
297            }
298            pgids
299        };
300
301        if pgids.is_empty() {
302            return Ok(true);
303        }
304
305        let step = Duration::from_millis(50);
306        let mut waited = Duration::from_millis(0);
307        while waited < timeout {
308            if pgids.iter().all(|pgid| !Self::pid_exists(*pgid)) {
309                return Ok(true);
310            }
311            sleep(step).await;
312            waited = waited.checked_add(step).ok_or_else(|| {
313                Self::to_err(anyhow!("timeout duration overflow"))
314            })?;
315        }
316
317        Ok(pgids.iter().all(|pgid| !Self::pid_exists(*pgid)))
318    }
319}
320
321#[cfg(test)]
322#[allow(
323    clippy::panic,
324    clippy::expect_used,
325    clippy::unwrap_used,
326    clippy::unwrap_in_result,
327    clippy::panic_in_result_fn,
328    clippy::indexing_slicing,
329    clippy::arithmetic_side_effects,
330    reason = "Standard repository test boilerplate"
331)]
332mod tests {
333    use tokio::time::timeout;
334
335    use crate::auth::capability::CapabilityBundle;
336    use ipc::ChildKind;
337
338    use super::*;
339
340    #[crate::ctb_test("tokio")]
341    async fn test_spawn_and_terminate_graceful() {
342        let manager = TokioProcessManager::new();
343        let params = SpawnParams {
344            kind: ChildKind::External,
345            parent: None,
346            program: Some("sleep".to_string()),
347            args: vec!["1".to_string()],
348            env: vec![],
349            cwd: None,
350            capabilities: CapabilityBundle::default(),
351        };
352        let handle = manager.spawn_child(params).await.unwrap();
353        // Terminate with force=false, should wait for graceful exit
354        let result = timeout(
355            Duration::from_secs(3),
356            manager.terminate_tree(handle.pid, false),
357        )
358        .await;
359        assert!(
360            result.is_ok(),
361            "graceful termination should complete within timeout"
362        );
363    }
364
365    #[crate::ctb_test("tokio")]
366    async fn test_spawn_and_terminate_force() {
367        let manager = TokioProcessManager::new();
368        let params = SpawnParams {
369            kind: ChildKind::External,
370            parent: None,
371            program: Some("sleep".to_string()),
372            args: vec!["10".to_string()], // Long sleep to test force kill
373            env: vec![],
374            cwd: None,
375            capabilities: CapabilityBundle::default(),
376        };
377        let handle = manager.spawn_child(params).await.unwrap();
378        // Terminate with force=true, should kill immediately
379        let result = manager.terminate_tree(handle.pid, true).await;
380        assert!(result.is_ok(), "force termination should succeed");
381    }
382}
383
384/* pid1-rs license:
385MIT License
386
387Copyright (c) 2023 FP Complete
388
389Permission is hereby granted, free of charge, to any person obtaining a copy
390of this software and associated documentation files (the "Software"), to deal
391in the Software without restriction, including without limitation the rights
392to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
393copies of the Software, and to permit persons to whom the Software is
394furnished to do so, subject to the following conditions:
395
396The above copyright notice and this permission notice shall be included in all
397copies or substantial portions of the Software.
398
399THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
400IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
401FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
402AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
403LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
404OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
405SOFTWARE.
406 */