fuse/
server.rs

1// Copyright 2019 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
5use std::cmp::max;
6use std::cmp::min;
7use std::convert::TryInto;
8use std::ffi::CStr;
9use std::io;
10use std::mem::size_of;
11use std::mem::MaybeUninit;
12use std::os::unix::io::AsRawFd;
13use std::time::Duration;
14
15use base::error;
16use base::pagesize;
17use base::Protection;
18use zerocopy::FromBytes;
19use zerocopy::Immutable;
20use zerocopy::IntoBytes;
21
22use crate::filesystem::Context;
23use crate::filesystem::DirEntry;
24use crate::filesystem::DirectoryIterator;
25use crate::filesystem::Entry;
26use crate::filesystem::FileSystem;
27use crate::filesystem::GetxattrReply;
28use crate::filesystem::IoctlReply;
29use crate::filesystem::ListxattrReply;
30use crate::filesystem::ZeroCopyReader;
31use crate::filesystem::ZeroCopyWriter;
32use crate::sys::*;
33use crate::Error;
34use crate::Result;
35
36const DIRENT_PADDING: [u8; 8] = [0; 8];
37
38const SELINUX_XATTR_CSTR: &[u8] = b"security.selinux\0";
39
40/// A trait for reading from the underlying FUSE endpoint.
41pub trait Reader: io::Read {
42    fn read_struct<T: IntoBytes + FromBytes>(&mut self) -> Result<T> {
43        let mut out = T::new_zeroed();
44        self.read_exact(out.as_mut_bytes())
45            .map_err(Error::DecodeMessage)?;
46        Ok(out)
47    }
48}
49
50impl<R: Reader> Reader for &'_ mut R {}
51
52/// A trait for writing to the underlying FUSE endpoint. The FUSE device expects the write
53/// operation to happen in one write transaction. Since there are cases when data needs to be
54/// generated earlier than the header, it implies the writer implementation to keep an internal
55/// buffer. The buffer then can be flushed once header and data are both prepared.
56pub trait Writer: io::Write {
57    /// The type passed in to the closure in `write_at`. For most implementations, this should be
58    /// `Self`.
59    type ClosureWriter: Writer + ZeroCopyWriter;
60
61    /// Allows a closure to generate and write data at the current writer's offset. The current
62    /// writer is passed as a mutable reference to the closure. As an example, this provides an
63    /// adapter for the read implementation of a filesystem to write directly to the final buffer
64    /// without generating the FUSE header first.
65    ///
66    /// Notes: An alternative implementation would be to return a slightly different writer for the
67    /// API client to write to the offset. Since the API needs to be called for more than one time,
68    /// it imposes some complexity to deal with borrowing and mutability. The current approach
69    /// simply does not need to create a different writer, thus no need to deal with the mentioned
70    /// complexity.
71    fn write_at<F>(&mut self, offset: usize, f: F) -> io::Result<usize>
72    where
73        F: Fn(&mut Self::ClosureWriter) -> io::Result<usize>;
74
75    /// Checks if the writer can still accept certain amount of data.
76    fn has_sufficient_buffer(&self, size: u32) -> bool;
77}
78
79impl<W: Writer> Writer for &'_ mut W {
80    type ClosureWriter = W::ClosureWriter;
81
82    fn write_at<F>(&mut self, offset: usize, f: F) -> io::Result<usize>
83    where
84        F: Fn(&mut Self::ClosureWriter) -> io::Result<usize>,
85    {
86        (**self).write_at(offset, f)
87    }
88
89    fn has_sufficient_buffer(&self, size: u32) -> bool {
90        (**self).has_sufficient_buffer(size)
91    }
92}
93
94/// A trait for memory mapping for DAX.
95///
96/// For some transports (like virtio) it may be possible to share a region of memory with the
97/// FUSE kernel driver so that it can access file contents directly without issuing read or
98/// write requests.  In this case the driver will instead send requests to map a section of a
99/// file into the shared memory region.
100pub trait Mapper {
101    /// Maps `size` bytes starting at `file_offset` bytes from within the given `fd` at `mem_offset`
102    /// bytes from the start of the memory region with `prot` protections. `mem_offset` must be
103    /// page aligned.
104    ///
105    /// # Arguments
106    /// * `mem_offset` - Page aligned offset into the memory region in bytes.
107    /// * `size` - Size of memory region in bytes.
108    /// * `fd` - File descriptor to mmap from.
109    /// * `file_offset` - Offset in bytes from the beginning of `fd` to start the mmap.
110    /// * `prot` - Protection of the memory region.
111    fn map(
112        &self,
113        mem_offset: u64,
114        size: usize,
115        fd: &dyn AsRawFd,
116        file_offset: u64,
117        prot: Protection,
118    ) -> io::Result<()>;
119
120    /// Unmaps `size` bytes at `offset` bytes from the start of the memory region. `offset` must be
121    /// page aligned.
122    ///
123    /// # Arguments
124    /// * `offset` - Page aligned offset into the arena in bytes.
125    /// * `size` - Size of memory region in bytes.
126    fn unmap(&self, offset: u64, size: u64) -> io::Result<()>;
127}
128
129impl<M: Mapper> Mapper for &M {
130    fn map(
131        &self,
132        mem_offset: u64,
133        size: usize,
134        fd: &dyn AsRawFd,
135        file_offset: u64,
136        prot: Protection,
137    ) -> io::Result<()> {
138        (**self).map(mem_offset, size, fd, file_offset, prot)
139    }
140
141    fn unmap(&self, offset: u64, size: u64) -> io::Result<()> {
142        (**self).unmap(offset, size)
143    }
144}
145
146pub struct Server<F: FileSystem + Sync> {
147    fs: F,
148    max_write: u32,
149}
150
151impl<F: FileSystem + Sync> Server<F> {
152    pub fn new(fs: F) -> Server<F> {
153        let max_write = fs.max_buffer_size();
154        Server { fs, max_write }
155    }
156
157    pub(crate) fn with_max_write(fs: F, max_write: u32) -> Server<F> {
158        let max_write = min(fs.max_buffer_size(), max_write);
159        Server { fs, max_write }
160    }
161
162    pub fn handle_message<R: Reader + ZeroCopyReader, W: Writer + ZeroCopyWriter, M: Mapper>(
163        &self,
164        mut r: R,
165        w: W,
166        mapper: M,
167    ) -> Result<usize> {
168        let in_header: InHeader = r.read_struct()?;
169        cros_tracing::trace_simple_print!("fuse server: handle_message: in_header={:?}", in_header);
170
171        if in_header.len
172            > size_of::<InHeader>() as u32 + size_of::<WriteIn>() as u32 + self.fs.max_buffer_size()
173        {
174            return reply_error(
175                io::Error::from_raw_os_error(libc::ENOMEM),
176                in_header.unique,
177                w,
178            );
179        }
180        match Opcode::n(in_header.opcode) {
181            Some(Opcode::Lookup) => self.lookup(in_header, r, w),
182            Some(Opcode::Forget) => self.forget(in_header, r), // No reply.
183            Some(Opcode::Getattr) => self.getattr(in_header, r, w),
184            Some(Opcode::Setattr) => self.setattr(in_header, r, w),
185            Some(Opcode::Readlink) => self.readlink(in_header, w),
186            Some(Opcode::Symlink) => self.symlink(in_header, r, w),
187            Some(Opcode::Mknod) => self.mknod(in_header, r, w),
188            Some(Opcode::Mkdir) => self.mkdir(in_header, r, w),
189            Some(Opcode::Unlink) => self.unlink(in_header, r, w),
190            Some(Opcode::Rmdir) => self.rmdir(in_header, r, w),
191            Some(Opcode::Rename) => self.rename(in_header, r, w),
192            Some(Opcode::Link) => self.link(in_header, r, w),
193            Some(Opcode::Open) => self.open(in_header, r, w),
194            Some(Opcode::Read) => self.read(in_header, r, w),
195            Some(Opcode::Write) => self.write(in_header, r, w),
196            Some(Opcode::Statfs) => self.statfs(in_header, w),
197            Some(Opcode::Release) => self.release(in_header, r, w),
198            Some(Opcode::Fsync) => self.fsync(in_header, r, w),
199            Some(Opcode::Setxattr) => self.setxattr(in_header, r, w),
200            Some(Opcode::Getxattr) => self.getxattr(in_header, r, w),
201            Some(Opcode::Listxattr) => self.listxattr(in_header, r, w),
202            Some(Opcode::Removexattr) => self.removexattr(in_header, r, w),
203            Some(Opcode::Flush) => self.flush(in_header, r, w),
204            Some(Opcode::Init) => self.init(in_header, r, w),
205            Some(Opcode::Opendir) => self.opendir(in_header, r, w),
206            Some(Opcode::Readdir) => self.readdir(in_header, r, w),
207            Some(Opcode::Releasedir) => self.releasedir(in_header, r, w),
208            Some(Opcode::Fsyncdir) => self.fsyncdir(in_header, r, w),
209            Some(Opcode::Getlk) => self.getlk(in_header, r, w),
210            Some(Opcode::Setlk) => self.setlk(in_header, r, w),
211            Some(Opcode::Setlkw) => self.setlkw(in_header, r, w),
212            Some(Opcode::Access) => self.access(in_header, r, w),
213            Some(Opcode::Create) => self.create(in_header, r, w),
214            Some(Opcode::Interrupt) => self.interrupt(in_header),
215            Some(Opcode::Bmap) => self.bmap(in_header, r, w),
216            Some(Opcode::Destroy) => self.destroy(),
217            Some(Opcode::Ioctl) => self.ioctl(in_header, r, w),
218            Some(Opcode::Poll) => self.poll(in_header, r, w),
219            Some(Opcode::NotifyReply) => self.notify_reply(in_header, r, w),
220            Some(Opcode::BatchForget) => self.batch_forget(in_header, r, w),
221            Some(Opcode::Fallocate) => self.fallocate(in_header, r, w),
222            Some(Opcode::Readdirplus) => self.readdirplus(in_header, r, w),
223            Some(Opcode::Rename2) => self.rename2(in_header, r, w),
224            Some(Opcode::Lseek) => self.lseek(in_header, r, w),
225            Some(Opcode::CopyFileRange) => self.copy_file_range(in_header, r, w),
226            Some(Opcode::ChromeOsTmpfile) => self.chromeos_tmpfile(in_header, r, w),
227            Some(Opcode::SetUpMapping) => self.set_up_mapping(in_header, r, w, mapper),
228            Some(Opcode::RemoveMapping) => self.remove_mapping(in_header, r, w, mapper),
229            Some(Opcode::OpenAtomic) => self.open_atomic(in_header, r, w),
230            None => reply_error(
231                io::Error::from_raw_os_error(libc::ENOSYS),
232                in_header.unique,
233                w,
234            ),
235        }
236    }
237
238    fn lookup<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
239        let namelen = (in_header.len as usize)
240            .checked_sub(size_of::<InHeader>())
241            .ok_or(Error::InvalidHeaderLength)?;
242
243        let mut buf = vec![0; namelen];
244
245        r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
246
247        let name = bytes_to_path_component(&buf)?;
248
249        match self
250            .fs
251            .lookup(Context::from(in_header), in_header.nodeid.into(), name)
252        {
253            Ok(entry) => {
254                let out = EntryOut::from(entry);
255
256                reply_ok(Some(out), None, in_header.unique, w)
257            }
258            Err(e) => reply_error(e, in_header.unique, w),
259        }
260    }
261
262    fn forget<R: Reader>(&self, in_header: InHeader, mut r: R) -> Result<usize> {
263        let ForgetIn { nlookup } = r.read_struct()?;
264
265        self.fs
266            .forget(Context::from(in_header), in_header.nodeid.into(), nlookup);
267
268        // There is no reply for forget messages.
269        Ok(0)
270    }
271
272    fn getattr<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
273        let GetattrIn {
274            flags,
275            dummy: _,
276            fh,
277        } = r.read_struct()?;
278
279        let handle = if (flags & GETATTR_FH) != 0 {
280            Some(fh.into())
281        } else {
282            None
283        };
284
285        match self
286            .fs
287            .getattr(Context::from(in_header), in_header.nodeid.into(), handle)
288        {
289            Ok((st, timeout)) => {
290                let out = AttrOut {
291                    attr_valid: timeout.as_secs(),
292                    attr_valid_nsec: timeout.subsec_nanos(),
293                    dummy: 0,
294                    attr: st.into(),
295                };
296                reply_ok(Some(out), None, in_header.unique, w)
297            }
298            Err(e) => reply_error(e, in_header.unique, w),
299        }
300    }
301
302    fn setattr<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
303        let setattr_in: SetattrIn = r.read_struct()?;
304
305        let handle = if setattr_in.valid & FATTR_FH != 0 {
306            Some(setattr_in.fh.into())
307        } else {
308            None
309        };
310
311        let valid = SetattrValid::from_bits_truncate(setattr_in.valid);
312
313        let st: libc::stat64 = setattr_in.into();
314
315        match self.fs.setattr(
316            Context::from(in_header),
317            in_header.nodeid.into(),
318            st,
319            handle,
320            valid,
321        ) {
322            Ok((st, timeout)) => {
323                let out = AttrOut {
324                    attr_valid: timeout.as_secs(),
325                    attr_valid_nsec: timeout.subsec_nanos(),
326                    dummy: 0,
327                    attr: st.into(),
328                };
329                reply_ok(Some(out), None, in_header.unique, w)
330            }
331            Err(e) => reply_error(e, in_header.unique, w),
332        }
333    }
334
335    fn readlink<W: Writer>(&self, in_header: InHeader, w: W) -> Result<usize> {
336        match self
337            .fs
338            .readlink(Context::from(in_header), in_header.nodeid.into())
339        {
340            Ok(linkname) => {
341                // We need to disambiguate the option type here even though it is `None`.
342                reply_ok(None::<u8>, Some(&linkname), in_header.unique, w)
343            }
344            Err(e) => reply_error(e, in_header.unique, w),
345        }
346    }
347
348    fn symlink<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
349        // Unfortunately the name and linkname are encoded one after another and
350        // separated by a nul character.
351        let len = (in_header.len as usize)
352            .checked_sub(size_of::<InHeader>())
353            .ok_or(Error::InvalidHeaderLength)?;
354        let mut buf = vec![0; len];
355
356        r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
357
358        let mut iter = buf.split_inclusive(|&c| c == b'\0');
359        let name = iter
360            .next()
361            .ok_or(Error::MissingParameter)
362            .and_then(bytes_to_path_component)?;
363        // `linkname` is a symlink target, which can contain `/` and `..` so we use `bytes_to_cstr`
364        // instead of `bytes_to_path_component`.
365        let linkname = iter
366            .next()
367            .ok_or(Error::MissingParameter)
368            .and_then(bytes_to_cstr)?;
369
370        let split_pos = name.to_bytes_with_nul().len() + linkname.to_bytes_with_nul().len();
371        let security_ctx = parse_selinux_xattr(&buf[split_pos..])?;
372
373        match self.fs.symlink(
374            Context::from(in_header),
375            linkname,
376            in_header.nodeid.into(),
377            name,
378            security_ctx,
379        ) {
380            Ok(entry) => {
381                let out = EntryOut::from(entry);
382
383                reply_ok(Some(out), None, in_header.unique, w)
384            }
385            Err(e) => reply_error(e, in_header.unique, w),
386        }
387    }
388
389    fn mknod<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
390        let MknodIn {
391            mode, rdev, umask, ..
392        } = r.read_struct()?;
393
394        let buflen = (in_header.len as usize)
395            .checked_sub(size_of::<InHeader>())
396            .and_then(|l| l.checked_sub(size_of::<MknodIn>()))
397            .ok_or(Error::InvalidHeaderLength)?;
398        let mut buf = vec![0; buflen];
399
400        r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
401
402        let mut iter = buf.split_inclusive(|&c| c == b'\0');
403        let name = iter
404            .next()
405            .ok_or(Error::MissingParameter)
406            .and_then(bytes_to_path_component)?;
407
408        let split_pos = name.to_bytes_with_nul().len();
409        let security_ctx = parse_selinux_xattr(&buf[split_pos..])?;
410
411        match self.fs.mknod(
412            Context::from(in_header),
413            in_header.nodeid.into(),
414            name,
415            mode,
416            rdev,
417            umask,
418            security_ctx,
419        ) {
420            Ok(entry) => {
421                let out = EntryOut::from(entry);
422
423                reply_ok(Some(out), None, in_header.unique, w)
424            }
425            Err(e) => reply_error(e, in_header.unique, w),
426        }
427    }
428
429    fn mkdir<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
430        let MkdirIn { mode, umask } = r.read_struct()?;
431
432        let buflen = (in_header.len as usize)
433            .checked_sub(size_of::<InHeader>())
434            .and_then(|l| l.checked_sub(size_of::<MkdirIn>()))
435            .ok_or(Error::InvalidHeaderLength)?;
436        let mut buf = vec![0; buflen];
437
438        r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
439
440        let mut iter = buf.split_inclusive(|&c| c == b'\0');
441        let name = iter
442            .next()
443            .ok_or(Error::MissingParameter)
444            .and_then(bytes_to_path_component)?;
445
446        let split_pos = name.to_bytes_with_nul().len();
447        let security_ctx = parse_selinux_xattr(&buf[split_pos..])?;
448
449        match self.fs.mkdir(
450            Context::from(in_header),
451            in_header.nodeid.into(),
452            name,
453            mode,
454            umask,
455            security_ctx,
456        ) {
457            Ok(entry) => {
458                let out = EntryOut::from(entry);
459
460                reply_ok(Some(out), None, in_header.unique, w)
461            }
462            Err(e) => reply_error(e, in_header.unique, w),
463        }
464    }
465
466    fn chromeos_tmpfile<R: Reader, W: Writer>(
467        &self,
468        in_header: InHeader,
469        mut r: R,
470        w: W,
471    ) -> Result<usize> {
472        let ChromeOsTmpfileIn { mode, umask } = r.read_struct()?;
473
474        let len = (in_header.len as usize)
475            .checked_sub(size_of::<InHeader>())
476            .and_then(|l| l.checked_sub(size_of::<ChromeOsTmpfileIn>()))
477            .ok_or(Error::InvalidHeaderLength)?;
478        let mut buf = vec![0; len];
479
480        r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
481
482        let security_ctx = parse_selinux_xattr(&buf)?;
483
484        match self.fs.chromeos_tmpfile(
485            Context::from(in_header),
486            in_header.nodeid.into(),
487            mode,
488            umask,
489            security_ctx,
490        ) {
491            Ok(entry) => {
492                let out = EntryOut::from(entry);
493
494                reply_ok(Some(out), None, in_header.unique, w)
495            }
496            Err(e) => reply_error(e, in_header.unique, w),
497        }
498    }
499
500    fn unlink<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
501        let namelen = (in_header.len as usize)
502            .checked_sub(size_of::<InHeader>())
503            .ok_or(Error::InvalidHeaderLength)?;
504        let mut name = vec![0; namelen];
505
506        r.read_exact(&mut name).map_err(Error::DecodeMessage)?;
507
508        match self.fs.unlink(
509            Context::from(in_header),
510            in_header.nodeid.into(),
511            bytes_to_path_component(&name)?,
512        ) {
513            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
514            Err(e) => reply_error(e, in_header.unique, w),
515        }
516    }
517
518    fn rmdir<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
519        let namelen = (in_header.len as usize)
520            .checked_sub(size_of::<InHeader>())
521            .ok_or(Error::InvalidHeaderLength)?;
522        let mut name = vec![0; namelen];
523
524        r.read_exact(&mut name).map_err(Error::DecodeMessage)?;
525
526        match self.fs.rmdir(
527            Context::from(in_header),
528            in_header.nodeid.into(),
529            bytes_to_path_component(&name)?,
530        ) {
531            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
532            Err(e) => reply_error(e, in_header.unique, w),
533        }
534    }
535
536    fn do_rename<R: Reader, W: Writer>(
537        &self,
538        in_header: InHeader,
539        msg_size: usize,
540        newdir: u64,
541        flags: u32,
542        mut r: R,
543        w: W,
544    ) -> Result<usize> {
545        let buflen = (in_header.len as usize)
546            .checked_sub(size_of::<InHeader>())
547            .and_then(|l| l.checked_sub(msg_size))
548            .ok_or(Error::InvalidHeaderLength)?;
549        let mut buf = vec![0; buflen];
550
551        r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
552
553        // We want to include the '\0' byte in the first slice.
554        let split_pos = buf
555            .iter()
556            .position(|c| *c == b'\0')
557            .map(|p| p + 1)
558            .ok_or(Error::MissingParameter)?;
559
560        let (oldname, newname) = buf.split_at(split_pos);
561
562        match self.fs.rename(
563            Context::from(in_header),
564            in_header.nodeid.into(),
565            bytes_to_path_component(oldname)?,
566            newdir.into(),
567            bytes_to_path_component(newname)?,
568            flags,
569        ) {
570            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
571            Err(e) => reply_error(e, in_header.unique, w),
572        }
573    }
574
575    fn rename<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
576        let RenameIn { newdir } = r.read_struct()?;
577
578        self.do_rename(in_header, size_of::<RenameIn>(), newdir, 0, r, w)
579    }
580
581    fn rename2<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
582        let Rename2In { newdir, flags, .. } = r.read_struct()?;
583
584        #[allow(clippy::unnecessary_cast)]
585        let flags = flags & (libc::RENAME_EXCHANGE | libc::RENAME_NOREPLACE) as u32;
586
587        self.do_rename(in_header, size_of::<Rename2In>(), newdir, flags, r, w)
588    }
589
590    fn link<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
591        let LinkIn { oldnodeid } = r.read_struct()?;
592
593        let namelen = (in_header.len as usize)
594            .checked_sub(size_of::<InHeader>())
595            .and_then(|l| l.checked_sub(size_of::<LinkIn>()))
596            .ok_or(Error::InvalidHeaderLength)?;
597        let mut name = vec![0; namelen];
598
599        r.read_exact(&mut name).map_err(Error::DecodeMessage)?;
600
601        match self.fs.link(
602            Context::from(in_header),
603            oldnodeid.into(),
604            in_header.nodeid.into(),
605            bytes_to_path_component(&name)?,
606        ) {
607            Ok(entry) => {
608                let out = EntryOut::from(entry);
609
610                reply_ok(Some(out), None, in_header.unique, w)
611            }
612            Err(e) => reply_error(e, in_header.unique, w),
613        }
614    }
615
616    fn open<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
617        let OpenIn { flags, .. } = r.read_struct()?;
618
619        match self
620            .fs
621            .open(Context::from(in_header), in_header.nodeid.into(), flags)
622        {
623            Ok((handle, opts)) => {
624                let out = OpenOut {
625                    fh: handle.map(Into::into).unwrap_or(0),
626                    open_flags: opts.bits(),
627                    ..Default::default()
628                };
629
630                reply_ok(Some(out), None, in_header.unique, w)
631            }
632            Err(e) => reply_error(e, in_header.unique, w),
633        }
634    }
635
636    fn read<R: Reader, W: ZeroCopyWriter + Writer>(
637        &self,
638        in_header: InHeader,
639        mut r: R,
640        mut w: W,
641    ) -> Result<usize> {
642        let ReadIn {
643            fh,
644            offset,
645            size,
646            read_flags,
647            lock_owner,
648            flags,
649            ..
650        } = r.read_struct()?;
651
652        if size > self.fs.max_buffer_size() {
653            return reply_error(
654                io::Error::from_raw_os_error(libc::ENOMEM),
655                in_header.unique,
656                w,
657            );
658        }
659
660        let owner = if read_flags & READ_LOCKOWNER != 0 {
661            Some(lock_owner)
662        } else {
663            None
664        };
665
666        // Skip for the header size to write the data first.
667        match w.write_at(size_of::<OutHeader>(), |writer| {
668            self.fs.read(
669                Context::from(in_header),
670                in_header.nodeid.into(),
671                fh.into(),
672                writer,
673                size,
674                offset,
675                owner,
676                flags,
677            )
678        }) {
679            Ok(count) => {
680                // Don't use `reply_ok` because we need to set a custom size length for the
681                // header.
682                let out = OutHeader {
683                    len: (size_of::<OutHeader>() + count) as u32,
684                    error: 0,
685                    unique: in_header.unique,
686                };
687
688                w.write_all(out.as_bytes()).map_err(Error::EncodeMessage)?;
689                w.flush().map_err(Error::FlushMessage)?;
690                Ok(out.len as usize)
691            }
692            Err(e) => reply_error(e, in_header.unique, w),
693        }
694    }
695
696    fn write<R: Reader + ZeroCopyReader, W: Writer>(
697        &self,
698        in_header: InHeader,
699        mut r: R,
700        w: W,
701    ) -> Result<usize> {
702        let WriteIn {
703            fh,
704            offset,
705            size,
706            write_flags,
707            lock_owner,
708            flags,
709            ..
710        } = r.read_struct()?;
711
712        if size > self.max_write {
713            return reply_error(
714                io::Error::from_raw_os_error(libc::ENOMEM),
715                in_header.unique,
716                w,
717            );
718        }
719
720        let owner = if write_flags & WRITE_LOCKOWNER != 0 {
721            Some(lock_owner)
722        } else {
723            None
724        };
725
726        let delayed_write = write_flags & WRITE_CACHE != 0;
727
728        match self.fs.write(
729            Context::from(in_header),
730            in_header.nodeid.into(),
731            fh.into(),
732            r,
733            size,
734            offset,
735            owner,
736            delayed_write,
737            flags,
738        ) {
739            Ok(count) => {
740                let out = WriteOut {
741                    size: count as u32,
742                    ..Default::default()
743                };
744
745                reply_ok(Some(out), None, in_header.unique, w)
746            }
747            Err(e) => reply_error(e, in_header.unique, w),
748        }
749    }
750
751    fn statfs<W: Writer>(&self, in_header: InHeader, w: W) -> Result<usize> {
752        match self
753            .fs
754            .statfs(Context::from(in_header), in_header.nodeid.into())
755        {
756            Ok(st) => reply_ok(Some(Kstatfs::from(st)), None, in_header.unique, w),
757            Err(e) => reply_error(e, in_header.unique, w),
758        }
759    }
760
761    fn release<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
762        let ReleaseIn {
763            fh,
764            flags,
765            release_flags,
766            lock_owner,
767        } = r.read_struct()?;
768
769        let flush = release_flags & RELEASE_FLUSH != 0;
770        let flock_release = release_flags & RELEASE_FLOCK_UNLOCK != 0;
771        let lock_owner = if flush || flock_release {
772            Some(lock_owner)
773        } else {
774            None
775        };
776
777        match self.fs.release(
778            Context::from(in_header),
779            in_header.nodeid.into(),
780            flags,
781            fh.into(),
782            flush,
783            flock_release,
784            lock_owner,
785        ) {
786            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
787            Err(e) => reply_error(e, in_header.unique, w),
788        }
789    }
790
791    fn fsync<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
792        let FsyncIn {
793            fh, fsync_flags, ..
794        } = r.read_struct()?;
795        let datasync = fsync_flags & 0x1 != 0;
796
797        match self.fs.fsync(
798            Context::from(in_header),
799            in_header.nodeid.into(),
800            datasync,
801            fh.into(),
802        ) {
803            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
804            Err(e) => reply_error(e, in_header.unique, w),
805        }
806    }
807
808    fn setxattr<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
809        let SetxattrIn { size, flags } = r.read_struct()?;
810
811        // The name and value and encoded one after another and separated by a '\0' character.
812        let len = (in_header.len as usize)
813            .checked_sub(size_of::<InHeader>())
814            .and_then(|l| l.checked_sub(size_of::<SetxattrIn>()))
815            .ok_or(Error::InvalidHeaderLength)?;
816        let mut buf = vec![0; len];
817
818        r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
819
820        // We want to include the '\0' byte in the first slice.
821        let split_pos = buf
822            .iter()
823            .position(|c| *c == b'\0')
824            .map(|p| p + 1)
825            .ok_or(Error::MissingParameter)?;
826
827        let (name, value) = buf.split_at(split_pos);
828
829        if size != value.len() as u32 {
830            return Err(Error::InvalidXattrSize(size, value.len()));
831        }
832
833        match self.fs.setxattr(
834            Context::from(in_header),
835            in_header.nodeid.into(),
836            // Extended attribute names are not path components, so we use `bytes_to_cstr`.
837            bytes_to_cstr(name)?,
838            value,
839            flags,
840        ) {
841            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
842            Err(e) => reply_error(e, in_header.unique, w),
843        }
844    }
845
846    fn getxattr<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
847        let GetxattrIn { size, .. } = r.read_struct()?;
848
849        let namelen = (in_header.len as usize)
850            .checked_sub(size_of::<InHeader>())
851            .and_then(|l| l.checked_sub(size_of::<GetxattrIn>()))
852            .ok_or(Error::InvalidHeaderLength)?;
853        let mut name = vec![0; namelen];
854
855        r.read_exact(&mut name).map_err(Error::DecodeMessage)?;
856
857        if size > self.fs.max_buffer_size() {
858            return reply_error(
859                io::Error::from_raw_os_error(libc::ENOMEM),
860                in_header.unique,
861                w,
862            );
863        }
864
865        match self.fs.getxattr(
866            Context::from(in_header),
867            in_header.nodeid.into(),
868            // Extended attribute names are not path components, so we use `bytes_to_cstr`.
869            bytes_to_cstr(&name)?,
870            size,
871        ) {
872            Ok(GetxattrReply::Value(val)) => reply_ok(None::<u8>, Some(&val), in_header.unique, w),
873            Ok(GetxattrReply::Count(count)) => {
874                let out = GetxattrOut {
875                    size: count,
876                    ..Default::default()
877                };
878
879                reply_ok(Some(out), None, in_header.unique, w)
880            }
881            Err(e) => reply_error(e, in_header.unique, w),
882        }
883    }
884
885    fn listxattr<R: Reader, W: Writer>(
886        &self,
887        in_header: InHeader,
888        mut r: R,
889        w: W,
890    ) -> Result<usize> {
891        let GetxattrIn { size, .. } = r.read_struct()?;
892
893        if size > self.fs.max_buffer_size() {
894            return reply_error(
895                io::Error::from_raw_os_error(libc::ENOMEM),
896                in_header.unique,
897                w,
898            );
899        }
900
901        match self
902            .fs
903            .listxattr(Context::from(in_header), in_header.nodeid.into(), size)
904        {
905            Ok(ListxattrReply::Names(val)) => reply_ok(None::<u8>, Some(&val), in_header.unique, w),
906            Ok(ListxattrReply::Count(count)) => {
907                let out = GetxattrOut {
908                    size: count,
909                    ..Default::default()
910                };
911
912                reply_ok(Some(out), None, in_header.unique, w)
913            }
914            Err(e) => reply_error(e, in_header.unique, w),
915        }
916    }
917
918    fn removexattr<R: Reader, W: Writer>(
919        &self,
920        in_header: InHeader,
921        mut r: R,
922        w: W,
923    ) -> Result<usize> {
924        let namelen = (in_header.len as usize)
925            .checked_sub(size_of::<InHeader>())
926            .ok_or(Error::InvalidHeaderLength)?;
927
928        let mut buf = vec![0; namelen];
929
930        r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
931
932        // Extended attribute names are not path components, so we use `bytes_to_cstr`.
933        let name = bytes_to_cstr(&buf)?;
934
935        match self
936            .fs
937            .removexattr(Context::from(in_header), in_header.nodeid.into(), name)
938        {
939            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
940            Err(e) => reply_error(e, in_header.unique, w),
941        }
942    }
943
944    fn flush<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
945        let FlushIn {
946            fh,
947            unused: _,
948            padding: _,
949            lock_owner,
950        } = r.read_struct()?;
951
952        match self.fs.flush(
953            Context::from(in_header),
954            in_header.nodeid.into(),
955            fh.into(),
956            lock_owner,
957        ) {
958            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
959            Err(e) => reply_error(e, in_header.unique, w),
960        }
961    }
962
963    fn init<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
964        cros_tracing::trace_simple_print!("fuse server: init: in_header={:?}", in_header);
965        let InitIn {
966            major,
967            minor,
968            max_readahead,
969            flags,
970        } = r.read_struct()?;
971
972        if major < KERNEL_VERSION {
973            error!("Unsupported fuse protocol version: {}.{}", major, minor);
974            return reply_error(
975                io::Error::from_raw_os_error(libc::EPROTO),
976                in_header.unique,
977                w,
978            );
979        }
980
981        if major > KERNEL_VERSION {
982            // Wait for the kernel to reply back with a 7.X version.
983            let out = InitOut {
984                major: KERNEL_VERSION,
985                minor: KERNEL_MINOR_VERSION,
986                ..Default::default()
987            };
988
989            return reply_ok(Some(out), None, in_header.unique, w);
990        }
991
992        if minor < OLDEST_SUPPORTED_KERNEL_MINOR_VERSION {
993            error!(
994                "Unsupported fuse protocol minor version: {}.{}",
995                major, minor
996            );
997            return reply_error(
998                io::Error::from_raw_os_error(libc::EPROTO),
999                in_header.unique,
1000                w,
1001            );
1002        }
1003
1004        let InitInExt { flags2, .. } =
1005            if (FsOptions::from_bits_truncate(u64::from(flags)) & FsOptions::INIT_EXT).is_empty() {
1006                InitInExt::default()
1007            } else {
1008                r.read_struct()?
1009            };
1010
1011        // These fuse features are supported by this server by default.
1012        let supported = FsOptions::ASYNC_READ
1013            | FsOptions::PARALLEL_DIROPS
1014            | FsOptions::BIG_WRITES
1015            | FsOptions::AUTO_INVAL_DATA
1016            | FsOptions::HANDLE_KILLPRIV
1017            | FsOptions::ASYNC_DIO
1018            | FsOptions::HAS_IOCTL_DIR
1019            | FsOptions::DO_READDIRPLUS
1020            | FsOptions::READDIRPLUS_AUTO
1021            | FsOptions::ATOMIC_O_TRUNC
1022            | FsOptions::MAX_PAGES
1023            | FsOptions::MAP_ALIGNMENT
1024            | FsOptions::INIT_EXT;
1025
1026        let capable = FsOptions::from_bits_truncate(u64::from(flags) | u64::from(flags2) << 32);
1027
1028        match self.fs.init(capable) {
1029            Ok(want) => {
1030                let mut enabled = capable & (want | supported);
1031
1032                // HANDLE_KILLPRIV doesn't work correctly when writeback caching is enabled so turn
1033                // it off.
1034                if enabled.contains(FsOptions::WRITEBACK_CACHE) {
1035                    enabled.remove(FsOptions::HANDLE_KILLPRIV);
1036                }
1037
1038                // ATOMIC_O_TRUNC doesn't work with ZERO_MESSAGE_OPEN.
1039                if enabled.contains(FsOptions::ZERO_MESSAGE_OPEN) {
1040                    enabled.remove(FsOptions::ATOMIC_O_TRUNC);
1041                }
1042
1043                let max_write = self.max_write;
1044                let max_pages = min(
1045                    max(max_readahead, max_write) / pagesize() as u32,
1046                    u16::MAX as u32,
1047                ) as u16;
1048                let out = InitOut {
1049                    major: KERNEL_VERSION,
1050                    minor: KERNEL_MINOR_VERSION,
1051                    max_readahead,
1052                    flags: enabled.bits() as u32,
1053                    max_background: u16::MAX,
1054                    congestion_threshold: (u16::MAX / 4) * 3,
1055                    max_write,
1056                    time_gran: 1, // nanoseconds
1057                    max_pages,
1058                    map_alignment: pagesize().trailing_zeros() as u16,
1059                    flags2: (enabled.bits() >> 32) as u32,
1060                    ..Default::default()
1061                };
1062
1063                reply_ok(Some(out), None, in_header.unique, w)
1064            }
1065            Err(e) => reply_error(e, in_header.unique, w),
1066        }
1067    }
1068
1069    fn opendir<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
1070        let OpenIn { flags, .. } = r.read_struct()?;
1071
1072        match self
1073            .fs
1074            .opendir(Context::from(in_header), in_header.nodeid.into(), flags)
1075        {
1076            Ok((handle, opts)) => {
1077                let out = OpenOut {
1078                    fh: handle.map(Into::into).unwrap_or(0),
1079                    open_flags: opts.bits(),
1080                    ..Default::default()
1081                };
1082
1083                reply_ok(Some(out), None, in_header.unique, w)
1084            }
1085            Err(e) => reply_error(e, in_header.unique, w),
1086        }
1087    }
1088
1089    fn readdir<R: Reader, W: Writer>(
1090        &self,
1091        in_header: InHeader,
1092        mut r: R,
1093        mut w: W,
1094    ) -> Result<usize> {
1095        let ReadIn {
1096            fh, offset, size, ..
1097        } = r.read_struct()?;
1098
1099        if size > self.fs.max_buffer_size() {
1100            return reply_error(
1101                io::Error::from_raw_os_error(libc::ENOMEM),
1102                in_header.unique,
1103                w,
1104            );
1105        }
1106
1107        if !size
1108            .checked_add(size_of::<OutHeader>() as u32)
1109            .is_some_and(|total| w.has_sufficient_buffer(total))
1110        {
1111            return reply_error(
1112                io::Error::from_raw_os_error(libc::ENOMEM),
1113                in_header.unique,
1114                w,
1115            );
1116        }
1117
1118        // Skip over enough bytes for the header.
1119        let unique = in_header.unique;
1120        let result = w.write_at(size_of::<OutHeader>(), |cursor| {
1121            match self.fs.readdir(
1122                Context::from(in_header),
1123                in_header.nodeid.into(),
1124                fh.into(),
1125                size,
1126                offset,
1127            ) {
1128                Ok(mut entries) => {
1129                    let mut total_written = 0;
1130                    while let Some(dirent) = entries.next() {
1131                        let remaining = (size as usize).saturating_sub(total_written);
1132                        match add_dirent(cursor, remaining, &dirent, None) {
1133                            // No more space left in the buffer.
1134                            Ok(0) => break,
1135                            Ok(bytes_written) => {
1136                                total_written += bytes_written;
1137                            }
1138                            Err(e) => return Err(e),
1139                        }
1140                    }
1141                    Ok(total_written)
1142                }
1143                Err(e) => Err(e),
1144            }
1145        });
1146
1147        match result {
1148            Ok(total_written) => reply_readdir(total_written, unique, w),
1149            Err(e) => reply_error(e, unique, w),
1150        }
1151    }
1152
1153    fn lookup_dirent_attribute(
1154        &self,
1155        in_header: &InHeader,
1156        dir_entry: &DirEntry,
1157    ) -> io::Result<Entry> {
1158        let parent = in_header.nodeid.into();
1159        let name = dir_entry.name.to_bytes();
1160        let entry = if name == b"." || name == b".." {
1161            // Don't do lookups on the current directory or the parent directory.
1162            // SAFETY: struct only contains integer fields and any value is valid.
1163            let mut attr = unsafe { MaybeUninit::<libc::stat64>::zeroed().assume_init() };
1164            attr.st_ino = dir_entry.ino;
1165            attr.st_mode = dir_entry.type_;
1166
1167            // We use 0 for the inode value to indicate a negative entry.
1168            Entry {
1169                inode: 0,
1170                generation: 0,
1171                attr,
1172                attr_timeout: Duration::from_secs(0),
1173                entry_timeout: Duration::from_secs(0),
1174            }
1175        } else {
1176            self.fs
1177                .lookup(Context::from(*in_header), parent, dir_entry.name)?
1178        };
1179
1180        Ok(entry)
1181    }
1182
1183    fn readdirplus<R: Reader, W: Writer>(
1184        &self,
1185        in_header: InHeader,
1186        mut r: R,
1187        mut w: W,
1188    ) -> Result<usize> {
1189        cros_tracing::trace_simple_print!("fuse server: readdirplus: in_header={:?}", in_header);
1190        let ReadIn {
1191            fh, offset, size, ..
1192        } = r.read_struct()?;
1193
1194        if size > self.fs.max_buffer_size() {
1195            return reply_error(
1196                io::Error::from_raw_os_error(libc::ENOMEM),
1197                in_header.unique,
1198                w,
1199            );
1200        }
1201
1202        if !size
1203            .checked_add(size_of::<OutHeader>() as u32)
1204            .is_some_and(|total| w.has_sufficient_buffer(total))
1205        {
1206            return reply_error(
1207                io::Error::from_raw_os_error(libc::ENOMEM),
1208                in_header.unique,
1209                w,
1210            );
1211        }
1212
1213        // Skip over enough bytes for the header.
1214        let unique = in_header.unique;
1215        let result = w.write_at(size_of::<OutHeader>(), |cursor| {
1216            match self.fs.readdir(
1217                Context::from(in_header),
1218                in_header.nodeid.into(),
1219                fh.into(),
1220                size,
1221                offset,
1222            ) {
1223                Ok(mut entries) => {
1224                    let mut total_written = 0;
1225                    while let Some(dirent) = entries.next() {
1226                        let mut entry_inode = None;
1227                        let dirent_result = self
1228                            .lookup_dirent_attribute(&in_header, &dirent)
1229                            .and_then(|e| {
1230                                entry_inode = Some(e.inode);
1231                                let remaining = (size as usize).saturating_sub(total_written);
1232                                add_dirent(cursor, remaining, &dirent, Some(e))
1233                            });
1234
1235                        match dirent_result {
1236                            Ok(0) => {
1237                                // No more space left in the buffer but we need to undo the lookup
1238                                // that created the Entry or we will end up with mismatched lookup
1239                                // counts.
1240                                if let Some(inode) = entry_inode {
1241                                    self.fs.forget(Context::from(in_header), inode.into(), 1);
1242                                }
1243                                break;
1244                            }
1245                            Ok(bytes_written) => {
1246                                total_written += bytes_written;
1247                            }
1248                            Err(e) => {
1249                                if let Some(inode) = entry_inode {
1250                                    self.fs.forget(Context::from(in_header), inode.into(), 1);
1251                                }
1252
1253                                if total_written == 0 {
1254                                    // We haven't filled any entries yet so we can just propagate
1255                                    // the error.
1256                                    return Err(e);
1257                                }
1258
1259                                // We already filled in some entries. Returning an error now will
1260                                // cause lookup count mismatches for those entries so just return
1261                                // whatever we already have.
1262                                break;
1263                            }
1264                        }
1265                    }
1266                    Ok(total_written)
1267                }
1268                Err(e) => Err(e),
1269            }
1270        });
1271
1272        match result {
1273            Ok(total_written) => reply_readdir(total_written, unique, w),
1274            Err(e) => reply_error(e, unique, w),
1275        }
1276    }
1277
1278    fn releasedir<R: Reader, W: Writer>(
1279        &self,
1280        in_header: InHeader,
1281        mut r: R,
1282        w: W,
1283    ) -> Result<usize> {
1284        let ReleaseIn { fh, flags, .. } = r.read_struct()?;
1285
1286        match self.fs.releasedir(
1287            Context::from(in_header),
1288            in_header.nodeid.into(),
1289            flags,
1290            fh.into(),
1291        ) {
1292            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
1293            Err(e) => reply_error(e, in_header.unique, w),
1294        }
1295    }
1296
1297    fn fsyncdir<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
1298        let FsyncIn {
1299            fh, fsync_flags, ..
1300        } = r.read_struct()?;
1301        let datasync = fsync_flags & 0x1 != 0;
1302
1303        match self.fs.fsyncdir(
1304            Context::from(in_header),
1305            in_header.nodeid.into(),
1306            datasync,
1307            fh.into(),
1308        ) {
1309            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
1310            Err(e) => reply_error(e, in_header.unique, w),
1311        }
1312    }
1313
1314    fn getlk<R: Reader, W: Writer>(&self, in_header: InHeader, mut _r: R, w: W) -> Result<usize> {
1315        if let Err(e) = self.fs.getlk() {
1316            reply_error(e, in_header.unique, w)
1317        } else {
1318            Ok(0)
1319        }
1320    }
1321
1322    fn setlk<R: Reader, W: Writer>(&self, in_header: InHeader, mut _r: R, w: W) -> Result<usize> {
1323        if let Err(e) = self.fs.setlk() {
1324            reply_error(e, in_header.unique, w)
1325        } else {
1326            Ok(0)
1327        }
1328    }
1329
1330    fn setlkw<R: Reader, W: Writer>(&self, in_header: InHeader, mut _r: R, w: W) -> Result<usize> {
1331        if let Err(e) = self.fs.setlkw() {
1332            reply_error(e, in_header.unique, w)
1333        } else {
1334            Ok(0)
1335        }
1336    }
1337
1338    fn access<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
1339        let AccessIn { mask, .. } = r.read_struct()?;
1340
1341        match self
1342            .fs
1343            .access(Context::from(in_header), in_header.nodeid.into(), mask)
1344        {
1345            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
1346            Err(e) => reply_error(e, in_header.unique, w),
1347        }
1348    }
1349
1350    fn create<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
1351        let CreateIn {
1352            flags, mode, umask, ..
1353        } = r.read_struct()?;
1354
1355        let buflen = (in_header.len as usize)
1356            .checked_sub(size_of::<InHeader>())
1357            .and_then(|l| l.checked_sub(size_of::<CreateIn>()))
1358            .ok_or(Error::InvalidHeaderLength)?;
1359
1360        let mut buf = vec![0; buflen];
1361
1362        r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
1363
1364        let mut iter = buf.split_inclusive(|&c| c == b'\0');
1365        let name = iter
1366            .next()
1367            .ok_or(Error::MissingParameter)
1368            .and_then(bytes_to_path_component)?;
1369
1370        let split_pos = name.to_bytes_with_nul().len();
1371        let security_ctx = parse_selinux_xattr(&buf[split_pos..])?;
1372
1373        match self.fs.create(
1374            Context::from(in_header),
1375            in_header.nodeid.into(),
1376            name,
1377            mode,
1378            flags,
1379            umask,
1380            security_ctx,
1381        ) {
1382            Ok((entry, handle, opts)) => {
1383                let entry_out = EntryOut {
1384                    nodeid: entry.inode,
1385                    generation: entry.generation,
1386                    entry_valid: entry.entry_timeout.as_secs(),
1387                    attr_valid: entry.attr_timeout.as_secs(),
1388                    entry_valid_nsec: entry.entry_timeout.subsec_nanos(),
1389                    attr_valid_nsec: entry.attr_timeout.subsec_nanos(),
1390                    attr: entry.attr.into(),
1391                };
1392                let open_out = OpenOut {
1393                    fh: handle.map(Into::into).unwrap_or(0),
1394                    open_flags: opts.bits(),
1395                    ..Default::default()
1396                };
1397
1398                // Kind of a hack to write both structs.
1399                reply_ok(
1400                    Some(entry_out),
1401                    Some(open_out.as_bytes()),
1402                    in_header.unique,
1403                    w,
1404                )
1405            }
1406            Err(e) => reply_error(e, in_header.unique, w),
1407        }
1408    }
1409
1410    #[allow(clippy::unnecessary_wraps)]
1411    fn interrupt(&self, _in_header: InHeader) -> Result<usize> {
1412        Ok(0)
1413    }
1414
1415    fn bmap<R: Reader, W: Writer>(&self, in_header: InHeader, mut _r: R, w: W) -> Result<usize> {
1416        if let Err(e) = self.fs.bmap() {
1417            reply_error(e, in_header.unique, w)
1418        } else {
1419            Ok(0)
1420        }
1421    }
1422
1423    #[allow(clippy::unnecessary_wraps)]
1424    fn destroy(&self) -> Result<usize> {
1425        // No reply to this function.
1426        self.fs.destroy();
1427
1428        Ok(0)
1429    }
1430
1431    fn ioctl<R: Reader, W: Writer>(&self, in_header: InHeader, mut r: R, w: W) -> Result<usize> {
1432        let IoctlIn {
1433            fh,
1434            flags,
1435            cmd,
1436            arg,
1437            in_size,
1438            out_size,
1439        } = r.read_struct()?;
1440
1441        let res = self.fs.ioctl(
1442            in_header.into(),
1443            in_header.nodeid.into(),
1444            fh.into(),
1445            IoctlFlags::from_bits_truncate(flags),
1446            cmd,
1447            arg,
1448            in_size,
1449            out_size,
1450            r,
1451        );
1452
1453        match res {
1454            Ok(reply) => match reply {
1455                IoctlReply::Retry { input, output } => {
1456                    retry_ioctl(in_header.unique, input, output, w)
1457                }
1458                IoctlReply::Done(res) => finish_ioctl(in_header.unique, res, w),
1459            },
1460            Err(e) => reply_error(e, in_header.unique, w),
1461        }
1462    }
1463
1464    fn poll<R: Reader, W: Writer>(&self, in_header: InHeader, mut _r: R, w: W) -> Result<usize> {
1465        if let Err(e) = self.fs.poll() {
1466            reply_error(e, in_header.unique, w)
1467        } else {
1468            Ok(0)
1469        }
1470    }
1471
1472    fn notify_reply<R: Reader, W: Writer>(
1473        &self,
1474        in_header: InHeader,
1475        mut _r: R,
1476        w: W,
1477    ) -> Result<usize> {
1478        if let Err(e) = self.fs.notify_reply() {
1479            reply_error(e, in_header.unique, w)
1480        } else {
1481            Ok(0)
1482        }
1483    }
1484
1485    fn batch_forget<R: Reader, W: Writer>(
1486        &self,
1487        in_header: InHeader,
1488        mut r: R,
1489        w: W,
1490    ) -> Result<usize> {
1491        let BatchForgetIn { count, .. } = r.read_struct()?;
1492
1493        if let Some(size) = (count as usize).checked_mul(size_of::<ForgetOne>()) {
1494            if size > self.fs.max_buffer_size() as usize {
1495                return reply_error(
1496                    io::Error::from_raw_os_error(libc::ENOMEM),
1497                    in_header.unique,
1498                    w,
1499                );
1500            }
1501        } else {
1502            return reply_error(
1503                io::Error::from_raw_os_error(libc::EOVERFLOW),
1504                in_header.unique,
1505                w,
1506            );
1507        }
1508
1509        let mut requests = Vec::with_capacity(count as usize);
1510        for _ in 0..count {
1511            let f: ForgetOne = r.read_struct()?;
1512            requests.push((f.nodeid.into(), f.nlookup));
1513        }
1514
1515        self.fs.batch_forget(Context::from(in_header), requests);
1516
1517        // No reply for forget messages.
1518        Ok(0)
1519    }
1520
1521    fn fallocate<R: Reader, W: Writer>(
1522        &self,
1523        in_header: InHeader,
1524        mut r: R,
1525        w: W,
1526    ) -> Result<usize> {
1527        let FallocateIn {
1528            fh,
1529            offset,
1530            length,
1531            mode,
1532            ..
1533        } = r.read_struct()?;
1534
1535        match self.fs.fallocate(
1536            Context::from(in_header),
1537            in_header.nodeid.into(),
1538            fh.into(),
1539            mode,
1540            offset,
1541            length,
1542        ) {
1543            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
1544            Err(e) => reply_error(e, in_header.unique, w),
1545        }
1546    }
1547
1548    fn lseek<R: Reader, W: Writer>(&self, in_header: InHeader, mut _r: R, w: W) -> Result<usize> {
1549        if let Err(e) = self.fs.lseek() {
1550            reply_error(e, in_header.unique, w)
1551        } else {
1552            Ok(0)
1553        }
1554    }
1555
1556    fn copy_file_range<R: Reader, W: Writer>(
1557        &self,
1558        in_header: InHeader,
1559        mut r: R,
1560        w: W,
1561    ) -> Result<usize> {
1562        let CopyFileRangeIn {
1563            fh_src,
1564            off_src,
1565            nodeid_dst,
1566            fh_dst,
1567            off_dst,
1568            len,
1569            flags,
1570        } = r.read_struct()?;
1571
1572        match self.fs.copy_file_range(
1573            Context::from(in_header),
1574            in_header.nodeid.into(),
1575            fh_src.into(),
1576            off_src,
1577            nodeid_dst.into(),
1578            fh_dst.into(),
1579            off_dst,
1580            len,
1581            flags,
1582        ) {
1583            Ok(count) => {
1584                let out = WriteOut {
1585                    size: count as u32,
1586                    ..Default::default()
1587                };
1588
1589                reply_ok(Some(out), None, in_header.unique, w)
1590            }
1591            Err(e) => reply_error(e, in_header.unique, w),
1592        }
1593    }
1594
1595    fn set_up_mapping<R, W, M>(
1596        &self,
1597        in_header: InHeader,
1598        mut r: R,
1599        w: W,
1600        mapper: M,
1601    ) -> Result<usize>
1602    where
1603        R: Reader,
1604        W: Writer,
1605        M: Mapper,
1606    {
1607        let SetUpMappingIn {
1608            fh,
1609            foffset,
1610            len,
1611            flags,
1612            moffset,
1613        } = r.read_struct()?;
1614        let flags = SetUpMappingFlags::from_bits_truncate(flags);
1615
1616        let mut prot = 0;
1617        if flags.contains(SetUpMappingFlags::READ) {
1618            prot |= libc::PROT_READ as u32;
1619        }
1620        if flags.contains(SetUpMappingFlags::WRITE) {
1621            prot |= libc::PROT_WRITE as u32;
1622        }
1623
1624        let size = if let Ok(s) = len.try_into() {
1625            s
1626        } else {
1627            return reply_error(
1628                io::Error::from_raw_os_error(libc::EOVERFLOW),
1629                in_header.unique,
1630                w,
1631            );
1632        };
1633
1634        match self.fs.set_up_mapping(
1635            Context::from(in_header),
1636            in_header.nodeid.into(),
1637            fh.into(),
1638            foffset,
1639            moffset,
1640            size,
1641            prot,
1642            mapper,
1643        ) {
1644            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
1645            Err(e) => {
1646                error!("set_up_mapping failed: {}", e);
1647                reply_error(e, in_header.unique, w)
1648            }
1649        }
1650    }
1651
1652    fn remove_mapping<R, W, M>(
1653        &self,
1654        in_header: InHeader,
1655        mut r: R,
1656        w: W,
1657        mapper: M,
1658    ) -> Result<usize>
1659    where
1660        R: Reader,
1661        W: Writer,
1662        M: Mapper,
1663    {
1664        let RemoveMappingIn { count } = r.read_struct()?;
1665
1666        // `FUSE_REMOVEMAPPING_MAX_ENTRY` is defined as
1667        // `PAGE_SIZE / sizeof(struct fuse_removemapping_one)` in /kernel/include/uapi/linux/fuse.h.
1668        let max_entry = pagesize() / std::mem::size_of::<RemoveMappingOne>();
1669
1670        if max_entry < count as usize {
1671            return reply_error(
1672                io::Error::from_raw_os_error(libc::EINVAL),
1673                in_header.unique,
1674                w,
1675            );
1676        }
1677
1678        let mut msgs = Vec::with_capacity(count as usize);
1679        for _ in 0..(count as usize) {
1680            let msg: RemoveMappingOne = r.read_struct()?;
1681            msgs.push(msg);
1682        }
1683
1684        match self.fs.remove_mapping(&msgs, mapper) {
1685            Ok(()) => reply_ok(None::<u8>, None, in_header.unique, w),
1686            Err(e) => reply_error(e, in_header.unique, w),
1687        }
1688    }
1689
1690    fn open_atomic<R: Reader, W: Writer>(
1691        &self,
1692        in_header: InHeader,
1693        mut r: R,
1694        w: W,
1695    ) -> Result<usize> {
1696        let CreateIn {
1697            flags, mode, umask, ..
1698        } = r.read_struct()?;
1699
1700        let buflen = (in_header.len as usize)
1701            .checked_sub(size_of::<InHeader>())
1702            .and_then(|l| l.checked_sub(size_of::<CreateIn>()))
1703            .ok_or(Error::InvalidHeaderLength)?;
1704
1705        let mut buf = vec![0; buflen];
1706
1707        r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
1708
1709        let mut iter = buf.split_inclusive(|&c| c == b'\0');
1710        let name = iter
1711            .next()
1712            .ok_or(Error::MissingParameter)
1713            .and_then(bytes_to_path_component)?;
1714
1715        let split_pos = name.to_bytes_with_nul().len();
1716        let security_ctx = parse_selinux_xattr(&buf[split_pos..])?;
1717
1718        match self.fs.atomic_open(
1719            Context::from(in_header),
1720            in_header.nodeid.into(),
1721            name,
1722            mode,
1723            flags,
1724            umask,
1725            security_ctx,
1726        ) {
1727            Ok((entry, handle, opts)) => {
1728                let entry_out = EntryOut {
1729                    nodeid: entry.inode,
1730                    generation: entry.generation,
1731                    entry_valid: entry.entry_timeout.as_secs(),
1732                    attr_valid: entry.attr_timeout.as_secs(),
1733                    entry_valid_nsec: entry.entry_timeout.subsec_nanos(),
1734                    attr_valid_nsec: entry.attr_timeout.subsec_nanos(),
1735                    attr: entry.attr.into(),
1736                };
1737                let open_out = OpenOut {
1738                    fh: handle.map(Into::into).unwrap_or(0),
1739                    open_flags: opts.bits(),
1740                    ..Default::default()
1741                };
1742
1743                // open_out passed the `data` argument, but the two out structs are independent
1744                // This is a hack to return two out stucts in one fuse reply
1745                reply_ok(
1746                    Some(entry_out),
1747                    Some(open_out.as_bytes()),
1748                    in_header.unique,
1749                    w,
1750                )
1751            }
1752            Err(e) => reply_error(e, in_header.unique, w),
1753        }
1754    }
1755}
1756
1757fn retry_ioctl<W: Writer>(
1758    unique: u64,
1759    input: Vec<IoctlIovec>,
1760    output: Vec<IoctlIovec>,
1761    mut w: W,
1762) -> Result<usize> {
1763    // We don't need to check for overflow here because if adding these 2 values caused an overflow
1764    // we would have run out of memory before reaching this point.
1765    if input.len() + output.len() > IOCTL_MAX_IOV {
1766        return Err(Error::TooManyIovecs(
1767            input.len() + output.len(),
1768            IOCTL_MAX_IOV,
1769        ));
1770    }
1771
1772    let len = size_of::<OutHeader>()
1773        + size_of::<IoctlOut>()
1774        + (input.len() * size_of::<IoctlIovec>())
1775        + (output.len() * size_of::<IoctlIovec>());
1776    let header = OutHeader {
1777        len: len as u32,
1778        error: 0,
1779        unique,
1780    };
1781    let out = IoctlOut {
1782        result: 0,
1783        flags: IoctlFlags::RETRY.bits(),
1784        in_iovs: input.len() as u32,
1785        out_iovs: output.len() as u32,
1786    };
1787
1788    let mut total_bytes = size_of::<OutHeader>() + size_of::<IoctlOut>();
1789    w.write_all(header.as_bytes())
1790        .map_err(Error::EncodeMessage)?;
1791    w.write_all(out.as_bytes()).map_err(Error::EncodeMessage)?;
1792    for i in input.into_iter().chain(output.into_iter()) {
1793        total_bytes += i.as_bytes().len();
1794        w.write_all(i.as_bytes()).map_err(Error::EncodeMessage)?;
1795    }
1796
1797    w.flush().map_err(Error::FlushMessage)?;
1798    debug_assert_eq!(len, total_bytes);
1799    Ok(len)
1800}
1801
1802fn finish_ioctl<W: Writer>(unique: u64, res: io::Result<Vec<u8>>, w: W) -> Result<usize> {
1803    let (out, data) = match res {
1804        Ok(data) => {
1805            let out = IoctlOut {
1806                result: 0,
1807                ..Default::default()
1808            };
1809            (out, Some(data))
1810        }
1811        Err(e) => {
1812            let out = IoctlOut {
1813                result: -e.raw_os_error().unwrap_or(libc::EIO),
1814                ..Default::default()
1815            };
1816            (out, None)
1817        }
1818    };
1819    reply_ok(Some(out), data.as_ref().map(|d| &d[..]), unique, w)
1820}
1821
1822fn reply_readdir<W: Writer>(len: usize, unique: u64, mut w: W) -> Result<usize> {
1823    let out = OutHeader {
1824        len: (size_of::<OutHeader>() + len) as u32,
1825        error: 0,
1826        unique,
1827    };
1828
1829    w.write_all(out.as_bytes()).map_err(Error::EncodeMessage)?;
1830    w.flush().map_err(Error::FlushMessage)?;
1831    Ok(out.len as usize)
1832}
1833
1834fn reply_ok<T: IntoBytes + Immutable, W: Writer>(
1835    out: Option<T>,
1836    data: Option<&[u8]>,
1837    unique: u64,
1838    mut w: W,
1839) -> Result<usize> {
1840    let mut len = size_of::<OutHeader>();
1841
1842    if out.is_some() {
1843        len += size_of::<T>();
1844    }
1845
1846    if let Some(data) = data {
1847        len += data.len();
1848    }
1849
1850    let header = OutHeader {
1851        len: len as u32,
1852        error: 0,
1853        unique,
1854    };
1855
1856    let mut total_bytes = size_of::<OutHeader>();
1857    w.write_all(header.as_bytes())
1858        .map_err(Error::EncodeMessage)?;
1859
1860    if let Some(out) = out {
1861        total_bytes += out.as_bytes().len();
1862        w.write_all(out.as_bytes()).map_err(Error::EncodeMessage)?;
1863    }
1864
1865    if let Some(data) = data {
1866        total_bytes += data.len();
1867        w.write_all(data).map_err(Error::EncodeMessage)?;
1868    }
1869
1870    w.flush().map_err(Error::FlushMessage)?;
1871    debug_assert_eq!(len, total_bytes);
1872    Ok(len)
1873}
1874
1875fn reply_error<W: Writer>(e: io::Error, unique: u64, mut w: W) -> Result<usize> {
1876    let header = OutHeader {
1877        len: size_of::<OutHeader>() as u32,
1878        error: -e.raw_os_error().unwrap_or(libc::EIO),
1879        unique,
1880    };
1881
1882    w.write_all(header.as_bytes())
1883        .map_err(Error::EncodeMessage)?;
1884    w.flush().map_err(Error::FlushMessage)?;
1885
1886    Ok(header.len as usize)
1887}
1888
1889/// Converts a byte buffer to a `CStr` without validating path components.
1890///
1891/// Use `bytes_to_path_component` instead if the input is a path component.
1892fn bytes_to_cstr(buf: &[u8]) -> Result<&CStr> {
1893    // Convert to a `CStr` first so that we can drop the '\0' byte at the end
1894    // and make sure there are no interior '\0' bytes.
1895    CStr::from_bytes_with_nul(buf).map_err(Error::InvalidCString)
1896}
1897
1898fn is_safe_name(name: &CStr) -> bool {
1899    let bytes = name.to_bytes();
1900    if bytes == b".." || bytes.contains(&b'/') {
1901        return false;
1902    }
1903    true
1904}
1905
1906fn bytes_to_path_component(buf: &[u8]) -> Result<&CStr> {
1907    let name = bytes_to_cstr(buf)?;
1908    if !is_safe_name(name) {
1909        return Err(Error::DecodeMessage(io::Error::from_raw_os_error(
1910            libc::EINVAL,
1911        )));
1912    }
1913    Ok(name)
1914}
1915
1916fn add_dirent<W: Writer>(
1917    cursor: &mut W,
1918    max: usize,
1919    d: &DirEntry,
1920    entry: Option<Entry>,
1921) -> io::Result<usize> {
1922    // Strip the trailing '\0'.
1923    let name = d.name.to_bytes();
1924    if name.len() > u32::MAX as usize {
1925        return Err(io::Error::from_raw_os_error(libc::EOVERFLOW));
1926    }
1927
1928    let dirent_len = size_of::<Dirent>()
1929        .checked_add(name.len())
1930        .ok_or_else(|| io::Error::from_raw_os_error(libc::EOVERFLOW))?;
1931
1932    // Directory entries must be padded to 8-byte alignment.  If adding 7 causes
1933    // an overflow then this dirent cannot be properly padded.
1934    let padded_dirent_len = dirent_len
1935        .checked_add(7)
1936        .map(|l| l & !7)
1937        .ok_or_else(|| io::Error::from_raw_os_error(libc::EOVERFLOW))?;
1938
1939    let total_len = if entry.is_some() {
1940        padded_dirent_len
1941            .checked_add(size_of::<EntryOut>())
1942            .ok_or_else(|| io::Error::from_raw_os_error(libc::EOVERFLOW))?
1943    } else {
1944        padded_dirent_len
1945    };
1946
1947    if max < total_len {
1948        Ok(0)
1949    } else {
1950        if let Some(entry) = entry {
1951            cursor.write_all(EntryOut::from(entry).as_bytes())?;
1952        }
1953
1954        let dirent = Dirent {
1955            ino: d.ino,
1956            off: d.offset,
1957            namelen: name.len() as u32,
1958            type_: d.type_,
1959        };
1960
1961        cursor.write_all(dirent.as_bytes())?;
1962        cursor.write_all(name)?;
1963
1964        // We know that `dirent_len` <= `padded_dirent_len` due to the check above
1965        // so there's no need for checked arithmetic.
1966        let padding = padded_dirent_len - dirent_len;
1967        if padding > 0 {
1968            cursor.write_all(&DIRENT_PADDING[..padding])?;
1969        }
1970
1971        Ok(total_len)
1972    }
1973}
1974
1975/// Parses the value of the desired attribute from the FUSE request input and returns it as an
1976/// `Ok(CStr)`. Returns `Ok(None)` if `buf` is empty or appears to be a valid request extension that
1977/// does not contain any security context information.
1978///
1979/// # Arguments
1980///
1981/// * `buf` - a byte array that contains the contents following any expected byte string parameters
1982///   of the FUSE request from the server. It begins with a struct `SecctxHeader`, and then the
1983///   subsequent entry is a struct `Secctx` followed by a nul-terminated string with the xattribute
1984///   name and then another nul-terminated string with the value for that xattr.
1985///
1986/// # Errors
1987///
1988/// * `Error::InvalidHeaderLength` - indicates that there is an inconsistency between the size of
1989///   the data read from `buf` and the stated `size` of the `SecctxHeader`, the respective `Secctx`
1990///   struct, or `buf` itself.
1991/// * `Error::DecodeMessage` - indicates that the expected structs cannot be read from `buf`.
1992/// * `Error::MissingParameter` - indicates that either a security context `name` or `value` is
1993///   missing from a security context entry.
1994fn parse_selinux_xattr(buf: &[u8]) -> Result<Option<&CStr>> {
1995    // Return early if request was not followed by context information
1996    if buf.is_empty() {
1997        return Ok(None);
1998    } else if buf.len() < size_of::<SecctxHeader>() {
1999        return Err(Error::InvalidHeaderLength);
2000    }
2001
2002    // Because the security context data block may have been preceded by variable-length strings,
2003    // `SecctxHeader` and the subsequent `Secctx` structs may not be correctly byte-aligned
2004    // within `buf`.
2005    let (secctx_header, _) = SecctxHeader::read_from_prefix(buf)
2006        .map_err(|_| Error::DecodeMessage(io::Error::from_raw_os_error(libc::EINVAL)))?;
2007
2008    // FUSE 7.38 introduced a generic request extension with the same structure as  `SecctxHeader`.
2009    // A `nr_secctx` value above `MAX_NR_SECCTX` indicates that this data block does not contain
2010    // any security context information.
2011    if secctx_header.nr_secctx > MAX_NR_SECCTX {
2012        return Ok(None);
2013    }
2014
2015    let mut cur_secctx_pos = size_of::<SecctxHeader>();
2016    let mut selinux_value = None;
2017    for _ in 0..secctx_header.nr_secctx {
2018        // `SecctxHeader.size` denotes the total size for the `SecctxHeader`, each of the
2019        // `nr_secctx` `Secctx` structs along with the corresponding context name and value,
2020        // and any additional padding.
2021        if (cur_secctx_pos + size_of::<Secctx>()) > buf.len()
2022            || (cur_secctx_pos + size_of::<Secctx>()) > secctx_header.size as usize
2023        {
2024            return Err(Error::InvalidHeaderLength);
2025        }
2026
2027        let secctx =
2028            Secctx::read_from_bytes(&buf[cur_secctx_pos..(cur_secctx_pos + size_of::<Secctx>())])
2029                .map_err(|_| Error::DecodeMessage(io::Error::from_raw_os_error(libc::EINVAL)))?;
2030
2031        cur_secctx_pos += size_of::<Secctx>();
2032
2033        // Extended attribute names and values are not path components, so we use `bytes_to_cstr`.
2034        let mut secctx_data = buf[cur_secctx_pos..]
2035            .split_inclusive(|&c| c == b'\0')
2036            .map(bytes_to_cstr);
2037        let name = secctx_data.next().ok_or(Error::MissingParameter)??;
2038        let value = secctx_data.next().ok_or(Error::MissingParameter)??;
2039
2040        cur_secctx_pos += name.to_bytes_with_nul().len() + value.to_bytes_with_nul().len();
2041        if cur_secctx_pos > secctx_header.size as usize {
2042            return Err(Error::InvalidHeaderLength);
2043        }
2044
2045        // `Secctx.size` contains the size of the security context value (not including the
2046        // corresponding context name).
2047        if value.to_bytes_with_nul().len() as u32 != secctx.size {
2048            return Err(Error::InvalidHeaderLength);
2049        }
2050
2051        if selinux_value.is_none() && name.to_bytes_with_nul() == SELINUX_XATTR_CSTR {
2052            selinux_value = Some(value);
2053        }
2054    }
2055
2056    // `SecctxHeader.size` is always the total size of the security context data padded to an
2057    // 8-byte alignment. If adding 7 causes an overflow, then the `size` field of our header
2058    // is invalid, so we should return an error.
2059    let padded_secctx_size = cur_secctx_pos
2060        .checked_next_multiple_of(8)
2061        .ok_or(Error::InvalidHeaderLength)?;
2062    if padded_secctx_size != secctx_header.size as usize {
2063        return Err(Error::InvalidHeaderLength);
2064    }
2065
2066    // If none of the `nr_secctx` attributes we parsed had a `name` matching `SELINUX_XATTR_CSTR`,
2067    // this returns `Ok(None)` to indicate that the security context data block was valid but there
2068    // was no specified selinux label attached to this request.
2069    Ok(selinux_value)
2070}
2071
2072#[cfg(test)]
2073mod tests {
2074    use super::*;
2075
2076    fn create_secctx(ctxs: &[(&[u8], &[u8])], size_truncation: u32) -> Vec<u8> {
2077        let nr_secctx = ctxs.len();
2078        let total_size = (size_of::<SecctxHeader>() as u32
2079            + (size_of::<Secctx>() * nr_secctx) as u32
2080            + ctxs
2081                .iter()
2082                .fold(0, |s, &(n, v)| s + n.len() as u32 + v.len() as u32))
2083        .checked_add(7)
2084        .map(|l| l & !7)
2085        .expect("total_size padded to 8-byte boundary")
2086        .checked_sub(size_truncation)
2087        .expect("size truncated by bytes < total_size");
2088
2089        let ctx_data: Vec<_> = ctxs
2090            .iter()
2091            .map(|(n, v)| {
2092                [
2093                    Secctx {
2094                        size: v.len() as u32,
2095                        padding: 0,
2096                    }
2097                    .as_bytes(),
2098                    n,
2099                    v,
2100                ]
2101                .concat()
2102            })
2103            .collect::<Vec<_>>()
2104            .concat();
2105
2106        [
2107            SecctxHeader {
2108                size: total_size,
2109                nr_secctx: nr_secctx as u32,
2110            }
2111            .as_bytes(),
2112            ctx_data.as_slice(),
2113        ]
2114        .concat()
2115    }
2116
2117    #[test]
2118    fn parse_selinux_xattr_empty() {
2119        let v: Vec<u8> = vec![];
2120        let res = parse_selinux_xattr(&v);
2121        assert_eq!(res.unwrap(), None);
2122    }
2123
2124    #[test]
2125    fn parse_selinux_xattr_basic() {
2126        let sec_value = c"user_u:object_r:security_type:s0";
2127        let v = create_secctx(&[(SELINUX_XATTR_CSTR, sec_value.to_bytes_with_nul())], 0);
2128
2129        let res = parse_selinux_xattr(&v);
2130        assert_eq!(res.unwrap(), Some(sec_value));
2131    }
2132
2133    #[test]
2134    fn parse_selinux_xattr_find_attr() {
2135        let foo_value = c"user_foo:object_foo:foo_type:s0";
2136        let sec_value = c"user_u:object_r:security_type:s0";
2137        let v = create_secctx(
2138            &[
2139                (b"foo\0", foo_value.to_bytes_with_nul()),
2140                (SELINUX_XATTR_CSTR, sec_value.to_bytes_with_nul()),
2141            ],
2142            0,
2143        );
2144
2145        let res = parse_selinux_xattr(&v);
2146        assert_eq!(res.unwrap(), Some(sec_value));
2147    }
2148
2149    #[test]
2150    fn parse_selinux_xattr_wrong_attr() {
2151        // Test with an xattr name that looks similar to security.selinux, but has extra
2152        // characters to ensure that `parse_selinux_xattr` will not return the associated
2153        // context value to the caller.
2154        let invalid_selinux_value = c"user_invalid:object_invalid:invalid_type:s0";
2155        let v = create_secctx(
2156            &[(
2157                b"invalid.security.selinux\0",
2158                invalid_selinux_value.to_bytes_with_nul(),
2159            )],
2160            0,
2161        );
2162
2163        let res = parse_selinux_xattr(&v);
2164        assert_eq!(res.unwrap(), None);
2165    }
2166
2167    #[test]
2168    fn parse_selinux_xattr_too_short() {
2169        // Test that parse_selinux_xattr will return an `Error::InvalidHeaderLength` when
2170        // the total size in the `SecctxHeader` does not encompass the entirety of the
2171        // associated data, regardless of whether `security.selinux` appears first or last.
2172        let foo_value = c"user_foo:object_foo:foo_type:s0";
2173        let sec_value = c"user_u:object_r:security_type:s0";
2174        let v = create_secctx(
2175            &[
2176                (b"foo\0", foo_value.to_bytes_with_nul()),
2177                (SELINUX_XATTR_CSTR, sec_value.to_bytes_with_nul()),
2178            ],
2179            8,
2180        );
2181
2182        let res = parse_selinux_xattr(&v);
2183        assert!(matches!(res, Err(Error::InvalidHeaderLength)));
2184
2185        let v_selinux_first = create_secctx(
2186            &[
2187                (SELINUX_XATTR_CSTR, sec_value.to_bytes_with_nul()),
2188                (b"foo\0", foo_value.to_bytes_with_nul()),
2189            ],
2190            8,
2191        );
2192
2193        let res = parse_selinux_xattr(&v_selinux_first);
2194        assert!(matches!(res, Err(Error::InvalidHeaderLength)));
2195
2196        // Also verify unaligned header size with a single security.selinux entry is rejected.
2197        let v_unaligned = create_secctx(&[(SELINUX_XATTR_CSTR, sec_value.to_bytes_with_nul())], 1);
2198        let res = parse_selinux_xattr(&v_unaligned);
2199        assert!(matches!(res, Err(Error::InvalidHeaderLength)));
2200    }
2201}
2202
2203#[cfg(kani)]
2204mod verification {
2205    use super::*;
2206
2207    /// Proves that `parse_selinux_xattr` never panics on any arbitrary `SecctxHeader`/`Secctx`
2208    /// input buffer and strictly enforces the 8-byte alignment and `MAX_NR_SECCTX` invariants.
2209    #[kani::proof]
2210    #[kani::unwind(4)]
2211    fn verify_parse_selinux_xattr() {
2212        let buf: [u8; 18] = kani::any();
2213        let len: usize = kani::any();
2214        kani::assume(len <= buf.len());
2215        let slice = &buf[..len];
2216
2217        // An 18-byte buffer can hold at most 1 valid `Secctx` entry (8-byte `SecctxHeader` +
2218        // 10-byte minimum `Secctx` entry). Constraining `nr_secctx` away from 3..=MAX_NR_SECCTX
2219        // bounds CBMC loop unwinding while still covering 0, 1, 2 (truncated 2nd entry), and
2220        // > MAX_NR_SECCTX.
2221        if slice.len() >= size_of::<SecctxHeader>() {
2222            let (hdr, _) = SecctxHeader::read_from_prefix(slice).unwrap();
2223            kani::assume(hdr.nr_secctx <= 2 || hdr.nr_secctx > MAX_NR_SECCTX);
2224        }
2225
2226        if let Ok(res) = parse_selinux_xattr(slice) {
2227            if slice.len() >= size_of::<SecctxHeader>() {
2228                let (hdr, _) = SecctxHeader::read_from_prefix(slice).unwrap();
2229                if hdr.nr_secctx <= MAX_NR_SECCTX {
2230                    assert_eq!(hdr.size % 8, 0);
2231                    assert!(hdr.size as usize >= size_of::<SecctxHeader>());
2232                    assert!(hdr.size as usize <= slice.len().next_multiple_of(8));
2233                } else {
2234                    assert!(res.is_none());
2235                }
2236            } else {
2237                assert!(slice.is_empty());
2238                assert!(res.is_none());
2239            }
2240        }
2241    }
2242
2243    #[test]
2244    fn test_bytes_to_path_component() {
2245        assert_eq!(
2246            bytes_to_path_component(b"valid.txt\0").unwrap(),
2247            c"valid.txt"
2248        );
2249        assert!(matches!(
2250            bytes_to_path_component(b"..\0"),
2251            Err(Error::DecodeMessage(e)) if e.raw_os_error() == Some(libc::EINVAL)
2252        ));
2253        assert!(matches!(
2254            bytes_to_path_component(b"/\0"),
2255            Err(Error::DecodeMessage(e)) if e.raw_os_error() == Some(libc::EINVAL)
2256        ));
2257        assert!(matches!(
2258            bytes_to_path_component(b"a/b\0"),
2259            Err(Error::DecodeMessage(e)) if e.raw_os_error() == Some(libc::EINVAL)
2260        ));
2261    }
2262}