use super::CapabilitySet;
use crate::{AsHandle, AsPath, ErrorKind, Result, sys};
const NAME: &[u8] = b"security.capability";
const VFS_CAP_REVISION_MASK: u32 = 0xff00_0000;
const VFS_CAP_FLAGS_EFFECTIVE: u32 = 1;
const VFS_CAP_REVISION_1: u32 = 0x0100_0000;
const VFS_CAP_REVISION_2: u32 = 0x0200_0000;
const VFS_CAP_REVISION_3: u32 = 0x0300_0000;
const SIZE_1: usize = 12;
const SIZE_2: usize = 20;
const SIZE_3: usize = 24;
#[repr(C)]
#[allow(dead_code)]
struct VfsNsCapData {
magic_etc: u32,
data: [[u32; 2]; 2],
rootid: u32,
}
const _: () = assert!(size_of::<VfsNsCapData>() == SIZE_3);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct FileCapabilities {
pub permitted: CapabilitySet,
pub inheritable: CapabilitySet,
pub effective: bool,
pub root_id: Option<u32>,
}
impl FileCapabilities {
pub const MAX_LEN: usize = SIZE_3;
pub const fn new(
permitted: CapabilitySet,
inheritable: CapabilitySet,
effective: bool,
) -> Self {
Self {
permitted,
inheritable,
effective,
root_id: None,
}
}
pub const fn with_root_id(mut self, root_id: u32) -> Self {
self.root_id = Some(root_id);
self
}
pub fn from_bytes(value: &[u8]) -> Result<Self> {
let word = |index: usize| {
let bytes = value.get(4 * index..4 * index + 4)?;
Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
};
let invalid = || crate::Error::from(ErrorKind::InvalidInput);
let magic = word(0).ok_or_else(invalid)?;
let (len, halves) = match magic & VFS_CAP_REVISION_MASK {
VFS_CAP_REVISION_1 => (SIZE_1, 1),
VFS_CAP_REVISION_2 => (SIZE_2, 2),
VFS_CAP_REVISION_3 => (SIZE_3, 2),
_ => return Err(invalid()),
};
if value.len() != len {
return Err(invalid());
}
let mut sets = [0u64; 2];
for half in 0..halves {
for (set, bits) in sets.iter_mut().enumerate() {
let part = word(1 + 2 * half + set).ok_or_else(invalid)?;
*bits |= u64::from(part) << (32 * half);
}
}
Ok(Self {
permitted: CapabilitySet::from_bits(sets[0]),
inheritable: CapabilitySet::from_bits(sets[1]),
effective: magic & VFS_CAP_FLAGS_EFFECTIVE != 0,
root_id: if len == SIZE_3 { word(5) } else { None },
})
}
pub fn to_bytes<'b>(&self, buf: &'b mut [u8; Self::MAX_LEN]) -> &'b [u8] {
let (revision, len) = match self.root_id {
Some(_) => (VFS_CAP_REVISION_3, SIZE_3),
None => (VFS_CAP_REVISION_2, SIZE_2),
};
let (permitted, inheritable) = (self.permitted.bits(), self.inheritable.bits());
let words = [
revision
| if self.effective {
VFS_CAP_FLAGS_EFFECTIVE
} else {
0
},
permitted as u32,
inheritable as u32,
(permitted >> 32) as u32,
(inheritable >> 32) as u32,
self.root_id.unwrap_or(0),
];
for (bytes, word) in buf.as_chunks_mut::<4>().0.iter_mut().zip(words) {
*bytes = word.to_le_bytes();
}
&buf[..len]
}
}
fn parse(value: &[u8; 64], len: Option<usize>) -> Result<Option<FileCapabilities>> {
match len {
None => Ok(None),
Some(len) => {
let value = value.get(..len).ok_or(ErrorKind::InvalidInput)?;
FileCapabilities::from_bytes(value).map(Some)
}
}
}
pub fn file_capabilities<P: AsPath + ?Sized>(path: &P) -> Result<Option<FileCapabilities>> {
let mut value = [0u8; 64];
let len = sys::fs::xattr::get(path.as_path_bytes(), NAME, &mut value, true)?;
parse(&value, len)
}
pub fn handle_file_capabilities(handle: impl AsHandle) -> Result<Option<FileCapabilities>> {
let mut value = [0u8; 64];
let len = sys::fs::xattr::fget(handle.as_handle(), NAME, &mut value)?;
parse(&value, len)
}
pub fn set_file_capabilities<P: AsPath + ?Sized>(
path: &P,
capabilities: &FileCapabilities,
) -> Result<()> {
let mut buf = [0u8; FileCapabilities::MAX_LEN];
let value = capabilities.to_bytes(&mut buf);
let mode = crate::fs::unix::XattrMode::Any;
sys::fs::xattr::set(path.as_path_bytes(), NAME, value, mode, true)
}
pub fn set_handle_file_capabilities(
handle: impl AsHandle,
capabilities: &FileCapabilities,
) -> Result<()> {
let mut buf = [0u8; FileCapabilities::MAX_LEN];
let value = capabilities.to_bytes(&mut buf);
let mode = crate::fs::unix::XattrMode::Any;
sys::fs::xattr::fset(handle.as_handle(), NAME, value, mode)
}
pub fn remove_file_capabilities<P: AsPath + ?Sized>(path: &P) -> Result<bool> {
removed(sys::fs::xattr::remove(path.as_path_bytes(), NAME, true))
}
pub fn remove_handle_file_capabilities(handle: impl AsHandle) -> Result<bool> {
removed(sys::fs::xattr::fremove(handle.as_handle(), NAME))
}
fn removed(result: Result<()>) -> Result<bool> {
match result {
Ok(()) => Ok(true),
Err(error) if error.raw_os_error() == sys::errno::ENODATA => Ok(false),
Err(error) => Err(error),
}
}