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..92f9a07 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,348 @@ +# 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, the dependency check and +# the sign-offs. +# +# 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; } + + 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" 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..0cf4483 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,372 @@ +# This file is automatically @generated by Cargo. +# 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" +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 = "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" +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 = "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" +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 = "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" +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 = "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" +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 = "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uapi16" +version = "0.1.0" +dependencies = [ + "libc", + "pathrs", + "rustix", + "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 = "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" +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..c73e3d2 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,36 @@ +# 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" + +[workspace.dependencies] +# 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. 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 +# 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/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/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/README.md b/README.md new file mode 100644 index 0000000..fecbcca --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# 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. + +## 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. + +[spec]: https://uapi-group.org/specifications/specs/file_manifest/ 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..b0fc0e0 100644 --- a/src/uapi16/Cargo.toml +++ b/src/uapi16/Cargo.toml @@ -2,25 +2,40 @@ [package] name = "uapi16" -version.workspace = true +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" [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. +# 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] +# 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/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! 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/ 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/blocking.rs b/src/uapi16/blocking.rs index f5f0869..b7c4418 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; @@ -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"]); @@ -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() } @@ -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()?; @@ -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 @@ -289,7 +314,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)) } @@ -310,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; @@ -623,7 +656,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 +687,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(); @@ -665,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 { diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index fbb28b6..94ec7b1 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -1,43 +1,52 @@ // 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. +#[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::{Finalize, Sha256Context}; -use crate::error::{ContentProblem, Error, ErrorKind, Field, SourceProblem, UnsupportedContent}; -use crate::object::{Contents, FileObject, InodeType, Location}; +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}; -/// 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 /// 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`] 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>), + /// Outside of the manifest. A [`DataProvider`] has it. + External(ExternalFile<'a>), } /// The file a file object has its data in, next to the manifest. @@ -46,16 +55,11 @@ 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 - /// object's own name. - pub file: &'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 struct ExternalFile<'a> { + 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. @@ -67,12 +71,33 @@ 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 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> { + 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,22 +108,22 @@ 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 /// 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 = |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.escape_debug(), - self.file.escape_debug(), + name.as_str().escape_debug(), + self.name.as_str().escape_debug(), len, total ); @@ -109,8 +134,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.name.as_str().escape_debug(), self.offset, size ); @@ -119,16 +144,17 @@ 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. + #[cfg(target_os = "linux")] fn unavailable(&self, object: &FileObject, error: OpenError) -> Error { let name = &object.name; let error = match error { OpenError::NotRegular => { let message = format!( "{}: {} is not a regular file", - name.escape_debug(), - self.file.escape_debug() + name.as_str().escape_debug(), + self.name.as_str().escape_debug() ); return Error::new(ErrorKind::Source(SourceProblem::NotRegular), message).named(name.as_str()); } @@ -141,8 +167,8 @@ impl<'a> Reference<'a> { }; let message = format!( "{}: failed to open {}: {}", - name.escape_debug(), - self.file.escape_debug(), + name.as_str().escape_debug(), + self.name.as_str().escape_debug(), error ); Error::new(ErrorKind::Source(problem), message) @@ -152,7 +178,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 +190,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()) @@ -178,10 +204,10 @@ 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()); + return Error::new(ErrorKind::Unsupported(UnsupportedData::Absent), message).named(self.name.as_str()); } let mut ways: Vec = self .contents @@ -196,10 +222,10 @@ 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) + Error::new(ErrorKind::Unsupported(UnsupportedData::UrlOrEncoding), message) .named(self.name.as_str()) .valued(ways) } @@ -209,28 +235,33 @@ 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<&ContentsObject>)> { 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; 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((Data::Literal(data), Some(contents))); + 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)| (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 @@ -246,9 +277,9 @@ 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((Data::External(_), _))) + matches!(self.unencoded_data(), Some((DataLocation::External(_), _))) } /// The hash the manifest gives for all of the file the data is in, @@ -267,30 +298,30 @@ 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 + /// 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`] 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 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_contents(&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, - 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) => 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); } @@ -299,7 +330,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. @@ -321,9 +352,9 @@ 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())) + Err(Error::new(ErrorKind::Data(DataProblem::HashMismatch), message).named(object.name.as_str())) } } @@ -333,31 +364,32 @@ 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. +#[cfg_attr(target_os = "linux", doc = "A [`DirectoryProvider`] does.")] /// -/// [`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); +/// 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")?; /// 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 +402,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, @@ -390,10 +422,10 @@ 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) + return Err(Error::new(ErrorKind::Data(DataProblem::SizeMismatch), message) .named(self.name.as_str()) .sizes(None, Some(size))); } @@ -410,27 +442,30 @@ 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 ); - 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))); } - if self.context.map(Finalize::finalize) != self.sha256 { - let message = format!("'{}' does not match the hash in the manifest", self.name.escape_debug()); - return Err(Error::new(ErrorKind::Content(ContentProblem::HashMismatch), message).named(self.name.as_str())); + 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() + ); + 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 @@ -460,32 +495,46 @@ 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. /// -/// [`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 -/// order of the manifest: those whose data it takes to -/// [`FileObject::copy_contents`], 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>; +/// [`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`]. +/// +/// 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 + /// 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(()) @@ -493,9 +542,9 @@ pub trait ContentSource { } /// Why a [`Directory`] does not hand out a file. +#[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 @@ -503,6 +552,7 @@ pub enum OpenError { Io(io::Error), } +#[cfg(target_os = "linux")] impl From for OpenError { fn from(e: io::Error) -> OpenError { OpenError::Io(e) @@ -514,9 +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. -pub trait Directory { +/// 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. +/// +/// 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(crate) trait Directory { /// A file of the directory, open for reading. type File: Read + Seek; @@ -526,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, @@ -541,7 +596,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 @@ -549,10 +604,41 @@ 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 { +/// +/// It exists on Linux only, not on Android. +#[cfg(target_os = "linux")] +#[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, @@ -560,10 +646,11 @@ pub struct DirectorySource { hashes: PieceHashes, } -impl DirectorySource { - /// A source that takes the files from `directory`. - pub fn new(directory: D) -> DirectorySource { - DirectorySource { +#[cfg(target_os = "linux")] +impl Provider { + /// A provider that takes the files from `directory`. + fn new(directory: D) -> Provider { + Provider { directory, buffer: Vec::new(), hashes: PieceHashes::default(), @@ -571,9 +658,10 @@ impl DirectorySource { } } -impl fmt::Debug for DirectorySource { +#[cfg(target_os = "linux")] +impl fmt::Debug for Provider { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("DirectorySource") + f.debug_struct("Provider") .field("directory", &self.directory) .field( "buffer", @@ -584,7 +672,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, @@ -596,6 +684,7 @@ impl fmt::Debug for DirectorySource { /// 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. @@ -604,6 +693,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 @@ -653,6 +743,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") @@ -662,7 +753,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. @@ -670,9 +763,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, } @@ -683,18 +778,18 @@ 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); } // 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.escape_debug(), place, what); - Error::new(ErrorKind::Content(problem), message).named(name.as_str()) + let message = format!("{}: {} {}", name.as_str().escape_debug(), place, what); + Error::new(ErrorKind::Data(problem), message).named(name.as_str()) } } @@ -744,8 +839,9 @@ 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. +#[cfg(target_os = "linux")] struct Pieces<'a, F> { file: F, /// What the file is read into: [`COPY_SIZE`] bytes. @@ -760,6 +856,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. @@ -880,30 +977,33 @@ 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 +#[cfg(target_os = "linux")] +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 - .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.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); @@ -943,7 +1043,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, @@ -953,10 +1053,12 @@ 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 sealed::Sealed for StreamProvider {} + +impl StreamProvider { + /// A provider that takes the data from `reader`. + pub fn new(reader: R) -> StreamProvider { + StreamProvider { reader, buffer: Vec::new(), last: None, @@ -968,14 +1070,14 @@ 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; } } -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", @@ -986,29 +1088,29 @@ impl fmt::Debug for StreamSource { } } -impl ContentSource for StreamSource { - fn copy(&mut self, object: &FileObject, reference: &Reference<'_>, sink: &mut dyn Write) -> Result<(), Error> { +impl DataProvider for StreamProvider { + 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.escape_debug() + 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.escape_debug()); - return Err(Error::new(ErrorKind::Unsupported(UnsupportedContent::NoSize), message) + let message = format!("{}: streamed contents need a known size", name.as_str().escape_debug()); + 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 }; @@ -1023,20 +1125,20 @@ 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) + return Err(Error::new(ErrorKind::Data(DataProblem::StreamEnded), message) .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.escape_debug(), - reference.file.escape_debug() + name.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(()) } @@ -1047,7 +1149,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(()) } @@ -1064,7 +1166,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()); @@ -1079,11 +1181,12 @@ impl ContentSource for StreamSource { } } -#[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}; - use crate::Digest; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -1192,8 +1295,18 @@ 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. + 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 { type File = Counted; @@ -1244,10 +1357,10 @@ mod tests { objects(&records).pop().unwrap() } - /// Copies the contents 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_contents(source, &mut out)?; + let written = object.copy_data(provider, &mut out)?; assert_eq!(written, out.len() as u64); Ok(out) } @@ -1267,12 +1380,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()); @@ -1287,12 +1400,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. @@ -1304,16 +1417,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 [ ( @@ -1325,8 +1443,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 ); @@ -1336,8 +1454,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!( @@ -1349,7 +1467,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. @@ -1365,22 +1483,22 @@ 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().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(), 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(); - assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::Absent)); - source.skip(o).unwrap(); + let e = copy(o, &mut provider).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::Absent)); + 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(&[ @@ -1388,19 +1506,19 @@ 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"); - assert_eq!(copy(&some[1], &mut source).unwrap(), b"x"); + 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"); } #[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 = Provider::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!( @@ -1452,23 +1570,23 @@ 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 size = ErrorKind::Content(ContentProblem::SizeMismatch); - let hash = ErrorKind::Content(ContentProblem::HashMismatch); + let mut provider = Provider::new(&files); + let size = ErrorKind::Data(DataProblem::SizeMismatch); + let hash = ErrorKind::Data(DataProblem::HashMismatch); for (record, expected) in [ // A file too short for the data. ( @@ -1555,7 +1673,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), @@ -1571,7 +1689,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 @@ -1587,9 +1705,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), ( @@ -1606,15 +1724,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), ( @@ -1632,10 +1750,10 @@ mod tests { #[test] fn files_that_change_while_they_are_read() { let files = Files::default(); - let mut source = DirectorySource::new(&files); + let mut provider = Provider::new(&files); let changed = |file: &str| { ( - ErrorKind::Content(ContentProblem::SourceChanged), + ErrorKind::Data(DataProblem::SourceChanged), Some("x"), None, None, @@ -1655,7 +1773,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); } @@ -1675,15 +1793,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( @@ -1697,7 +1815,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 @@ -1713,7 +1831,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); } @@ -1735,9 +1853,9 @@ mod tests { trouble: Trouble::Stall, }; let files = Files::default(); - let mut source = DirectorySource::new(&files); + let mut provider = Provider::new(&files); let changed = ( - ErrorKind::Content(ContentProblem::SourceChanged), + ErrorKind::Data(DataProblem::SourceChanged), Some("x"), None, None, @@ -1764,17 +1882,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); } @@ -1794,9 +1912,9 @@ mod tests { trouble: Trouble::FailRead(libc::EIO), }, ); - let mut source = DirectorySource::new(&files); + let mut provider = Provider::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()), ( @@ -1814,7 +1932,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()), ( @@ -1824,7 +1942,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()), ( @@ -1843,7 +1961,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()), ( @@ -1861,9 +1979,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()), ( @@ -1881,7 +1999,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 = Provider::new(&files); let part = |offset: usize, size: usize, total: usize, sha256: Option| { let sha256 = sha256.map(|sha256| format!(r#","originalSha256":"{}""#, sha256)); object(&format!( @@ -1892,7 +2010,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), @@ -1908,7 +2026,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 @@ -1919,7 +2037,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) { @@ -1932,7 +2050,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), ( @@ -1960,7 +2078,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), @@ -1968,13 +2086,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. @@ -1987,9 +2105,9 @@ mod tests { HELLO ), ] { - let mut source = DirectorySource::new(&small); + let mut provider = Provider::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); } } @@ -2067,14 +2185,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); @@ -2098,7 +2216,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)); @@ -2124,31 +2242,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 = Provider::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] @@ -2159,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 source = DirectorySource::new(&files); + let mut provider = Provider::new(&files); for (file, problem, errno, text) in [ ( "missing", @@ -2197,7 +2315,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); @@ -2207,7 +2325,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: "), @@ -2231,23 +2349,23 @@ 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), ( - ErrorKind::Content(ContentProblem::StreamEnded), + ErrorKind::Data(DataProblem::StreamEnded), Some("d/b"), Some(2), Some(5), @@ -2255,14 +2373,14 @@ 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), ( - ErrorKind::Content(ContentProblem::SizeMismatch), + ErrorKind::Data(DataProblem::SizeMismatch), Some("d/b"), None, Some(5), @@ -2272,11 +2390,11 @@ 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), ( - ErrorKind::Content(ContentProblem::SizeMismatch), + ErrorKind::Data(DataProblem::SizeMismatch), None, None, Some(0), @@ -2284,11 +2402,11 @@ 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(); - assert_eq!(e.kind(), ErrorKind::Content(ContentProblem::HashMismatch)); + let e = copy(streamed[0], &mut StreamProvider::new(&mut stream)).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Data(DataProblem::HashMismatch)); } /// The hash the manifest gives for all of a file is checked where a @@ -2296,10 +2414,10 @@ 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)); + let copied = copy(o, &mut StreamProvider::new(&mut stream)); assert!(stream.is_empty()); copied }; @@ -2315,7 +2433,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); @@ -2358,17 +2476,17 @@ 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(); - assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::NoSize)); + 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(UnsupportedContent::OffsetInStream)); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::OffsetInStream)); assert_eq!(e.name(), Some("x")); assert_eq!(stream, b"hello"); } @@ -2385,30 +2503,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(); - assert_eq!(e.kind(), ErrorKind::Content(ContentProblem::HashMismatch)); + 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(); - assert_eq!(e.kind(), ErrorKind::Content(ContentProblem::StreamEnded)); + 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(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(); + Provider::new(&files).skip(&all[0]).unwrap(); assert_eq!(files.read(), 0); } @@ -2418,8 +2536,10 @@ mod tests { careful: bool, } - impl ContentSource for Babbler { - fn copy(&mut self, _: &FileObject, _: &Reference<'_>, sink: &mut dyn Write) -> Result<(), Error> { + 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"); if self.careful { written?; @@ -2431,38 +2551,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), @@ -2474,18 +2594,18 @@ 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); - // 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}"#); 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()); } @@ -2509,42 +2629,65 @@ 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}"#); 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 = Provider::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 = Provider::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_contents(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 = Provider::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 9756af2..aa2334d 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -20,12 +20,11 @@ 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::{ - 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::{ @@ -54,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. @@ -297,9 +296,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 @@ -390,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(()) } } @@ -418,7 +408,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), ); @@ -439,7 +429,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 @@ -459,11 +449,50 @@ 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` /// 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` @@ -472,7 +501,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 @@ -491,7 +520,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), _) => { @@ -677,7 +706,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 @@ -696,7 +725,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] @@ -779,7 +808,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(), @@ -1190,7 +1219,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()), }) @@ -1299,7 +1328,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) @@ -1698,21 +1727,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; @@ -1730,14 +1759,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); @@ -1764,7 +1793,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, || { @@ -1780,8 +1809,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; } } @@ -1790,7 +1819,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, || { @@ -1802,7 +1831,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); } } @@ -1836,7 +1868,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 { @@ -1861,7 +1893,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)) } } @@ -1903,12 +1935,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) @@ -1919,7 +1951,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, @@ -1962,7 +1994,7 @@ impl SignatureMembers<'_> { } }, }; - let mut signature = Signature::new(mechanism); + let mut signature = SignatureObject::new(mechanism); signature.key = key; signature.data = data; Ok(signature) @@ -2011,7 +2043,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 +2115,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 +2277,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 ); @@ -2340,6 +2372,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 @@ -2388,13 +2429,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 { @@ -2404,13 +2445,13 @@ 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(); 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 [ ( @@ -2784,10 +2825,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/digest.rs b/src/uapi16/digest.rs index 4a88faa..c796688 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; @@ -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. 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, + ]); /// 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) @@ -135,13 +105,13 @@ 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; -/// use uapi16::{Finalize, Sha256, Sha256Context}; +/// 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")); @@ -151,16 +121,19 @@ 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); } -} -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 +180,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/directory.rs b/src/uapi16/directory.rs new file mode 100644 index 0000000..f6de553 --- /dev/null +++ b/src/uapi16/directory.rs @@ -0,0 +1,349 @@ +// 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 crate::testing::TempDir; + use rustix::fs::CWD; + use std::fs; + use std::io::Read; + use std::os::unix::fs::symlink; + + /// 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/error.rs b/src/uapi16/error.rs index 54c4a4a..b797f08 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 +pub enum UnsupportedData { + /// 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 - /// they end. + /// 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 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..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; @@ -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 309bee2..f86d0cc 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -18,17 +18,27 @@ //! - [`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. -//! - [`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 contents of the files come 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`]. +//! while it is read, and [`Sha256Context::finalize`] returns it. +//! - [`RootObject`], [`FileObject`], [`ContentsObject`] and +//! [`SignatureObject`] are the objects, and [`Name`], [`InodeType`], +//! [`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. [`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`]. //! //! 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 +58,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 @@ -60,10 +70,19 @@ //! 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. 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 @@ -88,14 +107,20 @@ #![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; mod decode; mod digest; +#[cfg(target_os = "linux")] +mod directory; mod error; mod features; mod hex; +mod metadata; mod name; mod object; mod reader; @@ -104,15 +129,19 @@ mod strict; 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 error::{ContentProblem, Error, ErrorKind, Field, Problem, SourceProblem, UnsupportedContent, ValidityProblem}; +#[cfg(target_os = "linux")] +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; +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, InvalidUuid, Location, Mode, RootObject, Signature, 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; @@ -152,14 +181,38 @@ 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::{ - 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, 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; 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"}"#; @@ -201,7 +254,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. @@ -321,8 +374,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 { @@ -344,7 +398,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")); @@ -353,7 +407,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()); @@ -389,15 +443,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/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/name.rs b/src/uapi16/name.rs index 72b8569..74a93f5 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; @@ -39,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 @@ -75,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, @@ -201,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; } @@ -217,12 +227,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. @@ -236,14 +247,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() @@ -409,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); @@ -444,6 +448,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); @@ -588,7 +594,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()) { @@ -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] @@ -710,14 +741,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); @@ -771,12 +806,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 fb9cb88..6263daf 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(()); @@ -59,10 +61,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) } @@ -96,34 +99,89 @@ 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. /// /// ``` /// 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. - 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; - - /// The mode with the bits `bits`, unless there are others among them - /// than a mode has. - pub const fn new(bits: u32) -> Option { + /// 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 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 { if bits & !Mode::ALL == 0 { - Some(Mode(bits)) + Ok(Mode(bits)) } else { - None + Err(InvalidMode(())) } } @@ -186,17 +244,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. @@ -348,20 +433,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 { @@ -380,6 +457,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 { @@ -395,11 +534,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 @@ -441,13 +576,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) } } @@ -498,24 +633,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 { @@ -534,24 +667,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 @@ -577,37 +708,34 @@ 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. -/// -/// ``` -/// 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); -/// ``` +/// [`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 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, + /// 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 { /// 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) { + /// 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 { @@ -616,21 +744,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; } @@ -642,27 +777,53 @@ 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 [`Contents`] and the `readOnly` of [`InodeAttributes`] can be -/// filled in. Each of them notes it in its own `filled_in`. +/// 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. +/// +/// 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 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(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, @@ -670,10 +831,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) @@ -685,14 +855,24 @@ 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 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); } @@ -706,8 +886,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(" | ")?; } @@ -725,12 +904,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)] @@ -754,6 +934,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 { @@ -762,6 +952,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!( @@ -796,16 +992,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. @@ -829,31 +1052,27 @@ 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))); - /// identity.fat_serial = Some(FatSerial(0x5678_9abc)); - /// assert_eq!(identity.volume_serial(), Some((FatSerial(0x5678_9abc), Field::FatSerial))); + /// identity.set_uuid("1234abcd-5678-4ef0-9abc-def012345678".parse().ok()); + /// assert_eq!(identity.volume_serial(), Some(FatSerial::new(0x1234_abcd))); + /// 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<(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)) } } -/// 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] @@ -875,64 +1094,172 @@ pub enum Location { /// decoded data that starts at `offset`. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] -pub struct Contents { - /// `file`, `url` or `literal`: where the data is. - pub location: Location, - /// `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 struct ContentsObject { + 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 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, } } + + /// `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; + } + + /// `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 { + 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 @@ -945,37 +1272,32 @@ impl Contents { /// 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` and `extendedAttributes`, where a reader filled them in. + /// `flags` notes the inode flags a reader filled in. + pub(crate) filled_in: FilledIn, } impl InodeAttributes { @@ -997,7 +1319,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(), @@ -1027,8 +1349,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() { @@ -1037,9 +1359,132 @@ 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); } } + /// `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.filled_in.remove(Field::ExtendedAttributes); + 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. + 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`, the inode flags and `extendedAttributes`, where a reader + /// filled them in, see [`FilledIn`]. + pub fn filled_in(&self) -> FilledIn { + self.filled_in.union(self.flags.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)) @@ -1073,54 +1518,121 @@ 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. + /// `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); + } + + /// `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. + /// `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); + } + + /// `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. + /// `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); + } + + /// `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. + /// `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); + } + + /// `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. + /// `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); + } } /// A file object: what a manifest says about one file below its root. /// /// 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 contents 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. - 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, where a reader filled them in. `dos_flags` + /// notes the DOS attributes a reader filled in. + pub(crate) filled_in: FilledIn, } impl FileObject { @@ -1163,6 +1675,180 @@ 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 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 + /// 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() + } + + /// 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 + } + + /// 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, 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.dos_flags.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. @@ -1227,12 +1913,59 @@ 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.escape_debug()) + .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. + /// `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); + } + + /// `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. + /// `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); + } + + /// `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. + /// `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); + } } /// The root file object: what a manifest says about the root directory of @@ -1248,22 +1981,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 { @@ -1277,6 +2000,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 { @@ -1301,8 +2088,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) @@ -1357,32 +2144,58 @@ impl RootObject { /// verify them. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] -pub struct Signature { - /// `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 struct SignatureObject { + pub(crate) mechanism: String, + pub(crate) key: Option>, + pub(crate) 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, } } + + /// `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)] mod tests { use super::*; - use crate::Digest; /// Gives an object a field. type Give = fn(&mut T); @@ -1401,12 +2214,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 "] { @@ -1414,6 +2222,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] { @@ -1421,9 +2255,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), @@ -1491,6 +2325,11 @@ mod tests { } } + #[test] + fn fat_serials() { + assert_eq!(format!("{:?}", FatSerial::new(0x1234_abcd)), "FatSerial(0x1234abcd)"); + } + #[test] fn times() { let mut inode = InodeAttributes::default(); @@ -1516,9 +2355,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()); @@ -1527,7 +2366,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()); } @@ -1585,20 +2424,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); @@ -1607,7 +2449,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); @@ -1625,6 +2467,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::default() }; + 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::default() }; + 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]); @@ -1676,7 +2585,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), @@ -1715,7 +2624,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); @@ -1754,18 +2663,173 @@ 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")); } + + /// 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")]); + } + + /// 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] + 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, 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.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)); + 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)); + // 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 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!(object.filled_in().is_empty()); + assert_eq!( + 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)); + } } diff --git a/src/uapi16/reader.rs b/src/uapi16/reader.rs index 2e985eb..d2b91a3 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. @@ -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. @@ -304,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, /// _ => {} /// } @@ -482,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::{Digest, 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 fac282b..35cca49 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!( @@ -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::{Contents, DosFlags, FatSerial, InodeFlags, Location, Mode, Name, Uuid}; + use crate::{ContentsObject, ContentsSource, FatSerial, Mode, Name, Uuid}; use std::num::NonZeroU64; /// Gives an object a field. @@ -322,7 +323,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), ( @@ -347,7 +352,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, ), ]; @@ -398,7 +403,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/tests/fixtures.rs b/src/uapi16/tests/fixtures.rs new file mode 100644 index 0000000..a3183b4 --- /dev/null +++ b/src/uapi16/tests/fixtures.rs @@ -0,0 +1,204 @@ +// 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::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +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. +#[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 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)?; + 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().with_stated_xattrs(), + read.with_stated_xattrs(), + "{}", + 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"} diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs index 433591a..61840fe 100644 --- a/src/uapi16/writer.rs +++ b/src/uapi16/writer.rs @@ -12,12 +12,11 @@ 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::{ - 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::{ @@ -114,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(()) @@ -190,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)); @@ -405,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> { @@ -531,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> { @@ -576,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 { @@ -684,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 @@ -720,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(()), } } @@ -749,9 +748,9 @@ 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 + ContentsObject::filled_in(self) } fn write_fields(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { @@ -797,7 +796,7 @@ impl Sha256 { } } -impl Fields for Signature { +impl Fields for SignatureObject { fn filled_in(&self) -> FilledIn { FilledIn::default() } @@ -827,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, @@ -865,14 +864,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 +879,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(); @@ -917,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); @@ -1027,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()]; @@ -1036,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. @@ -1155,10 +1154,14 @@ 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); - 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); } @@ -1186,13 +1189,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)); @@ -1272,7 +1275,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), ( @@ -1398,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] @@ -1407,13 +1465,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]; @@ -1437,9 +1495,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), @@ -1502,7 +1560,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, @@ -1519,9 +1577,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); }, @@ -1536,7 +1594,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); }, @@ -1547,9 +1605,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); }, @@ -1573,7 +1631,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 +1639,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 @@ -1621,7 +1682,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(); @@ -1630,7 +1691,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(); @@ -1667,20 +1728,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. @@ -1724,7 +1785,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, ), @@ -1761,7 +1822,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, ), @@ -1810,7 +1871,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()), ( @@ -1848,8 +1909,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. @@ -1870,7 +1931,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 +1956,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), ), @@ -1937,7 +1998,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() }]; @@ -1948,7 +2009,7 @@ mod tests { ( |o| { o.size = Some(5); - o.contents = vec![Contents { + o.contents = vec![ContentsObject { original_size: Some(6), offset: 2, ..file() @@ -1983,7 +2044,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(); @@ -2009,7 +2070,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!(