fuse/
lib.rs

1// Copyright 2020 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! FUSE (Filesystem in Userspace) server and filesystem mounting support.
6
7#![cfg(any(target_os = "android", target_os = "linux"))]
8
9use std::ffi::FromBytesWithNulError;
10use std::fs::File;
11use std::io;
12
13use remain::sorted;
14use thiserror::Error as ThisError;
15
16pub mod filesystem;
17pub mod fuzzing;
18pub mod mount;
19mod server;
20#[allow(dead_code)]
21pub mod sys;
22pub mod worker;
23
24use filesystem::FileSystem;
25pub use mount::mount;
26pub use server::Mapper;
27pub use server::Reader;
28pub use server::Server;
29pub use server::Writer;
30
31/// Errors that may occur during the creation or operation of an Fs device.
32#[sorted]
33#[derive(ThisError, Debug)]
34pub enum Error {
35    /// A request is missing readable descriptors.
36    /// Failed to decode protocol messages.
37    #[error("failed to decode fuse message: {0}")]
38    DecodeMessage(io::Error),
39    /// Failed to encode protocol messages.
40    #[error("failed to encode fuse message: {0}")]
41    EncodeMessage(io::Error),
42    /// Failed to set up FUSE endpoint to talk with.
43    #[error("failed to set up FUSE endpoint to talk with: {0}")]
44    EndpointSetup(io::Error),
45    /// Failed to flush protocol messages.
46    #[error("failed to flush fuse message: {0}")]
47    FlushMessage(io::Error),
48    /// A C string parameter is invalid.
49    #[error("a c string parameter is invalid: {0}")]
50    InvalidCString(FromBytesWithNulError),
51    /// The `len` field of the header is too small.
52    #[error("the `len` field of the header is too small")]
53    InvalidHeaderLength,
54    /// The `size` field of the `SetxattrIn` message does not match the length
55    /// of the decoded value.
56    #[error(
57        "The `size` field of the `SetxattrIn` message does not match the\
58             length of the decoded value: size = {0}, value.len() = {1}"
59    )]
60    InvalidXattrSize(u32, usize),
61    /// One or more parameters are missing.
62    #[error("one or more parameters are missing")]
63    MissingParameter,
64    /// Thread exited
65    #[error("Thread exited")]
66    ThreadExited,
67    /// Requested too many `iovec`s for an `ioctl` retry.
68    #[error(
69        "requested too many `iovec`s for an `ioctl` retry reply: requested\
70            {0}, max: {1}"
71    )]
72    TooManyIovecs(usize, usize),
73}
74
75pub type Result<T> = ::std::result::Result<T, Error>;
76
77#[derive(Default)]
78pub struct FuseConfig {
79    dev_fuse_file: Option<File>,
80    max_write_bytes: Option<u32>,
81    max_read_bytes: Option<u32>,
82    num_of_threads: Option<usize>,
83}
84
85impl FuseConfig {
86    pub fn new() -> Self {
87        FuseConfig {
88            ..Default::default()
89        }
90    }
91
92    /// Set the FUSE device.
93    pub fn dev_fuse(&mut self, file: File) -> &mut Self {
94        self.dev_fuse_file = Some(file);
95        self
96    }
97
98    /// Set the maximum data in a read request. Must be large enough (usually equal) to `n` in
99    /// `MountOption::MaxRead(n)`.
100    pub fn max_read(&mut self, bytes: u32) -> &mut Self {
101        self.max_read_bytes = Some(bytes);
102        self
103    }
104
105    /// Set the maximum data in a write request.
106    pub fn max_write(&mut self, bytes: u32) -> &mut Self {
107        self.max_write_bytes = Some(bytes);
108        self
109    }
110
111    /// Set the number of threads to run the `FileSystem`.
112    pub fn num_threads(&mut self, num: usize) -> &mut Self {
113        self.num_of_threads = Some(num);
114        self
115    }
116
117    pub fn enter_message_loop<F: FileSystem + Sync + Send>(self, fs: F) -> Result<()> {
118        let FuseConfig {
119            dev_fuse_file,
120            max_write_bytes,
121            max_read_bytes,
122            num_of_threads,
123        } = self;
124        let num = num_of_threads.unwrap_or(1);
125        if num == 1 {
126            worker::start_message_loop(
127                dev_fuse_file.ok_or(Error::MissingParameter)?,
128                max_write_bytes.ok_or(Error::MissingParameter)?,
129                max_read_bytes.ok_or(Error::MissingParameter)?,
130                fs,
131            )
132        } else {
133            worker::internal::start_message_loop_mt(
134                dev_fuse_file.ok_or(Error::MissingParameter)?,
135                max_write_bytes.ok_or(Error::MissingParameter)?,
136                max_read_bytes.ok_or(Error::MissingParameter)?,
137                num,
138                fs,
139            )
140        }
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use std::io::Read;
147    use std::io::Write;
148    use std::mem::size_of;
149    use std::os::fd::OwnedFd;
150    use std::os::unix::net::UnixStream;
151
152    use zerocopy::FromBytes;
153    use zerocopy::IntoBytes;
154
155    use super::*;
156    use crate::filesystem::Context;
157    use crate::filesystem::DirEntry;
158    use crate::filesystem::DirectoryIterator;
159    use crate::sys::InHeader;
160    use crate::sys::InitIn;
161    use crate::sys::InitOut;
162    use crate::sys::Opcode;
163    use crate::sys::OutHeader;
164    use crate::sys::ReadIn;
165    use crate::sys::KERNEL_MINOR_VERSION;
166    use crate::sys::KERNEL_VERSION;
167
168    struct EmptyDirIter;
169
170    impl DirectoryIterator for EmptyDirIter {
171        fn next(&mut self) -> Option<DirEntry> {
172            None
173        }
174    }
175
176    struct ReadOnlyDirFs;
177
178    impl FileSystem for ReadOnlyDirFs {
179        type Inode = u64;
180        type Handle = u64;
181        type DirIter = EmptyDirIter;
182
183        fn readdir(
184            &self,
185            _ctx: Context,
186            _inode: Self::Inode,
187            _handle: Self::Handle,
188            _size: u32,
189            _offset: u64,
190        ) -> io::Result<Self::DirIter> {
191            Ok(EmptyDirIter)
192        }
193    }
194
195    #[test]
196    fn fuse_config_readdir_exceeding_max_write_and_matching_max_read() {
197        const MAX_WRITE: u32 = 8 * 1024;
198        const MAX_READ: u32 = 64 * 1024;
199        const PAGE_SIZE_16K: u32 = 16 * 1024;
200
201        let (mut kernel_sock, daemon_sock) = UnixStream::pair().unwrap();
202        let dev_fuse = File::from(OwnedFd::from(daemon_sock));
203
204        let server_thread = std::thread::spawn(move || {
205            let mut config = FuseConfig::new();
206            config
207                .dev_fuse(dev_fuse)
208                .max_write(MAX_WRITE)
209                .max_read(MAX_READ);
210            config.enter_message_loop(ReadOnlyDirFs)
211        });
212
213        for (unique, opcode, req_size, expected_error) in [
214            (1_u64, Opcode::Readdir, PAGE_SIZE_16K, 0),
215            (2_u64, Opcode::Readdir, MAX_READ, 0),
216            (3_u64, Opcode::Readdir, MAX_READ + 1, -libc::ENOMEM),
217            (4_u64, Opcode::Readdirplus, MAX_READ, 0),
218            (5_u64, Opcode::Readdirplus, MAX_READ + 1, -libc::ENOMEM),
219        ] {
220            let in_header = InHeader {
221                len: (size_of::<InHeader>() + size_of::<ReadIn>()) as u32,
222                opcode: opcode as u32,
223                unique,
224                nodeid: 1,
225                uid: 0,
226                gid: 0,
227                pid: 1,
228                padding: 0,
229            };
230            let read_in = ReadIn {
231                fh: 1,
232                offset: 0,
233                size: req_size,
234                read_flags: 0,
235                lock_owner: 0,
236                flags: 0,
237                padding: 0,
238            };
239            kernel_sock.write_all(in_header.as_bytes()).unwrap();
240            kernel_sock.write_all(read_in.as_bytes()).unwrap();
241
242            let mut reply = [0_u8; size_of::<OutHeader>()];
243            kernel_sock.read_exact(&mut reply).unwrap();
244            let out_header = OutHeader::read_from_bytes(&reply).unwrap();
245            assert_eq!(out_header.unique, unique);
246            assert_eq!(out_header.error, expected_error);
247            assert_eq!(out_header.len, size_of::<OutHeader>() as u32);
248        }
249
250        drop(kernel_sock);
251        let res = server_thread.join().unwrap();
252        assert!(matches!(res, Err(Error::DecodeMessage(_))));
253    }
254
255    #[test]
256    fn fuse_config_init_clamps_max_write_to_configured_value() {
257        const MAX_WRITE: u32 = 8 * 1024;
258        const MAX_READ: u32 = 64 * 1024;
259        assert!(MAX_WRITE < ReadOnlyDirFs.max_buffer_size());
260
261        let (mut kernel_sock, daemon_sock) = UnixStream::pair().unwrap();
262        let dev_fuse = File::from(OwnedFd::from(daemon_sock));
263
264        let server_thread = std::thread::spawn(move || {
265            let mut config = FuseConfig::new();
266            config
267                .dev_fuse(dev_fuse)
268                .max_write(MAX_WRITE)
269                .max_read(MAX_READ);
270            config.enter_message_loop(ReadOnlyDirFs)
271        });
272
273        let in_header = InHeader {
274            len: (size_of::<InHeader>() + size_of::<InitIn>()) as u32,
275            opcode: Opcode::Init as u32,
276            unique: 1,
277            nodeid: 0,
278            uid: 0,
279            gid: 0,
280            pid: 1,
281            padding: 0,
282        };
283        let init_in = InitIn {
284            major: KERNEL_VERSION,
285            minor: KERNEL_MINOR_VERSION,
286            max_readahead: MAX_READ,
287            flags: 0,
288        };
289        kernel_sock.write_all(in_header.as_bytes()).unwrap();
290        kernel_sock.write_all(init_in.as_bytes()).unwrap();
291
292        let mut reply = [0_u8; size_of::<OutHeader>() + size_of::<InitOut>()];
293        kernel_sock.read_exact(&mut reply).unwrap();
294        let (hdr_bytes, body_bytes) = reply.split_at(size_of::<OutHeader>());
295        let out_header = OutHeader::read_from_bytes(hdr_bytes).unwrap();
296        let init_out = InitOut::read_from_bytes(body_bytes).unwrap();
297        assert_eq!(out_header.unique, 1);
298        assert_eq!(out_header.error, 0);
299        assert_eq!(
300            out_header.len,
301            (size_of::<OutHeader>() + size_of::<InitOut>()) as u32
302        );
303        assert_eq!(init_out.max_write, MAX_WRITE);
304
305        drop(kernel_sock);
306        let res = server_thread.join().unwrap();
307        assert!(matches!(res, Err(Error::DecodeMessage(_))));
308    }
309}