use crate::kwtty::{ExecOptions, exec_subprocess};
use crate::monitor::{ApprovalKind, AuditEvent, Monitor, is_sensitive_path, now_unix_ms};
use crate::vsock::{VsockHost, VsockStream};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fs::{self, File, OpenOptions};
use std::io;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use wasmtime::{Result, bail, format_err};
pub const P9_VSOCK_PORT: u32 = 564;
const P9_VERSION: &str = "9P2000.L";
const DEFAULT_MSIZE: u32 = 131_072;
const HDR_LEN: usize = 7;
const RLERROR: u8 = 7;
const TSTATFS: u8 = 8;
const TLOPEN: u8 = 12;
const TLCREATE: u8 = 14;
const TSYMLINK: u8 = 16;
const TMKNOD: u8 = 18;
const TRENAME: u8 = 20;
const TREADLINK: u8 = 22;
const TGETATTR: u8 = 24;
const TSETATTR: u8 = 26;
const TXATTRWALK: u8 = 30;
const TXATTRCREATE: u8 = 32;
const TREADDIR: u8 = 40;
const TFSYNC: u8 = 50;
const TLOCK: u8 = 52;
const TGETLOCK: u8 = 54;
const TLINK: u8 = 70;
const TMKDIR: u8 = 72;
const TRENAMEAT: u8 = 74;
const TUNLINKAT: u8 = 76;
const TVERSION: u8 = 100;
const TAUTH: u8 = 102;
const TATTACH: u8 = 104;
const TFLUSH: u8 = 108;
const TWALK: u8 = 110;
const TREAD: u8 = 116;
const TWRITE: u8 = 118;
const TCLUNK: u8 = 120;
const TREMOVE: u8 = 122;
const QTDIR: u8 = 0x80;
const QTSYMLINK: u8 = 0x02;
const QTFILE: u8 = 0x00;
const S_IFDIR: u32 = 0o040000;
const S_IFREG: u32 = 0o100000;
const S_IFLNK: u32 = 0o120000;
const DT_DIR: u8 = 4;
const DT_REG: u8 = 8;
const DT_LNK: u8 = 10;
const AT_REMOVEDIR: u32 = 0x200;
const O_ACCMODE: u32 = 0x3;
const O_EXCL: u32 = 0x80;
const O_TRUNC: u32 = 0x200;
const O_APPEND: u32 = 0x400;
const P9_STATS_BASIC: u64 = 0x07ff;
const V9FS_MAGIC: u32 = 0x0102_1997;
const EPERM: u32 = 1;
const ENOENT: u32 = 2;
const EIO: u32 = 5;
const EBADF: u32 = 9;
const EACCES: u32 = 13;
const EBUSY: u32 = 16;
const EEXIST: u32 = 17;
const ENOTDIR: u32 = 20;
const EISDIR: u32 = 21;
const EINVAL: u32 = 22;
const EROFS: u32 = 30;
const ENOTEMPTY: u32 = 39;
const EPROTO: u32 = 71;
const EOPNOTSUPP: u32 = 95;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkspaceDiff {
pub guest_path: String,
pub created: Vec<String>,
pub modified: Vec<String>,
pub deleted: Vec<String>,
}
impl WorkspaceDiff {
pub fn is_empty(&self) -> bool {
self.created.is_empty() && self.modified.is_empty() && self.deleted.is_empty()
}
}
#[derive(Clone, Debug)]
pub struct WorkspaceSnapshot {
pub host_root: PathBuf,
pub guest_path: String,
layer: CowLayer,
}
impl WorkspaceSnapshot {
pub fn diff(&self) -> WorkspaceDiff {
self.layer.diff(&self.host_root, &self.guest_path)
}
}
#[derive(Clone, Debug)]
enum CowEntry {
File {
data: Vec<u8>,
mode: u32,
mtime: u64,
},
Dir {
mode: u32,
mtime: u64,
},
Symlink {
target: String,
mtime: u64,
},
Whiteout,
}
#[derive(Clone, Debug, Default)]
struct CowLayer {
entries: BTreeMap<String, CowEntry>,
opaque_dirs: HashSet<String>,
discard_gen: u64,
}
struct CowStat {
qtype: u8,
fmt: u32,
perm: u32,
len: u64,
nlink: u64,
mtime: u64,
is_dir: bool,
is_file: bool,
ino: u64,
epoch: u64,
}
fn now_sec() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
fn norm_rel_key(rel: &Path) -> String {
rel.to_string_lossy()
.replace('\\', "/")
.trim_matches('/')
.to_string()
}
fn rel_from_key(key: &str) -> PathBuf {
let mut p = PathBuf::new();
for seg in key.split('/').filter(|s| !s.is_empty()) {
p.push(seg);
}
p
}
fn parent_key(key: &str) -> &str {
match key.rfind('/') {
Some(idx) => &key[..idx],
None => "",
}
}
fn synthetic_ino_with_epoch(rel: &Path, epoch: u64) -> u64 {
let norm = norm_rel_key(rel);
if norm.is_empty() {
return 1;
}
let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ epoch.wrapping_mul(0x9e37_79b9_7f4a_7c15);
for b in norm.as_bytes() {
h ^= *b as u64;
h = h.wrapping_mul(0x0100_0000_01b3);
}
h | 2
}
impl CowLayer {
fn ino_for(&self, rel: &Path) -> u64 {
synthetic_ino_with_epoch(rel, self.discard_gen)
}
fn is_host_hidden(&self, key: &str) -> bool {
if matches!(self.entries.get(key), Some(CowEntry::Whiteout)) {
return true;
}
let mut cur = key;
while let Some(idx) = cur.rfind('/') {
cur = &cur[..idx];
if matches!(self.entries.get(cur), Some(CowEntry::Whiteout))
|| self.opaque_dirs.contains(cur)
{
return true;
}
}
false
}
fn stat_entry(&self, host_root: &Path, rel: &Path) -> std::result::Result<CowStat, u32> {
let key = norm_rel_key(rel);
let ino = self.ino_for(rel);
let epoch = self.discard_gen;
if let Some(entry) = self.entries.get(&key) {
return match entry {
CowEntry::Whiteout => Err(ENOENT),
CowEntry::File { data, mode, mtime } => Ok(CowStat {
qtype: QTFILE,
fmt: S_IFREG,
perm: *mode & 0o7777,
len: data.len() as u64,
nlink: 1,
mtime: *mtime,
is_dir: false,
is_file: true,
ino,
epoch,
}),
CowEntry::Dir { mode, mtime } => Ok(CowStat {
qtype: QTDIR,
fmt: S_IFDIR,
perm: *mode & 0o7777,
len: 0,
nlink: 2,
mtime: *mtime,
is_dir: true,
is_file: false,
ino,
epoch,
}),
CowEntry::Symlink { target, mtime } => Ok(CowStat {
qtype: QTSYMLINK,
fmt: S_IFLNK,
perm: 0o777,
len: target.len() as u64,
nlink: 1,
mtime: *mtime,
is_dir: false,
is_file: false,
ino,
epoch,
}),
};
}
if self.is_host_hidden(&key) {
return Err(ENOENT);
}
let host_path = resolve_confined(host_root, rel, false)?;
let meta = fs::symlink_metadata(&host_path).map_err(io_to_errno)?;
let ft = meta.file_type();
let (qtype, fmt) = if ft.is_dir() {
(QTDIR, S_IFDIR)
} else if ft.is_symlink() {
(QTSYMLINK, S_IFLNK)
} else {
(QTFILE, S_IFREG)
};
let mtime = meta
.modified()
.ok()
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map(|d| d.as_secs())
.unwrap_or(0);
Ok(CowStat {
qtype,
fmt,
perm: meta_perm(&meta),
len: meta.len(),
nlink: meta_nlink(&meta),
mtime,
is_dir: ft.is_dir(),
is_file: ft.is_file(),
ino,
epoch,
})
}
fn copy_up_file(&mut self, host_root: &Path, rel: &Path) -> std::result::Result<(), u32> {
let key = norm_rel_key(rel);
if let Some(entry) = self.entries.get(&key) {
return match entry {
CowEntry::File { .. } => Ok(()),
CowEntry::Dir { .. } => Err(EISDIR),
CowEntry::Symlink { .. } => Err(EACCES),
CowEntry::Whiteout => Err(ENOENT),
};
}
if self.is_host_hidden(&key) {
return Err(ENOENT);
}
let host_path = resolve_confined(host_root, rel, false)?;
let meta = fs::symlink_metadata(&host_path).map_err(io_to_errno)?;
if meta.file_type().is_symlink() {
return Err(EACCES);
}
if meta.is_dir() {
return Err(EISDIR);
}
let data = fs::read(&host_path).map_err(io_to_errno)?;
let mode = meta_perm(&meta);
self.entries.insert(
key,
CowEntry::File {
data,
mode,
mtime: now_sec(),
},
);
Ok(())
}
fn merged_children(
&self,
host_root: &Path,
dir_rel: &Path,
) -> std::result::Result<Vec<DirCacheEntry>, u32> {
let dir_key = norm_rel_key(dir_rel);
let mut by_name: BTreeMap<String, DirCacheEntry> = BTreeMap::new();
if !self.is_host_hidden(&dir_key)
&& !self.opaque_dirs.contains(&dir_key)
&& let Ok(host_path) = resolve_confined(host_root, dir_rel, false)
&& let Ok(rd) = fs::read_dir(&host_path)
{
for dent in rd.flatten() {
let Ok(meta) = dent.metadata() else { continue };
let name = dent.file_name().to_string_lossy().into_owned();
let child_rel = dir_rel.join(&name);
let ft = meta.file_type();
let (qtype, dtype) = if ft.is_dir() {
(QTDIR, DT_DIR)
} else if ft.is_symlink() {
(QTSYMLINK, DT_LNK)
} else {
(QTFILE, DT_REG)
};
by_name.insert(
name.clone(),
DirCacheEntry {
ino: self.ino_for(&child_rel),
rel_path: child_rel,
name,
qtype,
dtype,
},
);
}
}
for (k, entry) in &self.entries {
if k.is_empty() || parent_key(k) != dir_key {
continue;
}
let name = k.rsplit('/').next().unwrap_or(k).to_string();
match entry {
CowEntry::Whiteout => {
by_name.remove(&name);
}
CowEntry::File { .. } => {
let child_rel = dir_rel.join(&name);
by_name.insert(
name.clone(),
DirCacheEntry {
ino: self.ino_for(&child_rel),
rel_path: child_rel,
name,
qtype: QTFILE,
dtype: DT_REG,
},
);
}
CowEntry::Dir { .. } => {
let child_rel = dir_rel.join(&name);
by_name.insert(
name.clone(),
DirCacheEntry {
ino: self.ino_for(&child_rel),
rel_path: child_rel,
name,
qtype: QTDIR,
dtype: DT_DIR,
},
);
}
CowEntry::Symlink { .. } => {
let child_rel = dir_rel.join(&name);
by_name.insert(
name.clone(),
DirCacheEntry {
ino: self.ino_for(&child_rel),
rel_path: child_rel,
name,
qtype: QTSYMLINK,
dtype: DT_LNK,
},
);
}
}
}
Ok(by_name.into_values().collect())
}
fn purge_subtree(&mut self, key: &str) {
let prefix = format!("{key}/");
self.entries.retain(|k, _| !k.starts_with(&prefix));
self.opaque_dirs
.retain(|k| k != key && !k.starts_with(&prefix));
}
fn remove_entry(
&mut self,
host_root: &Path,
rel: &Path,
expect_dir: bool,
) -> std::result::Result<(), u32> {
let key = norm_rel_key(rel);
if key.is_empty() {
return Err(EBUSY);
}
let st = self.stat_entry(host_root, rel)?;
if expect_dir && !st.is_dir {
return Err(ENOTDIR);
}
if !expect_dir && st.is_dir {
return Err(EISDIR);
}
if st.is_dir && !self.merged_children(host_root, rel)?.is_empty() {
return Err(ENOTEMPTY);
}
self.purge_subtree(&key);
self.entries.insert(key, CowEntry::Whiteout);
Ok(())
}
fn copy_subtree(
&mut self,
host_root: &Path,
src_rel: &Path,
dst_rel: &Path,
) -> std::result::Result<(), u32> {
let src_key = norm_rel_key(src_rel);
let dst_key = norm_rel_key(dst_rel);
let st = self.stat_entry(host_root, src_rel)?;
if st.is_dir {
let children = self.merged_children(host_root, src_rel)?;
self.purge_subtree(&dst_key);
self.opaque_dirs.insert(dst_key.clone());
self.entries.insert(
dst_key,
CowEntry::Dir {
mode: st.perm,
mtime: now_sec(),
},
);
for child in children {
let c_src = src_rel.join(&child.name);
let c_dst = dst_rel.join(&child.name);
self.copy_subtree(host_root, &c_src, &c_dst)?;
}
} else if st.is_file {
self.copy_up_file(host_root, src_rel)?;
if let Some(CowEntry::File { data, mode, .. }) = self.entries.get(&src_key).cloned() {
self.entries.insert(
dst_key,
CowEntry::File {
data,
mode,
mtime: now_sec(),
},
);
}
} else {
let target = if let Some(CowEntry::Symlink { target, .. }) = self.entries.get(&src_key)
{
target.clone()
} else {
let hp = resolve_confined(host_root, src_rel, false)?;
fs::read_link(&hp)
.map_err(io_to_errno)?
.to_string_lossy()
.into_owned()
};
self.entries.insert(
dst_key,
CowEntry::Symlink {
target,
mtime: now_sec(),
},
);
}
Ok(())
}
fn rename_entry(
&mut self,
host_root: &Path,
from_rel: &Path,
to_rel: &Path,
) -> std::result::Result<(), u32> {
let from_key = norm_rel_key(from_rel);
let to_key = norm_rel_key(to_rel);
if from_key == to_key {
return Ok(());
}
if from_key.is_empty() {
return Err(EBUSY);
}
self.copy_subtree(host_root, from_rel, to_rel)?;
self.purge_subtree(&from_key);
self.entries.insert(from_key, CowEntry::Whiteout);
Ok(())
}
fn read_file(&self, host_root: &Path, rel: &Path) -> std::result::Result<Option<Vec<u8>>, u32> {
let key = norm_rel_key(rel);
if let Some(entry) = self.entries.get(&key) {
return match entry {
CowEntry::File { data, .. } => Ok(Some(data.clone())),
CowEntry::Whiteout => Ok(None),
_ => Err(EISDIR),
};
}
if self.is_host_hidden(&key) {
return Ok(None);
}
match resolve_confined(host_root, rel, false) {
Ok(hp) => match fs::read(&hp) {
Ok(b) => Ok(Some(b)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(io_to_errno(e)),
},
Err(ENOENT) => Ok(None),
Err(e) => Err(e),
}
}
fn diff(&self, host_root: &Path, guest_path: &str) -> WorkspaceDiff {
let mut created = Vec::new();
let mut modified = Vec::new();
let mut deleted = Vec::new();
for (k, entry) in &self.entries {
if k.is_empty() {
continue;
}
let rel = rel_from_key(k);
let host_exists = resolve_confined(host_root, &rel, false)
.ok()
.and_then(|hp| fs::symlink_metadata(&hp).ok());
match entry {
CowEntry::Whiteout => {
if host_exists.is_some() {
deleted.push(k.clone());
}
}
CowEntry::File { data, .. } => match host_exists {
None => created.push(k.clone()),
Some(meta) => {
let same = meta.is_file()
&& resolve_confined(host_root, &rel, false)
.ok()
.and_then(|hp| fs::read(&hp).ok())
.is_some_and(|hb| hb == *data);
if !same {
modified.push(k.clone());
}
}
},
CowEntry::Dir { .. } => {
if host_exists.is_none() {
created.push(k.clone());
} else if host_exists.as_ref().is_some_and(|m| !m.is_dir()) {
modified.push(k.clone());
}
}
CowEntry::Symlink { .. } => {
if host_exists.is_none() {
created.push(k.clone());
} else {
modified.push(k.clone());
}
}
}
}
created.sort();
modified.sort();
deleted.sort();
WorkspaceDiff {
guest_path: guest_path.to_string(),
created,
modified,
deleted,
}
}
fn commit(&mut self, host_root: &Path, guest_path: &str) -> Result<WorkspaceDiff> {
let diff = self.diff(host_root, guest_path);
let mut whiteouts: Vec<String> = self
.entries
.iter()
.filter(|(_, e)| matches!(e, CowEntry::Whiteout))
.map(|(k, _)| k.clone())
.collect();
whiteouts.sort_by_key(|k| std::cmp::Reverse(k.len()));
for k in whiteouts {
let rel = rel_from_key(&k);
if let Ok(hp) = resolve_confined(host_root, &rel, false)
&& let Ok(meta) = fs::symlink_metadata(&hp)
{
if meta.is_dir() {
fs::remove_dir_all(&hp)?;
} else {
fs::remove_file(&hp)?;
}
}
}
let mut opaques: Vec<String> = self.opaque_dirs.iter().cloned().collect();
opaques.sort_by_key(|k| k.len());
for k in opaques {
let rel = rel_from_key(&k);
if let Ok(hp) = resolve_confined(host_root, &rel, false)
&& hp.is_dir()
{
fs::remove_dir_all(&hp)?;
}
}
let mut dirs: Vec<(String, u32)> = self
.entries
.iter()
.filter_map(|(k, e)| match e {
CowEntry::Dir { mode, .. } => Some((k.clone(), *mode)),
_ => None,
})
.collect();
dirs.sort_by_key(|(k, _)| k.len());
for (k, mode) in dirs {
let rel = rel_from_key(&k);
let hp = resolve_confined(host_root, &rel, true)
.map_err(|e| format_err!("commit mkdir {k}: errno {e}"))?;
fs::create_dir_all(&hp)?;
let _ = set_unix_mode(&hp, mode);
}
for (k, entry) in &self.entries {
if k.is_empty() {
continue;
}
let rel = rel_from_key(k);
match entry {
CowEntry::File { data, mode, .. } => {
let hp = resolve_confined(host_root, &rel, true)
.map_err(|e| format_err!("commit file {k}: errno {e}"))?;
if let Some(parent) = hp.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&hp, data)?;
let _ = set_unix_mode(&hp, *mode);
}
CowEntry::Symlink { target, .. } => {
let hp = resolve_confined(host_root, &rel, true)
.map_err(|e| format_err!("commit symlink {k}: errno {e}"))?;
if hp.exists() {
let _ = fs::remove_file(&hp);
}
let _ = create_symlink(target, &hp);
}
CowEntry::Dir { .. } | CowEntry::Whiteout => {}
}
}
self.entries.clear();
self.opaque_dirs.clear();
Ok(diff)
}
}
#[derive(Clone)]
pub struct ExportSpec {
pub name: String,
pub guest_path: String,
pub host_root: PathBuf,
pub read_only: bool,
cow: Option<Arc<Mutex<CowLayer>>>,
}
impl std::fmt::Debug for ExportSpec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ExportSpec")
.field("name", &self.name)
.field("guest_path", &self.guest_path)
.field("host_root", &self.host_root)
.field("read_only", &self.read_only)
.field("copy_on_write", &self.cow.is_some())
.finish()
}
}
pub struct P9Server {
exports: Mutex<HashMap<String, Arc<ExportSpec>>>,
next_id: Mutex<u32>,
monitor: Option<Arc<Monitor>>,
}
impl P9Server {
pub fn attach(vsock: &Arc<VsockHost>, monitor: Option<Arc<Monitor>>) -> Arc<Self> {
let server = Arc::new(Self {
exports: Mutex::new(HashMap::new()),
next_id: Mutex::new(0),
monitor,
});
let srv = server.clone();
vsock.listen(P9_VSOCK_PORT, move |stream| {
srv.serve_connection(stream);
});
server
}
pub fn add_export(
&self,
host_dir: &Path,
guest_path: &str,
read_only: bool,
) -> Result<Arc<ExportSpec>> {
self.add_export_with_cow(host_dir, guest_path, read_only, None)
}
fn add_export_with_cow(
&self,
host_dir: &Path,
guest_path: &str,
read_only: bool,
cow_layer: Option<CowLayer>,
) -> Result<Arc<ExportSpec>> {
let canonical = fs::canonicalize(host_dir)
.map_err(|e| format_err!("mount host dir {}: {e}", host_dir.display()))?;
if !canonical.is_dir() {
bail!("mount host path {} is not a directory", canonical.display());
}
let mut id = self.next_id.lock().unwrap();
let name = format!("m{}", *id);
*id += 1;
let spec = Arc::new(ExportSpec {
name: name.clone(),
guest_path: guest_path.to_string(),
host_root: canonical,
read_only: read_only && cow_layer.is_none(),
cow: cow_layer.map(|l| Arc::new(Mutex::new(l))),
});
self.exports.lock().unwrap().insert(name, spec.clone());
Ok(spec)
}
pub fn mount_in_guest(
&self,
vsock: &Arc<VsockHost>,
host_dir: &Path,
guest_path: &str,
read_only: bool,
timeout_ms: u64,
) -> Result<()> {
self.mount_in_guest_ext(
vsock, host_dir, guest_path, read_only, false, None, timeout_ms,
)
}
#[allow(clippy::too_many_arguments)]
pub fn mount_in_guest_ext(
&self,
vsock: &Arc<VsockHost>,
host_dir: &Path,
guest_path: &str,
read_only: bool,
copy_on_write: bool,
initial_snapshot: Option<&WorkspaceSnapshot>,
timeout_ms: u64,
) -> Result<()> {
if !guest_path.starts_with('/') || guest_path == "/" || guest_path.contains('\0') {
bail!("invalid guest mount path {guest_path:?}");
}
let cow_layer = if let Some(snap) = initial_snapshot {
Some(snap.layer.clone())
} else if copy_on_write {
Some(CowLayer::default())
} else {
None
};
let eff_ro = read_only && cow_layer.is_none();
let exp = self.add_export_with_cow(host_dir, guest_path, eff_ro, cow_layer)?;
let mut args = vec!["9p".to_string(), exp.name.clone(), guest_path.to_string()];
if eff_ro {
args.push("ro".to_string());
}
let mut opts = ExecOptions::new("/usr/bin/kwbox", args);
opts.user = Some("root".to_string());
opts.timeout_ms = Some(timeout_ms);
let res = exec_subprocess(vsock, &opts)?;
if res.exit_code != Some(0) {
let msg = format!(
"{} {}",
res.stderr_lossy().trim(),
res.stdout_lossy().trim()
);
bail!(
"mount {guest_path} failed (exit {:?}): {}",
res.exit_code,
msg.trim()
);
}
Ok(())
}
fn find_cow_export(&self, guest_path: &str) -> Result<(Arc<ExportSpec>, Arc<Mutex<CowLayer>>)> {
let want = guest_path.trim_end_matches('/');
let exports = self.exports.lock().unwrap();
for exp in exports.values() {
if exp.guest_path.trim_end_matches('/') == want {
let Some(cow) = &exp.cow else {
bail!("mount {guest_path:?} is not a copy-on-write (:cow) workspace");
};
return Ok((exp.clone(), cow.clone()));
}
}
bail!("no 9P mount found at {guest_path:?}")
}
pub fn diff_workspace(&self, guest_path: &str) -> Result<WorkspaceDiff> {
let (exp, cow) = self.find_cow_export(guest_path)?;
let guard = cow.lock().unwrap();
Ok(guard.diff(&exp.host_root, &exp.guest_path))
}
pub fn diff_all_cow_workspaces(&self) -> Vec<WorkspaceDiff> {
let exports: Vec<Arc<ExportSpec>> =
self.exports.lock().unwrap().values().cloned().collect();
let mut out = Vec::new();
for exp in exports {
if let Some(cow) = &exp.cow {
out.push(cow.lock().unwrap().diff(&exp.host_root, &exp.guest_path));
}
}
out.sort_by(|a, b| a.guest_path.cmp(&b.guest_path));
out
}
pub fn snapshot_workspace(&self, guest_path: &str) -> Result<WorkspaceSnapshot> {
let (exp, cow) = self.find_cow_export(guest_path)?;
Ok(WorkspaceSnapshot {
host_root: exp.host_root.clone(),
guest_path: exp.guest_path.clone(),
layer: cow.lock().unwrap().clone(),
})
}
pub fn snapshot_all_workspaces(&self) -> Vec<WorkspaceSnapshot> {
let exports: Vec<Arc<ExportSpec>> =
self.exports.lock().unwrap().values().cloned().collect();
let mut out = Vec::new();
for exp in exports {
if let Some(cow) = &exp.cow {
out.push(WorkspaceSnapshot {
host_root: exp.host_root.clone(),
guest_path: exp.guest_path.clone(),
layer: cow.lock().unwrap().clone(),
});
}
}
out.sort_by(|a, b| a.guest_path.cmp(&b.guest_path));
out
}
pub fn read_workspace_file(&self, guest_path: &str, rel_path: &str) -> Result<Option<Vec<u8>>> {
let (exp, cow) = self.find_cow_export(guest_path)?;
let rel = rel_from_key(rel_path);
cow.lock()
.unwrap()
.read_file(&exp.host_root, &rel)
.map_err(|e| format_err!("read workspace file {rel_path:?}: errno {e}"))
}
pub fn commit_workspace(&self, guest_path: &str) -> Result<WorkspaceDiff> {
let (exp, cow) = self.find_cow_export(guest_path)?;
cow.lock().unwrap().commit(&exp.host_root, &exp.guest_path)
}
pub fn discard_workspace(&self, guest_path: &str) -> Result<()> {
let (_exp, cow) = self.find_cow_export(guest_path)?;
let mut g = cow.lock().unwrap();
g.entries.clear();
g.opaque_dirs.clear();
g.discard_gen = g.discard_gen.wrapping_add(1);
Ok(())
}
fn serve_connection(&self, stream: VsockStream) {
let mut session = P9ConnSession {
msize: DEFAULT_MSIZE,
export: None,
fids: HashMap::new(),
monitor: self.monitor.clone(),
};
loop {
let mut len_buf = [0u8; 4];
if stream.read_exact_deadline(&mut len_buf, None).is_err() {
break;
}
let size = u32::from_le_bytes(len_buf) as usize;
if size < HDR_LEN || size > (DEFAULT_MSIZE as usize).max(1 << 20) {
break;
}
let mut frame = vec![0u8; size];
frame[0..4].copy_from_slice(&len_buf);
if stream.read_exact_deadline(&mut frame[4..], None).is_err() {
break;
}
let mtype = frame[4];
let tag = u16::from_le_bytes([frame[5], frame[6]]);
let reply = match session.handle(&self.exports, mtype, tag, &frame[HDR_LEN..]) {
Ok(w) => w.finish(mtype + 1, tag),
Err(errno) => {
let mut w = Writer::new(16);
w.u32(errno);
w.finish(RLERROR, tag)
}
};
if stream.write_all_deadline(&reply, None).is_err() {
break;
}
}
stream.close();
}
}
struct DirCacheEntry {
name: String,
rel_path: PathBuf,
qtype: u8,
dtype: u8,
ino: u64,
}
struct FidState {
rel_path: PathBuf, is_dir: bool,
file: Option<File>,
cow_open: bool,
dir_entries: Option<Vec<DirCacheEntry>>,
write_approved: bool,
}
struct P9ConnSession {
msize: u32,
export: Option<Arc<ExportSpec>>,
fids: HashMap<u32, FidState>,
monitor: Option<Arc<Monitor>>,
}
impl P9ConnSession {
fn audit_fs(
&self,
exp: &ExportSpec,
op: &str,
rel_path: &Path,
target_rel: Option<&Path>,
bytes: Option<usize>,
decision: &str,
) {
let Some(mon) = &self.monitor else { return };
let path_str = format_guest_rel(&exp.guest_path, rel_path);
let target_str = target_rel.map(|t| format_guest_rel(&exp.guest_path, t));
let sensitive = is_sensitive_path(&rel_path.to_string_lossy())
|| target_rel.is_some_and(|t| is_sensitive_path(&t.to_string_lossy()));
mon.emit(AuditEvent::FsOp {
ts_ms: now_unix_ms(),
mount: exp.guest_path.clone(),
op: op.to_string(),
path: path_str,
target_path: target_str,
bytes,
sensitive,
decision: decision.to_string(),
proc: mon.p9_proc(),
});
}
fn gate_fs_write(
&self,
exp: &ExportSpec,
op: &str,
rel_path: &Path,
target_rel: Option<&Path>,
) -> std::result::Result<(), u32> {
let Some(mon) = &self.monitor else {
return Ok(());
};
if !mon.ask_fs_write() {
return Ok(());
}
let target_path = format_guest_rel(&exp.guest_path, rel_path);
let detail = target_rel
.map(|t| format!("{op} -> {}", format_guest_rel(&exp.guest_path, t)))
.or_else(|| Some(op.to_string()));
let dec = mon.request_approval(
ApprovalKind::FsWrite,
&target_path,
target_path.clone(),
detail,
);
if !dec.is_allowed() {
self.audit_fs(exp, op, rel_path, target_rel, None, "deny_user");
return Err(EACCES);
}
Ok(())
}
fn gate_sensitive_read(
&self,
exp: &ExportSpec,
rel_path: &Path,
) -> std::result::Result<(), u32> {
let Some(mon) = &self.monitor else {
return Ok(());
};
if !mon.ask_sensitive_read() || !is_sensitive_path(&rel_path.to_string_lossy()) {
return Ok(());
}
let target_path = format_guest_rel(&exp.guest_path, rel_path);
let dec = mon.request_approval(
ApprovalKind::FsSensitiveRead,
&target_path,
target_path.clone(),
Some("sensitive_read".to_string()),
);
if !dec.is_allowed() {
self.audit_fs(exp, "open_read", rel_path, None, None, "deny_user");
return Err(EACCES);
}
Ok(())
}
fn handle(
&mut self,
exports: &Mutex<HashMap<String, Arc<ExportSpec>>>,
mtype: u8,
_tag: u16,
body: &[u8],
) -> std::result::Result<Writer, u32> {
let mut r = Reader::new(body);
if mtype == TFLUSH {
return Ok(Writer::new(HDR_LEN));
}
if mtype == TVERSION {
let req_msize = r.u32()?;
let ver = r.str()?;
self.msize = req_msize.clamp(4096, DEFAULT_MSIZE);
self.fids.clear();
let mut w = Writer::new(32);
w.u32(self.msize);
w.str(if ver.starts_with(P9_VERSION) {
P9_VERSION
} else {
"unknown"
});
return Ok(w);
}
if mtype == TAUTH {
return Err(EOPNOTSUPP);
}
if mtype == TATTACH {
let fid = r.u32()?;
let _afid = r.u32()?;
let _uname = r.str()?;
let aname = r.str()?;
let exp = exports.lock().unwrap().get(aname).cloned().ok_or(ENOENT)?;
let meta = fs::symlink_metadata(&exp.host_root).map_err(io_to_errno)?;
if !meta.is_dir() {
return Err(ENOTDIR);
}
let is_cow = exp.cow.is_some();
self.export = Some(exp);
self.fids.insert(
fid,
FidState {
rel_path: PathBuf::new(),
is_dir: true,
file: None,
cow_open: false,
dir_entries: None,
write_approved: false,
},
);
let mut w = Writer::new(24);
if is_cow {
w.u8(QTDIR);
w.u32(0);
w.u64(1);
} else {
w.qid(&meta, Path::new(""));
}
return Ok(w);
}
let exp = self.export.clone().ok_or(EBADF)?;
if exp.read_only {
let mutating = matches!(
mtype,
TLCREATE
| TSYMLINK
| TMKNOD
| TRENAME
| TSETATTR
| TLINK
| TMKDIR
| TRENAMEAT
| TUNLINKAT
| TWRITE
);
if mutating {
return Err(EROFS);
}
if mtype == TLOPEN && body.len() >= 8 {
let flags = u32::from_le_bytes([body[4], body[5], body[6], body[7]]);
if (flags & O_ACCMODE) != 0 || (flags & O_TRUNC) != 0 {
return Err(EROFS);
}
}
if mtype == TREMOVE {
let fid = r.u32()?;
self.fids.remove(&fid);
return Err(EROFS);
}
}
match mtype {
TWALK => {
let fid = r.u32()?;
let newfid = r.u32()?;
let nwname = r.u16()? as usize;
let base = self.fids.get(&fid).ok_or(EBADF)?;
let mut cur_rel = base.rel_path.clone();
let mut cur_is_dir = base.is_dir;
let mut qids: Vec<(u8, u32, u64)> = Vec::with_capacity(nwname);
for i in 0..nwname {
let name = r.str()?;
if !cur_is_dir {
if i == 0 {
return Err(ENOTDIR);
}
break;
}
let next_rel = match step_rel(&cur_rel, name) {
Ok(p) => p,
Err(e) => {
if i == 0 {
return Err(e);
}
break;
}
};
if let Some(cow) = &exp.cow {
match cow.lock().unwrap().stat_entry(&exp.host_root, &next_rel) {
Ok(st) => {
qids.push((
st.qtype,
(st.mtime as u32).wrapping_add(st.epoch as u32),
st.ino,
));
cur_is_dir = st.is_dir;
cur_rel = next_rel;
}
Err(e) => {
if i == 0 {
return Err(e);
}
break;
}
}
} else {
let host_path = match resolve_confined(&exp.host_root, &next_rel, false) {
Ok(p) => p,
Err(e) => {
if i == 0 {
return Err(e);
}
break;
}
};
match fs::symlink_metadata(&host_path) {
Ok(meta) => {
qids.push(meta_to_qid(&meta, &next_rel));
cur_is_dir = meta.is_dir();
cur_rel = next_rel;
}
Err(e) => {
if i == 0 {
return Err(io_to_errno(e));
}
break;
}
}
}
}
if qids.len() == nwname {
self.fids.insert(
newfid,
FidState {
rel_path: cur_rel,
is_dir: cur_is_dir,
file: None,
cow_open: false,
dir_entries: None,
write_approved: false,
},
);
}
let mut w = Writer::new(HDR_LEN + 2 + 13 * qids.len());
w.u16(qids.len() as u16);
for (qt, ver, path) in qids {
w.u8(qt);
w.u32(ver);
w.u64(path);
}
Ok(w)
}
TCLUNK => {
let fid = r.u32()?;
self.fids.remove(&fid).ok_or(EBADF)?;
Ok(Writer::new(HDR_LEN))
}
TREMOVE => {
let fid = r.u32()?;
let f = self.fids.remove(&fid).ok_or(EBADF)?;
if f.rel_path.as_os_str().is_empty() {
return Err(EBUSY);
}
self.gate_fs_write(&exp, "remove", &f.rel_path, None)?;
if let Some(cow) = &exp.cow {
cow.lock()
.unwrap()
.remove_entry(&exp.host_root, &f.rel_path, f.is_dir)?;
} else {
let host_path = resolve_confined(&exp.host_root, &f.rel_path, false)?;
if f.is_dir {
fs::remove_dir(&host_path).map_err(io_to_errno)?;
} else {
fs::remove_file(&host_path).map_err(io_to_errno)?;
}
}
self.audit_fs(&exp, "remove", &f.rel_path, None, None, "allow");
Ok(Writer::new(HDR_LEN))
}
TSTATFS => {
let fid = r.u32()?;
if !self.fids.contains_key(&fid) {
return Err(EBADF);
}
let mut w = Writer::new(72);
w.u32(V9FS_MAGIC);
w.u32(4096);
w.u64(1024 * 1024); w.u64(512 * 1024); w.u64(512 * 1024); w.u64(100_000); w.u64(50_000); w.u64(0); w.u32(255); Ok(w)
}
TLOPEN => {
let fid = r.u32()?;
let flags = r.u32()?;
let rel_path = self.fids.get(&fid).ok_or(EBADF)?.rel_path.clone();
if let Some(cow) = &exp.cow {
let st = cow.lock().unwrap().stat_entry(&exp.host_root, &rel_path)?;
if st.is_file {
let acc = flags & O_ACCMODE;
let read = acc != 1;
let write = acc != 0;
let truncate = (flags & O_TRUNC) != 0;
if read {
self.gate_sensitive_read(&exp, &rel_path)?;
}
if write || truncate {
self.gate_fs_write(&exp, "open_write", &rel_path, None)?;
}
let st2 = if write || truncate {
let mut g = cow.lock().unwrap();
g.copy_up_file(&exp.host_root, &rel_path)?;
if truncate
&& let Some(CowEntry::File { data, mtime, .. }) =
g.entries.get_mut(&norm_rel_key(&rel_path))
{
data.clear();
*mtime = now_sec();
}
g.stat_entry(&exp.host_root, &rel_path)?
} else {
st
};
let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
f.is_dir = false;
f.dir_entries = None;
f.file = None;
f.cow_open = true;
f.write_approved = write || truncate;
self.audit_fs(
&exp,
if write || truncate {
"open_write"
} else {
"open_read"
},
&rel_path,
None,
None,
"allow",
);
let mut w = Writer::new(32);
w.cow_qid(&st2);
w.u32(0);
return Ok(w);
}
let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
f.is_dir = st.is_dir;
f.dir_entries = None;
f.file = None;
f.cow_open = false;
let mut w = Writer::new(32);
w.cow_qid(&st);
w.u32(0);
return Ok(w);
}
let host_path = resolve_confined(&exp.host_root, &rel_path, false)?;
let meta = fs::symlink_metadata(&host_path).map_err(io_to_errno)?;
if meta.is_file() {
let acc = flags & O_ACCMODE;
let read = acc != 1;
let write = acc != 0;
let truncate = (flags & O_TRUNC) != 0;
let append = (flags & O_APPEND) != 0;
if read {
self.gate_sensitive_read(&exp, &rel_path)?;
}
if write || truncate {
self.gate_fs_write(&exp, "open_write", &rel_path, None)?;
}
let mut oo = OpenOptions::new();
oo.read(read).write(write).truncate(truncate).append(append);
configure_open_options(&mut oo, None);
let file = open_nofollow(&oo, &host_path)?;
let m2 = file.metadata().map_err(io_to_errno)?;
let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
f.is_dir = false;
f.dir_entries = None;
f.file = Some(file);
f.cow_open = false;
f.write_approved = write || truncate;
self.audit_fs(
&exp,
if write || truncate {
"open_write"
} else {
"open_read"
},
&rel_path,
None,
None,
"allow",
);
let mut w = Writer::new(32);
w.qid(&m2, &rel_path);
w.u32(0);
return Ok(w);
}
let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
f.is_dir = meta.is_dir();
f.dir_entries = None;
let mut w = Writer::new(32);
w.qid(&meta, &rel_path);
w.u32(0);
Ok(w)
}
TLCREATE => {
let fid = r.u32()?;
let name = r.str()?;
let flags = r.u32()?;
let mode = r.u32()?;
validate_component(name)?;
let parent_rel = {
let f = self.fids.get(&fid).ok_or(EBADF)?;
if !f.is_dir {
return Err(ENOTDIR);
}
f.rel_path.clone()
};
let new_rel = parent_rel.join(name);
if let Some(cow) = &exp.cow {
let existing = cow
.lock()
.unwrap()
.stat_entry(&exp.host_root, &new_rel)
.ok();
if (flags & O_ACCMODE) != 1 && existing.is_some() {
self.gate_sensitive_read(&exp, &new_rel)?;
}
self.gate_fs_write(&exp, "create", &new_rel, None)?;
let st = {
let mut g = cow.lock().unwrap();
if existing.is_some() {
if (flags & O_EXCL) != 0 {
return Err(EEXIST);
}
if (flags & O_TRUNC) != 0 {
g.entries.insert(
norm_rel_key(&new_rel),
CowEntry::File {
data: Vec::new(),
mode: mode & 0o7777,
mtime: now_sec(),
},
);
} else {
g.copy_up_file(&exp.host_root, &new_rel)?;
}
} else {
g.entries.insert(
norm_rel_key(&new_rel),
CowEntry::File {
data: Vec::new(),
mode: mode & 0o7777,
mtime: now_sec(),
},
);
}
g.stat_entry(&exp.host_root, &new_rel)?
};
self.audit_fs(&exp, "create", &new_rel, None, None, "allow");
let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
f.rel_path = new_rel;
f.is_dir = false;
f.file = None;
f.cow_open = true;
f.dir_entries = None;
f.write_approved = true;
let mut w = Writer::new(32);
w.cow_qid(&st);
w.u32(0);
return Ok(w);
}
let host_path = resolve_confined(&exp.host_root, &new_rel, true)?;
if (flags & O_ACCMODE) != 1 && host_path.exists() {
self.gate_sensitive_read(&exp, &new_rel)?;
}
self.gate_fs_write(&exp, "create", &new_rel, None)?;
let mut oo = OpenOptions::new();
oo.read((flags & O_ACCMODE) != 1)
.write(true)
.append((flags & O_APPEND) != 0)
.truncate((flags & O_TRUNC) != 0);
configure_open_options(&mut oo, Some(mode & 0o7777));
if (flags & O_EXCL) != 0 {
oo.create_new(true);
} else {
oo.create(true);
}
let file = open_nofollow(&oo, &host_path)?;
let meta = file.metadata().map_err(io_to_errno)?;
self.audit_fs(&exp, "create", &new_rel, None, None, "allow");
let qid_rel = new_rel.clone();
let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
f.rel_path = new_rel;
f.is_dir = false;
f.file = Some(file);
f.cow_open = false;
f.dir_entries = None;
f.write_approved = true;
let mut w = Writer::new(32);
w.qid(&meta, &qid_rel);
w.u32(0);
Ok(w)
}
TMKDIR => {
let fid = r.u32()?;
let name = r.str()?;
let mode = r.u32()?;
validate_component(name)?;
let parent_rel = {
let f = self.fids.get(&fid).ok_or(EBADF)?;
if !f.is_dir {
return Err(ENOTDIR);
}
f.rel_path.clone()
};
let new_rel = parent_rel.join(name);
self.gate_fs_write(&exp, "mkdir", &new_rel, None)?;
if let Some(cow) = &exp.cow {
let st = {
let mut g = cow.lock().unwrap();
if g.stat_entry(&exp.host_root, &new_rel).is_ok() {
return Err(EEXIST);
}
let key = norm_rel_key(&new_rel);
if matches!(g.entries.get(&key), Some(CowEntry::Whiteout))
|| resolve_confined(&exp.host_root, &new_rel, false)
.ok()
.and_then(|hp| fs::symlink_metadata(&hp).ok())
.is_some()
{
g.opaque_dirs.insert(key.clone());
}
g.entries.insert(
key,
CowEntry::Dir {
mode: mode & 0o7777,
mtime: now_sec(),
},
);
g.stat_entry(&exp.host_root, &new_rel)?
};
self.audit_fs(&exp, "mkdir", &new_rel, None, None, "allow");
let mut w = Writer::new(24);
w.cow_qid(&st);
return Ok(w);
}
let host_path = resolve_confined(&exp.host_root, &new_rel, true)?;
fs::create_dir(&host_path).map_err(io_to_errno)?;
let _ = set_unix_mode(&host_path, mode & 0o7777);
let meta = fs::symlink_metadata(&host_path).map_err(io_to_errno)?;
self.audit_fs(&exp, "mkdir", &new_rel, None, None, "allow");
let mut w = Writer::new(24);
w.qid(&meta, &new_rel);
Ok(w)
}
TSYMLINK => {
let fid = r.u32()?;
let name = r.str()?;
let target = r.str()?;
validate_component(name)?;
let parent_rel = {
let f = self.fids.get(&fid).ok_or(EBADF)?;
if !f.is_dir {
return Err(ENOTDIR);
}
f.rel_path.clone()
};
let new_rel = parent_rel.join(name);
self.gate_fs_write(&exp, "symlink", &new_rel, None)?;
if let Some(cow) = &exp.cow {
let st = {
let mut g = cow.lock().unwrap();
if g.stat_entry(&exp.host_root, &new_rel).is_ok() {
return Err(EEXIST);
}
g.entries.insert(
norm_rel_key(&new_rel),
CowEntry::Symlink {
target: target.to_string(),
mtime: now_sec(),
},
);
g.stat_entry(&exp.host_root, &new_rel)?
};
self.audit_fs(&exp, "symlink", &new_rel, None, None, "allow");
let mut w = Writer::new(24);
w.cow_qid(&st);
return Ok(w);
}
let host_path = resolve_confined(&exp.host_root, &new_rel, true)?;
create_symlink(target, &host_path)?;
let meta = fs::symlink_metadata(&host_path).map_err(io_to_errno)?;
self.audit_fs(&exp, "symlink", &new_rel, None, None, "allow");
let mut w = Writer::new(24);
w.qid(&meta, &new_rel);
Ok(w)
}
TLINK => Err(EPERM),
TMKNOD | TXATTRWALK | TXATTRCREATE => Err(EOPNOTSUPP),
TUNLINKAT => {
let dfid = r.u32()?;
let name = r.str()?;
let flags = r.u32()?;
validate_component(name)?;
let parent_rel = {
let f = self.fids.get(&dfid).ok_or(EBADF)?;
if !f.is_dir {
return Err(ENOTDIR);
}
f.rel_path.clone()
};
let target_rel = parent_rel.join(name);
let op = if (flags & AT_REMOVEDIR) != 0 {
"rmdir"
} else {
"unlink"
};
self.gate_fs_write(&exp, op, &target_rel, None)?;
if let Some(cow) = &exp.cow {
cow.lock().unwrap().remove_entry(
&exp.host_root,
&target_rel,
(flags & AT_REMOVEDIR) != 0,
)?;
} else {
let host_path = resolve_confined(&exp.host_root, &target_rel, false)?;
if (flags & AT_REMOVEDIR) != 0 {
fs::remove_dir(&host_path).map_err(io_to_errno)?;
} else {
fs::remove_file(&host_path).map_err(io_to_errno)?;
}
}
self.audit_fs(&exp, op, &target_rel, None, None, "allow");
Ok(Writer::new(HDR_LEN))
}
TRENAMEAT | TRENAME => {
let (from_rel, to_rel) = if mtype == TRENAMEAT {
let odfid = r.u32()?;
let oname = r.str()?;
let ndfid = r.u32()?;
let nname = r.str()?;
validate_component(oname)?;
validate_component(nname)?;
let od = self.fids.get(&odfid).ok_or(EBADF)?;
let nd = self.fids.get(&ndfid).ok_or(EBADF)?;
if !od.is_dir || !nd.is_dir {
return Err(ENOTDIR);
}
(od.rel_path.join(oname), nd.rel_path.join(nname))
} else {
let fid = r.u32()?;
let dfid = r.u32()?;
let name = r.str()?;
validate_component(name)?;
let f = self.fids.get(&fid).ok_or(EBADF)?;
let d = self.fids.get(&dfid).ok_or(EBADF)?;
if !d.is_dir {
return Err(ENOTDIR);
}
(f.rel_path.clone(), d.rel_path.join(name))
};
if from_rel.as_os_str().is_empty() {
return Err(EBUSY);
}
self.gate_sensitive_read(&exp, &from_rel)?;
self.gate_fs_write(&exp, "rename", &from_rel, Some(&to_rel))?;
if let Some(cow) = &exp.cow {
cow.lock()
.unwrap()
.rename_entry(&exp.host_root, &from_rel, &to_rel)?;
for f in self.fids.values_mut() {
if let Ok(rest) = f.rel_path.strip_prefix(&from_rel) {
f.rel_path = to_rel.join(rest);
}
}
} else {
let from_host = resolve_confined(&exp.host_root, &from_rel, false)?;
let to_host = resolve_confined(&exp.host_root, &to_rel, true)?;
if from_host != to_host {
#[cfg(windows)]
if to_host.is_file() {
let _ = fs::remove_file(&to_host);
}
fs::rename(&from_host, &to_host).map_err(io_to_errno)?;
for f in self.fids.values_mut() {
if let Ok(rest) = f.rel_path.strip_prefix(&from_rel) {
f.rel_path = to_rel.join(rest);
}
}
}
}
self.audit_fs(&exp, "rename", &from_rel, Some(&to_rel), None, "allow");
Ok(Writer::new(HDR_LEN))
}
TREADLINK => {
let fid = r.u32()?;
let f = self.fids.get(&fid).ok_or(EBADF)?;
let target = if let Some(cow) = &exp.cow {
let g = cow.lock().unwrap();
let key = norm_rel_key(&f.rel_path);
if let Some(entry) = g.entries.get(&key) {
match entry {
CowEntry::Symlink { target, .. } => target.clone(),
CowEntry::Whiteout => return Err(ENOENT),
_ => return Err(EINVAL),
}
} else if g.is_host_hidden(&key) {
return Err(ENOENT);
} else {
let host_path = resolve_confined(&exp.host_root, &f.rel_path, false)?;
fs::read_link(&host_path)
.map_err(io_to_errno)?
.to_string_lossy()
.into_owned()
}
} else {
let host_path = resolve_confined(&exp.host_root, &f.rel_path, false)?;
fs::read_link(&host_path)
.map_err(io_to_errno)?
.to_string_lossy()
.into_owned()
};
let mut w = Writer::new(64);
w.str(&target);
Ok(w)
}
TGETATTR => {
let fid = r.u32()?;
let _mask = r.u64()?;
let f = self.fids.get(&fid).ok_or(EBADF)?;
if let Some(cow) = &exp.cow {
let st = cow
.lock()
.unwrap()
.stat_entry(&exp.host_root, &f.rel_path)?;
let mut w = Writer::new(160);
w.u64(P9_STATS_BASIC);
w.cow_qid(&st);
w.u32(st.fmt | st.perm);
w.u32(1000); w.u32(1000); w.u64(st.nlink);
w.u64(0); w.u64(st.len);
w.u64(4096);
w.u64(st.len.div_ceil(512));
w.u64(st.mtime);
w.u64(0);
w.u64(st.mtime);
w.u64(0);
w.u64(st.mtime);
w.u64(0);
w.u64(0);
w.u64(0);
w.u64(st.epoch); w.u64(st.epoch); return Ok(w);
}
let meta = if let Some(file) = &f.file {
file.metadata().map_err(io_to_errno)?
} else {
let host_path = resolve_confined(&exp.host_root, &f.rel_path, false)?;
fs::symlink_metadata(&host_path).map_err(io_to_errno)?
};
let ft = meta.file_type();
let fmt = if ft.is_dir() {
S_IFDIR
} else if ft.is_symlink() {
S_IFLNK
} else {
S_IFREG
};
let perm = meta_perm(&meta);
let size = meta.len();
let (atime_s, atime_ns, mtime_s, mtime_ns, ctime_s, ctime_ns) = meta_times(&meta);
let mut w = Writer::new(160);
w.u64(P9_STATS_BASIC);
w.qid(&meta, &f.rel_path);
w.u32(fmt | perm);
w.u32(1000); w.u32(1000); w.u64(meta_nlink(&meta));
w.u64(0); w.u64(size);
w.u64(4096);
w.u64(size.div_ceil(512));
w.u64(atime_s);
w.u64(atime_ns);
w.u64(mtime_s);
w.u64(mtime_ns);
w.u64(ctime_s);
w.u64(ctime_ns);
w.u64(0);
w.u64(0);
w.u64(0); w.u64(0); Ok(w)
}
TSETATTR => {
let fid = r.u32()?;
let valid = r.u32()?;
let mode = r.u32()?;
let _uid = r.u32()?;
let _gid = r.u32()?;
let size = r.u64()?;
let _as = r.u64()?;
let _an = r.u64()?;
let _ms = r.u64()?;
let _mn = r.u64()?;
let (rel_path, already_approved) = {
let f = self.fids.get(&fid).ok_or(EBADF)?;
(f.rel_path.clone(), f.write_approved)
};
if (valid & 9) != 0 && !already_approved {
let op = if (valid & 8) != 0 {
"truncate"
} else {
"chmod"
};
self.gate_fs_write(&exp, op, &rel_path, None)?;
}
if let Some(cow) = &exp.cow {
let mut g = cow.lock().unwrap();
let key = norm_rel_key(&rel_path);
if (valid & 8) != 0 {
g.copy_up_file(&exp.host_root, &rel_path)?;
if let Some(CowEntry::File { data, mtime, .. }) = g.entries.get_mut(&key) {
data.resize(size as usize, 0);
*mtime = now_sec();
}
}
if (valid & 1) != 0 {
let st = g.stat_entry(&exp.host_root, &rel_path)?;
if st.is_file {
g.copy_up_file(&exp.host_root, &rel_path)?;
if let Some(CowEntry::File { mode: m, mtime, .. }) =
g.entries.get_mut(&key)
{
*m = mode & 0o7777;
*mtime = now_sec();
}
} else if st.is_dir {
g.entries.insert(
key,
CowEntry::Dir {
mode: mode & 0o7777,
mtime: now_sec(),
},
);
}
}
} else {
let f = self.fids.get(&fid).ok_or(EBADF)?;
let host_path = resolve_confined(&exp.host_root, &f.rel_path, false)?;
if (valid & 1) != 0 {
set_unix_mode(&host_path, mode & 0o7777)?;
}
if (valid & 8) != 0 {
if let Some(file) = &f.file {
file.set_len(size).map_err(io_to_errno)?;
} else {
let mut oo = OpenOptions::new();
oo.write(true);
configure_open_options(&mut oo, None);
let file = open_nofollow(&oo, &host_path)?;
file.set_len(size).map_err(io_to_errno)?;
}
}
}
if (valid & 9) != 0 {
let op = if (valid & 8) != 0 {
"truncate"
} else {
"chmod"
};
self.audit_fs(&exp, op, &rel_path, None, None, "allow");
}
Ok(Writer::new(HDR_LEN))
}
TREADDIR => {
let fid = r.u32()?;
let offset = r.u64()? as usize;
let count = r.u32()? as usize;
let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
if !f.is_dir {
return Err(ENOTDIR);
}
if offset == 0 || f.dir_entries.is_none() {
let parent_rel = f.rel_path.parent().unwrap_or(Path::new("")).to_path_buf();
if let Some(cow) = &exp.cow {
let g = cow.lock().unwrap();
let self_ino = g.ino_for(&f.rel_path);
let parent_ino = g.ino_for(&parent_rel);
let mut entries = vec![
DirCacheEntry {
name: ".".into(),
rel_path: f.rel_path.clone(),
qtype: QTDIR,
dtype: DT_DIR,
ino: self_ino,
},
DirCacheEntry {
name: "..".into(),
rel_path: parent_rel,
qtype: QTDIR,
dtype: DT_DIR,
ino: parent_ino,
},
];
entries.extend(g.merged_children(&exp.host_root, &f.rel_path)?);
f.dir_entries = Some(entries);
} else {
let host_path = resolve_confined(&exp.host_root, &f.rel_path, false)?;
let self_meta = fs::symlink_metadata(&host_path).map_err(io_to_errno)?;
let self_ino = meta_ino(&self_meta, &f.rel_path);
let mut entries = vec![
DirCacheEntry {
name: ".".into(),
rel_path: f.rel_path.clone(),
qtype: QTDIR,
dtype: DT_DIR,
ino: self_ino,
},
DirCacheEntry {
name: "..".into(),
rel_path: parent_rel,
qtype: QTDIR,
dtype: DT_DIR,
ino: self_ino,
},
];
for dent in fs::read_dir(&host_path).map_err(io_to_errno)? {
let Ok(dent) = dent else { continue };
let Ok(meta) = dent.metadata() else { continue };
let name = dent.file_name().to_string_lossy().into_owned();
let ft = meta.file_type();
let (qtype, dtype) = if ft.is_dir() {
(QTDIR, DT_DIR)
} else if ft.is_symlink() {
(QTSYMLINK, DT_LNK)
} else {
(QTFILE, DT_REG)
};
let child_rel = f.rel_path.join(&name);
let child_ino = meta_ino(&meta, &child_rel);
entries.push(DirCacheEntry {
rel_path: child_rel,
name,
qtype,
dtype,
ino: child_ino,
});
}
f.dir_entries = Some(entries);
}
}
let max = count.min((self.msize as usize).saturating_sub(HDR_LEN + 4));
let mut w = Writer::new(max.min(65536) + HDR_LEN + 4);
let count_pos = w.buf.len();
w.u32(0);
let data_start = w.buf.len();
if let Some(entries) = &f.dir_entries {
for (i, e) in entries.iter().enumerate().skip(offset) {
let nb = e.name.as_bytes();
if (w.buf.len() - data_start) + 24 + nb.len() > max {
break;
}
let _ = &e.rel_path;
w.u8(e.qtype);
w.u32(0);
w.u64(e.ino);
w.u64((i + 1) as u64);
w.u8(e.dtype);
w.u16(nb.len() as u16);
w.bytes(nb);
}
}
let written = (w.buf.len() - data_start) as u32;
w.buf[count_pos..count_pos + 4].copy_from_slice(&written.to_le_bytes());
Ok(w)
}
TREAD => {
let fid = r.u32()?;
let offset = r.u64()?;
let req_count = r.u32()? as usize;
let count = req_count.min((self.msize as usize).saturating_sub(HDR_LEN + 4));
let f = self.fids.get(&fid).ok_or(EBADF)?;
if let Some(cow) = &exp.cow {
if !f.cow_open {
return Err(if f.is_dir { EISDIR } else { EBADF });
}
let data = cow
.lock()
.unwrap()
.read_file(&exp.host_root, &f.rel_path)?
.ok_or(ENOENT)?;
let start = (offset as usize).min(data.len());
let end = start.saturating_add(count).min(data.len());
let slice = &data[start..end];
let mut w = Writer::new(HDR_LEN + 4 + slice.len());
w.u32(slice.len() as u32);
w.bytes(slice);
return Ok(w);
}
let Some(file) = &f.file else {
return Err(if f.is_dir { EISDIR } else { EBADF });
};
let mut buf = vec![0u8; count];
let n = file_read_at(file, &mut buf, offset).map_err(io_to_errno)?;
let mut w = Writer::new(HDR_LEN + 4 + n);
w.u32(n as u32);
w.bytes(&buf[..n]);
Ok(w)
}
TWRITE => {
let fid = r.u32()?;
let offset = r.u64()?;
let count = r.u32()? as usize;
let data = r.bytes(count)?;
let (rel_path, write_approved) = {
let f = self.fids.get(&fid).ok_or(EBADF)?;
(f.rel_path.clone(), f.write_approved)
};
if !write_approved {
self.gate_fs_write(&exp, "write", &rel_path, None)?;
if let Some(f) = self.fids.get_mut(&fid) {
f.write_approved = true;
}
}
if let Some(cow) = &exp.cow {
let f = self.fids.get(&fid).ok_or(EBADF)?;
if !f.cow_open {
return Err(if f.is_dir { EISDIR } else { EBADF });
}
let mut g = cow.lock().unwrap();
g.copy_up_file(&exp.host_root, &rel_path)?;
let key = norm_rel_key(&rel_path);
let Some(CowEntry::File {
data: buf, mtime, ..
}) = g.entries.get_mut(&key)
else {
return Err(EISDIR);
};
let start = offset as usize;
let end = start.checked_add(data.len()).ok_or(EINVAL)?;
if end > buf.len() {
buf.resize(end, 0);
}
buf[start..end].copy_from_slice(data);
*mtime = now_sec();
drop(g);
self.audit_fs(&exp, "write", &rel_path, None, Some(data.len()), "allow");
let mut w = Writer::new(16);
w.u32(data.len() as u32);
return Ok(w);
}
let f = self.fids.get(&fid).ok_or(EBADF)?;
let Some(file) = &f.file else {
return Err(if f.is_dir { EISDIR } else { EBADF });
};
let n = file_write_at(file, data, offset).map_err(io_to_errno)?;
self.audit_fs(&exp, "write", &rel_path, None, Some(n), "allow");
let mut w = Writer::new(16);
w.u32(n as u32);
Ok(w)
}
TFSYNC => {
let fid = r.u32()?;
let f = self.fids.get(&fid).ok_or(EBADF)?;
if let Some(file) = &f.file {
file.sync_all().map_err(io_to_errno)?;
}
Ok(Writer::new(HDR_LEN))
}
TLOCK => {
let fid = r.u32()?;
if !self.fids.contains_key(&fid) {
return Err(EBADF);
}
let mut w = Writer::new(12);
w.u8(0); Ok(w)
}
TGETLOCK => {
let fid = r.u32()?;
if !self.fids.contains_key(&fid) {
return Err(EBADF);
}
let _ty = r.u8()?;
let start = r.u64()?;
let len = r.u64()?;
let proc_id = r.u32()?;
let client = r.str()?;
let mut w = Writer::new(48);
w.u8(2); w.u64(start);
w.u64(len);
w.u32(proc_id);
w.str(client);
Ok(w)
}
_ => Err(EOPNOTSUPP),
}
}
}
fn format_guest_rel(mount_root: &str, rel: &Path) -> String {
let base = mount_root.trim_end_matches('/');
let rel_s = rel.to_string_lossy().replace('\\', "/");
if rel_s.is_empty() {
if base.is_empty() {
"/".to_string()
} else {
base.to_string()
}
} else {
format!("{base}/{rel_s}")
}
}
fn validate_component(name: &str) -> std::result::Result<(), u32> {
if name.is_empty()
|| name == "."
|| name == ".."
|| name.contains('/')
|| name.contains('\\')
|| name.contains('\0')
{
return Err(EINVAL);
}
#[cfg(windows)]
if name.contains(':') {
return Err(EINVAL);
}
Ok(())
}
fn step_rel(base: &Path, name: &str) -> std::result::Result<PathBuf, u32> {
if name == ".." {
Ok(base.parent().unwrap_or(Path::new("")).to_path_buf())
} else if name == "." {
Ok(base.to_path_buf())
} else {
validate_component(name)?;
Ok(base.join(name))
}
}
fn resolve_confined(
canonical_root: &Path,
rel: &Path,
allow_missing_leaf: bool,
) -> std::result::Result<PathBuf, u32> {
let mut cur = canonical_root.to_path_buf();
let comps: Vec<&std::ffi::OsStr> = rel
.components()
.map(|c| match c {
Component::Normal(s) => Ok(s),
_ => Err(EINVAL),
})
.collect::<std::result::Result<_, _>>()?;
for (idx, comp) in comps.iter().enumerate() {
let is_last = idx + 1 == comps.len();
let next = cur.join(comp);
if is_last && allow_missing_leaf {
return Ok(next);
}
match fs::symlink_metadata(&next) {
Ok(meta) => {
if meta.file_type().is_symlink() {
if is_last {
return Ok(next);
}
let resolved = fs::canonicalize(&next).map_err(io_to_errno)?;
if !resolved.starts_with(canonical_root) {
return Err(EACCES);
}
cur = resolved;
} else {
cur = next;
}
}
Err(e) => return Err(io_to_errno(e)),
}
}
if !cur.starts_with(canonical_root) {
return Err(EACCES);
}
Ok(cur)
}
fn file_read_at(file: &File, dst: &mut [u8], offset: u64) -> io::Result<usize> {
#[cfg(unix)]
{
use std::os::unix::fs::FileExt;
file.read_at(dst, offset)
}
#[cfg(windows)]
{
use std::os::windows::fs::FileExt;
file.seek_read(dst, offset)
}
}
fn file_write_at(file: &File, src: &[u8], offset: u64) -> io::Result<usize> {
#[cfg(unix)]
{
use std::os::unix::fs::FileExt;
file.write_at(src, offset)
}
#[cfg(windows)]
{
use std::os::windows::fs::FileExt;
file.seek_write(src, offset)
}
}
fn configure_open_options(oo: &mut OpenOptions, mode: Option<u32>) {
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
if let Some(m) = mode {
oo.mode(m);
}
oo.custom_flags(libc::O_NOFOLLOW);
}
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
let _ = mode;
oo.share_mode(1 | 2 | 4);
}
}
fn open_nofollow(oo: &OpenOptions, host_path: &Path) -> std::result::Result<File, u32> {
#[cfg(windows)]
if let Ok(meta) = fs::symlink_metadata(host_path)
&& meta.file_type().is_symlink()
{
return Err(EACCES);
}
oo.open(host_path).map_err(io_to_errno)
}
fn set_unix_mode(host_path: &Path, mode: u32) -> std::result::Result<(), u32> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(host_path, fs::Permissions::from_mode(mode)).map_err(io_to_errno)
}
#[cfg(not(unix))]
{
let _ = (host_path, mode);
Ok(())
}
}
fn create_symlink(target: &str, host_path: &Path) -> std::result::Result<(), u32> {
#[cfg(unix)]
{
std::os::unix::fs::symlink(target, host_path).map_err(io_to_errno)
}
#[cfg(not(unix))]
{
let _ = (target, host_path);
Err(EOPNOTSUPP)
}
}
fn meta_ino(meta: &fs::Metadata, rel_path: &Path) -> u64 {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
let _ = rel_path;
meta.ino()
}
#[cfg(not(unix))]
{
let _ = meta;
let norm = rel_path.to_string_lossy().replace('\\', "/");
if norm.is_empty() {
return 1;
}
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in norm.as_bytes() {
h ^= *b as u64;
h = h.wrapping_mul(0x0100_0000_01b3);
}
h | 2
}
}
fn meta_perm(meta: &fs::Metadata) -> u32 {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
meta.mode() & 0o7777
}
#[cfg(not(unix))]
{
if meta.is_dir() {
0o755
} else if meta.permissions().readonly() {
0o444
} else {
0o644
}
}
}
fn meta_nlink(meta: &fs::Metadata) -> u64 {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
meta.nlink()
}
#[cfg(not(unix))]
{
if meta.is_dir() { 2 } else { 1 }
}
}
fn meta_times(meta: &fs::Metadata) -> (u64, u64, u64, u64, u64, u64) {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
(
meta.atime().max(0) as u64,
meta.atime_nsec().max(0) as u64,
meta.mtime().max(0) as u64,
meta.mtime_nsec().max(0) as u64,
meta.ctime().max(0) as u64,
meta.ctime_nsec().max(0) as u64,
)
}
#[cfg(not(unix))]
{
let to_pair = |res: io::Result<SystemTime>| -> (u64, u64) {
res.ok()
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map(|d| (d.as_secs(), d.subsec_nanos() as u64))
.unwrap_or((0, 0))
};
let (as_, an) = to_pair(meta.accessed());
let (ms, mn) = to_pair(meta.modified());
let (cs, cn) = to_pair(meta.created());
(as_, an, ms, mn, cs, cn)
}
}
fn meta_to_qid(meta: &fs::Metadata, rel_path: &Path) -> (u8, u32, u64) {
let ft = meta.file_type();
let qt = if ft.is_dir() {
QTDIR
} else if ft.is_symlink() {
QTSYMLINK
} else {
QTFILE
};
let ver = meta
.modified()
.ok()
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map(|d| d.as_secs() as u32)
.unwrap_or_else(|| {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as u32)
.unwrap_or(0)
});
(qt, ver, meta_ino(meta, rel_path))
}
fn io_to_errno(e: io::Error) -> u32 {
#[cfg(unix)]
if let Some(raw) = e.raw_os_error()
&& raw > 0
{
return raw as u32;
}
#[cfg(windows)]
if let Some(raw) = e.raw_os_error() {
match raw {
32 | 33 => return EBUSY, 145 => return ENOTEMPTY, _ => {}
}
}
match e.kind() {
io::ErrorKind::NotFound => ENOENT,
io::ErrorKind::PermissionDenied => EACCES,
io::ErrorKind::AlreadyExists => EEXIST,
io::ErrorKind::InvalidInput => EINVAL,
io::ErrorKind::NotADirectory => ENOTDIR,
io::ErrorKind::IsADirectory => EISDIR,
io::ErrorKind::DirectoryNotEmpty => ENOTEMPTY,
io::ErrorKind::ReadOnlyFilesystem => EROFS,
_ => EIO,
}
}
struct Reader<'a> {
buf: &'a [u8],
p: usize,
}
impl<'a> Reader<'a> {
fn new(buf: &'a [u8]) -> Self {
Self { buf, p: 0 }
}
fn u8(&mut self) -> std::result::Result<u8, u32> {
if self.p + 1 > self.buf.len() {
return Err(EPROTO);
}
let v = self.buf[self.p];
self.p += 1;
Ok(v)
}
fn u16(&mut self) -> std::result::Result<u16, u32> {
if self.p + 2 > self.buf.len() {
return Err(EPROTO);
}
let v = u16::from_le_bytes([self.buf[self.p], self.buf[self.p + 1]]);
self.p += 2;
Ok(v)
}
fn u32(&mut self) -> std::result::Result<u32, u32> {
if self.p + 4 > self.buf.len() {
return Err(EPROTO);
}
let v = u32::from_le_bytes(self.buf[self.p..self.p + 4].try_into().unwrap());
self.p += 4;
Ok(v)
}
fn u64(&mut self) -> std::result::Result<u64, u32> {
if self.p + 8 > self.buf.len() {
return Err(EPROTO);
}
let v = u64::from_le_bytes(self.buf[self.p..self.p + 8].try_into().unwrap());
self.p += 8;
Ok(v)
}
fn bytes(&mut self, n: usize) -> std::result::Result<&'a [u8], u32> {
if self.p + n > self.buf.len() {
return Err(EPROTO);
}
let s = &self.buf[self.p..self.p + n];
self.p += n;
Ok(s)
}
fn str(&mut self) -> std::result::Result<&'a str, u32> {
let len = self.u16()? as usize;
let b = self.bytes(len)?;
std::str::from_utf8(b).map_err(|_| EINVAL)
}
}
struct Writer {
buf: Vec<u8>,
}
impl Writer {
fn new(cap: usize) -> Self {
let mut buf = Vec::with_capacity(cap.max(HDR_LEN));
buf.resize(HDR_LEN, 0);
Self { buf }
}
fn u8(&mut self, v: u8) {
self.buf.push(v);
}
fn u16(&mut self, v: u16) {
self.buf.extend_from_slice(&v.to_le_bytes());
}
fn u32(&mut self, v: u32) {
self.buf.extend_from_slice(&v.to_le_bytes());
}
fn u64(&mut self, v: u64) {
self.buf.extend_from_slice(&v.to_le_bytes());
}
fn bytes(&mut self, b: &[u8]) {
self.buf.extend_from_slice(b);
}
fn str(&mut self, s: &str) {
let b = s.as_bytes();
self.u16(b.len() as u16);
self.bytes(b);
}
fn qid(&mut self, meta: &fs::Metadata, rel_path: &Path) {
let (qt, ver, ino) = meta_to_qid(meta, rel_path);
self.u8(qt);
self.u32(ver);
self.u64(ino);
}
fn cow_qid(&mut self, st: &CowStat) {
self.u8(st.qtype);
self.u32((st.mtime as u32).wrapping_add(st.epoch as u32));
self.u64(st.ino);
}
fn finish(mut self, mtype: u8, tag: u16) -> Vec<u8> {
let sz = self.buf.len() as u32;
self.buf[0..4].copy_from_slice(&sz.to_le_bytes());
self.buf[4] = mtype;
self.buf[5..7].copy_from_slice(&tag.to_le_bytes());
self.buf
}
}