#[cfg(unix)]
use std::ffi::{c_char, c_void, CStr};
use std::fs::File;
use std::io;
use std::path::Path;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FileMeta {
pub size: u64,
pub mode: u32,
pub mtime_sec: i64,
pub mtime_nsec: u32,
pub atime_sec: i64,
pub atime_nsec: u32,
}
pub fn open_basis(path: &Path) -> io::Result<Option<File>> {
match std::fs::symlink_metadata(path) {
Ok(meta) if meta.is_dir() => Ok(None),
Ok(_) => Ok(Some(File::open(path)?)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
}
}
pub fn remove_file_any(path: &Path) -> io::Result<()> {
match std::fs::remove_file(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
#[cfg(windows)]
{
if let Ok(meta) = std::fs::metadata(path) {
let mut perms = meta.permissions();
#[allow(clippy::permissions_set_readonly_false)]
perms.set_readonly(false);
let _ = std::fs::set_permissions(path, perms);
}
std::fs::remove_file(path)
}
#[cfg(not(windows))]
{
Err(e)
}
}
Err(e) => Err(e),
}
}
pub(crate) fn remove_path_if_exists(path: &Path) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(meta) if meta.is_dir() => std::fs::remove_dir_all(path),
Ok(_) => remove_file_any(path),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
#[must_use]
pub(crate) fn mtime_secs(meta: &std::fs::Metadata) -> u64 {
meta.modified()
.unwrap_or(std::time::SystemTime::UNIX_EPOCH)
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
#[must_use]
pub(crate) fn mtime_nsecs(meta: &std::fs::Metadata) -> u32 {
meta.modified()
.unwrap_or(std::time::SystemTime::UNIX_EPOCH)
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.map_or(0, |d| d.subsec_nanos())
}
#[must_use]
pub(crate) fn atime_secs(meta: &std::fs::Metadata) -> u64 {
meta.accessed()
.unwrap_or(std::time::SystemTime::UNIX_EPOCH)
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
#[must_use]
pub(crate) fn atime_nsecs(meta: &std::fs::Metadata) -> u32 {
meta.accessed()
.unwrap_or(std::time::SystemTime::UNIX_EPOCH)
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.map_or(0, |d| d.subsec_nanos())
}
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn apply_owner(
path: &Path,
uid: Option<u32>,
gid: Option<u32>,
is_symlink: bool,
) -> io::Result<()> {
#[cfg(unix)]
{
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
let (Some(uid), Some(gid)) = (uid, gid) else {
return Ok(());
};
if uid == unsafe { libc::geteuid() } && gid == unsafe { libc::getegid() } {
return Ok(());
}
let cpath = CString::new(path.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL byte"))?;
let rc = unsafe {
if is_symlink {
libc::lchown(cpath.as_ptr(), uid, gid)
} else {
libc::chown(cpath.as_ptr(), uid, gid)
}
};
if rc == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(not(unix))]
{
let _ = (path, uid, gid, is_symlink);
Ok(())
}
}
#[cfg(target_os = "linux")]
pub fn preallocate(file: &File, size: u64) -> io::Result<()> {
use std::os::fd::AsRawFd;
let off_size = i64::try_from(size).map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidInput,
"file size exceeds supported range",
)
})?;
let rc = unsafe { libc::posix_fallocate(file.as_raw_fd(), 0, off_size) };
if rc == 0 {
return Ok(());
}
if matches!(
rc,
libc::EINTR | libc::EOPNOTSUPP | libc::EINVAL | libc::ENOSYS
) {
file.set_len(size)
} else {
Err(io::Error::from_raw_os_error(rc))
}
}
#[cfg(all(unix, not(target_os = "macos")))]
fn xattr_list_size(path: &CStr) -> isize {
unsafe { libc::listxattr(path.as_ptr(), std::ptr::null_mut(), 0) }
}
#[cfg(target_os = "macos")]
fn xattr_list_size(path: &CStr) -> isize {
unsafe { libc::listxattr(path.as_ptr(), std::ptr::null_mut(), 0, 0) }
}
#[cfg(all(unix, not(target_os = "macos")))]
fn xattr_list(path: &CStr, list: *mut c_char, len: usize) -> isize {
unsafe { libc::listxattr(path.as_ptr(), list, len) }
}
#[cfg(target_os = "macos")]
fn xattr_list(path: &CStr, list: *mut c_char, len: usize) -> isize {
unsafe { libc::listxattr(path.as_ptr(), list, len, 0) }
}
#[cfg(all(unix, not(target_os = "macos")))]
fn xattr_get_size(path: &CStr, name: &CStr) -> isize {
unsafe { libc::getxattr(path.as_ptr(), name.as_ptr(), std::ptr::null_mut(), 0) }
}
#[cfg(target_os = "macos")]
fn xattr_get_size(path: &CStr, name: &CStr) -> isize {
unsafe { libc::getxattr(path.as_ptr(), name.as_ptr(), std::ptr::null_mut(), 0, 0, 0) }
}
#[cfg(all(unix, not(target_os = "macos")))]
fn xattr_get(path: &CStr, name: &CStr, value: *mut c_void, len: usize) -> isize {
unsafe { libc::getxattr(path.as_ptr(), name.as_ptr(), value, len) }
}
#[cfg(target_os = "macos")]
fn xattr_get(path: &CStr, name: &CStr, value: *mut c_void, len: usize) -> isize {
unsafe { libc::getxattr(path.as_ptr(), name.as_ptr(), value, len, 0, 0) }
}
#[cfg(all(unix, not(target_os = "macos")))]
fn xattr_set(path: &CStr, name: &CStr, value: *const c_void, len: usize) -> libc::c_int {
unsafe { libc::setxattr(path.as_ptr(), name.as_ptr(), value, len, 0) }
}
#[cfg(target_os = "macos")]
fn xattr_set(path: &CStr, name: &CStr, value: *const c_void, len: usize) -> libc::c_int {
unsafe { libc::setxattr(path.as_ptr(), name.as_ptr(), value, len, 0, 0) }
}
#[must_use]
pub fn collect_xattrs(path: &Path) -> Vec<(String, Vec<u8>)> {
#[cfg(unix)]
{
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
let Ok(cpath) = CString::new(path.as_os_str().as_bytes()) else {
return Vec::new();
};
let size = xattr_list_size(&cpath);
if size <= 0 {
return Vec::new();
}
let mut buf = vec![0u8; usize::try_from(size).unwrap_or(0)];
let n = xattr_list(&cpath, buf.as_mut_ptr().cast(), buf.len());
if n <= 0 {
return Vec::new();
}
buf.truncate(usize::try_from(n).unwrap_or(0));
let mut out = Vec::new();
for name in buf.split(|&b| b == 0).filter(|s| !s.is_empty()) {
let Ok(name) = std::ffi::CString::new(name) else {
continue;
};
let vsize = xattr_get_size(&cpath, &name);
if vsize <= 0 {
continue;
}
let mut value = vec![0u8; usize::try_from(vsize).unwrap_or(0)];
let vn = xattr_get(&cpath, &name, value.as_mut_ptr().cast(), value.len());
if vn <= 0 {
continue;
}
value.truncate(usize::try_from(vn).unwrap_or(0));
out.push((name.to_string_lossy().into_owned(), value));
}
out
}
#[cfg(not(unix))]
{
let _ = path;
Vec::new()
}
}
pub fn apply_xattrs(path: &Path, xattrs: &[(String, Vec<u8>)]) -> io::Result<()> {
#[cfg(unix)]
{
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
let Ok(cpath) = CString::new(path.as_os_str().as_bytes()) else {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL byte"));
};
let mut first_err: Option<io::Error> = None;
for (name, value) in xattrs {
let Ok(cname) = std::ffi::CString::new(name.as_str()) else {
continue;
};
let rc = xattr_set(&cpath, &cname, value.as_ptr().cast(), value.len());
if rc != 0 && first_err.is_none() {
first_err = Some(io::Error::last_os_error());
}
}
match first_err {
Some(e) => Err(e),
None => Ok(()),
}
}
#[cfg(not(unix))]
{
let _ = (path, xattrs);
Ok(())
}
}
#[cfg(not(target_os = "linux"))]
pub fn preallocate(file: &File, size: u64) -> io::Result<()> {
file.set_len(size)
}
#[expect(clippy::fn_params_excessive_bools, reason = "the flags mirror the CLI one-to-one")]
pub fn apply_meta(
path: &Path,
meta: &FileMeta,
is_symlink: bool,
preserve_mode: bool,
preserve_times: bool,
preserve_atime: bool,
) -> io::Result<()> {
if preserve_mode {
apply_mode(path, meta.mode, is_symlink)?;
}
if preserve_times || preserve_atime {
apply_times(path, meta, preserve_times, preserve_atime, is_symlink)?;
}
Ok(())
}
#[cfg(unix)]
fn apply_mode(path: &Path, mode: u32, is_symlink: bool) -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
if is_symlink {
return Ok(());
}
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
}
#[cfg(not(unix))]
#[allow(clippy::unnecessary_wraps)]
fn apply_mode(_path: &Path, _mode: u32, _is_symlink: bool) -> io::Result<()> {
Ok(())
}
pub fn create_special(
path: &Path,
kind: crate::protocol::FileKind,
rdev: Option<u64>,
mode: u32,
) -> io::Result<()> {
#[cfg(unix)]
{
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
let cpath = CString::new(path.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL byte"))?;
let rc = unsafe {
if kind == crate::protocol::FileKind::Fifo {
libc::mkfifo(
cpath.as_ptr(),
libc::mode_t::try_from(mode & 0o777).expect("mode fits mode_t"),
)
} else {
let type_bit = match kind {
crate::protocol::FileKind::Socket => libc::S_IFSOCK,
crate::protocol::FileKind::BlockDevice => libc::S_IFBLK,
crate::protocol::FileKind::CharDevice => libc::S_IFCHR,
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"not a special file kind",
))
}
};
#[allow(clippy::cast_possible_truncation)]
libc::mknod(
cpath.as_ptr(),
type_bit | libc::mode_t::try_from(mode & 0o777).expect("mode fits mode_t"),
rdev.unwrap_or(0) as libc::dev_t,
)
}
};
if rc == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(not(unix))]
{
let _ = (path, kind, rdev, mode);
Ok(())
}
}
#[cfg(unix)]
fn apply_times(
path: &Path,
meta: &FileMeta,
preserve_times: bool,
preserve_atime: bool,
is_symlink: bool,
) -> io::Result<()> {
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
let cpath = CString::new(path.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL byte"))?;
let times = [
if preserve_atime {
libc::timespec {
tv_sec: meta.atime_sec,
tv_nsec: meta.atime_nsec.into(),
}
} else {
libc::timespec {
tv_sec: 0,
tv_nsec: libc::UTIME_OMIT,
}
},
if preserve_times {
libc::timespec {
tv_sec: meta.mtime_sec,
tv_nsec: meta.mtime_nsec.into(),
}
} else {
libc::timespec {
tv_sec: 0,
tv_nsec: libc::UTIME_OMIT,
}
},
];
let rc = unsafe {
if is_symlink {
libc::utimensat(
libc::AT_FDCWD,
cpath.as_ptr(),
times.as_ptr(),
libc::AT_SYMLINK_NOFOLLOW,
)
} else {
libc::utimensat(libc::AT_FDCWD, cpath.as_ptr(), times.as_ptr(), 0)
}
};
if rc == 0 {
return Ok(());
}
let err = io::Error::last_os_error();
if matches!(err.raw_os_error(), Some(libc::EINTR)) {
let rc = unsafe {
if is_symlink {
libc::utimensat(
libc::AT_FDCWD,
cpath.as_ptr(),
times.as_ptr(),
libc::AT_SYMLINK_NOFOLLOW,
)
} else {
libc::utimensat(libc::AT_FDCWD, cpath.as_ptr(), times.as_ptr(), 0)
}
};
if rc == 0 {
return Ok(());
}
}
Err(err)
}
#[cfg(not(unix))]
fn apply_times(
path: &Path,
meta: &FileMeta,
preserve_times: bool,
preserve_atime: bool,
_is_symlink: bool,
) -> io::Result<()> {
use std::fs::{FileTimes, OpenOptions};
use std::time::{Duration, UNIX_EPOCH};
let mut times = FileTimes::new();
if preserve_times {
let modified = UNIX_EPOCH
.checked_add(Duration::new(u64::try_from(meta.mtime_sec).unwrap_or(0), meta.mtime_nsec))
.unwrap_or(UNIX_EPOCH);
times = times.set_modified(modified);
}
if preserve_atime {
let accessed = UNIX_EPOCH
.checked_add(Duration::new(u64::try_from(meta.atime_sec).unwrap_or(0), meta.atime_nsec))
.unwrap_or(UNIX_EPOCH);
times = times.set_accessed(accessed);
}
#[cfg(windows)]
if std::fs::symlink_metadata(path).is_ok_and(|m| m.is_dir()) {
use std::os::windows::fs::OpenOptionsExt;
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
let dir = OpenOptions::new()
.write(true)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(path)?;
return dir.set_times(times);
}
let file = OpenOptions::new().write(true).open(path)?;
file.set_times(times)
}
pub fn sync_dir(path: &Path) -> io::Result<()> {
#[cfg(target_os = "linux")]
{
std::fs::File::open(path)?.sync_all()
}
#[cfg(target_os = "windows")]
{
use std::os::windows::fs::OpenOptionsExt;
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
let dir = std::fs::OpenOptions::new()
.write(true)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(path)?;
dir.sync_all()
}
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
{
let _ = path;
Ok(())
}
}
#[cfg(unix)]
pub fn enlarge_pipe<F: std::os::fd::AsRawFd>(fd: &F) {
const F_SETPIPE_SZ: libc::c_int = 1031;
let _ = unsafe { libc::fcntl(fd.as_raw_fd(), F_SETPIPE_SZ, 1024 * 1024) };
}
#[cfg(not(unix))]
pub fn enlarge_pipe<F>(fd: &F) {
let _ = fd;
}
#[must_use]
pub(crate) fn sig_cache_dir() -> Option<std::path::PathBuf> {
#[cfg(windows)]
{
std::env::var_os("LOCALAPPDATA")
.map(std::path::PathBuf::from)
.or_else(|| {
std::env::var_os("USERPROFILE")
.map(|h| std::path::PathBuf::from(h).join("AppData").join("Local"))
})
.map(|base| base.join("cp2").join("sig-cache"))
}
#[cfg(not(windows))]
{
std::env::var_os("HOME").map(|h| {
std::path::PathBuf::from(h)
.join(".cache")
.join("cp2")
.join("sig-cache")
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prealloc_sets_len() {
use std::fs::OpenOptions;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("p.bin");
let file = OpenOptions::new()
.create(true)
.truncate(true)
.read(true)
.write(true)
.open(&path)
.unwrap();
preallocate(&file, 1 << 20).unwrap();
assert_eq!(file.metadata().unwrap().len(), 1 << 20);
}
#[cfg(unix)]
#[test]
fn apply_owner_skips_self_and_fails_foreign() {
use std::os::unix::fs::MetadataExt;
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("f");
std::fs::write(&file, b"x").unwrap();
let meta = std::fs::metadata(&file).unwrap();
let uid = meta.uid();
let gid = meta.gid();
assert!(apply_owner(&file, Some(uid), Some(gid), false).is_ok());
if unsafe { libc::geteuid() } == 0 {
return; }
let err = apply_owner(&file, Some(uid.wrapping_add(1)), Some(gid), false).unwrap_err();
assert_eq!(err.raw_os_error(), Some(libc::EPERM));
}
#[test]
fn open_basis_treats_dir_and_missing_as_none() {
let dir = tempfile::tempdir().unwrap();
assert!(open_basis(&dir.path().join("nope")).unwrap().is_none());
let sub = dir.path().join("sub");
std::fs::create_dir(&sub).unwrap();
assert!(open_basis(&sub).unwrap().is_none());
let file = dir.path().join("f.bin");
std::fs::write(&file, b"data").unwrap();
let basis = open_basis(&file).unwrap();
assert!(basis.is_some());
drop(basis);
}
}