Skip to main content

subc_os/
script_pipe.rs

1//! Identity-bearing Unix script transport. The receiver validates before adopting
2//! a descriptor because runtimes may reuse inherited descriptor numbers for IPC.
3
4use std::{fs::File, io};
5
6pub const SCRIPT_FD_ENV: &str = "SUBC_SCRIPT_FD";
7pub const SCRIPT_FD: i32 = 6;
8
9/// Create close-on-exec sources; only ChildDescriptorSlots makes the reader
10/// inheritable in the intended child. Payload writes happen after spawn.
11#[cfg(unix)]
12pub fn handoff() -> io::Result<(std::os::fd::OwnedFd, File, String)> {
13    use std::os::unix::fs::MetadataExt;
14    let (reader, writer) = io::pipe()?;
15    let reader = crate::registration_channel::outside_child_slots(reader.into())?;
16    let file = File::from(reader);
17    let inode = file.metadata()?.ino();
18    Ok((
19        file.into(),
20        File::from(std::os::fd::OwnedFd::from(writer)),
21        format!("{SCRIPT_FD}:{inode}"),
22    ))
23}
24
25/// Take a pipe only after its type and inode match the advertised identity.
26/// A refusal leaves the descriptor untouched.
27#[cfg(unix)]
28#[allow(unsafe_code)]
29pub fn take(value: &str) -> io::Result<File> {
30    use std::os::fd::{BorrowedFd, FromRawFd};
31    use std::os::unix::fs::{FileTypeExt, MetadataExt};
32    let invalid = || io::Error::new(io::ErrorKind::InvalidInput, "invalid script pipe identity");
33    let (fd, inode) = value.split_once(':').ok_or_else(invalid)?;
34    let fd: i32 = fd.parse().map_err(|_| invalid())?;
35    let inode: u64 = inode.parse().map_err(|_| invalid())?;
36    if fd < 3 {
37        return Err(invalid());
38    }
39    // SAFETY: borrowing performs no I/O or ownership transfer. fstat checks
40    // validity before the descriptor is adopted, as in the nonce reader.
41    let borrowed = unsafe { BorrowedFd::borrow_raw(fd) };
42    let copy = borrowed.try_clone_to_owned()?;
43    let metadata = File::from(copy).metadata()?;
44    if !metadata.file_type().is_fifo() || metadata.ino() != inode {
45        return Err(invalid());
46    }
47    // SAFETY: validation succeeded; the caller transfers this descriptor once.
48    let file = unsafe { File::from_raw_fd(fd) };
49    rustix::io::fcntl_setfd(&file, rustix::io::FdFlags::CLOEXEC)?;
50    Ok(file)
51}
52
53/// Open only a local named pipe owned by the advertised daemon process.
54#[cfg(windows)]
55#[allow(unsafe_code)]
56pub fn connect(name: &str, daemon_pid: u32) -> io::Result<File> {
57    use std::os::windows::{fs::OpenOptionsExt, io::AsRawHandle};
58    use windows_sys::Win32::{
59        Storage::FileSystem::{
60            GetFileType, FILE_TYPE_PIPE, SECURITY_IDENTIFICATION, SECURITY_SQOS_PRESENT,
61        },
62        System::Pipes::GetNamedPipeServerProcessId,
63    };
64    if !name.starts_with(r"\\.\pipe\") || daemon_pid == 0 {
65        return Err(io::Error::new(
66            io::ErrorKind::InvalidInput,
67            "invalid script pipe identity",
68        ));
69    }
70    let file = std::fs::OpenOptions::new()
71        .read(true)
72        .custom_flags(SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION)
73        .open(name)?;
74    let mut server = 0;
75    // SAFETY: file retains the connected handle and server is writable.
76    if unsafe { GetFileType(file.as_raw_handle()) } != FILE_TYPE_PIPE
77        || unsafe { GetNamedPipeServerProcessId(file.as_raw_handle(), &mut server) } == 0
78        || server != daemon_pid
79    {
80        return Err(io::Error::new(
81            io::ErrorKind::PermissionDenied,
82            "script pipe server is not the daemon",
83        ));
84    }
85    Ok(file)
86}
87
88#[cfg(all(test, unix))]
89mod tests {
90    use super::*;
91    use std::os::fd::AsRawFd;
92
93    #[test]
94    fn script_pipe_handoff_names_fifo_and_keeps_sources_above_reserved_slots() {
95        let (reader, writer, metadata) = handoff().unwrap();
96        assert!(reader.as_raw_fd() > SCRIPT_FD);
97        let file = File::from(reader);
98        use std::os::unix::fs::{FileTypeExt, MetadataExt};
99        let stat = file.metadata().unwrap();
100        assert!(stat.file_type().is_fifo());
101        assert_eq!(metadata, format!("6:{}", stat.ino()));
102        drop(writer);
103    }
104
105    #[test]
106    fn script_pipe_wrong_identity_does_not_take_descriptor() {
107        let (reader, writer, _) = handoff().unwrap();
108        let fd = reader.as_raw_fd();
109        assert!(take(&format!("{fd}:0")).is_err());
110        assert!(File::from(reader).metadata().is_ok());
111        drop(writer);
112    }
113
114    #[test]
115    fn script_pipe_slot_six_survives_spawn_and_is_not_runtime_ipc_slot() {
116        let (reader, mut writer, metadata) = handoff().unwrap();
117        use std::io::Write;
118        writer.write_all(b"transport").unwrap();
119        drop(writer);
120        let mut command = std::process::Command::new("/bin/sh");
121        command.args(["-c", "read value <&6; test \"$value\" = transport"]);
122        let mut slots = crate::registration_channel::ChildDescriptorSlots::default();
123        slots.script(reader).unwrap();
124        slots.install(&mut command);
125        assert!(metadata.starts_with("6:"));
126        assert!(command.status().unwrap().success());
127    }
128}
129
130#[cfg(all(test, windows))]
131mod windows_tests {
132    use super::*;
133
134    #[test]
135    fn script_pipe_checks_local_name_and_server_process_before_reading() {
136        assert!(connect(r"\\remote\pipe\script", std::process::id()).is_err());
137        for correct in [false, true] {
138            let pipe = crate::registration_channel::RegistrationPipe::new().unwrap();
139            let name = pipe.name().to_owned();
140            let pid = std::process::id();
141            let server = std::thread::spawn(move || {
142                pipe.accept(
143                    pid,
144                    std::time::Instant::now() + std::time::Duration::from_secs(5),
145                )
146            });
147            let client = connect(&name, if correct { pid } else { pid + 1 });
148            assert_eq!(client.is_ok(), correct);
149            let accepted = server.join().unwrap();
150            if correct {
151                assert!(accepted.is_ok());
152            }
153            drop(client);
154            drop(accepted);
155        }
156    }
157}