use std::sync::atomic::{AtomicBool, Ordering};
use std::{fs, io, os::unix::fs::MetadataExt, path::Path};
use uuid::Uuid;
#[cfg(any(target_os = "linux", target_os = "macos"))]
const MARKER: &std::ffi::CStr = c"user.radio-cli.download-id";
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Ownership {
Missing,
Legacy,
Unverified,
Verified,
}
pub(super) fn stamp(file: &fs::File) -> io::Result<String> {
let meta = file.metadata()?;
let identity = format!("{}:{}", meta.dev(), meta.ino());
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
use rustix::fs::{XattrFlags, fsetxattr};
let marker = Uuid::new_v4();
match fsetxattr(file, MARKER, marker.as_bytes(), XattrFlags::empty()) {
Ok(()) => {
file.sync_all()?;
return Ok(format!("{identity}:{marker}"));
}
Err(rustix::io::Errno::NOTSUP) => (),
#[cfg(target_os = "macos")]
Err(rustix::io::Errno::OPNOTSUPP) => (),
Err(error) => return Err(error.into()),
}
}
Ok(identity)
}
pub(super) fn inspect(path: &Path, recorded: Option<&str>) -> io::Result<Ownership> {
let meta = match fs::symlink_metadata(path) {
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Ownership::Missing),
result => result?,
};
if !meta.is_file() {
return Ok(Ownership::Unverified);
}
let identity = format!("{}:{}", meta.dev(), meta.ino());
if recorded.is_none() || recorded == Some(&identity) {
return Ok(Ownership::Legacy);
}
if let Some((expected, token)) = recorded.and_then(marked_identity)
&& expected == identity
&& has_marker(path, token)?
{
return Ok(Ownership::Verified);
}
Ok(Ownership::Unverified)
}
pub(super) fn content_receipt(file: &fs::File, stop: &AtomicBool) -> anyhow::Result<String> {
use sha2::{Digest, Sha256};
use std::os::unix::fs::FileExt;
let meta = file.metadata()?;
let mut hash = Sha256::new();
let mut buffer = [0u8; 64 * 1024];
let mut offset = 0;
loop {
if stop.load(Ordering::Relaxed) {
return Err(crate::error::DomainError::new(crate::error::ErrorCode::Cancelled).into());
}
let n = file.read_at(&mut buffer, offset)?;
if n == 0 {
break;
}
hash.update(&buffer[..n]);
offset += n as u64;
}
anyhow::ensure!(
offset == meta.len(),
"{}",
crate::t!("podcast_invalid_download")
);
Ok(format!(
"{}:{}:sha256:{:x}",
meta.dev(),
meta.ino(),
hash.finalize()
))
}
pub(super) fn matches_receipt(
path: &Path,
recorded: Option<&str>,
bytes: u64,
stop: &AtomicBool,
) -> anyhow::Result<bool> {
use std::os::unix::fs::OpenOptionsExt;
let Some((identity, _)) = recorded.and_then(|s| s.split_once(":sha256:")) else {
return Ok(false);
};
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
) || e.raw_os_error() == Some(libc::ELOOP) =>
{
return Ok(false);
}
Err(e) => return Err(e.into()),
};
let meta = file.metadata()?;
if !meta.is_file()
|| meta.len() != bytes
|| identity != format!("{}:{}", meta.dev(), meta.ino())
|| Some(content_receipt(&file, stop)?.as_str()) != recorded
{
return Ok(false);
}
let named = match fs::symlink_metadata(path) {
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
result => result?,
};
Ok((
meta.dev(),
meta.ino(),
meta.ctime(),
meta.ctime_nsec(),
meta.len(),
) == (
named.dev(),
named.ino(),
named.ctime(),
named.ctime_nsec(),
named.len(),
))
}
pub(super) fn marked_identity(recorded: &str) -> Option<(&str, Uuid)> {
let (identity, token) = recorded.rsplit_once(':')?;
Some((identity, Uuid::parse_str(token).ok()?))
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn has_marker(path: &Path, token: Uuid) -> io::Result<bool> {
marker_matches(token, |value| rustix::fs::lgetxattr(path, MARKER, value))
}
pub(super) fn matches_file(file: &fs::File, recorded: &str) -> io::Result<bool> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
if let Some((identity, token)) = marked_identity(recorded) {
return marked_file(file, identity, token);
}
let meta = file.metadata()?;
Ok(meta.is_file() && recorded == format!("{}:{}", meta.dev(), meta.ino()))
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(super) fn marked_file(file: &fs::File, identity: &str, token: Uuid) -> io::Result<bool> {
let meta = file.metadata()?;
Ok(meta.is_file()
&& identity == format!("{}:{}", meta.dev(), meta.ino())
&& marker_matches(token, |value| rustix::fs::fgetxattr(file, MARKER, value))?)
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn marker_matches(
token: Uuid,
read: impl FnOnce(&mut [u8]) -> rustix::io::Result<usize>,
) -> io::Result<bool> {
use rustix::io::Errno;
#[cfg(target_os = "linux")]
const ABSENT: Errno = Errno::NODATA;
#[cfg(target_os = "macos")]
const ABSENT: Errno = Errno::NOATTR;
let mut value = [0; 16];
match read(&mut value) {
Ok(n) => Ok(&value[..n] == token.as_bytes()),
Err(ABSENT | Errno::NOTSUP | Errno::NOENT | Errno::RANGE | Errno::ACCESS) => Ok(false),
#[cfg(target_os = "macos")]
Err(Errno::OPNOTSUPP) => Ok(false),
Err(error) => Err(error.into()),
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn has_marker(_: &Path, _: Uuid) -> io::Result<bool> {
Ok(false)
}