1use 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
24pub const MAX_WRITE_SIZE: usize = 16 * 1024 * 1024;
28
29const 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#[derive(Debug)]
42pub struct Session<FS: Filesystem> {
43 pub(crate) filesystem: FS,
45 ch: Channel,
47 mount: Arc<Mutex<Option<Mount>>>,
49 mountpoint: PathBuf,
51 pub(crate) allowed: SessionACL,
54 pub(crate) session_owner: u32,
56 pub(crate) proto_major: u32,
58 pub(crate) proto_minor: u32,
60 pub(crate) initialized: bool,
62 pub(crate) destroyed: bool,
64}
65
66impl<FS: Filesystem> Session<FS> {
67 pub fn new(
69 filesystem: FS,
70 mountpoint: &Path,
71 options: &[MountOption],
72 ) -> io::Result<Session<FS>> {
73 info!("Mounting {}", mountpoint.display());
74 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 pub fn mountpoint(&self) -> &Path {
114 &self.mountpoint
115 }
116
117 pub fn run(&mut self) -> io::Result<()> {
122 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 match self.ch.receive(buf) {
133 Ok(size) => match Request::new(self.ch.sender(), &buf[..size]) {
134 Some(req) => req.dispatch(self),
136 None => break,
138 },
139 Err(err) => match err.raw_os_error() {
140 Some(ENOENT) => continue,
142 Some(EINTR) => continue,
144 Some(EAGAIN) => continue,
146 Some(ENODEV) => break,
148 _ => return Err(err),
150 },
151 }
152 }
153 Ok(())
154 }
155
156 pub fn unmount(&mut self) {
158 drop(std::mem::take(&mut *self.mount.lock().unwrap()));
159 }
160
161 pub fn unmount_callable(&mut self) -> SessionUnmounter {
163 SessionUnmounter {
164 mount: self.mount.clone(),
165 }
166 }
167
168 #[cfg(feature = "abi-7-11")]
170 pub fn notifier(&self) -> Notifier {
171 Notifier::new(self.ch.sender())
172 }
173}
174
175#[derive(Debug)]
176pub struct SessionUnmounter {
178 mount: Arc<Mutex<Option<Mount>>>,
179}
180
181impl SessionUnmounter {
182 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 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
215pub struct BackgroundSession {
217 pub mountpoint: PathBuf,
219 pub guard: JoinHandle<io::Result<()>>,
221 #[cfg(feature = "abi-7-11")]
223 sender: ChannelSender,
224 _mount: Mount,
226}
227
228impl BackgroundSession {
229 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 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 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 #[cfg(feature = "abi-7-11")]
266 pub fn notifier(&self) -> Notifier {
267 Notifier::new(self.sender.clone())
268 }
269}
270
271impl 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}