pub(crate) mod xattr;
use core::ffi::{CStr, c_char, c_int, c_uint, c_void};
use crate::fs::{
FileTimes, FileType, LockKind, Metadata, OpenOptions, RawDirEntry, Space, UnixMetadata,
};
use crate::path::with_cstr;
use crate::sys::io::fcntl;
use crate::sys::{cvt, cvt_long, errno, last_error};
use crate::time::Timestamp;
use crate::{AsHandle, BorrowedHandle, Error, ErrorKind, OwnedHandle, Result};
const O_WRONLY: c_int = 0x1;
const O_RDWR: c_int = 0x2;
const O_APPEND: c_int = 0x8;
const O_NOFOLLOW: c_int = 0x100;
const O_CREAT: c_int = 0x200;
const O_TRUNC: c_int = 0x400;
const O_EXCL: c_int = 0x800;
const O_DIRECTORY: c_int = 0x10_0000;
const O_CLOEXEC: c_int = 0x100_0000;
const F_FULLFSYNC: c_int = 51;
const F_PREALLOCATE: c_int = 42;
const F_ALLOCATEALL: c_uint = 0x4;
const F_PEOFPOSMODE: c_int = 3;
const COPYFILE_DATA: u32 = 1 << 3;
const COPYFILE_ALL: u32 = (1 << 0) | (1 << 1) | (1 << 2) | COPYFILE_DATA;
const COPYFILE_STATE_COPIED: u32 = 8;
#[repr(C)]
struct Fstore {
flags: c_uint,
posmode: c_int,
offset: i64,
length: i64,
bytesalloc: i64,
}
#[repr(C)]
struct Statfs {
bsize: u32,
iosize: i32,
blocks: u64,
bfree: u64,
bavail: u64,
files: u64,
ffree: u64,
fsid: [i32; 2],
owner: u32,
kind: u32,
flags: u32,
fssubtype: u32,
fstypename: [u8; 16],
mntonname: [u8; 1024],
mntfromname: [u8; 1024],
flags_ext: u32,
reserved: [u32; 7],
}
const _: () = assert!(size_of::<Statfs>() == 2168);
const AT_FDCWD: c_int = -2;
const AT_SYMLINK_NOFOLLOW: c_int = 0x20;
const AT_REMOVEDIR: c_int = 0x80;
const S_IFMT: u32 = 0o170000;
const S_IFIFO: u32 = 0o010000;
const S_IFCHR: u32 = 0o020000;
const S_IFDIR: u32 = 0o040000;
const S_IFBLK: u32 = 0o060000;
const S_IFREG: u32 = 0o100000;
const S_IFLNK: u32 = 0o120000;
const S_IFSOCK: u32 = 0o140000;
const UTIME_OMIT: i64 = -2;
const LOCK_SH: c_int = 1;
const LOCK_EX: c_int = 2;
const LOCK_NB: c_int = 4;
const LOCK_UN: c_int = 8;
const PATH_MAX: usize = 1024;
#[derive(Clone, Copy)]
#[repr(C)]
struct Timespec {
sec: i64,
nsec: i64,
}
#[repr(C)]
struct Stat {
dev: i32,
mode: u16,
nlink: u16,
ino: u64,
uid: u32,
gid: u32,
rdev: i32,
atime: Timespec,
mtime: Timespec,
ctime: Timespec,
birthtime: Timespec,
size: i64,
blocks: i64,
blksize: i32,
flags: u32,
generation: u32,
lspare: i32,
qspare: [i64; 2],
}
const _: () = assert!(size_of::<Stat>() == 144);
#[repr(C)]
struct AttrList {
bitmapcount: u16,
reserved: u16,
commonattr: u32,
volattr: u32,
dirattr: u32,
fileattr: u32,
forkattr: u32,
}
const ATTR_BIT_MAP_COUNT: u16 = 5;
const ATTR_CMN_NAME: u32 = 0x0000_0001;
const ATTR_CMN_OBJTYPE: u32 = 0x0000_0008;
const ATTR_CMN_FILEID: u32 = 0x0200_0000;
const ATTR_CMN_RETURNED_ATTRS: u32 = 0x8000_0000;
unsafe extern "C" {
#[link_name = "open"]
fn c_open(path: *const c_char, flags: c_int, ...) -> c_int;
#[cfg_attr(target_arch = "x86_64", link_name = "fstat$INODE64")]
fn fstat(fd: c_int, stat: *mut Stat) -> c_int;
#[cfg_attr(target_arch = "x86_64", link_name = "stat$INODE64")]
fn stat(path: *const c_char, stat: *mut Stat) -> c_int;
#[cfg_attr(target_arch = "x86_64", link_name = "lstat$INODE64")]
fn lstat(path: *const c_char, stat: *mut Stat) -> c_int;
fn ftruncate(fd: c_int, len: i64) -> c_int;
fn fsync(fd: c_int) -> c_int;
fn chmod(path: *const c_char, mode: u16) -> c_int;
fn fchmod(fd: c_int, mode: u16) -> c_int;
fn futimens(fd: c_int, times: *const Timespec) -> c_int;
fn utimensat(dirfd: c_int, path: *const c_char, times: *const Timespec, flags: c_int) -> c_int;
fn flock(fd: c_int, operation: c_int) -> c_int;
fn mkdir(path: *const c_char, mode: u16) -> c_int;
fn rmdir(path: *const c_char) -> c_int;
fn unlink(path: *const c_char) -> c_int;
#[link_name = "rename"]
fn c_rename(from: *const c_char, to: *const c_char) -> c_int;
fn link(original: *const c_char, link: *const c_char) -> c_int;
#[link_name = "symlink"]
fn c_symlink(target: *const c_char, link: *const c_char) -> c_int;
fn readlink(path: *const c_char, buf: *mut c_char, len: usize) -> isize;
#[link_name = "realpath$DARWIN_EXTSN"]
fn realpath(path: *const c_char, resolved: *mut c_char) -> *mut c_char;
fn getcwd(buf: *mut c_char, len: usize) -> *mut c_char;
fn chdir(path: *const c_char) -> c_int;
#[cfg_attr(target_arch = "x86_64", link_name = "statfs$INODE64")]
fn statfs(path: *const c_char, stat: *mut Statfs) -> c_int;
#[cfg_attr(target_arch = "x86_64", link_name = "fstatfs$INODE64")]
fn fstatfs(fd: c_int, stat: *mut Statfs) -> c_int;
fn fclonefileat(source: c_int, dirfd: c_int, path: *const c_char, flags: u32) -> c_int;
fn fcopyfile(from: c_int, to: c_int, state: *mut c_void, flags: u32) -> c_int;
fn copyfile_state_alloc() -> *mut c_void;
fn copyfile_state_free(state: *mut c_void) -> c_int;
fn copyfile_state_get(state: *mut c_void, flag: u32, value: *mut c_void) -> c_int;
#[link_name = "chown"]
fn c_chown(path: *const c_char, uid: u32, gid: u32) -> c_int;
#[link_name = "lchown"]
fn c_lchown(path: *const c_char, uid: u32, gid: u32) -> c_int;
#[link_name = "fchown"]
fn c_fchown(fd: c_int, uid: u32, gid: u32) -> c_int;
#[link_name = "mkfifo"]
fn c_mkfifo(path: *const c_char, mode: u16) -> c_int;
fn openat(dirfd: c_int, path: *const c_char, flags: c_int, ...) -> c_int;
#[cfg_attr(target_arch = "x86_64", link_name = "fstatat$INODE64")]
fn fstatat(dirfd: c_int, path: *const c_char, stat: *mut Stat, flags: c_int) -> c_int;
fn fchmodat(dirfd: c_int, path: *const c_char, mode: u16, flags: c_int) -> c_int;
fn mkdirat(dirfd: c_int, path: *const c_char, mode: u16) -> c_int;
fn unlinkat(dirfd: c_int, path: *const c_char, flags: c_int) -> c_int;
fn renameat(from_dir: c_int, from: *const c_char, to_dir: c_int, to: *const c_char) -> c_int;
fn linkat(
original_dir: c_int,
original: *const c_char,
link_dir: c_int,
link: *const c_char,
flags: c_int,
) -> c_int;
fn symlinkat(target: *const c_char, dirfd: c_int, link: *const c_char) -> c_int;
fn readlinkat(dirfd: c_int, path: *const c_char, buf: *mut c_char, len: usize) -> isize;
fn getattrlistbulk(
dirfd: c_int,
attrs: *mut AttrList,
buf: *mut c_void,
len: usize,
options: u64,
) -> c_int;
}
pub(crate) fn is_separator(c: u8) -> bool {
c == b'/'
}
fn open_flags(options: &OpenOptions) -> c_int {
let mut flags = O_CLOEXEC;
flags |= match (options.read, options.write || options.append) {
(_, false) => 0, (false, true) => O_WRONLY,
(true, true) => O_RDWR,
};
if options.append {
flags |= O_APPEND;
}
if options.create_new {
flags |= O_CREAT | O_EXCL;
} else {
if options.create {
flags |= O_CREAT;
}
if options.truncate {
flags |= O_TRUNC;
}
}
if options.no_follow {
flags |= O_NOFOLLOW;
}
if options.directory {
flags |= O_DIRECTORY;
}
flags
}
pub(crate) fn open_at(
dir: BorrowedHandle<'_>,
path: &[u8],
options: &OpenOptions,
) -> Result<OwnedHandle> {
let flags = open_flags(options);
let dirfd = dir.as_raw();
with_cstr(path, |path| {
match cvt(unsafe { openat(dirfd, path.as_ptr(), flags, options.mode as c_uint) }) {
Ok(fd) => Ok(unsafe { OwnedHandle::from_raw(fd) }),
Err(error)
if error.raw_os_error() == errno::ENOTDIR
&& options.directory
&& options.no_follow
&& stat_with(|st| unsafe {
fstatat(dirfd, path.as_ptr(), st, AT_SYMLINK_NOFOLLOW)
})
.is_ok_and(|found| found.is_symlink()) =>
{
Err(Error::from_raw_os_error(errno::ELOOP))
}
Err(error) => Err(error),
}
})
}
pub(crate) fn open(path: &[u8], options: &OpenOptions) -> Result<OwnedHandle> {
let flags = open_flags(options);
with_cstr(path, |path| {
match cvt(unsafe { c_open(path.as_ptr(), flags, options.mode as c_uint) }) {
Ok(fd) => Ok(unsafe { OwnedHandle::from_raw(fd) }),
Err(error)
if error.raw_os_error() == errno::ENOTDIR
&& options.directory
&& options.no_follow
&& stat_with(|st| unsafe { lstat(path.as_ptr(), st) })
.is_ok_and(|found| found.is_symlink()) =>
{
Err(Error::from_raw_os_error(errno::ELOOP))
}
Err(error) => Err(error),
}
})
}
fn file_type(mode: u32) -> FileType {
match mode & S_IFMT {
S_IFREG => FileType::File,
S_IFDIR => FileType::Directory,
S_IFLNK => FileType::Symlink,
S_IFBLK => FileType::BlockDevice,
S_IFCHR => FileType::CharDevice,
S_IFIFO => FileType::Fifo,
S_IFSOCK => FileType::Socket,
_ => FileType::Unknown,
}
}
fn stat_with(call: impl FnOnce(*mut Stat) -> c_int) -> Result<Metadata> {
let mut st = core::mem::MaybeUninit::<Stat>::zeroed();
cvt(call(st.as_mut_ptr()))?;
let st = unsafe { st.assume_init() };
let time = |t: Timespec| Timestamp {
secs: t.sec,
nanos: t.nsec.clamp(0, 999_999_999) as u32,
};
let mode = st.mode as u32;
Ok(Metadata {
file_type: file_type(mode),
len: st.size as u64,
mode: mode & 0o7777,
modified: time(st.mtime),
accessed: time(st.atime),
created: Some(time(st.birthtime)),
links: st.nlink as u64,
device: st.dev as u64,
inode: st.ino,
raw: mode,
unix: UnixMetadata {
uid: st.uid,
gid: st.gid,
rdev: st.rdev as u64,
blocks: st.blocks as u64,
block_size: st.blksize as u32,
},
})
}
pub(crate) fn metadata(path: &[u8], follow: bool) -> Result<Metadata> {
with_cstr(path, |path| {
stat_with(|st| {
unsafe {
if follow {
stat(path.as_ptr(), st)
} else {
lstat(path.as_ptr(), st)
}
}
})
})
}
pub(crate) fn metadata_at(dir: BorrowedHandle<'_>, path: &[u8], follow: bool) -> Result<Metadata> {
let flags = if follow { 0 } else { AT_SYMLINK_NOFOLLOW };
with_cstr(path, |path| {
stat_with(|st| unsafe { fstatat(dir.as_raw(), path.as_ptr(), st, flags) })
})
}
pub(crate) fn handle_metadata(handle: BorrowedHandle<'_>) -> Result<Metadata> {
stat_with(|st| unsafe { fstat(handle.as_raw(), st) })
}
pub(crate) fn set_len(handle: BorrowedHandle<'_>, len: u64) -> Result<()> {
cvt(unsafe { ftruncate(handle.as_raw(), len as i64) })?;
Ok(())
}
fn raw_stat(handle: BorrowedHandle<'_>) -> Result<Stat> {
let mut st = core::mem::MaybeUninit::<Stat>::zeroed();
cvt(unsafe { fstat(handle.as_raw(), st.as_mut_ptr()) })?;
Ok(unsafe { st.assume_init() })
}
pub(crate) fn allocate(handle: BorrowedHandle<'_>, len: u64) -> Result<()> {
let st = raw_stat(handle)?;
let size = st.size.max(0) as u64;
let allocated = (st.blocks.max(0) as u64).saturating_mul(512);
if len > allocated {
let mut store = Fstore {
flags: F_ALLOCATEALL,
posmode: F_PEOFPOSMODE,
offset: 0,
length: (len - allocated) as i64,
bytesalloc: 0,
};
cvt(unsafe { fcntl(handle.as_raw(), F_PREALLOCATE, &raw mut store) })?;
}
if len > size {
set_len(handle, len)?;
}
Ok(())
}
fn space_with(call: impl FnOnce(*mut Statfs) -> c_int) -> Result<Space> {
let mut stat = core::mem::MaybeUninit::<Statfs>::zeroed();
cvt(call(stat.as_mut_ptr()))?;
let stat = unsafe { stat.assume_init() };
let unit = stat.bsize as u64;
Ok(Space {
total: stat.blocks.saturating_mul(unit),
free: stat.bfree.saturating_mul(unit),
available: stat.bavail.saturating_mul(unit),
})
}
pub(crate) fn space(path: &[u8]) -> Result<Space> {
with_cstr(path, |path| {
space_with(|stat| unsafe { statfs(path.as_ptr(), stat) })
})
}
pub(crate) fn handle_space(handle: BorrowedHandle<'_>) -> Result<Space> {
space_with(|stat| unsafe { fstatfs(handle.as_raw(), stat) })
}
pub(crate) fn copy(from: &[u8], to: &[u8]) -> Result<u64> {
const READ: OpenOptions = OpenOptions::new().read(true);
let source = open(from, &READ)?;
let source_meta = handle_metadata(source.as_handle())?;
if source_meta.is_dir() {
return Err(ErrorKind::IsADirectory.into());
}
let cloned = with_cstr(to, |to| {
Ok(unsafe { fclonefileat(source.as_raw(), AT_FDCWD, to.as_ptr(), 0) } == 0)
})?;
if cloned {
return Ok(source_meta.len);
}
let options = OpenOptions::new()
.write(true)
.create(true)
.mode(source_meta.mode);
let dest = open(to, &options)?;
let dest_meta = handle_metadata(dest.as_handle())?;
if (source_meta.device, source_meta.inode) == (dest_meta.device, dest_meta.inode) {
return Err(ErrorKind::InvalidInput.into());
}
let flags = if dest_meta.is_file() {
set_len(dest.as_handle(), 0)?;
COPYFILE_ALL
} else {
COPYFILE_DATA
};
let state = unsafe { copyfile_state_alloc() };
if state.is_null() {
return Err(ErrorKind::OutOfMemory.into());
}
let mut copied: i64 = 0;
let result = unsafe {
let result = cvt(fcopyfile(source.as_raw(), dest.as_raw(), state, flags));
copyfile_state_get(state, COPYFILE_STATE_COPIED, (&raw mut copied).cast());
copyfile_state_free(state);
result
};
result?;
Ok(copied.max(0) as u64)
}
pub(crate) fn chown(path: &[u8], uid: u32, gid: u32, follow: bool) -> Result<()> {
with_cstr(path, |path| {
cvt(unsafe {
if follow {
c_chown(path.as_ptr(), uid, gid)
} else {
c_lchown(path.as_ptr(), uid, gid)
}
})?;
Ok(())
})
}
pub(crate) fn fchown(handle: BorrowedHandle<'_>, uid: u32, gid: u32) -> Result<()> {
cvt(unsafe { c_fchown(handle.as_raw(), uid, gid) })?;
Ok(())
}
pub(crate) fn mkfifo(path: &[u8], mode: u32) -> Result<()> {
with_cstr(path, |path| {
cvt(unsafe { c_mkfifo(path.as_ptr(), mode as u16) })?;
Ok(())
})
}
pub(crate) fn sync(handle: BorrowedHandle<'_>, _data_only: bool) -> Result<()> {
if unsafe { fcntl(handle.as_raw(), F_FULLFSYNC) } != -1 {
return Ok(());
}
let error = last_error();
if error.raw_os_error() == errno::EINTR {
return Err(error);
}
cvt(unsafe { fsync(handle.as_raw()) })?;
Ok(())
}
pub(crate) fn set_permissions(path: &[u8], mode: u32) -> Result<()> {
with_cstr(path, |path| {
cvt(unsafe { chmod(path.as_ptr(), mode as u16) })?;
Ok(())
})
}
pub(crate) fn set_permissions_at(dir: BorrowedHandle<'_>, path: &[u8], mode: u32) -> Result<()> {
with_cstr(path, |path| {
cvt(unsafe { fchmodat(dir.as_raw(), path.as_ptr(), mode as u16, 0) })?;
Ok(())
})
}
pub(crate) fn set_handle_permissions(handle: BorrowedHandle<'_>, mode: u32) -> Result<()> {
cvt(unsafe { fchmod(handle.as_raw(), mode as u16) })?;
Ok(())
}
fn timespecs(times: &FileTimes) -> [Timespec; 2] {
let spec = |time: Option<Timestamp>| match time {
Some(time) => Timespec {
sec: time.secs,
nsec: time.nanos as i64,
},
None => Timespec {
sec: 0,
nsec: UTIME_OMIT,
},
};
[spec(times.accessed), spec(times.modified)]
}
pub(crate) fn set_times(path: &[u8], times: &FileTimes) -> Result<()> {
let times = timespecs(times);
with_cstr(path, |path| {
cvt(unsafe { utimensat(AT_FDCWD, path.as_ptr(), times.as_ptr(), 0) })?;
Ok(())
})
}
pub(crate) fn set_times_at(dir: BorrowedHandle<'_>, path: &[u8], times: &FileTimes) -> Result<()> {
let times = timespecs(times);
with_cstr(path, |path| {
cvt(unsafe { utimensat(dir.as_raw(), path.as_ptr(), times.as_ptr(), 0) })?;
Ok(())
})
}
pub(crate) fn set_handle_times(handle: BorrowedHandle<'_>, times: &FileTimes) -> Result<()> {
let times = timespecs(times);
cvt(unsafe { futimens(handle.as_raw(), times.as_ptr()) })?;
Ok(())
}
pub(crate) fn lock(handle: BorrowedHandle<'_>, kind: LockKind, wait: bool) -> Result<bool> {
let mut operation = match kind {
LockKind::Shared => LOCK_SH,
LockKind::Exclusive => LOCK_EX,
};
if !wait {
operation |= LOCK_NB;
}
match cvt(unsafe { flock(handle.as_raw(), operation) }) {
Ok(_) => Ok(true),
Err(error) if !wait && error.raw_os_error() == errno::EAGAIN => Ok(false),
Err(error) => Err(error),
}
}
pub(crate) fn unlock(handle: BorrowedHandle<'_>) -> Result<()> {
cvt(unsafe { flock(handle.as_raw(), LOCK_UN) })?;
Ok(())
}
pub(crate) fn create_dir(path: &[u8], mode: u32) -> Result<()> {
with_cstr(path, |path| {
cvt(unsafe { mkdir(path.as_ptr(), mode as u16) })?;
Ok(())
})
}
pub(crate) fn create_dir_at(dir: BorrowedHandle<'_>, path: &[u8], mode: u32) -> Result<()> {
with_cstr(path, |path| {
cvt(unsafe { mkdirat(dir.as_raw(), path.as_ptr(), mode as u16) })?;
Ok(())
})
}
pub(crate) fn remove_dir_at(dir: BorrowedHandle<'_>, path: &[u8]) -> Result<()> {
with_cstr(path, |path| {
cvt(unsafe { unlinkat(dir.as_raw(), path.as_ptr(), AT_REMOVEDIR) })?;
Ok(())
})
}
pub(crate) fn remove_file_at(dir: BorrowedHandle<'_>, path: &[u8]) -> Result<()> {
let dirfd = dir.as_raw();
with_cstr(path, |path| {
let Err(error) = cvt(unsafe { unlinkat(dirfd, path.as_ptr(), 0) }) else {
return Ok(());
};
if error.raw_os_error() == errno::EPERM {
let found =
stat_with(|st| unsafe { fstatat(dirfd, path.as_ptr(), st, AT_SYMLINK_NOFOLLOW) });
if found.is_ok_and(|found| found.is_dir()) {
return Err(ErrorKind::IsADirectory.into());
}
}
Err(error)
})
}
pub(crate) fn rename_at(
from_dir: BorrowedHandle<'_>,
from: &[u8],
to_dir: BorrowedHandle<'_>,
to: &[u8],
) -> Result<()> {
with_cstr(from, |from| {
with_cstr(to, |to| {
cvt(unsafe {
renameat(
from_dir.as_raw(),
from.as_ptr(),
to_dir.as_raw(),
to.as_ptr(),
)
})?;
Ok(())
})
})
}
pub(crate) fn hard_link_at(
original_dir: BorrowedHandle<'_>,
original: &[u8],
link_dir: BorrowedHandle<'_>,
new: &[u8],
) -> Result<()> {
with_cstr(original, |original| {
with_cstr(new, |new| {
cvt(unsafe {
linkat(
original_dir.as_raw(),
original.as_ptr(),
link_dir.as_raw(),
new.as_ptr(),
0,
)
})?;
Ok(())
})
})
}
pub(crate) fn symlink_at(target: &[u8], dir: BorrowedHandle<'_>, link: &[u8]) -> Result<()> {
with_cstr(target, |target| {
with_cstr(link, |link| {
cvt(unsafe { symlinkat(target.as_ptr(), dir.as_raw(), link.as_ptr()) })?;
Ok(())
})
})
}
pub(crate) fn read_link_at(dir: BorrowedHandle<'_>, path: &[u8], buf: &mut [u8]) -> Result<usize> {
let readlink_into = |path: &CStr, buf: &mut [u8]| {
let len = unsafe {
readlinkat(
dir.as_raw(),
path.as_ptr(),
buf.as_mut_ptr().cast(),
buf.len(),
)
};
cvt_long(len as i64).map(|len| len as usize)
};
with_cstr(path, |path| {
if buf.is_empty() {
readlink_into(path, &mut [0])?;
return Err(ErrorKind::BufferTooSmall.into());
}
let len = readlink_into(path, buf)?;
if len >= buf.len() {
return Err(ErrorKind::BufferTooSmall.into());
}
Ok(len)
})
}
pub(crate) fn remove_dir(path: &[u8]) -> Result<()> {
with_cstr(path, |path| {
cvt(unsafe { rmdir(path.as_ptr()) })?;
Ok(())
})
}
pub(crate) fn remove_file(path: &[u8]) -> Result<()> {
with_cstr(path, |path| {
let Err(error) = cvt(unsafe { unlink(path.as_ptr()) }) else {
return Ok(());
};
if error.raw_os_error() == errno::EPERM {
let found = stat_with(|st| unsafe { lstat(path.as_ptr(), st) });
if found.is_ok_and(|found| found.is_dir()) {
return Err(ErrorKind::IsADirectory.into());
}
}
Err(error)
})
}
pub(crate) fn rename(from: &[u8], to: &[u8]) -> Result<()> {
with_cstr(from, |from| {
with_cstr(to, |to| {
cvt(unsafe { c_rename(from.as_ptr(), to.as_ptr()) })?;
Ok(())
})
})
}
pub(crate) fn hard_link(original: &[u8], new: &[u8]) -> Result<()> {
with_cstr(original, |original| {
with_cstr(new, |new| {
cvt(unsafe { link(original.as_ptr(), new.as_ptr()) })?;
Ok(())
})
})
}
pub(crate) fn symlink(target: &[u8], link: &[u8]) -> Result<()> {
with_cstr(target, |target| {
with_cstr(link, |link| {
cvt(unsafe { c_symlink(target.as_ptr(), link.as_ptr()) })?;
Ok(())
})
})
}
fn readlink_into(path: &CStr, buf: &mut [u8]) -> Result<usize> {
let len = unsafe { readlink(path.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
cvt_long(len as i64).map(|len| len as usize)
}
pub(crate) fn read_link(path: &[u8], buf: &mut [u8]) -> Result<usize> {
with_cstr(path, |path| {
if buf.is_empty() {
readlink_into(path, &mut [0])?;
return Err(ErrorKind::BufferTooSmall.into());
}
let len = readlink_into(path, buf)?;
if len >= buf.len() {
return Err(ErrorKind::BufferTooSmall.into());
}
Ok(len)
})
}
pub(crate) fn canonicalize(path: &[u8], buf: &mut [u8]) -> Result<usize> {
with_cstr(path, |path| {
let mut resolved = [0u8; PATH_MAX];
if unsafe { realpath(path.as_ptr(), resolved.as_mut_ptr().cast()) }.is_null() {
return Err(last_error());
}
let len = resolved.iter().position(|&c| c == 0).unwrap_or(PATH_MAX);
let out = buf.get_mut(..len).ok_or(ErrorKind::BufferTooSmall)?;
out.copy_from_slice(&resolved[..len]);
Ok(len)
})
}
pub(crate) fn current_dir(buf: &mut [u8]) -> Result<usize> {
if buf.is_empty() {
return Err(ErrorKind::BufferTooSmall.into());
}
if unsafe { getcwd(buf.as_mut_ptr().cast(), buf.len()) }.is_null() {
return Err(last_error());
}
buf.iter()
.position(|&c| c == 0)
.ok_or(ErrorKind::BufferTooSmall.into())
}
pub(crate) fn set_current_dir(path: &[u8]) -> Result<()> {
with_cstr(path, |path| {
cvt(unsafe { chdir(path.as_ptr()) })?;
Ok(())
})
}
const DIR_BUF: usize = 4096;
pub(crate) struct Dir {
handle: OwnedHandle,
buf: [u8; DIR_BUF],
pos: usize,
remaining: usize,
}
impl Dir {
pub(crate) fn new(handle: OwnedHandle) -> Self {
Self {
handle,
buf: [0; DIR_BUF],
pos: 0,
remaining: 0,
}
}
pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
self.handle.as_handle()
}
pub(crate) fn name(&self, entry: &RawDirEntry) -> &[u8] {
&self.buf[entry.name.0..entry.name.1]
}
fn u32_at(&self, at: usize) -> Result<u32> {
self.buf
.get(at..at + 4)
.and_then(|bytes| bytes.try_into().ok())
.map(u32::from_ne_bytes)
.ok_or(Error::from(ErrorKind::Other))
}
pub(crate) fn next(&mut self) -> Result<Option<RawDirEntry>> {
if self.remaining == 0 {
let mut attrs = AttrList {
bitmapcount: ATTR_BIT_MAP_COUNT,
reserved: 0,
commonattr: ATTR_CMN_RETURNED_ATTRS
| ATTR_CMN_NAME
| ATTR_CMN_OBJTYPE
| ATTR_CMN_FILEID,
volattr: 0,
dirattr: 0,
fileattr: 0,
forkattr: 0,
};
let count = cvt(unsafe {
getattrlistbulk(
self.handle.as_raw(),
&raw mut attrs,
self.buf.as_mut_ptr().cast(),
DIR_BUF,
0,
)
})?;
if count == 0 {
return Ok(None);
}
self.pos = 0;
self.remaining = count as usize;
}
let start = self.pos;
self.remaining -= 1;
let length = self.u32_at(start)? as usize;
let returned = self.u32_at(start + 4)?;
if length < 24 || start + length > DIR_BUF {
self.remaining = 0;
return Err(ErrorKind::Other.into());
}
self.pos = start + length;
let mut at = start + 24;
let mut name = (start, start);
if returned & ATTR_CMN_NAME != 0 {
let offset = self.u32_at(at)? as i32;
let len = self.u32_at(at + 4)? as usize;
let from = at.wrapping_add_signed(offset as isize);
let bytes = from
.checked_add(len)
.and_then(|to| self.buf.get(from..to))
.ok_or(Error::from(ErrorKind::Other))?;
let len = bytes.iter().position(|&c| c == 0).unwrap_or(len);
name = (from, from + len);
at += 8;
}
let mut file_type = None;
if returned & ATTR_CMN_OBJTYPE != 0 {
file_type = match self.u32_at(at)? {
1 => Some(FileType::File),
2 => Some(FileType::Directory),
3 => Some(FileType::BlockDevice),
4 => Some(FileType::CharDevice),
5 => Some(FileType::Symlink),
6 => Some(FileType::Socket),
7 => Some(FileType::Fifo),
_ => None,
};
at += 4;
}
let mut inode = 0;
if returned & ATTR_CMN_FILEID != 0 {
inode = self.u32_at(at)? as u64 | (self.u32_at(at + 4)? as u64) << 32;
}
Ok(Some(RawDirEntry {
name,
file_type,
inode,
}))
}
}