Skip to main content

fuser/
lib.rs

1//! FUSE userspace library implementation
2//!
3//! This is an improved rewrite of the FUSE userspace library (lowlevel interface) to fully take
4//! advantage of Rust's architecture. The only thing we rely on in the real libfuse are mount
5//! and unmount calls which are needed to establish a fd to talk to the kernel driver.
6
7#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
8#![allow(dead_code, unexpected_cfgs, unused_imports)]
9
10use libc::{c_int, ENOSYS, EPERM};
11use log::{debug, warn};
12use mnt::mount_options::parse_options_from_args;
13#[cfg(feature = "serializable")]
14use serde::{Deserialize, Serialize};
15use std::ffi::OsStr;
16use std::io;
17use std::path::Path;
18#[cfg(feature = "abi-7-23")]
19use std::time::Duration;
20use std::time::SystemTime;
21use std::{convert::AsRef, io::ErrorKind};
22
23use crate::ll::fuse_abi::consts::*;
24pub use crate::ll::fuse_abi::FUSE_ROOT_ID;
25pub use crate::ll::{fuse_abi::consts, TimeOrNow};
26use crate::mnt::mount_options::check_option_conflicts;
27use crate::session::MAX_WRITE_SIZE;
28#[cfg(feature = "abi-7-16")]
29pub use ll::fuse_abi::fuse_forget_one;
30pub use mnt::mount_options::MountOption;
31#[cfg(feature = "abi-7-11")]
32pub use notify::Notifier;
33#[cfg(feature = "abi-7-11")]
34pub use reply::ReplyPoll;
35#[cfg(target_os = "macos")]
36pub use reply::ReplyXTimes;
37pub use reply::ReplyXattr;
38pub use reply::{Reply, ReplyAttr, ReplyData, ReplyEmpty, ReplyEntry, ReplyOpen};
39pub use reply::{
40    ReplyBmap, ReplyCreate, ReplyDirectory, ReplyDirectoryPlus, ReplyIoctl, ReplyLock, ReplyLseek,
41    ReplyStatfs, ReplyWrite,
42};
43pub use request::Request;
44pub use session::{BackgroundSession, Session, SessionUnmounter};
45#[cfg(feature = "abi-7-28")]
46use std::cmp::max;
47#[cfg(feature = "abi-7-13")]
48use std::cmp::min;
49
50mod channel;
51mod ll;
52mod mnt;
53#[cfg(feature = "abi-7-11")]
54mod notify;
55mod reply;
56mod request;
57mod session;
58
59/// We generally support async reads
60#[cfg(all(not(target_os = "macos"), not(feature = "abi-7-10")))]
61const INIT_FLAGS: u32 = FUSE_ASYNC_READ;
62#[cfg(all(not(target_os = "macos"), feature = "abi-7-10"))]
63const INIT_FLAGS: u32 = FUSE_ASYNC_READ | FUSE_BIG_WRITES;
64// TODO: Add FUSE_EXPORT_SUPPORT
65
66/// On macOS, we additionally support case insensitiveness, volume renames and xtimes
67/// TODO: we should eventually let the filesystem implementation decide which flags to set
68#[cfg(target_os = "macos")]
69const INIT_FLAGS: u32 = FUSE_ASYNC_READ | FUSE_CASE_INSENSITIVE | FUSE_VOL_RENAME | FUSE_XTIMES;
70// TODO: Add FUSE_EXPORT_SUPPORT and FUSE_BIG_WRITES (requires ABI 7.10)
71
72const fn default_init_flags(#[allow(unused_variables)] capabilities: u32) -> u32 {
73    #[cfg(not(feature = "abi-7-28"))]
74    {
75        INIT_FLAGS
76    }
77
78    #[cfg(feature = "abi-7-28")]
79    {
80        let mut flags = INIT_FLAGS;
81        if capabilities & FUSE_MAX_PAGES != 0 {
82            flags |= FUSE_MAX_PAGES;
83        }
84        flags
85    }
86}
87
88/// File types
89#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
90#[cfg_attr(feature = "serializable", derive(Serialize, Deserialize))]
91pub enum FileType {
92    /// Named pipe (S_IFIFO)
93    NamedPipe,
94    /// Character device (S_IFCHR)
95    CharDevice,
96    /// Block device (S_IFBLK)
97    BlockDevice,
98    /// Directory (S_IFDIR)
99    Directory,
100    /// Regular file (S_IFREG)
101    RegularFile,
102    /// Symbolic link (S_IFLNK)
103    Symlink,
104    /// Unix domain socket (S_IFSOCK)
105    Socket,
106}
107
108/// File attributes
109#[derive(Clone, Copy, Debug, Eq, PartialEq)]
110#[cfg_attr(feature = "serializable", derive(Serialize, Deserialize))]
111pub struct FileAttr {
112    /// Inode number
113    pub ino: u64,
114    /// Size in bytes
115    pub size: u64,
116    /// Size in blocks
117    pub blocks: u64,
118    /// Time of last access
119    pub atime: SystemTime,
120    /// Time of last modification
121    pub mtime: SystemTime,
122    /// Time of last change
123    pub ctime: SystemTime,
124    /// Time of creation (macOS only)
125    pub crtime: SystemTime,
126    /// Kind of file (directory, file, pipe, etc)
127    pub kind: FileType,
128    /// Permissions
129    pub perm: u16,
130    /// Number of hard links
131    pub nlink: u32,
132    /// User id
133    pub uid: u32,
134    /// Group id
135    pub gid: u32,
136    /// Rdev
137    pub rdev: u32,
138    /// Block size
139    pub blksize: u32,
140    /// Flags (macOS only, see chflags(2))
141    pub flags: u32,
142}
143
144/// Configuration of the fuse kernel module connection
145#[derive(Debug)]
146pub struct KernelConfig {
147    capabilities: u32,
148    requested: u32,
149    max_readahead: u32,
150    max_max_readahead: u32,
151    #[cfg(feature = "abi-7-13")]
152    max_background: u16,
153    #[cfg(feature = "abi-7-13")]
154    congestion_threshold: Option<u16>,
155    max_write: u32,
156    #[cfg(feature = "abi-7-23")]
157    time_gran: Duration,
158}
159
160impl KernelConfig {
161    fn new(capabilities: u32, max_readahead: u32) -> Self {
162        Self {
163            capabilities,
164            requested: default_init_flags(capabilities),
165            max_readahead,
166            max_max_readahead: max_readahead,
167            #[cfg(feature = "abi-7-13")]
168            max_background: 16,
169            #[cfg(feature = "abi-7-13")]
170            congestion_threshold: None,
171            // use a max write size that fits into the session's buffer
172            max_write: MAX_WRITE_SIZE as u32,
173            // 1ns means nano-second granularity.
174            #[cfg(feature = "abi-7-23")]
175            time_gran: Duration::new(0, 1),
176        }
177    }
178
179    /// Set the timestamp granularity
180    ///
181    /// Must be a power of 10 nanoseconds. i.e. 1s, 0.1s, 0.01s, 1ms, 0.1ms...etc
182    ///
183    /// On success returns the previous value. On error returns the nearest value which will succeed
184    #[cfg(feature = "abi-7-23")]
185    pub fn set_time_granularity(&mut self, value: Duration) -> Result<Duration, Duration> {
186        if value.as_nanos() == 0 {
187            return Err(Duration::new(0, 1));
188        }
189        if value.as_secs() > 1 || (value.as_secs() == 1 && value.subsec_nanos() > 0) {
190            return Err(Duration::new(1, 0));
191        }
192        let mut power_of_10 = 1;
193        while power_of_10 < value.as_nanos() {
194            if value.as_nanos() < power_of_10 * 10 {
195                // value must not be a power of ten, since power_of_10 < value < power_of_10 * 10
196                return Err(Duration::new(0, power_of_10 as u32));
197            }
198            power_of_10 *= 10;
199        }
200        let previous = self.time_gran;
201        self.time_gran = value;
202        Ok(previous)
203    }
204
205    /// Set the maximum write size for a single request
206    ///
207    /// On success returns the previous value. On error returns the nearest value which will succeed
208    pub fn set_max_write(&mut self, value: u32) -> Result<u32, u32> {
209        if value == 0 {
210            return Err(1);
211        }
212        if value > MAX_WRITE_SIZE as u32 {
213            return Err(MAX_WRITE_SIZE as u32);
214        }
215        let previous = self.max_write;
216        self.max_write = value;
217        Ok(previous)
218    }
219
220    /// Set the maximum readahead size
221    ///
222    /// On success returns the previous value. On error returns the nearest value which will succeed
223    pub fn set_max_readahead(&mut self, value: u32) -> Result<u32, u32> {
224        if value == 0 {
225            return Err(1);
226        }
227        if value > self.max_max_readahead {
228            return Err(self.max_max_readahead);
229        }
230        let previous = self.max_readahead;
231        self.max_readahead = value;
232        Ok(previous)
233    }
234
235    /// Add a set of capabilities.
236    ///
237    /// On success returns Ok, else return bits of capabilities not supported when capabilities you provided are not all supported by kernel.
238    pub fn add_capabilities(&mut self, capabilities_to_add: u32) -> Result<(), u32> {
239        if capabilities_to_add & self.capabilities != capabilities_to_add {
240            return Err(capabilities_to_add - (capabilities_to_add & self.capabilities));
241        }
242        self.requested |= capabilities_to_add;
243        Ok(())
244    }
245
246    /// Set the maximum number of pending background requests. Such as readahead requests.
247    ///
248    /// On success returns the previous value. On error returns the nearest value which will succeed
249    #[cfg(feature = "abi-7-13")]
250    pub fn set_max_background(&mut self, value: u16) -> Result<u16, u16> {
251        if value == 0 {
252            return Err(1);
253        }
254        let previous = self.max_background;
255        self.max_background = value;
256        Ok(previous)
257    }
258
259    /// Set the threshold of background requests at which the kernel will consider the filesystem
260    /// request queue congested. (it may then switch to sleeping instead of spin-waiting, for example)
261    ///
262    /// On success returns the previous value. On error returns the nearest value which will succeed
263    #[cfg(feature = "abi-7-13")]
264    pub fn set_congestion_threshold(&mut self, value: u16) -> Result<u16, u16> {
265        if value == 0 {
266            return Err(1);
267        }
268        let previous = self.congestion_threshold();
269        self.congestion_threshold = Some(value);
270        Ok(previous)
271    }
272
273    #[cfg(feature = "abi-7-13")]
274    fn congestion_threshold(&self) -> u16 {
275        match self.congestion_threshold {
276            // Default to a threshold of 3/4 of the max background threads
277            None => (self.max_background as u32 * 3 / 4) as u16,
278            Some(value) => min(value, self.max_background),
279        }
280    }
281
282    #[cfg(feature = "abi-7-28")]
283    fn max_pages(&self) -> u16 {
284        ((max(self.max_write, self.max_readahead) - 1) / page_size::get() as u32) as u16 + 1
285    }
286}
287
288/// Filesystem trait.
289///
290/// This trait must be implemented to provide a userspace filesystem via FUSE.
291/// These methods correspond to fuse_lowlevel_ops in libfuse. Reasonable default
292/// implementations are provided here to get a mountable filesystem that does
293/// nothing.
294#[allow(clippy::too_many_arguments)]
295pub trait Filesystem {
296    /// Initialize filesystem.
297    /// Called before any other filesystem method.
298    /// The kernel module connection can be configured using the KernelConfig object
299    fn init(&mut self, _req: &Request<'_>, _config: &mut KernelConfig) -> Result<(), c_int> {
300        Ok(())
301    }
302
303    /// Clean up filesystem.
304    /// Called on filesystem exit.
305    fn destroy(&mut self) {}
306
307    /// Look up a directory entry by name and get its attributes.
308    fn lookup(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, reply: ReplyEntry) {
309        warn!(
310            "[Not Implemented] lookup(parent: {:#x?}, name {:?})",
311            parent, name
312        );
313        reply.error(ENOSYS);
314    }
315
316    /// Forget about an inode.
317    /// The nlookup parameter indicates the number of lookups previously performed on
318    /// this inode. If the filesystem implements inode lifetimes, it is recommended that
319    /// inodes acquire a single reference on each lookup, and lose nlookup references on
320    /// each forget. The filesystem may ignore forget calls, if the inodes don't need to
321    /// have a limited lifetime. On unmount it is not guaranteed, that all referenced
322    /// inodes will receive a forget message.
323    fn forget(&mut self, _req: &Request<'_>, _ino: u64, _nlookup: u64) {}
324
325    /// Like forget, but take multiple forget requests at once for performance. The default
326    /// implementation will fallback to forget.
327    #[cfg(feature = "abi-7-16")]
328    fn batch_forget(&mut self, req: &Request<'_>, nodes: &[fuse_forget_one]) {
329        for node in nodes {
330            self.forget(req, node.nodeid, node.nlookup);
331        }
332    }
333
334    /// Get file attributes.
335    fn getattr(&mut self, _req: &Request<'_>, ino: u64, reply: ReplyAttr) {
336        warn!("[Not Implemented] getattr(ino: {:#x?})", ino);
337        reply.error(ENOSYS);
338    }
339
340    /// Set file attributes.
341    fn setattr(
342        &mut self,
343        _req: &Request<'_>,
344        ino: u64,
345        mode: Option<u32>,
346        uid: Option<u32>,
347        gid: Option<u32>,
348        size: Option<u64>,
349        _atime: Option<TimeOrNow>,
350        _mtime: Option<TimeOrNow>,
351        _ctime: Option<SystemTime>,
352        fh: Option<u64>,
353        _crtime: Option<SystemTime>,
354        _chgtime: Option<SystemTime>,
355        _bkuptime: Option<SystemTime>,
356        flags: Option<u32>,
357        reply: ReplyAttr,
358    ) {
359        debug!(
360            "[Not Implemented] setattr(ino: {:#x?}, mode: {:?}, uid: {:?}, \
361            gid: {:?}, size: {:?}, fh: {:?}, flags: {:?})",
362            ino, mode, uid, gid, size, fh, flags
363        );
364        reply.error(ENOSYS);
365    }
366
367    /// Read symbolic link.
368    fn readlink(&mut self, _req: &Request<'_>, ino: u64, reply: ReplyData) {
369        debug!("[Not Implemented] readlink(ino: {:#x?})", ino);
370        reply.error(ENOSYS);
371    }
372
373    /// Create file node.
374    /// Create a regular file, character device, block device, fifo or socket node.
375    fn mknod(
376        &mut self,
377        _req: &Request<'_>,
378        parent: u64,
379        name: &OsStr,
380        mode: u32,
381        umask: u32,
382        rdev: u32,
383        reply: ReplyEntry,
384    ) {
385        debug!(
386            "[Not Implemented] mknod(parent: {:#x?}, name: {:?}, mode: {}, \
387            umask: {:#x?}, rdev: {})",
388            parent, name, mode, umask, rdev
389        );
390        reply.error(ENOSYS);
391    }
392
393    /// Create a directory.
394    fn mkdir(
395        &mut self,
396        _req: &Request<'_>,
397        parent: u64,
398        name: &OsStr,
399        mode: u32,
400        umask: u32,
401        reply: ReplyEntry,
402    ) {
403        debug!(
404            "[Not Implemented] mkdir(parent: {:#x?}, name: {:?}, mode: {}, umask: {:#x?})",
405            parent, name, mode, umask
406        );
407        reply.error(ENOSYS);
408    }
409
410    /// Remove a file.
411    fn unlink(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, reply: ReplyEmpty) {
412        debug!(
413            "[Not Implemented] unlink(parent: {:#x?}, name: {:?})",
414            parent, name,
415        );
416        reply.error(ENOSYS);
417    }
418
419    /// Remove a directory.
420    fn rmdir(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, reply: ReplyEmpty) {
421        debug!(
422            "[Not Implemented] rmdir(parent: {:#x?}, name: {:?})",
423            parent, name,
424        );
425        reply.error(ENOSYS);
426    }
427
428    /// Create a symbolic link.
429    fn symlink(
430        &mut self,
431        _req: &Request<'_>,
432        parent: u64,
433        link_name: &OsStr,
434        target: &Path,
435        reply: ReplyEntry,
436    ) {
437        debug!(
438            "[Not Implemented] symlink(parent: {:#x?}, link_name: {:?}, target: {:?})",
439            parent, link_name, target,
440        );
441        reply.error(EPERM);
442    }
443
444    /// Rename a file.
445    fn rename(
446        &mut self,
447        _req: &Request<'_>,
448        parent: u64,
449        name: &OsStr,
450        newparent: u64,
451        newname: &OsStr,
452        flags: u32,
453        reply: ReplyEmpty,
454    ) {
455        debug!(
456            "[Not Implemented] rename(parent: {:#x?}, name: {:?}, newparent: {:#x?}, \
457            newname: {:?}, flags: {})",
458            parent, name, newparent, newname, flags,
459        );
460        reply.error(ENOSYS);
461    }
462
463    /// Create a hard link.
464    fn link(
465        &mut self,
466        _req: &Request<'_>,
467        ino: u64,
468        newparent: u64,
469        newname: &OsStr,
470        reply: ReplyEntry,
471    ) {
472        debug!(
473            "[Not Implemented] link(ino: {:#x?}, newparent: {:#x?}, newname: {:?})",
474            ino, newparent, newname
475        );
476        reply.error(EPERM);
477    }
478
479    /// Open a file.
480    /// Open flags (with the exception of O_CREAT, O_EXCL, O_NOCTTY and O_TRUNC) are
481    /// available in flags. Filesystem may store an arbitrary file handle (pointer, index,
482    /// etc) in fh, and use this in other all other file operations (read, write, flush,
483    /// release, fsync). Filesystem may also implement stateless file I/O and not store
484    /// anything in fh. There are also some flags (direct_io, keep_cache) which the
485    /// filesystem may set, to change the way the file is opened. See fuse_file_info
486    /// structure in <fuse_common.h> for more details.
487    fn open(&mut self, _req: &Request<'_>, _ino: u64, _flags: i32, reply: ReplyOpen) {
488        reply.opened(0, 0);
489    }
490
491    /// Read data.
492    /// Read should send exactly the number of bytes requested except on EOF or error,
493    /// otherwise the rest of the data will be substituted with zeroes. An exception to
494    /// this is when the file has been opened in 'direct_io' mode, in which case the
495    /// return value of the read system call will reflect the return value of this
496    /// operation. fh will contain the value set by the open method, or will be undefined
497    /// if the open method didn't set any value.
498    ///
499    /// flags: these are the file flags, such as O_SYNC. Only supported with ABI >= 7.9
500    /// lock_owner: only supported with ABI >= 7.9
501    fn read(
502        &mut self,
503        _req: &Request<'_>,
504        ino: u64,
505        fh: u64,
506        offset: i64,
507        size: u32,
508        flags: i32,
509        lock_owner: Option<u64>,
510        reply: ReplyData,
511    ) {
512        warn!(
513            "[Not Implemented] read(ino: {:#x?}, fh: {}, offset: {}, size: {}, \
514            flags: {:#x?}, lock_owner: {:?})",
515            ino, fh, offset, size, flags, lock_owner
516        );
517        reply.error(ENOSYS);
518    }
519
520    /// Write data.
521    /// Write should return exactly the number of bytes requested except on error. An
522    /// exception to this is when the file has been opened in 'direct_io' mode, in
523    /// which case the return value of the write system call will reflect the return
524    /// value of this operation. fh will contain the value set by the open method, or
525    /// will be undefined if the open method didn't set any value.
526    ///
527    /// write_flags: will contain FUSE_WRITE_CACHE, if this write is from the page cache. If set,
528    /// the pid, uid, gid, and fh may not match the value that would have been sent if write cachin
529    /// is disabled
530    /// flags: these are the file flags, such as O_SYNC. Only supported with ABI >= 7.9
531    /// lock_owner: only supported with ABI >= 7.9
532    fn write(
533        &mut self,
534        _req: &Request<'_>,
535        ino: u64,
536        fh: u64,
537        offset: i64,
538        data: &[u8],
539        write_flags: u32,
540        flags: i32,
541        lock_owner: Option<u64>,
542        reply: ReplyWrite,
543    ) {
544        debug!(
545            "[Not Implemented] write(ino: {:#x?}, fh: {}, offset: {}, data.len(): {}, \
546            write_flags: {:#x?}, flags: {:#x?}, lock_owner: {:?})",
547            ino,
548            fh,
549            offset,
550            data.len(),
551            write_flags,
552            flags,
553            lock_owner
554        );
555        reply.error(ENOSYS);
556    }
557
558    /// Flush method.
559    /// This is called on each close() of the opened file. Since file descriptors can
560    /// be duplicated (dup, dup2, fork), for one open call there may be many flush
561    /// calls. Filesystems shouldn't assume that flush will always be called after some
562    /// writes, or that if will be called at all. fh will contain the value set by the
563    /// open method, or will be undefined if the open method didn't set any value.
564    /// NOTE: the name of the method is misleading, since (unlike fsync) the filesystem
565    /// is not forced to flush pending writes. One reason to flush data, is if the
566    /// filesystem wants to return write errors. If the filesystem supports file locking
567    /// operations (setlk, getlk) it should remove all locks belonging to 'lock_owner'.
568    fn flush(&mut self, _req: &Request<'_>, ino: u64, fh: u64, lock_owner: u64, reply: ReplyEmpty) {
569        debug!(
570            "[Not Implemented] flush(ino: {:#x?}, fh: {}, lock_owner: {:?})",
571            ino, fh, lock_owner
572        );
573        reply.error(ENOSYS);
574    }
575
576    /// Release an open file.
577    /// Release is called when there are no more references to an open file: all file
578    /// descriptors are closed and all memory mappings are unmapped. For every open
579    /// call there will be exactly one release call. The filesystem may reply with an
580    /// error, but error values are not returned to close() or munmap() which triggered
581    /// the release. fh will contain the value set by the open method, or will be undefined
582    /// if the open method didn't set any value. flags will contain the same flags as for
583    /// open.
584    fn release(
585        &mut self,
586        _req: &Request<'_>,
587        _ino: u64,
588        _fh: u64,
589        _flags: i32,
590        _lock_owner: Option<u64>,
591        _flush: bool,
592        reply: ReplyEmpty,
593    ) {
594        reply.ok();
595    }
596
597    /// Synchronize file contents.
598    /// If the datasync parameter is non-zero, then only the user data should be flushed,
599    /// not the meta data.
600    fn fsync(&mut self, _req: &Request<'_>, ino: u64, fh: u64, datasync: bool, reply: ReplyEmpty) {
601        debug!(
602            "[Not Implemented] fsync(ino: {:#x?}, fh: {}, datasync: {})",
603            ino, fh, datasync
604        );
605        reply.error(ENOSYS);
606    }
607
608    /// Open a directory.
609    /// Filesystem may store an arbitrary file handle (pointer, index, etc) in fh, and
610    /// use this in other all other directory stream operations (readdir, releasedir,
611    /// fsyncdir). Filesystem may also implement stateless directory I/O and not store
612    /// anything in fh, though that makes it impossible to implement standard conforming
613    /// directory stream operations in case the contents of the directory can change
614    /// between opendir and releasedir.
615    fn opendir(&mut self, _req: &Request<'_>, _ino: u64, _flags: i32, reply: ReplyOpen) {
616        reply.opened(0, 0);
617    }
618
619    /// Read directory.
620    /// Send a buffer filled using buffer.fill(), with size not exceeding the
621    /// requested size. Send an empty buffer on end of stream. fh will contain the
622    /// value set by the opendir method, or will be undefined if the opendir method
623    /// didn't set any value.
624    fn readdir(
625        &mut self,
626        _req: &Request<'_>,
627        ino: u64,
628        fh: u64,
629        offset: i64,
630        reply: ReplyDirectory,
631    ) {
632        warn!(
633            "[Not Implemented] readdir(ino: {:#x?}, fh: {}, offset: {})",
634            ino, fh, offset
635        );
636        reply.error(ENOSYS);
637    }
638
639    /// Read directory.
640    /// Send a buffer filled using buffer.fill(), with size not exceeding the
641    /// requested size. Send an empty buffer on end of stream. fh will contain the
642    /// value set by the opendir method, or will be undefined if the opendir method
643    /// didn't set any value.
644    fn readdirplus(
645        &mut self,
646        _req: &Request<'_>,
647        ino: u64,
648        fh: u64,
649        offset: i64,
650        reply: ReplyDirectoryPlus,
651    ) {
652        debug!(
653            "[Not Implemented] readdirplus(ino: {:#x?}, fh: {}, offset: {})",
654            ino, fh, offset
655        );
656        reply.error(ENOSYS);
657    }
658
659    /// Release an open directory.
660    /// For every opendir call there will be exactly one releasedir call. fh will
661    /// contain the value set by the opendir method, or will be undefined if the
662    /// opendir method didn't set any value.
663    fn releasedir(
664        &mut self,
665        _req: &Request<'_>,
666        _ino: u64,
667        _fh: u64,
668        _flags: i32,
669        reply: ReplyEmpty,
670    ) {
671        reply.ok();
672    }
673
674    /// Synchronize directory contents.
675    /// If the datasync parameter is set, then only the directory contents should
676    /// be flushed, not the meta data. fh will contain the value set by the opendir
677    /// method, or will be undefined if the opendir method didn't set any value.
678    fn fsyncdir(
679        &mut self,
680        _req: &Request<'_>,
681        ino: u64,
682        fh: u64,
683        datasync: bool,
684        reply: ReplyEmpty,
685    ) {
686        debug!(
687            "[Not Implemented] fsyncdir(ino: {:#x?}, fh: {}, datasync: {})",
688            ino, fh, datasync
689        );
690        reply.error(ENOSYS);
691    }
692
693    /// Get file system statistics.
694    fn statfs(&mut self, _req: &Request<'_>, _ino: u64, reply: ReplyStatfs) {
695        reply.statfs(0, 0, 0, 0, 0, 512, 255, 0);
696    }
697
698    /// Set an extended attribute.
699    fn setxattr(
700        &mut self,
701        _req: &Request<'_>,
702        ino: u64,
703        name: &OsStr,
704        _value: &[u8],
705        flags: i32,
706        position: u32,
707        reply: ReplyEmpty,
708    ) {
709        debug!(
710            "[Not Implemented] setxattr(ino: {:#x?}, name: {:?}, flags: {:#x?}, position: {})",
711            ino, name, flags, position
712        );
713        reply.error(ENOSYS);
714    }
715
716    /// Get an extended attribute.
717    /// If `size` is 0, the size of the value should be sent with `reply.size()`.
718    /// If `size` is not 0, and the value fits, send it with `reply.data()`, or
719    /// `reply.error(ERANGE)` if it doesn't.
720    fn getxattr(
721        &mut self,
722        _req: &Request<'_>,
723        ino: u64,
724        name: &OsStr,
725        size: u32,
726        reply: ReplyXattr,
727    ) {
728        debug!(
729            "[Not Implemented] getxattr(ino: {:#x?}, name: {:?}, size: {})",
730            ino, name, size
731        );
732        reply.error(ENOSYS);
733    }
734
735    /// List extended attribute names.
736    /// If `size` is 0, the size of the value should be sent with `reply.size()`.
737    /// If `size` is not 0, and the value fits, send it with `reply.data()`, or
738    /// `reply.error(ERANGE)` if it doesn't.
739    fn listxattr(&mut self, _req: &Request<'_>, ino: u64, size: u32, reply: ReplyXattr) {
740        debug!(
741            "[Not Implemented] listxattr(ino: {:#x?}, size: {})",
742            ino, size
743        );
744        reply.error(ENOSYS);
745    }
746
747    /// Remove an extended attribute.
748    fn removexattr(&mut self, _req: &Request<'_>, ino: u64, name: &OsStr, reply: ReplyEmpty) {
749        debug!(
750            "[Not Implemented] removexattr(ino: {:#x?}, name: {:?})",
751            ino, name
752        );
753        reply.error(ENOSYS);
754    }
755
756    /// Check file access permissions.
757    /// This will be called for the access() system call. If the 'default_permissions'
758    /// mount option is given, this method is not called. This method is not called
759    /// under Linux kernel versions 2.4.x
760    fn access(&mut self, _req: &Request<'_>, ino: u64, mask: i32, reply: ReplyEmpty) {
761        debug!("[Not Implemented] access(ino: {:#x?}, mask: {})", ino, mask);
762        reply.error(ENOSYS);
763    }
764
765    /// Create and open a file.
766    /// If the file does not exist, first create it with the specified mode, and then
767    /// open it. Open flags (with the exception of O_NOCTTY) are available in flags.
768    /// Filesystem may store an arbitrary file handle (pointer, index, etc) in fh,
769    /// and use this in other all other file operations (read, write, flush, release,
770    /// fsync). There are also some flags (direct_io, keep_cache) which the
771    /// filesystem may set, to change the way the file is opened. See fuse_file_info
772    /// structure in <fuse_common.h> for more details. If this method is not
773    /// implemented or under Linux kernel versions earlier than 2.6.15, the mknod()
774    /// and open() methods will be called instead.
775    fn create(
776        &mut self,
777        _req: &Request<'_>,
778        parent: u64,
779        name: &OsStr,
780        mode: u32,
781        umask: u32,
782        flags: i32,
783        reply: ReplyCreate,
784    ) {
785        debug!(
786            "[Not Implemented] create(parent: {:#x?}, name: {:?}, mode: {}, umask: {:#x?}, \
787            flags: {:#x?})",
788            parent, name, mode, umask, flags
789        );
790        reply.error(ENOSYS);
791    }
792
793    /// Test for a POSIX file lock.
794    fn getlk(
795        &mut self,
796        _req: &Request<'_>,
797        ino: u64,
798        fh: u64,
799        lock_owner: u64,
800        start: u64,
801        end: u64,
802        typ: i32,
803        pid: u32,
804        reply: ReplyLock,
805    ) {
806        debug!(
807            "[Not Implemented] getlk(ino: {:#x?}, fh: {}, lock_owner: {}, start: {}, \
808            end: {}, typ: {}, pid: {})",
809            ino, fh, lock_owner, start, end, typ, pid
810        );
811        reply.error(ENOSYS);
812    }
813
814    /// Acquire, modify or release a POSIX file lock.
815    /// For POSIX threads (NPTL) there's a 1-1 relation between pid and owner, but
816    /// otherwise this is not always the case.  For checking lock ownership,
817    /// 'fi->owner' must be used. The l_pid field in 'struct flock' should only be
818    /// used to fill in this field in getlk(). Note: if the locking methods are not
819    /// implemented, the kernel will still allow file locking to work locally.
820    /// Hence these are only interesting for network filesystems and similar.
821    fn setlk(
822        &mut self,
823        _req: &Request<'_>,
824        ino: u64,
825        fh: u64,
826        lock_owner: u64,
827        start: u64,
828        end: u64,
829        typ: i32,
830        pid: u32,
831        sleep: bool,
832        reply: ReplyEmpty,
833    ) {
834        debug!(
835            "[Not Implemented] setlk(ino: {:#x?}, fh: {}, lock_owner: {}, start: {}, \
836            end: {}, typ: {}, pid: {}, sleep: {})",
837            ino, fh, lock_owner, start, end, typ, pid, sleep
838        );
839        reply.error(ENOSYS);
840    }
841
842    /// Map block index within file to block index within device.
843    /// Note: This makes sense only for block device backed filesystems mounted
844    /// with the 'blkdev' option
845    fn bmap(&mut self, _req: &Request<'_>, ino: u64, blocksize: u32, idx: u64, reply: ReplyBmap) {
846        debug!(
847            "[Not Implemented] bmap(ino: {:#x?}, blocksize: {}, idx: {})",
848            ino, blocksize, idx,
849        );
850        reply.error(ENOSYS);
851    }
852
853    /// control device
854    fn ioctl(
855        &mut self,
856        _req: &Request<'_>,
857        ino: u64,
858        fh: u64,
859        flags: u32,
860        cmd: u32,
861        in_data: &[u8],
862        out_size: u32,
863        reply: ReplyIoctl,
864    ) {
865        debug!(
866            "[Not Implemented] ioctl(ino: {:#x?}, fh: {}, flags: {}, cmd: {}, \
867            in_data.len(): {}, out_size: {})",
868            ino,
869            fh,
870            flags,
871            cmd,
872            in_data.len(),
873            out_size,
874        );
875        reply.error(ENOSYS);
876    }
877
878    /// Poll for events
879    #[cfg(feature = "abi-7-11")]
880    fn poll(
881        &mut self,
882        _req: &Request<'_>,
883        ino: u64,
884        fh: u64,
885        kh: u64,
886        events: u32,
887        flags: u32,
888        reply: ReplyPoll,
889    ) {
890        debug!(
891            "[Not Implemented] poll(ino: {:#x?}, fh: {}, kh: {}, events: {}, flags: {})",
892            ino, fh, kh, events, flags
893        );
894        reply.error(ENOSYS);
895    }
896
897    /// Preallocate or deallocate space to a file
898    fn fallocate(
899        &mut self,
900        _req: &Request<'_>,
901        ino: u64,
902        fh: u64,
903        offset: i64,
904        length: i64,
905        mode: i32,
906        reply: ReplyEmpty,
907    ) {
908        debug!(
909            "[Not Implemented] fallocate(ino: {:#x?}, fh: {}, offset: {}, \
910            length: {}, mode: {})",
911            ino, fh, offset, length, mode
912        );
913        reply.error(ENOSYS);
914    }
915
916    /// Reposition read/write file offset
917    fn lseek(
918        &mut self,
919        _req: &Request<'_>,
920        ino: u64,
921        fh: u64,
922        offset: i64,
923        whence: i32,
924        reply: ReplyLseek,
925    ) {
926        debug!(
927            "[Not Implemented] lseek(ino: {:#x?}, fh: {}, offset: {}, whence: {})",
928            ino, fh, offset, whence
929        );
930        reply.error(ENOSYS);
931    }
932
933    /// Copy the specified range from the source inode to the destination inode
934    fn copy_file_range(
935        &mut self,
936        _req: &Request<'_>,
937        ino_in: u64,
938        fh_in: u64,
939        offset_in: i64,
940        ino_out: u64,
941        fh_out: u64,
942        offset_out: i64,
943        len: u64,
944        flags: u32,
945        reply: ReplyWrite,
946    ) {
947        debug!(
948            "[Not Implemented] copy_file_range(ino_in: {:#x?}, fh_in: {}, \
949            offset_in: {}, ino_out: {:#x?}, fh_out: {}, offset_out: {}, \
950            len: {}, flags: {})",
951            ino_in, fh_in, offset_in, ino_out, fh_out, offset_out, len, flags
952        );
953        reply.error(ENOSYS);
954    }
955
956    /// macOS only: Rename the volume. Set fuse_init_out.flags during init to
957    /// FUSE_VOL_RENAME to enable
958    #[cfg(target_os = "macos")]
959    fn setvolname(&mut self, _req: &Request<'_>, name: &OsStr, reply: ReplyEmpty) {
960        debug!("[Not Implemented] setvolname(name: {:?})", name);
961        reply.error(ENOSYS);
962    }
963
964    /// macOS only (undocumented)
965    #[cfg(target_os = "macos")]
966    fn exchange(
967        &mut self,
968        _req: &Request<'_>,
969        parent: u64,
970        name: &OsStr,
971        newparent: u64,
972        newname: &OsStr,
973        options: u64,
974        reply: ReplyEmpty,
975    ) {
976        debug!(
977            "[Not Implemented] exchange(parent: {:#x?}, name: {:?}, newparent: {:#x?}, \
978            newname: {:?}, options: {})",
979            parent, name, newparent, newname, options
980        );
981        reply.error(ENOSYS);
982    }
983
984    /// macOS only: Query extended times (bkuptime and crtime). Set fuse_init_out.flags
985    /// during init to FUSE_XTIMES to enable
986    #[cfg(target_os = "macos")]
987    fn getxtimes(&mut self, _req: &Request<'_>, ino: u64, reply: ReplyXTimes) {
988        debug!("[Not Implemented] getxtimes(ino: {:#x?})", ino);
989        reply.error(ENOSYS);
990    }
991}
992
993/// Mount the given filesystem to the given mountpoint. This function will
994/// not return until the filesystem is unmounted.
995///
996/// Note that you need to lead each option with a separate `"-o"` string. See
997/// `examples/hello.rs`.
998#[deprecated(note = "use mount2() instead")]
999pub fn mount<FS: Filesystem, P: AsRef<Path>>(
1000    filesystem: FS,
1001    mountpoint: P,
1002    options: &[&OsStr],
1003) -> io::Result<()> {
1004    let options = parse_options_from_args(options)?;
1005    mount2(filesystem, mountpoint, options.as_ref())
1006}
1007
1008/// Mount the given filesystem to the given mountpoint. This function will
1009/// not return until the filesystem is unmounted.
1010///
1011/// NOTE: This will eventually replace mount(), once the API is stable
1012pub fn mount2<FS: Filesystem, P: AsRef<Path>>(
1013    filesystem: FS,
1014    mountpoint: P,
1015    options: &[MountOption],
1016) -> io::Result<()> {
1017    check_option_conflicts(options)?;
1018    Session::new(filesystem, mountpoint.as_ref(), options).and_then(|mut se| se.run())
1019}
1020
1021/// Mount the given filesystem to the given mountpoint. This function spawns
1022/// a background thread to handle filesystem operations while being mounted
1023/// and therefore returns immediately. The returned handle should be stored
1024/// to reference the mounted filesystem. If it's dropped, the filesystem will
1025/// be unmounted.
1026#[deprecated(note = "use spawn_mount2() instead")]
1027pub fn spawn_mount<'a, FS: Filesystem + Send + 'static + 'a, P: AsRef<Path>>(
1028    filesystem: FS,
1029    mountpoint: P,
1030    options: &[&OsStr],
1031) -> io::Result<BackgroundSession> {
1032    let options: Option<Vec<_>> = options
1033        .iter()
1034        .map(|x| Some(MountOption::from_str(x.to_str()?)))
1035        .collect();
1036    let options = options.ok_or(ErrorKind::InvalidData)?;
1037    Session::new(filesystem, mountpoint.as_ref(), options.as_ref()).and_then(|se| se.spawn())
1038}
1039
1040/// Mount the given filesystem to the given mountpoint. This function spawns
1041/// a background thread to handle filesystem operations while being mounted
1042/// and therefore returns immediately. The returned handle should be stored
1043/// to reference the mounted filesystem. If it's dropped, the filesystem will
1044/// be unmounted.
1045///
1046/// NOTE: This is the corresponding function to mount2.
1047pub fn spawn_mount2<'a, FS: Filesystem + Send + 'static + 'a, P: AsRef<Path>>(
1048    filesystem: FS,
1049    mountpoint: P,
1050    options: &[MountOption],
1051) -> io::Result<BackgroundSession> {
1052    check_option_conflicts(options)?;
1053    Session::new(filesystem, mountpoint.as_ref(), options).and_then(|se| se.spawn())
1054}