radio-cli 0.14.0

A lightweight terminal radio and podcast player
Documentation
use anyhow::Result;
use std::{fs, path::Path};

pub(crate) fn open_private_directory(path: &Path) -> std::io::Result<fs::File> {
    use std::{
        io,
        os::unix::fs::{MetadataExt, OpenOptionsExt},
    };
    let dir = fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NOFOLLOW | libc::O_DIRECTORY)
        .open(path)?;
    let meta = dir.metadata()?;
    if meta.mode() & 0o077 != 0 || meta.uid() != unsafe { libc::geteuid() } {
        return Err(io::Error::from(io::ErrorKind::PermissionDenied));
    }
    Ok(dir)
}

// Linux can publish without requiring hard-link support from the filesystem.
pub(crate) fn publish_noclobber(partial: &Path, final_path: &Path) -> Result<()> {
    #[cfg(target_os = "linux")]
    let publication = {
        use std::{ffi::CString, os::unix::ffi::OsStrExt};
        let from = CString::new(partial.as_os_str().as_bytes())?;
        let to = CString::new(final_path.as_os_str().as_bytes())?;
        let result = unsafe {
            // musl does not expose a renameat2 wrapper on every toolchain.
            libc::syscall(
                libc::SYS_renameat2,
                libc::AT_FDCWD,
                from.as_ptr(),
                libc::AT_FDCWD,
                to.as_ptr(),
                libc::RENAME_NOREPLACE,
            )
        };
        if result == 0 {
            Ok(())
        } else {
            Err(std::io::Error::last_os_error())
        }
    };
    #[cfg(not(target_os = "linux"))]
    let publication = fs::hard_link(partial, final_path);

    if let Err(error) = publication {
        if error.kind() != std::io::ErrorKind::AlreadyExists {
            return Err(error.into());
        }
        use std::os::unix::fs::MetadataExt;
        let source = fs::symlink_metadata(partial)?;
        let target = fs::symlink_metadata(final_path)?;
        // A crash between linking and unlinking leaves two names for the same
        // file. Resume only that case; equal contents or a symlink are not proof
        // that the existing destination belongs to this publication.
        if partial == final_path
            || !source.is_file()
            || !target.is_file()
            || source.dev() != target.dev()
            || source.ino() != target.ino()
        {
            return Err(error.into());
        }
        fs::remove_file(partial)?;
        return Ok(());
    }
    #[cfg(not(target_os = "linux"))]
    fs::remove_file(partial)?;
    Ok(())
}

// Install access rules before writing any bytes. Apply the returned mode
// after the write because the filesystem can clear mode bits on modification.
pub(crate) fn prepare_replacement_permissions(
    source: &fs::File,
    target: &fs::File,
) -> std::io::Result<fs::Permissions> {
    use std::os::unix::fs::{MetadataExt, fchown};

    let original = source.metadata()?;
    let replacement = target.metadata()?;
    let uid = (original.uid() != replacement.uid()).then_some(original.uid());
    let gid = (original.gid() != replacement.gid()).then_some(original.gid());
    if uid.is_some() || gid.is_some() {
        fchown(target, uid, gid)?;
    }
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    copy_access_acl(source, target)?;
    Ok(original.permissions())
}

#[cfg(target_os = "linux")]
fn copy_access_acl(source: &fs::File, target: &fs::File) -> std::io::Result<()> {
    use rustix::fs::{XattrFlags, fgetxattr, fremovexattr, fsetxattr};
    use rustix::io::Errno;

    let name = c"system.posix_acl_access";
    // Linux limits an extended attribute value to 64 KiB.
    let mut acl = vec![0; 64 * 1024];
    match fgetxattr(source, name, &mut acl[..]) {
        Ok(n) => fsetxattr(target, name, &acl[..n], XattrFlags::empty())?,
        Err(Errno::NODATA | Errno::NOTSUP) => {
            // Creation in the same directory can still inherit a different ACL.
            match fremovexattr(target, name) {
                Ok(()) | Err(Errno::NODATA | Errno::NOTSUP) => (),
                Err(error) => return Err(error.into()),
            }
        }
        Err(error) => return Err(error.into()),
    }
    Ok(())
}

#[cfg(target_os = "macos")]
fn copy_access_acl(source: &fs::File, target: &fs::File) -> std::io::Result<()> {
    use std::{ffi::c_void, io::Error, os::fd::AsRawFd};

    unsafe extern "C" {
        fn acl_get_fd(fd: libc::c_int) -> *mut c_void;
        fn acl_init(count: libc::c_int) -> *mut c_void;
        fn acl_set_fd(fd: libc::c_int, acl: *mut c_void) -> libc::c_int;
        fn acl_free(acl: *mut c_void) -> libc::c_int;
    }

    // Both descriptors remain open throughout. Each ACL allocated by libSystem
    // is released after acl_set_fd has copied its contents to the target.
    unsafe {
        let mut acl = acl_get_fd(source.as_raw_fd());
        if acl.is_null() {
            let error = Error::last_os_error();
            match error.raw_os_error() {
                Some(libc::ENOTSUP) => return Ok(()),
                Some(libc::ENOENT) => acl = acl_init(0),
                _ => return Err(error),
            }
            if acl.is_null() {
                return Err(Error::last_os_error());
            }
        }
        let result = acl_set_fd(target.as_raw_fd(), acl);
        let error = (result != 0).then(Error::last_os_error);
        acl_free(acl);
        error.map_or(Ok(()), Err)
    }
}