use std::fs::{self, File};
use std::io;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::Path;
use std::time::SystemTime;
pub fn same_filesystem(a: &Path, b: &Path) -> bool {
match (fs::metadata(a), fs::metadata(b)) {
(Ok(a), Ok(b)) => a.dev() == b.dev(),
_ => false,
}
}
pub fn open_exclusive(path: &Path) -> io::Result<File> {
let file = fs::OpenOptions::new().read(true).write(true).open(path)?;
match file.try_lock() {
Ok(()) => Ok(file),
Err(fs::TryLockError::WouldBlock) => Err(io::ErrorKind::WouldBlock.into()),
Err(fs::TryLockError::Error(e)) => Err(e),
}
}
pub fn create_new_no_follow(path: &Path) -> io::Result<File> {
use std::os::unix::fs::OpenOptionsExt;
fs::OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.custom_flags(libc::O_NOFOLLOW)
.open(path)
}
pub fn open_existing_no_follow(path: &Path) -> io::Result<File> {
use std::os::unix::fs::OpenOptionsExt;
let file = fs::OpenOptions::new()
.read(true)
.write(true)
.custom_flags(libc::O_NOFOLLOW)
.open(path)?;
if !file.metadata()?.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"it is not a regular file",
));
}
Ok(file)
}
pub fn open_folder_no_follow(path: &Path) -> io::Result<File> {
use std::os::unix::fs::OpenOptionsExt;
fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_DIRECTORY)
.open(path)
}
pub fn unlock_folder(path: &Path) -> io::Result<()> {
let mode = fs::symlink_metadata(path)?.permissions().mode();
if mode & 0o700 == 0o700 {
return Ok(());
}
fs::set_permissions(path, fs::Permissions::from_mode(mode & 0o777 | 0o700))
}
pub fn allocated_bytes(path: &Path) -> io::Result<u64> {
Ok(fs::metadata(path)?.blocks() * 512)
}
pub fn local_time(
year: u16,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
) -> Option<SystemTime> {
let mut tm: libc::tm = unsafe { std::mem::zeroed() };
tm.tm_year = i32::from(year) - 1900;
tm.tm_mon = i32::from(month) - 1;
tm.tm_mday = day.into();
tm.tm_hour = hour.into();
tm.tm_min = minute.into();
tm.tm_sec = second.into();
tm.tm_isdst = -1;
match unsafe { libc::mktime(&mut tm) } {
-1 => None,
#[allow(clippy::unnecessary_cast)]
secs => crate::fsutil::from_epoch_secs(secs as i64),
}
}
pub fn link_count(path: &Path) -> io::Result<u64> {
Ok(fs::metadata(path)?.nlink())
}
pub fn name_problem(name: &str) -> Option<&'static str> {
if name.len() > 255 - ".hatchzip-part".len() {
return Some("the name is longer than this file system allows");
}
None
}
pub fn path_len(path: &Path) -> usize {
path.as_os_str().len()
}
pub fn sync_dir(dir: &Path) -> io::Result<()> {
File::open(dir)?.sync_all()
}
pub fn apply_mode(file: &File, mode: Option<u32>) -> io::Result<()> {
match mode {
Some(mode) => file.set_permissions(fs::Permissions::from_mode(mode & 0o777)),
None => Ok(()),
}
}
pub fn create_symlink(link: &Path, target: &Path) -> io::Result<()> {
match fs::symlink_metadata(link) {
Ok(_) => fs::remove_file(link)?,
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
std::os::unix::fs::symlink(target, link)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn links_and_existing_files_are_never_followed_or_replaced() {
let dir = std::env::temp_dir().join(format!("hatchzip-nofollow-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let file = dir.join("file");
fs::write(&file, b"kept").unwrap();
let link = dir.join("link");
std::os::unix::fs::symlink(&file, &link).unwrap();
let dangling = dir.join("dangling");
std::os::unix::fs::symlink(dir.join("nowhere"), &dangling).unwrap();
for p in [&file, &link, &dangling] {
let e = create_new_no_follow(p).unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::AlreadyExists, "{}", p.display());
}
assert!(!dir.join("nowhere").exists());
assert!(open_existing_no_follow(&link).is_err());
assert!(open_existing_no_follow(&dir).is_err());
assert!(open_existing_no_follow(&file).is_ok());
assert_eq!(fs::read(&file).unwrap(), b"kept");
assert!(create_new_no_follow(&dir.join("new")).is_ok());
fs::remove_dir_all(&dir).unwrap();
}
}