Skip to main content

unkernel_rs/
fs9p.rs

1//! Scoped host directory **9P2000.L** server over virtio-vsock port `564`.
2//!
3//! Exports host directories to the Linux guest via `/usr/bin/kwbox 9p <export> <guest_path> [ro]`
4//! with strict canonical path confinement (blocking `..` escapes and symlink escapes outside the
5//! mounted directory) and strict `EROFS` enforcement on read-only mounts.
6
7use crate::kwtty::{ExecOptions, exec_subprocess};
8use crate::monitor::{ApprovalKind, AuditEvent, Monitor, is_sensitive_path, now_unix_ms};
9use crate::vsock::{VsockHost, VsockStream};
10use serde::{Deserialize, Serialize};
11use std::collections::{BTreeMap, HashMap, HashSet};
12use std::fs::{self, File, OpenOptions};
13use std::io;
14use std::path::{Component, Path, PathBuf};
15use std::sync::{Arc, Mutex};
16use std::time::{SystemTime, UNIX_EPOCH};
17use wasmtime::{Result, bail, format_err};
18
19pub const P9_VSOCK_PORT: u32 = 564;
20const P9_VERSION: &str = "9P2000.L";
21const DEFAULT_MSIZE: u32 = 131_072;
22const HDR_LEN: usize = 7;
23
24// 9P2000.L message types
25const RLERROR: u8 = 7;
26const TSTATFS: u8 = 8;
27const TLOPEN: u8 = 12;
28const TLCREATE: u8 = 14;
29const TSYMLINK: u8 = 16;
30const TMKNOD: u8 = 18;
31const TRENAME: u8 = 20;
32const TREADLINK: u8 = 22;
33const TGETATTR: u8 = 24;
34const TSETATTR: u8 = 26;
35const TXATTRWALK: u8 = 30;
36const TXATTRCREATE: u8 = 32;
37const TREADDIR: u8 = 40;
38const TFSYNC: u8 = 50;
39const TLOCK: u8 = 52;
40const TGETLOCK: u8 = 54;
41const TLINK: u8 = 70;
42const TMKDIR: u8 = 72;
43const TRENAMEAT: u8 = 74;
44const TUNLINKAT: u8 = 76;
45const TVERSION: u8 = 100;
46const TAUTH: u8 = 102;
47const TATTACH: u8 = 104;
48const TFLUSH: u8 = 108;
49const TWALK: u8 = 110;
50const TREAD: u8 = 116;
51const TWRITE: u8 = 118;
52const TCLUNK: u8 = 120;
53const TREMOVE: u8 = 122;
54
55const QTDIR: u8 = 0x80;
56const QTSYMLINK: u8 = 0x02;
57const QTFILE: u8 = 0x00;
58
59const S_IFDIR: u32 = 0o040000;
60const S_IFREG: u32 = 0o100000;
61const S_IFLNK: u32 = 0o120000;
62
63const DT_DIR: u8 = 4;
64const DT_REG: u8 = 8;
65const DT_LNK: u8 = 10;
66
67const AT_REMOVEDIR: u32 = 0x200;
68const O_ACCMODE: u32 = 0x3;
69const O_EXCL: u32 = 0x80;
70const O_TRUNC: u32 = 0x200;
71const O_APPEND: u32 = 0x400;
72
73const P9_STATS_BASIC: u64 = 0x07ff;
74const V9FS_MAGIC: u32 = 0x0102_1997;
75
76// Linux errno values
77const EPERM: u32 = 1;
78const ENOENT: u32 = 2;
79const EIO: u32 = 5;
80const EBADF: u32 = 9;
81const EACCES: u32 = 13;
82const EBUSY: u32 = 16;
83const EEXIST: u32 = 17;
84const ENOTDIR: u32 = 20;
85const EISDIR: u32 = 21;
86const EINVAL: u32 = 22;
87const EROFS: u32 = 30;
88const ENOTEMPTY: u32 = 39;
89const EPROTO: u32 = 71;
90const EOPNOTSUPP: u32 = 95;
91
92/// Structured summary of mutations staged inside a copy-on-write (`:cow`) 9P workspace.
93#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
94pub struct WorkspaceDiff {
95    pub guest_path: String,
96    pub created: Vec<String>,
97    pub modified: Vec<String>,
98    pub deleted: Vec<String>,
99}
100
101impl WorkspaceDiff {
102    pub fn is_empty(&self) -> bool {
103        self.created.is_empty() && self.modified.is_empty() && self.deleted.is_empty()
104    }
105}
106
107/// Cloneable in-memory snapshot of a `:cow` 9P workspace overlay anchored to `host_root`.
108#[derive(Clone, Debug)]
109pub struct WorkspaceSnapshot {
110    pub host_root: PathBuf,
111    pub guest_path: String,
112    layer: CowLayer,
113}
114
115impl WorkspaceSnapshot {
116    pub fn diff(&self) -> WorkspaceDiff {
117        self.layer.diff(&self.host_root, &self.guest_path)
118    }
119}
120
121#[derive(Clone, Debug)]
122enum CowEntry {
123    File {
124        data: Vec<u8>,
125        mode: u32,
126        mtime: u64,
127    },
128    Dir {
129        mode: u32,
130        mtime: u64,
131    },
132    Symlink {
133        target: String,
134        mtime: u64,
135    },
136    Whiteout,
137}
138
139#[derive(Clone, Debug, Default)]
140struct CowLayer {
141    entries: BTreeMap<String, CowEntry>,
142    opaque_dirs: HashSet<String>,
143    /// Incremented on `discard_workspace` so Linux `v9fs` allocates fresh inodes with exact
144    /// reverted `i_size` instead of reusing stale cached `struct inode` entries.
145    discard_gen: u64,
146}
147
148struct CowStat {
149    qtype: u8,
150    fmt: u32,
151    perm: u32,
152    len: u64,
153    nlink: u64,
154    mtime: u64,
155    is_dir: bool,
156    is_file: bool,
157    ino: u64,
158    epoch: u64,
159}
160
161fn now_sec() -> u64 {
162    SystemTime::now()
163        .duration_since(UNIX_EPOCH)
164        .map(|d| d.as_secs())
165        .unwrap_or(0)
166}
167
168fn norm_rel_key(rel: &Path) -> String {
169    rel.to_string_lossy()
170        .replace('\\', "/")
171        .trim_matches('/')
172        .to_string()
173}
174
175fn rel_from_key(key: &str) -> PathBuf {
176    let mut p = PathBuf::new();
177    for seg in key.split('/').filter(|s| !s.is_empty()) {
178        p.push(seg);
179    }
180    p
181}
182
183fn parent_key(key: &str) -> &str {
184    match key.rfind('/') {
185        Some(idx) => &key[..idx],
186        None => "",
187    }
188}
189
190fn synthetic_ino_with_epoch(rel: &Path, epoch: u64) -> u64 {
191    let norm = norm_rel_key(rel);
192    if norm.is_empty() {
193        return 1;
194    }
195    let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ epoch.wrapping_mul(0x9e37_79b9_7f4a_7c15);
196    for b in norm.as_bytes() {
197        h ^= *b as u64;
198        h = h.wrapping_mul(0x0100_0000_01b3);
199    }
200    h | 2
201}
202
203impl CowLayer {
204    fn ino_for(&self, rel: &Path) -> u64 {
205        synthetic_ino_with_epoch(rel, self.discard_gen)
206    }
207
208    fn is_host_hidden(&self, key: &str) -> bool {
209        if matches!(self.entries.get(key), Some(CowEntry::Whiteout)) {
210            return true;
211        }
212        let mut cur = key;
213        while let Some(idx) = cur.rfind('/') {
214            cur = &cur[..idx];
215            if matches!(self.entries.get(cur), Some(CowEntry::Whiteout))
216                || self.opaque_dirs.contains(cur)
217            {
218                return true;
219            }
220        }
221        false
222    }
223
224    fn stat_entry(&self, host_root: &Path, rel: &Path) -> std::result::Result<CowStat, u32> {
225        let key = norm_rel_key(rel);
226        let ino = self.ino_for(rel);
227        let epoch = self.discard_gen;
228        if let Some(entry) = self.entries.get(&key) {
229            return match entry {
230                CowEntry::Whiteout => Err(ENOENT),
231                CowEntry::File { data, mode, mtime } => Ok(CowStat {
232                    qtype: QTFILE,
233                    fmt: S_IFREG,
234                    perm: *mode & 0o7777,
235                    len: data.len() as u64,
236                    nlink: 1,
237                    mtime: *mtime,
238                    is_dir: false,
239                    is_file: true,
240                    ino,
241                    epoch,
242                }),
243                CowEntry::Dir { mode, mtime } => Ok(CowStat {
244                    qtype: QTDIR,
245                    fmt: S_IFDIR,
246                    perm: *mode & 0o7777,
247                    len: 0,
248                    nlink: 2,
249                    mtime: *mtime,
250                    is_dir: true,
251                    is_file: false,
252                    ino,
253                    epoch,
254                }),
255                CowEntry::Symlink { target, mtime } => Ok(CowStat {
256                    qtype: QTSYMLINK,
257                    fmt: S_IFLNK,
258                    perm: 0o777,
259                    len: target.len() as u64,
260                    nlink: 1,
261                    mtime: *mtime,
262                    is_dir: false,
263                    is_file: false,
264                    ino,
265                    epoch,
266                }),
267            };
268        }
269        if self.is_host_hidden(&key) {
270            return Err(ENOENT);
271        }
272        let host_path = resolve_confined(host_root, rel, false)?;
273        let meta = fs::symlink_metadata(&host_path).map_err(io_to_errno)?;
274        let ft = meta.file_type();
275        let (qtype, fmt) = if ft.is_dir() {
276            (QTDIR, S_IFDIR)
277        } else if ft.is_symlink() {
278            (QTSYMLINK, S_IFLNK)
279        } else {
280            (QTFILE, S_IFREG)
281        };
282        let mtime = meta
283            .modified()
284            .ok()
285            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
286            .map(|d| d.as_secs())
287            .unwrap_or(0);
288        Ok(CowStat {
289            qtype,
290            fmt,
291            perm: meta_perm(&meta),
292            len: meta.len(),
293            nlink: meta_nlink(&meta),
294            mtime,
295            is_dir: ft.is_dir(),
296            is_file: ft.is_file(),
297            ino,
298            epoch,
299        })
300    }
301
302    fn copy_up_file(&mut self, host_root: &Path, rel: &Path) -> std::result::Result<(), u32> {
303        let key = norm_rel_key(rel);
304        if let Some(entry) = self.entries.get(&key) {
305            return match entry {
306                CowEntry::File { .. } => Ok(()),
307                CowEntry::Dir { .. } => Err(EISDIR),
308                CowEntry::Symlink { .. } => Err(EACCES),
309                CowEntry::Whiteout => Err(ENOENT),
310            };
311        }
312        if self.is_host_hidden(&key) {
313            return Err(ENOENT);
314        }
315        let host_path = resolve_confined(host_root, rel, false)?;
316        let meta = fs::symlink_metadata(&host_path).map_err(io_to_errno)?;
317        if meta.file_type().is_symlink() {
318            return Err(EACCES);
319        }
320        if meta.is_dir() {
321            return Err(EISDIR);
322        }
323        let data = fs::read(&host_path).map_err(io_to_errno)?;
324        let mode = meta_perm(&meta);
325        self.entries.insert(
326            key,
327            CowEntry::File {
328                data,
329                mode,
330                mtime: now_sec(),
331            },
332        );
333        Ok(())
334    }
335
336    fn merged_children(
337        &self,
338        host_root: &Path,
339        dir_rel: &Path,
340    ) -> std::result::Result<Vec<DirCacheEntry>, u32> {
341        let dir_key = norm_rel_key(dir_rel);
342        let mut by_name: BTreeMap<String, DirCacheEntry> = BTreeMap::new();
343
344        if !self.is_host_hidden(&dir_key)
345            && !self.opaque_dirs.contains(&dir_key)
346            && let Ok(host_path) = resolve_confined(host_root, dir_rel, false)
347            && let Ok(rd) = fs::read_dir(&host_path)
348        {
349            for dent in rd.flatten() {
350                let Ok(meta) = dent.metadata() else { continue };
351                let name = dent.file_name().to_string_lossy().into_owned();
352                let child_rel = dir_rel.join(&name);
353                let ft = meta.file_type();
354                let (qtype, dtype) = if ft.is_dir() {
355                    (QTDIR, DT_DIR)
356                } else if ft.is_symlink() {
357                    (QTSYMLINK, DT_LNK)
358                } else {
359                    (QTFILE, DT_REG)
360                };
361                by_name.insert(
362                    name.clone(),
363                    DirCacheEntry {
364                        ino: self.ino_for(&child_rel),
365                        rel_path: child_rel,
366                        name,
367                        qtype,
368                        dtype,
369                    },
370                );
371            }
372        }
373
374        for (k, entry) in &self.entries {
375            if k.is_empty() || parent_key(k) != dir_key {
376                continue;
377            }
378            let name = k.rsplit('/').next().unwrap_or(k).to_string();
379            match entry {
380                CowEntry::Whiteout => {
381                    by_name.remove(&name);
382                }
383                CowEntry::File { .. } => {
384                    let child_rel = dir_rel.join(&name);
385                    by_name.insert(
386                        name.clone(),
387                        DirCacheEntry {
388                            ino: self.ino_for(&child_rel),
389                            rel_path: child_rel,
390                            name,
391                            qtype: QTFILE,
392                            dtype: DT_REG,
393                        },
394                    );
395                }
396                CowEntry::Dir { .. } => {
397                    let child_rel = dir_rel.join(&name);
398                    by_name.insert(
399                        name.clone(),
400                        DirCacheEntry {
401                            ino: self.ino_for(&child_rel),
402                            rel_path: child_rel,
403                            name,
404                            qtype: QTDIR,
405                            dtype: DT_DIR,
406                        },
407                    );
408                }
409                CowEntry::Symlink { .. } => {
410                    let child_rel = dir_rel.join(&name);
411                    by_name.insert(
412                        name.clone(),
413                        DirCacheEntry {
414                            ino: self.ino_for(&child_rel),
415                            rel_path: child_rel,
416                            name,
417                            qtype: QTSYMLINK,
418                            dtype: DT_LNK,
419                        },
420                    );
421                }
422            }
423        }
424        Ok(by_name.into_values().collect())
425    }
426
427    fn purge_subtree(&mut self, key: &str) {
428        let prefix = format!("{key}/");
429        self.entries.retain(|k, _| !k.starts_with(&prefix));
430        self.opaque_dirs
431            .retain(|k| k != key && !k.starts_with(&prefix));
432    }
433
434    fn remove_entry(
435        &mut self,
436        host_root: &Path,
437        rel: &Path,
438        expect_dir: bool,
439    ) -> std::result::Result<(), u32> {
440        let key = norm_rel_key(rel);
441        if key.is_empty() {
442            return Err(EBUSY);
443        }
444        let st = self.stat_entry(host_root, rel)?;
445        if expect_dir && !st.is_dir {
446            return Err(ENOTDIR);
447        }
448        if !expect_dir && st.is_dir {
449            return Err(EISDIR);
450        }
451        if st.is_dir && !self.merged_children(host_root, rel)?.is_empty() {
452            return Err(ENOTEMPTY);
453        }
454        self.purge_subtree(&key);
455        self.entries.insert(key, CowEntry::Whiteout);
456        Ok(())
457    }
458
459    fn copy_subtree(
460        &mut self,
461        host_root: &Path,
462        src_rel: &Path,
463        dst_rel: &Path,
464    ) -> std::result::Result<(), u32> {
465        let src_key = norm_rel_key(src_rel);
466        let dst_key = norm_rel_key(dst_rel);
467        let st = self.stat_entry(host_root, src_rel)?;
468        if st.is_dir {
469            let children = self.merged_children(host_root, src_rel)?;
470            self.purge_subtree(&dst_key);
471            self.opaque_dirs.insert(dst_key.clone());
472            self.entries.insert(
473                dst_key,
474                CowEntry::Dir {
475                    mode: st.perm,
476                    mtime: now_sec(),
477                },
478            );
479            for child in children {
480                let c_src = src_rel.join(&child.name);
481                let c_dst = dst_rel.join(&child.name);
482                self.copy_subtree(host_root, &c_src, &c_dst)?;
483            }
484        } else if st.is_file {
485            self.copy_up_file(host_root, src_rel)?;
486            if let Some(CowEntry::File { data, mode, .. }) = self.entries.get(&src_key).cloned() {
487                self.entries.insert(
488                    dst_key,
489                    CowEntry::File {
490                        data,
491                        mode,
492                        mtime: now_sec(),
493                    },
494                );
495            }
496        } else {
497            let target = if let Some(CowEntry::Symlink { target, .. }) = self.entries.get(&src_key)
498            {
499                target.clone()
500            } else {
501                let hp = resolve_confined(host_root, src_rel, false)?;
502                fs::read_link(&hp)
503                    .map_err(io_to_errno)?
504                    .to_string_lossy()
505                    .into_owned()
506            };
507            self.entries.insert(
508                dst_key,
509                CowEntry::Symlink {
510                    target,
511                    mtime: now_sec(),
512                },
513            );
514        }
515        Ok(())
516    }
517
518    fn rename_entry(
519        &mut self,
520        host_root: &Path,
521        from_rel: &Path,
522        to_rel: &Path,
523    ) -> std::result::Result<(), u32> {
524        let from_key = norm_rel_key(from_rel);
525        let to_key = norm_rel_key(to_rel);
526        if from_key == to_key {
527            return Ok(());
528        }
529        if from_key.is_empty() {
530            return Err(EBUSY);
531        }
532        self.copy_subtree(host_root, from_rel, to_rel)?;
533        self.purge_subtree(&from_key);
534        self.entries.insert(from_key, CowEntry::Whiteout);
535        Ok(())
536    }
537
538    fn read_file(&self, host_root: &Path, rel: &Path) -> std::result::Result<Option<Vec<u8>>, u32> {
539        let key = norm_rel_key(rel);
540        if let Some(entry) = self.entries.get(&key) {
541            return match entry {
542                CowEntry::File { data, .. } => Ok(Some(data.clone())),
543                CowEntry::Whiteout => Ok(None),
544                _ => Err(EISDIR),
545            };
546        }
547        if self.is_host_hidden(&key) {
548            return Ok(None);
549        }
550        match resolve_confined(host_root, rel, false) {
551            Ok(hp) => match fs::read(&hp) {
552                Ok(b) => Ok(Some(b)),
553                Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
554                Err(e) => Err(io_to_errno(e)),
555            },
556            Err(ENOENT) => Ok(None),
557            Err(e) => Err(e),
558        }
559    }
560
561    fn diff(&self, host_root: &Path, guest_path: &str) -> WorkspaceDiff {
562        let mut created = Vec::new();
563        let mut modified = Vec::new();
564        let mut deleted = Vec::new();
565
566        for (k, entry) in &self.entries {
567            if k.is_empty() {
568                continue;
569            }
570            let rel = rel_from_key(k);
571            let host_exists = resolve_confined(host_root, &rel, false)
572                .ok()
573                .and_then(|hp| fs::symlink_metadata(&hp).ok());
574            match entry {
575                CowEntry::Whiteout => {
576                    if host_exists.is_some() {
577                        deleted.push(k.clone());
578                    }
579                }
580                CowEntry::File { data, .. } => match host_exists {
581                    None => created.push(k.clone()),
582                    Some(meta) => {
583                        let same = meta.is_file()
584                            && resolve_confined(host_root, &rel, false)
585                                .ok()
586                                .and_then(|hp| fs::read(&hp).ok())
587                                .is_some_and(|hb| hb == *data);
588                        if !same {
589                            modified.push(k.clone());
590                        }
591                    }
592                },
593                CowEntry::Dir { .. } => {
594                    if host_exists.is_none() {
595                        created.push(k.clone());
596                    } else if host_exists.as_ref().is_some_and(|m| !m.is_dir()) {
597                        modified.push(k.clone());
598                    }
599                }
600                CowEntry::Symlink { .. } => {
601                    if host_exists.is_none() {
602                        created.push(k.clone());
603                    } else {
604                        modified.push(k.clone());
605                    }
606                }
607            }
608        }
609
610        created.sort();
611        modified.sort();
612        deleted.sort();
613        WorkspaceDiff {
614            guest_path: guest_path.to_string(),
615            created,
616            modified,
617            deleted,
618        }
619    }
620
621    fn commit(&mut self, host_root: &Path, guest_path: &str) -> Result<WorkspaceDiff> {
622        let diff = self.diff(host_root, guest_path);
623
624        // 1. Apply deletions (deepest paths first)
625        let mut whiteouts: Vec<String> = self
626            .entries
627            .iter()
628            .filter(|(_, e)| matches!(e, CowEntry::Whiteout))
629            .map(|(k, _)| k.clone())
630            .collect();
631        whiteouts.sort_by_key(|k| std::cmp::Reverse(k.len()));
632        for k in whiteouts {
633            let rel = rel_from_key(&k);
634            if let Ok(hp) = resolve_confined(host_root, &rel, false)
635                && let Ok(meta) = fs::symlink_metadata(&hp)
636            {
637                if meta.is_dir() {
638                    fs::remove_dir_all(&hp)?;
639                } else {
640                    fs::remove_file(&hp)?;
641                }
642            }
643        }
644
645        // 2. Clear replaced opaque directories on host before materializing new children
646        let mut opaques: Vec<String> = self.opaque_dirs.iter().cloned().collect();
647        opaques.sort_by_key(|k| k.len());
648        for k in opaques {
649            let rel = rel_from_key(&k);
650            if let Ok(hp) = resolve_confined(host_root, &rel, false)
651                && hp.is_dir()
652            {
653                fs::remove_dir_all(&hp)?;
654            }
655        }
656
657        // 3. Create directories (shortest paths first)
658        let mut dirs: Vec<(String, u32)> = self
659            .entries
660            .iter()
661            .filter_map(|(k, e)| match e {
662                CowEntry::Dir { mode, .. } => Some((k.clone(), *mode)),
663                _ => None,
664            })
665            .collect();
666        dirs.sort_by_key(|(k, _)| k.len());
667        for (k, mode) in dirs {
668            let rel = rel_from_key(&k);
669            let hp = resolve_confined(host_root, &rel, true)
670                .map_err(|e| format_err!("commit mkdir {k}: errno {e}"))?;
671            fs::create_dir_all(&hp)?;
672            let _ = set_unix_mode(&hp, mode);
673        }
674
675        // 4. Write created/modified files and symlinks
676        for (k, entry) in &self.entries {
677            if k.is_empty() {
678                continue;
679            }
680            let rel = rel_from_key(k);
681            match entry {
682                CowEntry::File { data, mode, .. } => {
683                    let hp = resolve_confined(host_root, &rel, true)
684                        .map_err(|e| format_err!("commit file {k}: errno {e}"))?;
685                    if let Some(parent) = hp.parent() {
686                        fs::create_dir_all(parent)?;
687                    }
688                    fs::write(&hp, data)?;
689                    let _ = set_unix_mode(&hp, *mode);
690                }
691                CowEntry::Symlink { target, .. } => {
692                    let hp = resolve_confined(host_root, &rel, true)
693                        .map_err(|e| format_err!("commit symlink {k}: errno {e}"))?;
694                    if hp.exists() {
695                        let _ = fs::remove_file(&hp);
696                    }
697                    let _ = create_symlink(target, &hp);
698                }
699                CowEntry::Dir { .. } | CowEntry::Whiteout => {}
700            }
701        }
702
703        self.entries.clear();
704        self.opaque_dirs.clear();
705        Ok(diff)
706    }
707}
708
709/// Host directory export registered with the 9P server.
710#[derive(Clone)]
711pub struct ExportSpec {
712    pub name: String,
713    pub guest_path: String,
714    pub host_root: PathBuf,
715    pub read_only: bool,
716    cow: Option<Arc<Mutex<CowLayer>>>,
717}
718
719impl std::fmt::Debug for ExportSpec {
720    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
721        f.debug_struct("ExportSpec")
722            .field("name", &self.name)
723            .field("guest_path", &self.guest_path)
724            .field("host_root", &self.host_root)
725            .field("read_only", &self.read_only)
726            .field("copy_on_write", &self.cow.is_some())
727            .finish()
728    }
729}
730
731/// Manages the port-564 9P2000.L listener and active exports.
732pub struct P9Server {
733    exports: Mutex<HashMap<String, Arc<ExportSpec>>>,
734    next_id: Mutex<u32>,
735    monitor: Option<Arc<Monitor>>,
736}
737
738impl P9Server {
739    pub fn attach(vsock: &Arc<VsockHost>, monitor: Option<Arc<Monitor>>) -> Arc<Self> {
740        let server = Arc::new(Self {
741            exports: Mutex::new(HashMap::new()),
742            next_id: Mutex::new(0),
743            monitor,
744        });
745        let srv = server.clone();
746        vsock.listen(P9_VSOCK_PORT, move |stream| {
747            srv.serve_connection(stream);
748        });
749        server
750    }
751
752    pub fn add_export(
753        &self,
754        host_dir: &Path,
755        guest_path: &str,
756        read_only: bool,
757    ) -> Result<Arc<ExportSpec>> {
758        self.add_export_with_cow(host_dir, guest_path, read_only, None)
759    }
760
761    fn add_export_with_cow(
762        &self,
763        host_dir: &Path,
764        guest_path: &str,
765        read_only: bool,
766        cow_layer: Option<CowLayer>,
767    ) -> Result<Arc<ExportSpec>> {
768        let canonical = fs::canonicalize(host_dir)
769            .map_err(|e| format_err!("mount host dir {}: {e}", host_dir.display()))?;
770        if !canonical.is_dir() {
771            bail!("mount host path {} is not a directory", canonical.display());
772        }
773        let mut id = self.next_id.lock().unwrap();
774        let name = format!("m{}", *id);
775        *id += 1;
776        let spec = Arc::new(ExportSpec {
777            name: name.clone(),
778            guest_path: guest_path.to_string(),
779            host_root: canonical,
780            read_only: read_only && cow_layer.is_none(),
781            cow: cow_layer.map(|l| Arc::new(Mutex::new(l))),
782        });
783        self.exports.lock().unwrap().insert(name, spec.clone());
784        Ok(spec)
785    }
786
787    /// Mount `host_dir` inside the guest at `guest_path` by registering the 9p export and
788    /// running `/usr/bin/kwbox 9p <export> <guest_path> [ro]` as root via `kwtty`.
789    pub fn mount_in_guest(
790        &self,
791        vsock: &Arc<VsockHost>,
792        host_dir: &Path,
793        guest_path: &str,
794        read_only: bool,
795        timeout_ms: u64,
796    ) -> Result<()> {
797        self.mount_in_guest_ext(
798            vsock, host_dir, guest_path, read_only, false, None, timeout_ms,
799        )
800    }
801
802    /// Mount `host_dir` in copy-on-write (`:cow`) mode, optionally seeded from a [`WorkspaceSnapshot`].
803    #[allow(clippy::too_many_arguments)]
804    pub fn mount_in_guest_ext(
805        &self,
806        vsock: &Arc<VsockHost>,
807        host_dir: &Path,
808        guest_path: &str,
809        read_only: bool,
810        copy_on_write: bool,
811        initial_snapshot: Option<&WorkspaceSnapshot>,
812        timeout_ms: u64,
813    ) -> Result<()> {
814        if !guest_path.starts_with('/') || guest_path == "/" || guest_path.contains('\0') {
815            bail!("invalid guest mount path {guest_path:?}");
816        }
817        let cow_layer = if let Some(snap) = initial_snapshot {
818            Some(snap.layer.clone())
819        } else if copy_on_write {
820            Some(CowLayer::default())
821        } else {
822            None
823        };
824        let eff_ro = read_only && cow_layer.is_none();
825        let exp = self.add_export_with_cow(host_dir, guest_path, eff_ro, cow_layer)?;
826        let mut args = vec!["9p".to_string(), exp.name.clone(), guest_path.to_string()];
827        if eff_ro {
828            args.push("ro".to_string());
829        }
830        let mut opts = ExecOptions::new("/usr/bin/kwbox", args);
831        opts.user = Some("root".to_string());
832        opts.timeout_ms = Some(timeout_ms);
833
834        let res = exec_subprocess(vsock, &opts)?;
835        if res.exit_code != Some(0) {
836            let msg = format!(
837                "{} {}",
838                res.stderr_lossy().trim(),
839                res.stdout_lossy().trim()
840            );
841            bail!(
842                "mount {guest_path} failed (exit {:?}): {}",
843                res.exit_code,
844                msg.trim()
845            );
846        }
847        Ok(())
848    }
849
850    fn find_cow_export(&self, guest_path: &str) -> Result<(Arc<ExportSpec>, Arc<Mutex<CowLayer>>)> {
851        let want = guest_path.trim_end_matches('/');
852        let exports = self.exports.lock().unwrap();
853        for exp in exports.values() {
854            if exp.guest_path.trim_end_matches('/') == want {
855                let Some(cow) = &exp.cow else {
856                    bail!("mount {guest_path:?} is not a copy-on-write (:cow) workspace");
857                };
858                return Ok((exp.clone(), cow.clone()));
859            }
860        }
861        bail!("no 9P mount found at {guest_path:?}")
862    }
863
864    pub fn diff_workspace(&self, guest_path: &str) -> Result<WorkspaceDiff> {
865        let (exp, cow) = self.find_cow_export(guest_path)?;
866        let guard = cow.lock().unwrap();
867        Ok(guard.diff(&exp.host_root, &exp.guest_path))
868    }
869
870    pub fn diff_all_cow_workspaces(&self) -> Vec<WorkspaceDiff> {
871        let exports: Vec<Arc<ExportSpec>> =
872            self.exports.lock().unwrap().values().cloned().collect();
873        let mut out = Vec::new();
874        for exp in exports {
875            if let Some(cow) = &exp.cow {
876                out.push(cow.lock().unwrap().diff(&exp.host_root, &exp.guest_path));
877            }
878        }
879        out.sort_by(|a, b| a.guest_path.cmp(&b.guest_path));
880        out
881    }
882
883    pub fn snapshot_workspace(&self, guest_path: &str) -> Result<WorkspaceSnapshot> {
884        let (exp, cow) = self.find_cow_export(guest_path)?;
885        Ok(WorkspaceSnapshot {
886            host_root: exp.host_root.clone(),
887            guest_path: exp.guest_path.clone(),
888            layer: cow.lock().unwrap().clone(),
889        })
890    }
891
892    pub fn snapshot_all_workspaces(&self) -> Vec<WorkspaceSnapshot> {
893        let exports: Vec<Arc<ExportSpec>> =
894            self.exports.lock().unwrap().values().cloned().collect();
895        let mut out = Vec::new();
896        for exp in exports {
897            if let Some(cow) = &exp.cow {
898                out.push(WorkspaceSnapshot {
899                    host_root: exp.host_root.clone(),
900                    guest_path: exp.guest_path.clone(),
901                    layer: cow.lock().unwrap().clone(),
902                });
903            }
904        }
905        out.sort_by(|a, b| a.guest_path.cmp(&b.guest_path));
906        out
907    }
908
909    pub fn read_workspace_file(&self, guest_path: &str, rel_path: &str) -> Result<Option<Vec<u8>>> {
910        let (exp, cow) = self.find_cow_export(guest_path)?;
911        let rel = rel_from_key(rel_path);
912        cow.lock()
913            .unwrap()
914            .read_file(&exp.host_root, &rel)
915            .map_err(|e| format_err!("read workspace file {rel_path:?}: errno {e}"))
916    }
917
918    pub fn commit_workspace(&self, guest_path: &str) -> Result<WorkspaceDiff> {
919        let (exp, cow) = self.find_cow_export(guest_path)?;
920        cow.lock().unwrap().commit(&exp.host_root, &exp.guest_path)
921    }
922
923    pub fn discard_workspace(&self, guest_path: &str) -> Result<()> {
924        let (_exp, cow) = self.find_cow_export(guest_path)?;
925        let mut g = cow.lock().unwrap();
926        g.entries.clear();
927        g.opaque_dirs.clear();
928        g.discard_gen = g.discard_gen.wrapping_add(1);
929        Ok(())
930    }
931
932    fn serve_connection(&self, stream: VsockStream) {
933        let mut session = P9ConnSession {
934            msize: DEFAULT_MSIZE,
935            export: None,
936            fids: HashMap::new(),
937            monitor: self.monitor.clone(),
938        };
939
940        loop {
941            let mut len_buf = [0u8; 4];
942            if stream.read_exact_deadline(&mut len_buf, None).is_err() {
943                break;
944            }
945            let size = u32::from_le_bytes(len_buf) as usize;
946            if size < HDR_LEN || size > (DEFAULT_MSIZE as usize).max(1 << 20) {
947                break;
948            }
949            let mut frame = vec![0u8; size];
950            frame[0..4].copy_from_slice(&len_buf);
951            if stream.read_exact_deadline(&mut frame[4..], None).is_err() {
952                break;
953            }
954            let mtype = frame[4];
955            let tag = u16::from_le_bytes([frame[5], frame[6]]);
956
957            let reply = match session.handle(&self.exports, mtype, tag, &frame[HDR_LEN..]) {
958                Ok(w) => w.finish(mtype + 1, tag),
959                Err(errno) => {
960                    let mut w = Writer::new(16);
961                    w.u32(errno);
962                    w.finish(RLERROR, tag)
963                }
964            };
965            if stream.write_all_deadline(&reply, None).is_err() {
966                break;
967            }
968        }
969        stream.close();
970    }
971}
972
973struct DirCacheEntry {
974    name: String,
975    rel_path: PathBuf,
976    qtype: u8,
977    dtype: u8,
978    ino: u64,
979}
980
981struct FidState {
982    rel_path: PathBuf, // relative to export.host_root ("" = root)
983    is_dir: bool,
984    file: Option<File>,
985    cow_open: bool,
986    dir_entries: Option<Vec<DirCacheEntry>>,
987    write_approved: bool,
988}
989
990struct P9ConnSession {
991    msize: u32,
992    export: Option<Arc<ExportSpec>>,
993    fids: HashMap<u32, FidState>,
994    monitor: Option<Arc<Monitor>>,
995}
996
997impl P9ConnSession {
998    fn audit_fs(
999        &self,
1000        exp: &ExportSpec,
1001        op: &str,
1002        rel_path: &Path,
1003        target_rel: Option<&Path>,
1004        bytes: Option<usize>,
1005        decision: &str,
1006    ) {
1007        let Some(mon) = &self.monitor else { return };
1008        let path_str = format_guest_rel(&exp.guest_path, rel_path);
1009        let target_str = target_rel.map(|t| format_guest_rel(&exp.guest_path, t));
1010        let sensitive = is_sensitive_path(&rel_path.to_string_lossy())
1011            || target_rel.is_some_and(|t| is_sensitive_path(&t.to_string_lossy()));
1012        mon.emit(AuditEvent::FsOp {
1013            ts_ms: now_unix_ms(),
1014            mount: exp.guest_path.clone(),
1015            op: op.to_string(),
1016            path: path_str,
1017            target_path: target_str,
1018            bytes,
1019            sensitive,
1020            decision: decision.to_string(),
1021            proc: mon.p9_proc(),
1022        });
1023    }
1024
1025    fn gate_fs_write(
1026        &self,
1027        exp: &ExportSpec,
1028        op: &str,
1029        rel_path: &Path,
1030        target_rel: Option<&Path>,
1031    ) -> std::result::Result<(), u32> {
1032        let Some(mon) = &self.monitor else {
1033            return Ok(());
1034        };
1035        if !mon.ask_fs_write() {
1036            return Ok(());
1037        }
1038        let target_path = format_guest_rel(&exp.guest_path, rel_path);
1039        let detail = target_rel
1040            .map(|t| format!("{op} -> {}", format_guest_rel(&exp.guest_path, t)))
1041            .or_else(|| Some(op.to_string()));
1042        let dec = mon.request_approval(
1043            ApprovalKind::FsWrite,
1044            &target_path,
1045            target_path.clone(),
1046            detail,
1047        );
1048        if !dec.is_allowed() {
1049            self.audit_fs(exp, op, rel_path, target_rel, None, "deny_user");
1050            return Err(EACCES);
1051        }
1052        Ok(())
1053    }
1054
1055    fn gate_sensitive_read(
1056        &self,
1057        exp: &ExportSpec,
1058        rel_path: &Path,
1059    ) -> std::result::Result<(), u32> {
1060        let Some(mon) = &self.monitor else {
1061            return Ok(());
1062        };
1063        if !mon.ask_sensitive_read() || !is_sensitive_path(&rel_path.to_string_lossy()) {
1064            return Ok(());
1065        }
1066        let target_path = format_guest_rel(&exp.guest_path, rel_path);
1067        let dec = mon.request_approval(
1068            ApprovalKind::FsSensitiveRead,
1069            &target_path,
1070            target_path.clone(),
1071            Some("sensitive_read".to_string()),
1072        );
1073        if !dec.is_allowed() {
1074            self.audit_fs(exp, "open_read", rel_path, None, None, "deny_user");
1075            return Err(EACCES);
1076        }
1077        Ok(())
1078    }
1079    fn handle(
1080        &mut self,
1081        exports: &Mutex<HashMap<String, Arc<ExportSpec>>>,
1082        mtype: u8,
1083        _tag: u16,
1084        body: &[u8],
1085    ) -> std::result::Result<Writer, u32> {
1086        let mut r = Reader::new(body);
1087
1088        if mtype == TFLUSH {
1089            return Ok(Writer::new(HDR_LEN));
1090        }
1091        if mtype == TVERSION {
1092            let req_msize = r.u32()?;
1093            let ver = r.str()?;
1094            self.msize = req_msize.clamp(4096, DEFAULT_MSIZE);
1095            self.fids.clear();
1096            let mut w = Writer::new(32);
1097            w.u32(self.msize);
1098            w.str(if ver.starts_with(P9_VERSION) {
1099                P9_VERSION
1100            } else {
1101                "unknown"
1102            });
1103            return Ok(w);
1104        }
1105        if mtype == TAUTH {
1106            return Err(EOPNOTSUPP);
1107        }
1108        if mtype == TATTACH {
1109            let fid = r.u32()?;
1110            let _afid = r.u32()?;
1111            let _uname = r.str()?;
1112            let aname = r.str()?;
1113            let exp = exports.lock().unwrap().get(aname).cloned().ok_or(ENOENT)?;
1114            let meta = fs::symlink_metadata(&exp.host_root).map_err(io_to_errno)?;
1115            if !meta.is_dir() {
1116                return Err(ENOTDIR);
1117            }
1118            let is_cow = exp.cow.is_some();
1119            self.export = Some(exp);
1120            self.fids.insert(
1121                fid,
1122                FidState {
1123                    rel_path: PathBuf::new(),
1124                    is_dir: true,
1125                    file: None,
1126                    cow_open: false,
1127                    dir_entries: None,
1128                    write_approved: false,
1129                },
1130            );
1131            let mut w = Writer::new(24);
1132            if is_cow {
1133                w.u8(QTDIR);
1134                w.u32(0);
1135                w.u64(1);
1136            } else {
1137                w.qid(&meta, Path::new(""));
1138            }
1139            return Ok(w);
1140        }
1141
1142        let exp = self.export.clone().ok_or(EBADF)?;
1143
1144        if exp.read_only {
1145            let mutating = matches!(
1146                mtype,
1147                TLCREATE
1148                    | TSYMLINK
1149                    | TMKNOD
1150                    | TRENAME
1151                    | TSETATTR
1152                    | TLINK
1153                    | TMKDIR
1154                    | TRENAMEAT
1155                    | TUNLINKAT
1156                    | TWRITE
1157            );
1158            if mutating {
1159                return Err(EROFS);
1160            }
1161            if mtype == TLOPEN && body.len() >= 8 {
1162                let flags = u32::from_le_bytes([body[4], body[5], body[6], body[7]]);
1163                if (flags & O_ACCMODE) != 0 || (flags & O_TRUNC) != 0 {
1164                    return Err(EROFS);
1165                }
1166            }
1167            if mtype == TREMOVE {
1168                let fid = r.u32()?;
1169                self.fids.remove(&fid);
1170                return Err(EROFS);
1171            }
1172        }
1173
1174        match mtype {
1175            TWALK => {
1176                let fid = r.u32()?;
1177                let newfid = r.u32()?;
1178                let nwname = r.u16()? as usize;
1179                let base = self.fids.get(&fid).ok_or(EBADF)?;
1180                let mut cur_rel = base.rel_path.clone();
1181                let mut cur_is_dir = base.is_dir;
1182                let mut qids: Vec<(u8, u32, u64)> = Vec::with_capacity(nwname);
1183
1184                for i in 0..nwname {
1185                    let name = r.str()?;
1186                    if !cur_is_dir {
1187                        if i == 0 {
1188                            return Err(ENOTDIR);
1189                        }
1190                        break;
1191                    }
1192                    let next_rel = match step_rel(&cur_rel, name) {
1193                        Ok(p) => p,
1194                        Err(e) => {
1195                            if i == 0 {
1196                                return Err(e);
1197                            }
1198                            break;
1199                        }
1200                    };
1201                    if let Some(cow) = &exp.cow {
1202                        match cow.lock().unwrap().stat_entry(&exp.host_root, &next_rel) {
1203                            Ok(st) => {
1204                                qids.push((
1205                                    st.qtype,
1206                                    (st.mtime as u32).wrapping_add(st.epoch as u32),
1207                                    st.ino,
1208                                ));
1209                                cur_is_dir = st.is_dir;
1210                                cur_rel = next_rel;
1211                            }
1212                            Err(e) => {
1213                                if i == 0 {
1214                                    return Err(e);
1215                                }
1216                                break;
1217                            }
1218                        }
1219                    } else {
1220                        let host_path = match resolve_confined(&exp.host_root, &next_rel, false) {
1221                            Ok(p) => p,
1222                            Err(e) => {
1223                                if i == 0 {
1224                                    return Err(e);
1225                                }
1226                                break;
1227                            }
1228                        };
1229                        match fs::symlink_metadata(&host_path) {
1230                            Ok(meta) => {
1231                                qids.push(meta_to_qid(&meta, &next_rel));
1232                                cur_is_dir = meta.is_dir();
1233                                cur_rel = next_rel;
1234                            }
1235                            Err(e) => {
1236                                if i == 0 {
1237                                    return Err(io_to_errno(e));
1238                                }
1239                                break;
1240                            }
1241                        }
1242                    }
1243                }
1244
1245                if qids.len() == nwname {
1246                    self.fids.insert(
1247                        newfid,
1248                        FidState {
1249                            rel_path: cur_rel,
1250                            is_dir: cur_is_dir,
1251                            file: None,
1252                            cow_open: false,
1253                            dir_entries: None,
1254                            write_approved: false,
1255                        },
1256                    );
1257                }
1258                let mut w = Writer::new(HDR_LEN + 2 + 13 * qids.len());
1259                w.u16(qids.len() as u16);
1260                for (qt, ver, path) in qids {
1261                    w.u8(qt);
1262                    w.u32(ver);
1263                    w.u64(path);
1264                }
1265                Ok(w)
1266            }
1267            TCLUNK => {
1268                let fid = r.u32()?;
1269                self.fids.remove(&fid).ok_or(EBADF)?;
1270                Ok(Writer::new(HDR_LEN))
1271            }
1272            TREMOVE => {
1273                let fid = r.u32()?;
1274                let f = self.fids.remove(&fid).ok_or(EBADF)?;
1275                if f.rel_path.as_os_str().is_empty() {
1276                    return Err(EBUSY);
1277                }
1278                self.gate_fs_write(&exp, "remove", &f.rel_path, None)?;
1279                if let Some(cow) = &exp.cow {
1280                    cow.lock()
1281                        .unwrap()
1282                        .remove_entry(&exp.host_root, &f.rel_path, f.is_dir)?;
1283                } else {
1284                    let host_path = resolve_confined(&exp.host_root, &f.rel_path, false)?;
1285                    if f.is_dir {
1286                        fs::remove_dir(&host_path).map_err(io_to_errno)?;
1287                    } else {
1288                        fs::remove_file(&host_path).map_err(io_to_errno)?;
1289                    }
1290                }
1291                self.audit_fs(&exp, "remove", &f.rel_path, None, None, "allow");
1292                Ok(Writer::new(HDR_LEN))
1293            }
1294            TSTATFS => {
1295                let fid = r.u32()?;
1296                if !self.fids.contains_key(&fid) {
1297                    return Err(EBADF);
1298                }
1299                let mut w = Writer::new(72);
1300                w.u32(V9FS_MAGIC);
1301                w.u32(4096);
1302                w.u64(1024 * 1024); // blocks
1303                w.u64(512 * 1024); // bfree
1304                w.u64(512 * 1024); // bavail
1305                w.u64(100_000); // files
1306                w.u64(50_000); // ffree
1307                w.u64(0); // fsid
1308                w.u32(255); // namelen
1309                Ok(w)
1310            }
1311            TLOPEN => {
1312                let fid = r.u32()?;
1313                let flags = r.u32()?;
1314                let rel_path = self.fids.get(&fid).ok_or(EBADF)?.rel_path.clone();
1315                if let Some(cow) = &exp.cow {
1316                    let st = cow.lock().unwrap().stat_entry(&exp.host_root, &rel_path)?;
1317                    if st.is_file {
1318                        let acc = flags & O_ACCMODE;
1319                        let read = acc != 1;
1320                        let write = acc != 0;
1321                        let truncate = (flags & O_TRUNC) != 0;
1322                        if read {
1323                            self.gate_sensitive_read(&exp, &rel_path)?;
1324                        }
1325                        if write || truncate {
1326                            self.gate_fs_write(&exp, "open_write", &rel_path, None)?;
1327                        }
1328                        let st2 = if write || truncate {
1329                            let mut g = cow.lock().unwrap();
1330                            g.copy_up_file(&exp.host_root, &rel_path)?;
1331                            if truncate
1332                                && let Some(CowEntry::File { data, mtime, .. }) =
1333                                    g.entries.get_mut(&norm_rel_key(&rel_path))
1334                            {
1335                                data.clear();
1336                                *mtime = now_sec();
1337                            }
1338                            g.stat_entry(&exp.host_root, &rel_path)?
1339                        } else {
1340                            st
1341                        };
1342                        let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
1343                        f.is_dir = false;
1344                        f.dir_entries = None;
1345                        f.file = None;
1346                        f.cow_open = true;
1347                        f.write_approved = write || truncate;
1348                        self.audit_fs(
1349                            &exp,
1350                            if write || truncate {
1351                                "open_write"
1352                            } else {
1353                                "open_read"
1354                            },
1355                            &rel_path,
1356                            None,
1357                            None,
1358                            "allow",
1359                        );
1360                        let mut w = Writer::new(32);
1361                        w.cow_qid(&st2);
1362                        w.u32(0);
1363                        return Ok(w);
1364                    }
1365                    let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
1366                    f.is_dir = st.is_dir;
1367                    f.dir_entries = None;
1368                    f.file = None;
1369                    f.cow_open = false;
1370                    let mut w = Writer::new(32);
1371                    w.cow_qid(&st);
1372                    w.u32(0);
1373                    return Ok(w);
1374                }
1375                let host_path = resolve_confined(&exp.host_root, &rel_path, false)?;
1376                let meta = fs::symlink_metadata(&host_path).map_err(io_to_errno)?;
1377
1378                if meta.is_file() {
1379                    let acc = flags & O_ACCMODE;
1380                    let read = acc != 1;
1381                    let write = acc != 0;
1382                    let truncate = (flags & O_TRUNC) != 0;
1383                    let append = (flags & O_APPEND) != 0;
1384                    if read {
1385                        self.gate_sensitive_read(&exp, &rel_path)?;
1386                    }
1387                    if write || truncate {
1388                        self.gate_fs_write(&exp, "open_write", &rel_path, None)?;
1389                    }
1390                    let mut oo = OpenOptions::new();
1391                    oo.read(read).write(write).truncate(truncate).append(append);
1392                    configure_open_options(&mut oo, None);
1393                    let file = open_nofollow(&oo, &host_path)?;
1394                    let m2 = file.metadata().map_err(io_to_errno)?;
1395                    let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
1396                    f.is_dir = false;
1397                    f.dir_entries = None;
1398                    f.file = Some(file);
1399                    f.cow_open = false;
1400                    f.write_approved = write || truncate;
1401                    self.audit_fs(
1402                        &exp,
1403                        if write || truncate {
1404                            "open_write"
1405                        } else {
1406                            "open_read"
1407                        },
1408                        &rel_path,
1409                        None,
1410                        None,
1411                        "allow",
1412                    );
1413                    let mut w = Writer::new(32);
1414                    w.qid(&m2, &rel_path);
1415                    w.u32(0);
1416                    return Ok(w);
1417                }
1418                let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
1419                f.is_dir = meta.is_dir();
1420                f.dir_entries = None;
1421                let mut w = Writer::new(32);
1422                w.qid(&meta, &rel_path);
1423                w.u32(0);
1424                Ok(w)
1425            }
1426            TLCREATE => {
1427                let fid = r.u32()?;
1428                let name = r.str()?;
1429                let flags = r.u32()?;
1430                let mode = r.u32()?;
1431                validate_component(name)?;
1432
1433                let parent_rel = {
1434                    let f = self.fids.get(&fid).ok_or(EBADF)?;
1435                    if !f.is_dir {
1436                        return Err(ENOTDIR);
1437                    }
1438                    f.rel_path.clone()
1439                };
1440                let new_rel = parent_rel.join(name);
1441                if let Some(cow) = &exp.cow {
1442                    let existing = cow
1443                        .lock()
1444                        .unwrap()
1445                        .stat_entry(&exp.host_root, &new_rel)
1446                        .ok();
1447                    if (flags & O_ACCMODE) != 1 && existing.is_some() {
1448                        self.gate_sensitive_read(&exp, &new_rel)?;
1449                    }
1450                    self.gate_fs_write(&exp, "create", &new_rel, None)?;
1451                    let st = {
1452                        let mut g = cow.lock().unwrap();
1453                        if existing.is_some() {
1454                            if (flags & O_EXCL) != 0 {
1455                                return Err(EEXIST);
1456                            }
1457                            if (flags & O_TRUNC) != 0 {
1458                                g.entries.insert(
1459                                    norm_rel_key(&new_rel),
1460                                    CowEntry::File {
1461                                        data: Vec::new(),
1462                                        mode: mode & 0o7777,
1463                                        mtime: now_sec(),
1464                                    },
1465                                );
1466                            } else {
1467                                g.copy_up_file(&exp.host_root, &new_rel)?;
1468                            }
1469                        } else {
1470                            g.entries.insert(
1471                                norm_rel_key(&new_rel),
1472                                CowEntry::File {
1473                                    data: Vec::new(),
1474                                    mode: mode & 0o7777,
1475                                    mtime: now_sec(),
1476                                },
1477                            );
1478                        }
1479                        g.stat_entry(&exp.host_root, &new_rel)?
1480                    };
1481                    self.audit_fs(&exp, "create", &new_rel, None, None, "allow");
1482                    let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
1483                    f.rel_path = new_rel;
1484                    f.is_dir = false;
1485                    f.file = None;
1486                    f.cow_open = true;
1487                    f.dir_entries = None;
1488                    f.write_approved = true;
1489                    let mut w = Writer::new(32);
1490                    w.cow_qid(&st);
1491                    w.u32(0);
1492                    return Ok(w);
1493                }
1494
1495                let host_path = resolve_confined(&exp.host_root, &new_rel, true)?;
1496                if (flags & O_ACCMODE) != 1 && host_path.exists() {
1497                    self.gate_sensitive_read(&exp, &new_rel)?;
1498                }
1499                self.gate_fs_write(&exp, "create", &new_rel, None)?;
1500
1501                let mut oo = OpenOptions::new();
1502                oo.read((flags & O_ACCMODE) != 1)
1503                    .write(true)
1504                    .append((flags & O_APPEND) != 0)
1505                    .truncate((flags & O_TRUNC) != 0);
1506                configure_open_options(&mut oo, Some(mode & 0o7777));
1507                if (flags & O_EXCL) != 0 {
1508                    oo.create_new(true);
1509                } else {
1510                    oo.create(true);
1511                }
1512                let file = open_nofollow(&oo, &host_path)?;
1513                let meta = file.metadata().map_err(io_to_errno)?;
1514
1515                self.audit_fs(&exp, "create", &new_rel, None, None, "allow");
1516                let qid_rel = new_rel.clone();
1517                let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
1518                f.rel_path = new_rel;
1519                f.is_dir = false;
1520                f.file = Some(file);
1521                f.cow_open = false;
1522                f.dir_entries = None;
1523                f.write_approved = true;
1524
1525                let mut w = Writer::new(32);
1526                w.qid(&meta, &qid_rel);
1527                w.u32(0);
1528                Ok(w)
1529            }
1530            TMKDIR => {
1531                let fid = r.u32()?;
1532                let name = r.str()?;
1533                let mode = r.u32()?;
1534                validate_component(name)?;
1535                let parent_rel = {
1536                    let f = self.fids.get(&fid).ok_or(EBADF)?;
1537                    if !f.is_dir {
1538                        return Err(ENOTDIR);
1539                    }
1540                    f.rel_path.clone()
1541                };
1542                let new_rel = parent_rel.join(name);
1543                self.gate_fs_write(&exp, "mkdir", &new_rel, None)?;
1544                if let Some(cow) = &exp.cow {
1545                    let st = {
1546                        let mut g = cow.lock().unwrap();
1547                        if g.stat_entry(&exp.host_root, &new_rel).is_ok() {
1548                            return Err(EEXIST);
1549                        }
1550                        let key = norm_rel_key(&new_rel);
1551                        if matches!(g.entries.get(&key), Some(CowEntry::Whiteout))
1552                            || resolve_confined(&exp.host_root, &new_rel, false)
1553                                .ok()
1554                                .and_then(|hp| fs::symlink_metadata(&hp).ok())
1555                                .is_some()
1556                        {
1557                            g.opaque_dirs.insert(key.clone());
1558                        }
1559                        g.entries.insert(
1560                            key,
1561                            CowEntry::Dir {
1562                                mode: mode & 0o7777,
1563                                mtime: now_sec(),
1564                            },
1565                        );
1566                        g.stat_entry(&exp.host_root, &new_rel)?
1567                    };
1568                    self.audit_fs(&exp, "mkdir", &new_rel, None, None, "allow");
1569                    let mut w = Writer::new(24);
1570                    w.cow_qid(&st);
1571                    return Ok(w);
1572                }
1573                let host_path = resolve_confined(&exp.host_root, &new_rel, true)?;
1574                fs::create_dir(&host_path).map_err(io_to_errno)?;
1575                let _ = set_unix_mode(&host_path, mode & 0o7777);
1576                let meta = fs::symlink_metadata(&host_path).map_err(io_to_errno)?;
1577                self.audit_fs(&exp, "mkdir", &new_rel, None, None, "allow");
1578                let mut w = Writer::new(24);
1579                w.qid(&meta, &new_rel);
1580                Ok(w)
1581            }
1582            TSYMLINK => {
1583                let fid = r.u32()?;
1584                let name = r.str()?;
1585                let target = r.str()?;
1586                validate_component(name)?;
1587                let parent_rel = {
1588                    let f = self.fids.get(&fid).ok_or(EBADF)?;
1589                    if !f.is_dir {
1590                        return Err(ENOTDIR);
1591                    }
1592                    f.rel_path.clone()
1593                };
1594                let new_rel = parent_rel.join(name);
1595                self.gate_fs_write(&exp, "symlink", &new_rel, None)?;
1596                if let Some(cow) = &exp.cow {
1597                    let st = {
1598                        let mut g = cow.lock().unwrap();
1599                        if g.stat_entry(&exp.host_root, &new_rel).is_ok() {
1600                            return Err(EEXIST);
1601                        }
1602                        g.entries.insert(
1603                            norm_rel_key(&new_rel),
1604                            CowEntry::Symlink {
1605                                target: target.to_string(),
1606                                mtime: now_sec(),
1607                            },
1608                        );
1609                        g.stat_entry(&exp.host_root, &new_rel)?
1610                    };
1611                    self.audit_fs(&exp, "symlink", &new_rel, None, None, "allow");
1612                    let mut w = Writer::new(24);
1613                    w.cow_qid(&st);
1614                    return Ok(w);
1615                }
1616                let host_path = resolve_confined(&exp.host_root, &new_rel, true)?;
1617                create_symlink(target, &host_path)?;
1618                let meta = fs::symlink_metadata(&host_path).map_err(io_to_errno)?;
1619                self.audit_fs(&exp, "symlink", &new_rel, None, None, "allow");
1620                let mut w = Writer::new(24);
1621                w.qid(&meta, &new_rel);
1622                Ok(w)
1623            }
1624            TLINK => Err(EPERM),
1625            TMKNOD | TXATTRWALK | TXATTRCREATE => Err(EOPNOTSUPP),
1626            TUNLINKAT => {
1627                let dfid = r.u32()?;
1628                let name = r.str()?;
1629                let flags = r.u32()?;
1630                validate_component(name)?;
1631                let parent_rel = {
1632                    let f = self.fids.get(&dfid).ok_or(EBADF)?;
1633                    if !f.is_dir {
1634                        return Err(ENOTDIR);
1635                    }
1636                    f.rel_path.clone()
1637                };
1638                let target_rel = parent_rel.join(name);
1639                let op = if (flags & AT_REMOVEDIR) != 0 {
1640                    "rmdir"
1641                } else {
1642                    "unlink"
1643                };
1644                self.gate_fs_write(&exp, op, &target_rel, None)?;
1645                if let Some(cow) = &exp.cow {
1646                    cow.lock().unwrap().remove_entry(
1647                        &exp.host_root,
1648                        &target_rel,
1649                        (flags & AT_REMOVEDIR) != 0,
1650                    )?;
1651                } else {
1652                    let host_path = resolve_confined(&exp.host_root, &target_rel, false)?;
1653                    if (flags & AT_REMOVEDIR) != 0 {
1654                        fs::remove_dir(&host_path).map_err(io_to_errno)?;
1655                    } else {
1656                        fs::remove_file(&host_path).map_err(io_to_errno)?;
1657                    }
1658                }
1659                self.audit_fs(&exp, op, &target_rel, None, None, "allow");
1660                Ok(Writer::new(HDR_LEN))
1661            }
1662            TRENAMEAT | TRENAME => {
1663                let (from_rel, to_rel) = if mtype == TRENAMEAT {
1664                    let odfid = r.u32()?;
1665                    let oname = r.str()?;
1666                    let ndfid = r.u32()?;
1667                    let nname = r.str()?;
1668                    validate_component(oname)?;
1669                    validate_component(nname)?;
1670                    let od = self.fids.get(&odfid).ok_or(EBADF)?;
1671                    let nd = self.fids.get(&ndfid).ok_or(EBADF)?;
1672                    if !od.is_dir || !nd.is_dir {
1673                        return Err(ENOTDIR);
1674                    }
1675                    (od.rel_path.join(oname), nd.rel_path.join(nname))
1676                } else {
1677                    let fid = r.u32()?;
1678                    let dfid = r.u32()?;
1679                    let name = r.str()?;
1680                    validate_component(name)?;
1681                    let f = self.fids.get(&fid).ok_or(EBADF)?;
1682                    let d = self.fids.get(&dfid).ok_or(EBADF)?;
1683                    if !d.is_dir {
1684                        return Err(ENOTDIR);
1685                    }
1686                    (f.rel_path.clone(), d.rel_path.join(name))
1687                };
1688                if from_rel.as_os_str().is_empty() {
1689                    return Err(EBUSY);
1690                }
1691                self.gate_sensitive_read(&exp, &from_rel)?;
1692                self.gate_fs_write(&exp, "rename", &from_rel, Some(&to_rel))?;
1693                if let Some(cow) = &exp.cow {
1694                    cow.lock()
1695                        .unwrap()
1696                        .rename_entry(&exp.host_root, &from_rel, &to_rel)?;
1697                    for f in self.fids.values_mut() {
1698                        if let Ok(rest) = f.rel_path.strip_prefix(&from_rel) {
1699                            f.rel_path = to_rel.join(rest);
1700                        }
1701                    }
1702                } else {
1703                    let from_host = resolve_confined(&exp.host_root, &from_rel, false)?;
1704                    let to_host = resolve_confined(&exp.host_root, &to_rel, true)?;
1705                    if from_host != to_host {
1706                        #[cfg(windows)]
1707                        if to_host.is_file() {
1708                            let _ = fs::remove_file(&to_host);
1709                        }
1710                        fs::rename(&from_host, &to_host).map_err(io_to_errno)?;
1711                        for f in self.fids.values_mut() {
1712                            if let Ok(rest) = f.rel_path.strip_prefix(&from_rel) {
1713                                f.rel_path = to_rel.join(rest);
1714                            }
1715                        }
1716                    }
1717                }
1718                self.audit_fs(&exp, "rename", &from_rel, Some(&to_rel), None, "allow");
1719                Ok(Writer::new(HDR_LEN))
1720            }
1721            TREADLINK => {
1722                let fid = r.u32()?;
1723                let f = self.fids.get(&fid).ok_or(EBADF)?;
1724                let target = if let Some(cow) = &exp.cow {
1725                    let g = cow.lock().unwrap();
1726                    let key = norm_rel_key(&f.rel_path);
1727                    if let Some(entry) = g.entries.get(&key) {
1728                        match entry {
1729                            CowEntry::Symlink { target, .. } => target.clone(),
1730                            CowEntry::Whiteout => return Err(ENOENT),
1731                            _ => return Err(EINVAL),
1732                        }
1733                    } else if g.is_host_hidden(&key) {
1734                        return Err(ENOENT);
1735                    } else {
1736                        let host_path = resolve_confined(&exp.host_root, &f.rel_path, false)?;
1737                        fs::read_link(&host_path)
1738                            .map_err(io_to_errno)?
1739                            .to_string_lossy()
1740                            .into_owned()
1741                    }
1742                } else {
1743                    let host_path = resolve_confined(&exp.host_root, &f.rel_path, false)?;
1744                    fs::read_link(&host_path)
1745                        .map_err(io_to_errno)?
1746                        .to_string_lossy()
1747                        .into_owned()
1748                };
1749                let mut w = Writer::new(64);
1750                w.str(&target);
1751                Ok(w)
1752            }
1753            TGETATTR => {
1754                let fid = r.u32()?;
1755                let _mask = r.u64()?;
1756                let f = self.fids.get(&fid).ok_or(EBADF)?;
1757                if let Some(cow) = &exp.cow {
1758                    let st = cow
1759                        .lock()
1760                        .unwrap()
1761                        .stat_entry(&exp.host_root, &f.rel_path)?;
1762                    let mut w = Writer::new(160);
1763                    w.u64(P9_STATS_BASIC);
1764                    w.cow_qid(&st);
1765                    w.u32(st.fmt | st.perm);
1766                    w.u32(1000); // uid mapped to guest default user
1767                    w.u32(1000); // gid
1768                    w.u64(st.nlink);
1769                    w.u64(0); // rdev
1770                    w.u64(st.len);
1771                    w.u64(4096);
1772                    w.u64(st.len.div_ceil(512));
1773                    w.u64(st.mtime);
1774                    w.u64(0);
1775                    w.u64(st.mtime);
1776                    w.u64(0);
1777                    w.u64(st.mtime);
1778                    w.u64(0);
1779                    w.u64(0);
1780                    w.u64(0);
1781                    w.u64(st.epoch); // gen
1782                    w.u64(st.epoch); // data_version
1783                    return Ok(w);
1784                }
1785                let meta = if let Some(file) = &f.file {
1786                    file.metadata().map_err(io_to_errno)?
1787                } else {
1788                    let host_path = resolve_confined(&exp.host_root, &f.rel_path, false)?;
1789                    fs::symlink_metadata(&host_path).map_err(io_to_errno)?
1790                };
1791                let ft = meta.file_type();
1792                let fmt = if ft.is_dir() {
1793                    S_IFDIR
1794                } else if ft.is_symlink() {
1795                    S_IFLNK
1796                } else {
1797                    S_IFREG
1798                };
1799                let perm = meta_perm(&meta);
1800                let size = meta.len();
1801                let (atime_s, atime_ns, mtime_s, mtime_ns, ctime_s, ctime_ns) = meta_times(&meta);
1802                let mut w = Writer::new(160);
1803                w.u64(P9_STATS_BASIC);
1804                w.qid(&meta, &f.rel_path);
1805                w.u32(fmt | perm);
1806                w.u32(1000); // uid mapped to guest default user
1807                w.u32(1000); // gid
1808                w.u64(meta_nlink(&meta));
1809                w.u64(0); // rdev
1810                w.u64(size);
1811                w.u64(4096);
1812                w.u64(size.div_ceil(512));
1813                w.u64(atime_s);
1814                w.u64(atime_ns);
1815                w.u64(mtime_s);
1816                w.u64(mtime_ns);
1817                w.u64(ctime_s);
1818                w.u64(ctime_ns);
1819                w.u64(0);
1820                w.u64(0);
1821                w.u64(0); // gen
1822                w.u64(0); // data_version
1823                Ok(w)
1824            }
1825            TSETATTR => {
1826                let fid = r.u32()?;
1827                let valid = r.u32()?;
1828                let mode = r.u32()?;
1829                let _uid = r.u32()?;
1830                let _gid = r.u32()?;
1831                let size = r.u64()?;
1832                let _as = r.u64()?;
1833                let _an = r.u64()?;
1834                let _ms = r.u64()?;
1835                let _mn = r.u64()?;
1836                let (rel_path, already_approved) = {
1837                    let f = self.fids.get(&fid).ok_or(EBADF)?;
1838                    (f.rel_path.clone(), f.write_approved)
1839                };
1840                if (valid & 9) != 0 && !already_approved {
1841                    let op = if (valid & 8) != 0 {
1842                        "truncate"
1843                    } else {
1844                        "chmod"
1845                    };
1846                    self.gate_fs_write(&exp, op, &rel_path, None)?;
1847                }
1848                if let Some(cow) = &exp.cow {
1849                    let mut g = cow.lock().unwrap();
1850                    let key = norm_rel_key(&rel_path);
1851                    if (valid & 8) != 0 {
1852                        g.copy_up_file(&exp.host_root, &rel_path)?;
1853                        if let Some(CowEntry::File { data, mtime, .. }) = g.entries.get_mut(&key) {
1854                            data.resize(size as usize, 0);
1855                            *mtime = now_sec();
1856                        }
1857                    }
1858                    if (valid & 1) != 0 {
1859                        let st = g.stat_entry(&exp.host_root, &rel_path)?;
1860                        if st.is_file {
1861                            g.copy_up_file(&exp.host_root, &rel_path)?;
1862                            if let Some(CowEntry::File { mode: m, mtime, .. }) =
1863                                g.entries.get_mut(&key)
1864                            {
1865                                *m = mode & 0o7777;
1866                                *mtime = now_sec();
1867                            }
1868                        } else if st.is_dir {
1869                            g.entries.insert(
1870                                key,
1871                                CowEntry::Dir {
1872                                    mode: mode & 0o7777,
1873                                    mtime: now_sec(),
1874                                },
1875                            );
1876                        }
1877                    }
1878                } else {
1879                    let f = self.fids.get(&fid).ok_or(EBADF)?;
1880                    let host_path = resolve_confined(&exp.host_root, &f.rel_path, false)?;
1881                    if (valid & 1) != 0 {
1882                        set_unix_mode(&host_path, mode & 0o7777)?;
1883                    }
1884                    if (valid & 8) != 0 {
1885                        if let Some(file) = &f.file {
1886                            file.set_len(size).map_err(io_to_errno)?;
1887                        } else {
1888                            let mut oo = OpenOptions::new();
1889                            oo.write(true);
1890                            configure_open_options(&mut oo, None);
1891                            let file = open_nofollow(&oo, &host_path)?;
1892                            file.set_len(size).map_err(io_to_errno)?;
1893                        }
1894                    }
1895                }
1896                if (valid & 9) != 0 {
1897                    let op = if (valid & 8) != 0 {
1898                        "truncate"
1899                    } else {
1900                        "chmod"
1901                    };
1902                    self.audit_fs(&exp, op, &rel_path, None, None, "allow");
1903                }
1904                Ok(Writer::new(HDR_LEN))
1905            }
1906            TREADDIR => {
1907                let fid = r.u32()?;
1908                let offset = r.u64()? as usize;
1909                let count = r.u32()? as usize;
1910                let f = self.fids.get_mut(&fid).ok_or(EBADF)?;
1911                if !f.is_dir {
1912                    return Err(ENOTDIR);
1913                }
1914                if offset == 0 || f.dir_entries.is_none() {
1915                    let parent_rel = f.rel_path.parent().unwrap_or(Path::new("")).to_path_buf();
1916                    if let Some(cow) = &exp.cow {
1917                        let g = cow.lock().unwrap();
1918                        let self_ino = g.ino_for(&f.rel_path);
1919                        let parent_ino = g.ino_for(&parent_rel);
1920                        let mut entries = vec![
1921                            DirCacheEntry {
1922                                name: ".".into(),
1923                                rel_path: f.rel_path.clone(),
1924                                qtype: QTDIR,
1925                                dtype: DT_DIR,
1926                                ino: self_ino,
1927                            },
1928                            DirCacheEntry {
1929                                name: "..".into(),
1930                                rel_path: parent_rel,
1931                                qtype: QTDIR,
1932                                dtype: DT_DIR,
1933                                ino: parent_ino,
1934                            },
1935                        ];
1936                        entries.extend(g.merged_children(&exp.host_root, &f.rel_path)?);
1937                        f.dir_entries = Some(entries);
1938                    } else {
1939                        let host_path = resolve_confined(&exp.host_root, &f.rel_path, false)?;
1940                        let self_meta = fs::symlink_metadata(&host_path).map_err(io_to_errno)?;
1941                        let self_ino = meta_ino(&self_meta, &f.rel_path);
1942                        let mut entries = vec![
1943                            DirCacheEntry {
1944                                name: ".".into(),
1945                                rel_path: f.rel_path.clone(),
1946                                qtype: QTDIR,
1947                                dtype: DT_DIR,
1948                                ino: self_ino,
1949                            },
1950                            DirCacheEntry {
1951                                name: "..".into(),
1952                                rel_path: parent_rel,
1953                                qtype: QTDIR,
1954                                dtype: DT_DIR,
1955                                ino: self_ino,
1956                            },
1957                        ];
1958                        for dent in fs::read_dir(&host_path).map_err(io_to_errno)? {
1959                            let Ok(dent) = dent else { continue };
1960                            let Ok(meta) = dent.metadata() else { continue };
1961                            let name = dent.file_name().to_string_lossy().into_owned();
1962                            let ft = meta.file_type();
1963                            let (qtype, dtype) = if ft.is_dir() {
1964                                (QTDIR, DT_DIR)
1965                            } else if ft.is_symlink() {
1966                                (QTSYMLINK, DT_LNK)
1967                            } else {
1968                                (QTFILE, DT_REG)
1969                            };
1970                            let child_rel = f.rel_path.join(&name);
1971                            let child_ino = meta_ino(&meta, &child_rel);
1972                            entries.push(DirCacheEntry {
1973                                rel_path: child_rel,
1974                                name,
1975                                qtype,
1976                                dtype,
1977                                ino: child_ino,
1978                            });
1979                        }
1980                        f.dir_entries = Some(entries);
1981                    }
1982                }
1983
1984                let max = count.min((self.msize as usize).saturating_sub(HDR_LEN + 4));
1985                let mut w = Writer::new(max.min(65536) + HDR_LEN + 4);
1986                let count_pos = w.buf.len();
1987                w.u32(0);
1988                let data_start = w.buf.len();
1989
1990                if let Some(entries) = &f.dir_entries {
1991                    for (i, e) in entries.iter().enumerate().skip(offset) {
1992                        let nb = e.name.as_bytes();
1993                        if (w.buf.len() - data_start) + 24 + nb.len() > max {
1994                            break;
1995                        }
1996                        let _ = &e.rel_path;
1997                        w.u8(e.qtype);
1998                        w.u32(0);
1999                        w.u64(e.ino);
2000                        w.u64((i + 1) as u64);
2001                        w.u8(e.dtype);
2002                        w.u16(nb.len() as u16);
2003                        w.bytes(nb);
2004                    }
2005                }
2006                let written = (w.buf.len() - data_start) as u32;
2007                w.buf[count_pos..count_pos + 4].copy_from_slice(&written.to_le_bytes());
2008                Ok(w)
2009            }
2010            TREAD => {
2011                let fid = r.u32()?;
2012                let offset = r.u64()?;
2013                let req_count = r.u32()? as usize;
2014                let count = req_count.min((self.msize as usize).saturating_sub(HDR_LEN + 4));
2015                let f = self.fids.get(&fid).ok_or(EBADF)?;
2016                if let Some(cow) = &exp.cow {
2017                    if !f.cow_open {
2018                        return Err(if f.is_dir { EISDIR } else { EBADF });
2019                    }
2020                    let data = cow
2021                        .lock()
2022                        .unwrap()
2023                        .read_file(&exp.host_root, &f.rel_path)?
2024                        .ok_or(ENOENT)?;
2025                    let start = (offset as usize).min(data.len());
2026                    let end = start.saturating_add(count).min(data.len());
2027                    let slice = &data[start..end];
2028                    let mut w = Writer::new(HDR_LEN + 4 + slice.len());
2029                    w.u32(slice.len() as u32);
2030                    w.bytes(slice);
2031                    return Ok(w);
2032                }
2033                let Some(file) = &f.file else {
2034                    return Err(if f.is_dir { EISDIR } else { EBADF });
2035                };
2036                let mut buf = vec![0u8; count];
2037                let n = file_read_at(file, &mut buf, offset).map_err(io_to_errno)?;
2038                let mut w = Writer::new(HDR_LEN + 4 + n);
2039                w.u32(n as u32);
2040                w.bytes(&buf[..n]);
2041                Ok(w)
2042            }
2043            TWRITE => {
2044                let fid = r.u32()?;
2045                let offset = r.u64()?;
2046                let count = r.u32()? as usize;
2047                let data = r.bytes(count)?;
2048                let (rel_path, write_approved) = {
2049                    let f = self.fids.get(&fid).ok_or(EBADF)?;
2050                    (f.rel_path.clone(), f.write_approved)
2051                };
2052                if !write_approved {
2053                    self.gate_fs_write(&exp, "write", &rel_path, None)?;
2054                    if let Some(f) = self.fids.get_mut(&fid) {
2055                        f.write_approved = true;
2056                    }
2057                }
2058                if let Some(cow) = &exp.cow {
2059                    let f = self.fids.get(&fid).ok_or(EBADF)?;
2060                    if !f.cow_open {
2061                        return Err(if f.is_dir { EISDIR } else { EBADF });
2062                    }
2063                    let mut g = cow.lock().unwrap();
2064                    g.copy_up_file(&exp.host_root, &rel_path)?;
2065                    let key = norm_rel_key(&rel_path);
2066                    let Some(CowEntry::File {
2067                        data: buf, mtime, ..
2068                    }) = g.entries.get_mut(&key)
2069                    else {
2070                        return Err(EISDIR);
2071                    };
2072                    let start = offset as usize;
2073                    let end = start.checked_add(data.len()).ok_or(EINVAL)?;
2074                    if end > buf.len() {
2075                        buf.resize(end, 0);
2076                    }
2077                    buf[start..end].copy_from_slice(data);
2078                    *mtime = now_sec();
2079                    drop(g);
2080                    self.audit_fs(&exp, "write", &rel_path, None, Some(data.len()), "allow");
2081                    let mut w = Writer::new(16);
2082                    w.u32(data.len() as u32);
2083                    return Ok(w);
2084                }
2085                let f = self.fids.get(&fid).ok_or(EBADF)?;
2086                let Some(file) = &f.file else {
2087                    return Err(if f.is_dir { EISDIR } else { EBADF });
2088                };
2089                let n = file_write_at(file, data, offset).map_err(io_to_errno)?;
2090                self.audit_fs(&exp, "write", &rel_path, None, Some(n), "allow");
2091                let mut w = Writer::new(16);
2092                w.u32(n as u32);
2093                Ok(w)
2094            }
2095            TFSYNC => {
2096                let fid = r.u32()?;
2097                let f = self.fids.get(&fid).ok_or(EBADF)?;
2098                if let Some(file) = &f.file {
2099                    file.sync_all().map_err(io_to_errno)?;
2100                }
2101                Ok(Writer::new(HDR_LEN))
2102            }
2103            TLOCK => {
2104                let fid = r.u32()?;
2105                if !self.fids.contains_key(&fid) {
2106                    return Err(EBADF);
2107                }
2108                let mut w = Writer::new(12);
2109                w.u8(0); // P9_LOCK_SUCCESS
2110                Ok(w)
2111            }
2112            TGETLOCK => {
2113                let fid = r.u32()?;
2114                if !self.fids.contains_key(&fid) {
2115                    return Err(EBADF);
2116                }
2117                let _ty = r.u8()?;
2118                let start = r.u64()?;
2119                let len = r.u64()?;
2120                let proc_id = r.u32()?;
2121                let client = r.str()?;
2122                let mut w = Writer::new(48);
2123                w.u8(2); // F_UNLCK
2124                w.u64(start);
2125                w.u64(len);
2126                w.u32(proc_id);
2127                w.str(client);
2128                Ok(w)
2129            }
2130            _ => Err(EOPNOTSUPP),
2131        }
2132    }
2133}
2134
2135fn format_guest_rel(mount_root: &str, rel: &Path) -> String {
2136    let base = mount_root.trim_end_matches('/');
2137    let rel_s = rel.to_string_lossy().replace('\\', "/");
2138    if rel_s.is_empty() {
2139        if base.is_empty() {
2140            "/".to_string()
2141        } else {
2142            base.to_string()
2143        }
2144    } else {
2145        format!("{base}/{rel_s}")
2146    }
2147}
2148
2149fn validate_component(name: &str) -> std::result::Result<(), u32> {
2150    if name.is_empty()
2151        || name == "."
2152        || name == ".."
2153        || name.contains('/')
2154        || name.contains('\\')
2155        || name.contains('\0')
2156    {
2157        return Err(EINVAL);
2158    }
2159    #[cfg(windows)]
2160    if name.contains(':') {
2161        return Err(EINVAL);
2162    }
2163    Ok(())
2164}
2165
2166fn step_rel(base: &Path, name: &str) -> std::result::Result<PathBuf, u32> {
2167    if name == ".." {
2168        Ok(base.parent().unwrap_or(Path::new("")).to_path_buf())
2169    } else if name == "." {
2170        Ok(base.to_path_buf())
2171    } else {
2172        validate_component(name)?;
2173        Ok(base.join(name))
2174    }
2175}
2176
2177/// Resolve `rel` strictly inside `canonical_root`, rejecting any `..` escape or intermediate
2178/// symlink that points outside `canonical_root`.
2179fn resolve_confined(
2180    canonical_root: &Path,
2181    rel: &Path,
2182    allow_missing_leaf: bool,
2183) -> std::result::Result<PathBuf, u32> {
2184    let mut cur = canonical_root.to_path_buf();
2185    let comps: Vec<&std::ffi::OsStr> = rel
2186        .components()
2187        .map(|c| match c {
2188            Component::Normal(s) => Ok(s),
2189            _ => Err(EINVAL),
2190        })
2191        .collect::<std::result::Result<_, _>>()?;
2192
2193    for (idx, comp) in comps.iter().enumerate() {
2194        let is_last = idx + 1 == comps.len();
2195        let next = cur.join(comp);
2196        if is_last && allow_missing_leaf {
2197            // Parent `cur` is already canonical and verified under `canonical_root`.
2198            // If leaf exists as a symlink, do not follow it; caller opens with O_NOFOLLOW.
2199            return Ok(next);
2200        }
2201        match fs::symlink_metadata(&next) {
2202            Ok(meta) => {
2203                if meta.file_type().is_symlink() {
2204                    if is_last {
2205                        // Allow stat/readlink/unlink on the symlink itself, but never traverse outside root
2206                        return Ok(next);
2207                    }
2208                    // Intermediate symlink: must resolve strictly inside canonical_root
2209                    let resolved = fs::canonicalize(&next).map_err(io_to_errno)?;
2210                    if !resolved.starts_with(canonical_root) {
2211                        return Err(EACCES);
2212                    }
2213                    cur = resolved;
2214                } else {
2215                    cur = next;
2216                }
2217            }
2218            Err(e) => return Err(io_to_errno(e)),
2219        }
2220    }
2221    if !cur.starts_with(canonical_root) {
2222        return Err(EACCES);
2223    }
2224    Ok(cur)
2225}
2226
2227fn file_read_at(file: &File, dst: &mut [u8], offset: u64) -> io::Result<usize> {
2228    #[cfg(unix)]
2229    {
2230        use std::os::unix::fs::FileExt;
2231        file.read_at(dst, offset)
2232    }
2233    #[cfg(windows)]
2234    {
2235        use std::os::windows::fs::FileExt;
2236        file.seek_read(dst, offset)
2237    }
2238}
2239
2240fn file_write_at(file: &File, src: &[u8], offset: u64) -> io::Result<usize> {
2241    #[cfg(unix)]
2242    {
2243        use std::os::unix::fs::FileExt;
2244        file.write_at(src, offset)
2245    }
2246    #[cfg(windows)]
2247    {
2248        use std::os::windows::fs::FileExt;
2249        file.seek_write(src, offset)
2250    }
2251}
2252
2253fn configure_open_options(oo: &mut OpenOptions, mode: Option<u32>) {
2254    #[cfg(unix)]
2255    {
2256        use std::os::unix::fs::OpenOptionsExt;
2257        if let Some(m) = mode {
2258            oo.mode(m);
2259        }
2260        oo.custom_flags(libc::O_NOFOLLOW);
2261    }
2262    #[cfg(windows)]
2263    {
2264        use std::os::windows::fs::OpenOptionsExt;
2265        let _ = mode;
2266        // FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE allows POSIX-like rename/unlink while open
2267        oo.share_mode(1 | 2 | 4);
2268    }
2269}
2270
2271fn open_nofollow(oo: &OpenOptions, host_path: &Path) -> std::result::Result<File, u32> {
2272    #[cfg(windows)]
2273    if let Ok(meta) = fs::symlink_metadata(host_path)
2274        && meta.file_type().is_symlink()
2275    {
2276        return Err(EACCES);
2277    }
2278    oo.open(host_path).map_err(io_to_errno)
2279}
2280
2281fn set_unix_mode(host_path: &Path, mode: u32) -> std::result::Result<(), u32> {
2282    #[cfg(unix)]
2283    {
2284        use std::os::unix::fs::PermissionsExt;
2285        fs::set_permissions(host_path, fs::Permissions::from_mode(mode)).map_err(io_to_errno)
2286    }
2287    #[cfg(not(unix))]
2288    {
2289        let _ = (host_path, mode);
2290        Ok(())
2291    }
2292}
2293
2294fn create_symlink(target: &str, host_path: &Path) -> std::result::Result<(), u32> {
2295    #[cfg(unix)]
2296    {
2297        std::os::unix::fs::symlink(target, host_path).map_err(io_to_errno)
2298    }
2299    #[cfg(not(unix))]
2300    {
2301        let _ = (target, host_path);
2302        Err(EOPNOTSUPP)
2303    }
2304}
2305
2306fn meta_ino(meta: &fs::Metadata, rel_path: &Path) -> u64 {
2307    #[cfg(unix)]
2308    {
2309        use std::os::unix::fs::MetadataExt;
2310        let _ = rel_path;
2311        meta.ino()
2312    }
2313    #[cfg(not(unix))]
2314    {
2315        let _ = meta;
2316        let norm = rel_path.to_string_lossy().replace('\\', "/");
2317        if norm.is_empty() {
2318            return 1;
2319        }
2320        // Stable deterministic FNV-1a 64-bit hash for synthetic Windows inodes (never 0 or 1)
2321        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
2322        for b in norm.as_bytes() {
2323            h ^= *b as u64;
2324            h = h.wrapping_mul(0x0100_0000_01b3);
2325        }
2326        h | 2
2327    }
2328}
2329
2330fn meta_perm(meta: &fs::Metadata) -> u32 {
2331    #[cfg(unix)]
2332    {
2333        use std::os::unix::fs::MetadataExt;
2334        meta.mode() & 0o7777
2335    }
2336    #[cfg(not(unix))]
2337    {
2338        if meta.is_dir() {
2339            0o755
2340        } else if meta.permissions().readonly() {
2341            0o444
2342        } else {
2343            0o644
2344        }
2345    }
2346}
2347
2348fn meta_nlink(meta: &fs::Metadata) -> u64 {
2349    #[cfg(unix)]
2350    {
2351        use std::os::unix::fs::MetadataExt;
2352        meta.nlink()
2353    }
2354    #[cfg(not(unix))]
2355    {
2356        if meta.is_dir() { 2 } else { 1 }
2357    }
2358}
2359
2360fn meta_times(meta: &fs::Metadata) -> (u64, u64, u64, u64, u64, u64) {
2361    #[cfg(unix)]
2362    {
2363        use std::os::unix::fs::MetadataExt;
2364        (
2365            meta.atime().max(0) as u64,
2366            meta.atime_nsec().max(0) as u64,
2367            meta.mtime().max(0) as u64,
2368            meta.mtime_nsec().max(0) as u64,
2369            meta.ctime().max(0) as u64,
2370            meta.ctime_nsec().max(0) as u64,
2371        )
2372    }
2373    #[cfg(not(unix))]
2374    {
2375        let to_pair = |res: io::Result<SystemTime>| -> (u64, u64) {
2376            res.ok()
2377                .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
2378                .map(|d| (d.as_secs(), d.subsec_nanos() as u64))
2379                .unwrap_or((0, 0))
2380        };
2381        let (as_, an) = to_pair(meta.accessed());
2382        let (ms, mn) = to_pair(meta.modified());
2383        let (cs, cn) = to_pair(meta.created());
2384        (as_, an, ms, mn, cs, cn)
2385    }
2386}
2387
2388fn meta_to_qid(meta: &fs::Metadata, rel_path: &Path) -> (u8, u32, u64) {
2389    let ft = meta.file_type();
2390    let qt = if ft.is_dir() {
2391        QTDIR
2392    } else if ft.is_symlink() {
2393        QTSYMLINK
2394    } else {
2395        QTFILE
2396    };
2397    let ver = meta
2398        .modified()
2399        .ok()
2400        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
2401        .map(|d| d.as_secs() as u32)
2402        .unwrap_or_else(|| {
2403            SystemTime::now()
2404                .duration_since(UNIX_EPOCH)
2405                .map(|d| d.as_secs() as u32)
2406                .unwrap_or(0)
2407        });
2408    (qt, ver, meta_ino(meta, rel_path))
2409}
2410
2411fn io_to_errno(e: io::Error) -> u32 {
2412    #[cfg(unix)]
2413    if let Some(raw) = e.raw_os_error()
2414        && raw > 0
2415    {
2416        return raw as u32;
2417    }
2418    #[cfg(windows)]
2419    if let Some(raw) = e.raw_os_error() {
2420        match raw {
2421            32 | 33 => return EBUSY, // ERROR_SHARING_VIOLATION / ERROR_LOCK_VIOLATION
2422            145 => return ENOTEMPTY, // ERROR_DIR_NOT_EMPTY
2423            _ => {}
2424        }
2425    }
2426    match e.kind() {
2427        io::ErrorKind::NotFound => ENOENT,
2428        io::ErrorKind::PermissionDenied => EACCES,
2429        io::ErrorKind::AlreadyExists => EEXIST,
2430        io::ErrorKind::InvalidInput => EINVAL,
2431        io::ErrorKind::NotADirectory => ENOTDIR,
2432        io::ErrorKind::IsADirectory => EISDIR,
2433        io::ErrorKind::DirectoryNotEmpty => ENOTEMPTY,
2434        io::ErrorKind::ReadOnlyFilesystem => EROFS,
2435        _ => EIO,
2436    }
2437}
2438
2439struct Reader<'a> {
2440    buf: &'a [u8],
2441    p: usize,
2442}
2443
2444impl<'a> Reader<'a> {
2445    fn new(buf: &'a [u8]) -> Self {
2446        Self { buf, p: 0 }
2447    }
2448    fn u8(&mut self) -> std::result::Result<u8, u32> {
2449        if self.p + 1 > self.buf.len() {
2450            return Err(EPROTO);
2451        }
2452        let v = self.buf[self.p];
2453        self.p += 1;
2454        Ok(v)
2455    }
2456    fn u16(&mut self) -> std::result::Result<u16, u32> {
2457        if self.p + 2 > self.buf.len() {
2458            return Err(EPROTO);
2459        }
2460        let v = u16::from_le_bytes([self.buf[self.p], self.buf[self.p + 1]]);
2461        self.p += 2;
2462        Ok(v)
2463    }
2464    fn u32(&mut self) -> std::result::Result<u32, u32> {
2465        if self.p + 4 > self.buf.len() {
2466            return Err(EPROTO);
2467        }
2468        let v = u32::from_le_bytes(self.buf[self.p..self.p + 4].try_into().unwrap());
2469        self.p += 4;
2470        Ok(v)
2471    }
2472    fn u64(&mut self) -> std::result::Result<u64, u32> {
2473        if self.p + 8 > self.buf.len() {
2474            return Err(EPROTO);
2475        }
2476        let v = u64::from_le_bytes(self.buf[self.p..self.p + 8].try_into().unwrap());
2477        self.p += 8;
2478        Ok(v)
2479    }
2480    fn bytes(&mut self, n: usize) -> std::result::Result<&'a [u8], u32> {
2481        if self.p + n > self.buf.len() {
2482            return Err(EPROTO);
2483        }
2484        let s = &self.buf[self.p..self.p + n];
2485        self.p += n;
2486        Ok(s)
2487    }
2488    fn str(&mut self) -> std::result::Result<&'a str, u32> {
2489        let len = self.u16()? as usize;
2490        let b = self.bytes(len)?;
2491        std::str::from_utf8(b).map_err(|_| EINVAL)
2492    }
2493}
2494
2495struct Writer {
2496    buf: Vec<u8>,
2497}
2498
2499impl Writer {
2500    fn new(cap: usize) -> Self {
2501        let mut buf = Vec::with_capacity(cap.max(HDR_LEN));
2502        buf.resize(HDR_LEN, 0);
2503        Self { buf }
2504    }
2505    fn u8(&mut self, v: u8) {
2506        self.buf.push(v);
2507    }
2508    fn u16(&mut self, v: u16) {
2509        self.buf.extend_from_slice(&v.to_le_bytes());
2510    }
2511    fn u32(&mut self, v: u32) {
2512        self.buf.extend_from_slice(&v.to_le_bytes());
2513    }
2514    fn u64(&mut self, v: u64) {
2515        self.buf.extend_from_slice(&v.to_le_bytes());
2516    }
2517    fn bytes(&mut self, b: &[u8]) {
2518        self.buf.extend_from_slice(b);
2519    }
2520    fn str(&mut self, s: &str) {
2521        let b = s.as_bytes();
2522        self.u16(b.len() as u16);
2523        self.bytes(b);
2524    }
2525    fn qid(&mut self, meta: &fs::Metadata, rel_path: &Path) {
2526        let (qt, ver, ino) = meta_to_qid(meta, rel_path);
2527        self.u8(qt);
2528        self.u32(ver);
2529        self.u64(ino);
2530    }
2531    fn cow_qid(&mut self, st: &CowStat) {
2532        self.u8(st.qtype);
2533        self.u32((st.mtime as u32).wrapping_add(st.epoch as u32));
2534        self.u64(st.ino);
2535    }
2536    fn finish(mut self, mtype: u8, tag: u16) -> Vec<u8> {
2537        let sz = self.buf.len() as u32;
2538        self.buf[0..4].copy_from_slice(&sz.to_le_bytes());
2539        self.buf[4] = mtype;
2540        self.buf[5..7].copy_from_slice(&tag.to_le_bytes());
2541        self.buf
2542    }
2543}