radio-cli 0.14.0

A lightweight terminal radio and podcast player
Documentation
//! A checked public pathname can change before unlink. Move the directory
//! entry first, then authorize unlink only inside our private directory.
use super::download_ownership::Ownership;
use std::path::Path;

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(super) use supported::{claim, recover};

#[cfg(any(target_os = "linux", target_os = "macos"))]
mod supported {
    use super::*;
    use crate::podcast::download_ownership::{marked_file, marked_identity};
    use anyhow::{Context, Result};
    use rustix::fs::{self as at, AtFlags, CWD, Mode, OFlags, RenameFlags};
    use rustix::io::Errno;
    use std::{fs, io, os::unix::fs::DirBuilderExt};
    use uuid::Uuid;

    const ENTRY: &str = "audio";

    fn directory(path: &Path, token: Uuid) -> std::path::PathBuf {
        path.with_file_name(format!(".radio-remove-{token}"))
    }

    // The per-episode write transaction serializes access to this directory.
    // Never recursively clean it: an unrecognized entry must survive errors.
    fn finish(dir: &fs::File, path: &Path, identity: &str, token: Uuid) -> Result<Ownership> {
        let held = directory(path, token).join(ENTRY);
        let status = match at::statat(dir, ENTRY, AtFlags::SYMLINK_NOFOLLOW) {
            Ok(stat) => stat,
            Err(Errno::NOENT) => return Ok(Ownership::Missing),
            Err(e) => return Err(e.into()),
        };
        let verified = if at::FileType::from_raw_mode(status.st_mode) == at::FileType::RegularFile {
            match at::openat(
                dir,
                ENTRY,
                OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
                Mode::empty(),
            ) {
                Ok(fd) => marked_file(&fs::File::from(fd), identity, token),
                Err(e) => Err(e.into()),
            }
        } else {
            Ok(false)
        };
        if matches!(verified, Ok(true)) {
            at::unlinkat(dir, ENTRY, AtFlags::empty())?;
            return Ok(Ownership::Verified);
        }
        at::renameat_with(dir, ENTRY, CWD, path, RenameFlags::NOREPLACE)
            .with_context(|| crate::t!("podcast_download_restore", "path" => path.display(), "held" => held.display()))?;
        verified?;
        Ok(Ownership::Unverified)
    }

    pub(in crate::podcast) fn recover(path: &Path, recorded: Option<&str>) -> Result<()> {
        let Some((identity, token)) = recorded.and_then(marked_identity) else {
            return Ok(());
        };
        let holding = directory(path, token);
        let dir = match crate::files::open_private_directory(&holding) {
            Ok(dir) => dir,
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
            Err(e) => return Err(e.into()),
        };
        finish(&dir, path, identity, token)?;
        fs::remove_dir(holding)?;
        Ok(())
    }

    pub(in crate::podcast) fn claim(path: &Path, recorded: Option<&str>) -> Result<Ownership> {
        let Some((identity, token)) = recorded.and_then(marked_identity) else {
            return Ok(Ownership::Unverified);
        };
        let holding = directory(path, token);
        fs::DirBuilder::new().mode(0o700).create(&holding)?;
        let dir = crate::files::open_private_directory(&holding)?;
        let moved = at::renameat_with(CWD, path, &dir, ENTRY, RenameFlags::NOREPLACE);
        let result = match moved {
            Ok(()) => finish(&dir, path, identity, token)?,
            Err(Errno::NOENT) => Ownership::Missing,
            Err(e) => {
                fs::remove_dir(&holding)?;
                return Err(e.into());
            }
        };
        fs::remove_dir(holding)?;
        Ok(result)
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::podcast::download_ownership::{inspect, stamp};

        #[test]
        fn removal_rechecks_the_entry_moved_out_of_the_public_path() -> Result<()> {
            let root = tempfile::tempdir()?;
            let path = root.path().join("episode.audio");
            fs::write(&path, b"download")?;
            let record = stamp(&fs::File::open(&path)?)?;
            let Some(_) = marked_identity(&record) else {
                return Ok(());
            };
            assert!(inspect(&path, Some(&record))? == Ownership::Verified);
            fs::rename(&path, root.path().join("original"))?;
            fs::write(&path, b"replacement")?;

            assert!(claim(&path, Some(&record))? == Ownership::Unverified);
            assert_eq!(fs::read(&path)?, b"replacement");
            assert_eq!(fs::read(root.path().join("original"))?, b"download");
            Ok(())
        }

        #[test]
        fn interrupted_removal_preserves_both_files_when_restoration_conflicts() -> Result<()> {
            let root = tempfile::tempdir()?;
            let path = root.path().join("episode.audio");
            fs::write(&path, b"download")?;
            let record = stamp(&fs::File::open(&path)?)?;
            let Some((_, token)) = marked_identity(&record) else {
                return Ok(());
            };
            let holding = directory(&path, token);
            fs::DirBuilder::new().mode(0o700).create(&holding)?;
            let held = holding.join(ENTRY);
            // The claim completed just before the process exited. A second
            // writer has since occupied the public name.
            fs::write(&held, b"first replacement")?;
            fs::write(&path, b"second replacement")?;
            let err = recover(&path, Some(&record)).unwrap_err();
            assert!(err.to_string().contains(held.to_str().unwrap()));
            assert_eq!(fs::read(&path)?, b"second replacement");
            assert_eq!(fs::read(&held)?, b"first replacement");
            fs::remove_file(&path)?;
            recover(&path, Some(&record))?;
            assert_eq!(fs::read(&path)?, b"first replacement");
            assert!(!holding.exists());
            Ok(())
        }
    }
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub(super) fn recover(_: &Path, _: Option<&str>) -> anyhow::Result<()> {
    Ok(())
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub(super) fn claim(_: &Path, _: Option<&str>) -> anyhow::Result<Ownership> {
    Ok(Ownership::Unverified)
}