gent-link 0.2.24

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
use anyhow::{Context, Result, ensure};
use rustix::fs::{
    AtFlags, CWD, FileType, Mode, OFlags, RenameFlags, mkdirat, openat, renameat_with, statat,
    unlinkat,
};
use std::{
    ffi::OsStr,
    fs::File,
    io::{self, Read},
    os::unix::fs::MetadataExt,
    path::Path,
};
use zeroize::Zeroizing;

// Resolve parent aliases (such as /tmp on macOS) once, then use the pinned
// directory for all operations. Only the final file must never follow a link.
fn parent(path: &Path) -> Result<(File, &OsStr)> {
    ensure!(path != Path::new("-"), "a file path is required");
    let name = path.file_name().context("expected a file name")?;
    let parent = path.parent().context("missing parent")?;
    let parent = if parent.as_os_str().is_empty() {
        Path::new(".")
    } else {
        parent
    };
    let dir = openat(
        CWD,
        parent,
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
        Mode::empty(),
    )?;
    Ok((dir.into(), name))
}

pub(super) fn read(
    path: &Path,
    limit: usize,
    private_identity: bool,
) -> Result<Zeroizing<Vec<u8>>> {
    let (directory, name) = parent(path)?;
    let before = statat(&directory, name, AtFlags::SYMLINK_NOFOLLOW)?;
    ensure!(
        FileType::from_raw_mode(before.st_mode) == FileType::RegularFile && before.st_nlink == 1,
        "input must be a regular file without links"
    );
    let file = File::from(openat(
        &directory,
        name,
        OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::NOCTTY | OFlags::CLOEXEC,
        Mode::empty(),
    )?);
    let opened = rustix::fs::fstat(&file)?;
    ensure!(
        opened.st_dev == before.st_dev && opened.st_ino == before.st_ino,
        "input changed while opening"
    );
    let meta = file.metadata()?;
    ensure!(
        meta.is_file() && meta.nlink() == 1,
        "input must be a regular file without links"
    );
    if private_identity {
        ensure!(
            crate::managed_file::owned_not_world_writable(&meta) && meta.mode() & 0o077 == 0,
            "identity must be a private file owned by this user"
        );
    }
    ensure!(
        (1..=limit as u64).contains(&meta.len()),
        "input is empty or exceeds the size limit"
    );
    let mut bytes = Zeroizing::new(Vec::with_capacity(limit + 1));
    (&file).take((limit + 1) as u64).read_to_end(&mut bytes)?;
    let after = file.metadata()?;
    ensure!(
        bytes.len() as u64 == meta.len()
            && after.len() == meta.len()
            && after.nlink() == 1
            && (after.ctime(), after.ctime_nsec()) == (meta.ctime(), meta.ctime_nsec()),
        "input changed while reading"
    );
    Ok(bytes)
}

pub(super) fn publish(path: &Path, write: impl FnOnce(&mut File) -> io::Result<()>) -> Result<()> {
    let (directory, name) = parent(path)?;
    // A private staging directory keeps the temporary file's name protected
    // even when the chosen destination directory is shared.
    let stage_name = format!(".gent-secret-{}", uuid::Uuid::new_v4());
    mkdirat(&directory, &stage_name, Mode::RWXU)?;
    let result = (|| -> Result<()> {
        let stage = File::from(openat(
            &directory,
            &stage_name,
            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
            Mode::empty(),
        )?);
        let meta = stage.metadata()?;
        ensure!(
            crate::managed_file::owned_not_world_writable(&meta) && meta.mode() & 0o077 == 0,
            "cannot secure the temporary output directory"
        );
        let mode = Mode::RUSR | Mode::WUSR;
        let mut file = File::from(openat(
            &stage,
            "value",
            OFlags::CREATE | OFlags::EXCL | OFlags::WRONLY | OFlags::CLOEXEC,
            mode,
        )?);
        let publish = (|| -> Result<()> {
            rustix::fs::fchmod(&file, mode)?;
            write(&mut file)?;
            file.sync_all()?;
            renameat_with(&stage, "value", &directory, name, RenameFlags::NOREPLACE)?;
            Ok(())
        })();
        if publish.is_err() {
            unlinkat(&stage, "value", AtFlags::empty())?;
        }
        publish
    })();
    unlinkat(&directory, &stage_name, AtFlags::REMOVEDIR)?;
    result?;
    directory.sync_all()?;
    Ok(())
}