rfuse3 0.0.8

FUSE user-space library async version implementation.
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
use clap::Parser;
use futures_util::Stream;
use rfuse3::{
    raw::{prelude::*, Filesystem, Session},
    MountOptions, Result,
};
use std::ffi::OsStr;
use std::time::{Duration, SystemTime};
use tokio::signal;
use tracing::{debug, info, warn};

/// A minimal read-only filesystem implementation
#[derive(Debug)]
struct MinimalFileSystem {
    content: String,
}

impl MinimalFileSystem {
    fn new() -> Self {
        Self {
            content: "Hello, rfuse3! This is a minimal filesystem example.\n".to_string(),
        }
    }

    /// Create a FileAttr for the root directory
    fn root_attr(&self) -> FileAttr {
        FileAttr {
            ino: 1,
            size: 0,
            blocks: 0,
            atime: SystemTime::now().into(),
            mtime: SystemTime::now().into(),
            ctime: SystemTime::now().into(),
            #[cfg(target_os = "macos")]
            crtime: SystemTime::now().into(),
            kind: FileType::Directory,
            perm: 0o755,
            nlink: 2,
            uid: 0,
            gid: 0,
            rdev: 0,
            blksize: 4096,
            #[cfg(target_os = "macos")]
            flags: 0,
        }
    }

    /// Create a FileAttr for the hello.txt file
    fn file_attr(&self) -> FileAttr {
        FileAttr {
            ino: 2,
            size: self.content.len() as u64,
            blocks: 1,
            atime: SystemTime::now().into(),
            mtime: SystemTime::now().into(),
            ctime: SystemTime::now().into(),
            #[cfg(target_os = "macos")]
            crtime: SystemTime::now().into(),
            kind: FileType::RegularFile,
            perm: 0o644,
            nlink: 1,
            uid: 0,
            gid: 0,
            rdev: 0,
            blksize: 4096,
            #[cfg(target_os = "macos")]
            flags: 0,
        }
    }
}

impl Filesystem for MinimalFileSystem {
    async fn init(&self, _req: Request) -> Result<ReplyInit> {
        info!("Filesystem initialization");
        Ok(ReplyInit::default())
    }

    async fn destroy(&self, _req: Request) {
        info!("Filesystem destruction");
    }

    async fn lookup(&self, _req: Request, parent: u64, name: &OsStr) -> Result<ReplyEntry> {
        let name_str = name.to_string_lossy();
        debug!("Looking up file: parent={}, name={}", parent, name_str);

        if parent == 1 && name_str == "hello.txt" {
            Ok(ReplyEntry {
                ttl: Duration::from_secs(1),
                attr: self.file_attr(),
                generation: 0,
            })
        } else {
            Err(libc::ENOENT.into())
        }
    }

    async fn getattr(
        &self,
        _req: Request,
        inode: u64,
        _fh: Option<u64>,
        _flags: u32,
    ) -> Result<ReplyAttr> {
        debug!("Getting attributes: inode={}", inode);

        let attr = match inode {
            1 => self.root_attr(),
            2 => self.file_attr(),
            _ => return Err(libc::ENOENT.into()),
        };

        Ok(ReplyAttr {
            ttl: Duration::from_secs(1),
            attr,
        })
    }

    async fn opendir(&self, _req: Request, inode: u64, _flags: u32) -> Result<ReplyOpen> {
        debug!("Opening directory: inode={}", inode);

        if inode == 1 {
            Ok(ReplyOpen { fh: 1, flags: 0 })
        } else {
            Err(libc::ENOENT.into())
        }
    }

    async fn readdir<'a>(
        &'a self,
        _req: Request,
        parent: u64,
        _fh: u64,
        offset: i64,
    ) -> Result<ReplyDirectory<impl Stream<Item = Result<DirectoryEntry>> + Send + 'a>> {
        debug!("Reading directory: parent={}, offset={}", parent, offset);

        if parent == 1 {
            let entries = vec![
                DirectoryEntry {
                    inode: 1,
                    offset: 1,
                    kind: FileType::Directory,
                    name: std::ffi::OsString::from("."),
                },
                DirectoryEntry {
                    inode: 1,
                    offset: 2,
                    kind: FileType::Directory,
                    name: std::ffi::OsString::from(".."),
                },
                DirectoryEntry {
                    inode: 2,
                    offset: 3,
                    kind: FileType::RegularFile,
                    name: std::ffi::OsString::from("hello.txt"),
                },
            ];

            let filtered: Vec<_> = entries
                .into_iter()
                .filter(|entry| entry.offset > offset)
                .map(Ok)
                .collect();

            Ok(ReplyDirectory {
                entries: futures_util::stream::iter(filtered),
            })
        } else {
            Err(libc::ENOENT.into())
        }
    }

    async fn readdirplus<'a>(
        &'a self,
        _req: Request,
        parent: u64,
        _fh: u64,
        offset: u64,
        _lock_owner: u64,
    ) -> Result<ReplyDirectoryPlus<impl Stream<Item = Result<DirectoryEntryPlus>> + Send + 'a>>
    {
        debug!(
            "Reading directory plus: parent={}, offset={}",
            parent, offset
        );

        if parent == 1 {
            let root_attr = self.root_attr();
            let file_attr = self.file_attr();

            let entries = vec![
                DirectoryEntryPlus {
                    inode: 1,
                    generation: 0,
                    kind: FileType::Directory,
                    name: std::ffi::OsString::from("."),
                    offset: 1,
                    attr: root_attr,
                    entry_ttl: Duration::from_secs(1),
                    attr_ttl: Duration::from_secs(1),
                },
                DirectoryEntryPlus {
                    inode: 1,
                    generation: 0,
                    kind: FileType::Directory,
                    name: std::ffi::OsString::from(".."),
                    offset: 2,
                    attr: root_attr,
                    entry_ttl: Duration::from_secs(1),
                    attr_ttl: Duration::from_secs(1),
                },
                DirectoryEntryPlus {
                    inode: 2,
                    generation: 0,
                    kind: FileType::RegularFile,
                    name: std::ffi::OsString::from("hello.txt"),
                    offset: 3,
                    attr: file_attr,
                    entry_ttl: Duration::from_secs(1),
                    attr_ttl: Duration::from_secs(1),
                },
            ];

            let filtered: Vec<_> = entries
                .into_iter()
                .filter(|entry| (entry.offset as u64) > offset)
                .map(Ok)
                .collect();

            Ok(ReplyDirectoryPlus {
                entries: futures_util::stream::iter(filtered),
            })
        } else {
            Err(libc::ENOENT.into())
        }
    }

    async fn open(&self, _req: Request, inode: u64, _flags: u32) -> Result<ReplyOpen> {
        debug!("Opening file: inode={}", inode);

        if inode == 2 {
            Ok(ReplyOpen { fh: 2, flags: 0 })
        } else {
            Err(libc::ENOENT.into())
        }
    }

    async fn read(
        &self,
        _req: Request,
        inode: u64,
        _fh: u64,
        offset: u64,
        size: u32,
    ) -> Result<ReplyData> {
        debug!(
            "Reading file: inode={}, offset={}, size={}",
            inode, offset, size
        );

        if inode == 2 {
            let start = offset as usize;
            let end = std::cmp::min(start + size as usize, self.content.len());

            let data = if start < self.content.len() {
                self.content.as_bytes()[start..end].to_vec()
            } else {
                Vec::new()
            };

            Ok(ReplyData { data: data.into() })
        } else {
            Err(libc::ENOENT.into())
        }
    }

    async fn statfs(&self, _req: Request, _inode: u64) -> Result<ReplyStatFs> {
        debug!("Getting filesystem statistics");

        Ok(ReplyStatFs {
            blocks: 1000, // Total blocks
            bfree: 800,   // Free blocks
            bavail: 800,  // Available blocks
            files: 100,   // Total files
            ffree: 50,    // Free files
            bsize: 4096,  // Block size
            namelen: 255, // Maximum filename length
            frsize: 4096, // Fragment size
        })
    }

    async fn access(&self, _req: Request, inode: u64, _mask: u32) -> Result<()> {
        debug!("Checking access permissions: inode={}", inode);

        if inode == 1 || inode == 2 {
            Ok(())
        } else {
            Err(libc::ENOENT.into())
        }
    }

    async fn getxattr(
        &self,
        _req: Request,
        inode: u64,
        name: &OsStr,
        _size: u32,
    ) -> Result<ReplyXAttr> {
        debug!(
            "Getting extended attributes: inode={}, name={:?}",
            inode, name
        );
        Err(libc::ENODATA.into())
    }

    async fn listxattr(&self, _req: Request, inode: u64, _size: u32) -> Result<ReplyXAttr> {
        debug!("Listing extended attributes: inode={}", inode);
        Ok(ReplyXAttr::Data(Vec::new().into()))
    }
}

#[derive(Parser, Debug)]
#[command(author, version, about = "A minimal rfuse3 filesystem example")]
struct Args {
    /// Mount point path
    #[arg(long)]
    mountpoint: String,
}

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        .init();

    let args = Args::parse();
    let fs = MinimalFileSystem::new();

    let mut mount_options = MountOptions::default();
    // Optional: enable force_readdir_plus for better performance
    // mount_options.force_readdir_plus(true);

    let uid = unsafe { libc::getuid() };
    let gid = unsafe { libc::getgid() };
    mount_options.uid(uid).gid(gid);

    let mount_path = std::ffi::OsString::from(&args.mountpoint);

    info!(
        "Starting to mount minimal filesystem to: {}",
        args.mountpoint
    );

    let mut mount_handle = {
        #[cfg(all(target_os = "linux", feature = "unprivileged"))]
        {
            Session::new(mount_options)
                .mount_with_unprivileged(fs, mount_path)
                .await
        }
        #[cfg(target_os = "macos")]
        {
            Session::new(mount_options)
                .mount_with_unprivileged(fs, mount_path)
                .await
        }
        #[cfg(target_os = "freebsd")]
        {
            Session::new(mount_options)
                .mount_with_unprivileged(fs, mount_path)
                .await
        }
        #[cfg(not(any(
            all(target_os = "linux", feature = "unprivileged"),
            target_os = "macos",
            target_os = "freebsd"
        )))]
        {
            Session::new(mount_options).mount(fs, mount_path).await
        }
    }
    .map_err(|e| {
        eprintln!("Mount failed: {}", e);
        e
    })?;

    info!("Filesystem successfully mounted!");
    info!("You can try the following operations:");
    info!("  - ls {}  # List directory contents", args.mountpoint);
    info!("  - cat {}/hello.txt  # Read file", args.mountpoint);
    info!("Press Ctrl+C to unmount the filesystem");
    tokio::select! {
        res = &mut mount_handle => {
            match res {
                Ok(_) => info!("Filesystem exited normally"),
                Err(e) => {
                    warn!("Filesystem runtime error: {}", e);
                    return Err(e.into());
                }
            }
        },
        _ = signal::ctrl_c() => {
            info!("Received exit signal, unmounting filesystem...");
        }
    }

    // Unmount after the select completes to avoid overlapping borrows
    mount_handle.unmount().await.map_err(|e| {
        eprintln!("Unmount failed: {}", e);
        e
    })?;
    info!("Filesystem unmounted");

    Ok(())
}