filament-cli 0.6.3

P2P file transfer between terminals and browsers, no upload, no account. The terminal end of filament.autumated.com.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
// Unix FUSE client adapter for the mesh-native mount protocol (Linux FUSE and
// macOS macFUSE).
//
// This is the `MountHost` piece from docs/design-cross-platform-capabilities.md:
// the mesh serves a uniform SFTP-like file protocol (see mount_proto.rs), and
// this adapter presents that protocol as a real local filesystem via FUSE. The
// server needs no FUSE; only the client mount does. macOS reuses this same crate
// (macFUSE) and Windows gets a WinFsp/ProjFS adapter in a later round.
//
// Design notes:
//   * The wire protocol is PATH-based; FUSE is INODE-based. `InodeMap` is the
//     client-side bridge: a stable u64 inode per path (root = 1), allocated on
//     first lookup/readdir and reused so the kernel's inode cache stays coherent.
//   * Server file handles pass straight through as FUSE file handles.
//   * fuser 0.17's `Filesystem` methods take `&self`, but `MountClient::call_sync`
//     needs `&mut` (it owns the framing buffer + id counter), so the client lives
//     behind a `Mutex`. fuser runs a single event-loop thread by default, so this
//     never contends.
//   * `call_sync` blocks the calling thread on a tokio mpsc, so the whole FUSE
//     session runs inside `spawn_blocking` while the mux pump tasks keep draining
//     the transport on the tokio runtime.

#![cfg(any(target_os = "linux", all(target_os = "macos", feature = "mount-macos")))]

use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use fuser::{
    Config, FileAttr, FileType, Filesystem, Generation, MountOption, OpenFlags, ReplyAttr,
    ReplyCreate, ReplyData, ReplyDirectory, ReplyEmpty, ReplyEntry, ReplyOpen, ReplyWrite, Request,
    TimeOrNow,
};
use fuser::{Errno, FileHandle, FopenFlags, INodeNo};
use serde_json::Value;

use crate::mount_proto::{FileKind, FileStat, MountClient, MountOp, MountResult};

const EIO: i32 = 5;
const TTL: Duration = Duration::from_secs(1);

/// Maps stable FUSE inode numbers to protocol paths (relative to the mount root)
/// and back. Root is inode 1, path ".". New inodes are handed out monotonically
/// and cached both ways so repeated lookups of the same path are stable.
///
/// When `case_sensitive` is false (e.g. macOS mounting a case-preserving but
/// case-insensitive filesystem) the reverse lookup key is lowercased so that
/// "File" and "file" resolve to the same inode. This is an ASCII-centric
/// approximation; full Unicode case folding is left to a future normalization
/// pass.
struct InodeMap {
    fwd: HashMap<u64, PathBuf>,
    rev: HashMap<String, u64>,
    next: u64,
    case_sensitive: bool,
}

impl InodeMap {
    fn new(case_sensitive: bool) -> Self {
        let mut fwd = HashMap::new();
        let mut rev = HashMap::new();
        fwd.insert(1, PathBuf::from("."));
        rev.insert(Self::normalize(Path::new(".")), 1);
        InodeMap { fwd, rev, next: 2, case_sensitive }
    }

    fn normalize(path: &Path) -> String {
        path.to_string_lossy().to_lowercase()
    }

    fn key(&self, path: &Path) -> String {
        if self.case_sensitive {
            path.to_string_lossy().into_owned()
        } else {
            Self::normalize(path)
        }
    }

    fn path(&self, ino: u64) -> Option<PathBuf> {
        self.fwd.get(&ino).cloned()
    }

    fn intern(&mut self, path: PathBuf) -> u64 {
        let key = self.key(&path);
        if let Some(&i) = self.rev.get(&key) {
            return i;
        }
        let i = self.next;
        self.next += 1;
        self.fwd.insert(i, path);
        self.rev.insert(key, i);
        i
    }

    fn forget(&mut self, path: &Path) {
        let key = self.key(path);
        if let Some(i) = self.rev.remove(&key) {
            self.fwd.remove(&i);
        }
    }
}

/// A cached directory listing, captured on the first `readdir` for an open dir
/// handle and served across the paginated readdir calls the kernel makes.
struct CachedDir {
    // (child inode, kind, name) triples, in listing order.
    entries: Vec<(u64, FileType, OsString)>,
}

pub struct FilamentFs {
    client: Mutex<MountClient>,
    inodes: Mutex<InodeMap>,
    // Keyed by the server file handle returned from opendir.
    dirs: Mutex<HashMap<u64, CachedDir>>,
}

impl FilamentFs {
    pub fn new(client: MountClient) -> Self {
        // The mount protocol is v2+. A v1 client reaching here is a programming
        // error; fail fast rather than silently return empty data.
        assert!(client.binary_frames, "FilamentFs requires a v2 MountClient");
        let case_sensitive = client.caps.case_sensitive;
        FilamentFs {
            client: Mutex::new(client),
            inodes: Mutex::new(InodeMap::new(case_sensitive)),
            dirs: Mutex::new(HashMap::new()),
        }
    }

    /// Issue one protocol op and unwrap the result to either the ok `Value` or a
    /// POSIX errno the FUSE reply can carry. A dead channel maps to EIO.
    fn call(&self, op: MountOp) -> Result<Value, i32> {
        self.call_data(op, None).map(|(v, _)| v)
    }

    /// Issue one protocol op with an optional binary data payload (for Write)
    /// and collect any binary payload from the response (for Read).
    fn call_data(&self, op: MountOp, data: Option<&[u8]>) -> Result<(Value, Option<Vec<u8>>), i32> {
        let mut c = self.client.lock().unwrap();
        match c.call_sync_binary(op, data) {
            Ok((resp, bin)) => match resp.result {
                MountResult::Ok(v) => Ok((v, bin.map(|b| b.to_vec()))),
                MountResult::Err(e) => Err(e.code),
            },
            Err(_) => Err(EIO),
        }
    }

    fn path_of(&self, ino: u64) -> Result<PathBuf, i32> {
        self.inodes
            .lock()
            .unwrap()
            .path(ino)
            .ok_or(libc::ENOENT)
    }

    fn supports_fifo(&self) -> bool {
        self.client.lock().unwrap().caps.supports_fifo
    }
}

/// Join a child name onto a parent path, keeping the root as "." rather than
/// "./name" so the encoded wire path and the inode-map key stay canonical.
fn child_path(parent: &Path, name: &OsStr) -> PathBuf {
    if parent == Path::new(".") {
        PathBuf::from(name)
    } else {
        parent.join(name)
    }
}

fn encode(path: &Path) -> String {
    crate::mount_proto::path_encode(path)
}

fn kind_to_fuse(stat: &FileStat, supports_fifo: bool) -> FileType {
    match stat.kind {
        Some(FileKind::Dir) => FileType::Directory,
        Some(FileKind::Symlink) => FileType::Symlink,
        _ => {
            // No explicit kind: fall back to the mode type bits.
            match stat.mode & 0o170000 {
                0o040000 => FileType::Directory,
                0o120000 => FileType::Symlink,
                0o010000 => {
                    if supports_fifo { FileType::NamedPipe } else { FileType::RegularFile }
                }
                0o140000 => FileType::Socket,
                0o020000 => FileType::CharDevice,
                0o060000 => FileType::BlockDevice,
                _ => FileType::RegularFile,
            }
        }
    }
}

/// Build a fuser `FileAttr` from the protocol `FileStat`, stamping the given
/// stable inode. Times we cannot represent collapse to mtime (v1 carries mtime
/// only, per the spec's best-effort metadata rule).
fn to_attr(ino: u64, stat: &FileStat, supports_fifo: bool) -> FileAttr {
    let mtime = UNIX_EPOCH + Duration::from_secs(stat.mtime);
    FileAttr {
        ino: INodeNo(ino),
        size: stat.size,
        blocks: stat.blocks,
        atime: mtime,
        mtime,
        ctime: mtime,
        crtime: mtime,
        kind: kind_to_fuse(stat, supports_fifo),
        perm: (stat.mode & 0o7777) as u16,
        nlink: stat.nlink.max(1),
        uid: stat.uid,
        gid: stat.gid,
        rdev: 0,
        blksize: stat.blksize,
        flags: 0,
    }
}

fn parse_stat(v: &Value) -> Result<FileStat, i32> {
    serde_json::from_value(v.clone()).map_err(|_| EIO)
}

impl Filesystem for FilamentFs {
    fn lookup(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEntry) {
        let parent_path = match self.path_of(parent.0) {
            Ok(p) => p,
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        let path = child_path(&parent_path, name);
        match self.call(MountOp::GetAttr { path: encode(&path) }) {
            Ok(v) => match parse_stat(&v) {
                Ok(stat) => {
                    let ino = self.inodes.lock().unwrap().intern(path);
                    reply.entry(&TTL, &to_attr(ino, &stat, self.supports_fifo()), Generation(0));
                }
                Err(e) => reply.error(Errno::from_i32(e)),
            },
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }

    fn getattr(&self, _req: &Request, ino: INodeNo, _fh: Option<FileHandle>, reply: ReplyAttr) {
        let path = match self.path_of(ino.0) {
            Ok(p) => p,
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        match self.call(MountOp::GetAttr { path: encode(&path) }) {
            Ok(v) => match parse_stat(&v) {
                Ok(stat) => reply.attr(&TTL, &to_attr(ino.0, &stat, self.supports_fifo())),
                Err(e) => reply.error(Errno::from_i32(e)),
            },
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }

    fn setattr(
        &self,
        _req: &Request,
        ino: INodeNo,
        _mode: Option<u32>,
        _uid: Option<u32>,
        _gid: Option<u32>,
        size: Option<u64>,
        _atime: Option<TimeOrNow>,
        _mtime: Option<TimeOrNow>,
        _ctime: Option<SystemTime>,
        _fh: Option<FileHandle>,
        _crtime: Option<SystemTime>,
        _chgtime: Option<SystemTime>,
        _bkuptime: Option<SystemTime>,
        _flags: Option<fuser::BsdFileFlags>,
        reply: ReplyAttr,
    ) {
        let path = match self.path_of(ino.0) {
            Ok(p) => p,
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        // v1 honours the one setattr that changes bytes: truncate. mode/uid/gid/
        // timestamps are acked best-effort (the spec's honest-metadata rule); we
        // re-stat and return the server's truth rather than fake the requested
        // values.
        if let Some(sz) = size {
            if let Err(e) = self.call(MountOp::Truncate { path: encode(&path), size: sz }) {
                return reply.error(Errno::from_i32(e));
            }
        }
        match self.call(MountOp::GetAttr { path: encode(&path) }) {
            Ok(v) => match parse_stat(&v) {
                Ok(stat) => reply.attr(&TTL, &to_attr(ino.0, &stat, self.supports_fifo())),
                Err(e) => reply.error(Errno::from_i32(e)),
            },
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }

    fn readlink(&self, _req: &Request, ino: INodeNo, reply: ReplyData) {
        let path = match self.path_of(ino.0) {
            Ok(p) => p,
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        match self.call(MountOp::ReadLink { path: encode(&path) }) {
            // The server returns the target as an encoded raw-byte path; the link
            // body handed to the kernel is exactly those bytes.
            Ok(Value::String(enc)) => match crate::mount_proto::path_decode(&enc) {
                Ok(target) => reply.data(target.as_os_str().as_bytes()),
                Err(_) => reply.error(Errno::from_i32(EIO)),
            },
            Ok(_) => reply.error(Errno::from_i32(EIO)),
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }

    fn open(&self, _req: &Request, ino: INodeNo, flags: OpenFlags, reply: ReplyOpen) {
        let path = match self.path_of(ino.0) {
            Ok(p) => p,
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        match self.call(MountOp::Open { path: encode(&path), flags: flags.0 }) {
            Ok(v) => {
                let fh = v["fh"].as_u64().unwrap_or(0);
                reply.opened(FileHandle(fh), FopenFlags::empty());
            }
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }

    fn read(
        &self,
        _req: &Request,
        _ino: INodeNo,
        fh: FileHandle,
        offset: u64,
        size: u32,
        _flags: OpenFlags,
        _lock_owner: Option<fuser::LockOwner>,
        reply: ReplyData,
    ) {
        let max_read = self.client.lock().unwrap().caps.max_read_size;
        let size = size.min(max_read);
        match self.call_data(MountOp::Read { fh: fh.0, offset, size }, None) {
            Ok((_v, Some(bytes))) => reply.data(&bytes),
            Ok((_, None)) => reply.data(&[]),
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }

    fn write(
        &self,
        _req: &Request,
        _ino: INodeNo,
        fh: FileHandle,
        offset: u64,
        data: &[u8],
        _write_flags: fuser::WriteFlags,
        _flags: OpenFlags,
        _lock_owner: Option<fuser::LockOwner>,
        reply: ReplyWrite,
    ) {
        // The kernel may hand us a buffer larger than the server advertised.
        // Split it into cap-sized chunks so each frame fits through every
        // transport path (direct-quic, relay, WebRTC DataChannel).
        let max_write = self.client.lock().unwrap().caps.max_write_size;
        let mut written: u32 = 0;
        for chunk in data.chunks(max_write as usize) {
            match self.call_data(
                MountOp::Write {
                    fh: fh.0,
                    offset: offset + written as u64,
                    size: chunk.len() as u32,
                },
                Some(chunk),
            ) {
                Ok((v, _)) => written += v["size"].as_u64().unwrap_or(0) as u32,
                Err(e) => return reply.error(Errno::from_i32(e)),
            }
        }
        reply.written(written);
    }

    fn flush(
        &self,
        _req: &Request,
        _ino: INodeNo,
        _fh: FileHandle,
        _lock_owner: fuser::LockOwner,
        reply: ReplyEmpty,
    ) {
        // No client-side write buffering: writes are already synchronous round
        // trips to the server, so there is nothing to flush here.
        reply.ok();
    }

    fn fsync(&self, _req: &Request, _ino: INodeNo, fh: FileHandle, datasync: bool, reply: ReplyEmpty) {
        match self.call(MountOp::FSync { fh: fh.0, datasync }) {
            Ok(_) => reply.ok(),
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }

    fn release(
        &self,
        _req: &Request,
        _ino: INodeNo,
        fh: FileHandle,
        _flags: OpenFlags,
        _lock_owner: Option<fuser::LockOwner>,
        _flush: bool,
        reply: ReplyEmpty,
    ) {
        let _ = self.call(MountOp::Release { fh: fh.0 });
        reply.ok();
    }

    fn opendir(&self, _req: &Request, ino: INodeNo, flags: OpenFlags, reply: ReplyOpen) {
        let path = match self.path_of(ino.0) {
            Ok(p) => p,
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        // The server serves ReadDir off an open handle, so a dir opens like a file.
        match self.call(MountOp::Open { path: encode(&path), flags: flags.0 }) {
            Ok(v) => {
                let fh = v["fh"].as_u64().unwrap_or(0);
                reply.opened(FileHandle(fh), FopenFlags::empty());
            }
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }

    fn readdir(
        &self,
        _req: &Request,
        ino: INodeNo,
        fh: FileHandle,
        offset: u64,
        mut reply: ReplyDirectory,
    ) {
        // Populate the cache once (offset 0), then paginate from it. The server
        // returns the whole listing in one ReadDir, so caching keeps readdir
        // stable across the kernel's paginated calls.
        if offset == 0 {
            let dir_path = match self.path_of(ino.0) {
                Ok(p) => p,
                Err(e) => return reply.error(Errno::from_i32(e)),
            };
            let listing = match self.call(MountOp::ReadDir { fh: fh.0, offset: 0 }) {
                Ok(v) => v,
                Err(e) => return reply.error(Errno::from_i32(e)),
            };
            let parent_ino = {
                let inodes = self.inodes.lock().unwrap();
                dir_path
                    .parent()
                    .filter(|p| !p.as_os_str().is_empty())
                    .and_then(|p| {
                        let key = inodes.key(p);
                        inodes.rev.get(&key).copied()
                    })
                    .unwrap_or(1)
            };
            let mut entries: Vec<(u64, FileType, OsString)> = Vec::new();
            entries.push((ino.0, FileType::Directory, OsString::from(".")));
            entries.push((parent_ino, FileType::Directory, OsString::from("..")));
            if let Some(arr) = listing.as_array() {
                let mut inodes = self.inodes.lock().unwrap();
                for e in arr {
                    let name_enc = e["name"].as_str().unwrap_or("");
                    // Names are raw bytes on the wire; decode to an OsString and
                    // never lossy-convert (spec rule 2). Skip anything undecodable.
                    let name_os = match crate::mount_proto::path_decode(name_enc) {
                        Ok(p) => match p.file_name() {
                            Some(n) => n.to_os_string(),
                            None => continue,
                        },
                        Err(_) => continue,
                    };
                    let stat: FileStat = match serde_json::from_value(e["stat"].clone()) {
                        Ok(s) => s,
                        Err(_) => continue,
                    };
                    let child = child_path(&dir_path, &name_os);
                    let child_ino = inodes.intern(child);
                    entries.push((child_ino, kind_to_fuse(&stat, self.supports_fifo()), name_os));
                }
            }
            self.dirs.lock().unwrap().insert(fh.0, CachedDir { entries });
        }

        let dirs = self.dirs.lock().unwrap();
        if let Some(cached) = dirs.get(&fh.0) {
            for (idx, (child_ino, kind, name)) in
                cached.entries.iter().enumerate().skip(offset as usize)
            {
                // The offset we hand back is the index of the NEXT entry, so a
                // resumed readdir continues correctly.
                let next = (idx + 1) as u64;
                if reply.add(INodeNo(*child_ino), next, *kind, name) {
                    break; // kernel buffer full; the rest comes on the next call
                }
            }
        }
        reply.ok();
    }

    fn releasedir(
        &self,
        _req: &Request,
        _ino: INodeNo,
        fh: FileHandle,
        _flags: OpenFlags,
        reply: ReplyEmpty,
    ) {
        self.dirs.lock().unwrap().remove(&fh.0);
        let _ = self.call(MountOp::Release { fh: fh.0 });
        reply.ok();
    }

    fn create(
        &self,
        _req: &Request,
        parent: INodeNo,
        name: &OsStr,
        mode: u32,
        _umask: u32,
        flags: i32,
        reply: ReplyCreate,
    ) {
        let parent_path = match self.path_of(parent.0) {
            Ok(p) => p,
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        let path = child_path(&parent_path, name);
        let fh = match self.call(MountOp::Create { path: encode(&path), mode, flags }) {
            Ok(v) => v["fh"].as_u64().unwrap_or(0),
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        match self.call(MountOp::GetAttr { path: encode(&path) }) {
            Ok(v) => match parse_stat(&v) {
                Ok(stat) => {
                    let ino = self.inodes.lock().unwrap().intern(path);
                    reply.created(
                        &TTL,
                        &to_attr(ino, &stat, self.supports_fifo()),
                        Generation(0),
                        FileHandle(fh),
                        FopenFlags::empty(),
                    );
                }
                Err(e) => reply.error(Errno::from_i32(e)),
            },
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }

    fn mkdir(
        &self,
        _req: &Request,
        parent: INodeNo,
        name: &OsStr,
        mode: u32,
        _umask: u32,
        reply: ReplyEntry,
    ) {
        let parent_path = match self.path_of(parent.0) {
            Ok(p) => p,
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        let path = child_path(&parent_path, name);
        if let Err(e) = self.call(MountOp::MkDir { path: encode(&path), mode }) {
            return reply.error(Errno::from_i32(e));
        }
        match self.call(MountOp::GetAttr { path: encode(&path) }) {
            Ok(v) => match parse_stat(&v) {
                Ok(stat) => {
                    let ino = self.inodes.lock().unwrap().intern(path);
                    reply.entry(&TTL, &to_attr(ino, &stat, self.supports_fifo()), Generation(0));
                }
                Err(e) => reply.error(Errno::from_i32(e)),
            },
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }

    fn unlink(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {
        let parent_path = match self.path_of(parent.0) {
            Ok(p) => p,
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        let path = child_path(&parent_path, name);
        match self.call(MountOp::Unlink { path: encode(&path) }) {
            Ok(_) => {
                self.inodes.lock().unwrap().forget(&path);
                reply.ok();
            }
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }

    fn rmdir(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {
        let parent_path = match self.path_of(parent.0) {
            Ok(p) => p,
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        let path = child_path(&parent_path, name);
        match self.call(MountOp::RmDir { path: encode(&path) }) {
            Ok(_) => {
                self.inodes.lock().unwrap().forget(&path);
                reply.ok();
            }
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }

    fn rename(
        &self,
        _req: &Request,
        parent: INodeNo,
        name: &OsStr,
        newparent: INodeNo,
        newname: &OsStr,
        _flags: fuser::RenameFlags,
        reply: ReplyEmpty,
    ) {
        let from_parent = match self.path_of(parent.0) {
            Ok(p) => p,
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        let to_parent = match self.path_of(newparent.0) {
            Ok(p) => p,
            Err(e) => return reply.error(Errno::from_i32(e)),
        };
        let from = child_path(&from_parent, name);
        let to = child_path(&to_parent, newname);
        match self.call(MountOp::Rename { from: encode(&from), to: encode(&to) }) {
            Ok(_) => {
                // Drop the stale inode bindings; the kernel re-looks-up as needed.
                let mut inodes = self.inodes.lock().unwrap();
                inodes.forget(&from);
                inodes.forget(&to);
                reply.ok();
            }
            Err(e) => reply.error(Errno::from_i32(e)),
        }
    }
}

/// Mount the protocol served by `client` at `mountpoint` via FUSE. Blocks the
/// calling thread running the FUSE session loop until the filesystem is
/// unmounted (by `fusermount -u`, `umount`, or the kernel on teardown). Because
/// `MountClient::call_sync` blocks on the tokio mpsc, callers must run this on a
/// dedicated blocking thread (`spawn_blocking`) so the mux pump keeps draining.
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn inodemap_case_sensitive_distinct_keys() {
        let mut map = InodeMap::new(true);
        let a = map.intern(PathBuf::from("File.txt"));
        let b = map.intern(PathBuf::from("file.txt"));
        assert_ne!(a, b, "case-sensitive map treats File and file as distinct");
    }

    #[test]
    fn inodemap_case_insensitive_merges_keys() {
        let mut map = InodeMap::new(false);
        let a = map.intern(PathBuf::from("File.txt"));
        let b = map.intern(PathBuf::from("file.txt"));
        assert_eq!(a, b, "case-insensitive map merges File and file");
    }

    #[test]
    fn inodemap_case_insensitive_forget_by_other_case() {
        let mut map = InodeMap::new(false);
        let _ = map.intern(PathBuf::from("Foo"));
        map.forget(Path::new("foo"));
        assert!(map.path(2).is_none());
    }

    #[test]
    fn kind_to_fuse_fifo_when_supported() {
        let stat = FileStat { ino: 1, kind: None, mode: 0o010644, size: 0, blocks: 0, mtime: 0, nlink: 1, uid: 0, gid: 0, blksize: 512 };
        assert_eq!(kind_to_fuse(&stat, true), FileType::NamedPipe);
    }

    #[test]
    fn kind_to_fuse_fifo_mapped_to_regular_when_not_supported() {
        let stat = FileStat { ino: 1, kind: None, mode: 0o010644, size: 0, blocks: 0, mtime: 0, nlink: 1, uid: 0, gid: 0, blksize: 512 };
        assert_eq!(kind_to_fuse(&stat, false), FileType::RegularFile);
    }
}

pub fn run_mount(client: MountClient, mountpoint: &Path) -> anyhow::Result<()> {
    let max_read = client.caps.max_read_size;
    let fs = FilamentFs::new(client);
    let mut cfg = Config::default();
    // FSName labels the mount in /proc/mounts. max_read matches the server's
    // advertised cap so the kernel never requests a single read larger than
    // one transport frame. We deliberately omit AutoUnmount (it needs
    // allow_other and a fuse.conf tweak); teardown is driven explicitly by the
    // caller via fusermount -u / ctrl-c.
    cfg.mount_options = vec![
        MountOption::FSName("filament".into()),
        MountOption::CUSTOM(format!("max_read={max_read}")),
    ];
    // macOS-specific mount options for macFUSE.
    #[cfg(target_os = "macos")]
    {
        cfg.mount_options.extend([
            MountOption::CUSTOM("volname=Filament".into()),
            MountOption::CUSTOM("local".into()),
            MountOption::CUSTOM("noappledouble".into()),
            MountOption::CUSTOM("daemon_timeout=60".into()),
        ]);
    }
    fuser::mount2(fs, mountpoint, &cfg)?;
    Ok(())
}