From 3cc1dd4e887837a848cd4d0e041917a8cd917332 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 11:31:55 +0100 Subject: [PATCH 01/32] uapi16: build the crate in a workspace of its own In ufat the crate is a member of ufat's workspace and takes its edition, rust-version, license, publish setting, lints and dependency versions from there. This repository is going to hold more than the crate: a C library and a tool that generates and checks manifests. So it becomes a workspace the way ufat is one, with every crate below src/. The crate stays in src/uapi16, exactly where it is in ufat. The root Cargo.toml takes over what applies from ufat's. resolver 3 makes cargo update pick dependency versions that build with rust-version 1.85. [workspace.dependencies] has the four crates uapi16 uses. sha2 stays on 0.11.0, since 0.11.1 needs rustc 1.88, and libc on 0.2 like in ufat, so that ufat never builds two versions of it. The lints are ufat's, minus the check-cfg list, which only names cfgs of ufat's own. src/uapi16/Cargo.toml loses a single line, version.workspace = true. The crate gets its version later, together with the rest of what crates.io needs, and cargo refuses to inherit a version the workspace doesn't have. Without one cargo treats the crate as 0.0.0. It isn't published either way, since the workspace says publish = false. Cargo.lock is checked in and lists the versions ufat's Cargo.lock has, so the crate is built and tested with exactly what ufat uses. Builds use --locked. rustfmt.toml is ufat's as well, so the code is formatted the same way. ufat has no clippy configuration beyond the lints. Signed-off-by: Christian Brauner (Amutable) --- .gitignore | 1 + Cargo.lock | 213 ++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 30 ++++++ rustfmt.toml | 2 + src/uapi16/Cargo.toml | 1 - 5 files changed, 246 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 rustfmt.toml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..a479656 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,213 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uapi16" +version = "0.0.0" +dependencies = [ + "libc", + "serde_core", + "serde_json", + "sha2", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..ac50312 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,30 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later + +[workspace] +members = ["src/uapi16"] +# cargo update picks dependency versions that support rust-version. +resolver = "3" + +[workspace.package] +edition = "2021" +# uapi16 has to keep building with this rustc. +rust-version = "1.85" +license = "LGPL-2.1-or-later" +publish = false + +[workspace.dependencies] +# Stay on 0.2 like ufat, which uses uapi16, so that ufat never builds +# two versions of libc. +libc = "0.2.191" +# Reads and writes JSON. What a manifest asks for beyond JSON is checked +# by src/uapi16/strict.rs. Never turn on arbitrary_precision: serde_json +# then hands numbers to the visitors of uapi16 as objects, see the crate +# docs of uapi16. +serde_core = "1.0.229" +serde_json = "1.0.154" +# 0.11.1 and later need rustc 1.88. +sha2 = { version = "0.11.0", default-features = false } + +[workspace.lints.rust] +unreachable_pub = "warn" +unused_qualifications = "warn" diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..34c78b8 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +# The width the code was written to; everything else is rustfmt's default. +max_width = 120 diff --git a/src/uapi16/Cargo.toml b/src/uapi16/Cargo.toml index d716245..088758f 100644 --- a/src/uapi16/Cargo.toml +++ b/src/uapi16/Cargo.toml @@ -2,7 +2,6 @@ [package] name = "uapi16" -version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true From 06a399a9199374fae2a70ee75f113bd1a2d12972 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 11:32:52 +0100 Subject: [PATCH 02/32] uapi16: test with the manifests systemd-manifest writes Bring over the manifests systemd-manifest wrote from ufat, with the two tests there that only exercise this crate: - read every manifest and check what its objects hold - check that a signature changes none of the file objects - check that fewer fields give the same names and values - write every manifest back and read the same objects again They go below src/uapi16/tests, so that they belong to the crate and come with its package. tests/ at the top is left for the tool. The six manifests are byte for byte the ones in tests/fixtures of ufat, where they last changed in c9bcc12 ("manifest: write manifests with the uapi16 crate"). systemd-manifest of systemd commit 4343b7c7d5 wrote them. ufat's make-fixtures.sh then added the features and the order, which that systemd-manifest didn't write yet, and took the hash of no data out of the empty file. tests/fixtures/README.md in ufat has the details. The trees the manifests describe stay in ufat, since nothing here reads them. The tests use the reader and the writer directly instead of going through fat::manifest. writes_records_the_way_systemd_does() in writer.rs points at these manifests, so that holds again. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/tests/fixtures.rs | 187 ++++++++++++++++++ .../tests/fixtures/empty/Uapi16Manifest | 2 + src/uapi16/tests/fixtures/esp/Uapi16Manifest | 15 ++ .../tests/fixtures/esp/none.Uapi16Manifest | 15 ++ .../tests/fixtures/esp/signed.Uapi16Manifest | 16 ++ .../esp/size-hash-mtime.Uapi16Manifest | 15 ++ .../tests/fixtures/special/Uapi16Manifest | 15 ++ 7 files changed, 265 insertions(+) create mode 100644 src/uapi16/tests/fixtures.rs create mode 100644 src/uapi16/tests/fixtures/empty/Uapi16Manifest create mode 100644 src/uapi16/tests/fixtures/esp/Uapi16Manifest create mode 100644 src/uapi16/tests/fixtures/esp/none.Uapi16Manifest create mode 100644 src/uapi16/tests/fixtures/esp/signed.Uapi16Manifest create mode 100644 src/uapi16/tests/fixtures/esp/size-hash-mtime.Uapi16Manifest create mode 100644 src/uapi16/tests/fixtures/special/Uapi16Manifest diff --git a/src/uapi16/tests/fixtures.rs b/src/uapi16/tests/fixtures.rs new file mode 100644 index 0000000..215e5bf --- /dev/null +++ b/src/uapi16/tests/fixtures.rs @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! Manifests written by systemd's own tool, read and written back. They +//! are copies of the fixtures of ufat, whose tests/fixtures/README.md says +//! how they were made. + +use std::path::{Path, PathBuf}; + +use uapi16::{Error, FileObject, InodeType, Object, Order, Reader, RootObject, Signature, Writer}; + +/// A manifest read to its end: its root file object, its file objects and +/// its signature objects. +#[derive(Debug, PartialEq)] +struct Manifest { + root: RootObject, + files: Vec, + signatures: Vec, +} + +impl Manifest { + /// Reads the manifest `bytes` to its end. + fn read(bytes: &[u8]) -> Result { + let mut reader = Reader::open(bytes)?; + let mut manifest = Manifest { + root: reader.root().clone(), + files: Vec::new(), + signatures: Vec::new(), + }; + for object in &mut reader { + match object? { + Object::File(file) => manifest.files.push(*file), + Object::Signature(signature) => manifest.signatures.push(signature), + other => panic!("{:?} is neither a file object nor a signature", other), + } + } + Ok(manifest) + } + + /// Reads the fixture `name` of the case `case`. + fn load(case: &str, name: &str) -> Manifest { + let path = fixture(case, name); + let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {}", path.display(), e)); + Manifest::read(&bytes).unwrap_or_else(|e| panic!("{}: {}", path.display(), e)) + } + + /// The manifest the writer writes for the objects. + fn write(&self) -> Result, Error> { + let mut writer = Writer::begin(Vec::new(), &self.root)?; + for file in &self.files { + writer.file(file)?; + } + for signature in &self.signatures { + writer.signature(signature)?; + } + writer.finish() + } + + /// The names of the file objects, in the order of the manifest. + fn names(&self) -> Vec<&str> { + self.files.iter().map(|file| file.name.as_str()).collect() + } +} + +/// The path of the fixture `name` of the case `case`. +fn fixture(case: &str, name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(case) + .join(name) +} + +#[test] +fn every_fixture_parses() { + let esp = Manifest::load("esp", "Uapi16Manifest"); + assert_eq!(esp.files.len(), 13); + assert_eq!( + esp.files + .iter() + .filter(|e| e.inode_type == InodeType::Directory) + .count(), + 6 + ); + assert_eq!(esp.root.inode.mtime_nsec, Some(1_699_999_000_000_000_000)); + assert!(esp.signatures.is_empty()); + assert_eq!( + esp.names(), + vec![ + "EFI", + "EFI/BOOT", + "EFI/BOOT/BOOTX64.EFI", + "EFI/Linux", + "EFI/Linux/linux-6.12.4-200.fc41.x86_64+3.efi", + "EFI/systemd", + "EFI/systemd/systemd-bootx64.efi", + "loader", + "loader/entries", + "loader/entries/fedora.conf", + "loader/entries.srel", + "loader/loader.conf", + "loader/random-seed", + ] + ); + let uki = &esp.files[4]; + assert_eq!(uki.size, Some(6395)); + assert_eq!(uki.inode.mode.map(u32::from), Some(0o664)); + assert_eq!(uki.inode.mtime_nsec, Some(1_700_000_002_000_000_000)); + assert!(!uki.inode.is_read_only()); + assert!(uki.contents.is_empty()); + + // The signature does not change the file objects. + let signed = Manifest::load("esp", "signed.Uapi16Manifest"); + assert_eq!(signed.signatures.len(), 1); + assert_eq!(signed.files, esp.files); + assert_eq!(signed.root, esp.root); + + // Fewer fields, same tree. + let lean = Manifest::load("esp", "size-hash-mtime.Uapi16Manifest"); + assert_eq!(lean.names(), esp.names()); + assert!(lean.files.iter().all(|e| e.inode.mode.is_none())); + assert!(lean + .files + .iter() + .zip(&esp.files) + .all(|(a, b)| a.size == b.size && a.sha256 == b.sha256 && a.inode.mtime_nsec == b.inode.mtime_nsec)); + let none = Manifest::load("esp", "none.Uapi16Manifest"); + assert_eq!(none.names(), esp.names()); + assert!(none + .files + .iter() + .all(|e| e.size.is_none() && e.sha256.is_none() && e.inode.mtime_nsec.is_none())); + + let special = Manifest::load("special", "Uapi16Manifest"); + assert_eq!(special.files.len(), 13); + let types: Vec = special.files.iter().map(|e| e.inode_type).collect(); + assert_eq!(types.iter().filter(|&&t| t == InodeType::Symlink).count(), 1); + assert_eq!(types.iter().filter(|&&t| t == InodeType::Fifo).count(), 1); + let link = special + .files + .iter() + .find(|e| e.inode_type == InodeType::Symlink) + .unwrap(); + assert_eq!(link.contents[0].literal(), Some(&b"a.txt"[..])); + let hardlinks: Vec<&str> = special + .files + .iter() + .filter(|e| e.inode_token.is_some()) + .map(|e| e.name.as_str()) + .collect(); + assert_eq!(hardlinks, vec!["sub/hl_a", "sub/hl_b"]); + let readonly = special.files.iter().find(|e| e.name == "sub/readonly.bin").unwrap(); + assert_eq!(readonly.inode.mode.map(u32::from), Some(0o444)); + assert!(readonly.inode.is_read_only()); + assert!(special.names().contains(&"sub/\u{fc}mlaut \u{221e}.txt")); + + let empty = Manifest::load("empty", "Uapi16Manifest"); + assert!(empty.files.is_empty()); + assert_eq!(empty.root.inode.mtime_nsec, Some(1_700_000_200_000_000_000)); +} + +/// The reader reads every manifest systemd-manifest wrote, and what the +/// writer writes for one reads back as the same manifest. That holds since +/// ufat's make-fixtures.sh took the hash of no data out of the empty file +/// of the special case: the writer leaves out a hash given next to the +/// size 0, and the reader marks the one it fills in as filled in, so the +/// objects would differ in that mark. +#[test] +fn reads_and_writes_back_every_fixture() { + for (case, name, files, signatures) in [ + ("esp", "Uapi16Manifest", 13, 0), + ("esp", "signed.Uapi16Manifest", 13, 1), + ("esp", "size-hash-mtime.Uapi16Manifest", 13, 0), + ("esp", "none.Uapi16Manifest", 13, 0), + ("special", "Uapi16Manifest", 13, 0), + ("empty", "Uapi16Manifest", 0, 0), + ] { + let path = fixture(case, name); + let read = Manifest::load(case, name); + assert_eq!( + (read.files.len(), read.signatures.len()), + (files, signatures), + "{}", + path.display() + ); + assert_eq!(read.root.order, Some(Order::CodePoint), "{}", path.display()); + let written = read.write().unwrap_or_else(|e| panic!("{}: {}", path.display(), e)); + assert_eq!(Manifest::read(&written).unwrap(), read, "{}", path.display()); + } +} diff --git a/src/uapi16/tests/fixtures/empty/Uapi16Manifest b/src/uapi16/tests/fixtures/empty/Uapi16Manifest new file mode 100644 index 0000000..f611451 --- /dev/null +++ b/src/uapi16/tests/fixtures/empty/Uapi16Manifest @@ -0,0 +1,2 @@ +{"extendedAttributes":{"user":{}},"features":["device","gid","hardlink","mode","mtime","sha256","size","symlink","uid","user-xattr"],"gid":1000,"mTimeNSec":1700000200000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"order":"codepoint","uid":1000} +{"mediaType":"application/vnd.uapi.16.trailer"} diff --git a/src/uapi16/tests/fixtures/esp/Uapi16Manifest b/src/uapi16/tests/fixtures/esp/Uapi16Manifest new file mode 100644 index 0000000..407c2f5 --- /dev/null +++ b/src/uapi16/tests/fixtures/esp/Uapi16Manifest @@ -0,0 +1,15 @@ +{"extendedAttributes":{"user":{}},"features":["device","gid","hardlink","mode","mtime","sha256","size","symlink","uid","user-xattr"],"gid":1000,"mTimeNSec":1699999000000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"order":"codepoint","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI","type":"dir","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI/BOOT","type":"dir","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000000000000000,"mode":436,"name":"EFI/BOOT/BOOTX64.EFI","sha256":"608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b","size":4096,"uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI/Linux","type":"dir","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000002000000000,"mode":436,"name":"EFI/Linux/linux-6.12.4-200.fc41.x86_64+3.efi","sha256":"cf9d3feda36430c2d43bb92ae7d7b67b5744d0de121eac8ba2c4e7d0e6123995","size":6395,"uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI/systemd","type":"dir","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000000000000000,"mode":436,"name":"EFI/systemd/systemd-bootx64.efi","sha256":"608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b","size":4096,"uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"loader","type":"dir","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"loader/entries","type":"dir","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000004000000000,"mode":436,"name":"loader/entries/fedora.conf","sha256":"6c7db879a08b17a44f43a5694a8af1f9bdd695cf06d0bdce080566c6fcf91ec4","size":65,"uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000004000000000,"mode":436,"name":"loader/entries.srel","sha256":"067fc514414e89fa29898b3d61ce88577bebc2fbcad0ba42c2b769698c8baafc","size":6,"uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000004000000000,"mode":436,"name":"loader/loader.conf","sha256":"a97712b6f8e885e801ff6b57f97ae84cbdc5a05f82fe0663499e761444bbe660","size":28,"uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000006000000000,"mode":436,"name":"loader/random-seed","sha256":"05fb14e37191f77ecc756576084369cefe8c33f94a03a5133d25fa486a7e1375","size":32,"uid":1000} +{"mediaType":"application/vnd.uapi.16.trailer"} diff --git a/src/uapi16/tests/fixtures/esp/none.Uapi16Manifest b/src/uapi16/tests/fixtures/esp/none.Uapi16Manifest new file mode 100644 index 0000000..c76497c --- /dev/null +++ b/src/uapi16/tests/fixtures/esp/none.Uapi16Manifest @@ -0,0 +1,15 @@ +{"features":[],"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"} +{"name":"EFI","type":"dir"} +{"name":"EFI/BOOT","type":"dir"} +{"name":"EFI/BOOT/BOOTX64.EFI"} +{"name":"EFI/Linux","type":"dir"} +{"name":"EFI/Linux/linux-6.12.4-200.fc41.x86_64+3.efi"} +{"name":"EFI/systemd","type":"dir"} +{"name":"EFI/systemd/systemd-bootx64.efi"} +{"name":"loader","type":"dir"} +{"name":"loader/entries","type":"dir"} +{"name":"loader/entries/fedora.conf"} +{"name":"loader/entries.srel"} +{"name":"loader/loader.conf"} +{"name":"loader/random-seed"} +{"mediaType":"application/vnd.uapi.16.trailer"} diff --git a/src/uapi16/tests/fixtures/esp/signed.Uapi16Manifest b/src/uapi16/tests/fixtures/esp/signed.Uapi16Manifest new file mode 100644 index 0000000..b1996fb --- /dev/null +++ b/src/uapi16/tests/fixtures/esp/signed.Uapi16Manifest @@ -0,0 +1,16 @@ +{"extendedAttributes":{"user":{}},"features":["device","gid","hardlink","mode","mtime","sha256","size","symlink","uid","user-xattr"],"gid":1000,"mTimeNSec":1699999000000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"order":"codepoint","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI","type":"dir","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI/BOOT","type":"dir","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000000000000000,"mode":436,"name":"EFI/BOOT/BOOTX64.EFI","sha256":"608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b","size":4096,"uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI/Linux","type":"dir","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000002000000000,"mode":436,"name":"EFI/Linux/linux-6.12.4-200.fc41.x86_64+3.efi","sha256":"cf9d3feda36430c2d43bb92ae7d7b67b5744d0de121eac8ba2c4e7d0e6123995","size":6395,"uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI/systemd","type":"dir","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000000000000000,"mode":436,"name":"EFI/systemd/systemd-bootx64.efi","sha256":"608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b","size":4096,"uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"loader","type":"dir","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"loader/entries","type":"dir","uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000004000000000,"mode":436,"name":"loader/entries/fedora.conf","sha256":"6c7db879a08b17a44f43a5694a8af1f9bdd695cf06d0bdce080566c6fcf91ec4","size":65,"uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000004000000000,"mode":436,"name":"loader/entries.srel","sha256":"067fc514414e89fa29898b3d61ce88577bebc2fbcad0ba42c2b769698c8baafc","size":6,"uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000004000000000,"mode":436,"name":"loader/loader.conf","sha256":"a97712b6f8e885e801ff6b57f97ae84cbdc5a05f82fe0663499e761444bbe660","size":28,"uid":1000} +{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000006000000000,"mode":436,"name":"loader/random-seed","sha256":"05fb14e37191f77ecc756576084369cefe8c33f94a03a5133d25fa486a7e1375","size":32,"uid":1000} +{"data":"MIIEnAYJKoZIhvcNAQcCoIIEjTCCBIkCAQExDTALBglghkgBZQMEAgEwCwYJKoZIhvcNAQcBoIIDDTCCAwkwggHxoAMCAQICFGR5b8UEre4UpKFEfzb+RRucG88dMA0GCSqGSIb3DQEBCwUAMBQxEjAQBgNVBAMMCXVmYXQgdGVzdDAeFw0yNjExMDYyMTE0MzJaFw0zNjExMDMyMTE0MzJaMBQxEjAQBgNVBAMMCXVmYXQgdGVzdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAM9TzZPpWG49fOhQt3uEbxfAnEtAg7bDxylrqfnFvd+r/01ySoyzGTQz4RUKLzUjznuCg0uXakste46Lr08WXxnEjiAwmyxVt4sxDR9OzrAvQwZr/jKiSSdMdI4uh2hpG1gc+SUz83ViCFRylPlChATIvYgCcXk1W2O4VKqYTnrWWoQ919Ht/GfjVdTaSr4Ni16xpAjOyLCUBauMyWj+DfnauxvbCRYXB+Gr6+3z9SL5NRPwMP5BiEqwQuPk2ASfDdpMuxjmhmTrL/2VJrj/C+VwCxSidAfpCdGTvM9Fo5oMexDS4VSdE5TWFa21DQhvONvv9+vyIivaIdXhbKcntDkCAwEAAaNTMFEwHQYDVR0OBBYEFEBh4/6FwVkKsS6J8N5FRvG282yVMB8GA1UdIwQYMBaAFEBh4/6FwVkKsS6J8N5FRvG282yVMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFVGvBT/he5M0oWcDhDqrVPdckvaSZ1BnrzenNhnz0d5iAqOWli33Q7EWMxv8Kg66vKyj8B4eTxf/q0Lyiu1aYtDbZk81hEh8SIRCo2ggMlJ/toZdpqqE4KAgPQeQQ2/oeCcQC6fMC6vA7TiV8L1v1+WPgaRdyPNooMBZbKRQFjeSh8eDjlLJ5tu/nRm88Vtdps74/a1jmWLFGnUtnMDt1UypY0EQ3eWINCrOjuqHKM3qapxSJJ9xkL++CDG6arBllq0MoeyXaVkmuzYu/OFpjUGtLGFZA4JOrGVggYTAPdfXhiYoSux5J9I5sKJHgRtpF083tQk0XTf39LGmyc2PyIxggFVMIIBUQIBATAsMBQxEjAQBgNVBAMMCXVmYXQgdGVzdAIUZHlvxQSt7hSkoUR/Nv5FG5wbzx0wCwYJYIZIAWUDBAIBMA0GCSqGSIb3DQEBAQUABIIBAEf3V67SNBsULHmjR7Kex8RybASrQmytqyjZKvyM4cTbbADng69r0cqNmL4MqTe4XkVVI1mKjm4J33RhFghUEEXCZe94fIRYhg5GC6t1pmt6YoV0aHCTWWVyj2+IATTCLkQ2oqVwobe1S+L/I5JITWHa1a0VTyUpydw80oivsZhUXk0W20gUALW1XHHLCyu79f9XlT3RuoFs82ceLLtzQKyGfg58kT64jotM2n5xA1i1XHfNU1N0MX19QAGHqgtXRfbFjrcMq2rMo/SqNIYj0/uGmdMeVXvwpi/E6ah3D84iHjQG4Q78Ya4S/A3faF6ArGZyzcWGUA1v/25hCQe0LFk=","key":"391c1f5f2e3799de760abb1cf391763058c998e7caed0abe9bbb6970b05400f3","mechanism":"pkcs7","mediaType":"application/vnd.uapi.16.signature"} +{"mediaType":"application/vnd.uapi.16.trailer"} diff --git a/src/uapi16/tests/fixtures/esp/size-hash-mtime.Uapi16Manifest b/src/uapi16/tests/fixtures/esp/size-hash-mtime.Uapi16Manifest new file mode 100644 index 0000000..a19baf9 --- /dev/null +++ b/src/uapi16/tests/fixtures/esp/size-hash-mtime.Uapi16Manifest @@ -0,0 +1,15 @@ +{"features":["mtime","sha256","size"],"mTimeNSec":1699999000000000000,"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"} +{"mTimeNSec":1699999000000000000,"name":"EFI","type":"dir"} +{"mTimeNSec":1699999000000000000,"name":"EFI/BOOT","type":"dir"} +{"mTimeNSec":1700000000000000000,"name":"EFI/BOOT/BOOTX64.EFI","sha256":"608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b","size":4096} +{"mTimeNSec":1699999000000000000,"name":"EFI/Linux","type":"dir"} +{"mTimeNSec":1700000002000000000,"name":"EFI/Linux/linux-6.12.4-200.fc41.x86_64+3.efi","sha256":"cf9d3feda36430c2d43bb92ae7d7b67b5744d0de121eac8ba2c4e7d0e6123995","size":6395} +{"mTimeNSec":1699999000000000000,"name":"EFI/systemd","type":"dir"} +{"mTimeNSec":1700000000000000000,"name":"EFI/systemd/systemd-bootx64.efi","sha256":"608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b","size":4096} +{"mTimeNSec":1699999000000000000,"name":"loader","type":"dir"} +{"mTimeNSec":1699999000000000000,"name":"loader/entries","type":"dir"} +{"mTimeNSec":1700000004000000000,"name":"loader/entries/fedora.conf","sha256":"6c7db879a08b17a44f43a5694a8af1f9bdd695cf06d0bdce080566c6fcf91ec4","size":65} +{"mTimeNSec":1700000004000000000,"name":"loader/entries.srel","sha256":"067fc514414e89fa29898b3d61ce88577bebc2fbcad0ba42c2b769698c8baafc","size":6} +{"mTimeNSec":1700000004000000000,"name":"loader/loader.conf","sha256":"a97712b6f8e885e801ff6b57f97ae84cbdc5a05f82fe0663499e761444bbe660","size":28} +{"mTimeNSec":1700000006000000000,"name":"loader/random-seed","sha256":"05fb14e37191f77ecc756576084369cefe8c33f94a03a5133d25fa486a7e1375","size":32} +{"mediaType":"application/vnd.uapi.16.trailer"} diff --git a/src/uapi16/tests/fixtures/special/Uapi16Manifest b/src/uapi16/tests/fixtures/special/Uapi16Manifest new file mode 100644 index 0000000..18d9767 --- /dev/null +++ b/src/uapi16/tests/fixtures/special/Uapi16Manifest @@ -0,0 +1,15 @@ +{"extendedAttributes":{"user":{}},"features":["device","gid","group-name","hardlink","mode","mtime","sha256","size","symlink","uid","user-name","user-xattr"],"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"order":"codepoint","uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000100000000000,"mode":436,"name":"Mixed Case.TXT","sha256":"480c2336b410f1ad5f8bf1b28944490255804b65350c527787e74ebdd511e3a4","size":7,"uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{"comment":{"text":"set by make-fixtures"}}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000100000000000,"mode":436,"name":"a.txt","sha256":"b640e840b19d378660b32fb51ae18d67dccb4a8596a29e7bd72c1b2ae5928f41","size":6,"uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"mode":436,"name":"empty","size":0,"uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mode":509,"name":"empty dir","type":"dir","uid":1000,"userName":"brauner"} +{"contents":[{"literal":"YS50eHQ="}],"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"name":"link","size":5,"type":"lnk","uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mode":509,"name":"sub","type":"dir","uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"mode":436,"name":"sub/fifo","type":"fifo","uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","inodeToken":1,"mTimeNSec":1700000102000000000,"mode":436,"name":"sub/hl_a","sha256":"028d1d55eece761b070d497008da1ef8e0adcd40b26dfae326849aa811605df2","size":11,"uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","inodeToken":1,"mTimeNSec":1700000102000000000,"mode":436,"name":"sub/hl_b","sha256":"028d1d55eece761b070d497008da1ef8e0adcd40b26dfae326849aa811605df2","size":11,"uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mode":509,"name":"sub/nested","type":"dir","uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000100000000000,"mode":436,"name":"sub/nested/deep.conf","sha256":"5eef8098ed6ec0a16249fc7c12422027fc9fd75b16130cc9382cf09102014796","size":6,"uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000100000000000,"mode":292,"name":"sub/readonly.bin","sha256":"28dc50ce2c559549546af000e2a606f45a45dac10f91bcefc7b21b9555ca1334","size":10,"uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"mode":436,"name":"sub/ümlaut ∞.txt","sha256":"eefeabce9a2687ecae740bf791ad4e768b642ec837cc05e9677b25de098e2547","size":7,"uid":1000,"userName":"brauner"} +{"mediaType":"application/vnd.uapi.16.trailer"} From 804d53898511f7f38c0d3958e070c2b34e0796bc Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 11:33:24 +0100 Subject: [PATCH 03/32] LICENSE: add the license text The crate is LGPL-2.1-or-later. Add the text of the LGPL 2.1 twice: at the top for the repository, where GitHub looks for it, and in src/uapi16 for the package cargo publish uploads. cargo packages only what is in the crate's directory, and an include pattern can't reach outside of it. Both are the same file ufat has. Signed-off-by: Christian Brauner (Amutable) --- LICENSE | 502 +++++++++++++++++++++++++++++++++++++++++++++ src/uapi16/LICENSE | 502 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1004 insertions(+) create mode 100644 LICENSE create mode 100644 src/uapi16/LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..86c73c7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/src/uapi16/LICENSE b/src/uapi16/LICENSE new file mode 100644 index 0000000..86c73c7 --- /dev/null +++ b/src/uapi16/LICENSE @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! From a516a9be15ea1b7b58baa568e49dadf755bf39bb Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 15:27:21 +0100 Subject: [PATCH 04/32] uapi16: mark Step non-exhaustive "uapi16: mark the open-ended enums non-exhaustive" left Step exhaustive because a caller that doesn't know a step can't keep driving the decoder. A new step that asks the caller for something, the way Step::Input asks for more of the manifest, would be passed over by an old caller. It would call step() again without doing what was asked and get the same step back, forever. But that only holds for a step that asks the caller to act. A step that only hands something out, like Step::Root and Step::Object do, needs nothing but another call to step(). So let's promise exactly that in the docs: a step the caller doesn't know needs nothing from it except another call to step(). Then new steps can be added in a compatible release as long as they only hand something out, and Step can be #[non_exhaustive] like the other open-ended enums. The example of Decoder already passes over the steps it doesn't care about with a catch-all arm. Nothing in ufat uses Decoder or matches on Step. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/reader.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/uapi16/reader.rs b/src/uapi16/reader.rs index 2e985eb..e639882 100644 --- a/src/uapi16/reader.rs +++ b/src/uapi16/reader.rs @@ -249,7 +249,14 @@ enum Stage { } /// What a [`Decoder`] has for its caller next. +/// +/// [`Step::Input`] asks for more of the manifest, [`Step::End`] says that +/// there is nothing more, and the other steps hand something out. A step +/// the caller does not know needs nothing from it but another call to +/// [`Decoder::step`], so the caller can pass over it. Steps that come in +/// later releases only hand something out. #[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum Step { /// More of the manifest: [`Decoder::feed`] takes it, and /// [`Decoder::end`] says that the input ended. From 46f333f6ef7ae14d156acb8c68637c103110be52 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 17:46:20 +0100 Subject: [PATCH 05/32] uapi16: take the bits of Mode from the specification Mode::ALL and Mode::WRITE are built from libc's S_I* constants. Those are mode_t, which is u32 on most targets but u16 on 32-bit Android, so the two constants don't even build there. They also aren't what a mode is in a manifest. The specification gives `mode` the range 0o0000 to 0o7777 and talks about its three 'w' bits, so use exactly that: 0o7777 and 0o222, as named constants that say where they come from. With that the library doesn't use libc anymore. The tests still take errno values from it, so libc moves to [dev-dependencies]. Note that this also takes away the reason the comment in Cargo.toml gives for keeping libc on 0.2, since ufat never builds a dev-dependency of uapi16. The tests stay on 0.2 all the same: sha2's cpufeatures uses libc 0.2 on aarch64 and loongarch64, and a newer libc would mean two versions of it there. So say that instead. Signed-off-by: Christian Brauner (Amutable) --- Cargo.toml | 4 ++-- src/uapi16/Cargo.toml | 5 +++-- src/uapi16/object.rs | 12 +++++++----- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index ac50312..5939179 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,8 +13,8 @@ license = "LGPL-2.1-or-later" publish = false [workspace.dependencies] -# Stay on 0.2 like ufat, which uses uapi16, so that ufat never builds -# two versions of libc. +# Stay on 0.2 like sha2's cpufeatures on aarch64 and loongarch64, so +# that the tests never build two versions of libc there. libc = "0.2.191" # Reads and writes JSON. What a manifest asks for beyond JSON is checked # by src/uapi16/strict.rs. Never turn on arbitrary_precision: serde_json diff --git a/src/uapi16/Cargo.toml b/src/uapi16/Cargo.toml index 088758f..b5d7189 100644 --- a/src/uapi16/Cargo.toml +++ b/src/uapi16/Cargo.toml @@ -11,15 +11,16 @@ publish.workspace = true path = "lib.rs" [dependencies] -libc.workspace = true serde_core.workspace = true # Without float_roundtrip serde_json refuses some spellings of the largest # doubles as out of range, such as 1.7976931348623158e308. serde_json = { workspace = true, features = ["float_roundtrip"] } sha2.workspace = true -# The tests look at the order of the keys the writer writes. [dev-dependencies] +# The errno values of the errors the tests make. +libc.workspace = true +# The tests look at the order of the keys the writer writes. serde_json = { workspace = true, features = ["preserve_order"] } [lints] diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index fb9cb88..b4e4c70 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -111,11 +111,13 @@ impl FromStr for InodeType { pub struct Mode(u32); impl Mode { - /// Every bit a mode can have. - const ALL: u32 = libc::S_ISUID | libc::S_ISGID | libc::S_ISVTX | libc::S_IRWXU | libc::S_IRWXG | libc::S_IRWXO; - /// The write permission of the owner, of the group and of everybody - /// else. - const WRITE: u32 = libc::S_IWUSR | libc::S_IWGRP | libc::S_IWOTH; + /// Every bit a mode can have. The specification gives `mode` the range + /// `0o0000` to `0o7777`: the permission bits, the set-user-ID, the + /// set-group-ID and the sticky bit. + const ALL: u32 = 0o7777; + /// The three 'w' bits of the specification: the write permission of + /// the owner, of the group and of everybody else. + const WRITE: u32 = 0o222; /// The mode with the bits `bits`, unless there are others among them /// than a mode has. From 5dc1a35101f4b4ae4856cf6d98684fc1c6cd83e8 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 21:27:07 +0100 Subject: [PATCH 06/32] uapi16: let Mode::new() fail with InvalidMode Mode::new() returns None for bits that are not a mode. But the mode of the inode attributes is an Option as well, and there None means that the object has no mode. So inode.mode = Mode::new(0o100644); builds and records no mode at all. That's an easy mistake to make: an st_mode always carries the bits of the file type, so a mode handed straight from stat() to Mode::new() is refused every time, and nothing says so. So make Mode::new() return Result, with InvalidMode a new error like InvalidFatSerial and InvalidUuid. The line above doesn't build anymore, and callers write inode.mode = Some(Mode::new(bits)?); The reader takes and refuses the same modes as before. The tests that set a mode say Some() now. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/decode.rs | 10 +++++----- src/uapi16/lib.rs | 6 +++--- src/uapi16/object.rs | 43 +++++++++++++++++++++++++++--------------- src/uapi16/sequence.rs | 8 ++++++-- src/uapi16/writer.rs | 19 +++++++++++-------- 5 files changed, 53 insertions(+), 33 deletions(-) diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index 9756af2..e20c51a 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -1299,7 +1299,7 @@ impl<'a> RecordDecoder<'a> { /// one. fn mode(&mut self, field: Field, value: Value<'a, T>) -> Option { let bits = self.unsigned(field, value)?; - let mode = u32::try_from(bits).ok().and_then(Mode::new); + let mode = u32::try_from(bits).ok().and_then(|bits| Mode::new(bits).ok()); if mode.is_none() { self.note_error(Problem::FieldOutOfRange, field, || { format!("manifest field '{}' is out of range: {}", field, bits) @@ -2011,7 +2011,7 @@ mod tests { assert_eq!(o.name, "dir/file"); assert_eq!(o.inode_type, InodeType::Regular); assert_eq!(o.size, Some(5)); - assert_eq!(o.inode.mode, Mode::new(0o644)); + assert_eq!(o.inode.mode, Some(Mode::new(0o644).unwrap())); assert_eq!((o.inode.uid, o.inode.gid), (Some(1000), Some(100))); assert_eq!(o.inode.user_name.as_deref(), Some("Domain Users")); assert_eq!(o.inode.group_name.as_deref(), Some("users")); @@ -2083,7 +2083,7 @@ mod tests { assert_eq!(root.inode.user_xattrs.as_deref().map(BTreeMap::len), Some(0)); assert_eq!( (root.inode.uid, root.inode.gid, root.inode.mode), - (Some(1000), Some(1000), Mode::new(0o775)) + (Some(1000), Some(1000), Some(Mode::new(0o775).unwrap())) ); assert_eq!(root.inode.read_only, Some(false)); assert_eq!(root.gpt_disk_uuid, Some(uuid)); @@ -2245,7 +2245,7 @@ mod tests { for (text, mode) in [("420", 0o644), ("4095", 0o7777), ("0", 0)] { assert_eq!( object(&format!(r#"{{"name":"x","mode":{}}}"#, text)).inode.mode, - Mode::new(mode), + Some(Mode::new(mode).unwrap()), "{}", text ); @@ -2410,7 +2410,7 @@ mod tests { empty.contents.clear(); empty.sha256 = EMPTY.parse().ok(); let mut read_only = file(None, hello()); - read_only.inode.mode = Mode::new(0o644); + read_only.inode.mode = Some(Mode::new(0o644).unwrap()); read_only.inode.read_only = Some(true); for (object, record) in [ ( diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 309bee2..ccb96c5 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -111,8 +111,8 @@ pub use features::{Features, Order, UnknownFeature}; pub use name::{Name, NameProblem}; pub use object::{ Contents, DosFlags, FatSerial, FileObject, FileSystemIdentity, FilledIn, FlagStates, GptPartition, InodeAttributes, - InodeFlags, InodeType, InvalidFatSerial, InvalidUuid, Location, Mode, RootObject, Signature, UnknownInodeType, - Uuid, Validity, ValidityWindow, + InodeFlags, InodeType, InvalidFatSerial, InvalidMode, InvalidUuid, Location, Mode, RootObject, Signature, + UnknownInodeType, Uuid, Validity, ValidityWindow, }; pub use reader::{Decoder, Object, Step}; pub use writer::Encoder; @@ -353,7 +353,7 @@ pub(crate) mod testing { encoded.offset = 4; let mut object = FileObject::new(name("a/\u{e9} \"quoted\"\\")); object.size = Some(5); - object.inode.mode = Mode::new(0o440); + object.inode.mode = Some(Mode::new(0o440).unwrap()); object.inode.uid = Some(1); object.inode.gid = Some(2); object.inode.user_name = Some("user".into()); diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index b4e4c70..495fc73 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -102,14 +102,27 @@ impl FromStr for InodeType { /// ``` /// use uapi16::Mode; /// -/// let mode = Mode::new(0o644).unwrap(); +/// let mode = Mode::new(0o644)?; /// assert!(mode.is_writable()); -/// assert!(!Mode::new(0o444).unwrap().is_writable()); -/// assert_eq!(Mode::new(0o10000), None); +/// assert!(!Mode::new(0o444)?.is_writable()); +/// assert!(Mode::new(0o100644).is_err()); +/// # Ok::<(), uapi16::InvalidMode>(()) /// ``` #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct Mode(u32); +/// Bits that are not a mode, see [`Mode::new`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InvalidMode(()); + +impl fmt::Display for InvalidMode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("not the bits of a mode") + } +} + +impl std::error::Error for InvalidMode {} + impl Mode { /// Every bit a mode can have. The specification gives `mode` the range /// `0o0000` to `0o7777`: the permission bits, the set-user-ID, the @@ -119,13 +132,13 @@ impl Mode { /// the owner, of the group and of everybody else. const WRITE: u32 = 0o222; - /// The mode with the bits `bits`, unless there are others among them - /// than a mode has. - pub const fn new(bits: u32) -> Option { + /// The mode with the bits `bits`. Bits that a mode does not have, such + /// as those of the file type in an `st_mode`, fail. + pub const fn new(bits: u32) -> Result { if bits & !Mode::ALL == 0 { - Some(Mode(bits)) + Ok(Mode(bits)) } else { - None + Err(InvalidMode(())) } } @@ -1423,9 +1436,9 @@ mod tests { assert_eq!(mode.bits(), bits); assert_eq!(u32::from(mode), bits); } - assert_eq!(Mode::new(0o10000), None); - assert_eq!(Mode::new(0o100644), None); - assert_eq!(Mode::new(u32::MAX), None); + assert_eq!(Mode::new(0o10000), Err(InvalidMode(()))); + assert_eq!(Mode::new(0o100644), Err(InvalidMode(()))); + assert_eq!(Mode::new(u32::MAX), Err(InvalidMode(()))); for (bits, writable) in [ (0o644, true), (0o444, false), @@ -1518,9 +1531,9 @@ mod tests { fn read_only() { let mut inode = InodeAttributes::default(); assert!(!inode.is_read_only()); - inode.mode = Mode::new(0o444); + inode.mode = Some(Mode::new(0o444).unwrap()); assert!(inode.is_read_only()); - inode.mode = Mode::new(0o464); + inode.mode = Some(Mode::new(0o464).unwrap()); assert!(!inode.is_read_only()); inode.read_only = Some(true); assert!(inode.is_read_only()); @@ -1529,7 +1542,7 @@ mod tests { inode.read_only = Some(false); assert!(!inode.is_read_only()); // What readOnly says counts, the false a reader fills in too. - inode.mode = Mode::new(0o444); + inode.mode = Some(Mode::new(0o444).unwrap()); assert!(!inode.is_read_only()); } @@ -1678,7 +1691,7 @@ mod tests { |o| o.dos_flags.put(DosFlags::ARCHIVE, Some(true)), Features::FLAG_ARCHIVE, ), - (|o| o.inode.mode = Mode::new(0o644), Features::MODE), + (|o| o.inode.mode = Some(Mode::new(0o644).unwrap()), Features::MODE), (|o| o.inode.uid = Some(0), Features::UID), (|o| o.inode.user_name = Some("u".into()), Features::USER_NAME), (|o| o.inode.mtime_nsec = Some(0), Features::MTIME), diff --git a/src/uapi16/sequence.rs b/src/uapi16/sequence.rs index fac282b..7b071e4 100644 --- a/src/uapi16/sequence.rs +++ b/src/uapi16/sequence.rs @@ -322,7 +322,11 @@ mod tests { // two the object has, for symbolic links the target in `contents`. let none = SequenceCheck::new(Features::NONE, None); let cases: [(InodeType, Give, Field); 8] = [ - (InodeType::Regular, |o| o.inode.mode = Mode::new(0o644), Field::Mode), + ( + InodeType::Regular, + |o| o.inode.mode = Some(Mode::new(0o644).unwrap()), + Field::Mode, + ), (InodeType::CharDevice, |o| o.major = Some(1), Field::Major), (InodeType::BlockDevice, |o| o.minor = Some(1), Field::Minor), ( @@ -398,7 +402,7 @@ mod tests { ), (|o| o.inode.user_name = Some("u".into()), Field::UserName), (|o| o.inode.read_only = Some(true), Field::ReadOnly), - (|o| o.inode.mode = Mode::new(0o444), Field::Mode), + (|o| o.inode.mode = Some(Mode::new(0o444).unwrap()), Field::Mode), ( |o| o.inode.user_xattrs = Some(Box::default()), Field::ExtendedAttributes, diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs index 433591a..cb6b6a9 100644 --- a/src/uapi16/writer.rs +++ b/src/uapi16/writer.rs @@ -865,14 +865,14 @@ mod tests { root.inode.user_xattrs = Some(Box::default()); root.inode.gid = Some(1000); root.inode.mtime_nsec = Some(1_699_999_000_000_000_000); - root.inode.mode = Mode::new(0o775); + root.inode.mode = Some(Mode::new(0o775).unwrap()); root.inode.uid = Some(1000); let owned_directory = |name_of: &str| { let mut owned = directory(name_of); owned.inode.user_xattrs = Some(Box::default()); owned.inode.gid = Some(1000); owned.inode.mtime_nsec = Some(1_699_999_000_000_000_000); - owned.inode.mode = Mode::new(0o775); + owned.inode.mode = Some(Mode::new(0o775).unwrap()); owned.inode.uid = Some(1000); owned }; @@ -880,7 +880,7 @@ mod tests { file.inode.user_xattrs = Some(Box::default()); file.inode.gid = Some(1000); file.inode.mtime_nsec = Some(1_700_000_000_000_000_000); - file.inode.mode = Mode::new(0o664); + file.inode.mode = Some(Mode::new(0o664).unwrap()); file.sha256 = "608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b" .parse() .ok(); @@ -1272,7 +1272,7 @@ mod tests { ..RootObject::default() }; root.inode.read_only = Some(true); - root.inode.mode = Mode::new(0o755); + root.inode.mode = Some(Mode::new(0o755).unwrap()); assert_eq!( refused(&root), ( @@ -1573,7 +1573,7 @@ mod tests { r#"{"mode":420,"name":"x","readOnly":true,"size":1,"type":"fifo"}"#.into(), |o| { (o.inode_type, o.size) = (InodeType::Fifo, Some(1)); - (o.inode.mode, o.inode.read_only) = (Mode::new(0o644), Some(true)); + (o.inode.mode, o.inode.read_only) = (Some(Mode::new(0o644).unwrap()), Some(true)); }, Problem::FieldNotPermitted, ), @@ -1581,7 +1581,10 @@ mod tests { // feature the manifest does not record. ( r#"{"mTimeNSec":1,"mode":420,"name":"x","readOnly":true}"#.into(), - |o| (o.inode.mtime_nsec, o.inode.mode, o.inode.read_only) = (Some(1), Mode::new(0o644), Some(true)), + |o| { + (o.inode.mtime_nsec, o.inode.mode) = (Some(1), Some(Mode::new(0o644).unwrap())); + o.inode.read_only = Some(true); + }, Problem::Contradiction, ), // A value, before a field of a feature the manifest does not @@ -1870,7 +1873,7 @@ mod tests { ), (|o| o.major = Some(1), Problem::FieldNotPermitted, Some(Field::Major)), ( - |o| (o.inode_type, o.inode.mode) = (InodeType::Symlink, Mode::new(0o777)), + |o| (o.inode_type, o.inode.mode) = (InodeType::Symlink, Some(Mode::new(0o777).unwrap())), Problem::FieldNotPermitted, Some(Field::Mode), ), @@ -1895,7 +1898,7 @@ mod tests { // readOnly against mode and against gptFlags, both ways, and // gptFlags against the field of one of its flags. ( - |o| (o.inode.read_only, o.inode.mode) = (Some(true), Mode::new(0o644)), + |o| (o.inode.read_only, o.inode.mode) = (Some(true), Some(Mode::new(0o644).unwrap())), Problem::Contradiction, Some(Field::ReadOnly), ), From 700f9d5a305890129a4eed651c300ac8798649fd Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 17:47:35 +0100 Subject: [PATCH 07/32] uapi16: drop the Deref of Name Name derefs to str. The Rust API guidelines keep Deref for smart pointers, and a Name isn't one. It's a string that was checked against the rules of the specification and that has an order of its own. Through Deref every method of str becomes a method of Name, and a Name can never stop being a str without breaking callers. So drop it before 0.1.0. as_str(), AsRef, Display, the comparisons with str and &str, From for String and the TryFrom impls stay. A caller that used a Name as a str calls as_str() now. In the crate that's about thirty places, most of them in the error messages of content.rs. No functional changes. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/content.rs | 50 +++++++++++++++++++++++-------------------- src/uapi16/decode.rs | 4 ++-- src/uapi16/lib.rs | 3 ++- src/uapi16/name.rs | 15 +++---------- src/uapi16/object.rs | 2 +- 5 files changed, 35 insertions(+), 39 deletions(-) diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index fbb28b6..7a1d5c0 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -97,8 +97,8 @@ impl<'a> Reference<'a> { if let Some(total) = self.original_size.filter(|&total| total != len) { let message = format!( "{}: {} is {} bytes, the manifest says {}", - name.escape_debug(), - self.file.escape_debug(), + name.as_str().escape_debug(), + self.file.as_str().escape_debug(), len, total ); @@ -109,8 +109,8 @@ impl<'a> Reference<'a> { if end.is_none_or(|end| end > len) { let message = format!( "{}: {} is too short for offset {} and size {}", - name.escape_debug(), - self.file.escape_debug(), + name.as_str().escape_debug(), + self.file.as_str().escape_debug(), self.offset, size ); @@ -127,8 +127,8 @@ impl<'a> Reference<'a> { OpenError::NotRegular => { let message = format!( "{}: {} is not a regular file", - name.escape_debug(), - self.file.escape_debug() + name.as_str().escape_debug(), + self.file.as_str().escape_debug() ); return Error::new(ErrorKind::Source(SourceProblem::NotRegular), message).named(name.as_str()); } @@ -141,8 +141,8 @@ impl<'a> Reference<'a> { }; let message = format!( "{}: failed to open {}: {}", - name.escape_debug(), - self.file.escape_debug(), + name.as_str().escape_debug(), + self.file.as_str().escape_debug(), error ); Error::new(ErrorKind::Source(problem), message) @@ -178,7 +178,7 @@ impl FileObject { if self.contents.is_empty() { let message = format!( "'{}' is a {} without contents objects, which has no data", - self.name.escape_debug(), + self.name.as_str().escape_debug(), self.inode_type ); return Error::new(ErrorKind::Unsupported(UnsupportedContent::Absent), message).named(self.name.as_str()); @@ -196,7 +196,7 @@ impl FileObject { let ways = ways.join(" or "); let message = format!( "'{}' is only available through {}, which is not supported", - self.name.escape_debug(), + self.name.as_str().escape_debug(), ways ); Error::new(ErrorKind::Unsupported(UnsupportedContent::UrlOrEncoding), message) @@ -321,7 +321,7 @@ impl Contents { } let message = format!( "'{}' is a part of literal contents that do not match the hash in the manifest", - object.name.escape_debug() + object.name.as_str().escape_debug() ); Err(Error::new(ErrorKind::Content(ContentProblem::HashMismatch), message).named(object.name.as_str())) } @@ -390,7 +390,7 @@ impl<'a> ContentCheck<'a> { if let Some(size) = self.size.filter(|&size| added > size.saturating_sub(self.len)) { let message = format!( "'{}' has more than the {} bytes the manifest says", - self.name.escape_debug(), + self.name.as_str().escape_debug(), size ); return Err(Error::new(ErrorKind::Content(ContentProblem::SizeMismatch), message) @@ -410,7 +410,7 @@ impl<'a> ContentCheck<'a> { if let Some(size) = self.size.filter(|&size| size != self.len) { let message = format!( "'{}' is {} bytes, the manifest says {}", - self.name.escape_debug(), + self.name.as_str().escape_debug(), self.len, size ); @@ -419,7 +419,10 @@ impl<'a> ContentCheck<'a> { .sizes(Some(self.len), Some(size))); } if self.context.map(Finalize::finalize) != self.sha256 { - let message = format!("'{}' does not match the hash in the manifest", self.name.escape_debug()); + let message = format!( + "'{}' does not match the hash in the manifest", + self.name.as_str().escape_debug() + ); return Err(Error::new(ErrorKind::Content(ContentProblem::HashMismatch), message).named(self.name.as_str())); } Ok(self.len) @@ -683,7 +686,7 @@ impl CopyFailure { let name = &object.name; let (problem, what) = match self { CopyFailure::ReadFailed(error) => { - let message = format!("{}: failed to read {}: {}", name.escape_debug(), place, error); + let message = format!("{}: failed to read {}: {}", name.as_str().escape_debug(), place, error); return Error::new(ErrorKind::Source(SourceProblem::Unreadable), message) .named(name.as_str()) .caused_by(error); @@ -693,7 +696,7 @@ impl CopyFailure { CopyFailure::HashMismatch => (ContentProblem::HashMismatch, "does not match the hash in the manifest"), CopyFailure::SourceChanged => (ContentProblem::SourceChanged, "changed while it was read"), }; - let message = format!("{}: {} {}", name.escape_debug(), place, what); + let message = format!("{}: {} {}", name.as_str().escape_debug(), place, what); Error::new(ErrorKind::Content(problem), message).named(name.as_str()) } } @@ -902,7 +905,8 @@ impl ContentSource for DirectorySource { } else { DataExtent::PartOfFile }; - let failed = |failure: CopyFailure| failure.into_error(object, &reference.file.escape_debug().to_string()); + let failed = + |failure: CopyFailure| failure.into_error(object, &reference.file.as_str().escape_debug().to_string()); let Some(sha256) = object.original_sha256_to_check(reference.original_sha256, extent) else { return pieces.copy_data(sink).map_err(failed); }; @@ -968,7 +972,7 @@ impl StreamSource { fn note_served(&mut self, name: &Name, size: u64) { let (last, last_size) = self.last.get_or_insert_with(Default::default); last.clear(); - last.push_str(name); + last.push_str(name.as_str()); *last_size = size; } } @@ -992,14 +996,14 @@ impl ContentSource for StreamSource { if reference.offset != 0 { let message = format!( "{}: an offset cannot be used with streamed contents", - name.escape_debug() + name.as_str().escape_debug() ); return Err( Error::new(ErrorKind::Unsupported(UnsupportedContent::OffsetInStream), message).named(name.as_str()), ); } let Some(size) = object.size else { - let message = format!("{}: streamed contents need a known size", name.escape_debug()); + let message = format!("{}: streamed contents need a known size", name.as_str().escape_debug()); return Err(Error::new(ErrorKind::Unsupported(UnsupportedContent::NoSize), message) .at(Field::Size) .named(name.as_str())); @@ -1023,7 +1027,7 @@ impl ContentSource for StreamSource { if copied < size { let message = format!( "{}: the stream ended {} bytes early", - name.escape_debug(), + name.as_str().escape_debug(), size - copied ); return Err(Error::new(ErrorKind::Content(ContentProblem::StreamEnded), message) @@ -1033,8 +1037,8 @@ impl ContentSource for StreamSource { if context.map(Finalize::finalize) != sha256 { let message = format!( "{}: {} does not match the hash in the manifest", - name.escape_debug(), - reference.file.escape_debug() + name.as_str().escape_debug(), + reference.file.as_str().escape_debug() ); return Err(Error::new(ErrorKind::Content(ContentProblem::HashMismatch), message).named(name.as_str())); } diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index e20c51a..66d5a90 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -297,9 +297,9 @@ impl Draft { /// The name the record gives, valid or not. fn stated_name(&self) -> Option<&str> { if !self.object.name.is_root() { - return Some(&self.object.name); + return Some(self.object.name.as_str()); } - self.name.as_deref().or(self.invalid_name.as_deref()) + self.name.as_ref().map(Name::as_str).or(self.invalid_name.as_deref()) } /// The fields of a partition, which are made when the first of them is diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index ccb96c5..66c9083 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -321,8 +321,9 @@ pub(crate) mod testing { let (root, root_text) = recording_all(); let directories: Vec = object .name + .as_str() .match_indices('/') - .map(|(end, _)| directory(&object.name[..end])) + .map(|(end, _)| directory(&object.name.as_str()[..end])) .collect(); let mut records = written(&root, |writer| { for directory in &directories { diff --git a/src/uapi16/name.rs b/src/uapi16/name.rs index 72b8569..feda7a4 100644 --- a/src/uapi16/name.rs +++ b/src/uapi16/name.rs @@ -4,7 +4,6 @@ use std::cmp::Ordering; use std::fmt; use std::iter; -use std::ops::Deref; use std::str::FromStr; use crate::strict::StringRules; @@ -236,14 +235,6 @@ impl Name { } } -impl Deref for Name { - type Target = str; - - fn deref(&self) -> &str { - &self.0 - } -} - impl Ord for Name { fn cmp(&self, other: &Name) -> Ordering { NamePair::new(&self.0, &other.0).ordering() @@ -771,12 +762,12 @@ mod tests { assert_eq!(Name::ROOT.join("a").unwrap().join("b").unwrap(), "a/b"); // The length of the whole name counts. let mut deep = Name::ROOT; - while deep.len() + 2 * (long.len() + 1) <= Name::MAX_LEN { + while deep.as_str().len() + 2 * (long.len() + 1) <= Name::MAX_LEN { deep = deep.join(&long).unwrap(); } - let room = Name::MAX_LEN - (deep.len() + 1); + let room = Name::MAX_LEN - (deep.as_str().len() + 1); assert!(room > 0); - assert_eq!(deep.join(&"y".repeat(room)).unwrap().len(), Name::MAX_LEN); + assert_eq!(deep.join(&"y".repeat(room)).unwrap().as_str().len(), Name::MAX_LEN); assert_eq!(deep.join(&"y".repeat(room + 1)), Err(NameProblem::TooLong)); // A component that is too long, and wrong in another way too, is // refused for its length, as the whole name is. diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 495fc73..13983ee 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -1245,7 +1245,7 @@ impl FileObject { /// true of everything in it. pub fn check_validity(&self, now_usec: u64) -> Result<(), Error> { self.validity - .check(now_usec, self.name.escape_debug()) + .check(now_usec, self.name.as_str().escape_debug()) .map_err(|e| e.named(self.name.as_str())) } } From 6db11eeefeab4181a9b98d20d90d360701deb78b Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Mon, 23 Nov 2026 10:27:38 +0100 Subject: [PATCH 08/32] uapi16: refuse names below a name reserved for the manifest Name::new() holds the names the specification reserves for the manifest only against the whole name. "Uapi16Manifest.d/inside" is refused, since it begins with "Uapi16Manifest.", but "Uapi16Manifest/x" is a valid name. Its directory isn't: "Uapi16Manifest" is reserved, so no manifest can list it. A file below it can never be listed either, and the reader refuses one as Misplaced, since the object of its directory never comes right before it. So refuse a name whose first component is reserved, with NameProblem::Reserved like the reserved name itself. The reader then reports such a file as InvalidName, which says what is wrong with it. Name::is_reserved() goes by the first component as well, so it says what Name::new() refuses, and the docs of Name and of NameProblem::Reserved say so too. With that every directory a name is in has a valid name, which the next commit relies on. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/decode.rs | 9 +++++++++ src/uapi16/name.rs | 33 +++++++++++++++++++++++---------- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index 66d5a90..d38ffa3 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -2340,6 +2340,15 @@ mod tests { e.to_string(), format!("manifest object 1: name is longer than 4095 bytes: '{}x'", name) ); + // A name below one that is reserved for the manifest is reserved as + // well: its directory cannot be listed, so it could only come out + // of place. + let e = refused(r#"{"name":"Uapi16Manifest/x"}"#); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::InvalidName)); + assert_eq!( + e.to_string(), + "manifest object 1: name is reserved for the manifest: 'Uapi16Manifest/x'" + ); } /// A `readOnly` the reader filled in is not one the object has: the diff --git a/src/uapi16/name.rs b/src/uapi16/name.rs index feda7a4..e390a93 100644 --- a/src/uapi16/name.rs +++ b/src/uapi16/name.rs @@ -38,9 +38,9 @@ const RULES: StringRules = STRING_RULES.without(StringRules::NO_NUL); /// single slashes, and none of them is empty, `.` or `..`. It has no /// control characters and no noncharacters, and it is at most /// [`Name::MAX_LEN`] bytes long. Its components are not limited on their -/// own. It is not `Uapi16Manifest` and does not begin with -/// `Uapi16Manifest.`, the names the manifest itself and what belongs to it -/// have inside the tree. +/// own. Its first component is not `Uapi16Manifest` and does not begin +/// with `Uapi16Manifest.`, the names the manifest itself and what belongs +/// to it have inside the tree. /// /// Names are ordered the way the specification orders the file objects of /// a manifest in code point order: component by component, each compared @@ -74,8 +74,10 @@ pub enum NameProblem { Empty, /// It is longer than [`Name::MAX_LEN`] bytes. TooLong, - /// It is `Uapi16Manifest` or begins with `Uapi16Manifest.`, which the - /// specification reserves for the manifest and what belongs to it. + /// Its first component is `Uapi16Manifest` or begins with + /// `Uapi16Manifest.`, which the specification reserves for the manifest + /// and what belongs to it. A file below a directory of such a name + /// cannot be listed, since its directory cannot be. Reserved, /// It contains a control character: ASCII 0 to 31 or 127. ContainsControlCharacter, @@ -216,12 +218,13 @@ impl Name { } /// Whether `name` is one the specification reserves for the manifest - /// and what belongs to it: `Uapi16Manifest`, or a name that begins - /// with `Uapi16Manifest.`. A file of such a name is not listed in a - /// manifest. + /// and what belongs to it: one whose first component is `Uapi16Manifest` + /// or begins with `Uapi16Manifest.`. A file of such a name is not listed + /// in a manifest, and neither is a file below a directory of such a + /// name. pub fn is_reserved(name: &str) -> bool { name.strip_prefix(FILENAME) - .is_some_and(|rest| rest.is_empty() || rest.starts_with(SUFFIX_SEPARATOR)) + .is_some_and(|rest| rest.is_empty() || rest.starts_with(SUFFIX_SEPARATOR) || rest.starts_with(SEPARATOR)) } /// Whether this is the name of the root file object. @@ -435,6 +438,8 @@ mod tests { ("Uapi16Manifest.sig", NameProblem::Reserved), ("Uapi16Manifest.gz", NameProblem::Reserved), ("Uapi16Manifest.d/inside", NameProblem::Reserved), + ("Uapi16Manifest/inside", NameProblem::Reserved), + ("Uapi16Manifest/a/b", NameProblem::Reserved), ] { assert_eq!(Name::new(name), Err(reason), "{:?}", name); assert_eq!(name.parse::(), Err(reason), "{:?}", name); @@ -579,7 +584,11 @@ mod tests { if name.len() > Name::MAX_LEN { reasons.push(NameProblem::TooLong); } - if Name::is_reserved(name) { + let first = name.split(SEPARATOR).next().unwrap_or_default(); + if first + .strip_prefix(FILENAME) + .is_some_and(|rest| rest.is_empty() || rest.starts_with(SUFFIX_SEPARATOR)) + { reasons.push(NameProblem::Reserved); } if name.chars().any(|c| c.is_ascii_control()) { @@ -701,14 +710,18 @@ mod tests { "Uapi16Manifest.", "Uapi16Manifest.sig", "Uapi16Manifest.d/x", + "Uapi16Manifest/x", + "Uapi16Manifest/x/y", ] { assert!(Name::is_reserved(name), "{:?}", name); } for name in [ "", "Uapi16Manifest2", + "Uapi16Manifest2/x", "Uapi16Manifes", "sub/Uapi16Manifest", + "sub/Uapi16Manifest/x", "x.Uapi16Manifest", ] { assert!(!Name::is_reserved(name), "{:?}", name); From b3fbaf262eec49c8810d0176ef16d205fb3cd757 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Mon, 23 Nov 2026 10:27:58 +0100 Subject: [PATCH 09/32] uapi16: return a Name from Name::parent() Name::parent() returns a &str. A caller that wants to look the directory up, join a name to it or hand it on as a name has to make a Name of it with Name::new(), which checks it all over again, or is left with a string where it wants a Name. Since the previous commit every directory a name is in has a valid name. Each part of a name has valid text and valid components, and only its first component could be reserved, which Name::new() refuses for the whole name now. So parent() returns Option, and copies the part of the name in front of its last component into a Name without checking it again: None for the root, and Name::ROOT for a name at the top. The tests check that Name::new() takes every parent as it is, for every valid name they have and for the names they make up. The reader looks at the parent of an object only to name it in the error for an object that is out of place. It keeps doing that without a copy, through a crate-private parent_str(). file_name() keeps returning a &str. A component is not always a name: "a/Uapi16Manifest" is one, "Uapi16Manifest" isn't. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/name.rs | 43 ++++++++++++++++++++++++++++++++++++------ src/uapi16/sequence.rs | 2 +- 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/src/uapi16/name.rs b/src/uapi16/name.rs index e390a93..74a93f5 100644 --- a/src/uapi16/name.rs +++ b/src/uapi16/name.rs @@ -202,9 +202,18 @@ impl Name { self.0.split(SEPARATOR).filter(|component| !component.is_empty()) } - /// The name of the directory the file is in, which is the empty name - /// of the root for a file at the top. The root has none. - pub fn parent(&self) -> Option<&str> { + /// The name of the directory the file is in, [`Name::ROOT`] for a file + /// at the top. The root has none. + pub fn parent(&self) -> Option { + // The first component of a name is not reserved, and that is the + // only check a part of a name could fail. So every directory a name + // is in has a name, which is not checked again. + self.parent_str().map(|parent| Name(parent.to_owned())) + } + + /// The name of the directory the file is in, as [`Name::parent`] has + /// it, without a copy. + pub(crate) fn parent_str(&self) -> Option<&str> { if self.is_root() { return None; } @@ -403,6 +412,7 @@ mod tests { "xUapi16Manifest.sig", ] { let parsed = Name::new(name).unwrap_or_else(|_| panic!("{:?}", name)); + check_parent(&parsed); assert_eq!(parsed, name); assert_eq!(parsed.as_str(), name); assert_eq!(parsed.to_string(), name); @@ -652,7 +662,10 @@ mod tests { ] { let reasons = reasons(&name); match Name::new(name.as_str()) { - Ok(_) => assert!(reasons.is_empty(), "{:?} {:?}", name, reasons), + Ok(valid) => { + assert!(reasons.is_empty(), "{:?} {:?}", name, reasons); + check_parent(&valid); + } Err(reason) => assert!(reasons.contains(&reason), "{:?} {:?} {:?}", name, reason, reasons), } valid[usize::from(reasons.is_empty())] += 1; @@ -685,14 +698,32 @@ mod tests { let name = Name::new("a/b/c").unwrap(); assert_eq!(name.components().collect::>(), ["a", "b", "c"]); assert_eq!(name.components().next_back(), Some("c")); - assert_eq!(name.parent(), Some("a/b")); + assert_eq!(name.parent(), Some(Name::new("a/b").unwrap())); assert_eq!(name.file_name(), Some("c")); let top = Name::new("a").unwrap(); - assert_eq!(top.parent(), Some("")); + assert_eq!(top.parent(), Some(Name::ROOT)); assert_eq!(top.file_name(), Some("a")); assert_eq!(Name::ROOT.components().count(), 0); assert_eq!(Name::ROOT.parent(), None); assert_eq!(Name::ROOT.file_name(), None); + // A component is not always a name: the last one of a name can be + // one that is reserved at the top. + let below = Name::new("a/Uapi16Manifest").unwrap(); + assert_eq!(below.file_name(), Some("Uapi16Manifest")); + assert_eq!(Name::new("Uapi16Manifest"), Err(NameProblem::Reserved)); + for name in full_tree_names(&["a", "...", ".hidden", "Uapi16Manifest2", "b c"], 3) { + check_parent(&name); + } + } + + /// Checks that the directory `name` is in has a name, which is why + /// [`Name::parent`] does not check it again. + fn check_parent(name: &Name) { + match name.parent() { + None => assert!(name.is_root()), + Some(parent) if parent.is_root() => assert_eq!(name.components().count(), 1, "{:?}", name), + Some(parent) => assert_eq!(Name::new(parent.as_str()), Ok(parent), "{:?}", name), + } } #[test] diff --git a/src/uapi16/sequence.rs b/src/uapi16/sequence.rs index 7b071e4..7666cc7 100644 --- a/src/uapi16/sequence.rs +++ b/src/uapi16/sequence.rs @@ -117,7 +117,7 @@ impl SequenceCheck { // at once. let pair = NamePair::new(&self.last, name); if !pair.second_is_in_open_directory(self.last_type) { - let directory = object.name.parent().unwrap_or_default(); + let directory = object.name.parent_str().unwrap_or_default(); return Err(Error::manifest( Problem::Misplaced, format!( From 971b621bc9feca327212db40d1c4a534bb33c082 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 17:48:01 +0100 Subject: [PATCH 10/32] uapi16: return only the serial from volume_serial() FileSystemIdentity::volume_serial() returns the serial number together with the field it was taken from. Nobody calls it yet, and a caller that needs to know where the serial came from can look at whether fatSerial is set. That's all the rule of the specification says: fatSerial where it's given, and the first four bytes of fsUUID otherwise. So return Option and leave the Field out of it. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/object.rs | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 13983ee..54a9113 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -844,24 +844,19 @@ impl FileSystemIdentity { /// The volume serial number a FAT or exFAT file system takes from the /// identity, as the specification has it: `fatSerial`, or else the one - /// derived from `fsUUID`, see [`FatSerial::from_uuid`]. Returned with - /// the field it comes from. + /// derived from `fsUUID`, see [`FatSerial::from_uuid`]. /// /// ``` - /// use uapi16::{FatSerial, Field, FileSystemIdentity}; + /// use uapi16::{FatSerial, FileSystemIdentity}; /// /// let mut identity = FileSystemIdentity::default(); /// identity.uuid = "1234abcd-5678-4ef0-9abc-def012345678".parse().ok(); - /// assert_eq!(identity.volume_serial(), Some((FatSerial(0x1234_abcd), Field::FsUuid))); + /// assert_eq!(identity.volume_serial(), Some(FatSerial(0x1234_abcd))); /// identity.fat_serial = Some(FatSerial(0x5678_9abc)); - /// assert_eq!(identity.volume_serial(), Some((FatSerial(0x5678_9abc), Field::FatSerial))); + /// assert_eq!(identity.volume_serial(), Some(FatSerial(0x5678_9abc))); /// ``` - pub fn volume_serial(&self) -> Option<(FatSerial, Field)> { - match (self.fat_serial, &self.uuid) { - (Some(serial), _) => Some((serial, Field::FatSerial)), - (None, Some(uuid)) => Some((FatSerial::from_uuid(uuid), Field::FsUuid)), - (None, None) => None, - } + pub fn volume_serial(&self) -> Option { + self.fat_serial.or_else(|| self.uuid.as_ref().map(FatSerial::from_uuid)) } } From 64d9d340a6506f1b5623e7a4aefc627becd4bad1 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 17:48:56 +0100 Subject: [PATCH 11/32] uapi16: make the hash methods inherent Sha256::EMPTY and Sha256Context::finalize() come from the traits Digest and Finalize, so a caller has to import a trait to use either of them. The traits abstract over the hash algorithm, but the specification only has SHA-256 and there's no second implementation in sight. Make EMPTY an associated constant of Sha256 and finalize() a method of Sha256Context, and drop both traits. Callers drop their imports of Digest and Finalize and nothing else changes for them. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/content.rs | 7 ++--- src/uapi16/decode.rs | 1 - src/uapi16/digest.rs | 64 ++++++++++--------------------------------- src/uapi16/lib.rs | 4 +-- src/uapi16/object.rs | 1 - src/uapi16/reader.rs | 2 +- src/uapi16/writer.rs | 1 - 7 files changed, 21 insertions(+), 59 deletions(-) diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index 7a1d5c0..42c52cb 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -8,7 +8,7 @@ use std::fmt; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::ops::Range; -use crate::digest::{Finalize, Sha256Context}; +use crate::digest::Sha256Context; use crate::error::{ContentProblem, Error, ErrorKind, Field, SourceProblem, UnsupportedContent}; use crate::object::{Contents, FileObject, InodeType, Location}; use crate::{Name, Sha256}; @@ -418,7 +418,7 @@ impl<'a> ContentCheck<'a> { .named(self.name.as_str()) .sizes(Some(self.len), Some(size))); } - if self.context.map(Finalize::finalize) != self.sha256 { + if self.context.map(Sha256Context::finalize) != self.sha256 { let message = format!( "'{}' does not match the hash in the manifest", self.name.as_str().escape_debug() @@ -1034,7 +1034,7 @@ impl ContentSource for StreamSource { .named(name.as_str()) .sizes(Some(copied), Some(size))); } - if context.map(Finalize::finalize) != sha256 { + if context.map(Sha256Context::finalize) != sha256 { let message = format!( "{}: {} does not match the hash in the manifest", name.as_str().escape_debug(), @@ -1087,7 +1087,6 @@ impl ContentSource for StreamSource { mod tests { use super::*; use crate::testing::{json, manifest, read_whole, sequence, HELLO, TRAILER, WORLD}; - use crate::Digest; use std::cell::{Cell, RefCell}; use std::rc::Rc; diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index d38ffa3..75d4bd3 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -20,7 +20,6 @@ use std::num::NonZeroU64; use serde_core::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor}; use crate::base64::Base64; -use crate::digest::Digest; use crate::error::{Error, Field, Problem}; use crate::hex::Hex; use crate::object::{ diff --git a/src/uapi16/digest.rs b/src/uapi16/digest.rs index 4a88faa..4df4b8b 100644 --- a/src/uapi16/digest.rs +++ b/src/uapi16/digest.rs @@ -9,33 +9,6 @@ use sha2::Digest as _; use crate::hex::Hex; -/// A hash a manifest gives for contents. -/// -/// The specification defines one algorithm, SHA-256, which is [`Sha256`], -/// and says that another one gets fields of its own next to the SHA-256 -/// ones. A type with this trait gives the hash of no data and a context -/// that computes the hash of data that comes in pieces. -pub trait Digest: Copy + Eq { - /// The hash of no data. Contents of size 0 have this hash, and only - /// they do. - const EMPTY: Self; - - /// Computes the hash of data that comes in pieces. What is written to - /// it is the data, and [`Finalize::finalize`] gives the hash of all of - /// it. - type Context: Default + io::Write + Finalize; -} - -/// The computation of a hash, which ends with the hash of all the data, -/// such as [`Digest::Context`]. -pub trait Finalize { - /// The hash it computes. - type Digest: Digest; - - /// Ends the computation and gives the hash of all the data. - fn finalize(self) -> Self::Digest; -} - /// A SHA-256 hash, as the `sha256` field of a file object and the /// `encodedSha256` and `originalSha256` fields of a contents object have /// it. @@ -45,7 +18,7 @@ pub trait Finalize { /// the digits, is refused. /// /// ``` -/// use uapi16::{Digest, Sha256}; +/// use uapi16::Sha256; /// /// let hash = Sha256::digest(b"hello"); /// assert_eq!( @@ -75,6 +48,12 @@ impl std::error::Error for InvalidDigest {} impl Sha256 { /// The size of the hash in bytes. pub const SIZE: usize = 32; + /// The hash of no data. Contents of size 0 have this hash, and only + /// they do. + pub const EMPTY: Sha256 = Sha256([ + 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, + 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, + ]); /// The hash of `data`. pub fn digest(data: &[u8]) -> Sha256 { @@ -87,15 +66,6 @@ impl Sha256 { } } -impl Digest for Sha256 { - const EMPTY: Sha256 = Sha256([ - 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, - 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, - ]); - - type Context = Sha256Context; -} - impl From<[u8; Sha256::SIZE]> for Sha256 { fn from(bytes: [u8; Sha256::SIZE]) -> Sha256 { Sha256(bytes) @@ -139,7 +109,7 @@ impl FromStr for Sha256 { /// /// ``` /// use std::io::Write; -/// use uapi16::{Finalize, Sha256, Sha256Context}; +/// use uapi16::{Sha256, Sha256Context}; /// /// let mut context = Sha256Context::default(); /// context.update(b"hel"); @@ -155,12 +125,9 @@ impl Sha256Context { pub fn update(&mut self, data: &[u8]) { self.0.update(data); } -} - -impl Finalize for Sha256Context { - type Digest = Sha256; - fn finalize(self) -> Sha256 { + /// Ends the computation and gives the hash of all the data. + pub fn finalize(self) -> Sha256 { Sha256(self.0.finalize().into()) } } @@ -207,20 +174,19 @@ mod tests { assert_eq!(Sha256::digest(b""), Sha256::EMPTY); } - /// The hash of `data` computed with nothing but what [`Digest`] gives: - /// a context that takes the data and is then finalized. - fn computed(data: &[u8]) -> D { + /// The hash of `data` computed with a context the data is written to. + fn computed(data: &[u8]) -> Sha256 { use std::io::Write; - let mut context = D::Context::default(); + let mut context = Sha256Context::default(); context.write_all(data).unwrap(); context.finalize() } #[test] fn contexts() { - assert_eq!(computed::(b""), Sha256::EMPTY); - assert_eq!(computed::(b"hello"), Sha256::digest(b"hello")); + assert_eq!(computed(b""), Sha256::EMPTY); + assert_eq!(computed(b"hello"), Sha256::digest(b"hello")); } #[test] diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 66c9083..2f11a9e 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -18,7 +18,7 @@ //! - [`Writer`] writes a manifest record by record to a [`Write`], and //! checks it the way the reader does. [`Encoder`] does the same into a //! string, and does no I/O. [`Sha256Context`] computes the hash of a file -//! while it is read, and [`Finalize::finalize`] returns it. +//! while it is read, and [`Sha256Context::finalize`] returns it. //! - [`RootObject`], [`FileObject`], [`Contents`] and [`Signature`] are the //! objects, and [`Name`], [`InodeType`], [`Mode`], [`DosFlags`], //! [`InodeFlags`], [`Sha256`] and [`Uuid`] what their fields hold. What @@ -105,7 +105,7 @@ mod writer; pub use blocking::{Reader, Writer}; pub use content::{ContentCheck, ContentSource, Data, Directory, DirectorySource, OpenError, Reference, StreamSource}; -pub use digest::{Digest, Finalize, InvalidDigest, Sha256, Sha256Context}; +pub use digest::{InvalidDigest, Sha256, Sha256Context}; pub use error::{ContentProblem, Error, ErrorKind, Field, Problem, SourceProblem, UnsupportedContent, ValidityProblem}; pub use features::{Features, Order, UnknownFeature}; pub use name::{Name, NameProblem}; diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 54a9113..c82ecb5 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -1392,7 +1392,6 @@ impl Signature { #[cfg(test)] mod tests { use super::*; - use crate::Digest; /// Gives an object a field. type Give = fn(&mut T); diff --git a/src/uapi16/reader.rs b/src/uapi16/reader.rs index e639882..34baa3a 100644 --- a/src/uapi16/reader.rs +++ b/src/uapi16/reader.rs @@ -491,7 +491,7 @@ mod tests { use crate::error::{ErrorKind, Field}; use crate::testing::{manifest, sequence, ROOT, SIGNATURE, TRAILER}; use crate::testing::{read_whole, Whole, HELLO, PIECES}; - use crate::{Digest, DosFlags, Features, FlagStates, InodeFlags, InodeType, Order, Reader, RootObject, Sha256}; + use crate::{DosFlags, Features, FlagStates, InodeFlags, InodeType, Order, Reader, RootObject, Sha256}; use std::collections::BTreeMap; /// Reads `bytes` to the end and returns the names of the file objects diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs index cb6b6a9..7a5fb1b 100644 --- a/src/uapi16/writer.rs +++ b/src/uapi16/writer.rs @@ -12,7 +12,6 @@ use serde_core::ser::{Serialize, SerializeMap, Serializer}; use crate::base64::Base64; use crate::decode::{Subject, ROOT_RECORD}; -use crate::digest::Digest; use crate::error::{Error, Field, Problem}; use crate::hex::Hex; use crate::object::{ From 59feceff0e36e96c0ba9e06fd0c798733418bbfe Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 17:51:59 +0100 Subject: [PATCH 12/32] uapi16: call the bytes of a file its data The specification calls the bytes of a file its data. "contents" is the `contents` field of a file object with the contents objects in it, and "source" is where a contents object says the data is. The crate mixes these up. ContentCheck checks data, copy_contents() copies data, ContentProblem says what is wrong with data, and the docs say contents for the bytes all over the place. Use the terms of the specification for everything that is about the bytes of a file: - Data becomes DataLocation, and FileObject::data() becomes data_location() - Reference becomes ExternalFile, and its field `file` becomes `name` - copy_contents() becomes copy_data() - ContentCheck becomes DataCheck - InodeType::has_contents() becomes has_data() - ContentProblem becomes DataProblem, and ErrorKind::Content becomes ErrorKind::Data - UnsupportedContent becomes UnsupportedData, still inside ErrorKind::Unsupported The docs follow. The error messages stay as they are. Callers use the new names. No functional changes. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/base64.rs | 4 +- src/uapi16/content.rs | 283 +++++++++++++++++++++-------------------- src/uapi16/decode.rs | 4 +- src/uapi16/digest.rs | 8 +- src/uapi16/error.rs | 64 +++++----- src/uapi16/features.rs | 4 +- src/uapi16/lib.rs | 24 ++-- src/uapi16/object.rs | 20 ++- 8 files changed, 207 insertions(+), 204 deletions(-) diff --git a/src/uapi16/base64.rs b/src/uapi16/base64.rs index 6d1b2ea..cec734d 100644 --- a/src/uapi16/base64.rs +++ b/src/uapi16/base64.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LGPL-2.1-or-later -//! Base64, the way a manifest carries literal contents, the values of -//! extended attributes and the data of a signature. +//! Base64, the way a manifest carries the data of a literal, the values +//! of extended attributes and the data of a signature. use std::fmt; diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index 42c52cb..6c726f4 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LGPL-2.1-or-later -//! The contents of the files a manifest describes: where they are, and -//! copying them from there with the sizes and hashes of the manifest -//! checked. +//! The data of the files a manifest describes: where it is, and copying +//! it from there with the sizes and hashes of the manifest checked. use std::collections::HashMap; use std::fmt; @@ -9,7 +8,7 @@ use std::io::{self, Read, Seek, SeekFrom, Write}; use std::ops::Range; use crate::digest::Sha256Context; -use crate::error::{ContentProblem, Error, ErrorKind, Field, SourceProblem, UnsupportedContent}; +use crate::error::{DataProblem, Error, ErrorKind, Field, SourceProblem, UnsupportedData}; use crate::object::{Contents, FileObject, InodeType, Location}; use crate::{Name, Sha256}; @@ -30,14 +29,15 @@ const FILE_ENTRY_BYTES: usize = size_of::<(Sha256, u64)>() + size_of::()) as u64; -/// Where the data of a file object is, as [`FileObject::data`] finds it. +/// Where the data of a file object is, as [`FileObject::data_location`] +/// finds it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] -pub enum Data<'a> { +pub enum DataLocation<'a> { /// In the manifest itself. This is the data. Literal(&'a [u8]), /// Outside of the manifest. A [`ContentSource`] has it. - External(Reference<'a>), + External(ExternalFile<'a>), } /// The file a file object has its data in, next to the manifest. @@ -46,10 +46,10 @@ pub enum Data<'a> { /// file objects can each be a part of the same file. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] -pub struct Reference<'a> { - /// The file: the one a contents object names, or else the one of the +pub struct ExternalFile<'a> { + /// The name of the file: the one a contents object names, or else the /// object's own name. - pub file: &'a Name, + pub name: &'a Name, /// Where the data starts in the file. pub offset: u64, /// The size of the whole file, if the manifest gives it. @@ -67,12 +67,12 @@ enum DataExtent { PartOfFile, } -impl<'a> Reference<'a> { - /// The reference of an object to the file `file`, by way of the - /// contents object `contents` if one names it. - fn new(file: &'a Name, contents: Option<&'a Contents>) -> Reference<'a> { - Reference { - file, +impl<'a> ExternalFile<'a> { + /// The file `name` an object has its data in, by way of the contents + /// object `contents` if one names it. + fn new(name: &'a Name, contents: Option<&'a Contents>) -> ExternalFile<'a> { + ExternalFile { + name, offset: contents.map_or(0, |contents| contents.offset), original_size: contents.and_then(|contents| contents.original_size), original_sha256: contents.and_then(|contents| contents.original_sha256), @@ -83,7 +83,7 @@ impl<'a> Reference<'a> { /// of it and of the data of `object` in it. Returns the size of that /// data: the rest of the file from the offset on when the object gives /// none. A length that does not fit is a - /// [`ContentProblem::SizeMismatch`]. + /// [`DataProblem::SizeMismatch`]. /// /// The data is the part of the file that starts at the offset and is /// as long as the object says, whatever else the file holds. So the @@ -91,14 +91,13 @@ impl<'a> Reference<'a> { /// where the manifest gives that. fn check_len(&self, object: &FileObject, len: u64) -> Result { let name = &object.name; - let mismatch = |message: String| { - Error::new(ErrorKind::Content(ContentProblem::SizeMismatch), message).named(name.as_str()) - }; + let mismatch = + |message: String| Error::new(ErrorKind::Data(DataProblem::SizeMismatch), message).named(name.as_str()); if let Some(total) = self.original_size.filter(|&total| total != len) { let message = format!( "{}: {} is {} bytes, the manifest says {}", name.as_str().escape_debug(), - self.file.as_str().escape_debug(), + self.name.as_str().escape_debug(), len, total ); @@ -110,7 +109,7 @@ impl<'a> Reference<'a> { let message = format!( "{}: {} is too short for offset {} and size {}", name.as_str().escape_debug(), - self.file.as_str().escape_debug(), + self.name.as_str().escape_debug(), self.offset, size ); @@ -119,8 +118,8 @@ impl<'a> Reference<'a> { Ok(size) } - /// The error for the file of the reference that `object` cannot be - /// taken from. + /// The error for the file that the data of `object` cannot be taken + /// from. fn unavailable(&self, object: &FileObject, error: OpenError) -> Error { let name = &object.name; let error = match error { @@ -128,7 +127,7 @@ impl<'a> Reference<'a> { let message = format!( "{}: {} is not a regular file", name.as_str().escape_debug(), - self.file.as_str().escape_debug() + self.name.as_str().escape_debug() ); return Error::new(ErrorKind::Source(SourceProblem::NotRegular), message).named(name.as_str()); } @@ -142,7 +141,7 @@ impl<'a> Reference<'a> { let message = format!( "{}: failed to open {}: {}", name.as_str().escape_debug(), - self.file.as_str().escape_debug(), + self.name.as_str().escape_debug(), error ); Error::new(ErrorKind::Source(problem), message) @@ -152,7 +151,7 @@ impl<'a> Reference<'a> { } impl FileObject { - /// Where the data of the file is: the contents of a regular file, the + /// Where the data of the file is: the bytes of a regular file, the /// target of a symbolic link, or the manifest of its own that a /// directory refers to. /// @@ -164,10 +163,10 @@ impl FileObject { /// objects has it in the file of its own name too. Data that has to be /// decoded or fetched from a URL is not taken: an object whose every /// contents object gives it that way fails with - /// [`UnsupportedContent::UrlOrEncoding`]. Any other object without + /// [`UnsupportedData::UrlOrEncoding`]. Any other object without /// contents objects has no data and fails with - /// [`UnsupportedContent::Absent`]. - pub fn data(&self) -> Result, Error> { + /// [`UnsupportedData::Absent`]. + pub fn data_location(&self) -> Result, Error> { self.unencoded_data() .map(|(data, _)| data) .ok_or_else(|| self.unsupported()) @@ -181,7 +180,7 @@ impl FileObject { self.name.as_str().escape_debug(), self.inode_type ); - return Error::new(ErrorKind::Unsupported(UnsupportedContent::Absent), message).named(self.name.as_str()); + return Error::new(ErrorKind::Unsupported(UnsupportedData::Absent), message).named(self.name.as_str()); } let mut ways: Vec = self .contents @@ -199,7 +198,7 @@ impl FileObject { self.name.as_str().escape_debug(), ways ); - Error::new(ErrorKind::Unsupported(UnsupportedContent::UrlOrEncoding), message) + Error::new(ErrorKind::Unsupported(UnsupportedData::UrlOrEncoding), message) .named(self.name.as_str()) .valued(ways) } @@ -209,9 +208,9 @@ impl FileObject { /// literal, else in the file of the first contents object that names /// one. The specification implies a contents object for a regular file /// that has none, with the file of its own name. - fn unencoded_data(&self) -> Option<(Data<'_>, Option<&Contents>)> { + fn unencoded_data(&self) -> Option<(DataLocation<'_>, Option<&Contents>)> { if self.contents.is_empty() { - let implied = Data::External(Reference::new(&self.name, None)); + let implied = DataLocation::External(ExternalFile::new(&self.name, None)); return (self.inode_type == InodeType::Regular).then_some((implied, None)); } let mut file = None; @@ -219,7 +218,7 @@ impl FileObject { match &contents.location { Location::Literal(literal) => { let data = self.data_in_literal(literal, contents.offset); - return Some((Data::Literal(data), Some(contents))); + return Some((DataLocation::Literal(data), Some(contents))); } Location::File(name) => { file.get_or_insert((name, contents)); @@ -230,7 +229,12 @@ impl FileObject { Location::Url(_) => {} } } - file.map(|(name, contents)| (Data::External(Reference::new(name, Some(contents))), Some(contents))) + file.map(|(name, contents)| { + ( + DataLocation::External(ExternalFile::new(name, Some(contents))), + Some(contents), + ) + }) } /// The data of the file in the literal `literal`: from `offset` on, as @@ -248,7 +252,7 @@ impl FileObject { /// Whether the data of the file is outside of the manifest, where a /// [`ContentSource`] has it. pub fn has_external_data(&self) -> bool { - matches!(self.unencoded_data(), Some((Data::External(_), _))) + matches!(self.unencoded_data(), Some((DataLocation::External(_), _))) } /// The hash the manifest gives for all of the file the data is in, @@ -268,25 +272,25 @@ impl FileObject { /// Writes the data of the file to `sink`: the literal of the manifest, /// or what `source` has. Checks the data against the size and the hash - /// the object gives with a [`ContentCheck`], and returns how many bytes + /// the object gives with a [`DataCheck`], and returns how many bytes /// it is. An object whose data this crate cannot take fails as - /// [`FileObject::data`] does, and the source is not asked for it. An - /// error of the sink comes back as it was. + /// [`FileObject::data_location`] does, and the source is not asked for + /// it. An error of the sink comes back as it was. /// /// What was written to the sink when this fails is not the data of /// the file. - pub fn copy_contents(&self, source: &mut dyn ContentSource, sink: &mut dyn Write) -> Result { + pub fn copy_data(&self, source: &mut dyn ContentSource, sink: &mut dyn Write) -> Result { let (data, contents) = self.unencoded_data().ok_or_else(|| self.unsupported())?; let mut checked = CheckedSink { sink, - check: ContentCheck::new(self), + check: DataCheck::new(self), failure: None, }; let copied = match data { - Data::Literal(data) => contents + DataLocation::Literal(data) => contents .map_or(Ok(()), |contents| contents.check_literal(self, data)) .and_then(|()| checked.write_all(data).map_err(Error::from)), - Data::External(reference) => source.copy(self, &reference, &mut checked), + DataLocation::External(file) => source.copy(self, &file, &mut checked), }; let CheckedSink { check, failure, .. } = checked; // What the check refused and what the sink failed to take reached @@ -323,7 +327,7 @@ impl Contents { "'{}' is a part of literal contents that do not match the hash in the manifest", object.name.as_str().escape_debug() ); - Err(Error::new(ErrorKind::Content(ContentProblem::HashMismatch), message).named(object.name.as_str())) + Err(Error::new(ErrorKind::Data(DataProblem::HashMismatch), message).named(object.name.as_str())) } } @@ -335,29 +339,29 @@ impl Contents { /// objects say of the files the data is in, their sizes and hashes, is /// for whoever reads those files to check, such as a [`DirectorySource`]. /// -/// [`FileObject::copy_contents`] checks what it copies with one. A caller +/// [`FileObject::copy_data`] checks what it copies with one. A caller /// that moves the data itself, such as a copy in an async runtime, hands -/// every piece of it to [`ContentCheck::update`] before it writes it on, -/// and calls [`ContentCheck::finish`] after the last one. +/// every piece of it to [`DataCheck::update`] before it writes it on, +/// and calls [`DataCheck::finish`] after the last one. /// /// ``` -/// use uapi16::{ContentCheck, FileObject, Name, Sha256}; +/// use uapi16::{DataCheck, FileObject, Name, Sha256}; /// /// let mut object = FileObject::new(Name::new("hello.txt")?); /// object.size = Some(5); /// object.sha256 = Some(Sha256::digest(b"hello")); -/// let mut check = ContentCheck::new(&object); +/// let mut check = DataCheck::new(&object); /// check.update(b"hel")?; /// check.update(b"lo")?; /// assert_eq!(check.finish()?, 5); /// -/// let mut check = ContentCheck::new(&object); +/// let mut check = DataCheck::new(&object); /// check.update(b"hello")?; /// assert!(check.update(b"!").is_err()); /// # Ok::<(), Box>(()) /// ``` #[derive(Debug)] -pub struct ContentCheck<'a> { +pub struct DataCheck<'a> { /// The name of the object, which an error carries. name: &'a Name, /// The size the object gives. @@ -370,10 +374,10 @@ pub struct ContentCheck<'a> { len: u64, } -impl<'a> ContentCheck<'a> { +impl<'a> DataCheck<'a> { /// A check of the data of `object`, of which nothing has passed yet. - pub fn new(object: &'a FileObject) -> ContentCheck<'a> { - ContentCheck { + pub fn new(object: &'a FileObject) -> DataCheck<'a> { + DataCheck { name: &object.name, size: object.size, sha256: object.sha256, @@ -393,7 +397,7 @@ impl<'a> ContentCheck<'a> { self.name.as_str().escape_debug(), size ); - return Err(Error::new(ErrorKind::Content(ContentProblem::SizeMismatch), message) + return Err(Error::new(ErrorKind::Data(DataProblem::SizeMismatch), message) .named(self.name.as_str()) .sizes(None, Some(size))); } @@ -414,7 +418,7 @@ impl<'a> ContentCheck<'a> { self.len, size ); - return Err(Error::new(ErrorKind::Content(ContentProblem::SizeMismatch), message) + return Err(Error::new(ErrorKind::Data(DataProblem::SizeMismatch), message) .named(self.name.as_str()) .sizes(Some(self.len), Some(size))); } @@ -423,17 +427,17 @@ impl<'a> ContentCheck<'a> { "'{}' does not match the hash in the manifest", self.name.as_str().escape_debug() ); - return Err(Error::new(ErrorKind::Content(ContentProblem::HashMismatch), message).named(self.name.as_str())); + return Err(Error::new(ErrorKind::Data(DataProblem::HashMismatch), message).named(self.name.as_str())); } Ok(self.len) } } -/// A sink that hands what is written to it to a [`ContentCheck`] before it +/// A sink that hands what is written to it to a [`DataCheck`] before it /// passes it on. struct CheckedSink<'a, 'b> { sink: &'a mut dyn Write, - check: ContentCheck<'b>, + check: DataCheck<'b>, /// Why what was written did not go through, if it did not: the check /// refused it, or the sink failed to take it. The writer is told with /// an I/O error of that kind, and this is the error to report. Nothing @@ -470,15 +474,14 @@ impl Write for CheckedSink<'_, '_> { /// [`StreamSource`] from one stream that carries it all, in the order of /// the manifest. A consumer hands a source every file object, in the /// order of the manifest: those whose data it takes to -/// [`FileObject::copy_contents`], which calls [`ContentSource::copy`], and +/// [`FileObject::copy_data`], which calls [`ContentSource::copy`], and /// the others to [`ContentSource::skip`]. After the last one it calls /// [`ContentSource::end`]. pub trait ContentSource { - /// Writes the data of `object` to `sink`, which `reference` says - /// where to find: exactly `object.size` bytes when the object has a - /// size. An error of the sink comes back as it was, and one of the - /// source names the object. - fn copy(&mut self, object: &FileObject, reference: &Reference<'_>, sink: &mut dyn Write) -> Result<(), Error>; + /// Writes the data of `object`, which is in `file`, to `sink`: exactly + /// `object.size` bytes when the object has a size. An error of the sink + /// comes back as it was, and one of the source names the object. + fn copy(&mut self, object: &FileObject, file: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error>; /// Passes over the data of `object`, which the consumer does not take. /// A source that hands out the data in the order of the manifest reads @@ -693,11 +696,11 @@ impl CopyFailure { } // The error of the sink comes back as it was. CopyFailure::WriteFailed(error) => return Error::from(error), - CopyFailure::HashMismatch => (ContentProblem::HashMismatch, "does not match the hash in the manifest"), - CopyFailure::SourceChanged => (ContentProblem::SourceChanged, "changed while it was read"), + CopyFailure::HashMismatch => (DataProblem::HashMismatch, "does not match the hash in the manifest"), + CopyFailure::SourceChanged => (DataProblem::SourceChanged, "changed while it was read"), }; let message = format!("{}: {} {}", name.as_str().escape_debug(), place, what); - Error::new(ErrorKind::Content(problem), message).named(name.as_str()) + Error::new(ErrorKind::Data(problem), message).named(name.as_str()) } } @@ -884,30 +887,29 @@ impl Pieces<'_, F> { } impl ContentSource for DirectorySource { - fn copy(&mut self, object: &FileObject, reference: &Reference<'_>, sink: &mut dyn Write) -> Result<(), Error> { - let (file, len) = self + fn copy(&mut self, object: &FileObject, file: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error> { + let (opened, len) = self .directory - .open(reference.file) - .map_err(|e| reference.unavailable(object, e))?; - let size = reference.check_len(object, len)?; + .open(file.name) + .map_err(|e| file.unavailable(object, e))?; + let size = file.check_len(object, len)?; self.buffer.resize(COPY_SIZE, 0); let mut pieces = Pieces { - file, + file: opened, buffer: &mut self.buffer, len, piece_size: PieceHashes::piece_size(len), pos: 0, // check_len made sure that this is inside the file. - data: reference.offset..reference.offset + size, + data: file.offset..file.offset + size, }; let extent = if pieces.data == (0..len) { DataExtent::WholeFile } else { DataExtent::PartOfFile }; - let failed = - |failure: CopyFailure| failure.into_error(object, &reference.file.as_str().escape_debug().to_string()); - let Some(sha256) = object.original_sha256_to_check(reference.original_sha256, extent) else { + let failed = |failure: CopyFailure| failure.into_error(object, &file.name.as_str().escape_debug().to_string()); + let Some(sha256) = object.original_sha256_to_check(file.original_sha256, extent) else { return pieces.copy_data(sink).map_err(failed); }; let piece_count = PieceHashes::piece_count(len); @@ -991,28 +993,28 @@ impl fmt::Debug for StreamSource { } impl ContentSource for StreamSource { - fn copy(&mut self, object: &FileObject, reference: &Reference<'_>, sink: &mut dyn Write) -> Result<(), Error> { + fn copy(&mut self, object: &FileObject, file: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error> { let name = &object.name; - if reference.offset != 0 { + if file.offset != 0 { let message = format!( "{}: an offset cannot be used with streamed contents", name.as_str().escape_debug() ); return Err( - Error::new(ErrorKind::Unsupported(UnsupportedContent::OffsetInStream), message).named(name.as_str()), + Error::new(ErrorKind::Unsupported(UnsupportedData::OffsetInStream), message).named(name.as_str()), ); } let Some(size) = object.size else { let message = format!("{}: streamed contents need a known size", name.as_str().escape_debug()); - return Err(Error::new(ErrorKind::Unsupported(UnsupportedContent::NoSize), message) + return Err(Error::new(ErrorKind::Unsupported(UnsupportedData::NoSize), message) .at(Field::Size) .named(name.as_str())); }; // The stream has all of the file where the contents object gives // its size, and that is the size of the object. A part cannot be // checked against the hash of the whole file. - let sha256 = if reference.original_size == Some(size) { - object.original_sha256_to_check(reference.original_sha256, DataExtent::WholeFile) + let sha256 = if file.original_size == Some(size) { + object.original_sha256_to_check(file.original_sha256, DataExtent::WholeFile) } else { None }; @@ -1030,7 +1032,7 @@ impl ContentSource for StreamSource { name.as_str().escape_debug(), size - copied ); - return Err(Error::new(ErrorKind::Content(ContentProblem::StreamEnded), message) + return Err(Error::new(ErrorKind::Data(DataProblem::StreamEnded), message) .named(name.as_str()) .sizes(Some(copied), Some(size))); } @@ -1038,9 +1040,9 @@ impl ContentSource for StreamSource { let message = format!( "{}: {} does not match the hash in the manifest", name.as_str().escape_debug(), - reference.file.as_str().escape_debug() + file.name.as_str().escape_debug() ); - return Err(Error::new(ErrorKind::Content(ContentProblem::HashMismatch), message).named(name.as_str())); + return Err(Error::new(ErrorKind::Data(DataProblem::HashMismatch), message).named(name.as_str())); } Ok(()) } @@ -1051,7 +1053,7 @@ impl ContentSource for StreamSource { /// every object after it would get the wrong bytes. fn skip(&mut self, object: &FileObject) -> Result<(), Error> { if object.has_external_data() { - object.copy_contents(self, &mut io::sink())?; + object.copy_data(self, &mut io::sink())?; } Ok(()) } @@ -1068,7 +1070,7 @@ impl ContentSource for StreamSource { if read == 0 { return Ok(()); } - let kind = ErrorKind::Content(ContentProblem::SizeMismatch); + let kind = ErrorKind::Data(DataProblem::SizeMismatch); Err(match &self.last { Some((name, size)) => { let message = format!("{}: the stream goes on after the last file", name.escape_debug()); @@ -1247,10 +1249,10 @@ mod tests { objects(&records).pop().unwrap() } - /// Copies the contents of `object` from `source`. + /// Copies the data of `object` from `source`. fn copy(object: &FileObject, source: &mut dyn ContentSource) -> Result, Error> { let mut out = Vec::new(); - let written = object.copy_contents(source, &mut out)?; + let written = object.copy_data(source, &mut out)?; assert_eq!(written, out.len() as u64); Ok(out) } @@ -1270,12 +1272,12 @@ mod tests { // Without contents objects a regular file has it in the file of its // name. let o = object(r#"{"name":"dir/x","size":5}"#); - let Data::External(reference) = o.data().unwrap() else { + let DataLocation::External(external) = o.data_location().unwrap() else { panic!() }; - assert_eq!(reference.file.as_str(), "dir/x"); + assert_eq!(external.name.as_str(), "dir/x"); assert_eq!( - (reference.offset, reference.original_size, reference.original_sha256), + (external.offset, external.original_size, external.original_sha256), (0, None, None) ); assert!(o.has_external_data()); @@ -1290,12 +1292,12 @@ mod tests { r#"{{"name":"x","size":3,"contents":[{},{},{{"file":"z"}}]}}"#, others, file )); - let Data::External(reference) = o.data().unwrap() else { + let DataLocation::External(external) = o.data_location().unwrap() else { panic!() }; - assert_eq!(reference.file.as_str(), "data/y.bin"); - assert_eq!((reference.offset, reference.original_size), (2, Some(9))); - assert_eq!(reference.original_sha256, WORLD.parse().ok()); + assert_eq!(external.name.as_str(), "data/y.bin"); + assert_eq!((external.offset, external.original_size), (2, Some(9))); + assert_eq!(external.original_sha256, WORLD.parse().ok()); assert!(o.has_external_data()); // A literal is taken before any file, wherever it is among the // contents objects. One in an encoding is not. @@ -1307,16 +1309,21 @@ mod tests { format!(r#"{{"literal":"AAAA","encoding":"gzip"}},{},{}"#, file, literal), ] { let o = object(&format!(r#"{{"name":"x","size":3,"contents":[{}]}}"#, contents)); - assert_eq!(o.data().unwrap(), Data::Literal(b"hel"), "{}", contents); + assert_eq!( + o.data_location().unwrap(), + DataLocation::Literal(b"hel"), + "{}", + contents + ); assert!(!o.has_external_data()); } // A contents object that names no place is the file of the // object's name. let o = object(r#"{"name":"x","contents":[{"offset":1,"originalSize":4}]}"#); - let Data::External(reference) = o.data().unwrap() else { + let DataLocation::External(external) = o.data_location().unwrap() else { panic!() }; - assert_eq!((reference.file.as_str(), reference.offset), ("x", 1)); + assert_eq!((external.name.as_str(), external.offset), ("x", 1)); // The part of a literal that the object is. for (record, data) in [ ( @@ -1328,8 +1335,8 @@ mod tests { (r#"{"name":"x","contents":[{"literal":"aGVsbG8="}],"size":2}"#, "he"), ] { assert_eq!( - object(record).data().unwrap(), - Data::Literal(data.as_bytes()), + object(record).data_location().unwrap(), + DataLocation::Literal(data.as_bytes()), "{}", record ); @@ -1339,8 +1346,8 @@ mod tests { r#"{"name":"dir/x","contents":[{"url":"https://example.com/x"},{"file":"x.zst","encoding":"zstd"},"#, r#"{"url":"http://example.com/x"},{"literal":"AAAA","encoding":"gzip"},{"encoding":"zstd"}]}"# )); - let e = o.data().unwrap_err(); - assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::UrlOrEncoding)); + let e = o.data_location().unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::UrlOrEncoding)); assert_eq!(e.name(), Some("dir/x")); assert_eq!(e.value(), Some("'gzip' encoding or 'zstd' encoding or a URL")); assert_eq!( @@ -1370,8 +1377,8 @@ mod tests { let mut stream = &b"hello"[..]; let mut source = StreamSource::new(&mut stream); for (o, kind) in none.iter().zip(["dir", "fifo", "lnk"]) { - let e = o.data().unwrap_err(); - assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::Absent)); + let e = o.data_location().unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::Absent)); assert_eq!(e.name(), Some(o.name.as_str())); assert_eq!( e.to_string(), @@ -1379,7 +1386,7 @@ mod tests { ); assert!(!o.has_external_data()); let e = copy(o, &mut source).unwrap_err(); - assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::Absent)); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::Absent)); source.skip(o).unwrap(); } assert_eq!(copy(&none[3], &mut source).unwrap(), b"hello"); @@ -1391,7 +1398,7 @@ mod tests { r#"{"name":"l","type":"lnk","contents":[{"literal":"eA=="}]}"#, ]); assert!(some[0].has_external_data()); - assert_eq!(some[1].data().unwrap(), Data::Literal(b"x")); + assert_eq!(some[1].data_location().unwrap(), DataLocation::Literal(b"x")); let files = Files::of(&[("d.Uapi16Manifest", b"abc")]); let mut source = DirectorySource::new(&files); assert_eq!(copy(&some[0], &mut source).unwrap(), b"abc"); @@ -1403,7 +1410,7 @@ mod tests { let files = Files::of(&[("a", b"hello world"), ("empty", b""), ("dir/b", b"hello")]); let mut source = DirectorySource::new(&files); for (record, data) in [ - // A whole file, by the name of the object and by a file reference. + // A whole file, by the name of the object and by a file external. (format!(r#"{{"name":"dir/b","size":5,"sha256":"{}"}}"#, HELLO), "hello"), ( format!( @@ -1470,8 +1477,8 @@ mod tests { fn files_that_are_not_what_the_manifest_says() { let files = Files::of(&[("a", b"hello world"), ("dir/b", b"hello")]); let mut source = DirectorySource::new(&files); - let size = ErrorKind::Content(ContentProblem::SizeMismatch); - let hash = ErrorKind::Content(ContentProblem::HashMismatch); + let size = ErrorKind::Data(DataProblem::SizeMismatch); + let hash = ErrorKind::Data(DataProblem::HashMismatch); for (record, expected) in [ // A file too short for the data. ( @@ -1638,7 +1645,7 @@ mod tests { let mut source = DirectorySource::new(&files); let changed = |file: &str| { ( - ErrorKind::Content(ContentProblem::SourceChanged), + ErrorKind::Data(DataProblem::SourceChanged), Some("x"), None, None, @@ -1740,7 +1747,7 @@ mod tests { let files = Files::default(); let mut source = DirectorySource::new(&files); let changed = ( - ErrorKind::Content(ContentProblem::SourceChanged), + ErrorKind::Data(DataProblem::SourceChanged), Some("x"), None, None, @@ -1895,7 +1902,7 @@ mod tests { sha256.unwrap_or_default() )) }; - let hash = ErrorKind::Content(ContentProblem::HashMismatch); + let hash = ErrorKind::Data(DataProblem::HashMismatch); let parts = [ (5, 10), (0, 1), @@ -2250,7 +2257,7 @@ mod tests { assert_eq!( facts(&e), ( - ErrorKind::Content(ContentProblem::StreamEnded), + ErrorKind::Data(DataProblem::StreamEnded), Some("d/b"), Some(2), Some(5), @@ -2265,7 +2272,7 @@ mod tests { assert_eq!( facts(&e), ( - ErrorKind::Content(ContentProblem::SizeMismatch), + ErrorKind::Data(DataProblem::SizeMismatch), Some("d/b"), None, Some(5), @@ -2279,7 +2286,7 @@ mod tests { assert_eq!( facts(&e), ( - ErrorKind::Content(ContentProblem::SizeMismatch), + ErrorKind::Data(DataProblem::SizeMismatch), None, None, Some(0), @@ -2291,7 +2298,7 @@ mod tests { // Contents that are not the ones the manifest describes. let mut stream = &b"hellp"[..]; let e = copy(streamed[0], &mut StreamSource::new(&mut stream)).unwrap_err(); - assert_eq!(e.kind(), ErrorKind::Content(ContentProblem::HashMismatch)); + assert_eq!(e.kind(), ErrorKind::Data(DataProblem::HashMismatch)); } /// The hash the manifest gives for all of a file is checked where a @@ -2299,7 +2306,7 @@ mod tests { /// the hash of the object alone. #[test] fn whole_files_and_parts_in_a_stream() { - let hash = ErrorKind::Content(ContentProblem::HashMismatch); + let hash = ErrorKind::Data(DataProblem::HashMismatch); let check = |o: &FileObject, data: &'static [u8]| { let mut stream = data; let copied = copy(o, &mut StreamSource::new(&mut stream)); @@ -2363,7 +2370,7 @@ mod tests { let mut stream = &b"hello"[..]; let mut source = StreamSource::new(&mut stream); let e = copy(&object(r#"{"name":"x"}"#), &mut source).unwrap_err(); - assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::NoSize)); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::NoSize)); assert_eq!((e.name(), e.field()), (Some("x"), Some(Field::Size))); assert_eq!(e.to_string(), "x: streamed contents need a known size"); let e = copy( @@ -2371,7 +2378,7 @@ mod tests { &mut source, ) .unwrap_err(); - assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::OffsetInStream)); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::OffsetInStream)); assert_eq!(e.name(), Some("x")); assert_eq!(stream, b"hello"); } @@ -2400,15 +2407,15 @@ mod tests { // A skip fails where a copy would. let mut stream = &b"hellp"[..]; let e = StreamSource::new(&mut stream).skip(&all[0]).unwrap_err(); - assert_eq!(e.kind(), ErrorKind::Content(ContentProblem::HashMismatch)); + assert_eq!(e.kind(), ErrorKind::Data(DataProblem::HashMismatch)); let mut stream = &b"hel"[..]; let e = StreamSource::new(&mut stream).skip(&all[0]).unwrap_err(); - assert_eq!(e.kind(), ErrorKind::Content(ContentProblem::StreamEnded)); + assert_eq!(e.kind(), ErrorKind::Data(DataProblem::StreamEnded)); let mut stream = &b"hello"[..]; let e = StreamSource::new(&mut stream) .skip(&object(r#"{"name":"x"}"#)) .unwrap_err(); - assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::NoSize)); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::NoSize)); // A directory has nothing to read past. let files = Files::of(&[("a", b"hello")]); DirectorySource::new(&files).skip(&all[0]).unwrap(); @@ -2422,7 +2429,7 @@ mod tests { } impl ContentSource for Babbler { - fn copy(&mut self, _: &FileObject, _: &Reference<'_>, sink: &mut dyn Write) -> Result<(), Error> { + fn copy(&mut self, _: &FileObject, _: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error> { let written = sink.write_all(b"hello world"); if self.careful { written?; @@ -2434,38 +2441,38 @@ mod tests { #[test] fn checks_what_passes() { let o = object(&format!(r#"{{"name":"x","size":5,"sha256":"{}"}}"#, HELLO)); - let mut check = ContentCheck::new(&o); + let mut check = DataCheck::new(&o); for piece in [&b"he"[..], b"", b"llo"] { check.update(piece).unwrap(); } assert_eq!(check.finish().unwrap(), 5); // Too few bytes, the wrong ones, and too many. - let mut check = ContentCheck::new(&o); + let mut check = DataCheck::new(&o); check.update(b"hell").unwrap(); let e = check.finish().unwrap_err(); assert_eq!( facts(&e), ( - ErrorKind::Content(ContentProblem::SizeMismatch), + ErrorKind::Data(DataProblem::SizeMismatch), Some("x"), Some(4), Some(5), "'x' is 4 bytes, the manifest says 5".to_string() ) ); - let mut check = ContentCheck::new(&o); + let mut check = DataCheck::new(&o); check.update(b"world").unwrap(); assert_eq!( check.finish().unwrap_err().kind(), - ErrorKind::Content(ContentProblem::HashMismatch) + ErrorKind::Data(DataProblem::HashMismatch) ); - let mut check = ContentCheck::new(&o); + let mut check = DataCheck::new(&o); check.update(b"hell").unwrap(); let e = check.update(b"o!").unwrap_err(); assert_eq!( facts(&e), ( - ErrorKind::Content(ContentProblem::SizeMismatch), + ErrorKind::Data(DataProblem::SizeMismatch), Some("x"), None, Some(5), @@ -2477,7 +2484,7 @@ mod tests { assert_eq!(check.finish().unwrap(), 5); // Without a size and a hash it counts. let o = object(r#"{"name":"x","contents":[{"url":"https://example.com/x"}]}"#); - let mut check = ContentCheck::new(&o); + let mut check = DataCheck::new(&o); check.update(b"any").unwrap(); check.update(b"thing").unwrap(); assert_eq!(check.finish().unwrap(), 8); @@ -2487,8 +2494,8 @@ mod tests { let o = object(r#"{"name":"x","size":5}"#); for careful in [true, false] { let mut out = Vec::new(); - let e = o.copy_contents(&mut Babbler { careful }, &mut out).unwrap_err(); - assert_eq!(e.kind(), ErrorKind::Content(ContentProblem::SizeMismatch)); + let e = o.copy_data(&mut Babbler { careful }, &mut out).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Data(DataProblem::SizeMismatch)); assert_eq!((e.found_size(), e.expected_size()), (None, Some(5))); assert!(out.is_empty()); } @@ -2525,7 +2532,7 @@ mod tests { let sources: [(&FileObject, &mut dyn ContentSource); 3] = [(&o, &mut directory), (&o, &mut stream), (&literal, &mut empty)]; for (object, source) in sources { - let e = object.copy_contents(source, &mut Full(4)).unwrap_err(); + let e = object.copy_data(source, &mut Full(4)).unwrap_err(); assert_eq!(e.kind(), ErrorKind::Io); assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::ENOSPC)); } diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index 75d4bd3..b6c5e99 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -417,7 +417,7 @@ impl FileObject { pub(crate) fn check_permitted_fields(&self, subject: Subject<'_>) -> Result<(), Error> { let inode_type = self.inode_type; let not_permitted = |message: String| Error::manifest(Problem::FieldNotPermitted, message); - if self.size.is_some() && !inode_type.has_contents() { + if self.size.is_some() && !inode_type.has_data() { return Err( not_permitted(format!("{}: 'size' is not permitted on a {}", subject, inode_type)).at(Field::Size), ); @@ -438,7 +438,7 @@ impl FileObject { .at(Field::InodeToken), ); } - if (!self.contents.is_empty() || self.sha256.is_some()) && !inode_type.has_contents() { + if (!self.contents.is_empty() || self.sha256.is_some()) && !inode_type.has_data() { return Err(not_permitted(format!( "{}: 'contents' and 'sha256' are not permitted on a {}", subject, inode_type diff --git a/src/uapi16/digest.rs b/src/uapi16/digest.rs index 4df4b8b..042ab12 100644 --- a/src/uapi16/digest.rs +++ b/src/uapi16/digest.rs @@ -1,5 +1,5 @@ // SPDX-License-Identifier: LGPL-2.1-or-later -//! The hashes a manifest gives for the contents of files. +//! The hashes a manifest gives for the data of files. use std::fmt; use std::io; @@ -48,8 +48,8 @@ impl std::error::Error for InvalidDigest {} impl Sha256 { /// The size of the hash in bytes. pub const SIZE: usize = 32; - /// The hash of no data. Contents of size 0 have this hash, and only - /// they do. + /// The hash of no data. Data of size 0 has this hash, and only it + /// does. pub const EMPTY: Sha256 = Sha256([ 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, @@ -105,7 +105,7 @@ impl FromStr for Sha256 { } /// Computes the [`Sha256`] of data that comes in pieces, such as the -/// contents of a file a manifest is written for. +/// data of a file a manifest is written for. /// /// ``` /// use std::io::Write; diff --git a/src/uapi16/error.rs b/src/uapi16/error.rs index 54c4a4a..c9eed7c 100644 --- a/src/uapi16/error.rs +++ b/src/uapi16/error.rs @@ -185,43 +185,42 @@ pub enum SourceProblem { Unreadable, } -/// How contents fail to be what the manifest describes, found while they -/// are copied. +/// How the data of a file fails to be what the manifest describes, found +/// while it is copied. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] -pub enum ContentProblem { - /// They are not as many bytes as the manifest says, their file is too - /// short for them, or their file is not as long as the `originalSize` - /// the manifest gives, shorter or longer. +pub enum DataProblem { + /// It is not as many bytes as the manifest says, its file is too short + /// for it, or its file is not as long as the `originalSize` the + /// manifest gives, shorter or longer. SizeMismatch, - /// They do not have the hash the manifest says, or their file does not + /// It does not have the hash the manifest says, or its file does not /// have the hash the manifest gives for it. HashMismatch, - /// The stream they come from ended before they were complete. + /// The stream it comes from ended before it was complete. StreamEnded, - /// The file they are in changed while it was read: it is not as long - /// as it was when it was opened, or longer. + /// The file it is in changed while it was read: it is not as long as + /// it was when it was opened, or longer. SourceChanged, } -/// Contents that a manifest gives in a way this crate cannot take. +/// Data that a manifest gives in a way this crate cannot take. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] -pub enum UnsupportedContent { - /// They start at an offset in their file, and the source is a - /// [`StreamSource`](crate::StreamSource), which has them and nothing - /// else of the file. +pub enum UnsupportedData { + /// It starts at an offset in its file, and the source is a + /// [`StreamSource`](crate::StreamSource), which has it and nothing else + /// of the file. OffsetInStream, /// The object gives no size, and the source is a /// [`StreamSource`](crate::StreamSource), which needs it to know where - /// they end. + /// the data ends. NoSize, - /// Every contents object of the file has them at a URL or in an - /// encoding, and they would have to be fetched or decoded. + /// Every contents object of the file has it at a URL or in an + /// encoding, and it would have to be fetched or decoded. UrlOrEncoding, - /// There are none. The object has no contents objects, and only a - /// regular file has its contents in the file of its own name without - /// one. + /// There is none. The object has no contents objects, and only a + /// regular file has its data in the file of its own name without one. Absent, } @@ -245,10 +244,11 @@ pub enum ErrorKind { Manifest(Problem), /// The data of a file object cannot be had from where it is. Source(SourceProblem), - /// Contents are not what the manifest describes. - Content(ContentProblem), - /// The manifest gives contents in a way this crate cannot take. - Unsupported(UnsupportedContent), + /// The data of a file is not what the manifest describes. + Data(DataProblem), + /// The manifest gives the data of a file in a way this crate cannot + /// take. + Unsupported(UnsupportedData), /// A file object is revoked or outside its validity window. NotValid(ValidityProblem), /// Reading or writing failed. @@ -521,8 +521,7 @@ impl Error { self } - /// Notes what is not supported: the ways the contents are available - /// in. + /// Notes what is not supported: the ways the data is available in. #[must_use] pub(crate) fn valued(mut self, value: impl Into) -> Error { self.0.value = Some(value.into()); @@ -659,8 +658,8 @@ impl Error { } /// The size that was found, when the error is about a size and it is - /// known: for a [`ContentProblem::SizeMismatch`] and a - /// [`ContentProblem::StreamEnded`]. + /// known: for a [`DataProblem::SizeMismatch`] and a + /// [`DataProblem::StreamEnded`]. pub fn found_size(&self) -> Option { self.0.found_size } @@ -672,9 +671,8 @@ impl Error { self.0.expected_size } - /// What is not supported, for [`UnsupportedContent::UrlOrEncoding`]: - /// the ways the contents are available in, such as `'gzip' encoding or - /// a URL`. + /// What is not supported, for [`UnsupportedData::UrlOrEncoding`]: the + /// ways the data is available in, such as `'gzip' encoding or a URL`. pub fn value(&self) -> Option<&str> { self.0.value.as_deref() } @@ -766,7 +764,7 @@ mod tests { assert_eq!(e.to_string(), "message"); assert_eq!((e.found_size(), e.expected_size(), e.value()), (None, None, None)); assert!(e.io_error().is_none() && std::error::Error::source(&e).is_none()); - let e = Error::new(ErrorKind::Content(ContentProblem::SizeMismatch), String::new()) + let e = Error::new(ErrorKind::Data(DataProblem::SizeMismatch), String::new()) .sizes(Some(1), Some(2)) .valued("gzip"); assert_eq!( diff --git a/src/uapi16/features.rs b/src/uapi16/features.rs index c2ff73f..e7123ea 100644 --- a/src/uapi16/features.rs +++ b/src/uapi16/features.rs @@ -62,9 +62,9 @@ impl Features { pub const USER_NAME: Features = Features(1 << 3); /// `group-name`: the name of the owning group, the field `groupName`. pub const GROUP_NAME: Features = Features(1 << 4); - /// `size`: the size of the contents, the field `size`. + /// `size`: the size of the data, the field `size`. pub const SIZE: Features = Features(1 << 5); - /// `sha256`: the hash of the contents, the field `sha256`. + /// `sha256`: the hash of the data, the field `sha256`. pub const SHA256: Features = Features(1 << 6); /// `symlink`: the targets of symbolic links, the field `contents` of /// file objects of the type `lnk`. Every one of them has its target in diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 2f11a9e..be5a639 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -24,11 +24,11 @@ //! [`InodeFlags`], [`Sha256`] and [`Uuid`] what their fields hold. What //! the root file object and a file object both have is in //! [`InodeAttributes`] and [`ValidityWindow`]. -//! - [`ContentSource`] is where the contents of the files come from when a +//! - [`ContentSource`] is where the data of the files comes from when a //! manifest is applied: [`DirectorySource`] for the files next to the //! manifest and [`StreamSource`] for one stream with all of them. -//! [`FileObject::copy_contents`] copies the contents of a file and checks -//! them against the manifest with a [`ContentCheck`]. +//! [`FileObject::copy_data`] copies the data of a file and checks it +//! against the manifest with a [`DataCheck`]. //! //! A manifest that does not come through a [`Read`], such as one from an //! async runtime, goes to a [`Decoder`] as it comes. [`Decoder::step`] says @@ -48,10 +48,10 @@ //! [`Encoder::signature`] and [`Encoder::finish`] append its records to a //! string, and the caller sends them on. //! -//! Contents that do not go through a [`Write`] are checked with a -//! [`ContentCheck`]: [`ContentCheck::update`] takes them as they come, and -//! [`ContentCheck::finish`] says whether they have the size and the hash -//! the manifest gives. +//! Data that does not go through a [`Write`] is checked with a +//! [`DataCheck`]: [`DataCheck::update`] takes it as it comes, and +//! [`DataCheck::finish`] says whether it has the size and the hash the +//! manifest gives. //! //! A manifest is input from outside and can be very large. Reading one //! takes time in proportion to its size, and keeps one record without its @@ -62,8 +62,8 @@ //! //! Signature objects are read and not verified: that takes an OpenPGP or //! an X.509 implementation. [`Reader::signed_len`] says how much of the -//! manifest they sign. Contents that are stored in an encoding or that -//! have to be fetched from a URL are not taken. +//! manifest they sign. Data that is stored in an encoding or that has to +//! be fetched from a URL is not taken. //! //! The reader takes every field the specification has. A field it does //! not know is passed over, as the specification asks, unless it holds a @@ -104,9 +104,11 @@ mod strict; mod writer; pub use blocking::{Reader, Writer}; -pub use content::{ContentCheck, ContentSource, Data, Directory, DirectorySource, OpenError, Reference, StreamSource}; +pub use content::{ + ContentSource, DataCheck, DataLocation, Directory, DirectorySource, ExternalFile, OpenError, StreamSource, +}; pub use digest::{InvalidDigest, Sha256, Sha256Context}; -pub use error::{ContentProblem, Error, ErrorKind, Field, Problem, SourceProblem, UnsupportedContent, ValidityProblem}; +pub use error::{DataProblem, Error, ErrorKind, Field, Problem, SourceProblem, UnsupportedData, ValidityProblem}; pub use features::{Features, Order, UnknownFeature}; pub use name::{Name, NameProblem}; pub use object::{ diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index c82ecb5..7aad692 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -59,10 +59,11 @@ impl InodeType { } } - /// Whether an object of this type has contents: a regular file its - /// data, a symbolic link its target and a directory a manifest of its - /// own. Only such an object has a size, contents objects and a hash. - pub const fn has_contents(self) -> bool { + /// Whether an object of this type has data: a regular file the bytes + /// it holds, a symbolic link its target and a directory a manifest of + /// its own. Only such an object has a size, contents objects and a + /// hash. + pub const fn has_data(self) -> bool { matches!(self, InodeType::Regular | InodeType::Symlink | InodeType::Directory) } @@ -1102,11 +1103,11 @@ pub struct FileObject { /// `type`: the inode type. An object that does not say is a regular /// file. pub inode_type: InodeType, - /// `size`: the size of the contents in bytes. For a symbolic link that + /// `size`: the size of the data in bytes. For a symbolic link that /// is the length of its target, for a directory the size of the /// manifest of its own that `contents` refers to. pub size: Option, - /// `sha256`: the hash of the contents. + /// `sha256`: the hash of the data. pub sha256: Option, /// `contents`: where the contents can be taken from. Without any they /// are in the file of the object's name next to the manifest. @@ -1410,12 +1411,7 @@ mod tests { assert_eq!(name.parse(), Ok(inode_type)); assert_eq!(inode_type.as_str(), name); assert_eq!(inode_type.to_string(), name); - assert_eq!( - inode_type.has_contents(), - ["reg", "dir", "lnk"].contains(&name), - "{}", - name - ); + assert_eq!(inode_type.has_data(), ["reg", "dir", "lnk"].contains(&name), "{}", name); assert_eq!(inode_type.is_device(), ["chr", "blk"].contains(&name), "{}", name); } for name in ["", "REG", "file", "symlink", "reg "] { From f9e4723ef4e58da1ad02a5ed1c272ab4318206ee Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 17:54:29 +0100 Subject: [PATCH 13/32] uapi16: rename the object types and the data providers Signature and Contents are the signature object and the contents object of the specification, but the names read like a signature and like the contents of a file. Location is what the specification calls the source of a contents object. And ContentSource, DirectorySource and StreamSource aren't sources in the sense of the specification at all. They provide the data of the files when a manifest is applied. Rename them: - Signature becomes SignatureObject, which Object::Signature holds - Contents becomes ContentsObject - Location becomes ContentsSource, and the field `location` of a contents object becomes `source` - ContentSource becomes DataProvider - DirectorySource becomes DirectoryProvider - StreamSource becomes StreamProvider FileObject, RootObject, Object, MAX_CONTENTS and SourceProblem keep their names. The decoder's own marker for a contents object had the name ContentsObject already and is called ContentsElement now. Callers use the new names. Writer::signature() and Encoder::signature() take a &SignatureObject. No functional changes. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/blocking.rs | 10 +- src/uapi16/content.rs | 322 +++++++++++++++++------------------ src/uapi16/decode.rs | 69 ++++---- src/uapi16/error.rs | 12 +- src/uapi16/lib.rs | 41 ++--- src/uapi16/object.rs | 57 ++++--- src/uapi16/reader.rs | 4 +- src/uapi16/sequence.rs | 4 +- src/uapi16/tests/fixtures.rs | 4 +- src/uapi16/writer.rs | 96 ++++++----- 10 files changed, 313 insertions(+), 306 deletions(-) diff --git a/src/uapi16/blocking.rs b/src/uapi16/blocking.rs index f5f0869..bd221d7 100644 --- a/src/uapi16/blocking.rs +++ b/src/uapi16/blocking.rs @@ -8,7 +8,7 @@ use std::iter::FusedIterator; use crate::decode::ROOT_RECORD; use crate::error::Error; -use crate::object::{FileObject, RootObject, Signature}; +use crate::object::{FileObject, RootObject, SignatureObject}; use crate::reader::{Decoder, Object, Step}; use crate::writer::Encoder; @@ -131,7 +131,7 @@ impl Reader { /// its record separator. None as long as no signature object was read. /// /// This crate does not verify signatures. With this number and the - /// [`Signature`] objects a caller can. + /// signature objects, see [`SignatureObject`], a caller can. pub fn signed_len(&self) -> Option { self.decoder.signed_len() } @@ -289,7 +289,7 @@ impl Writer { /// Writes a signature object. No file object can follow it: it would /// be one the signature does not cover. - pub fn signature(&mut self, signature: &Signature) -> Result<(), Error> { + pub fn signature(&mut self, signature: &SignatureObject) -> Result<(), Error> { self.send_record(|encoder| encoder.encode_signature(signature)) } @@ -623,7 +623,7 @@ mod tests { writer.file(&largest).unwrap(); assert_eq!(writer.get_ref().len() - before, MAX_RECORD_SIZE); assert!(writer.encoder.record.capacity() <= RECORD_CAPACITY); - let mut signature = Signature::new("pkcs7"); + let mut signature = SignatureObject::new("pkcs7"); signature.data = Some(vec![0; MAX_RECORD_SIZE]); let e = writer.signature(&signature).unwrap_err(); assert_eq!( @@ -654,7 +654,7 @@ mod tests { writer.file(&FileObject::new(name("a"))).unwrap(); let signed = writer.get_ref().len(); let hash = Sha256::digest(writer.get_ref()); - let mut signature = Signature::new("pkcs7"); + let mut signature = SignatureObject::new("pkcs7"); signature.data = Some(hash.as_bytes().to_vec()); writer.signature(&signature).unwrap(); let bytes = writer.finish().unwrap(); diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index 6c726f4..6fa7b7e 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -9,13 +9,13 @@ use std::ops::Range; use crate::digest::Sha256Context; use crate::error::{DataProblem, Error, ErrorKind, Field, SourceProblem, UnsupportedData}; -use crate::object::{Contents, FileObject, InodeType, Location}; +use crate::object::{ContentsObject, ContentsSource, FileObject, InodeType}; use crate::{Name, Sha256}; -/// How much a source copies at a time. It is also the smallest piece a +/// How much a provider copies at a time. It is also the smallest piece a /// file is hashed in. const COPY_SIZE: usize = 1024 * 1024; -/// How many bytes the hashes a [`DirectorySource`] keeps of the pieces of +/// How many bytes the hashes a [`DirectoryProvider`] keeps of the pieces of /// files take at most: 32 bytes for every piece of a file, and what the /// file takes besides, see [`PieceHashes::stored_bytes`]. The map that /// holds them adds up to about half a MiB, with many small files, which @@ -36,7 +36,7 @@ const MAX_PIECES: u64 = ((PIECE_HASH_BYTES - FILE_ENTRY_BYTES) / size_of:: { /// In the manifest itself. This is the data. Literal(&'a [u8]), - /// Outside of the manifest. A [`ContentSource`] has it. + /// Outside of the manifest. A [`DataProvider`] has it. External(ExternalFile<'a>), } @@ -70,7 +70,7 @@ enum DataExtent { impl<'a> ExternalFile<'a> { /// The file `name` an object has its data in, by way of the contents /// object `contents` if one names it. - fn new(name: &'a Name, contents: Option<&'a Contents>) -> ExternalFile<'a> { + fn new(name: &'a Name, contents: Option<&'a ContentsObject>) -> ExternalFile<'a> { ExternalFile { name, offset: contents.map_or(0, |contents| contents.offset), @@ -208,25 +208,25 @@ impl FileObject { /// literal, else in the file of the first contents object that names /// one. The specification implies a contents object for a regular file /// that has none, with the file of its own name. - fn unencoded_data(&self) -> Option<(DataLocation<'_>, Option<&Contents>)> { + fn unencoded_data(&self) -> Option<(DataLocation<'_>, Option<&ContentsObject>)> { if self.contents.is_empty() { let implied = DataLocation::External(ExternalFile::new(&self.name, None)); return (self.inode_type == InodeType::Regular).then_some((implied, None)); } let mut file = None; for contents in self.contents.iter().filter(|contents| contents.encoding.is_none()) { - match &contents.location { - Location::Literal(literal) => { + match &contents.source { + ContentsSource::Literal(literal) => { let data = self.data_in_literal(literal, contents.offset); return Some((DataLocation::Literal(data), Some(contents))); } - Location::File(name) => { + ContentsSource::File(name) => { file.get_or_insert((name, contents)); } - Location::Implied => { + ContentsSource::Implied => { file.get_or_insert((&self.name, contents)); } - Location::Url(_) => {} + ContentsSource::Url(_) => {} } } file.map(|(name, contents)| { @@ -250,7 +250,7 @@ impl FileObject { } /// Whether the data of the file is outside of the manifest, where a - /// [`ContentSource`] has it. + /// [`DataProvider`] has it. pub fn has_external_data(&self) -> bool { matches!(self.unencoded_data(), Some((DataLocation::External(_), _))) } @@ -271,15 +271,15 @@ impl FileObject { } /// Writes the data of the file to `sink`: the literal of the manifest, - /// or what `source` has. Checks the data against the size and the hash + /// or what `provider` has. Checks the data against the size and the hash /// the object gives with a [`DataCheck`], and returns how many bytes /// it is. An object whose data this crate cannot take fails as - /// [`FileObject::data_location`] does, and the source is not asked for + /// [`FileObject::data_location`] does, and the provider is not asked for /// it. An error of the sink comes back as it was. /// /// What was written to the sink when this fails is not the data of /// the file. - pub fn copy_data(&self, source: &mut dyn ContentSource, sink: &mut dyn Write) -> Result { + pub fn copy_data(&self, provider: &mut dyn DataProvider, sink: &mut dyn Write) -> Result { let (data, contents) = self.unencoded_data().ok_or_else(|| self.unsupported())?; let mut checked = CheckedSink { sink, @@ -290,11 +290,11 @@ impl FileObject { DataLocation::Literal(data) => contents .map_or(Ok(()), |contents| contents.check_literal(self, data)) .and_then(|()| checked.write_all(data).map_err(Error::from)), - DataLocation::External(file) => source.copy(self, &file, &mut checked), + DataLocation::External(file) => provider.copy(self, &file, &mut checked), }; let CheckedSink { check, failure, .. } = checked; // What the check refused and what the sink failed to take reached - // the source as I/O errors. These are the errors to report. + // the provider as I/O errors. These are the errors to report. if let Some(failure) = failure { return Err(failure); } @@ -303,7 +303,7 @@ impl FileObject { } } -impl Contents { +impl ContentsObject { /// Checks the literal of the contents object, which `data`, the data /// of `object`, is all of or a part of, against the hash the manifest /// gives for all of it, where the data is to be checked against that. @@ -337,7 +337,7 @@ impl Contents { /// It checks what the object says of its data, the check the /// specification has for the data of every file. What its contents /// objects say of the files the data is in, their sizes and hashes, is -/// for whoever reads those files to check, such as a [`DirectorySource`]. +/// for whoever reads those files to check, such as a [`DirectoryProvider`]. /// /// [`FileObject::copy_data`] checks what it copies with one. A caller /// that moves the data itself, such as a copy in an async runtime, hands @@ -470,28 +470,28 @@ impl Write for CheckedSink<'_, '_> { /// Has the data of the file objects whose data is outside of the /// manifest. /// -/// [`DirectorySource`] takes it from the files next to the manifest and -/// [`StreamSource`] from one stream that carries it all, in the order of -/// the manifest. A consumer hands a source every file object, in the +/// [`DirectoryProvider`] takes it from the files next to the manifest and +/// [`StreamProvider`] from one stream that carries it all, in the order of +/// the manifest. A consumer hands a provider every file object, in the /// order of the manifest: those whose data it takes to -/// [`FileObject::copy_data`], which calls [`ContentSource::copy`], and -/// the others to [`ContentSource::skip`]. After the last one it calls -/// [`ContentSource::end`]. -pub trait ContentSource { +/// [`FileObject::copy_data`], which calls [`DataProvider::copy`], and +/// the others to [`DataProvider::skip`]. After the last one it calls +/// [`DataProvider::end`]. +pub trait DataProvider { /// Writes the data of `object`, which is in `file`, to `sink`: exactly /// `object.size` bytes when the object has a size. An error of the sink - /// comes back as it was, and one of the source names the object. + /// comes back as it was, and one of the provider names the object. fn copy(&mut self, object: &FileObject, file: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error>; /// Passes over the data of `object`, which the consumer does not take. - /// A source that hands out the data in the order of the manifest reads + /// A provider that hands out the data in the order of the manifest reads /// past it, and fails where a copy of it would. fn skip(&mut self, _object: &FileObject) -> Result<(), Error> { Ok(()) } /// Called after the last file object of the manifest, whether the - /// source had the data of any or not. A source that has data the file + /// provider had the data of any or not. A provider that has data the file /// objects do not account for fails here. fn end(&mut self) -> Result<(), Error> { Ok(()) @@ -547,7 +547,7 @@ pub trait Directory { /// that one, as every object is, and the specification lets a consumer /// that takes a part of a file skip the checks of all of it. So only a /// part without a hash of its own is checked against the hash of the whole -/// file. The source reads the file whole for the first of these parts and +/// file. The provider reads the file whole for the first of these parts and /// keeps the hash of every piece of it, if they fit into what is left of /// the 1 MiB the hashes it keeps take at most. The parts after that are /// checked against those, and only the pieces they are in are read. A @@ -555,10 +555,10 @@ pub trait Directory { /// the hashes of a file of any size fit into 1 MiB, and those of a file of /// about 32 GiB or more take all of it. A part of a file whose hashes do /// not fit is not checked against the hash of the whole file, as the -/// specification allows. So the memory the source takes does not grow +/// specification allows. So the memory the provider takes does not grow /// with the manifest, and while copies succeed, a file of more than one /// piece is read whole once at most for its parts. -pub struct DirectorySource { +pub struct DirectoryProvider { directory: D, /// What a copy goes through, made when the first file is copied. buffer: Vec, @@ -566,10 +566,10 @@ pub struct DirectorySource { hashes: PieceHashes, } -impl DirectorySource { - /// A source that takes the files from `directory`. - pub fn new(directory: D) -> DirectorySource { - DirectorySource { +impl DirectoryProvider { + /// A provider that takes the files from `directory`. + pub fn new(directory: D) -> DirectoryProvider { + DirectoryProvider { directory, buffer: Vec::new(), hashes: PieceHashes::default(), @@ -577,9 +577,9 @@ impl DirectorySource { } } -impl fmt::Debug for DirectorySource { +impl fmt::Debug for DirectoryProvider { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("DirectorySource") + f.debug_struct("DirectoryProvider") .field("directory", &self.directory) .field( "buffer", @@ -590,7 +590,7 @@ impl fmt::Debug for DirectorySource { } } -/// The files a [`DirectorySource`] read whole for a part of them, which +/// The files a [`DirectoryProvider`] read whole for a part of them, which /// have the hash the manifest gives for them, with the hash of every piece /// of each. A file is known by its hash and its length: a part of it is /// checked against the hashes of the pieces of the file of that hash, @@ -750,7 +750,7 @@ trait ReadSome: Read { impl ReadSome for R {} -/// A file a [`DirectorySource`] copies the data of an object from, in +/// A file a [`DirectoryProvider`] copies the data of an object from, in /// pieces where it checks them. struct Pieces<'a, F> { file: F, @@ -886,7 +886,7 @@ impl Pieces<'_, F> { } } -impl ContentSource for DirectorySource { +impl DataProvider for DirectoryProvider { fn copy(&mut self, object: &FileObject, file: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error> { let (opened, len) = self .directory @@ -949,7 +949,7 @@ impl ContentSource for DirectorySource { /// that is the size of the object. A part of a file is checked against the /// hash of its object, and is taken unchecked where the object gives none, /// as the specification permits a consumer that takes a part of a file. -pub struct StreamSource { +pub struct StreamProvider { reader: R, /// What a copy goes through, made when the first file is copied. buffer: Vec, @@ -959,10 +959,10 @@ pub struct StreamSource { last: Option<(String, u64)>, } -impl StreamSource { - /// A source that takes the data from `reader`. - pub fn new(reader: R) -> StreamSource { - StreamSource { +impl StreamProvider { + /// A provider that takes the data from `reader`. + pub fn new(reader: R) -> StreamProvider { + StreamProvider { reader, buffer: Vec::new(), last: None, @@ -979,9 +979,9 @@ impl StreamSource { } } -impl fmt::Debug for StreamSource { +impl fmt::Debug for StreamProvider { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("StreamSource") + f.debug_struct("StreamProvider") .field("reader", &self.reader) .field( "buffer", @@ -992,7 +992,7 @@ impl fmt::Debug for StreamSource { } } -impl ContentSource for StreamSource { +impl DataProvider for StreamProvider { fn copy(&mut self, object: &FileObject, file: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error> { let name = &object.name; if file.offset != 0 { @@ -1197,8 +1197,8 @@ mod tests { } } - /// A source over a reference to the files, so that a test can look - /// at them and change them while the source has them. + /// A provider over a reference to the files, so that a test can look + /// at them and change them while the provider has them. impl Directory for &Files { type File = Counted; @@ -1249,10 +1249,10 @@ mod tests { objects(&records).pop().unwrap() } - /// Copies the data of `object` from `source`. - fn copy(object: &FileObject, source: &mut dyn ContentSource) -> Result, Error> { + /// Copies the data of `object` from `provider`. + fn copy(object: &FileObject, provider: &mut dyn DataProvider) -> Result, Error> { let mut out = Vec::new(); - let written = object.copy_data(source, &mut out)?; + let written = object.copy_data(provider, &mut out)?; assert_eq!(written, out.len() as u64); Ok(out) } @@ -1359,7 +1359,7 @@ mod tests { /// Only a regular file has a contents object implied. Any other object /// without one has no data, and a copy of it fails without a look at - /// the source. + /// the provider. #[test] fn objects_without_data() { // A manifest that does not record the targets of symbolic links. @@ -1375,7 +1375,7 @@ mod tests { .unwrap() .objects; let mut stream = &b"hello"[..]; - let mut source = StreamSource::new(&mut stream); + let mut provider = StreamProvider::new(&mut stream); for (o, kind) in none.iter().zip(["dir", "fifo", "lnk"]) { let e = o.data_location().unwrap_err(); assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::Absent)); @@ -1385,12 +1385,12 @@ mod tests { format!("'{}' is a {} without contents objects, which has no data", o.name, kind) ); assert!(!o.has_external_data()); - let e = copy(o, &mut source).unwrap_err(); + let e = copy(o, &mut provider).unwrap_err(); assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::Absent)); - source.skip(o).unwrap(); + provider.skip(o).unwrap(); } - assert_eq!(copy(&none[3], &mut source).unwrap(), b"hello"); - source.end().unwrap(); + assert_eq!(copy(&none[3], &mut provider).unwrap(), b"hello"); + provider.end().unwrap(); // A symbolic link with its target in the manifest, and a directory // that refers to a manifest of its own in a file. let some = objects(&[ @@ -1400,15 +1400,15 @@ mod tests { assert!(some[0].has_external_data()); assert_eq!(some[1].data_location().unwrap(), DataLocation::Literal(b"x")); let files = Files::of(&[("d.Uapi16Manifest", b"abc")]); - let mut source = DirectorySource::new(&files); - assert_eq!(copy(&some[0], &mut source).unwrap(), b"abc"); - assert_eq!(copy(&some[1], &mut source).unwrap(), b"x"); + let mut provider = DirectoryProvider::new(&files); + assert_eq!(copy(&some[0], &mut provider).unwrap(), b"abc"); + assert_eq!(copy(&some[1], &mut provider).unwrap(), b"x"); } #[test] fn copies_from_a_directory() { let files = Files::of(&[("a", b"hello world"), ("empty", b""), ("dir/b", b"hello")]); - let mut source = DirectorySource::new(&files); + let mut provider = DirectoryProvider::new(&files); for (record, data) in [ // A whole file, by the name of the object and by a file external. (format!(r#"{{"name":"dir/b","size":5,"sha256":"{}"}}"#, HELLO), "hello"), @@ -1462,21 +1462,21 @@ mod tests { ), "world", ), - // A literal needs no source. + // A literal needs no provider. ( r#"{"name":"missing","contents":[{"literal":"aGVsbG8="}]}"#.to_string(), "hello", ), ] { let o = object(&record); - assert_eq!(copy(&o, &mut source).unwrap(), data.as_bytes(), "{}", record); + assert_eq!(copy(&o, &mut provider).unwrap(), data.as_bytes(), "{}", record); } } #[test] fn files_that_are_not_what_the_manifest_says() { let files = Files::of(&[("a", b"hello world"), ("dir/b", b"hello")]); - let mut source = DirectorySource::new(&files); + let mut provider = DirectoryProvider::new(&files); let size = ErrorKind::Data(DataProblem::SizeMismatch); let hash = ErrorKind::Data(DataProblem::HashMismatch); for (record, expected) in [ @@ -1565,7 +1565,7 @@ mod tests { ), ] { let o = object(&record); - let e = copy(&o, &mut source).unwrap_err(); + let e = copy(&o, &mut provider).unwrap_err(); let (kind, name, found, expected_size, text) = expected; assert_eq!( facts(&e), @@ -1581,7 +1581,7 @@ mod tests { r#"{{"name":"x","size":5,"sha256":"{}","contents":[{{"file":"a","originalSize":11,"originalSha256":"{}"}}]}}"#, HELLO, WORLD )); - assert_eq!(copy(&o, &mut source).unwrap(), b"hello"); + assert_eq!(copy(&o, &mut provider).unwrap(), b"hello"); assert_eq!(files.read(), 5); // A part of a literal is held against the hash of all of the // literal the manifest gives, as a part of a file is, unless the @@ -1597,9 +1597,9 @@ mod tests { ), ] { let o = object(&format!(r#"{}"{}"}}]}}"#, record, HELLO)); - assert_eq!(copy(&o, &mut source).unwrap(), data.as_bytes()); + assert_eq!(copy(&o, &mut provider).unwrap(), data.as_bytes()); let o = object(&format!(r#"{}"{}"}}]}}"#, record, WORLD)); - let e = copy(&o, &mut source).unwrap_err(); + let e = copy(&o, &mut provider).unwrap_err(); assert_eq!( facts(&e), ( @@ -1616,15 +1616,15 @@ mod tests { Sha256::digest(b"he"), WORLD )); - assert_eq!(copy(&o, &mut source).unwrap(), b"he"); + assert_eq!(copy(&o, &mut provider).unwrap(), b"he"); // A literal that is not what the object says. let o = object( r#"{"name":"x","size":5,"contents":[{"literal":"aGVsbG8="}],"sha256":"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7"}"#, ); - assert_eq!(copy(&o, &mut source).unwrap_err().kind(), hash); + assert_eq!(copy(&o, &mut provider).unwrap_err().kind(), hash); let mut o = object(r#"{"name":"x","contents":[{"literal":"aGVsbG8="}]}"#); o.size = Some(6); - let e = copy(&o, &mut source).unwrap_err(); + let e = copy(&o, &mut provider).unwrap_err(); assert_eq!( facts(&e), ( @@ -1642,7 +1642,7 @@ mod tests { #[test] fn files_that_change_while_they_are_read() { let files = Files::default(); - let mut source = DirectorySource::new(&files); + let mut provider = DirectoryProvider::new(&files); let changed = |file: &str| { ( ErrorKind::Data(DataProblem::SourceChanged), @@ -1665,7 +1665,7 @@ mod tests { len: 5, }, ); - let e = copy(&object(&part), &mut source).unwrap_err(); + let e = copy(&object(&part), &mut provider).unwrap_err(); assert_eq!(facts(&e), changed("g")); assert_eq!(files.read(), read); } @@ -1685,15 +1685,15 @@ mod tests { len, Sha256::digest(&blob[..len]) )); - let e = copy(&o, &mut source).unwrap_err(); + let e = copy(&o, &mut provider).unwrap_err(); assert_eq!(facts(&e), changed("p")); assert_eq!(files.read(), len as u64 + 1); - assert!(source.hashes.files.is_empty()); + assert!(provider.hashes.files.is_empty()); // Once it is as long as it was, it is taken. files.put("p", Entry::File(blob[..len].into())); - assert_eq!(copy(&o, &mut source).unwrap(), &blob[1..4]); + assert_eq!(copy(&o, &mut provider).unwrap(), &blob[1..4]); assert_eq!(files.read(), len as u64); - assert_eq!(source.hashes.files.len(), 1); + assert_eq!(provider.hashes.files.len(), 1); // The data of an object that is checked against its own hash only // is taken from a file that grew. files.put( @@ -1707,7 +1707,7 @@ mod tests { r#"{{"name":"x","size":5,"sha256":"{}","contents":[{{"file":"g"}}]}}"#, HELLO )); - assert_eq!(copy(&o, &mut source).unwrap(), b"hello"); + assert_eq!(copy(&o, &mut provider).unwrap(), b"hello"); assert_eq!(files.read(), 5); // A file that is shorter than when it was opened, for an object // that says nothing about its size or its hash and for one that @@ -1723,7 +1723,7 @@ mod tests { r#"{"name":"x","contents":[{"file":"g"}]}"#, r#"{"name":"x","size":5,"contents":[{"file":"g"}]}"#, ] { - let e = copy(&object(record), &mut source).unwrap_err(); + let e = copy(&object(record), &mut provider).unwrap_err(); assert_eq!(facts(&e), changed("g"), "{}", record); assert_eq!(files.read(), 3); } @@ -1745,7 +1745,7 @@ mod tests { trouble: Trouble::Stall, }; let files = Files::default(); - let mut source = DirectorySource::new(&files); + let mut provider = DirectoryProvider::new(&files); let changed = ( ErrorKind::Data(DataProblem::SourceChanged), Some("x"), @@ -1774,17 +1774,17 @@ mod tests { (object(r#"{"name":"x","contents":[{"file":"blob","offset":1}]}"#), 1), ] { files.put("blob", stalling()); - let e = copy(&o, &mut source).unwrap_err(); + let e = copy(&o, &mut provider).unwrap_err(); assert_eq!(facts(&e), changed, "{:?}", o); assert_eq!(files.read(), (at - from) as u64, "{:?}", o); - assert!(source.hashes.files.is_empty()); + assert!(provider.hashes.files.is_empty()); } // A part checked against the hashes of the pieces of the file. files.put("blob", Entry::File(Rc::clone(&blob))); - assert_eq!(copy(&part(5, 10), &mut source).unwrap(), &blob[5..15]); + assert_eq!(copy(&part(5, 10), &mut provider).unwrap(), &blob[5..15]); assert_eq!(files.read(), len as u64); files.put("blob", stalling()); - let e = copy(&part(COPY_SIZE + 7, 10), &mut source).unwrap_err(); + let e = copy(&part(COPY_SIZE + 7, 10), &mut provider).unwrap_err(); assert_eq!(facts(&e), changed); assert_eq!(files.read(), (at - COPY_SIZE) as u64); } @@ -1804,9 +1804,9 @@ mod tests { trouble: Trouble::FailRead(libc::EIO), }, ); - let mut source = DirectorySource::new(&files); + let mut provider = DirectoryProvider::new(&files); let o = object(r#"{"name":"x","size":11,"contents":[{"file":"bad"}]}"#); - let e = copy(&o, &mut source).unwrap_err(); + let e = copy(&o, &mut provider).unwrap_err(); assert_eq!( (e.kind(), e.name(), e.to_string()), ( @@ -1824,7 +1824,7 @@ mod tests { } } let o = object(r#"{"name":"x","size":5}"#); - let e = copy(&o, &mut StreamSource::new(Failing)).unwrap_err(); + let e = copy(&o, &mut StreamProvider::new(Failing)).unwrap_err(); assert_eq!( (e.kind(), e.name(), e.to_string()), ( @@ -1834,7 +1834,7 @@ mod tests { ) ); assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::EIO)); - let e = StreamSource::new(Failing).end().unwrap_err(); + let e = StreamProvider::new(Failing).end().unwrap_err(); assert_eq!( (e.kind(), e.name(), e.to_string()), ( @@ -1853,7 +1853,7 @@ mod tests { }; files.put("blob", unseekable()); let o = object(r#"{"name":"x","size":3,"contents":[{"file":"blob","offset":2}]}"#); - let e = copy(&o, &mut source).unwrap_err(); + let e = copy(&o, &mut provider).unwrap_err(); assert_eq!( (e.kind(), e.name(), e.to_string()), ( @@ -1871,9 +1871,9 @@ mod tests { )) }; files.put("blob", Entry::File(Rc::clone(&blob))); - assert_eq!(copy(&part(0), &mut source).unwrap(), &blob[..3]); + assert_eq!(copy(&part(0), &mut provider).unwrap(), &blob[..3]); files.put("blob", unseekable()); - let e = copy(&part(COPY_SIZE + 1), &mut source).unwrap_err(); + let e = copy(&part(COPY_SIZE + 1), &mut provider).unwrap_err(); assert_eq!( (e.kind(), e.to_string()), ( @@ -1891,7 +1891,7 @@ mod tests { let whole = Sha256::digest(&blob); let files = Files::default(); files.put("blob", Entry::File(blob[..].into())); - let mut source = DirectorySource::new(&files); + let mut provider = DirectoryProvider::new(&files); let part = |offset: usize, size: usize, total: usize, sha256: Option| { let sha256 = sha256.map(|sha256| format!(r#","originalSha256":"{}""#, sha256)); object(&format!( @@ -1918,7 +1918,7 @@ mod tests { // Without the hash of the file a part is all that is read. for (offset, size) in parts { let o = part(offset, size, len, None); - assert_eq!(copy(&o, &mut source).unwrap(), &blob[offset..offset + size]); + assert_eq!(copy(&o, &mut provider).unwrap(), &blob[offset..offset + size]); assert_eq!(files.read(), size as u64); } // With it the file is read whole for the first part. For the @@ -1929,7 +1929,7 @@ mod tests { let mut first = true; for (offset, size) in parts { let o = part(offset, size, len, Some(whole)); - assert_eq!(copy(&o, &mut source).unwrap(), &blob[offset..offset + size]); + assert_eq!(copy(&o, &mut provider).unwrap(), &blob[offset..offset + size]); let from = offset / COPY_SIZE * COPY_SIZE; let to = (offset + size).next_multiple_of(COPY_SIZE).min(len); let read = match (size, first) { @@ -1942,7 +1942,7 @@ mod tests { } // Another hash for the same file is not taken on trust. let o = part(5, 10, len, Some(Sha256::digest(b"another file"))); - let e = copy(&o, &mut source).unwrap_err(); + let e = copy(&o, &mut provider).unwrap_err(); assert_eq!( facts(&e), ( @@ -1970,7 +1970,7 @@ mod tests { (1, len - 1, false), (0, len, false), ] { - let copied = copy(&part(offset, size, len, Some(whole)), &mut source); + let copied = copy(&part(offset, size, len, Some(whole)), &mut provider); match copied { Ok(data) => assert!(good && data == changed[offset..offset + size], "{} at {}", size, offset), Err(e) => assert!(!good && e.kind() == hash, "{} at {}: {}", size, offset, e), @@ -1978,13 +1978,13 @@ mod tests { } files.read(); files.put("blob", Entry::File(blob[..len - 1].into())); - let e = copy(&part(5, 10, len - 1, Some(whole)), &mut source).unwrap_err(); + let e = copy(&part(5, 10, len - 1, Some(whole)), &mut provider).unwrap_err(); assert_eq!(e.kind(), hash); assert_eq!(files.read(), len as u64 - 1); let shorter = Sha256::digest(&blob[..len - 1]); for _ in 0..2 { let o = part(len - 11, 10, len - 1, Some(shorter)); - assert_eq!(copy(&o, &mut source).unwrap(), &blob[len - 11..len - 1]); + assert_eq!(copy(&o, &mut provider).unwrap(), &blob[len - 11..len - 1]); } assert_eq!(files.read(), (len - 1 + COPY_SIZE / 2 - 1) as u64); // A file that is one object is read once, hash or no hash. @@ -1997,9 +1997,9 @@ mod tests { HELLO ), ] { - let mut source = DirectorySource::new(&small); + let mut provider = DirectoryProvider::new(&small); for _ in 0..2 { - assert_eq!(copy(&object(&record), &mut source).unwrap(), b"hello", "{}", record); + assert_eq!(copy(&object(&record), &mut provider).unwrap(), b"hello", "{}", record); assert_eq!(small.read(), 5); } } @@ -2077,14 +2077,14 @@ mod tests { } } - /// What a source keeps of the files it read whole does not grow with + /// What a provider keeps of the files it read whole does not grow with /// the manifest, and what it decides to keep it keeps. #[test] fn keeps_hashes_up_to_the_bound() { let mib = COPY_SIZE as u64; // A file is cut into pieces of 1 MiB, and of more where it would // have more than MAX_PIECES of them. The hashes of the pieces of a - // file of any length fit into what a source keeps. + // file of any length fit into what a provider keeps. assert_eq!(PieceHashes::piece_size(MAX_PIECES * mib), mib); assert_eq!(PieceHashes::piece_size(MAX_PIECES * mib + 1), mib + 1); assert_eq!(PieceHashes::piece_count(MAX_PIECES * mib + 1), MAX_PIECES); @@ -2108,7 +2108,7 @@ mod tests { ); assert!(PieceHashes::stored_bytes(count) <= PIECE_HASH_BYTES, "{}", len); } - // So a source that holds no hashes keeps those of any file of more + // So a provider that holds no hashes keeps those of any file of more // than one piece. let empty = PieceHashes::default(); assert!(empty.is_keepable(u64::MAX) && empty.is_keepable(mib + 1)); @@ -2134,31 +2134,31 @@ mod tests { // file, and nothing is kept of it. let names = ["a", "b", "c", "d"]; let files = Files::of(&names.map(|name| (name, &b"ab"[..]))); - let mut source = DirectorySource::new(&files); + let mut provider = DirectoryProvider::new(&files); for name in names { let o = object(&format!( r#"{{"name":"x","size":1,"contents":[{{"file":"{}","offset":1,"originalSize":2,"originalSha256":"{}"}}]}}"#, name, Sha256::digest(b"ab") )); - assert_eq!(copy(&o, &mut source).unwrap(), b"b"); + assert_eq!(copy(&o, &mut provider).unwrap(), b"b"); assert_eq!(files.read(), 2); } - assert_eq!((source.hashes.files.len(), source.hashes.bytes), (0, 0)); - // A part of a file whose hashes the source cannot keep any more is + assert_eq!((provider.hashes.files.len(), provider.hashes.bytes), (0, 0)); + // A part of a file whose hashes the provider cannot keep any more is // copied without the check of the whole file: the hash the // manifest gives for that is not looked at. let blob: Vec = (0..2 * COPY_SIZE).map(|i| (i >> 3) as u8).collect(); files.put("blob", Entry::File(blob[..].into())); - source.hashes = kept; + provider.hashes = kept; let o = object(&format!( r#"{{"name":"x","size":3,"contents":[{{"file":"blob","offset":5,"originalSize":{},"originalSha256":"{}"}}]}}"#, blob.len(), hash_of(3) )); - assert_eq!(copy(&o, &mut source).unwrap(), &blob[5..8]); + assert_eq!(copy(&o, &mut provider).unwrap(), &blob[5..8]); assert_eq!(files.read(), 3); - assert_eq!(source.hashes.files.len(), 2); + assert_eq!(provider.hashes.files.len(), 2); } #[test] @@ -2169,7 +2169,7 @@ mod tests { files.put("odd", Entry::Fails(libc::EINVAL)); files.put("link", Entry::Fails(libc::ELOOP)); files.put("secret", Entry::Fails(libc::EACCES)); - let mut source = DirectorySource::new(&files); + let mut provider = DirectoryProvider::new(&files); for (file, problem, errno, text) in [ ( "missing", @@ -2207,7 +2207,7 @@ mod tests { r#"{{"name":"x","size":5,"contents":[{{"file":"{}"}}]}}"#, file )); - let e = copy(&o, &mut source).unwrap_err(); + let e = copy(&o, &mut provider).unwrap_err(); assert_eq!(e.kind(), ErrorKind::Source(problem), "{}", file); assert_eq!(e.name(), Some("x")); assert_eq!(e.io_error().and_then(io::Error::raw_os_error), errno, "{}", file); @@ -2217,7 +2217,7 @@ mod tests { // A name is quoted with its control characters escaped: one of C1 // is a control sequence on a terminal. let o = object(r#"{"name":"x\u009b2J","size":5}"#); - let e = copy(&o, &mut source).unwrap_err(); + let e = copy(&o, &mut provider).unwrap_err(); assert_eq!(e.name(), Some("x\u{9b}2J")); assert!( e.to_string().starts_with(r"x\u{9b}2J: failed to open x\u{9b}2J: "), @@ -2241,19 +2241,19 @@ mod tests { let streamed: Vec<&FileObject> = all.iter().filter(|o| o.has_external_data()).collect(); assert_eq!(streamed.len(), 3); let mut stream = &b"helloworld"[..]; - let mut source = StreamSource::new(&mut stream); - assert_eq!(copy(streamed[0], &mut source).unwrap(), b"hello"); - assert_eq!(copy(&all[2], &mut source).unwrap(), b"hello"); - assert_eq!(copy(streamed[1], &mut source).unwrap(), b""); - assert_eq!(copy(streamed[2], &mut source).unwrap(), b"world"); - source.end().unwrap(); + let mut provider = StreamProvider::new(&mut stream); + assert_eq!(copy(streamed[0], &mut provider).unwrap(), b"hello"); + assert_eq!(copy(&all[2], &mut provider).unwrap(), b"hello"); + assert_eq!(copy(streamed[1], &mut provider).unwrap(), b""); + assert_eq!(copy(streamed[2], &mut provider).unwrap(), b"world"); + provider.end().unwrap(); assert!(stream.is_empty()); // A stream that ends early, and one that goes on after the last file. let mut stream = &b"hellowo"[..]; - let mut source = StreamSource::new(&mut stream); - copy(streamed[0], &mut source).unwrap(); - let e = copy(streamed[2], &mut source).unwrap_err(); + let mut provider = StreamProvider::new(&mut stream); + copy(streamed[0], &mut provider).unwrap(); + let e = copy(streamed[2], &mut provider).unwrap_err(); assert_eq!( facts(&e), ( @@ -2265,10 +2265,10 @@ mod tests { ) ); let mut stream = &b"helloworldmore"[..]; - let mut source = StreamSource::new(&mut stream); - copy(streamed[0], &mut source).unwrap(); - copy(streamed[2], &mut source).unwrap(); - let e = source.end().unwrap_err(); + let mut provider = StreamProvider::new(&mut stream); + copy(streamed[0], &mut provider).unwrap(); + copy(streamed[2], &mut provider).unwrap(); + let e = provider.end().unwrap_err(); assert_eq!( facts(&e), ( @@ -2282,7 +2282,7 @@ mod tests { // A stream that has data when it had none of a file, and one that // has none. let mut stream = &b"junk"[..]; - let e = StreamSource::new(&mut stream).end().unwrap_err(); + let e = StreamProvider::new(&mut stream).end().unwrap_err(); assert_eq!( facts(&e), ( @@ -2294,10 +2294,10 @@ mod tests { ) ); let mut stream = &b""[..]; - StreamSource::new(&mut stream).end().unwrap(); + StreamProvider::new(&mut stream).end().unwrap(); // Contents that are not the ones the manifest describes. let mut stream = &b"hellp"[..]; - let e = copy(streamed[0], &mut StreamSource::new(&mut stream)).unwrap_err(); + let e = copy(streamed[0], &mut StreamProvider::new(&mut stream)).unwrap_err(); assert_eq!(e.kind(), ErrorKind::Data(DataProblem::HashMismatch)); } @@ -2309,7 +2309,7 @@ mod tests { let hash = ErrorKind::Data(DataProblem::HashMismatch); let check = |o: &FileObject, data: &'static [u8]| { let mut stream = data; - let copied = copy(o, &mut StreamSource::new(&mut stream)); + let copied = copy(o, &mut StreamProvider::new(&mut stream)); assert!(stream.is_empty()); copied }; @@ -2325,7 +2325,7 @@ mod tests { // An object that is all of its file without a hash of its own. let mut whole = FileObject::new(Name::new("x").unwrap()); whole.size = Some(5); - let mut contents = Contents::new(Location::Implied); + let mut contents = ContentsObject::new(ContentsSource::Implied); contents.original_size = Some(5); contents.original_sha256 = HELLO.parse().ok(); whole.contents.push(contents); @@ -2368,14 +2368,14 @@ mod tests { } // A stream has no place for a file without a size or at an offset. let mut stream = &b"hello"[..]; - let mut source = StreamSource::new(&mut stream); - let e = copy(&object(r#"{"name":"x"}"#), &mut source).unwrap_err(); + let mut provider = StreamProvider::new(&mut stream); + let e = copy(&object(r#"{"name":"x"}"#), &mut provider).unwrap_err(); assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::NoSize)); assert_eq!((e.name(), e.field()), (Some("x"), Some(Field::Size))); assert_eq!(e.to_string(), "x: streamed contents need a known size"); let e = copy( &object(r#"{"name":"x","size":2,"contents":[{"offset":1}]}"#), - &mut source, + &mut provider, ) .unwrap_err(); assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::OffsetInStream)); @@ -2395,30 +2395,30 @@ mod tests { r#"{"name":"remote","contents":[{"url":"https://example.com/x"}]}"#, ]); let mut stream = &b"helloworld"[..]; - let mut source = StreamSource::new(&mut stream); + let mut provider = StreamProvider::new(&mut stream); for o in [&all[0], &all[1]] { - source.skip(o).unwrap(); + provider.skip(o).unwrap(); } - assert_eq!(copy(&all[2], &mut source).unwrap(), b"world"); + assert_eq!(copy(&all[2], &mut provider).unwrap(), b"world"); for o in &all[3..] { - source.skip(o).unwrap(); + provider.skip(o).unwrap(); } - source.end().unwrap(); + provider.end().unwrap(); // A skip fails where a copy would. let mut stream = &b"hellp"[..]; - let e = StreamSource::new(&mut stream).skip(&all[0]).unwrap_err(); + let e = StreamProvider::new(&mut stream).skip(&all[0]).unwrap_err(); assert_eq!(e.kind(), ErrorKind::Data(DataProblem::HashMismatch)); let mut stream = &b"hel"[..]; - let e = StreamSource::new(&mut stream).skip(&all[0]).unwrap_err(); + let e = StreamProvider::new(&mut stream).skip(&all[0]).unwrap_err(); assert_eq!(e.kind(), ErrorKind::Data(DataProblem::StreamEnded)); let mut stream = &b"hello"[..]; - let e = StreamSource::new(&mut stream) + let e = StreamProvider::new(&mut stream) .skip(&object(r#"{"name":"x"}"#)) .unwrap_err(); assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::NoSize)); // A directory has nothing to read past. let files = Files::of(&[("a", b"hello")]); - DirectorySource::new(&files).skip(&all[0]).unwrap(); + DirectoryProvider::new(&files).skip(&all[0]).unwrap(); assert_eq!(files.read(), 0); } @@ -2428,7 +2428,7 @@ mod tests { careful: bool, } - impl ContentSource for Babbler { + impl DataProvider for Babbler { fn copy(&mut self, _: &FileObject, _: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error> { let written = sink.write_all(b"hello world"); if self.careful { @@ -2488,7 +2488,7 @@ mod tests { check.update(b"any").unwrap(); check.update(b"thing").unwrap(); assert_eq!(check.finish().unwrap(), 8); - // A source that writes more than the size of the object is stopped + // A provider that writes more than the size of the object is stopped // before the sink gets any of it, and fails the copy with what the // check says, also when it passes over the error of the write. let o = object(r#"{"name":"x","size":5}"#); @@ -2525,36 +2525,36 @@ mod tests { let literal = object(r#"{"name":"l","contents":[{"literal":"aGVsbG8="}]}"#); let files = Files::of(&[("a", b"hello")]); let nothing = Files::default(); - let mut directory = DirectorySource::new(&files); + let mut directory = DirectoryProvider::new(&files); let mut stream = &b"hello"[..]; - let mut stream = StreamSource::new(&mut stream); - let mut empty = DirectorySource::new(¬hing); - let sources: [(&FileObject, &mut dyn ContentSource); 3] = + let mut stream = StreamProvider::new(&mut stream); + let mut empty = DirectoryProvider::new(¬hing); + let sources: [(&FileObject, &mut dyn DataProvider); 3] = [(&o, &mut directory), (&o, &mut stream), (&literal, &mut empty)]; - for (object, source) in sources { - let e = object.copy_data(source, &mut Full(4)).unwrap_err(); + for (object, provider) in sources { + let e = object.copy_data(provider, &mut Full(4)).unwrap_err(); assert_eq!(e.kind(), ErrorKind::Io); assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::ENOSPC)); } } - /// What a source prints for debugging says how large its buffer is, + /// What a provider prints for debugging says how large its buffer is, /// and does not hold it. #[test] fn debug_shows_no_buffers() { let files = Files::of(&[("a", b"hello")]); - let mut source = DirectorySource::new(&files); - copy(&object(r#"{"name":"a","size":5}"#), &mut source).unwrap(); - let text = format!("{:?}", source); + let mut provider = DirectoryProvider::new(&files); + copy(&object(r#"{"name":"a","size":5}"#), &mut provider).unwrap(); + let text = format!("{:?}", provider); assert!(text.len() < 500, "{}", text); assert!( text.contains("buffer: 1048576/1048576, hashes: PieceHashes { files: 0, bytes: 0/1048576 }"), "{}", text ); - let mut source = StreamSource::new(io::repeat(7).take(2 * COPY_SIZE as u64)); - copy(&object(r#"{"name":"a","size":5}"#), &mut source).unwrap(); - let text = format!("{:?}", source); + let mut provider = StreamProvider::new(io::repeat(7).take(2 * COPY_SIZE as u64)); + copy(&object(r#"{"name":"a","size":5}"#), &mut provider).unwrap(); + let text = format!("{:?}", provider); assert!(text.len() < 200, "{}", text); assert!( text.ends_with(r#"buffer: 1048576/1048576, last: Some(("a", 5)) }"#), diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index b6c5e99..224cbfa 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -23,8 +23,8 @@ use crate::base64::Base64; use crate::error::{Error, Field, Problem}; use crate::hex::Hex; use crate::object::{ - Contents, DosFlags, FatSerial, FileObject, FileSystemIdentity, FlagSet, GptPartition, InodeAttributes, InodeFlags, - InodeType, Location, Mode, RootObject, Signature, Uuid, Validity, + ContentsObject, ContentsSource, DosFlags, FatSerial, FileObject, FileSystemIdentity, FlagSet, GptPartition, + InodeAttributes, InodeFlags, InodeType, Mode, RootObject, SignatureObject, Uuid, Validity, }; use crate::strict::{FieldTable, Key, Members, Skip, Strict}; use crate::{ @@ -53,7 +53,7 @@ pub(crate) enum DecodedObject { /// A file object, or what is wrong with it. File(Result, Error>), /// A signature object. - Signature(Signature), + Signature(SignatureObject), /// The trailer object. Trailer, /// An object of a media type this crate does not know. @@ -462,7 +462,7 @@ impl FileObject { /// specification requires: `readOnly` and `mode`, and the size and the /// hash of the object and those of its contents objects. `contents_data` /// gives what each contents object says of its data: what - /// [`Contents::check_consistency`] returns for it, or what its fields + /// [`ContentsObject::check_consistency`] returns for it, or what its fields /// hold once a reader checked and filled it in. Returns the size and the /// hash of the data of the object: those it gives, and those that follow /// from its contents objects and from each other. Whether `gptFlags` @@ -471,7 +471,7 @@ impl FileObject { pub(crate) fn check_consistency( &self, subject: Subject<'_>, - contents_data: impl Fn(&Contents) -> Result, + contents_data: impl Fn(&ContentsObject) -> Result, ) -> Result { self.inode.check_read_only(subject)?; // The size and the hash of the object and those of its contents @@ -490,7 +490,7 @@ impl FileObject { let Some(total) = original.size else { continue; }; - // Contents::check_consistency found the offset inside the data. + // ContentsObject::check_consistency found the offset inside the data. let rest = total - contents.offset; match (self.size, data.size) { (Some(stated), _) => { @@ -676,7 +676,7 @@ impl InodeAttributes { } } -impl Contents { +impl ContentsObject { /// Checks that the fields of the contents object agree with each /// other, as the specification requires, and returns what they say of /// its data with what follows from them: a literal gives the size of @@ -695,7 +695,7 @@ impl Contents { let mut data = self.data(); // A literal is as large as the data as it is stored, and without // an encoding that is the data. - if let Location::Literal(literal) = &self.location { + if let ContentsSource::Literal(literal) = &self.source { let len = literal.len() as u64; let original = data.original.size.filter(|_| self.encoding.is_none()); if let Some(size) = [data.encoded.size, original] @@ -778,7 +778,7 @@ impl Contents { } /// Fills in what follows from the fields of the contents object, `data` - /// from [`Contents::check_consistency`], and notes what it filled in. + /// from [`ContentsObject::check_consistency`], and notes what it filled in. fn fill_in(&mut self, data: ContentsData) { let given = [ self.encoded_size.is_some(), @@ -1189,7 +1189,7 @@ impl<'a> RecordDecoder<'a> { let (media_type, candidate) = RecordDecoder::read(text, record_number)?; Ok(match media_type { MediaType::Trailer => DecodedObject::Trailer, - MediaType::Signature => DecodedObject::Signature(Signature::decode(text, record_number)?), + MediaType::Signature => DecodedObject::Signature(SignatureObject::decode(text, record_number)?), MediaType::Other => DecodedObject::Other, MediaType::Absent | MediaType::Manifest => DecodedObject::File(candidate.into_file_object()), }) @@ -1697,21 +1697,21 @@ impl<'a> Part<'a> for XattrValue { struct ContentsArray; impl<'a> Part<'a> for ContentsArray { - type Value = Vec; + type Value = Vec; fn array>(self, decoder: &mut RecordDecoder<'a>, mut seq: A) -> Parsed<'a, Self::Value, A::Error> { let subject = decoder.subject(); let mut list = Vec::new(); let error_before = decoder.first_error.is_some(); let mut count = 0usize; - while let Some(value) = seq.next_element_seed(decoder.seed(ContentsObject))? { + while let Some(value) = seq.next_element_seed(decoder.seed(ContentsElement))? { let contents = match value { Value::Part(contents) => contents, _ => { decoder.note_error(Problem::InvalidContents, Field::Contents, || { format!("{}: contents entry is not an object", subject) }); - Contents::default() + ContentsObject::default() } }; count += 1; @@ -1729,14 +1729,14 @@ impl<'a> Part<'a> for ContentsArray { } /// A contents object. -struct ContentsObject; +struct ContentsElement; -impl<'a> Part<'a> for ContentsObject { - type Value = Contents; +impl<'a> Part<'a> for ContentsElement { + type Value = ContentsObject; fn object>(self, decoder: &mut RecordDecoder<'a>, map: A) -> Parsed<'a, Self::Value, A::Error> { let subject = decoder.subject(); - let mut contents = Contents::default(); + let mut contents = ContentsObject::default(); // How many of file, url and literal the object has. let mut places = 0; let mut members = Members::new(map, &Field::CONTENTS, &mut decoder.json); @@ -1763,7 +1763,7 @@ impl<'a> Part<'a> for ContentsObject { if let Some(file) = decoder.string(field, value) { match Name::new(file.as_ref()) { Ok(file) => { - contents.location = Location::File(file); + contents.source = ContentsSource::File(file); places += 1; } Err(reason) => decoder.note_error(Problem::InvalidContents, field, || { @@ -1779,8 +1779,8 @@ impl<'a> Part<'a> for ContentsObject { } Field::Url => { if let Some(url) = decoder.string(field, value) { - if decoder.note_err(Contents::check_url(&url, subject)).is_some() { - contents.location = Location::Url(url.into_owned()); + if decoder.note_err(ContentsObject::check_url(&url, subject)).is_some() { + contents.source = ContentsSource::Url(url.into_owned()); places += 1; } } @@ -1789,7 +1789,7 @@ impl<'a> Part<'a> for ContentsObject { if let Some(literal) = decoder.string(field, value) { match Base64::decode(&literal) { Some(literal) => { - contents.location = Location::Literal(literal); + contents.source = ContentsSource::Literal(literal); places += 1; } None => decoder.note_error(Problem::InvalidContents, field, || { @@ -1801,7 +1801,10 @@ impl<'a> Part<'a> for ContentsObject { Field::Encoding => { if let Some(encoding) = decoder.string(field, value) { let encoding = encoding.to_ascii_lowercase(); - if decoder.note_err(Contents::check_encoding(&encoding, subject)).is_some() { + if decoder + .note_err(ContentsObject::check_encoding(&encoding, subject)) + .is_some() + { contents.encoding = Some(encoding); } } @@ -1835,7 +1838,7 @@ impl<'a> Part<'a> for ContentsObject { } /// `httpHeaders`: an object that maps the names of HTTP header fields to -/// their values, see [`Contents::check_headers`]. +/// their values, see [`ContentsObject::check_headers`]. struct HeaderFields; impl<'a> Part<'a> for HeaderFields { @@ -1860,7 +1863,7 @@ impl<'a> Part<'a> for HeaderFields { }), } } - decoder.note_err(Contents::check_headers(&headers, subject)); + decoder.note_err(ContentsObject::check_headers(&headers, subject)); Ok(Value::Part(headers)) } } @@ -1902,12 +1905,12 @@ impl<'a> Part<'a> for SignatureRecord { } } -impl Signature { +impl SignatureObject { /// Reads the signature object the record `text` holds, the one with the /// number `record_number`, which is known to be a JSON object. The /// signature is not verified, but a manifest whose signature objects /// are malformed is refused like systemd refuses it. - fn decode(text: &str, record_number: u64) -> Result { + fn decode(text: &str, record_number: u64) -> Result { RecordDecoder::new(record_number) .object(text, SignatureRecord)? .into_signature(record_number) @@ -1918,7 +1921,7 @@ impl Signature { impl SignatureMembers<'_> { /// The signature object of the record with the number `record_number` /// that has these members. - fn into_signature(self, record_number: u64) -> Result { + fn into_signature(self, record_number: u64) -> Result { let not_a_string = |field: Field| { Error::manifest( Problem::WrongFieldType, @@ -1961,7 +1964,7 @@ impl SignatureMembers<'_> { } }, }; - let mut signature = Signature::new(mechanism); + let mut signature = SignatureObject::new(mechanism); signature.key = key; signature.data = data; Ok(signature) @@ -2396,13 +2399,13 @@ mod tests { let subject = Subject::new(object, 1); object.check_consistency(subject, |contents| contents.check_consistency(subject)) }; - let file = |size: Option, contents: Contents| { + let file = |size: Option, contents: ContentsObject| { let mut object = FileObject::new(Name::new("x").unwrap()); object.size = size; object.contents = vec![contents]; object }; - let hello = || Contents::new(Location::Literal(b"hello".to_vec())); + let hello = || ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())); assert_eq!( check(&file(None, hello())).unwrap(), SizeAndHash { @@ -2412,7 +2415,7 @@ mod tests { ); let mut beyond = hello(); beyond.offset = 7; - let mut headers = Contents::new(Location::File(Name::new("a").unwrap())); + let mut headers = ContentsObject::new(ContentsSource::File(Name::new("a").unwrap())); headers.http_headers = vec![("A".to_string(), "b".to_string())]; let mut empty = file(Some(3), hello()); empty.contents.clear(); @@ -2792,10 +2795,10 @@ mod tests { .contents .remove(0) }; - assert_eq!(contents("{}"), Contents::default()); + assert_eq!(contents("{}"), ContentsObject::default()); assert_eq!( contents(r#"{"file":null,"url":null,"literal":null,"offset":null,"xHeaders":{"A":"b"}}"#), - Contents::default() + ContentsObject::default() ); // The header fields of a request for a URL, sorted by nothing but // the manifest. diff --git a/src/uapi16/error.rs b/src/uapi16/error.rs index c9eed7c..b797f08 100644 --- a/src/uapi16/error.rs +++ b/src/uapi16/error.rs @@ -208,13 +208,13 @@ pub enum DataProblem { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum UnsupportedData { - /// It starts at an offset in its file, and the source is a - /// [`StreamSource`](crate::StreamSource), which has it and nothing else - /// of the file. + /// It starts at an offset in its file, and the provider is a + /// [`StreamProvider`](crate::StreamProvider), which has it and nothing + /// else of the file. OffsetInStream, - /// The object gives no size, and the source is a - /// [`StreamSource`](crate::StreamSource), which needs it to know where - /// the data ends. + /// The object gives no size, and the provider is a + /// [`StreamProvider`](crate::StreamProvider), which needs it to know + /// where the data ends. NoSize, /// Every contents object of the file has it at a URL or in an /// encoding, and it would have to be fetched or decoded. diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index be5a639..698581d 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -19,14 +19,14 @@ //! checks it the way the reader does. [`Encoder`] does the same into a //! string, and does no I/O. [`Sha256Context`] computes the hash of a file //! while it is read, and [`Sha256Context::finalize`] returns it. -//! - [`RootObject`], [`FileObject`], [`Contents`] and [`Signature`] are the -//! objects, and [`Name`], [`InodeType`], [`Mode`], [`DosFlags`], -//! [`InodeFlags`], [`Sha256`] and [`Uuid`] what their fields hold. What -//! the root file object and a file object both have is in -//! [`InodeAttributes`] and [`ValidityWindow`]. -//! - [`ContentSource`] is where the data of the files comes from when a -//! manifest is applied: [`DirectorySource`] for the files next to the -//! manifest and [`StreamSource`] for one stream with all of them. +//! - [`RootObject`], [`FileObject`], [`ContentsObject`] and +//! [`SignatureObject`] are the objects, and [`Name`], [`InodeType`], +//! [`Mode`], [`DosFlags`], [`InodeFlags`], [`Sha256`] and [`Uuid`] what +//! their fields hold. What the root file object and a file object both +//! have is in [`InodeAttributes`] and [`ValidityWindow`]. +//! - [`DataProvider`] is where the data of the files comes from when a +//! manifest is applied: [`DirectoryProvider`] for the files next to the +//! manifest and [`StreamProvider`] for one stream with all of them. //! [`FileObject::copy_data`] copies the data of a file and checks it //! against the manifest with a [`DataCheck`]. //! @@ -105,16 +105,16 @@ mod writer; pub use blocking::{Reader, Writer}; pub use content::{ - ContentSource, DataCheck, DataLocation, Directory, DirectorySource, ExternalFile, OpenError, StreamSource, + DataCheck, DataLocation, DataProvider, Directory, DirectoryProvider, ExternalFile, OpenError, StreamProvider, }; pub use digest::{InvalidDigest, Sha256, Sha256Context}; pub use error::{DataProblem, Error, ErrorKind, Field, Problem, SourceProblem, UnsupportedData, ValidityProblem}; pub use features::{Features, Order, UnknownFeature}; pub use name::{Name, NameProblem}; pub use object::{ - Contents, DosFlags, FatSerial, FileObject, FileSystemIdentity, FilledIn, FlagStates, GptPartition, InodeAttributes, - InodeFlags, InodeType, InvalidFatSerial, InvalidMode, InvalidUuid, Location, Mode, RootObject, Signature, - UnknownInodeType, Uuid, Validity, ValidityWindow, + ContentsObject, ContentsSource, DosFlags, FatSerial, FileObject, FileSystemIdentity, FilledIn, FlagStates, + GptPartition, InodeAttributes, InodeFlags, InodeType, InvalidFatSerial, InvalidMode, InvalidUuid, Mode, RootObject, + SignatureObject, UnknownInodeType, Uuid, Validity, ValidityWindow, }; pub use reader::{Decoder, Object, Step}; pub use writer::Encoder; @@ -155,8 +155,9 @@ pub(crate) const STRING_RULES: strict::StringRules = pub(crate) mod testing { use super::blocking::READ_SIZE; use super::{ - Contents, DosFlags, Error, Features, FileObject, GptPartition, InodeFlags, InodeType, Location, Mode, Name, - Object, Reader, RootObject, Sha256, Signature, Uuid, Validity, Writer, RECORD_END, RECORD_SEPARATOR, + ContentsObject, ContentsSource, DosFlags, Error, Features, FileObject, GptPartition, InodeFlags, InodeType, + Mode, Name, Object, Reader, RootObject, Sha256, SignatureObject, Uuid, Validity, Writer, RECORD_END, + RECORD_SEPARATOR, }; use crate::strict::{ParseError, Skip, Strict}; use serde_core::de::DeserializeSeed; @@ -203,7 +204,7 @@ pub(crate) mod testing { pub(crate) struct Whole { pub(crate) root: RootObject, pub(crate) objects: Vec, - pub(crate) signatures: Vec, + pub(crate) signatures: Vec, } /// How many arrays and objects serde_json reads inside each other. @@ -347,7 +348,7 @@ pub(crate) mod testing { bytes[Uuid::SIZE - 1] = last; Uuid::new(bytes) }; - let mut encoded = Contents::new(Location::File(name("blob.gz"))); + let mut encoded = ContentsObject::new(ContentsSource::File(name("blob.gz"))); encoded.encoding = Some("gzip".into()); encoded.encoded_size = Some(3); encoded.encoded_sha256 = Some(Sha256::digest(b"gz")); @@ -392,15 +393,15 @@ pub(crate) mod testing { object.inode.read_only = Some(true); object.contents = vec![ encoded, - Contents { + ContentsObject { http_headers: vec![ ("X-Foo".into(), "bar".into()), ("Authorization".into(), "Bearer x".into()), ], - ..Contents::new(Location::Url("https://example.com/blob".into())) + ..ContentsObject::new(ContentsSource::Url("https://example.com/blob".into())) }, - Contents::new(Location::Literal(b"hello".to_vec())), - Contents::default(), + ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())), + ContentsObject::default(), ]; object.sha256 = HELLO.parse().ok(); object.validity.since_usec = 6; diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 7aad692..3f996c1 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -671,7 +671,7 @@ impl FlagStates { /// an object take a filled-in `readOnly` for one that is not there. /// /// The `size` and the `sha256` of a [`FileObject`], the sizes and hashes -/// of a [`Contents`] and the `readOnly` of [`InodeAttributes`] can be +/// of a [`ContentsObject`] and the `readOnly` of [`InodeAttributes`] can be /// filled in. Each of them notes it in its own `filled_in`. #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct FilledIn(u8); @@ -861,10 +861,11 @@ impl FileSystemIdentity { } } -/// Where a contents object says the data is. It names at most one place. +/// The source of a contents object: where it says the data is. It names +/// at most one. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] -pub enum Location { +pub enum ContentsSource { /// Neither `file`, `url` nor `literal` is given: the data is in the /// file of the object's own name, next to the manifest. #[default] @@ -886,9 +887,9 @@ pub enum Location { /// decoded data that starts at `offset`. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] -pub struct Contents { +pub struct ContentsObject { /// `file`, `url` or `literal`: where the data is. - pub location: Location, + pub source: ContentsSource, /// `httpHeaders`: the header fields of the HTTP requests for the data /// at `url`, by name, in the order the manifest lists them. pub http_headers: Vec<(String, String)>, @@ -910,37 +911,37 @@ pub struct Contents { pub filled_in: FilledIn, } -impl Contents { - /// A contents object for data in the place `location`, stored as it +impl ContentsObject { + /// A contents object for data from the source `source`, stored as it /// is. - pub fn new(location: Location) -> Contents { - Contents { - location, - ..Contents::default() + pub fn new(source: ContentsSource) -> ContentsObject { + ContentsObject { + source, + ..ContentsObject::default() } } /// The data the manifest carries itself, if this is where the data /// is. pub fn literal(&self) -> Option<&[u8]> { - match &self.location { - Location::Literal(data) => Some(data), + match &self.source { + ContentsSource::Literal(data) => Some(data), _ => None, } } /// The file next to the manifest the data is in, if `file` names one. pub fn file(&self) -> Option<&Name> { - match &self.location { - Location::File(name) => Some(name), + match &self.source { + ContentsSource::File(name) => Some(name), _ => None, } } /// The URL the data is at, if this is where the data is. pub fn url(&self) -> Option<&str> { - match &self.location { - Location::Url(url) => Some(url), + match &self.source { + ContentsSource::Url(url) => Some(url), _ => None, } } @@ -1111,7 +1112,7 @@ pub struct FileObject { pub sha256: Option, /// `contents`: where the contents can be taken from. Without any they /// are in the file of the object's name next to the manifest. - pub contents: Vec, + pub contents: Vec, /// `inodeToken`: the objects that carry the same token are hard links /// to one file. None is a file of its own. pub inode_token: Option, @@ -1368,7 +1369,7 @@ impl RootObject { /// verify them. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] -pub struct Signature { +pub struct SignatureObject { /// `mechanism`: how the signature was made. The specification has /// `openpgp` and `pkcs7`. pub mechanism: String, @@ -1378,11 +1379,11 @@ pub struct Signature { pub data: Option>, } -impl Signature { +impl SignatureObject { /// A signature object of the mechanism `mechanism`, without a key /// and without data. - pub fn new(mechanism: impl Into) -> Signature { - Signature { + pub fn new(mechanism: impl Into) -> SignatureObject { + SignatureObject { mechanism: mechanism.into(), key: None, data: None, @@ -1720,7 +1721,7 @@ mod tests { // The contents of a symbolic link are its target, which a feature // records. Those of other files are not. let mut object = FileObject::new(Name::new("f").unwrap()); - object.contents = vec![Contents::new(Location::Literal(b"t".to_vec()))]; + object.contents = vec![ContentsObject::new(ContentsSource::Literal(b"t".to_vec()))]; assert_eq!(object.stated_features(), Features::NONE); object.inode_type = InodeType::Symlink; assert_eq!(object.stated_features(), Features::SYMLINK); @@ -1759,18 +1760,18 @@ mod tests { #[test] fn contents_objects() { - let contents = Contents::default(); - assert_eq!(contents.location, Location::Implied); + let contents = ContentsObject::default(); + assert_eq!(contents.source, ContentsSource::Implied); assert_eq!( (contents.literal(), contents.file(), contents.url()), (None, None, None) ); - let literal = Contents::new(Location::Literal(b"data".to_vec())); + let literal = ContentsObject::new(ContentsSource::Literal(b"data".to_vec())); assert_eq!(literal.literal(), Some(&b"data"[..])); assert_eq!((literal.file(), literal.url(), literal.offset), (None, None, 0)); - let file = Contents::new(Location::File(Name::new("blob").unwrap())); + let file = ContentsObject::new(ContentsSource::File(Name::new("blob").unwrap())); assert_eq!(file.file().map(Name::as_str), Some("blob")); - let url = Contents::new(Location::Url("https://example.com/x".to_string())); + let url = ContentsObject::new(ContentsSource::Url("https://example.com/x".to_string())); assert_eq!(url.url(), Some("https://example.com/x")); } } diff --git a/src/uapi16/reader.rs b/src/uapi16/reader.rs index 34baa3a..e5a776c 100644 --- a/src/uapi16/reader.rs +++ b/src/uapi16/reader.rs @@ -6,7 +6,7 @@ use std::io::{self, BufRead}; use crate::decode::{DecodedObject, RecordDecoder, ROOT_RECORD}; use crate::error::{Error, Problem}; -use crate::object::{FileObject, RootObject, Signature}; +use crate::object::{FileObject, RootObject, SignatureObject}; use crate::sequence::SequenceCheck; use crate::strict::is_whitespace; use crate::{MAX_RECORD_SIZE, RECORD_END, RECORD_SEPARATOR}; @@ -232,7 +232,7 @@ pub enum Object { /// A file object. File(Box), /// A signature object. It comes after the last file object. - Signature(Signature), + Signature(SignatureObject), } /// How far a decoder has got in the manifest. diff --git a/src/uapi16/sequence.rs b/src/uapi16/sequence.rs index 7666cc7..1d61c94 100644 --- a/src/uapi16/sequence.rs +++ b/src/uapi16/sequence.rs @@ -158,7 +158,7 @@ mod tests { use super::*; use crate::error::ErrorKind; use crate::testing::full_tree_names; - use crate::{Contents, DosFlags, FatSerial, InodeFlags, Location, Mode, Name, Uuid}; + use crate::{ContentsObject, ContentsSource, DosFlags, FatSerial, InodeFlags, Mode, Name, Uuid}; use std::num::NonZeroU64; /// Gives an object a field. @@ -351,7 +351,7 @@ mod tests { ), ( InodeType::Symlink, - |o| o.contents = vec![Contents::new(Location::Literal(b"t".to_vec()))], + |o| o.contents = vec![ContentsObject::new(ContentsSource::Literal(b"t".to_vec()))], Field::Contents, ), ]; diff --git a/src/uapi16/tests/fixtures.rs b/src/uapi16/tests/fixtures.rs index 215e5bf..77f9a45 100644 --- a/src/uapi16/tests/fixtures.rs +++ b/src/uapi16/tests/fixtures.rs @@ -5,7 +5,7 @@ use std::path::{Path, PathBuf}; -use uapi16::{Error, FileObject, InodeType, Object, Order, Reader, RootObject, Signature, Writer}; +use uapi16::{Error, FileObject, InodeType, Object, Order, Reader, RootObject, SignatureObject, Writer}; /// A manifest read to its end: its root file object, its file objects and /// its signature objects. @@ -13,7 +13,7 @@ use uapi16::{Error, FileObject, InodeType, Object, Order, Reader, RootObject, Si struct Manifest { root: RootObject, files: Vec, - signatures: Vec, + signatures: Vec, } impl Manifest { diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs index 7a5fb1b..9c538d0 100644 --- a/src/uapi16/writer.rs +++ b/src/uapi16/writer.rs @@ -15,8 +15,8 @@ use crate::decode::{Subject, ROOT_RECORD}; use crate::error::{Error, Field, Problem}; use crate::hex::Hex; use crate::object::{ - Contents, FileObject, FileSystemIdentity, FilledIn, FlagSet, FlagStates, GptPartition, InodeAttributes, InodeType, - RootObject, Signature, Validity, ValidityWindow, + ContentsObject, FileObject, FileSystemIdentity, FilledIn, FlagSet, FlagStates, GptPartition, InodeAttributes, + InodeType, RootObject, SignatureObject, Validity, ValidityWindow, }; use crate::sequence::SequenceCheck; use crate::{ @@ -113,7 +113,7 @@ impl Encoder { /// Appends the record of the signature object `signature` to `text`. /// No file object can follow it: it would be one the signature does /// not cover. - pub fn signature(&mut self, signature: &Signature, text: &mut String) -> Result<(), Error> { + pub fn signature(&mut self, signature: &SignatureObject, text: &mut String) -> Result<(), Error> { self.encode_signature(signature)?; self.append_to(text); Ok(()) @@ -189,7 +189,7 @@ impl Encoder { } /// Puts together the record of the signature object `signature`. - pub(crate) fn encode_signature(&mut self, signature: &Signature) -> Result<(), Error> { + pub(crate) fn encode_signature(&mut self, signature: &SignatureObject) -> Result<(), Error> { let record_number = self.next_record; if self.stage == Stage::Done { return Err(Error::data_after_trailer(record_number)); @@ -575,7 +575,7 @@ impl Fields for FileObject { } /// The contents objects of a file object, as `contents` has them. -struct ContentsList<'a>(&'a [Contents]); +struct ContentsList<'a>(&'a [ContentsObject]); impl Serialize for ContentsList<'_> { fn serialize(&self, serializer: S) -> Result { @@ -683,7 +683,7 @@ impl ValidityWindow { } } -impl Contents { +impl ContentsObject { /// Checks every string of the contents object, one of those of the /// file object `subject` names, in the order of the keys, for what the /// strings of a manifest may not hold, and its header fields for two of @@ -719,18 +719,18 @@ impl Contents { /// Checks the contents object, one of those of the file object /// `subject` names, as a reader does: the value of every field, in the - /// order of the keys. [`Contents::check_consistency`] checks the fields - /// against each other. + /// order of the keys. [`ContentsObject::check_consistency`] checks the + /// fields against each other. fn check(&self, subject: Subject<'_>) -> Result<(), Error> { if let Some(encoding) = &self.encoding { - Contents::check_encoding(encoding, subject)?; + ContentsObject::check_encoding(encoding, subject)?; } // A reader checks the header fields in the order they are written. if !self.http_headers.is_empty() { - Contents::check_headers(self.sorted_headers(), subject)?; + ContentsObject::check_headers(self.sorted_headers(), subject)?; } match self.url() { - Some(url) => Contents::check_url(url, subject), + Some(url) => ContentsObject::check_url(url, subject), None => Ok(()), } } @@ -748,7 +748,7 @@ impl Contents { /// filled in, the hash of no data next to the size 0, and without an /// encoding the encoded size and hash where the original ones say the /// same. A reader fills them in again. -impl Fields for Contents { +impl Fields for ContentsObject { fn filled_in(&self) -> FilledIn { self.filled_in } @@ -796,7 +796,7 @@ impl Sha256 { } } -impl Fields for Signature { +impl Fields for SignatureObject { fn filled_in(&self) -> FilledIn { FilledIn::default() } @@ -826,7 +826,7 @@ impl Fields for Trailer { mod tests { use super::*; use crate::error::ErrorKind; - use crate::object::{DosFlags, FatSerial, InodeFlags, Location, Mode, Uuid}; + use crate::object::{ContentsSource, DosFlags, FatSerial, InodeFlags, Mode, Uuid}; use crate::testing::{ directory, everything, json, name, read_whole, record, recording_all, sequence, write_whole, written, Whole, EMPTY, HELLO, ROOT, SIGNATURE, TRAILER, @@ -916,7 +916,7 @@ mod tests { // names of one hard-linked file. let mut link = FileObject::new(name("link")); link.inode_type = InodeType::Symlink; - link.contents = vec![Contents::new(Location::Literal(b"a.txt".to_vec()))]; + link.contents = vec![ContentsObject::new(ContentsSource::Literal(b"a.txt".to_vec()))]; link.inode.gid = Some(1000); link.inode.group_name = Some("brauner".into()); link.size = Some(5); @@ -1026,7 +1026,7 @@ mod tests { fat_serial: Some(FatSerial(0x1234_abcd)), }; root.inode.mtime_nsec = Some(0); - let mut signature = Signature::new("pkcs7"); + let mut signature = SignatureObject::new("pkcs7"); signature.key = Some(vec![0xde, 0xad]); signature.data = Some(vec![1, 2, 3, 4]); let objects = [directory("a"), object.clone(), directory("dev"), device.clone()]; @@ -1035,7 +1035,7 @@ mod tests { writer.file(object).unwrap(); } writer.signature(&signature).unwrap(); - writer.signature(&Signature::new("openpgp")).unwrap(); + writer.signature(&SignatureObject::new("openpgp")).unwrap(); }); // No whitespace but the one in the name and in a header, and every // key in its place. @@ -1157,7 +1157,7 @@ mod tests { object.fill_in(Features::ALL); } assert_eq!(m.objects, expected); - assert_eq!(m.signatures, [signature, Signature::new("openpgp")]); + assert_eq!(m.signatures, [signature, SignatureObject::new("openpgp")]); assert_eq!(read_whole(&write_whole(&m).unwrap()).unwrap(), m); } @@ -1185,13 +1185,13 @@ mod tests { let e = writer.file(&FileObject::new(Name::ROOT)).unwrap_err(); assert_eq!(kind(e), (Problem::NoName, Some(1), Some(Field::Name))); writer.file(&FileObject::new(name("a"))).unwrap(); - writer.signature(&Signature::new("pkcs7")).unwrap(); + writer.signature(&SignatureObject::new("pkcs7")).unwrap(); let e = writer.file(&FileObject::new(name("b"))).unwrap_err(); assert_eq!(kind(e), (Problem::FileAfterSignature, Some(3), None)); // As for a reader, that comes before a missing name. let e = writer.file(&FileObject::new(Name::ROOT)).unwrap_err(); assert_eq!(kind(e), (Problem::FileAfterSignature, Some(3), None)); - writer.signature(&Signature::new("openpgp")).unwrap(); + writer.signature(&SignatureObject::new("openpgp")).unwrap(); let bytes = writer.finish().unwrap(); let m = read_whole(&bytes).unwrap(); assert_eq!((m.objects.len(), m.signatures.len()), (1, 2)); @@ -1406,13 +1406,13 @@ mod tests { let mut object = FileObject::new(name("x")); (object.size, object.sha256) = (Some(0), Some(empty)); // With an encoding, that of the encoded and of the original data. - let mut encoded = Contents::new(Location::File(name("x.gz"))); + let mut encoded = ContentsObject::new(ContentsSource::File(name("x.gz"))); encoded.encoding = Some("gzip".into()); (encoded.encoded_size, encoded.encoded_sha256) = (Some(0), Some(empty)); (encoded.original_size, encoded.original_sha256) = (Some(0), Some(empty)); // Without an encoding, the encoded size and hash next to the // original ones, which say the same. - let mut plain = Contents::new(Location::File(name("x"))); + let mut plain = ContentsObject::new(ContentsSource::File(name("x"))); (plain.encoded_size, plain.encoded_sha256) = (Some(0), Some(empty)); (plain.original_size, plain.original_sha256) = (Some(0), Some(empty)); object.contents = vec![encoded, plain]; @@ -1436,9 +1436,9 @@ mod tests { } // Where only the encoded size says it, it stays. let mut only = FileObject::new(name("y")); - only.contents = vec![Contents { + only.contents = vec![ContentsObject { encoded_size: Some(5), - ..Contents::new(Location::File(name("y"))) + ..ContentsObject::new(ContentsSource::File(name("y"))) }]; assert_eq!( record(&only), @@ -1501,7 +1501,7 @@ mod tests { noncharacter() ), |o| { - o.contents = vec![Contents::new(Location::Literal(vec![0; MAX_RECORD_SIZE / 4 * 3]))]; + o.contents = vec![ContentsObject::new(ContentsSource::Literal(vec![0; MAX_RECORD_SIZE / 4 * 3]))]; o.inode.user_name = Some(format!("u{}", noncharacter()).into()); }, Problem::RecordTooLarge, @@ -1518,9 +1518,9 @@ mod tests { r#"{"contents":[{"httpHeaders":{"A":"b","A":"c"},"url":"https://example.com/x"}],"name":"x","uid":65535}"# .into(), |o| { - o.contents = vec![Contents { + o.contents = vec![ContentsObject { http_headers: vec![("A".into(), "b".into()), ("A".into(), "c".into())], - ..Contents::new(Location::Url("https://example.com/x".into())) + ..ContentsObject::new(ContentsSource::Url("https://example.com/x".into())) }]; o.inode.uid = Some(65535); }, @@ -1535,7 +1535,7 @@ mod tests { ), |o| { o.contents = (0..=MAX_CONTENTS) - .map(|_| Contents::new(Location::Literal(b"a".to_vec()))) + .map(|_| ContentsObject::new(ContentsSource::Literal(b"a".to_vec()))) .collect(); o.contents[0].original_size = Some(5); }, @@ -1546,9 +1546,9 @@ mod tests { ( r#"{"contents":[{"file":"a","httpHeaders":{"A":"b"}}],"name":"x","uid":65535}"#.into(), |o| { - o.contents = vec![Contents { + o.contents = vec![ContentsObject { http_headers: vec![("A".into(), "b".into())], - ..Contents::new(Location::File(name("a"))) + ..ContentsObject::new(ContentsSource::File(name("a"))) }]; o.inode.uid = Some(65535); }, @@ -1623,7 +1623,7 @@ mod tests { (ErrorKind::Manifest(Problem::InvalidString), Some(2)) ); let mut writer = Writer::begin(Vec::new(), &root).unwrap(); - writer.signature(&Signature::new("pkcs7")).unwrap(); + writer.signature(&SignatureObject::new("pkcs7")).unwrap(); let mut object = FileObject::new(name("x")); object.inode.user_name = Some(format!("u{}", noncharacter()).into()); let w = writer.file(&object).unwrap_err(); @@ -1632,7 +1632,7 @@ mod tests { let e = read_whole(&sequence(&[root_text, SIGNATURE, r#"{"uid":65535}"#, TRAILER])).unwrap_err(); assert_eq!(e.kind(), ErrorKind::Manifest(Problem::FileAfterSignature)); let mut writer = Writer::begin(Vec::new(), &root).unwrap(); - writer.signature(&Signature::new("pkcs7")).unwrap(); + writer.signature(&SignatureObject::new("pkcs7")).unwrap(); let mut nameless = FileObject::new(Name::ROOT); nameless.inode.uid = Some(65535); let w = writer.file(&nameless).unwrap_err(); @@ -1669,20 +1669,20 @@ mod tests { /// Gives an object a value. type Give = fn(&mut FileObject); /// Contents at a URL, with the header fields `headers`. - fn headers(headers: &[(&str, &str)]) -> Contents { - Contents { + fn headers(headers: &[(&str, &str)]) -> ContentsObject { + ContentsObject { http_headers: headers .iter() .map(|&(name, value)| (name.into(), value.into())) .collect(), - ..Contents::new(Location::Url("https://example.com/x".into())) + ..ContentsObject::new(ContentsSource::Url("https://example.com/x".into())) } } /// Contents in the encoding `encoding`. - fn encoded(encoding: &str) -> Contents { - Contents { + fn encoded(encoding: &str) -> ContentsObject { + ContentsObject { encoding: Some(encoding.into()), - ..Contents::new(Location::File(name("x.gz"))) + ..ContentsObject::new(ContentsSource::File(name("x.gz"))) } } /// Gives `object` the extended attribute `name`, without a value. @@ -1726,7 +1726,7 @@ mod tests { (|o| o.gpt = gpt("x\0"), Problem::InvalidString, Field::GptLabel), (|o| o.gpt = gpt("a\tb"), Problem::WrongFieldType, Field::GptLabel), ( - |o| o.contents = vec![Contents::new(Location::Url("ftp://example.com/x".into()))], + |o| o.contents = vec![ContentsObject::new(ContentsSource::Url("ftp://example.com/x".into()))], Problem::InvalidContents, Field::Url, ), @@ -1763,7 +1763,7 @@ mod tests { Field::HttpHeaders, ), ( - |o| o.contents = vec![Contents::default(); MAX_CONTENTS + 1], + |o| o.contents = vec![ContentsObject::default(); MAX_CONTENTS + 1], Problem::InvalidContents, Field::Contents, ), @@ -1812,7 +1812,7 @@ mod tests { } // The mechanism of a signature. let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); - let e = writer.signature(&Signature::new("pkcs7\u{fffe}")).unwrap_err(); + let e = writer.signature(&SignatureObject::new("pkcs7\u{fffe}")).unwrap_err(); assert_eq!( (e.kind(), e.field(), e.record_number()), ( @@ -1850,8 +1850,8 @@ mod tests { })) } /// Contents in the file "x". - fn file() -> Contents { - Contents::new(Location::File(name("x"))) + fn file() -> ContentsObject { + ContentsObject::new(ContentsSource::File(name("x"))) } let cases: [(Give, Problem, Option); 17] = [ // Fields the inode type does not permit. @@ -1939,7 +1939,7 @@ mod tests { // httpHeaders without a URL, and a part beyond the data. ( |o| { - o.contents = vec![Contents { + o.contents = vec![ContentsObject { http_headers: vec![("A".into(), "b".into())], ..file() }]; @@ -1950,7 +1950,7 @@ mod tests { ( |o| { o.size = Some(5); - o.contents = vec![Contents { + o.contents = vec![ContentsObject { original_size: Some(6), offset: 2, ..file() @@ -1985,7 +1985,7 @@ mod tests { let whole = Whole { root: root.clone(), objects: vec![directory("a"), everything()], - signatures: vec![Signature::new("pkcs7")], + signatures: vec![SignatureObject::new("pkcs7")], }; let mut text = String::new(); let mut encoder = Encoder::begin(&root, &mut text).unwrap(); @@ -2011,7 +2011,9 @@ mod tests { for e in [ encoder.file(&FileObject::new(name("z")), &mut text).unwrap_err(), encoder.file(&FileObject::new(Name::ROOT), &mut text).unwrap_err(), - encoder.signature(&Signature::new("pkcs7"), &mut text).unwrap_err(), + encoder + .signature(&SignatureObject::new("pkcs7"), &mut text) + .unwrap_err(), encoder.finish(&mut text).unwrap_err(), ] { assert_eq!( From 434b9caa2e4309f7f01e59b3b7904f0f73864c3f Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 17:54:59 +0100 Subject: [PATCH 14/32] uapi16: make the bits of FatSerial private FatSerial is a tuple struct with a public u32, so its representation is part of the API. Make the field private and give FatSerial a constructor and a getter instead, new() and get(), named like Mode::new(), Uuid::new() and NonZeroU32::get(). Both are const, so a serial can still be a constant. Callers write FatSerial::new(x) instead of FatSerial(x) and serial.get() instead of serial.0. While at it, give FatSerial a Debug of its own that prints the serial in hexadecimal, FatSerial(0x1234abcd), the way Mode prints its bits in octal. The derived one printed it in decimal, FatSerial(305441741) for 1234-ABCD. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/object.rs | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 3f996c1..12cd6df 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -741,12 +741,13 @@ impl fmt::Debug for FilledIn { /// use uapi16::FatSerial; /// /// let serial: FatSerial = "1234-abcd".parse()?; -/// assert_eq!(serial, FatSerial(0x1234_abcd)); +/// assert_eq!(serial, FatSerial::new(0x1234_abcd)); +/// assert_eq!(serial.get(), 0x1234_abcd); /// assert_eq!(serial.to_string(), "1234-ABCD"); /// # Ok::<(), uapi16::InvalidFatSerial>(()) /// ``` -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct FatSerial(pub u32); +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct FatSerial(pub(crate) u32); /// A string that is not a FAT volume serial number, see [`FatSerial`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -770,6 +771,16 @@ impl FatSerial { /// The radix of the digits. const HEX: u32 = 16; + /// The serial number with the 32 bits `serial`. + pub const fn new(serial: u32) -> FatSerial { + FatSerial(serial) + } + + /// The 32 bits of the serial number. + pub const fn get(self) -> u32 { + self.0 + } + /// The serial number the specification derives from a file system /// UUID: its first four bytes. pub fn from_uuid(uuid: &Uuid) -> FatSerial { @@ -778,6 +789,12 @@ impl FatSerial { } } +impl fmt::Debug for FatSerial { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "FatSerial({:#x})", self.0) + } +} + impl fmt::Display for FatSerial { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( @@ -852,9 +869,9 @@ impl FileSystemIdentity { /// /// let mut identity = FileSystemIdentity::default(); /// identity.uuid = "1234abcd-5678-4ef0-9abc-def012345678".parse().ok(); - /// assert_eq!(identity.volume_serial(), Some(FatSerial(0x1234_abcd))); - /// identity.fat_serial = Some(FatSerial(0x5678_9abc)); - /// assert_eq!(identity.volume_serial(), Some(FatSerial(0x5678_9abc))); + /// assert_eq!(identity.volume_serial(), Some(FatSerial::new(0x1234_abcd))); + /// identity.fat_serial = Some(FatSerial::new(0x5678_9abc)); + /// assert_eq!(identity.volume_serial(), Some(FatSerial::new(0x5678_9abc))); /// ``` pub fn volume_serial(&self) -> Option { self.fat_serial.or_else(|| self.uuid.as_ref().map(FatSerial::from_uuid)) @@ -1497,6 +1514,11 @@ mod tests { } } + #[test] + fn fat_serials() { + assert_eq!(format!("{:?}", FatSerial::new(0x1234_abcd)), "FatSerial(0x1234abcd)"); + } + #[test] fn times() { let mut inode = InodeAttributes::default(); From 26bb6a3ba32b6a7ef55b2da6ea4945c28b59d8f6 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 17:56:19 +0100 Subject: [PATCH 15/32] uapi16: give every flag field an accessor of its own The specification has a boolean field for every flag: flagHidden, flagSystem and flagArchive for the DOS attributes, and flagAppendOnly, flagImmutable, flagNoAtime, flagNoCow and flagNoDump for the inode flags. Callers get at them through a FlagStates and a mask: object.dos_flags.get(DosFlags::HIDDEN) object.inode.flags.put(InodeFlags::NO_COW, Some(false)) Give every one of these fields a getter and a setter of its own instead, the way readOnly and the gpt flags have them. They take and return an Option: Some(true) for a flag that is set, Some(false) for one that is cleared, and None where the object says nothing about it: object.flag_hidden() object.inode.set_flag_no_cow(Some(false)) FileObject gets the three DOS attributes and InodeAttributes the five inode flags. That's one pair for every entry of DosFlags::FIELDS and InodeFlags::FIELDS, which a test checks. The masks stay the representation, and every accessor is one get() or put() on them. So filling in, the checks of the inode type and the writer keep working on whole masks. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/object.rs | 163 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 163 insertions(+) diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 12cd6df..aa3a4ef 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -1102,6 +1102,66 @@ impl InodeAttributes { (None, None) => false, } } + + /// `flagAppendOnly`: whether the inode flag `FS_APPEND_FL` is set. None + /// says nothing about it. + pub fn flag_append_only(&self) -> Option { + self.flags.get(InodeFlags::APPEND_ONLY) + } + + /// Sets `flagAppendOnly`: the inode flag `FS_APPEND_FL` is set, cleared, or + /// not known. + pub fn set_flag_append_only(&mut self, append_only: Option) { + self.flags.put(InodeFlags::APPEND_ONLY, append_only); + } + + /// `flagImmutable`: whether the inode flag `FS_IMMUTABLE_FL` is set. None + /// says nothing about it. + pub fn flag_immutable(&self) -> Option { + self.flags.get(InodeFlags::IMMUTABLE) + } + + /// Sets `flagImmutable`: the inode flag `FS_IMMUTABLE_FL` is set, cleared, + /// or not known. + pub fn set_flag_immutable(&mut self, immutable: Option) { + self.flags.put(InodeFlags::IMMUTABLE, immutable); + } + + /// `flagNoAtime`: whether the inode flag `FS_NOATIME_FL` is set. None says + /// nothing about it. + pub fn flag_no_atime(&self) -> Option { + self.flags.get(InodeFlags::NO_ATIME) + } + + /// Sets `flagNoAtime`: the inode flag `FS_NOATIME_FL` is set, cleared, or + /// not known. + pub fn set_flag_no_atime(&mut self, no_atime: Option) { + self.flags.put(InodeFlags::NO_ATIME, no_atime); + } + + /// `flagNoCow`: whether the inode flag `FS_NOCOW_FL` is set. None says + /// nothing about it. + pub fn flag_no_cow(&self) -> Option { + self.flags.get(InodeFlags::NO_COW) + } + + /// Sets `flagNoCow`: the inode flag `FS_NOCOW_FL` is set, cleared, or not + /// known. + pub fn set_flag_no_cow(&mut self, no_cow: Option) { + self.flags.put(InodeFlags::NO_COW, no_cow); + } + + /// `flagNoDump`: whether the inode flag `FS_NODUMP_FL` is set. None says + /// nothing about it. + pub fn flag_no_dump(&self) -> Option { + self.flags.get(InodeFlags::NO_DUMP) + } + + /// Sets `flagNoDump`: the inode flag `FS_NODUMP_FL` is set, cleared, or not + /// known. + pub fn set_flag_no_dump(&mut self, no_dump: Option) { + self.flags.put(InodeFlags::NO_DUMP, no_dump); + } } /// A file object: what a manifest says about one file below its root. @@ -1262,6 +1322,42 @@ impl FileObject { .check(now_usec, self.name.as_str().escape_debug()) .map_err(|e| e.named(self.name.as_str())) } + + /// `flagArchive`: whether the DOS attribute `ATTR_ARCHIVE` is set. None + /// says nothing about it. + pub fn flag_archive(&self) -> Option { + self.dos_flags.get(DosFlags::ARCHIVE) + } + + /// Sets `flagArchive`: the DOS attribute `ATTR_ARCHIVE` is set, cleared, or + /// not known. + pub fn set_flag_archive(&mut self, archive: Option) { + self.dos_flags.put(DosFlags::ARCHIVE, archive); + } + + /// `flagHidden`: whether the DOS attribute `ATTR_HIDDEN` is set. None says + /// nothing about it. + pub fn flag_hidden(&self) -> Option { + self.dos_flags.get(DosFlags::HIDDEN) + } + + /// Sets `flagHidden`: the DOS attribute `ATTR_HIDDEN` is set, cleared, or + /// not known. + pub fn set_flag_hidden(&mut self, hidden: Option) { + self.dos_flags.put(DosFlags::HIDDEN, hidden); + } + + /// `flagSystem`: whether the DOS attribute `ATTR_SYSTEM` is set. None says + /// nothing about it. + pub fn flag_system(&self) -> Option { + self.dos_flags.get(DosFlags::SYSTEM) + } + + /// Sets `flagSystem`: the DOS attribute `ATTR_SYSTEM` is set, cleared, or + /// not known. + pub fn set_flag_system(&mut self, system: Option) { + self.dos_flags.put(DosFlags::SYSTEM, system); + } } /// The root file object: what a manifest says about the root directory of @@ -1653,6 +1749,73 @@ mod tests { assert_eq!(states, FlagStates::default()); } + /// Every flag has a getter and a setter of its own, for its field and + /// no other. + #[test] + fn flag_accessors() { + type Get = fn(&T) -> Option; + type Set = fn(&mut T, Option); + let inode: [(InodeFlags, Get, Set); 5] = [ + ( + InodeFlags::APPEND_ONLY, + InodeAttributes::flag_append_only, + InodeAttributes::set_flag_append_only, + ), + ( + InodeFlags::IMMUTABLE, + InodeAttributes::flag_immutable, + InodeAttributes::set_flag_immutable, + ), + ( + InodeFlags::NO_ATIME, + InodeAttributes::flag_no_atime, + InodeAttributes::set_flag_no_atime, + ), + ( + InodeFlags::NO_COW, + InodeAttributes::flag_no_cow, + InodeAttributes::set_flag_no_cow, + ), + ( + InodeFlags::NO_DUMP, + InodeAttributes::flag_no_dump, + InodeAttributes::set_flag_no_dump, + ), + ]; + let dos: [(DosFlags, Get, Set); 3] = [ + ( + DosFlags::ARCHIVE, + FileObject::flag_archive, + FileObject::set_flag_archive, + ), + (DosFlags::HIDDEN, FileObject::flag_hidden, FileObject::set_flag_hidden), + (DosFlags::SYSTEM, FileObject::flag_system, FileObject::set_flag_system), + ]; + // One pair for every field, in the order of the fields. + let fields: Vec = InodeFlags::FIELDS.iter().map(|&(flag, _, _)| flag).collect(); + assert_eq!(inode.map(|(flag, _, _)| flag).to_vec(), fields); + let fields: Vec = DosFlags::FIELDS.iter().map(|&(flag, _, _)| flag).collect(); + assert_eq!(dos.map(|(flag, _, _)| flag).to_vec(), fields); + for state in [Some(true), Some(false), None] { + for (flag, get, set) in inode { + let mut attributes = InodeAttributes::default(); + set(&mut attributes, state); + assert_eq!(get(&attributes), state, "{:?}", flag); + let stated = if state.is_some() { flag } else { InodeFlags::NONE }; + assert_eq!(attributes.flags.stated, stated, "{:?}", flag); + assert_eq!(attributes.flags.get(flag), state, "{:?}", flag); + } + for (flag, get, set) in dos { + let mut object = FileObject::new(Name::new("f").unwrap()); + set(&mut object, state); + assert_eq!(get(&object), state, "{:?}", flag); + let stated = if state.is_some() { flag } else { DosFlags::NONE }; + assert_eq!(object.dos_flags.stated, stated, "{:?}", flag); + assert_eq!(object.dos_flags.get(flag), state, "{:?}", flag); + } + } + } + #[test] fn features_of_the_fields() { const UUID: Uuid = Uuid::new([1; Uuid::SIZE]); From 03a97ccc7455ef6532e4d610f76a1ef325a5b7ea Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 18:04:12 +0100 Subject: [PATCH 16/32] uapi16: make the fields of the objects private The objects of a manifest are structs with public fields. That makes how they're stored part of the API: the names of the owners are a Box, the extended attributes a boxed BTreeMap, a partition a Box, and the flags a pair of masks. None of that could change after 0.1.0. It also lets a caller set a value the reader filled in without taking away the mark that says so, and the writer then leaves the new value out. So every public field becomes pub(crate), with a getter named after the field and a set_x() next to it. An optional field has one setter that takes an Option. ExternalFile only gets the getters, since only the crate makes one. The crate keeps using the fields itself, so the reader and the writer don't change. The getters hand out what's stored, but not how: &str for the names, an iterator for the extended attributes and one for the HTTP header fields, Option<&GptPartition> for the partition. The extended attributes can be looked up by name as well. Only the inode attributes of both objects and the identity of the file system get an x_mut(), since callers change those in place, and into_name() is the only into_x(). The flag masks leave the API together with the fields that held them. FlagStates, DosFlags and InodeFlags stay the representation behind the accessors of the flags, but they aren't exported anymore. What a reader filled in needs more care. A value that is set is not one the reader filled in, so its setter takes the mark away. But the sizes and hashes a reader fills in follow from other values: the size 0 from the hash of no data and the other way around, the size of a file from its contents object, and the sizes and hashes of a contents object from each other, from its literal and from having no encoding. Change one of those and what was filled in from it may be wrong. The writer then refuses an object that is fine, or a copy of the data goes by a size that no longer holds. So the setters of the size, the hash and the contents objects of a file object, and those of the sizes, the hashes, the encoding and the source of a contents object drop every size and hash the reader filled in on the same object: they become None and lose their mark. The next reader of the manifest fills them in again. The values a record gave are never dropped. readOnly only takes its own mark away when it is set. FilledIn::insert() and remove() become crate-private, since a caller only ever holds a copy of the marks. FileObject::filled_in() returns the marks of the object together with those of its inode attributes, which is what the writer leaves out. Callers write object.size() for object.size and object.set_size(x) for object.size = x, object.inode().mode() and object.inode_mut().set_mode() for the inode attributes, root.file_system_mut().set_label() for the identity, and use the flag accessors where they used the masks. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/blocking.rs | 6 +- src/uapi16/content.rs | 43 +- src/uapi16/lib.rs | 23 +- src/uapi16/object.rs | 983 ++++++++++++++++++++++++++++------- src/uapi16/reader.rs | 5 +- src/uapi16/sequence.rs | 3 +- src/uapi16/tests/fixtures.rs | 48 +- src/uapi16/writer.rs | 4 +- 8 files changed, 877 insertions(+), 238 deletions(-) diff --git a/src/uapi16/blocking.rs b/src/uapi16/blocking.rs index bd221d7..cb60356 100644 --- a/src/uapi16/blocking.rs +++ b/src/uapi16/blocking.rs @@ -63,7 +63,7 @@ pub(crate) const READ_SIZE: usize = 64 * 1024; /// let mut names = Vec::new(); /// for object in Reader::open(manifest.as_bytes())? { /// if let Object::File(object) = object? { -/// names.push(object.name); +/// names.push(object.into_name()); /// } /// } /// assert_eq!(names, ["a", "b"]); @@ -245,9 +245,9 @@ impl FusedIterator for Reader {} /// use uapi16::{FileObject, Name, Object, Order, Reader, RootObject, Writer}; /// /// let mut root = RootObject::default(); -/// root.order = Some(Order::CodePoint); +/// root.set_order(Some(Order::CodePoint)); /// let mut file = FileObject::new(Name::new("a")?); -/// file.size = Some(3); +/// file.set_size(Some(3)); /// let mut writer = Writer::begin(Vec::new(), &root)?; /// writer.file(&file)?; /// let bytes = writer.finish()?; diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index 6fa7b7e..daac878 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -47,15 +47,10 @@ pub enum DataLocation<'a> { #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct ExternalFile<'a> { - /// The name of the file: the one a contents object names, or else the - /// object's own name. - pub name: &'a Name, - /// Where the data starts in the file. - pub offset: u64, - /// The size of the whole file, if the manifest gives it. - pub original_size: Option, - /// The hash of the whole file, if the manifest gives it. - pub original_sha256: Option, + pub(crate) name: &'a Name, + pub(crate) offset: u64, + pub(crate) original_size: Option, + pub(crate) original_sha256: Option, } /// How much of its file the data of a file object is. @@ -68,6 +63,27 @@ enum DataExtent { } impl<'a> ExternalFile<'a> { + /// The name of the file: the one a contents object names, or else the + /// object's own name. + pub fn name(&self) -> &'a Name { + self.name + } + + /// Where the data starts in the file. + pub fn offset(&self) -> u64 { + self.offset + } + + /// The size of the whole file, if the manifest gives it. + pub fn original_size(&self) -> Option { + self.original_size + } + + /// The hash of the whole file, if the manifest gives it. + pub fn original_sha256(&self) -> Option { + self.original_sha256 + } + /// The file `name` an object has its data in, by way of the contents /// object `contents` if one names it. fn new(name: &'a Name, contents: Option<&'a ContentsObject>) -> ExternalFile<'a> { @@ -348,8 +364,8 @@ impl ContentsObject { /// use uapi16::{DataCheck, FileObject, Name, Sha256}; /// /// let mut object = FileObject::new(Name::new("hello.txt")?); -/// object.size = Some(5); -/// object.sha256 = Some(Sha256::digest(b"hello")); +/// object.set_size(Some(5)); +/// object.set_sha256(Some(Sha256::digest(b"hello"))); /// let mut check = DataCheck::new(&object); /// check.update(b"hel")?; /// check.update(b"lo")?; @@ -479,8 +495,9 @@ impl Write for CheckedSink<'_, '_> { /// [`DataProvider::end`]. pub trait DataProvider { /// Writes the data of `object`, which is in `file`, to `sink`: exactly - /// `object.size` bytes when the object has a size. An error of the sink - /// comes back as it was, and one of the provider names the object. + /// `object.size()` bytes when the object has a size. An error of the + /// sink comes back as it was, and one of the provider names the + /// object. fn copy(&mut self, object: &FileObject, file: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error>; /// Passes over the data of `object`, which the consumer does not take. diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 698581d..39fdb37 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -21,9 +21,14 @@ //! while it is read, and [`Sha256Context::finalize`] returns it. //! - [`RootObject`], [`FileObject`], [`ContentsObject`] and //! [`SignatureObject`] are the objects, and [`Name`], [`InodeType`], -//! [`Mode`], [`DosFlags`], [`InodeFlags`], [`Sha256`] and [`Uuid`] what -//! their fields hold. What the root file object and a file object both -//! have is in [`InodeAttributes`] and [`ValidityWindow`]. +//! [`Mode`], [`Sha256`] and [`Uuid`] what their fields hold. Each field +//! has a getter named after it, and most have a setter. The inode +//! attributes and the identity of the file system are changed in place +//! instead, through [`FileObject::inode_mut`], [`RootObject::inode_mut`] +//! and [`RootObject::file_system_mut`], and the marks of what a reader +//! filled in, [`FilledIn`], can only be read. What the root file object +//! and a file object both have is in [`InodeAttributes`] and +//! [`ValidityWindow`]. //! - [`DataProvider`] is where the data of the files comes from when a //! manifest is applied: [`DirectoryProvider`] for the files next to the //! manifest and [`StreamProvider`] for one stream with all of them. @@ -112,9 +117,9 @@ pub use error::{DataProblem, Error, ErrorKind, Field, Problem, SourceProblem, Un pub use features::{Features, Order, UnknownFeature}; pub use name::{Name, NameProblem}; pub use object::{ - ContentsObject, ContentsSource, DosFlags, FatSerial, FileObject, FileSystemIdentity, FilledIn, FlagStates, - GptPartition, InodeAttributes, InodeFlags, InodeType, InvalidFatSerial, InvalidMode, InvalidUuid, Mode, RootObject, - SignatureObject, UnknownInodeType, Uuid, Validity, ValidityWindow, + ContentsObject, ContentsSource, FatSerial, FileObject, FileSystemIdentity, FilledIn, GptPartition, InodeAttributes, + InodeType, InvalidFatSerial, InvalidMode, InvalidUuid, Mode, RootObject, SignatureObject, UnknownInodeType, Uuid, + Validity, ValidityWindow, }; pub use reader::{Decoder, Object, Step}; pub use writer::Encoder; @@ -154,10 +159,10 @@ pub(crate) const STRING_RULES: strict::StringRules = #[cfg(test)] pub(crate) mod testing { use super::blocking::READ_SIZE; + use super::object::{DosFlags, InodeFlags}; use super::{ - ContentsObject, ContentsSource, DosFlags, Error, Features, FileObject, GptPartition, InodeFlags, InodeType, - Mode, Name, Object, Reader, RootObject, Sha256, SignatureObject, Uuid, Validity, Writer, RECORD_END, - RECORD_SEPARATOR, + ContentsObject, ContentsSource, Error, Features, FileObject, GptPartition, InodeType, Mode, Name, Object, + Reader, RootObject, Sha256, SignatureObject, Uuid, Validity, Writer, RECORD_END, RECORD_SEPARATOR, }; use crate::strict::{ParseError, Skip, Strict}; use serde_core::de::DeserializeSeed; diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index aa3a4ef..7449b12 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -202,17 +202,44 @@ impl fmt::Display for Validity { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ValidityWindow { + pub(crate) since_usec: u64, + pub(crate) until_usec: Option, + pub(crate) state: Validity, +} + +impl ValidityWindow { /// `validSinceUSec`: the file is not to be used before this time, in /// microseconds since the epoch. - pub since_usec: u64, + pub fn since_usec(&self) -> u64 { + self.since_usec + } + + /// Sets `validSinceUSec`. + pub fn set_since_usec(&mut self, since_usec: u64) { + self.since_usec = since_usec; + } + /// `validUntilUSec`: the file is not to be used from this time on, in /// microseconds since the epoch. - pub until_usec: Option, + pub fn until_usec(&self) -> Option { + self.until_usec + } + + /// Sets `validUntilUSec`. + pub fn set_until_usec(&mut self, until_usec: Option) { + self.until_usec = until_usec; + } + /// `validity`: whether the file is revoked. - pub state: Validity, -} + pub fn state(&self) -> Validity { + self.state + } + + /// Sets `validity`. + pub fn set_state(&mut self, state: Validity) { + self.state = state; + } -impl ValidityWindow { /// Checks that what the window is of, which a message calls `subject`, /// may be used at the time `now_usec`, in microseconds since the epoch: /// that it is not revoked and that the time is inside the window. @@ -364,20 +391,12 @@ impl FromStr for Uuid { #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct GptPartition { - /// `gptLabel`: the partition label, at most 36 UTF-16 units. - pub label: Option, - /// `gptUuid`: the partition UUID. - pub uuid: Option, - /// `gptTypeUuid`: the partition type UUID. - pub type_uuid: Option, - /// `gptFlags`: the attribute flags of the partition entry. - pub flags: Option, - /// `gptFlagNoAuto`: the flag of that name in the Discoverable - /// Partitions Specification, [`GptPartition::FLAG_NO_AUTO`]. - pub no_auto: Option, - /// `gptFlagGrowFileSystem`: the flag of that name in the Discoverable - /// Partitions Specification, [`GptPartition::FLAG_GROW_FILE_SYSTEM`]. - pub grow_file_system: Option, + pub(crate) label: Option, + pub(crate) uuid: Option, + pub(crate) type_uuid: Option, + pub(crate) flags: Option, + pub(crate) no_auto: Option, + pub(crate) grow_file_system: Option, } impl GptPartition { @@ -396,6 +415,68 @@ impl GptPartition { /// The longest partition label, in UTF-16 units. pub const LABEL_MAX: usize = 36; + /// `gptLabel`: the partition label, at most 36 UTF-16 units. + pub fn label(&self) -> Option<&str> { + self.label.as_deref() + } + + /// Sets `gptLabel`. + pub fn set_label(&mut self, label: Option) { + self.label = label; + } + + /// `gptUuid`: the partition UUID. + pub fn uuid(&self) -> Option { + self.uuid + } + + /// Sets `gptUuid`. + pub fn set_uuid(&mut self, uuid: Option) { + self.uuid = uuid; + } + + /// `gptTypeUuid`: the partition type UUID. + pub fn type_uuid(&self) -> Option { + self.type_uuid + } + + /// Sets `gptTypeUuid`. + pub fn set_type_uuid(&mut self, type_uuid: Option) { + self.type_uuid = type_uuid; + } + + /// `gptFlags`: the attribute flags of the partition entry. + pub fn flags(&self) -> Option { + self.flags + } + + /// Sets `gptFlags`. + pub fn set_flags(&mut self, flags: Option) { + self.flags = flags; + } + + /// `gptFlagNoAuto`: the flag of that name in the Discoverable + /// Partitions Specification, [`GptPartition::FLAG_NO_AUTO`]. + pub fn no_auto(&self) -> Option { + self.no_auto + } + + /// Sets `gptFlagNoAuto`. + pub fn set_no_auto(&mut self, no_auto: Option) { + self.no_auto = no_auto; + } + + /// `gptFlagGrowFileSystem`: the flag of that name in the Discoverable + /// Partitions Specification, [`GptPartition::FLAG_GROW_FILE_SYSTEM`]. + pub fn grow_file_system(&self) -> Option { + self.grow_file_system + } + + /// Sets `gptFlagGrowFileSystem`. + pub fn set_grow_file_system(&mut self, grow_file_system: Option) { + self.grow_file_system = grow_file_system; + } + /// Whether any of the fields is set. Only a regular file describes a /// partition. pub fn describes_partition(&self) -> bool { @@ -411,11 +492,7 @@ impl GptPartition { /// A set of flags of one kind that the specification has a field for each: /// [`DosFlags`] and [`InodeFlags`]. [`FlagStates`] says the states of the /// flags of one kind. -/// -/// It is public only so that it can bound the methods of [`FlagStates`]. -/// The crate does not export it, so no other crate can name or implement -/// it. -pub trait FlagSet: +pub(crate) trait FlagSet: Copy + Default + PartialEq + BitAnd + BitOr + Not + 'static { /// Every single flag with its field and the feature that records it, in @@ -457,13 +534,13 @@ macro_rules! flag_set { ($flags:ident) => { impl $flags { /// Whether every flag of `flags` is among these. - pub const fn contains(self, flags: $flags) -> bool { + pub(crate) const fn contains(self, flags: $flags) -> bool { self.0 & flags.0 == flags.0 } /// These flags without those of `flags`. #[must_use] - pub const fn without(self, flags: $flags) -> $flags { + pub(crate) const fn without(self, flags: $flags) -> $flags { $flags(self.0 & !flags.0) } } @@ -514,24 +591,22 @@ macro_rules! flag_set { /// /// They are the attributes of FAT, of exFAT and of file systems like them. /// The read-only attribute has no field of its own. `readOnly` stands for -/// it, see [`InodeAttributes::read_only`]. Only regular files and +/// it, see [`InodeAttributes::read_only()`]. Only regular files and /// directories have DOS attributes, and the root directory has none: the /// root directory of FAT has no directory entry to keep them in. #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] -pub struct DosFlags(u8); +pub(crate) struct DosFlags(u8); impl DosFlags { /// `flagHidden`: the DOS attribute `ATTR_HIDDEN`. - pub const HIDDEN: DosFlags = DosFlags(1 << 0); + pub(crate) const HIDDEN: DosFlags = DosFlags(1 << 0); /// `flagSystem`: the DOS attribute `ATTR_SYSTEM`. - pub const SYSTEM: DosFlags = DosFlags(1 << 1); + pub(crate) const SYSTEM: DosFlags = DosFlags(1 << 1); /// `flagArchive`: the DOS attribute `ATTR_ARCHIVE`. - pub const ARCHIVE: DosFlags = DosFlags(1 << 2); + pub(crate) const ARCHIVE: DosFlags = DosFlags(1 << 2); - /// No DOS attribute. - pub const NONE: DosFlags = DosFlags(0); /// Every DOS attribute. - pub const ALL: DosFlags = DosFlags(DosFlags::HIDDEN.0 | DosFlags::SYSTEM.0 | DosFlags::ARCHIVE.0); + pub(crate) const ALL: DosFlags = DosFlags(DosFlags::HIDDEN.0 | DosFlags::SYSTEM.0 | DosFlags::ARCHIVE.0); } impl FlagSet for DosFlags { @@ -550,24 +625,22 @@ flag_set!(DosFlags); /// Only regular files and directories have them, the root directory among /// them. #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] -pub struct InodeFlags(u8); +pub(crate) struct InodeFlags(u8); impl InodeFlags { /// `flagAppendOnly`: the inode flag `FS_APPEND_FL`. - pub const APPEND_ONLY: InodeFlags = InodeFlags(1 << 0); + pub(crate) const APPEND_ONLY: InodeFlags = InodeFlags(1 << 0); /// `flagImmutable`: the inode flag `FS_IMMUTABLE_FL`. - pub const IMMUTABLE: InodeFlags = InodeFlags(1 << 1); + pub(crate) const IMMUTABLE: InodeFlags = InodeFlags(1 << 1); /// `flagNoAtime`: the inode flag `FS_NOATIME_FL`. - pub const NO_ATIME: InodeFlags = InodeFlags(1 << 2); + pub(crate) const NO_ATIME: InodeFlags = InodeFlags(1 << 2); /// `flagNoCow`: the inode flag `FS_NOCOW_FL`. - pub const NO_COW: InodeFlags = InodeFlags(1 << 3); + pub(crate) const NO_COW: InodeFlags = InodeFlags(1 << 3); /// `flagNoDump`: the inode flag `FS_NODUMP_FL`. - pub const NO_DUMP: InodeFlags = InodeFlags(1 << 4); + pub(crate) const NO_DUMP: InodeFlags = InodeFlags(1 << 4); - /// No inode flag. - pub const NONE: InodeFlags = InodeFlags(0); /// Every inode flag. - pub const ALL: InodeFlags = InodeFlags( + pub(crate) const ALL: InodeFlags = InodeFlags( InodeFlags::APPEND_ONLY.0 | InodeFlags::IMMUTABLE.0 | InodeFlags::NO_ATIME.0 @@ -594,34 +667,26 @@ flag_set!(InodeFlags); /// What an object says about the flags of one kind, [`DosFlags`] or /// [`InodeFlags`]: which of them it states, and which of those are set. -/// Nothing is known about the others. -/// -/// ``` -/// use uapi16::{DosFlags, FlagStates}; -/// -/// let mut states = FlagStates::default(); -/// states.put(DosFlags::HIDDEN, Some(true)); -/// states.put(DosFlags::ARCHIVE, Some(false)); -/// assert_eq!(states.get(DosFlags::HIDDEN), Some(true)); -/// assert_eq!(states.get(DosFlags::ARCHIVE), Some(false)); -/// assert_eq!(states.get(DosFlags::SYSTEM), None); -/// ``` +/// Nothing is known about the others. The objects give one getter and one +/// setter for each flag, which go through [`FlagStates::get`] and +/// [`FlagStates::put`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub struct FlagStates { +pub(crate) struct FlagStates { /// The flags the object states. - pub stated: F, - /// Of those, the flags that are set. - pub set: F, + pub(crate) stated: F, + /// Of those, the flags that are set. [`FlagStates::put`] keeps them + /// among those it states. + pub(crate) set: F, } impl FlagStates { /// Whether `flag` is set, cleared, or not known. - pub fn get(self, flag: F) -> Option { + pub(crate) fn get(self, flag: F) -> Option { ((self.stated & flag) == flag).then_some((self.set & flag) == flag) } /// States `flag` as set or cleared, or as not known. - pub fn put(&mut self, flag: F, state: Option) { + pub(crate) fn put(&mut self, flag: F, state: Option) { self.stated = self.stated & !flag; self.set = self.set & !flag; if let Some(set) = state { @@ -672,7 +737,15 @@ impl FlagStates { /// /// The `size` and the `sha256` of a [`FileObject`], the sizes and hashes /// of a [`ContentsObject`] and the `readOnly` of [`InodeAttributes`] can be -/// filled in. Each of them notes it in its own `filled_in`. +/// filled in. [`FileObject::filled_in()`], [`ContentsObject::filled_in()`] +/// and [`InodeAttributes::filled_in()`] say which were. +/// +/// A value that is set is not one a reader filled in. A value that the +/// sizes and hashes of the same object follow from also drops those that +/// a reader filled in when it is set: they are None then. These are the +/// size, the hash and the contents objects of a file object, and the sizes, +/// the hashes, the encoding and the source of a contents object. The next +/// reader of the manifest fills them in again. #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct FilledIn(u8); @@ -702,13 +775,13 @@ impl FilledIn { } /// Notes that `field` was filled in, if it is one that can be. - pub fn insert(&mut self, field: Field) { + pub(crate) fn insert(&mut self, field: Field) { self.0 |= FilledIn::bit(field); } /// Notes that `field` was not filled in, for a value that was set /// since. - pub fn remove(&mut self, field: Field) { + pub(crate) fn remove(&mut self, field: Field) { self.0 &= !FilledIn::bit(field); } @@ -829,16 +902,43 @@ impl FromStr for FatSerial { #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct FileSystemIdentity { + pub(crate) uuid: Option, + pub(crate) label: Option, + pub(crate) fat_serial: Option, +} + +impl FileSystemIdentity { /// `fsUUID`: the UUID of the file system. - pub uuid: Option, + pub fn uuid(&self) -> Option { + self.uuid + } + + /// Sets `fsUUID`. + pub fn set_uuid(&mut self, uuid: Option) { + self.uuid = uuid; + } + /// `fsLabel`: the label of the file system, see /// [`FileSystemIdentity::is_valid_label`]. - pub label: Option, + pub fn label(&self) -> Option<&str> { + self.label.as_deref() + } + + /// Sets `fsLabel`. + pub fn set_label(&mut self, label: Option) { + self.label = label; + } + /// `fatSerial`: the volume serial number of a FAT or exFAT file system. - pub fat_serial: Option, -} + pub fn fat_serial(&self) -> Option { + self.fat_serial + } + + /// Sets `fatSerial`. + pub fn set_fat_serial(&mut self, fat_serial: Option) { + self.fat_serial = fat_serial; + } -impl FileSystemIdentity { /// Whether `label` can be the label of a file system in a manifest, /// in `fsLabel`: a string a manifest can have, without control /// characters. A file system can take less than that. @@ -868,9 +968,9 @@ impl FileSystemIdentity { /// use uapi16::{FatSerial, FileSystemIdentity}; /// /// let mut identity = FileSystemIdentity::default(); - /// identity.uuid = "1234abcd-5678-4ef0-9abc-def012345678".parse().ok(); + /// identity.set_uuid("1234abcd-5678-4ef0-9abc-def012345678".parse().ok()); /// assert_eq!(identity.volume_serial(), Some(FatSerial::new(0x1234_abcd))); - /// identity.fat_serial = Some(FatSerial::new(0x5678_9abc)); + /// identity.set_fat_serial(Some(FatSerial::new(0x5678_9abc))); /// assert_eq!(identity.volume_serial(), Some(FatSerial::new(0x5678_9abc))); /// ``` pub fn volume_serial(&self) -> Option { @@ -905,27 +1005,16 @@ pub enum ContentsSource { #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct ContentsObject { - /// `file`, `url` or `literal`: where the data is. - pub source: ContentsSource, - /// `httpHeaders`: the header fields of the HTTP requests for the data - /// at `url`, by name, in the order the manifest lists them. - pub http_headers: Vec<(String, String)>, - /// `encoding`: the HTTP content coding the data is stored in, in - /// lower case. None is no encoding. - pub encoding: Option, - /// `encodedSize`: the size of the data as it is stored. - pub encoded_size: Option, - /// `encodedSha256`: the hash of the data as it is stored. - pub encoded_sha256: Option, - /// `originalSize`: the size of the decoded data. - pub original_size: Option, - /// `originalSha256`: the hash of the decoded data. - pub original_sha256: Option, - /// `offset`: where the file object's data starts in the decoded data. - pub offset: u64, - /// The sizes and hashes that follow from the other fields, if a reader - /// filled them in. Whoever sets another value takes the field out. - pub filled_in: FilledIn, + pub(crate) source: ContentsSource, + pub(crate) http_headers: Vec<(String, String)>, + pub(crate) encoding: Option, + pub(crate) encoded_size: Option, + pub(crate) encoded_sha256: Option, + pub(crate) original_size: Option, + pub(crate) original_sha256: Option, + pub(crate) offset: u64, + /// The sizes and hashes a reader filled in. + pub(crate) filled_in: FilledIn, } impl ContentsObject { @@ -962,6 +1051,119 @@ impl ContentsObject { _ => None, } } + + /// `file`, `url` or `literal`: where the data is. + pub fn source(&self) -> &ContentsSource { + &self.source + } + + /// Sets `file`, `url` or `literal`, and drops what a reader filled in. + pub fn set_source(&mut self, source: ContentsSource) { + self.drop_filled_in(); + self.source = source; + } + + /// `httpHeaders`: the header fields of the HTTP requests for the data + /// at `url`, by name, in the order the manifest lists them. + pub fn http_headers(&self) -> impl ExactSizeIterator { + self.http_headers + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())) + } + + /// Sets `httpHeaders`. + pub fn set_http_headers(&mut self, headers: Vec<(String, String)>) { + self.http_headers = headers; + } + + /// `encoding`: the HTTP content coding the data is stored in, in + /// lower case. None is no encoding. + pub fn encoding(&self) -> Option<&str> { + self.encoding.as_deref() + } + + /// Sets `encoding`, and drops what a reader filled in. + pub fn set_encoding(&mut self, encoding: Option) { + self.drop_filled_in(); + self.encoding = encoding; + } + + /// `encodedSize`: the size of the data as it is stored. + pub fn encoded_size(&self) -> Option { + self.encoded_size + } + + /// Sets `encodedSize`, and drops what a reader filled in. + pub fn set_encoded_size(&mut self, size: Option) { + self.drop_filled_in(); + self.encoded_size = size; + } + + /// `encodedSha256`: the hash of the data as it is stored. + pub fn encoded_sha256(&self) -> Option { + self.encoded_sha256 + } + + /// Sets `encodedSha256`, and drops what a reader filled in. + pub fn set_encoded_sha256(&mut self, sha256: Option) { + self.drop_filled_in(); + self.encoded_sha256 = sha256; + } + + /// `originalSize`: the size of the decoded data. + pub fn original_size(&self) -> Option { + self.original_size + } + + /// Sets `originalSize`, and drops what a reader filled in. + pub fn set_original_size(&mut self, size: Option) { + self.drop_filled_in(); + self.original_size = size; + } + + /// `originalSha256`: the hash of the decoded data. + pub fn original_sha256(&self) -> Option { + self.original_sha256 + } + + /// Sets `originalSha256`, and drops what a reader filled in. + pub fn set_original_sha256(&mut self, sha256: Option) { + self.drop_filled_in(); + self.original_sha256 = sha256; + } + + /// `offset`: where the file object's data starts in the decoded data. + pub fn offset(&self) -> u64 { + self.offset + } + + /// Sets `offset`. + pub fn set_offset(&mut self, offset: u64) { + self.offset = offset; + } + + /// The sizes and hashes a reader filled in, see [`FilledIn`]. + pub fn filled_in(&self) -> FilledIn { + self.filled_in + } + + /// Drops the sizes and hashes a reader filled in, which follow from the + /// other fields: they are None, and none is noted as filled in. + fn drop_filled_in(&mut self) { + let filled_in = std::mem::take(&mut self.filled_in); + if filled_in.contains(Field::EncodedSize) { + self.encoded_size = None; + } + if filled_in.contains(Field::EncodedSha256) { + self.encoded_sha256 = None; + } + if filled_in.contains(Field::OriginalSize) { + self.original_size = None; + } + if filled_in.contains(Field::OriginalSha256) { + self.original_sha256 = None; + } + } } /// The inode attributes of a file: its access mode, its owner, its @@ -974,37 +1176,31 @@ impl ContentsObject { /// where a directory is described twice: by the file object of the /// manifest it is in and by the root file object of a sub-manifest of its /// own. +/// +/// The Linux inode flags the specification has, some of those +/// `chattr(1)` changes, have a field each, such as `flagImmutable`. Only +/// regular files and directories have them, the root directory among +/// them. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct InodeAttributes { - /// `mode`: the access mode. - pub mode: Option, - /// `uid`: the owning user. - pub uid: Option, - /// `gid`: the owning group. - pub gid: Option, - /// `userName`: the name of the owning user. - pub user_name: Option>, - /// `groupName`: the name of the owning group. - pub group_name: Option>, - /// `mTimeNSec`: the modification time in nanoseconds since the epoch, - /// see [`InodeAttributes::mtime`]. - pub mtime_nsec: Option, - /// `extendedAttributes`: the extended attributes of the `user` - /// namespace, by their names without the `user.` in front. None says - /// nothing about them. A map lists them all, so an empty one says the - /// file has none. - pub user_xattrs: Option>>>, - /// `readOnly`: whether the file is read-only, see - /// [`InodeAttributes::is_read_only`]. It stands for the read-only - /// attribute of DOS and for [`GptPartition::FLAG_READ_ONLY`] too. - pub read_only: Option, + pub(crate) mode: Option, + pub(crate) uid: Option, + pub(crate) gid: Option, + pub(crate) user_name: Option>, + pub(crate) group_name: Option>, + pub(crate) mtime_nsec: Option, + /// The extended attributes by their names. A map lists them all, so an + /// empty one says the file has none. Few files have any, and the box + /// keeps the attributes of the others small. + #[allow(clippy::box_collection)] + pub(crate) user_xattrs: Option>>>, + pub(crate) read_only: Option, /// `flagAppendOnly` and the other fields of the inode flags: the /// flags the object states. - pub flags: FlagStates, - /// `readOnly`, if a reader filled it in. Whoever sets another value - /// takes the field out. - pub filled_in: FilledIn, + pub(crate) flags: FlagStates, + /// `readOnly`, if a reader filled it in. + pub(crate) filled_in: FilledIn, } impl InodeAttributes { @@ -1069,6 +1265,107 @@ impl InodeAttributes { } } + /// `mode`: the access mode. + pub fn mode(&self) -> Option { + self.mode + } + + /// Sets `mode`. + pub fn set_mode(&mut self, mode: Option) { + self.mode = mode; + } + + /// `uid`: the owning user. + pub fn uid(&self) -> Option { + self.uid + } + + /// Sets `uid`. + pub fn set_uid(&mut self, uid: Option) { + self.uid = uid; + } + + /// `gid`: the owning group. + pub fn gid(&self) -> Option { + self.gid + } + + /// Sets `gid`. + pub fn set_gid(&mut self, gid: Option) { + self.gid = gid; + } + + /// `userName`: the name of the owning user. + pub fn user_name(&self) -> Option<&str> { + self.user_name.as_deref() + } + + /// Sets `userName`. + pub fn set_user_name(&mut self, name: Option) { + self.user_name = name.map(String::into_boxed_str); + } + + /// `groupName`: the name of the owning group. + pub fn group_name(&self) -> Option<&str> { + self.group_name.as_deref() + } + + /// Sets `groupName`. + pub fn set_group_name(&mut self, name: Option) { + self.group_name = name.map(String::into_boxed_str); + } + + /// `mTimeNSec`: the modification time in nanoseconds since the epoch, + /// see [`InodeAttributes::mtime`]. + pub fn mtime_nsec(&self) -> Option { + self.mtime_nsec + } + + /// Sets `mTimeNSec`. Unlike [`InodeAttributes::set_mtime`] it can take + /// the time away. + pub fn set_mtime_nsec(&mut self, nsec: Option) { + self.mtime_nsec = nsec; + } + + /// `extendedAttributes`: the extended attributes of the `user` + /// namespace, by their names without the `user.` in front, in the order + /// of their names. None says nothing about them. Some lists them all, + /// so where it lists none the file has none. + pub fn user_xattrs(&self) -> Option> { + let xattrs = self.user_xattrs.as_deref()?; + Some(xattrs.iter().map(|(name, value)| (name.as_str(), value.as_slice()))) + } + + /// The value of the extended attribute of the `user` namespace whose + /// name without the `user.` in front is `name`, if the attributes list + /// it. + pub fn user_xattr(&self, name: &str) -> Option<&[u8]> { + self.user_xattrs.as_deref()?.get(name).map(Vec::as_slice) + } + + /// Sets `extendedAttributes`, see [`InodeAttributes::user_xattrs`]. + pub fn set_user_xattrs(&mut self, xattrs: Option>>) { + self.user_xattrs = xattrs.map(Box::new); + } + + /// `readOnly`: whether the file is read-only, see + /// [`InodeAttributes::is_read_only`]. It stands for the read-only + /// attribute of DOS and for [`GptPartition::FLAG_READ_ONLY`] too. + pub fn read_only(&self) -> Option { + self.read_only + } + + /// Sets `readOnly`. + pub fn set_read_only(&mut self, read_only: Option) { + self.filled_in.remove(Field::ReadOnly); + self.read_only = read_only; + } + + /// `readOnly`, if a reader filled it in, see [`FilledIn`]. + pub fn filled_in(&self) -> FilledIn { + self.filled_in + } + /// The modification time, if the attributes have one. pub fn mtime(&self) -> Option { self.mtime_nsec.map(|nsec| UNIX_EPOCH + Duration::from_nanos(nsec)) @@ -1168,48 +1465,39 @@ impl InodeAttributes { /// /// Every field but the name and the type is optional. What the file is as /// an inode, its access mode, owner, time and the like, is in -/// [`FileObject::inode`], as it is for the root directory in the +/// [`FileObject::inode()`], as it is for the root directory in the /// [`RootObject`]. A reader fills in what follows from the other fields: /// the size 0 for the hash of no data and that hash for the size 0, and /// the size and the hash of a file whose contents object gives them. It -/// notes them in `filled_in`, and a writer leaves them out. +/// notes them, see [`FileObject::filled_in()`], and a writer leaves them +/// out. +/// +/// The DOS attributes hidden, system and archive have a field each: +/// `flagHidden`, `flagSystem` and `flagArchive`. They are the attributes +/// of FAT, of exFAT and of file systems like them. The read-only attribute +/// has no field of its own. `readOnly` stands for it, see +/// [`InodeAttributes::read_only()`]. Only regular files and directories +/// have DOS attributes, and the root directory has none: the root +/// directory of FAT has no directory entry to keep them in. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct FileObject { - /// `name`: the path of the file below the root. - pub name: Name, - /// `type`: the inode type. An object that does not say is a regular - /// file. - pub inode_type: InodeType, - /// `size`: the size of the data in bytes. For a symbolic link that - /// is the length of its target, for a directory the size of the - /// manifest of its own that `contents` refers to. - pub size: Option, - /// `sha256`: the hash of the data. - pub sha256: Option, - /// `contents`: where the contents can be taken from. Without any they - /// are in the file of the object's name next to the manifest. - pub contents: Vec, - /// `inodeToken`: the objects that carry the same token are hard links - /// to one file. None is a file of its own. - pub inode_token: Option, - /// `major`: the major number of a device node. - pub major: Option, - /// `minor`: the minor number of a device node. - pub minor: Option, - /// The `gpt` fields, if the object describes a partition. - pub gpt: Option>, + pub(crate) name: Name, + pub(crate) inode_type: InodeType, + pub(crate) size: Option, + pub(crate) sha256: Option, + pub(crate) contents: Vec, + pub(crate) inode_token: Option, + pub(crate) major: Option, + pub(crate) minor: Option, + pub(crate) gpt: Option>, /// `flagHidden`, `flagSystem` and `flagArchive`: the DOS attributes the /// object states. - pub dos_flags: FlagStates, - /// The inode attributes of the file. - pub inode: InodeAttributes, - /// `validSinceUSec`, `validUntilUSec` and `validity`: when the file may - /// be used. - pub validity: ValidityWindow, - /// The size and the hash, if a reader filled them in. Whoever sets - /// another value takes the field out. - pub filled_in: FilledIn, + pub(crate) dos_flags: FlagStates, + pub(crate) inode: InodeAttributes, + pub(crate) validity: ValidityWindow, + /// The size and the hash, if a reader filled them in. + pub(crate) filled_in: FilledIn, } impl FileObject { @@ -1252,6 +1540,154 @@ impl FileObject { } } + /// `name`: the path of the file below the root. + pub fn name(&self) -> &Name { + &self.name + } + + /// Sets `name`. + pub fn set_name(&mut self, name: Name) { + self.name = name; + } + + /// The name, the object taken apart for it. + pub fn into_name(self) -> Name { + self.name + } + + /// `type`: the inode type. An object that does not say is a regular + /// file. + pub fn inode_type(&self) -> InodeType { + self.inode_type + } + + /// Sets `type`. + pub fn set_inode_type(&mut self, inode_type: InodeType) { + self.inode_type = inode_type; + } + + /// `size`: the size of the data in bytes. For a symbolic link that is + /// the length of its target, for a directory the size of the manifest + /// of its own that `contents` refers to. + pub fn size(&self) -> Option { + self.size + } + + /// Sets `size`, and drops what a reader filled in, see [`FilledIn`]. + pub fn set_size(&mut self, size: Option) { + self.drop_filled_in(); + self.size = size; + } + + /// `sha256`: the hash of the data. + pub fn sha256(&self) -> Option { + self.sha256 + } + + /// Sets `sha256`, and drops what a reader filled in, see [`FilledIn`]. + pub fn set_sha256(&mut self, sha256: Option) { + self.drop_filled_in(); + self.sha256 = sha256; + } + + /// `contents`: where the data can be taken from. A regular file without + /// contents objects has its data in the file of its own name next to + /// the manifest, see [`FileObject::data_location`]. + pub fn contents(&self) -> &[ContentsObject] { + &self.contents + } + + /// Sets `contents`, and drops what a reader filled in, see + /// [`FilledIn`]. A writer refuses more than [`MAX_CONTENTS`] of them. + /// + /// [`MAX_CONTENTS`]: crate::MAX_CONTENTS + pub fn set_contents(&mut self, contents: Vec) { + self.drop_filled_in(); + self.contents = contents; + } + + /// `inodeToken`: the objects that carry the same token are hard links + /// to one file. None is a file of its own. + pub fn inode_token(&self) -> Option { + self.inode_token + } + + /// Sets `inodeToken`. + pub fn set_inode_token(&mut self, token: Option) { + self.inode_token = token; + } + + /// `major`: the major number of a device node. + pub fn major(&self) -> Option { + self.major + } + + /// Sets `major`. + pub fn set_major(&mut self, major: Option) { + self.major = major; + } + + /// `minor`: the minor number of a device node. + pub fn minor(&self) -> Option { + self.minor + } + + /// Sets `minor`. + pub fn set_minor(&mut self, minor: Option) { + self.minor = minor; + } + + /// The `gpt` fields, if the object describes a partition. + pub fn gpt(&self) -> Option<&GptPartition> { + self.gpt.as_deref() + } + + /// Sets the `gpt` fields. + pub fn set_gpt(&mut self, gpt: Option) { + self.gpt = gpt.map(Box::new); + } + + /// The inode attributes of the file. + pub fn inode(&self) -> &InodeAttributes { + &self.inode + } + + /// The inode attributes of the file, to change them. + pub fn inode_mut(&mut self) -> &mut InodeAttributes { + &mut self.inode + } + + /// `validSinceUSec`, `validUntilUSec` and `validity`: when the file may + /// be used. + pub fn validity(&self) -> ValidityWindow { + self.validity + } + + /// Sets `validSinceUSec`, `validUntilUSec` and `validity`. + pub fn set_validity(&mut self, validity: ValidityWindow) { + self.validity = validity; + } + + /// What a reader filled in of the object: its size and its hash, and + /// the `readOnly` of its inode attributes, see [`FilledIn`]. A writer + /// leaves these out. + pub fn filled_in(&self) -> FilledIn { + self.filled_in.union(self.inode.filled_in) + } + + /// Drops the size and the hash a reader filled in, which follow from + /// each other and from the contents objects: they are None, and + /// neither is noted as filled in. + fn drop_filled_in(&mut self) { + let filled_in = std::mem::take(&mut self.filled_in); + if filled_in.contains(Field::Size) { + self.size = None; + } + if filled_in.contains(Field::Sha256) { + self.sha256 = None; + } + } + /// Whether the object has `field`, one of [`FileObject::FEATURE_FIELDS`], /// other than one a reader filled in. `contents` belongs to a feature on /// a symbolic link only. @@ -1373,22 +1809,12 @@ impl FileObject { #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct RootObject { - /// The inode attributes of the root directory. - pub inode: InodeAttributes, - /// `fsUUID`, `fsLabel` and `fatSerial`: the identity of the file - /// system the file objects are placed in. - pub file_system: FileSystemIdentity, - /// `gptDiskUuid`: the disk UUID of the GPT partition table the file - /// objects are placed in as partitions. - pub gpt_disk_uuid: Option, - /// `order`: the order the manifest lists its file objects in. - pub order: Option, - /// `features`: what the manifest records. None is - /// [`Features::DEFAULT`]. - pub features: Option, - /// `validSinceUSec`, `validUntilUSec` and `validity`: when the - /// manifest may be used. - pub validity: ValidityWindow, + pub(crate) inode: InodeAttributes, + pub(crate) file_system: FileSystemIdentity, + pub(crate) gpt_disk_uuid: Option, + pub(crate) order: Option, + pub(crate) features: Option, + pub(crate) validity: ValidityWindow, } impl RootObject { @@ -1402,6 +1828,70 @@ impl RootObject { (Field::GptDiskUuid, Features::GPT_DISK_UUID), ]; + /// The inode attributes of the root directory. + pub fn inode(&self) -> &InodeAttributes { + &self.inode + } + + /// The inode attributes of the root directory, to change them. + pub fn inode_mut(&mut self) -> &mut InodeAttributes { + &mut self.inode + } + + /// `fsUUID`, `fsLabel` and `fatSerial`: the identity of the file + /// system the file objects are placed in. + pub fn file_system(&self) -> &FileSystemIdentity { + &self.file_system + } + + /// The identity of the file system, to change it. + pub fn file_system_mut(&mut self) -> &mut FileSystemIdentity { + &mut self.file_system + } + + /// `gptDiskUuid`: the disk UUID of the GPT partition table the file + /// objects are placed in as partitions. + pub fn gpt_disk_uuid(&self) -> Option { + self.gpt_disk_uuid + } + + /// Sets `gptDiskUuid`. + pub fn set_gpt_disk_uuid(&mut self, uuid: Option) { + self.gpt_disk_uuid = uuid; + } + + /// `order`: the order the manifest lists its file objects in. + pub fn order(&self) -> Option { + self.order + } + + /// Sets `order`. + pub fn set_order(&mut self, order: Option) { + self.order = order; + } + + /// `features`: what the manifest records. None is + /// [`Features::DEFAULT`]. + pub fn features(&self) -> Option { + self.features + } + + /// Sets `features`. + pub fn set_features(&mut self, features: Option) { + self.features = features; + } + + /// `validSinceUSec`, `validUntilUSec` and `validity`: when the + /// manifest may be used. + pub fn validity(&self) -> ValidityWindow { + self.validity + } + + /// Sets `validSinceUSec`, `validUntilUSec` and `validity`. + pub fn set_validity(&mut self, validity: ValidityWindow) { + self.validity = validity; + } + /// Whether the object has `field`, one of /// [`RootObject::FEATURE_FIELDS`]. fn has_feature_field(&self, field: Field) -> bool { @@ -1483,13 +1973,9 @@ impl RootObject { #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct SignatureObject { - /// `mechanism`: how the signature was made. The specification has - /// `openpgp` and `pkcs7`. - pub mechanism: String, - /// `key`: what identifies the key, such as its fingerprint. - pub key: Option>, - /// `data`: the signature. - pub data: Option>, + pub(crate) mechanism: String, + pub(crate) key: Option>, + pub(crate) data: Option>, } impl SignatureObject { @@ -1502,6 +1988,37 @@ impl SignatureObject { data: None, } } + + /// `mechanism`: how the signature was made. The specification has + /// `openpgp` and `pkcs7`. + pub fn mechanism(&self) -> &str { + &self.mechanism + } + + /// Sets `mechanism`. + pub fn set_mechanism(&mut self, mechanism: impl Into) { + self.mechanism = mechanism.into(); + } + + /// `key`: what identifies the key, such as its fingerprint. + pub fn key(&self) -> Option<&[u8]> { + self.key.as_deref() + } + + /// Sets `key`. + pub fn set_key(&mut self, key: Option>) { + self.key = key; + } + + /// `data`: the signature. + pub fn data(&self) -> Option<&[u8]> { + self.data.as_deref() + } + + /// Sets `data`. + pub fn set_data(&mut self, data: Option>) { + self.data = data; + } } #[cfg(test)] @@ -1709,20 +2226,23 @@ mod tests { assert!(inode.windows(2).all(|pair| pair[0] < pair[1]), "{:?}", inode); let every_dos = DosFlags::FIELDS .iter() - .fold(DosFlags::NONE, |every, (flag, _, _)| every | *flag); + .fold(DosFlags::default(), |every, (flag, _, _)| every | *flag); let every_inode = InodeFlags::FIELDS .iter() - .fold(InodeFlags::NONE, |every, (flag, _, _)| every | *flag); + .fold(InodeFlags::default(), |every, (flag, _, _)| every | *flag); assert_eq!((every_dos, every_inode), (DosFlags::ALL, InodeFlags::ALL)); // A field is the field of one kind of flags. assert!(dos.iter().all(|field| !inode.contains(field))); for &(flag, _, _) in DosFlags::FIELDS { - assert_eq!((!flag & flag, !flag | flag), (DosFlags::NONE, DosFlags::ALL)); + assert_eq!((!flag & flag, !flag | flag), (DosFlags::default(), DosFlags::ALL)); } for &(flag, _, _) in InodeFlags::FIELDS { - assert_eq!((!flag & flag, !flag | flag), (InodeFlags::NONE, InodeFlags::ALL)); + assert_eq!((!flag & flag, !flag | flag), (InodeFlags::default(), InodeFlags::ALL)); } - assert_eq!((!DosFlags::NONE, !InodeFlags::ALL), (DosFlags::ALL, InodeFlags::NONE)); + assert_eq!( + (!DosFlags::default(), !InodeFlags::ALL), + (DosFlags::ALL, InodeFlags::default()) + ); let flags = DosFlags::HIDDEN | DosFlags::ARCHIVE; assert!(flags.contains(DosFlags::ARCHIVE) && !flags.contains(DosFlags::ALL)); assert_eq!(flags.without(DosFlags::ARCHIVE), DosFlags::HIDDEN); @@ -1731,7 +2251,7 @@ mod tests { format!("{:?}", InodeFlags::NO_COW | InodeFlags::APPEND_ONLY), "InodeFlags(flagAppendOnly | flagNoCow)" ); - assert_eq!(format!("{:?}", InodeFlags::NONE), "InodeFlags()"); + assert_eq!(format!("{:?}", InodeFlags::default()), "InodeFlags()"); // What an object says about the flags of one kind. let mut states = FlagStates::default(); assert_eq!(states.get(InodeFlags::IMMUTABLE), None); @@ -1801,7 +2321,7 @@ mod tests { let mut attributes = InodeAttributes::default(); set(&mut attributes, state); assert_eq!(get(&attributes), state, "{:?}", flag); - let stated = if state.is_some() { flag } else { InodeFlags::NONE }; + let stated = if state.is_some() { flag } else { InodeFlags::default() }; assert_eq!(attributes.flags.stated, stated, "{:?}", flag); assert_eq!(attributes.flags.get(flag), state, "{:?}", flag); } @@ -1809,7 +2329,7 @@ mod tests { let mut object = FileObject::new(Name::new("f").unwrap()); set(&mut object, state); assert_eq!(get(&object), state, "{:?}", flag); - let stated = if state.is_some() { flag } else { DosFlags::NONE }; + let stated = if state.is_some() { flag } else { DosFlags::default() }; assert_eq!(object.dos_flags.stated, stated, "{:?}", flag); assert_eq!(object.dos_flags.get(flag), state, "{:?}", flag); } @@ -1959,4 +2479,101 @@ mod tests { let url = ContentsObject::new(ContentsSource::Url("https://example.com/x".to_string())); assert_eq!(url.url(), Some("https://example.com/x")); } + + /// The extended attributes and the HTTP header fields come out as they + /// went in, the attributes in the order of their names. + #[test] + fn lists() { + let mut inode = InodeAttributes::default(); + assert!(inode.user_xattrs().is_none()); + assert_eq!(inode.user_xattr("a"), None); + inode.set_user_xattrs(Some(BTreeMap::from([ + ("b".to_string(), b"2".to_vec()), + ("a".to_string(), Vec::new()), + ]))); + let listed: Vec<(&str, &[u8])> = inode.user_xattrs().unwrap().collect(); + assert_eq!(listed, [("a", &b""[..]), ("b", &b"2"[..])]); + assert_eq!(inode.user_xattrs().map(|xattrs| xattrs.len()), Some(2)); + assert_eq!((inode.user_xattr("b"), inode.user_xattr("c")), (Some(&b"2"[..]), None)); + // None of them, which says that the file has none. + inode.set_user_xattrs(Some(BTreeMap::new())); + assert_eq!(inode.user_xattrs().map(|xattrs| xattrs.len()), Some(0)); + let mut contents = ContentsObject::new(ContentsSource::Url("https://example.com/x".to_string())); + contents.set_http_headers(vec![("X-B".into(), "2".into()), ("X-A".into(), "1".into())]); + let headers: Vec<(&str, &str)> = contents.http_headers().collect(); + assert_eq!(headers, [("X-B", "2"), ("X-A", "1")]); + } + + /// A value that is set drops the sizes and hashes a reader filled in on + /// the same object, and leaves the ones the record gives. + #[test] + fn setters_drop_what_a_reader_filled_in() { + use crate::testing::{manifest, read_whole, record, sequence, EMPTY, HELLO, TRAILER}; + + let read = |record: &str| read_whole(&manifest(&[record])).unwrap().objects.pop().unwrap(); + let hello: Option = HELLO.parse().ok(); + let none = FilledIn::default(); + // The size 0 a reader fills in for the hash of no data, and the + // hash of no data for the size 0. + let mut object = read(&format!(r#"{{"name":"a","sha256":"{}"}}"#, EMPTY)); + assert_eq!( + (object.size(), object.filled_in().contains(Field::Size)), + (Some(0), true) + ); + object.set_sha256(hello); + assert_eq!( + (object.size(), object.sha256(), object.filled_in()), + (None, hello, none) + ); + assert_eq!(record(&object), format!(r#"{{"name":"a","sha256":"{}"}}"#, HELLO)); + let mut object = read(r#"{"name":"a","size":0}"#); + assert!(object.filled_in().contains(Field::Sha256)); + object.set_size(Some(5)); + assert_eq!( + (object.size(), object.sha256(), object.filled_in()), + (Some(5), None, none) + ); + // The size a contents object gives. + let mut object = read(r#"{"name":"a","contents":[{"file":"blob","originalSize":3}]}"#); + assert_eq!(object.size(), Some(3)); + let mut contents = object.contents()[0].clone(); + contents.set_original_size(Some(7)); + object.set_contents(vec![contents]); + assert_eq!((object.size(), object.filled_in()), (None, none)); + // What the record gives stays. + let mut object = read(&format!(r#"{{"name":"a","size":5,"sha256":"{}"}}"#, HELLO)); + object.set_size(Some(5)); + assert_eq!((object.size(), object.sha256()), (Some(5), hello)); + // Without an encoding the encoded size is the original size, and a + // literal gives both. + let object = read(r#"{"name":"a","contents":[{"file":"blob","originalSize":3}]}"#); + let mut contents = object.contents()[0].clone(); + assert_eq!(contents.encoded_size(), Some(3)); + assert!(contents.filled_in().contains(Field::EncodedSize)); + contents.set_original_size(Some(7)); + assert_eq!( + (contents.encoded_size(), contents.original_size(), contents.filled_in()), + (None, Some(7), none) + ); + let mut contents = object.contents()[0].clone(); + contents.set_encoding(Some("gzip".to_string())); + assert_eq!((contents.encoded_size(), contents.original_size()), (None, Some(3))); + let object = read(r#"{"name":"a","contents":[{"literal":"aGVsbG8="}]}"#); + let mut contents = object.contents()[0].clone(); + assert_eq!((contents.encoded_size(), contents.original_size()), (Some(5), Some(5))); + contents.set_source(ContentsSource::File(Name::new("blob").unwrap())); + assert_eq!( + (contents.encoded_size(), contents.original_size(), contents.filled_in()), + (None, None, none) + ); + // readOnly, which the object notes with its own marks. + let root = r#"{"features":["read-only"],"mediaType":"application/vnd.uapi.16.manifest"}"#; + let whole = read_whole(&sequence(&[root, r#"{"name":"a"}"#, TRAILER])).unwrap(); + let mut object = whole.objects.into_iter().next().unwrap(); + assert_eq!(object.inode().read_only(), Some(false)); + assert!(object.filled_in().contains(Field::ReadOnly)); + object.inode_mut().set_read_only(Some(false)); + assert_eq!(object.inode().read_only(), Some(false)); + assert!(!object.filled_in().contains(Field::ReadOnly)); + } } diff --git a/src/uapi16/reader.rs b/src/uapi16/reader.rs index e5a776c..d2b91a3 100644 --- a/src/uapi16/reader.rs +++ b/src/uapi16/reader.rs @@ -311,7 +311,7 @@ pub enum Step { /// let taken = decoder.feed(&input[..input.len().min(5)]); /// input = &input[taken..]; /// } -/// Step::Object(Object::File(object)) => names.push(object.name), +/// Step::Object(Object::File(object)) => names.push(object.into_name()), /// Step::End => break, /// _ => {} /// } @@ -489,9 +489,10 @@ mod tests { use super::*; use crate::blocking::READ_SIZE; use crate::error::{ErrorKind, Field}; + use crate::object::{DosFlags, FlagStates, InodeFlags}; use crate::testing::{manifest, sequence, ROOT, SIGNATURE, TRAILER}; use crate::testing::{read_whole, Whole, HELLO, PIECES}; - use crate::{DosFlags, Features, FlagStates, InodeFlags, InodeType, Order, Reader, RootObject, Sha256}; + use crate::{Features, InodeType, Order, Reader, RootObject, Sha256}; use std::collections::BTreeMap; /// Reads `bytes` to the end and returns the names of the file objects diff --git a/src/uapi16/sequence.rs b/src/uapi16/sequence.rs index 1d61c94..35cca49 100644 --- a/src/uapi16/sequence.rs +++ b/src/uapi16/sequence.rs @@ -157,8 +157,9 @@ impl SequenceCheck { mod tests { use super::*; use crate::error::ErrorKind; + use crate::object::{DosFlags, InodeFlags}; use crate::testing::full_tree_names; - use crate::{ContentsObject, ContentsSource, DosFlags, FatSerial, InodeFlags, Mode, Name, Uuid}; + use crate::{ContentsObject, ContentsSource, FatSerial, Mode, Name, Uuid}; use std::num::NonZeroU64; /// Gives an object a field. diff --git a/src/uapi16/tests/fixtures.rs b/src/uapi16/tests/fixtures.rs index 77f9a45..ecf9f7a 100644 --- a/src/uapi16/tests/fixtures.rs +++ b/src/uapi16/tests/fixtures.rs @@ -56,7 +56,7 @@ impl Manifest { /// The names of the file objects, in the order of the manifest. fn names(&self) -> Vec<&str> { - self.files.iter().map(|file| file.name.as_str()).collect() + self.files.iter().map(|file| file.name().as_str()).collect() } } @@ -75,11 +75,11 @@ fn every_fixture_parses() { assert_eq!( esp.files .iter() - .filter(|e| e.inode_type == InodeType::Directory) + .filter(|e| e.inode_type() == InodeType::Directory) .count(), 6 ); - assert_eq!(esp.root.inode.mtime_nsec, Some(1_699_999_000_000_000_000)); + assert_eq!(esp.root.inode().mtime_nsec(), Some(1_699_999_000_000_000_000)); assert!(esp.signatures.is_empty()); assert_eq!( esp.names(), @@ -100,11 +100,11 @@ fn every_fixture_parses() { ] ); let uki = &esp.files[4]; - assert_eq!(uki.size, Some(6395)); - assert_eq!(uki.inode.mode.map(u32::from), Some(0o664)); - assert_eq!(uki.inode.mtime_nsec, Some(1_700_000_002_000_000_000)); - assert!(!uki.inode.is_read_only()); - assert!(uki.contents.is_empty()); + assert_eq!(uki.size(), Some(6395)); + assert_eq!(uki.inode().mode().map(u32::from), Some(0o664)); + assert_eq!(uki.inode().mtime_nsec(), Some(1_700_000_002_000_000_000)); + assert!(!uki.inode().is_read_only()); + assert!(uki.contents().is_empty()); // The signature does not change the file objects. let signed = Manifest::load("esp", "signed.Uapi16Manifest"); @@ -115,45 +115,43 @@ fn every_fixture_parses() { // Fewer fields, same tree. let lean = Manifest::load("esp", "size-hash-mtime.Uapi16Manifest"); assert_eq!(lean.names(), esp.names()); - assert!(lean.files.iter().all(|e| e.inode.mode.is_none())); - assert!(lean - .files - .iter() - .zip(&esp.files) - .all(|(a, b)| a.size == b.size && a.sha256 == b.sha256 && a.inode.mtime_nsec == b.inode.mtime_nsec)); + assert!(lean.files.iter().all(|e| e.inode().mode().is_none())); + assert!(lean.files.iter().zip(&esp.files).all(|(a, b)| a.size() == b.size() + && a.sha256() == b.sha256() + && a.inode().mtime_nsec() == b.inode().mtime_nsec())); let none = Manifest::load("esp", "none.Uapi16Manifest"); assert_eq!(none.names(), esp.names()); assert!(none .files .iter() - .all(|e| e.size.is_none() && e.sha256.is_none() && e.inode.mtime_nsec.is_none())); + .all(|e| e.size().is_none() && e.sha256().is_none() && e.inode().mtime_nsec().is_none())); let special = Manifest::load("special", "Uapi16Manifest"); assert_eq!(special.files.len(), 13); - let types: Vec = special.files.iter().map(|e| e.inode_type).collect(); + let types: Vec = special.files.iter().map(|e| e.inode_type()).collect(); assert_eq!(types.iter().filter(|&&t| t == InodeType::Symlink).count(), 1); assert_eq!(types.iter().filter(|&&t| t == InodeType::Fifo).count(), 1); let link = special .files .iter() - .find(|e| e.inode_type == InodeType::Symlink) + .find(|e| e.inode_type() == InodeType::Symlink) .unwrap(); - assert_eq!(link.contents[0].literal(), Some(&b"a.txt"[..])); + assert_eq!(link.contents()[0].literal(), Some(&b"a.txt"[..])); let hardlinks: Vec<&str> = special .files .iter() - .filter(|e| e.inode_token.is_some()) - .map(|e| e.name.as_str()) + .filter(|e| e.inode_token().is_some()) + .map(|e| e.name().as_str()) .collect(); assert_eq!(hardlinks, vec!["sub/hl_a", "sub/hl_b"]); - let readonly = special.files.iter().find(|e| e.name == "sub/readonly.bin").unwrap(); - assert_eq!(readonly.inode.mode.map(u32::from), Some(0o444)); - assert!(readonly.inode.is_read_only()); + let readonly = special.files.iter().find(|e| e.name() == "sub/readonly.bin").unwrap(); + assert_eq!(readonly.inode().mode().map(u32::from), Some(0o444)); + assert!(readonly.inode().is_read_only()); assert!(special.names().contains(&"sub/\u{fc}mlaut \u{221e}.txt")); let empty = Manifest::load("empty", "Uapi16Manifest"); assert!(empty.files.is_empty()); - assert_eq!(empty.root.inode.mtime_nsec, Some(1_700_000_200_000_000_000)); + assert_eq!(empty.root.inode().mtime_nsec(), Some(1_700_000_200_000_000_000)); } /// The reader reads every manifest systemd-manifest wrote, and what the @@ -180,7 +178,7 @@ fn reads_and_writes_back_every_fixture() { "{}", path.display() ); - assert_eq!(read.root.order, Some(Order::CodePoint), "{}", path.display()); + assert_eq!(read.root.order(), Some(Order::CodePoint), "{}", path.display()); let written = read.write().unwrap_or_else(|e| panic!("{}: {}", path.display(), e)); assert_eq!(Manifest::read(&written).unwrap(), read, "{}", path.display()); } diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs index 9c538d0..e437f5c 100644 --- a/src/uapi16/writer.rs +++ b/src/uapi16/writer.rs @@ -530,7 +530,7 @@ impl FileObject { impl Fields for FileObject { fn filled_in(&self) -> FilledIn { - self.filled_in.union(self.inode.filled_in) + FileObject::filled_in(self) } fn write_fields(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { @@ -750,7 +750,7 @@ impl ContentsObject { /// same. A reader fills them in again. impl Fields for ContentsObject { fn filled_in(&self) -> FilledIn { - self.filled_in + ContentsObject::filled_in(self) } fn write_fields(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { From 3d71ff13ea7aa0a7b6d9013f0deaf6d74aa902a2 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 21:36:16 +0100 Subject: [PATCH 17/32] uapi16: mark the flags and extended attributes a reader fills in Where a manifest records the feature of a flag, a file object without the field has the flag cleared, and the reader fills that in: flag_hidden() of such an object is Some(false). Under user-xattr the reader fills in that a file has no extended attributes. Unlike readOnly, neither is marked. So both look like values the object states: - stated_features() counts them, although its docs say that what a reader filled in doesn't count. - The writer refuses the object for a manifest that doesn't record the feature: "'flagHidden' is a field of the feature 'flag-hidden', which the manifest does not record". - Turned into a FIFO, the object is refused because a FIFO has no flags. - The root file object, set to the default features, is refused for its extendedAttributes. So mark them the way readOnly is marked. FilledIn notes the three DOS attributes, the five inode flags and extendedAttributes as well, which takes it from 8 to 16 bits. FlagStates keeps the marks of the flags next to what it states and what is set, and FileObject::filled_in() and InodeAttributes::filled_in() hand them out with the others. The checks of the writer only look at what the record of an object gives, and the writer leaves the marked values out, as it already did with cleared flags and empty extended attributes. A setter takes the mark away, like every setter does. stated_features() then does what its docs say. A flag that a caller clears is stated, and it still needs its feature: without the feature a missing field means that the flag is not known, so the writer would lose the cleared state. The docs of the flag setters say so now. Note that a manifest that states what its features imply, such as the empty extendedAttributes systemd-manifest writes for every object, doesn't come back with the same marks: the writer leaves those out, and a reader of what it wrote fills them in. The fixture test takes them as stated for the comparison, and the test of the writer whose object clears flags expects them back filled in. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/object.rs | 153 +++++++++++++++++++++++++++-------- src/uapi16/tests/fixtures.rs | 23 +++++- src/uapi16/writer.rs | 61 +++++++++++++- 3 files changed, 200 insertions(+), 37 deletions(-) diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 7449b12..d02c6d5 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -666,10 +666,10 @@ impl FlagSet for InodeFlags { flag_set!(InodeFlags); /// What an object says about the flags of one kind, [`DosFlags`] or -/// [`InodeFlags`]: which of them it states, and which of those are set. -/// Nothing is known about the others. The objects give one getter and one -/// setter for each flag, which go through [`FlagStates::get`] and -/// [`FlagStates::put`]. +/// [`InodeFlags`]: which of them it states, which of those are set, and +/// which a reader filled in. Nothing is known about the others. The +/// objects give one getter and one setter for each flag, which go through +/// [`FlagStates::get`] and [`FlagStates::put`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub(crate) struct FlagStates { /// The flags the object states. @@ -677,6 +677,9 @@ pub(crate) struct FlagStates { /// Of those, the flags that are set. [`FlagStates::put`] keeps them /// among those it states. pub(crate) set: F, + /// Of those stated, the flags a reader filled in, see [`FilledIn`]. + /// They are cleared, and the record of the object does not have them. + pub(crate) filled: F, } impl FlagStates { @@ -685,10 +688,12 @@ impl FlagStates { ((self.stated & flag) == flag).then_some((self.set & flag) == flag) } - /// States `flag` as set or cleared, or as not known. + /// States `flag` as set or cleared, or as not known. A flag a reader + /// filled in is one the object states from then on. pub(crate) fn put(&mut self, flag: F, state: Option) { self.stated = self.stated & !flag; self.set = self.set & !flag; + self.filled = self.filled & !flag; if let Some(set) = state { self.stated = self.stated | flag; if set { @@ -697,21 +702,28 @@ impl FlagStates { } } - /// The fields of the flags the object states, each with the feature - /// that records it. + /// The flags the record of the object gives: those it states but a + /// reader did not fill in. + fn given(&self) -> F { + self.stated & !self.filled + } + + /// The fields of the flags the record of the object gives, each with + /// the feature that records it. pub(crate) fn feature_fields(&self) -> impl Iterator + '_ { + let given = self.given(); F::FIELDS .iter() - .filter(move |(flag, _, _)| (self.stated & *flag) == *flag) + .filter(move |(flag, _, _)| (given & *flag) == *flag) .map(|&(_, field, feature)| (field, feature)) } - /// The field of the first flag stated that an object of the type - /// `inode_type` cannot have. The flags stated are held against those + /// The field of the first flag the record gives that an object of the + /// type `inode_type` cannot have. The flags given are held against those /// the type permits all at once, and the fields are only looked through /// to name the first flag that is not permitted. pub(crate) fn unpermitted_field(&self, inode_type: InodeType) -> Option { - let unpermitted = self.stated & !F::permitted(inode_type); + let unpermitted = self.given() & !F::permitted(inode_type); if unpermitted == F::default() { return None; } @@ -723,20 +735,36 @@ impl FlagStates { /// Fills in what `features`, which a manifest records, say about the /// flags an object of the type `inode_type` does not state: a flag the - /// manifest records is cleared. + /// manifest records is cleared, and noted as filled in. pub(crate) fn fill_in(&mut self, features: Features, inode_type: InodeType) { - self.stated = self.stated | (F::recorded_by(features) & F::permitted(inode_type)); + let filled = F::recorded_by(features) & F::permitted(inode_type) & !self.stated; + self.stated = self.stated | filled; + self.filled = self.filled | filled; + } + + /// The fields of the flags a reader filled in. + pub(crate) fn filled_in(&self) -> FilledIn { + F::FIELDS + .iter() + .filter(|&&(flag, _, _)| (self.filled & flag) == flag) + .fold(FilledIn::default(), |mut filled_in, &(_, field, _)| { + filled_in.insert(field); + filled_in + }) } } /// The fields of an object of a manifest that a reader filled in, which /// the record of the object does not have: the sizes and hashes that -/// follow from other fields, and `readOnly`, which is false where the -/// manifest lists `read-only`. A writer leaves them out, and the checks of -/// an object take a filled-in `readOnly` for one that is not there. +/// follow from other fields, `readOnly` and the flags, which are false +/// where the manifest records their features, and `extendedAttributes`, +/// which lists none where the manifest records `user-xattr`. A writer +/// leaves them out, and the checks of an object take a filled-in +/// `readOnly`, flag or `extendedAttributes` for one that is not there. /// -/// The `size` and the `sha256` of a [`FileObject`], the sizes and hashes -/// of a [`ContentsObject`] and the `readOnly` of [`InodeAttributes`] can be +/// The `size`, the `sha256` and the DOS attributes of a [`FileObject`], +/// the sizes and hashes of a [`ContentsObject`] and the `readOnly`, the +/// inode flags and the `extendedAttributes` of [`InodeAttributes`] can be /// filled in. [`FileObject::filled_in()`], [`ContentsObject::filled_in()`] /// and [`InodeAttributes::filled_in()`] say which were. /// @@ -747,11 +775,11 @@ impl FlagStates { /// the hashes, the encoding and the source of a contents object. The next /// reader of the manifest fills them in again. #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] -pub struct FilledIn(u8); +pub struct FilledIn(u16); impl FilledIn { /// The fields that can be filled in, in the order of their bits. - const FIELDS: [Field; 7] = [ + const FIELDS: [Field; 16] = [ Field::Size, Field::Sha256, Field::EncodedSize, @@ -759,10 +787,19 @@ impl FilledIn { Field::OriginalSize, Field::OriginalSha256, Field::ReadOnly, + Field::ExtendedAttributes, + Field::FlagAppendOnly, + Field::FlagArchive, + Field::FlagHidden, + Field::FlagImmutable, + Field::FlagNoAtime, + Field::FlagNoCow, + Field::FlagNoDump, + Field::FlagSystem, ]; /// The bit of `field`, none for one that cannot be filled in. - fn bit(field: Field) -> u8 { + fn bit(field: Field) -> u16 { FilledIn::FIELDS .iter() .position(|&fillable| fillable == field) @@ -1199,7 +1236,8 @@ pub struct InodeAttributes { /// `flagAppendOnly` and the other fields of the inode flags: the /// flags the object states. pub(crate) flags: FlagStates, - /// `readOnly`, if a reader filled it in. + /// `readOnly` and `extendedAttributes`, where a reader filled them in. + /// `flags` notes the inode flags a reader filled in. pub(crate) filled_in: FilledIn, } @@ -1222,7 +1260,7 @@ impl InodeAttributes { /// [`InodeAttributes::FEATURE_FIELDS`]. fn has_feature_field(&self, field: Field) -> bool { match field { - Field::ExtendedAttributes => self.user_xattrs.is_some(), + Field::ExtendedAttributes => self.user_xattrs.is_some() && !self.filled_in.contains(field), Field::Gid => self.gid.is_some(), Field::GroupName => self.group_name.is_some(), Field::MTimeNSec => self.mtime_nsec.is_some(), @@ -1252,8 +1290,8 @@ impl InodeAttributes { /// Fills in what `features`, which the manifest records, say about the /// attributes a file of the type `inode_type` does not have: an inode /// flag the manifest records is cleared, the file is not read-only if - /// the manifest records `readOnly`, which is noted in `filled_in`, and - /// it has no extended attributes if the manifest records them. + /// the manifest records `readOnly`, and it has no extended attributes + /// if the manifest records them. Each is noted as filled in. fn fill_in(&mut self, features: Features, inode_type: InodeType) { self.flags.fill_in(features, inode_type); if features.contains(Features::READ_ONLY) && self.read_only.is_none() { @@ -1262,6 +1300,7 @@ impl InodeAttributes { } if features.contains(Features::USER_XATTR) && self.user_xattrs.is_none() { self.user_xattrs = Some(Box::default()); + self.filled_in.insert(Field::ExtendedAttributes); } } @@ -1345,6 +1384,7 @@ impl InodeAttributes { /// Sets `extendedAttributes`, see [`InodeAttributes::user_xattrs`]. pub fn set_user_xattrs(&mut self, xattrs: Option>>) { + self.filled_in.remove(Field::ExtendedAttributes); self.user_xattrs = xattrs.map(Box::new); } @@ -1361,9 +1401,10 @@ impl InodeAttributes { self.read_only = read_only; } - /// `readOnly`, if a reader filled it in, see [`FilledIn`]. + /// `readOnly`, the inode flags and `extendedAttributes`, where a reader + /// filled them in, see [`FilledIn`]. pub fn filled_in(&self) -> FilledIn { - self.filled_in + self.filled_in.union(self.flags.filled_in()) } /// The modification time, if the attributes have one. @@ -1408,6 +1449,9 @@ impl InodeAttributes { /// Sets `flagAppendOnly`: the inode flag `FS_APPEND_FL` is set, cleared, or /// not known. + /// `Some(false)` needs a manifest that records `flag-append-only` just as + /// `Some(true)` does: a writer leaves a cleared flag out, and only the + /// feature makes a missing field mean cleared. pub fn set_flag_append_only(&mut self, append_only: Option) { self.flags.put(InodeFlags::APPEND_ONLY, append_only); } @@ -1420,6 +1464,9 @@ impl InodeAttributes { /// Sets `flagImmutable`: the inode flag `FS_IMMUTABLE_FL` is set, cleared, /// or not known. + /// `Some(false)` needs a manifest that records `flag-immutable` just as + /// `Some(true)` does: a writer leaves a cleared flag out, and only the + /// feature makes a missing field mean cleared. pub fn set_flag_immutable(&mut self, immutable: Option) { self.flags.put(InodeFlags::IMMUTABLE, immutable); } @@ -1432,6 +1479,9 @@ impl InodeAttributes { /// Sets `flagNoAtime`: the inode flag `FS_NOATIME_FL` is set, cleared, or /// not known. + /// `Some(false)` needs a manifest that records `flag-no-atime` just as + /// `Some(true)` does: a writer leaves a cleared flag out, and only the + /// feature makes a missing field mean cleared. pub fn set_flag_no_atime(&mut self, no_atime: Option) { self.flags.put(InodeFlags::NO_ATIME, no_atime); } @@ -1444,6 +1494,9 @@ impl InodeAttributes { /// Sets `flagNoCow`: the inode flag `FS_NOCOW_FL` is set, cleared, or not /// known. + /// `Some(false)` needs a manifest that records `flag-no-cow` just as + /// `Some(true)` does: a writer leaves a cleared flag out, and only the + /// feature makes a missing field mean cleared. pub fn set_flag_no_cow(&mut self, no_cow: Option) { self.flags.put(InodeFlags::NO_COW, no_cow); } @@ -1456,6 +1509,9 @@ impl InodeAttributes { /// Sets `flagNoDump`: the inode flag `FS_NODUMP_FL` is set, cleared, or not /// known. + /// `Some(false)` needs a manifest that records `flag-no-dump` just as + /// `Some(true)` does: a writer leaves a cleared flag out, and only the + /// feature makes a missing field mean cleared. pub fn set_flag_no_dump(&mut self, no_dump: Option) { self.flags.put(InodeFlags::NO_DUMP, no_dump); } @@ -1496,7 +1552,8 @@ pub struct FileObject { pub(crate) dos_flags: FlagStates, pub(crate) inode: InodeAttributes, pub(crate) validity: ValidityWindow, - /// The size and the hash, if a reader filled them in. + /// The size and the hash, where a reader filled them in. `dos_flags` + /// notes the DOS attributes a reader filled in. pub(crate) filled_in: FilledIn, } @@ -1668,11 +1725,13 @@ impl FileObject { self.validity = validity; } - /// What a reader filled in of the object: its size and its hash, and - /// the `readOnly` of its inode attributes, see [`FilledIn`]. A writer - /// leaves these out. + /// What a reader filled in of the object: its size, its hash and its + /// DOS attributes, and what [`InodeAttributes::filled_in()`] says of its + /// inode attributes, see [`FilledIn`]. A writer leaves these out. pub fn filled_in(&self) -> FilledIn { - self.filled_in.union(self.inode.filled_in) + self.filled_in + .union(self.dos_flags.filled_in()) + .union(self.inode.filled_in()) } /// Drops the size and the hash a reader filled in, which follow from @@ -1767,6 +1826,9 @@ impl FileObject { /// Sets `flagArchive`: the DOS attribute `ATTR_ARCHIVE` is set, cleared, or /// not known. + /// `Some(false)` needs a manifest that records `flag-archive` just as + /// `Some(true)` does: a writer leaves a cleared flag out, and only the + /// feature makes a missing field mean cleared. pub fn set_flag_archive(&mut self, archive: Option) { self.dos_flags.put(DosFlags::ARCHIVE, archive); } @@ -1779,6 +1841,9 @@ impl FileObject { /// Sets `flagHidden`: the DOS attribute `ATTR_HIDDEN` is set, cleared, or /// not known. + /// `Some(false)` needs a manifest that records `flag-hidden` just as + /// `Some(true)` does: a writer leaves a cleared flag out, and only the + /// feature makes a missing field mean cleared. pub fn set_flag_hidden(&mut self, hidden: Option) { self.dos_flags.put(DosFlags::HIDDEN, hidden); } @@ -1791,6 +1856,9 @@ impl FileObject { /// Sets `flagSystem`: the DOS attribute `ATTR_SYSTEM` is set, cleared, or /// not known. + /// `Some(false)` needs a manifest that records `flag-system` just as + /// `Some(true)` does: a writer leaves a cleared flag out, and only the + /// feature makes a missing field mean cleared. pub fn set_flag_system(&mut self, system: Option) { self.dos_flags.put(DosFlags::SYSTEM, system); } @@ -1916,8 +1984,8 @@ impl RootObject { } /// The features whose fields the object has, see [`Features`]. A - /// manifest records them all or this is not its root file object. A - /// `readOnly` a reader filled in, see [`FilledIn`], does not count. + /// manifest records them all or this is not its root file object. What + /// a reader filled in, see [`FilledIn`], does not count. pub fn stated_features(&self) -> Features { self.feature_fields() .fold(Features::NONE, |features, (_, feature)| features | feature) @@ -2575,5 +2643,22 @@ mod tests { object.inode_mut().set_read_only(Some(false)); assert_eq!(object.inode().read_only(), Some(false)); assert!(!object.filled_in().contains(Field::ReadOnly)); + // The flags and the extended attributes as well. + let root = concat!( + r#"{"features":["flag-hidden","flag-no-dump","user-xattr"],"#, + r#""mediaType":"application/vnd.uapi.16.manifest"}"# + ); + let whole = read_whole(&sequence(&[root, r#"{"name":"a"}"#, TRAILER])).unwrap(); + let mut object = whole.objects.into_iter().next().unwrap(); + let fields = [Field::FlagHidden, Field::FlagNoDump, Field::ExtendedAttributes]; + assert!(fields.into_iter().all(|field| object.filled_in().contains(field))); + object.set_flag_hidden(Some(false)); + object.inode_mut().set_flag_no_dump(Some(false)); + object.inode_mut().set_user_xattrs(Some(BTreeMap::new())); + assert_eq!(object.filled_in(), none); + assert_eq!( + object.stated_features(), + Features::FLAG_HIDDEN | Features::FLAG_NO_DUMP | Features::USER_XATTR + ); } } diff --git a/src/uapi16/tests/fixtures.rs b/src/uapi16/tests/fixtures.rs index ecf9f7a..a3183b4 100644 --- a/src/uapi16/tests/fixtures.rs +++ b/src/uapi16/tests/fixtures.rs @@ -3,9 +3,10 @@ //! are copies of the fixtures of ufat, whose tests/fixtures/README.md says //! how they were made. +use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use uapi16::{Error, FileObject, InodeType, Object, Order, Reader, RootObject, SignatureObject, Writer}; +use uapi16::{Error, Field, FileObject, InodeType, Object, Order, Reader, RootObject, SignatureObject, Writer}; /// A manifest read to its end: its root file object, its file objects and /// its signature objects. @@ -42,6 +43,19 @@ impl Manifest { Manifest::read(&bytes).unwrap_or_else(|e| panic!("{}: {}", path.display(), e)) } + /// The manifest with the extended attributes a reader filled in taken + /// as ones the objects state. systemd-manifest states the empty ones, + /// which the writer leaves out and a reader fills in again. + fn with_stated_xattrs(mut self) -> Manifest { + let files = self.files.iter_mut().map(FileObject::inode_mut); + for inode in std::iter::once(self.root.inode_mut()).chain(files) { + if inode.filled_in().contains(Field::ExtendedAttributes) { + inode.set_user_xattrs(Some(BTreeMap::new())); + } + } + self + } + /// The manifest the writer writes for the objects. fn write(&self) -> Result, Error> { let mut writer = Writer::begin(Vec::new(), &self.root)?; @@ -180,6 +194,11 @@ fn reads_and_writes_back_every_fixture() { ); assert_eq!(read.root.order(), Some(Order::CodePoint), "{}", path.display()); let written = read.write().unwrap_or_else(|e| panic!("{}: {}", path.display(), e)); - assert_eq!(Manifest::read(&written).unwrap(), read, "{}", path.display()); + assert_eq!( + Manifest::read(&written).unwrap().with_stated_xattrs(), + read.with_stated_xattrs(), + "{}", + path.display() + ); } } diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs index e437f5c..61840fe 100644 --- a/src/uapi16/writer.rs +++ b/src/uapi16/writer.rs @@ -404,7 +404,7 @@ impl RootObject { /// name nor a type: it is a directory. impl Fields for RootObject { fn filled_in(&self) -> FilledIn { - self.inode.filled_in + self.inode.filled_in() } fn write_fields(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { @@ -1154,6 +1154,10 @@ mod tests { literal.filled_in.insert(Field::OriginalSize); expected[1].contents[1].http_headers.sort(); for object in &mut expected { + // A flag that is cleared goes out as no field at all, and the + // reader fills it in. + object.dos_flags.stated = object.dos_flags.set; + object.inode.flags.stated = object.inode.flags.set; object.fill_in(Features::ALL); } assert_eq!(m.objects, expected); @@ -1397,6 +1401,61 @@ mod tests { assert_eq!(contradiction(Writer::begin(Vec::new(), &root).unwrap_err()), expected); } + /// The flags and the extended attributes a reader filled in are, like + /// a readOnly it filled in, no fields the object has: they state no + /// feature, the writer leaves them out, and its checks hold them + /// neither against the features of the manifest nor against the type + /// of the object. A flag a caller sets is stated, cleared or not. + #[test] + fn writes_back_flags_and_attributes_a_reader_filled_in() { + let root = concat!( + r#"{"features":["flag-hidden","flag-no-dump","read-only","user-xattr"],"#, + r#""mediaType":"application/vnd.uapi.16.manifest"}"# + ); + let bytes = sequence(&[root, r#"{"name":"x"}"#, TRAILER]); + let m = read_whole(&bytes).unwrap(); + let object = &m.objects[0]; + assert_eq!(object.flag_hidden(), Some(false)); + assert_eq!(object.inode().flag_no_dump(), Some(false)); + assert_eq!(object.inode().user_xattrs().map(|xattrs| xattrs.len()), Some(0)); + for filled_in in [object.filled_in(), m.root.inode().filled_in()] { + for field in [Field::ExtendedAttributes, Field::FlagNoDump, Field::ReadOnly] { + assert!(filled_in.contains(field), "{:?}", field); + } + } + assert!(object.filled_in().contains(Field::FlagHidden)); + assert_eq!( + (m.root.stated_features(), object.stated_features()), + (Features::NONE, Features::NONE) + ); + assert_eq!(write_whole(&m).unwrap(), bytes); + // Under a manifest that records none of the features, on a fifo, + // and for the root file object. + let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); + writer.file(object).unwrap(); + let mut fifo = object.clone(); + fifo.set_inode_type(InodeType::Fifo); + let mut writer = Writer::begin(Vec::new(), &m.root).unwrap(); + writer.file(&fifo).unwrap(); + let mut root = m.root.clone(); + root.set_features(None); + Writer::begin(Vec::new(), &root).unwrap(); + // Set by a caller, the cleared flag is stated and needs its + // feature, so the manifest says it is cleared. + let mut set = object.clone(); + set.set_flag_hidden(Some(false)); + assert!(!set.filled_in().contains(Field::FlagHidden)); + assert_eq!(set.stated_features(), Features::FLAG_HIDDEN); + let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); + let e = writer.file(&set).unwrap_err(); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::UnlistedFeature), Some(Field::FlagHidden)) + ); + let mut writer = Writer::begin(Vec::new(), &m.root).unwrap(); + writer.file(&set).unwrap(); + } + /// The writer leaves out what the specification recommends to leave /// out where it says nothing more, and a reader fills it in again. #[test] From 9660157672a1480e578512557bed3e1175a9c7ef Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 21:40:50 +0100 Subject: [PATCH 18/32] uapi16: let callers change what a reader returned Since the fields became private, a caller that changes an object a reader returned has the setters, x_mut() for the inode attributes and the identity of the file system, and a copy that it changes and sets back. That doesn't work everywhere: - The contents objects are only handed out as a slice. A copy of all of them, set back, drops the size and the hash a reader filled in from them. A copy of the data from a stream then fails with NoSize, although the contents objects still give the size. - The fields of a GPT partition are copied out and set back whole. - One extended attribute is changed by copying and setting back all of them. - The data of a literal, which can be 4 MiB, is only lent out. So do what Rust usually does with private fields. A value that nothing else follows from is changed in place: gpt_mut() hands out the fields of the partition the way inode_mut() hands out the inode attributes, and take_gpt() goes with set_gpt(). A value that other fields follow from gets no _mut(). It is taken out, changed and set back. take_contents() takes the contents objects out, together with the size and the hash a reader filled in from them. set_contents() fills in again what follows from the contents it gets, as the reader does: what each contents object says of its own data, and the size and the hash of the file, marked as filled in. It runs the code of the reader for that, which moves into a method of its own. What a reader filled in that no longer follows is dropped, and what the object states stays. Where the new contents contradict a size or a hash the object states nothing is filled in, and the writer refuses the object as before. The extended attributes get single entries the way HashMap has them: insert_user_xattr() and remove_user_xattr() return what insert() and remove() return, and take away the mark of extendedAttributes like every setter. ContentsObject::into_source() moves the source out of a contents object, so the data of a literal isn't copied. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/content.rs | 23 +++++++++ src/uapi16/decode.rs | 50 ++++++++++++++++---- src/uapi16/object.rs | 107 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 161 insertions(+), 19 deletions(-) diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index daac878..8a119c2 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -2536,6 +2536,29 @@ mod tests { } } + /// The size a reader fills in from a contents object comes back where + /// the contents are set back, and a copy from a stream goes by it. + #[test] + fn contents_set_back_give_the_size_again() { + let record = format!( + r#"{{"name":"s","contents":[{{"originalSize":5,"originalSha256":"{}"}}]}}"#, + HELLO + ); + let mut object = object(&record); + assert_eq!(object.size(), Some(5)); + object.set_contents(object.contents().to_vec()); + assert_eq!(object.size(), Some(5)); + let mut stream = &b"hello"[..]; + let copied = object.copy_data(&mut StreamProvider::new(&mut stream), &mut io::sink()); + assert_eq!(copied.unwrap(), 5); + let contents = object.take_contents(); + assert_eq!(object.size(), None); + object.set_contents(contents); + let mut stream = &b"hello"[..]; + let copied = object.copy_data(&mut StreamProvider::new(&mut stream), &mut io::sink()); + assert_eq!(copied.unwrap(), 5); + } + #[test] fn a_sink_that_fails() { let o = object(r#"{"name":"a","size":5}"#); diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index 224cbfa..aa2334d 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -389,16 +389,7 @@ impl Draft { // The contents objects were checked when they were read, and hold // what follows from their fields. let data = object.check_consistency(subject, |contents| Ok(contents.data()))?; - // What the record does not give was filled in. - for (field, given, known) in [ - (Field::Size, object.size.is_some(), data.size.is_some()), - (Field::Sha256, object.sha256.is_some(), data.sha256.is_some()), - ] { - if known && !given { - object.filled_in.insert(field); - } - } - (object.size, object.sha256) = (data.size, data.sha256); + object.fill_in_data(data); Ok(()) } } @@ -458,6 +449,45 @@ impl FileObject { } } + /// Fills in the size and the hash of the data, `data` from + /// [`FileObject::check_consistency`], and notes those the object does + /// not give. + fn fill_in_data(&mut self, data: SizeAndHash) { + for (field, given, known) in [ + (Field::Size, self.size.is_some(), data.size.is_some()), + (Field::Sha256, self.sha256.is_some(), data.sha256.is_some()), + ] { + if known && !given { + self.filled_in.insert(field); + } + } + (self.size, self.sha256) = (data.size, data.sha256); + } + + /// Fills in what follows from the contents objects, as a reader does: + /// what each of them says of its own data, and the size and the hash of + /// the data of the object. Where fields contradict each other nothing + /// follows from them, and a writer refuses the object. + pub(crate) fn fill_in_from_contents(&mut self) { + // The object is in no record, and what is wrong with it is not + // shown, so the number of the record does not matter. + let subject = Subject::new(self, ROOT_RECORD); + let data: Vec<_> = self + .contents + .iter() + .map(|contents| contents.check_consistency(subject).ok()) + .collect(); + for (contents, data) in self.contents.iter_mut().zip(data) { + if let Some(data) = data { + contents.fill_in(data); + } + } + let subject = Subject::new(self, ROOT_RECORD); + if let Ok(data) = self.check_consistency(subject, |contents| Ok(contents.data())) { + self.fill_in_data(data); + } + } + /// Checks that the fields of the object agree with each other, as the /// specification requires: `readOnly` and `mode`, and the size and the /// hash of the object and those of its contents objects. `contents_data` diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index d02c6d5..c99a549 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -771,9 +771,11 @@ impl FlagStates { /// A value that is set is not one a reader filled in. A value that the /// sizes and hashes of the same object follow from also drops those that /// a reader filled in when it is set: they are None then. These are the -/// size, the hash and the contents objects of a file object, and the sizes, -/// the hashes, the encoding and the source of a contents object. The next -/// reader of the manifest fills them in again. +/// size and the hash of a file object, and the sizes, the hashes, the +/// encoding and the source of a contents object. The next reader of the +/// manifest fills them in again. The contents objects of a file object +/// fill in again what follows from them when they are set, see +/// [`FileObject::set_contents`]. #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct FilledIn(u16); @@ -1100,6 +1102,12 @@ impl ContentsObject { self.source = source; } + /// `file`, `url` or `literal`, moved out of the contents object, such + /// as the data of a literal. + pub fn into_source(self) -> ContentsSource { + self.source + } + /// `httpHeaders`: the header fields of the HTTP requests for the data /// at `url`, by name, in the order the manifest lists them. pub fn http_headers(&self) -> impl ExactSizeIterator { @@ -1388,6 +1396,25 @@ impl InodeAttributes { self.user_xattrs = xattrs.map(Box::new); } + /// Sets the extended attribute of the `user` namespace whose name + /// without the `user.` in front is `name` to `value`, and returns the + /// value it had, like [`BTreeMap::insert`]. Attributes that said + /// nothing about the extended attributes list this one alone then. + pub fn insert_user_xattr(&mut self, name: impl Into, value: impl Into>) -> Option> { + self.filled_in.remove(Field::ExtendedAttributes); + self.user_xattrs + .get_or_insert_with(Box::default) + .insert(name.into(), value.into()) + } + + /// Removes the extended attribute of the `user` namespace whose name + /// without the `user.` in front is `name`, and returns its value, like + /// [`BTreeMap::remove`]. + pub fn remove_user_xattr(&mut self, name: &str) -> Option> { + self.filled_in.remove(Field::ExtendedAttributes); + self.user_xattrs.as_deref_mut()?.remove(name) + } + /// `readOnly`: whether the file is read-only, see /// [`InodeAttributes::is_read_only`]. It stands for the read-only /// attribute of DOS and for [`GptPartition::FLAG_READ_ONLY`] too. @@ -1654,13 +1681,27 @@ impl FileObject { &self.contents } - /// Sets `contents`, and drops what a reader filled in, see - /// [`FilledIn`]. A writer refuses more than [`MAX_CONTENTS`] of them. + /// Sets `contents`, and fills in what follows from them as a reader + /// does, see [`FilledIn`]: what each contents object says of its own + /// data, and the size and the hash of the data of the file. What a + /// reader filled in that no longer follows is dropped, and what the + /// object states stays. A writer refuses an object whose fields + /// contradict each other, and more than [`MAX_CONTENTS`] contents + /// objects. /// /// [`MAX_CONTENTS`]: crate::MAX_CONTENTS pub fn set_contents(&mut self, contents: Vec) { self.drop_filled_in(); self.contents = contents; + self.fill_in_from_contents(); + } + + /// Takes `contents` out of the object, with the size and the hash a + /// reader filled in, which follow from them. Set back with + /// [`FileObject::set_contents`], they fill them in again. + pub fn take_contents(&mut self) -> Vec { + self.drop_filled_in(); + std::mem::take(&mut self.contents) } /// `inodeToken`: the objects that carry the same token are hard links @@ -1699,11 +1740,21 @@ impl FileObject { self.gpt.as_deref() } + /// The `gpt` fields to change in place. Nothing follows from them. + pub fn gpt_mut(&mut self) -> Option<&mut GptPartition> { + self.gpt.as_deref_mut() + } + /// Sets the `gpt` fields. pub fn set_gpt(&mut self, gpt: Option) { self.gpt = gpt.map(Box::new); } + /// Takes the `gpt` fields out of the object. + pub fn take_gpt(&mut self) -> Option { + self.gpt.take().map(|gpt| *gpt) + } + /// The inode attributes of the file. pub fn inode(&self) -> &InodeAttributes { &self.inode @@ -2572,6 +2623,18 @@ mod tests { assert_eq!(headers, [("X-B", "2"), ("X-A", "1")]); } + /// The fields of a partition change in place, and come out whole. + #[test] + fn gpt_in_place() { + let mut object = FileObject::new(Name::new("a").unwrap()); + assert!(object.gpt_mut().is_none()); + object.set_gpt(Some(GptPartition::default())); + object.gpt_mut().unwrap().set_label(Some("esp".to_string())); + assert_eq!(object.gpt().and_then(GptPartition::label), Some("esp")); + let gpt = object.take_gpt().unwrap(); + assert_eq!((gpt.label(), object.gpt()), (Some("esp"), None)); + } + /// A value that is set drops the sizes and hashes a reader filled in on /// the same object, and leaves the ones the record gives. #[test] @@ -2601,13 +2664,29 @@ mod tests { (object.size(), object.sha256(), object.filled_in()), (Some(5), None, none) ); - // The size a contents object gives. + // The size a contents object gives, which contents that are set + // fill in again. let mut object = read(r#"{"name":"a","contents":[{"file":"blob","originalSize":3}]}"#); assert_eq!(object.size(), Some(3)); - let mut contents = object.contents()[0].clone(); - contents.set_original_size(Some(7)); - object.set_contents(vec![contents]); + let mut contents = object.take_contents(); assert_eq!((object.size(), object.filled_in()), (None, none)); + contents[0].set_original_size(Some(7)); + object.set_contents(contents); + assert_eq!( + ( + object.size(), + object.contents()[0].encoded_size(), + object.filled_in().contains(Field::Size) + ), + (Some(7), Some(7), true) + ); + // Contents that contradict the size the object states fill in + // nothing, and the size stays. + let mut object = read(r#"{"name":"a","size":3,"contents":[{"file":"blob","originalSize":3}]}"#); + let mut contents = object.take_contents(); + contents[0].set_original_size(Some(7)); + object.set_contents(contents); + assert_eq!((object.size(), object.filled_in()), (Some(3), none)); // What the record gives stays. let mut object = read(&format!(r#"{{"name":"a","size":5,"sha256":"{}"}}"#, HELLO)); object.set_size(Some(5)); @@ -2660,5 +2739,15 @@ mod tests { object.stated_features(), Features::FLAG_HIDDEN | Features::FLAG_NO_DUMP | Features::USER_XATTR ); + // One extended attribute at a time as well. + let whole = read_whole(&sequence(&[root, r#"{"name":"a"}"#, TRAILER])).unwrap(); + let mut object = whole.objects.into_iter().next().unwrap(); + let inode = object.inode_mut(); + assert_eq!(inode.remove_user_xattr("comment"), None); + assert!(!inode.filled_in().contains(Field::ExtendedAttributes)); + assert_eq!(inode.insert_user_xattr("comment", b"one"), None); + assert_eq!(inode.insert_user_xattr("comment", b"two"), Some(b"one".to_vec())); + assert_eq!(inode.remove_user_xattr("comment"), Some(b"two".to_vec())); + assert_eq!(inode.user_xattrs().map(|xattrs| xattrs.len()), Some(0)); } } From 281ec0334f75e7ca0a55cdb6fad42ec0909aea51 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 21:41:41 +0100 Subject: [PATCH 19/32] uapi16: add Sha256Context::new(), FilledIn::is_empty() and iter() Three things a consumer of the API missed: - Sha256Context only has Default, so its new() is spelled default(). Add new(), which does the same. - FilledIn only answers contains() for one field at a time. Add is_empty() and iter(), which hands out the fields it notes, so a caller sees what a reader filled in without asking for every field. Its Debug goes through iter() as well. - The docs of Writer don't show a copy of a manifest. Add one. The writer takes the root file object by reference, so it starts before the loop with what the reader returns, and the root needs no clone. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/blocking.rs | 25 +++++++++++++++++++++++++ src/uapi16/digest.rs | 8 +++++++- src/uapi16/object.rs | 22 +++++++++++++++++----- 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/src/uapi16/blocking.rs b/src/uapi16/blocking.rs index cb60356..23f5982 100644 --- a/src/uapi16/blocking.rs +++ b/src/uapi16/blocking.rs @@ -264,6 +264,31 @@ impl FusedIterator for Reader {} /// # Ok::<(), Box>(()) /// ``` /// +/// A copy of a manifest writes back what a reader returns, one object at +/// a time. The writer takes the root file object by reference, so it +/// starts before the loop and needs no copy of it: +/// +/// ``` +/// use uapi16::{Object, Reader, Writer}; +/// +/// let manifest = concat!( +/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n", +/// "\x1e{\"name\":\"a\",\"size\":3}\n", +/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", +/// ); +/// let mut reader = Reader::open(manifest.as_bytes())?; +/// let mut writer = Writer::begin(Vec::new(), reader.root())?; +/// for object in &mut reader { +/// match object? { +/// Object::File(file) => writer.file(&file)?, +/// Object::Signature(signature) => writer.signature(&signature)?, +/// _ => {} +/// } +/// } +/// assert_eq!(writer.finish()?, manifest.as_bytes()); +/// # Ok::<(), uapi16::Error>(()) +/// ``` +/// /// [`FilledIn`]: crate::FilledIn /// [`MAX_CONTENTS`]: crate::MAX_CONTENTS /// [`MAX_RECORD_SIZE`]: crate::MAX_RECORD_SIZE diff --git a/src/uapi16/digest.rs b/src/uapi16/digest.rs index 042ab12..c796688 100644 --- a/src/uapi16/digest.rs +++ b/src/uapi16/digest.rs @@ -111,7 +111,7 @@ impl FromStr for Sha256 { /// use std::io::Write; /// use uapi16::{Sha256, Sha256Context}; /// -/// let mut context = Sha256Context::default(); +/// let mut context = Sha256Context::new(); /// context.update(b"hel"); /// context.write_all(b"lo")?; /// assert_eq!(context.finalize(), Sha256::digest(b"hello")); @@ -121,6 +121,12 @@ impl FromStr for Sha256 { pub struct Sha256Context(sha2::Sha256); impl Sha256Context { + /// A computation that has taken no data yet, the same as the default + /// one. + pub fn new() -> Sha256Context { + Sha256Context::default() + } + /// Takes more of the data. pub fn update(&mut self, data: &[u8]) { self.0.update(data); diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index c99a549..6860886 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -813,6 +813,16 @@ impl FilledIn { self.0 & FilledIn::bit(field) != 0 } + /// Whether no field was filled in. + pub fn is_empty(self) -> bool { + self.0 == 0 + } + + /// The fields that were filled in. + pub fn iter(self) -> impl Iterator { + FilledIn::FIELDS.into_iter().filter(move |&field| self.contains(field)) + } + /// Notes that `field` was filled in, if it is one that can be. pub(crate) fn insert(&mut self, field: Field) { self.0 |= FilledIn::bit(field); @@ -834,8 +844,7 @@ impl FilledIn { impl fmt::Debug for FilledIn { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("FilledIn(")?; - let filled = FilledIn::FIELDS.into_iter().filter(|&field| self.contains(field)); - for (i, field) in filled.enumerate() { + for (i, field) in self.iter().enumerate() { if i > 0 { f.write_str(" | ")?; } @@ -2729,12 +2738,15 @@ mod tests { ); let whole = read_whole(&sequence(&[root, r#"{"name":"a"}"#, TRAILER])).unwrap(); let mut object = whole.objects.into_iter().next().unwrap(); - let fields = [Field::FlagHidden, Field::FlagNoDump, Field::ExtendedAttributes]; - assert!(fields.into_iter().all(|field| object.filled_in().contains(field))); + let filled_in: Vec = object.filled_in().iter().collect(); + assert_eq!( + filled_in, + [Field::ExtendedAttributes, Field::FlagHidden, Field::FlagNoDump] + ); object.set_flag_hidden(Some(false)); object.inode_mut().set_flag_no_dump(Some(false)); object.inode_mut().set_user_xattrs(Some(BTreeMap::new())); - assert_eq!(object.filled_in(), none); + assert!(object.filled_in().is_empty()); assert_eq!( object.stated_features(), Features::FLAG_HIDDEN | Features::FLAG_NO_DUMP | Features::USER_XATTR From 779fdcbe37fbe7f2a9c5d2cc18d4c8d6f589b3f8 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Mon, 23 Nov 2026 10:28:40 +0100 Subject: [PATCH 20/32] uapi16: add Writer::get_mut() Reader has get_ref() and get_mut(), but Writer only has get_ref(). A caller that wants to flush the output in between, or change something about it, can't get at it until finish() hands it back. Add Writer::get_mut(). Its docs say what those of std's BufWriter::get_mut() say, that writing to the output directly breaks what the writer writes. The writer holds nothing back: every method writes its whole record to the output before it returns, so the output always has the manifest up to the last record. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/blocking.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/uapi16/blocking.rs b/src/uapi16/blocking.rs index 23f5982..b7c4418 100644 --- a/src/uapi16/blocking.rs +++ b/src/uapi16/blocking.rs @@ -335,6 +335,14 @@ impl Writer { &self.out } + /// What the manifest is written to, to change it, such as to flush it + /// in between. Writing to it directly breaks the manifest the writer + /// writes. The writer holds nothing back: every method writes its whole + /// record to it before it returns. + pub fn get_mut(&mut self) -> &mut W { + &mut self.out + } + /// Writes out the record that `encode` has the encoder put together. fn send_record(&mut self, encode: impl FnOnce(&mut Encoder) -> Result<(), Error>) -> Result<(), Error> { let record_number = self.encoder.next_record; @@ -690,6 +698,17 @@ mod tests { assert_eq!(Sha256::digest(&bytes[..signed]), hash); } + /// What the writer writes to is lent out as it is, with every record + /// written so far in it. + #[test] + fn lends_out_what_it_writes_to() { + let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); + let root = sequence(&[ROOT]); + assert_eq!(writer.get_mut(), &root); + writer.get_mut().flush().unwrap(); + assert_eq!(writer.finish().unwrap(), sequence(&[ROOT, TRAILER])); + } + /// Notes every write and every flush, and fails the write `fail_at`. #[derive(Debug, Default)] struct Calls { From b05ce6c94c727bc1d65bb6cdb4410de0a61406e9 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 18:14:39 +0100 Subject: [PATCH 21/32] uapi16: add PinnedDirectory DirectoryProvider reads the data of the files from a Directory, but the crate has no Directory a caller can use. ufat has one, PinnedDirectory. It resolves every name below the directory the way systemd's chase() does with a root: an absolute symbolic link starts over at the directory, ".." at the directory stays there, magic links are refused, and symbolic links are only followed when the caller asks for it. It does that with code of ufat's own, openat2() with RESOLVE_IN_ROOT and a walk by hand where openat2() isn't there, and that code needs unsafe, which uapi16 denies. So add PinnedDirectory to uapi16, built on pathrs, which resolves paths below a root the same way, and on rustix. new() and follow_symlinks() keep their signatures and what they do. A file is opened by resolving its name with Root::resolve() to an O_PATH handle, with ResolverFlags::NO_SYMLINKS unless symbolic links are followed. It then checks with fstat() that the handle is a regular file, and only then reopens it for reading with O_RDONLY|O_NONBLOCK|O_NOCTTY. So nothing but a regular file is ever opened, not even a FIFO a manifest names. The errors are those of the system calls, as before, and an error of pathrs itself becomes an io::Error of its own. pathrs refuses the empty path, which ufat took for the directory itself, so the empty name of the root is resolved as "." to keep that. The reopen goes through O_EMPTYPATH where the kernel has it, as it did in ufat: openat(fd, "", O_EMPTYPATH|...) reopens the handle without procfs, and Linux 7.2 has it. The flag is probed the way systemd's fd_reopen() does. An older kernel ignores it and fails the empty path with ENOENT, so the first ENOENT turns O_EMPTYPATH off for the process, unless it worked before. Where it is missing the handle is reopened with Handle::reopen() of pathrs, which goes through procfs and checks it on the way. That costs: opening a small file and reading it takes 2.4us and 9 system calls here with O_EMPTYPATH, as in ufat, and 38us and 53 system calls with Handle::reopen(). new() takes the directory as a descriptor the caller opened, which it can't check. Its docs say that it has to be a directory, since below anything else every file fails to open, the way pathrs documents Root::from_fd(). ufat's callers opened the directory themselves, but a caller that has a path gets open() now, which opens it with O_PATH|O_DIRECTORY|O_CLOEXEC like pathrs's Root::open(). So a path that isn't a directory fails right there with ENOTDIR, and the directory needs no read permission. The tests are those of ufat's chase(), with the names a manifest can have, and give the errors they gave there, below /proc too. They open their directories with open(). A new one reopens a pinned file both ways, after it was replaced under its name and after it was unlinked, and another one checks that open() takes a directory and nothing else. pathrs is empty on Android. So pathrs and rustix are dependencies on Linux only, and PinnedDirectory, Directory, DirectoryProvider and OpenError are there on Linux only as well, which their docs say. On Android the data of the files next to a manifest can't be read, and everything else works as before. The docs of what is there on Android as well mention DirectoryProvider and PinnedDirectory on Linux only, so that no link in them leads to something that isn't there. The tests of content.rs build their directories in memory for a DirectoryProvider, so they're for Linux only too. Cargo.lock gains 18 crates: pathrs and rustix with what they need, the build dependency of pathrs on tempfile with what that needs, and the crates for Windows and UEFI that some of them name, which nothing builds here. pathrs, errno and getrandom use libc 0.2, so the comment in Cargo.toml names them as a reason for the tests to stay on it as well. Signed-off-by: Christian Brauner (Amutable) --- Cargo.lock | 159 +++++++++++++++++ Cargo.toml | 10 +- src/uapi16/Cargo.toml | 5 + src/uapi16/content.rs | 58 +++++-- src/uapi16/directory.rs | 370 ++++++++++++++++++++++++++++++++++++++++ src/uapi16/lib.rs | 19 ++- 6 files changed, 604 insertions(+), 17 deletions(-) create mode 100644 src/uapi16/directory.rs diff --git a/Cargo.lock b/Cargo.lock index a479656..11b6de9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + [[package]] name = "block-buffer" version = "0.12.1" @@ -45,18 +51,51 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + [[package]] name = "equivalent" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "foldhash" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + [[package]] name = "hashbrown" version = "0.17.1" @@ -82,6 +121,15 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.19" @@ -94,12 +142,42 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pathrs" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd74b8fd656302d50059a07147444e46d6c2f162656271cf626e8ff3fad4cce8" +dependencies = [ + "bitflags", + "itertools", + "libc", + "memchr", + "once_cell", + "rustix", + "rustversion", + "static_assertions", + "tempfile", + "thiserror", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -118,6 +196,31 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + [[package]] name = "serde" version = "1.0.229" @@ -173,6 +276,12 @@ dependencies = [ "digest", ] +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "syn" version = "3.0.10" @@ -184,6 +293,39 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "typenum" version = "1.20.1" @@ -195,6 +337,8 @@ name = "uapi16" version = "0.0.0" dependencies = [ "libc", + "pathrs", + "rustix", "serde_core", "serde_json", "sha2", @@ -206,6 +350,21 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 5939179..1e12740 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,9 +13,15 @@ license = "LGPL-2.1-or-later" publish = false [workspace.dependencies] -# Stay on 0.2 like sha2's cpufeatures on aarch64 and loongarch64, so -# that the tests never build two versions of libc there. +# Stay on 0.2 like pathrs, errno, getrandom and sha2's cpufeatures, so +# that the tests never build two versions of libc. libc = "0.2.191" +# Resolves the names of the files next to a manifest below their +# directory, for PinnedDirectory. It builds on Linux only. +pathrs = "0.2.6" +# Tells what pathrs resolved apart before it is opened, and reopens it +# through O_EMPTYPATH. +rustix = "1.1.6" # Reads and writes JSON. What a manifest asks for beyond JSON is checked # by src/uapi16/strict.rs. Never turn on arbitrary_precision: serde_json # then hands numbers to the visitors of uapi16 as objects, see the crate diff --git a/src/uapi16/Cargo.toml b/src/uapi16/Cargo.toml index b5d7189..625309b 100644 --- a/src/uapi16/Cargo.toml +++ b/src/uapi16/Cargo.toml @@ -17,6 +17,11 @@ serde_core.workspace = true serde_json = { workspace = true, features = ["float_roundtrip"] } sha2.workspace = true +# PinnedDirectory, which only Linux has. +[target.'cfg(target_os = "linux")'.dependencies] +pathrs.workspace = true +rustix = { workspace = true, features = ["fs"] } + [dev-dependencies] # The errno values of the errors the tests make. libc.workspace = true diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index 8a119c2..e65d1fd 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -2,9 +2,13 @@ //! The data of the files a manifest describes: where it is, and copying //! it from there with the sizes and hashes of the manifest checked. +#[cfg(target_os = "linux")] use std::collections::HashMap; use std::fmt; -use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::io::{self, Read, Write}; +#[cfg(target_os = "linux")] +use std::io::{Seek, SeekFrom}; +#[cfg(target_os = "linux")] use std::ops::Range; use crate::digest::Sha256Context; @@ -20,13 +24,16 @@ const COPY_SIZE: usize = 1024 * 1024; /// file takes besides, see [`PieceHashes::stored_bytes`]. The map that /// holds them adds up to about half a MiB, with many small files, which /// does not grow with the manifest either. +#[cfg(target_os = "linux")] const PIECE_HASH_BYTES: usize = 1024 * 1024; /// What a file takes in [`PieceHashes`] besides the hashes of its pieces: /// its hash and its length, which it is known by, and the pointer to the /// hashes of its pieces. +#[cfg(target_os = "linux")] const FILE_ENTRY_BYTES: usize = size_of::<(Sha256, u64)>() + size_of::>(); /// The most pieces a file is hashed in, so that the hashes of a file of /// any length fit into [`PIECE_HASH_BYTES`]. +#[cfg(target_os = "linux")] const MAX_PIECES: u64 = ((PIECE_HASH_BYTES - FILE_ENTRY_BYTES) / size_of::()) as u64; /// Where the data of a file object is, as [`FileObject::data_location`] @@ -105,6 +112,7 @@ impl<'a> ExternalFile<'a> { /// as long as the object says, whatever else the file holds. So the /// file has to be long enough for it, and as long as `originalSize` /// where the manifest gives that. + #[cfg(target_os = "linux")] fn check_len(&self, object: &FileObject, len: u64) -> Result { let name = &object.name; let mismatch = @@ -136,6 +144,7 @@ impl<'a> ExternalFile<'a> { /// The error for the file that the data of `object` cannot be taken /// from. + #[cfg(target_os = "linux")] fn unavailable(&self, object: &FileObject, error: OpenError) -> Error { let name = &object.name; let error = match error { @@ -353,7 +362,8 @@ impl ContentsObject { /// It checks what the object says of its data, the check the /// specification has for the data of every file. What its contents /// objects say of the files the data is in, their sizes and hashes, is -/// for whoever reads those files to check, such as a [`DirectoryProvider`]. +/// for whoever reads those files to check. +#[cfg_attr(target_os = "linux", doc = "A [`DirectoryProvider`] does.")] /// /// [`FileObject::copy_data`] checks what it copies with one. A caller /// that moves the data itself, such as a copy in an async runtime, hands @@ -486,12 +496,16 @@ impl Write for CheckedSink<'_, '_> { /// Has the data of the file objects whose data is outside of the /// manifest. /// -/// [`DirectoryProvider`] takes it from the files next to the manifest and -/// [`StreamProvider`] from one stream that carries it all, in the order of -/// the manifest. A consumer hands a provider every file object, in the -/// order of the manifest: those whose data it takes to -/// [`FileObject::copy_data`], which calls [`DataProvider::copy`], and -/// the others to [`DataProvider::skip`]. After the last one it calls +/// [`StreamProvider`] takes it from one stream that carries it all, in the +/// order of the manifest. +#[cfg_attr( + target_os = "linux", + doc = "[`DirectoryProvider`] takes it from the files next to the manifest." +)] +/// A consumer hands a provider every file object, in the order of the +/// manifest: those whose data it takes to [`FileObject::copy_data`], +/// which calls [`DataProvider::copy`], and the others to +/// [`DataProvider::skip`]. After the last one it calls /// [`DataProvider::end`]. pub trait DataProvider { /// Writes the data of `object`, which is in `file`, to `sink`: exactly @@ -516,6 +530,9 @@ pub trait DataProvider { } /// Why a [`Directory`] does not hand out a file. +/// +/// It exists on Linux only, not on Android. +#[cfg(target_os = "linux")] #[derive(Debug)] #[non_exhaustive] pub enum OpenError { @@ -526,6 +543,7 @@ pub enum OpenError { Io(io::Error), } +#[cfg(target_os = "linux")] impl From for OpenError { fn from(e: io::Error) -> OpenError { OpenError::Io(e) @@ -539,6 +557,9 @@ impl From for OpenError { /// names it gives are normalized relative paths, see [`Name`], but a /// symbolic link in the directory can still lead out of it. It is on the /// implementation to resolve a name below the directory and nowhere else. +/// +/// It exists on Linux only, not on Android. +#[cfg(target_os = "linux")] pub trait Directory { /// A file of the directory, open for reading. type File: Read + Seek; @@ -575,6 +596,9 @@ pub trait Directory { /// specification allows. So the memory the provider takes does not grow /// with the manifest, and while copies succeed, a file of more than one /// piece is read whole once at most for its parts. +/// +/// It exists on Linux only, not on Android. +#[cfg(target_os = "linux")] pub struct DirectoryProvider { directory: D, /// What a copy goes through, made when the first file is copied. @@ -583,6 +607,7 @@ pub struct DirectoryProvider { hashes: PieceHashes, } +#[cfg(target_os = "linux")] impl DirectoryProvider { /// A provider that takes the files from `directory`. pub fn new(directory: D) -> DirectoryProvider { @@ -594,6 +619,7 @@ impl DirectoryProvider { } } +#[cfg(target_os = "linux")] impl fmt::Debug for DirectoryProvider { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("DirectoryProvider") @@ -619,6 +645,7 @@ impl fmt::Debug for DirectoryProvider { /// fit are not checked against the hash of the whole file, which the /// specification allows for a file that is taken only in part. A part that /// gives a hash of its own is checked against that one in any case. +#[cfg(target_os = "linux")] #[derive(Default)] struct PieceHashes { /// The hashes of the pieces of each file, by its hash and its length. @@ -627,6 +654,7 @@ struct PieceHashes { bytes: usize, } +#[cfg(target_os = "linux")] impl PieceHashes { /// The size of the pieces a file of the length `len` is hashed in: /// [`COPY_SIZE`], or more for a file that would have more than @@ -676,6 +704,7 @@ impl PieceHashes { } } +#[cfg(target_os = "linux")] impl fmt::Debug for PieceHashes { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PieceHashes") @@ -685,7 +714,9 @@ impl fmt::Debug for PieceHashes { } } -/// Why a copy from a file or a stream did not go through. +/// Why a copy from a file or a stream did not go through. A copy from a +/// stream fails the first two ways only, and the files of a directory are +/// read on Linux only. #[derive(Debug)] enum CopyFailure { /// Reading the file or the stream failed. @@ -693,9 +724,11 @@ enum CopyFailure { /// The sink did not take what was read. WriteFailed(io::Error), /// The file does not have the hash it is checked against. + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] HashMismatch, /// The file is not as long as it was when it was opened, or longer: /// it changed while it was read. + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] SourceChanged, } @@ -769,6 +802,7 @@ impl ReadSome for R {} /// A file a [`DirectoryProvider`] copies the data of an object from, in /// pieces where it checks them. +#[cfg(target_os = "linux")] struct Pieces<'a, F> { file: F, /// What the file is read into: [`COPY_SIZE`] bytes. @@ -783,6 +817,7 @@ struct Pieces<'a, F> { data: Range, } +#[cfg(target_os = "linux")] impl Pieces<'_, F> { /// Copies the data without a look at the rest of the file. A file that /// ends before the data does changed since it was opened. @@ -903,6 +938,7 @@ impl Pieces<'_, F> { } } +#[cfg(target_os = "linux")] impl DataProvider for DirectoryProvider { fn copy(&mut self, object: &FileObject, file: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error> { let (opened, len) = self @@ -1102,7 +1138,9 @@ impl DataProvider for StreamProvider { } } -#[cfg(test)] +// The tests build their directories in memory, and DirectoryProvider is +// for Linux only. +#[cfg(all(test, target_os = "linux"))] mod tests { use super::*; use crate::testing::{json, manifest, read_whole, sequence, HELLO, TRAILER, WORLD}; diff --git a/src/uapi16/directory.rs b/src/uapi16/directory.rs new file mode 100644 index 0000000..1da098b --- /dev/null +++ b/src/uapi16/directory.rs @@ -0,0 +1,370 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The directory next to a manifest that the data of its files is taken +//! from, with every name resolved below it. + +use std::fs::File; +use std::io; +use std::os::fd::OwnedFd; +use std::path::Path; +use std::sync::atomic::{AtomicU8, Ordering}; + +use pathrs::error::{Error as PathrsError, ErrorKind as PathrsErrorKind}; +use pathrs::flags::{OpenFlags, ResolverFlags}; +use pathrs::{Handle, Root}; +use rustix::fs::{FileType, Mode, OFlags}; +use rustix::io::Errno; + +use crate::content::{Directory, OpenError}; +use crate::Name; + +/// What this process found out about O_EMPTYPATH: whether the kernel +/// reopens a descriptor with `openat(fd, "", O_EMPTYPATH | ..)`, which +/// needs no procfs. Linux 7.2 has it. +struct EmptyPath; + +impl EmptyPath { + /// O_EMPTYPATH, include/uapi/asm-generic/fcntl.h. No architecture + /// overrides it, and fs/fcntl.c checks at build time that it is a bit + /// of its own on every architecture. + const FLAG: u32 = 1 << 26; + /// Not tried yet. + const UNKNOWN: u8 = 0; + /// It worked once, so ENOENT is the file's own error from now on. + const WORKS: u8 = 1; + /// The kernel ignored the flag and refused the empty path. + const MISSING: u8 = 2; +} + +/// The state of [`EmptyPath`] for this process. +static EMPTYPATH: AtomicU8 = AtomicU8::new(EmptyPath::UNKNOWN); + +/// The directory on the host the files of a manifest are taken from: the +/// one the manifest lives in, or the one the caller chose instead. It is +/// opened once and never looked up again, and each file below it is +/// pinned before it is opened. +/// +/// A [`DirectoryProvider`](crate::DirectoryProvider) reads the data of the +/// files from it. The copy of an object fails with +/// [`SourceProblem::Missing`] where its file is not there, with +/// [`SourceProblem::NotRegular`] where it is not a regular file, such as a +/// directory or a FIFO, and with [`DataProblem::SizeMismatch`] where it is +/// too short for the data the manifest says it holds. Unless symbolic +/// links are followed, see [`PinnedDirectory::follow_symlinks`], a name +/// that leads through one fails with [`SourceProblem::Unreadable`], and +/// [`Error::io_error`] gives ELOOP. +/// +/// It exists on Linux only, not on Android. +/// +/// [`SourceProblem::Missing`]: crate::SourceProblem::Missing +/// [`SourceProblem::NotRegular`]: crate::SourceProblem::NotRegular +/// [`SourceProblem::Unreadable`]: crate::SourceProblem::Unreadable +/// [`DataProblem::SizeMismatch`]: crate::DataProblem::SizeMismatch +/// [`Error::io_error`]: crate::Error::io_error +#[derive(Debug)] +pub struct PinnedDirectory { + root: Root, +} + +impl PinnedDirectory { + /// How a file is opened once it is pinned and known to be a regular + /// file: for reading, without waiting for anything, and without + /// becoming the controlling terminal. + const OPEN_FLAGS: OpenFlags = OpenFlags::O_RDONLY + .union(OpenFlags::O_NONBLOCK) + .union(OpenFlags::O_NOCTTY); + /// The same for the reopen through rustix, with O_CLOEXEC, which + /// pathrs adds on its own. + const REOPEN_FLAGS: OFlags = OFlags::RDONLY + .union(OFlags::NONBLOCK) + .union(OFlags::NOCTTY) + .union(OFlags::CLOEXEC); + /// How [`PinnedDirectory::open`] opens the directory: as a handle that + /// nothing is read through, for a directory and nothing else. + const DIRECTORY_FLAGS: OFlags = OFlags::PATH.union(OFlags::DIRECTORY).union(OFlags::CLOEXEC); + /// What the root file object is resolved as, which has the empty name: + /// the directory itself. + const ITSELF: &'static str = "."; + + /// The files below the open directory `dir`, which the caller resolved + /// once and which is never looked up again. A name is resolved below it + /// the way systemd's chase() resolves a path below a root: an absolute + /// symbolic link target starts over at `dir`, `..` at `dir` stays + /// there, nothing resolves to anything outside it, and symbolic links + /// are followed only when [`PinnedDirectory::follow_symlinks`] allows + /// them. Magic links, such as those below `/proc/self/fd`, are never + /// followed. + /// + /// `dir` has to be a directory, as [`PinnedDirectory::open`] makes + /// sure: below anything else every file fails to open. + pub fn new(dir: OwnedFd) -> PinnedDirectory { + PinnedDirectory { + root: Root::from_fd(dir).with_resolver_flags(ResolverFlags::NO_SYMLINKS), + } + } + + /// Opens the directory `path` and pins the files below it, see + /// [`PinnedDirectory::new`]. The directory is opened with O_PATH, so it + /// needs no read permission, and with O_DIRECTORY, so a path that is + /// not a directory fails here, with ENOTDIR. + pub fn open(path: impl AsRef) -> io::Result { + let dir = rustix::fs::open(path.as_ref(), PinnedDirectory::DIRECTORY_FLAGS, Mode::empty())?; + Ok(PinnedDirectory::new(dir)) + } + + /// Follows symbolic links, resolved as if the directory were the root: + /// a link that points out of the directory leads to what has that path + /// inside it instead. Off by default: a link planted in a tree would + /// otherwise make a privileged copy read any file below the directory, + /// such as one the planter cannot read. + #[must_use] + pub fn follow_symlinks(mut self, follow: bool) -> PinnedDirectory { + let flags = if follow { + ResolverFlags::empty() + } else { + ResolverFlags::NO_SYMLINKS + }; + self.root.set_resolver_flags(flags); + self + } + + /// Pins the file `file` names below the directory and checks that it + /// is a regular file. Returns it with its size. + fn pin(&self, file: &Name) -> Result<(Handle, u64), OpenError> { + let path = if file.is_root() { + PinnedDirectory::ITSELF + } else { + file.as_str() + }; + let pinned = self.root.resolve(path).map_err(PinnedDirectory::io_error)?; + let stat = rustix::fs::fstat(&pinned).map_err(io::Error::from)?; + if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile { + return Err(OpenError::NotRegular); + } + // The size of a regular file is never negative. + let len = u64::try_from(stat.st_size).map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?; + Ok((pinned, len)) + } + + /// Opens the regular file `pinned` refers to for reading: through + /// O_EMPTYPATH where the kernel has it, probed the way systemd's + /// fd_reopen() does, and with the checked reopen of pathrs through + /// procfs where it does not. + fn reopen(pinned: &Handle) -> io::Result { + let state = EMPTYPATH.load(Ordering::Relaxed); + if state != EmptyPath::MISSING { + let flags = PinnedDirectory::REOPEN_FLAGS | OFlags::from_bits_retain(EmptyPath::FLAG); + match rustix::fs::openat(pinned, "", flags, Mode::empty()) { + Ok(fd) => { + EMPTYPATH.store(EmptyPath::WORKS, Ordering::Relaxed); + return Ok(File::from(fd)); + } + // An older kernel ignores the flag and refuses the empty + // path. Once it worked, ENOENT comes from the file itself. + Err(Errno::NOENT) if state != EmptyPath::WORKS => { + EMPTYPATH.store(EmptyPath::MISSING, Ordering::Relaxed); + } + Err(e) => return Err(e.into()), + } + } + pinned + .reopen(PinnedDirectory::OPEN_FLAGS) + .map_err(PinnedDirectory::io_error) + } + + /// The error `error` of pathrs as an I/O error: that of the system call + /// that failed, or the error of pathrs itself where none did. + fn io_error(error: PathrsError) -> io::Error { + match error.kind() { + PathrsErrorKind::OsError(Some(errno)) => io::Error::from_raw_os_error(errno), + _ => io::Error::other(error), + } + } +} + +impl Directory for PinnedDirectory { + type File = File; + + /// Opens the file: pinned, checked to be a regular file, and only then + /// opened for reading. + fn open(&self, file: &Name) -> Result<(File, u64), OpenError> { + let (pinned, len) = self.pin(file)?; + Ok((PinnedDirectory::reopen(&pinned)?, len)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rustix::fs::CWD; + use std::fs; + use std::io::Read; + use std::os::unix::fs::symlink; + use std::path::PathBuf; + + /// A directory of its own below the temporary directory, removed with + /// everything in it when the test ends. + struct TempDir(PathBuf); + + impl TempDir { + fn new(name: &str) -> TempDir { + let path = std::env::temp_dir().join(format!("uapi16-{}-{}", name, std::process::id())); + // What a test of the same name in a process of the same number + // left behind. + let _ = fs::remove_dir_all(&path); + fs::create_dir(&path).unwrap(); + TempDir(path) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + /// What `dir` has under `name`: the text of a regular file, or why it + /// has none. + fn text(dir: &PinnedDirectory, name: &str) -> Result { + let (mut file, len) = dir.open(&Name::new(name).unwrap()).map_err(Opened::from)?; + let mut text = String::new(); + file.read_to_string(&mut text).unwrap(); + assert_eq!(text.len() as u64, len, "{}", name); + Ok(text) + } + + /// Why a file was not opened, in a form a test compares. + #[derive(Debug, PartialEq)] + enum Opened { + NotRegular, + Errno(i32), + } + + impl From for Opened { + fn from(e: OpenError) -> Opened { + match e { + OpenError::NotRegular => Opened::NotRegular, + OpenError::Io(e) => Opened::Errno(e.raw_os_error().unwrap_or_else(|| panic!("{:?}", e))), + } + } + } + + /// The escapes a resolution below the directory has to refuse, and the + /// errors it refuses them with. + #[test] + fn stays_below_the_directory() { + let tmp = TempDir::new("pinned"); + let dir = &tmp.0; + fs::create_dir_all(dir.join("root/sub/deep")).unwrap(); + fs::write(dir.join("root/sub/deep/file"), b"inside").unwrap(); + fs::write(dir.join("root/top"), b"top").unwrap(); + fs::write(dir.join("outside"), b"outside").unwrap(); + symlink("deep/file", dir.join("root/sub/rel")).unwrap(); + symlink("/top", dir.join("root/sub/abs")).unwrap(); + symlink("../../outside", dir.join("root/sub/up")).unwrap(); + symlink(dir.join("outside"), dir.join("root/sub/far")).unwrap(); + symlink("loop", dir.join("root/loop")).unwrap(); + symlink("/proc/self/fd/0", dir.join("root/magic")).unwrap(); + let plain = PinnedDirectory::open(dir.join("root")).unwrap(); + assert_eq!(text(&plain, "sub/deep/file").as_deref(), Ok("inside")); + assert_eq!(text(&plain, "top").as_deref(), Ok("top")); + // A directory is not a regular file, and neither is the directory + // itself, which the root file object names. + assert_eq!(text(&plain, "sub"), Err(Opened::NotRegular)); + assert_eq!( + plain.open(&Name::ROOT).map(|_| ()).map_err(Opened::from), + Err(Opened::NotRegular) + ); + assert_eq!(text(&plain, "missing"), Err(Opened::Errno(libc::ENOENT))); + assert_eq!(text(&plain, "top/x"), Err(Opened::Errno(libc::ENOTDIR))); + // Without following, every symbolic link is a dead end. + for link in ["sub/rel", "sub/abs", "sub/up", "sub/far", "loop", "magic"] { + assert_eq!(text(&plain, link), Err(Opened::Errno(libc::ELOOP)), "{}", link); + } + // Following stays inside the directory: an absolute target starts at + // the directory, ".." above it stays there, and a target that leads + // outside is looked for inside. + let following = PinnedDirectory::open(dir.join("root")).unwrap().follow_symlinks(true); + assert_eq!(text(&following, "sub/rel").as_deref(), Ok("inside")); + assert_eq!(text(&following, "sub/abs").as_deref(), Ok("top")); + assert_eq!(text(&following, "sub/up"), Err(Opened::Errno(libc::ENOENT))); + assert_eq!(text(&following, "sub/far"), Err(Opened::Errno(libc::ENOENT))); + assert_eq!(text(&following, "loop"), Err(Opened::Errno(libc::ELOOP))); + assert_eq!(text(&following, "magic"), Err(Opened::Errno(libc::ENOENT))); + // Following can be turned off again. + let plain = following.follow_symlinks(false); + assert_eq!(text(&plain, "sub/rel"), Err(Opened::Errno(libc::ELOOP))); + } + + /// A magic link is refused even where the directory is /proc, and the + /// directories of procfs are not regular files. + #[test] + fn follows_no_magic_links() { + if rustix::fs::statfs("/proc").unwrap().f_type != rustix::fs::PROC_SUPER_MAGIC { + return; + } + let following = PinnedDirectory::open("/proc").unwrap().follow_symlinks(true); + assert_eq!(text(&following, "self/fd/0"), Err(Opened::Errno(libc::ELOOP))); + assert_eq!(text(&following, "self/fd"), Err(Opened::NotRegular)); + let plain = following.follow_symlinks(false); + assert_eq!(text(&plain, "self/fd/0"), Err(Opened::Errno(libc::ELOOP))); + } + + /// A pinned file is reopened whichever way the kernel offers, also after + /// it was unlinked or replaced under its name. + #[test] + fn reopens_what_was_pinned() { + let tmp = TempDir::new("pinned-reopen"); + let dir = &tmp.0; + fs::write(dir.join("file"), b"pinned").unwrap(); + let directory = PinnedDirectory::open(dir).unwrap(); + let read = |file: &mut File| { + let mut text = String::new(); + file.read_to_string(&mut text).unwrap(); + text + }; + for state in [EmptyPath::UNKNOWN, EmptyPath::MISSING] { + EMPTYPATH.store(state, Ordering::Relaxed); + let (handle, _) = directory.pin(&Name::new("file").unwrap()).unwrap(); + fs::rename(dir.join("file"), dir.join("moved")).unwrap(); + fs::write(dir.join("file"), b"impostor").unwrap(); + assert_eq!(read(&mut PinnedDirectory::reopen(&handle).unwrap()), "pinned"); + fs::remove_file(dir.join("moved")).unwrap(); + assert_eq!(read(&mut PinnedDirectory::reopen(&handle).unwrap()), "pinned"); + fs::write(dir.join("file"), b"pinned").unwrap(); + } + EMPTYPATH.store(EmptyPath::UNKNOWN, Ordering::Relaxed); + } + + /// Only a directory is pinned: anything else fails right away, where + /// every file below it would fail to open later. + #[test] + fn pins_only_directories() { + let tmp = TempDir::new("pinned-open"); + let dir = &tmp.0; + fs::write(dir.join("file"), b"data").unwrap(); + let e = PinnedDirectory::open(dir.join("file")).unwrap_err(); + assert_eq!(e.raw_os_error(), Some(libc::ENOTDIR)); + let directory = PinnedDirectory::open(dir).unwrap(); + assert_eq!(text(&directory, "file").as_deref(), Ok("data")); + } + + /// Nothing but a regular file is opened: a FIFO, whose open would wait + /// for a writer, is not a regular file and is never opened. + #[test] + fn opens_only_regular_files() { + let tmp = TempDir::new("pinned-fifo"); + let dir = &tmp.0; + let fifo = dir.join("fifo"); + rustix::fs::mknodat(CWD, &fifo, FileType::Fifo, Mode::RUSR | Mode::WUSR, 0).unwrap(); + fs::write(dir.join("file"), b"data").unwrap(); + let directory = PinnedDirectory::open(dir).unwrap(); + assert_eq!(text(&directory, "fifo"), Err(Opened::NotRegular)); + assert_eq!(text(&directory, "file").as_deref(), Ok("data")); + // The file is the one that was pinned, open for reading only. + let (file, len) = directory.open(&Name::new("file").unwrap()).unwrap(); + assert_eq!(len, 4); + let flags = rustix::fs::fcntl_getfl(&file).unwrap(); + assert_eq!(flags & OFlags::RWMODE, OFlags::RDONLY); + assert!(flags.contains(OFlags::NONBLOCK)); + } +} diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 39fdb37..01b9b73 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -30,8 +30,13 @@ //! and a file object both have is in [`InodeAttributes`] and //! [`ValidityWindow`]. //! - [`DataProvider`] is where the data of the files comes from when a -//! manifest is applied: [`DirectoryProvider`] for the files next to the -//! manifest and [`StreamProvider`] for one stream with all of them. +//! manifest is applied. [`StreamProvider`] takes it from one stream +//! that carries it all. +#![cfg_attr( + target_os = "linux", + doc = " On Linux, [`DirectoryProvider`] takes it from the files next to the", + doc = " manifest, in a [`PinnedDirectory`]." +)] //! [`FileObject::copy_data`] copies the data of a file and checks it //! against the manifest with a [`DataCheck`]. //! @@ -98,6 +103,8 @@ mod blocking; mod content; mod decode; mod digest; +#[cfg(target_os = "linux")] +mod directory; mod error; mod features; mod hex; @@ -109,10 +116,12 @@ mod strict; mod writer; pub use blocking::{Reader, Writer}; -pub use content::{ - DataCheck, DataLocation, DataProvider, Directory, DirectoryProvider, ExternalFile, OpenError, StreamProvider, -}; +pub use content::{DataCheck, DataLocation, DataProvider, ExternalFile, StreamProvider}; +#[cfg(target_os = "linux")] +pub use content::{Directory, DirectoryProvider, OpenError}; pub use digest::{InvalidDigest, Sha256, Sha256Context}; +#[cfg(target_os = "linux")] +pub use directory::PinnedDirectory; pub use error::{DataProblem, Error, ErrorKind, Field, Problem, SourceProblem, UnsupportedData, ValidityProblem}; pub use features::{Features, Order, UnknownFeature}; pub use name::{Name, NameProblem}; From 82a9035bba18396498a57184262b2cca2bd759e0 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 18:15:48 +0100 Subject: [PATCH 22/32] uapi16: seal DataProvider and make Directory private Directory and DataProvider are public traits, so any crate can implement them, and the crate could never add a method to either without breaking those implementations. Nobody needs to implement them: the only implementation outside of the crate was ufat's PinnedDirectory, which the previous commit brought into the crate. And a DirectoryProvider relies on its Directory to resolve names below the directory and nowhere else, which is easy to get wrong. So seal DataProvider with a private supertrait. The crate implements it for DirectoryProvider, StreamProvider and the providers of its tests, and the docs of the trait say that it is sealed. Directory goes further and becomes the crate's own, with OpenError. A sealed trait can still be called: generic code over D: Directory calls open() of whatever directory it is handed. PinnedDirectory is the only directory a caller has, so a public trait would only add API that can be called. DirectoryProvider takes a PinnedDirectory and loses its type parameter. A private Provider does the work, and the tests use it with their directory in memory. A public struct bounded by a private trait would trip the private_bounds lint, which the newtype avoids. Opening the trait up again later is a minor change: a public Directory and DirectoryProvider. Callers that use DirectoryProvider::new() with a PinnedDirectory keep working as they are. Where they spell out the type, as DirectoryProvider, they drop the type parameter. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/content.rs | 117 +++++++++++++++++++++++++++++++----------- src/uapi16/lib.rs | 4 +- 2 files changed, 88 insertions(+), 33 deletions(-) diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index e65d1fd..94ec7b1 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -12,6 +12,8 @@ use std::io::{Seek, SeekFrom}; use std::ops::Range; use crate::digest::Sha256Context; +#[cfg(target_os = "linux")] +use crate::directory::PinnedDirectory; use crate::error::{DataProblem, Error, ErrorKind, Field, SourceProblem, UnsupportedData}; use crate::object::{ContentsObject, ContentsSource, FileObject, InodeType}; use crate::{Name, Sha256}; @@ -493,6 +495,13 @@ impl Write for CheckedSink<'_, '_> { } } +/// What keeps [`DataProvider`] to the types of this crate: a supertrait +/// that no other crate can name. +pub(crate) mod sealed { + /// Implemented by the providers of this crate, and by no other type. + pub trait Sealed {} +} + /// Has the data of the file objects whose data is outside of the /// manifest. /// @@ -507,7 +516,10 @@ impl Write for CheckedSink<'_, '_> { /// which calls [`DataProvider::copy`], and the others to /// [`DataProvider::skip`]. After the last one it calls /// [`DataProvider::end`]. -pub trait DataProvider { +/// +/// The trait is sealed: the providers of this crate implement it, and it +/// is not meant to be implemented anywhere else. +pub trait DataProvider: sealed::Sealed { /// Writes the data of `object`, which is in `file`, to `sink`: exactly /// `object.size()` bytes when the object has a size. An error of the /// sink comes back as it was, and one of the provider names the @@ -530,12 +542,9 @@ pub trait DataProvider { } /// Why a [`Directory`] does not hand out a file. -/// -/// It exists on Linux only, not on Android. #[cfg(target_os = "linux")] #[derive(Debug)] -#[non_exhaustive] -pub enum OpenError { +pub(crate) enum OpenError { /// What the name names is not a regular file. NotRegular, /// The file could not be reached. An error of the kind `NotFound` or @@ -555,12 +564,14 @@ impl From for OpenError { /// /// A manifest is not to be trusted to stay inside that directory. The /// names it gives are normalized relative paths, see [`Name`], but a -/// symbolic link in the directory can still lead out of it. It is on the -/// implementation to resolve a name below the directory and nowhere else. +/// symbolic link in the directory can still lead out of it. A name has to +/// be resolved below the directory and nowhere else, which +/// [`PinnedDirectory`] does. /// -/// It exists on Linux only, not on Android. +/// The trait is the crate's own: [`PinnedDirectory`] is the one directory +/// a caller has, and the tests have one in memory. #[cfg(target_os = "linux")] -pub trait Directory { +pub(crate) trait Directory { /// A file of the directory, open for reading. type File: Read + Seek; @@ -570,7 +581,7 @@ pub trait Directory { } /// Takes the data of file objects from the files next to the manifest, -/// in a [`Directory`]. +/// in a [`PinnedDirectory`]. /// /// The data of an object is the part of its file that starts at the /// offset its contents object gives and is as long as the object says, @@ -599,7 +610,35 @@ pub trait Directory { /// /// It exists on Linux only, not on Android. #[cfg(target_os = "linux")] -pub struct DirectoryProvider { +#[derive(Debug)] +pub struct DirectoryProvider { + inner: Provider, +} + +#[cfg(target_os = "linux")] +impl sealed::Sealed for DirectoryProvider {} + +#[cfg(target_os = "linux")] +impl DirectoryProvider { + /// A provider that takes the files from `directory`. + pub fn new(directory: PinnedDirectory) -> DirectoryProvider { + DirectoryProvider { + inner: Provider::new(directory), + } + } +} + +#[cfg(target_os = "linux")] +impl DataProvider for DirectoryProvider { + fn copy(&mut self, object: &FileObject, file: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error> { + self.inner.copy(object, file, sink) + } +} + +/// What a [`DirectoryProvider`] is, over any [`Directory`], so that the +/// tests can give it one in memory. +#[cfg(target_os = "linux")] +struct Provider { directory: D, /// What a copy goes through, made when the first file is copied. buffer: Vec, @@ -608,10 +647,10 @@ pub struct DirectoryProvider { } #[cfg(target_os = "linux")] -impl DirectoryProvider { +impl Provider { /// A provider that takes the files from `directory`. - pub fn new(directory: D) -> DirectoryProvider { - DirectoryProvider { + fn new(directory: D) -> Provider { + Provider { directory, buffer: Vec::new(), hashes: PieceHashes::default(), @@ -620,9 +659,9 @@ impl DirectoryProvider { } #[cfg(target_os = "linux")] -impl fmt::Debug for DirectoryProvider { +impl fmt::Debug for Provider { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("DirectoryProvider") + f.debug_struct("Provider") .field("directory", &self.directory) .field( "buffer", @@ -939,7 +978,9 @@ impl Pieces<'_, F> { } #[cfg(target_os = "linux")] -impl DataProvider for DirectoryProvider { +impl Provider { + /// Copies the data of `object`, which is in `file`, to `sink`, see + /// [`DataProvider::copy`]. fn copy(&mut self, object: &FileObject, file: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error> { let (opened, len) = self .directory @@ -1012,6 +1053,8 @@ pub struct StreamProvider { last: Option<(String, u64)>, } +impl sealed::Sealed for StreamProvider {} + impl StreamProvider { /// A provider that takes the data from `reader`. pub fn new(reader: R) -> StreamProvider { @@ -1252,6 +1295,16 @@ mod tests { } } + impl sealed::Sealed for Provider<&Files> {} + + /// The tests copy through a provider over the files in memory, which + /// does what a [`DirectoryProvider`] does. + impl DataProvider for Provider<&Files> { + fn copy(&mut self, object: &FileObject, file: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error> { + Provider::copy(self, object, file, sink) + } + } + /// A provider over a reference to the files, so that a test can look /// at them and change them while the provider has them. impl Directory for &Files { @@ -1455,7 +1508,7 @@ mod tests { assert!(some[0].has_external_data()); assert_eq!(some[1].data_location().unwrap(), DataLocation::Literal(b"x")); let files = Files::of(&[("d.Uapi16Manifest", b"abc")]); - let mut provider = DirectoryProvider::new(&files); + let mut provider = Provider::new(&files); assert_eq!(copy(&some[0], &mut provider).unwrap(), b"abc"); assert_eq!(copy(&some[1], &mut provider).unwrap(), b"x"); } @@ -1463,7 +1516,7 @@ mod tests { #[test] fn copies_from_a_directory() { let files = Files::of(&[("a", b"hello world"), ("empty", b""), ("dir/b", b"hello")]); - let mut provider = DirectoryProvider::new(&files); + let mut provider = Provider::new(&files); for (record, data) in [ // A whole file, by the name of the object and by a file external. (format!(r#"{{"name":"dir/b","size":5,"sha256":"{}"}}"#, HELLO), "hello"), @@ -1531,7 +1584,7 @@ mod tests { #[test] fn files_that_are_not_what_the_manifest_says() { let files = Files::of(&[("a", b"hello world"), ("dir/b", b"hello")]); - let mut provider = DirectoryProvider::new(&files); + let mut provider = Provider::new(&files); let size = ErrorKind::Data(DataProblem::SizeMismatch); let hash = ErrorKind::Data(DataProblem::HashMismatch); for (record, expected) in [ @@ -1697,7 +1750,7 @@ mod tests { #[test] fn files_that_change_while_they_are_read() { let files = Files::default(); - let mut provider = DirectoryProvider::new(&files); + let mut provider = Provider::new(&files); let changed = |file: &str| { ( ErrorKind::Data(DataProblem::SourceChanged), @@ -1800,7 +1853,7 @@ mod tests { trouble: Trouble::Stall, }; let files = Files::default(); - let mut provider = DirectoryProvider::new(&files); + let mut provider = Provider::new(&files); let changed = ( ErrorKind::Data(DataProblem::SourceChanged), Some("x"), @@ -1859,7 +1912,7 @@ mod tests { trouble: Trouble::FailRead(libc::EIO), }, ); - let mut provider = DirectoryProvider::new(&files); + let mut provider = Provider::new(&files); let o = object(r#"{"name":"x","size":11,"contents":[{"file":"bad"}]}"#); let e = copy(&o, &mut provider).unwrap_err(); assert_eq!( @@ -1946,7 +1999,7 @@ mod tests { let whole = Sha256::digest(&blob); let files = Files::default(); files.put("blob", Entry::File(blob[..].into())); - let mut provider = DirectoryProvider::new(&files); + let mut provider = Provider::new(&files); let part = |offset: usize, size: usize, total: usize, sha256: Option| { let sha256 = sha256.map(|sha256| format!(r#","originalSha256":"{}""#, sha256)); object(&format!( @@ -2052,7 +2105,7 @@ mod tests { HELLO ), ] { - let mut provider = DirectoryProvider::new(&small); + let mut provider = Provider::new(&small); for _ in 0..2 { assert_eq!(copy(&object(&record), &mut provider).unwrap(), b"hello", "{}", record); assert_eq!(small.read(), 5); @@ -2189,7 +2242,7 @@ mod tests { // file, and nothing is kept of it. let names = ["a", "b", "c", "d"]; let files = Files::of(&names.map(|name| (name, &b"ab"[..]))); - let mut provider = DirectoryProvider::new(&files); + let mut provider = Provider::new(&files); for name in names { let o = object(&format!( r#"{{"name":"x","size":1,"contents":[{{"file":"{}","offset":1,"originalSize":2,"originalSha256":"{}"}}]}}"#, @@ -2224,7 +2277,7 @@ mod tests { files.put("odd", Entry::Fails(libc::EINVAL)); files.put("link", Entry::Fails(libc::ELOOP)); files.put("secret", Entry::Fails(libc::EACCES)); - let mut provider = DirectoryProvider::new(&files); + let mut provider = Provider::new(&files); for (file, problem, errno, text) in [ ( "missing", @@ -2473,7 +2526,7 @@ mod tests { assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::NoSize)); // A directory has nothing to read past. let files = Files::of(&[("a", b"hello")]); - DirectoryProvider::new(&files).skip(&all[0]).unwrap(); + Provider::new(&files).skip(&all[0]).unwrap(); assert_eq!(files.read(), 0); } @@ -2483,6 +2536,8 @@ mod tests { careful: bool, } + impl sealed::Sealed for Babbler {} + impl DataProvider for Babbler { fn copy(&mut self, _: &FileObject, _: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error> { let written = sink.write_all(b"hello world"); @@ -2603,10 +2658,10 @@ mod tests { let literal = object(r#"{"name":"l","contents":[{"literal":"aGVsbG8="}]}"#); let files = Files::of(&[("a", b"hello")]); let nothing = Files::default(); - let mut directory = DirectoryProvider::new(&files); + let mut directory = Provider::new(&files); let mut stream = &b"hello"[..]; let mut stream = StreamProvider::new(&mut stream); - let mut empty = DirectoryProvider::new(¬hing); + let mut empty = Provider::new(¬hing); let sources: [(&FileObject, &mut dyn DataProvider); 3] = [(&o, &mut directory), (&o, &mut stream), (&literal, &mut empty)]; for (object, provider) in sources { @@ -2621,7 +2676,7 @@ mod tests { #[test] fn debug_shows_no_buffers() { let files = Files::of(&[("a", b"hello")]); - let mut provider = DirectoryProvider::new(&files); + let mut provider = Provider::new(&files); copy(&object(r#"{"name":"a","size":5}"#), &mut provider).unwrap(); let text = format!("{:?}", provider); assert!(text.len() < 500, "{}", text); diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 01b9b73..0a5ec4b 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -116,9 +116,9 @@ mod strict; mod writer; pub use blocking::{Reader, Writer}; -pub use content::{DataCheck, DataLocation, DataProvider, ExternalFile, StreamProvider}; #[cfg(target_os = "linux")] -pub use content::{Directory, DirectoryProvider, OpenError}; +pub use content::DirectoryProvider; +pub use content::{DataCheck, DataLocation, DataProvider, ExternalFile, StreamProvider}; pub use digest::{InvalidDigest, Sha256, Sha256Context}; #[cfg(target_os = "linux")] pub use directory::PinnedDirectory; From f8113c6276917cf1c94d0b49339d3c6539597016 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 18:16:13 +0100 Subject: [PATCH 23/32] uapi16: refuse to build for anything but Linux and Android uapi16 is built and tested on Linux, and built for Android. Nothing else is, and reading the data of the files next to a manifest needs Linux anyway. Rather than let it build somewhere nobody ever checked, refuse every target_os but linux and android with a compile_error!(). Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/lib.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 0a5ec4b..ce19b25 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -98,6 +98,9 @@ #![deny(unsafe_code)] #![warn(missing_docs)] +#[cfg(not(any(target_os = "linux", target_os = "android")))] +compile_error!("uapi16 supports Linux and Android only"); + mod base64; mod blocking; mod content; From 4119a65ede2d3ceeae53cc917d51b569bcbd4491 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 21:46:25 +0100 Subject: [PATCH 24/32] uapi16: tell the inode type of a file from its metadata A caller that writes a manifest for the files on disk has their metadata, and needs the inode type of each. Add TryFrom for InodeType, with std's FileTypeExt for the types that are Unix's own: a regular file, a directory, a symbolic link, a FIFO, a character or a block device and a socket each have theirs, and anything else fails with UnknownInodeType. Its docs now say that it is a string or a file type that is not an inode type. The temporary directory of the tests of PinnedDirectory moves into the module the tests share, so the tests of object.rs make their files in one too. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/directory.rs | 23 +-------------- src/uapi16/lib.rs | 23 +++++++++++++++ src/uapi16/object.rs | 63 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 86 insertions(+), 23 deletions(-) diff --git a/src/uapi16/directory.rs b/src/uapi16/directory.rs index 1da098b..f6de553 100644 --- a/src/uapi16/directory.rs +++ b/src/uapi16/directory.rs @@ -195,32 +195,11 @@ impl Directory for PinnedDirectory { #[cfg(test)] mod tests { use super::*; + use crate::testing::TempDir; use rustix::fs::CWD; use std::fs; use std::io::Read; use std::os::unix::fs::symlink; - use std::path::PathBuf; - - /// A directory of its own below the temporary directory, removed with - /// everything in it when the test ends. - struct TempDir(PathBuf); - - impl TempDir { - fn new(name: &str) -> TempDir { - let path = std::env::temp_dir().join(format!("uapi16-{}-{}", name, std::process::id())); - // What a test of the same name in a process of the same number - // left behind. - let _ = fs::remove_dir_all(&path); - fs::create_dir(&path).unwrap(); - TempDir(path) - } - } - - impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } - } /// What `dir` has under `name`: the text of a regular file, or why it /// has none. diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index ce19b25..1a21f2d 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -179,7 +179,30 @@ pub(crate) mod testing { use crate::strict::{ParseError, Skip, Strict}; use serde_core::de::DeserializeSeed; use std::collections::BTreeMap; + use std::fs; use std::num::NonZeroU64; + use std::path::PathBuf; + + /// A directory of its own below the temporary directory, removed with + /// everything in it when the test ends. + pub(crate) struct TempDir(pub(crate) PathBuf); + + impl TempDir { + pub(crate) fn new(name: &str) -> TempDir { + let path = std::env::temp_dir().join(format!("uapi16-{}-{}", name, std::process::id())); + // What a test of the same name in a process of the same number + // left behind. + let _ = fs::remove_dir_all(&path); + fs::create_dir(&path).unwrap(); + TempDir(path) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } /// The root file object that says nothing but that this is a manifest. pub(crate) const ROOT: &str = r#"{"mediaType":"application/vnd.uapi.16.manifest"}"#; diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 6860886..862b9b6 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -3,8 +3,10 @@ use std::collections::BTreeMap; use std::fmt; +use std::fs; use std::num::NonZeroU64; use std::ops::{BitAnd, BitOr, Not}; +use std::os::unix::fs::FileTypeExt; use std::str::FromStr; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -33,7 +35,7 @@ pub enum InodeType { Socket, } -/// A string that is not the name of an inode type. +/// A string or a file type that is not an inode type, see [`InodeType`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct UnknownInodeType(()); @@ -97,6 +99,39 @@ impl FromStr for InodeType { } } +/// The inode type of a file, from the file type its metadata gives. +/// +/// ``` +/// use uapi16::InodeType; +/// +/// let metadata = std::fs::symlink_metadata("/")?; +/// assert_eq!(InodeType::try_from(metadata.file_type()), Ok(InodeType::Directory)); +/// # Ok::<(), std::io::Error>(()) +/// ``` +impl TryFrom for InodeType { + type Error = UnknownInodeType; + + fn try_from(file_type: fs::FileType) -> Result { + Ok(if file_type.is_file() { + InodeType::Regular + } else if file_type.is_dir() { + InodeType::Directory + } else if file_type.is_symlink() { + InodeType::Symlink + } else if file_type.is_fifo() { + InodeType::Fifo + } else if file_type.is_char_device() { + InodeType::CharDevice + } else if file_type.is_block_device() { + InodeType::BlockDevice + } else if file_type.is_socket() { + InodeType::Socket + } else { + return Err(UnknownInodeType(())); + }) + } +} + /// The access mode of a file object, its `mode` field: the permission /// bits with the set-user-ID, the set-group-ID and the sticky bit. /// @@ -2178,6 +2213,32 @@ mod tests { } } + /// The types of file a test makes without help, and a device node every + /// system has. FileObject::from_metadata() is tested with a FIFO as well. + #[test] + fn inode_types_of_files() { + use crate::testing::TempDir; + use std::os::unix::fs::symlink; + use std::os::unix::net::UnixListener; + + let tmp = TempDir::new("inode-types"); + let dir = &tmp.0; + fs::write(dir.join("file"), b"").unwrap(); + fs::create_dir(dir.join("dir")).unwrap(); + symlink("file", dir.join("link")).unwrap(); + let _socket = UnixListener::bind(dir.join("socket")).unwrap(); + for (path, inode_type) in [ + (dir.join("file"), InodeType::Regular), + (dir.join("dir"), InodeType::Directory), + (dir.join("link"), InodeType::Symlink), + (dir.join("socket"), InodeType::Socket), + ("/dev/null".into(), InodeType::CharDevice), + ] { + let file_type = fs::symlink_metadata(&path).unwrap().file_type(); + assert_eq!(InodeType::try_from(file_type), Ok(inode_type), "{}", path.display()); + } + } + #[test] fn modes() { for bits in [0, 0o644, 0o755, 0o4755, 0o7777] { From 9f6a6832f2a801a51b86093aa085b74d14a1716d Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 21:49:48 +0100 Subject: [PATCH 25/32] uapi16: make a file object from the metadata of a file With the type of a file comes the rest of what its metadata says. Add FileObject::from_metadata(), which makes the file object for a file from its std::fs::Metadata, with the fields that the features it is given record and no others. Callers pass the features of the manifest, root.recorded_features(), so the writer refuses none of the fields it fills in for that manifest. It follows the rules for the fields of each inode type that the reader and the writer check: - the access mode, st_mode without the bits of the file type, on everything but a symbolic link - the user and the group ID of the owner - the modification time, where mTimeNSec can express it - the size of a regular file - the major and the minor number of a device node, which rustix splits st_rdev into It sets no hash, no target of a symbolic link and no inode token, which take more than the metadata of one file. A manifest that records symlink or hardlink, as the default features do, needs them from the caller: a writer refuses a symbolic link without its target there, and takes an object without a token for a file of no other name. The docs say so. The mode comes from a crate-private Mode::from_st_mode(), which drops the bits of the file type itself, so there is no error to handle. rustix becomes a dependency on Android as well, for major() and minor(), and pathrs stays on Linux. Cargo.lock doesn't change: on Android rustix only takes crates the lock has already. The test makes every type of file it can make without privileges and looks at /dev/null for a device node. It makes the objects with no features, the default ones and all of them, checks their fields, and writes them for a manifest that records the same features. Signed-off-by: Christian Brauner (Amutable) --- Cargo.toml | 3 +- src/uapi16/Cargo.toml | 3 + src/uapi16/lib.rs | 1 + src/uapi16/metadata.rs | 141 +++++++++++++++++++++++++++++++++++++++++ src/uapi16/object.rs | 7 ++ 5 files changed, 154 insertions(+), 1 deletion(-) create mode 100644 src/uapi16/metadata.rs diff --git a/Cargo.toml b/Cargo.toml index 1e12740..a8ed7c5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,8 @@ libc = "0.2.191" # directory, for PinnedDirectory. It builds on Linux only. pathrs = "0.2.6" # Tells what pathrs resolved apart before it is opened, and reopens it -# through O_EMPTYPATH. +# through O_EMPTYPATH. Splits the device number of a file into its major +# and minor numbers, for FileObject::from_metadata(). rustix = "1.1.6" # Reads and writes JSON. What a manifest asks for beyond JSON is checked # by src/uapi16/strict.rs. Never turn on arbitrary_precision: serde_json diff --git a/src/uapi16/Cargo.toml b/src/uapi16/Cargo.toml index 625309b..952e1a7 100644 --- a/src/uapi16/Cargo.toml +++ b/src/uapi16/Cargo.toml @@ -20,6 +20,9 @@ sha2.workspace = true # PinnedDirectory, which only Linux has. [target.'cfg(target_os = "linux")'.dependencies] pathrs.workspace = true + +# PinnedDirectory, and the device numbers of FileObject::from_metadata(). +[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies] rustix = { workspace = true, features = ["fs"] } [dev-dependencies] diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 1a21f2d..59183ba 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -111,6 +111,7 @@ mod directory; mod error; mod features; mod hex; +mod metadata; mod name; mod object; mod reader; diff --git a/src/uapi16/metadata.rs b/src/uapi16/metadata.rs new file mode 100644 index 0000000..24c2135 --- /dev/null +++ b/src/uapi16/metadata.rs @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! File objects from what the file system says of a file. + +use std::fs::Metadata; +use std::os::unix::fs::MetadataExt; + +use crate::object::{FileObject, InodeType, Mode, UnknownInodeType}; +use crate::{Features, Name}; + +impl FileObject { + /// A file object for the file `name`, whose metadata is `meta`, with + /// the fields that `features` records, such as the features + /// [`RootObject::recorded_features`] gives. So a writer refuses none of + /// them for a manifest that records those features. The object has the + /// type of the file, and where `features` records them the access mode, + /// except on a symbolic link, the user and the group ID of the owner, + /// the modification time where `mTimeNSec` can express it, the size of + /// a regular file and the device numbers of a device node. + /// + /// It has no hash, no target of a symbolic link and no inode token, and + /// the caller gives it those a manifest needs. One that records + /// `symlink`, as [`Features::DEFAULT`] does, refuses a symbolic link + /// without its target. One that records `hardlink`, as the default + /// features do too, takes an object without a token for a file of no + /// other name, so the files with more than one name need their tokens. + /// + /// It fails for a file whose type is not an inode type. + /// + /// [`RootObject::recorded_features`]: crate::RootObject::recorded_features + pub fn from_metadata(name: Name, meta: &Metadata, features: Features) -> Result { + let mut object = FileObject::new(name); + object.inode_type = InodeType::try_from(meta.file_type())?; + let inode = &mut object.inode; + if features.contains(Features::MODE) && object.inode_type != InodeType::Symlink { + inode.mode = Some(Mode::from_st_mode(meta.mode())); + } + if features.contains(Features::UID) { + inode.uid = Some(meta.uid()); + } + if features.contains(Features::GID) { + inode.gid = Some(meta.gid()); + } + if features.contains(Features::MTIME) { + if let Ok(time) = meta.modified() { + inode.set_mtime(time); + } + } + if features.contains(Features::SIZE) && object.inode_type == InodeType::Regular { + object.size = Some(meta.len()); + } + if features.contains(Features::DEVICE) && object.inode_type.is_device() { + let device = meta.rdev(); + object.major = Some(u64::from(rustix::fs::major(device))); + object.minor = Some(u64::from(rustix::fs::minor(device))); + } + Ok(object) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{ContentsObject, ContentsSource, InodeAttributes}; + use crate::testing::TempDir; + use crate::{RootObject, Writer}; + use rustix::fs::{FileType, CWD}; + use std::fs; + use std::os::unix::ffi::OsStringExt; + use std::os::unix::fs::symlink; + use std::os::unix::net::UnixListener; + use std::path::PathBuf; + + /// Every type of file a test can make, and a device node every system + /// has, with the fields each set of features gives them. A writer takes + /// the objects for a manifest that records the same features. + #[test] + fn objects_of_every_inode_type() { + let tmp = TempDir::new("metadata"); + let dir = &tmp.0; + fs::write(dir.join("file"), b"hello").unwrap(); + fs::create_dir(dir.join("dir")).unwrap(); + symlink("file", dir.join("link")).unwrap(); + let fifo_mode = rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR; + rustix::fs::mknodat(CWD, dir.join("fifo"), FileType::Fifo, fifo_mode, 0).unwrap(); + let _socket = UnixListener::bind(dir.join("socket")).unwrap(); + // In the order of their names, as the writer wants them. + let files = [ + ("dir", dir.join("dir"), InodeType::Directory), + ("fifo", dir.join("fifo"), InodeType::Fifo), + ("file", dir.join("file"), InodeType::Regular), + ("link", dir.join("link"), InodeType::Symlink), + ("null", PathBuf::from("/dev/null"), InodeType::CharDevice), + ("socket", dir.join("socket"), InodeType::Socket), + ]; + for features in [Features::NONE, Features::DEFAULT, Features::ALL] { + let mut root = RootObject::default(); + root.set_features(Some(features)); + let mut writer = Writer::begin(Vec::new(), &root).unwrap(); + for (name, path, inode_type) in &files { + let meta = fs::symlink_metadata(path).unwrap(); + let mut object = FileObject::from_metadata(Name::new(*name).unwrap(), &meta, features).unwrap(); + assert_eq!(object.inode_type(), *inode_type, "{}", name); + let has = |feature: Features| features.contains(feature); + let mut inode = InodeAttributes { + mode: (has(Features::MODE) && *inode_type != InodeType::Symlink) + .then(|| Mode::from_st_mode(meta.mode())), + uid: has(Features::UID).then(|| meta.uid()), + gid: has(Features::GID).then(|| meta.gid()), + ..InodeAttributes::default() + }; + if has(Features::MTIME) { + inode.set_mtime(meta.modified().unwrap()); + } + assert_eq!(object.inode(), &inode, "{}", name); + let size = (has(Features::SIZE) && *inode_type == InodeType::Regular).then_some(5); + assert_eq!(object.size(), size, "{}", name); + let device = (has(Features::DEVICE) && inode_type.is_device()).then(|| { + let device = meta.rdev(); + ( + u64::from(rustix::fs::major(device)), + u64::from(rustix::fs::minor(device)), + ) + }); + assert_eq!(object.major().zip(object.minor()), device, "{}", name); + assert_eq!( + (object.sha256(), object.contents().len(), object.inode_token()), + (None, 0, None) + ); + assert!(features.contains(object.stated_features()), "{}", name); + // The target of a symbolic link comes from the caller, where + // the manifest records it. + if *inode_type == InodeType::Symlink && has(Features::SYMLINK) { + let target = fs::read_link(path).unwrap().into_os_string().into_vec(); + object.set_contents(vec![ContentsObject::new(ContentsSource::Literal(target))]); + } + writer.file(&object).unwrap_or_else(|e| panic!("{}: {}", name, e)); + } + writer.finish().unwrap(); + } + } +} diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 862b9b6..c500f03 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -168,6 +168,13 @@ impl Mode { /// the owner, of the group and of everybody else. const WRITE: u32 = 0o222; + /// The mode of the file mode `st_mode`: its permission bits with the + /// set-user-ID, the set-group-ID and the sticky bit, without the bits + /// of the file type. + pub(crate) const fn from_st_mode(st_mode: u32) -> Mode { + Mode(st_mode & Mode::ALL) + } + /// The mode with the bits `bits`. Bits that a mode does not have, such /// as those of the file type in an `st_mode`, fail. pub const fn new(bits: u32) -> Result { From c9e13156da543c94ea0f8f68b85d7f2dc94d80fa Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 18:16:44 +0100 Subject: [PATCH 26/32] uapi16: say which checks are up to the caller A reader checks every object against the rules of the specification, but two checks need something only the caller knows: whether it relies on the order of the file objects, and what time it is. The crate docs don't say so. Name both, require_order() and check_validity(). Also say that the validity of a directory doesn't carry over to its entries. What is true of a directory is true of everything in it, but check_validity() of an entry only looks at the entry. A caller that uses an entry checks the directories it is in as well. The docs of FileObject::check_validity() already say that what is true of a directory is true of everything in it, so say there as well that the check looks at the object alone. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/lib.rs | 9 +++++++++ src/uapi16/object.rs | 4 +++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 59183ba..f86d0cc 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -70,6 +70,15 @@ //! grows with the manifest. Writing one keeps the record it puts together, //! its separator included, and the name of the file object before it. //! +//! Two checks are up to the caller: whether a manifest declares the order +//! of its file objects, [`RootObject::require_order`], and whether an +//! object may be used at a given time, [`RootObject::check_validity`] and +//! [`FileObject::check_validity`]. What is true of a directory is true of +//! everything in it, but the validity of a directory does not carry over +//! to its entries: [`FileObject::check_validity`] looks at the object +//! alone. A caller that uses an entry checks the objects of the +//! directories it is in as well, which come before it in the manifest. +//! //! Signature objects are read and not verified: that takes an OpenPGP or //! an X.509 implementation. [`Reader::signed_len`] says how much of the //! manifest they sign. Data that is stored in an encoding or that has to diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index c500f03..6263daf 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -1913,7 +1913,9 @@ impl FileObject { /// Checks that the object may be used at the time `now_usec`, in /// microseconds since the epoch: that it is not revoked and that the /// time is inside its validity window. What is true of a directory is - /// true of everything in it. + /// true of everything in it, but the check looks at the object alone. A + /// caller that uses an entry checks the objects of the directories it + /// is in as well, which come before it in the manifest. pub fn check_validity(&self, now_usec: u64) -> Result<(), Error> { self.validity .check(now_usec, self.name.as_str().escape_debug()) From 76849c37bf516ffbb2bb44c428c20528021cd66a Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Mon, 23 Nov 2026 11:32:43 +0100 Subject: [PATCH 27/32] uapi16: give the default features as the specification has them The docs of Features say that a manifest which doesn't list its features records Features::DEFAULT, "what systemd-manifest make records unless it is told otherwise". That ties the docs to the defaults of a tool, and those move: systemd commit 1843e578d2 ("manifest-util: make the user-xattr field opt-in") changed what make records by default. What a manifest without features records is the specification's to say, so say only that: device, gid, hardlink, mode, sha256, size, symlink and uid. Nothing in the docs names a default of systemd-manifest anymore. No functional changes. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/features.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/uapi16/features.rs b/src/uapi16/features.rs index e7123ea..a995e07 100644 --- a/src/uapi16/features.rs +++ b/src/uapi16/features.rs @@ -24,9 +24,9 @@ use std::str::FromStr; /// without the field has that flag cleared. Where the list doesn't name the /// feature, nothing is known about these properties. /// -/// A manifest that does not list its features records -/// [`Features::DEFAULT`], what `systemd-manifest make` records unless it -/// is told otherwise. +/// A manifest that does not list `features` records [`Features::DEFAULT`], +/// the features the specification gives such a manifest: `device`, `gid`, +/// `hardlink`, `mode`, `sha256`, `size`, `symlink` and `uid`. /// /// ``` /// use uapi16::Features; From 81b5dae104162be13b6f734f5a46451cd1868116 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 11:34:07 +0100 Subject: [PATCH 28/32] uapi16: make the crate publishable Give the crate what crates.io shows for it: version 0.1.0, a description, the repository, keywords, categories, and a README for its page. The README says what the crate does for the people who use it, which checks are left to the caller, and which systems it supports: Linux 5.10 or newer, the minimum baseline of systemd, and Android. It also says what to do with a Rust older than what later releases of its dependencies need, such as sha2 from 0.11.1 on, and what the versions promise: a new minor release such as 0.2.0 may break callers, and releases within a minor version stay compatible. The version is set in the crate, since the workspace has none. The crate starts at 0.1.0 and not at 0.0.0. cargo takes every 0.0.z release as incompatible with every other one, so a caller that asks for 0.0.0 wouldn't even get 0.0.1. The crate no longer takes publish = false from the workspace. Nothing else in the workspace takes it either, and cargo 1.100 warns about a field of [workspace.package] that no crate uses. So the workspace drops it as well. The package that cargo publish uploads holds what is needed to build and test the crate: the sources with refused.jsonl, the tests with the manifests they read, the README and the license. cargo adds Cargo.toml and Cargo.lock on its own. The include list names them, so that nothing else that ends up in src/uapi16 goes into the package. The tests are part of it so that they can be run from the package as well. cargo publish --dry-run takes it, and the tests of the packaged crate pass on their own. Signed-off-by: Christian Brauner (Amutable) --- Cargo.lock | 2 +- Cargo.toml | 1 - src/uapi16/Cargo.toml | 9 +++++++- src/uapi16/README.md | 50 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 src/uapi16/README.md diff --git a/Cargo.lock b/Cargo.lock index 11b6de9..0cf4483 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -334,7 +334,7 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "uapi16" -version = "0.0.0" +version = "0.1.0" dependencies = [ "libc", "pathrs", diff --git a/Cargo.toml b/Cargo.toml index a8ed7c5..c73e3d2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,6 @@ edition = "2021" # uapi16 has to keep building with this rustc. rust-version = "1.85" license = "LGPL-2.1-or-later" -publish = false [workspace.dependencies] # Stay on 0.2 like pathrs, errno, getrandom and sha2's cpufeatures, so diff --git a/src/uapi16/Cargo.toml b/src/uapi16/Cargo.toml index 952e1a7..b0fc0e0 100644 --- a/src/uapi16/Cargo.toml +++ b/src/uapi16/Cargo.toml @@ -2,10 +2,17 @@ [package] name = "uapi16" +version = "0.1.0" edition.workspace = true rust-version.workspace = true license.workspace = true -publish.workspace = true +description = "Reading, checking and writing UAPI.16 file manifests" +repository = "https://github.com/systemd/uapi16" +keywords = ["uapi", "manifest", "filesystem", "systemd", "json-seq"] +categories = ["filesystem", "parser-implementations", "encoding"] +# What the package cargo publish uploads holds next to Cargo.toml and +# Cargo.lock. +include = ["/*.rs", "/refused.jsonl", "/tests/", "/README.md", "/LICENSE"] [lib] path = "lib.rs" diff --git a/src/uapi16/README.md b/src/uapi16/README.md new file mode 100644 index 0000000..456098a --- /dev/null +++ b/src/uapi16/README.md @@ -0,0 +1,50 @@ +# uapi16 + +uapi16 reads, checks and writes [UAPI.16 file manifests][spec]. + +A file manifest describes a tree of files. It is a JSON text sequence as +RFC 7464 defines it. The first object describes the root of the tree. An +object for every file follows, with its name, its type, its size, its +hash, its owner, its mode and its modification time. Signature objects +can follow the file objects, and a trailer object ends the manifest. + +uapi16 can: + +- read a manifest and check every object against the rules of the + specification, +- write a manifest and check it the same way, +- do both without doing any I/O itself, for example in an async runtime, +- copy the data of the files a manifest describes and check its size and + hash. + +A manifest is read one record at a time. Memory use does not grow with +the size of the manifest. + +Two checks are up to the caller: whether a manifest declares the order +of its file objects (RootObject::require_order) and whether an object +may be used at a given time (check_validity). + +Signature objects are read and not verified. Data that is stored in an +encoding or that has to be fetched from a URL is not supported. + +uapi16 reads JSON with serde_json. If another crate in the same build +turns on serde_json's arbitrary_precision feature, numbers are read +differently, see the crate documentation. + +uapi16 supports Linux 5.10 or newer, the minimum baseline of systemd, +and Android. Reading the data of the files from the directory next to +the manifest works on Linux only. uapi16 needs Rust 1.85 or newer. Some +of its dependencies need a newer Rust in later releases, such as sha2 +from version 0.11.1 on. With an older Rust, use resolver 3, the default +of edition 2024, so that cargo picks versions that build, or pin such a +dependency, for example with `cargo update -p sha2 --precise 0.11.0`. + +A new minor release, such as 0.2.0, may change the API in ways that +break callers. Releases within a minor version, such as 0.1.1 after +0.1.0, stay compatible. + +## License + +LGPL-2.1-or-later, see LICENSE. + +[spec]: https://uapi-group.org/specifications/specs/file_manifest/ From c8a1696130cdb64f2d13a042a373588ce9e230f1 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 11:35:11 +0100 Subject: [PATCH 29/32] README: describe the repository Add a README for the repository: what it holds and under which license. The page crates.io shows for the crate is src/uapi16/README.md. cargo would package this README with readme = "../../README.md" as well, but it describes the repository, which is going to hold the C library and the tool too. Signed-off-by: Christian Brauner (Amutable) --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..04c008f --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# uapi16 + +This repository holds uapi16, a Rust crate that reads, checks and +writes [UAPI.16 file manifests][spec]. The crate is in src/uapi16, and +its README describes what it does. + +## License + +LGPL-2.1-or-later, see LICENSE. + +[spec]: https://uapi-group.org/specifications/specs/file_manifest/ From 9c4f6af63134324500779afffe074ae65d51962f Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 11:36:43 +0100 Subject: [PATCH 30/32] ci: add GitHub Actions workflows Build and test the workspace for every pull request, every push to main and once a week: - build and test with rustc 1.85 and the current stable rustc on x86_64, with glibc and with musl - build for i686 and run the tests there - run clippy with both for the twelve targets ufat checks and for aarch64 and armv7 Android - check the formatting - build the documentation, for Linux and for aarch64 Android - run cargo publish --dry-run for uapi16 and the tests of the package it builds - check the crates in Cargo.lock against an explicit list Warnings fail the build through CARGO_TARGET__RUSTFLAGS, clippy's -D warnings and RUSTDOCFLAGS. All of it comes from ufat's CI, minus what only applies to ufat, and covers every crate of the workspace the way ufat's does. The documentation and the package jobs are new, and so are the two Android targets of clippy, which need no NDK since nothing is linked. Neither does the documentation for Android. What is there on Linux only is missing on Android, and that build fails on a link that would lead to it. The package is tested from its unpacked copy with a target directory of its own, so a file the tests need but the package lacks fails the job. cargo publish --dry-run only warns about a version that is on crates.io already, so the job keeps passing after a release. The actions are pinned to the same commits ufat uses, and dependabot bumps them once a month, together with the crates. sha2 stays on 0.11.0, the last release rustc 1.85 can build. libc stays on 0.2 like pathrs, errno, getrandom and sha2's cpufeatures, so that the tests never build two versions of it. Signed-off-by: Christian Brauner (Amutable) --- .github/dependabot.yml | 47 +++++++ .github/workflows/ci.yml | 296 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 343 insertions(+) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..564be32 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,47 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + groups: + actions: + patterns: + - "*" + cooldown: + default-days: 7 + open-pull-requests-limit: 2 + + - package-ecosystem: "cargo" + directory: "/" + schedule: + interval: "monthly" + groups: + # sha2 and the crates it needs move together. + rustcrypto: + patterns: + - "block-buffer" + - "cfg-if" + - "cpufeatures" + - "crypto-common" + - "digest" + - "hybrid-array" + - "sha2" + - "typenum" + ignore: + # Stay on 0.2 like pathrs, errno, getrandom and sha2's cpufeatures, + # so that the tests never build two versions of libc. + - dependency-name: "libc" + update-types: + - "version-update:semver-major" + - "version-update:semver-minor" + # sha2 0.11.1 and later need rustc 1.88, newer than rust-version. + # Drop this when rust-version reaches it. + - dependency-name: "sha2" + versions: + - ">= 0.11.1" + cooldown: + default-days: 7 + open-pull-requests-limit: 1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b990475 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,296 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +# +# The build and the tests with the oldest and the newest rustc on x86_64, +# the same with musl, the build and the tests on i686, the lints for +# fourteen targets, the formatting, the documentation for Linux and +# Android, the package cargo publish uploads and the dependency check. +# +# Warnings fail the build through CARGO_TARGET__RUSTFLAGS, +# clippy's -D warnings and RUSTDOCFLAGS. + +name: CI + +on: + push: + branches: + - main + pull_request: + branches: + - main + schedule: + # Weekly, which catches a new stable rustc or runner image. + - cron: '17 3 * * 1' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +defaults: + run: + shell: bash + +jobs: + build: + name: Build and test (rustc ${{ matrix.rust }}) + runs-on: ubuntu-26.04 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + rust: ['1.85.0', stable] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install rustc ${{ matrix.rust }} + env: + RUST: ${{ matrix.rust }} + run: | + rustup toolchain install "$RUST" --profile minimal + rustup default "$RUST" + rustc --version + host=$(rustc -vV | sed -n 's/^host: //p' | tr 'a-z-' 'A-Z_') + echo "CARGO_TARGET_${host}_RUSTFLAGS=-D warnings" >> "$GITHUB_ENV" + + - name: Build + run: cargo build --locked --workspace --all-targets + + - name: Test + run: cargo test --locked + + musl: + name: Build and test (x86_64-unknown-linux-musl, rustc ${{ matrix.rust }}) + runs-on: ubuntu-26.04 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + rust: ['1.85.0', stable] + env: + TARGET: x86_64-unknown-linux-musl + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install rustc ${{ matrix.rust }} + env: + RUST: ${{ matrix.rust }} + run: | + rustup toolchain install "$RUST" --profile minimal + rustup default "$RUST" + rustup target add "$TARGET" + rustc --version + t=$(echo "$TARGET" | tr 'a-z-' 'A-Z_') + echo "CARGO_TARGET_${t}_RUSTFLAGS=-D warnings" >> "$GITHUB_ENV" + + # rustc links a musl binary with the C library and the startup + # files that come with the target, so no musl toolchain is needed. + - name: Build + run: cargo build --locked --target "$TARGET" --workspace --all-targets + + - name: Test + run: cargo test --locked --target "$TARGET" + + i686: + name: Build and test (i686-unknown-linux-gnu) + runs-on: ubuntu-26.04 + timeout-minutes: 30 + env: + TARGET: i686-unknown-linux-gnu + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install dependencies + # The tests run on the x86_64 kernel with the i386 libraries of + # the runner. + run: | + sudo apt-get update -q + sudo apt-get install -y -q --no-install-recommends \ + gcc-i686-linux-gnu libc6-dev-i386-cross libc6-i386-cross libc6-i386 lib32gcc-s1 + + - name: Install rustc + run: | + rustup toolchain install stable --profile minimal + rustup default stable + rustup target add "$TARGET" + rustc --version + t=$(echo "$TARGET" | tr 'a-z-' 'A-Z_') + { + echo "CARGO_TARGET_${t}_LINKER=i686-linux-gnu-gcc" + echo "CARGO_TARGET_${t}_RUSTFLAGS=-D warnings" + } >> "$GITHUB_ENV" + + - name: Build + run: cargo build --locked --target "$TARGET" --workspace --all-targets + + - name: Test + run: cargo test --locked --target "$TARGET" + + clippy: + name: clippy (rustc ${{ matrix.rust }}) + runs-on: ubuntu-26.04 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + rust: ['1.85.0', stable] + env: + TARGETS: >- + x86_64-unknown-linux-gnu + i686-unknown-linux-gnu + aarch64-unknown-linux-gnu + armv7-unknown-linux-gnueabihf + loongarch64-unknown-linux-gnu + powerpc-unknown-linux-gnu + powerpc64-unknown-linux-gnu + powerpc64le-unknown-linux-gnu + riscv64gc-unknown-linux-gnu + s390x-unknown-linux-gnu + sparc64-unknown-linux-gnu + x86_64-unknown-linux-musl + aarch64-linux-android + armv7-linux-androideabi + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install rustc ${{ matrix.rust }} + env: + RUST: ${{ matrix.rust }} + run: | + rustup toolchain install "$RUST" --profile minimal --component clippy + rustup default "$RUST" + # shellcheck disable=SC2086 + rustup target add $TARGETS + rustc --version + + - name: clippy + # The lints differ between architectures. Checking needs no cross + # linker. + run: | + rc=0 + for t in $TARGETS; do + echo "::group::$t" + cargo clippy --locked --target "$t" --workspace --all-targets -- -D warnings || + { echo "::error::clippy failed for $t"; rc=1; } + echo "::endgroup::" + done + exit $rc + + fmt: + name: rustfmt + runs-on: ubuntu-26.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install rustc + run: | + rustup toolchain install stable --profile minimal --component rustfmt + rustup default stable + rustc --version + + - name: rustfmt + run: cargo fmt --all --check + + doc: + name: Documentation + runs-on: ubuntu-26.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install rustc + run: | + rustup toolchain install stable --profile minimal + rustup default stable + rustup target add aarch64-linux-android + rustc --version + + - name: rustdoc + env: + RUSTDOCFLAGS: -D warnings + run: cargo doc --locked --workspace --no-deps + + # What is there on Linux only is missing on Android, and no link may + # lead to it there. The documentation needs no NDK. + - name: rustdoc for Android + env: + RUSTDOCFLAGS: -D warnings + run: cargo doc --locked --workspace --no-deps --target aarch64-linux-android + + package: + name: Package + runs-on: ubuntu-26.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install rustc + run: | + rustup toolchain install stable --profile minimal + rustup default stable + rustc --version + host=$(rustc -vV | sed -n 's/^host: //p' | tr 'a-z-' 'A-Z_') + echo "CARGO_TARGET_${host}_RUSTFLAGS=-D warnings" >> "$GITHUB_ENV" + + - name: cargo publish --dry-run + # Builds the package that would be uploaded, from its unpacked + # copy in target/package. A version that is on crates.io already + # only gets a warning. + run: cargo publish --dry-run --locked -p uapi16 + + - name: Test the package + # With a target directory of its own, so that nothing of the + # repository is used. + run: | + cd target/package/uapi16-*/ + CARGO_TARGET_DIR=$RUNNER_TEMP/package cargo test --locked + + deps: + name: Dependencies + runs-on: ubuntu-26.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Check the crates uapi16 depends on + # Cargo.lock lists every dependency, for all targets and features, + # the build and test dependencies included: libc, pathrs, rustix, + # serde_core, serde_json and sha2 with the crates they need, those + # for other operating systems among them. The tests turn on + # preserve_order of serde_json, which adds foldhash and indexmap + # with the crates it needs. serde_json and serde_core name serde + # and serde_derive for cfg(any()), which no target has, so that + # all three keep one version. So these two are in Cargo.lock, and + # nothing builds them. + env: + EXPECTED: >- + bitflags block-buffer cfg-if cpufeatures crypto-common digest either equivalent errno fastrand + foldhash getrandom hashbrown hybrid-array indexmap itertools itoa libc linux-raw-sys memchr + once_cell pathrs proc-macro2 quote r-efi rustix rustversion serde serde_core serde_derive + serde_json sha2 static_assertions syn tempfile thiserror thiserror-impl typenum unicode-ident + windows-link windows-sys zmij + run: | + deps=$(cargo metadata --locked --format-version 1 | + jq -r '.workspace_members as $m | .packages[] | select(.id as $i | $m | index($i) | not) | .name' | + LC_ALL=C sort -u | xargs) + echo "$deps" + [ "$deps" = "$EXPECTED" ] || { echo "::error::expected the crates $EXPECTED, found $deps"; exit 1; } From 98d42b4985684df505cfcdf902bf706f433087c4 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 11:36:57 +0100 Subject: [PATCH 31/32] DCO: add the Developer Certificate of Origin Every commit to uapi16 carries a Signed-off-by: line from its author. Add the DCO that the line certifies, verbatim, the same file ufat has. There's no HACKING.md here, so the README of the repository says how to submit changes. Signed-off-by: Christian Brauner (Amutable) --- DCO | 37 +++++++++++++++++++++++++++++++++++++ README.md | 7 +++++++ 2 files changed, 44 insertions(+) create mode 100644 DCO diff --git a/DCO b/DCO new file mode 100644 index 0000000..8201f99 --- /dev/null +++ b/DCO @@ -0,0 +1,37 @@ +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +1 Letterman Drive +Suite D4700 +San Francisco, CA, 94129 + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. diff --git a/README.md b/README.md index 04c008f..fecbcca 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,13 @@ This repository holds uapi16, a Rust crate that reads, checks and writes [UAPI.16 file manifests][spec]. The crate is in src/uapi16, and its README describes what it does. +## Submitting changes + +Changes go in as pull requests on GitHub. Every commit carries a +`Signed-off-by:` line from its author. `git commit -s` adds one. With +it the author certifies the Developer Certificate of Origin in the file +DCO. Merge commits don't need one. + ## License LGPL-2.1-or-later, see LICENSE. From 171c0a6a551318f4680125520a1820aa24e6321e Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Sun, 22 Nov 2026 11:36:57 +0100 Subject: [PATCH 32/32] ci: check that every commit is signed off Fail when a commit lacks a Signed-off-by: line from its author: for a pull request every commit in it, for a push every commit it added. Merge commits are left out, since GitHub's merge button writes them without a sign-off. A sign-off counts when its address or its name is the author's. An affiliation in parentheses changes the name, and dependabot signs off with another address than it commits with. The job is the one ufat has. Signed-off-by: Christian Brauner (Amutable) --- .github/workflows/ci.yml | 54 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b990475..92f9a07 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,7 +3,8 @@ # The build and the tests with the oldest and the newest rustc on x86_64, # the same with musl, the build and the tests on i686, the lints for # fourteen targets, the formatting, the documentation for Linux and -# Android, the package cargo publish uploads and the dependency check. +# Android, the package cargo publish uploads, the dependency check and +# the sign-offs. # # Warnings fail the build through CARGO_TARGET__RUSTFLAGS, # clippy's -D warnings and RUSTDOCFLAGS. @@ -294,3 +295,54 @@ jobs: LC_ALL=C sort -u | xargs) echo "$deps" [ "$deps" = "$EXPECTED" ] || { echo "::error::expected the crates $EXPECTED, found $deps"; exit 1; } + + signoff: + name: Sign-off + runs-on: ubuntu-26.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 + + - name: Check that every commit is signed off + # Every commit carries a Signed-off-by: line from its author: the + # commits of a pull request, and those a push added. Merge commits + # are left out, since GitHub's merge button writes them without a + # sign-off. A sign-off counts when its address or its name is the + # author's: an affiliation in parentheses changes the name, and + # dependabot signs off with another address than it commits with. + env: + EVENT: ${{ github.event_name }} + BEFORE: ${{ github.event.before }} + run: | + case $EVENT in + pull_request) range=HEAD^1..HEAD^2 ;; + push) + range=$BEFORE..HEAD + # A new branch or a push that replaced the history: all of it. + git merge-base --is-ancestor "$BEFORE" HEAD 2>/dev/null || range=HEAD + ;; + *) exit 0 ;; + esac + # A range git can't list fails the step here. + commits=$(git log --no-merges --format='%H %ae %an' "$range") + bad=0 + while read -r commit email name; do + [ -n "$commit" ] || continue + ok=0 + while read -r signoff; do + signoff_name=${signoff%% <*} + signoff_email=${signoff##*<} + signoff_email=${signoff_email%%>*} + if [ "${signoff_email,,}" = "${email,,}" ] || [ "${signoff_name,,}" = "${name,,}" ]; then + ok=1 + fi + done < <(git log -1 --format='%(trailers:key=Signed-off-by,valueonly)' "$commit") + if [ "$ok" = 0 ]; then + echo "::error::$(git log -1 --format='%h %s' "$commit"): no Signed-off-by: from $name <$email>" + bad=1 + fi + done <<< "$commits" + exit "$bad"