use dashmap::DashMap;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
pub type InodeKey = (u64, u64);
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FakeInode {
pub uid: u32,
pub gid: u32,
pub mode: Option<u32>,
pub rdev: Option<u64>,
pub xattrs: HashMap<String, Vec<u8>>,
}
impl FakeInode {
#[must_use]
pub fn new(uid: u32, gid: u32) -> Self {
Self {
uid,
gid,
mode: None,
rdev: None,
xattrs: HashMap::new(),
}
}
}
pub struct FakeRootState {
pub inode_map: DashMap<InodeKey, FakeInode>,
pub current_uid: AtomicU32,
pub current_gid: AtomicU32,
}
impl Default for FakeRootState {
fn default() -> Self {
Self {
inode_map: DashMap::new(),
current_uid: AtomicU32::new(0),
current_gid: AtomicU32::new(0),
}
}
}
impl FakeRootState {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[inline]
pub fn set_current(&self, uid: u32, gid: u32) {
self.current_uid.store(uid, Ordering::Relaxed);
self.current_gid.store(gid, Ordering::Relaxed);
}
#[inline]
#[must_use]
pub fn current_uid(&self) -> u32 {
self.current_uid.load(Ordering::Relaxed)
}
#[inline]
#[must_use]
pub fn current_gid(&self) -> u32 {
self.current_gid.load(Ordering::Relaxed)
}
#[inline]
pub fn set_inode(&self, key: InodeKey, inode: FakeInode) {
self.inode_map.insert(key, inode);
}
#[inline]
#[must_use]
pub fn get_inode(&self, key: InodeKey) -> Option<FakeInode> {
self.inode_map.get(&key).map(|entry| entry.value().clone())
}
#[inline]
pub fn remove_inode(&self, key: InodeKey) -> Option<FakeInode> {
self.inode_map.remove(&key).map(|(_, v)| v)
}
pub const ID_UNCHANGED: u32 = u32::MAX;
#[inline]
pub fn upsert_chown(
&self,
key: InodeKey,
uid: u32,
gid: u32,
default_uid: u32,
default_gid: u32,
) {
self.inode_map
.entry(key)
.and_modify(|inode| {
if uid != Self::ID_UNCHANGED {
inode.uid = uid;
}
if gid != Self::ID_UNCHANGED {
inode.gid = gid;
}
})
.or_insert_with(|| {
let mut inode = FakeInode::new(default_uid, default_gid);
if uid != Self::ID_UNCHANGED {
inode.uid = uid;
}
if gid != Self::ID_UNCHANGED {
inode.gid = gid;
}
inode
});
}
}
static GLOBAL_STATE: std::sync::OnceLock<RwLock<FakeRootState>> = std::sync::OnceLock::new();
pub fn init_global_state() -> RwLockWriteGuard<'static, FakeRootState> {
let lock = GLOBAL_STATE.get_or_init(|| RwLock::new(FakeRootState::new()));
lock.write()
.expect("Failed to acquire write lock on global state")
}
pub fn global_state_read() -> RwLockReadGuard<'static, FakeRootState> {
let lock = GLOBAL_STATE.get_or_init(|| RwLock::new(FakeRootState::new()));
lock.read()
.expect("Failed to acquire read lock on global state")
}
pub fn global_state_write() -> RwLockWriteGuard<'static, FakeRootState> {
let lock = GLOBAL_STATE.get_or_init(|| RwLock::new(FakeRootState::new()));
lock.write()
.expect("Failed to acquire write lock on global state")
}