Skip to main content

rustic_rs/commands/mount/
fusefs.rs

1#[cfg(not(windows))]
2use std::os::unix::prelude::OsStrExt;
3use std::{
4    collections::BTreeMap,
5    ffi::{CString, OsStr},
6    path::Path,
7    sync::RwLock,
8    time::{Duration, SystemTime},
9};
10
11use rustic_core::{
12    repofile::{Node, NodeType},
13    vfs::{FilePolicy, OpenFile, Vfs},
14};
15
16use fuse_mt::{
17    CallbackResult, DirectoryEntry, FileAttr, FileType, FilesystemMT, RequestInfo, ResultData,
18    ResultEmpty, ResultEntry, ResultOpen, ResultReaddir, ResultSlice, ResultXattr, Xattr,
19};
20use itertools::Itertools;
21
22use crate::repository::IndexedRepo;
23
24pub struct FuseFS {
25    repo: IndexedRepo,
26    vfs: Vfs,
27    open_files: RwLock<BTreeMap<u64, OpenFile>>,
28    now: SystemTime,
29    file_policy: FilePolicy,
30}
31
32impl FuseFS {
33    pub(crate) fn new(repo: IndexedRepo, vfs: Vfs, file_policy: FilePolicy) -> Self {
34        let open_files = RwLock::new(BTreeMap::new());
35
36        Self {
37            repo,
38            vfs,
39            open_files,
40            now: SystemTime::now(),
41            file_policy,
42        }
43    }
44
45    fn node_from_path(&self, path: &Path) -> Result<Node, i32> {
46        self.vfs
47            .node_from_path(&self.repo, path)
48            .map_err(|_| libc::ENOENT)
49    }
50
51    fn dir_entries_from_path(&self, path: &Path) -> Result<Vec<Node>, i32> {
52        self.vfs
53            .dir_entries_from_path(&self.repo, path)
54            .map_err(|_| libc::ENOENT)
55    }
56}
57
58fn node_to_filetype(node: &Node) -> FileType {
59    match node.node_type {
60        NodeType::File => FileType::RegularFile,
61        NodeType::Dir => FileType::Directory,
62        NodeType::Symlink { .. } => FileType::Symlink,
63        NodeType::Chardev { .. } => FileType::CharDevice,
64        NodeType::Dev { .. } => FileType::BlockDevice,
65        NodeType::Fifo => FileType::NamedPipe,
66        NodeType::Socket => FileType::Socket,
67    }
68}
69
70fn node_type_to_rdev(tpe: &NodeType) -> u32 {
71    u32::try_from(match tpe {
72        NodeType::Dev { device } | NodeType::Chardev { device } => *device,
73        _ => 0,
74    })
75    .unwrap()
76}
77
78fn node_to_linktarget(node: &Node) -> Option<&OsStr> {
79    if node.is_symlink() {
80        Some(node.node_type.to_link().as_os_str())
81    } else {
82        None
83    }
84}
85
86fn node_to_file_attr(node: &Node, now: SystemTime) -> FileAttr {
87    FileAttr {
88        // Size in bytes
89        size: node.meta.size,
90        // Size in blocks
91        blocks: 0,
92        // Time of last access
93        atime: node.meta.atime.map(SystemTime::from).unwrap_or(now),
94        // Time of last modification
95        mtime: node.meta.mtime.map(SystemTime::from).unwrap_or(now),
96        // Time of last metadata change
97        ctime: node.meta.ctime.map(SystemTime::from).unwrap_or(now),
98        // Time of creation (macOS only)
99        crtime: now,
100        // Kind of file (directory, file, pipe, etc.)
101        kind: node_to_filetype(node),
102        // Permissions
103        perm: node.meta.mode.unwrap_or(0o755) as u16,
104        // Number of hard links
105        nlink: node.meta.links.try_into().unwrap_or(1),
106        // User ID
107        uid: node.meta.uid.unwrap_or(0),
108        // Group ID
109        gid: node.meta.gid.unwrap_or(0),
110        // Device ID (if special file)
111        rdev: node_type_to_rdev(&node.node_type),
112        // Flags (macOS only; see chflags(2))
113        flags: 0,
114    }
115}
116
117impl FilesystemMT for FuseFS {
118    fn getattr(&self, _req: RequestInfo, path: &Path, _fh: Option<u64>) -> ResultEntry {
119        let node = self.node_from_path(path)?;
120        Ok((Duration::from_secs(1), node_to_file_attr(&node, self.now)))
121    }
122
123    #[cfg(not(windows))]
124    fn readlink(&self, _req: RequestInfo, path: &Path) -> ResultData {
125        let target = node_to_linktarget(&self.node_from_path(path)?)
126            .ok_or(libc::ENOSYS)?
127            .as_bytes()
128            .to_vec();
129
130        Ok(target)
131    }
132
133    fn open(&self, _req: RequestInfo, path: &Path, _flags: u32) -> ResultOpen {
134        if matches!(self.file_policy, FilePolicy::Forbidden) {
135            return Err(libc::ENOTSUP);
136        }
137        let node = self.node_from_path(path)?;
138        let open = self.repo.open_file(&node).map_err(|_| libc::ENOSYS)?;
139        let fh = {
140            let mut open_files = self.open_files.write().unwrap();
141            let fh = open_files.last_key_value().map_or(0, |(fh, _)| *fh + 1);
142            _ = open_files.insert(fh, open);
143            fh
144        };
145        Ok((fh, 0))
146    }
147
148    fn release(
149        &self,
150        _req: RequestInfo,
151        _path: &Path,
152        fh: u64,
153        _flags: u32,
154        _lock_owner: u64,
155        _flush: bool,
156    ) -> ResultEmpty {
157        _ = self.open_files.write().unwrap().remove(&fh);
158        Ok(())
159    }
160
161    fn read(
162        &self,
163        _req: RequestInfo,
164        _path: &Path,
165        fh: u64,
166        offset: u64,
167        size: u32,
168        callback: impl FnOnce(ResultSlice<'_>) -> CallbackResult,
169    ) -> CallbackResult {
170        if let Some(open_file) = self.open_files.read().unwrap().get(&fh)
171            && let Ok(data) =
172                self.repo
173                    .read_file_at(open_file, offset.try_into().unwrap(), size as usize)
174        {
175            return callback(Ok(&data));
176        }
177        callback(Err(libc::ENOSYS))
178    }
179
180    fn opendir(&self, _req: RequestInfo, _path: &Path, _flags: u32) -> ResultOpen {
181        Ok((0, 0))
182    }
183
184    fn readdir(&self, _req: RequestInfo, path: &Path, _fh: u64) -> ResultReaddir {
185        let nodes = self.dir_entries_from_path(path)?;
186
187        let result = nodes
188            .into_iter()
189            .map(|node| DirectoryEntry {
190                name: node.name(),
191                kind: node_to_filetype(&node),
192            })
193            .collect();
194        Ok(result)
195    }
196
197    fn releasedir(&self, _req: RequestInfo, _path: &Path, _fh: u64, _flags: u32) -> ResultEmpty {
198        Ok(())
199    }
200
201    fn listxattr(&self, _req: RequestInfo, path: &Path, size: u32) -> ResultXattr {
202        let node = self.node_from_path(path)?;
203        let xattrs = node
204            .meta
205            .extended_attributes
206            .into_iter()
207            // convert into null-terminated [u8]
208            .map(|a| CString::new(a.name).unwrap().into_bytes_with_nul())
209            .concat();
210
211        if size == 0 {
212            Ok(Xattr::Size(u32::try_from(xattrs.len()).unwrap()))
213        } else {
214            Ok(Xattr::Data(xattrs))
215        }
216    }
217
218    fn getxattr(&self, _req: RequestInfo, path: &Path, name: &OsStr, size: u32) -> ResultXattr {
219        let node = self.node_from_path(path)?;
220        match node
221            .meta
222            .extended_attributes
223            .into_iter()
224            .find(|a| name == OsStr::new(&a.name))
225        {
226            None => Err(libc::ENOSYS),
227            Some(attr) => {
228                let value = attr.value.unwrap_or_default();
229                if size == 0 {
230                    Ok(Xattr::Size(u32::try_from(value.len()).unwrap()))
231                } else {
232                    Ok(Xattr::Data(value))
233                }
234            }
235        }
236    }
237}