composefs_sys/
lib.rs

1//! # Bindings for libcomposefs
2//!
3//! This crate contains a few manually maintained system bindings for libcomposefs.
4pub const LCFS_SHA256_DIGEST_LEN: usize = 32;
5
6extern "C" {
7    pub fn lcfs_compute_fsverity_from_fd(
8        digest: *mut u8,
9        fd: std::os::raw::c_int,
10    ) -> std::os::raw::c_int;
11    pub fn lcfs_fd_get_fsverity(digest: *mut u8, fd: std::os::raw::c_int) -> std::os::raw::c_int;
12    #[cfg(feature = "v1_0_4")]
13    pub fn lcfs_fd_enable_fsverity(fd: std::os::raw::c_int) -> std::os::raw::c_int;
14}
15
16/// Convert an integer return value into a `Result`.
17pub fn map_result(r: std::os::raw::c_int) -> std::io::Result<()> {
18    match r {
19        0 => Ok(()),
20        _ => Err(std::io::Error::last_os_error()),
21    }
22}
23
24#[cfg(test)]
25mod tests {
26    use anyhow::Result;
27    use std::io::{Seek, Write};
28    use std::os::fd::AsRawFd;
29
30    use super::*;
31
32    #[test]
33    #[cfg(feature = "v1_0_4")]
34    fn test_fd_enable_fsverity() -> Result<()> {
35        // We can't require fsverity in our test suite, so just verify we can call the
36        // function.
37        let mut tf = tempfile::NamedTempFile::new()?;
38        tf.write_all(b"hello")?;
39        let tf = std::fs::File::open(tf.path())?;
40        let _ = unsafe { lcfs_fd_enable_fsverity(tf.as_raw_fd()) };
41        Ok(())
42    }
43
44    #[test]
45    fn test_digest() -> Result<()> {
46        for f in [lcfs_compute_fsverity_from_fd, lcfs_fd_get_fsverity] {
47            let mut tf = tempfile::tempfile()?;
48            tf.write_all(b"hello world")?;
49            let mut buf = [0u8; LCFS_SHA256_DIGEST_LEN];
50            tf.seek(std::io::SeekFrom::Start(0))?;
51            unsafe { f(buf.as_mut_ptr(), tf.as_raw_fd()) };
52            assert_eq!(
53                buf,
54                [
55                    30, 46, 170, 66, 2, 215, 80, 164, 17, 116, 238, 69, 73, 112, 185, 44, 27, 194,
56                    249, 37, 177, 227, 80, 118, 216, 199, 213, 245, 99, 98, 186, 100
57                ]
58            );
59        }
60        Ok(())
61    }
62}