use std::ffi::CStr;
use std::os::unix::ffi::OsStrExt as _;
pub(crate) const ACL_USER_OBJ: u16 = 0x01;
pub(crate) const ACL_USER: u16 = 0x02;
pub(crate) const ACL_GROUP_OBJ: u16 = 0x04;
pub(crate) const ACL_MASK: u16 = 0x10;
pub(crate) const ACL_OTHER: u16 = 0x20;
pub(crate) const ACL_UNDEFINED_ID: u32 = 0xffff_ffff;
pub(crate) fn encode_acl(entries: &[(u16, u16, u32)]) -> Vec<u8> {
let mut out = 2u32.to_le_bytes().to_vec();
for &(tag, perm, id) in entries {
out.extend_from_slice(&tag.to_le_bytes());
out.extend_from_slice(&perm.to_le_bytes());
out.extend_from_slice(&id.to_le_bytes());
}
out
}
pub(crate) fn restrictive_access_acl() -> Vec<u8> {
encode_acl(&[
(ACL_USER_OBJ, 7, ACL_UNDEFINED_ID),
(ACL_USER, 0, 65534),
(ACL_GROUP_OBJ, 0, ACL_UNDEFINED_ID),
(ACL_MASK, 5, ACL_UNDEFINED_ID),
(ACL_OTHER, 5, ACL_UNDEFINED_ID),
])
}
pub(crate) fn permissive_acl() -> Vec<u8> {
encode_acl(&[
(ACL_USER_OBJ, 7, ACL_UNDEFINED_ID),
(ACL_USER, 7, 65534),
(ACL_GROUP_OBJ, 5, ACL_UNDEFINED_ID),
(ACL_MASK, 7, ACL_UNDEFINED_ID),
(ACL_OTHER, 5, ACL_UNDEFINED_ID),
])
}
pub(crate) fn rejected_access_acl() -> Vec<u8> {
encode_acl(&[(ACL_USER, 7, 65534)])
}
pub(crate) fn set_xattr_at(path: &std::path::Path, name: &CStr, value: &[u8]) {
let cpath = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
let rc = unsafe {
libc::setxattr(
cpath.as_ptr(),
name.as_ptr(),
value.as_ptr().cast(),
value.len(),
0,
)
};
assert_eq!(
rc,
0,
"fixture setxattr({name:?}) on {path:?} failed: {} — this filesystem cannot hold \
POSIX ACLs, so these tests cannot run here",
std::io::Error::last_os_error()
);
}
pub(crate) fn get_xattr_at(path: &std::path::Path, name: &CStr) -> Option<Vec<u8>> {
let cpath = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
let size = unsafe { libc::getxattr(cpath.as_ptr(), name.as_ptr(), std::ptr::null_mut(), 0) };
if size < 0 {
let err = std::io::Error::last_os_error();
assert_eq!(
err.raw_os_error(),
Some(libc::ENODATA),
"getxattr({name:?}) on {path:?} failed with {err} — only ENODATA means \"no such \
attribute\"; anything else means the check never happened"
);
return None;
}
let mut buf = vec![0u8; size as usize];
if buf.is_empty() {
return Some(buf);
}
let n = unsafe {
libc::getxattr(
cpath.as_ptr(),
name.as_ptr(),
buf.as_mut_ptr().cast(),
buf.len(),
)
};
assert!(
n >= 0,
"getxattr({name:?}) on {path:?} failed after its size was read: {}",
std::io::Error::last_os_error()
);
buf.truncate(n as usize);
Some(buf)
}