radio-cli 0.14.0

A lightweight terminal radio and podcast player
Documentation
use super::{
    download_ownership::{self, Ownership},
    download_removal, error,
};
use crate::store::Store;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::{
    fs, io,
    os::unix::fs::{DirBuilderExt, FileExt, MetadataExt, OpenOptionsExt},
    path::{Path, PathBuf},
};
use uuid::Uuid;

// The reservation commits before any bytes are written. Its token names a
// private directory next to the recorded destination, independent of its name.
#[derive(Serialize, Deserialize)]
pub(super) struct Stage {
    token: Uuid,
    identity: Option<String>,
}

impl Stage {
    fn key(id: &str) -> String {
        format!("podcast_download_stage:{id}")
    }

    pub(super) fn load(store: &Store, id: &str) -> Result<Option<Self>> {
        Ok(store
            .meta(&Self::key(id))?
            .map(|s| serde_json::from_str(&s))
            .transpose()?)
    }

    fn directory(&self, target: &Path) -> PathBuf {
        target.with_file_name(format!(".radio-download-{}", self.token))
    }

    pub(super) fn path(&self, target: &Path) -> PathBuf {
        self.directory(target).join("audio.part")
    }

    // The final file is initially published from this same inode. Do not
    // publish or complete using a reservation replaced by another attempt.
    pub(super) fn check_current(&self, store: &Store, id: &str) -> Result<()> {
        if Self::load(store, id)?.is_some_and(|s| s.token == self.token) {
            Ok(())
        } else {
            Err(crate::error::DomainError::new(crate::error::ErrorCode::Cancelled).into())
        }
    }

    // Caller holds the download transaction. Never adopt the public <id>.part.
    pub(super) fn reserve(store: &Store, id: &str, target: &Path) -> Result<(Self, u64)> {
        if let Some(stage) = Self::load(store, id)? {
            let path = stage.path(target);
            if stage.identity.is_some() && stage.owned(target)? {
                let meta = fs::symlink_metadata(&path)?;
                if meta.nlink() == 1 {
                    let offset = if meta.len() == 16 && stage.has_reservation_token(&path)? {
                        0
                    } else {
                        meta.len()
                    };
                    return Ok((stage, offset));
                }
            }
            stage.discard(target)?;
        }
        let stage = Self {
            token: Uuid::new_v4(),
            identity: None,
        };
        store.set_meta(&Self::key(id), &serde_json::to_string(&stage)?)?;
        Ok((stage, 0))
    }

    // Before registration commits, the only bytes in a new file are the
    // reservation UUID. A rollback leaves this proof available to the next
    // process even when the filesystem does not support extended attributes.
    fn has_reservation_token(&self, path: &Path) -> io::Result<bool> {
        let file = match fs::File::options()
            .read(true)
            .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
            .open(path)
        {
            Ok(file) => file,
            Err(e)
                if matches!(
                    e.kind(),
                    io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied
                ) || matches!(e.raw_os_error(), Some(libc::ELOOP | libc::ENXIO)) =>
            {
                return Ok(false);
            }
            Err(e) => return Err(e),
        };
        let meta = file.metadata()?;
        let mut bytes = [0; 16];
        if !meta.is_file() || meta.nlink() != 1 || meta.len() != bytes.len() as u64 {
            return Ok(false);
        }
        file.read_exact_at(&mut bytes, 0)?;
        Ok(&bytes == self.token.as_bytes())
    }

    fn owned(&self, target: &Path) -> Result<bool> {
        match crate::files::open_private_directory(&self.directory(target)) {
            Ok(_) => (),
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
            Err(e) => return Err(e.into()),
        }
        let path = self.path(target);
        let Some(identity) = self.identity.as_deref() else {
            return Ok(self.has_reservation_token(&path)?);
        };
        Ok(matches!(
            download_ownership::inspect(&path, Some(identity))?,
            Ownership::Verified | Ownership::Legacy
        ))
    }

    pub(super) fn open(
        &mut self,
        store: &Store,
        id: &str,
        target: &Path,
        offset: u64,
        stamp: fn(&fs::File) -> io::Result<String>,
    ) -> Result<fs::File> {
        self.check_current(store, id)?;
        let fresh = self.identity.is_none();
        if fresh {
            fs::DirBuilder::new()
                .mode(0o700)
                .create(self.directory(target))?;
        } else if !self.owned(target)? {
            return Err(error(crate::t!("podcast_file_exists")));
        }
        let file = fs::OpenOptions::new()
            .create_new(fresh)
            .read(true)
            .write(true)
            .append(offset > 0)
            // Publication keeps this inode's mode. The 0700 directory
            // protects the partial while the caller's umask governs the audio.
            .mode(0o666)
            .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
            .open(self.path(target))?;
        let meta = file.metadata()?;
        if !meta.is_file() || meta.nlink() != 1 || (offset > 0 && meta.len() != offset) {
            return Err(error(crate::t!("podcast_file_exists")));
        }
        if let Some(identity) = &self.identity {
            if !download_ownership::matches_file(&file, identity)? {
                return Err(error(crate::t!("podcast_file_exists")));
            }
        } else {
            file.write_all_at(self.token.as_bytes(), 0)?;
            self.identity = Some(stamp(&file)?);
            store.set_meta(&Self::key(id), &serde_json::to_string(self)?)?;
        }
        Ok(file)
    }

    pub(super) fn is_unregistered(&self) -> bool {
        self.identity.is_none()
    }

    pub(super) fn identity(&self) -> &str {
        self.identity.as_deref().expect("opened staging file")
    }

    fn discard(&self, target: &Path) -> Result<()> {
        let directory = self.directory(target);
        match crate::files::open_private_directory(&directory) {
            Ok(_) => (),
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
            Err(e) => return Err(e.into()),
        }
        let path = self.path(target);
        download_removal::recover(&path, self.identity.as_deref())?;
        if self.owned(target)? {
            if self
                .identity
                .as_deref()
                .and_then(download_ownership::marked_identity)
                .is_some()
            {
                download_removal::claim(&path, self.identity.as_deref())?;
            } else {
                // The unmarked inode lives inside our reserved, private directory.
                fs::remove_file(&path)?;
            }
        }
        match fs::remove_dir(directory) {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == io::ErrorKind::DirectoryNotEmpty => Ok(()),
            Err(e) => Err(e.into()),
        }
    }

    pub(super) fn clear(store: &Store, id: &str, target: &Path) -> Result<()> {
        if let Some(stage) = Self::load(store, id)? {
            stage.discard(target)?;
            store
                .conn
                .execute("DELETE FROM meta WHERE key=?1", [Self::key(id)])?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_committed_reservation_token_is_never_used_as_a_range_offset() -> Result<()> {
        let root = tempfile::tempdir()?;
        let store = Store::open(&root.path().join("radio.db"))?;
        let target = root.path().join("episode.audio");
        let (mut stage, _) = Stage::reserve(&store, "episode", &target)?;
        let file = stage.open(&store, "episode", &target, 0, download_ownership::stamp)?;

        // The process exited after registration committed and before truncation.
        assert_eq!(Stage::reserve(&store, "episode", &target)?.1, 0);
        file.write_all_at(&[0; 16], 0)?;
        assert_eq!(Stage::reserve(&store, "episode", &target)?.1, 16);
        Ok(())
    }

    #[test]
    fn an_unregistered_stage_preserves_a_foreign_file_of_the_same_length() -> Result<()> {
        let root = tempfile::tempdir()?;
        let store = Store::open(&root.path().join("radio.db"))?;
        let target = root.path().join("episode.audio");
        let (stage, _) = Stage::reserve(&store, "episode", &target)?;
        fs::DirBuilder::new()
            .mode(0o700)
            .create(stage.directory(&target))?;
        let path = stage.path(&target);
        fs::write(&path, [0; 16])?;
        Stage::clear(&store, "episode", &target)?;
        assert_eq!(fs::read(path)?, [0; 16]);
        Ok(())
    }
}