Skip to main content

hyprstream_tui/
shell.rs

1//! PTY-backed shell spawner.  Native only (not WASI).
2
3#![cfg(not(target_os = "wasi"))]
4
5use std::io::{self, Read, Write};
6use std::os::unix::io::{AsRawFd, FromRawFd};
7use std::path::{Path, PathBuf};
8use std::process::{Command, Stdio};
9use std::sync::mpsc::{self, Receiver, SyncSender};
10
11// ============================================================================
12// Public types
13// ============================================================================
14
15pub enum ShellInput {
16    Bytes(Vec<u8>),
17    Resize { cols: u16, rows: u16 },
18    Kill,
19}
20
21pub struct ShellWindow {
22    /// ANSI bytes from the PTY — poll with try_recv() in tick().
23    pub stdout_rx: Receiver<Vec<u8>>,
24    /// Send input bytes or control signals to the shell.
25    pub input_tx: SyncSender<ShellInput>,
26    /// OS PID for SIGTERM on close.
27    pub pid: u32,
28}
29
30// ============================================================================
31// Spawner
32// ============================================================================
33
34pub fn spawn_shell(cwd: Option<PathBuf>, cols: u16, rows: u16) -> io::Result<ShellWindow> {
35    let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_owned());
36
37    let (master_fd, slave_fd) = open_pty(cols, rows)?;
38
39    // Create all slave dups BEFORE wrapping in Stdio so we know their exact FD numbers.
40    // These three FDs will be dup2'd to stdin=0, stdout=1, stderr=2 by Rust's Command
41    // after the pre_exec callback runs.
42    let slave_dup1 = dup_fd(slave_fd)?;
43    let slave_dup2 = dup_fd(slave_fd)?;
44
45    let slave_in = unsafe { Stdio::from_raw_fd(slave_fd) };
46    let slave_out = unsafe { Stdio::from_raw_fd(slave_dup1) };
47    let slave_err = unsafe { Stdio::from_raw_fd(slave_dup2) };
48
49    let mut cmd = Command::new(&shell);
50    cmd.stdin(slave_in).stdout(slave_out).stderr(slave_err);
51    cmd.env("TERM", "xterm-256color");
52    if let Some(ref dir) = cwd {
53        cmd.current_dir(dir);
54    }
55
56    // Pre-compute sandbox paths in the parent (before fork) so no heap allocation
57    // occurs post-fork in the child process.  Both are Option<PathBuf> moved into the
58    // pre_exec closure.  sandbox_cwd = None means no sandboxing (plain shell tab).
59    //
60    // Sandbox support: Linux (Landlock) and OpenBSD (unveil).
61    // Other platforms leave cwd unused here; it was already consumed by current_dir above.
62    #[cfg(any(target_os = "linux", target_os = "openbsd"))]
63    let sandbox_cwd: Option<PathBuf> = cwd;
64    #[cfg(any(target_os = "linux", target_os = "openbsd"))]
65    let sandbox_home: Option<PathBuf> = std::env::var_os("HOME").map(PathBuf::from);
66    #[cfg(not(any(target_os = "linux", target_os = "openbsd")))]
67    let _ = cwd;
68
69    // FDs the child must keep open for Rust's stdio dup2 setup (happens after pre_exec).
70    let keep_fds = [slave_fd, slave_dup1, slave_dup2];
71
72    unsafe {
73        use std::os::unix::process::CommandExt;
74        cmd.pre_exec(move || {
75            libc::setsid();
76            libc::ioctl(slave_fd, libc::TIOCSCTTY, 0_i32);
77            // Close all inherited FDs > 2 except the three PTY slave FDs.
78            // Without this, the exec'd shell inherits ZMQ's internal socketpair FDs.
79            // When the shell eventually closes them, the parent's ZMQ signaler receives
80            // an unexpected EOF that triggers zmq_assert(dummy == 0) in recv_failable().
81            let mut rl = libc::rlimit {
82                rlim_cur: 0,
83                rlim_max: 0,
84            };
85            let soft_limit = if libc::getrlimit(libc::RLIMIT_NOFILE, &mut rl) == 0 {
86                rl.rlim_cur as i32
87            } else {
88                1024
89            };
90            let max_fd = soft_limit.min(65536);
91            for fd in 3..max_fd {
92                if !keep_fds.contains(&fd) {
93                    libc::close(fd);
94                }
95            }
96            // Apply filesystem sandboxing for scoped (worktree) terminals.
97            // Paths were pre-allocated in the parent; no heap allocation here.
98            // Linux: Landlock MAC.  OpenBSD: unveil(2).
99            #[cfg(any(target_os = "linux", target_os = "openbsd"))]
100            if let Some(ref wt) = sandbox_cwd {
101                apply_worktree_sandbox(wt, sandbox_home.as_deref());
102            }
103            Ok(())
104        });
105    }
106
107    // Allocate write_fd before spawn so it gets a fresh FD number above the slave FDs.
108    // This prevents write_fd from colliding with slave_fd after cmd's Drop closes slave_in.
109    let write_fd = dup_fd(master_fd)?;
110    let child = cmd.spawn()?;
111    let pid = child.id();
112    // slave_fd is owned by slave_in (passed into cmd); cmd's Drop closes it — no manual close.
113
114    let mut reader = unsafe { std::fs::File::from_raw_fd(master_fd) };
115    let mut writer = unsafe { std::fs::File::from_raw_fd(write_fd) };
116
117    let (stdout_tx, stdout_rx) = mpsc::sync_channel::<Vec<u8>>(64);
118    let (input_tx, input_rx) = mpsc::sync_channel::<ShellInput>(64);
119
120    // Reader: PTY master → stdout_tx
121    std::thread::spawn(move || {
122        let mut buf = [0u8; 4096];
123        loop {
124            match reader.read(&mut buf) {
125                Ok(0) | Err(_) => break,
126                Ok(n) => {
127                    if stdout_tx.send(buf[..n].to_vec()).is_err() {
128                        break;
129                    }
130                }
131            }
132        }
133    });
134
135    // Writer: input_rx → PTY master
136    std::thread::spawn(move || {
137        while let Ok(msg) = input_rx.recv() {
138            match msg {
139                ShellInput::Bytes(data) => {
140                    if writer.write_all(&data).is_err() {
141                        break;
142                    }
143                }
144                ShellInput::Resize { cols, rows } => {
145                    let ws = libc::winsize {
146                        ws_row: rows,
147                        ws_col: cols,
148                        ws_xpixel: 0,
149                        ws_ypixel: 0,
150                    };
151                    unsafe { libc::ioctl(writer.as_raw_fd(), libc::TIOCSWINSZ, &ws) };
152                }
153                ShellInput::Kill => break,
154            }
155        }
156    });
157
158    Ok(ShellWindow {
159        stdout_rx,
160        input_tx,
161        pid,
162    })
163}
164
165pub fn kill_shell(pid: u32) {
166    unsafe { libc::kill(pid as libc::pid_t, libc::SIGTERM) };
167}
168
169// ============================================================================
170// Helpers
171// ============================================================================
172
173fn open_pty(cols: u16, rows: u16) -> io::Result<(i32, i32)> {
174    let ws = libc::winsize {
175        ws_row: rows,
176        ws_col: cols,
177        ws_xpixel: 0,
178        ws_ypixel: 0,
179    };
180    let mut master: libc::c_int = -1;
181    let mut slave: libc::c_int = -1;
182    let ret = unsafe {
183        libc::openpty(
184            &mut master,
185            &mut slave,
186            std::ptr::null_mut(),
187            std::ptr::null(),
188            &ws,
189        )
190    };
191    if ret != 0 {
192        return Err(io::Error::last_os_error());
193    }
194    Ok((master, slave))
195}
196
197fn dup_fd(fd: i32) -> io::Result<i32> {
198    let new = unsafe { libc::dup(fd) };
199    if new < 0 {
200        Err(io::Error::last_os_error())
201    } else {
202        Ok(new)
203    }
204}
205
206// ============================================================================
207// Landlock sandbox (Linux only)
208// ============================================================================
209
210/// Restrict the current process's filesystem access to a model worktree.
211///
212/// Policy:
213/// - System paths (`/usr`, `/lib*`, `/bin`, `/etc`, `/proc`, `/dev`, …) — read + execute
214/// - `/tmp`           — read + execute only (no writes; avoids temp-file leakage)
215/// - `$HOME`          — read + execute only (shell init files; no history writes)
216/// - `worktree`       — full access (the model directory the terminal is scoped to)
217/// - everything else  — blocked (including other model worktrees)
218///
219/// Best-effort: if the running kernel does not support Landlock (< 5.13) or the
220/// process lacks permission, sandboxing is silently skipped.
221///
222/// # Safety
223/// Called from `pre_exec` (post-fork, pre-exec child).  All `PathBuf` arguments
224/// were allocated in the parent before the fork; no heap allocation occurs here.
225#[cfg(target_os = "linux")]
226fn apply_worktree_sandbox(worktree: &Path, home: Option<&Path>) {
227    use landlock::{
228        path_beneath_rules, Access, AccessFs, CompatLevel, Compatible, Ruleset, RulesetAttr,
229        RulesetCreatedAttr, ABI,
230    };
231
232    // ABI::V3 = Linux 5.19 (Truncate right).  The crate degrades gracefully on older ABIs.
233    let abi = ABI::V3;
234
235    // Read-only rights: open files + list directories + execute binaries.
236    let read_exec = AccessFs::from_read(abi);
237    // Full rights for this ABI level.
238    let full = AccessFs::from_all(abi);
239
240    // Standard system paths that a usable shell needs to read/execute.
241    // path_beneath_rules() silently skips paths that cannot be opened (e.g. /nix on non-NixOS).
242    let sys_paths: &[&Path] = &[
243        Path::new("/usr"),
244        Path::new("/lib"),
245        Path::new("/lib64"),
246        Path::new("/lib32"),
247        Path::new("/libx32"),
248        Path::new("/bin"),
249        Path::new("/sbin"),
250        Path::new("/etc"),
251        Path::new("/proc"),
252        Path::new("/dev"),
253        Path::new("/run"),
254        Path::new("/sys"),
255        Path::new("/nix"),
256        Path::new("/opt"),
257        Path::new("/snap"),
258    ];
259
260    // Best-effort: if any step fails (unsupported kernel, EPERM, …) just return.
261    let result = (|| {
262        let created = Ruleset::default()
263            .set_compatibility(CompatLevel::BestEffort)
264            .handle_access(full)?
265            .create()?;
266
267        // System paths: read + execute only.
268        let created = created.add_rules(path_beneath_rules(sys_paths, read_exec))?;
269
270        // /tmp: read + execute only (avoid leaking temp files across sessions).
271        let created = created.add_rules(path_beneath_rules(&[Path::new("/tmp")], read_exec))?;
272
273        // $HOME: read + execute only (shell init files; bash_history not written in sandboxed sessions).
274        let created = match home {
275            Some(h) => created.add_rules(path_beneath_rules(&[h], read_exec))?,
276            None => created,
277        };
278
279        // Worktree: full access — the user is here to work on this model.
280        let created = created.add_rules(path_beneath_rules(&[worktree], full))?;
281
282        created.restrict_self()
283    })();
284
285    // Silently discard errors (best-effort sandbox).
286    let _ = result;
287}
288
289/// Restrict the current process's filesystem access to a model worktree (OpenBSD).
290///
291/// Uses `unveil(2)` which is the direct OpenBSD equivalent of Linux Landlock:
292/// applied once pre-exec and inherited by the shell and all its children.
293///
294/// Policy mirrors the Linux implementation:
295/// - System paths — read + execute
296/// - `$HOME`       — read only (shell init files)
297/// - `worktree`    — full access
298/// - everything else — blocked (including other model worktrees)
299///
300/// `pledge(2)` is intentionally NOT called here: the spawned shell will set its
301/// own pledges, and pre-pledging would prevent the shell from expanding to the
302/// syscall set it needs for interactive use.
303///
304/// # Safety
305/// Called from `pre_exec` (post-fork, pre-exec child).  All `PathBuf` arguments
306/// were allocated in the parent before the fork; no heap allocation occurs here.
307#[cfg(target_os = "openbsd")]
308fn apply_worktree_sandbox(worktree: &Path, home: Option<&Path>) {
309    use std::ffi::CString;
310    use std::os::unix::ffi::OsStrExt;
311
312    // Open a path with the given unveil permissions.  Errors are silently ignored.
313    let do_unveil = |path: &Path, perms: &[u8]| {
314        let Ok(c_path) = CString::new(path.as_os_str().as_bytes()) else {
315            return;
316        };
317        unsafe { libc::unveil(c_path.as_ptr(), perms.as_ptr() as *const libc::c_char) };
318    };
319
320    // Standard system paths the shell needs to read/execute.
321    // /proc is not mounted by default on OpenBSD so is omitted.
322    let sys_paths: &[&str] = &[
323        "/usr", "/lib", "/libexec", // OpenBSD: ld.so lives here
324        "/bin", "/sbin", "/etc", "/dev",
325    ];
326    for &p in sys_paths {
327        do_unveil(Path::new(p), b"rx\0");
328    }
329
330    // /tmp: read + write + create (for shell temp files; no execute needed).
331    do_unveil(Path::new("/tmp"), b"rwc\0");
332
333    // $HOME: read only (shell init files; history not written in sandboxed sessions).
334    if let Some(h) = home {
335        do_unveil(h, b"r\0");
336    }
337
338    // Worktree: full access — read, write, execute, create/remove.
339    do_unveil(worktree, b"rwxc\0");
340
341    // Lock: calling unveil(NULL, NULL) prevents any further unveil calls and
342    // blocks access to all paths not already unveiled.
343    unsafe { libc::unveil(std::ptr::null(), std::ptr::null()) };
344}