ostrya_composefs/lib.rs
1#![forbid(unsafe_code)]
2
3//! A byte-exact writer of composefs EROFS images, with an fs-verity hasher.
4//!
5//! A caller builds a tree of directories, symlinks, and regular files. The
6//! crate writes the EROFS image of the tree and returns the fs-verity digest of
7//! the image. The image is byte-identical to the composefs image of the
8//! `ostree` command, format version 0. The crate is synchronous and does not
9//! read a repository.
10//!
11//! # Entry points
12//!
13//! - [`Directory`] is the root of a tree, and [`Node`] is one entry of it.
14//! - [`Metadata`] holds the mode, the owner, the mtime, and the xattrs of a node.
15//! - [`Content`] is the content of a [`Regular`] file: empty or a loose object.
16//! - [`build_image`] writes the image into an [`Image`] in memory.
17//! - [`write_image_to`] writes the image through a sink and does not keep it.
18//! - [`FsVerityHasher`] calculates an fs-verity digest of a byte stream.
19//! - [`Error`] is the error of the two image writers.
20//!
21//! # Examples
22//!
23//! ```
24//! use ostrya_composefs::{Content, Directory, FsVerityHasher, Metadata, Node, Regular};
25//!
26//! let mut root = Directory::new(Metadata { mode: 0o755, ..Metadata::default() });
27//! let meta = Metadata { mode: 0o644, ..Metadata::default() };
28//! root.insert("empty", Node::Regular(Regular { meta, content: Content::Empty }));
29//!
30//! let image = ostrya_composefs::build_image(&root)?;
31//! assert_eq!(FsVerityHasher::hash(&image.bytes), image.fs_verity);
32//!
33//! // The streaming writer writes the same bytes and returns the same digest.
34//! let mut sink = Vec::new();
35//! assert_eq!(ostrya_composefs::write_image_to(&root, &mut sink)?, image.fs_verity);
36//! assert_eq!(sink, image.bytes);
37//! # Ok::<(), ostrya_composefs::Error>(())
38//! ```
39
40// tests/golden.rs compares the output byte for byte with images that the
41// `ostree` command wrote.
42
43mod fsverity;
44mod tree;
45mod writer;
46mod xxhash;
47
48use std::fmt;
49
50pub use fsverity::FsVerityHasher;
51pub use tree::{Content, Directory, Metadata, Node, Regular, Symlink};
52pub use writer::write_image_to;
53#[doc(hidden)]
54pub use writer::write_image_unhashed_to;
55
56/// The error of [`build_image`] and [`write_image_to`].
57#[derive(Debug)]
58pub enum Error {
59 /// A tree item that the image cannot hold.
60 ///
61 /// The message names the item.
62 Unsupported(String),
63 /// An I/O error from the sink.
64 Io(std::io::Error),
65}
66
67impl fmt::Display for Error {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 match self {
70 Error::Unsupported(msg) => f.write_str(msg),
71 Error::Io(err) => write!(f, "{err}"),
72 }
73 }
74}
75
76impl std::error::Error for Error {
77 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
78 match self {
79 Error::Unsupported(_) => None,
80 Error::Io(err) => Some(err),
81 }
82 }
83}
84
85impl From<std::io::Error> for Error {
86 fn from(err: std::io::Error) -> Self {
87 Error::Io(err)
88 }
89}
90
91/// A composefs EROFS image in memory, with its fs-verity digest.
92pub struct Image {
93 /// The bytes of the complete EROFS image.
94 pub bytes: Vec<u8>,
95 /// The fs-verity digest of the image (SHA-256, 4096-byte blocks, no salt).
96 ///
97 /// The `ostree` command stores this value in the
98 /// `ostree.composefs.digest.v0` key of the commit metadata.
99 pub fs_verity: [u8; 32],
100}
101
102/// Writes the composefs EROFS image of the tree at `root` into memory.
103///
104/// The bytes and the digest are the same as the result of [`write_image_to`].
105/// [Image format](write_image_to#image-format) gives the layout of the image.
106///
107/// # Errors
108///
109/// - [`Error::Unsupported`] if a child name is empty, is `.` or `..`, holds
110/// `/`, or is longer than 255 bytes. [`Directory::children`] gives the
111/// rules.
112/// - [`Error::Unsupported`] if a symlink target is too long for its inode
113/// block. [`Symlink::target`] gives the limit.
114///
115/// # Panics
116///
117/// Panics if an xattr name, an xattr value, or the xattr area of one node is
118/// larger than the limits on [`Metadata::xattrs`].
119pub fn build_image(root: &Directory) -> Result<Image, Error> {
120 let plan = writer::plan(root)?;
121 let mut bytes = Vec::with_capacity(plan.size);
122 // A `Vec<u8>` sink accepts every write, so the emitting pass cannot fail.
123 let fs_verity = writer::emit(&plan, &mut bytes).expect("a Vec sink never fails");
124 Ok(Image { bytes, fs_verity })
125}
126
127#[cfg(test)]
128mod send_sync {
129 use super::*;
130
131 // The public types are `Send` and `Sync`.
132 fn assert_send_sync<T: Send + Sync>() {}
133
134 #[test]
135 fn public_types_are_send_sync() {
136 assert_send_sync::<Image>();
137 assert_send_sync::<Directory>();
138 assert_send_sync::<Node>();
139 assert_send_sync::<Regular>();
140 assert_send_sync::<Symlink>();
141 assert_send_sync::<Metadata>();
142 assert_send_sync::<Content>();
143 assert_send_sync::<FsVerityHasher>();
144 }
145}