use anyhow::{Context, Result};
use std::{fs, io, io::Write, path::Path};
pub(crate) fn write_atomic(path: &Path, data: &[u8], mode: Option<u32>) -> Result<()> {
let dir = path.parent().context("missing parent directory")?;
let temp = dir.join(format!("{}.tmp", uuid::Uuid::new_v4()));
let result = (|| -> Result<()> {
let mut options = fs::OpenOptions::new();
options.write(true).create_new(true);
if let Some(mode) = mode {
use std::os::unix::fs::OpenOptionsExt;
options.mode(mode);
}
let mut file = options.open(&temp)?;
file.write_all(data)?;
file.sync_all()?;
fs::rename(&temp, path)?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(temp);
}
result
}
pub(crate) fn open_nofollow_nonblock(path: &Path) -> io::Result<Option<fs::File>> {
use std::os::unix::fs::OpenOptionsExt;
match fs::File::options()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(path)
{
Ok(file) => Ok(Some(file)),
Err(e)
if matches!(
e.kind(),
io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied
) || matches!(e.raw_os_error(), Some(libc::ELOOP | libc::ENXIO)) =>
{
Ok(None)
}
Err(e) => Err(e),
}
}
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)
}
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 {
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)?;
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(())
}
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";
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) => {
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;
}
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)
}
}