Skip to main content

fuser/
session.rs

1//! Filesystem session
2//!
3//! A session runs a filesystem implementation while it is being mounted to a specific mount
4//! point. A session begins by mounting the filesystem and ends by unmounting it. While the
5//! filesystem is mounted, the session loop receives, dispatches and replies to kernel requests
6//! for filesystem operations under its mount point.
7
8use libc::{EAGAIN, EINTR, ENODEV, ENOENT};
9use log::{info, warn};
10use std::fmt;
11use std::path::{Path, PathBuf};
12use std::sync::{Arc, Mutex};
13use std::thread::{self, JoinHandle};
14use std::{io, ops::DerefMut};
15
16use crate::ll::fuse_abi as abi;
17use crate::request::Request;
18use crate::Filesystem;
19use crate::MountOption;
20use crate::{channel::Channel, mnt::Mount};
21#[cfg(feature = "abi-7-11")]
22use crate::{channel::ChannelSender, notify::Notifier};
23
24/// The max size of write requests from the kernel. The absolute minimum is 4k,
25/// FUSE recommends at least 128k, max 16M. The FUSE default is 16M on macOS
26/// and 128k on other systems.
27pub const MAX_WRITE_SIZE: usize = 16 * 1024 * 1024;
28
29/// Size of the buffer for reading a request from the kernel. Since the kernel may send
30/// up to MAX_WRITE_SIZE bytes in a write request, we use that value plus some extra space.
31const BUFFER_SIZE: usize = MAX_WRITE_SIZE + 4096;
32
33#[derive(Debug, Eq, PartialEq)]
34pub(crate) enum SessionACL {
35    All,
36    RootAndOwner,
37    Owner,
38}
39
40/// The session data structure
41#[derive(Debug)]
42pub struct Session<FS: Filesystem> {
43    /// Filesystem operation implementations
44    pub(crate) filesystem: FS,
45    /// Communication channel to the kernel driver
46    ch: Channel,
47    /// Handle to the mount.  Dropping this unmounts.
48    mount: Arc<Mutex<Option<Mount>>>,
49    /// Mount point
50    mountpoint: PathBuf,
51    /// Whether to restrict access to owner, root + owner, or unrestricted
52    /// Used to implement allow_root and auto_unmount
53    pub(crate) allowed: SessionACL,
54    /// User that launched the fuser process
55    pub(crate) session_owner: u32,
56    /// FUSE protocol major version
57    pub(crate) proto_major: u32,
58    /// FUSE protocol minor version
59    pub(crate) proto_minor: u32,
60    /// True if the filesystem is initialized (init operation done)
61    pub(crate) initialized: bool,
62    /// True if the filesystem was destroyed (destroy operation done)
63    pub(crate) destroyed: bool,
64}
65
66impl<FS: Filesystem> Session<FS> {
67    /// Create a new session by mounting the given filesystem to the given mountpoint
68    pub fn new(
69        filesystem: FS,
70        mountpoint: &Path,
71        options: &[MountOption],
72    ) -> io::Result<Session<FS>> {
73        info!("Mounting {}", mountpoint.display());
74        // If AutoUnmount is requested, but not AllowRoot or AllowOther we enforce the ACL
75        // ourself and implicitly set AllowOther because fusermount needs allow_root or allow_other
76        // to handle the auto_unmount option
77        let (file, mount) = if options.contains(&MountOption::AutoUnmount)
78            && !(options.contains(&MountOption::AllowRoot)
79                || options.contains(&MountOption::AllowOther))
80        {
81            warn!("Given auto_unmount without allow_root or allow_other; adding allow_other, with userspace permission handling");
82            let mut modified_options = options.to_vec();
83            modified_options.push(MountOption::AllowOther);
84            Mount::new(mountpoint, &modified_options)?
85        } else {
86            Mount::new(mountpoint, options)?
87        };
88
89        let ch = Channel::new(file);
90        let allowed = if options.contains(&MountOption::AllowRoot) {
91            SessionACL::RootAndOwner
92        } else if options.contains(&MountOption::AllowOther) {
93            SessionACL::All
94        } else {
95            SessionACL::Owner
96        };
97
98        Ok(Session {
99            filesystem,
100            ch,
101            mount: Arc::new(Mutex::new(Some(mount))),
102            mountpoint: mountpoint.to_owned(),
103            allowed,
104            session_owner: unsafe { libc::geteuid() },
105            proto_major: 0,
106            proto_minor: 0,
107            initialized: false,
108            destroyed: false,
109        })
110    }
111
112    /// Return path of the mounted filesystem
113    pub fn mountpoint(&self) -> &Path {
114        &self.mountpoint
115    }
116
117    /// Run the session loop that receives kernel requests and dispatches them to method
118    /// calls into the filesystem. This read-dispatch-loop is non-concurrent to prevent
119    /// having multiple buffers (which take up much memory), but the filesystem methods
120    /// may run concurrent by spawning threads.
121    pub fn run(&mut self) -> io::Result<()> {
122        // Buffer for receiving requests from the kernel. Only one is allocated and
123        // it is reused immediately after dispatching to conserve memory and allocations.
124        let mut buffer = vec![0; BUFFER_SIZE];
125        let buf = aligned_sub_buf(
126            buffer.deref_mut(),
127            std::mem::align_of::<abi::fuse_in_header>(),
128        );
129        loop {
130            // Read the next request from the given channel to kernel driver
131            // The kernel driver makes sure that we get exactly one request per read
132            match self.ch.receive(buf) {
133                Ok(size) => match Request::new(self.ch.sender(), &buf[..size]) {
134                    // Dispatch request
135                    Some(req) => req.dispatch(self),
136                    // Quit loop on illegal request
137                    None => break,
138                },
139                Err(err) => match err.raw_os_error() {
140                    // Operation interrupted. Accordingly to FUSE, this is safe to retry
141                    Some(ENOENT) => continue,
142                    // Interrupted system call, retry
143                    Some(EINTR) => continue,
144                    // Explicitly try again
145                    Some(EAGAIN) => continue,
146                    // Filesystem was unmounted, quit the loop
147                    Some(ENODEV) => break,
148                    // Unhandled error
149                    _ => return Err(err),
150                },
151            }
152        }
153        Ok(())
154    }
155
156    /// Unmount the filesystem
157    pub fn unmount(&mut self) {
158        drop(std::mem::take(&mut *self.mount.lock().unwrap()));
159    }
160
161    /// Returns a thread-safe object that can be used to unmount the Filesystem
162    pub fn unmount_callable(&mut self) -> SessionUnmounter {
163        SessionUnmounter {
164            mount: self.mount.clone(),
165        }
166    }
167
168    /// Returns an object that can be used to send notifications to the kernel
169    #[cfg(feature = "abi-7-11")]
170    pub fn notifier(&self) -> Notifier {
171        Notifier::new(self.ch.sender())
172    }
173}
174
175#[derive(Debug)]
176/// A thread-safe object that can be used to unmount a Filesystem
177pub struct SessionUnmounter {
178    mount: Arc<Mutex<Option<Mount>>>,
179}
180
181impl SessionUnmounter {
182    /// Unmount the filesystem
183    pub fn unmount(&mut self) -> io::Result<()> {
184        drop(std::mem::take(&mut *self.mount.lock().unwrap()));
185        Ok(())
186    }
187}
188
189fn aligned_sub_buf(buf: &mut [u8], alignment: usize) -> &mut [u8] {
190    let off = alignment - (buf.as_ptr() as usize) % alignment;
191    if off == alignment {
192        buf
193    } else {
194        &mut buf[off..]
195    }
196}
197
198impl<FS: 'static + Filesystem + Send> Session<FS> {
199    /// Run the session loop in a background thread
200    pub fn spawn(self) -> io::Result<BackgroundSession> {
201        BackgroundSession::new(self)
202    }
203}
204
205impl<FS: Filesystem> Drop for Session<FS> {
206    fn drop(&mut self) {
207        if !self.destroyed {
208            self.filesystem.destroy();
209            self.destroyed = true;
210        }
211        info!("Unmounted {}", self.mountpoint().display());
212    }
213}
214
215/// The background session data structure
216pub struct BackgroundSession {
217    /// Path of the mounted filesystem
218    pub mountpoint: PathBuf,
219    /// Thread guard of the background session
220    pub guard: JoinHandle<io::Result<()>>,
221    /// Object for creating Notifiers for client use
222    #[cfg(feature = "abi-7-11")]
223    sender: ChannelSender,
224    /// Ensures the filesystem is unmounted when the session ends
225    _mount: Mount,
226}
227
228impl BackgroundSession {
229    /// Create a new background session for the given session by running its
230    /// session loop in a background thread. If the returned handle is dropped,
231    /// the filesystem is unmounted and the given session ends.
232    pub fn new<FS: Filesystem + Send + 'static>(se: Session<FS>) -> io::Result<BackgroundSession> {
233        let mountpoint = se.mountpoint().to_path_buf();
234        #[cfg(feature = "abi-7-11")]
235        let sender = se.ch.sender();
236        // Take the fuse_session, so that we can unmount it
237        let mount = std::mem::take(&mut *se.mount.lock().unwrap());
238        let mount = mount.ok_or_else(|| io::Error::from_raw_os_error(libc::ENODEV))?;
239        let guard = thread::spawn(move || {
240            let mut se = se;
241            se.run()
242        });
243        Ok(BackgroundSession {
244            mountpoint,
245            guard,
246            #[cfg(feature = "abi-7-11")]
247            sender,
248            _mount: mount,
249        })
250    }
251    /// Unmount the filesystem and join the background thread.
252    pub fn join(self) {
253        let Self {
254            mountpoint: _,
255            guard,
256            #[cfg(feature = "abi-7-11")]
257                sender: _,
258            _mount,
259        } = self;
260        drop(_mount);
261        guard.join().unwrap().unwrap();
262    }
263
264    /// Returns an object that can be used to send notifications to the kernel
265    #[cfg(feature = "abi-7-11")]
266    pub fn notifier(&self) -> Notifier {
267        Notifier::new(self.sender.clone())
268    }
269}
270
271// replace with #[derive(Debug)] if Debug ever gets implemented for
272// thread_scoped::JoinGuard
273impl fmt::Debug for BackgroundSession {
274    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
275        write!(
276            f,
277            "BackgroundSession {{ mountpoint: {:?}, guard: JoinGuard<()> }}",
278            self.mountpoint
279        )
280    }
281}