diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 564be32..5892249 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -32,7 +32,7 @@ updates: - "typenum" ignore: # Stay on 0.2 like pathrs, errno, getrandom and sha2's cpufeatures, - # so that the tests never build two versions of libc. + # so that no build has two versions of libc. - dependency-name: "libc" update-types: - "version-update:semver-major" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 92f9a07..58f8f44 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,10 +1,13 @@ # 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. +# the same with musl, the build and the tests on i686, the tests on FAT, +# the lints for twelve targets, the formatting, the documentation, the C +# library with its header and its tests, the package cargo publish +# uploads, the dependency check and the sign-offs. +# +# The tests and the lints run without and with the feature capi, the C +# API. # # Warnings fail the build through CARGO_TARGET__RUSTFLAGS, # clippy's -D warnings and RUSTDOCFLAGS. @@ -58,12 +61,44 @@ jobs: host=$(rustc -vV | sed -n 's/^host: //p' | tr 'a-z-' 'A-Z_') echo "CARGO_TARGET_${host}_RUSTFLAGS=-D warnings" >> "$GITHUB_ENV" + - name: Install fuse-overlayfs + # Tests mount it in their namespaces: a FUSE file system that + # takes no privileges, for what the kernel's own don't do. + run: | + sudo apt-get update -q + sudo apt-get install -y -q --no-install-recommends fuse-overlayfs + + - name: Enable unprivileged user namespaces + # Tests that need mounts of their own run again in a user and a + # mount namespace from unshare(1), and skip where it can't make + # them. AppArmor keeps a program without a profile from using a + # user namespace on the runner, so this turns that off, as + # mkosi's action does. Where unshare still fails the job fails + # here, so that these tests don't skip for that. Those that + # mount fuse-overlayfs there skip where that can't be mounted. So + # this mounts one as well, and the job fails here where it can't. + # The tests that take an automount point skip in every job: only + # root can make one. So does the test that takes a file system + # that keeps a file that was unlinked while it is open, as NFS + # does: no job mounts one. + run: | + sudo sysctl --ignore --write kernel.apparmor_restrict_unprivileged_userns=0 + unshare -Urm true + d=$(mktemp -d) + mkdir "$d/lower" "$d/upper" "$d/work" "$d/merged" + unshare -Urm sh -c 'fuse-overlayfs -o "$1" "$2" && umount "$2"' sh \ + "lowerdir=$d/lower,upperdir=$d/upper,workdir=$d/work" "$d/merged" + rm -r "$d" + - name: Build run: cargo build --locked --workspace --all-targets - name: Test run: cargo test --locked + - name: Test with the C API + run: cargo test --locked --features capi + musl: name: Build and test (x86_64-unknown-linux-musl, rustc ${{ matrix.rust }}) runs-on: ubuntu-26.04 @@ -90,6 +125,35 @@ jobs: t=$(echo "$TARGET" | tr 'a-z-' 'A-Z_') echo "CARGO_TARGET_${t}_RUSTFLAGS=-D warnings" >> "$GITHUB_ENV" + - name: Install fuse-overlayfs + # Tests mount it in their namespaces: a FUSE file system that + # takes no privileges, for what the kernel's own don't do. + run: | + sudo apt-get update -q + sudo apt-get install -y -q --no-install-recommends fuse-overlayfs + + - name: Enable unprivileged user namespaces + # Tests that need mounts of their own run again in a user and a + # mount namespace from unshare(1), and skip where it can't make + # them. AppArmor keeps a program without a profile from using a + # user namespace on the runner, so this turns that off, as + # mkosi's action does. Where unshare still fails the job fails + # here, so that these tests don't skip for that. Those that + # mount fuse-overlayfs there skip where that can't be mounted. So + # this mounts one as well, and the job fails here where it can't. + # The tests that take an automount point skip in every job: only + # root can make one. So does the test that takes a file system + # that keeps a file that was unlinked while it is open, as NFS + # does: no job mounts one. + run: | + sudo sysctl --ignore --write kernel.apparmor_restrict_unprivileged_userns=0 + unshare -Urm true + d=$(mktemp -d) + mkdir "$d/lower" "$d/upper" "$d/work" "$d/merged" + unshare -Urm sh -c 'fuse-overlayfs -o "$1" "$2" && umount "$2"' sh \ + "lowerdir=$d/lower,upperdir=$d/upper,workdir=$d/work" "$d/merged" + rm -r "$d" + # 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 @@ -98,6 +162,9 @@ jobs: - name: Test run: cargo test --locked --target "$TARGET" + - name: Test with the C API + run: cargo test --locked --target "$TARGET" --features capi + i686: name: Build and test (i686-unknown-linux-gnu) runs-on: ubuntu-26.04 @@ -111,11 +178,15 @@ jobs: - name: Install dependencies # The tests run on the x86_64 kernel with the i386 libraries of - # the runner. + # the runner. Tests mount fuse-overlayfs in their namespaces, a + # FUSE file system that takes no privileges, for what the + # kernel's own don't do. It is the runner's own program here as + # well. 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 + gcc-i686-linux-gnu libc6-dev-i386-cross libc6-i386-cross libc6-i386 lib32gcc-s1 \ + fuse-overlayfs - name: Install rustc run: | @@ -129,12 +200,91 @@ jobs: echo "CARGO_TARGET_${t}_RUSTFLAGS=-D warnings" } >> "$GITHUB_ENV" + - name: Enable unprivileged user namespaces + # Tests that need mounts of their own run again in a user and a + # mount namespace from unshare(1), and skip where it can't make + # them. AppArmor keeps a program without a profile from using a + # user namespace on the runner, so this turns that off, as + # mkosi's action does. Where unshare still fails the job fails + # here, so that these tests don't skip for that. Those that + # mount fuse-overlayfs there skip where that can't be mounted. So + # this mounts one as well, and the job fails here where it can't. + # The tests that take an automount point skip in every job: only + # root can make one. So does the test that takes a file system + # that keeps a file that was unlinked while it is open, as NFS + # does: no job mounts one. + run: | + sudo sysctl --ignore --write kernel.apparmor_restrict_unprivileged_userns=0 + unshare -Urm true + d=$(mktemp -d) + mkdir "$d/lower" "$d/upper" "$d/work" "$d/merged" + unshare -Urm sh -c 'fuse-overlayfs -o "$1" "$2" && umount "$2"' sh \ + "lowerdir=$d/lower,upperdir=$d/upper,workdir=$d/work" "$d/merged" + rm -r "$d" + - name: Build run: cargo build --locked --target "$TARGET" --workspace --all-targets - name: Test run: cargo test --locked --target "$TARGET" + - name: Test with the C API + run: cargo test --locked --target "$TARGET" --features capi + + fat: + name: Tests on FAT + runs-on: ubuntu-26.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install dependencies + run: | + sudo apt-get update -q + sudo apt-get install -y -q --no-install-recommends dosfstools + + - 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: Make a FAT file system + # One the user owns, with a regular file, a read-only one and a + # directory on it, which the tests of the DOS attributes look at. + run: | + fat=$RUNNER_TEMP/fat + truncate -s 1G "$fat.img" + /usr/sbin/mkfs.vfat -F 32 "$fat.img" + mkdir "$fat" + sudo mount -o "loop,uid=$(id -u),gid=$(id -g)" "$fat.img" "$fat" + echo file > "$fat/file" + echo read-only > "$fat/read-only" + chmod a-w "$fat/read-only" + mkdir "$fat/dir" + echo "UAPI16_TEST_FAT_DIR=$fat" >> "$GITHUB_ENV" + + - name: Test the DOS attributes and the volume serial number + run: cargo test --locked --lib -- --exact ioctl::tests::fat optional::tests::fat + + - name: Sort on FAT + # The scratch file of a sort on a file system that has no O_TMPFILE + # and can't punch holes, in a directory of its own, which the tests + # of the DOS attributes don't look at. + run: | + mkdir "$UAPI16_TEST_FAT_DIR/tmp" + TMPDIR=$UAPI16_TEST_FAT_DIR/tmp cargo test --locked --lib -- --exact sort::tests::gives_room_back + + - name: Build a manifest on FAT + # The manifest and its scratch files on FAT: the scratch files get + # names they lose right away, and the manifest gets its name with + # RENAME_NOREPLACE. + run: TMPDIR=$UAPI16_TEST_FAT_DIR/tmp cargo test --locked --lib -- --exact manifest::tests::on_fat + clippy: name: clippy (rustc ${{ matrix.rust }}) runs-on: ubuntu-26.04 @@ -157,8 +307,6 @@ jobs: 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: @@ -180,10 +328,13 @@ jobs: 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::" + for features in "" "--features capi"; do + echo "::group::$t $features" + # shellcheck disable=SC2086 + cargo clippy --locked --target "$t" --workspace --all-targets $features -- -D warnings || + { echo "::error::clippy $features failed for $t"; rc=1; } + echo "::endgroup::" + done done exit $rc @@ -218,7 +369,6 @@ jobs: run: | rustup toolchain install stable --profile minimal rustup default stable - rustup target add aarch64-linux-android rustc --version - name: rustdoc @@ -226,12 +376,183 @@ jobs: 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 + header: + name: uapi16.h + runs-on: ubuntu-26.04 + timeout-minutes: 15 + env: + # The cbindgen that writes uapi16.h. + CBINDGEN: 0.29.4 + 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 + + - name: Install cbindgen + run: cargo install --locked cbindgen --version "$CBINDGEN" + + - name: Check that uapi16.h is what cbindgen writes + working-directory: src/uapi16 + run: | + cbindgen --quiet --config cbindgen.toml --output "$RUNNER_TEMP/uapi16.h" capi.rs + diff -u uapi16.h "$RUNNER_TEMP/uapi16.h" || + { echo "::error::uapi16.h is out of date, see cbindgen.toml"; exit 1; } + + - name: Install the compilers + run: | + sudo apt-get update -q + sudo apt-get install -y -q --no-install-recommends clang g++ gcc-multilib + + - name: Compile uapi16.h on its own + # A program includes the header and nothing before it: as C99 to + # C23 with and without the extensions of GNU, for 64 and for 32 + # bits, and from C++11 to C++23. + working-directory: src/uapi16 + run: | + for cc in gcc clang; do + for std in c99 c11 c17 c23 gnu99 gnu11 gnu17 gnu23; do + for bits in -m64 -m32; do + echo '#include "uapi16.h"' | + $cc -std=$std $bits -Wall -Wextra -Werror -I. -x c -fsyntax-only - + done + done + done + for cxx in g++ clang++; do + for std in c++11 c++14 c++17 c++20 c++23; do + echo '#include "uapi16.h"' | + $cxx -std=$std -Wall -Wextra -Werror -I. -x c++ -fsyntax-only - + done + done + # A program uses the two macros: with constants, with a variable + # for a feature, and with as many features as + # UAPI16_FEATURES_SET() takes, which expands every helper of it. + # The two macros use static_cast in C++, so a C++ program built + # with -Wold-style-cast can use them. And every conversion in + # them is a cast, so a program built with -Wconversion and + # -Wsign-conversion can use them as well, in C and in C++. + program=$(printf '%s\n' '#include "uapi16.h"' \ + 'extern const uapi16_features_t some, none, every;' \ + 'const uapi16_features_t some = UAPI16_FEATURES_SET(UAPI16_FEATURE_MTIME, UAPI16_FEATURE_SIZE);' \ + 'const uapi16_features_t none = UAPI16_FEATURES_EMPTY;' \ + "const uapi16_features_t every = UAPI16_FEATURES_SET($(seq -s ', ' 1 64));" \ + 'uapi16_features_t made(uapi16_feature_t feature, int number);' \ + 'uapi16_features_t made(uapi16_feature_t feature, int number) {' \ + ' uapi16_features_t set = UAPI16_FEATURES_SET(feature, number);' \ + ' return set;' \ + '}') + warnings='-Wall -Wextra -Wconversion -Wsign-conversion -Werror' + for cc in gcc clang; do + for std in c99 c23; do + echo "$program" | $cc -std=$std $warnings -I. -x c -fsyntax-only - + done + done + for cxx in g++ clang++; do + for std in c++11 c++14 c++17 c++20 c++23; do + echo "$program" | + $cxx -std=$std $warnings -Wold-style-cast -I. -x c++ -fsyntax-only - + done + done + + capi: + name: C library (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 dependencies + # The test takes what it is built with from uapi16.pc, and + # mkfs.vfat makes the FAT file system it looks at. + run: | + sudo apt-get update -q + sudo apt-get install -y -q --no-install-recommends pkgconf dosfstools + + - name: Install rustc ${{ matrix.rust }} env: - RUSTDOCFLAGS: -D warnings - run: cargo doc --locked --workspace --no-deps --target aarch64-linux-android + 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: Enable unprivileged user namespaces + # Four tests make a user namespace for themselves, and skip where + # they can't: the one of a loop through a bind mount, the one of a + # file system without a UUID and the one of a file system that is + # full with a mount namespace, and the one of a child with the PID + # of its parent with a PID namespace. + # AppArmor keeps a program without a profile from using a user + # namespace on the runner, so this turns that off, as the jobs + # that run the tests of the crate do. Where unshare still fails + # the job fails here, so that these tests don't skip unseen. + run: | + sudo sysctl --ignore --write kernel.apparmor_restrict_unprivileged_userns=0 + unshare -Urm true + + - name: Build the static and the shared library + # cargo builds the static library, and the C compiler links the + # shared one from it. + run: src/uapi16/build.sh -- --locked + + - name: Install + run: src/uapi16/install.sh --prefix="$RUNNER_TEMP/usr" + + - name: Make a FAT file system + # One the user owns, with a regular file, a read-only one and a + # directory on it, as the job for FAT makes one. The test walks it + # and makes a manifest in it. + run: | + fat=$RUNNER_TEMP/fat + truncate -s 1G "$fat.img" + /usr/sbin/mkfs.vfat -F 32 "$fat.img" + mkdir "$fat" + sudo mount -o "loop,uid=$(id -u),gid=$(id -g)" "$fat.img" "$fat" + echo file > "$fat/file" + echo read-only > "$fat/read-only" + chmod a-w "$fat/read-only" + mkdir "$fat/dir" + echo "UAPI16_TEST_FAT_DIR=$fat" >> "$GITHUB_ENV" + + - name: Test + # What the shared library exports, tests/capi.c against both + # libraries and the programs of examples/, with the address and the + # undefined behavior sanitizer. The test on FAT skips where it has + # no FAT directory, so the job fails unless it ran for both + # libraries. The parts that run under a seccomp filter skip where + # a process can't have one, and "forks", which has two of them, + # skips as a whole where no memory is wiped in a child. The job + # fails for a line that starts as one of those skip lines does, + # whatever the line says after that. + run: | + out=$RUNNER_TEMP/capi.out + src/uapi16/tests/capi.sh "$RUNNER_TEMP/usr" > "$out" 2>&1 || { cat "$out"; exit 1; } + cat "$out" + if [ "$(grep -c '^ok fat$' "$out")" != 2 ] || grep -q '^skipping a .* on FAT' "$out"; then + echo "::error::the test on FAT did not run for both libraries" + exit 1 + fi + if grep -q \ + -e '^skipping a new file' \ + -e '^skipping a fork that nothing tells' \ + -e '^skipping forks:' \ + "$out"; then + echo "::error::a part of the tests under a seccomp filter did not run" + exit 1 + fi package: name: Package @@ -250,6 +571,35 @@ jobs: host=$(rustc -vV | sed -n 's/^host: //p' | tr 'a-z-' 'A-Z_') echo "CARGO_TARGET_${host}_RUSTFLAGS=-D warnings" >> "$GITHUB_ENV" + - name: Install fuse-overlayfs + # Tests mount it in their namespaces: a FUSE file system that + # takes no privileges, for what the kernel's own don't do. + run: | + sudo apt-get update -q + sudo apt-get install -y -q --no-install-recommends fuse-overlayfs + + - name: Enable unprivileged user namespaces + # Tests that need mounts of their own run again in a user and a + # mount namespace from unshare(1), and skip where it can't make + # them. AppArmor keeps a program without a profile from using a + # user namespace on the runner, so this turns that off, as + # mkosi's action does. Where unshare still fails the job fails + # here, so that these tests don't skip for that. Those that + # mount fuse-overlayfs there skip where that can't be mounted. So + # this mounts one as well, and the job fails here where it can't. + # The tests that take an automount point skip in every job: only + # root can make one. So does the test that takes a file system + # that keeps a file that was unlinked while it is open, as NFS + # does: no job mounts one. + run: | + sudo sysctl --ignore --write kernel.apparmor_restrict_unprivileged_userns=0 + unshare -Urm true + d=$(mktemp -d) + mkdir "$d/lower" "$d/upper" "$d/work" "$d/merged" + unshare -Urm sh -c 'fuse-overlayfs -o "$1" "$2" && umount "$2"' sh \ + "lowerdir=$d/lower,upperdir=$d/upper,workdir=$d/work" "$d/merged" + rm -r "$d" + - 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 diff --git a/Cargo.toml b/Cargo.toml index c73e3d2..2a53e73 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,8 +12,9 @@ rust-version = "1.85" license = "LGPL-2.1-or-later" [workspace.dependencies] +# Looks up the names of users and groups, which rustix has no call for. # Stay on 0.2 like pathrs, errno, getrandom and sha2's cpufeatures, so -# that the tests never build two versions of libc. +# that no build has 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. diff --git a/README.md b/README.md index fecbcca..9e4a9fa 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,16 @@ # 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. +writes [UAPI.16 file manifests][spec], and its C library, libuapi16. The +crate is in src/uapi16, and its README describes both. + +## C library + +From the top of the repository, these build the C library and install +it into /usr: + + src/uapi16/build.sh + src/uapi16/install.sh --prefix=/usr ## Submitting changes diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..3e91791 --- /dev/null +++ b/TODO.md @@ -0,0 +1,138 @@ +# TODO + +Work that is planned for a later release, and ideas that are not decided +yet. + +## Manifest builder + +- A flag that leaves out every mount point a walk doesn't cross. Without + `CROSS_MOUNTS`, `generate_at()` and `generate()` record a directory + that is a mount point as an empty directory with the attributes of the + mounted root, and a file or a device node that is a mount point as the + mount shows it. The flag leaves out all of them, directories and files + alike. It could be `AddFlags::DROP_LEAF_MOUNTS` and + `UAPI16_ADD_DROP_LEAF_MOUNTS`, or have a name such as + `ONE_FILE_SYSTEM`. What it means together with `CROSS_MOUNTS` is still + open, and so is whether it also leaves out an automount point that + isn't triggered, which a walk records as an empty directory. + +- Add and finish in steps, so that a caller can stop an add between + two of them or keep each call short, as an event loop has to. The + builder works in steps inside already, so this is an addition to the + API in Rust and C: a call that sets up an add or the finish, a step + with a budget, and an end that says how the add ended. For every step + to stay short, more has to work in parts first: + - The doubling of the table of hard links. The step that begins one + writes about 0.9 MiB whatever its budget, every step that copies + writes twice its budget, and the step that ends one truncates the + old file, in 3 to 45 ms for tables of 128 MiB to 2 GiB. + - A merge. One step can read up to 32 MiB into the buffers of its + runs. + - The stages of a step. One that goes on from one stage to the next + can do two or three times its budget. + - Very small file objects of a caller. A budget in bytes lets a step + over them take ten times as long as one over files, and a weight + per record would even that out. + +- Read no page of a new table of hard links while it is still a hole. + Today the copy of a doubling reads every new page from its file before + it writes it, so the copy reads three times what it copies. Knowing + which pages are still holes needs no memory that grows with the table: + the copy touches the pages of each half of the new table in order, + except for groups that wrapped around the end of the old table. + +- Keep the table of hard links on disk in one file. Today a table on + disk doubles into a second file, and the two take turns, so the table + holds one more descriptor and is copied at every doubling. Two designs + could manage with a single pages file: + - The new table appended past the old one, with the old part punched + out afterwards. FAT can't punch holes, so there the space would + double. + - Linear hashing, which splits one page at a time in place, so there's + no doubling copy at all. It would mean a different table. + +- Check and escape the bytes of a name a word at a time. Today the split + of a name into its components, the check of the order of names and the + escape of a record's strings, which serde_json does, go through a name + a byte at a time. Over long names the adds and the finish take up to a + third longer in one build than in another of the same source, by where + these loops land. + +- Give the room of a run back on a tmpfs with huge pages. statx() says + 2 MiB there, and the sort gives back only whole blocks of that size, + so a run keeps up to 2 MiB of its file until the merge is over: 1256 + MiB for the 627 runs of 1.2e8 records, where xfs keeps 2 MiB. The + kernel frees smaller holes there too, so the page size would do as + the block. + +- Close the window between the check of a directory for an automount + point and its open by name. A directory that becomes an automount + point in between is triggered, and `generate_at()` or `generate()` + fails with `TreeProblem::Changed`. Where the kernel has `O_EMPTYPATH`, + the handle can be reopened without a lookup, and since Linux 6.18 + `openat2()` with `RESOLVE_NO_XDEV` doesn't trigger an automount. + +- Signing the manifest a builder writes. systemd-manifest make feeds the + text of every record into its signer as it writes the record, and + appends the signature record at the end. + +- A CI job with privileges for what the FAT job doesn't cover: block + devices and device nodes made with mknod, the append-only and + immutable flags, NOCOW, btrfs subvolumes, an mtime after 2554 on + btrfs, automount points, and a file system that keeps a file that was + unlinked while it is open, as NFS does. + +- An add of a descriptor that takes the hash of the data of a regular + file from its caller and doesn't read the data. A tool that builds an + image hashes the data while it copies it, with `Sha256Context`, and + adds it with `add_object()`. But then it reads the attributes of the + file itself, extended attributes and flags included, and numbers the + hard links. The new add reads everything but the data from the + descriptor. It could be + `ManifestWriter::add_hashed(entry, name, sha256)` and + `uapi16_manifest_writer_add_hashed()`. The hash is taken as it is, + like the hash of a file object of a caller. Still open: whether the + add also takes how many bytes were hashed and what `statx()` said of + the file before they were read, so that a file that changed while it + was copied fails with `TreeProblem::Changed`, and whether the hasher + comes from the writer, so that it hashes only what the manifest + records. + +## C API + +- Options for the install script to leave out the static or the shared + library. + +## pathrs + +- Dropping pathrs remains an option. When a call of pathrs fails, pathrs + looks up the path of the descriptor of the call in /proc for its + error, and it panics where it can't: where /proc is missing or is not + a procfs, and on a real procfs where no descriptor is left to open + /proc with. Both panics are in pathrs 0.2.6, the latest release, and + gone from the main branch of libpathrs (8e60d5f "procfs: drop panic in + ProcfsBase::into_path", 0ce0614 "*: get rid of silly panics"). Until a + release has that, in both cases `PinnedDirectory` panics for a name it + can't resolve, and it and the builder panic when they reopen a file on + a kernel without `O_EMPTYPATH`. A release of pathrs that returns an + error there instead of panicking takes care of this. + +- Without pathrs, `PinnedDirectory` resolves a name with `openat2()`, + `RESOLVE_IN_ROOT` and `RESOLVE_NO_MAGICLINKS`, plus + `RESOLVE_NO_SYMLINKS` unless it follows symbolic links, and tries + again on `EAGAIN`. Where the kernel has no `O_EMPTYPATH`, a file is + reopened through /proc/thread-self/fd and checked to be the inode of + its descriptor once it is open. That fails where /proc is not usable + instead of panicking, but unlike pathrs it opens what the link leads + to before it checks it. The builder's reopen, its only use of pathrs, + changes the same way. + +- Still open: where seccomp refuses `openat2()`, a walk of one + component at a time with `O_NOFOLLOW` still works, but + `follow_symlinks(true)` needs a resolver of our own, or fails there. + +## Maybe + +- Accepting `AT_FDCWD` as the directory descriptor of `create_at()` and + `generate_at()`, in C and as rustix's `CWD` in Rust. + Today it is refused with `EBADF`, like any other negative descriptor. diff --git a/src/uapi16/Cargo.toml b/src/uapi16/Cargo.toml index b0fc0e0..7a488ce 100644 --- a/src/uapi16/Cargo.toml +++ b/src/uapi16/Cargo.toml @@ -11,32 +11,57 @@ 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"] +# Cargo.lock. The header, the configuration of cbindgen, the version script +# and the two scripts are what the C library is built and installed with. +include = [ + "/*.rs", + "/refused.jsonl", + "/tests/", + "/examples/", + "/README.md", + "/LICENSE", + "/build.sh", + "/cbindgen.toml", + "/install.sh", + "/libuapi16.sym", + "/uapi16.h", +] [lib] path = "lib.rs" +[features] +# The C API of the crate, which uapi16.h declares. build.sh builds the +# static and the shared library of it, and install.sh installs them. +capi = [] + [dependencies] +# getpwuid_r() and getgrgid_r(), which give the names of the owners of the +# files a manifest is built from. The tests take errno values from it. +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 -# PinnedDirectory, which only Linux has. +# uapi16 supports Linux only. A build for another system fails with the +# error of lib.rs, and builds neither of the two for it. [target.'cfg(target_os = "linux")'.dependencies] +# PinnedDirectory. 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"] } +# open_tree(), which takes the handle of a file of a tree, is in the mount +# module. +rustix = { workspace = true, features = ["fs", "mount"] } [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"] } +[target.'cfg(target_os = "linux")'.dev-dependencies] +# The tests of the Writer write to a pipe. +rustix = { workspace = true, features = ["pipe"] } + [lints] workspace = true diff --git a/src/uapi16/README.md b/src/uapi16/README.md index 456098a..d655b53 100644 --- a/src/uapi16/README.md +++ b/src/uapi16/README.md @@ -13,12 +13,16 @@ 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. + hash, +- build a manifest from the file objects a tool makes, in any order, for + example while it writes a file system image, +- build the manifest of a tree of files on the host, which it reads + through descriptors. A manifest is read one record at a time. Memory use does not grow with -the size of the manifest. +the size of the manifest. Building a large manifest takes room on disk +instead of memory. Two checks are up to the caller: whether a manifest declares the order of its file objects (RootObject::require_order) and whether an object @@ -31,18 +35,87 @@ 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`. +uapi16 supports Linux 5.10 or newer, the minimum baseline of systemd. It +does not build for any other system, Android included. 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. +## Building a manifest + +ManifestOptions says what a manifest records, and makes the +ManifestWriter that takes the file objects it lists. generate_at() writes +the manifest of a directory and everything below it to a new file: + +```rust +use std::fs::File; +use std::path::Path; +use uapi16::{AddFlags, Features, ManifestOptions}; + +let esp = File::open("/efi")?; +let out_dir = File::open("/var/lib/manifests")?; +let report = ManifestOptions::new() + .features(Features::DEFAULT | Features::MTIME) + .generate_at(&out_dir, Path::new("esp.manifest"), &esp, AddFlags::NONE)?; +println!("{} files, {} bytes", report.files(), report.bytes()); +``` + +The new file appears once the manifest is complete. +examples/mkmanifest.rs is a program that does this for the directory +and the file it is given: + + cargo run --example mkmanifest -- /efi esp.manifest + +A tool that builds an image writes the manifest while it does: it gives +the writer the root with add_root() and a file object for every file +with add_object(), in any order, and finish() writes the manifest. + +## C library + +With the feature capi, the crate is also a C library, libuapi16. It +builds manifests, reads and writes them record by record, and checks the +data of the files they list. uapi16.h declares its functions and says +what each of them does. What holds for all of them is at its top. + +examples/ has six programs that use it: + +- generate.c writes the manifest of a directory. +- listing.c writes the manifest of a store from the records a tool has + of its files. +- build.c copies a tree into an image and writes the manifest of the + image while it does. +- assemble.c builds an image from a manifest and the files next to it. +- sorted.c writes a manifest record by record, in the order of the + manifest. +- signed.c writes a manifest with a signature object and reads it back. + +tests/capi.sh builds and runs them. + +build.sh builds the static library with cargo and links the shared one +from it with the C compiler. install.sh installs both with uapi16.h and +uapi16.pc: + + ./build.sh + ./install.sh --prefix=/usr + +build.sh works from any directory of the tree. Its default --builddir +is in the target directory of cargo. install.sh looks in target/release +below the current directory, or in the release directory of +CARGO_TARGET_DIR where that is set. So run it from the top of the crate, +or pass --builddir. In the repository the scripts are +src/uapi16/build.sh and src/uapi16/install.sh, and the top is the top of +the repository. Both list their options with --help. + +A program that uses the library gets the flags for it from pkg-config: + + cc -o program program.c $(pkg-config --cflags --libs uapi16) + ## License LGPL-2.1-or-later, see LICENSE. diff --git a/src/uapi16/blocking.rs b/src/uapi16/blocking.rs index fc849d4..571fb6a 100644 --- a/src/uapi16/blocking.rs +++ b/src/uapi16/blocking.rs @@ -6,8 +6,10 @@ use std::io::{self, BufRead, BufReader, Read, Write}; use std::iter::FusedIterator; +use rustix::io::Errno; + use crate::decode::ROOT_RECORD; -use crate::error::Error; +use crate::error::{Error, ErrorKind}; use crate::object::{FileObject, RootObject, SignatureObject}; use crate::reader::{Decoder, Object, Step}; use crate::writer::Encoder; @@ -192,6 +194,41 @@ impl Iterator for Reader { impl FusedIterator for Reader {} +/// A write of a [`Writer`] that failed: the number of its record and what +/// its error said. +#[derive(Debug)] +struct FailedWrite { + record_number: u64, + said: String, +} + +impl FailedWrite { + /// The errno of the error that every call after the write fails with. + const ERRNO: Errno = Errno::STALE; + + /// The write of the record with the number `record_number`, which + /// failed with `error`. + fn new(record_number: u64, error: &io::Error) -> FailedWrite { + FailedWrite { + record_number, + said: error.to_string(), + } + } + + /// The error of a call that comes after the write: an I/O error of + /// [`FailedWrite::ERRNO`] about the record of the write, which says + /// what the write failed with. + fn error(&self) -> Error { + let message = format!( + "the write of record {} failed earlier: {}", + self.record_number, self.said + ); + Error::new(ErrorKind::Io, message) + .caused_by(io::Error::from(FailedWrite::ERRNO)) + .in_record(self.record_number) + } +} + /// Writes a manifest record by record. /// /// [`Writer::begin`] writes the root file object, [`Writer::file`] the @@ -204,9 +241,8 @@ impl FusedIterator for Reader {} /// separator, the object with its keys sorted and without whitespace, and /// a newline, the way `systemd-manifest` writes it. A field that says /// nothing is left out. So is the inode type where the specification -/// implies it, on the root file object and on regular files. An -/// [`Encoder`] puts each record together, and it goes out in one write, so -/// a file wants a `BufWriter` around it. +/// implies it, on the root file object and on regular files. Each +/// record goes out in one write, so a file wants a `BufWriter` around it. /// /// The root file object says what the manifest records in `features` and /// which order it lists its file objects in in `order`. The writer checks @@ -222,7 +258,8 @@ impl FusedIterator for Reader {} /// [`MAX_RECORD_SIZE`], its record separator included, and no file object /// has more than [`MAX_CONTENTS`] contents objects. An object the writer /// refuses is not written, and the writer goes on as if it had not been -/// given it. +/// given it. A write that fails ends the writer: every later call fails +/// with an [`ErrorKind::Io`] error that names the write that failed. /// /// The writer leaves out what the manifest says without it: where the /// manifest records them, a flag that is cleared, `readOnly` of false, @@ -296,13 +333,19 @@ impl FusedIterator for Reader {} pub struct Writer { out: W, encoder: Encoder, + /// The write that failed, which ended the writer. + failed: Option, } impl Writer { /// Starts a manifest in `out` with the root file object `root`. pub fn begin(out: W, root: &RootObject) -> Result, Error> { let encoder = Encoder::start(root)?; - let mut writer = Writer { out, encoder }; + let mut writer = Writer { + out, + encoder, + failed: None, + }; writer.write_out(ROOT_RECORD)?; Ok(writer) } @@ -327,6 +370,15 @@ impl Writer { Ok(self.out) } + /// The number of the record that is written next, counting from 0 for + /// the root: the number a record that is refused would have had. The C + /// API names that record in an error about an object that it refuses + /// itself. + #[cfg(feature = "capi")] + pub(crate) fn next_record(&self) -> u64 { + self.encoder.next_record + } + /// What the manifest is written to. Every method writes its record to /// it before it returns, so it has the manifest up to the last record. /// Before the first signature object, that is what the signature @@ -344,32 +396,43 @@ impl Writer { } /// Writes out the record that `encode` has the encoder put together. + /// After a write that failed the encoder is given nothing more. fn send_record(&mut self, encode: impl FnOnce(&mut Encoder) -> Result<(), Error>) -> Result<(), Error> { + if let Some(failed) = &self.failed { + return Err(failed.error()); + } let record_number = self.encoder.next_record; encode(&mut self.encoder)?; self.write_out(record_number) } /// Writes out the record the encoder put together, the one with the - /// number `record_number`, in one write. + /// number `record_number`, in one write. A write that fails is the last + /// one: the encoder has taken the record by then, and a part of it may + /// be written. fn write_out(&mut self, record_number: u64) -> Result<(), Error> { let written = self.out.write_all(&self.encoder.record); self.encoder.clear_record(); - written.map_err(|e| Error::from(e).in_record(record_number)) + written.map_err(|e| { + self.failed = Some(FailedWrite::new(record_number, &e)); + Error::from(e).in_record(record_number) + }) } } #[cfg(test)] mod tests { use super::*; - use crate::error::{ErrorKind, Problem}; + use crate::error::Problem; use crate::testing::{ directory, everything, manifest, name, read_whole, read_whole_from, record, recording_all, sequence, write_whole, Whole, EMPTY, PIECES, ROOT, SIGNATURE, TRAILER, }; use crate::writer::RECORD_CAPACITY; use crate::{InodeType, Name, Sha256, MAX_RECORD_SIZE, RECORD_SEPARATOR}; + use rustix::pipe::PipeFlags; use std::collections::BTreeMap; + use std::fs::File; #[test] fn the_reader_as_an_iterator() { @@ -388,9 +451,9 @@ mod tests { assert_eq!(reader.record_number(), 0); // Records of whitespace do not count, objects that are passed over // do. - assert!(matches!(reader.next(), Some(Ok(Object::File(object))) if object.name == "a")); + assert!(matches!(reader.next(), Some(Ok(Object::File(object))) if object.name() == "a")); assert_eq!(reader.record_number(), 1); - assert!(matches!(reader.next(), Some(Ok(Object::File(object))) if object.name == "b")); + assert!(matches!(reader.next(), Some(Ok(Object::File(object))) if object.name() == "b")); assert_eq!(reader.record_number(), 3); assert_eq!(reader.signed_len(), None); assert!(matches!(reader.next(), Some(Ok(Object::Signature(signature))) if signature.mechanism == "pkcs7")); @@ -452,7 +515,7 @@ mod tests { let bytes = manifest(&[r#"{"name":"a","size":0}"#, &long, r#"{"name":"é","type":"dir"}"#]); let whole = read_whole(&bytes).unwrap(); assert_eq!(whole.objects.len(), 3); - assert_eq!(whole.objects[2].name, Name::new("\u{e9}").unwrap()); + assert_eq!(whole.objects[2].name(), Name::new("\u{e9}").unwrap()); // The pieces end anywhere: inside a record, inside a character, // right in front of a separator. for step in PIECES { @@ -478,7 +541,7 @@ mod tests { }) .unwrap(); for name in ["a", "long", "b"] { - assert!(matches!(reader.next(), Some(Ok(Object::File(object))) if object.name == name)); + assert!(matches!(reader.next(), Some(Ok(Object::File(object))) if object.name() == name)); } assert_eq!(reader.signed_len(), None); for _ in 0..2 { @@ -624,7 +687,9 @@ mod tests { // and an extended attribute, plus `pad` bytes. let padded = |name_of: &str, pad: usize| { let mut object = FileObject::new(name(name_of)); - object.inode.user_xattrs = Some(Box::new(BTreeMap::from([("p".to_string(), vec![b'x'; pad])]))); + object + .inode_mut() + .set_user_xattrs(Some(BTreeMap::from([("p".to_string(), vec![b'x'; pad])]))); object }; // The separator and the newline are not in what record() returns. @@ -646,7 +711,7 @@ mod tests { // A directory that is not written is not the directory of what // comes next. let mut large = padded("d", MAX_RECORD_SIZE); - large.inode_type = InodeType::Directory; + large.set_inode_type(InodeType::Directory); let e = writer.file(&large).unwrap_err(); assert_eq!(e.kind(), ErrorKind::Manifest(Problem::RecordTooLarge)); let e = writer.file(&FileObject::new(name("d/x"))).unwrap_err(); @@ -666,12 +731,13 @@ mod tests { let bytes = writer.finish().unwrap(); let m = read_whole(&bytes).unwrap(); assert_eq!(m.objects.len(), 1); - assert_eq!(m.objects[0].inode.user_xattrs, largest.inode.user_xattrs); + assert_eq!(m.objects[0].inode().user_xattr_map(), largest.inode().user_xattr_map()); // What a reader read, the writer writes back. assert_eq!(write_whole(&m).unwrap(), bytes); // The root file object's record is record 0. let mut root = recording_all().0; - root.inode.user_xattrs = padded("a", MAX_RECORD_SIZE).inode.user_xattrs; + root.inode + .set_user_xattrs(padded("a", MAX_RECORD_SIZE).inode().user_xattr_map().cloned()); let e = Writer::begin(Vec::new(), &root).unwrap_err(); assert_eq!( (e.kind(), e.record_number()), @@ -740,7 +806,7 @@ mod tests { writer.file(&directory("a")).unwrap(); writer.file(&everything()).unwrap(); let mut empty = FileObject::new(name("empty")); - empty.sha256 = EMPTY.parse().ok(); + empty.set_sha256(EMPTY.parse().ok()); writer.file(&empty).unwrap(); writer.finish().unwrap(); assert_eq!(calls.writes.len(), 5); @@ -761,4 +827,204 @@ mod tests { assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::ENOSPC)); } } + + /// What the tests compare of an error of a writer: its kind, the errno + /// of its I/O error, the number of its record and what it says. + fn facts(e: &Error) -> (ErrorKind, Option, Option, String) { + ( + e.kind(), + e.io_error().and_then(io::Error::raw_os_error), + e.record_number(), + e.to_string(), + ) + } + + /// Makes every later call on `writer`, whose write of the record + /// `record_number` failed with `first`: file() with `again`, + /// signature() and finish(). Each fails with an I/O error of ESTALE + /// about that record, which says what the write failed with. + fn later_calls_fail(mut writer: Writer, again: &FileObject, record_number: u64, first: &io::Error) { + let ended = ( + ErrorKind::Io, + Some(libc::ESTALE), + Some(record_number), + format!("the write of record {} failed earlier: {}", record_number, first), + ); + assert_eq!(facts(&writer.file(again).unwrap_err()), ended); + assert_eq!( + facts(&writer.signature(&SignatureObject::new("pkcs7")).unwrap_err()), + ended + ); + assert_eq!(facts(&writer.finish().map(drop).unwrap_err()), ended); + } + + /// A pipe that does not block: a write to it fails with EAGAIN while it + /// is full, and a read from it while it is empty. + #[derive(Debug)] + struct Pipe { + /// The end that is read from. + read_end: File, + /// What was read from it so far. + read: Vec, + } + + impl Pipe { + /// How both ends are made: no read or write waits. + const FLAGS: PipeFlags = PipeFlags::NONBLOCK.union(PipeFlags::CLOEXEC); + /// More bytes than the pipe takes, which has room for 16 pages at + /// most. + const MORE_THAN_FITS: usize = MAX_RECORD_SIZE / 2; + + /// A pipe without a name, and the end of it that is written to. + fn new() -> (Pipe, File) { + let (read_end, write_end) = rustix::pipe::pipe_with(Pipe::FLAGS).unwrap(); + let pipe = Pipe { + read_end: File::from(read_end), + read: Vec::new(), + }; + (pipe, File::from(write_end)) + } + + /// Reads the pipe empty, and says how many bytes that were. + fn drain(&mut self) -> usize { + let before = self.read.len(); + match self.read_end.read_to_end(&mut self.read) { + Ok(_) => {} + Err(e) if e.kind() == io::ErrorKind::WouldBlock => {} + Err(e) => panic!("{}", e), + } + self.read.len() - before + } + } + + /// A pipe that is full fails the write of a record with EAGAIN, and + /// takes nothing of a record of at most a page. The writer ends there. + /// Once the pipe is empty, the same object again fails for the write + /// that failed, and not as a duplicate of itself, and so do signature() + /// and finish(). What the pipe took has no trailer, so no reader takes + /// it for a manifest that lacks the object. + #[test] + fn a_full_pipe_ends_the_writer() { + let (mut pipe, write_end) = Pipe::new(); + let mut writer = Writer::begin(write_end, &RootObject::default()).unwrap(); + // File objects until the pipe is full. It takes each of their + // records whole or not at all. + let small = |number: u64| FileObject::new(name(&format!("{:08}", number))); + let (failed, e) = (1..=Pipe::MORE_THAN_FITS as u64) + .find_map(|number| writer.file(&small(number)).err().map(|e| (number, e))) + .unwrap(); + let eagain = io::Error::from_raw_os_error(libc::EAGAIN); + assert_eq!( + facts(&e), + (ErrorKind::Io, Some(libc::EAGAIN), Some(failed), eagain.to_string()) + ); + // The pipe is empty again, and has room for the record. + pipe.drain(); + later_calls_fail(writer, &small(failed), failed, &eagain); + // None of them wrote anything. A reader finds every file object + // before the one that was not written, and no trailer. + assert_eq!(pipe.drain(), 0); + let mut reader = Reader::open(&pipe.read[..]).unwrap(); + for number in 1..failed { + assert!(matches!(reader.next(), Some(Ok(Object::File(object))) if object.name() == small(number).name())); + } + let e = reader.next().unwrap().unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::NoTrailer)); + } + + /// A record of more than a page that the pipe has no room for is cut + /// off: the pipe takes a part of it before the write fails. The writer + /// ends there as well, and nothing follows that part, where a trailer + /// would end a manifest with a broken record in it. + #[test] + fn a_record_cut_off_ends_the_writer() { + let (mut pipe, write_end) = Pipe::new(); + let (root, root_text) = recording_all(); + let mut large = FileObject::new(name("large")); + let pad = vec![b'x'; Pipe::MORE_THAN_FITS]; + large + .inode_mut() + .set_user_xattrs(Some(BTreeMap::from([("p".to_string(), pad)]))); + let mut writer = Writer::begin(write_end, &root).unwrap(); + let eagain = io::Error::from_raw_os_error(libc::EAGAIN); + let e = writer.file(&large).unwrap_err(); + assert_eq!( + facts(&e), + (ErrorKind::Io, Some(libc::EAGAIN), Some(1), eagain.to_string()) + ); + // The pipe took the root file object and a part of the record. + pipe.drain(); + let whole = sequence(&[root_text.as_str(), record(&large).as_str()]); + assert!(whole.starts_with(&pipe.read)); + assert!(sequence(&[root_text.as_str()]).len() < pipe.read.len() && pipe.read.len() < whole.len()); + later_calls_fail(writer, &large, 1, &eagain); + // None of them wrote anything. A reader finds the record that was + // cut off, and nothing behind it. + assert_eq!(pipe.drain(), 0); + let e = read_whole(&pipe.read).unwrap_err(); + assert_eq!( + (e.kind(), e.record_number()), + (ErrorKind::Manifest(Problem::NotJson), Some(1)) + ); + } + + /// Takes `room` bytes and then says that no space is left, as a file + /// does on a file system that is full. /dev/full has no room at all: + /// the root file object is not written to it, so no writer begins + /// there. + #[derive(Debug)] + struct Full { + room: usize, + taken: Vec, + } + + impl Write for Full { + fn write(&mut self, data: &[u8]) -> io::Result { + let n = data.len().min(self.room); + if n == 0 { + return Err(io::Error::from_raw_os_error(libc::ENOSPC)); + } + self.room -= n; + self.taken.extend_from_slice(&data[..n]); + Ok(n) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + /// No space left ends the writer as a pipe that is full does, with a + /// part of the record written. Room that there is later changes + /// nothing. + #[test] + fn no_space_left_ends_the_writer() { + // Room for the root file object, for a file object and for half of + // the record of the next one. + let before = sequence(&[ROOT, r#"{"name":"a"}"#]); + let half = sequence(&[r#"{"name":"b"}"#]); + let half = &half[..half.len() / 2]; + let mut full = Full { + room: before.len() + half.len(), + taken: Vec::new(), + }; + let mut writer = Writer::begin(&mut full, &RootObject::default()).unwrap(); + writer.file(&FileObject::new(name("a"))).unwrap(); + let b = FileObject::new(name("b")); + let enospc = io::Error::from_raw_os_error(libc::ENOSPC); + let e = writer.file(&b).unwrap_err(); + assert_eq!( + facts(&e), + (ErrorKind::Io, Some(libc::ENOSPC), Some(2), enospc.to_string()) + ); + // There is room again, which the writer does not use. + writer.get_mut().room = MAX_RECORD_SIZE; + later_calls_fail(writer, &b, 2, &enospc); + assert_eq!(full.taken, [&before[..], half].concat()); + let e = read_whole(&full.taken).unwrap_err(); + assert_eq!( + (e.kind(), e.record_number()), + (ErrorKind::Manifest(Problem::NotJson), Some(2)) + ); + } } diff --git a/src/uapi16/build.sh b/src/uapi16/build.sh new file mode 100755 index 0000000..d9c2290 --- /dev/null +++ b/src/uapi16/build.sh @@ -0,0 +1,164 @@ +#!/bin/sh +# SPDX-License-Identifier: LGPL-2.1-or-later +# +# Builds the C library of uapi16: the static library with cargo, and the +# shared library from the static one with the C compiler. install.sh +# installs the two. +# +# The shared library is linked the way a C library is: by the C compiler, +# with CFLAGS and LDFLAGS, and with the version script libuapi16.sym, which +# says what it exports. cargo could build a shared library itself, but +# rustc gives the linker a version script of its own for one, and no symbol +# gets a version next to that. + +set -eu + +usage() { + cat <&2 + exit 1 + ;; + esac + shift +done + +fail() { + echo "$0: $*" >&2 + exit 1 +} + +# What cargo builds for another target is not where it puts what it builds +# for the host. +for option; do + case $option in + --target | --target=*) [ -n "$builddir" ] || fail "--target needs --builddir" ;; + esac +done + +# Where cargo builds, which it says itself: target at the top of the +# workspace unless CARGO_TARGET_DIR or its configuration name another +# directory, whatever directory this is run from. What it builds for the +# host is in release below it. What it builds for another target is in a +# directory of that target, also where no option names the target but +# CARGO_BUILD_TARGET or the configuration of cargo. Nothing says that +# before cargo has built the library, so where it put it is checked below. +if [ -z "$builddir" ]; then + target=$(cargo metadata --manifest-path "$here/Cargo.toml" --format-version 1 --no-deps | + sed -n 's/.*"target_directory":"\([^"]*\)".*/\1/p') + # A backslash is how cargo writes a character that this does not read. + case $target in + '' | *\\*) fail "cargo does not say where it builds, say it with --builddir" ;; + esac + builddir=$target/release +fi +mkdir -p "$builddir" +builddir=$(CDPATH= cd -P -- "$builddir" && pwd) +static=$builddir/libuapi16.a +shared=$builddir/libuapi16.so +libs=$builddir/libuapi16.libs + +# The static library. rustc writes what a program that links it has to link +# as well into a file, which install.sh puts into uapi16.pc. It writes the +# file when it builds the library, and into a file of another name first: +# the library it builds need not be the one in $builddir. One that an +# earlier run left there is of no use. +# +# cargo says what it built in messages of one line of JSON each, also for +# what it had built before and does not build again, and shows what the +# compiler says as it does without them. +rm -f "$libs.new" +messages=$(cargo rustc --manifest-path "$here/Cargo.toml" --release --features capi --crate-type staticlib \ + --message-format=json-render-diagnostics "$@" -- --print "native-static-libs=$libs.new") + +# The message for the static library names the file it is in. A backslash +# is how cargo writes a character that this does not read, and more than +# one line is more than one library. +built=$(printf '%s\n' "$messages" | + sed -n '/"reason":"compiler-artifact"/s/.*"filenames":\[[^]]*"\([^"]*\/libuapi16\.a\)".*/\1/p') +case $built in +'' | *\\* | *' +'*) + rm -f "$libs.new" + fail "cargo does not say where it put libuapi16.a" + ;; +esac + +# A library that is in $builddir from an earlier build is not what cargo +# built now if cargo built for another target. What that build left in +# $builddir stays as it is then. +built=$(CDPATH= cd -P -- "$(dirname -- "$built")" && pwd)/libuapi16.a +if [ "$built" != "$static" ]; then + rm -f "$libs.new" + fail "cargo built $built and not $static, name its directory with --builddir" +fi + +# cargo does not build a library again that it has, also not where the file +# rustc wrote with it is gone, so nothing writes that file again then. +[ ! -f "$libs.new" ] || mv -f "$libs.new" "$libs" +[ -f "$libs" ] || fail "$libs is missing, and rustc only writes it when cargo builds" \ + "libuapi16.a, which cargo did not do again. Run 'cargo clean --manifest-path" \ + "$here/Cargo.toml --release -p uapi16', with the --target of this build if it has" \ + "one, and then this again" + +# The shared library is all of the static one. libuapi16.sym exports the +# functions of uapi16.h from it and nothing else, and a name in it that the +# library does not define fails the link. The other options are those rustc +# gives the linker for a shared library of its own: what the functions do +# not need is left out, only the libraries that are needed are recorded, +# the library is bound when it is loaded and read-only after that, its +# stack is not executable and it has no debug sections. CFLAGS and then +# LDFLAGS come after all of that, so they can say otherwise. A link gets +# both from automake and from meson as well. +# +# $CC, $CFLAGS, $LDFLAGS and what is in $libs are lists of words. +# shellcheck disable=SC2086 +${CC:-cc} -shared -o "$shared" \ + -Wl,-soname,libuapi16.so.0 \ + -Xlinker "--version-script=$here/libuapi16.sym" -Wl,--no-undefined-version \ + -Wl,--gc-sections -Wl,--as-needed \ + -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack $strip_debug \ + ${CFLAGS:-} ${LDFLAGS:-} \ + -Wl,--whole-archive "$static" -Wl,--no-whole-archive \ + $(cat "$libs") + +echo "built $static and $shared" diff --git a/src/uapi16/capi.rs b/src/uapi16/capi.rs new file mode 100644 index 0000000..2f7baa0 --- /dev/null +++ b/src/uapi16/capi.rs @@ -0,0 +1,9230 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The C API of the crate, which the feature `capi` adds: what uapi16.h +//! declares. cbindgen writes that header from this file, see cbindgen.toml: +//! the types, the enums with their numbers, the functions, and the comments +//! on them, which are written for callers in C. The rules that hold for +//! every function are in the comment at the top of the header, which +//! cbindgen.toml has. +//! +//! With the feature, this module has unsafe code as well, next to the +//! modules ioctl and nss and the one cast of the module name. A caller in C +//! hands over pointers and numbers, and nothing can check what a pointer +//! leads to. So every function takes this on trust, which the SAFETY +//! comments call the rules of the caller: +//! +//! - An object is NULL, or a pointer that a function of this module +//! returned and that was not freed since. No two calls use an object at +//! the same time, except for calls that only read it: those of reports +//! and errors, of a file object that nothing changes, and the opens of a +//! directory. +//! - A string is NULL, or points to bytes that end in a NUL and that do +//! not change during the call. +//! - Bytes are a pointer and a size. Unless the size is 0, the pointer is +//! NULL or valid for the read of that many bytes, which do not change +//! during the call. +//! - A set of features is NULL, or aligned as a uint64_t and valid for the +//! read of its size, which is its first 8 bytes. Where that is a size a +//! set can have, the set is valid for the read of as many bytes, and for +//! the write of them where the call changes or fills it. Nothing else +//! changes them during the call. +//! - `ret` and every `ret_` argument are NULL, or valid for the write of +//! what they are for. The `ret` of the two functions that read from a +//! reader is valid for the read of a pointer as well, and that pointer +//! is NULL or an object, as above. +//! - `reterr` is NULL, or valid for the read and the write of a pointer +//! that nothing else uses during the call. A caller is told that it +//! points to NULL then. +//! - A descriptor that is not negative is open and stays open during the +//! call. One that an object keeps stays open until the object is freed. +//! +//! Everything else is checked before it is used: an object, a set, a +//! string, bytes or a `ret` that is NULL, a `reterr` that points to +//! anything but NULL, a descriptor that is negative, the size of a set, a +//! flag, a bit or a number that nothing here knows, a name of a file object +//! that is not UTF-8 or that is none for another reason, and a name of a +//! new file that names none. One number is not held to what the library +//! knows: uapi16_features_add() and uapi16_features_remove() take any +//! number that the set of the caller has room for, and a call that takes +//! the set checks its features. The pointers are turned into references, +//! borrowed descriptors, strings and slices where a function begins, in +//! [`Descriptor`], [`Text`], [`Bytes`], [`Place`], [`Refill`], +//! [`ErrorPlace`] and [`Object`], and everything after that is safe code. +//! The exceptions are [`Lent`], which holds a descriptor that a caller +//! lends to an object, [`SetWords`] and [`SetWordsMut`], which read and +//! write a set of features of a caller word by word, since it can be +//! shorter or longer than the library's, and two types that have nothing of +//! a caller: [`ForkCheck`], which maps the page that tells a child of a +//! fork(), and [`OnceBox`], which keeps what is made once. +//! +//! A panic does not unwind into C: a function with the C ABI aborts the +//! process instead. So does an allocation that fails. + +#![deny(unsafe_op_in_unsafe_fn)] +#![warn(clippy::undocumented_unsafe_blocks)] +// The types, the enumerators and the functions have the names C has for +// them. +#![allow(non_camel_case_types)] + +use std::borrow::Cow; +use std::cmp::Ordering; +use std::collections::BTreeMap; +use std::ffi::{c_char, c_int, c_void, CStr, CString, OsStr}; +use std::fs::File; +use std::io::{self, Read, Write}; +use std::marker::PhantomData; +use std::mem::{self, ManuallyDrop}; +use std::num::{NonZeroU64, NonZeroUsize}; +use std::ops::{Deref, DerefMut}; +use std::os::fd::{AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd}; +use std::os::unix::ffi::OsStrExt; +use std::path::Path; +use std::ptr::{self, NonNull}; +use std::slice; +use std::sync::atomic::{self, AtomicBool, AtomicPtr, AtomicUsize}; +use std::sync::Arc; + +use rustix::fs::IFlags; + +use crate::decode::ROOT_RECORD; +use crate::error::{ + DataProblem, Error, ErrorKind, Field, Problem, SourceProblem, TreeProblem, UnsupportedData, ValidityProblem, +}; +use crate::ioctl::DosAttributes; +use crate::name::NamePair; +use crate::reader::Object as Record; +use crate::sys::NewFile; +use crate::{ + AddFlags, ContentsObject, ContentsSource, DataCheck, DataLocation, ExternalFile, FatSerial, Features, FileObject, + FileSystemIdentity, InodeAttributes, InodeType, ManifestOptions, ManifestReport, ManifestWriter, Mode, Name, + NameProblem, Order, PinnedDirectory, Reader, RootObject, Sha256, Sha256Context, SignatureObject, Uuid, + ValidityWindow, Writer, +}; + +/// A feature of a manifest: what its file objects record. The features +/// are those of the specification, which spells them in lower case with +/// dashes: UAPI16_FEATURE_USER_XATTR is user-xattr. A feature is a number, +/// and a set of features is a uapi16_features_t. Later versions add +/// features after the last one. +/// +/// The features of partitions, UAPI16_FEATURE_GPT_LABEL to +/// UAPI16_FEATURE_GPT_FLAG_GROW_FILE_SYSTEM, don't apply to a tree of +/// files. No manifest writer is made for options that have one of them, and +/// the generate functions refuse them. The writer of records takes them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(C)] +enum uapi16_feature_t { + /// No feature. uapi16_feature_from_name() returns it for a name that no + /// feature has. + UAPI16_FEATURE_NONE = 0, + /// The access mode. + UAPI16_FEATURE_MODE = 1, + /// The user ID of the owner. + UAPI16_FEATURE_UID = 2, + /// The group ID of the owner. + UAPI16_FEATURE_GID = 3, + /// The name of the owning user, as the user database of the host has + /// it. + UAPI16_FEATURE_USER_NAME = 4, + /// The name of the owning group, as the user database of the host has + /// it. + UAPI16_FEATURE_GROUP_NAME = 5, + /// The size of the data of a regular file. + UAPI16_FEATURE_SIZE = 6, + /// The SHA-256 hash of the data of a regular file. + UAPI16_FEATURE_SHA256 = 7, + /// The targets of symbolic links. + UAPI16_FEATURE_SYMLINK = 8, + /// The major and minor numbers of device nodes. + UAPI16_FEATURE_DEVICE = 9, + /// Which file objects are names of one file. + UAPI16_FEATURE_HARDLINK = 10, + /// The modification time. + UAPI16_FEATURE_MTIME = 11, + /// The extended attributes of the user namespace. + /// + /// The generate functions open no file for its extended attributes. + /// Those of a file that is open anyway are read from the open file: a + /// directory that is walked into, a regular file whose data is hashed, + /// and a regular file or a directory that is opened for its inode + /// flags, its DOS attributes or the identity of its file system. Those + /// of any other file are read through /proc. Without a /proc they can't + /// be read, and it has to be the one of the kernel: whoever can mount + /// something else there can have such a file recorded with the + /// attributes of another one. + UAPI16_FEATURE_USER_XATTR = 12, + /// The DOS attribute hidden. + UAPI16_FEATURE_FLAG_HIDDEN = 13, + /// The DOS attribute system. + UAPI16_FEATURE_FLAG_SYSTEM = 14, + /// The DOS attribute archive. + UAPI16_FEATURE_FLAG_ARCHIVE = 15, + /// The inode flag append only. + UAPI16_FEATURE_FLAG_APPEND_ONLY = 16, + /// The inode flag immutable. + UAPI16_FEATURE_FLAG_IMMUTABLE = 17, + /// The inode flag no atime updates. + UAPI16_FEATURE_FLAG_NO_ATIME = 18, + /// The inode flag no copy on write. + UAPI16_FEATURE_FLAG_NO_COW = 19, + /// The inode flag no dump. + UAPI16_FEATURE_FLAG_NO_DUMP = 20, + /// Whether a file is read-only. + UAPI16_FEATURE_READ_ONLY = 21, + /// The UUID of the file system of the root. + /// + /// UAPI16_FEATURE_FS_UUID and UAPI16_FEATURE_FAT_SERIAL are read from the + /// root. A root whose file system has no UUID is written without one, + /// and so is one whose volume serial number can't be read, which only + /// FAT gives. Before Linux 6.9 no UUID can be read. Each is counted in + /// uapi16_manifest_report_fields_omitted() as well. A manifest without a + /// root has neither. + UAPI16_FEATURE_FS_UUID = 22, + /// The label of the file system of the root. + UAPI16_FEATURE_FS_LABEL = 23, + /// The volume serial number of the FAT file system of the root. + UAPI16_FEATURE_FAT_SERIAL = 24, + /// The label of a partition. + UAPI16_FEATURE_GPT_LABEL = 25, + /// The UUID of a partition. + UAPI16_FEATURE_GPT_UUID = 26, + /// The type UUID of a partition. + UAPI16_FEATURE_GPT_TYPE_UUID = 27, + /// The disk UUID of a partition table. + UAPI16_FEATURE_GPT_DISK_UUID = 28, + /// The attribute flags of a partition. + UAPI16_FEATURE_GPT_FLAGS = 29, + /// The partition attribute flag no auto. + UAPI16_FEATURE_GPT_FLAG_NO_AUTO = 30, + /// The partition attribute flag grow file system. + UAPI16_FEATURE_GPT_FLAG_GROW_FILE_SYSTEM = 31, +} + +/// The order a manifest lists its file objects in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u64)] +enum uapi16_order_t { + /// No order. With options that have it, uapi16_writer_begin() writes a + /// manifest that declares none, and uapi16_reader_order() returns it + /// for such a manifest. The functions that sort refuse options that + /// have it. + UAPI16_ORDER_NONE = 0, + /// The order of the code points of the names, component by component: + /// codepoint in the specification. + UAPI16_ORDER_CODEPOINT = 1, +} + +/// A flag of the generate functions. A set of them is a +/// uapi16_add_flags_t. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u64)] +enum uapi16_add_flag_t { + /// No flag. + // Only C names it: a set without a flag is 0 here. + #[allow(dead_code)] + UAPI16_ADD_NONE = 0, + /// Walk into mount points instead of writing them as empty + /// directories. + UAPI16_ADD_CROSS_MOUNTS = 1 << 0, + /// Leave out files whose names a manifest can't hold, a directory with + /// everything below it, and count them in + /// uapi16_manifest_report_entries_omitted(), instead of failing. + UAPI16_ADD_GRACEFUL = 1 << 1, +} + +/// What kind of error a uapi16_error is, with the errno of each kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u64)] +enum uapi16_error_kind_t { + /// Reading or writing failed. The errno is that of the system call + /// that failed, or EIO where none did. + UAPI16_ERROR_IO = 1, + /// The name of the file to create is taken. EEXIST. + UAPI16_ERROR_EXISTS = 2, + /// The same name was added for two different files that are not both + /// directories. EEXIST. + UAPI16_ERROR_DUPLICATE = 3, + /// A file changed while it was read. ESTALE. + UAPI16_ERROR_CHANGED = 4, + /// Two names of one inode don't show the same file. ESTALE. + UAPI16_ERROR_HARDLINK_MISMATCH = 5, + /// A file has a name that a manifest can't hold. EILSEQ for a name that + /// is not UTF-8, ENAMETOOLONG for one that is too long, and EINVAL for + /// any other. + UAPI16_ERROR_UNWRITABLE_NAME = 6, + /// A file that is not a directory is where a directory is needed. + /// ENOTDIR. + UAPI16_ERROR_NOT_DIRECTORY = 7, + /// A feature that was asked for can't be read here, or the data of a + /// file object is not data the library takes. EOPNOTSUPP. + UAPI16_ERROR_UNSUPPORTED = 8, + /// The call is not a valid one. EINVAL for a NULL object, set or + /// string, no `ret` for an object other than a report, an unknown flag + /// or order and a name that is none. EBADF for a negative descriptor. + /// ECHILD in a child of fork(). EINVAL for options with a feature of + /// partitions, which a call that makes a manifest writer checks after + /// the process, and for options whose order is UAPI16_ORDER_NONE in a + /// function that sorts, which checks them there too. + UAPI16_ERROR_INVALID_ARGUMENT = 9, + /// A directory is one of the directories it is in, because a mount + /// shows it again. ELOOP. + UAPI16_ERROR_LOOP = 10, + /// A directory that files were added below was not added itself, and + /// the features need what it would record. ENOENT. + UAPI16_ERROR_MISSING_PARENT = 11, + /// What a manifest records of a file is more than one of its records + /// has room for, such as more than 4 MiB of extended attributes. E2BIG. + UAPI16_ERROR_TOO_LARGE = 12, + /// The object takes nothing more: a writer, a computation or a check + /// that is finished, a writer that failed to write a record, or a + /// reader that failed to read an object. ESTALE. A call is checked for + /// what it is given first and for its process next, so one that is + /// UAPI16_ERROR_INVALID_ARGUMENT is that on such an object as well. + UAPI16_ERROR_ENDED = 13, + /// A manifest is malformed, or a file object is not one a manifest can + /// hold. uapi16_error_problem() names the rule that is broken, + /// uapi16_error_field() the field and uapi16_error_record() the record. + /// EBADMSG. + UAPI16_ERROR_MANIFEST = 14, + /// The file a manifest has the data of a file object in is not there. + /// ENOENT. + UAPI16_ERROR_SOURCE_MISSING = 15, + /// The file a manifest has the data of a file object in is not a regular + /// file. EINVAL. + UAPI16_ERROR_SOURCE_NOT_REGULAR = 16, + /// The data of a file is not as many bytes as the manifest says, or its + /// file is too short for it. EBADMSG. + UAPI16_ERROR_SIZE_MISMATCH = 17, + /// The data of a file does not have the hash the manifest says. EBADMSG. + UAPI16_ERROR_HASH_MISMATCH = 18, + /// A file object or a manifest is revoked. EKEYREVOKED. + UAPI16_ERROR_REVOKED = 19, + /// The time is before the one a file object or a manifest may be used + /// from. EKEYEXPIRED. + UAPI16_ERROR_NOT_YET_VALID = 20, + /// The time is not before the one a file object or a manifest may be + /// used until. EKEYEXPIRED. + UAPI16_ERROR_EXPIRED = 21, +} + +/// Which rule of the names of a manifest a name breaks. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u64)] +enum uapi16_name_problem_t { + /// It is not UTF-8. + UAPI16_NAME_PROBLEM_NOT_UTF8 = 1, + /// It is empty. + UAPI16_NAME_PROBLEM_EMPTY = 2, + /// It is longer than 4095 bytes. + UAPI16_NAME_PROBLEM_TOO_LONG = 3, + /// Its first component is Uapi16Manifest or begins with + /// Uapi16Manifest., which the specification reserves. + UAPI16_NAME_PROBLEM_RESERVED = 4, + /// It has a control character: ASCII 0 to 31 or 127. + UAPI16_NAME_PROBLEM_CONTROL_CHARACTER = 5, + /// It has a Unicode noncharacter. + UAPI16_NAME_PROBLEM_NONCHARACTER = 6, + /// One of its components is empty: it begins or ends with a slash, or + /// has two slashes in a row. + UAPI16_NAME_PROBLEM_EMPTY_COMPONENT = 7, + /// One of its components is "." or "..". + UAPI16_NAME_PROBLEM_DOT_COMPONENT = 8, +} + +/// Where the data of a file object is, as uapi16_file_object_data_location() +/// finds it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u64)] +enum uapi16_data_location_t { + /// Nowhere: the object has no data. + UAPI16_DATA_LOCATION_NONE = 0, + /// In the manifest itself. uapi16_file_object_literal() gives it. + UAPI16_DATA_LOCATION_LITERAL = 1, + /// In a file next to the manifest. uapi16_directory_open_data() opens + /// it. + UAPI16_DATA_LOCATION_EXTERNAL = 2, + /// At a URL or in an encoding. The library neither fetches nor decodes + /// data. + UAPI16_DATA_LOCATION_UNSUPPORTED = 3, +} + +/// A flag of uapi16_directory_new(). A set of them is a +/// uapi16_directory_flags_t. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u64)] +enum uapi16_directory_flag_t { + /// No flag. + // Only C names it: a set without a flag is 0 here. + #[allow(dead_code)] + UAPI16_DIRECTORY_NONE = 0, + /// Follow symbolic links below the directory, 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. Without this flag a + /// name that leads through a symbolic link fails with ELOOP. + UAPI16_DIRECTORY_FOLLOW_SYMLINKS = 1 << 0, +} + +/// Whether a file object says that its file is read-only. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u64)] +enum uapi16_read_only_t { + /// The object does not say. + UAPI16_READ_ONLY_UNSTATED = 0, + /// The file is not read-only. + UAPI16_READ_ONLY_NO = 1, + /// The file is read-only. + UAPI16_READ_ONLY_YES = 2, +} + +/// Where one name comes to another in the code point order, as +/// uapi16_name_compare() returns it. This is the one signed enum: its +/// numbers are those a comparison function of qsort() returns. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(i64)] +enum uapi16_name_order_t { + /// The first name comes before the second. + UAPI16_NAME_BEFORE = -1, + /// The two names are the same. + UAPI16_NAME_SAME = 0, + /// The first name comes after the second. + UAPI16_NAME_AFTER = 1, +} + +/// What uapi16_reader_next() and uapi16_reader_next_signature() read. Each +/// returns one of these as an int, or a negative errno. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u64)] +enum uapi16_read_t { + /// The trailer was read and checked. The manifest is complete. + UAPI16_READ_END = 0, + /// One file object was read, and is in `ret`. + UAPI16_READ_FILE = 1, + /// The file objects have ended, and signature objects follow. From now + /// on uapi16_reader_signed_len() has what they sign. + UAPI16_READ_SIGNATURES = 2, + /// One signature object was read, and is in `ret`. Only + /// uapi16_reader_next_signature() returns this. + UAPI16_READ_SIGNATURE = 3, +} + +/// A set of uapi16_add_flag_t: their bitwise OR. +type uapi16_add_flags_t = u64; + +/// A set of uapi16_directory_flag_t: their bitwise OR. +type uapi16_directory_flags_t = u64; + +/// The token of a file, see uapi16_file_object_set_inode_token(). +type uapi16_inode_token_t = u64; + +/// The number that is no token, see uapi16_file_object_set_inode_token(). +// cbindgen writes only the constants that are pub. +#[allow(unreachable_pub)] +pub const UAPI16_INODE_TOKEN_NONE: uapi16_inode_token_t = 0; + +// How many bytes a UUID has, and how many uint64_t that is. cbindgen writes +// only the constants that are pub, and it takes a number or one name as +// the length of an array, so the second one is a constant of its own. +/// The size of a UUID in bytes: the length of uapi16_uuid_t's bytes. +#[allow(unreachable_pub)] +pub const UAPI16_UUID_SIZE: usize = 16; +/// The number of 64-bit words of a UUID: the length of uapi16_uuid_t's +/// qwords. +#[allow(unreachable_pub)] +pub const UAPI16_UUID_QWORDS: usize = 2; + +const _: () = assert!(UAPI16_UUID_QWORDS * size_of::() == UAPI16_UUID_SIZE); + +/// A UUID, as the fs-uuid field carries one. +#[repr(C)] +union uapi16_uuid_t { + bytes: [u8; UAPI16_UUID_SIZE], + qwords: [u64; UAPI16_UUID_QWORDS], +} + +// The same for a SHA-256 hash. +/// The size of a SHA-256 hash in bytes: the length of +/// uapi16_sha256_digest_t's bytes. +#[allow(unreachable_pub)] +pub const UAPI16_SHA256_SIZE: usize = 32; +/// The number of 64-bit words of a SHA-256 hash: the length of +/// uapi16_sha256_digest_t's qwords. +#[allow(unreachable_pub)] +pub const UAPI16_SHA256_QWORDS: usize = 4; + +const _: () = assert!(UAPI16_SHA256_QWORDS * size_of::() == UAPI16_SHA256_SIZE); + +/// A SHA-256 hash. +#[repr(C)] +union uapi16_sha256_digest_t { + bytes: [u8; UAPI16_SHA256_SIZE], + qwords: [u64; UAPI16_SHA256_QWORDS], +} + +// A word more is a line more in UAPI16_FEATURES_SET(), which is written by +// hand in cbindgen.toml. A test holds the two together. +/// The number of 64-bit words of a uapi16_features_t, each with room for 64 +/// features. +#[allow(unreachable_pub)] +pub const UAPI16_FEATURES_WORDS: usize = 2; +/// The first size of a uapi16_features_t in bytes, which every library +/// takes. +#[allow(unreachable_pub)] +pub const UAPI16_FEATURES_SIZE_VER0: usize = 24; +/// The largest size of a uapi16_features_t in bytes. +#[allow(unreachable_pub)] +pub const UAPI16_FEATURES_SIZE_MAX: usize = 4096; + +/// A set of features that a program owns. UAPI16_FEATURES_EMPTY and +/// UAPI16_FEATURES_SET() make one. +#[repr(C)] +struct uapi16_features_t { + /// sizeof(uapi16_features_t), in bytes. + size: u64, + /// The features: feature f is bit (f - 1) % 64 of word (f - 1) / 64. + words: [u64; UAPI16_FEATURES_WORDS], +} + +// A set is its size and its words, each a uint64_t, with nothing between +// them, which is how capi.rs reads the set of a caller. The first size is +// that of the set this library has, and the largest one is a size a set +// can have. +const _: () = { + assert!(mem::offset_of!(uapi16_features_t, size) == 0); + assert!(mem::offset_of!(uapi16_features_t, words) == size_of::()); + assert!(size_of::() == size_of::() * (1 + UAPI16_FEATURES_WORDS)); + assert!(size_of::() == UAPI16_FEATURES_SIZE_VER0); + assert!(align_of::() == align_of::()); + assert!(UAPI16_FEATURES_SIZE_MAX >= UAPI16_FEATURES_SIZE_VER0); + assert!(UAPI16_FEATURES_SIZE_MAX % size_of::() == 0); +}; + +/// A number of uapi16_order_t as a caller passes it: any number, since +/// nothing holds C to those of the enum. uapi16.h has it as +/// uapi16_order_t, see cbindgen.toml. +/// cbindgen:no-export +type OrderNumber = u64; +/// A number of uapi16_error_kind_t as a caller gets it, or 0 for none. +/// uapi16.h has it as uapi16_error_kind_t. +/// cbindgen:no-export +type ErrorKindNumber = u64; +/// A number of uapi16_feature_t as a caller passes it and gets it, or 0 for +/// none: any number of 32 bits, since nothing holds C to those of the enum. +/// uapi16.h has it as uapi16_feature_t, the one enum that is a plain enum +/// of C and not 64 bits wide. +/// cbindgen:no-export +type FeatureNumber = u32; +/// A number of uapi16_name_problem_t as a caller gets it, or 0 for none. +/// uapi16.h has it as uapi16_name_problem_t. +/// cbindgen:no-export +type NameProblemNumber = u64; +/// A number of uapi16_data_location_t as a caller gets it, or 0 for none. +/// uapi16.h has it as uapi16_data_location_t. +/// cbindgen:no-export +type DataLocationNumber = u64; +/// A number of uapi16_read_only_t as a caller passes it and gets it. +/// uapi16.h has it as uapi16_read_only_t. +/// cbindgen:no-export +type ReadOnlyNumber = u64; + +impl uapi16_read_only_t { + /// Every answer, as C has it and as Rust has it. + const ALL: [(uapi16_read_only_t, Option); 3] = [ + (uapi16_read_only_t::UAPI16_READ_ONLY_UNSTATED, None), + (uapi16_read_only_t::UAPI16_READ_ONLY_NO, Some(false)), + (uapi16_read_only_t::UAPI16_READ_ONLY_YES, Some(true)), + ]; + + /// What C has for what a file object says of `readOnly`. + fn of(read_only: Option) -> uapi16_read_only_t { + let mut all = uapi16_read_only_t::ALL.into_iter(); + let found = all.find(|(_, rust)| *rust == read_only); + found.map_or(uapi16_read_only_t::UAPI16_READ_ONLY_UNSTATED, |(c, _)| c) + } + + /// What a file object says of `readOnly` for the number `read_only` of + /// a caller. A number that is none of the enum fails. + fn of_number(read_only: ReadOnlyNumber) -> Result, uapi16_error> { + let mut all = uapi16_read_only_t::ALL.into_iter(); + let found = all.find(|(c, _)| *c as ReadOnlyNumber == read_only); + found.map(|(_, rust)| rust).ok_or_else(uapi16_error::misuse) + } +} + +impl uapi16_name_order_t { + /// What C has for the ordering `ordering` of two names. + fn of(ordering: Ordering) -> uapi16_name_order_t { + match ordering { + Ordering::Less => uapi16_name_order_t::UAPI16_NAME_BEFORE, + Ordering::Equal => uapi16_name_order_t::UAPI16_NAME_SAME, + Ordering::Greater => uapi16_name_order_t::UAPI16_NAME_AFTER, + } + } +} + +/// A value that is made when it is first asked for, and kept: what a +/// OnceLock is, without its lock. +/// +/// A lock would be held while the value is made. Another thread can fork at +/// any time, and its child has that one thread: there the lock is never +/// released, and whoever asks for the same value waits for it forever. So +/// no thread waits for another here. Threads that ask at the same time make +/// a value each. The one that is stored first is the value, and the others +/// drop theirs. +#[derive(Debug)] +struct OnceBox { + /// The value, which was a Box, or null as long as there is none. + value: AtomicPtr, + /// The cell owns the value, though it holds it as a pointer. + owned: PhantomData>, +} + +impl OnceBox { + /// A cell without a value. + const fn new() -> OnceBox { + OnceBox { + value: AtomicPtr::new(ptr::null_mut()), + owned: PhantomData, + } + } + + /// Forgets the value, so that the next one who asks has it made anew. + fn reset(&mut self) { + let value = mem::replace(self.value.get_mut(), ptr::null_mut()); + if !value.is_null() { + // SAFETY: `value` came from Box::into_raw() in get_or_init() and + // was stored, so the cell owns it. Nothing borrows it any more: + // every borrow of it is one of the cell, which is borrowed + // mutably here. + drop(unsafe { Box::from_raw(value) }); + } + } +} + +// A value can be made by one thread and dropped by another, and several +// threads can read it at once. +impl OnceBox { + /// The value, which `make` makes where there is none yet. + fn get_or_init(&self, make: impl FnOnce() -> T) -> &T { + let mut value = self.value.load(atomic::Ordering::Acquire); + if value.is_null() { + let made = Box::into_raw(Box::new(make())); + let stored = self.value.compare_exchange( + ptr::null_mut(), + made, + atomic::Ordering::AcqRel, + atomic::Ordering::Acquire, + ); + value = match stored { + Ok(_) => made, + Err(theirs) => { + // SAFETY: `made` came from Box::into_raw() just now and + // was not stored, so nothing else has it. + drop(unsafe { Box::from_raw(made) }); + theirs + } + }; + } + // SAFETY: `value` came from Box::into_raw() and was stored, so the + // cell owns it, and it is dropped by reset() and by drop() alone. + // Both borrow the cell mutably, which they can't while this borrow + // of it lasts. + unsafe { &*value } + } +} + +impl Default for OnceBox { + fn default() -> OnceBox { + OnceBox::new() + } +} + +impl Drop for OnceBox { + fn drop(&mut self) { + self.reset(); + } +} + +/// The names the library hands out as constants: those the specification +/// has for a field, for a rule and for a feature. Rust has each as a +/// `&'static str`, and C takes a string that ends in a NUL. So a copy of a +/// name is made when it is first asked for, and stays for as long as the +/// process runs. +#[derive(Debug)] +struct Constants([OnceBox>; N]); + +impl Constants { + /// Room for `N` names, none of which was asked for yet. + const fn new() -> Constants { + Constants([const { OnceBox::new() }; N]) + } + + /// The name `name`, which is number `index` of these, as C takes it. + /// None for a number these have no room for, and for a name with a NUL, + /// which the specification has none of. + fn get(&'static self, index: usize, name: &'static str) -> Option<&'static CStr> { + let slot = self.0.get(index)?; + slot.get_or_init(|| CString::new(name).ok()).as_deref() + } +} + +/// The names of the fields, each at the number of its field. They have +/// room for more fields than there are. +static FIELD_NAMES: Constants<{ u8::MAX as usize + 1 }> = Constants::new(); +/// The names of the rules of the specification, each at the number of its +/// rule. +static PROBLEM_NAMES: Constants<{ Problem::ALL.len() }> = Constants::new(); +/// The names of the features, each at the place of its feature in +/// [`uapi16_feature_t::ALL`]. +static FEATURE_NAMES: Constants<{ uapi16_feature_t::ALL.len() }> = Constants::new(); + +impl Field { + /// The field as the specification spells it, as C takes it. + fn c_name(self) -> Option<&'static CStr> { + FIELD_NAMES.get(self as usize, self.as_str()) + } +} + +impl Problem { + /// The name of the rule, which never changes, as C takes it. + fn c_name(self) -> Option<&'static CStr> { + PROBLEM_NAMES.get(self as usize, self.as_str()) + } +} + +impl uapi16_feature_t { + /// Every single feature as C has it, in the order of their numbers. It + /// has as many entries as Rust has features, so one that is missing + /// does not build. + const ALL: [uapi16_feature_t; Features::count()] = [ + uapi16_feature_t::UAPI16_FEATURE_MODE, + uapi16_feature_t::UAPI16_FEATURE_UID, + uapi16_feature_t::UAPI16_FEATURE_GID, + uapi16_feature_t::UAPI16_FEATURE_USER_NAME, + uapi16_feature_t::UAPI16_FEATURE_GROUP_NAME, + uapi16_feature_t::UAPI16_FEATURE_SIZE, + uapi16_feature_t::UAPI16_FEATURE_SHA256, + uapi16_feature_t::UAPI16_FEATURE_SYMLINK, + uapi16_feature_t::UAPI16_FEATURE_DEVICE, + uapi16_feature_t::UAPI16_FEATURE_HARDLINK, + uapi16_feature_t::UAPI16_FEATURE_MTIME, + uapi16_feature_t::UAPI16_FEATURE_USER_XATTR, + uapi16_feature_t::UAPI16_FEATURE_FLAG_HIDDEN, + uapi16_feature_t::UAPI16_FEATURE_FLAG_SYSTEM, + uapi16_feature_t::UAPI16_FEATURE_FLAG_ARCHIVE, + uapi16_feature_t::UAPI16_FEATURE_FLAG_APPEND_ONLY, + uapi16_feature_t::UAPI16_FEATURE_FLAG_IMMUTABLE, + uapi16_feature_t::UAPI16_FEATURE_FLAG_NO_ATIME, + uapi16_feature_t::UAPI16_FEATURE_FLAG_NO_COW, + uapi16_feature_t::UAPI16_FEATURE_FLAG_NO_DUMP, + uapi16_feature_t::UAPI16_FEATURE_READ_ONLY, + uapi16_feature_t::UAPI16_FEATURE_FS_UUID, + uapi16_feature_t::UAPI16_FEATURE_FS_LABEL, + uapi16_feature_t::UAPI16_FEATURE_FAT_SERIAL, + uapi16_feature_t::UAPI16_FEATURE_GPT_LABEL, + uapi16_feature_t::UAPI16_FEATURE_GPT_UUID, + uapi16_feature_t::UAPI16_FEATURE_GPT_TYPE_UUID, + uapi16_feature_t::UAPI16_FEATURE_GPT_DISK_UUID, + uapi16_feature_t::UAPI16_FEATURE_GPT_FLAGS, + uapi16_feature_t::UAPI16_FEATURE_GPT_FLAG_NO_AUTO, + uapi16_feature_t::UAPI16_FEATURE_GPT_FLAG_GROW_FILE_SYSTEM, + ]; + + /// The feature of Rust that the enumerator is: the one of its name. + /// None for UAPI16_FEATURE_NONE. The match has every enumerator, so + /// one that is added to the enum does not build until it is here. + const fn rust(self) -> Option { + match self { + uapi16_feature_t::UAPI16_FEATURE_NONE => None, + uapi16_feature_t::UAPI16_FEATURE_MODE => Some(Features::MODE), + uapi16_feature_t::UAPI16_FEATURE_UID => Some(Features::UID), + uapi16_feature_t::UAPI16_FEATURE_GID => Some(Features::GID), + uapi16_feature_t::UAPI16_FEATURE_USER_NAME => Some(Features::USER_NAME), + uapi16_feature_t::UAPI16_FEATURE_GROUP_NAME => Some(Features::GROUP_NAME), + uapi16_feature_t::UAPI16_FEATURE_SIZE => Some(Features::SIZE), + uapi16_feature_t::UAPI16_FEATURE_SHA256 => Some(Features::SHA256), + uapi16_feature_t::UAPI16_FEATURE_SYMLINK => Some(Features::SYMLINK), + uapi16_feature_t::UAPI16_FEATURE_DEVICE => Some(Features::DEVICE), + uapi16_feature_t::UAPI16_FEATURE_HARDLINK => Some(Features::HARDLINK), + uapi16_feature_t::UAPI16_FEATURE_MTIME => Some(Features::MTIME), + uapi16_feature_t::UAPI16_FEATURE_USER_XATTR => Some(Features::USER_XATTR), + uapi16_feature_t::UAPI16_FEATURE_FLAG_HIDDEN => Some(Features::FLAG_HIDDEN), + uapi16_feature_t::UAPI16_FEATURE_FLAG_SYSTEM => Some(Features::FLAG_SYSTEM), + uapi16_feature_t::UAPI16_FEATURE_FLAG_ARCHIVE => Some(Features::FLAG_ARCHIVE), + uapi16_feature_t::UAPI16_FEATURE_FLAG_APPEND_ONLY => Some(Features::FLAG_APPEND_ONLY), + uapi16_feature_t::UAPI16_FEATURE_FLAG_IMMUTABLE => Some(Features::FLAG_IMMUTABLE), + uapi16_feature_t::UAPI16_FEATURE_FLAG_NO_ATIME => Some(Features::FLAG_NO_ATIME), + uapi16_feature_t::UAPI16_FEATURE_FLAG_NO_COW => Some(Features::FLAG_NO_COW), + uapi16_feature_t::UAPI16_FEATURE_FLAG_NO_DUMP => Some(Features::FLAG_NO_DUMP), + uapi16_feature_t::UAPI16_FEATURE_READ_ONLY => Some(Features::READ_ONLY), + uapi16_feature_t::UAPI16_FEATURE_FS_UUID => Some(Features::FS_UUID), + uapi16_feature_t::UAPI16_FEATURE_FS_LABEL => Some(Features::FS_LABEL), + uapi16_feature_t::UAPI16_FEATURE_FAT_SERIAL => Some(Features::FAT_SERIAL), + uapi16_feature_t::UAPI16_FEATURE_GPT_LABEL => Some(Features::GPT_LABEL), + uapi16_feature_t::UAPI16_FEATURE_GPT_UUID => Some(Features::GPT_UUID), + uapi16_feature_t::UAPI16_FEATURE_GPT_TYPE_UUID => Some(Features::GPT_TYPE_UUID), + uapi16_feature_t::UAPI16_FEATURE_GPT_DISK_UUID => Some(Features::GPT_DISK_UUID), + uapi16_feature_t::UAPI16_FEATURE_GPT_FLAGS => Some(Features::GPT_FLAGS), + uapi16_feature_t::UAPI16_FEATURE_GPT_FLAG_NO_AUTO => Some(Features::GPT_FLAG_NO_AUTO), + uapi16_feature_t::UAPI16_FEATURE_GPT_FLAG_GROW_FILE_SYSTEM => Some(Features::GPT_FLAG_GROW_FILE_SYSTEM), + } + } + + /// The number C has for the single feature `feature`, as an error + /// names one. + fn of(feature: Features) -> Option { + let mut all = uapi16_feature_t::ALL.into_iter(); + all.find(|c| c.rust() == Some(feature)) + } + + /// The place in [`uapi16_feature_t::ALL`] of the feature with the number + /// `feature`, which is that place and one more. None for + /// UAPI16_FEATURE_NONE and for a number that is no feature. + fn place_of(feature: FeatureNumber) -> Option { + let place = usize::try_from(feature.checked_sub(1)?).ok()?; + (place < uapi16_feature_t::ALL.len()).then_some(place) + } + + /// The feature Rust has for the number `feature`. None for + /// UAPI16_FEATURE_NONE and for a number that is no feature. + fn rust_of(feature: FeatureNumber) -> Option { + uapi16_feature_t::place_of(feature).and_then(|place| uapi16_feature_t::ALL[place].rust()) + } + + /// The name the specification has for the feature with the number + /// `feature`, as C takes it. None for a number that is not one feature. + fn name_of(feature: FeatureNumber) -> Option<&'static CStr> { + let place = uapi16_feature_t::place_of(feature)?; + let name = uapi16_feature_t::ALL[place].rust()?.names().next()?; + FEATURE_NAMES.get(place, name) + } +} + +// A feature goes between C and Rust as its number, which is its place in +// the table and one more. What holds the enum of C, the table and the +// features of Rust together where the crate is built: +// - The table has an entry for each feature of Rust, since it is an array +// of as many. +// - The match of uapi16_feature_t::rust() gives an enumerator the feature +// of Rust of its name. It has every enumerator, so one that is added +// does not build until it is there. +// - Entry i of the table has the number i + 1, and the feature the match +// gives it is the bit i and no other. All of them together are every +// feature of Rust. +// So the numbers of the table have no gap, each of its enumerators has +// the number of the feature of its name, and C has every feature Rust +// has. A set of C has the bit of a feature where the set of Rust has it, +// and room for every feature. The plain enum C has for a feature is as +// wide as the number capi.rs takes for one. None of that builds otherwise. +const _: () = { + assert!(uapi16_feature_t::ALL.len() <= UAPI16_FEATURES_WORDS * u64::BITS as usize); + assert!(uapi16_feature_t::UAPI16_FEATURE_NONE as u64 == 0); + assert!(uapi16_feature_t::UAPI16_FEATURE_NONE.rust().is_none()); + let mut all = Features::NONE; + let mut next = 0; + while next < uapi16_feature_t::ALL.len() { + let c = uapi16_feature_t::ALL[next]; + assert!(c as u64 == next as u64 + 1); + let rust = match c.rust() { + Some(rust) => rust, + None => panic!("an enumerator of the table is no feature"), + }; + let mut word = 0; + while word < UAPI16_FEATURES_WORDS { + let bit = if word == next / u64::BITS as usize { + 1 << (next % u64::BITS as usize) + } else { + 0 + }; + assert!(rust.word(word) == bit); + word += 1; + } + all = all.union(rust); + next += 1; + } + assert!(all.contains(Features::ALL) && Features::ALL.contains(all)); + assert!(size_of::() == size_of::()); +}; + +impl Features { + /// Whether the set has the feature with the number `feature` of C. It + /// has none for a number that is no feature. + fn has_number(self, feature: FeatureNumber) -> bool { + uapi16_feature_t::rust_of(feature).is_some_and(|rust| self.contains(rust)) + } +} + +impl uapi16_name_problem_t { + /// The number C has for `problem`. A name with more than one component + /// where one is taken has none: no name gets here that way. A caller + /// in C passes whole names, and the kernel lists no name with a slash + /// in a directory. + fn of(problem: NameProblem) -> Option { + Some(match problem { + NameProblem::NotUtf8 => uapi16_name_problem_t::UAPI16_NAME_PROBLEM_NOT_UTF8, + NameProblem::Empty => uapi16_name_problem_t::UAPI16_NAME_PROBLEM_EMPTY, + NameProblem::TooLong => uapi16_name_problem_t::UAPI16_NAME_PROBLEM_TOO_LONG, + NameProblem::Reserved => uapi16_name_problem_t::UAPI16_NAME_PROBLEM_RESERVED, + NameProblem::ContainsControlCharacter => uapi16_name_problem_t::UAPI16_NAME_PROBLEM_CONTROL_CHARACTER, + NameProblem::ContainsNoncharacter => uapi16_name_problem_t::UAPI16_NAME_PROBLEM_NONCHARACTER, + NameProblem::EmptyComponent => uapi16_name_problem_t::UAPI16_NAME_PROBLEM_EMPTY_COMPONENT, + NameProblem::ContainsDotComponent => uapi16_name_problem_t::UAPI16_NAME_PROBLEM_DOT_COMPONENT, + NameProblem::ContainsSeparator => return None, + }) + } +} + +/// The process an object of the C API was made in. After fork() the child +/// has the objects of its parent, and must not use them: they share +/// descriptors, scratch files and a file that is not complete with the +/// parent. A call on such an object fails with ECHILD. +/// +/// A process is known by its generation, see [`ForkCheck`]: a number that +/// the child of a fork() does not have in common with its parent. An object +/// has the generation of the process that made it. +/// +/// A call is checked in the order sd-bus checks one: what it is given +/// first, an object, a string, a flag, a name or a descriptor, which fails +/// with EINVAL or EBADF, then the process, and then what the options and +/// the writer say of themselves: the features of the options where a +/// writer is made, and whether the writer takes anything more. Nothing is +/// done before the process is checked. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Process { + /// A process with its generation. + Known(NonZeroUsize), + /// A process without a generation, since its line of processes used up + /// every one of them. No object is an object of such a process, also + /// none it makes itself. + Spent, + /// A process that nothing tells from its children: the kernel gave it + /// no page that is wiped in a child, see [`ForkCheck::of_process`]. + /// Nothing is checked there. A child uses the objects of its parent + /// like its own, and frees them like its parent would. + Untold, +} + +impl Process { + /// The process that is running. + fn current() -> Process { + match ForkCheck::of_process() { + Some(check) => check.generation().map_or(Process::Spent, Process::Known), + None => Process::Untold, + } + } + + /// Fails in any process but this one. + fn check(self) -> Result<(), uapi16_error> { + if self.is(Process::current()) { + Ok(()) + } else { + Err(uapi16_error::refused(libc::ECHILD)) + } + } + + /// Whether this is the process `running`, as far as that can be told. + /// A process without a generation is no process that is known, not even + /// itself. Where nothing tells a child, every process passes for the + /// one that is running. So does the process of an object that was made + /// without a page, also in a process that has one by now. + fn is(self, running: Process) -> bool { + match (self, running) { + (Process::Known(made), Process::Known(now)) => made == now, + (Process::Spent, _) | (_, Process::Spent) => false, + (Process::Untold, _) | (_, Process::Untold) => true, + } + } +} + +/// How a process finds out that it is the child of a fork(), which has the +/// objects of its parent in its memory: by a page of memory that a child +/// gets filled with zeroes, one with MADV_WIPEONFORK, see madvise(2). The +/// page holds the generation of the process, which is never 0. A child +/// finds 0 there and takes the next generation. So a child is known also +/// where it has the PID of its parent, as the first process of a new PID +/// namespace can have, and no call asks the kernel for a PID. +#[derive(Clone, Copy, Debug)] +struct ForkCheck(&'static AtomicUsize); + +impl ForkCheck { + /// How many bytes are mapped for the generation. The kernel maps whole + /// pages, so this is one page. + const LEN: usize = size_of::(); + + /// The first generation. 0 is what a page holds that has none. + const FIRST: usize = 1; + + /// The page of this process, by which it and its children are told + /// apart. None where the kernel makes no such page: an old one, or one + /// that a seccomp filter keeps a process from. Nothing tells a child + /// there, and there is nothing to fall back to: the calls go on, in a + /// child as in its parent. The first call of a process finds that out, + /// and a child has what its parent found. + /// + /// No lock is held for that. Another thread can fork at any time, and + /// its child has that one thread: a lock that another thread of the + /// parent held is never released there, and the first call of the child + /// would wait for it forever. So threads that make the first call at + /// the same time map a page each. The page that is stored first is the + /// page of the process, and the other threads unmap theirs. A child that + /// is forked before a page is stored maps its own. + fn of_process() -> Option { + /// The page of this process, or null as long as it has none. + static FOUND: AtomicPtr = AtomicPtr::new(ptr::null_mut()); + /// Whether the kernel refused the page, so that it is asked once + /// and not at every call. + /// + /// A refusal need not last. A mmap() can fail once, in a thread + /// whose first call comes while another thread stores a page. The + /// process has its page then, and that one call goes on without + /// it: an object it makes is of no process that is told, and passes + /// in every child, see [`Process::is`]. Nothing is done about + /// that. It is what every object is like where the kernel has no + /// such page, and there the calls are to go on. + static REFUSED: AtomicBool = AtomicBool::new(false); + let mut found = FOUND.load(atomic::Ordering::Acquire); + if found.is_null() { + if REFUSED.load(atomic::Ordering::Relaxed) { + return None; + } + let Some(mine) = ForkCheck::wiped_page() else { + REFUSED.store(true, atomic::Ordering::Relaxed); + return None; + }; + let stored = FOUND.compare_exchange( + ptr::null_mut(), + mine.as_ptr(), + atomic::Ordering::AcqRel, + atomic::Ordering::Acquire, + ); + found = match stored { + Ok(_) => mine.as_ptr(), + Err(theirs) => { + // SAFETY: `mine` is a mapping of wiped_page() that was + // not stored, so nothing refers to the mapping that + // goes. + unsafe { libc::munmap(mine.as_ptr().cast(), ForkCheck::LEN) }; + theirs + } + }; + } + // SAFETY: `found` is a mapping of wiped_page() that was stored as + // the page of the process, and such a mapping is never unmapped. It + // is as large as an AtomicUsize at least and starts at a page, so + // it is aligned for one. It is readable and writable, and it was + // made of zeroes, which are a value of it. Nothing reads or writes + // it but through references like this one, and the kernel, which + // fills it with zeroes for a child: the child starts with that, and + // an atomic is read anew each time. + Some(ForkCheck(unsafe { &*found })) + } + + /// Maps a page that a child of a fork() gets filled with zeroes. None + /// where the kernel refuses the mapping or does not wipe it. + fn wiped_page() -> Option> { + // Miri has no such madvise(), and stops at it. So there is no + // page under Miri, as on a kernel that refuses one. + if cfg!(miri) { + return None; + } + let protection = libc::PROT_READ | libc::PROT_WRITE; + let flags = libc::MAP_PRIVATE | libc::MAP_ANONYMOUS; + // SAFETY: a new mapping of memory that belongs to no file, at an + // address the kernel picks, changes nothing that is mapped. + let page = unsafe { libc::mmap(ptr::null_mut(), ForkCheck::LEN, protection, flags, -1, 0) }; + if page == libc::MAP_FAILED { + return None; + } + // SAFETY: `page` is the mapping that was just made, and nothing + // else has it. + if unsafe { libc::madvise(page, ForkCheck::LEN, libc::MADV_WIPEONFORK) } != 0 { + // SAFETY: as above, so nothing refers to the mapping that goes. + unsafe { libc::munmap(page, ForkCheck::LEN) }; + return None; + } + NonNull::new(page.cast()) + } + + /// The generation of the process that is running. None for a process + /// whose line of processes used up every generation. + fn generation(self) -> Option { + /// The generation that is handed out next. A child has the count of + /// its parent. + static NEXT: AtomicUsize = AtomicUsize::new(ForkCheck::FIRST); + ForkCheck::generation_of(self.0, &NEXT) + } + + /// The generation `page` holds. A page that holds 0 is one that no + /// generation was stored in yet: that of a process that was just + /// forked, or one that was just mapped. It gets the generation `next` + /// counts, which is above every one that was handed out before. Threads + /// that find 0 at the same time agree on the generation of the one that + /// stores it first. + /// + /// The count stops at its end and does not start over, since a + /// generation that comes again would be that of an object of a process + /// long before. A page gets none then, and neither does a page of any + /// child after it. + fn generation_of(page: &AtomicUsize, next: &AtomicUsize) -> Option { + let held = match page.load(atomic::Ordering::Acquire) { + 0 => { + let taken = ForkCheck::counted(next)?; + let stored = page.compare_exchange(0, taken, atomic::Ordering::AcqRel, atomic::Ordering::Acquire); + stored.map_or_else(|theirs| theirs, |_| taken) + } + held => held, + }; + NonZeroUsize::new(held) + } + + /// Takes the generation `next` is at, and counts one up. None once the + /// count is at its end, where it stays. + fn counted(next: &AtomicUsize) -> Option { + let mut taken = next.load(atomic::Ordering::Relaxed); + loop { + let after = taken.checked_add(1)?; + match next.compare_exchange_weak(taken, after, atomic::Ordering::Relaxed, atomic::Ordering::Relaxed) { + Ok(_) => return Some(taken), + Err(now) => taken = now, + } + } + } +} + +/// A descriptor as a caller passes it: a number, which is one of its open +/// descriptors unless it is negative. +#[derive(Clone, Copy, Debug)] +struct Descriptor<'fd>(c_int, PhantomData>); + +impl<'fd> Descriptor<'fd> { + /// The descriptor `fd` of a caller. + /// + /// # Safety + /// + /// Unless `fd` is negative, it is an open descriptor, and stays open + /// for `'fd`. + unsafe fn new(fd: c_int) -> Descriptor<'fd> { + Descriptor(fd, PhantomData) + } + + /// Borrows the descriptor. A negative number is none, also AT_FDCWD, + /// which stands for a directory only where a path is looked up. + fn borrow(self) -> Result, uapi16_error> { + if self.0 < 0 { + return Err(uapi16_error::refused(uapi16_error::NO_DESCRIPTOR)); + } + // SAFETY: the number is not negative, so it is not -1, and whoever + // made this said that it is an open descriptor then, which stays + // open for `'fd`. + Ok(unsafe { BorrowedFd::borrow_raw(self.0) }) + } + + /// Lends the descriptor to what `make` makes of it, which holds it as + /// if it owned it. Nothing closes the descriptor all the same, and no + /// duplicate is made of it: the [`Lent`] this returns gives it back + /// when it is dropped. + /// + /// # Safety + /// + /// The descriptor stays open until what this returns is dropped. + /// `make` returns the descriptor inside what it makes of it. + unsafe fn lend(self, make: impl FnOnce(OwnedFd) -> T) -> Result, uapi16_error> { + let fd = self.borrow()?; + // SAFETY: the descriptor is open, and stays open for as long as + // what is made of it lives, as the caller says. It is owned in name + // only: `make` keeps it inside what it makes, and `Lent` takes it + // out of that again instead of closing it. + let owned = unsafe { OwnedFd::from_raw_fd(fd.as_raw_fd()) }; + Ok(Lent(ManuallyDrop::new(make(owned)))) + } +} + +/// What the library makes of a descriptor that a caller lends it, and that +/// can be taken apart for the descriptor again. +trait Borrower { + /// The descriptor this was made of. None where something shares it + /// still: nothing closes it then either. + fn into_descriptor(self) -> Option; +} + +/// The file a manifest is read from or written to. +impl Borrower for File { + fn into_descriptor(self) -> Option { + Some(self.into()) + } +} + +/// The directory the files of a manifest are taken from. +impl Borrower for PinnedDirectory { + fn into_descriptor(self) -> Option { + Some(self.into_fd()) + } +} + +/// The directory of a new manifest file, which the file shares with what +/// else the writer keeps there while the manifest is built. +impl Borrower for Arc { + /// A directory that something shares still is forgotten and not + /// dropped, so that whatever drops it last does not close it. + fn into_descriptor(self) -> Option { + Arc::try_unwrap(self).map_err(mem::forget).ok() + } +} + +/// What the library holds of a descriptor that a caller lends it: `T` is +/// made of the descriptor as if it owned it. The descriptor stays the +/// caller's, which keeps it open for as long as this lives. When this is +/// dropped, `T` is taken apart and the descriptor is left open: nothing +/// here closes it, and no duplicate is made of it. +#[derive(Debug)] +struct Lent(ManuallyDrop); + +impl Deref for Lent { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +impl DerefMut for Lent { + fn deref_mut(&mut self) -> &mut T { + &mut self.0 + } +} + +impl Drop for Lent { + fn drop(&mut self) { + // SAFETY: the value is taken out once, here, and nothing uses this + // after it was dropped. + let made = unsafe { ManuallyDrop::take(&mut self.0) }; + if let Some(descriptor) = made.into_descriptor() { + // The descriptor is the caller's, which closes it. + let _ = descriptor.into_raw_fd(); + } + } +} + +impl Read for Lent { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.0.read(buf) + } +} + +impl Write for Lent { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } +} + +/// A string as a caller passes it: NULL, or NUL-terminated. +#[derive(Clone, Copy, Debug)] +struct Text<'a>(Option<&'a CStr>); + +impl<'a> Text<'a> { + /// The string `text` of a caller. + /// + /// # Safety + /// + /// `text` is NULL, or points to bytes that end in a NUL and that are + /// valid and do not change for `'a`. + unsafe fn new(text: *const c_char) -> Text<'a> { + if text.is_null() { + return Text(None); + } + // SAFETY: `text` is not NULL, so it points to bytes that end in a + // NUL and stay as they are for `'a`, as the caller says. + Text(Some(unsafe { CStr::from_ptr(text) })) + } + + /// The string, which has to be one. + fn get(self) -> Result<&'a CStr, uapi16_error> { + self.0.ok_or_else(uapi16_error::misuse) + } + + /// The string as text, whatever it is: NULL is the empty string, and + /// bytes that are not UTF-8 become the replacement character. + fn lossy(self) -> Cow<'a, str> { + self.0.map_or(Cow::Borrowed(""), CStr::to_string_lossy) + } +} + +impl Order { + /// Every order, as C has it and as Rust has it. UAPI16_ORDER_NONE is no + /// order. + const ALL: [(uapi16_order_t, Option); 2] = [ + (uapi16_order_t::UAPI16_ORDER_NONE, None), + (uapi16_order_t::UAPI16_ORDER_CODEPOINT, Some(Order::CodePoint)), + ]; + + /// The order a caller in C passes as `order`: a number of + /// uapi16_order_t, of which UAPI16_ORDER_NONE is no order. Any other + /// number fails. + fn of_number(order: OrderNumber) -> Result, uapi16_error> { + let mut all = Order::ALL.into_iter(); + all.find(|(c, _)| *c as OrderNumber == order) + .map(|(_, rust)| rust) + .ok_or_else(uapi16_error::misuse) + } + + /// The number C has for the order `order`, or for none. + fn number(order: Option) -> uapi16_order_t { + let mut all = Order::ALL.into_iter(); + all.find(|(_, rust)| *rust == order) + .map_or(uapi16_order_t::UAPI16_ORDER_NONE, |(c, _)| c) + } +} + +impl Name { + /// The name a caller in C passes as `text`: the empty string for the + /// root of the tree, which has no name, and the name of a file object + /// for any other file. + fn of_text(text: Text<'_>) -> Result<&Name, uapi16_error> { + let text = text.get()?.to_str(); + let text = text.map_err(|_| uapi16_error::bad_name(NameProblem::NotUtf8))?; + if text.is_empty() { + return Ok(Name::ROOT); + } + Name::new(text).map_err(uapi16_error::bad_name) + } +} + +impl uapi16_add_flag_t { + /// Every flag, as C has it and as Rust has it. + const ALL: [(uapi16_add_flag_t, AddFlags); 2] = [ + (uapi16_add_flag_t::UAPI16_ADD_CROSS_MOUNTS, AddFlags::CROSS_MOUNTS), + (uapi16_add_flag_t::UAPI16_ADD_GRACEFUL, AddFlags::GRACEFUL), + ]; +} + +impl AddFlags { + /// The flags a caller in C passes as `bits`: a set of + /// uapi16_add_flag_t. A bit that is no flag fails. + fn of_bits(bits: uapi16_add_flags_t) -> Result { + let mut flags = AddFlags::NONE; + let mut known = 0; + for (c, rust) in uapi16_add_flag_t::ALL { + let bit = c as u64; + known |= bit; + if bits & bit != 0 { + flags |= rust; + } + } + if bits & !known != 0 { + return Err(uapi16_error::misuse()); + } + Ok(flags) + } +} + +/// Where a call stores its error, as a caller passes it in `reterr`: NULL +/// for a caller that wants no error, or a place for one, which a caller is +/// told to set to NULL. +#[derive(Debug)] +struct ErrorPlace<'a>(Option<&'a mut *mut uapi16_error>); + +impl<'a> ErrorPlace<'a> { + /// No place: what a function has that takes no `reterr`. + const NONE: ErrorPlace<'static> = ErrorPlace(None); + + /// The place `reterr` of a caller. + /// + /// # Safety + /// + /// `reterr` is NULL, or valid for the read and the write of a pointer + /// for `'a`, and nothing else uses what it points to for `'a`. + unsafe fn new(reterr: *mut *mut uapi16_error) -> ErrorPlace<'a> { + // SAFETY: `reterr` is NULL or points to a pointer that can be read + // and written for `'a` and that nothing else uses then, as the + // caller says. + ErrorPlace(unsafe { reterr.as_mut() }) + } + + /// Whether a call can store an error here: there is no place, or it + /// holds NULL. A place that holds anything else is not clear, and a + /// call that is given one is no valid call. What it holds may be an + /// error that was not freed, which a new one would leak, or no error at + /// all, so nothing ever reads through it, frees it or replaces it. + fn is_clear(&self) -> bool { + self.0.as_deref().is_none_or(|held| held.is_null()) + } + + /// What a call returns that ended as `result`: 0, or the errno of the + /// error, negated. The error goes to the place if there is one, and + /// nothing is written there for a call that did not fail. A place that + /// is not clear keeps what it holds: the call was refused for it. + fn returned(self, result: Result<(), uapi16_error>) -> c_int { + let Err(error) = result else { + return 0; + }; + let errno = error.errno; + if let Some(place) = self.0.filter(|place| place.is_null()) { + *place = error.into_raw(); + } + -errno + } + + /// What a call returns that was to read an object and ended as `read`: + /// the number of what it read, or what [`ErrorPlace::returned`] returns + /// for the error. + fn read(self, read: Result) -> c_int { + match read { + // The numbers of uapi16_read_t are small. + Ok(read) => read as c_int, + Err(e) => self.returned(Err(e)), + } + } +} + +/// An object of the C API. A caller holds it by a pointer, and frees it +/// with the function of its type. +trait Object: Sized { + /// Hands the object to a caller. + fn into_raw(self) -> *mut Self { + Box::into_raw(Box::new(self)) + } + + /// Frees the object `object` points to, unless that is NULL, and + /// returns NULL. + /// + /// # Safety + /// + /// `object` is NULL, or came from [`Object::into_raw`], was not freed + /// since, and is used by nothing else now or later. + unsafe fn free(object: *mut Self) -> *mut Self { + if !object.is_null() { + // SAFETY: `object` is not NULL, so it came from Box::into_raw() + // and nothing else has it, as the caller says. + drop(unsafe { Box::from_raw(object) }); + } + ptr::null_mut() + } + + /// What a call returns that was to make an object of this type and + /// ended as `made`: 0 with the object in `ret`, or what + /// [`ErrorPlace::returned`] returns for the error, which goes to + /// `reterr`. A caller that passes NULL for `ret` does not want the + /// object, which is dropped. + /// + /// # Safety + /// + /// `ret` is NULL or valid for the write of a pointer. + unsafe fn returned(made: Result, ret: *mut *mut Self, reterr: ErrorPlace<'_>) -> c_int { + let stored = made.map(|object| { + if !ret.is_null() { + // SAFETY: `ret` is not NULL, so it is valid for the write of + // a pointer, as the caller says. + unsafe { ret.write(object.into_raw()) }; + } + }); + reterr.returned(stored) + } +} + +/// Where a read stores the object it read, as getline() takes its buffer. +/// What a caller passes in `ret` points to NULL, and the read makes a new +/// object there, or to an object of the caller, which the read fills again +/// in place of all it held. A read that has no object to store leaves both +/// alone, so the object stays the caller's whatever the read returns. +#[derive(Debug)] +struct Refill<'a, T: Object>(&'a mut *mut T); + +impl<'a, T: Object> Refill<'a, T> { + /// The place `ret` of a caller, or None where that is NULL. + /// + /// # Safety + /// + /// `ret` is NULL, or valid for the read and the write of a pointer for + /// `'a`. That pointer is NULL, or came from [`Object::into_raw`] and + /// was not freed since. Nothing else uses the pointer or the object + /// for `'a`. + unsafe fn new(ret: *mut *mut T) -> Option> { + // SAFETY: `ret` is NULL or points to a pointer that can be read and + // written for `'a` and that nothing else uses then, as the caller + // says. + unsafe { ret.as_mut() }.map(Refill) + } + + /// The object of the caller, if it has one. + fn object(&self) -> Option<&T> { + // SAFETY: the pointer is NULL or an object that was not freed and + // that nothing else uses for `'a`, as whoever made this said. + unsafe { (*self.0).as_ref() } + } + + /// Stores `object`: in the object of the caller, in place of all it + /// held, or as a new object where the caller has none. + fn store(self, object: T) { + // SAFETY: the pointer is NULL or an object that was not freed and + // that nothing else uses for `'a`, as whoever made this said. + match unsafe { (*self.0).as_mut() } { + Some(kept) => *kept = object, + None => *self.0 = object.into_raw(), + } + } +} + +/// Bytes as a caller passes them: a pointer and how many there are. +#[derive(Clone, Copy, Debug)] +struct Bytes<'a>(Option<&'a [u8]>); + +impl<'a> Bytes<'a> { + /// The `size` bytes at `data` of a caller. Where `size` is 0 there are + /// none, and `data` is not looked at. A size over `isize::MAX` is one + /// that nothing in memory has, so there are no bytes for it, as for + /// NULL. + /// + /// # Safety + /// + /// Unless `size` is 0 or over `isize::MAX`, `data` is NULL or valid for + /// the read of `size` bytes, which do not change for `'a`. + unsafe fn new(data: *const c_void, size: usize) -> Bytes<'a> { + if size == 0 { + return Bytes(Some(&[])); + } + if data.is_null() || isize::try_from(size).is_err() { + return Bytes(None); + } + // SAFETY: `size` is not 0 and not over isize::MAX, and `data` is + // not NULL, so it is valid for the read of `size` bytes that stay + // as they are for `'a`, as the caller says. + Bytes(Some(unsafe { slice::from_raw_parts(data.cast::(), size) })) + } + + /// The bytes, which have to be there. + fn get(self) -> Result<&'a [u8], uapi16_error> { + self.0.ok_or_else(uapi16_error::misuse) + } +} + +/// Where the bit of a feature is in a set: the feature with the number f +/// has bit (f - 1) % 64 of word (f - 1) / 64. +#[derive(Clone, Copy, Debug)] +struct FeatureBit { + /// The word the bit is in, counted from 0. + word: usize, + /// The bit, in that word. + mask: u64, +} + +impl FeatureBit { + /// The bit of the feature with the number `feature`. None for + /// UAPI16_FEATURE_NONE, which has none. + fn of(feature: FeatureNumber) -> Option { + let bit = feature.checked_sub(1)?; + Some(FeatureBit { + word: (bit / u64::BITS) as usize, + mask: 1 << (bit % u64::BITS), + }) + } +} + +/// The words of a set of features of a caller, to read: where they are and +/// how many the set has by its size. A set of a caller is as long as its +/// header says, which can be shorter or longer than the uapi16_features_t +/// of this library. So no reference to one is ever made: its size and its +/// words are read through the pointer of the caller, one at a time. +#[derive(Clone, Copy, Debug)] +struct SetWords<'a> { + first: *const u64, + count: usize, + set: PhantomData<&'a u64>, +} + +impl<'a> SetWords<'a> { + /// The bytes of a word of a set, and of its size. + const WORD_SIZE: u64 = size_of::() as u64; + + /// How many words a set of `size` bytes has. A size above the largest + /// one is too large, and a size below the first one or that is no + /// multiple of a word is none, in the order clone3() checks its size. + fn count_of(size: u64) -> Result { + if size > UAPI16_FEATURES_SIZE_MAX as u64 { + return Err(uapi16_error::too_large()); + } + if size < UAPI16_FEATURES_SIZE_VER0 as u64 || size % SetWords::WORD_SIZE != 0 { + return Err(uapi16_error::misuse()); + } + // The size itself is the first word of these. + Ok((size / SetWords::WORD_SIZE) as usize - 1) + } + + /// The set `s` of a caller, with the words its size says. NULL is no + /// set, and neither is one with a size no set has. + /// + /// # Safety + /// + /// `s` is NULL, or aligned as a `u64` and valid for the read of the + /// size of a set. Where that is a size a set can have, `s` is valid for + /// the read of as many bytes. Nothing writes them for `'a` but a call + /// that changes this very set through a [`SetWordsMut`]. + unsafe fn new(s: *const uapi16_features_t) -> Result, uapi16_error> { + if s.is_null() { + return Err(uapi16_error::misuse()); + } + let size = s.cast::(); + // SAFETY: `s` is not NULL, so its size can be read, as the caller + // says. + let count = SetWords::count_of(unsafe { size.read() })?; + Ok(SetWords { + // SAFETY: the size is one a set can have, so the set has words + // after it, as the caller says. + first: unsafe { size.add(1) }, + count, + set: PhantomData, + }) + } + + /// Word `index` of the set. A word the set does not have counts as 0. + fn word(self, index: usize) -> u64 { + if index >= self.count { + return 0; + } + // SAFETY: the set has the word, so it can be read, as whoever made + // this said. + unsafe { self.first.add(index).read() } + } + + /// Whether the set has the feature with the number `feature`. + fn has(self, feature: FeatureNumber) -> bool { + FeatureBit::of(feature).is_some_and(|bit| self.word(bit.word) & bit.mask != 0) + } + + /// The lowest feature of the set above `after`, or UAPI16_FEATURE_NONE + /// where it has none. It starts at the word of that feature and reads + /// every word after it once at most, so a walk over a set with this + /// reads each of its words about once. + fn next(self, after: FeatureNumber) -> FeatureNumber { + // The feature after `after` has the bit with the number `after`. + let mut index = (after / u64::BITS) as usize; + let mut word = self.word(index) & (u64::MAX << (after % u64::BITS)); + while index < self.count { + if word != 0 { + return index as FeatureNumber * u64::BITS + word.trailing_zeros() + 1; + } + index += 1; + word = self.word(index); + } + uapi16_feature_t::UAPI16_FEATURE_NONE as FeatureNumber + } + + /// Whether the set and `other` have the same features, whatever their + /// sizes are. + fn equals(self, other: SetWords<'_>) -> bool { + (0..self.count.max(other.count)).all(|index| self.word(index) == other.word(index)) + } + + /// The features of the set, as copy_struct_from_user() takes a struct + /// of its caller: a word past those of the library that is not 0 makes + /// the set too large, and a bit that is the bit of no feature of the + /// library fails. Nothing is taken of such a set. + fn features(self) -> Result { + if (UAPI16_FEATURES_WORDS..self.count).any(|index| self.word(index) != 0) { + return Err(uapi16_error::too_large()); + } + let mut words = [0; UAPI16_FEATURES_WORDS]; + for (index, word) in words.iter_mut().enumerate() { + *word = self.word(index); + } + Features::of_words(&words).ok_or_else(uapi16_error::misuse) + } +} + +/// The words of a set of features of a caller that a call changes or +/// fills. The size of the set is read and never written. +#[derive(Debug)] +struct SetWordsMut<'a> { + first: *mut u64, + count: usize, + set: PhantomData<&'a mut u64>, +} + +impl<'a> SetWordsMut<'a> { + /// The set `s` of a caller, as [`SetWords::new`] takes one. + /// + /// # Safety + /// + /// What [`SetWords::new`] asks, and `s` is valid for the write of the + /// bytes it is valid for the read of. Nothing else reads or writes + /// them for `'a` but a [`SetWords`] of this very set that this one is + /// combined with. + unsafe fn new(s: *mut uapi16_features_t) -> Result, uapi16_error> { + // SAFETY: `s` is what SetWords::new() takes, as the caller says. + let words = unsafe { SetWords::new(s) }?; + Ok(SetWordsMut { + // SAFETY: the set has words after its size, as above. The + // pointer comes from `s`, which can be written through. + first: unsafe { s.cast::().add(1) }, + count: words.count, + set: PhantomData, + }) + } + + /// The words, to read. + fn words(&self) -> SetWords<'_> { + SetWords { + first: self.first, + count: self.count, + set: PhantomData, + } + } + + /// Makes word `index` of the set `word`. The set has that word. + fn put(&mut self, index: usize, word: u64) { + assert!(index < self.count); + // SAFETY: the set has the word, so it can be written, as whoever + // made this said. + unsafe { self.first.add(index).write(word) }; + } + + /// Adds the feature with the number `feature` to the set where `has` + /// says so, and takes it out where not. UAPI16_FEATURE_NONE is no + /// feature, and neither is a number the set has no room for. + fn change(&mut self, feature: FeatureNumber, has: bool) -> Result<(), uapi16_error> { + let bit = FeatureBit::of(feature).filter(|bit| bit.word < self.count); + let bit = bit.ok_or_else(uapi16_error::misuse)?; + let word = self.words().word(bit.word); + self.put(bit.word, if has { word | bit.mask } else { word & !bit.mask }); + Ok(()) + } + + /// Makes every word of the set what `combine` makes of it and of the + /// same word of `other`. The set keeps its size: a word `other` does + /// not have counts as 0, and what `other` has past the words of this + /// set is dropped. `other` can be this set itself. + fn combine(&mut self, other: SetWords<'_>, combine: impl Fn(u64, u64) -> u64) { + for index in 0..self.count { + let word = combine(self.words().word(index), other.word(index)); + self.put(index, word); + } + } + + /// Fills the set with `features`, as copy_struct_to_user() fills a + /// struct of its caller: the words both have are copied, the words the + /// set has past them are cleared, and what the set has no room for is + /// dropped. + fn fill(&mut self, features: Features) { + for index in 0..self.count { + self.put(index, features.word(index)); + } + } +} + +/// Where a call stores a value, as a caller passes it in `ret` or in one of +/// its `ret_` arguments: NULL, or a place for the value. +#[derive(Debug)] +struct Place<'a, T>(*mut T, PhantomData<&'a mut T>); + +impl<'a, T> Place<'a, T> { + /// The place `to` of a caller. + /// + /// # Safety + /// + /// `to` is NULL, or valid for the write of a `T` for `'a`. + unsafe fn new(to: *mut T) -> Place<'a, T> { + Place(to, PhantomData) + } + + /// The place, which has to be one. + fn needed(self) -> Result, uapi16_error> { + if self.0.is_null() { + return Err(uapi16_error::misuse()); + } + Ok(self) + } + + /// Stores `value`, unless there is no place for it. + fn store(self, value: T) { + if !self.0.is_null() { + // SAFETY: the place is not NULL, so it is valid for the write of + // a `T`, as whoever made it said. + unsafe { self.0.write(value) }; + } + } +} + +impl InodeType { + /// Every type, with the bits `st_mode` has for it. + const ST_MODES: [(InodeType, u32); 7] = [ + (InodeType::Regular, libc::S_IFREG), + (InodeType::Directory, libc::S_IFDIR), + (InodeType::Symlink, libc::S_IFLNK), + (InodeType::Fifo, libc::S_IFIFO), + (InodeType::CharDevice, libc::S_IFCHR), + (InodeType::BlockDevice, libc::S_IFBLK), + (InodeType::Socket, libc::S_IFSOCK), + ]; + + /// The type the bits of the file type in `st_mode` are, if they are + /// one. + fn of_st_mode(st_mode: u32) -> Option { + let bits = st_mode & libc::S_IFMT; + let mut all = InodeType::ST_MODES.into_iter(); + all.find(|(_, known)| *known == bits).map(|(inode_type, _)| inode_type) + } + + /// The bits `st_mode` has for the type. + fn st_mode(self) -> u32 { + let mut all = InodeType::ST_MODES.into_iter(); + all.find(|(inode_type, _)| *inode_type == self) + .map_or(0, |(_, bits)| bits) + } +} + +/// How to write a manifest: the features it records, the order of its +/// file objects and whether a new file is synced. Made by +/// uapi16_manifest_options_new(), which gives the default features and +/// the code point order and does not sync, and freed by +/// uapi16_manifest_options_free(). +#[derive(Debug)] +struct uapi16_manifest_options { + options: ManifestOptions, + /// The features and the order of the options, which a writer of records + /// gives its root file object. Options of C can have no order, which + /// `options` can't: only a writer of records takes those. + features: Features, + order: Option, + process: Process, +} + +impl Object for uapi16_manifest_options {} + +impl uapi16_manifest_options { + /// New options, of this process. + fn new() -> uapi16_manifest_options { + uapi16_manifest_options { + options: ManifestOptions::new(), + features: Features::DEFAULT, + order: Some(Order::CodePoint), + process: Process::current(), + } + } + + /// The features the options record. + fn features(&self) -> Features { + self.features + } + + /// What uapi16_manifest_options_set_features() does, for the features + /// of its set. + fn set_features(&mut self, features: Features) -> Result<(), uapi16_error> { + self.process.check()?; + self.options.features(features); + self.features = features; + Ok(()) + } + + /// What uapi16_manifest_options_set_order() does. + fn set_order(&mut self, order: OrderNumber) -> Result<(), uapi16_error> { + let order = Order::of_number(order)?; + self.process.check()?; + if let Some(order) = order { + self.options.order(order); + } + self.order = order; + Ok(()) + } + + /// The options for a writer that sorts: the manifest writer and the + /// generate functions list the file objects in the order of the + /// options, and declare it. Options without an order are no options + /// for them. + fn sorted(&self) -> Result<&ManifestOptions, uapi16_error> { + self.order.map(|_| &self.options).ok_or_else(uapi16_error::misuse) + } + + /// What uapi16_manifest_options_set_sync() does. + fn set_sync(&mut self, sync: bool) -> Result<(), uapi16_error> { + self.process.check()?; + self.options.sync(sync); + Ok(()) + } + + /// The name of a new file as a caller passes it in `name`: a path, + /// which is taken as the bytes it is, as Rust takes a `Path`, and not + /// as UTF-8, as the other strings that go in are. A name that names no + /// file below a directory is refused here, as an argument that is not + /// valid, before anything is looked up. + fn file_name(name: Text<'_>) -> Result<&Path, uapi16_error> { + let name = Path::new(OsStr::from_bytes(name.get()?.to_bytes())); + if NewFile::split(name).is_none() { + return Err(uapi16_error::misuse()); + } + Ok(name) + } + + /// What uapi16_manifest_writer_create_at() does. The writer has `dir` + /// on loan: a file whose name has one component and what else the + /// writer keeps in the directory of the file use `dir` itself. + /// + /// # Safety + /// + /// `dir` stays open until the writer this returns is dropped. + unsafe fn create_at(&self, dir: Descriptor<'_>, name: Text<'_>) -> Result { + let name = uapi16_manifest_options::file_name(name)?; + // SAFETY: the writer keeps the directory until it is dropped, and + // the descriptor stays open for that long, as the caller says. + let dir = unsafe { dir.lend(Arc::new) }?; + self.process.check()?; + let created = self.sorted()?.create_at_lent(&dir, name); + let writer = created.map_err(|e| uapi16_error::from(e).of_new_file())?; + Ok(uapi16_manifest_writer::new(WriterTo::NewFile(writer, dir))) + } + + /// What uapi16_manifest_writer_open() does. The writer has `fd` on + /// loan, and writes the manifest to it. + /// + /// # Safety + /// + /// `fd` stays open until the writer this returns is dropped. + unsafe fn open(&self, fd: Descriptor<'_>) -> Result { + // SAFETY: the writer keeps the file until it is dropped, and the + // descriptor stays open for that long, as the caller says. + let out = unsafe { fd.lend(File::from) }?; + self.process.check()?; + let writer = self.sorted()?.open(out)?; + Ok(uapi16_manifest_writer::new(WriterTo::Descriptor(writer))) + } + + /// What uapi16_manifest_generate_at() does. + fn generate_at( + &self, + dir: Descriptor<'_>, + name: Text<'_>, + top: Descriptor<'_>, + flags: uapi16_add_flags_t, + ) -> Result { + let flags = AddFlags::of_bits(flags)?; + let name = uapi16_manifest_options::file_name(name)?; + // SAFETY: the directory is dropped before this returns, and the + // descriptor is open for that long, as whoever made `dir` said. + let dir = unsafe { dir.lend(Arc::new) }?; + let top = top.borrow()?; + self.process.check()?; + let generated = self.sorted()?.generate_at_lent(&dir, name, top, flags); + let report = generated.map_err(|e| uapi16_error::from(e).of_new_file())?; + Ok(uapi16_manifest_report { report }) + } + + /// What uapi16_manifest_generate() does. + fn generate( + &self, + fd: Descriptor<'_>, + top: Descriptor<'_>, + flags: uapi16_add_flags_t, + ) -> Result { + let flags = AddFlags::of_bits(flags)?; + // SAFETY: the file is dropped before this returns, and the + // descriptor is open for that long, as whoever made `fd` said. + let out = unsafe { fd.lend(File::from) }?; + let top = top.borrow()?; + self.process.check()?; + let (_, report) = self.sorted()?.generate(out, top, flags)?; + Ok(uapi16_manifest_report { report }) + } +} + +/// Takes the files a manifest lists, and writes the manifest once it has +/// them all. Made by uapi16_manifest_writer_create_at() and +/// uapi16_manifest_writer_open(), and freed by +/// uapi16_manifest_writer_free(). +/// +/// The manifest lists its file objects in the order of the options, +/// whatever order the adds came in. Two equal file objects under one name +/// are listed once. A directory added twice is listed with what the first +/// add said of it. Two other files under one name, also a directory and a +/// file that is none, are UAPI16_ERROR_DUPLICATE, from +/// uapi16_manifest_writer_finish(). +/// +/// An add that fails leaves the writer as it was, as if the add had not +/// been. +struct uapi16_manifest_writer { + /// The writer, until uapi16_manifest_writer_finish() took it. + writer: Option, + process: Process, +} + +/// The writer of a manifest of the C API, by where its manifest goes. +enum WriterTo { + /// To a new file, of uapi16_manifest_writer_create_at(), which gets + /// its name when the writer finishes. With it comes the directory the + /// caller lent. The writer is dropped before it, with everything that + /// shares the directory. + NewFile(ManifestWriter, Lent>), + /// To the descriptor the caller lent to uapi16_manifest_writer_open(). + Descriptor(ManifestWriter>), +} + +impl WriterTo { + /// [`ManifestWriter::add_object`]. + fn add_object(&mut self, object: &FileObject) -> Result<(), Error> { + match self { + WriterTo::NewFile(writer, _) => writer.add_object(object), + WriterTo::Descriptor(writer) => writer.add_object(object), + } + } + + /// [`ManifestWriter::add_root`]. + fn add_root(&mut self, root: &RootObject) -> Result<(), Error> { + match self { + WriterTo::NewFile(writer, _) => writer.add_root(root.inode(), root.file_system()), + WriterTo::Descriptor(writer) => writer.add_root(root.inode(), root.file_system()), + } + } + + /// [`ManifestWriter::finish`]. What the manifest was written to is + /// done with here: the new file is closed, and the descriptor of the + /// caller is left open. + fn finish(self) -> Result { + match self { + WriterTo::NewFile(writer, _directory) => { + let finished = writer.finish().map_err(|e| uapi16_error::from(e).of_new_file())?; + Ok(finished.1) + } + WriterTo::Descriptor(writer) => Ok(writer.finish()?.1), + } + } + + /// [`ManifestWriter::abandon`]. + fn abandon(self) { + match self { + WriterTo::NewFile(writer, _directory) => writer.abandon(), + WriterTo::Descriptor(writer) => writer.abandon(), + } + } +} + +impl Object for uapi16_manifest_writer {} + +impl uapi16_manifest_writer { + /// The writer of this process for `writer`. + fn new(writer: WriterTo) -> uapi16_manifest_writer { + uapi16_manifest_writer { + writer: Some(writer), + process: Process::current(), + } + } + + /// The writer, unless it is finished: one that is takes nothing more. + fn writer(&mut self) -> Result<&mut WriterTo, uapi16_error> { + self.writer.as_mut().ok_or_else(uapi16_error::ended) + } + + /// What uapi16_manifest_writer_add_object() does. A call that is not + /// valid fails for that in another process and on a writer that is + /// finished as well. + fn add_object(&mut self, object: &uapi16_file_object) -> Result<(), uapi16_error> { + self.process.check()?; + object.process.check()?; + let writer = self.writer()?; + if object.is_root() { + let added = writer.add_root(&object.as_tree_root()?); + added.map_err(|e| uapi16_error::from(e).of_root())?; + } else { + writer.add_object(object.as_file()?)?; + } + Ok(()) + } + + /// What uapi16_manifest_writer_finish() does. The writer is finished + /// after that, also where it failed. + fn finish(&mut self) -> Result { + self.process.check()?; + let writer = self.writer.take().ok_or_else(uapi16_error::ended)?; + let report = writer.finish()?; + Ok(uapi16_manifest_report { report }) + } +} + +impl Drop for uapi16_manifest_writer { + /// A writer that is freed in the process that made it is dropped as + /// any writer. In another one, the child of a fork(), nothing of it is + /// removed: a file that has a name until it is complete is the + /// parent's, which has the writer still. + fn drop(&mut self) { + let Some(writer) = self.writer.take() else { + return; + }; + if !self.process.is(Process::current()) { + writer.abandon(); + } + } +} + +/// What a manifest lists, counted per file object: a file with three names +/// counts three times. Made by uapi16_manifest_writer_finish() and the +/// generate functions, and freed by uapi16_manifest_report_free(). +#[derive(Debug)] +struct uapi16_manifest_report { + report: ManifestReport, +} + +impl Object for uapi16_manifest_report {} + +/// Why a call failed. A call that fails stores one where its `reterr` +/// points to, unless `reterr` is NULL, and uapi16_error_free() frees it. +/// `reterr` has to point to NULL: a call that finds anything else there, +/// such as an error that was not freed, fails with -EINVAL before it does +/// anything, and leaves what is there as it is. +#[derive(Debug)] +struct uapi16_error { + kind: uapi16_error_kind_t, + /// The errno, a positive number. + errno: c_int, + path: Option, + hardlink_path: Option, + /// The one feature it is about. + feature: Option, + raw_name: Option>, + name_problem: Option, + /// The field it is about. + field: Option, + /// The record it is about, counting from 0. + record: Option, + /// The rule of the specification that is broken. + problem: Option, +} + +impl Object for uapi16_error {} + +// What the description of the C API leaves open about errors. These are +// the answers until it says. +impl uapi16_error { + /// The errno of an I/O error that no system call gave one: a link of + /// procfs that leads to another file than the one it is for, a scratch + /// file that was changed, and a file of no type a manifest has. + const WITHOUT_ERRNO: c_int = libc::EIO; + /// The errno of a descriptor that is negative. + const NO_DESCRIPTOR: c_int = libc::EBADF; + /// The errno of a getter of what its object does not have: a field of + /// a file object, and the record of an error that is about none. + const NO_DATA: c_int = libc::ENODATA; + /// The errno of a set of features that is larger than a set can be, or + /// that has features in words this library does not have. + const TOO_LARGE: c_int = libc::E2BIG; +} + +impl uapi16_error { + /// The kind and the errno of a call on an object that takes nothing + /// more: a writer, a computation or a check that is finished, and a + /// reader that failed. + const ENDED: (uapi16_error_kind_t, c_int) = (uapi16_error_kind_t::UAPI16_ERROR_ENDED, libc::ESTALE); + + /// An error of the kind `kind` with the errno `errno`, about nothing in + /// particular. + fn new(kind: uapi16_error_kind_t, errno: c_int) -> uapi16_error { + uapi16_error { + kind, + errno, + path: None, + hardlink_path: None, + feature: None, + raw_name: None, + name_problem: None, + field: None, + record: None, + problem: None, + } + } + + /// The error of a call that is refused for how it was made, before it + /// did anything, with the errno `errno`. + fn refused(errno: c_int) -> uapi16_error { + uapi16_error::new(uapi16_error_kind_t::UAPI16_ERROR_INVALID_ARGUMENT, errno) + } + + /// The error of a call with an object, a string or a `ret` that is + /// NULL, or with a flag, a bit or a number nothing knows. + fn misuse() -> uapi16_error { + uapi16_error::refused(libc::EINVAL) + } + + /// The error of a call with a set of features that is larger than a + /// set can be, or that has features in words this library does not + /// have. Such a call takes no `reterr`, so only its errno gets to a + /// caller. + fn too_large() -> uapi16_error { + uapi16_error::refused(uapi16_error::TOO_LARGE) + } + + /// The error of a getter of what its object does not have. Such a + /// getter takes no `reterr`, so only its errno gets to a caller. + fn absent() -> uapi16_error { + uapi16_error::refused(uapi16_error::NO_DATA) + } + + /// The error of a call on an object that takes nothing more: a writer, + /// a computation or a check that is finished, and a reader that failed. + fn ended() -> uapi16_error { + let (kind, errno) = uapi16_error::ENDED; + uapi16_error::new(kind, errno) + } + + /// The error of a call with a name that is not the name of a file + /// object, for `problem`. + fn bad_name(problem: NameProblem) -> uapi16_error { + uapi16_error { + name_problem: uapi16_name_problem_t::of(problem), + ..uapi16_error::misuse() + } + } + + /// The same error as that of a call that makes a new file or gives it + /// its name. There, EEXIST of a system call says that the name is + /// taken. + fn of_new_file(mut self) -> uapi16_error { + if self.kind == uapi16_error_kind_t::UAPI16_ERROR_IO && self.errno == libc::EEXIST { + self.kind = uapi16_error_kind_t::UAPI16_ERROR_EXISTS; + } + self + } + + /// The same error, about the file `name` where it names none. The root + /// is the empty string in C, where Rust names no file. + fn about(mut self, name: &Name) -> uapi16_error { + if self.path.is_none() { + self.path = CString::new(name.as_str()).ok(); + } + self + } + + /// The same error as that of a writer of records that refused the + /// record `record`: the number the record would have had. An error that + /// names a record keeps it. + fn in_record(mut self, record: u64) -> uapi16_error { + self.record.get_or_insert(record); + self + } + + /// The same error as that of a call that was given the root. Where a + /// rule of the specification refuses the root, the error is about the + /// root. + fn of_root(self) -> uapi16_error { + if self.problem.is_some() { + self.about(Name::ROOT) + } else { + self + } + } + + /// The same error as that of a reader that read the record of the + /// root. An error about a field of that record is about the root. One + /// about the record as a whole, such as text that is no JSON, is about + /// no file. + fn of_root_record(self) -> uapi16_error { + if self.field.is_some() { + self.about(Name::ROOT) + } else { + self + } + } + + /// The kind and the errno C has for the error `error` of the builder. + fn kind_of(error: &Error) -> (uapi16_error_kind_t, c_int) { + match error.kind() { + ErrorKind::Io => uapi16_error::io_kind_of(error), + ErrorKind::Tree(problem) => match problem { + TreeProblem::Duplicate => (uapi16_error_kind_t::UAPI16_ERROR_DUPLICATE, libc::EEXIST), + TreeProblem::Changed => (uapi16_error_kind_t::UAPI16_ERROR_CHANGED, libc::ESTALE), + TreeProblem::HardlinkMismatch => (uapi16_error_kind_t::UAPI16_ERROR_HARDLINK_MISMATCH, libc::ESTALE), + TreeProblem::UnwritableName => { + let errno = match error.name_problem() { + Some(NameProblem::NotUtf8) => libc::EILSEQ, + Some(NameProblem::TooLong) => libc::ENAMETOOLONG, + _ => libc::EINVAL, + }; + (uapi16_error_kind_t::UAPI16_ERROR_UNWRITABLE_NAME, errno) + } + TreeProblem::NotDirectory => (uapi16_error_kind_t::UAPI16_ERROR_NOT_DIRECTORY, libc::ENOTDIR), + TreeProblem::FeatureUnavailable => (uapi16_error_kind_t::UAPI16_ERROR_UNSUPPORTED, libc::EOPNOTSUPP), + TreeProblem::FeatureNotForTrees => (uapi16_error_kind_t::UAPI16_ERROR_INVALID_ARGUMENT, libc::EINVAL), + TreeProblem::Loop => (uapi16_error_kind_t::UAPI16_ERROR_LOOP, libc::ELOOP), + TreeProblem::MissingParent => (uapi16_error_kind_t::UAPI16_ERROR_MISSING_PARENT, libc::ENOENT), + }, + ErrorKind::Manifest(Problem::RecordTooLarge) => (uapi16_error_kind_t::UAPI16_ERROR_TOO_LARGE, libc::E2BIG), + ErrorKind::Manifest(_) => (uapi16_error_kind_t::UAPI16_ERROR_MANIFEST, libc::EBADMSG), + ErrorKind::Source(problem) => match problem { + SourceProblem::Missing => (uapi16_error_kind_t::UAPI16_ERROR_SOURCE_MISSING, libc::ENOENT), + SourceProblem::NotRegular => (uapi16_error_kind_t::UAPI16_ERROR_SOURCE_NOT_REGULAR, libc::EINVAL), + SourceProblem::Unreadable => uapi16_error::io_kind_of(error), + }, + ErrorKind::Data(problem) => match problem { + DataProblem::SizeMismatch => (uapi16_error_kind_t::UAPI16_ERROR_SIZE_MISMATCH, libc::EBADMSG), + DataProblem::HashMismatch => (uapi16_error_kind_t::UAPI16_ERROR_HASH_MISMATCH, libc::EBADMSG), + // Only a provider that copies data finds these two, and no + // call of the C API copies data. + DataProblem::StreamEnded | DataProblem::SourceChanged => { + (uapi16_error_kind_t::UAPI16_ERROR_IO, uapi16_error::WITHOUT_ERRNO) + } + }, + ErrorKind::Unsupported(data) => match data { + UnsupportedData::OffsetInStream + | UnsupportedData::NoSize + | UnsupportedData::UrlOrEncoding + | UnsupportedData::Absent => (uapi16_error_kind_t::UAPI16_ERROR_UNSUPPORTED, libc::EOPNOTSUPP), + }, + ErrorKind::NotValid(problem) => match problem { + ValidityProblem::Revoked => (uapi16_error_kind_t::UAPI16_ERROR_REVOKED, libc::EKEYREVOKED), + ValidityProblem::NotYetValid => (uapi16_error_kind_t::UAPI16_ERROR_NOT_YET_VALID, libc::EKEYEXPIRED), + ValidityProblem::Expired => (uapi16_error_kind_t::UAPI16_ERROR_EXPIRED, libc::EKEYEXPIRED), + }, + } + } + + /// The kind and the errno of the error `error` of a system call: the + /// errno it failed with, or [`uapi16_error::WITHOUT_ERRNO`] where it + /// has none. + fn io_kind_of(error: &Error) -> (uapi16_error_kind_t, c_int) { + let errno = error.io_error().and_then(io::Error::raw_os_error); + let errno = errno.filter(|errno| *errno > 0); + ( + uapi16_error_kind_t::UAPI16_ERROR_IO, + errno.unwrap_or(uapi16_error::WITHOUT_ERRNO), + ) + } +} + +impl From for uapi16_error { + /// The error C has for the error `error` of the builder: its kind and + /// its errno, and what it is about as strings C can take. + fn from(error: Error) -> uapi16_error { + let (kind, errno) = uapi16_error::kind_of(&error); + // No name of a file object has a NUL, which is a control character. + let text = |text: Option<&str>| text.and_then(|text| CString::new(text).ok()); + uapi16_error { + kind, + errno, + path: text(error.name()), + hardlink_path: text(error.hardlink_name()), + feature: error.feature().and_then(uapi16_feature_t::of), + raw_name: error.raw_name().map(|name| name.as_bytes().into()), + name_problem: error.name_problem().and_then(uapi16_name_problem_t::of), + field: error.field(), + record: error.record_number(), + problem: match error.kind() { + ErrorKind::Manifest(problem) => Some(problem), + _ => None, + }, + } + } +} + +/// How a flag of a `T` is read: whether it is set, cleared or not stated. +/// cbindgen:no-export +type FlagGetter = fn(&T) -> Option; +/// How a flag of a `T` is stated as set or cleared, or taken away. +/// cbindgen:no-export +type FlagSetter = fn(&mut T, Option); + +/// The strings of a file object as C takes them: each ends in a NUL. Rust +/// keeps none of them that way, so a copy of a string is made when a caller +/// first asks for it, and stays until the object is given another one +/// there. +#[derive(Debug, Default)] +struct Texts { + name: OnceBox, + user_name: OnceBox>, + group_name: OnceBox>, + fs_label: OnceBox>, + /// The name of the file the data is in, where that is another one than + /// the object's own. It is handed out only while the object names that + /// file, and made again once it names another one. + contents_file: OnceBox>, + /// The names of the extended attributes, in their order. + xattr_names: OnceBox>, +} + +impl Texts { + /// The string `text` as C takes it, which `slot` keeps: NULL where + /// there is none, and for one with a NUL, which C can't take. + fn optional(slot: &OnceBox>, text: Option<&str>) -> *const c_char { + let kept = slot.get_or_init(|| text.and_then(|text| CString::new(text).ok())); + kept.as_deref().map_or(ptr::null(), CStr::as_ptr) + } +} + +/// A file object: what a manifest says about one file, or about the root +/// directory of the tree it describes. Made by uapi16_file_object_new() and +/// by uapi16_reader_next(), handed out by uapi16_reader_root(), and freed by +/// uapi16_file_object_free(). +/// +/// The root is the object with the empty name. It is a directory. Besides +/// its attributes it has the label, the UUID and the FAT serial number of +/// the file system. It has no size, no hash, no target, no device numbers, +/// no token and no DOS attributes. +/// +/// A setter stores what it is given and checks the call alone. A writer +/// checks the object when it gets it. A getter of a number that the object +/// does not have fails with -ENODATA and stores nothing, and a getter of a +/// string returns NULL for it. What a reader filled in reads like any other +/// value: a size and a hash that follow from other fields, and a flag that +/// is cleared, a file that is not read-only and extended attributes there +/// are none of, where the features of the manifest say so. A writer leaves +/// these out again. +/// +/// The object keeps a copy of every string and of all bytes it is given. +#[derive(Debug)] +struct uapi16_file_object { + /// What the object says of the file. The root is here as well, under + /// the empty name and as a directory: a setter stores what it is given, + /// and a writer refuses a root that has what only another file object + /// has. + object: FileObject, + /// What only the root says: the identity of its file system. A writer + /// refuses any other object that has one. + file_system: FileSystemIdentity, + /// `gptDiskUuid` of a root that a reader handed out, which no setter + /// sets. A writer of records writes it back. + gpt_disk_uuid: Option, + texts: Texts, + process: Process, +} + +impl Object for uapi16_file_object {} + +impl uapi16_file_object { + /// The Linux inode flags a manifest has: the bit FS_IOC_GETFLAGS has + /// for each, how it is read and how it is set. + const INODE_FLAGS: [(IFlags, FlagGetter, FlagSetter); 5] = [ + ( + IFlags::APPEND, + InodeAttributes::flag_append_only, + InodeAttributes::set_flag_append_only, + ), + ( + IFlags::IMMUTABLE, + InodeAttributes::flag_immutable, + InodeAttributes::set_flag_immutable, + ), + ( + IFlags::NOATIME, + InodeAttributes::flag_no_atime, + InodeAttributes::set_flag_no_atime, + ), + ( + IFlags::NOCOW, + InodeAttributes::flag_no_cow, + InodeAttributes::set_flag_no_cow, + ), + ( + IFlags::NODUMP, + InodeAttributes::flag_no_dump, + InodeAttributes::set_flag_no_dump, + ), + ]; + /// The DOS attributes a manifest has a field for: the bit a directory + /// entry of FAT has for each, how it is read and how it is set. + const DOS_ATTRIBUTES: [(u32, FlagGetter, FlagSetter); 3] = [ + ( + DosAttributes::HIDDEN, + FileObject::flag_hidden, + FileObject::set_flag_hidden, + ), + ( + DosAttributes::SYSTEM, + FileObject::flag_system, + FileObject::set_flag_system, + ), + ( + DosAttributes::ARCHIVE, + FileObject::flag_archive, + FileObject::set_flag_archive, + ), + ]; + + /// The object of this process for the file object `object` and the + /// identity `file_system` of a file system. + fn of(object: FileObject, file_system: FileSystemIdentity, gpt_disk_uuid: Option) -> uapi16_file_object { + uapi16_file_object { + object, + file_system, + gpt_disk_uuid, + texts: Texts::default(), + process: Process::current(), + } + } + + /// What uapi16_file_object_new() does. + fn new(name: Text<'_>) -> Result { + let name = Name::of_text(name)?; + let mut object = FileObject::new(name.to_owned()); + if name.is_root() { + object.set_inode_type(InodeType::Directory); + } + Ok(uapi16_file_object::of(object, FileSystemIdentity::default(), None)) + } + + /// The object for a file object that a reader read. + fn of_file(object: FileObject) -> uapi16_file_object { + uapi16_file_object::of(object, FileSystemIdentity::default(), None) + } + + /// The object for the root file object `root` that a reader read. What + /// the root says of the manifest as a whole stays with the reader: the + /// features and the order. + fn of_root(root: &RootObject) -> uapi16_file_object { + let mut object = FileObject::new(Name::ROOT.to_owned()); + object.set_inode_type(InodeType::Directory); + *object.inode_mut() = root.inode().clone(); + object.set_validity(root.validity()); + uapi16_file_object::of(object, root.file_system().clone(), root.gpt_disk_uuid()) + } + + /// Whether the object is the root: the one with the empty name. + fn is_root(&self) -> bool { + self.object.name().is_root() + } + + /// The root file object of what the object says, whatever its name is, + /// without what a manifest says as a whole: its features and its order. + fn root(&self) -> RootObject { + let mut root = RootObject::default(); + *root.inode_mut() = self.object.inode().clone(); + *root.file_system_mut() = self.file_system.clone(); + root.set_gpt_disk_uuid(self.gpt_disk_uuid); + root.set_validity(self.object.validity()); + root + } + + /// The root as a manifest writer lists it: the inode attributes of the + /// root directory and the identity of its file system, which is all + /// the manifest of a tree says of its root. A root that says more is + /// refused, as an object with a field it can't have. Only a root that + /// a reader read can: the UUID of a disk, and when the manifest may be + /// used. + fn as_tree_root(&self) -> Result { + let root = self.as_root()?; + let validity = root.validity(); + let more = [ + (Field::GptDiskUuid, root.gpt_disk_uuid().is_some()), + ( + Field::ValidSinceUSec, + validity.since_usec() != ValidityWindow::default().since_usec(), + ), + (Field::ValidUntilUSec, validity.until_usec().is_some()), + (Field::Validity, validity.state() != ValidityWindow::default().state()), + ]; + match more.into_iter().find(|(_, has)| *has) { + Some((field, _)) => Err(self.not_permitted(field)), + None => Ok(root), + } + } + + /// The error of a writer that is given an object with the field + /// `field`, which a manifest can't hold on it. + fn not_permitted(&self, field: Field) -> uapi16_error { + let message = format!("'{}' is not permitted on this file object", field); + Error::manifest(Problem::FieldNotPermitted, message) + .at(field) + .named(self.object.name().as_str()) + .into() + } + + /// The object as the root file object a writer takes. The root has no + /// size, no hash, no contents, no token, no device numbers and no DOS + /// attributes, so an object that states one of them is refused, as a + /// reader refuses a root with such a field. An object with another name + /// is no root. + fn as_root(&self) -> Result { + if !self.is_root() { + return Err(uapi16_error::misuse()); + } + let object = &self.object; + let stated = |field, has: bool| has && !object.filled_in().contains(field); + let only_files_have = [ + (Field::Size, stated(Field::Size, object.size().is_some())), + (Field::Sha256, stated(Field::Sha256, object.sha256().is_some())), + (Field::Contents, !object.contents().is_empty()), + (Field::InodeToken, object.inode_token().is_some()), + (Field::Major, object.major().is_some()), + (Field::Minor, object.minor().is_some()), + (Field::FlagArchive, object.flag_archive().is_some()), + (Field::FlagHidden, object.flag_hidden().is_some()), + (Field::FlagSystem, object.flag_system().is_some()), + ]; + match only_files_have.into_iter().find(|(_, has)| *has) { + Some((field, _)) => Err(self.not_permitted(field)), + None => Ok(self.root()), + } + } + + /// The object as a file object a writer takes. Only the root has the + /// identity of a file system, so any other object that has a part of + /// one is refused, as a reader refuses it. The root is passed on as it + /// is: the writer says what it makes of a file object without a name. + fn as_file(&self) -> Result<&FileObject, uapi16_error> { + match self.only_the_root_has() { + Some(field) if !self.is_root() => Err(self.not_permitted(field)), + _ => Ok(&self.object), + } + } + + /// The first field the object has of those only the root has, which + /// are kept next to its file object. None for an object without any. + fn only_the_root_has(&self) -> Option { + let only_the_root_has = [ + (Field::FatSerial, self.file_system.fat_serial().is_some()), + (Field::FsLabel, self.file_system.label().is_some()), + (Field::FsUuid, self.file_system.uuid().is_some()), + (Field::GptDiskUuid, self.gpt_disk_uuid.is_some()), + ]; + let mut fields = only_the_root_has.into_iter(); + fields.find(|(_, has)| *has).map(|(field, _)| field) + } + + /// What uapi16_file_object_set_name() does. + fn set_name(&mut self, name: Text<'_>) -> Result<(), uapi16_error> { + let name = Name::of_text(name)?; + if self.is_root() || name.is_root() { + return Err(uapi16_error::misuse()); + } + self.process.check()?; + self.object.set_name(name.to_owned()); + self.texts.name.reset(); + Ok(()) + } + + /// What uapi16_file_object_name() does. + fn name(&self) -> *const c_char { + let name = || CString::new(self.object.name().as_str()).unwrap_or_default(); + self.texts.name.get_or_init(name).as_ptr() + } + + /// What uapi16_file_object_set_type() does. + fn set_type(&mut self, st_mode: u32) -> Result<(), uapi16_error> { + let inode_type = InodeType::of_st_mode(st_mode).ok_or_else(uapi16_error::misuse)?; + if self.is_root() && inode_type != InodeType::Directory { + return Err(uapi16_error::misuse()); + } + self.process.check()?; + self.object.set_inode_type(inode_type); + Ok(()) + } + + /// What uapi16_file_object_set_mode() does. + fn set_mode(&mut self, st_mode: u32) -> Result<(), uapi16_error> { + let mode = Mode::new(st_mode & !libc::S_IFMT).map_err(|_| uapi16_error::misuse())?; + self.process.check()?; + self.object.inode_mut().set_mode(Some(mode)); + Ok(()) + } + + /// The inode attributes, to change them, in the process that made the + /// object. + fn inode_mut(&mut self) -> Result<&mut InodeAttributes, uapi16_error> { + self.process.check()?; + Ok(self.object.inode_mut()) + } + + /// The inode attributes, in the process that made the object. + fn inode(&self) -> Result<&InodeAttributes, uapi16_error> { + self.process.check()?; + Ok(self.object.inode()) + } + + /// The file object, to change it, in the process that made the object. + fn file_mut(&mut self) -> Result<&mut FileObject, uapi16_error> { + self.process.check()?; + Ok(&mut self.object) + } + + /// The file object, in the process that made the object. + fn file(&self) -> Result<&FileObject, uapi16_error> { + self.process.check()?; + Ok(&self.object) + } + + /// The identity of the file system, to change it, in the process that + /// made the object. + fn file_system_mut(&mut self) -> Result<&mut FileSystemIdentity, uapi16_error> { + self.process.check()?; + Ok(&mut self.file_system) + } + + /// The identity of the file system, in the process that made the + /// object. + fn file_system(&self) -> Result<&FileSystemIdentity, uapi16_error> { + self.process.check()?; + Ok(&self.file_system) + } + + /// A string as a setter takes it: UTF-8, which a caller is told to + /// pass. + fn text(text: Text<'_>) -> Result { + let text = text.get()?.to_str().map_err(|_| uapi16_error::misuse())?; + Ok(text.to_owned()) + } + + /// What uapi16_file_object_set_user_name() does. + fn set_user_name(&mut self, name: Text<'_>) -> Result<(), uapi16_error> { + let name = uapi16_file_object::text(name)?; + self.inode_mut()?.set_user_name(Some(name)); + self.texts.user_name.reset(); + Ok(()) + } + + /// What uapi16_file_object_user_name() does. + fn user_name(&self) -> *const c_char { + Texts::optional(&self.texts.user_name, self.object.inode().user_name()) + } + + /// What uapi16_file_object_set_group_name() does. + fn set_group_name(&mut self, name: Text<'_>) -> Result<(), uapi16_error> { + let name = uapi16_file_object::text(name)?; + self.inode_mut()?.set_group_name(Some(name)); + self.texts.group_name.reset(); + Ok(()) + } + + /// What uapi16_file_object_group_name() does. + fn group_name(&self) -> *const c_char { + Texts::optional(&self.texts.group_name, self.object.inode().group_name()) + } + + /// What uapi16_file_object_set_inode_token() does: + /// UAPI16_INODE_TOKEN_NONE is no token. + fn set_inode_token(&mut self, token: uapi16_inode_token_t) -> Result<(), uapi16_error> { + let token = match token { + UAPI16_INODE_TOKEN_NONE => None, + token => NonZeroU64::new(token), + }; + self.file_mut()?.set_inode_token(token); + Ok(()) + } + + /// What uapi16_file_object_set_user_xattrs() does. + fn set_user_xattrs(&mut self) -> Result<(), uapi16_error> { + self.inode_mut()?.set_user_xattrs(Some(BTreeMap::new())); + // No attribute is left, so no name is handed out before one is + // added, which has the names made anew. This frees the old ones + // early. + self.texts.xattr_names.reset(); + Ok(()) + } + + /// What uapi16_file_object_add_user_xattr() does. + fn add_user_xattr(&mut self, name: Text<'_>, value: Bytes<'_>) -> Result<(), uapi16_error> { + let (name, value) = (uapi16_file_object::text(name)?, value.get()?); + self.inode_mut()?.insert_user_xattr(name, value); + self.texts.xattr_names.reset(); + Ok(()) + } + + /// What uapi16_file_object_user_xattrs() does. + fn user_xattrs(&self) -> Result { + let xattrs = self.inode()?.user_xattrs().ok_or_else(uapi16_error::absent)?; + Ok(xattrs.len()) + } + + /// What uapi16_file_object_user_xattr() does: the name, the value and + /// the size of the value of the extended attribute number `i`. The + /// names are copied once for all of them, and a value is looked up by + /// its name, so that going through all of them does not look at each + /// one for every other. + fn user_xattr(&self, i: usize) -> Result<(*const c_char, *const c_void, usize), uapi16_error> { + let inode = self.object.inode(); + // What a call is given comes first, then the process, and the + // names are made after both. + if i >= inode.user_xattrs().map_or(0, |xattrs| xattrs.len()) { + return Err(uapi16_error::misuse()); + } + self.process.check()?; + let listed = || match inode.user_xattrs() { + Some(xattrs) => xattrs.map(|(name, _)| CString::new(name).unwrap_or_default()).collect(), + None => Box::default(), + }; + let name = self.texts.xattr_names.get_or_init(listed).get(i); + let name = name.ok_or_else(uapi16_error::misuse)?; + let value = name.to_str().ok().and_then(|name| inode.user_xattr(name)); + let value = value.unwrap_or_default(); + Ok((name.as_ptr(), value.as_ptr().cast(), value.len())) + } + + /// What uapi16_file_object_set_read_only() does. + fn set_read_only(&mut self, read_only: ReadOnlyNumber) -> Result<(), uapi16_error> { + let read_only = uapi16_read_only_t::of_number(read_only)?; + self.inode_mut()?.set_read_only(read_only); + Ok(()) + } + + /// What uapi16_file_object_set_inode_flags() does. + fn set_inode_flags(&mut self, stated: u32, set: u32) -> Result<(), uapi16_error> { + let inode = self.inode_mut()?; + for (flag, _, put) in uapi16_file_object::INODE_FLAGS { + let flag = flag.bits(); + put(inode, (stated & flag != 0).then_some(set & flag != 0)); + } + Ok(()) + } + + /// What uapi16_file_object_inode_flags() does: the flags the object + /// states, and those of them that are set. + fn inode_flags(&self) -> Result<(u32, u32), uapi16_error> { + let inode = self.inode()?; + let mut flags = (0, 0); + for (flag, get, _) in uapi16_file_object::INODE_FLAGS { + if let Some(set) = get(inode) { + flags.0 |= flag.bits(); + flags.1 |= if set { flag.bits() } else { 0 }; + } + } + Ok(flags) + } + + /// What uapi16_file_object_set_dos_attributes() does. + fn set_dos_attributes(&mut self, stated: u32, set: u32) -> Result<(), uapi16_error> { + let object = self.file_mut()?; + for (attribute, _, put) in uapi16_file_object::DOS_ATTRIBUTES { + put(object, (stated & attribute != 0).then_some(set & attribute != 0)); + } + Ok(()) + } + + /// What uapi16_file_object_dos_attributes() does: the attributes the + /// object states, and those of them that are set. + fn dos_attributes(&self) -> Result<(u32, u32), uapi16_error> { + let object = self.file()?; + let mut attributes = (0, 0); + for (attribute, get, _) in uapi16_file_object::DOS_ATTRIBUTES { + if let Some(set) = get(object) { + attributes.0 |= attribute; + attributes.1 |= if set { attribute } else { 0 }; + } + } + Ok(attributes) + } + + /// What uapi16_file_object_set_target() does. + fn set_target(&mut self, target: Bytes<'_>) -> Result<(), uapi16_error> { + let target = ContentsSource::Literal(target.get()?.to_vec()); + self.file_mut()?.set_contents(vec![ContentsObject::new(target)]); + Ok(()) + } + + /// What uapi16_file_object_set_contents_file() does. The empty name is + /// that of the root, which is no file next to a manifest. + fn set_contents_file(&mut self, file: Text<'_>) -> Result<(), uapi16_error> { + let file = Name::of_text(file)?; + if file.is_root() { + return Err(uapi16_error::bad_name(NameProblem::Empty)); + } + let file = ContentsSource::File(file.to_owned()); + self.file_mut()?.set_contents(vec![ContentsObject::new(file)]); + self.texts.contents_file.reset(); + Ok(()) + } + + /// The file the data of the object is in and where the data starts in + /// it, where that is another file than the one of its own name. + fn other_file(&self) -> Option> { + match self.object.data_location() { + Ok(DataLocation::External(file)) if file.name() != self.object.name() => Some(file), + _ => None, + } + } + + /// What uapi16_file_object_contents_file() does: the name of that file, + /// as a string of the object, and where the data starts in it. + fn contents_file(&self) -> Result<(*const c_char, u64), uapi16_error> { + self.process.check()?; + let file = self.other_file().ok_or_else(uapi16_error::absent)?; + let name = Texts::optional(&self.texts.contents_file, Some(file.name().as_str())); + Ok((name, file.offset())) + } + + /// What uapi16_file_object_data_location() does: where the data is. + fn data_location(&self) -> uapi16_data_location_t { + match self.object.data_location() { + Ok(DataLocation::Literal(_)) => uapi16_data_location_t::UAPI16_DATA_LOCATION_LITERAL, + Ok(DataLocation::External(_)) => uapi16_data_location_t::UAPI16_DATA_LOCATION_EXTERNAL, + Err(e) if e.kind() == ErrorKind::Unsupported(UnsupportedData::UrlOrEncoding) => { + uapi16_data_location_t::UAPI16_DATA_LOCATION_UNSUPPORTED + } + Err(_) => uapi16_data_location_t::UAPI16_DATA_LOCATION_NONE, + } + } + + /// What uapi16_file_object_literal() does: the data, where the manifest + /// carries it. + fn literal(&self) -> Option<&[u8]> { + match self.object.data_location() { + Ok(DataLocation::Literal(data)) => Some(data), + _ => None, + } + } + + /// What uapi16_file_object_set_fs_label() does. + fn set_fs_label(&mut self, label: Text<'_>) -> Result<(), uapi16_error> { + let label = uapi16_file_object::text(label)?; + self.file_system_mut()?.set_label(Some(label)); + self.texts.fs_label.reset(); + Ok(()) + } + + /// What uapi16_file_object_fs_label() does. + fn fs_label(&self) -> *const c_char { + Texts::optional(&self.texts.fs_label, self.file_system.label()) + } + + /// What uapi16_file_object_has_stated_feature() says and + /// uapi16_file_object_stated_features() stores: the features of the + /// fields of a file object, which it keeps as a set, and of those only + /// the root has. A root file object knows the features of the + /// second. It gets them without what is in them, and gets no inode + /// attributes, which the file object counts itself: a field that is + /// there states its feature, whatever it holds. So the two getters + /// copy neither the extended attributes nor the label of an object, + /// however large they are. An object without any field that only the + /// root has states no feature of one, and no root is asked: that is + /// every file object of a manifest but one. + fn stated_features(&self) -> Features { + if self.only_the_root_has().is_none() { + return self.object.stated_features(); + } + let mut root = RootObject::default(); + let identity = root.file_system_mut(); + identity.set_uuid(self.file_system.uuid()); + identity.set_label(self.file_system.label().map(|_| String::new())); + identity.set_fat_serial(self.file_system.fat_serial()); + root.set_gpt_disk_uuid(self.gpt_disk_uuid); + self.object.stated_features() | root.stated_features() + } + + /// What uapi16_file_object_retain_features() does. What only the root + /// has is kept next to the file object, so it goes through a root file + /// object for that, which knows the features of its fields. A string + /// the object handed out stays where it is as long as its field does. + fn retain_features(&mut self, features: Features) -> Result<(), uapi16_error> { + self.process.check()?; + self.object.retain_features(features); + let mut root = RootObject::default(); + *root.file_system_mut() = mem::take(&mut self.file_system); + root.set_gpt_disk_uuid(self.gpt_disk_uuid); + root.retain_features(features); + self.file_system = mem::take(root.file_system_mut()); + self.gpt_disk_uuid = root.gpt_disk_uuid(); + let inode = self.object.inode(); + if inode.user_name().is_none() { + self.texts.user_name.reset(); + } + if inode.group_name().is_none() { + self.texts.group_name.reset(); + } + if inode.user_xattrs().is_none() { + // As in set_user_xattrs(): this frees the old names early. + self.texts.xattr_names.reset(); + } + if self.file_system.label().is_none() { + self.texts.fs_label.reset(); + } + Ok(()) + } + + /// What uapi16_file_object_check_validity() does. The validity of the + /// root is that of its manifest, which a root file object checks. It + /// gets the validity and nothing else, so the check copies none of the + /// object's fields. + fn check_validity(&self, now_usec: u64) -> Result<(), uapi16_error> { + self.process.check()?; + if self.is_root() { + let mut root = RootObject::default(); + root.set_validity(self.object.validity()); + let checked = root.check_validity(now_usec); + checked.map_err(|e| uapi16_error::from(e).about(Name::ROOT))?; + } else { + self.object.check_validity(now_usec)?; + } + Ok(()) + } +} + +/// A signature object: a signature over the manifest up to the first +/// signature object. Made by uapi16_signature_new() and by +/// uapi16_reader_next_signature(), and freed by uapi16_signature_free(). +/// +/// A manifest can carry several. The library reads and writes them, and +/// neither makes nor verifies a signature: that takes an OpenPGP or an X.509 +/// implementation. +#[derive(Debug)] +struct uapi16_signature { + signature: SignatureObject, + /// The mechanism as C takes it, from when a caller first asks for it. + mechanism: OnceBox>, + process: Process, +} + +impl Object for uapi16_signature {} + +impl uapi16_signature { + /// The object of this process for the signature object `signature`. + fn of(signature: SignatureObject) -> uapi16_signature { + uapi16_signature { + signature, + mechanism: OnceBox::new(), + process: Process::current(), + } + } + + /// What uapi16_signature_new() does. + fn new(mechanism: Text<'_>) -> Result { + let mechanism = mechanism.get()?.to_str().map_err(|_| uapi16_error::misuse())?; + Ok(uapi16_signature::of(SignatureObject::new(mechanism))) + } + + /// What uapi16_signature_mechanism() does. + fn mechanism(&self) -> *const c_char { + Texts::optional(&self.mechanism, Some(self.signature.mechanism())) + } + + /// The signature object, to change it, in the process that made the + /// object. + fn signature_mut(&mut self) -> Result<&mut SignatureObject, uapi16_error> { + self.process.check()?; + Ok(&mut self.signature) + } + + /// Bytes as the two setters take them: the `size` bytes at `data`, or + /// none at all for a `data` of NULL, which takes them away. + /// + /// # Safety + /// + /// `data` is NULL, or valid for the read of `size` bytes that do not + /// change for `'a`. + unsafe fn bytes<'a>(data: *const c_void, size: usize) -> Option> { + if data.is_null() { + return None; + } + // SAFETY: `data` is not NULL, so it is valid for the read of `size` + // bytes that stay as they are for `'a`, as the caller says. + Some(unsafe { Bytes::new(data, size) }) + } + + /// What a getter of bytes returns for `bytes`: where they are, with + /// how many there are in `ret_size`, or NULL and 0 for none. + fn bytes_out(bytes: Option<&[u8]>, ret_size: Place<'_, usize>) -> *const c_void { + ret_size.store(bytes.map_or(0, <[u8]>::len)); + bytes.map_or(ptr::null(), |bytes| bytes.as_ptr().cast()) + } +} + +/// Reads a manifest record by record, and checks it. Made by +/// uapi16_reader_open(), and freed by uapi16_reader_free(). +/// +/// The reader checks every object against the rules of the specification, +/// and where it comes: right after the object of its directory, and in the +/// order the manifest declares. It keeps one record in memory, whatever the +/// size of the manifest, and reads its descriptor once, so a manifest can +/// come through a pipe. +/// +/// uapi16_reader_next() reads the file objects, and says what it read with +/// a uapi16_read_t. It returns UAPI16_READ_END once it has read and checked +/// the trailer: then the manifest is complete. Where signature objects +/// follow the file objects, it returns UAPI16_READ_SIGNATURES first. A +/// caller that wants them reads them with uapi16_reader_next_signature() +/// then. A caller that does not goes on with uapi16_reader_next(), which +/// passes over them. The signature objects are checked and not verified. +/// +/// Once one of the two failed to read an object, every later call of them +/// fails with UAPI16_ERROR_ENDED. EAGAIN of a descriptor that does not +/// block is the exception: the reader lost nothing, and reads on with the +/// next call. +#[derive(Debug)] +struct uapi16_reader { + /// The reader, of the descriptor the caller lent to + /// uapi16_reader_open(). + reader: Reader>, + /// The root of the manifest as the file object that + /// uapi16_reader_root() hands out. + root: uapi16_file_object, + stage: Stage, + process: Process, +} + +/// How far a reader of the C API has got in its manifest. +#[derive(Debug)] +enum Stage { + /// File objects come. + Files, + /// The file objects are done and signature objects come. The first of + /// them was read to find that out, and waits here until a caller takes + /// it or passes over it. + Signatures(Option), + /// The trailer was read, so the manifest is complete. + End, + /// A call failed to read an object. The reader takes nothing more. + Failed, +} + +impl Object for uapi16_reader {} + +impl uapi16_reader { + /// What uapi16_reader_open() does. The reader has `fd` on loan, and + /// reads the manifest from it. + /// + /// # Safety + /// + /// `fd` stays open until the reader this returns is dropped. + unsafe fn open(fd: Descriptor<'_>) -> Result { + // SAFETY: the reader keeps the file until it is dropped, and the + // descriptor stays open for that long, as the caller says. + let file = unsafe { fd.lend(File::from) }?; + let reader = Reader::open(file).map_err(|e| uapi16_error::from(e).of_root_record())?; + Ok(uapi16_reader { + root: uapi16_file_object::of_root(reader.root()), + reader, + stage: Stage::Files, + process: Process::current(), + }) + } + + /// What uapi16_reader_features() stores: the features the manifest + /// records. + fn features(&self) -> Result { + self.process.check()?; + Ok(self.reader.root().recorded_features()) + } + + /// What uapi16_reader_order() does: the order the manifest declares. + fn order(&self) -> uapi16_order_t { + Order::number(self.reader.root().order()) + } + + /// What uapi16_reader_require_order() does. No order is none to + /// require. The error is about the root, whose record has the field. + fn require_order(&self, order: OrderNumber) -> Result<(), uapi16_error> { + let order = Order::of_number(order)?.ok_or_else(uapi16_error::misuse)?; + self.process.check()?; + let required = self.reader.root().require_order(order); + required.map_err(|e| uapi16_error::from(e).of_root_record())?; + Ok(()) + } + + /// What uapi16_reader_check_validity() does. + fn check_validity(&self, now_usec: u64) -> Result<(), uapi16_error> { + self.process.check()?; + let checked = self.reader.root().check_validity(now_usec); + checked.map_err(|e| uapi16_error::from(e).about(Name::ROOT))?; + Ok(()) + } + + /// What uapi16_reader_signed_len() does. + fn signed_len(&self) -> Result { + self.process.check()?; + self.reader.signed_len().ok_or_else(uapi16_error::absent) + } + + /// Reads the next object of the manifest, or None once its trailer was + /// read. An error ends the reader, unless it is that of a descriptor + /// that does not block and has nothing right now: the reader lost + /// nothing then, and reads on with the next call. + fn pull(&mut self) -> Result, uapi16_error> { + match self.reader.next() { + Some(Ok(object)) => Ok(Some(object)), + None => { + self.stage = Stage::End; + Ok(None) + } + Some(Err(e)) => { + if e.io_error().map(io::Error::kind) != Some(io::ErrorKind::WouldBlock) { + self.stage = Stage::Failed; + } + Err(e.into()) + } + } + } + + /// What uapi16_reader_next() does: what the call returns. A file + /// object goes to `kept`, which stays as it is where the call returns + /// anything but UAPI16_READ_FILE. An object of the caller that the + /// call is to fill is one of this process, as every object a call is + /// given. + fn next(&mut self, kept: Refill<'_, uapi16_file_object>) -> Result { + self.process.check()?; + kept.object().map_or(Ok(()), |object| object.process.check())?; + loop { + match self.stage { + Stage::Failed => return Err(uapi16_error::ended()), + Stage::End => return Ok(uapi16_read_t::UAPI16_READ_END), + Stage::Files => match self.pull()? { + Some(Record::File(object)) => { + kept.store(uapi16_file_object::of_file(*object)); + return Ok(uapi16_read_t::UAPI16_READ_FILE); + } + Some(Record::Signature(signature)) => { + self.stage = Stage::Signatures(Some(signature)); + return Ok(uapi16_read_t::UAPI16_READ_SIGNATURES); + } + None => {} + }, + // The signature objects are passed over. The reader checks + // each of them all the same, and that no file object comes + // after them. + Stage::Signatures(_) => { + self.stage = Stage::Signatures(None); + self.pull()?; + } + } + } + } + + /// What uapi16_reader_next_signature() does: what the call returns. A + /// signature object goes to `kept`, as a file object of + /// uapi16_reader_next() does. It is not a valid call while file objects + /// come. At the end of a manifest it says so, also for a manifest that + /// has no signature objects. + fn next_signature(&mut self, kept: Refill<'_, uapi16_signature>) -> Result { + self.process.check()?; + kept.object().map_or(Ok(()), |signature| signature.process.check())?; + loop { + let signature = match &mut self.stage { + Stage::Failed => return Err(uapi16_error::ended()), + Stage::End => return Ok(uapi16_read_t::UAPI16_READ_END), + Stage::Files => return Err(uapi16_error::misuse()), + Stage::Signatures(waiting) => waiting.take(), + }; + let signature = match signature { + Some(signature) => Some(signature), + None => match self.pull()? { + Some(Record::Signature(signature)) => Some(signature), + // The reader refuses a file object after a signature + // object, so none comes here. + Some(Record::File(_)) | None => None, + }, + }; + if let Some(signature) = signature { + kept.store(uapi16_signature::of(signature)); + return Ok(uapi16_read_t::UAPI16_READ_SIGNATURE); + } + } + } +} + +/// Writes a manifest record by record, for a caller that has its file +/// objects in the order of the manifest already: every directory before +/// what is in it, and the names of a directory in the order of their bytes. +/// Made by uapi16_writer_begin(), and freed by uapi16_writer_free(). +/// +/// With options whose order is UAPI16_ORDER_NONE the manifest declares no +/// order, and the file objects are written in the order of the caller. Each +/// still comes right after the object of its directory. +/// +/// Every call writes its record before it returns, and nothing is kept on +/// disk. A manifest without its trailer is one a reader takes as +/// incomplete, so a writer that is freed before it finished leaves nothing +/// that passes for a manifest. A write that fails ends the writer. +#[derive(Debug)] +struct uapi16_writer { + /// The writer, of the descriptor the caller lent to + /// uapi16_writer_begin(), until uapi16_writer_finish() took it. + writer: Option>>, + process: Process, +} + +impl Object for uapi16_writer {} + +impl uapi16_writer { + /// What uapi16_writer_begin() does. The root says what the root + /// directory and its file system are like, and the options what the + /// manifest records and in which order. The writer has `fd` on loan, + /// and writes the manifest to it. + /// + /// # Safety + /// + /// `fd` stays open until the writer this returns is dropped. + unsafe fn begin( + options: &uapi16_manifest_options, + fd: Descriptor<'_>, + root: Option<&uapi16_file_object>, + ) -> Result { + if root.is_some_and(|root| !root.is_root()) { + return Err(uapi16_error::misuse()); + } + // SAFETY: the writer keeps the file until it is dropped, and the + // descriptor stays open for that long, as the caller says. + let out = unsafe { fd.lend(File::from) }?; + options.process.check()?; + root.map_or(Ok(()), |root| root.process.check())?; + // A root that is refused here would have been the first record, as + // one that the writer refuses. + let root = root.map_or_else(|| Ok(RootObject::default()), uapi16_file_object::as_root); + let mut root = root.map_err(|e| e.in_record(ROOT_RECORD))?; + root.set_features(Some(options.features())); + root.set_order(options.order); + let writer = Writer::begin(out, &root).map_err(|e| uapi16_error::from(e).of_root())?; + Ok(uapi16_writer { + writer: Some(writer), + process: Process::current(), + }) + } + + /// The writer in the process that made it, unless it is finished: one + /// that is takes nothing more. + fn writer(&mut self) -> Result<&mut Writer>, uapi16_error> { + self.process.check()?; + self.writer.as_mut().ok_or_else(uapi16_error::ended) + } + + /// What uapi16_writer_file() does. The object is one of this process + /// as well, as every object a call is given. An object that is refused + /// here is refused as the record it would have been, as one that the + /// writer refuses. + fn file(&mut self, object: &uapi16_file_object) -> Result<(), uapi16_error> { + self.process.check()?; + object.process.check()?; + let writer = self.writer()?; + let file = object.as_file().map_err(|e| e.in_record(writer.next_record()))?; + let written = writer.file(file); + self.written(written) + } + + /// What uapi16_writer_signature() does. + fn signature(&mut self, signature: &uapi16_signature) -> Result<(), uapi16_error> { + self.process.check()?; + signature.process.check()?; + let written = self.writer()?.signature(&signature.signature); + self.written(written) + } + + /// What a write of a record came to. A write that failed ends the + /// writer: it takes nothing more, as after uapi16_writer_finish(). The + /// writer has counted the record as written before its bytes went out, + /// so what was written lacks the record, or has a part of it, and + /// whatever came after that would pass for a manifest that has it. A + /// record that the writer refuses is no write, and leaves the writer as + /// it was. + fn written(&mut self, written: Result<(), Error>) -> Result<(), uapi16_error> { + if written.as_ref().is_err_and(|e| e.kind() == ErrorKind::Io) { + self.writer = None; + } + Ok(written?) + } + + /// What uapi16_writer_finish() does. The writer is finished after + /// that, also where it failed. The descriptor of the caller is done + /// with here, and is left open. + fn finish(&mut self) -> Result<(), uapi16_error> { + self.process.check()?; + let writer = self.writer.take().ok_or_else(uapi16_error::ended)?; + writer.finish()?; + Ok(()) + } +} + +/// Computes the SHA-256 hash of data that comes in pieces, such as the data +/// of a file while it is copied into an image. Made by uapi16_sha256_new(), +/// and freed by uapi16_sha256_free(). +#[derive(Debug)] +struct uapi16_sha256 { + /// The computation, until uapi16_sha256_finish() took it. + context: Option, + process: Process, +} + +impl Object for uapi16_sha256 {} + +impl uapi16_sha256 { + /// A computation of this process that has taken no data yet. + fn new() -> uapi16_sha256 { + uapi16_sha256 { + context: Some(Sha256Context::new()), + process: Process::current(), + } + } + + /// The computation in the process that made it, unless it is finished: + /// one that is takes nothing more. + fn context(&mut self) -> Result<&mut Sha256Context, uapi16_error> { + self.process.check()?; + self.context.as_mut().ok_or_else(uapi16_error::ended) + } + + /// What uapi16_sha256_update() does. + fn update(&mut self, data: Bytes<'_>) -> Result<(), uapi16_error> { + let data = data.get()?; + self.context()?.update(data); + Ok(()) + } + + /// What uapi16_sha256_update_zeros() does. + fn update_zeros(&mut self, size: u64) -> Result<(), uapi16_error> { + self.context()?.update_zeros(size); + Ok(()) + } + + /// What uapi16_sha256_finish() does: the hash of all the data. + fn finish(&mut self) -> Result<[u8; Sha256::SIZE], uapi16_error> { + self.process.check()?; + let context = self.context.take().ok_or_else(uapi16_error::ended)?; + Ok(context.finalize().into()) + } +} + +/// The directory the files of a manifest are taken from: the one the +/// manifest is in, or one the caller chose instead. Made by +/// uapi16_directory_new(), and freed by uapi16_directory_free(). +/// +/// The directory is never looked up again, and nothing resolves to +/// anything outside it. Several threads can open files from one directory +/// at the same time. +#[derive(Debug)] +struct uapi16_directory { + /// The directory, of the descriptor the caller lent to + /// uapi16_directory_new(). + directory: Lent, + process: Process, +} + +impl Object for uapi16_directory {} + +impl uapi16_directory { + /// What uapi16_directory_new() does. A bit of `flags` that is no flag + /// fails. The directory has `dir` on loan. + /// + /// # Safety + /// + /// `dir` stays open until the directory this returns is dropped. + unsafe fn new(dir: Descriptor<'_>, flags: uapi16_directory_flags_t) -> Result { + let follow = uapi16_directory_flag_t::UAPI16_DIRECTORY_FOLLOW_SYMLINKS as u64; + if flags & !follow != 0 { + return Err(uapi16_error::misuse()); + } + let pin = |dir| PinnedDirectory::new(dir).follow_symlinks(flags & follow != 0); + // SAFETY: the directory is kept until this is dropped, and the + // descriptor stays open for that long, as the caller says. + let directory = unsafe { dir.lend(pin) }?; + Ok(uapi16_directory { + directory, + process: Process::current(), + }) + } + + /// What uapi16_directory_open_data() does: the file the data of + /// `object` is in, open for reading, and where the data starts in it. + /// Data that is not in a file is none this opens. + fn open_data(&self, object: &uapi16_file_object) -> Result<(OwnedFd, u64), uapi16_error> { + self.process.check()?; + let object = object.file()?; + match object.data_location()? { + DataLocation::External(file) => { + let opened = self.directory.open_data(object, &file)?; + Ok((opened.into(), file.offset())) + } + DataLocation::Literal(_) => { + let in_no_file = uapi16_error::new(uapi16_error_kind_t::UAPI16_ERROR_UNSUPPORTED, libc::EOPNOTSUPP); + Err(in_no_file.about(object.name())) + } + } + } +} + +/// Holds the data of a file object against the size and the hash the +/// object gives, as the data passes. Made by uapi16_data_check_new(), and +/// freed by uapi16_data_check_free(). +#[derive(Debug)] +struct uapi16_data_check { + /// The check, until uapi16_data_check_finish() took it. It has the name + /// of the file object of the caller as its own, and what else it needs + /// of the object, so the caller can change or free the object. + check: Option>, + process: Process, +} + +impl Object for uapi16_data_check {} + +impl uapi16_data_check { + /// What uapi16_data_check_new() does. + fn new(object: &uapi16_file_object) -> Result { + object.process.check()?; + Ok(uapi16_data_check { + check: Some(DataCheck::new(&object.object).into_owned()), + process: Process::current(), + }) + } + + /// The check in the process that made it, unless it is finished: one + /// that is takes nothing more. + fn check(&mut self) -> Result<&mut DataCheck<'static>, uapi16_error> { + self.process.check()?; + self.check.as_mut().ok_or_else(uapi16_error::ended) + } + + /// What uapi16_data_check_update() does. + fn update(&mut self, data: Bytes<'_>) -> Result<(), uapi16_error> { + let data = data.get()?; + self.check()?.update(data)?; + Ok(()) + } + + /// What uapi16_data_check_update_zeros() does. + fn update_zeros(&mut self, size: u64) -> Result<(), uapi16_error> { + self.check()?.update_zeros(size)?; + Ok(()) + } + + /// What uapi16_data_check_finish() does: how many bytes the data is. + /// The check is finished after that, also where it failed. + fn finish(&mut self) -> Result { + self.process.check()?; + let check = self.check.take().ok_or_else(uapi16_error::ended)?; + Ok(check.finish()?) + } +} + +/// Makes options with the default features, the code point order and no +/// syncing. The default features are those of a manifest that lists none: +/// UAPI16_FEATURE_MODE, UAPI16_FEATURE_UID, UAPI16_FEATURE_GID, +/// UAPI16_FEATURE_SIZE, UAPI16_FEATURE_SHA256, UAPI16_FEATURE_SYMLINK, +/// UAPI16_FEATURE_DEVICE and UAPI16_FEATURE_HARDLINK. They are freed with +/// uapi16_manifest_options_free(). +#[no_mangle] +extern "C" fn uapi16_manifest_options_new() -> *mut uapi16_manifest_options { + uapi16_manifest_options::new().into_raw() +} + +/// Sets the features to record to those of the set `s`, and no others. The +/// features of partitions are taken here, and refused when a manifest writer +/// is made. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_manifest_options_set_features( + o: *mut uapi16_manifest_options, + s: *const uapi16_features_t, +) -> c_int { + // SAFETY: by the rules of the caller `s` is NULL or a set that does not + // change during the call. + let features = unsafe { SetWords::new(s) }.and_then(SetWords::features); + // SAFETY: by the rules of the caller `o` is NULL or options that nothing + // else uses during the call. + let options = unsafe { o.as_mut() }; + let set = options + .ok_or_else(uapi16_error::misuse) + .and_then(|options| options.set_features(features?)); + ErrorPlace::NONE.returned(set) +} + +/// Sets the order of the file objects. UAPI16_ORDER_CODEPOINT is the only +/// one. UAPI16_ORDER_NONE is taken too, for a manifest that declares no +/// order, and any other number fails with -EINVAL. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_manifest_options_set_order(o: *mut uapi16_manifest_options, order: OrderNumber) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or options that nothing + // else uses during the call. + let options = unsafe { o.as_mut() }; + let set = match options { + Some(options) => options.set_order(order), + None => Err(uapi16_error::misuse()), + }; + ErrorPlace::NONE.returned(set) +} + +/// Sets whether the new file of uapi16_manifest_writer_create_at() and +/// uapi16_manifest_generate_at() is written to disk before +/// uapi16_manifest_writer_finish() or uapi16_manifest_generate_at() +/// returns, so that a crash after that does not lose it. It is off unless +/// set. +/// +/// The file is synced before it gets its name, so that the name never +/// leads to a manifest that is not all on disk, and once more after it got +/// it, with the directory it is in, so that the name is on disk as well. +/// Nothing else is synced: uapi16_manifest_writer_open() and +/// uapi16_manifest_generate() write to a descriptor of the caller, which +/// the caller syncs. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_manifest_options_set_sync(o: *mut uapi16_manifest_options, sync: bool) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or options that nothing + // else uses during the call. + let options = unsafe { o.as_mut() }; + let set = match options { + Some(options) => options.set_sync(sync), + None => Err(uapi16_error::misuse()), + }; + ErrorPlace::NONE.returned(set) +} + +/// Frees options. NULL is fine. Returns NULL, so that +/// `o = uapi16_manifest_options_free(o);` clears the pointer. A writer +/// that was made with them does not need them any more. +#[no_mangle] +unsafe extern "C" fn uapi16_manifest_options_free(o: *mut uapi16_manifest_options) -> *mut uapi16_manifest_options { + // SAFETY: by the rules of the caller `o` is NULL or options that were + // not freed, and nothing uses them after this call. + unsafe { uapi16_manifest_options::free(o) } +} + +/// Writes the manifest of the directory `top_fd` and everything below it +/// to a new file `name` in the directory `dir_fd`, and stores a report of +/// what it lists in `ret`, unless that is NULL. It is +/// uapi16_manifest_writer_create_at(), a walk of `top_fd` as the root, and +/// uapi16_manifest_writer_finish() in one call. `name` is what +/// uapi16_manifest_writer_create_at() takes, and `flags` is a set of +/// uapi16_add_flag_t. The manifest is sorted, so options whose order is +/// UAPI16_ORDER_NONE fail with -EINVAL. +/// +/// Symbolic links are recorded and never followed. Mount points are not +/// crossed unless UAPI16_ADD_CROSS_MOUNTS is given: one that is a +/// directory is written as an empty directory. The walk mounts nothing: an +/// automount point that nothing is mounted on yet is written as an empty +/// directory with its own attributes, with any flags. There is one known +/// limit. The walk looks at a directory before it opens it, and a +/// directory that becomes an automount point in between has its file +/// system mounted by that open. The walk fails with UAPI16_ERROR_CHANGED +/// then. That takes someone who can mount in the mount namespace of the +/// caller, or an automount unit that is started at that moment. +/// +/// A file that changes while it is read fails with UAPI16_ERROR_CHANGED, +/// where its size, its times or its number of links show the change. +/// +/// Where the features record UAPI16_FEATURE_FLAG_HIDDEN, +/// UAPI16_FEATURE_FLAG_SYSTEM or UAPI16_FEATURE_FLAG_ARCHIVE, a tree on a +/// file system without DOS attributes fails before anything is read. +/// +/// The data of a regular file of more than 1 TiB is not hashed. Where the +/// manifest records hashes, or hard links and the file has more than one +/// name, the walk fails at such a file with UAPI16_ERROR_IO and EFBIG, +/// before anything is read of it. +/// +/// A walk of the directory the new file is in passes over what the +/// manifest keeps there, and over the new file under its temporary name. +/// On a file system without O_TMPFILE, such as FAT, a manifest that is +/// created inside the tree it describes can make the walk of a large tree +/// fail with UAPI16_ERROR_CHANGED, since the room it takes changes its own +/// directory while the walk reads it. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_manifest_generate_at( + o: *const uapi16_manifest_options, + dir_fd: c_int, + name: *const c_char, + top_fd: c_int, + flags: uapi16_add_flags_t, + ret: *mut *mut uapi16_manifest_report, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses during the + // call. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `o` is NULL or options that nothing + // changes during the call. + let options = unsafe { o.as_ref() }; + // SAFETY: by the rules of the caller `dir_fd` and `top_fd` are open + // during the call unless they are negative. + let (dir, top) = unsafe { (Descriptor::new(dir_fd), Descriptor::new(top_fd)) }; + // SAFETY: by the rules of the caller `name` is NULL or a string that + // does not change during the call. + let name = unsafe { Text::new(name) }; + let generated = match options { + Some(options) if reterr.is_clear() => options.generate_at(dir, name, top, flags), + _ => Err(uapi16_error::misuse()), + }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a pointer. + unsafe { uapi16_manifest_report::returned(generated, ret, reterr) } +} + +/// Writes the manifest of the directory `top_fd` and everything below it +/// to the descriptor `fd`, and stores a report of what it lists in `ret`, +/// unless that is NULL. It is uapi16_manifest_writer_open(), a walk of +/// `top_fd` as the root, and uapi16_manifest_writer_finish() in one call. +/// `flags` is a set of uapi16_add_flag_t, and the walk is the one of +/// uapi16_manifest_generate_at(). The manifest is sorted, so options whose +/// order is UAPI16_ORDER_NONE fail with -EINVAL. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_manifest_generate( + o: *const uapi16_manifest_options, + fd: c_int, + top_fd: c_int, + flags: uapi16_add_flags_t, + ret: *mut *mut uapi16_manifest_report, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses during the + // call. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `o` is NULL or options that nothing + // changes during the call. + let options = unsafe { o.as_ref() }; + // SAFETY: by the rules of the caller `fd` and `top_fd` are open during + // the call unless they are negative. + let (fd, top) = unsafe { (Descriptor::new(fd), Descriptor::new(top_fd)) }; + let generated = match options { + Some(options) if reterr.is_clear() => options.generate(fd, top, flags), + _ => Err(uapi16_error::misuse()), + }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a pointer. + unsafe { uapi16_manifest_report::returned(generated, ret, reterr) } +} + +/// Makes a writer for a new manifest file `name` in the directory +/// `dir_fd`, and stores it in `ret`. The file appears when +/// uapi16_manifest_writer_finish() gives it its name, with the whole +/// manifest in it. Until then nothing has the name, and a writer that is +/// freed instead leaves nothing behind. The writer sorts, so options whose +/// order is UAPI16_ORDER_NONE fail with -EINVAL. +/// +/// The writer borrows `dir_fd` until it is freed: the caller keeps it open +/// until then, and closes it itself. +/// +/// `name` is a path, and is taken as the bytes it is, which need not be +/// UTF-8. One with more than one component names a file in a directory +/// below `dir_fd`. The components on the way are opened one at a time, +/// each without following a symbolic link, and the file goes into the +/// directory its last component is in. A symbolic link on the way fails +/// with -ELOOP, and anything else on the way that is no directory with +/// -ENOTDIR. A name that names no file below `dir_fd` fails with -EINVAL +/// before anything is looked up: one that is empty or that ends in a +/// slash, "." or "..", an absolute one, and one with "." or ".." on the +/// way. For a file in a directory that is not below `dir_fd`, open that +/// directory and pass it as `dir_fd`. +/// +/// This never replaces a file: where something has the name already, it +/// fails with UAPI16_ERROR_EXISTS. The name is checked again when the file +/// gets it. To write over a file, open it and use +/// uapi16_manifest_writer_open(). +/// +/// On FAT the new file gets the mode the mount gives every file, and it +/// can't be larger than 4 GiB, so a manifest there holds about 2e7 file +/// objects at most: uapi16_manifest_writer_finish() fails with EFBIG for +/// more. A tree with more than about 9e6 files that have several names +/// fails with EFBIG already while it is added. +/// +/// The manifest of a large tree takes room on disk while it is built, in +/// the directory the file goes to. On a file system without O_TMPFILE, such +/// as FAT, the new file is in that directory under a temporary name until +/// uapi16_manifest_writer_finish(). +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_manifest_writer_create_at( + o: *const uapi16_manifest_options, + dir_fd: c_int, + name: *const c_char, + ret: *mut *mut uapi16_manifest_writer, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses during the + // call. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `o` is NULL or options that nothing + // changes during the call. + let options = unsafe { o.as_ref() }; + // SAFETY: by the rules of the caller `dir_fd` is open during the call + // unless it is negative. + let dir = unsafe { Descriptor::new(dir_fd) }; + // SAFETY: by the rules of the caller `name` is NULL or a string that + // does not change during the call. + let name = unsafe { Text::new(name) }; + // A writer that nobody takes would be dropped, so no place for it is + // no call. Neither is a place for the error that holds something. + let made = match options { + // SAFETY: by the rules of the caller `dir_fd` stays open until the + // writer is freed, which is when it is dropped. + Some(options) if !ret.is_null() && reterr.is_clear() => unsafe { options.create_at(dir, name) }, + _ => Err(uapi16_error::misuse()), + }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a pointer. + unsafe { uapi16_manifest_writer::returned(made, ret, reterr) } +} + +/// Makes a writer for a manifest that is written to the descriptor `fd`, +/// and stores it in `ret`. Nothing is written before +/// uapi16_manifest_writer_finish(), and the manifest is complete once that +/// returns 0. The writer borrows `fd` until it is freed: the caller keeps it +/// open until then, and closes it itself. The writer sorts, so options whose +/// order is UAPI16_ORDER_NONE fail with -EINVAL. +/// +/// The manifest of a large tree takes room on disk while it is built, in +/// the directory TMPDIR names, or in /var/tmp where it names none. Where it +/// is on FAT, which can't hold a file of more than 4 GiB, a manifest of +/// more than about 3e7 file objects fails with EFBIG, and a tree with +/// more than about 9e6 files that have several names fails with EFBIG +/// already while it is added. A TMPDIR that is set is used as it is. It has +/// to be a directory the caller trusts, since whoever controls it can +/// change the manifest. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_manifest_writer_open( + o: *const uapi16_manifest_options, + fd: c_int, + ret: *mut *mut uapi16_manifest_writer, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses during the + // call. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `o` is NULL or options that nothing + // changes during the call. + let options = unsafe { o.as_ref() }; + // SAFETY: by the rules of the caller `fd` is open during the call + // unless it is negative. + let fd = unsafe { Descriptor::new(fd) }; + // A writer that nobody takes would be dropped, so no place for it is + // no call. Neither is a place for the error that holds something. + let made = match options { + // SAFETY: by the rules of the caller `fd` stays open until the + // writer is freed, which is when it is dropped. + Some(options) if !ret.is_null() && reterr.is_clear() => unsafe { options.open(fd) }, + _ => Err(uapi16_error::misuse()), + }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a pointer. + unsafe { uapi16_manifest_writer::returned(made, ret, reterr) } +} + +/// Adds the file object `o`. It is checked as a writer of records checks a +/// file object, but for where it comes, which +/// uapi16_manifest_writer_finish() checks. An object that is refused is not +/// added, and the writer is as it was. The writer keeps a copy: the caller +/// can change the object, add it again under another name, or free it. +/// +/// The objects can come in any order. The object with the empty name is the +/// root, and says what the root directory and its file system are like. A +/// root with a validity, a validity window or a GPT disk UUID, which only a +/// root that a reader read can have, is refused, since this writer writes +/// none of them. uapi16_writer_begin() writes them. The first object of a +/// directory says what the directory is like. Two equal objects of one name +/// are listed once, and two that differ and are not both directories are +/// UAPI16_ERROR_DUPLICATE, from uapi16_manifest_writer_finish(). +/// +/// Objects with the same token are names of one file, and say the same +/// about it. One that does not fails the add with +/// UAPI16_ERROR_HARDLINK_MISMATCH, and uapi16_error_hardlink_path() names the +/// first of them. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_manifest_writer_add_object( + w: *mut uapi16_manifest_writer, + o: *const uapi16_file_object, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `w` is NULL or an object that + // nothing else uses during the call, and `o` is NULL or an object that + // nothing changes during it. + let (writer, object) = unsafe { (w.as_mut(), o.as_ref()) }; + let added = match (writer, object) { + (Some(writer), Some(object)) if reterr.is_clear() => writer.add_object(object), + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(added) +} + +/// Writes the manifest, and stores a report of what it lists in `ret`, +/// unless that is NULL. With uapi16_manifest_writer_create_at() the file +/// gets its name now, unless something took the name since, which is +/// UAPI16_ERROR_EXISTS. Where something fails once the file has its name, +/// such as the sync of its directory, the file keeps the name, and the +/// call fails all the same. +/// +/// What the adds left open fails here: two different files under one +/// name, a directory that was not added where the features need it, a file +/// that is not a directory and that files were added below, and a record +/// that is too large. +/// +/// The writer is finished after this, whether it succeeded or failed. +/// Every later add and finish on it fails with UAPI16_ERROR_ENDED, and +/// uapi16_manifest_writer_free() frees it. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_manifest_writer_finish( + w: *mut uapi16_manifest_writer, + ret: *mut *mut uapi16_manifest_report, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses during the + // call. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `w` is NULL or a writer that + // nothing else uses during the call. + let writer = unsafe { w.as_mut() }; + let finished = match writer { + Some(writer) if reterr.is_clear() => writer.finish(), + _ => Err(uapi16_error::misuse()), + }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a pointer. + unsafe { uapi16_manifest_report::returned(finished, ret, reterr) } +} + +/// Frees a writer. One that was not finished writes nothing and leaves no +/// file behind. NULL is fine. Returns NULL. The descriptor of the caller +/// stays open. +#[no_mangle] +unsafe extern "C" fn uapi16_manifest_writer_free(w: *mut uapi16_manifest_writer) -> *mut uapi16_manifest_writer { + // SAFETY: by the rules of the caller `w` is NULL or a writer that was + // not freed, and nothing uses it after this call. + unsafe { uapi16_manifest_writer::free(w) } +} + +/// How many regular files the manifest lists. 0 for NULL, as for every +/// function of a report. +#[no_mangle] +unsafe extern "C" fn uapi16_manifest_report_files(r: *const uapi16_manifest_report) -> u64 { + // SAFETY: by the rules of the caller `r` is NULL or a report that was + // not freed. + let report = unsafe { r.as_ref() }; + report.map_or(0, |r| r.report.files()) +} + +/// How many directories the manifest lists, the root among them. +#[no_mangle] +unsafe extern "C" fn uapi16_manifest_report_directories(r: *const uapi16_manifest_report) -> u64 { + // SAFETY: by the rules of the caller `r` is NULL or a report that was + // not freed. + let report = unsafe { r.as_ref() }; + report.map_or(0, |r| r.report.directories()) +} + +/// How many other files the manifest lists: symbolic links, FIFOs, device +/// nodes and sockets. +#[no_mangle] +unsafe extern "C" fn uapi16_manifest_report_others(r: *const uapi16_manifest_report) -> u64 { + // SAFETY: by the rules of the caller `r` is NULL or a report that was + // not freed. + let report = unsafe { r.as_ref() }; + report.map_or(0, |r| r.report.others()) +} + +/// The sizes of the regular files, added up. The data of a file with more +/// than one name counts for each. +#[no_mangle] +unsafe extern "C" fn uapi16_manifest_report_bytes(r: *const uapi16_manifest_report) -> u64 { + // SAFETY: by the rules of the caller `r` is NULL or a report that was + // not freed. + let report = unsafe { r.as_ref() }; + report.map_or(0, |r| r.report.bytes()) +} + +/// How many files UAPI16_ADD_GRACEFUL left out, a directory with everything +/// below it as one. +#[no_mangle] +unsafe extern "C" fn uapi16_manifest_report_entries_omitted(r: *const uapi16_manifest_report) -> u64 { + // SAFETY: by the rules of the caller `r` is NULL or a report that was + // not freed. + let report = unsafe { r.as_ref() }; + report.map_or(0, |r| r.report.entries_omitted()) +} + +/// How many fields were left out of the file objects: the names of owners +/// that the user database does not have, the user and group IDs 65535 and +/// 4294967295, modification times before 1970 or after 2554, and the UUID +/// or the volume serial number of a file system that gives none. +#[no_mangle] +unsafe extern "C" fn uapi16_manifest_report_fields_omitted(r: *const uapi16_manifest_report) -> u64 { + // SAFETY: by the rules of the caller `r` is NULL or a report that was + // not freed. + let report = unsafe { r.as_ref() }; + report.map_or(0, |r| r.report.fields_omitted()) +} + +/// Frees a report. NULL is fine. Returns NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_manifest_report_free(r: *mut uapi16_manifest_report) -> *mut uapi16_manifest_report { + // SAFETY: by the rules of the caller `r` is NULL or a report that was + // not freed, and nothing uses it after this call. + unsafe { uapi16_manifest_report::free(r) } +} + +/// Starts to read a manifest from the descriptor `fd`, reads its root, and +/// stores the reader in `ret`. The reader borrows `fd` until it is freed: +/// the caller keeps it open until then, and closes it itself. On a +/// descriptor that does not block, EAGAIN fails the open and loses what it +/// read, so the descriptor has to block, or already hold the root and the +/// start of the next record. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_reader_open( + fd: c_int, + ret: *mut *mut uapi16_reader, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `fd` is one of its descriptors + // unless it is negative. + let fd = unsafe { Descriptor::new(fd) }; + let made = if !ret.is_null() && reterr.is_clear() { + // SAFETY: by the rules of the caller `fd` stays open until the + // reader is freed, which is when it is dropped. + unsafe { uapi16_reader::open(fd) } + } else { + Err(uapi16_error::misuse()) + }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a pointer. + unsafe { uapi16_reader::returned(made, ret, reterr) } +} + +/// The root of the manifest: an object with the empty name. It belongs to +/// the reader and lives until the reader is freed. NULL for NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_reader_root(r: *const uapi16_reader) -> *const uapi16_file_object { + if r.is_null() { + return ptr::null(); + } + // SAFETY: by the rules of the caller `r` is an object, so its root is + // in bounds of it. The pointer comes from `r` itself and not from a + // reference to the reader: the caller keeps it, and the next call that + // changes the reader takes the reader as a whole, which ends every + // pointer that came from an earlier reference to it. + unsafe { &raw const (*r).root } +} + +/// Whether the manifest records the feature `feature`. A manifest that lists +/// no features records the default features. false for a number that is no +/// feature, and for NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_reader_has_feature(r: *const uapi16_reader, feature: FeatureNumber) -> bool { + // SAFETY: by the rules of the caller `r` is NULL or an object that + // nothing changes during the call. + let reader = unsafe { r.as_ref() }; + reader.is_some_and(|reader| reader.reader.root().recorded_features().has_number(feature)) +} + +/// Stores the features the manifest records in `ret`. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_reader_features(r: *const uapi16_reader, ret: *mut uapi16_features_t) -> c_int { + // SAFETY: by the rules of the caller `r` is NULL or an object that + // nothing changes during the call. + let reader = unsafe { r.as_ref() }; + // SAFETY: by the rules of the caller `ret` is NULL or a set that nothing + // else uses during the call. + let ret = unsafe { SetWordsMut::new(ret) }; + let stored = reader.ok_or_else(uapi16_error::misuse).and_then(|reader| { + let mut ret = ret?; + ret.fill(reader.features()?); + Ok(()) + }); + ErrorPlace::NONE.returned(stored) +} + +/// The order the manifest declares, or UAPI16_ORDER_NONE where it declares +/// none. +#[no_mangle] +unsafe extern "C" fn uapi16_reader_order(r: *const uapi16_reader) -> OrderNumber { + // SAFETY: by the rules of the caller `r` is NULL or an object that + // nothing changes during the call. + let reader = unsafe { r.as_ref() }; + let order = reader.map_or(uapi16_order_t::UAPI16_ORDER_NONE, uapi16_reader::order); + order as OrderNumber +} + +/// Requires the manifest to declare the order `order`, as a caller does +/// that relies on it. A manifest that does not fails with +/// UAPI16_ERROR_MANIFEST, even if its file objects are in that order. The +/// reader checks the file objects against the order the manifest declares +/// while it reads them. UAPI16_ORDER_NONE is no order to require, and fails +/// with -EINVAL. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_reader_require_order( + r: *const uapi16_reader, + order: OrderNumber, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `r` is NULL or an object that + // nothing changes during the call. + let reader = unsafe { r.as_ref() }; + let required = match reader { + Some(reader) if reterr.is_clear() => reader.require_order(order), + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(required) +} + +/// Checks that the manifest may be used at the time `now_usec`, in +/// microseconds since 1970: that its root is not revoked and that the time +/// is inside its validity window. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_reader_check_validity( + r: *const uapi16_reader, + now_usec: u64, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `r` is NULL or an object that + // nothing changes during the call. + let reader = unsafe { r.as_ref() }; + let checked = match reader { + Some(reader) if reterr.is_clear() => reader.check_validity(now_usec), + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(checked) +} + +/// Reads on, and returns what it read as a uapi16_read_t, or a negative +/// errno: +/// +/// - UAPI16_READ_FILE: one file object, which is in `*ret`. +/// - UAPI16_READ_SIGNATURES: the file objects have ended, and signature +/// objects follow. The next call passes over them, and checks them. +/// - UAPI16_READ_END: the trailer was read and checked, and the manifest is +/// complete. Every later call returns this again. +/// +/// `ret` points to NULL or to a file object of the caller. Where it points +/// to NULL, a file object that is read is stored there as a new object. +/// Where it points to an object, that object is cleared and filled again, +/// and nothing of what it held before is left: the strings and bytes its +/// getters returned before are gone with it. So one object serves a whole +/// loop, as the buffer of getline() does. A call that reads no file object +/// leaves `*ret` as it is. The object stays the caller's, to free with +/// uapi16_file_object_free(), also after a call that failed. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_reader_next( + r: *mut uapi16_reader, + ret: *mut *mut uapi16_file_object, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `r` is NULL or an object that + // nothing else uses during the call. + let reader = unsafe { r.as_mut() }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the read + // and the write of a pointer, which is NULL or a file object that + // nothing else uses during the call. + let kept = unsafe { Refill::new(ret) }; + let read = match (reader, kept) { + (Some(reader), Some(kept)) if reterr.is_clear() => reader.next(kept), + _ => Err(uapi16_error::misuse()), + }; + reterr.read(read) +} + +/// Reads the next signature object, and returns what it read as a +/// uapi16_read_t, or a negative errno: +/// +/// - UAPI16_READ_SIGNATURE: one signature object, which is in `*ret`. +/// - UAPI16_READ_END: the trailer was read and checked, and the manifest is +/// complete. Every later call returns this again. +/// +/// The signature objects come after the file objects: a call before +/// uapi16_reader_next() returned UAPI16_READ_SIGNATURES or UAPI16_READ_END +/// fails with -EINVAL. `ret` points to NULL or to a signature object of the +/// caller, and is used as uapi16_reader_next() uses its `ret`. The object is +/// freed with uapi16_signature_free(). +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_reader_next_signature( + r: *mut uapi16_reader, + ret: *mut *mut uapi16_signature, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `r` is NULL or an object that + // nothing else uses during the call. + let reader = unsafe { r.as_mut() }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the read + // and the write of a pointer, which is NULL or a signature object that + // nothing else uses during the call. + let kept = unsafe { Refill::new(ret) }; + let read = match (reader, kept) { + (Some(reader), Some(kept)) if reterr.is_clear() => reader.next_signature(kept), + _ => Err(uapi16_error::misuse()), + }; + reterr.read(read) +} + +/// Stores in `ret` how many bytes at the start of the manifest its signature +/// objects sign: all that comes before the record of the first of them, up +/// to its record separator. -ENODATA before uapi16_reader_next() returned +/// UAPI16_READ_SIGNATURES, and so for a manifest without signature objects. +/// +/// The library does not verify signatures. With this number and the +/// signature objects a caller can. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_reader_signed_len(r: *const uapi16_reader, ret: *mut u64) -> c_int { + // SAFETY: by the rules of the caller `r` is NULL or an object that + // nothing changes during the call. + let reader = unsafe { r.as_ref() }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a number. + let ret = unsafe { Place::new(ret) }; + let got = match (reader, ret.needed()) { + (Some(reader), Ok(ret)) => reader.signed_len().map(|len| ret.store(len)), + _ => Err(uapi16_error::misuse()), + }; + ErrorPlace::NONE.returned(got) +} + +/// Frees a reader, and its root with it. NULL is fine. Returns NULL. The +/// descriptor of the caller stays open. +#[no_mangle] +unsafe extern "C" fn uapi16_reader_free(r: *mut uapi16_reader) -> *mut uapi16_reader { + // SAFETY: by the rules of the caller `r` is NULL or an object that + // nothing uses any more. + unsafe { uapi16_reader::free(r) } +} + +/// Starts a manifest on the descriptor `fd` with the root `root`, and stores +/// the writer in `ret`. The features and the order are those of the options +/// `o`, and options with UAPI16_ORDER_NONE make a manifest that declares no +/// order. `root` is an object with the empty name, or NULL for a root that +/// says nothing. The writer borrows `fd` until it is freed: the caller keeps +/// it open until then, and closes it itself. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_writer_begin( + o: *const uapi16_manifest_options, + fd: c_int, + root: *const uapi16_file_object, + ret: *mut *mut uapi16_writer, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `o` and `root` are NULL or objects + // that nothing changes during the call. + let (options, root) = unsafe { (o.as_ref(), root.as_ref()) }; + // SAFETY: by the rules of the caller `fd` is one of its descriptors + // unless it is negative. + let fd = unsafe { Descriptor::new(fd) }; + let made = match options { + // SAFETY: by the rules of the caller `fd` stays open until the + // writer is freed, which is when it is dropped. + Some(options) if !ret.is_null() && reterr.is_clear() => unsafe { uapi16_writer::begin(options, fd, root) }, + _ => Err(uapi16_error::misuse()), + }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a pointer. + unsafe { uapi16_writer::returned(made, ret, reterr) } +} + +/// Writes the file object `o`. The writer checks it as a reader does: it has +/// no field of a feature the manifest does not record, it comes right after +/// the object of its directory, and it keeps to the order. An object that is +/// refused is not written, and the writer goes on as if it had not been +/// given it. +/// +/// In a manifest that declares no order, the order of the names is not +/// checked. A name that comes again right after the entries of the directory +/// it names is still refused. One that comes again later is not found. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_writer_file( + w: *mut uapi16_writer, + o: *const uapi16_file_object, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `w` is NULL or an object that + // nothing else uses during the call, and `o` is NULL or an object that + // nothing changes during it. + let (writer, object) = unsafe { (w.as_mut(), o.as_ref()) }; + let written = match (writer, object) { + (Some(writer), Some(object)) if reterr.is_clear() => writer.file(object), + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(written) +} + +/// Writes the signature object `s`. No file object can follow it: it would +/// be one the signature does not cover. The signature objects of a manifest +/// sign the manifest up to the first of them, which is all that the writer +/// wrote to its descriptor before the first call of this. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_writer_signature( + w: *mut uapi16_writer, + s: *const uapi16_signature, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `w` is NULL or an object that + // nothing else uses during the call, and `s` is NULL or an object that + // nothing changes during it. + let (writer, signature) = unsafe { (w.as_mut(), s.as_ref()) }; + let written = match (writer, signature) { + (Some(writer), Some(signature)) if reterr.is_clear() => writer.signature(signature), + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(written) +} + +/// Ends the manifest with its trailer. The writer is finished after this, +/// whether it succeeded or failed: every later call on it fails with +/// UAPI16_ERROR_ENDED, and uapi16_writer_free() frees it. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_writer_finish(w: *mut uapi16_writer, reterr: *mut *mut uapi16_error) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `w` is NULL or an object that + // nothing else uses during the call. + let writer = unsafe { w.as_mut() }; + let finished = match writer { + Some(writer) if reterr.is_clear() => writer.finish(), + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(finished) +} + +/// Frees a writer of records. NULL is fine. Returns NULL. The descriptor of +/// the caller stays open. +#[no_mangle] +unsafe extern "C" fn uapi16_writer_free(w: *mut uapi16_writer) -> *mut uapi16_writer { + // SAFETY: by the rules of the caller `w` is NULL or an object that + // nothing uses any more. + unsafe { uapi16_writer::free(w) } +} + +/// Makes a signature object of the mechanism `mechanism`, without a key and +/// without data, and stores it in `ret`. The specification has "openpgp" and +/// "pkcs7". +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_signature_new(mechanism: *const c_char, ret: *mut *mut uapi16_signature) -> c_int { + // SAFETY: by the rules of the caller `mechanism` is NULL or a string + // that does not change during the call. + let mechanism = unsafe { Text::new(mechanism) }; + let made = if ret.is_null() { + Err(uapi16_error::misuse()) + } else { + uapi16_signature::new(mechanism) + }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a pointer. + unsafe { uapi16_signature::returned(made, ret, ErrorPlace::NONE) } +} + +/// How the signature was made: its mechanism. NULL for NULL. The string +/// belongs to the object. +#[no_mangle] +unsafe extern "C" fn uapi16_signature_mechanism(s: *const uapi16_signature) -> *const c_char { + // SAFETY: by the rules of the caller `s` is NULL or an object that + // nothing changes during the call. + let signature = unsafe { s.as_ref() }; + signature.map_or(ptr::null(), uapi16_signature::mechanism) +} + +/// Sets what identifies the key, such as its fingerprint: the `size` bytes +/// at `key`. A `key` of NULL takes it away. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_signature_set_key(s: *mut uapi16_signature, key: *const c_void, size: usize) -> c_int { + // SAFETY: by the rules of the caller `s` is NULL or an object that + // nothing else uses during the call. + let signature = unsafe { s.as_mut() }; + // SAFETY: by the rules of the caller `key` is NULL or valid for the + // read of `size` bytes. + let key = unsafe { uapi16_signature::bytes(key, size) }; + let set = signature.ok_or_else(uapi16_error::misuse).and_then(|signature| { + let key = key.map(Bytes::get).transpose()?.map(<[u8]>::to_vec); + signature.signature_mut().map(|signature| signature.set_key(key)) + }); + ErrorPlace::NONE.returned(set) +} + +/// What identifies the key, and its size in `ret_size`, unless that is NULL. +/// No NUL ends the bytes. NULL and 0 where the object has none. The bytes +/// belong to the object. +#[no_mangle] +unsafe extern "C" fn uapi16_signature_key(s: *const uapi16_signature, ret_size: *mut usize) -> *const c_void { + // SAFETY: by the rules of the caller `s` is NULL or an object that + // nothing changes during the call. + let signature = unsafe { s.as_ref() }; + // SAFETY: by the rules of the caller `ret_size` is NULL or valid for + // the write of a size. + let ret_size = unsafe { Place::new(ret_size) }; + uapi16_signature::bytes_out(signature.and_then(|signature| signature.signature.key()), ret_size) +} + +/// Sets the signature: the `size` bytes at `data`. A `data` of NULL takes it +/// away. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_signature_set_data(s: *mut uapi16_signature, data: *const c_void, size: usize) -> c_int { + // SAFETY: by the rules of the caller `s` is NULL or an object that + // nothing else uses during the call. + let signature = unsafe { s.as_mut() }; + // SAFETY: by the rules of the caller `data` is NULL or valid for the + // read of `size` bytes. + let data = unsafe { uapi16_signature::bytes(data, size) }; + let set = signature.ok_or_else(uapi16_error::misuse).and_then(|signature| { + let data = data.map(Bytes::get).transpose()?.map(<[u8]>::to_vec); + signature.signature_mut().map(|signature| signature.set_data(data)) + }); + ErrorPlace::NONE.returned(set) +} + +/// The signature, and its size in `ret_size`, unless that is NULL. No NUL +/// ends the bytes. NULL and 0 where the object has none. The bytes belong to +/// the object. +#[no_mangle] +unsafe extern "C" fn uapi16_signature_data(s: *const uapi16_signature, ret_size: *mut usize) -> *const c_void { + // SAFETY: by the rules of the caller `s` is NULL or an object that + // nothing changes during the call. + let signature = unsafe { s.as_ref() }; + // SAFETY: by the rules of the caller `ret_size` is NULL or valid for + // the write of a size. + let ret_size = unsafe { Place::new(ret_size) }; + uapi16_signature::bytes_out(signature.and_then(|signature| signature.signature.data()), ret_size) +} + +/// Frees a signature object. NULL is fine. Returns NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_signature_free(s: *mut uapi16_signature) -> *mut uapi16_signature { + // SAFETY: by the rules of the caller `s` is NULL or an object that + // nothing uses any more. + unsafe { uapi16_signature::free(s) } +} + +impl uapi16_file_object { + /// What a setter returns that changes the object `o` points to with + /// `set`: 0, or a negative errno. NULL is no object. + /// + /// # Safety + /// + /// `o` is NULL, or an object of a caller that nothing else uses during + /// the call. + unsafe fn change( + o: *mut uapi16_file_object, + set: impl FnOnce(&mut uapi16_file_object) -> Result<(), uapi16_error>, + ) -> c_int { + // SAFETY: `o` is NULL or an object nothing else uses now, as the + // caller says. + let object = unsafe { o.as_mut() }; + ErrorPlace::NONE.returned(object.ok_or_else(uapi16_error::misuse).and_then(set)) + } + + /// What a getter returns that stores in `ret` what `get` reads of the + /// object `o` points to: 0, or a negative errno, for which nothing is + /// stored. NULL is no object, and no place to store anything. + /// + /// # Safety + /// + /// `o` is NULL, or an object of a caller that nothing changes during + /// the call. `ret` is NULL, or valid for the write of a `T`. + unsafe fn read( + o: *const uapi16_file_object, + ret: *mut T, + get: impl FnOnce(&uapi16_file_object) -> Result, + ) -> c_int { + // SAFETY: `o` is NULL or an object nothing changes now, as the + // caller says. + let object = unsafe { o.as_ref() }; + // SAFETY: `ret` is NULL or valid for the write of a `T`, as the + // caller says. + let ret = unsafe { Place::new(ret) }; + let got = match (object, ret.needed()) { + (Some(object), Ok(ret)) => get(object).map(|value| ret.store(value)), + _ => Err(uapi16_error::misuse()), + }; + ErrorPlace::NONE.returned(got) + } +} + +/// Makes a file object for the regular file `name` that says nothing else +/// about it, and stores it in `ret`. `name` is the path of the file below +/// the root of the tree, as a manifest has it: components separated by +/// single slashes, none of them empty, "." or "..". The empty string makes +/// the root. A name that a manifest can't hold fails with +/// UAPI16_ERROR_INVALID_ARGUMENT, and uapi16_error_name_problem() says which +/// rule it breaks. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_new( + name: *const c_char, + ret: *mut *mut uapi16_file_object, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `name` is NULL or a string that + // does not change during the call. + let name = unsafe { Text::new(name) }; + let made = if !ret.is_null() && reterr.is_clear() { + uapi16_file_object::new(name) + } else { + Err(uapi16_error::misuse()) + }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a pointer. + unsafe { uapi16_file_object::returned(made, ret, reterr) } +} + +/// Frees a file object. NULL is fine. Returns NULL. An object of +/// uapi16_reader_root() belongs to its reader and is not freed with this. +#[no_mangle] +unsafe extern "C" fn uapi16_file_object_free(o: *mut uapi16_file_object) -> *mut uapi16_file_object { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing uses any more. + unsafe { uapi16_file_object::free(o) } +} + +/// Gives the object the name `name`, which uapi16_file_object_new() checks +/// the same way. The names of one file carry the same fields: a caller adds +/// the object under one name, sets the next name and adds it again. A name +/// that is refused leaves the object as it was. The root keeps its name, and +/// no other object takes the empty one: both fail with -EINVAL. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_name( + o: *mut uapi16_file_object, + name: *const c_char, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing else uses during the call. + let object = unsafe { o.as_mut() }; + // SAFETY: by the rules of the caller `name` is NULL or a string that + // does not change during the call. + let name = unsafe { Text::new(name) }; + let set = match object { + Some(object) if reterr.is_clear() => object.set_name(name), + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(set) +} + +/// The name of the file: its path below the root. The root is the empty +/// string. NULL for NULL. The string belongs to the object and lives until +/// the name is set again or the object is freed. +#[no_mangle] +unsafe extern "C" fn uapi16_file_object_name(o: *const uapi16_file_object) -> *const c_char { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + object.map_or(ptr::null(), uapi16_file_object::name) +} + +/// Sets the type of the file from an `st_mode` as stat() gives it: S_IFREG, +/// S_IFDIR, S_IFLNK, S_IFIFO, S_IFCHR, S_IFBLK or S_IFSOCK. Only the bits of +/// the file type are read, and bits that are none of these fail with +/// -EINVAL. The root is a directory: S_IFDIR is fine for it, and any other +/// type fails with -EINVAL. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_type(o: *mut uapi16_file_object, st_mode: u32) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.set_type(st_mode)) } +} + +/// The type of the file, as the bits of the file type in an `st_mode`. An +/// object that was given none is a regular file. 0 for NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_file_object_type(o: *const uapi16_file_object) -> u32 { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + object.map_or(0, |object| object.object.inode_type().st_mode()) +} + +/// Sets the access mode from an `st_mode` as stat() gives it: the permission +/// bits with the set-user-ID, the set-group-ID and the sticky bit. The bits +/// of the file type are not read. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_mode(o: *mut uapi16_file_object, st_mode: u32) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.set_mode(st_mode)) } +} + +/// Stores the access mode in `ret`: the permission bits with the +/// set-user-ID, the set-group-ID and the sticky bit, and no bits of a file +/// type. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_mode(o: *const uapi16_file_object, ret: *mut u32) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // changes during the call, and `ret` is NULL or valid + // for the write of what is stored there. + unsafe { + uapi16_file_object::read(o, ret, |object| { + object.inode()?.mode().map(Mode::bits).ok_or_else(uapi16_error::absent) + }) + } +} + +/// Sets the user ID of the owner. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_uid(o: *mut uapi16_file_object, uid: u32) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.inode_mut().map(|inode| inode.set_uid(Some(uid)))) } +} + +/// Stores the user ID of the owner in `ret`. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_uid(o: *const uapi16_file_object, ret: *mut u32) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // changes during the call, and `ret` is NULL or valid + // for the write of what is stored there. + unsafe { uapi16_file_object::read(o, ret, |object| object.inode()?.uid().ok_or_else(uapi16_error::absent)) } +} + +/// Sets the group ID of the owner. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_gid(o: *mut uapi16_file_object, gid: u32) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.inode_mut().map(|inode| inode.set_gid(Some(gid)))) } +} + +/// Stores the group ID of the owner in `ret`. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_gid(o: *const uapi16_file_object, ret: *mut u32) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // changes during the call, and `ret` is NULL or valid + // for the write of what is stored there. + unsafe { uapi16_file_object::read(o, ret, |object| object.inode()?.gid().ok_or_else(uapi16_error::absent)) } +} + +/// Sets the name of the owning user. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_user_name(o: *mut uapi16_file_object, name: *const c_char) -> c_int { + // SAFETY: by the rules of the caller `name` is NULL or a string that + // does not change during the call. + let name = unsafe { Text::new(name) }; + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.set_user_name(name)) } +} + +/// The name of the owning user, or NULL where the object has none. The +/// string belongs to the object. +#[no_mangle] +unsafe extern "C" fn uapi16_file_object_user_name(o: *const uapi16_file_object) -> *const c_char { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + object.map_or(ptr::null(), uapi16_file_object::user_name) +} + +/// Sets the name of the owning group. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_group_name(o: *mut uapi16_file_object, name: *const c_char) -> c_int { + // SAFETY: by the rules of the caller `name` is NULL or a string that + // does not change during the call. + let name = unsafe { Text::new(name) }; + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.set_group_name(name)) } +} + +/// The name of the owning group, or NULL where the object has none. The +/// string belongs to the object. +#[no_mangle] +unsafe extern "C" fn uapi16_file_object_group_name(o: *const uapi16_file_object) -> *const c_char { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + object.map_or(ptr::null(), uapi16_file_object::group_name) +} + +/// Sets the modification time, in nanoseconds since 1970. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_mtime_nsec(o: *mut uapi16_file_object, nsec: u64) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { + uapi16_file_object::change(o, |object| { + object.inode_mut().map(|inode| inode.set_mtime_nsec(Some(nsec))) + }) + } +} + +/// Stores the modification time in `ret`, in nanoseconds since 1970. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_mtime_nsec(o: *const uapi16_file_object, ret: *mut u64) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // changes during the call, and `ret` is NULL or valid + // for the write of what is stored there. + unsafe { + uapi16_file_object::read(o, ret, |object| { + object.inode()?.mtime_nsec().ok_or_else(uapi16_error::absent) + }) + } +} + +/// Sets the size of the data in bytes. For a symbolic link that is the +/// length of its target. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_size(o: *mut uapi16_file_object, size: u64) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.file_mut().map(|file| file.set_size(Some(size)))) } +} + +/// Stores the size of the data in `ret`, in bytes. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_size(o: *const uapi16_file_object, ret: *mut u64) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // changes during the call, and `ret` is NULL or valid + // for the write of what is stored there. + unsafe { uapi16_file_object::read(o, ret, |object| object.file()?.size().ok_or_else(uapi16_error::absent)) } +} + +/// Sets the SHA-256 hash of the data to the one at `sha256`. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_sha256( + o: *mut uapi16_file_object, + sha256: *const uapi16_sha256_digest_t, +) -> c_int { + // SAFETY: by the rules of the caller `sha256` is NULL or valid for the + // read of a hash, which is its bytes. + let sha256 = unsafe { sha256.cast::<[u8; UAPI16_SHA256_SIZE]>().as_ref() }; + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { + uapi16_file_object::change(o, |object| { + let sha256 = Sha256::from(*sha256.ok_or_else(uapi16_error::misuse)?); + object.file_mut().map(|file| file.set_sha256(Some(sha256))) + }) + } +} + +/// Stores the SHA-256 hash of the data in `ret`. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_sha256( + o: *const uapi16_file_object, + ret: *mut uapi16_sha256_digest_t, +) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // changes during the call, and `ret` is NULL or valid + // for the write of what is stored there. + unsafe { + uapi16_file_object::read(o, ret.cast(), |object| { + object + .file()? + .sha256() + .map(<[u8; Sha256::SIZE]>::from) + .ok_or_else(uapi16_error::absent) + }) + } +} + +/// Sets the major number of a device node. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_major(o: *mut uapi16_file_object, major: u64) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.file_mut().map(|file| file.set_major(Some(major)))) } +} + +/// Stores the major number of a device node in `ret`. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_major(o: *const uapi16_file_object, ret: *mut u64) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // changes during the call, and `ret` is NULL or valid + // for the write of what is stored there. + unsafe { uapi16_file_object::read(o, ret, |object| object.file()?.major().ok_or_else(uapi16_error::absent)) } +} + +/// Sets the minor number of a device node. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_minor(o: *mut uapi16_file_object, minor: u64) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.file_mut().map(|file| file.set_minor(Some(minor)))) } +} + +/// Stores the minor number of a device node in `ret`. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_minor(o: *const uapi16_file_object, ret: *mut u64) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // changes during the call, and `ret` is NULL or valid + // for the write of what is stored there. + unsafe { uapi16_file_object::read(o, ret, |object| object.file()?.minor().ok_or_else(uapi16_error::absent)) } +} + +/// Sets the token of the file. The objects that carry the same token are +/// names of one file. Any number but 0 is a token, and +/// UAPI16_INODE_TOKEN_NONE takes the token away. +/// uapi16_manifest_writer_add_object() takes the numbers of the caller as +/// they are and gives the files the numbers the specification asks for. +/// uapi16_writer_file() writes the token as it is, so its caller numbers the +/// files itself: from 1, in the order they first come in the manifest. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_inode_token( + o: *mut uapi16_file_object, + token: uapi16_inode_token_t, +) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.set_inode_token(token)) } +} + +/// Stores the token of the file in `ret`. -ENODATA where the object has +/// none: a file of no other name. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_inode_token( + o: *const uapi16_file_object, + ret: *mut uapi16_inode_token_t, +) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // changes during the call, and `ret` is NULL or valid + // for the write of what is stored there. + unsafe { + uapi16_file_object::read(o, ret, |object| { + let token = object.file()?.inode_token().map(NonZeroU64::get); + token.ok_or_else(uapi16_error::absent) + }) + } +} + +/// Makes the object list its extended attributes of the user namespace, and +/// lists none: the file has none, until uapi16_file_object_add_user_xattr() +/// adds one. An object that does not list them says nothing about them. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_user_xattrs(o: *mut uapi16_file_object) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, uapi16_file_object::set_user_xattrs) } +} + +/// Adds the extended attribute `name` of the user namespace with the `size` +/// bytes at `value` as its value, or gives it that value where the object +/// lists it already. `name` is the name without "user." in front. The object +/// lists its extended attributes after this. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_add_user_xattr( + o: *mut uapi16_file_object, + name: *const c_char, + value: *const c_void, + size: usize, +) -> c_int { + // SAFETY: by the rules of the caller `name` is NULL or a string that + // does not change during the call. + let name = unsafe { Text::new(name) }; + // SAFETY: by the rules of the caller `value` is NULL or valid for the + // read of `size` bytes, unless `size` is 0. + let value = unsafe { Bytes::new(value, size) }; + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.add_user_xattr(name, value)) } +} + +/// Stores in `ret_count` how many extended attributes of the user namespace +/// the object lists. -ENODATA where it says nothing about them. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_user_xattrs(o: *const uapi16_file_object, ret_count: *mut usize) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // changes during the call, and `ret_count` is NULL or valid + // for the write of what is stored there. + unsafe { uapi16_file_object::read(o, ret_count, |object| object.user_xattrs()) } +} + +/// Stores the name, the value and the size of the value of the extended +/// attribute number `i`, counting from 0 in the order of the names. The name +/// comes without "user." in front, and no NUL ends the value. Each of the +/// three can be NULL. An `i` that is not below the count of +/// uapi16_file_object_user_xattrs() fails with -EINVAL. The name and the +/// value belong to the object and live until it is changed or freed. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_user_xattr( + o: *const uapi16_file_object, + i: usize, + ret_name: *mut *const c_char, + ret_value: *mut *const c_void, + ret_size: *mut usize, +) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + // SAFETY: by the rules of the caller each of the three is NULL or valid + // for the write of what is stored there. + let (ret_name, ret_value, ret_size) = + unsafe { (Place::new(ret_name), Place::new(ret_value), Place::new(ret_size)) }; + let got = object + .ok_or_else(uapi16_error::misuse) + .and_then(|object| object.user_xattr(i)); + ErrorPlace::NONE.returned(got.map(|(name, value, size)| { + ret_name.store(name); + ret_value.store(value); + ret_size.store(size); + })) +} + +/// Sets whether the file is read-only: UAPI16_READ_ONLY_YES or +/// UAPI16_READ_ONLY_NO. UAPI16_READ_ONLY_UNSTATED takes the field away. Any +/// other number fails with -EINVAL. The field stands for the read-only +/// attribute of DOS too. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_read_only(o: *mut uapi16_file_object, read_only: ReadOnlyNumber) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.set_read_only(read_only)) } +} + +/// Whether the file is read-only. UAPI16_READ_ONLY_UNSTATED where the object +/// does not say, and for NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_file_object_read_only(o: *const uapi16_file_object) -> ReadOnlyNumber { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + let read_only = object.and_then(|object| object.object.inode().read_only()); + uapi16_read_only_t::of(read_only) as ReadOnlyNumber +} + +/// Sets the Linux inode flags, as the bits FS_IOC_GETFLAGS gives. `stated` +/// has the flags the object says something about, and `set` those of them +/// that are set. A manifest has FS_APPEND_FL, FS_IMMUTABLE_FL, FS_NOATIME_FL, +/// FS_NOCOW_FL and FS_NODUMP_FL. Other bits are not read. A flag that is not +/// in `stated` is taken away from the object. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_inode_flags(o: *mut uapi16_file_object, stated: u32, set: u32) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.set_inode_flags(stated, set)) } +} + +/// Stores the Linux inode flags the object says something about in +/// `ret_stated`, and those of them that are set in `ret_set`, as the bits +/// FS_IOC_GETFLAGS gives. Either can be NULL. An object that says nothing +/// about any flag stores 0 in both. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_inode_flags( + o: *const uapi16_file_object, + ret_stated: *mut u32, + ret_set: *mut u32, +) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + // SAFETY: by the rules of the caller each of the two is NULL or valid + // for the write of what is stored there. + let (ret_stated, ret_set) = unsafe { (Place::new(ret_stated), Place::new(ret_set)) }; + let got = object + .ok_or_else(uapi16_error::misuse) + .and_then(uapi16_file_object::inode_flags); + ErrorPlace::NONE.returned(got.map(|(stated, set)| { + ret_stated.store(stated); + ret_set.store(set); + })) +} + +/// Sets the DOS attributes hidden, system and archive, as the bits a +/// directory entry of FAT has: 0x02, 0x04 and 0x20. `stated` has the +/// attributes the object says something about, and `set` those of them that +/// are set. Other bits are not read. An attribute that is not in `stated` is +/// taken away from the object. The read-only attribute is +/// uapi16_file_object_set_read_only(). +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_dos_attributes(o: *mut uapi16_file_object, stated: u32, set: u32) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.set_dos_attributes(stated, set)) } +} + +/// Stores the DOS attributes the object says something about in +/// `ret_stated`, and those of them that are set in `ret_set`, as the bits a +/// directory entry of FAT has. Either can be NULL. An object that says +/// nothing about any of them stores 0 in both. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_dos_attributes( + o: *const uapi16_file_object, + ret_stated: *mut u32, + ret_set: *mut u32, +) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + // SAFETY: by the rules of the caller each of the two is NULL or valid + // for the write of what is stored there. + let (ret_stated, ret_set) = unsafe { (Place::new(ret_stated), Place::new(ret_set)) }; + let got = object + .ok_or_else(uapi16_error::misuse) + .and_then(uapi16_file_object::dos_attributes); + ErrorPlace::NONE.returned(got.map(|(stated, set)| { + ret_stated.store(stated); + ret_set.store(set); + })) +} + +/// Sets the target of a symbolic link: the `size` bytes at `target`, which +/// need not be UTF-8 and which no NUL ends. The manifest carries the target +/// itself. On a regular file they are the data of the file, which the +/// manifest carries the same way. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_target( + o: *mut uapi16_file_object, + target: *const c_void, + size: usize, +) -> c_int { + // SAFETY: by the rules of the caller `target` is NULL or valid for the + // read of `size` bytes, unless `size` is 0. + let target = unsafe { Bytes::new(target, size) }; + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.set_target(target)) } +} + +/// Says that the data of the file is in the file `file` next to the +/// manifest, under another name than its own. `file` is a name as +/// uapi16_file_object_new() takes one, but for the empty one. A name that is +/// none fails as it does there. Without this, the data of a regular file is +/// in the file of its own name next to the manifest. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_contents_file( + o: *mut uapi16_file_object, + file: *const c_char, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing else uses during the call. + let object = unsafe { o.as_mut() }; + // SAFETY: by the rules of the caller `file` is NULL or a string that + // does not change during the call. + let file = unsafe { Text::new(file) }; + let set = match object { + Some(object) if reterr.is_clear() => object.set_contents_file(file), + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(set) +} + +/// The file the data of `o` is in, where that is another file than the one +/// of its own name, and where the data starts in it. -ENODATA where the +/// object names no such file. Both `ret_file` and `ret_offset` are needed: a +/// NULL one fails with -EINVAL. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_contents_file( + o: *const uapi16_file_object, + ret_file: *mut *const c_char, + ret_offset: *mut u64, +) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + // SAFETY: by the rules of the caller `ret_file` and `ret_offset` are + // NULL or valid for the write of a pointer and of a number. + let (ret_file, ret_offset) = unsafe { (Place::new(ret_file), Place::new(ret_offset)) }; + let read = match (object, ret_file.needed(), ret_offset.needed()) { + (Some(object), Ok(ret_file), Ok(ret_offset)) => object.contents_file().map(|(file, offset)| { + ret_file.store(file); + ret_offset.store(offset); + }), + _ => Err(uapi16_error::misuse()), + }; + ErrorPlace::NONE.returned(read) +} + +/// Where the data of the file is: the bytes of a regular file or the target +/// of a symbolic link. A literal is taken first. Otherwise the data is in +/// the file next to the manifest that the object refers to, or in the file +/// of its own name where it is a regular file and refers to none. +/// UAPI16_DATA_LOCATION_NONE for an object without data, and for NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_file_object_data_location(o: *const uapi16_file_object) -> DataLocationNumber { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + let none = uapi16_data_location_t::UAPI16_DATA_LOCATION_NONE; + object.map_or(none, uapi16_file_object::data_location) as DataLocationNumber +} + +/// The data of the file where the manifest carries it itself, such as the +/// target of a symbolic link, and its size in `ret_size`, unless that is +/// NULL. Where the object gives a size, the data is that many bytes. No NUL +/// ends the bytes. NULL and 0 where the data is not in the manifest. The +/// bytes belong to the object. +#[no_mangle] +unsafe extern "C" fn uapi16_file_object_literal(o: *const uapi16_file_object, ret_size: *mut usize) -> *const c_void { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + // SAFETY: by the rules of the caller `ret_size` is NULL or valid for + // the write of a size. + let ret_size = unsafe { Place::new(ret_size) }; + let literal = object.and_then(uapi16_file_object::literal); + ret_size.store(literal.map_or(0, <[u8]>::len)); + literal.map_or(ptr::null(), |literal| literal.as_ptr().cast()) +} + +/// Sets the label of the file system. Only the root has one. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_fs_label(o: *mut uapi16_file_object, label: *const c_char) -> c_int { + // SAFETY: by the rules of the caller `label` is NULL or a string that + // does not change during the call. + let label = unsafe { Text::new(label) }; + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.set_fs_label(label)) } +} + +/// The label of the file system, or NULL where the object has none. The +/// string belongs to the object. +#[no_mangle] +unsafe extern "C" fn uapi16_file_object_fs_label(o: *const uapi16_file_object) -> *const c_char { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + object.map_or(ptr::null(), uapi16_file_object::fs_label) +} + +/// Sets the UUID of the file system to the one at `uuid`. Only the root has +/// one. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_fs_uuid(o: *mut uapi16_file_object, uuid: *const uapi16_uuid_t) -> c_int { + // SAFETY: by the rules of the caller `uuid` is NULL or valid for the + // read of a UUID, which is its bytes. + let uuid = unsafe { uuid.cast::<[u8; UAPI16_UUID_SIZE]>().as_ref() }; + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { + uapi16_file_object::change(o, |object| { + let uuid = Uuid::new(*uuid.ok_or_else(uapi16_error::misuse)?); + object + .file_system_mut() + .map(|file_system| file_system.set_uuid(Some(uuid))) + }) + } +} + +/// Stores the UUID of the file system in `ret`. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_fs_uuid(o: *const uapi16_file_object, ret: *mut uapi16_uuid_t) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // changes during the call, and `ret` is NULL or valid + // for the write of what is stored there. + unsafe { + uapi16_file_object::read(o, ret.cast(), |object| { + object + .file_system()? + .uuid() + .map(|uuid| *uuid.as_bytes()) + .ok_or_else(uapi16_error::absent) + }) + } +} + +/// Sets the volume serial number of a FAT or exFAT file system. Only the +/// root has one. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_set_fat_serial(o: *mut uapi16_file_object, serial: u32) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { + uapi16_file_object::change(o, |object| { + object + .file_system_mut() + .map(|file_system| file_system.set_fat_serial(Some(FatSerial::new(serial)))) + }) + } +} + +/// Stores the volume serial number of a FAT or exFAT file system in `ret`. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_fat_serial(o: *const uapi16_file_object, ret: *mut u32) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // changes during the call, and `ret` is NULL or valid + // for the write of what is stored there. + unsafe { + uapi16_file_object::read(o, ret, |object| { + object + .file_system()? + .fat_serial() + .map(FatSerial::get) + .ok_or_else(uapi16_error::absent) + }) + } +} + +/// Whether the object has the fields of the feature `feature`. A manifest +/// records every such feature, or the object is not one of its file objects. +/// What a reader filled in does not count. false for a number that is no +/// feature, and for NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_file_object_has_stated_feature( + o: *const uapi16_file_object, + feature: FeatureNumber, +) -> bool { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + object.is_some_and(|object| object.stated_features().has_number(feature)) +} + +/// Stores the features whose fields the object has in `ret`, as +/// uapi16_file_object_has_stated_feature() counts them. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_stated_features( + o: *const uapi16_file_object, + ret: *mut uapi16_features_t, +) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + // SAFETY: by the rules of the caller `ret` is NULL or a set that nothing + // else uses during the call. + let ret = unsafe { SetWordsMut::new(ret) }; + let stored = object.ok_or_else(uapi16_error::misuse).and_then(|object| { + let mut ret = ret?; + object.process.check()?; + ret.fill(object.stated_features()); + Ok(()) + }); + ErrorPlace::NONE.returned(stored) +} + +/// Takes away the fields of every feature that is not in the set `s`. So a +/// caller sets all it knows of a file and keeps what its manifest records. +/// The name, the type and what belongs to no feature stay. The target of a +/// symbolic link goes without UAPI16_FEATURE_SYMLINK. The data a manifest +/// carries of a regular file and the file its data is in belong to no +/// feature, and stay. An object whose data starts at an offset in a file +/// reaches to the end of it once its size goes, and a hash that stays no +/// longer fits. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_retain_features( + o: *mut uapi16_file_object, + s: *const uapi16_features_t, +) -> c_int { + // SAFETY: by the rules of the caller `s` is NULL or a set that does not + // change during the call. + let features = unsafe { SetWords::new(s) }.and_then(SetWords::features); + // SAFETY: by the rules of the caller `o` is NULL or an object that nothing + // else uses during the call. + unsafe { uapi16_file_object::change(o, |object| object.retain_features(features?)) } +} + +/// Checks that the object may be used at the time `now_usec`, in +/// microseconds since 1970: that it is not revoked and that the time is +/// inside its validity window. The check looks at the object alone. A caller +/// that uses a file checks the objects of the directories it is in as well, +/// which come before it in the manifest. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_file_object_check_validity( + o: *const uapi16_file_object, + now_usec: u64, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + let checked = match object { + Some(object) if reterr.is_clear() => object.check_validity(now_usec), + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(checked) +} + +/// Makes a directory from the descriptor `dir_fd`, which may be opened with +/// O_PATH, and stores it in `ret`. `flags` is a set of +/// uapi16_directory_flag_t. The directory borrows `dir_fd` until it is +/// freed: the caller keeps it open until then, and closes it itself. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_directory_new( + dir_fd: c_int, + flags: uapi16_directory_flags_t, + ret: *mut *mut uapi16_directory, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `dir_fd` is one of its descriptors + // unless it is negative. + let dir = unsafe { Descriptor::new(dir_fd) }; + let made = if !ret.is_null() && reterr.is_clear() { + // SAFETY: by the rules of the caller `dir_fd` stays open until the + // directory is freed, which is when it is dropped. + unsafe { uapi16_directory::new(dir, flags) } + } else { + Err(uapi16_error::misuse()) + }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a pointer. + unsafe { uapi16_directory::returned(made, ret, reterr) } +} + +/// Opens the file the data of `o` is in, for reading, and stores a new +/// descriptor in `ret_fd`, which the caller closes. The descriptor is open +/// for reading, and blocks as a regular file does. Where the data starts in +/// the file is stored in `ret_offset`. Both `ret_fd` and `ret_offset` are +/// needed: a NULL one fails with -EINVAL. The data is as long as the object +/// says, or reaches to the end of the file where the object gives no size. +/// +/// The file is a regular file. One that is not there fails with +/// UAPI16_ERROR_SOURCE_MISSING, one that is no regular file with +/// UAPI16_ERROR_SOURCE_NOT_REGULAR, one that can't be opened with +/// UAPI16_ERROR_IO and the errno of the system call, such as ELOOP for a +/// symbolic link on the way, and one that is too short for the data, or of +/// another size than the manifest gives for the file, with +/// UAPI16_ERROR_SIZE_MISMATCH. An object whose data is not in a file, see +/// uapi16_file_object_data_location(), fails with UAPI16_ERROR_UNSUPPORTED. +/// +/// The caller checks what it reads with a uapi16_data_check. A file can hold +/// the data of several file objects. Where the manifest gives a hash for +/// the whole file and none for the object, the data of the object is not +/// checked against it. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_directory_open_data( + d: *const uapi16_directory, + o: *const uapi16_file_object, + ret_fd: *mut c_int, + ret_offset: *mut u64, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `d` and `o` are NULL or objects + // that nothing changes during the call. + let (directory, object) = unsafe { (d.as_ref(), o.as_ref()) }; + // SAFETY: by the rules of the caller `ret_fd` and `ret_offset` are NULL + // or valid for the write of a number. + let (ret_fd, ret_offset) = unsafe { (Place::new(ret_fd), Place::new(ret_offset)) }; + // A descriptor that nobody takes would stay open, and data read from + // the wrong place is other data, so both places are needed. + let opened = match (directory, object, ret_fd.needed(), ret_offset.needed()) { + (Some(directory), Some(object), Ok(ret_fd), Ok(ret_offset)) if reterr.is_clear() => { + directory.open_data(object).map(|(file, offset)| { + // The descriptor is the caller's from here on. + ret_fd.store(file.into_raw_fd()); + ret_offset.store(offset); + }) + } + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(opened) +} + +/// Frees a directory. NULL is fine. Returns NULL. The descriptor of the +/// caller stays open, and so do those that uapi16_directory_open_data() +/// stored. +#[no_mangle] +unsafe extern "C" fn uapi16_directory_free(d: *mut uapi16_directory) -> *mut uapi16_directory { + // SAFETY: by the rules of the caller `d` is NULL or an object that + // nothing uses any more. + unsafe { uapi16_directory::free(d) } +} + +/// Makes a check of the data of `o`, of which nothing has passed yet, and +/// stores it in `ret`. The check keeps what it needs of the object, which +/// can be changed or freed after the call. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_data_check_new(o: *const uapi16_file_object, ret: *mut *mut uapi16_data_check) -> c_int { + // SAFETY: by the rules of the caller `o` is NULL or an object that + // nothing changes during the call. + let object = unsafe { o.as_ref() }; + let made = match object { + Some(object) if !ret.is_null() => uapi16_data_check::new(object), + _ => Err(uapi16_error::misuse()), + }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a pointer. + unsafe { uapi16_data_check::returned(made, ret, ErrorPlace::NONE) } +} + +/// Takes the `size` bytes at `data` as the next bytes of the data. Fails +/// with UAPI16_ERROR_SIZE_MISMATCH, and takes none of them, where they +/// would make the data larger than the size the object gives. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_data_check_update( + c: *mut uapi16_data_check, + data: *const c_void, + size: usize, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `c` is NULL or an object that + // nothing else uses during the call. + let check = unsafe { c.as_mut() }; + // SAFETY: by the rules of the caller `data` is NULL or valid for the + // read of `size` bytes, unless `size` is 0. + let data = unsafe { Bytes::new(data, size) }; + let updated = match check { + Some(check) if reterr.is_clear() => check.update(data), + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(updated) +} + +/// Takes `size` zero bytes as the next bytes of the data, such as a hole of +/// a sparse file that the caller did not read. Fails as +/// uapi16_data_check_update() does. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_data_check_update_zeros( + c: *mut uapi16_data_check, + size: u64, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `c` is NULL or an object that + // nothing else uses during the call. + let check = unsafe { c.as_mut() }; + let updated = match check { + Some(check) if reterr.is_clear() => check.update_zeros(size), + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(updated) +} + +/// Checks the data that passed against the size and the hash the object +/// gives, and stores how many bytes it is in `ret_size`, unless that is +/// NULL. Data of another size fails with UAPI16_ERROR_SIZE_MISMATCH, and +/// data with another hash with UAPI16_ERROR_HASH_MISMATCH. Every later call +/// on the check but uapi16_data_check_free() fails with -ESTALE. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_data_check_finish( + c: *mut uapi16_data_check, + ret_size: *mut u64, + reterr: *mut *mut uapi16_error, +) -> c_int { + // SAFETY: by the rules of the caller `reterr` is NULL or valid for the + // read and the write of a pointer that nothing else uses now. + let reterr = unsafe { ErrorPlace::new(reterr) }; + // SAFETY: by the rules of the caller `c` is NULL or an object that + // nothing else uses during the call. + let check = unsafe { c.as_mut() }; + // SAFETY: by the rules of the caller `ret_size` is NULL or valid for + // the write of a size. + let ret_size = unsafe { Place::new(ret_size) }; + let finished = match check { + Some(check) if reterr.is_clear() => check.finish().map(|size| ret_size.store(size)), + _ => Err(uapi16_error::misuse()), + }; + reterr.returned(finished) +} + +/// Frees a check. NULL is fine. Returns NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_data_check_free(c: *mut uapi16_data_check) -> *mut uapi16_data_check { + // SAFETY: by the rules of the caller `c` is NULL or an object that + // nothing uses any more. + unsafe { uapi16_data_check::free(c) } +} + +/// Makes a computation that has taken no data yet. It is freed with +/// uapi16_sha256_free(). +#[no_mangle] +extern "C" fn uapi16_sha256_new() -> *mut uapi16_sha256 { + uapi16_sha256::new().into_raw() +} + +/// Takes the `size` bytes at `data` as more of the data. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_sha256_update(s: *mut uapi16_sha256, data: *const c_void, size: usize) -> c_int { + // SAFETY: by the rules of the caller `s` is NULL or an object that + // nothing else uses during the call. + let sha256 = unsafe { s.as_mut() }; + // SAFETY: by the rules of the caller `data` is NULL or valid for the + // read of `size` bytes, unless `size` is 0. + let data = unsafe { Bytes::new(data, size) }; + let updated = sha256 + .ok_or_else(uapi16_error::misuse) + .and_then(|sha256| sha256.update(data)); + ErrorPlace::NONE.returned(updated) +} + +/// Takes `size` zero bytes as more of the data, such as a hole of a sparse +/// file that the caller did not read. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_sha256_update_zeros(s: *mut uapi16_sha256, size: u64) -> c_int { + // SAFETY: by the rules of the caller `s` is NULL or an object that + // nothing else uses during the call. + let sha256 = unsafe { s.as_mut() }; + let updated = sha256 + .ok_or_else(uapi16_error::misuse) + .and_then(|sha256| sha256.update_zeros(size)); + ErrorPlace::NONE.returned(updated) +} + +/// Ends the computation and stores the hash of all the data in `ret`. Every +/// later call on it but uapi16_sha256_free() fails with -ESTALE. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_sha256_finish(s: *mut uapi16_sha256, ret: *mut uapi16_sha256_digest_t) -> c_int { + // SAFETY: by the rules of the caller `s` is NULL or an object that + // nothing else uses during the call. + let sha256 = unsafe { s.as_mut() }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a hash, which is its bytes. + let ret = unsafe { Place::new(ret.cast::<[u8; UAPI16_SHA256_SIZE]>()) }; + let finished = match (sha256, ret.needed()) { + (Some(sha256), Ok(ret)) => sha256.finish().map(|hash| ret.store(hash)), + _ => Err(uapi16_error::misuse()), + }; + ErrorPlace::NONE.returned(finished) +} + +/// Frees a computation. NULL is fine. Returns NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_sha256_free(s: *mut uapi16_sha256) -> *mut uapi16_sha256 { + // SAFETY: by the rules of the caller `s` is NULL or an object that + // nothing uses any more. + unsafe { uapi16_sha256::free(s) } +} + +/// Compares two names the way a manifest in code point order lists its file +/// objects: component by component, each by its bytes, so that the name of +/// a directory comes right before the names below it. Returns one of +/// uapi16_name_order_t as an int: UAPI16_NAME_BEFORE where `a` comes before +/// `b`, UAPI16_NAME_SAME where they are the same, and UAPI16_NAME_AFTER +/// where `a` comes after `b`. A comparison function of qsort() returns that +/// as it is. This is not the order of strcmp(): "a/x" comes before "a-b". +/// NULL is the empty name, which comes first. Strings that are not UTF-8 are +/// no names, and they compare after the replacement. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_name_compare(a: *const c_char, b: *const c_char) -> c_int { + // SAFETY: by the rules of the caller `a` and `b` are NULL or strings + // that do not change during the call. + let (a, b) = unsafe { (Text::new(a), Text::new(b)) }; + // A string that is not UTF-8 is no name. Its bytes that are none are + // taken as the replacement character, so that every two strings have an + // order. + let (a, b) = (a.lossy(), b.lossy()); + // The three numbers of uapi16_name_order_t are small. + uapi16_name_order_t::of(NamePair::new(&a, &b).ordering()) as c_int +} + +/// Adds the feature `feature` to the set `s`. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_features_add(s: *mut uapi16_features_t, feature: FeatureNumber) -> c_int { + // SAFETY: by the rules of the caller `s` is NULL or a set that nothing + // else uses during the call. + let set = unsafe { SetWordsMut::new(s) }; + ErrorPlace::NONE.returned(set.and_then(|mut set| set.change(feature, true))) +} + +/// Takes the feature `feature` out of the set `s`. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_features_remove(s: *mut uapi16_features_t, feature: FeatureNumber) -> c_int { + // SAFETY: by the rules of the caller `s` is NULL or a set that nothing + // else uses during the call. + let set = unsafe { SetWordsMut::new(s) }; + ErrorPlace::NONE.returned(set.and_then(|mut set| set.change(feature, false))) +} + +/// Whether the feature `feature` is in the set `s`. false for NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_features_has(s: *const uapi16_features_t, feature: FeatureNumber) -> bool { + // SAFETY: by the rules of the caller `s` is NULL or a set that does not + // change during the call. + let set = unsafe { SetWords::new(s) }; + set.is_ok_and(|set| set.has(feature)) +} + +/// The lowest feature of the set `s` above `after`. UAPI16_FEATURE_NONE as +/// `after` gives the first one, and UAPI16_FEATURE_NONE comes back after the +/// last one, and for NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_features_next(s: *const uapi16_features_t, after: FeatureNumber) -> FeatureNumber { + // SAFETY: by the rules of the caller `s` is NULL or a set that does not + // change during the call. + let set = unsafe { SetWords::new(s) }; + set.map_or(uapi16_feature_t::UAPI16_FEATURE_NONE as FeatureNumber, |set| { + set.next(after) + }) +} + +/// Adds the features of the set `other` to the set `s`. +#[no_mangle] +unsafe extern "C" fn uapi16_features_union(s: *mut uapi16_features_t, other: *const uapi16_features_t) { + // SAFETY: by the rules of the caller each of the two is NULL or a set, + // `s` is one that nothing else uses during the call and `other` does not + // change during it but through `s`, which it can be. + let (set, other) = unsafe { (SetWordsMut::new(s), SetWords::new(other)) }; + if let (Ok(mut set), Ok(other)) = (set, other) { + set.combine(other, |own, theirs| own | theirs); + } +} + +/// Keeps the features of the set `s` that the set `other` has as well. +#[no_mangle] +unsafe extern "C" fn uapi16_features_intersect(s: *mut uapi16_features_t, other: *const uapi16_features_t) { + // SAFETY: as in uapi16_features_union(). + let (set, other) = unsafe { (SetWordsMut::new(s), SetWords::new(other)) }; + if let (Ok(mut set), Ok(other)) = (set, other) { + set.combine(other, |own, theirs| own & theirs); + } +} + +/// Takes the features of the set `other` out of the set `s`. +#[no_mangle] +unsafe extern "C" fn uapi16_features_subtract(s: *mut uapi16_features_t, other: *const uapi16_features_t) { + // SAFETY: as in uapi16_features_union(). + let (set, other) = unsafe { (SetWordsMut::new(s), SetWords::new(other)) }; + if let (Ok(mut set), Ok(other)) = (set, other) { + set.combine(other, |own, theirs| own & !theirs); + } +} + +/// Whether the sets `a` and `b` have the same features. false for NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_features_equal(a: *const uapi16_features_t, b: *const uapi16_features_t) -> bool { + // SAFETY: by the rules of the caller each of the two is NULL or a set + // that does not change during the call. + let (a, b) = unsafe { (SetWords::new(a), SetWords::new(b)) }; + matches!((a, b), (Ok(a), Ok(b)) if a.equals(b)) +} + +/// The name the specification has for the feature `feature`, such as +/// "user-xattr" for UAPI16_FEATURE_USER_XATTR. NULL for a number that is not +/// one feature of this library. The string is a constant of the library. +#[no_mangle] +extern "C" fn uapi16_feature_name(feature: FeatureNumber) -> *const c_char { + uapi16_feature_t::name_of(feature).map_or(ptr::null(), CStr::as_ptr) +} + +/// The feature with the name `name`, as the specification spells it. +/// UAPI16_FEATURE_NONE for a name that no feature has, and for NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_feature_from_name(name: *const c_char) -> FeatureNumber { + // SAFETY: by the rules of the caller `name` is NULL or a string that + // does not change during the call. + let name = unsafe { Text::new(name) }; + let name = name.get().ok().and_then(|name| name.to_str().ok()); + let feature = name.and_then(|name| name.parse::().ok()); + let feature = feature.and_then(uapi16_feature_t::of); + feature.unwrap_or(uapi16_feature_t::UAPI16_FEATURE_NONE) as FeatureNumber +} + +/// Stores the default features in `ret`: those of a manifest that lists +/// none, and those of new options. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_features_default(ret: *mut uapi16_features_t) -> c_int { + // SAFETY: by the rules of the caller `ret` is NULL or a set that nothing + // else uses during the call. + let ret = unsafe { SetWordsMut::new(ret) }; + ErrorPlace::NONE.returned(ret.map(|mut ret| ret.fill(Features::DEFAULT))) +} + +/// Stores every feature this library has in `ret`. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_features_known(ret: *mut uapi16_features_t) -> c_int { + // SAFETY: by the rules of the caller `ret` is NULL or a set that nothing + // else uses during the call. + let ret = unsafe { SetWordsMut::new(ret) }; + ErrorPlace::NONE.returned(ret.map(|mut ret| ret.fill(Features::ALL))) +} + +/// What kind of error this is. 0 for NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_error_kind(e: *const uapi16_error) -> ErrorKindNumber { + // SAFETY: by the rules of the caller `e` is NULL or an error that was + // not freed. + let error = unsafe { e.as_ref() }; + error.map_or(0, |e| e.kind as u64) +} + +/// The errno of the error, a positive number as errno has it. The call +/// that failed returned it negated. 0 for NULL. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_error_errno(e: *const uapi16_error) -> c_int { + // SAFETY: by the rules of the caller `e` is NULL or an error that was + // not freed. + let error = unsafe { e.as_ref() }; + error.map_or(0, |e| e.errno) +} + +/// The name of the file the error is about, as the manifest has it, or +/// NULL if the error is about no file. The root of the tree is the empty +/// string. For a name a manifest can't hold, it is the name of the +/// directory the file is in. The string belongs to the error. +#[no_mangle] +unsafe extern "C" fn uapi16_error_path(e: *const uapi16_error) -> *const c_char { + // SAFETY: by the rules of the caller `e` is NULL or an error that was + // not freed. + let error = unsafe { e.as_ref() }; + let path = error.and_then(|e| e.path.as_deref()); + path.map_or(ptr::null(), CStr::as_ptr) +} + +/// For UAPI16_ERROR_HARDLINK_MISMATCH, the other name of the inode, which +/// the file of uapi16_error_path() was compared with. NULL for any other +/// error. The string belongs to the error. +#[no_mangle] +unsafe extern "C" fn uapi16_error_hardlink_path(e: *const uapi16_error) -> *const c_char { + // SAFETY: by the rules of the caller `e` is NULL or an error that was + // not freed. + let error = unsafe { e.as_ref() }; + let path = error.and_then(|e| e.hardlink_path.as_deref()); + path.map_or(ptr::null(), CStr::as_ptr) +} + +/// The feature the error is about: for UAPI16_ERROR_UNSUPPORTED the one +/// that can't be read, and for a feature of partitions that feature. +/// UAPI16_FEATURE_NONE if the error is about no feature. +#[no_mangle] +unsafe extern "C" fn uapi16_error_feature(e: *const uapi16_error) -> FeatureNumber { + // SAFETY: by the rules of the caller `e` is NULL or an error that was + // not freed. + let error = unsafe { e.as_ref() }; + let feature = error.and_then(|e| e.feature); + feature.unwrap_or(uapi16_feature_t::UAPI16_FEATURE_NONE) as FeatureNumber +} + +/// For UAPI16_ERROR_UNWRITABLE_NAME, the name of the file as its directory +/// has it: one component. Its bytes need not be UTF-8, and no NUL ends +/// them. How many there are is stored in `ret_size`, unless that is NULL. +/// For any other error this returns NULL and stores 0. The bytes belong to +/// the error. +#[no_mangle] +unsafe extern "C" fn uapi16_error_raw_name(e: *const uapi16_error, ret_size: *mut usize) -> *const c_void { + // SAFETY: by the rules of the caller `e` is NULL or an error that was + // not freed. + let error = unsafe { e.as_ref() }; + let name = error.and_then(|e| e.raw_name.as_deref()); + if !ret_size.is_null() { + // SAFETY: `ret_size` is not NULL, so it is valid for the write of a + // size by the rules of the caller. + unsafe { ret_size.write(name.map_or(0, <[u8]>::len)) }; + } + name.map_or(ptr::null(), |name| name.as_ptr().cast()) +} + +/// Which rule of a name the name breaks: for UAPI16_ERROR_UNWRITABLE_NAME +/// the name of uapi16_error_raw_name(), and for a name passed to a file +/// object that is no name, that one. 0 for any other error. +#[no_mangle] +unsafe extern "C" fn uapi16_error_name_problem(e: *const uapi16_error) -> NameProblemNumber { + // SAFETY: by the rules of the caller `e` is NULL or an error that was + // not freed. + let error = unsafe { e.as_ref() }; + let problem = error.and_then(|e| e.name_problem); + problem.map_or(0, |problem| problem as u64) +} + +/// The field the error is about, as the specification spells it, such as +/// "mode" or "inodeToken". NULL if the error is about no field. The string +/// is a constant of the library. +#[no_mangle] +unsafe extern "C" fn uapi16_error_field(e: *const uapi16_error) -> *const c_char { + // SAFETY: by the rules of the caller `e` is NULL or an error that was + // not freed. + let error = unsafe { e.as_ref() }; + let field = error.and_then(|e| e.field).and_then(Field::c_name); + field.map_or(ptr::null(), CStr::as_ptr) +} + +/// Stores in `ret` the number of the record the error is about, counting +/// from 0, which is the record of the root. For a reader that is the record +/// that failed, and for a writer of records the number the record it refused +/// would have had. -ENODATA if the error is about no record, as no error of +/// a manifest writer is. +#[no_mangle] +#[must_use] +unsafe extern "C" fn uapi16_error_record(e: *const uapi16_error, ret: *mut u64) -> c_int { + // SAFETY: by the rules of the caller `e` is NULL or an error that was + // not freed. + let error = unsafe { e.as_ref() }; + // SAFETY: by the rules of the caller `ret` is NULL or valid for the + // write of a number. + let ret = unsafe { Place::new(ret) }; + let got = match (error, ret.needed()) { + (Some(error), Ok(ret)) => { + let record = error.record.ok_or_else(uapi16_error::absent); + record.map(|record| ret.store(record)) + } + _ => Err(uapi16_error::misuse()), + }; + ErrorPlace::NONE.returned(got) +} + +/// For UAPI16_ERROR_MANIFEST and UAPI16_ERROR_TOO_LARGE, the rule of the +/// specification that a manifest or a file object breaks, by a name that +/// never changes. NULL for any other error. The string is a constant of the +/// library. +/// +/// The names are "notJson", "duplicateKey", "invalidString", "notObject", +/// "notUtf8", "nulByte", "recordSeparator", "recordTooLarge", "empty", +/// "noTrailer", "dataAfterTrailer", "fileAfterSignature", "mediaType", +/// "firstHasName", "firstNotDirectory", "noOrder", "noName", "invalidName", +/// "duplicateName", "misplaced", "outOfOrder", "unlistedFeature", +/// "noTarget", "unknownType", "fieldType", "fieldRange", +/// "fieldNotPermitted", "contradiction", "contents", "signature" and +/// "extendedAttributes". +#[no_mangle] +unsafe extern "C" fn uapi16_error_problem(e: *const uapi16_error) -> *const c_char { + // SAFETY: by the rules of the caller `e` is NULL or an error that was + // not freed. + let error = unsafe { e.as_ref() }; + let problem = error.and_then(|e| e.problem).and_then(Problem::c_name); + problem.map_or(ptr::null(), CStr::as_ptr) +} + +/// Frees an error. NULL is fine. Returns NULL. +#[no_mangle] +unsafe extern "C" fn uapi16_error_free(e: *mut uapi16_error) -> *mut uapi16_error { + // SAFETY: by the rules of the caller `e` is NULL or an error that was + // not freed, and nothing uses it after this call. + unsafe { uapi16_error::free(e) } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::TempDir; + use crate::NameBuf; + use crate::Validity; + use std::fs; + use std::io::Seek; + use std::os::fd::AsRawFd; + + /// The descriptor of `file` as a caller in C passes it. + impl Process { + /// A process that is not the one that is running. None where + /// nothing tells the one that is running from another, as under + /// Miri, which has no page for that. + fn elsewhere() -> Option { + match Process::current() { + Process::Known(generation) => generation.checked_add(1).map(Process::Known), + Process::Spent | Process::Untold => None, + } + } + } + + fn descriptor(file: &File) -> Descriptor<'_> { + Descriptor(file.as_raw_fd(), PhantomData) + } + + /// The string `text` as a caller in C passes it. + fn text(text: &CStr) -> Text<'_> { + Text(Some(text)) + } + + /// The numbers C has for the features `features`, in their order. + fn numbers_of(features: Features) -> Vec { + let held = uapi16_feature_t::ALL + .into_iter() + .filter(|c| c.rust().is_some_and(|rust| features.contains(rust))); + held.map(|c| c as FeatureNumber).collect() + } + + /// A set of features as a program in C has one: its size, and after it + /// its words. It is as long as the test makes it and no longer, so that + /// Miri finds a call that reads or writes past it. + #[derive(Clone, Debug, PartialEq, Eq)] + struct CallerSet(Vec); + + impl CallerSet { + /// How many bits a word has. + const BITS: usize = u64::BITS as usize; + /// How many words the largest set has. + const WORDS_MAX: usize = UAPI16_FEATURES_SIZE_MAX / size_of::() - 1; + + /// A set of `words` words with the features `features`, with the + /// size a header with as many words gives it. + fn of(words: usize, features: &[FeatureNumber]) -> CallerSet { + let mut set = vec![0; 1 + words]; + set[0] = (size_of::() * (1 + words)) as u64; + for feature in features { + let bit = *feature as usize - 1; + set[1 + bit / CallerSet::BITS] |= 1 << (bit % CallerSet::BITS); + } + CallerSet(set) + } + + /// A set with the size `size`, which no set has, and nothing after + /// it: nothing of such a set is looked at but its size. + fn sized(size: u64) -> CallerSet { + CallerSet(vec![size]) + } + + /// A set with the words `words`, and the size that goes with them. + fn with_words(words: &[u64]) -> CallerSet { + let mut set = CallerSet::of(words.len(), &[]); + set.0[1..].copy_from_slice(words); + set + } + + fn as_ptr(&self) -> *const uapi16_features_t { + self.0.as_ptr().cast() + } + + fn as_mut_ptr(&mut self) -> *mut uapi16_features_t { + self.0.as_mut_ptr().cast() + } + + fn size(&self) -> u64 { + self.0[0] + } + + fn words(&self) -> &[u64] { + &self.0[1..] + } + + /// The features of the set, lowest first, as its words have them. + fn features(&self) -> Vec { + let mut features = Vec::new(); + for (index, word) in self.words().iter().enumerate() { + let first = (index * CallerSet::BITS) as FeatureNumber + 1; + let mut bits = *word; + while bits != 0 { + features.push(first + bits.trailing_zeros()); + bits &= bits - 1; + } + } + features + } + + /// The features of the set as a walk with uapi16_features_next() + /// gives them. + fn walked(&self) -> Vec { + let mut features = Vec::new(); + // SAFETY: the set is one of a caller, as long as its size says. + let mut next = unsafe { uapi16_features_next(self.as_ptr(), 0) }; + while next != 0 { + // A walk gives no feature twice. + assert!(features.len() < self.words().len() * CallerSet::BITS); + features.push(next); + // SAFETY: as above. + next = unsafe { uapi16_features_next(self.as_ptr(), next) }; + } + features + } + } + + /// The bytes `bytes` as a caller in C passes them. + fn bytes(bytes: &[u8]) -> Bytes<'_> { + Bytes(Some(bytes)) + } + + /// A tree with a directory and two files. + fn tree(name: &str) -> (TempDir, File) { + let tmp = TempDir::new(name); + fs::create_dir(tmp.0.join("a")).unwrap(); + fs::write(tmp.0.join("a/file"), b"hello").unwrap(); + fs::write(tmp.0.join("top"), b"top").unwrap(); + let top = File::open(&tmp.0).unwrap(); + (tmp, top) + } + + /// The kind and the errno of the error of the C API for `error`. + fn kind_and_errno(error: Error) -> (uapi16_error_kind_t, c_int) { + let error = uapi16_error::from(error); + (error.kind, error.errno) + } + + /// A file object of the C API with the name `name`. + fn object(name: &CStr) -> uapi16_file_object { + uapi16_file_object::new(text(name)).unwrap() + } + + /// The numbers of the enums, which never change: C callers are built + /// with them. + #[test] + fn numbers() { + use uapi16_error_kind_t::*; + use uapi16_name_problem_t::*; + for (i, c) in uapi16_feature_t::ALL.into_iter().enumerate() { + assert_eq!(c as u64, i as u64 + 1); + // An enumerator has the name of its feature, as the header + // says: in upper case, with an underscore for a dash. + let names: Vec<&str> = c.rust().unwrap().names().collect(); + assert_eq!(names.len(), 1); + let spelled = names[0].to_uppercase().replace('-', "_"); + assert_eq!(format!("{:?}", c), format!("UAPI16_FEATURE_{}", spelled)); + } + assert_eq!(uapi16_feature_t::UAPI16_FEATURE_NONE.rust(), None); + assert_eq!(uapi16_feature_t::UAPI16_FEATURE_NONE as u64, 0); + assert_eq!(uapi16_order_t::UAPI16_ORDER_NONE as u64, 0); + assert_eq!(uapi16_order_t::UAPI16_ORDER_CODEPOINT as u64, 1); + assert_eq!(uapi16_read_only_t::UAPI16_READ_ONLY_UNSTATED as u64, 0); + assert_eq!(uapi16_read_only_t::UAPI16_READ_ONLY_NO as u64, 1); + assert_eq!(uapi16_read_only_t::UAPI16_READ_ONLY_YES as u64, 2); + // The numbers of an order of two names are those qsort() takes. + assert_eq!(uapi16_name_order_t::UAPI16_NAME_BEFORE as i64, -1); + assert_eq!(uapi16_name_order_t::UAPI16_NAME_SAME as i64, 0); + assert_eq!(uapi16_name_order_t::UAPI16_NAME_AFTER as i64, 1); + assert_eq!(uapi16_add_flag_t::UAPI16_ADD_NONE as u64, 0); + assert_eq!(uapi16_add_flag_t::UAPI16_ADD_CROSS_MOUNTS as u64, 1); + assert_eq!(uapi16_add_flag_t::UAPI16_ADD_GRACEFUL as u64, 2); + assert_eq!(UAPI16_INODE_TOKEN_NONE, 0); + let kinds = [ + (UAPI16_ERROR_IO, 1), + (UAPI16_ERROR_EXISTS, 2), + (UAPI16_ERROR_DUPLICATE, 3), + (UAPI16_ERROR_CHANGED, 4), + (UAPI16_ERROR_HARDLINK_MISMATCH, 5), + (UAPI16_ERROR_UNWRITABLE_NAME, 6), + (UAPI16_ERROR_NOT_DIRECTORY, 7), + (UAPI16_ERROR_UNSUPPORTED, 8), + (UAPI16_ERROR_INVALID_ARGUMENT, 9), + (UAPI16_ERROR_LOOP, 10), + (UAPI16_ERROR_MISSING_PARENT, 11), + (UAPI16_ERROR_TOO_LARGE, 12), + (UAPI16_ERROR_ENDED, 13), + (UAPI16_ERROR_MANIFEST, 14), + (UAPI16_ERROR_SOURCE_MISSING, 15), + (UAPI16_ERROR_SOURCE_NOT_REGULAR, 16), + (UAPI16_ERROR_SIZE_MISMATCH, 17), + (UAPI16_ERROR_HASH_MISMATCH, 18), + (UAPI16_ERROR_REVOKED, 19), + (UAPI16_ERROR_NOT_YET_VALID, 20), + (UAPI16_ERROR_EXPIRED, 21), + ]; + for (kind, number) in kinds { + assert_eq!(kind as u64, number, "{:?}", kind); + } + let problems = [ + (UAPI16_NAME_PROBLEM_NOT_UTF8, 1), + (UAPI16_NAME_PROBLEM_EMPTY, 2), + (UAPI16_NAME_PROBLEM_TOO_LONG, 3), + (UAPI16_NAME_PROBLEM_RESERVED, 4), + (UAPI16_NAME_PROBLEM_CONTROL_CHARACTER, 5), + (UAPI16_NAME_PROBLEM_NONCHARACTER, 6), + (UAPI16_NAME_PROBLEM_EMPTY_COMPONENT, 7), + (UAPI16_NAME_PROBLEM_DOT_COMPONENT, 8), + ]; + for (problem, number) in problems { + assert_eq!(problem as u64, number, "{:?}", problem); + } + assert_eq!(uapi16_read_t::UAPI16_READ_END as u64, 0); + assert_eq!(uapi16_read_t::UAPI16_READ_FILE as u64, 1); + assert_eq!(uapi16_read_t::UAPI16_READ_SIGNATURES as u64, 2); + assert_eq!(uapi16_read_t::UAPI16_READ_SIGNATURE as u64, 3); + assert_eq!(uapi16_data_location_t::UAPI16_DATA_LOCATION_NONE as u64, 0); + assert_eq!(uapi16_data_location_t::UAPI16_DATA_LOCATION_LITERAL as u64, 1); + assert_eq!(uapi16_data_location_t::UAPI16_DATA_LOCATION_EXTERNAL as u64, 2); + assert_eq!(uapi16_data_location_t::UAPI16_DATA_LOCATION_UNSUPPORTED as u64, 3); + assert_eq!(uapi16_directory_flag_t::UAPI16_DIRECTORY_NONE as u64, 0); + assert_eq!(uapi16_directory_flag_t::UAPI16_DIRECTORY_FOLLOW_SYMLINKS as u64, 1); + // What a manifest has of the two kinds of flags is what the kernel + // has for them. + let inode_flags = uapi16_file_object::INODE_FLAGS.map(|(flag, _, _)| flag.bits()); + assert_eq!(inode_flags, [0x20, 0x10, 0x80, 0x0080_0000, 0x40]); + let dos_attributes = uapi16_file_object::DOS_ATTRIBUTES.map(|(attribute, _, _)| attribute); + assert_eq!(dos_attributes, [0x02, 0x04, 0x20]); + } + + /// Every error of the crate has its kind and its errno in C. + #[test] + fn kinds_and_errnos() { + use uapi16_error_kind_t::*; + let of = |kind| Error::new(kind, String::new()); + for (kind, c, errno) in [ + ( + ErrorKind::Tree(TreeProblem::Duplicate), + UAPI16_ERROR_DUPLICATE, + libc::EEXIST, + ), + ( + ErrorKind::Tree(TreeProblem::Changed), + UAPI16_ERROR_CHANGED, + libc::ESTALE, + ), + ( + ErrorKind::Tree(TreeProblem::HardlinkMismatch), + UAPI16_ERROR_HARDLINK_MISMATCH, + libc::ESTALE, + ), + ( + ErrorKind::Tree(TreeProblem::UnwritableName), + UAPI16_ERROR_UNWRITABLE_NAME, + libc::EINVAL, + ), + ( + ErrorKind::Tree(TreeProblem::NotDirectory), + UAPI16_ERROR_NOT_DIRECTORY, + libc::ENOTDIR, + ), + ( + ErrorKind::Tree(TreeProblem::FeatureUnavailable), + UAPI16_ERROR_UNSUPPORTED, + libc::EOPNOTSUPP, + ), + ( + ErrorKind::Tree(TreeProblem::FeatureNotForTrees), + UAPI16_ERROR_INVALID_ARGUMENT, + libc::EINVAL, + ), + (ErrorKind::Tree(TreeProblem::Loop), UAPI16_ERROR_LOOP, libc::ELOOP), + ( + ErrorKind::Tree(TreeProblem::MissingParent), + UAPI16_ERROR_MISSING_PARENT, + libc::ENOENT, + ), + ( + ErrorKind::Manifest(Problem::RecordTooLarge), + UAPI16_ERROR_TOO_LARGE, + libc::E2BIG, + ), + ( + ErrorKind::Source(SourceProblem::Missing), + UAPI16_ERROR_SOURCE_MISSING, + libc::ENOENT, + ), + ( + ErrorKind::Source(SourceProblem::NotRegular), + UAPI16_ERROR_SOURCE_NOT_REGULAR, + libc::EINVAL, + ), + (ErrorKind::Source(SourceProblem::Unreadable), UAPI16_ERROR_IO, libc::EIO), + ( + ErrorKind::Data(DataProblem::SizeMismatch), + UAPI16_ERROR_SIZE_MISMATCH, + libc::EBADMSG, + ), + ( + ErrorKind::Data(DataProblem::HashMismatch), + UAPI16_ERROR_HASH_MISMATCH, + libc::EBADMSG, + ), + ( + ErrorKind::Unsupported(UnsupportedData::UrlOrEncoding), + UAPI16_ERROR_UNSUPPORTED, + libc::EOPNOTSUPP, + ), + ( + ErrorKind::Unsupported(UnsupportedData::Absent), + UAPI16_ERROR_UNSUPPORTED, + libc::EOPNOTSUPP, + ), + ( + ErrorKind::NotValid(ValidityProblem::Revoked), + UAPI16_ERROR_REVOKED, + libc::EKEYREVOKED, + ), + ( + ErrorKind::NotValid(ValidityProblem::NotYetValid), + UAPI16_ERROR_NOT_YET_VALID, + libc::EKEYEXPIRED, + ), + ( + ErrorKind::NotValid(ValidityProblem::Expired), + UAPI16_ERROR_EXPIRED, + libc::EKEYEXPIRED, + ), + (ErrorKind::Io, UAPI16_ERROR_IO, libc::EIO), + ] { + assert_eq!(kind_and_errno(of(kind)), (c, errno), "{:?}", kind); + } + // Every rule of the specification but the one of the size of a + // record is the one kind, with the name of the rule. + for &problem in Problem::ALL { + let error = uapi16_error::from(of(ErrorKind::Manifest(problem))); + let expected = match problem { + Problem::RecordTooLarge => (UAPI16_ERROR_TOO_LARGE, libc::E2BIG), + _ => (UAPI16_ERROR_MANIFEST, libc::EBADMSG), + }; + assert_eq!((error.kind, error.errno), expected, "{:?}", problem); + assert_eq!(error.problem, Some(problem)); + assert_eq!(problem.c_name().unwrap().to_str(), Ok(problem.as_str())); + } + // The errno of a name a manifest cannot hold says which rule it + // breaks. + for (problem, errno) in [ + (NameProblem::NotUtf8, libc::EILSEQ), + (NameProblem::TooLong, libc::ENAMETOOLONG), + (NameProblem::ContainsControlCharacter, libc::EINVAL), + ] { + let error = of(ErrorKind::Tree(TreeProblem::UnwritableName)).because(problem); + assert_eq!( + kind_and_errno(error), + (UAPI16_ERROR_UNWRITABLE_NAME, errno), + "{:?}", + problem + ); + } + // An I/O error has the errno of its system call, where it has one, + // and so has a file of a manifest that can't be read. + let io = |errno| io::Error::from_raw_os_error(errno); + assert_eq!( + kind_and_errno(Error::from(io(libc::ENOSPC))), + (UAPI16_ERROR_IO, libc::ENOSPC) + ); + let unreadable = of(ErrorKind::Source(SourceProblem::Unreadable)).caused_by(io(libc::EACCES)); + assert_eq!(kind_and_errno(unreadable), (UAPI16_ERROR_IO, libc::EACCES)); + let other = Error::from(io::Error::other("no errno")); + assert_eq!(kind_and_errno(other), (UAPI16_ERROR_IO, libc::EIO)); + // EEXIST where a new file gets its name is the name that is taken. + let exists = uapi16_error::from(Error::from(io(libc::EEXIST))).of_new_file(); + assert_eq!((exists.kind, exists.errno), (UAPI16_ERROR_EXISTS, libc::EEXIST)); + assert_eq!(uapi16_error::ended().errno, libc::ESTALE); + assert_eq!(uapi16_error::absent().errno, libc::ENODATA); + assert_eq!(uapi16_error::misuse().errno, libc::EINVAL); + } + + /// The header lists the names of the rules: every one of + /// [`Problem::ALL`], in its order, and no other. + #[test] + fn the_header_names_every_rule() { + let header = include_str!("uapi16.h"); + let (_, names) = header.split_once(" * The names are ").unwrap(); + let (names, _) = names.split_once(".\n */\nconst char *uapi16_error_problem(").unwrap(); + let listed: Vec<&str> = names.split('"').skip(1).step_by(2).collect(); + let rules: Vec<&str> = Problem::ALL.iter().map(|problem| problem.as_str()).collect(); + assert_eq!(listed, rules); + } + + /// UAPI16_FEATURES_SET() is written by hand. It has a line for each + /// word of a uapi16_features_t, in their order, and no other. + #[test] + fn the_macro_fills_every_word() { + let header = include_str!("uapi16.h"); + let (_, set) = header.split_once("#define UAPI16_FEATURES_SET(...) \\\n").unwrap(); + let (set, _) = set.split_once(" } }\n").unwrap(); + let mut lines = set.lines(); + assert_eq!(lines.next(), Some(" { sizeof(uapi16_features_t), { \\")); + let words: Vec<&str> = lines + .map(|line| line.trim_end_matches(" \\").trim_end_matches(',').trim()) + .collect(); + let expected: Vec = (0..UAPI16_FEATURES_WORDS) + .map(|word| format!("UAPI16_FEATURES_OR_({}, __VA_ARGS__)", word)) + .collect(); + assert_eq!(words, expected); + } + + /// An error says in C what it says in Rust: the names, the feature, the + /// name as its directory has it with the rule it breaks, the field, the + /// record and the rule. The names of fields, rules and features are + /// constants: the same string every time. + #[test] + fn what_an_error_is_about() { + let error = Error::new(ErrorKind::Tree(TreeProblem::HardlinkMismatch), String::new()) + .named("a/second") + .linked(NameBuf::new("a/first").unwrap()); + let error = uapi16_error::from(error); + assert_eq!(error.path.as_deref(), Some(c"a/second")); + assert_eq!(error.hardlink_path.as_deref(), Some(c"a/first")); + assert_eq!((error.field, error.record, error.problem), (None, None, None)); + + let error = + Error::new(ErrorKind::Tree(TreeProblem::FeatureUnavailable), String::new()).about(Features::USER_XATTR); + let error = uapi16_error::from(error); + assert_eq!(error.feature, Some(uapi16_feature_t::UAPI16_FEATURE_USER_XATTR)); + + let error = Error::new(ErrorKind::Tree(TreeProblem::UnwritableName), String::new()) + .named("a") + .raw(OsStr::from_bytes(b"\xff")) + .because(NameProblem::NotUtf8); + let error = uapi16_error::from(error); + assert_eq!(error.raw_name.as_deref(), Some(&b"\xff"[..])); + assert_eq!( + error.name_problem, + Some(uapi16_name_problem_t::UAPI16_NAME_PROBLEM_NOT_UTF8) + ); + + let refused = || { + let error = Error::manifest(Problem::FieldNotPermitted, String::new()); + uapi16_error::from(error.at(Field::InodeToken).in_record(7).named("x")) + }; + let error = refused(); + assert_eq!(error.field, Some(Field::InodeToken)); + assert_eq!(error.record, Some(7)); + assert_eq!(error.problem, Some(Problem::FieldNotPermitted)); + // The record as C gets it: 0 is the record of the root, and an + // error about no record stores none. + for number in [0, 7] { + let about = Error::manifest(Problem::FieldNotPermitted, String::new()).in_record(number); + let e = uapi16_error::from(about).into_raw(); + let mut record = 77u64; + // SAFETY: `e` is an error that is freed once, here, and `record` + // is a local. + unsafe { + assert_eq!(uapi16_error_record(e, &mut record), 0); + assert_eq!(record, number); + assert_eq!(uapi16_error_record(e, ptr::null_mut()), -libc::EINVAL); + assert_eq!(uapi16_error_record(ptr::null(), &mut record), -libc::EINVAL); + assert!(uapi16_error_free(e).is_null()); + } + } + let e = uapi16_error::misuse().into_raw(); + let mut record = 77u64; + // SAFETY: as above. + unsafe { + assert_eq!(uapi16_error_record(e, &mut record), -libc::ENODATA); + assert_eq!(record, 77); + assert!(uapi16_error_free(e).is_null()); + } + assert_eq!(Field::InodeToken.c_name(), Some(c"inodeToken")); + assert_eq!(Problem::FieldNotPermitted.c_name(), Some(c"fieldNotPermitted")); + let again = |name: Option<&CStr>| name.map(CStr::as_ptr); + assert_eq!(again(Field::InodeToken.c_name()), again(Field::InodeToken.c_name())); + assert_eq!( + again(Problem::FieldNotPermitted.c_name()), + again(Problem::FieldNotPermitted.c_name()) + ); + + for c in uapi16_feature_t::ALL { + let name = uapi16_feature_t::name_of(c as FeatureNumber).unwrap(); + assert_eq!(name.to_str().unwrap().parse::().ok(), c.rust()); + assert_eq!( + uapi16_feature_t::name_of(c as FeatureNumber).map(CStr::as_ptr), + Some(name.as_ptr()) + ); + } + assert_eq!( + uapi16_feature_t::name_of(uapi16_feature_t::UAPI16_FEATURE_USER_XATTR as FeatureNumber), + Some(c"user-xattr") + ); + for none in [ + 0, + uapi16_feature_t::ALL.len() as FeatureNumber + 1, + 1 << 31, + FeatureNumber::MAX, + ] { + assert_eq!(uapi16_feature_t::name_of(none), None, "{:#x}", none); + } + } + + /// The size of a set: one above the largest size is too large, one + /// below the first size or that is no multiple of 8 is none. Nothing of + /// a set with such a size is read but the size, and nothing of it is + /// written. The calls without a result take it for a set without + /// features and change nothing. No set is none either. + #[test] + fn sizes_of_sets() { + const FIRST: u64 = UAPI16_FEATURES_SIZE_VER0 as u64; + const MAX: u64 = UAPI16_FEATURES_SIZE_MAX as u64; + const WORD: u64 = SetWords::WORD_SIZE; + let words = |size: u64| SetWords::count_of(size).map_err(|e| e.errno); + assert_eq!(UAPI16_FEATURES_SIZE_VER0, 24); + for (size, expected) in [ + (FIRST, 2), + (FIRST + WORD, 3), + (FIRST + 2 * WORD, 4), + (MAX - WORD, CallerSet::WORDS_MAX - 1), + (MAX, CallerSet::WORDS_MAX), + ] { + assert_eq!(words(size), Ok(expected), "{}", size); + } + let no_sizes = [ + 0, + 1, + WORD, + FIRST - WORD, + FIRST - 1, + FIRST + 1, + FIRST + WORD / 2, + FIRST + WORD - 1, + FIRST + WORD + 1, + MAX - 1, + ]; + let too_large = [MAX + 1, MAX + WORD, 1 << 32, (1 << 32) + FIRST, u64::MAX - 7, u64::MAX]; + for size in no_sizes { + assert_eq!(words(size), Err(libc::EINVAL), "{}", size); + } + for size in too_large { + assert_eq!(words(size), Err(libc::E2BIG), "{}", size); + } + + for (sizes, errno) in [(&no_sizes[..], libc::EINVAL), (&too_large[..], libc::E2BIG)] { + for &size in sizes { + let mut none = CallerSet::sized(size); + let mut some = CallerSet::of(2, &[1, 65]); + // SAFETY: each set is as long as it says where its size is + // one a set has, and its size can be read where it is not. + unsafe { + assert_eq!(uapi16_features_add(none.as_mut_ptr(), 1), -errno); + assert_eq!(uapi16_features_remove(none.as_mut_ptr(), 1), -errno); + assert!(!uapi16_features_has(none.as_ptr(), 1)); + assert_eq!(uapi16_features_next(none.as_ptr(), 0), 0); + assert!(!uapi16_features_equal(none.as_ptr(), none.as_ptr())); + assert!(!uapi16_features_equal(none.as_ptr(), some.as_ptr())); + assert!(!uapi16_features_equal(some.as_ptr(), none.as_ptr())); + uapi16_features_union(some.as_mut_ptr(), none.as_ptr()); + uapi16_features_intersect(some.as_mut_ptr(), none.as_ptr()); + uapi16_features_subtract(some.as_mut_ptr(), none.as_ptr()); + assert_eq!(some, CallerSet::of(2, &[1, 65])); + uapi16_features_union(none.as_mut_ptr(), some.as_ptr()); + uapi16_features_intersect(none.as_mut_ptr(), some.as_ptr()); + uapi16_features_subtract(none.as_mut_ptr(), some.as_ptr()); + assert_eq!(uapi16_features_default(none.as_mut_ptr()), -errno); + assert_eq!(uapi16_features_known(none.as_mut_ptr()), -errno); + let taken = SetWords::new(none.as_ptr()).and_then(SetWords::features); + assert_eq!(taken.unwrap_err().errno, errno); + let mut options = uapi16_manifest_options::new(); + assert_eq!( + uapi16_manifest_options_set_features(&mut options, none.as_ptr()), + -errno + ); + assert_eq!(options.features(), Features::DEFAULT); + let mut file = object(c"file"); + file.set_mode(0o644).unwrap(); + assert_eq!(uapi16_file_object_retain_features(&mut file, none.as_ptr()), -errno); + assert_eq!(uapi16_file_object_stated_features(&file, none.as_mut_ptr()), -errno); + assert_eq!(file.stated_features(), Features::MODE); + } + assert_eq!(none, CallerSet::sized(size)); + } + } + + let mut some = CallerSet::of(2, &[1, 65]); + // SAFETY: NULL is no set, and the others are sets of a caller. + unsafe { + assert_eq!(uapi16_features_add(ptr::null_mut(), 1), -libc::EINVAL); + assert_eq!(uapi16_features_remove(ptr::null_mut(), 1), -libc::EINVAL); + assert!(!uapi16_features_has(ptr::null(), 1)); + assert_eq!(uapi16_features_next(ptr::null(), 0), 0); + assert!(!uapi16_features_equal(ptr::null(), ptr::null())); + assert!(!uapi16_features_equal(some.as_ptr(), ptr::null())); + assert!(!uapi16_features_equal(ptr::null(), some.as_ptr())); + uapi16_features_union(some.as_mut_ptr(), ptr::null()); + uapi16_features_intersect(some.as_mut_ptr(), ptr::null()); + uapi16_features_subtract(some.as_mut_ptr(), ptr::null()); + uapi16_features_union(ptr::null_mut(), some.as_ptr()); + uapi16_features_intersect(ptr::null_mut(), some.as_ptr()); + uapi16_features_subtract(ptr::null_mut(), some.as_ptr()); + assert_eq!(uapi16_features_default(ptr::null_mut()), -libc::EINVAL); + assert_eq!(uapi16_features_known(ptr::null_mut()), -libc::EINVAL); + let mut options = uapi16_manifest_options::new(); + assert_eq!( + uapi16_manifest_options_set_features(&mut options, ptr::null()), + -libc::EINVAL + ); + assert_eq!( + uapi16_manifest_options_set_features(ptr::null_mut(), some.as_ptr()), + -libc::EINVAL + ); + let mut file = object(c"file"); + assert_eq!( + uapi16_file_object_retain_features(&mut file, ptr::null()), + -libc::EINVAL + ); + assert_eq!( + uapi16_file_object_retain_features(ptr::null_mut(), some.as_ptr()), + -libc::EINVAL + ); + assert_eq!( + uapi16_file_object_stated_features(&file, ptr::null_mut()), + -libc::EINVAL + ); + assert_eq!( + uapi16_file_object_stated_features(ptr::null(), some.as_mut_ptr()), + -libc::EINVAL + ); + assert_eq!(uapi16_reader_features(ptr::null(), some.as_mut_ptr()), -libc::EINVAL); + } + assert_eq!(some, CallerSet::of(2, &[1, 65])); + } + + /// The bits of a set: a feature is added, asked for and taken out by + /// its number, in sets of the first size, of the next one and of the + /// largest. UAPI16_FEATURE_NONE is no feature, and neither is a number + /// the set has no room for. A walk gives the features in the order of + /// their numbers, from any number on, and goes from every word into the + /// next one. The size is never written. + #[test] + fn bits_of_sets() { + for words in [2, 3, CallerSet::WORDS_MAX] { + let last = (words * CallerSet::BITS) as FeatureNumber; + let mut set = CallerSet::of(words, &[]); + let size = set.size(); + let numbers = [1, 2, 31, 32, 63, 64, 65, 100, 128, last - 64, last - 1, last]; + let mut expected = Vec::new(); + for feature in numbers { + // SAFETY: the set is as long as its size says. + unsafe { + assert!(!uapi16_features_has(set.as_ptr(), feature) || expected.contains(&feature)); + assert_eq!(uapi16_features_add(set.as_mut_ptr(), feature), 0); + assert_eq!(uapi16_features_add(set.as_mut_ptr(), feature), 0); + assert!(uapi16_features_has(set.as_ptr(), feature)); + } + if !expected.contains(&feature) { + expected.push(feature); + } + expected.sort_unstable(); + assert_eq!(set.features(), expected, "{} words, {}", words, feature); + assert_eq!(set.walked(), expected); + } + for none in [0, last + 1, last + 64, 1 << 31, FeatureNumber::MAX] { + // SAFETY: as above. + unsafe { + assert_eq!(uapi16_features_add(set.as_mut_ptr(), none), -libc::EINVAL); + assert_eq!(uapi16_features_remove(set.as_mut_ptr(), none), -libc::EINVAL); + assert!(!uapi16_features_has(set.as_ptr(), none)); + } + } + // A walk goes on from any number, whether the set has it or + // not, and ends past the last feature. Miri takes minutes for + // every number of the largest set, so there the walk goes on + // from the numbers next to every feature and at the two ends + // of the set. + let every: Vec = if cfg!(miri) { + let near = [0, last].into_iter().chain(numbers); + near.flat_map(|number| [number.saturating_sub(1), number, number + 1]) + .collect() + } else { + (0..=last + 1).collect() + }; + for after in every { + let next = expected.iter().copied().find(|feature| *feature > after); + // SAFETY: as above. + let walked = unsafe { uapi16_features_next(set.as_ptr(), after) }; + assert_eq!(walked, next.unwrap_or(0), "{} words, after {}", words, after); + } + for after in [last + 64, 1 << 31, FeatureNumber::MAX] { + // SAFETY: as above. + assert_eq!(unsafe { uapi16_features_next(set.as_ptr(), after) }, 0); + } + for feature in numbers { + // SAFETY: as above. + unsafe { + assert_eq!(uapi16_features_remove(set.as_mut_ptr(), feature), 0); + assert_eq!(uapi16_features_remove(set.as_mut_ptr(), feature), 0); + assert!(!uapi16_features_has(set.as_ptr(), feature)); + } + expected.retain(|kept| *kept != feature); + assert_eq!(set.walked(), expected); + } + assert_eq!(set, CallerSet::of(words, &[])); + assert_eq!(set.size(), size); + + // A walk goes from every word into the next one: over a set + // with the first and the last feature of each word it gives + // every one of them, each after the one before it. + let ends: Vec = (0..words as FeatureNumber) + .flat_map(|word| [word * u64::BITS + 1, (word + 1) * u64::BITS]) + .collect(); + assert_eq!(CallerSet::of(words, &ends).walked(), ends); + } + } + + /// Two sets are combined by the sizes they carry: a word a set does not + /// have counts as 0, the first set keeps its size, and a union drops + /// what the first set has no room for. Two sets are equal that have the + /// same features, whatever their sizes are. A set is combined with + /// itself as with another. + #[test] + fn sets_combined() { + type Combine = unsafe extern "C" fn(*mut uapi16_features_t, *const uapi16_features_t); + // What a call makes of a word of the first set and one of the other. + type Words = fn(u64, u64) -> u64; + let calls: [(Combine, Words); 3] = [ + (uapi16_features_union, |own, theirs| own | theirs), + (uapi16_features_intersect, |own, theirs| own & theirs), + (uapi16_features_subtract, |own, theirs| own & !theirs), + ]; + let patterns: [&[u64]; 6] = [ + &[0, 0], + &[0x8000_0000_4000_0003, 1], + &[0x0000_0001_4000_0002, 0x8000_0000_0000_0001], + &[1, 0, 0x10], + &[0x8000_0000_4000_0003, 1, 0, 0x8000_0000_0000_0000], + &[u64::MAX, u64::MAX, u64::MAX], + ]; + let word = |words: &[u64], index: usize| words.get(index).copied().unwrap_or(0); + for own in patterns { + for theirs in patterns { + for (call, combined) in calls { + let mut set = CallerSet::with_words(own); + let other = CallerSet::with_words(theirs); + // SAFETY: both are sets of a caller, as long as their + // sizes say. + unsafe { call(set.as_mut_ptr(), other.as_ptr()) }; + let expected: Vec = (0..own.len()) + .map(|index| combined(own[index], word(theirs, index))) + .collect(); + assert_eq!(set, CallerSet::with_words(&expected), "{:x?} {:x?}", own, theirs); + assert_eq!(other, CallerSet::with_words(theirs)); + } + let same = (0..own.len().max(theirs.len())).all(|index| word(own, index) == word(theirs, index)); + let (a, b) = (CallerSet::with_words(own), CallerSet::with_words(theirs)); + // SAFETY: as above. + assert_eq!(unsafe { uapi16_features_equal(a.as_ptr(), b.as_ptr()) }, same); + } + // With itself: the same set is read and written. + for (call, combined) in calls { + let mut set = CallerSet::with_words(own); + let itself = set.as_mut_ptr(); + // SAFETY: the set is one of a caller, and both arguments + // are this one set. + unsafe { + call(itself, itself); + assert!(uapi16_features_equal(itself, itself)); + } + let expected: Vec = own.iter().map(|word| combined(*word, *word)).collect(); + assert_eq!(set, CallerSet::with_words(&expected)); + } + } + // A set without a feature in its words past the first size is + // equal to the shorter one, and the largest set there is to one of + // the first size. + let largest = CallerSet::of(CallerSet::WORDS_MAX, &[1, 128]); + let first = CallerSet::of(2, &[1, 128]); + // SAFETY: as above. + unsafe { + assert!(uapi16_features_equal(largest.as_ptr(), first.as_ptr())); + assert!(uapi16_features_equal(first.as_ptr(), largest.as_ptr())); + let last = (CallerSet::WORDS_MAX * CallerSet::BITS) as FeatureNumber; + let more = CallerSet::of(CallerSet::WORDS_MAX, &[1, 128, last]); + assert!(!uapi16_features_equal(more.as_ptr(), first.as_ptr())); + assert!(!uapi16_features_equal(first.as_ptr(), more.as_ptr())); + let mut union = CallerSet::of(2, &[2]); + uapi16_features_union(union.as_mut_ptr(), more.as_ptr()); + assert_eq!(union, CallerSet::of(2, &[1, 2, 128])); + } + } + + /// The calls that fill a set and those that take one, with sets that + /// are shorter than the set of the library, as long and longer. A set + /// is filled by its own size: the words both have are copied, the rest + /// of the set is cleared, and its size is never written. A set that is + /// taken has no word that is not 0 past those of the library, and no + /// bit that is the bit of no feature, and nothing is taken of one that + /// has. + #[test] + fn sets_filled_and_taken() { + let known = Features::ALL.word(0); + let default = Features::DEFAULT.word(0); + assert_eq!(known, (1 << uapi16_feature_t::ALL.len()) - 1); + assert_eq!((Features::ALL.word(1), Features::ALL.word(usize::MAX)), (0, 0)); + + // Filled: every word of the set is written, and no other. + for words in [2, 3, 4, CallerSet::WORDS_MAX] { + let ones = vec![u64::MAX; words]; + let mut expected = vec![0; words]; + for (stored, fill) in [ + (default, uapi16_features_default as unsafe extern "C" fn(_) -> _), + (known, uapi16_features_known), + ] { + let mut set = CallerSet::with_words(&ones); + // SAFETY: the set is as long as its size says. + assert_eq!(unsafe { fill(set.as_mut_ptr()) }, 0); + expected[0] = stored; + assert_eq!(set, CallerSet::with_words(&expected)); + } + let mut file = object(c"file"); + file.set_mode(0o644).unwrap(); + file.file_mut().unwrap().set_size(Some(1)); + let mut set = CallerSet::with_words(&ones); + // SAFETY: as above, and the object is there. + let stored = unsafe { uapi16_file_object_stated_features(&file, set.as_mut_ptr()) }; + assert_eq!(stored, 0); + let mode = uapi16_feature_t::UAPI16_FEATURE_MODE as FeatureNumber; + let size = uapi16_feature_t::UAPI16_FEATURE_SIZE as FeatureNumber; + assert_eq!(set, CallerSet::of(words, &[mode, size])); + } + // A set that is shorter than the set of the library gets the words + // it has room for. No header gives a set that short, so this one + // is made by hand. + let mut short = [u64::MAX]; + let mut filled = SetWordsMut { + first: short.as_mut_ptr(), + count: short.len(), + set: PhantomData, + }; + filled.fill(Features::ALL); + assert_eq!(short, [known]); + + // Taken: what the library has, in a set of every length. + let taken = |words: &[u64]| { + let set = CallerSet::with_words(words); + // SAFETY: the set is as long as its size says. + unsafe { SetWords::new(set.as_ptr()) } + .and_then(SetWords::features) + .map_err(|e| e.errno) + }; + assert_eq!(taken(&[0, 0]), Ok(Features::NONE)); + assert_eq!(taken(&[default, 0]), Ok(Features::DEFAULT)); + assert_eq!(taken(&[known, 0]), Ok(Features::ALL)); + assert_eq!(taken(&[known, 0, 0]), Ok(Features::ALL)); + assert_eq!(taken(&[1, 0, 0, 0, 0]), Ok(Features::MODE)); + let mut largest = vec![0; CallerSet::WORDS_MAX]; + largest[0] = default; + assert_eq!(taken(&largest), Ok(Features::DEFAULT)); + // A feature the library does not have, in the words it has. + for unknown in [[known + 1, 0], [1 << 31, 0], [1 << 63, 0], [0, 1], [known, 1 << 63]] { + assert_eq!(taken(&unknown), Err(libc::EINVAL), "{:x?}", unknown); + assert_eq!(taken(&[unknown[0], unknown[1], 0]), Err(libc::EINVAL)); + } + // A word past those of the library that is not 0, wherever it is, + // also with a feature before it that the library does not have. + for at in [2, 3, CallerSet::WORDS_MAX - 1] { + for first in [0, default, known + 1] { + let mut words = vec![0; CallerSet::WORDS_MAX]; + words[0] = first; + words[at] = 1; + assert_eq!(taken(&words[..=at]), Err(libc::E2BIG), "{} {:x}", at, first); + assert_eq!(taken(&words), Err(libc::E2BIG)); + } + } + // A set that is shorter than the set of the library has no feature + // in the words it lacks. + let short = [default]; + let read = SetWords { + first: short.as_ptr(), + count: short.len(), + set: PhantomData, + }; + assert_eq!(read.features().map_err(|e| e.errno), Ok(Features::DEFAULT)); + assert_eq!((read.word(0), read.word(1), read.word(usize::MAX)), (default, 0, 0)); + assert!(read.has(1) && !read.has(65) && !read.has(FeatureNumber::MAX)); + assert_eq!((read.next(0), read.next(64), read.next(FeatureNumber::MAX)), (1, 0, 0)); + // It is compared and combined with a longer one as any other: the + // longer set loses what the shorter one lacks in an intersection, + // and keeps it in a union. + let equal = CallerSet::with_words(&[default, 0, 0]); + let mut longer = CallerSet::with_words(&[default | (1 << 63), 1, 1]); + // SAFETY: the sets are as long as their sizes say. + unsafe { + let equal = SetWords::new(equal.as_ptr()).unwrap(); + assert!(read.equals(equal) && equal.equals(read) && read.equals(read)); + let mut own = SetWordsMut::new(longer.as_mut_ptr()).unwrap(); + assert!(!read.equals(own.words()) && !own.words().equals(read)); + own.combine(read, |own, theirs| own | theirs); + assert!(!read.equals(own.words())); + own.combine(read, |own, theirs| own & theirs); + assert!(read.equals(own.words()) && own.words().equals(read)); + } + assert_eq!(longer, CallerSet::with_words(&[default, 0, 0])); + // And it is changed by its one word: it has room for 64 features, + // and takes of a longer set what it has room for. + let longer = CallerSet::with_words(&[2, 1, 1]); + let mut short = [0]; + let mut changed = SetWordsMut { + first: short.as_mut_ptr(), + count: short.len(), + set: PhantomData, + }; + assert!(changed.change(64, true).is_ok() && changed.change(1, true).is_ok()); + assert!(changed.change(1, false).is_ok() && changed.words().has(64)); + for none in [0, 65, FeatureNumber::MAX] { + assert_eq!(changed.change(none, true).unwrap_err().errno, libc::EINVAL); + assert_eq!(changed.change(none, false).unwrap_err().errno, libc::EINVAL); + } + // SAFETY: the set is as long as its size says. + let other = unsafe { SetWords::new(longer.as_ptr()) }.unwrap(); + changed.combine(other, |own, theirs| own | theirs); + assert!(!changed.words().equals(other) && !other.equals(changed.words())); + assert_eq!((changed.words().next(0), changed.words().next(2)), (2, 64)); + assert_eq!(changed.words().next(64), 0); + changed.combine(other, |own, theirs| own & !theirs); + assert_eq!(short, [1 << 63]); + + // Through the calls: the options take the features of a set or + // stay as they are, and an object keeps the fields of those of a + // set or stays as it is. + let mut options = uapi16_manifest_options::new(); + let mut file = object(c"file"); + file.set_mode(0o644).unwrap(); + file.file_mut().unwrap().set_size(Some(1)); + file.inode_mut().unwrap().set_mtime_nsec(Some(1)); + let stated = file.stated_features(); + // SAFETY: the sets are as long as their sizes say, and the options + // and the object are there. + unsafe { + for refused in [ + CallerSet::with_words(&[known + 1, 0]), + CallerSet::with_words(&[1, 1]), + CallerSet::with_words(&[1, 0, 1]), + ] { + let errno = if refused.words().len() > 2 { + libc::E2BIG + } else { + libc::EINVAL + }; + assert_eq!( + uapi16_manifest_options_set_features(&mut options, refused.as_ptr()), + -errno + ); + assert_eq!(options.features(), Features::DEFAULT); + assert_eq!(uapi16_file_object_retain_features(&mut file, refused.as_ptr()), -errno); + assert_eq!(file.stated_features(), stated); + } + let kept = Features::MODE | Features::MTIME | Features::SHA256; + for words in [2, 3, CallerSet::WORDS_MAX] { + let set = CallerSet::of(words, &numbers_of(kept)); + assert_eq!(uapi16_manifest_options_set_features(&mut options, set.as_ptr()), 0); + assert_eq!(options.features(), kept); + assert_eq!( + uapi16_manifest_options_set_features(&mut options, CallerSet::of(words, &[]).as_ptr()), + 0 + ); + assert_eq!(options.features(), Features::NONE); + } + assert_eq!( + uapi16_file_object_retain_features(&mut file, CallerSet::of(3, &numbers_of(kept)).as_ptr()), + 0 + ); + assert_eq!(file.stated_features(), Features::MODE | Features::MTIME); + // What an object states goes back into it. + let mut own = CallerSet::of(2, &[]); + assert_eq!(uapi16_file_object_stated_features(&file, own.as_mut_ptr()), 0); + assert_eq!(own.features(), numbers_of(Features::MODE | Features::MTIME)); + assert_eq!(uapi16_file_object_retain_features(&mut file, own.as_ptr()), 0); + assert_eq!(file.stated_features(), Features::MODE | Features::MTIME); + assert_eq!( + uapi16_file_object_retain_features(&mut file, CallerSet::of(2, &[]).as_ptr()), + 0 + ); + assert_eq!(file.stated_features(), Features::NONE); + } + } + + /// What a caller passes is checked before it is used: names, flags, + /// bits, orders, descriptors, bytes and places. + #[test] + fn checks_what_a_caller_passes() { + let misuse = |e: uapi16_error| { + assert_eq!( + (e.kind, e.errno), + (uapi16_error_kind_t::UAPI16_ERROR_INVALID_ARGUMENT, libc::EINVAL) + ); + e.name_problem + }; + assert_eq!(Name::of_text(text(c"")).unwrap(), Name::ROOT); + assert_eq!(Name::of_text(text(c"a/b")).unwrap().as_str(), "a/b"); + assert_eq!(misuse(Name::of_text(Text(None)).unwrap_err()), None); + for (name, problem) in [ + (c"a//b", uapi16_name_problem_t::UAPI16_NAME_PROBLEM_EMPTY_COMPONENT), + (c"a/../b", uapi16_name_problem_t::UAPI16_NAME_PROBLEM_DOT_COMPONENT), + (c"\xff", uapi16_name_problem_t::UAPI16_NAME_PROBLEM_NOT_UTF8), + (c"Uapi16Manifest", uapi16_name_problem_t::UAPI16_NAME_PROBLEM_RESERVED), + (c"a\x01", uapi16_name_problem_t::UAPI16_NAME_PROBLEM_CONTROL_CHARACTER), + ] { + assert_eq!( + misuse(Name::of_text(text(name)).unwrap_err()), + Some(problem), + "{:?}", + name + ); + } + + assert_eq!(AddFlags::of_bits(0).unwrap(), AddFlags::NONE); + assert_eq!( + AddFlags::of_bits(3).unwrap(), + AddFlags::CROSS_MOUNTS | AddFlags::GRACEFUL + ); + for bits in [1 << 2, 1 << 63, u64::MAX] { + misuse(AddFlags::of_bits(bits).unwrap_err()); + } + assert_eq!(Order::of_number(1).unwrap(), Some(Order::CodePoint)); + assert_eq!(Order::of_number(0).unwrap(), None); + for number in [2, u64::MAX] { + misuse(Order::of_number(number).unwrap_err()); + } + for (c, rust) in Order::ALL { + assert_eq!(Order::number(rust), c); + } + + for none in [-1, libc::AT_FDCWD, c_int::MIN] { + let e = Descriptor(none, PhantomData).borrow().unwrap_err(); + assert_eq!( + (e.kind, e.errno), + (uapi16_error_kind_t::UAPI16_ERROR_INVALID_ARGUMENT, libc::EBADF) + ); + } + + // The name of a new file is bytes, and names a file below a + // directory. + let file_name = |name| uapi16_manifest_options::file_name(text(name)); + assert_eq!( + file_name(c"sub/caf\xe9").unwrap().as_os_str().as_bytes(), + b"sub/caf\xe9" + ); + for name in [c"", c"/m", c"./m", c"../m", c"sub/../m", c"sub/"] { + misuse(file_name(name).unwrap_err()); + } + misuse(uapi16_manifest_options::file_name(Text(None)).unwrap_err()); + + // No bytes are no pointer to look at. Some bytes need one. + // SAFETY: nothing is read for a size of 0, and NULL is not read + // through either. + let (none, missing) = unsafe { (Bytes::new(ptr::null(), 0), Bytes::new(ptr::null(), 1)) }; + assert_eq!(none.get().unwrap(), b""); + misuse(missing.get().unwrap_err()); + let three = *b"abc"; + // SAFETY: `three` is three bytes, which stay as they are. + let some = unsafe { Bytes::new(three.as_ptr().cast(), three.len()) }; + assert_eq!(some.get().unwrap(), b"abc"); + // A size that nothing in memory has is refused like bytes that are + // missing. + for size in [isize::MAX.unsigned_abs() + 1, usize::MAX] { + // SAFETY: nothing is read through the pointer for such a size. + let huge = unsafe { Bytes::new(three.as_ptr().cast(), size) }; + misuse(huge.get().unwrap_err()); + } + // SAFETY: as above. NULL takes the bytes of a signature away, and + // an empty key is a key. + let (gone, empty) = unsafe { + ( + uapi16_signature::bytes(ptr::null(), 3), + uapi16_signature::bytes(three.as_ptr().cast(), 0), + ) + }; + assert!(gone.is_none()); + assert_eq!(empty.unwrap().get().unwrap(), b""); + + // A place is written to once, and one that is needed is not NULL. + let mut number = 0u64; + // SAFETY: `number` is a local that nothing else uses. + unsafe { Place::new(&mut number) }.needed().unwrap().store(7); + assert_eq!(number, 7); + // SAFETY: NULL is no place, and nothing is written to it. + let nowhere = unsafe { Place::::new(ptr::null_mut()) }; + misuse(nowhere.needed().unwrap_err()); + // SAFETY: as above. + unsafe { Place::::new(ptr::null_mut()) }.store(1); + + // A string that is no UTF-8 has an order all the same. + assert_eq!(Text(None).lossy(), ""); + assert_eq!(text(c"a\xffb").lossy(), "a\u{fffd}b"); + } + + /// A file object stores what it is given and gives it back, and what it + /// was not given is not there. The strings it hands out end in a NUL + /// and stay where they are until the object is given others. + #[test] + fn file_objects() { + let absent = |e: uapi16_error| assert_eq!(e.errno, libc::ENODATA); + let mut o = object(c"dir/file"); + // SAFETY: name() returns a string of the object, which is not + // changed while it is read. + let name = |o: &uapi16_file_object| unsafe { CStr::from_ptr(o.name()) }.to_owned(); + assert_eq!(name(&o).as_c_str(), c"dir/file"); + assert_eq!(o.name(), o.name()); + assert_eq!(o.object.inode_type().st_mode(), libc::S_IFREG); + assert!(!o.is_root()); + + o.set_name(text(c"dir/other")).unwrap(); + assert_eq!(name(&o).as_c_str(), c"dir/other"); + assert_eq!(o.set_name(text(c"")).unwrap_err().errno, libc::EINVAL); + assert_eq!(o.set_name(text(c"a//b")).unwrap_err().errno, libc::EINVAL); + assert_eq!(name(&o).as_c_str(), c"dir/other"); + + for (inode_type, st_mode) in InodeType::ST_MODES { + o.set_type(st_mode | 0o777).unwrap(); + assert_eq!(o.object.inode_type(), inode_type); + assert_eq!(inode_type.st_mode(), st_mode); + } + assert_eq!(o.set_type(0).unwrap_err().errno, libc::EINVAL); + assert_eq!(o.set_type(0o777).unwrap_err().errno, libc::EINVAL); + o.set_type(libc::S_IFREG).unwrap(); + + absent(o.inode().unwrap().mode().ok_or_else(uapi16_error::absent).unwrap_err()); + o.set_mode(libc::S_IFREG | 0o4755).unwrap(); + assert_eq!(o.object.inode().mode().map(Mode::bits), Some(0o4755)); + assert_eq!(o.object.inode_type(), InodeType::Regular); + // A bit that is neither of the file type nor of the mode is refused. + for no_mode in [(libc::S_IFMT | 0o7777) + 1, !libc::S_IFMT] { + assert_eq!(o.set_mode(no_mode).unwrap_err().errno, libc::EINVAL); + } + assert_eq!(o.object.inode().mode().map(Mode::bits), Some(0o4755)); + + assert!(o.user_name().is_null() && o.group_name().is_null() && o.fs_label().is_null()); + o.set_user_name(text(c"root")).unwrap(); + o.set_group_name(text(c"wheel")).unwrap(); + // SAFETY: the two return strings of the object, which is not changed + // while they are read. + let (user, group) = unsafe { (CStr::from_ptr(o.user_name()), CStr::from_ptr(o.group_name())) }; + assert_eq!((user, group), (c"root", c"wheel")); + assert_eq!(o.user_name(), o.user_name()); + assert_eq!(o.set_user_name(text(c"\xff")).unwrap_err().errno, libc::EINVAL); + assert_eq!(o.set_user_name(Text(None)).unwrap_err().errno, libc::EINVAL); + assert_eq!(o.object.inode().user_name(), Some("root")); + + o.set_inode_token(7).unwrap(); + assert_eq!(o.object.inode_token().map(NonZeroU64::get), Some(7)); + o.set_inode_token(UAPI16_INODE_TOKEN_NONE).unwrap(); + assert_eq!(o.object.inode_token(), None); + + // Extended attributes: none said, none there, and some, in the + // order of their names. + absent(o.user_xattrs().unwrap_err()); + assert_eq!(o.user_xattr(0).unwrap_err().errno, libc::EINVAL); + o.set_user_xattrs().unwrap(); + assert_eq!(o.user_xattrs().unwrap(), 0); + o.add_user_xattr(text(c"b"), bytes(b"two")).unwrap(); + o.add_user_xattr(text(c"a"), bytes(b"")).unwrap(); + o.add_user_xattr(text(c"b"), bytes(b"2\x00")).unwrap(); + assert_eq!(o.user_xattrs().unwrap(), 2); + let xattr = |o: &uapi16_file_object, i| { + let (name, value, size) = o.user_xattr(i).unwrap(); + // SAFETY: the name is a string of the object and the value + // `size` of its bytes, and the object is not changed meanwhile. + unsafe { + ( + CStr::from_ptr(name).to_owned(), + slice::from_raw_parts(value.cast::(), size).to_vec(), + ) + } + }; + assert_eq!(xattr(&o, 0), (c"a".to_owned(), b"".to_vec())); + assert_eq!(xattr(&o, 1), (c"b".to_owned(), b"2\x00".to_vec())); + assert_eq!(o.user_xattr(2).unwrap_err().errno, libc::EINVAL); + // The number of an attribute is checked before the process is, as + // what a call is given comes first. + if let Some(elsewhere) = Process::elsewhere() { + let made = mem::replace(&mut o.process, elsewhere); + assert_eq!(o.user_xattr(2).unwrap_err().errno, libc::EINVAL); + assert_eq!(o.user_xattr(0).unwrap_err().errno, libc::ECHILD); + o.process = made; + } + o.set_user_xattrs().unwrap(); + assert_eq!(o.user_xattrs().unwrap(), 0); + // None of the names that were handed out is one of its attributes. + assert_eq!(o.user_xattr(0).unwrap_err().errno, libc::EINVAL); + // The names that were handed out are made anew after every change: + // of all the attributes, and of one that is added. + o.add_user_xattr(text(c"z"), bytes(b"1")).unwrap(); + assert_eq!(xattr(&o, 0), (c"z".to_owned(), b"1".to_vec())); + o.add_user_xattr(text(c"y"), bytes(b"2")).unwrap(); + assert_eq!(xattr(&o, 0), (c"y".to_owned(), b"2".to_vec())); + assert_eq!(xattr(&o, 1), (c"z".to_owned(), b"1".to_vec())); + o.set_user_xattrs().unwrap(); + + // Whether it is read-only has three answers, and a setter for + // each. + for (c, rust) in uapi16_read_only_t::ALL { + o.set_read_only(c as u64).unwrap(); + assert_eq!(o.object.inode().read_only(), rust); + assert_eq!(uapi16_read_only_t::of(rust), c); + } + assert_eq!(o.set_read_only(3).unwrap_err().errno, libc::EINVAL); + assert_eq!(o.object.inode().read_only(), Some(true)); + + // The flags of the two kinds: what is stated, and what of it is + // set. A flag that is not stated is taken away. + assert_eq!(o.inode_flags().unwrap(), (0, 0)); + o.set_inode_flags(0x20 | 0x10 | 0x1, 0x20 | 0x40).unwrap(); + assert_eq!(o.inode_flags().unwrap(), (0x20 | 0x10, 0x20)); + o.set_inode_flags(0x0080_0000, 0).unwrap(); + assert_eq!(o.inode_flags().unwrap(), (0x0080_0000, 0)); + assert_eq!(o.dos_attributes().unwrap(), (0, 0)); + o.set_dos_attributes(0x02 | 0x20 | 0x01, 0x20 | 0x04).unwrap(); + assert_eq!(o.dos_attributes().unwrap(), (0x02 | 0x20, 0x20)); + + // Where the data is. An object that refers to another file names + // it, with a string of its own that stays until it refers to + // another one. + assert_eq!(o.data_location(), uapi16_data_location_t::UAPI16_DATA_LOCATION_EXTERNAL); + assert_eq!(o.literal(), None); + absent(o.contents_file().unwrap_err()); + o.set_contents_file(text(c"blobs/1")).unwrap(); + assert_eq!(o.data_location(), uapi16_data_location_t::UAPI16_DATA_LOCATION_EXTERNAL); + let named = |o: &uapi16_file_object| { + let (file, offset) = o.contents_file().unwrap(); + // SAFETY: the name is a string of the object, which is not + // changed while this reads it. + (unsafe { CStr::from_ptr(file) }.to_owned(), offset) + }; + assert_eq!(named(&o), (c"blobs/1".to_owned(), 0)); + assert_eq!(o.contents_file().unwrap().0, o.contents_file().unwrap().0); + o.set_contents_file(text(c"blobs/2")).unwrap(); + assert_eq!(named(&o), (c"blobs/2".to_owned(), 0)); + // The file of its own name is no other file. + let own = CString::new(o.object.name().as_str()).unwrap(); + o.set_contents_file(text(&own)).unwrap(); + absent(o.contents_file().unwrap_err()); + o.set_contents_file(text(c"blobs/1")).unwrap(); + let empty = o.set_contents_file(text(c"")).unwrap_err(); + assert_eq!( + empty.name_problem, + Some(uapi16_name_problem_t::UAPI16_NAME_PROBLEM_EMPTY) + ); + o.set_type(libc::S_IFLNK).unwrap(); + o.set_target(bytes(b"to\xff")).unwrap(); + assert_eq!(o.data_location(), uapi16_data_location_t::UAPI16_DATA_LOCATION_LITERAL); + assert_eq!(o.literal(), Some(&b"to\xff"[..])); + let mut fifo = object(c"fifo"); + fifo.set_type(libc::S_IFIFO).unwrap(); + assert_eq!(fifo.data_location(), uapi16_data_location_t::UAPI16_DATA_LOCATION_NONE); + + // What the object states, as the features of its fields. + let mut plain = object(c"plain"); + assert_eq!(plain.stated_features(), Features::NONE); + plain.set_mode(0o644).unwrap(); + plain.file_mut().unwrap().set_size(Some(1)); + assert_eq!(plain.stated_features(), Features::MODE | Features::SIZE); + plain.check_validity(0).unwrap(); + plain.as_file().unwrap(); + assert_eq!(plain.as_root().unwrap_err().errno, libc::EINVAL); + } + + /// The root is the object with the empty name, a directory. A setter + /// stores what it is given there as well, and a writer refuses a root + /// with what only another file object has, and any other object with + /// what only the root has. + #[test] + fn roots() { + let refused = |e: uapi16_error, field: &CStr| { + assert_eq!( + (e.kind, e.errno), + (uapi16_error_kind_t::UAPI16_ERROR_MANIFEST, libc::EBADMSG) + ); + assert_eq!(e.problem, Some(Problem::FieldNotPermitted)); + assert_eq!(e.field.and_then(Field::c_name), Some(field)); + e.path + }; + let mut root = object(c""); + assert!(root.is_root()); + assert_eq!(root.object.inode_type().st_mode(), libc::S_IFDIR); + root.set_type(libc::S_IFDIR).unwrap(); + assert_eq!(root.set_type(libc::S_IFREG).unwrap_err().errno, libc::EINVAL); + assert_eq!(root.set_name(text(c"a")).unwrap_err().errno, libc::EINVAL); + root.set_mode(0o755).unwrap(); + root.set_fs_label(text(c"label")).unwrap(); + root.file_system_mut().unwrap().set_fat_serial(Some(FatSerial::new(7))); + // SAFETY: fs_label() returns a string of the object, which is not + // changed while it is read. + assert_eq!(unsafe { CStr::from_ptr(root.fs_label()) }, c"label"); + assert_eq!( + root.stated_features(), + Features::MODE | Features::FS_LABEL | Features::FAT_SERIAL + ); + let written = root.as_root().unwrap(); + assert_eq!(written.inode().mode().map(Mode::bits), Some(0o755)); + assert_eq!(written.file_system().label(), Some("label")); + assert_eq!(written.file_system().fat_serial().map(FatSerial::get), Some(7)); + + // What a root can't have is stored, and refused when it is written. + type Setter = fn(&mut uapi16_file_object); + let setters: [(&CStr, Setter); 6] = [ + (c"size", |o| o.file_mut().unwrap().set_size(Some(1))), + (c"sha256", |o| o.file_mut().unwrap().set_sha256(Some(Sha256::EMPTY))), + (c"contents", |o| o.set_target(Bytes(Some(b"t"))).unwrap()), + (c"inodeToken", |o| o.set_inode_token(1).unwrap()), + (c"major", |o| o.file_mut().unwrap().set_major(Some(1))), + (c"flagHidden", |o| o.set_dos_attributes(0x02, 0).unwrap()), + ]; + for (field, set) in setters { + let mut root = object(c""); + set(&mut root); + assert_eq!(refused(root.as_root().unwrap_err(), field).as_deref(), Some(c"")); + } + + // The other way round. + let mut file = object(c"a/file"); + file.as_file().unwrap(); + file.set_fs_label(text(c"label")).unwrap(); + assert_eq!( + refused(file.as_file().unwrap_err(), c"fsLabel").as_deref(), + Some(c"a/file") + ); + let mut file = object(c"a/file"); + file.file_system_mut() + .unwrap() + .set_uuid(Some(Uuid::new([1; Uuid::SIZE]))); + refused(file.as_file().unwrap_err(), c"fsUUID"); + + // A root that a reader read keeps what no setter sets. + let mut read = RootObject::default(); + read.inode_mut().set_uid(Some(1)); + read.set_gpt_disk_uuid(Some(Uuid::new([2; Uuid::SIZE]))); + read.set_features(Some(Features::UID)); + let handed_out = uapi16_file_object::of_root(&read); + assert!(handed_out.is_root()); + let mut back = handed_out.as_root().unwrap(); + back.set_features(read.features()); + assert_eq!(back, read); + // A manifest writer lists the root directory and its file system, + // and no more: it refuses a root with what only a manifest that + // was read can say of it. + refused(handed_out.as_tree_root().unwrap_err(), c"gptDiskUuid"); + type Window = fn(&mut ValidityWindow); + let validity: [(&CStr, Window); 3] = [ + (c"validSinceUSec", |window| window.set_since_usec(1)), + (c"validUntilUSec", |window| window.set_until_usec(Some(2))), + (c"validity", |window| window.set_state(Validity::Revoked)), + ]; + for (field, set) in validity { + let mut read = RootObject::default(); + let mut window = read.validity(); + set(&mut window); + read.set_validity(window); + let handed_out = uapi16_file_object::of_root(&read); + handed_out.as_root().unwrap(); + refused(handed_out.as_tree_root().unwrap_err(), field); + } + root.as_tree_root().unwrap(); + } + + /// An error about the root names it: the empty string. A reader says so + /// for a field of the root record that it refuses, and not for a record + /// that is no root at all. So does the check of when a root may be + /// used. + #[test] + fn errors_about_the_root() { + let out = TempDir::new("capi-root-errors"); + let open = |root: &str| { + let mut file = tempfile(&out); + file.write_all(format!("\x1e{}\n", root).as_bytes()).unwrap(); + file.rewind().unwrap(); + // SAFETY: no reader is made, and the file is open during the + // call. + unsafe { uapi16_reader::open(descriptor(&file)) }.unwrap_err() + }; + let refused = open("{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"size\":1}"); + assert_eq!(refused.problem, Some(Problem::FieldNotPermitted)); + assert_eq!((refused.field, refused.record), (Some(Field::Size), Some(0))); + assert_eq!(refused.path.as_deref(), Some(c"")); + let no_directory = open("{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"type\":\"reg\"}"); + assert_eq!(no_directory.problem, Some(Problem::RootNotDirectory)); + assert_eq!(no_directory.path.as_deref(), Some(c"")); + // A root with a name has that name. + let named = open("{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"name\":\"x\"}"); + assert_eq!(named.path.as_deref(), Some(c"x")); + // What is no root record is about no file. + for no_root in ["{\"mediaType\":\"nope\"}", "nope"] { + let e = open(no_root); + assert_eq!(e.kind, uapi16_error_kind_t::UAPI16_ERROR_MANIFEST); + assert_eq!((e.path, e.record), (None, Some(0))); + } + let mut revoked = RootObject::default(); + let mut window = revoked.validity(); + window.set_state(Validity::Revoked); + revoked.set_validity(window); + let e = uapi16_file_object::of_root(&revoked).check_validity(0).unwrap_err(); + assert_eq!(e.kind, uapi16_error_kind_t::UAPI16_ERROR_REVOKED); + assert_eq!(e.path.as_deref(), Some(c"")); + } + + /// A manifest writer takes the root as the object with the empty name: + /// the manifest says of its root directory and its file system what + /// that object says. The first root that is added counts, and one with + /// a field the manifest does not record is refused and adds nothing. + #[test] + fn root_adds() { + let out = TempDir::new("capi-root-adds"); + let mut options = uapi16_manifest_options::new(); + let features = Features::MODE | Features::FS_LABEL | Features::FS_UUID; + options.set_features(features).unwrap(); + let into = tempfile(&out); + { + // SAFETY: `into` is open until the writer was dropped. + let mut writer = unsafe { options.open(descriptor(&into)) }.unwrap(); + let mut refused = object(c""); + refused.set_mode(0o700).unwrap(); + refused + .file_system_mut() + .unwrap() + .set_fat_serial(Some(FatSerial::new(7))); + let unlisted = writer.add_object(&refused).unwrap_err(); + assert_eq!(unlisted.kind, uapi16_error_kind_t::UAPI16_ERROR_MANIFEST); + assert_eq!(unlisted.problem, Some(Problem::UnlistedFeature)); + assert_eq!(unlisted.field, Some(Field::FatSerial)); + // An error about the root names it: the empty string. It is + // about no record: a manifest writer has none until it finishes. + assert_eq!(unlisted.path.as_deref(), Some(c"")); + assert_eq!(unlisted.record, None); + // A writer of records refuses the root as the record it would + // have been, the first one, whoever finds what is wrong with it. + // SAFETY: no writer is made, so nothing keeps `into`. + let begun = unsafe { uapi16_writer::begin(&options, descriptor(&into), Some(&refused)) }; + let begun = begun.unwrap_err(); + assert_eq!(begun.problem, Some(Problem::UnlistedFeature)); + assert_eq!(begun.path.as_deref(), Some(c"")); + assert_eq!(begun.record, Some(ROOT_RECORD)); + let mut with_size = object(c""); + with_size.file_mut().unwrap().set_size(Some(1)); + // SAFETY: as above. + let begun = unsafe { uapi16_writer::begin(&options, descriptor(&into), Some(&with_size)) }; + let begun = begun.unwrap_err(); + assert_eq!(begun.problem, Some(Problem::FieldNotPermitted)); + assert_eq!(begun.record, Some(ROOT_RECORD)); + let not_permitted = writer.add_object(&with_size).unwrap_err(); + assert_eq!(not_permitted.problem, Some(Problem::FieldNotPermitted)); + assert_eq!(not_permitted.path.as_deref(), Some(c"")); + assert_eq!(not_permitted.record, None); + + writer.add_object(&object(c"file")).unwrap(); + let mut root = object(c""); + root.set_mode(0o750).unwrap(); + root.set_fs_label(text(c"label")).unwrap(); + let uuid = Uuid::new([3; Uuid::SIZE]); + root.file_system_mut().unwrap().set_uuid(Some(uuid)); + writer.add_object(&root).unwrap(); + // Added twice, the first one says what the root is like. + let mut again = object(c""); + again.set_mode(0o755).unwrap(); + writer.add_object(&again).unwrap(); + let report = writer.finish().unwrap().report; + assert_eq!((report.files(), report.directories()), (1, 1)); + } + (&into).rewind().unwrap(); + // SAFETY: the reader is dropped before `into`. + let reader = unsafe { reader_of(&into) }; + let read = reader.reader.root(); + assert_eq!(read.inode().mode().map(Mode::bits), Some(0o750)); + assert_eq!(read.file_system().label(), Some("label")); + assert_eq!(read.file_system().uuid(), Some(Uuid::new([3; Uuid::SIZE]))); + assert_eq!(read.file_system().fat_serial(), None); + assert_eq!(read.features(), Some(features)); + } + + /// The features an object states are those of its file object and of + /// the root it would be. The two getters answer from the fields that + /// are there, without a copy of what is in them, so the answer is held + /// against that of a whole root here: for every set of the fields that + /// only the root has, with and without inode attributes, under the + /// name of the root and under another one. + #[test] + fn stated_features() { + type Setter = fn(&mut uapi16_file_object); + let only_the_root_has: [(Features, Setter); 4] = [ + (Features::FS_LABEL, |o| o.set_fs_label(text(c"label")).unwrap()), + (Features::FS_UUID, |o| { + o.file_system_mut().unwrap().set_uuid(Some(Uuid::new([1; Uuid::SIZE]))) + }), + (Features::FAT_SERIAL, |o| { + o.file_system_mut().unwrap().set_fat_serial(Some(FatSerial::new(7))) + }), + (Features::GPT_DISK_UUID, |o| { + o.gpt_disk_uuid = Some(Uuid::new([2; Uuid::SIZE])) + }), + ]; + for name in [c"", c"dir/file"] { + for chosen in 0..1usize << only_the_root_has.len() { + for with_inode_attributes in [false, true] { + let mut o = object(name); + let mut expected = Features::NONE; + if with_inode_attributes { + o.set_mode(0o755).unwrap(); + o.set_user_xattrs().unwrap(); + o.add_user_xattr(text(c"key"), bytes(b"value")).unwrap(); + expected |= Features::MODE | Features::USER_XATTR; + } + for (place, (feature, set)) in only_the_root_has.iter().enumerate() { + if chosen & (1 << place) != 0 { + set(&mut o); + expected |= *feature; + } + } + assert_eq!(o.stated_features(), expected); + assert_eq!( + o.stated_features(), + o.object.stated_features() | o.root().stated_features() + ); + } + } + } + } + + /// The check of when an object may be used answers for the root what a + /// whole root answers, with the same error, and without a copy of what + /// the object holds: for every validity, at times before, in and after + /// it, for a root with and without inode attributes and a label. A file + /// is checked as itself. + #[test] + fn validity_checks() { + const TIMES: [u64; 4] = [0, 15, 25, u64::MAX]; + type Window = fn(&mut ValidityWindow); + // Each with the times of TIMES at which it holds. + let windows: [(Window, [bool; TIMES.len()]); 4] = [ + (|_| {}, [true, true, true, true]), + (|window| window.set_since_usec(10), [false, true, true, true]), + (|window| window.set_until_usec(Some(20)), [true, true, false, false]), + ( + |window| window.set_state(Validity::Revoked), + [false, false, false, false], + ), + ]; + // Every field of an error, to hold one error against another. + let said = |checked: Result<(), uapi16_error>| checked.map_err(|e| format!("{:?}", e)); + for (set, holds) in windows { + let mut window = ValidityWindow::default(); + set(&mut window); + for with_fields in [false, true] { + let mut read = RootObject::default(); + read.set_validity(window); + let mut root = uapi16_file_object::of_root(&read); + let mut file = object(c"dir/file"); + file.object.set_validity(window); + if with_fields { + for o in [&mut root, &mut file] { + o.set_mode(0o755).unwrap(); + o.set_user_xattrs().unwrap(); + o.add_user_xattr(text(c"key"), bytes(b"value")).unwrap(); + o.set_fs_label(text(c"label")).unwrap(); + } + } + for (now, valid) in TIMES.into_iter().zip(holds) { + let whole = root.root().check_validity(now); + let whole = whole.map_err(|e| uapi16_error::from(e).about(Name::ROOT)); + assert_eq!(root.check_validity(now).is_ok(), valid); + assert_eq!(said(root.check_validity(now)), said(whole)); + let itself = file.object.check_validity(now).map_err(uapi16_error::from); + assert_eq!(file.check_validity(now).is_ok(), valid); + assert_eq!(said(file.check_validity(now)), said(itself)); + } + } + } + } + + /// An object keeps the fields of the features it is told to retain, and + /// loses the others, also what only the root has. The name, the type + /// and what belongs to no feature stay. A string the object handed out + /// stays where it is as long as its field does. + #[test] + fn retained_features() { + let mut o = object(c"dir/file"); + o.set_mode(libc::S_IFREG | 0o644).unwrap(); + o.inode_mut().unwrap().set_uid(Some(1)); + o.set_user_name(text(c"user")).unwrap(); + o.set_group_name(text(c"group")).unwrap(); + o.file_mut().unwrap().set_size(Some(3)); + o.set_user_xattrs().unwrap(); + o.add_user_xattr(text(c"key"), bytes(b"value")).unwrap(); + o.set_inode_token(4).unwrap(); + o.set_contents_file(text(c"blobs/1")).unwrap(); + let (name, user, group) = (o.name(), o.user_name(), o.group_name()); + assert!(!user.is_null() && !group.is_null()); + assert_eq!(o.user_xattr(0).map(|(name, _, _)| name.is_null()).ok(), Some(false)); + let all = o.stated_features(); + assert!(all.contains(Features::MODE | Features::UID | Features::USER_NAME | Features::GROUP_NAME)); + + // Every feature it has: nothing changes. + o.retain_features(all).unwrap(); + assert_eq!(o.stated_features(), all); + assert_eq!((o.name(), o.user_name(), o.group_name()), (name, user, group)); + + let kept = Features::MODE | Features::USER_NAME | Features::SIZE; + o.retain_features(kept).unwrap(); + assert_eq!(o.stated_features(), kept); + assert_eq!(o.object.inode().mode().map(Mode::bits), Some(0o644)); + assert_eq!((o.object.inode().uid(), o.object.size()), (None, Some(3))); + assert_eq!(o.object.inode_token(), None); + // The name of the user stays where it was, and the name of the + // group is gone, with the extended attributes. + assert_eq!((o.name(), o.user_name()), (name, user)); + assert!(o.group_name().is_null()); + assert_eq!(o.user_xattrs().unwrap_err().errno, libc::ENODATA); + assert_eq!(o.user_xattr(0).unwrap_err().errno, libc::EINVAL); + // The names of the attributes that went are not handed out for the + // ones that come after them. + o.add_user_xattr(text(c"later"), bytes(b"1")).unwrap(); + let (later, _, _) = o.user_xattr(0).unwrap(); + // SAFETY: the name is a string of the object, which is there. + assert_eq!(unsafe { CStr::from_ptr(later) }, c"later"); + o.set_user_xattrs().unwrap(); + o.retain_features(kept).unwrap(); + // What belongs to no feature stays. + assert_eq!(o.object.inode_type(), InodeType::Regular); + assert_eq!(o.object.contents().len(), 1); + + // No feature at all. + o.retain_features(Features::NONE).unwrap(); + assert_eq!(o.stated_features(), Features::NONE); + assert!(o.user_name().is_null()); + assert_eq!(o.name(), name); + + // The root loses what only it has the same way. + let mut root = object(c""); + root.set_mode(0o755).unwrap(); + root.set_fs_label(text(c"label")).unwrap(); + root.file_system_mut().unwrap().set_fat_serial(Some(FatSerial::new(7))); + root.file_system_mut() + .unwrap() + .set_uuid(Some(Uuid::new([1; Uuid::SIZE]))); + let label = root.fs_label(); + root.retain_features(Features::FS_LABEL | Features::FS_UUID).unwrap(); + assert_eq!(root.stated_features(), Features::FS_LABEL | Features::FS_UUID); + assert_eq!(root.fs_label(), label); + assert_eq!(root.file_system.fat_serial(), None); + root.retain_features(Features::FS_UUID).unwrap(); + assert!(root.fs_label().is_null()); + assert_eq!(root.stated_features(), Features::FS_UUID); + // The UUID goes like the label and the serial. + let mut other = object(c""); + other + .file_system_mut() + .unwrap() + .set_uuid(Some(Uuid::new([1; Uuid::SIZE]))); + other.retain_features(Features::FS_LABEL).unwrap(); + assert_eq!(other.file_system.uuid(), None); + assert_eq!(other.stated_features(), Features::NONE); + // The UUID of a disk, which only a root that was read has, stays + // with its feature and goes without it. + let mut read = RootObject::default(); + read.set_gpt_disk_uuid(Some(Uuid::new([2; Uuid::SIZE]))); + let mut handed_out = uapi16_file_object::of_root(&read); + assert!(handed_out.gpt_disk_uuid.is_some()); + handed_out.retain_features(Features::GPT_DISK_UUID).unwrap(); + assert_eq!(handed_out.gpt_disk_uuid, read.gpt_disk_uuid()); + handed_out.retain_features(Features::MODE).unwrap(); + assert_eq!(handed_out.gpt_disk_uuid, None); + + // Another process. + if let Some(elsewhere) = Process::elsewhere() { + root.process = elsewhere; + assert_eq!(root.retain_features(Features::NONE).unwrap_err().errno, libc::ECHILD); + assert_eq!(root.stated_features(), Features::FS_UUID); + } + } + + /// Zero bytes that a caller did not read count as data: for a hash and + /// for a check of data, which takes no more of them than its object + /// has room for. + #[test] + fn zeros() { + const HOLE: u64 = 70_000; + let mut data = b"head".to_vec(); + data.resize(data.len() + HOLE as usize, 0); + data.extend_from_slice(b"tail"); + let mut sha256 = uapi16_sha256::new(); + sha256.update(bytes(b"head")).unwrap(); + sha256.update_zeros(HOLE).unwrap(); + sha256.update_zeros(0).unwrap(); + sha256.update(bytes(b"tail")).unwrap(); + let hash = Sha256::from(sha256.finish().unwrap()); + assert_eq!(hash, Sha256::digest(&data)); + assert_eq!(sha256.update_zeros(1).unwrap_err().errno, libc::ESTALE); + + let mut o = object(c"sparse"); + let file = o.file_mut().unwrap(); + file.set_size(Some(data.len() as u64)); + file.set_sha256(Some(hash)); + let mut check = uapi16_data_check::new(&o).unwrap(); + check.update(bytes(b"head")).unwrap(); + check.update_zeros(HOLE).unwrap(); + check.update(bytes(b"tail")).unwrap(); + assert_eq!(check.finish().unwrap(), data.len() as u64); + assert_eq!(check.update_zeros(1).unwrap_err().errno, libc::ESTALE); + // More zero bytes than the object has room for are refused, as + // other bytes are, and none of them is taken. + let mut check = uapi16_data_check::new(&o).unwrap(); + check.update(bytes(b"head")).unwrap(); + let too_many = check.update_zeros(HOLE + 5).unwrap_err(); + assert_eq!(too_many.kind, uapi16_error_kind_t::UAPI16_ERROR_SIZE_MISMATCH); + check.update_zeros(HOLE).unwrap(); + check.update(bytes(b"tail")).unwrap(); + assert_eq!(check.finish().unwrap(), data.len() as u64); + // Zero bytes where the data has others are another hash. + let mut check = uapi16_data_check::new(&o).unwrap(); + check.update_zeros(data.len() as u64).unwrap(); + assert_eq!( + check.finish().unwrap_err().kind, + uapi16_error_kind_t::UAPI16_ERROR_HASH_MISMATCH + ); + let mut check = uapi16_data_check::new(&o).unwrap(); + if let Some(elsewhere) = Process::elsewhere() { + check.process = elsewhere; + assert_eq!(check.update_zeros(1).unwrap_err().errno, libc::ECHILD); + } + } + + /// A directory opens the file the data of a file object is in, below + /// the descriptor it has on loan, and says where the data starts. The + /// descriptor it returns is new, and the caller's. + #[test] + fn opened_data() { + let (tmp, top) = tree("capi-opened-data"); + fs::create_dir(tmp.0.join("blobs")).unwrap(); + fs::write(tmp.0.join("blobs/1"), b"0123456789").unwrap(); + std::os::unix::fs::symlink("a/file", tmp.0.join("link")).unwrap(); + let kind = |e: uapi16_error| (e.kind, e.errno); + let read = |opened: (OwnedFd, u64)| { + let mut data = Vec::new(); + File::from(opened.0).read_to_end(&mut data).unwrap(); + (data, opened.1) + }; + // SAFETY: the directories are dropped before `top`. + let directory = unsafe { uapi16_directory::new(descriptor(&top), 0) }.unwrap(); + let follow = uapi16_directory_flag_t::UAPI16_DIRECTORY_FOLLOW_SYMLINKS as u64; + // SAFETY: as above. + let following = unsafe { uapi16_directory::new(descriptor(&top), follow) }.unwrap(); + + // The file of its own name. + let mut file = object(c"a/file"); + let opened = directory.open_data(&file).unwrap(); + assert_ne!(opened.0.as_raw_fd(), top.as_raw_fd()); + assert_eq!(read(opened), (b"hello".to_vec(), 0)); + file.file_mut().unwrap().set_size(Some(5)); + assert_eq!(read(directory.open_data(&file).unwrap()).0, b"hello"); + // A file that is too short for the data. + file.file_mut().unwrap().set_size(Some(6)); + assert_eq!( + kind(directory.open_data(&file).unwrap_err()), + (uapi16_error_kind_t::UAPI16_ERROR_SIZE_MISMATCH, libc::EBADMSG) + ); + // The file the object refers to. + let mut blob = object(c"elsewhere"); + blob.set_contents_file(text(c"blobs/1")).unwrap(); + assert_eq!(read(directory.open_data(&blob).unwrap()), (b"0123456789".to_vec(), 0)); + // A manifest can say how long that file is. A file of another size, + // shorter or longer, is not the one it means. + let mut sized = object(c"sized"); + let mut contents = ContentsObject::new(ContentsSource::File(Name::new("blobs/1").unwrap().to_owned())); + for (original_size, fits) in [(10, true), (11, false), (9, false)] { + contents.set_original_size(Some(original_size)); + sized.file_mut().unwrap().set_contents(vec![contents.clone()]); + let opened = directory.open_data(&sized); + if fits { + assert_eq!(read(opened.unwrap()).0, b"0123456789"); + } else { + let mismatch = opened.unwrap_err(); + assert_eq!(mismatch.path.as_deref(), Some(c"sized")); + assert_eq!( + kind(mismatch), + (uapi16_error_kind_t::UAPI16_ERROR_SIZE_MISMATCH, libc::EBADMSG) + ); + } + } + + let missing = object(c"a/none"); + assert_eq!( + kind(directory.open_data(&missing).unwrap_err()), + (uapi16_error_kind_t::UAPI16_ERROR_SOURCE_MISSING, libc::ENOENT) + ); + let no_file = object(c"a"); + assert_eq!( + kind(directory.open_data(&no_file).unwrap_err()), + (uapi16_error_kind_t::UAPI16_ERROR_SOURCE_NOT_REGULAR, libc::EINVAL) + ); + // A symbolic link on the way is followed only where the directory + // was made to follow them. + let through = object(c"link"); + assert_eq!( + kind(directory.open_data(&through).unwrap_err()), + (uapi16_error_kind_t::UAPI16_ERROR_IO, libc::ELOOP) + ); + assert_eq!(read(following.open_data(&through).unwrap()).0, b"hello"); + + // Data that is in the manifest, and an object without data. + let unsupported = (uapi16_error_kind_t::UAPI16_ERROR_UNSUPPORTED, libc::EOPNOTSUPP); + let mut link = object(c"l"); + link.set_type(libc::S_IFLNK).unwrap(); + link.set_target(bytes(b"to")).unwrap(); + let carried = directory.open_data(&link).unwrap_err(); + assert_eq!(carried.path.as_deref(), Some(c"l")); + assert_eq!(kind(carried), unsupported); + let mut fifo = object(c"fifo"); + fifo.set_type(libc::S_IFIFO).unwrap(); + assert_eq!(kind(directory.open_data(&fifo).unwrap_err()), unsupported); + assert_eq!(kind(directory.open_data(&object(c"")).unwrap_err()), unsupported); + + // Through the pointers C has: nothing is stored where it fails, and + // both places are needed. + let (mut fd, mut offset) = (-7, 7u64); + let mut e: *mut uapi16_error = ptr::null_mut(); + // SAFETY: the objects are locals that live through the calls, and + // the places are locals too. + unsafe { + let (d, o): (*const uapi16_directory, *const uapi16_file_object) = (&directory, &missing); + assert_eq!( + uapi16_directory_open_data(d, o, &mut fd, &mut offset, &mut e), + -libc::ENOENT + ); + assert_eq!((fd, offset), (-7, 7)); + assert_eq!( + uapi16_error_kind(e), + uapi16_error_kind_t::UAPI16_ERROR_SOURCE_MISSING as u64 + ); + e = uapi16_error_free(e); + let o: *const uapi16_file_object = &blob; + for (ret_fd, ret_offset) in [ + (ptr::null_mut(), &mut offset as *mut u64), + (&mut fd as *mut c_int, ptr::null_mut()), + ] { + assert_eq!( + uapi16_directory_open_data(d, o, ret_fd, ret_offset, &mut e), + -libc::EINVAL + ); + e = uapi16_error_free(e); + } + assert_eq!( + uapi16_directory_open_data(ptr::null(), o, &mut fd, &mut offset, &mut e), + -libc::EINVAL + ); + e = uapi16_error_free(e); + assert_eq!( + uapi16_directory_open_data(d, ptr::null(), &mut fd, &mut offset, &mut e), + -libc::EINVAL + ); + e = uapi16_error_free(e); + assert_eq!((fd, offset), (-7, 7)); + assert_eq!(uapi16_directory_open_data(d, o, &mut fd, &mut offset, &mut e), 0); + assert!(fd >= 0 && offset == 0 && e.is_null()); + // The descriptor is the caller's: it is open, and closed here. + assert_eq!(read((OwnedFd::from_raw_fd(fd), offset)).0, b"0123456789"); + } + // In another process, and with an object of another process. + let mut elsewhere = object(c"a/file"); + drop(following); + let mut directory = directory; + if let Some(other) = Process::elsewhere() { + elsewhere.process = other; + assert_eq!(directory.open_data(&elsewhere).unwrap_err().errno, libc::ECHILD); + directory.process = other; + assert_eq!(directory.open_data(&blob).unwrap_err().errno, libc::ECHILD); + } + drop(directory); + assert!(rustix::io::fcntl_getfd(&top).is_ok()); + drop(tmp); + } + + /// In another process than the one that made it, an object only fails + /// where it can, and a writer that is dropped there leaves the file of + /// its manifest to its parent. A call fails for what it is given first, + /// then for the process, and only then for what the object says. + #[test] + fn another_process() { + let child = |e: uapi16_error| { + assert_eq!( + (e.kind, e.errno), + (uapi16_error_kind_t::UAPI16_ERROR_INVALID_ARGUMENT, libc::ECHILD) + ) + }; + // Where nothing tells a process from another one, there is nothing + // to refuse. + let Some(elsewhere) = Process::elsewhere() else { + return; + }; + let out = TempDir::new("capi-process-out"); + let dir = File::open(&out.0).unwrap(); + + let mut options = uapi16_manifest_options::new(); + // SAFETY: here and below, `dir` and `nowhere` stay open until the + // test ends, and what borrows them is dropped before that. + let mut created = unsafe { options.create_at(descriptor(&dir), text(c"m")) }.unwrap(); + // The name the new file has until it gets its own, where the file + // system makes no file without a name. + let names = || fs::read_dir(&out.0).unwrap().map(|entry| entry.unwrap().file_name()); + let temporary: Vec<_> = names().collect(); + let nowhere = File::options().write(true).open("/dev/null").unwrap(); + // SAFETY: as above. + let mut finished = unsafe { options.open(descriptor(&nowhere)) }.unwrap(); + finished.finish().unwrap(); + let mut file = object(c"a"); + let mut sha256 = uapi16_sha256::new(); + let mut check = uapi16_data_check::new(&file).unwrap(); + // SAFETY: as above. + let mut records = unsafe { uapi16_writer::begin(&options, descriptor(&nowhere), None) }.unwrap(); + + options.process = elsewhere; + created.process = elsewhere; + finished.process = elsewhere; + file.process = elsewhere; + sha256.process = elsewhere; + check.process = elsewhere; + records.process = elsewhere; + + child(options.set_features(Features::NONE).unwrap_err()); + child(options.set_order(1).unwrap_err()); + child(options.set_sync(true).unwrap_err()); + // SAFETY: as above. + unsafe { + child(options.create_at(descriptor(&dir), text(c"n")).err().unwrap()); + child(options.open(descriptor(&nowhere)).err().unwrap()); + child(uapi16_writer::begin(&options, descriptor(&nowhere), None).unwrap_err()); + } + child(created.add_object(&object(c"x")).unwrap_err()); + child(created.finish().unwrap_err()); + // A writer that is finished says so only in its own process. + child(finished.finish().unwrap_err()); + child(file.set_mode(0o644).unwrap_err()); + child(file.set_name(text(c"b")).unwrap_err()); + child(file.user_xattrs().unwrap_err()); + child(file.contents_file().unwrap_err()); + child(file.check_validity(0).unwrap_err()); + child(uapi16_data_check::new(&file).unwrap_err()); + child(sha256.update(bytes(b"x")).unwrap_err()); + child(sha256.finish().unwrap_err()); + child(check.update(bytes(b"x")).unwrap_err()); + child(check.finish().unwrap_err()); + child(records.file(&object(c"x")).unwrap_err()); + child(records.finish().unwrap_err()); + // An object of another process is none to give to an object of + // this one either: a file object to the two writers, a root to a + // writer of records that begins, and a signature object. + { + let here = uapi16_manifest_options::new(); + // SAFETY: as above. + let mut to_descriptor = unsafe { here.open(descriptor(&nowhere)) }.unwrap(); + // SAFETY: as above. + let mut of_records = unsafe { uapi16_writer::begin(&here, descriptor(&nowhere), None) }.unwrap(); + let mut foreign = object(c""); + foreign.process = elsewhere; + child(to_descriptor.add_object(&file).unwrap_err()); + child(to_descriptor.add_object(&foreign).unwrap_err()); + child(of_records.file(&file).unwrap_err()); + // SAFETY: as above. + child(unsafe { uapi16_writer::begin(&here, descriptor(&nowhere), Some(&foreign)) }.unwrap_err()); + let mut signature = uapi16_signature::new(text(c"openpgp")).unwrap(); + signature.process = elsewhere; + child(of_records.signature(&signature).unwrap_err()); + of_records.file(&object(c"x")).unwrap(); + to_descriptor.add_object(&object(c"x")).unwrap(); + } + // What a call is given is looked at first. + // SAFETY: the options are these, which nothing else uses. + let set = unsafe { + ( + uapi16_manifest_options_set_features(&mut options, CallerSet::with_words(&[1 << 31, 0]).as_ptr()), + uapi16_manifest_options_set_features(&mut options, CallerSet::with_words(&[1, 0, 1]).as_ptr()), + uapi16_manifest_options_set_features(&mut options, CallerSet::of(2, &[1]).as_ptr()), + ) + }; + assert_eq!(set, (-libc::EINVAL, -libc::E2BIG, -libc::ECHILD)); + assert_eq!(options.set_order(9).unwrap_err().errno, libc::EINVAL); + assert_eq!(file.set_type(0).unwrap_err().errno, libc::EINVAL); + assert_eq!(file.set_name(text(c"a//b")).unwrap_err().errno, libc::EINVAL); + assert_eq!(sha256.update(Bytes(None)).unwrap_err().errno, libc::EINVAL); + let nowhere_to = Descriptor(-1, PhantomData); + // SAFETY: it is no descriptor, so nothing borrows it. + let no_descriptor = unsafe { options.open(nowhere_to) }.err().unwrap(); + assert_eq!(no_descriptor.errno, libc::EBADF); + // What can't fail gives what the object has. + assert!(!file.name().is_null()); + assert_eq!(file.stated_features(), Features::NONE); + + // Dropped here they leave the directory as it is: nothing was + // made, and the name the new file has is its parent's. + drop((created, finished, records)); + assert_eq!(names().collect::>(), temporary); + } + + /// The functions of the builder as C calls them: the manifest of a tree + /// goes to a new file and to a descriptor, and file objects of a caller + /// make the manifest a record writer writes for them. + #[test] + fn the_functions() { + let (tmp, top) = tree("capi-functions"); + let out = TempDir::new("capi-functions-out"); + let dir = File::open(&out.0).unwrap(); + let read = |mut file: File| { + let mut data = Vec::new(); + file.rewind().unwrap(); + file.read_to_end(&mut data).unwrap(); + data + }; + + let options = uapi16_manifest_options::new(); + let report = options.generate_at(descriptor(&dir), text(c"m"), descriptor(&top), 0); + let report = report.unwrap().report; + assert_eq!((report.files(), report.directories()), (2, 2)); + let generated = fs::read(out.0.join("m")).unwrap(); + let into = tempfile(&out); + options.generate(descriptor(&into), descriptor(&top), 0).unwrap(); + assert_eq!(read(into), generated); + let exists = options.generate_at(descriptor(&dir), text(c"m"), descriptor(&top), 0); + let exists = exists.unwrap_err(); + assert_eq!(exists.kind, uapi16_error_kind_t::UAPI16_ERROR_EXISTS); + let unknown = options.generate(descriptor(&dir), descriptor(&top), 1 << 2); + assert_eq!(unknown.unwrap_err().errno, libc::EINVAL); + + // The same manifest from file objects, which come in any order. + let mut objects = Vec::new(); + for (name, st_mode, data) in [ + (c"top", libc::S_IFREG, Some(&b"top"[..])), + (c"a/file", libc::S_IFREG, Some(&b"hello"[..])), + (c"a", libc::S_IFDIR, None), + ] { + let mut object = object(name); + object.set_type(st_mode).unwrap(); + if let Some(data) = data { + let mut sha256 = uapi16_sha256::new(); + sha256.update(bytes(data)).unwrap(); + let hash = Sha256::from(sha256.finish().unwrap()); + assert_eq!(sha256.finish().unwrap_err().errno, libc::ESTALE); + assert_eq!(sha256.update(bytes(data)).unwrap_err().errno, libc::ESTALE); + let file = object.file_mut().unwrap(); + file.set_size(Some(data.len() as u64)); + file.set_sha256(Some(hash)); + } + objects.push(object); + } + let mut options = uapi16_manifest_options::new(); + let features = Features::SIZE | Features::SHA256; + options.set_features(features).unwrap(); + let into = tempfile(&out); + // SAFETY: `into` is open until the writer was dropped. + let mut writer = unsafe { options.open(descriptor(&into)) }.unwrap(); + for object in &objects { + writer.add_object(object).unwrap(); + } + // An object that is refused is not added, and the writer is as it + // was. + let mut with_mode = object(c"refused"); + with_mode.set_mode(0o644).unwrap(); + let refused = writer.add_object(&with_mode).unwrap_err(); + assert_eq!(refused.kind, uapi16_error_kind_t::UAPI16_ERROR_MANIFEST); + assert_eq!(refused.field, Some(Field::Mode)); + let report = writer.finish().unwrap().report; + assert_eq!((report.files(), report.directories(), report.bytes()), (2, 2, 8)); + assert_eq!( + writer.finish().unwrap_err().kind, + uapi16_error_kind_t::UAPI16_ERROR_ENDED + ); + assert_eq!(writer.add_object(&objects[0]).unwrap_err().errno, libc::ESTALE); + drop(writer); + let built = read(into); + + // The record writer takes them in the order of the manifest. + let records = tempfile(&out); + // SAFETY: `records` is open until the writer was dropped. + let mut record_writer = unsafe { uapi16_writer::begin(&options, descriptor(&records), None) }.unwrap(); + // An object that is refused is not written, and the writer goes + // on as if it had not been given it. + let misplaced = record_writer.file(&objects[1]).unwrap_err(); + assert_eq!(misplaced.problem, Some(Problem::Misplaced)); + record_writer.file(&objects[2]).unwrap(); + record_writer.file(&objects[1]).unwrap(); + record_writer.file(&objects[0]).unwrap(); + record_writer.finish().unwrap(); + assert_eq!(record_writer.finish().unwrap_err().errno, libc::ESTALE); + assert_eq!(record_writer.file(&objects[0]).unwrap_err().errno, libc::ESTALE); + drop(record_writer); + let written = read(records); + assert_eq!(String::from_utf8_lossy(&written), String::from_utf8_lossy(&built)); + drop(tmp); + } + + /// A file in `dir` that is there to be written to and read back. + fn tempfile(dir: &TempDir) -> File { + use std::sync::atomic::{AtomicU32, Ordering}; + static NEXT: AtomicU32 = AtomicU32::new(0); + let path = dir.0.join(format!("scratch-{}", NEXT.fetch_add(1, Ordering::Relaxed))); + File::options() + .read(true) + .write(true) + .create_new(true) + .open(path) + .unwrap() + } + + /// Where a caller keeps the object that a reader fills: a pointer, which + /// is NULL until a read stored an object there. The object is freed + /// with it. + struct Kept(*mut T); + + impl Kept { + /// A place without an object. + fn new() -> Kept { + Kept(ptr::null_mut()) + } + + /// The place as the two read functions of a reader take it. + fn place(&mut self) -> Refill<'_, T> { + // SAFETY: the pointer is a field of this, and is NULL or the + // object a read stored there, which nothing else has. + unsafe { Refill::new(&mut self.0) }.unwrap() + } + + /// The object, if a read stored one. + fn get(&self) -> Option<&T> { + // SAFETY: as in place(). + unsafe { self.0.as_ref() } + } + } + + impl Drop for Kept { + fn drop(&mut self) { + // SAFETY: as in place(), and nothing uses the object after this. + unsafe { T::free(self.0) }; + } + } + + /// A reader of the manifest in `file`. + /// + /// # Safety + /// + /// `file` stays open until the reader is dropped. + unsafe fn reader_of(file: &File) -> uapi16_reader { + // SAFETY: `file` stays open until the reader is dropped, as the + // caller says. + unsafe { uapi16_reader::open(descriptor(file)) }.unwrap() + } + + /// A reader hands out the file objects, says when signature objects + /// follow, and reads those for a caller that asks for them, or passes + /// over them. The manifest is complete once it said so. A read fills + /// the object of its caller, and one that reads no object leaves it as + /// it is. + #[test] + fn reading() { + use uapi16_read_t::*; + let out = TempDir::new("capi-reading"); + let manifest = |signatures: &[&str], after: &str| { + let mut text = String::from(concat!( + "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", + "\x1e{\"name\":\"a\",\"type\":\"dir\"}\n", + "\x1e{\"name\":\"a/b\",\"size\":0}\n", + )); + for signature in signatures { + text.push_str(&format!( + "\x1e{{\"mediaType\":\"application/vnd.uapi.16.signature\",\"mechanism\":\"{}\"}}\n", + signature + )); + } + text.push_str(after); + let mut file = tempfile(&out); + file.write_all(text.as_bytes()).unwrap(); + file.rewind().unwrap(); + file + }; + let trailer = "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n"; + // The names of the file objects that come, read into one object, + // and what came after them. + let files = |reader: &mut uapi16_reader| { + let mut kept = Kept::new(); + let mut names = Vec::new(); + loop { + match reader.next(kept.place()).unwrap() { + UAPI16_READ_FILE => names.push(kept.get().unwrap().object.name().as_str().to_owned()), + other => return (names, other), + } + } + }; + let next = |reader: &mut uapi16_reader| reader.next(Kept::new().place()); + let next_signature = |reader: &mut uapi16_reader| reader.next_signature(Kept::new().place()); + + // No signature objects: the file objects, and the end. + { + let file = manifest(&[], trailer); + // SAFETY: here and below, a reader is dropped before its file. + let mut reader = unsafe { reader_of(&file) }; + assert!(reader.root.is_root()); + assert_eq!(reader.order(), uapi16_order_t::UAPI16_ORDER_CODEPOINT); + reader.require_order(1).unwrap(); + assert_eq!(reader.require_order(2).unwrap_err().errno, libc::EINVAL); + assert_eq!(reader.require_order(0).unwrap_err().errno, libc::EINVAL); + reader.check_validity(0).unwrap(); + assert_eq!(reader.signed_len().unwrap_err().errno, libc::ENODATA); + assert_eq!(next_signature(&mut reader).unwrap_err().errno, libc::EINVAL); + assert_eq!( + files(&mut reader), + (vec!["a".to_owned(), "a/b".to_owned()], UAPI16_READ_END) + ); + assert_eq!(reader.signed_len().unwrap_err().errno, libc::ENODATA); + // It stays at its end, also for a caller that asks for signature + // objects, of which it has none. That caller keeps the object + // it has, as it is. + assert_eq!(next(&mut reader).unwrap(), UAPI16_READ_END); + let mut kept = Kept::new(); + assert_eq!(reader.next_signature(kept.place()).unwrap(), UAPI16_READ_END); + assert!(kept.get().is_none()); + kept.place().store(uapi16_signature::new(text(c"mine")).unwrap()); + let mine = kept.0; + for _ in 0..2 { + assert_eq!(reader.next_signature(kept.place()).unwrap(), UAPI16_READ_END); + assert_eq!(kept.0, mine); + assert_eq!(kept.get().unwrap().signature.mechanism(), "mine"); + } + assert_eq!(next(&mut reader).unwrap(), UAPI16_READ_END); + } + + // Signature objects that are passed over. + { + let file = manifest(&["openpgp", "pkcs7"], trailer); + // SAFETY: as above. + let mut reader = unsafe { reader_of(&file) }; + assert_eq!(files(&mut reader).1, UAPI16_READ_SIGNATURES); + let signed = reader.signed_len().unwrap(); + assert!(signed > 0); + assert_eq!(next(&mut reader).unwrap(), UAPI16_READ_END); + assert_eq!(reader.signed_len().unwrap(), signed); + } + + // Signature objects that are read, each once, into one object. The + // end leaves that object as it is. + { + let file = manifest(&["openpgp", "pkcs7"], trailer); + // SAFETY: as above. + let mut reader = unsafe { reader_of(&file) }; + assert_eq!(files(&mut reader).1, UAPI16_READ_SIGNATURES); + let mut kept = Kept::new(); + for mechanism in ["openpgp", "pkcs7"] { + assert_eq!(reader.next_signature(kept.place()).unwrap(), UAPI16_READ_SIGNATURE); + assert_eq!(kept.get().unwrap().signature.mechanism(), mechanism); + } + let last = kept.0; + assert_eq!(reader.next_signature(kept.place()).unwrap(), UAPI16_READ_END); + assert_eq!(kept.0, last); + assert_eq!(kept.get().unwrap().signature.mechanism(), "pkcs7"); + assert_eq!(next(&mut reader).unwrap(), UAPI16_READ_END); + } + + // One that is read and the rest passed over. + { + let file = manifest(&["openpgp", "pkcs7"], trailer); + // SAFETY: as above. + let mut reader = unsafe { reader_of(&file) }; + assert_eq!(files(&mut reader).1, UAPI16_READ_SIGNATURES); + assert_eq!(next_signature(&mut reader).unwrap(), UAPI16_READ_SIGNATURE); + assert_eq!(next(&mut reader).unwrap(), UAPI16_READ_END); + } + + // A file object after a signature object is refused, also where the + // signature objects are passed over, and the reader takes nothing + // more after that. + let late = "\x1e{\"name\":\"c\"}\n"; + for take in [false, true] { + let file = manifest(&["openpgp"], late); + // SAFETY: as above. + let mut reader = unsafe { reader_of(&file) }; + assert_eq!(files(&mut reader).1, UAPI16_READ_SIGNATURES); + let failed = if take { + assert_eq!(next_signature(&mut reader).unwrap(), UAPI16_READ_SIGNATURE); + next_signature(&mut reader).unwrap_err() + } else { + next(&mut reader).unwrap_err() + }; + assert_eq!(failed.problem, Some(Problem::FileAfterSignature)); + assert_eq!(failed.kind, uapi16_error_kind_t::UAPI16_ERROR_MANIFEST); + let ended = uapi16_error_kind_t::UAPI16_ERROR_ENDED; + assert_eq!(next(&mut reader).unwrap_err().kind, ended); + assert_eq!(next_signature(&mut reader).unwrap_err().kind, ended); + } + + // A manifest that ends without its trailer is not complete. The + // read that finds that out leaves the object of the caller as the + // read before left it, and so does every read after it. + let file = manifest(&[], ""); + // SAFETY: as above. + let mut reader = unsafe { reader_of(&file) }; + let mut kept = Kept::new(); + let mut names = Vec::new(); + let failed = loop { + match reader.next(kept.place()) { + Ok(UAPI16_READ_FILE) => names.push(kept.get().unwrap().object.name().as_str().to_owned()), + Ok(other) => panic!("{:?}", other), + Err(e) => break e, + } + }; + assert_eq!(names, ["a", "a/b"]); + assert_eq!(failed.problem, Some(Problem::NoTrailer)); + let last = kept.0; + assert_eq!(kept.get().unwrap().object.name().as_str(), "a/b"); + assert_eq!(reader.next(kept.place()).unwrap_err().errno, libc::ESTALE); + assert_eq!(kept.0, last); + assert_eq!(kept.get().unwrap().object.name().as_str(), "a/b"); + } + + /// A reader fills the object of a caller again as getline() fills its + /// buffer: the object stays where it is, and nothing of the record + /// before is left in it, also not the strings it handed out. An object + /// of another process is not one a read fills. + #[test] + fn refilled_objects() { + use uapi16_read_t::*; + let out = TempDir::new("capi-refill"); + // A file object that says what an object can say, and one after it + // that says nothing. + let mut full = object(c"full"); + full.set_mode(libc::S_IFREG | 0o440).unwrap(); + let inode = full.inode_mut().unwrap(); + inode.set_uid(Some(1)); + inode.set_gid(Some(2)); + inode.set_mtime_nsec(Some(3)); + full.set_user_name(text(c"user")).unwrap(); + full.set_group_name(text(c"group")).unwrap(); + let file = full.file_mut().unwrap(); + file.set_size(Some(0)); + file.set_sha256(Some(Sha256::digest(b""))); + full.set_inode_token(9).unwrap(); + full.set_user_xattrs().unwrap(); + full.add_user_xattr(text(c"key"), bytes(b"value")).unwrap(); + full.set_read_only(uapi16_read_only_t::UAPI16_READ_ONLY_YES as u64) + .unwrap(); + full.set_inode_flags(0x20 | 0x10, 0x20).unwrap(); + full.set_dos_attributes(0x02 | 0x20, 0x20).unwrap(); + full.set_contents_file(text(c"blobs/1")).unwrap(); + let mut options = uapi16_manifest_options::new(); + options.set_features(full.stated_features()).unwrap(); + let manifest = tempfile(&out); + { + // SAFETY: `manifest` is open until the writer was dropped. + let mut writer = unsafe { uapi16_writer::begin(&options, descriptor(&manifest), None) }.unwrap(); + writer.file(&full).unwrap(); + writer.file(&object(c"plain")).unwrap(); + writer.finish().unwrap(); + } + + // Each record read into an object of its own. + (&manifest).rewind().unwrap(); + let fresh = { + // SAFETY: here and below, a reader is dropped before `manifest`. + let mut reader = unsafe { reader_of(&manifest) }; + let mut objects = Vec::new(); + loop { + let mut kept = Kept::new(); + match reader.next(kept.place()).unwrap() { + UAPI16_READ_FILE => objects.push(kept), + UAPI16_READ_END => break objects, + other => panic!("{:?}", other), + } + } + }; + assert_eq!(fresh.len(), 2); + let same = |a: &uapi16_file_object, b: &uapi16_file_object| { + assert_eq!(a.object, b.object); + assert_eq!(a.file_system, b.file_system); + assert_eq!(a.gpt_disk_uuid, b.gpt_disk_uuid); + }; + // The strings an object hands out, which it keeps until it is + // filled again. + let strings = |o: &uapi16_file_object| { + // SAFETY: a string that is not NULL is one of the object, which + // is not changed while it is copied. + let copy = |text: *const c_char| (!text.is_null()).then(|| unsafe { CStr::from_ptr(text) }.to_owned()); + let xattrs = o.user_xattrs().ok().map(|count| { + let names = (0..count).map(|i| copy(o.user_xattr(i).unwrap().0)); + names.collect::>() + }); + let (name, label) = (copy(o.name()), copy(o.fs_label())); + (name, copy(o.user_name()), copy(o.group_name()), label, xattrs) + }; + + // Both records read into one object. + (&manifest).rewind().unwrap(); + // SAFETY: as above. + let mut reader = unsafe { reader_of(&manifest) }; + let mut kept = Kept::new(); + assert_eq!(reader.next(kept.place()).unwrap(), UAPI16_READ_FILE); + let first = kept.0; + same(kept.get().unwrap(), fresh[0].get().unwrap()); + let handed_out = strings(kept.get().unwrap()); + assert_eq!(handed_out, strings(&full)); + assert_eq!(handed_out.1.as_deref(), Some(c"user")); + assert_eq!(handed_out.4, Some(vec![Some(c"key".to_owned())])); + assert_eq!(reader.next(kept.place()).unwrap(), UAPI16_READ_FILE); + assert_eq!(kept.0, first); + let plain = kept.get().unwrap(); + same(plain, fresh[1].get().unwrap()); + assert_eq!(strings(plain), strings(fresh[1].get().unwrap())); + assert_eq!(strings(plain).0.as_deref(), Some(c"plain")); + assert!(plain.user_name().is_null() && plain.group_name().is_null()); + let inode = plain.object.inode(); + assert_eq!( + (inode.mode(), inode.uid(), inode.gid(), inode.mtime_nsec()), + (None, None, None, None) + ); + assert_eq!((plain.object.size(), plain.object.sha256()), (None, None)); + assert_eq!(plain.object.inode_token(), None); + assert!(plain.object.contents().is_empty()); + // What the manifest records and the object does not say is filled + // in, as for an object of its own. + assert_eq!(plain.user_xattrs().unwrap(), 0); + assert_eq!(inode.read_only(), Some(false)); + // The end leaves the object as it is. + assert_eq!(reader.next(kept.place()).unwrap(), UAPI16_READ_END); + assert_eq!(kept.0, first); + same(kept.get().unwrap(), fresh[1].get().unwrap()); + drop(reader); + + // An object of another process is not filled, and nothing is read + // for it. + (&manifest).rewind().unwrap(); + // SAFETY: as above. + let mut reader = unsafe { reader_of(&manifest) }; + // SAFETY: the object is the one the reads stored, which nothing + // else uses. + if let Some(elsewhere) = Process::elsewhere() { + // SAFETY: as above. + unsafe { (*kept.0).process = elsewhere }; + assert_eq!(reader.next(kept.place()).unwrap_err().errno, libc::ECHILD); + same(kept.get().unwrap(), fresh[1].get().unwrap()); + } + let mut other = Kept::new(); + assert_eq!(reader.next(other.place()).unwrap(), UAPI16_READ_FILE); + same(other.get().unwrap(), fresh[0].get().unwrap()); + + // One object for two records whose attributes have other names: the + // names of the first record are not those of the second. + let named = |name: &CStr, attribute: &CStr| { + let mut o = object(name); + o.set_user_xattrs().unwrap(); + o.add_user_xattr(text(attribute), bytes(b"1")).unwrap(); + o + }; + let mut options = uapi16_manifest_options::new(); + options.set_features(Features::USER_XATTR).unwrap(); + let attributes = tempfile(&out); + { + // SAFETY: `attributes` is open until the writer was dropped. + let mut writer = unsafe { uapi16_writer::begin(&options, descriptor(&attributes), None) }.unwrap(); + writer.file(&named(c"a", c"one")).unwrap(); + writer.file(&named(c"b", c"two")).unwrap(); + writer.finish().unwrap(); + } + (&attributes).rewind().unwrap(); + // SAFETY: `attributes` is open until the reader was dropped. + let mut reader = unsafe { uapi16_reader::open(descriptor(&attributes)) }.unwrap(); + let mut kept = Kept::new(); + for attribute in [c"one", c"two"] { + assert_eq!(reader.next(kept.place()).unwrap(), UAPI16_READ_FILE); + let (name, _, _) = kept.get().unwrap().user_xattr(0).unwrap(); + // SAFETY: the name is a string of the object, which is there. + assert_eq!(unsafe { CStr::from_ptr(name) }, attribute); + } + } + + /// An object that keeps a descriptor has it on loan from its caller: it + /// uses that descriptor and no duplicate of it, and leaves it open when + /// it is dropped, also where it could not be made and in another + /// process. + #[test] + fn lent_descriptors() { + let out = TempDir::new("capi-lent"); + let dir = File::open(&out.0).unwrap(); + fs::create_dir(out.0.join("sub")).unwrap(); + let open = |file: &File| rustix::io::fcntl_getfd(file).is_ok(); + let options = uapi16_manifest_options::new(); + let mut manifest = tempfile(&out); + let root = "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n"; + let trailer = "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n"; + manifest.write_all(root.as_bytes()).unwrap(); + manifest.write_all(trailer.as_bytes()).unwrap(); + manifest.rewind().unwrap(); + let empty = tempfile(&out); + let records = tempfile(&out); + let listing = tempfile(&out); + + // SAFETY: every object is dropped before the file it has on loan, + // which is open until the test ends. + unsafe { + let reader = uapi16_reader::open(descriptor(&manifest)).unwrap(); + assert_eq!(reader.reader.get_ref().as_raw_fd(), manifest.as_raw_fd()); + drop(reader); + assert!(open(&manifest)); + // A file that is no manifest makes no reader, and stays open. + let no_manifest = uapi16_reader::open(descriptor(&empty)).unwrap_err(); + assert_eq!(no_manifest.kind, uapi16_error_kind_t::UAPI16_ERROR_MANIFEST); + assert!(open(&empty)); + + let mut writer = uapi16_writer::begin(&options, descriptor(&records), None).unwrap(); + let lent = writer.writer.as_ref().unwrap().get_ref().as_raw_fd(); + assert_eq!(lent, records.as_raw_fd()); + writer.finish().unwrap(); + assert!(open(&records)); + drop(writer); + assert!(open(&records)); + // What it wrote went to the file of the caller. + assert!(records.metadata().unwrap().len() > 0); + + let mut writer = options.open(descriptor(&listing)).unwrap(); + writer.add_object(&object(c"a")).unwrap(); + writer.finish().unwrap(); + assert!(open(&listing)); + drop(writer); + assert!(open(&listing)); + // One that is dropped before it finished leaves it open too. + drop(options.open(descriptor(&listing)).unwrap()); + assert!(open(&listing)); + + // A new file whose name has one component is made in the + // directory of the caller, which the writer shares with what it + // keeps there. For a longer name the writer opens the + // directory of the file itself. + for (name, shared) in [(c"m", true), (c"sub/m", false)] { + let writer = options.create_at(descriptor(&dir), text(name)).unwrap(); + let Some(WriterTo::NewFile(_, lent)) = writer.writer.as_ref() else { + panic!("no writer of a new file"); + }; + assert_eq!(lent.as_raw_fd(), dir.as_raw_fd()); + assert_eq!(Arc::strong_count(lent) > 1, shared, "{:?}", name); + drop(writer); + assert!(open(&dir)); + } + let mut writer = options.create_at(descriptor(&dir), text(c"m")).unwrap(); + writer.finish().unwrap(); + assert!(open(&dir)); + drop(writer); + assert!(open(&dir)); + // A name that is taken makes no writer. + let exists = options.create_at(descriptor(&dir), text(c"m")).err().unwrap(); + assert_eq!(exists.kind, uapi16_error_kind_t::UAPI16_ERROR_EXISTS); + assert!(open(&dir)); + // In another process the writer leaves the descriptor open as + // well. + let mut writer = options.create_at(descriptor(&dir), text(c"n")).unwrap(); + if let Some(elsewhere) = Process::elsewhere() { + writer.process = elsewhere; + } + drop(writer); + assert!(open(&dir)); + + let directory = uapi16_directory::new(descriptor(&dir), 0).unwrap(); + drop(directory); + assert!(open(&dir)); + assert_eq!( + uapi16_directory::new(descriptor(&dir), 1 << 1).unwrap_err().errno, + libc::EINVAL + ); + assert!(open(&dir)); + } + + // The functions that make no object borrow for the call. + let top = File::open(out.0.join("sub")).unwrap(); + options + .generate_at(descriptor(&dir), text(c"g"), descriptor(&top), 0) + .unwrap(); + options.generate(descriptor(&listing), descriptor(&top), 0).unwrap(); + assert!(open(&dir) && open(&listing) && open(&top)); + // What was lent is still what it was: the manifest reads again. + manifest.rewind().unwrap(); + // SAFETY: the reader is dropped before `manifest`. + let mut reader = unsafe { reader_of(&manifest) }; + let read = reader.next(Kept::new().place()).unwrap(); + assert_eq!(read, uapi16_read_t::UAPI16_READ_END); + } + + /// A manifest goes through a pipe, from a writer of records to a reader + /// and into one object of the caller. The writer and the reader have + /// their ends of the pipe on loan, and leave them open. So does a + /// directory, and a descriptor that was shared for a while. This test + /// needs no file system, so it runs under Miri as well. + #[test] + fn through_a_pipe() { + use uapi16_read_t::*; + let mut ends = [0; 2]; + // SAFETY: pipe2() stores two descriptors in the array. + assert_eq!(unsafe { libc::pipe2(ends.as_mut_ptr(), libc::O_CLOEXEC) }, 0); + // SAFETY: the two are new descriptors, which nothing else has. + let (from, into) = unsafe { (File::from_raw_fd(ends[0]), File::from_raw_fd(ends[1])) }; + let open = |file: &File| rustix::io::fcntl_getfd(file).is_ok(); + let options = uapi16_manifest_options::new(); + { + // SAFETY: `into` is open until the writer was dropped. + let mut writer = unsafe { uapi16_writer::begin(&options, descriptor(&into), None) }.unwrap(); + let lent = writer.writer.as_ref().unwrap().get_ref().as_raw_fd(); + assert_eq!(lent, into.as_raw_fd()); + for name in [c"a", c"b"] { + writer.file(&object(name)).unwrap(); + } + // An object that is refused would have been the next record, + // whether the writer finds what is wrong with it or this does: + // one that is out of order, and one with a field of the root. + let out_of_order = writer.file(&object(c"a")).unwrap_err(); + assert_eq!(out_of_order.problem, Some(Problem::OutOfOrder)); + let mut labeled = object(c"c"); + labeled.set_fs_label(text(c"label")).unwrap(); + let not_permitted = writer.file(&labeled).unwrap_err(); + assert_eq!(not_permitted.problem, Some(Problem::FieldNotPermitted)); + assert_eq!((out_of_order.record, not_permitted.record), (Some(3), Some(3))); + writer.file(&object(c"c")).unwrap(); + writer + .signature(&uapi16_signature::new(text(c"openpgp")).unwrap()) + .unwrap(); + writer.finish().unwrap(); + } + assert!(open(&into)); + drop(into); + + // SAFETY: the reader is dropped before `from`. + let mut reader = unsafe { reader_of(&from) }; + assert_eq!(reader.reader.get_ref().as_raw_fd(), from.as_raw_fd()); + let mut kept = Kept::new(); + let mut names = Vec::new(); + let mut places = Vec::new(); + while reader.next(kept.place()).unwrap() == UAPI16_READ_FILE { + names.push(kept.get().unwrap().object.name().as_str().to_owned()); + places.push(kept.0); + } + assert_eq!(names, ["a", "b", "c"]); + // One object took all three, where the first read made it. + assert!(!places[0].is_null() && places.iter().all(|place| *place == places[0])); + let mut signature = Kept::new(); + assert_eq!(reader.next_signature(signature.place()).unwrap(), UAPI16_READ_SIGNATURE); + assert_eq!(signature.get().unwrap().signature.mechanism(), "openpgp"); + assert_eq!(reader.next_signature(signature.place()).unwrap(), UAPI16_READ_END); + assert_eq!(signature.get().unwrap().signature.mechanism(), "openpgp"); + drop(reader); + assert!(open(&from)); + + // SAFETY: what borrows `from` is dropped before it. + unsafe { + drop(uapi16_directory::new(descriptor(&from), 0).unwrap()); + assert!(open(&from)); + let lent = descriptor(&from).lend(Arc::new).unwrap(); + let shared = Arc::clone(&lent); + assert_eq!(shared.as_raw_fd(), from.as_raw_fd()); + drop(shared); + drop(lent); + assert!(open(&from)); + } + } + + /// A reader of a pipe that does not block fails with EAGAIN while + /// nothing is there to read. That does not end it: it lost nothing, and + /// it reads on with the next call, also where half a record came in + /// between. The object of the caller stays as it is until then. + #[test] + fn no_blocking() { + use uapi16_read_t::*; + let mut ends = [0; 2]; + // SAFETY: pipe2() stores two descriptors in the array. + let made = unsafe { libc::pipe2(ends.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) }; + assert_eq!(made, 0); + // SAFETY: the two are new descriptors, which nothing else has. + let (from, mut into) = unsafe { (File::from_raw_fd(ends[0]), File::from_raw_fd(ends[1])) }; + let begin = concat!( + "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", + "\x1e{\"name\":\"a\"}\n", + "\x1e", + ); + let rest = concat!( + "\"size\":7}\n", + "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + ); + into.write_all(begin.as_bytes()).unwrap(); + // SAFETY: the reader is dropped before `from`. + let mut reader = unsafe { reader_of(&from) }; + let mut kept = Kept::new(); + assert_eq!(reader.next(kept.place()).unwrap(), UAPI16_READ_FILE); + for half in [None, Some("{\"name\":\"b\",")] { + if let Some(half) = half { + into.write_all(half.as_bytes()).unwrap(); + } + let nothing = reader.next(kept.place()).unwrap_err(); + assert_eq!( + (nothing.kind, nothing.errno), + (uapi16_error_kind_t::UAPI16_ERROR_IO, libc::EAGAIN) + ); + assert_eq!(kept.get().unwrap().object.name().as_str(), "a"); + } + into.write_all(rest.as_bytes()).unwrap(); + drop(into); + assert_eq!(reader.next(kept.place()).unwrap(), UAPI16_READ_FILE); + let read = &kept.get().unwrap().object; + assert_eq!((read.name().as_str(), read.size()), ("b", Some(7))); + assert_eq!(reader.next(kept.place()).unwrap(), UAPI16_READ_END); + } + + /// The root of a reader as C uses it: the pointer is taken once, and the + /// root is read through it while the reader reads on, until the reader + /// is freed. This test needs no file system, so it runs under Miri as + /// well, which finds a pointer that a later call on the reader ended. + #[test] + fn the_root_of_a_reader() { + const LABEL: FeatureNumber = uapi16_feature_t::UAPI16_FEATURE_FS_LABEL as FeatureNumber; + let mut ends = [0; 2]; + // SAFETY: pipe2() stores two descriptors in the array. + assert_eq!(unsafe { libc::pipe2(ends.as_mut_ptr(), libc::O_CLOEXEC) }, 0); + // SAFETY: the two are new descriptors, which nothing else has. + let (from, into) = unsafe { (File::from_raw_fd(ends[0]), File::from_raw_fd(ends[1])) }; + // SAFETY: the pointers are locals, the strings are literals, and + // every object is used as the functions say: made once, freed once, + // and not used after that. The ends of the pipe are open for as + // long as the writer and the reader are there. + unsafe { + let options = uapi16_manifest_options_new(); + let mut features = CallerSet::of(2, &[]); + assert_eq!(uapi16_features_default(features.as_mut_ptr()), 0); + assert_eq!(uapi16_features_add(features.as_mut_ptr(), LABEL), 0); + assert_eq!(uapi16_manifest_options_set_features(options, features.as_ptr()), 0); + let mut root: *mut uapi16_file_object = ptr::null_mut(); + assert_eq!(uapi16_file_object_new(c"".as_ptr(), &mut root, ptr::null_mut()), 0); + assert_eq!(uapi16_file_object_set_fs_label(root, c"label".as_ptr()), 0); + let mut writer: *mut uapi16_writer = ptr::null_mut(); + let begun = uapi16_writer_begin(options, into.as_raw_fd(), root, &mut writer, ptr::null_mut()); + assert_eq!(begun, 0); + for name in [c"a", c"b"] { + let mut file: *mut uapi16_file_object = ptr::null_mut(); + assert_eq!(uapi16_file_object_new(name.as_ptr(), &mut file, ptr::null_mut()), 0); + assert_eq!(uapi16_writer_file(writer, file, ptr::null_mut()), 0); + uapi16_file_object_free(file); + } + assert_eq!(uapi16_writer_finish(writer, ptr::null_mut()), 0); + uapi16_writer_free(writer); + uapi16_file_object_free(root); + uapi16_manifest_options_free(options); + drop(into); + + let mut reader: *mut uapi16_reader = ptr::null_mut(); + assert_eq!(uapi16_reader_open(from.as_raw_fd(), &mut reader, ptr::null_mut()), 0); + let root = uapi16_reader_root(reader); + let check_root = || { + assert_eq!(CStr::from_ptr(uapi16_file_object_name(root)), c""); + assert_eq!(uapi16_file_object_type(root), libc::S_IFDIR); + assert_eq!(CStr::from_ptr(uapi16_file_object_fs_label(root)), c"label"); + let mut stated = CallerSet::of(3, &[1, 129]); + assert_eq!(uapi16_file_object_stated_features(root, stated.as_mut_ptr()), 0); + assert_eq!(stated, CallerSet::of(3, &[LABEL])); + assert!(uapi16_file_object_has_stated_feature(root, LABEL)); + }; + check_root(); + let mut kept: *mut uapi16_file_object = ptr::null_mut(); + for name in [c"a", c"b"] { + let read = uapi16_reader_next(reader, &mut kept, ptr::null_mut()); + assert_eq!(read, uapi16_read_t::UAPI16_READ_FILE as c_int); + assert_eq!(CStr::from_ptr(uapi16_file_object_name(kept)), name); + check_root(); + assert_eq!(uapi16_reader_root(reader), root); + } + let read = uapi16_reader_next(reader, &mut kept, ptr::null_mut()); + assert_eq!(read, uapi16_read_t::UAPI16_READ_END as c_int); + check_root(); + // The features of the manifest, into sets of two sizes. + let recorded = numbers_of(Features::DEFAULT | Features::FS_LABEL); + for words in [2, 3] { + let mut stored = CallerSet::with_words(&vec![u64::MAX; words]); + assert_eq!(uapi16_reader_features(reader, stored.as_mut_ptr()), 0); + assert_eq!(stored, CallerSet::of(words, &recorded)); + } + for feature in recorded { + assert!(uapi16_reader_has_feature(reader, feature)); + } + assert!(!uapi16_reader_has_feature(reader, 0)); + assert_eq!(uapi16_reader_features(reader, ptr::null_mut()), -libc::EINVAL); + assert_eq!( + uapi16_reader_features(reader, CallerSet::sized(16).as_mut_ptr()), + -libc::EINVAL + ); + check_root(); + uapi16_reader_free(reader); + uapi16_file_object_free(kept); + assert!(uapi16_reader_root(ptr::null()).is_null()); + } + } + + /// Options of C can have no order. A writer of records takes them: it + /// writes the file objects in the order they come in and declares + /// none. It still wants every object right after its directory, and + /// finds a name that comes again right after the objects of the + /// directory it names, but not every name that comes twice, as it does + /// with an order. The writers that sort take no such options, and + /// write nothing. + #[test] + fn no_order() { + let (tmp, top) = tree("capi-no-order"); + let out = TempDir::new("capi-no-order-out"); + let dir = File::open(&out.0).unwrap(); + let mut options = uapi16_manifest_options::new(); + // File objects as a caller that does not sort has them, and what + // the writer says to each. + let write = |options: &uapi16_manifest_options, into: &File| { + // SAFETY: `into` is open until the writer was dropped. + let mut writer = unsafe { uapi16_writer::begin(options, descriptor(into), None) }.unwrap(); + let mut said = Vec::new(); + for (name, st_mode) in [ + (c"b", libc::S_IFDIR), + (c"b/z", libc::S_IFREG), + (c"b/y", libc::S_IFREG), + (c"b/z", libc::S_IFREG), + (c"b", libc::S_IFDIR), + (c"a", libc::S_IFREG), + (c"a", libc::S_IFREG), + (c"b/x", libc::S_IFREG), + ] { + let mut object = object(name); + object.set_type(st_mode).unwrap(); + said.push(writer.file(&object).err().and_then(|e| e.problem)); + } + writer.finish().unwrap(); + said + }; + + options.set_order(uapi16_order_t::UAPI16_ORDER_NONE as u64).unwrap(); + let unsorted = tempfile(&out); + assert_eq!( + write(&options, &unsorted), + [ + None, + None, + // After b/z, which it sorts before. + None, + // A name that comes twice, with another one in between. + None, + // The directory again, right after its objects. + Some(Problem::DuplicateName), + None, + // The same name again, right away. + Some(Problem::DuplicateName), + // Not right after the object of its directory. + Some(Problem::Misplaced), + ] + ); + // The manifest declares no order, and a reader takes it as it is. + (&unsorted).rewind().unwrap(); + { + // SAFETY: the reader is dropped before `unsorted`. + let mut reader = unsafe { reader_of(&unsorted) }; + assert_eq!(reader.order(), uapi16_order_t::UAPI16_ORDER_NONE); + let required = reader.require_order(uapi16_order_t::UAPI16_ORDER_CODEPOINT as u64); + let required = required.unwrap_err(); + assert_eq!(required.kind, uapi16_error_kind_t::UAPI16_ERROR_MANIFEST); + // The field is one of the record of the root, which the error + // names. + assert_eq!(required.path.as_deref(), Some(c"")); + let mut kept = Kept::new(); + let mut names = Vec::new(); + while reader.next(kept.place()).unwrap() == uapi16_read_t::UAPI16_READ_FILE { + names.push(kept.get().unwrap().object.name().as_str().to_owned()); + } + assert_eq!(names, ["b", "b/z", "b/y", "b/z", "a"]); + } + + // The writers that sort take no options without an order. + let refused = |e: uapi16_error| { + assert_eq!( + (e.kind, e.errno), + (uapi16_error_kind_t::UAPI16_ERROR_INVALID_ARGUMENT, libc::EINVAL) + ) + }; + let into = tempfile(&out); + let names = || { + let mut names: Vec<_> = fs::read_dir(&out.0) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + names.sort(); + names + }; + let before = names(); + // SAFETY: no writer is made, so nothing keeps `dir` or `into`. + unsafe { + refused(options.create_at(descriptor(&dir), text(c"m")).err().unwrap()); + refused(options.open(descriptor(&into)).err().unwrap()); + } + refused( + options + .generate_at(descriptor(&dir), text(c"m"), descriptor(&top), 0) + .unwrap_err(), + ); + refused(options.generate(descriptor(&into), descriptor(&top), 0).unwrap_err()); + assert_eq!(into.metadata().unwrap().len(), 0); + assert_eq!(names(), before); + + // With the code point order the names have to be in it, every name + // that comes twice is found, and the writers that sort work again. + options + .set_order(uapi16_order_t::UAPI16_ORDER_CODEPOINT as u64) + .unwrap(); + let sorted = tempfile(&out); + assert_eq!( + write(&options, &sorted), + [ + None, + None, + Some(Problem::OutOfOrder), + Some(Problem::DuplicateName), + Some(Problem::DuplicateName), + Some(Problem::OutOfOrder), + Some(Problem::OutOfOrder), + Some(Problem::OutOfOrder), + ] + ); + options.generate(descriptor(&into), descriptor(&top), 0).unwrap(); + assert!(into.metadata().unwrap().len() > 0); + drop(tmp); + } + + /// A check of data holds what passes against the size and the hash of + /// its object. It has what it needs of the object as its own, the name + /// included, so the object of the caller can go. + #[test] + fn data_checks() { + let mut o = object(c"data"); + let file = o.file_mut().unwrap(); + file.set_size(Some(5)); + file.set_sha256(Some(Sha256::digest(b"hello"))); + let mut check = uapi16_data_check::new(&o).unwrap(); + let mut wrong = uapi16_data_check::new(&o).unwrap(); + let mut short = uapi16_data_check::new(&o).unwrap(); + drop(o); + check.update(bytes(b"hel")).unwrap(); + check.update(bytes(b"")).unwrap(); + let more = check.update(bytes(b"lo!")).unwrap_err(); + assert_eq!(more.kind, uapi16_error_kind_t::UAPI16_ERROR_SIZE_MISMATCH); + assert_eq!(more.path.as_deref(), Some(c"data")); + check.update(bytes(b"lo")).unwrap(); + assert_eq!(check.finish().unwrap(), 5); + assert_eq!(check.finish().unwrap_err().errno, libc::ESTALE); + assert_eq!(check.update(bytes(b"x")).unwrap_err().errno, libc::ESTALE); + + wrong.update(bytes(b"hallo")).unwrap(); + assert_eq!( + wrong.finish().unwrap_err().kind, + uapi16_error_kind_t::UAPI16_ERROR_HASH_MISMATCH + ); + assert_eq!(wrong.finish().unwrap_err().errno, libc::ESTALE); + short.update(bytes(b"hell")).unwrap(); + assert_eq!( + short.finish().unwrap_err().kind, + uapi16_error_kind_t::UAPI16_ERROR_SIZE_MISMATCH + ); + // One that is dropped before it is finished frees what it has. + let unfinished = uapi16_data_check::new(&object(c"other")).unwrap(); + drop(unfinished); + } + + /// A value that is made once: the first one who asks has it made, and + /// whoever asks after that gets the same one. A thread that asks while + /// another one is still making its value does not wait for it: it makes + /// one itself, and the thread whose value comes second drops it and + /// takes the first. A cell that is reset has its value made anew, and + /// one that is dropped drops its value. + #[test] + fn once_boxes() { + use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; + use std::sync::mpsc; + /// How many values there are. + static LIVE: AtomicUsize = AtomicUsize::new(0); + /// How long an answer may take that has nothing to wait for. + const PATIENCE: std::time::Duration = std::time::Duration::from_secs(30); + struct Counted(usize); + impl Counted { + fn new(number: usize) -> Counted { + LIVE.fetch_add(1, SeqCst); + Counted(number) + } + } + impl Drop for Counted { + fn drop(&mut self) { + LIVE.fetch_sub(1, SeqCst); + } + } + + let mut cell = OnceBox::new(); + assert_eq!(cell.get_or_init(|| Counted::new(1)).0, 1); + assert_eq!(cell.get_or_init(|| Counted::new(2)).0, 1); + assert_eq!(LIVE.load(SeqCst), 1); + cell.reset(); + assert_eq!(LIVE.load(SeqCst), 0); + cell.reset(); + assert_eq!(cell.get_or_init(|| Counted::new(3)).0, 3); + assert_eq!(LIVE.load(SeqCst), 1); + drop(cell); + assert_eq!(LIVE.load(SeqCst), 0); + + // A thread is making its value, and another one asks meanwhile. It + // gets its answer while the first one is still at it. A thread that + // waited for the first one would wait forever here, so the wait for + // its answer ends after a while. + let cell = Arc::new(OnceBox::new()); + let (making, is_making) = mpsc::channel(); + let (go_on, may_go_on) = mpsc::channel(); + let (answer, answered) = mpsc::channel(); + let first = { + let cell = Arc::clone(&cell); + std::thread::spawn(move || { + let slow = move || { + making.send(()).unwrap(); + may_go_on.recv().unwrap(); + Counted::new(4) + }; + cell.get_or_init(slow).0 + }) + }; + is_making.recv().unwrap(); + let second = { + let cell = Arc::clone(&cell); + std::thread::spawn(move || answer.send(cell.get_or_init(|| Counted::new(5)).0).unwrap()) + }; + assert_eq!(answered.recv_timeout(PATIENCE), Ok(5)); + go_on.send(()).unwrap(); + assert_eq!(first.join().unwrap(), 5); + second.join().unwrap(); + assert_eq!(cell.get_or_init(|| Counted::new(6)).0, 5); + assert_eq!(LIVE.load(SeqCst), 1); + drop(cell); + assert_eq!(LIVE.load(SeqCst), 0); + } + + /// A process is known by its generation, which is the same each time + /// it is asked for. A page of zeroes, as a child of a fork() has it, + /// gets the next generation: one above every generation before it, and + /// the same for threads that ask at the same time. An object is one of + /// the process with its generation, and of no other. Where a process + /// has no page, nothing tells it from another, and nothing is refused. + /// + /// Under Miri the process has no page, so what a page does is shown on + /// one of the test's own, which nothing wipes but the test. + #[test] + fn generations() { + static PAGE: AtomicUsize = AtomicUsize::new(0); + const CHILDREN: usize = 3; + const THREADS: usize = 8; + + let check = ForkCheck(&PAGE); + let parent = check.generation().unwrap(); + assert_eq!(check.generation(), Some(parent)); + let mut last = parent; + for _ in 0..CHILDREN { + PAGE.store(0, atomic::Ordering::Release); + let child = check.generation().unwrap(); + assert!(child > last); + assert_eq!(check.generation(), Some(child)); + last = child; + } + PAGE.store(0, atomic::Ordering::Release); + let agreed: Vec> = std::thread::scope(|scope| { + let asking: Vec<_> = (0..THREADS).map(|_| scope.spawn(|| check.generation())).collect(); + asking.into_iter().map(|thread| thread.join().unwrap()).collect() + }); + assert!(agreed.iter().all(|generation| *generation == agreed[0])); + assert!(agreed[0].unwrap() > last); + assert_eq!(check.generation(), agreed[0]); + + // The object of a parent, in the parent and in its child. + let (parent, child) = (Process::Known(parent), Process::Known(last)); + assert!(parent.is(parent)); + assert!(child.is(child)); + assert!(!parent.is(child)); + assert!(!child.is(parent)); + // Without a page there is no telling, and nothing is refused: not + // an object of such a process, and not in such a process. + assert!(Process::Untold.is(Process::Untold)); + assert!(Process::Untold.is(child)); + assert!(parent.is(Process::Untold)); + + // The process that is running is itself, and where it has a page it + // is no other. + let running = Process::current(); + assert_eq!(Process::current(), running); + assert!(running.is(running)); + running.check().unwrap(); + match Process::elsewhere() { + Some(elsewhere) => { + assert!(!elsewhere.is(running)); + assert_eq!(elsewhere.check().unwrap_err().errno, libc::ECHILD); + } + None => assert_eq!(running, Process::Untold), + } + if cfg!(miri) { + assert_eq!(running, Process::Untold); + } + } + + /// The count of the generations stops at its end: the last generation + /// is handed out once, and a page that is wiped after that gets none, + /// however often it asks. A process without a generation is no process + /// of any object, also of none it made itself. + #[test] + fn spent_generations() { + static PAGE: AtomicUsize = AtomicUsize::new(0); + static NEXT: AtomicUsize = AtomicUsize::new(usize::MAX - 1); + let last = ForkCheck::generation_of(&PAGE, &NEXT); + assert_eq!(last, NonZeroUsize::new(usize::MAX - 1)); + assert_eq!(ForkCheck::generation_of(&PAGE, &NEXT), last); + for _ in 0..2 { + PAGE.store(0, atomic::Ordering::Release); + assert_eq!(ForkCheck::generation_of(&PAGE, &NEXT), None); + assert_eq!(PAGE.load(atomic::Ordering::Acquire), 0); + assert_eq!(NEXT.load(atomic::Ordering::Acquire), usize::MAX); + } + + let spent = Process::Spent; + let known = Process::Known(last.unwrap()); + assert!(!spent.is(spent)); + assert!(!spent.is(known)); + assert!(!known.is(spent)); + assert!(!spent.is(Process::Untold)); + assert!(!Process::Untold.is(spent)); + assert_eq!(spent.check().unwrap_err().errno, libc::ECHILD); + } + + /// A place for an error takes one error: it is written to once, by a + /// call that fails, and one that holds something keeps it, whatever it + /// is. An object that a caller passes no place for is dropped. + #[test] + fn error_places() { + assert!(ErrorPlace::NONE.is_clear()); + assert_eq!(ErrorPlace::NONE.returned(Ok(())), 0); + assert_eq!(ErrorPlace::NONE.returned(Err(uapi16_error::ended())), -libc::ESTALE); + let mut e: *mut uapi16_error = ptr::null_mut(); + // SAFETY: `e` is a local that nothing else uses while a place has + // it. + let place = unsafe { ErrorPlace::new(&mut e) }; + assert!(place.is_clear()); + assert_eq!(place.returned(Ok(())), 0); + assert!(e.is_null()); + // SAFETY: as above. + let place = unsafe { ErrorPlace::new(&mut e) }; + assert_eq!(place.returned(Err(uapi16_error::ended())), -libc::ESTALE); + let held = e; + assert!(!held.is_null()); + // SAFETY: as above. + let place = unsafe { ErrorPlace::new(&mut e) }; + assert!(!place.is_clear()); + assert_eq!(place.returned(Err(uapi16_error::misuse())), -libc::EINVAL); + assert_eq!(e, held); + // SAFETY: `e` is the error returned() stored, which is freed once. + unsafe { + assert_eq!(uapi16_error_kind(e), uapi16_error_kind_t::UAPI16_ERROR_ENDED as u64); + assert!(uapi16_error_field(e).is_null() && uapi16_error_problem(e).is_null()); + // It is about no record, and says so without storing one. + let mut record = 77u64; + assert_eq!(uapi16_error_record(e, &mut record), -libc::ENODATA); + assert_eq!(record, 77); + assert!(uapi16_error_free(e).is_null()); + } + // What is no error at all is kept as well, and not read through. + let mut no_error = ptr::dangling_mut::(); + // SAFETY: `no_error` is a local that nothing else uses while a + // place has it. + let place = unsafe { ErrorPlace::new(&mut no_error) }; + assert!(!place.is_clear()); + assert_eq!(place.returned(Err(uapi16_error::misuse())), -libc::EINVAL); + assert_eq!(no_error, ptr::dangling_mut()); + + // A caller that passes no place for an object does not want it, and + // the object is dropped. Miri finds one that is not. + // SAFETY: NULL is a `ret` that nothing is written to. + let unwanted = + unsafe { uapi16_file_object::returned(Ok(object(c"unwanted")), ptr::null_mut(), ErrorPlace::NONE) }; + assert_eq!(unwanted, 0); + } + + /// The functions as C calls them, with pointers: an object is made, + /// changed, read and freed, NULL is no object, and a getter stores + /// nothing where it fails. + #[test] + fn through_pointers() { + let mut o: *mut uapi16_file_object = ptr::null_mut(); + let mut e: *mut uapi16_error = ptr::null_mut(); + // SAFETY: the pointers are locals, the strings are literals, and + // every object is used as the functions say: made once, freed once, + // and not used after that. + unsafe { + assert_eq!(uapi16_file_object_new(c"a//b".as_ptr(), &mut o, &mut e), -libc::EINVAL); + assert!(o.is_null()); + assert_eq!( + uapi16_error_name_problem(e), + uapi16_name_problem_t::UAPI16_NAME_PROBLEM_EMPTY_COMPONENT as u64 + ); + // A place that holds an error takes no other. + assert_eq!(uapi16_file_object_new(c"a".as_ptr(), &mut o, &mut e), -libc::EINVAL); + assert!(o.is_null()); + e = uapi16_error_free(e); + assert_eq!( + uapi16_file_object_new(c"a".as_ptr(), ptr::null_mut(), &mut e), + -libc::EINVAL + ); + e = uapi16_error_free(e); + assert_eq!( + uapi16_file_object_new(ptr::null(), &mut o, ptr::null_mut()), + -libc::EINVAL + ); + assert_eq!(uapi16_file_object_new(c"a".as_ptr(), &mut o, &mut e), 0); + assert!(!o.is_null() && e.is_null()); + + let mut number = 77u32; + assert_eq!(uapi16_file_object_uid(o, &mut number), -libc::ENODATA); + assert_eq!(number, 77); + assert_eq!(uapi16_file_object_set_uid(o, 1000), 0); + assert_eq!(uapi16_file_object_uid(o, &mut number), 0); + assert_eq!(number, 1000); + assert_eq!(uapi16_file_object_uid(o, ptr::null_mut()), -libc::EINVAL); + assert_eq!(uapi16_file_object_uid(ptr::null(), &mut number), -libc::EINVAL); + assert_eq!(uapi16_file_object_set_uid(ptr::null_mut(), 1), -libc::EINVAL); + + let hash = uapi16_sha256_digest_t { + bytes: [7; UAPI16_SHA256_SIZE], + }; + let mut read = uapi16_sha256_digest_t { + bytes: [0; UAPI16_SHA256_SIZE], + }; + assert_eq!(uapi16_file_object_sha256(o, &mut read), -libc::ENODATA); + assert_eq!(uapi16_file_object_set_sha256(o, ptr::null()), -libc::EINVAL); + assert_eq!(uapi16_file_object_set_sha256(o, &hash), 0); + assert_eq!(uapi16_file_object_sha256(o, &mut read), 0); + assert_eq!(read.bytes, hash.bytes); + + assert_eq!(uapi16_file_object_read_only(o), 0); + assert_eq!(uapi16_file_object_set_read_only(o, 5), -libc::EINVAL); + assert_eq!(uapi16_file_object_set_read_only(o, 2), 0); + assert_eq!(uapi16_file_object_read_only(o), 2); + assert_eq!(uapi16_file_object_set_read_only(o, 0), 0); + assert_eq!(uapi16_file_object_read_only(o), 0); + assert_eq!(uapi16_file_object_read_only(ptr::null()), 0); + let mut token = 77u64; + assert_eq!(uapi16_file_object_inode_token(o, &mut token), -libc::ENODATA); + assert_eq!(token, 77); + assert_eq!(uapi16_file_object_set_inode_token(o, 9), 0); + assert_eq!(uapi16_file_object_inode_token(o, &mut token), 0); + assert_eq!(token, 9); + assert_eq!(uapi16_file_object_set_inode_token(o, UAPI16_INODE_TOKEN_NONE), 0); + assert_eq!(uapi16_file_object_inode_token(o, &mut token), -libc::ENODATA); + + assert_eq!(uapi16_file_object_add_user_xattr(o, c"k".as_ptr(), ptr::null(), 0), 0); + assert_eq!( + uapi16_file_object_add_user_xattr(o, c"k".as_ptr(), ptr::null(), 1), + -libc::EINVAL + ); + let (mut name, mut value, mut size) = (ptr::null(), ptr::null(), 9usize); + assert_eq!(uapi16_file_object_user_xattr(o, 0, &mut name, &mut value, &mut size), 0); + assert_eq!((CStr::from_ptr(name), size), (c"k", 0)); + assert_eq!( + uapi16_file_object_user_xattr(o, 0, ptr::null_mut(), ptr::null_mut(), ptr::null_mut()), + 0 + ); + assert_eq!( + uapi16_file_object_user_xattr(o, 1, &mut name, &mut value, &mut size), + -libc::EINVAL + ); + + let mut literal_size = 9usize; + assert!(uapi16_file_object_literal(o, &mut literal_size).is_null()); + assert_eq!(literal_size, 0); + assert_eq!(uapi16_file_object_set_target(o, c"to".as_ptr().cast(), 2), 0); + let literal = uapi16_file_object_literal(o, &mut literal_size); + assert_eq!(slice::from_raw_parts(literal.cast::(), literal_size), b"to"); + assert!(!uapi16_file_object_literal(o, ptr::null_mut()).is_null()); + assert_eq!(uapi16_file_object_type(o), libc::S_IFREG); + assert_eq!(uapi16_file_object_type(ptr::null()), 0); + assert_eq!(uapi16_file_object_inode_token(ptr::null(), &mut token), -libc::EINVAL); + assert!(uapi16_file_object_name(ptr::null()).is_null()); + assert!(!uapi16_file_object_has_stated_feature(ptr::null(), 1)); + assert_eq!(uapi16_file_object_data_location(ptr::null()), 0); + + assert!(uapi16_file_object_free(o).is_null()); + + // A check outlives the object it was made of. + let mut check: *mut uapi16_data_check = ptr::null_mut(); + assert_eq!(uapi16_file_object_new(c"data".as_ptr(), &mut o, &mut e), 0); + assert_eq!(uapi16_file_object_set_size(o, 2), 0); + assert_eq!(uapi16_data_check_new(o, &mut check), 0); + assert_eq!(uapi16_data_check_new(o, ptr::null_mut()), -libc::EINVAL); + assert_eq!(uapi16_data_check_new(ptr::null(), &mut check), -libc::EINVAL); + assert!(uapi16_file_object_free(o).is_null()); + let mut total = 0u64; + assert_eq!(uapi16_data_check_update(check, c"to".as_ptr().cast(), 2, &mut e), 0); + assert_eq!(uapi16_data_check_finish(check, &mut total, &mut e), 0); + assert_eq!(total, 2); + assert_eq!(uapi16_data_check_finish(check, ptr::null_mut(), &mut e), -libc::ESTALE); + assert_eq!(uapi16_error_kind(e), uapi16_error_kind_t::UAPI16_ERROR_ENDED as u64); + e = uapi16_error_free(e); + assert!(uapi16_data_check_free(check).is_null() && e.is_null()); + + let sha256 = uapi16_sha256_new(); + assert_eq!(uapi16_sha256_update(sha256, c"hello".as_ptr().cast(), 5), 0); + assert_eq!(uapi16_sha256_finish(sha256, ptr::null_mut()), -libc::EINVAL); + assert_eq!(uapi16_sha256_finish(sha256, &mut read), 0); + assert_eq!(read.bytes, *Sha256::digest(b"hello").as_bytes()); + assert_eq!(uapi16_sha256_finish(sha256, &mut read), -libc::ESTALE); + assert!(uapi16_sha256_free(sha256).is_null()); + + let mut signature: *mut uapi16_signature = ptr::null_mut(); + assert_eq!(uapi16_signature_new(ptr::null(), &mut signature), -libc::EINVAL); + assert_eq!( + uapi16_signature_new(c"openpgp".as_ptr(), ptr::null_mut()), + -libc::EINVAL + ); + assert_eq!(uapi16_signature_new(c"openpgp".as_ptr(), &mut signature), 0); + assert_eq!(CStr::from_ptr(uapi16_signature_mechanism(signature)), c"openpgp"); + let mut key_size = 9usize; + assert!(uapi16_signature_key(signature, &mut key_size).is_null()); + assert_eq!(key_size, 0); + assert_eq!(uapi16_signature_set_key(signature, c"id".as_ptr().cast(), 2), 0); + let key = uapi16_signature_key(signature, &mut key_size); + assert_eq!(slice::from_raw_parts(key.cast::(), key_size), b"id"); + assert_eq!(uapi16_signature_set_key(signature, ptr::null(), 2), 0); + assert!(uapi16_signature_key(signature, ptr::null_mut()).is_null()); + assert_eq!(uapi16_signature_set_data(signature, c"".as_ptr().cast(), 0), 0); + assert!(!uapi16_signature_data(signature, &mut key_size).is_null()); + assert_eq!(key_size, 0); + assert!(uapi16_signature_free(signature).is_null()); + + assert_eq!(uapi16_name_compare(c"a/x".as_ptr(), c"a-b".as_ptr()), -1); + assert_eq!(uapi16_name_compare(c"a-b".as_ptr(), c"a/x".as_ptr()), 1); + assert_eq!(uapi16_name_compare(ptr::null(), c"".as_ptr()), 0); + assert_eq!(uapi16_name_compare(ptr::null(), c"a".as_ptr()), -1); + // What is not UTF-8 is replaced before two strings are compared, + // so two different ones can be the same. + assert_eq!(uapi16_name_compare(c"a\xffb".as_ptr(), c"a\xfeb".as_ptr()), 0); + assert_eq!(uapi16_name_compare(c"\xff".as_ptr(), c"\u{fffd}".as_ptr()), 0); + assert_eq!(uapi16_name_compare(c"\xff".as_ptr(), c"a".as_ptr()), 1); + let user_xattr = uapi16_feature_t::UAPI16_FEATURE_USER_XATTR as FeatureNumber; + let no_feature = uapi16_feature_t::ALL.len() as FeatureNumber + 1; + assert_eq!(uapi16_feature_from_name(c"user-xattr".as_ptr()), user_xattr); + assert_eq!(uapi16_feature_from_name(c"none".as_ptr()), 0); + assert_eq!(uapi16_feature_from_name(ptr::null()), 0); + assert_eq!(CStr::from_ptr(uapi16_feature_name(user_xattr)), c"user-xattr"); + assert!(uapi16_feature_name(0).is_null()); + assert!(uapi16_feature_name(no_feature).is_null()); + } + } + + /// The objects go from thread to thread: a caller uses one from one + /// thread at a time, and reads reports, errors and file objects that + /// nothing changes from any. + #[test] + fn send_and_sync() { + fn send() {} + fn sync() {} + send::(); + send::(); + send::(); + sync::(); + send::(); + sync::(); + send::(); + sync::(); + send::(); + send::(); + send::(); + send::(); + send::(); + sync::(); + send::(); + } +} diff --git a/src/uapi16/cbindgen.toml b/src/uapi16/cbindgen.toml new file mode 100644 index 0000000..ff9b177 --- /dev/null +++ b/src/uapi16/cbindgen.toml @@ -0,0 +1,375 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +# +# How cbindgen writes uapi16.h from capi.rs: +# +# cbindgen --quiet --config cbindgen.toml --output uapi16.h capi.rs +# +# uapi16.h is checked in, and CI fails if it is not what cbindgen 0.29.4 +# writes. cbindgen is a tool here and not a dependency of the crate. +# Without --quiet it says that it passes over the constants of capi.rs +# that are not for C. +# +# cbindgen takes the types, the functions and their comments from capi.rs. +# What it cannot take from there is in this file: the rules at the top of +# the header with the macro UAPI16_NODISCARD behind them, and the macros +# UAPI16_FEATURES_SET() and UAPI16_FEATURES_EMPTY and the helpers for +# __attribute__((cleanup)) at its end, which are C. + +language = "C" +# C++ can include the header as well. +cpp_compat = true +no_includes = true +sys_includes = ["stdbool.h", "stddef.h", "stdint.h"] +line_length = 100 +tab_width = 8 +usize_is_size_t = true +style = "type" + +# The include guard is opened here and closed in the trailer. cbindgen's +# own would close before the trailer and leave the helpers outside of it. +header = ''' +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#ifndef UAPI16_H +#define UAPI16_H''' + +autogen_warning = ''' +/* + * cbindgen wrote this file from capi.rs and cbindgen.toml. Change those and + * write it again: + * + * cbindgen --quiet --config cbindgen.toml --output uapi16.h capi.rs + */''' + +after_includes = ''' + +/* + * The C API of uapi16: building UAPI.16 file manifests of trees of files, + * and reading and writing them record by record. + * https://uapi-group.org/specifications/specs/file_manifest/ + * + * What holds for every function: + * + * - A function that can fail returns 0, or a negative errno if it fails. + * uapi16_reader_next() and uapi16_reader_next_signature() are the one + * exception: each returns a uapi16_read_t that says what it read, or a + * negative errno. uapi16_error_errno() can't fail and returns an errno + * as a positive number. + * + * - `reterr` is NULL or points to NULL. Unless it is NULL, a call that + * fails stores a new error there, which the caller frees with + * uapi16_error_free(). A call that succeeds does not write to it. A + * call whose `reterr` points to anything but NULL fails with -EINVAL + * before it does anything, and leaves what is there as it is. + * + * - Every call that makes an object stores it in `ret` if it succeeds, + * and does not write to `ret` if it fails. uapi16_reader_next() and + * uapi16_reader_next_signature() are the one exception: `*ret` is NULL + * or an object of the caller, which is cleared and filled again, and + * which stays the caller's whatever the call returns. A caller that + * does not want a report passes NULL for its `ret`. Every other object + * needs its `ret`. + * + * - Descriptors are borrowed. An object that keeps a descriptor borrows + * the caller's until its free function returns, and never closes it: a + * reader, a writer, a writer of records and a directory. The caller + * keeps the descriptor open until then. A function that makes no object + * borrows a descriptor for the call. A call that fails to make its + * object leaves the descriptor with the caller. Where the name of + * uapi16_manifest_writer_create_at() has several components, the + * library opens the directory of the file itself. A negative number is + * no descriptor, AT_FDCWD included, and fails with -EBADF. + * + * - Strings that go in are NUL-terminated UTF-8 and are read during the + * call. The name of a new manifest file is the exception: `name` of + * uapi16_manifest_writer_create_at() and uapi16_manifest_generate_at() + * is a path, which is taken as the bytes it is. Strings and bytes that + * come out belong to the object they come from. They live until it is + * freed, or until a call sets their field again, takes it away or fills + * the object again. + * + * - uapi16_feature_t is a plain enum: a feature is a number. Later versions + * add numbers after the last one, with no gaps, and a number keeps its + * name. uapi16_feature_name() returns NULL for a number this library + * doesn't have. The other enums are 64 bits wide. + * + * - The numbers of an enum never change and new ones are only added, so a + * switch over one needs a default case. A set of flags has a type of its + * own: uapi16_add_flags_t and uapi16_directory_flags_t. + * uapi16_name_order_t is the one signed enum: it is 64 bits wide like + * the others, and its numbers are -1, 0 and 1. + * + * - An object is used by one thread at a time, and the library takes no + * locks. Reports and errors can be read from any thread. No thread of + * the library runs once a call returned, so a caller can fork() between + * calls. + * + * - After fork(), the child can't use the objects of its parent: a + * function that can fail fails with -ECHILD there. + * + * - The library installs no signal handlers and changes no signal masks. + * A system call that a signal interrupts is made again. SIGPIPE behaves + * as with write(2). + * + * - A call that is not valid fails with -EINVAL: one with an object, a set + * or a string that is NULL, with no `ret` for an object other than a + * report, with a `reterr` that points to anything but NULL, or with a + * flag or an order that is unknown. If memory runs out or the library + * panics, the process aborts. + * + * - A call is checked in this order: what it is given first, which fails + * with -EINVAL, -E2BIG or -EBADF, then the process it is made in, which + * fails with -ECHILD, and then its options or its writer. Options with a + * feature of partitions fail with -EINVAL in the calls that make a + * manifest writer, the generate functions among them, and a writer fails + * with -ESTALE once it takes nothing more. So a call that is not valid + * fails for that in a child and on such a writer as well, and a child + * gets -ECHILD for options with a feature of partitions. + * + * - Options whose order is UAPI16_ORDER_NONE are for a writer of records. + * The functions that sort refuse them with -EINVAL, where options with + * a feature of partitions fail too: uapi16_manifest_writer_create_at(), + * uapi16_manifest_writer_open(), uapi16_manifest_generate_at() and + * uapi16_manifest_generate(). + * + * - Bytes go in as a pointer and a size, and are copied during the call. + * The pointer is not read where the size is 0. Bytes that are there and + * empty come out as a pointer that is not NULL, with the size 0. + * + * - A set's size is what the program's header says. UAPI16_FEATURES_EMPTY + * or UAPI16_FEATURES_SET() writes it, and the library reads it but never + * writes it. A size above UAPI16_FEATURES_SIZE_MAX fails with -E2BIG and + * one below UAPI16_FEATURES_SIZE_VER0 with -EINVAL, as in clone3. A size + * that is not a multiple of 8 fails with -EINVAL. Calls without a result + * treat such a set as empty and change nothing: has() is false, next() + * is NONE, and equal() is false. + * + * - Set calls work on the bits, by the sizes the sets carry. A word a set + * doesn't have counts as zero. union(), intersect() and subtract() + * change the first set and keep its size. A union drops bits the first + * set has no room for. add() and remove() fail with -EINVAL for NONE, + * and for a number the set has no room for. + * + * - Calls that take a set (set_features, retain_features) follow + * copy_struct_from_user(). Non-zero words past the library's fail with + * -E2BIG, a feature the library doesn't have fails with -EINVAL, and + * nothing changes. + * + * - Getters (default, known, the reader's and the object's) follow + * copy_struct_to_user() with the set's own size. They copy what fits, + * clear the rest of the set, drop what doesn't fit, and return 0. + * + * - A getter of a field that an object does not have fails with -ENODATA + * and stores nothing, or returns NULL for a string. + * + * - A file object that no thread changes can be read from any thread, and + * several threads can open files from one uapi16_directory at the same + * time. + * + * - A reader that failed to read an object or a writer that failed to + * write a record, and a writer of records, a computation and a check + * that are finished, take nothing more: a later call fails with -ESTALE. + */ + +#if (defined(__cplusplus) && __cplusplus >= 201703L) || \ + (!defined(__cplusplus) && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) +# define UAPI16_NODISCARD [[nodiscard]] +#elif defined(__clang__) +# define UAPI16_NODISCARD __attribute__((warn_unused_result)) +#else +# define UAPI16_NODISCARD +#endif''' + +trailer = ''' +/* + * What UAPI16_FEATURES_SET() is made of. + */ +#ifdef __cplusplus +# define UAPI16_FEATURES_U64_(x) static_cast(x) +#else +# define UAPI16_FEATURES_U64_(x) ((uint64_t) (x)) +#endif +#define UAPI16_FEATURES_BIT_(w, f) \ + (UAPI16_FEATURES_U64_((f) != 0 && ((UAPI16_FEATURES_U64_(f) - 1) >> 6) == (w)) << ((UAPI16_FEATURES_U64_(f) - 1) & 63)) +#define UAPI16_FEATURES_OR_1(w, a) UAPI16_FEATURES_BIT_(w, a) +#define UAPI16_FEATURES_OR_2(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_1(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_3(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_2(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_4(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_3(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_5(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_4(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_6(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_5(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_7(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_6(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_8(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_7(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_9(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_8(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_10(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_9(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_11(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_10(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_12(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_11(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_13(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_12(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_14(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_13(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_15(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_14(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_16(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_15(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_17(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_16(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_18(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_17(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_19(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_18(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_20(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_19(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_21(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_20(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_22(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_21(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_23(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_22(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_24(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_23(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_25(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_24(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_26(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_25(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_27(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_26(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_28(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_27(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_29(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_28(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_30(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_29(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_31(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_30(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_32(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_31(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_33(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_32(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_34(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_33(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_35(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_34(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_36(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_35(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_37(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_36(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_38(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_37(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_39(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_38(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_40(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_39(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_41(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_40(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_42(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_41(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_43(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_42(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_44(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_43(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_45(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_44(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_46(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_45(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_47(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_46(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_48(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_47(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_49(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_48(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_50(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_49(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_51(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_50(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_52(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_51(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_53(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_52(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_54(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_53(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_55(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_54(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_56(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_55(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_57(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_56(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_58(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_57(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_59(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_58(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_60(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_59(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_61(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_60(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_62(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_61(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_63(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_62(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_64(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_63(w, __VA_ARGS__) +#define UAPI16_FEATURES_COUNT_N_(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, N, ...) N +#define UAPI16_FEATURES_COUNT_(...) UAPI16_FEATURES_COUNT_N_(__VA_ARGS__, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) +#define UAPI16_FEATURES_CAT2_(a, b) a##b +#define UAPI16_FEATURES_CAT_(a, b) UAPI16_FEATURES_CAT2_(a, b) +#define UAPI16_FEATURES_OR_(w, ...) \ + UAPI16_FEATURES_CAT_(UAPI16_FEATURES_OR_, UAPI16_FEATURES_COUNT_(__VA_ARGS__))(w, __VA_ARGS__) + +/** + * A set of the features given, up to 64 of them: + * `uapi16_features_t s = UAPI16_FEATURES_SET(UAPI16_FEATURE_MTIME, UAPI16_FEATURE_SIZE);`. + * UAPI16_FEATURE_NONE among them is passed over, and so is a number the set + * has no room for. + */ +#define UAPI16_FEATURES_SET(...) \ + { sizeof(uapi16_features_t), { \ + UAPI16_FEATURES_OR_(0, __VA_ARGS__), \ + UAPI16_FEATURES_OR_(1, __VA_ARGS__) \ + } } + +/** + * A set without features: `uapi16_features_t s = UAPI16_FEATURES_EMPTY;`. + */ +#define UAPI16_FEATURES_EMPTY { sizeof(uapi16_features_t), { 0 } } + +/* + * For __attribute__((cleanup(...))): each frees the object that its + * argument points to, unless that is NULL. + */ +static inline void uapi16_manifest_options_freep(uapi16_manifest_options **o) { + if (*o) + *o = uapi16_manifest_options_free(*o); +} + +static inline void uapi16_manifest_writer_freep(uapi16_manifest_writer **w) { + if (*w) + *w = uapi16_manifest_writer_free(*w); +} + +static inline void uapi16_manifest_report_freep(uapi16_manifest_report **r) { + if (*r) + *r = uapi16_manifest_report_free(*r); +} + +static inline void uapi16_error_freep(uapi16_error **e) { + if (*e) + *e = uapi16_error_free(*e); +} + +static inline void uapi16_file_object_freep(uapi16_file_object **o) { + if (*o) + *o = uapi16_file_object_free(*o); +} + +static inline void uapi16_writer_freep(uapi16_writer **w) { + if (*w) + *w = uapi16_writer_free(*w); +} + +static inline void uapi16_signature_freep(uapi16_signature **s) { + if (*s) + *s = uapi16_signature_free(*s); +} + +static inline void uapi16_sha256_freep(uapi16_sha256 **s) { + if (*s) + *s = uapi16_sha256_free(*s); +} + +static inline void uapi16_reader_freep(uapi16_reader **r) { + if (*r) + *r = uapi16_reader_free(*r); +} + +static inline void uapi16_directory_freep(uapi16_directory **d) { + if (*d) + *d = uapi16_directory_free(*d); +} + +static inline void uapi16_data_check_freep(uapi16_data_check **c) { + if (*c) + *c = uapi16_data_check_free(*c); +} + +#endif /* UAPI16_H */''' + +[export] +# No function has an enum as the type of an argument or of what it +# returns, see below, so cbindgen is told to write them. +include = [ + "uapi16_feature_t", + "uapi16_order_t", + "uapi16_add_flag_t", + "uapi16_error_kind_t", + "uapi16_name_problem_t", + "uapi16_read_only_t", + "uapi16_name_order_t", + "uapi16_read_t", + "uapi16_data_location_t", + "uapi16_directory_flag_t", +] + +# In Rust, a function of the C API takes and returns the number of an enum +# as a u64, or as a u32 for a feature, and checks it: an enum of Rust that +# holds a number it has no variant for is undefined behavior, and nothing +# holds a caller in C to the numbers. In C the number has the type of its +# enum, which is as wide. +[export.rename] +"OrderNumber" = "uapi16_order_t" +"ErrorKindNumber" = "uapi16_error_kind_t" +"FeatureNumber" = "uapi16_feature_t" +"NameProblemNumber" = "uapi16_name_problem_t" +"DataLocationNumber" = "uapi16_data_location_t" +"ReadOnlyNumber" = "uapi16_read_only_t" + +[fn] +args = "auto" +# A function that returns an int is #[must_use] in capi.rs. +must_use = "UAPI16_NODISCARD" diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index 2115f43..fa52a7a 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -2,17 +2,13 @@ //! The data of the files a manifest describes: where it is, and copying //! it from there with the sizes and hashes of the manifest checked. -#[cfg(target_os = "linux")] +use std::borrow::Cow; use std::collections::HashMap; use std::fmt; -use std::io::{self, Read, Write}; -#[cfg(target_os = "linux")] -use std::io::{Seek, SeekFrom}; -#[cfg(target_os = "linux")] +use std::io::{self, Read, Seek, SeekFrom, Write}; use std::ops::Range; use crate::digest::Sha256Context; -#[cfg(target_os = "linux")] use crate::directory::PinnedDirectory; use crate::error::{DataProblem, Error, ErrorKind, Field, SourceProblem, UnsupportedData}; use crate::object::{ContentsObject, ContentsSource, FileObject, InodeType}; @@ -26,16 +22,13 @@ const COPY_SIZE: usize = 1024 * 1024; /// file takes besides, see [`PieceHashes::stored_bytes`]. The map that /// holds them adds up to about half a MiB, with many small files, which /// does not grow with the manifest either. -#[cfg(target_os = "linux")] const PIECE_HASH_BYTES: usize = 1024 * 1024; /// What a file takes in [`PieceHashes`] besides the hashes of its pieces: /// its hash and its length, which it is known by, and the pointer to the /// hashes of its pieces. -#[cfg(target_os = "linux")] const FILE_ENTRY_BYTES: usize = size_of::<(Sha256, u64)>() + size_of::>(); /// The most pieces a file is hashed in, so that the hashes of a file of /// any length fit into [`PIECE_HASH_BYTES`]. -#[cfg(target_os = "linux")] const MAX_PIECES: u64 = ((PIECE_HASH_BYTES - FILE_ENTRY_BYTES) / size_of::()) as u64; /// Where the data of a file object is, as [`FileObject::data_location`] @@ -114,9 +107,8 @@ impl<'a> ExternalFile<'a> { /// as long as the object says, whatever else the file holds. So the /// file has to be long enough for it, and as long as `originalSize` /// where the manifest gives that. - #[cfg(target_os = "linux")] - fn check_len(&self, object: &FileObject, len: u64) -> Result { - let name = &object.name; + pub(crate) fn check_len(&self, object: &FileObject, len: u64) -> Result { + let name = object.name(); 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) { @@ -129,7 +121,7 @@ impl<'a> ExternalFile<'a> { ); return Err(mismatch(message).sizes(Some(len), Some(total))); } - let size = object.size.unwrap_or(len.saturating_sub(self.offset)); + let size = object.size().unwrap_or(len.saturating_sub(self.offset)); let end = self.offset.checked_add(size); if end.is_none_or(|end| end > len) { let message = format!( @@ -146,9 +138,8 @@ impl<'a> ExternalFile<'a> { /// The error for the file that the data of `object` cannot be taken /// from. - #[cfg(target_os = "linux")] - fn unavailable(&self, object: &FileObject, error: OpenError) -> Error { - let name = &object.name; + pub(crate) fn unavailable(&self, object: &FileObject, error: OpenError) -> Error { + let name = object.name(); let error = match error { OpenError::NotRegular => { let message = format!( @@ -203,16 +194,16 @@ impl FileObject { /// The error of an object whose data this crate cannot take. fn unsupported(&self) -> Error { - if self.contents.is_empty() { + if self.contents().is_empty() { let message = format!( "'{}' is a {} without contents objects, which has no data", - self.name.as_str().escape_debug(), - self.inode_type + self.name().as_str().escape_debug(), + self.inode_type() ); - return Error::new(ErrorKind::Unsupported(UnsupportedData::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 + .contents() .iter() .map(|contents| match &contents.encoding { Some(encoding) => format!("'{}' encoding", encoding.escape_debug()), @@ -224,11 +215,11 @@ impl FileObject { let ways = ways.join(" or "); let message = format!( "'{}' is only available through {}, which is not supported", - self.name.as_str().escape_debug(), + self.name().as_str().escape_debug(), ways ); Error::new(ErrorKind::Unsupported(UnsupportedData::UrlOrEncoding), message) - .named(self.name.as_str()) + .named(self.name().as_str()) .valued(ways) } @@ -238,22 +229,22 @@ impl FileObject { /// one. The specification implies a contents object for a regular file /// that has none, with the file of its own name. fn unencoded_data(&self) -> Option<(DataLocation<'_>, Option<&ContentsObject>)> { - if self.contents.is_empty() { - let implied = DataLocation::External(ExternalFile::new(&self.name, None)); - return (self.inode_type == InodeType::Regular).then_some((implied, None)); + if self.contents().is_empty() { + let implied = DataLocation::External(ExternalFile::new(self.name(), None)); + return (self.inode_type() == InodeType::Regular).then_some((implied, None)); } let mut file = None; - for contents in self.contents.iter().filter(|contents| contents.encoding.is_none()) { + for contents in self.contents().iter().filter(|contents| contents.encoding.is_none()) { match &contents.source { ContentsSource::Literal(literal) => { let data = self.data_in_literal(literal, contents.offset); return Some((DataLocation::Literal(data), Some(contents))); } ContentsSource::File(name) => { - file.get_or_insert((name, contents)); + file.get_or_insert((name.as_name(), contents)); } ContentsSource::Implied => { - file.get_or_insert((&self.name, contents)); + file.get_or_insert((self.name(), contents)); } ContentsSource::Url(_) => {} } @@ -272,7 +263,7 @@ impl FileObject { pub(crate) fn data_in_literal<'a>(&self, literal: &'a [u8], offset: u64) -> &'a [u8] { let offset = usize::try_from(offset).unwrap_or(usize::MAX); let data = literal.get(offset..).unwrap_or(&[]); - match self.size.map(usize::try_from) { + match self.size().map(usize::try_from) { Some(Ok(size)) => data.get(..size).unwrap_or(data), _ => data, } @@ -292,7 +283,7 @@ impl FileObject { /// lets a consumer that takes a part of a file skip the checks of all /// of it. fn original_sha256_to_check(&self, original_sha256: Option, extent: DataExtent) -> Option { - original_sha256.filter(|&sha256| match (self.sha256, extent) { + original_sha256.filter(|&sha256| match (self.sha256(), extent) { (None, _) => true, (Some(own), DataExtent::WholeFile) => own != sha256, (Some(_), DataExtent::PartOfFile) => false, @@ -354,9 +345,9 @@ impl ContentsObject { } let message = format!( "'{}' is a part of literal contents that do not match the hash in the manifest", - object.name.as_str().escape_debug() + object.name().as_str().escape_debug() ); - Err(Error::new(ErrorKind::Data(DataProblem::HashMismatch), message).named(object.name.as_str())) + Err(Error::new(ErrorKind::Data(DataProblem::HashMismatch), message).named(object.name().as_str())) } } @@ -366,8 +357,7 @@ impl ContentsObject { /// It checks what the object says of its data, the check the /// specification has for the data of every file. What its contents /// objects say of the files the data is in, their sizes and hashes, is -/// for whoever reads those files to check. -#[cfg_attr(target_os = "linux", doc = "A [`DirectoryProvider`] does.")] +/// for whoever reads those files to check. A [`DirectoryProvider`] does. /// /// [`FileObject::copy_data`] checks what it copies with one. A caller /// that moves the data itself, such as a copy in an async runtime, hands @@ -393,7 +383,7 @@ impl ContentsObject { #[derive(Debug)] pub struct DataCheck<'a> { /// The name of the object, which an error carries. - name: &'a Name, + name: Cow<'a, Name>, /// The size the object gives. size: Option, /// The hash the object gives. @@ -408,19 +398,55 @@ impl<'a> DataCheck<'a> { /// A check of the data of `object`, of which nothing has passed yet. pub fn new(object: &'a FileObject) -> DataCheck<'a> { DataCheck { - name: &object.name, - size: object.size, - sha256: object.sha256, - context: object.sha256.map(|_| Sha256Context::default()), + name: Cow::Borrowed(object.name()), + size: object.size(), + sha256: object.sha256(), + context: object.sha256().map(|_| Sha256Context::default()), len: 0, } } + /// The check with a name of its own instead of the one it borrows from + /// its object, with what passed so far. The C API keeps such a check: + /// its caller can change or free the object while the check is there. + #[cfg(feature = "capi")] + pub(crate) fn into_owned(self) -> DataCheck<'static> { + DataCheck { + name: Cow::Owned(self.name.into_owned()), + size: self.size, + sha256: self.sha256, + context: self.context, + len: self.len, + } + } + /// Takes `data`, the next bytes of the data. Fails, and takes none of /// them, when they would make the data larger than the size the object /// gives. pub fn update(&mut self, data: &[u8]) -> Result<(), Error> { - let added = data.len() as u64; + self.count(data.len() as u64)?; + if let Some(context) = &mut self.context { + context.update(data); + } + Ok(()) + } + + /// Takes `size` zero bytes as the next bytes of the data, such as a + /// hole of a sparse file that the caller did not read. Fails, and takes + /// none of them, when they would make the data larger than the size the + /// object gives. + pub fn update_zeros(&mut self, size: u64) -> Result<(), Error> { + self.count(size)?; + if let Some(context) = &mut self.context { + context.update_zeros(size); + } + Ok(()) + } + + /// Counts `added` more bytes of the data. Fails, and counts none of + /// them, when they would make the data larger than the size the object + /// gives. + fn count(&mut self, added: u64) -> Result<(), Error> { 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", @@ -431,9 +457,6 @@ impl<'a> DataCheck<'a> { .named(self.name.as_str()) .sizes(None, Some(size))); } - if let Some(context) = &mut self.context { - context.update(data); - } self.len = self.len.saturating_add(added); Ok(()) } @@ -508,15 +531,11 @@ pub(crate) mod sealed { /// manifest. /// /// [`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 +/// order of the manifest. [`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 @@ -544,7 +563,6 @@ pub trait DataProvider: sealed::Sealed { } /// Why a [`Directory`] does not hand out a file. -#[cfg(target_os = "linux")] #[derive(Debug)] pub(crate) enum OpenError { /// What the name names is not a regular file. @@ -554,7 +572,6 @@ pub(crate) enum OpenError { Io(io::Error), } -#[cfg(target_os = "linux")] impl From for OpenError { fn from(e: io::Error) -> OpenError { OpenError::Io(e) @@ -572,7 +589,6 @@ impl From for OpenError { /// /// 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; @@ -609,18 +625,13 @@ pub(crate) trait Directory { /// specification allows. So the memory the provider takes does not grow /// with the manifest, and while copies succeed, a file of more than one /// piece is read whole once at most for its parts. -/// -/// It exists on Linux only, not on Android. -#[cfg(target_os = "linux")] #[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 { @@ -630,7 +641,6 @@ impl DirectoryProvider { } } -#[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) @@ -639,7 +649,6 @@ impl DataProvider for DirectoryProvider { /// 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. @@ -648,7 +657,6 @@ struct Provider { hashes: PieceHashes, } -#[cfg(target_os = "linux")] impl Provider { /// A provider that takes the files from `directory`. fn new(directory: D) -> Provider { @@ -660,7 +668,6 @@ impl Provider { } } -#[cfg(target_os = "linux")] impl fmt::Debug for Provider { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Provider") @@ -686,7 +693,6 @@ impl fmt::Debug for Provider { /// 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. @@ -695,7 +701,6 @@ 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 @@ -745,7 +750,6 @@ impl PieceHashes { } } -#[cfg(target_os = "linux")] impl fmt::Debug for PieceHashes { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PieceHashes") @@ -756,8 +760,7 @@ impl fmt::Debug for PieceHashes { } /// 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. +/// stream fails the first two ways only. #[derive(Debug)] enum CopyFailure { /// Reading the file or the stream failed. @@ -765,11 +768,9 @@ 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, } @@ -777,7 +778,7 @@ impl CopyFailure { /// The error of a copy of the data of `object` from `place`, its file /// or the stream, that failed so. fn into_error(self, object: &FileObject, place: &str) -> Error { - let name = &object.name; + let name = object.name(); let (problem, what) = match self { CopyFailure::ReadFailed(error) => { let message = format!("{}: failed to read {}: {}", name.as_str().escape_debug(), place, error); @@ -843,7 +844,6 @@ impl ReadSome for R {} /// A file a [`DirectoryProvider`] copies the data of an object from, in /// pieces where it checks them. -#[cfg(target_os = "linux")] struct Pieces<'a, F> { file: F, /// What the file is read into: [`COPY_SIZE`] bytes. @@ -858,7 +858,6 @@ 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. @@ -979,7 +978,6 @@ impl Pieces<'_, F> { } } -#[cfg(target_os = "linux")] impl Provider { /// Copies the data of `object`, which is in `file`, to `sink`, see /// [`DataProvider::copy`]. @@ -1092,7 +1090,7 @@ impl fmt::Debug for StreamProvider { impl DataProvider for StreamProvider { fn copy(&mut self, object: &FileObject, file: &ExternalFile<'_>, sink: &mut dyn Write) -> Result<(), Error> { - let name = &object.name; + let name = object.name(); if file.offset != 0 { let message = format!( "{}: an offset cannot be used with streamed contents", @@ -1102,7 +1100,7 @@ impl DataProvider for StreamProvider { Error::new(ErrorKind::Unsupported(UnsupportedData::OffsetInStream), message).named(name.as_str()), ); } - let Some(size) = object.size else { + let Some(size) = object.size() else { let message = format!("{}: streamed contents need a known size", name.as_str().escape_debug()); return Err(Error::new(ErrorKind::Unsupported(UnsupportedData::NoSize), message) .at(Field::Size) @@ -1183,9 +1181,7 @@ impl DataProvider for StreamProvider { } } -// The tests build their directories in memory, and DirectoryProvider is -// for Linux only. -#[cfg(all(test, target_os = "linux"))] +#[cfg(test)] mod tests { use super::*; use crate::error::Problem; @@ -1491,10 +1487,14 @@ mod tests { for (o, kind) in none.iter().zip(["dir", "fifo", "lnk"]) { let e = o.data_location().unwrap_err(); assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedData::Absent)); - assert_eq!(e.name(), Some(o.name.as_str())); + 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) + format!( + "'{}' is a {} without contents objects, which has no data", + o.name(), + kind + ) ); assert!(!o.has_external_data()); let e = copy(o, &mut provider).unwrap_err(); @@ -1718,7 +1718,7 @@ mod tests { let mut o = object(&format!(r#"{}"{}"}}]}}"#, record, HELLO)); assert_eq!(copy(&o, &mut provider).unwrap(), data.as_bytes()); assert_eq!(refused(&format!(r#"{}"{}"}}]}}"#, record, WORLD)), contradiction); - o.contents[0].original_sha256 = WORLD.parse().ok(); + o.contents_mut()[0].original_sha256 = WORLD.parse().ok(); let e = copy(&o, &mut provider).unwrap_err(); assert_eq!( facts(&e), @@ -1740,7 +1740,7 @@ mod tests { }; assert_eq!(refused(&record(WORLD)), contradiction); let mut o = object(&record(HELLO)); - o.contents[0].original_sha256 = WORLD.parse().ok(); + o.contents_mut()[0].original_sha256 = WORLD.parse().ok(); assert_eq!(copy(&o, &mut provider).unwrap(), b"he"); // A literal that is not what the object says. let record = format!( @@ -1749,10 +1749,10 @@ mod tests { ); assert_eq!(refused(&record), contradiction); let mut o = object(r#"{"name":"x","size":5,"contents":[{"literal":"aGVsbG8="}]}"#); - o.sha256 = WORLD.parse().ok(); + o.set_sha256(WORLD.parse().ok()); assert_eq!(copy(&o, &mut provider).unwrap_err().kind(), hash); let mut o = object(r#"{"name":"x","contents":[{"literal":"aGVsbG8="}]}"#); - o.size = Some(6); + o.set_size(Some(6)); let e = copy(&o, &mut provider).unwrap_err(); assert_eq!( facts(&e), @@ -2448,16 +2448,16 @@ mod tests { r#"{{"name":"x","size":5,"contents":[{{"originalSize":5,"originalSha256":"{}"}}]}}"#, HELLO )); - assert_eq!(sized.sha256, HELLO.parse().ok()); + assert_eq!(sized.sha256(), HELLO.parse().ok()); assert_eq!(check(&sized, b"hello").unwrap(), b"hello"); assert_eq!(check(&sized, b"world").unwrap_err().kind(), hash); // An object that is all of its file without a hash of its own. let mut whole = FileObject::new(NameBuf::new("x").unwrap()); - whole.size = Some(5); + whole.set_size(Some(5)); let mut contents = ContentsObject::new(ContentsSource::Implied); contents.original_size = Some(5); contents.original_sha256 = HELLO.parse().ok(); - whole.contents.push(contents); + whole.put_contents(vec![contents]); assert_eq!(check(&whole, b"hello").unwrap(), b"hello"); let e = check(&whole, b"world").unwrap_err(); assert_eq!( @@ -2491,8 +2491,8 @@ mod tests { ), ] { let o = object(&record); - assert_eq!(o.sha256, None); - let data: &'static [u8] = if o.size == Some(2) { b"xx" } else { b"world" }; + assert_eq!(o.sha256(), None); + let data: &'static [u8] = if o.size() == Some(2) { b"xx" } else { b"world" }; assert_eq!(check(&o, data).unwrap(), data, "{}", record); } // A stream has no place for a file without a size or at an offset. @@ -2632,6 +2632,151 @@ mod tests { } } + /// A run of zero bytes passes a check as the same bytes do that are + /// handed to it as data: they are counted and hashed. A run that would + /// make the data larger than the object says is refused, and none of + /// it is taken. + #[test] + fn checks_runs_of_zeros() { + // A sparse file: a hole, data, and a hole at its end. + let data = [&[0u8; 5000][..], b"hello", &[0; 3]].concat(); + let size = data.len() as u64; + let o = object(&format!( + r#"{{"name":"x","size":{},"sha256":"{}"}}"#, + size, + Sha256::digest(&data) + )); + let mut check = DataCheck::new(&o); + check.update(&data).unwrap(); + assert_eq!(check.finish().unwrap(), size); + let mut check = DataCheck::new(&o); + check.update_zeros(5000).unwrap(); + check.update(b"hello").unwrap(); + check.update_zeros(0).unwrap(); + check.update_zeros(3).unwrap(); + assert_eq!(check.finish().unwrap(), size); + // A hole in two runs, and holes of which a part is read as data. + let mut check = DataCheck::new(&o); + check.update_zeros(1).unwrap(); + check.update_zeros(4096).unwrap(); + check.update(&[0; 903]).unwrap(); + check.update(b"hello\0").unwrap(); + check.update_zeros(2).unwrap(); + assert_eq!(check.finish().unwrap(), size); + // Zero bytes where the data has others, and too few of them. + let mut check = DataCheck::new(&o); + check.update_zeros(size).unwrap(); + let e = check.finish().unwrap_err(); + assert_eq!( + facts(&e), + ( + ErrorKind::Data(DataProblem::HashMismatch), + Some("x"), + None, + None, + "'x' does not match the hash in the manifest".to_string() + ) + ); + let mut check = DataCheck::new(&o); + check.update_zeros(5000).unwrap(); + check.update(b"hello").unwrap(); + check.update_zeros(2).unwrap(); + let e = check.finish().unwrap_err(); + assert_eq!( + facts(&e), + ( + ErrorKind::Data(DataProblem::SizeMismatch), + Some("x"), + Some(5007), + Some(5008), + "'x' is 5007 bytes, the manifest says 5008".to_string() + ) + ); + // Too many of them, after data and as the first bytes. + let mut check = DataCheck::new(&o); + check.update_zeros(5000).unwrap(); + check.update(b"hello").unwrap(); + let e = check.update_zeros(4).unwrap_err(); + assert_eq!( + facts(&e), + ( + ErrorKind::Data(DataProblem::SizeMismatch), + Some("x"), + None, + Some(5008), + "'x' has more than the 5008 bytes the manifest says".to_string() + ) + ); + // What it refused it did not take. + check.update_zeros(3).unwrap(); + assert_eq!(check.finish().unwrap(), size); + let mut check = DataCheck::new(&o); + let e = check.update_zeros(size + 1).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Data(DataProblem::SizeMismatch)); + check.update(&data).unwrap(); + assert_eq!(check.finish().unwrap(), size); + // An object of the size 0 takes a run of no bytes and no other. + let o = object(r#"{"name":"x","size":0}"#); + let mut check = DataCheck::new(&o); + check.update_zeros(0).unwrap(); + let e = check.update_zeros(1).unwrap_err(); + assert_eq!( + (e.kind(), e.found_size(), e.expected_size()), + (ErrorKind::Data(DataProblem::SizeMismatch), None, Some(0)) + ); + assert_eq!(check.finish().unwrap(), 0); + /// A hole of 1 TiB, which no test could hash. + const HOLE: u64 = 1 << 40; + // Without a hash the zero bytes are counted and not hashed, so a + // run of any size takes no time. The size holds for it too. + let o = object(&format!(r#"{{"name":"x","size":{}}}"#, HOLE + 5)); + let mut check = DataCheck::new(&o); + check.update_zeros(HOLE).unwrap(); + let e = check.update_zeros(u64::MAX).unwrap_err(); + assert_eq!( + (e.kind(), e.found_size(), e.expected_size()), + (ErrorKind::Data(DataProblem::SizeMismatch), None, Some(HOLE + 5)) + ); + assert_eq!( + check.update_zeros(6).unwrap_err().kind(), + ErrorKind::Data(DataProblem::SizeMismatch) + ); + check.update(b"hello").unwrap(); + assert_eq!(check.finish().unwrap(), HOLE + 5); + // Without a size and a hash it counts. + let o = object(r#"{"name":"x","contents":[{"url":"https://example.com/x"}]}"#); + let mut check = DataCheck::new(&o); + check.update(b"any").unwrap(); + check.update_zeros(HOLE).unwrap(); + check.update_zeros(2).unwrap(); + assert_eq!(check.finish().unwrap(), HOLE + 5); + // More zero bytes than a number counts are the largest number. + let mut check = DataCheck::new(&o); + check.update_zeros(u64::MAX).unwrap(); + check.update_zeros(u64::MAX).unwrap(); + assert_eq!(check.finish().unwrap(), u64::MAX); + } + + /// A check that has the name of its object as its own goes on where it + /// was, without the object: with what passed so far, and with the name, + /// the size and the hash it holds the data against. + #[cfg(feature = "capi")] + #[test] + fn owned_checks_go_on() { + let o = object(&format!(r#"{{"name":"x","size":5,"sha256":"{}"}}"#, HELLO)); + let mut borrowed = DataCheck::new(&o); + borrowed.update(b"hel").unwrap(); + let mut check = borrowed.into_owned(); + drop(o); + let e = check.update(b"lo!").unwrap_err(); + assert_eq!( + (e.kind(), e.name(), e.expected_size()), + (ErrorKind::Data(DataProblem::SizeMismatch), Some("x"), Some(5)) + ); + check.update(b"lo").unwrap(); + assert_eq!(check.finish().unwrap(), 5); + } + /// Takes a few bytes and then fails. #[derive(Debug)] struct Full(usize); diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index 6a10060..7bed50f 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -93,11 +93,12 @@ enum SizeHashConflict { } /// The object a message is about: `manifest object 5`, and with its name -/// `manifest object 5 (EFI/BOOT)`. +/// `manifest object 5 (EFI/BOOT)`. A file object that is in no manifest +/// yet is `file object (EFI/BOOT)`. #[derive(Clone, Copy)] pub(crate) struct Subject<'a> { - /// The number of the record the object is in. - record_number: u64, + /// The number of the record the object is in, if it is in one. + record_number: Option, name: Option<&'a str>, } @@ -123,15 +124,32 @@ impl<'a> Subject<'a> { /// `record_number`. pub(crate) fn new(object: &'a FileObject, record_number: u64) -> Subject<'a> { Subject { - record_number, - name: (!object.name.is_root()).then_some(object.name.as_str()), + record_number: Some(record_number), + name: (!object.name().is_root()).then_some(object.name().as_str()), + } + } + + /// The file object `object`, which is in no manifest yet. + pub(crate) fn unwritten(object: &'a FileObject) -> Subject<'a> { + Subject { + record_number: None, + name: (!object.name().is_root()).then_some(object.name().as_str()), + } + } + + /// A file object of the record with the number `record_number` that + /// has no name, or whose name is not known yet. + pub(crate) fn unnamed(record_number: u64) -> Subject<'static> { + Subject { + record_number: Some(record_number), + name: None, } } /// The root file object, which the first record holds. pub(crate) fn root() -> Subject<'static> { Subject { - record_number: ROOT_RECORD, + record_number: Some(ROOT_RECORD), name: Some(ROOT_NAME), } } @@ -139,7 +157,10 @@ impl<'a> Subject<'a> { impl fmt::Display for Subject<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "manifest object {}", self.record_number)?; + match self.record_number { + Some(record_number) => write!(f, "manifest object {}", record_number)?, + None => f.write_str("file object")?, + } match self.name { Some(name) => write!(f, " ({})", name.escape_debug()), None => Ok(()), @@ -296,8 +317,8 @@ 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.as_str()); + if !self.object.name().is_root() { + return Some(self.object.name().as_str()); } self.name.as_deref().map(Name::as_str).or(self.invalid_name.as_deref()) } @@ -305,7 +326,7 @@ impl Draft { /// The fields of a partition, which are made when the first of them is /// read. fn gpt(&mut self) -> &mut GptPartition { - self.object.gpt.get_or_insert_with(Box::default) + self.object.gpt_or_default() } /// The first field the draft has that only the file objects after the @@ -315,17 +336,17 @@ impl Draft { fn file_only_field(&self) -> Option { let object = &*self.object; [ - (Field::Size, object.size.is_some()), - (Field::Sha256, object.sha256.is_some()), - (Field::Contents, !object.contents.is_empty()), - (Field::InodeToken, object.inode_token.is_some()), - (Field::Major, object.major.is_some()), - (Field::Minor, object.minor.is_some()), + (Field::Size, object.size().is_some()), + (Field::Sha256, object.sha256().is_some()), + (Field::Contents, !object.contents().is_empty()), + (Field::InodeToken, object.inode_token().is_some()), + (Field::Major, object.major().is_some()), + (Field::Minor, object.minor().is_some()), ] .into_iter() .find_map(|(field, has)| has.then_some(field)) - .or_else(|| object.gpt.as_deref().and_then(GptPartition::first_field)) - .or_else(|| object.dos_flags.feature_fields().map(|(field, _)| field).next()) + .or_else(|| object.gpt().and_then(GptPartition::first_field)) + .or_else(|| object.dos_flags().feature_fields().map(|(field, _)| field).next()) } /// Checks the draft of the first record as the root file object: it @@ -355,15 +376,14 @@ impl Draft { /// The root file object the draft of the first record holds, once /// [`Draft::check_root`] found nothing wrong with it. - fn into_root(self) -> RootObject { - let object = *self.object; + fn into_root(mut self) -> RootObject { RootObject { - inode: object.inode, + inode: std::mem::take(self.object.inode_mut()), file_system: self.file_system, gpt_disk_uuid: self.gpt_disk_uuid, order: self.order, features: self.features, - validity: object.validity, + validity: self.object.validity(), } } @@ -373,11 +393,11 @@ impl Draft { /// follows from them. fn finish(&mut self, record_number: u64) -> Result<(), Error> { let Some(name) = self.name.take() else { - return Err(Error::no_name(record_number)); + return Err(Error::no_name(Subject::unnamed(record_number)).in_record(record_number)); }; let object = &mut *self.object; - object.name = name; - object.inode_type = self.inode_type.unwrap_or(InodeType::Regular); + object.set_name(name); + object.set_inode_type(self.inode_type.unwrap_or(InodeType::Regular)); let subject = Subject::new(object, record_number); object.check_permitted_fields(subject)?; if let Some(field) = self.root_only { @@ -389,7 +409,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, object.contents.iter().map(ContentsObject::data))?; + let data = object.check_consistency(subject, object.contents().iter().map(ContentsObject::data))?; object.fill_in_data(data); Ok(()) } @@ -407,30 +427,30 @@ impl FileObject { /// directory, the fields of a partition on anything but a regular file, /// and flags on anything but a regular file or a directory. pub(crate) fn check_permitted_fields(&self, subject: Subject<'_>) -> Result<(), Error> { - let inode_type = self.inode_type; + let inode_type = self.inode_type(); let not_permitted = |message: String| Error::manifest(Problem::FieldNotPermitted, message); - if self.size.is_some() && !inode_type.has_data() { + 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), ); } - if (self.major.is_some() || self.minor.is_some()) && !inode_type.is_device() { + if (self.major().is_some() || self.minor().is_some()) && !inode_type.is_device() { return Err(not_permitted(format!( "{}: 'major' and 'minor' are not permitted on a {}", subject, inode_type )) .at(Field::Major)); } - if self.inode.mode.is_some() && inode_type == InodeType::Symlink { + if self.inode().mode().is_some() && inode_type == InodeType::Symlink { return Err(not_permitted(format!("{}: 'mode' is not permitted on a symlink", subject)).at(Field::Mode)); } - if self.inode_token.is_some() && inode_type == InodeType::Directory { + if self.inode_token().is_some() && inode_type == InodeType::Directory { return Err( not_permitted(format!("{}: 'inodeToken' is not permitted on a directory", subject)) .at(Field::InodeToken), ); } - if (!self.contents.is_empty() || self.sha256.is_some()) && !inode_type.has_data() { + 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 @@ -438,7 +458,7 @@ impl FileObject { .at(Field::Contents)); } if inode_type != InodeType::Regular { - if let Some(field) = self.gpt.as_deref().and_then(GptPartition::first_field) { + if let Some(field) = self.gpt().and_then(GptPartition::first_field) { return Err( not_permitted(format!("{}: '{}' is not permitted on a {}", subject, field, inode_type)).at(field), ); @@ -450,21 +470,6 @@ 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. Only a contents object a reader takes gives @@ -478,14 +483,14 @@ impl FileObject { pub(crate) fn fill_in_from_contents(&mut self) { // A reader refuses the record of an object with more than // MAX_CONTENTS contents objects, and nothing follows from them. - if self.contents.len() > MAX_CONTENTS { + if self.contents().len() > MAX_CONTENTS { return; } // 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 + .contents() .iter() .map(|contents| { contents @@ -495,7 +500,7 @@ impl FileObject { }) .collect(); let taken = data.iter().all(Option::is_some); - for (contents, data) in self.contents.iter_mut().zip(data) { + for (contents, data) in self.contents_mut().iter_mut().zip(data) { if let Some(data) = data { contents.fill_in(data); } @@ -506,7 +511,7 @@ impl FileObject { return; } let subject = Subject::new(self, ROOT_RECORD); - if let Ok(data) = self.check_consistency(subject, self.contents.iter().map(ContentsObject::data)) { + if let Ok(data) = self.check_consistency(subject, self.contents().iter().map(ContentsObject::data)) { self.fill_in_data(data); } } @@ -528,7 +533,7 @@ impl FileObject { subject: Subject<'_>, contents_data: impl Iterator + Clone, ) -> Result { - self.inode.check_read_only(subject)?; + self.inode().check_read_only(subject)?; // The size and the hash of the object and those of its contents // objects have to agree where they are about the same data. A part // of the data of a contents object, of the size the object gives, @@ -537,10 +542,10 @@ impl FileObject { // every contents object that gives one has to give the same. A // contents object that is all of the data gives its hash. let mut data = SizeAndHash { - size: self.size, - sha256: self.sha256, + size: self.size(), + sha256: self.sha256(), }; - for (contents, contents_data) in self.contents.iter().zip(contents_data.clone()) { + for (contents, contents_data) in self.contents().iter().zip(contents_data.clone()) { let original = contents_data.original; let Some(total) = original.size else { continue; @@ -550,7 +555,7 @@ impl FileObject { let Some(rest) = total.checked_sub(contents.offset) else { return Err(Error::offset_beyond_data(subject, contents.offset, total)); }; - match (self.size, data.size) { + match (self.size(), data.size) { (Some(stated), _) => { if contents.offset.checked_add(stated).is_none_or(|end| end > total) { return Err(Error::manifest( @@ -611,7 +616,7 @@ impl FileObject { contents_data: impl Iterator, subject: Subject<'_>, ) -> Result<(), Error> { - for (contents, contents_data) in self.contents.iter().zip(contents_data) { + for (contents, contents_data) in self.contents().iter().zip(contents_data) { let Some(literal) = contents.literal().filter(|_| contents.encoding.is_none()) else { continue; }; @@ -642,9 +647,9 @@ impl FileObject { /// counts as having it cleared, and `gptFlags` as 0. Only a regular /// file has `gptFlags`. pub(crate) fn check_partition_flags(&self, features: Features, subject: Subject<'_>) -> Result<(), Error> { - let gpt = self.gpt.as_deref(); + let gpt = self.gpt(); let given = gpt.and_then(|gpt| gpt.flags); - let implied = (self.inode_type == InodeType::Regular && features.contains(Features::GPT_FLAGS)).then_some(0); + let implied = (self.inode_type() == InodeType::Regular && features.contains(Features::GPT_FLAGS)).then_some(0); let Some(flags) = given.or(implied) else { return Ok(()); }; @@ -663,7 +668,7 @@ impl FileObject { ), ( Field::ReadOnly, - self.inode.stated_read_only(), + self.inode().stated_read_only(), Features::READ_ONLY, GptPartition::FLAG_READ_ONLY, ), @@ -700,11 +705,17 @@ impl FileObject { Ok(()) } + /// Whether `id` is a user or a group ID a manifest can have: any but the + /// two that stand for no ID. + pub(crate) fn is_valid_id(id: u32) -> bool { + id != INVALID_ID && id != INVALID_ID_16 + } + /// The user or group ID `id`, the value of `field`, if it is one. The /// two IDs that stand for no ID are none. pub(crate) fn check_id(field: Field, id: u64, subject: Subject<'_>) -> Result { match u32::try_from(id) { - Ok(id) if id != INVALID_ID && id != INVALID_ID_16 => Ok(id), + Ok(id) if FileObject::is_valid_id(id) => Ok(id), _ => Err(Error::manifest( Problem::FieldOutOfRange, format!("{}: {} {} is out of range", subject, field, id), @@ -713,19 +724,24 @@ impl FileObject { } } - /// Checks `name`, the value of `field`, as the name of a user or of a - /// group. systemd's relaxed rules take anything that is not obviously - /// broken or a number in disguise. - pub(crate) fn check_owner_name(field: Field, name: &str, subject: Subject<'_>) -> Result<(), Error> { + /// Whether `name` can be the name of a user or of a group. systemd's + /// relaxed rules take anything that is not obviously broken or a number + /// in disguise. + pub(crate) fn is_owner_name(name: &str) -> bool { let digits = name.strip_prefix('-').unwrap_or(name); - if name.is_empty() + !(name.is_empty() || name.starts_with(' ') || name.ends_with(' ') || name == "." || name == ".." || name.chars().any(|c| c.is_ascii_control() || c == ':' || c == '/') - || digits.bytes().all(|b| b.is_ascii_digit()) - { + || digits.bytes().all(|b| b.is_ascii_digit())) + } + + /// Checks `name`, the value of `field`, as the name of a user or of a + /// group, see [`FileObject::is_owner_name`]. + pub(crate) fn check_owner_name(field: Field, name: &str, subject: Subject<'_>) -> Result<(), Error> { + if !FileObject::is_owner_name(name) { return Err(Error::manifest( Problem::WrongFieldType, format!("{}: {} '{}' is not a valid name", subject, field, name.escape_debug()), @@ -735,10 +751,16 @@ impl FileObject { Ok(()) } - /// Checks `name` as the name of an extended attribute: it is not empty - /// and has no control character. + /// Whether `name` can be the name of an extended attribute: it is not + /// empty and has no control character. + pub(crate) fn is_xattr_name(name: &str) -> bool { + !name.is_empty() && !name.chars().any(|c| c.is_ascii_control()) + } + + /// Checks `name` as the name of an extended attribute, see + /// [`FileObject::is_xattr_name`]. pub(crate) fn check_xattr_name(name: &str, subject: Subject<'_>) -> Result<(), Error> { - if name.is_empty() || name.chars().any(|c| c.is_ascii_control()) { + if !FileObject::is_xattr_name(name) { return Err(Error::manifest( Problem::InvalidExtendedAttributes, format!("{}: invalid extended attribute name '{}'", subject, name.escape_debug()), @@ -763,7 +785,7 @@ impl InodeAttributes { /// `readOnly` a reader filled in is not one the attributes have, see /// [`FilledIn`](crate::FilledIn). fn check_read_only(&self, subject: Subject<'_>) -> Result<(), Error> { - match (self.stated_read_only(), self.mode) { + match (self.stated_read_only(), self.mode()) { (Some(read_only), Some(mode)) if read_only == mode.is_writable() => Err(Error::manifest( Problem::Contradiction, format!("{}: 'readOnly' and 'mode' contradict each other", subject), @@ -1304,12 +1326,17 @@ impl<'a> RecordDecoder<'a> { }) } + /// Notes the error `error` makes, unless an error was noted before. + fn note(&mut self, error: impl FnOnce() -> Error) { + if self.first_error.is_none() { + self.first_error = Some(error()); + } + } + /// Notes the error `problem` in `field`, which `message` describes, /// unless an error was noted before. fn note_error(&mut self, problem: Problem, field: Field, message: impl FnOnce() -> String) { - if self.first_error.is_none() { - self.first_error = Some(Error::manifest(problem, message()).at(field)); - } + self.note(|| Error::manifest(problem, message()).at(field)); } /// The value `checked` holds, or None after noting its error, unless an @@ -1328,10 +1355,7 @@ impl<'a> RecordDecoder<'a> { if self.record_number == ROOT_RECORD { return Subject::root(); } - Subject { - record_number: self.record_number, - name: None, - } + Subject::unnamed(self.record_number) } /// What the part made of `value`, which is none for null. A value of @@ -1423,10 +1447,10 @@ impl<'a> RecordDecoder<'a> { } /// The name of a user or of a group `value` is. - fn user_or_group_name(&mut self, field: Field, value: Value<'a, T>) -> Option> { + fn user_or_group_name(&mut self, field: Field, value: Value<'a, T>) -> Option { let name = self.string(field, value)?; let checked = FileObject::check_owner_name(field, &name, self.subject()); - self.note_err(checked).map(|()| name.into()) + self.note_err(checked).map(|()| name.into_owned()) } /// The UUID `value` is. @@ -1492,8 +1516,9 @@ impl<'a> RecordDecoder<'a> { Ok(name) => draft.name = Some(name.to_owned()), Err(reason) => { let subject = self.subject(); - self.note_error(Problem::InvalidName, field, || { - format!("{}: {}: '{}'", subject, reason, name.escape_debug()) + self.note(|| { + let message = format!("{}: {}: '{}'", subject, reason, name.escape_debug()); + Error::manifest(Problem::InvalidName, message).at(field).because(reason) }); draft.invalid_name = Some(name.into_owned()); } @@ -1511,27 +1536,27 @@ impl<'a> RecordDecoder<'a> { } } } - Field::Size => object.size = self.unsigned(field, value), - Field::Mode => object.inode.mode = self.mode(field, value), - Field::Uid => object.inode.uid = self.id(field, value), - Field::Gid => object.inode.gid = self.id(field, value), - Field::UserName => object.inode.user_name = self.user_or_group_name(field, value), - Field::GroupName => object.inode.group_name = self.user_or_group_name(field, value), - Field::Major => object.major = self.unsigned(field, value), - Field::Minor => object.minor = self.unsigned(field, value), - Field::MTimeNSec => object.inode.mtime_nsec = self.unsigned(field, value), + Field::Size => object.set_size(self.unsigned(field, value)), + Field::Mode => object.inode_mut().set_mode(self.mode(field, value)), + Field::Uid => object.inode_mut().set_uid(self.id(field, value)), + Field::Gid => object.inode_mut().set_gid(self.id(field, value)), + Field::UserName => object.inode_mut().set_user_name(self.user_or_group_name(field, value)), + Field::GroupName => object.inode_mut().set_group_name(self.user_or_group_name(field, value)), + Field::Major => object.set_major(self.unsigned(field, value)), + Field::Minor => object.set_minor(self.unsigned(field, value)), + Field::MTimeNSec => object.inode_mut().set_mtime_nsec(self.unsigned(field, value)), // The token 0 is that of a file with one name. - Field::InodeToken => object.inode_token = self.unsigned(field, value).and_then(NonZeroU64::new), + Field::InodeToken => object.set_inode_token(self.unsigned(field, value).and_then(NonZeroU64::new)), Field::GptLabel => draft.gpt().label = self.gpt_label(field, value), Field::GptUuid => draft.gpt().uuid = self.uuid(field, value), Field::GptTypeUuid => draft.gpt().type_uuid = self.uuid(field, value), Field::GptFlags => draft.gpt().flags = self.unsigned(field, value), Field::GptFlagNoAuto => draft.gpt().no_auto = self.bool(field, value), Field::GptFlagGrowFileSystem => draft.gpt().grow_file_system = self.bool(field, value), - Field::ReadOnly => object.inode.read_only = self.bool(field, value), + Field::ReadOnly => object.inode_mut().set_read_only(self.bool(field, value)), Field::FlagHidden | Field::FlagSystem | Field::FlagArchive => { if let (Some(flag), Some(set)) = (DosFlags::from_field(field), self.bool(field, value)) { - object.dos_flags.put(flag, Some(set)); + object.put_dos_flag(flag, Some(set)); } } Field::FlagAppendOnly @@ -1540,7 +1565,7 @@ impl<'a> RecordDecoder<'a> { | Field::FlagNoCow | Field::FlagNoDump => { if let (Some(flag), Some(set)) = (InodeFlags::from_field(field), self.bool(field, value)) { - object.inode.flags.put(flag, Some(set)); + object.inode_mut().put_flag(flag, Some(set)); } } Field::FatSerial => { @@ -1563,14 +1588,16 @@ impl<'a> RecordDecoder<'a> { draft.root_only.get_or_insert(field); draft.order = self.order(field, value); } - Field::Sha256 => object.sha256 = self.digest(field, value), - Field::ValidSinceUSec => object.validity.since_usec = self.unsigned(field, value).unwrap_or_default(), - Field::ValidUntilUSec => object.validity.until_usec = self.unsigned(field, value), + Field::Sha256 => object.set_sha256(self.digest(field, value)), + Field::ValidSinceUSec => { + object.validity_mut().since_usec = self.unsigned(field, value).unwrap_or_default(); + } + Field::ValidUntilUSec => object.validity_mut().until_usec = self.unsigned(field, value), // A value the specification does not have yet is good. Field::Validity => { let validity = self.string(field, value); if validity.is_some_and(|validity| validity == Validity::Revoked.as_str()) { - object.validity.state = Validity::Revoked; + object.validity_mut().state = Validity::Revoked; } } _ => {} @@ -1612,14 +1639,14 @@ impl<'a> Part<'a> for FileObjectRecord { let user = decoder.part(value, Problem::InvalidExtendedAttributes, field, || { format!("{}: 'extendedAttributes' is not an object", subject) }); - draft.object.inode.user_xattrs = user.flatten().map(Box::new); + draft.object.inode_mut().set_user_xattrs(user.flatten()); } Field::Contents => { let value = members.value(decoder.seed(ContentsArray))?; let contents = decoder.part(value, Problem::WrongFieldType, field, || { format!("manifest field '{}' is not an array", field) }); - draft.object.contents = contents.unwrap_or_default(); + draft.object.put_contents(contents.unwrap_or_default()); } Field::Features => { let value = members.value(decoder.seed(FeatureNames))?; @@ -2077,6 +2104,7 @@ mod tests { use super::*; use crate::error::ErrorKind; use crate::testing::{read_whole, sequence, EMPTY, HELLO, MAX_NESTING, ROOT, SIGNATURE, TRAILER, WORLD}; + use crate::NameProblem; /// The file object of `record`, the record after the root file object. fn object(record: &str) -> FileObject { @@ -2111,56 +2139,56 @@ mod tests { ), HELLO, WORLD )); - assert_eq!(o.name, "dir/file"); - assert_eq!(o.inode_type, InodeType::Regular); - assert_eq!(o.size, Some(5)); - 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")); - assert_eq!((o.major, o.minor), (None, None)); - assert_eq!(o.inode.mtime_nsec, Some(1_700_000_000_000_000_005)); - assert_eq!(o.inode_token, NonZeroU64::new(7)); - let attributes = o.inode.user_xattrs.as_ref().unwrap(); + assert_eq!(o.name(), "dir/file"); + assert_eq!(o.inode_type(), InodeType::Regular); + assert_eq!(o.size(), Some(5)); + 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(), Some("Domain Users")); + assert_eq!(o.inode().group_name(), Some("users")); + assert_eq!((o.major(), o.minor()), (None, None)); + assert_eq!(o.inode().mtime_nsec(), Some(1_700_000_000_000_000_005)); + assert_eq!(o.inode_token(), NonZeroU64::new(7)); + let attributes = o.inode().user_xattr_map().unwrap(); let listed: Vec<(&str, &[u8])> = attributes.iter().map(|(k, v)| (k.as_str(), &v[..])).collect(); assert_eq!(listed, [("a", &b"x"[..]), ("b", &[0, 0xff])]); - let gpt = o.gpt.as_deref().unwrap(); + let gpt = o.gpt().unwrap(); let uuid: Uuid = "4f68bce3-e8cd-4db1-96e7-fbcaf984b709".parse().unwrap(); assert_eq!(gpt.label.as_deref(), Some("root")); assert_eq!((gpt.uuid, gpt.type_uuid), (Some(uuid), Some(uuid))); assert_eq!(gpt.flags, Some(GptPartition::FLAG_NO_AUTO)); assert_eq!((gpt.no_auto, gpt.grow_file_system), (Some(true), Some(false))); - assert_eq!(o.inode.read_only, Some(false)); - assert_eq!(o.sha256, HELLO.parse().ok()); - assert_eq!(o.contents.len(), 2); - assert_eq!(o.contents[0].url(), Some("https://example.com/x")); - assert_eq!(o.contents[1].file().map(Name::as_str), Some("blob")); - assert_eq!((o.contents[1].offset, o.contents[1].original_size), (2, Some(7))); - assert_eq!(o.contents[1].original_sha256, WORLD.parse().ok()); - assert_eq!((o.validity.since_usec, o.validity.until_usec), (10, Some(20))); - assert_eq!(o.validity.state, Validity::Revoked); + assert_eq!(o.inode().read_only(), Some(false)); + assert_eq!(o.sha256(), HELLO.parse().ok()); + assert_eq!(o.contents().len(), 2); + assert_eq!(o.contents()[0].url(), Some("https://example.com/x")); + assert_eq!(o.contents()[1].file().map(Name::as_str), Some("blob")); + assert_eq!((o.contents()[1].offset, o.contents()[1].original_size), (2, Some(7))); + assert_eq!(o.contents()[1].original_sha256, WORLD.parse().ok()); + assert_eq!((o.validity().since_usec, o.validity().until_usec), (10, Some(20))); + assert_eq!(o.validity().state, Validity::Revoked); // The fields of the other inode types. let o = object(r#"{"name":"null","type":"chr","major":1,"minor":3,"mode":438}"#); assert_eq!( - (o.inode_type, o.major, o.minor), + (o.inode_type(), o.major(), o.minor()), (InodeType::CharDevice, Some(1), Some(3)) ); let o = object(r#"{"name":"sda","type":"blk","major":18446744073709551615}"#); assert_eq!( - (o.inode_type, o.major, o.minor), + (o.inode_type(), o.major(), o.minor()), (InodeType::BlockDevice, Some(u64::MAX), None) ); let o = object(r#"{"contents":[{"literal":"YS50eHQ="}],"name":"link","size":5,"type":"lnk"}"#); - assert_eq!(o.inode_type, InodeType::Symlink); - assert_eq!(o.contents[0].literal(), Some(&b"a.txt"[..])); + assert_eq!(o.inode_type(), InodeType::Symlink); + assert_eq!(o.contents()[0].literal(), Some(&b"a.txt"[..])); for (name, inode_type) in [ ("fifo", InodeType::Fifo), ("sock", InodeType::Socket), ("dir", InodeType::Directory), ] { assert_eq!( - object(&format!(r#"{{"name":"x","type":"{}"}}"#, name)).inode_type, + object(&format!(r#"{{"name":"x","type":"{}"}}"#, name)).inode_type(), inode_type ); } @@ -2183,12 +2211,12 @@ mod tests { | Features::READ_ONLY | Features::GPT_DISK_UUID ); - assert_eq!(root.inode.user_xattrs.as_deref().map(BTreeMap::len), Some(0)); + assert_eq!(root.inode.user_xattr_map().map(BTreeMap::len), Some(0)); assert_eq!( - (root.inode.uid, root.inode.gid, root.inode.mode), + (root.inode.uid(), root.inode.gid(), root.inode.mode()), (Some(1000), Some(1000), Some(Mode::new(0o775).unwrap())) ); - assert_eq!(root.inode.read_only, Some(false)); + assert_eq!(root.inode.read_only(), Some(false)); assert_eq!(root.gpt_disk_uuid, Some(uuid)); assert_eq!(root.validity.until_usec, Some(20)); // Saying that it has no name, that it is a directory or that it is @@ -2319,7 +2347,7 @@ mod tests { // Integers are numbers of up to 64 bits. for (text, size) in [("5", 5), ("0", 0), ("18446744073709551615", u64::MAX)] { assert_eq!( - object(&format!(r#"{{"name":"x","size":{}}}"#, text)).size, + object(&format!(r#"{{"name":"x","size":{}}}"#, text)).size(), Some(size), "{}", text @@ -2347,7 +2375,7 @@ mod tests { // no strings of octal digits. for (text, mode) in [("420", 0o644), ("4095", 0o7777), ("0", 0)] { assert_eq!( - object(&format!(r#"{{"name":"x","mode":{}}}"#, text)).inode.mode, + object(&format!(r#"{{"name":"x","mode":{}}}"#, text)).inode().mode(), Some(Mode::new(mode).unwrap()), "{}", text @@ -2365,10 +2393,13 @@ mod tests { // The largest ID, and the token of a file with one name. An ID is // any below (uid_t) -1 but the one that is -1 in 16 bits. assert_eq!( - object(r#"{"name":"x","uid":4294967294,"gid":65534}"#).inode.uid, + object(r#"{"name":"x","uid":4294967294,"gid":65534}"#).inode().uid(), Some(u32::MAX - 1) ); - assert_eq!(object(r#"{"name":"x","uid":65536,"gid":65534}"#).inode.gid, Some(65534)); + assert_eq!( + object(r#"{"name":"x","uid":65536,"gid":65534}"#).inode().gid(), + Some(65534) + ); for (record, field) in [ (r#"{"name":"x","uid":65535}"#, Field::Uid), (r#"{"name":"x","gid":65535}"#, Field::Gid), @@ -2383,8 +2414,11 @@ mod tests { record ); } - assert_eq!(object(r#"{"name":"x","inodeToken":0}"#).inode_token, None); - assert_eq!(object(r#"{"name":"x","type":"dir","inodeToken":0}"#).inode_token, None); + assert_eq!(object(r#"{"name":"x","inodeToken":0}"#).inode_token(), None); + assert_eq!( + object(r#"{"name":"x","type":"dir","inodeToken":0}"#).inode_token(), + None + ); // Any validity but revoked is good. for (text, validity) in [ ("good", Validity::Good), @@ -2395,7 +2429,7 @@ mod tests { ] { assert_eq!( object(&format!(r#"{{"name":"x","validity":"{}"}}"#, text)) - .validity + .validity() .state, validity, "{:?}", @@ -2409,17 +2443,17 @@ mod tests { name, name )); assert_eq!( - (o.inode.user_name.as_deref(), o.inode.group_name.as_deref()), + (o.inode().user_name(), o.inode().group_name()), (Some(name), Some(name)) ); } // A partition label has room for 36 UTF-16 units. let label = "x".repeat(GptPartition::LABEL_MAX); let o = object(&format!(r#"{{"name":"x","gptLabel":"{}"}}"#, label)); - assert_eq!(o.gpt.unwrap().label, Some(label)); + assert_eq!(o.gpt().unwrap().label, Some(label)); let pairs = "\u{1f600}".repeat(GptPartition::LABEL_MAX / 2); assert!(object(&format!(r#"{{"name":"x","gptLabel":"{}"}}"#, pairs)) - .gpt + .gpt() .is_some()); for label in [ format!("{}x", pairs), @@ -2436,9 +2470,10 @@ mod tests { // The longest name, and one byte more. A component is not limited // on its own. let name = "x".repeat(Name::MAX_LEN); - assert_eq!(object(&format!(r#"{{"name":"{}"}}"#, name)).name, name.as_str()); + assert_eq!(object(&format!(r#"{{"name":"{}"}}"#, name)).name(), name.as_str()); let e = refused(&format!(r#"{{"name":"{}x"}}"#, name)); assert_eq!(e.kind(), ErrorKind::Manifest(Problem::InvalidName)); + assert_eq!(e.name_problem(), Some(NameProblem::TooLong)); assert_eq!( e.to_string(), format!("manifest object 1: name is longer than 4095 bytes: '{}x'", name) @@ -2448,10 +2483,27 @@ mod tests { // of place. let e = refused(r#"{"name":"Uapi16Manifest/x"}"#); assert_eq!(e.kind(), ErrorKind::Manifest(Problem::InvalidName)); + assert_eq!(e.name_problem(), Some(NameProblem::Reserved)); assert_eq!( e.to_string(), "manifest object 1: name is reserved for the manifest: 'Uapi16Manifest/x'" ); + // A contents object that refers to its file by what is not a name + // says why it is not one. + for (file, reason) in [ + ("../x", NameProblem::ContainsDotComponent), + ("a//b", NameProblem::EmptyComponent), + ("Uapi16Manifest.sig", NameProblem::Reserved), + ] { + let e = refused(&format!(r#"{{"name":"x","contents":[{{"file":"{}"}}]}}"#, file)); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::InvalidContents), "{}", file); + assert_eq!( + (e.field(), e.name_problem()), + (Some(Field::File), Some(reason)), + "{}", + file + ); + } } /// A `readOnly` the reader filled in is not one the object has: the @@ -2462,16 +2514,16 @@ mod tests { let root = r#"{"mediaType":"application/vnd.uapi.16.manifest","features":["mode","read-only"],"mode":365}"#; let m = read_whole(&sequence(&[root, r#"{"name":"x","mode":292}"#, TRAILER])).unwrap(); let (root, object) = (&m.root, &m.objects[0]); - for inode in [&root.inode, &object.inode] { - assert_eq!(inode.read_only, Some(false)); - assert!(inode.filled_in.contains(Field::ReadOnly)); + for inode in [&root.inode, object.inode()] { + assert_eq!(inode.read_only(), Some(false)); + assert!(inode.marks().contains(Field::ReadOnly)); assert!(!inode.is_read_only()); } assert!(root.check_consistency().is_ok()); let subject = Subject::new(object, 1); assert_eq!( object - .check_consistency(subject, object.contents.iter().map(ContentsObject::data)) + .check_consistency(subject, object.contents().iter().map(ContentsObject::data)) .unwrap(), SizeAndHash::default() ); @@ -2481,9 +2533,13 @@ mod tests { ); // A readOnly the object has is held against its mode. let mut given = object.clone(); - given.inode.filled_in.remove(Field::ReadOnly); + let read_only = given.inode().read_only(); + given.inode_mut().set_read_only(read_only); let e = given - .check_consistency(Subject::new(&given, 1), given.contents.iter().map(ContentsObject::data)) + .check_consistency( + Subject::new(&given, 1), + given.contents().iter().map(ContentsObject::data), + ) .unwrap_err(); assert_eq!( (e.kind(), e.field()), @@ -2499,7 +2555,7 @@ mod tests { let check = |object: &FileObject| { let subject = Subject::new(object, 1); let contents_data = object - .contents + .contents() .iter() .map(|contents| contents.check_consistency(subject)) .collect::, _>>()?; @@ -2507,8 +2563,8 @@ mod tests { }; let file = |size: Option, contents: ContentsObject| { let mut object = FileObject::new(NameBuf::new("x").unwrap()); - object.size = size; - object.contents = vec![contents]; + object.set_size(size); + object.put_contents(vec![contents]); object }; let hello = || ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())); @@ -2524,11 +2580,11 @@ mod tests { let mut headers = ContentsObject::new(ContentsSource::File(NameBuf::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(); + empty.put_contents(Vec::new()); + empty.set_sha256(EMPTY.parse().ok()); let mut read_only = file(None, hello()); - read_only.inode.mode = Some(Mode::new(0o644).unwrap()); - read_only.inode.read_only = Some(true); + read_only.inode_mut().set_mode(Some(Mode::new(0o644).unwrap())); + read_only.inode_mut().set_read_only(Some(true)); for (object, record) in [ ( file(None, beyond), @@ -2731,12 +2787,12 @@ mod tests { #[test] fn flags_and_the_file_system() { let o = object(r#"{"name":"x","flagHidden":true,"flagArchive":false,"flagNoCow":null}"#); - assert_eq!(o.dos_flags.get(DosFlags::HIDDEN), Some(true)); - assert_eq!(o.dos_flags.get(DosFlags::ARCHIVE), Some(false)); - assert_eq!(o.inode.flags.get(InodeFlags::NO_COW), None); + assert_eq!(o.dos_flags().get(DosFlags::HIDDEN), Some(true)); + assert_eq!(o.dos_flags().get(DosFlags::ARCHIVE), Some(false)); + assert_eq!(o.inode().flags().get(InodeFlags::NO_COW), None); let dir = object(r#"{"name":"d","type":"dir","flagImmutable":true,"flagSystem":true}"#); assert_eq!( - (dir.dos_flags.set, dir.inode.flags.set), + (dir.dos_flags().set, dir.inode().flags().set), (DosFlags::SYSTEM, InodeFlags::IMMUTABLE) ); // Only regular files and directories have flags. The root has no @@ -2763,7 +2819,7 @@ mod tests { r#""features":["flag-immutable","x-later","size"]}"# )) .unwrap(); - assert_eq!(root.inode.flags.get(InodeFlags::IMMUTABLE), Some(true)); + assert_eq!(root.inode.flags().get(InodeFlags::IMMUTABLE), Some(true)); assert_eq!( root.stated_features(), Features::FLAG_IMMUTABLE | Features::FAT_SERIAL | Features::FS_UUID | Features::FS_LABEL @@ -2816,7 +2872,7 @@ mod tests { fn extended_attributes() { let attributes = |text: &str| { let object = object(&format!(r#"{{"name":"x","extendedAttributes":{}}}"#, text)); - object.inode.user_xattrs.map(|attributes| *attributes) + object.inode().user_xattr_map().cloned() }; // Nothing is said about the namespace, or it is empty. assert_eq!(attributes("{}"), None); @@ -2848,27 +2904,27 @@ mod tests { let hello: Sha256 = HELLO.parse().unwrap(); // The size 0 and the hash of no data go together. let o = object(r#"{"name":"x","size":0}"#); - assert_eq!((o.size, o.sha256), (Some(0), Some(empty))); + assert_eq!((o.size(), o.sha256()), (Some(0), Some(empty))); let o = object(&format!(r#"{{"name":"x","sha256":"{}"}}"#, EMPTY)); - assert_eq!((o.size, o.sha256), (Some(0), Some(empty))); + assert_eq!((o.size(), o.sha256()), (Some(0), Some(empty))); let o = object(&format!(r#"{{"name":"x","type":"dir","sha256":"{}"}}"#, EMPTY)); - assert_eq!(o.size, Some(0)); + assert_eq!(o.size(), Some(0)); // A literal says how long it is. let o = object(r#"{"name":"x","contents":[{"literal":"aGVsbG8="}]}"#); - assert_eq!(o.size, Some(5)); + assert_eq!(o.size(), Some(5)); assert_eq!( - (o.contents[0].encoded_size, o.contents[0].original_size), + (o.contents()[0].encoded_size, o.contents()[0].original_size), (Some(5), Some(5)) ); let o = object(r#"{"name":"x","contents":[{"literal":"aGVsbG8=","offset":2}]}"#); - assert_eq!(o.size, Some(3)); + assert_eq!(o.size(), Some(3)); let o = object(r#"{"name":"x","contents":[{"literal":""}]}"#); - assert_eq!((o.size, o.sha256), (Some(0), Some(empty))); + assert_eq!((o.size(), o.sha256()), (Some(0), Some(empty))); // An encoded literal says how long the encoded data is. let o = object( r#"{"name":"x","size":5,"contents":[{"literal":"H4sIAAAAAAAAA8tIzcnJBwCGphA2BQAAAA==","encoding":"GZIP"}]}"#, ); - let contents = &o.contents[0]; + let contents = &o.contents()[0]; assert_eq!(contents.encoding.as_deref(), Some("gzip")); assert_eq!((contents.encoded_size, contents.original_size), (Some(25), None)); // Without an encoding the encoded data is the original data. @@ -2876,7 +2932,7 @@ mod tests { r#"{{"name":"x","contents":[{{"file":"a","encodedSize":5,"originalSha256":"{}"}}]}}"#, HELLO )); - let contents = &o.contents[0]; + let contents = &o.contents()[0]; assert_eq!((contents.encoded_size, contents.original_size), (Some(5), Some(5))); assert_eq!( (contents.encoded_sha256, contents.original_sha256), @@ -2884,24 +2940,24 @@ mod tests { ); // The object is the whole of the contents: their size and hash are // its own. - assert_eq!((o.size, o.sha256), (Some(5), Some(hello))); + assert_eq!((o.size(), o.sha256()), (Some(5), Some(hello))); // It is a part of them: the size follows, the hash does not. let o = object(&format!( r#"{{"name":"x","contents":[{{"file":"a","offset":2,"originalSize":5,"originalSha256":"{}"}}]}}"#, HELLO )); - assert_eq!((o.size, o.sha256), (Some(3), None)); + assert_eq!((o.size(), o.sha256()), (Some(3), None)); let o = object(&format!( r#"{{"name":"x","size":3,"sha256":"{}","contents":[{{"file":"a","originalSize":5,"originalSha256":"{}"}}]}}"#, HELLO, WORLD )); - assert_eq!((o.size, o.sha256), (Some(3), Some(hello))); + assert_eq!((o.size(), o.sha256()), (Some(3), Some(hello))); // Every contents object that gives a size gives the same one, // whichever comes first. let o = object( r#"{"name":"x","contents":[{"file":"a","originalSize":5,"offset":1},{"file":"b","originalSize":4}]}"#, ); - assert_eq!(o.size, Some(4)); + assert_eq!(o.size(), Some(4)); for contents in [ [r#"{"file":"a","originalSize":5}"#, r#"{"file":"b","originalSize":4}"#], [r#"{"literal":"YWJj"}"#, r#"{"literal":"YWJjZA=="}"#], @@ -3182,11 +3238,7 @@ mod tests { #[test] fn contents_objects() { - let contents = |text: &str| { - object(&format!(r#"{{"name":"x","contents":[{}]}}"#, text)) - .contents - .remove(0) - }; + let contents = |text: &str| object(&format!(r#"{{"name":"x","contents":[{}]}}"#, text)).contents()[0].clone(); assert_eq!(contents("{}"), ContentsObject::default()); assert_eq!( contents(r#"{"file":null,"url":null,"literal":null,"offset":null,"xHeaders":{"A":"b"}}"#), @@ -3267,7 +3319,7 @@ mod tests { vec![r#"{"literal":"AA=="}"#; n].join(",") ) }; - assert_eq!(object(&many(MAX_CONTENTS)).contents.len(), MAX_CONTENTS); + assert_eq!(object(&many(MAX_CONTENTS)).contents().len(), MAX_CONTENTS); let e = refused(&many(MAX_CONTENTS + 1)); assert_eq!( (e.kind(), e.field()), @@ -3612,6 +3664,17 @@ mod tests { assert_eq!(e.name(), name.as_str(), "{}", line); assert_eq!(e.field().map(Field::as_str), field.as_str(), "{}", line); assert_eq!(Some(e.to_string().as_str()), message.as_str(), "{}", line); + // An invalid name breaks the rule that Name::new() gives, and + // so does an invalid contents file reference. Nothing else is + // about a name. + if found == Problem::InvalidName { + assert_eq!(e.name_problem(), Name::new(e.name().unwrap()).err(), "{}", line); + } else { + let file_reference = found == Problem::InvalidContents && e.field() == Some(Field::File); + assert_eq!(e.name_problem().is_some(), file_reference, "{}", line); + } + let others = (e.hardlink_name(), e.raw_name(), e.feature()); + assert_eq!(others, (None, None, None), "{}", line); problems.insert(found); } // Every problem a manifest can have is among them, but those of diff --git a/src/uapi16/digest.rs b/src/uapi16/digest.rs index c796688..b086174 100644 --- a/src/uapi16/digest.rs +++ b/src/uapi16/digest.rs @@ -121,6 +121,10 @@ impl FromStr for Sha256 { pub struct Sha256Context(sha2::Sha256); impl Sha256Context { + /// The zero bytes [`Sha256Context::update_zeros`] takes at a time. A + /// run of any size goes through them. + const ZEROS: &'static [u8] = &[0; 4096]; + /// A computation that has taken no data yet, the same as the default /// one. pub fn new() -> Sha256Context { @@ -132,6 +136,18 @@ impl Sha256Context { self.0.update(data); } + /// Takes `size` zero bytes as more of the data, such as a hole of a + /// sparse file that the caller did not read. + pub fn update_zeros(&mut self, size: u64) { + let zeros = Sha256Context::ZEROS; + let mut left = size; + while left > 0 { + let piece = usize::try_from(left).map_or(zeros.len(), |left| left.min(zeros.len())); + self.update(&zeros[..piece]); + left -= piece as u64; + } + } + /// Ends the computation and gives the hash of all the data. pub fn finalize(self) -> Sha256 { Sha256(self.0.finalize().into()) @@ -195,6 +211,91 @@ mod tests { assert_eq!(computed(b"hello"), Sha256::digest(b"hello")); } + /// The hash of `data` computed with a context that takes `data` in + /// the pieces `pieces`, each as data or, where it says so, as a run of + /// as many zero bytes. + fn in_pieces(data: &[u8], pieces: &[(usize, bool)]) -> Sha256 { + let mut context = Sha256Context::new(); + let mut rest = data; + for &(size, as_zeros) in pieces { + let (piece, after) = rest.split_at(size); + if as_zeros { + assert!(piece.iter().all(|&byte| byte == 0)); + context.update_zeros(size as u64); + } else { + context.update(piece); + } + rest = after; + } + assert!(rest.is_empty()); + context.finalize() + } + + /// A run of zero bytes gives the hash that as many zero bytes give + /// as data: a run of no bytes, runs around the size of the pieces a run + /// is hashed in, and a run between other data. + #[test] + fn runs_of_zeros() { + // What sha256sum prints for no data, for 4096 zero bytes and for + // 1 MiB of them. + for (size, expected) in [ + (0, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"), + (4096, "ad7facb2586fc6e966c004d7d1d16b024f5805ff7cb47c7a85dabd8b48892ca7"), + ( + 1024 * 1024, + "30e14955ebf1352266dc2ff8067e68104607e750abb9d3b36582b8af909fcb58", + ), + ] { + let mut context = Sha256Context::new(); + context.update_zeros(size); + assert_eq!(context.finalize().to_string(), expected, "{}", size); + } + let piece = Sha256Context::ZEROS.len(); + // 64 bytes are a block of SHA-256. + let sizes = [ + 0, + 1, + 63, + 64, + 65, + piece - 1, + piece, + piece + 1, + 2 * piece - 1, + 2 * piece, + 2 * piece + 1, + 5 * piece + 7, + ]; + for size in sizes { + let zeros = vec![0u8; size]; + assert_eq!(in_pieces(&zeros, &[(size, true)]), Sha256::digest(&zeros), "{}", size); + // Between other data, which leaves a part of a block for the + // run to go on in. + let data = [&b"before"[..], &zeros, b"after"].concat(); + assert_eq!( + in_pieces(&data, &[(6, false), (size, true), (5, false)]), + Sha256::digest(&data), + "{}", + size + ); + // In two runs, in a run and as data, and as data and in a run. + let half = size / 2; + for (first, second) in [(true, true), (true, false), (false, true)] { + assert_eq!( + in_pieces(&zeros, &[(half, first), (size - half, second)]), + Sha256::digest(&zeros), + "{}", + size + ); + } + } + // A run of no bytes takes nothing. + let mut context = Sha256Context::new(); + context.update(b"hello"); + context.update_zeros(0); + assert_eq!(context.finalize(), Sha256::digest(b"hello")); + } + #[test] fn text() { let hash = Sha256::digest(b"hello"); diff --git a/src/uapi16/directory.rs b/src/uapi16/directory.rs index c18addb..6f456e8 100644 --- a/src/uapi16/directory.rs +++ b/src/uapi16/directory.rs @@ -4,39 +4,16 @@ use std::fs::File; use std::io; -use std::os::fd::OwnedFd; +use std::os::fd::{AsFd, 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::flags::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); +use crate::content::{Directory, ExternalFile, OpenError}; +use crate::sys::{pathrs_io_error, PinnedFile}; +use crate::{Error, FileObject, Name}; /// 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 @@ -48,13 +25,12 @@ static EMPTYPATH: AtomicU8 = AtomicU8::new(EmptyPath::UNKNOWN); /// [`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 +/// too short for the data the manifest says it holds, or of another length +/// than [`ExternalFile::original_size`] says. 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 @@ -66,18 +42,6 @@ pub struct PinnedDirectory { } 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); @@ -127,6 +91,56 @@ impl PinnedDirectory { self } + /// Opens `file` for reading: the file the data of `object` is in, as + /// [`FileObject::data_location`] gives it. The data starts at + /// [`ExternalFile::offset`] in it and is as long as the object says, or + /// reaches to the end of the file where the object gives no size. The + /// file is open for reading, and blocks as a regular file does. + /// + /// The file is a regular file below the directory. One that is not + /// there fails with [`SourceProblem::Missing`], one that is no regular + /// file with [`SourceProblem::NotRegular`], one that can't be opened + /// with [`SourceProblem::Unreadable`], and one that is too short for the + /// data, or of another length than [`ExternalFile::original_size`] says, + /// with [`DataProblem::SizeMismatch`]. The error names the object. + /// + /// The caller checks what it reads with a [`DataCheck`]. A file can hold + /// the data of several file objects. Where the manifest gives a hash + /// for the whole file and none for the object, the data of the object + /// is not checked against it. A caller that wants that check reads the + /// whole file and holds it against [`ExternalFile::original_sha256`]. + /// + /// [`SourceProblem::Missing`]: crate::SourceProblem::Missing + /// [`SourceProblem::NotRegular`]: crate::SourceProblem::NotRegular + /// [`SourceProblem::Unreadable`]: crate::SourceProblem::Unreadable + /// [`DataProblem::SizeMismatch`]: crate::DataProblem::SizeMismatch + /// [`DataCheck`]: crate::DataCheck + pub fn open_data(&self, object: &FileObject, file: &ExternalFile<'_>) -> Result { + let (opened, len) = Directory::open(self, file.name()).map_err(|e| file.unavailable(object, e))?; + file.check_len(object, len)?; + PinnedDirectory::hand_out(opened).map_err(|e| file.unavailable(object, OpenError::Io(e))) + } + + /// The file `file`, which [`PinnedDirectory::reopen`] opened, as a + /// caller gets it: without O_NONBLOCK. The file is opened with the + /// flag so that the open waits for nothing. read() and pread() of a + /// regular file don't look at it, but io_uring does: where the file + /// system has no reads that don't wait, it fails the read of such a + /// descriptor with EAGAIN and doesn't hand it to a worker. + fn hand_out(file: File) -> io::Result { + let flags = rustix::fs::fcntl_getfl(&file)?; + rustix::fs::fcntl_setfl(&file, flags.difference(OFlags::NONBLOCK))?; + Ok(file) + } + + /// The descriptor the directory was made of, which it is taken apart + /// for. A caller of the C API lends its descriptor to a directory and + /// gets it back this way, so that nothing closes it. + #[cfg(feature = "capi")] + pub(crate) fn into_fd(self) -> OwnedFd { + self.root.into() + } + /// 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> { @@ -135,7 +149,7 @@ impl PinnedDirectory { } else { file.as_str() }; - let pinned = self.root.resolve(path).map_err(PinnedDirectory::io_error)?; + let pinned = self.root.resolve(path).map_err(pathrs_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); @@ -145,39 +159,10 @@ impl PinnedDirectory { 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. + /// Opens the regular file `pinned` refers to for reading, through the + /// handle, as [`PinnedFile::reopen`] does. 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), - } + PinnedFile::new(pinned.as_fd()).reopen() } } @@ -195,11 +180,18 @@ impl Directory for PinnedDirectory { #[cfg(test)] mod tests { use super::*; + use crate::sys::{EmptyPath, EMPTYPATH}; use crate::testing::TempDir; - use rustix::fs::CWD; + use crate::{ + ContentsObject, ContentsSource, DataCheck, DataLocation, DataProblem, DirectoryProvider, ErrorKind, NameBuf, + Sha256, Sha256Context, SourceProblem, + }; + use rustix::fs::{SeekFrom, CWD}; + use rustix::io::Errno; use std::fs; use std::io::Read; - use std::os::unix::fs::symlink; + use std::os::unix::fs::{symlink, FileExt}; + use std::sync::atomic::Ordering; /// What `dir` has under `name`: the text of a regular file, or why it /// has none. @@ -346,4 +338,367 @@ mod tests { assert_eq!(flags & OFlags::RWMODE, OFlags::RDONLY); assert!(flags.contains(OFlags::NONBLOCK)); } + + /// The contents object that has the data in the file `file`, from + /// `offset` on. + fn in_file(file: &str, offset: u64) -> ContentsObject { + let mut contents = ContentsObject::new(ContentsSource::File(NameBuf::new(file).unwrap())); + contents.set_offset(offset); + contents + } + + /// The object `name` of a regular file with the contents object + /// `contents`, and with the size `size` if it gives one. + fn part(name: &str, contents: ContentsObject, size: Option) -> FileObject { + let mut object = FileObject::new(NameBuf::new(name).unwrap()); + object.set_contents(vec![contents]); + object.set_size(size); + object + } + + /// The file `object` has its data in. + fn external(object: &FileObject) -> ExternalFile<'_> { + match object.data_location() { + Ok(DataLocation::External(file)) => file, + other => panic!("{:?}", other), + } + } + + /// Reads the data of `object` as a caller of open_data() does: from the + /// offset on, as many bytes as the object says or all there are up to + /// the end of the file, each piece through a check. + fn data(dir: &PinnedDirectory, object: &FileObject) -> Result, Error> { + let file = external(object); + let opened = dir.open_data(object, &file)?; + let mut check = DataCheck::new(object); + let mut data = Vec::new(); + let mut buffer = [0u8; 4]; + let mut left = object.size().unwrap_or(u64::MAX); + while left > 0 { + let want = usize::try_from(left).map_or(buffer.len(), |left| left.min(buffer.len())); + let at = file.offset() + data.len() as u64; + let read = opened.read_at(&mut buffer[..want], at).unwrap(); + if read == 0 { + break; + } + check.update(&buffer[..read])?; + data.extend_from_slice(&buffer[..read]); + left -= read as u64; + } + assert_eq!(check.finish()?, data.len() as u64); + Ok(data) + } + + /// open_data() opens the file the data of an object is in: the file of + /// its own name, or the one its contents object names. The data is in + /// it from the offset on, as long as the object says or up to the end + /// of the file, and a caller reads it from there and checks it. + #[test] + fn opens_the_file_the_data_is_in() { + let tmp = TempDir::new("pinned-data"); + let dir = &tmp.0; + fs::create_dir(dir.join("sub")).unwrap(); + fs::write(dir.join("blob"), b"hello world").unwrap(); + fs::write(dir.join("sub/blob"), b"below").unwrap(); + fs::write(dir.join("empty"), b"").unwrap(); + let directory = PinnedDirectory::open(dir).unwrap(); + // A regular file without contents objects has its data in the file + // of its name. + let mut whole = FileObject::new(NameBuf::new("blob").unwrap()); + assert_eq!(data(&directory, &whole).unwrap(), b"hello world"); + whole.set_size(Some(11)); + whole.set_sha256(Some(Sha256::digest(b"hello world"))); + assert_eq!(data(&directory, &whole).unwrap(), b"hello world"); + for (file, offset, size, expected) in [ + ("sub/blob", 0, None, "below"), + ("sub/blob", 0, Some(5), "below"), + ("empty", 0, None, ""), + ("empty", 0, Some(0), ""), + // The start of a file that holds more, parts of it, and what + // it holds from an offset on. + ("blob", 0, Some(5), "hello"), + ("blob", 6, Some(5), "world"), + ("blob", 2, Some(3), "llo"), + ("blob", 6, None, "world"), + ("blob", 11, None, ""), + ("blob", 11, Some(0), ""), + ] { + let object = part("x", in_file(file, offset), size); + assert_eq!( + data(&directory, &object).unwrap(), + expected.as_bytes(), + "{} {} {:?}", + file, + offset, + size + ); + } + // The file is open for reading only, and without O_NONBLOCK, which + // it was opened with: a caller gets a descriptor like any other. It + // is the whole file, at its start, wherever the data is in it. + let object = part("x", in_file("blob", 6), Some(5)); + let mut opened = directory.open_data(&object, &external(&object)).unwrap(); + let flags = rustix::fs::fcntl_getfl(&opened).unwrap(); + assert_eq!(flags & OFlags::RWMODE, OFlags::RDONLY); + assert!(!flags.contains(OFlags::NONBLOCK)); + let mut text = String::new(); + opened.read_to_string(&mut text).unwrap(); + assert_eq!(text, "hello world"); + // Data that is not what the object says is found by the check of + // the caller, not by the open. + let mut object = part("x", in_file("blob", 6), Some(5)); + object.set_sha256(Some(Sha256::digest(b"world"))); + assert_eq!(data(&directory, &object).unwrap(), b"world"); + object.set_sha256(Some(Sha256::digest(b"hello"))); + let e = data(&directory, &object).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Data(DataProblem::HashMismatch)); + } + + /// open_data() opens nothing but a regular file below the directory + /// that is long enough for the data. Its error says what is wrong with + /// the file and names the object. + #[test] + fn opens_only_a_file_that_holds_the_data() { + let tmp = TempDir::new("pinned-data-errors"); + let dir = &tmp.0; + fs::create_dir_all(dir.join("root/sub")).unwrap(); + fs::write(dir.join("root/blob"), b"hello world").unwrap(); + fs::write(dir.join("outside"), b"outside").unwrap(); + symlink("blob", dir.join("root/link")).unwrap(); + symlink("../outside", dir.join("root/out")).unwrap(); + let fifo = dir.join("root/fifo"); + rustix::fs::mknodat(CWD, &fifo, FileType::Fifo, Mode::RUSR | Mode::WUSR, 0).unwrap(); + let directory = PinnedDirectory::open(dir.join("root")).unwrap(); + for (file, problem, errno, text) in [ + ( + "missing", + SourceProblem::Missing, + Some(libc::ENOENT), + "x/y: failed to open missing: ", + ), + ( + "blob/below", + SourceProblem::Missing, + Some(libc::ENOTDIR), + "x/y: failed to open blob/below: ", + ), + ("sub", SourceProblem::NotRegular, None, "x/y: sub is not a regular file"), + // Nobody writes to the FIFO: it is refused before anything is + // opened, so nothing waits for a writer. + ( + "fifo", + SourceProblem::NotRegular, + None, + "x/y: fifo is not a regular file", + ), + // A symbolic link is not followed, wherever it leads. + ( + "link", + SourceProblem::Unreadable, + Some(libc::ELOOP), + "x/y: failed to open link: ", + ), + ( + "out", + SourceProblem::Unreadable, + Some(libc::ELOOP), + "x/y: failed to open out: ", + ), + ] { + let object = part("x/y", in_file(file, 0), None); + let e = directory.open_data(&object, &external(&object)).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Source(problem), "{}", file); + assert_eq!(e.name(), Some("x/y"), "{}", file); + assert_eq!(e.io_error().and_then(io::Error::raw_os_error), errno, "{}", file); + let cause = errno.map(|errno| io::Error::from_raw_os_error(errno).to_string()); + assert_eq!(e.to_string(), format!("{}{}", text, cause.unwrap_or_default())); + } + // The file of the name of the object, which is not there. + let object = FileObject::new(NameBuf::new("sub/none").unwrap()); + let e = directory.open_data(&object, &external(&object)).unwrap_err(); + assert_eq!( + (e.kind(), e.name()), + (ErrorKind::Source(SourceProblem::Missing), Some("sub/none")) + ); + // Where symbolic links are followed, one leads to the file it names + // in the directory, and one that leads out of it to nothing. + let following = PinnedDirectory::open(dir.join("root")).unwrap().follow_symlinks(true); + let object = part("x/y", in_file("link", 6), Some(5)); + assert_eq!(data(&following, &object).unwrap(), b"world"); + let object = part("x/y", in_file("out", 0), None); + let e = following.open_data(&object, &external(&object)).unwrap_err(); + assert_eq!( + (e.kind(), e.io_error().and_then(io::Error::raw_os_error)), + (ErrorKind::Source(SourceProblem::Missing), Some(libc::ENOENT)) + ); + // A file that is too short for the data: by one byte, for a part of + // it, and for an offset behind its end. + let mismatch = ErrorKind::Data(DataProblem::SizeMismatch); + for (offset, size, text) in [ + (0, Some(12), "x/y: blob is too short for offset 0 and size 12"), + (6, Some(6), "x/y: blob is too short for offset 6 and size 6"), + (12, Some(0), "x/y: blob is too short for offset 12 and size 0"), + (12, None, "x/y: blob is too short for offset 12 and size 0"), + ] { + let object = part("x/y", in_file("blob", offset), size); + let e = directory.open_data(&object, &external(&object)).unwrap_err(); + assert_eq!( + (e.kind(), e.name(), e.found_size(), e.expected_size()), + (mismatch, Some("x/y"), Some(11), Some(12)), + "{}", + text + ); + assert_eq!(e.to_string(), text); + } + // An offset and a size whose sum no number holds. + let object = part("x/y", in_file("blob", u64::MAX), Some(5)); + let e = directory.open_data(&object, &external(&object)).unwrap_err(); + assert_eq!( + (e.kind(), e.found_size(), e.expected_size()), + (mismatch, Some(11), None) + ); + // A file that is not as long as the manifest says the whole file + // is, shorter or longer, fails the same way, as it does for a copy. + for original_size in [10, 12] { + let mut contents = in_file("blob", 0); + contents.set_original_size(Some(original_size)); + let object = part("x/y", contents, Some(5)); + let e = directory.open_data(&object, &external(&object)).unwrap_err(); + assert_eq!( + (e.kind(), e.name(), e.found_size(), e.expected_size()), + (mismatch, Some("x/y"), Some(11), Some(original_size)) + ); + assert_eq!( + e.to_string(), + format!("x/y: blob is 11 bytes, the manifest says {}", original_size) + ); + } + } + + /// A file can hold the data of several objects. open_data() does not + /// hold the data of one of them against the hash the manifest gives for + /// the whole file, which a copy does. A caller that reads the whole + /// file can. + #[test] + fn leaves_the_hash_of_the_whole_file_to_the_caller() { + let tmp = TempDir::new("pinned-data-whole"); + let dir = &tmp.0; + fs::write(dir.join("blob"), b"hello world").unwrap(); + let directory = PinnedDirectory::open(dir).unwrap(); + // The hash the manifest gives for the whole file: the one the file + // has, and another one. + for (original_sha256, matches) in [ + (Sha256::digest(b"hello world"), true), + (Sha256::digest(b"another file"), false), + ] { + let mut provider = DirectoryProvider::new(PinnedDirectory::open(dir).unwrap()); + // Two parts of the file, without hashes of their own. + for (name, offset, text) in [("first", 0, "hello"), ("second", 6, "world")] { + let mut contents = in_file("blob", offset); + contents.set_original_size(Some(11)); + contents.set_original_sha256(Some(original_sha256)); + let object = part(name, contents, Some(5)); + // The data passes the check of its object either way. + assert_eq!(data(&directory, &object).unwrap(), text.as_bytes(), "{}", name); + // A caller that wants the whole file checked reads it. + let file = external(&object); + let mut whole = Vec::new(); + let mut opened = directory.open_data(&object, &file).unwrap(); + opened.read_to_end(&mut whole).unwrap(); + assert_eq!(file.original_sha256() == Some(Sha256::digest(&whole)), matches); + // A copy checks the whole file itself. + let copied = object.copy_data(&mut provider, &mut Vec::new()); + let expected = if matches { + Ok(5) + } else { + Err(ErrorKind::Data(DataProblem::HashMismatch)) + }; + assert_eq!(copied.map_err(|e| e.kind()), expected, "{}", name); + } + } + } + + /// Reads the data of `object` as a tool does that skips the holes of a + /// sparse file: what the file system says is a hole is not read, and + /// goes into the check and into a hash as a run of zero bytes. Returns + /// that hash. On a file system that knows no holes all of the file is + /// data and is read. + fn data_without_holes(dir: &PinnedDirectory, object: &FileObject) -> Result { + let file = external(object); + let opened = dir.open_data(object, &file)?; + let mut check = DataCheck::new(object); + let mut context = Sha256Context::new(); + let mut buffer = [0u8; 4096]; + let mut at = file.offset(); + let end = at + object.size().unwrap(); + while at < end { + // Where the next data is. ENXIO says that a hole reaches to the + // end of the file. + let data = match rustix::fs::seek(&opened, SeekFrom::Data(at)) { + Ok(data) => data.min(end), + Err(Errno::NXIO) => end, + Err(e) => panic!("{}", e), + }; + if data > at { + check.update_zeros(data - at)?; + context.update_zeros(data - at); + at = data; + continue; + } + let hole = rustix::fs::seek(&opened, SeekFrom::Hole(at)).unwrap().min(end); + while at < hole { + let want = usize::try_from(hole - at).map_or(buffer.len(), |left| left.min(buffer.len())); + let read = opened.read_at(&mut buffer[..want], at).unwrap(); + assert_ne!(read, 0); + check.update(&buffer[..read])?; + context.update(&buffer[..read]); + at += read as u64; + } + } + check.finish()?; + Ok(context.finalize()) + } + + /// The data of a sparse file passes its check and gets its hash + /// without its holes being read: each goes in as a run of zero bytes, + /// whether the data is all of the file or a part of it that starts or + /// ends in a hole. + #[test] + fn reads_a_sparse_file_without_its_holes() { + /// As large as the largest block of the file systems the tests run + /// on, so that the file has holes there. + const BLOCK: u64 = 64 * 1024; + let tmp = TempDir::new("pinned-data-sparse"); + let dir = &tmp.0; + // A hole, a block with data, a hole, a block with data and a hole. + let sparse = File::create(dir.join("sparse")).unwrap(); + sparse.set_len(5 * BLOCK).unwrap(); + sparse.write_all_at(b"hello", BLOCK).unwrap(); + sparse.write_all_at(b"world", 3 * BLOCK + 7).unwrap(); + drop(sparse); + let whole = fs::read(dir.join("sparse")).unwrap(); + let directory = PinnedDirectory::open(dir).unwrap(); + for (offset, size) in [ + (0, 5 * BLOCK), + // From a hole to a hole, the data alone, from data to data, a + // hole alone, and nothing at the end of the file. + (BLOCK / 2, 2 * BLOCK), + (BLOCK, 5), + (BLOCK + 2, 2 * BLOCK + 8), + (4 * BLOCK, BLOCK), + (5 * BLOCK, 0), + ] { + let data = &whole[offset as usize..(offset + size) as usize]; + let mut object = part("x", in_file("sparse", offset), Some(size)); + object.set_sha256(Some(Sha256::digest(data))); + let hash = data_without_holes(&directory, &object).unwrap(); + assert_eq!(hash, Sha256::digest(data), "{} {}", offset, size); + } + // An object that takes the file for a single hole: the data in it + // fails the check. + let mut object = part("x", in_file("sparse", 0), Some(5 * BLOCK)); + object.set_sha256(Some(Sha256::digest(&vec![0; whole.len()]))); + let e = data_without_holes(&directory, &object).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Data(DataProblem::HashMismatch)); + } } diff --git a/src/uapi16/error.rs b/src/uapi16/error.rs index 3d7a377..304134c 100644 --- a/src/uapi16/error.rs +++ b/src/uapi16/error.rs @@ -1,13 +1,14 @@ // SPDX-License-Identifier: LGPL-2.1-or-later //! The error of this crate. +use std::ffi::{OsStr, OsString}; use std::fmt; use std::io; use crate::decode::Subject; use crate::object::FileObject; use crate::strict::{ParseError, ParseErrorKind}; -use crate::{NameProblem, MAX_CONTENTS, MAX_RECORD_SIZE}; +use crate::{Features, NameBuf, NameProblem, MAX_CONTENTS, MAX_RECORD_SIZE}; /// What is wrong with a manifest. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -236,6 +237,71 @@ pub enum ValidityProblem { Expired, } +/// How the files being added to a manifest cannot be described as asked. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum TreeProblem { + /// The same name was added twice, for two different files that are not + /// both directories. + Duplicate, + /// A file changed while it was read. Its size, its modification time, + /// its change time and how many names it has are compared before and + /// after. The data of a regular file has to end at its size as well, + /// which that of a file of procfs or sysfs does not. + Changed, + /// Two names of one inode do not show the same file: its type, mode, + /// owner, device numbers, size, modification time, birth time or data + /// differ, or one of the other fields the specification wants the names + /// of one inode to share: the names of the owners, the extended + /// attributes and the inode flags. [`Error::hardlink_name`] gives the + /// name that [`Error::name`] was compared with. + HardlinkMismatch, + /// A file has a name that a manifest cannot hold: one that is not UTF-8, + /// that is too long, or that has a control character or a + /// noncharacter. [`Error::name_problem`] says which, and + /// [`Error::raw_name`] gives the name as its directory has it. + UnwritableName, + /// A file that is not a directory is where a directory is needed. + NotDirectory, + /// A feature that was asked for cannot be read here. + /// [`Error::feature`] gives the feature. Without a feature, the kernel + /// is too old to tell mount points apart: statx() reports no mount ID. + FeatureUnavailable, + /// A feature of a partition, such as [`Features::GPT_LABEL`], was asked + /// for. It does not apply to a tree of files. [`Error::feature`] gives + /// the feature. + FeatureNotForTrees, + /// A directory is its own ancestor: a mount point below it shows it + /// again. That can only happen when the walk crosses mount points. + /// [`Error::name`] gives the directory below. + Loop, + /// A directory that files were added below was not added itself, and + /// the features asked for give a missing field a meaning, as + /// [`Features::READ_ONLY`] and [`Features::USER_XATTR`] do. A plain + /// directory has none of those fields and would claim that they are + /// cleared. [`Error::name`] gives the directory. + MissingParent, +} + +impl TreeProblem { + /// The name of the problem, such as `hardlinkMismatch`, for a caller + /// that passes it on, in the errors of an interface for example. The + /// names are stable. + pub const fn as_str(self) -> &'static str { + match self { + TreeProblem::Duplicate => "duplicate", + TreeProblem::Changed => "changed", + TreeProblem::HardlinkMismatch => "hardlinkMismatch", + TreeProblem::UnwritableName => "unwritableName", + TreeProblem::NotDirectory => "notDirectory", + TreeProblem::FeatureUnavailable => "featureUnavailable", + TreeProblem::FeatureNotForTrees => "featureNotForTrees", + TreeProblem::Loop => "loop", + TreeProblem::MissingParent => "missingParent", + } + } +} + /// What kind of error an [`Error`] is. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] @@ -251,6 +317,8 @@ pub enum ErrorKind { Unsupported(UnsupportedData), /// A file object is revoked or outside its validity window. NotValid(ValidityProblem), + /// The files being added to a manifest cannot be described as asked. + Tree(TreeProblem), /// Reading or writing failed. Io, } @@ -465,7 +533,11 @@ struct Inner { message: String, record_number: Option, name: Option, + hardlink_name: Option, + raw_name: Option, + name_problem: Option, field: Option, + feature: Option, found_size: Option, expected_size: Option, value: Option, @@ -479,7 +551,11 @@ impl Error { message, record_number: None, name: None, + hardlink_name: None, + raw_name: None, + name_problem: None, field: None, + feature: None, found_size: None, expected_size: None, value: None, @@ -506,6 +582,35 @@ impl Error { self } + /// Names the other name of the inode the error is about. + #[must_use] + pub(crate) fn linked(mut self, name: NameBuf) -> Error { + self.0.hardlink_name = Some(name.into()); + self + } + + /// Notes the name of the file the error is about as its directory has + /// it. + #[must_use] + pub(crate) fn raw(mut self, name: impl Into) -> Error { + self.0.raw_name = Some(name.into()); + self + } + + /// Notes the rule of a name that the name of the error breaks. + #[must_use] + pub(crate) fn because(mut self, problem: NameProblem) -> Error { + self.0.name_problem = Some(problem); + self + } + + /// Names the feature the error is about, a single one. + #[must_use] + pub(crate) fn about(mut self, feature: Features) -> Error { + self.0.feature = Some(feature); + self + } + /// Names the field the error is about. #[must_use] pub(crate) fn at(mut self, field: Field) -> Error { @@ -535,6 +640,17 @@ impl Error { self } + /// The I/O error `error`, which `about` says what it was about, as an + /// I/O error of its kind for code that hands I/O errors on. Where it + /// becomes an error of this crate, it is one of the kind Io that says + /// both, "about: error", and whose cause is `error`, so that the errno + /// of the system call stays. + pub(crate) fn io_about(about: String, error: io::Error) -> io::Error { + let kind = error.kind(); + let message = format!("{}: {}", about, error); + io::Error::new(kind, IoAbout(Error::new(ErrorKind::Io, message).caused_by(error))) + } + /// A record that is not JSON, that has a key twice in an object, or /// that has a string the specification does not permit. pub(crate) fn not_json(record_number: u64, error: ParseError) -> Error { @@ -574,15 +690,10 @@ impl Error { .at(Field::Type) } - /// A file object after the root file object, in the record with the - /// number `record_number`, that has no name. - pub(crate) fn no_name(record_number: u64) -> Error { - Error::manifest( - Problem::NoName, - format!("manifest object {} has no name", record_number), - ) - .at(Field::Name) - .in_record(record_number) + /// A file object after the root file object, which `subject` names, + /// that has no name. + pub(crate) fn no_name(subject: Subject<'_>) -> Error { + Error::manifest(Problem::NoName, format!("{} has no name", subject)).at(Field::Name) } /// A file object in the record with the number `record_number`, behind @@ -616,7 +727,7 @@ impl Error { /// A file object, which `subject` names, with more than /// [`MAX_CONTENTS`] contents objects. - pub(crate) fn too_many_contents(subject: Subject<'_>) -> Error { + pub(crate) fn too_many_contents(subject: impl fmt::Display) -> Error { Error::manifest( Problem::InvalidContents, format!("{}: more than {} contents entries", subject, MAX_CONTENTS), @@ -650,6 +761,7 @@ impl Error { ), ) .at(Field::File) + .because(reason) } /// `object`, which `subject` names, states the flag of the field @@ -657,7 +769,7 @@ impl Error { pub(crate) fn unpermitted_flag(object: &FileObject, field: Field, subject: Subject<'_>) -> Error { Error::manifest( Problem::FieldNotPermitted, - format!("{}: '{}' is not permitted on a {}", subject, field, object.inode_type), + format!("{}: '{}' is not permitted on a {}", subject, field, object.inode_type()), ) .at(field) } @@ -676,15 +788,49 @@ impl Error { /// The name of the file object the error is about, as its record has /// it. The name can be the very thing that is wrong. + /// + /// For the files being added to a manifest, it is the name of the file + /// in the manifest, and for [`TreeProblem::UnwritableName`] the name of + /// the directory the file is in. pub fn name(&self) -> Option<&str> { self.0.name.as_deref() } + /// The other name of the file, for [`TreeProblem::HardlinkMismatch`]: + /// the name of the same inode that [`Error::name`] was compared with. + pub fn hardlink_name(&self) -> Option<&str> { + self.0.hardlink_name.as_deref() + } + + /// The name of the file as its directory has it, for + /// [`TreeProblem::UnwritableName`]: one component, which need not be + /// UTF-8. + pub fn raw_name(&self) -> Option<&OsStr> { + self.0.raw_name.as_deref() + } + + /// Which rule of a name the name breaks: for + /// [`TreeProblem::UnwritableName`] the name [`Error::raw_name`] gives, + /// for [`Problem::InvalidName`] the name of the record, and for + /// [`Problem::InvalidContents`] in [`Field::File`] the file a contents + /// object refers to. + pub fn name_problem(&self) -> Option { + self.0.name_problem + } + /// The field the error is about. pub fn field(&self) -> Option { self.0.field } + /// The feature the error is about, for + /// [`TreeProblem::FeatureUnavailable`] and + /// [`TreeProblem::FeatureNotForTrees`]: a single one, such as + /// [`Features::MTIME`]. + pub fn feature(&self) -> Option { + self.0.feature + } + /// The size that was found, when the error is about a size and it is /// known: for a [`DataProblem::SizeMismatch`] and a /// [`DataProblem::StreamEnded`]. @@ -717,7 +863,10 @@ impl Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match (&self.0.kind, &self.0.cause) { - (ErrorKind::Io, Some(Cause::Io(e))) => e.fmt(f), + // An I/O error shows as its cause, but for one that says what + // it was about, such as one of a Writer after a write that + // failed, one of a file of a tree or one of Error::io_about(). + (ErrorKind::Io, Some(Cause::Io(e))) if self.0.message.is_empty() => e.fmt(f), _ => f.write_str(&self.0.message), } } @@ -735,7 +884,30 @@ impl std::error::Error for Error { impl From for Error { fn from(e: io::Error) -> Error { - Error::new(ErrorKind::Io, String::new()).caused_by(e) + // An error of this crate that says what an I/O error was about, + // which the I/O error carried on its way up, see Error::io_about(), + // is that error again. + match e.downcast::() { + Ok(about) => about.0, + Err(e) => Error::new(ErrorKind::Io, String::new()).caused_by(e), + } + } +} + +/// An error of the kind Io that says what it was about, which an I/O error +/// carries on its way up, see [`Error::io_about`]. +#[derive(Debug)] +struct IoAbout(Error); + +impl fmt::Display for IoAbout { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&self.0, f) + } +} + +impl std::error::Error for IoAbout { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + std::error::Error::source(&self.0) } } @@ -766,6 +938,10 @@ mod tests { assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::ENOSPC)); assert_eq!(e.to_string(), io::Error::from_raw_os_error(libc::ENOSPC).to_string()); assert!(std::error::Error::source(&e).is_some()); + assert_eq!( + (e.name(), e.hardlink_name(), e.raw_name(), e.name_problem(), e.feature()), + (None, None, None, None, None) + ); assert_eq!(io::Error::from(e).raw_os_error(), Some(libc::ENOSPC)); // Any other error is carried by an I/O error. let e = Error::manifest(Problem::NoTrailer, "incomplete".to_string()); @@ -776,6 +952,31 @@ mod tests { assert_eq!(io.to_string(), "incomplete"); } + /// An I/O error that says what it was about is an I/O error of its kind + /// on the way up, and an error of the kind Io here that says both, with + /// the I/O error as its cause. As an I/O error again it is that of the + /// system call. + #[test] + fn io_errors_that_say_what_they_were_about() { + let enoent = || io::Error::from_raw_os_error(libc::ENOENT); + let io = Error::io_about("the directory".to_string(), enoent()); + assert_eq!(io.kind(), io::ErrorKind::NotFound); + let e = Error::from(io); + assert_eq!(e.kind(), ErrorKind::Io); + assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::ENOENT)); + assert_eq!(e.to_string(), format!("the directory: {}", enoent())); + assert!(std::error::Error::source(&e).is_some()); + assert_eq!(io::Error::from(e).raw_os_error(), Some(libc::ENOENT)); + } + + /// An error can be sent to another thread, shared between threads and + /// kept for as long as needed, as an I/O error can. + #[test] + fn errors_are_send_and_sync() { + fn send_sync_static() {} + send_sync_static::(); + } + #[test] fn what_an_error_is_about() { let e = Error::manifest(Problem::WrongFieldType, "message".to_string()) @@ -792,6 +993,13 @@ 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()); + // What only some errors are about. + assert_eq!( + (e.hardlink_name(), e.raw_name(), e.name_problem(), e.feature()), + (None, None, None, None) + ); + let e = Error::manifest(Problem::InvalidName, String::new()).because(NameProblem::TooLong); + assert_eq!(e.name_problem(), Some(NameProblem::TooLong)); let e = Error::new(ErrorKind::Data(DataProblem::SizeMismatch), String::new()) .sizes(Some(1), Some(2)) .valued("gzip"); @@ -885,4 +1093,70 @@ mod tests { let names: std::collections::HashSet<&str> = Problem::ALL.iter().map(|problem| problem.as_str()).collect(); assert_eq!(names.len(), Problem::ALL.len()); } + + /// Every problem of the files being added, in the order of the + /// variants. + const TREE_PROBLEMS: [TreeProblem; 9] = [ + TreeProblem::Duplicate, + TreeProblem::Changed, + TreeProblem::HardlinkMismatch, + TreeProblem::UnwritableName, + TreeProblem::NotDirectory, + TreeProblem::FeatureUnavailable, + TreeProblem::FeatureNotForTrees, + TreeProblem::Loop, + TreeProblem::MissingParent, + ]; + + /// Where `problem` is in [`TREE_PROBLEMS`]. As a constant it does not + /// build for a problem that the list lacks. + const fn position_in_tree_problems(problem: TreeProblem) -> usize { + let mut position = 0; + while position < TREE_PROBLEMS.len() { + if TREE_PROBLEMS[position] as usize == problem as usize { + return position; + } + position += 1; + } + panic!("TREE_PROBLEMS lacks a problem"); + } + + /// TREE_PROBLEMS holds every problem once, in the order of the variants, + /// and each has its stable name, which no other one has. The match names + /// every problem, so a problem added to the enum does not build without + /// an arm here, and its arm, a constant, does not build until the list + /// has the problem. + #[test] + fn all_tree_problems() { + let position = |problem: TreeProblem| match problem { + TreeProblem::Duplicate => const { position_in_tree_problems(TreeProblem::Duplicate) }, + TreeProblem::Changed => const { position_in_tree_problems(TreeProblem::Changed) }, + TreeProblem::HardlinkMismatch => const { position_in_tree_problems(TreeProblem::HardlinkMismatch) }, + TreeProblem::UnwritableName => const { position_in_tree_problems(TreeProblem::UnwritableName) }, + TreeProblem::NotDirectory => const { position_in_tree_problems(TreeProblem::NotDirectory) }, + TreeProblem::FeatureUnavailable => const { position_in_tree_problems(TreeProblem::FeatureUnavailable) }, + TreeProblem::FeatureNotForTrees => const { position_in_tree_problems(TreeProblem::FeatureNotForTrees) }, + TreeProblem::Loop => const { position_in_tree_problems(TreeProblem::Loop) }, + TreeProblem::MissingParent => const { position_in_tree_problems(TreeProblem::MissingParent) }, + }; + for (i, &problem) in TREE_PROBLEMS.iter().enumerate() { + assert_eq!((position(problem), problem as usize), (i, i), "{:?}", problem); + } + assert_eq!( + TREE_PROBLEMS.map(TreeProblem::as_str), + [ + "duplicate", + "changed", + "hardlinkMismatch", + "unwritableName", + "notDirectory", + "featureUnavailable", + "featureNotForTrees", + "loop", + "missingParent", + ] + ); + let names: std::collections::HashSet<&str> = TREE_PROBLEMS.iter().map(|problem| problem.as_str()).collect(); + assert_eq!(names.len(), TREE_PROBLEMS.len()); + } } diff --git a/src/uapi16/examples/assemble.c b/src/uapi16/examples/assemble.c new file mode 100644 index 0000000..d7532c0 --- /dev/null +++ b/src/uapi16/examples/assemble.c @@ -0,0 +1,327 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +/* + * Builds an image from a manifest and the files next to it, as a mkfs tool + * does for an option like --manifest: assemble SOURCE-DIR IMAGE-DIR, with + * the manifest on standard input. + * + * The image is a new directory here. It stands in for the file system a + * tool makes. The tool reads the data itself, through a descriptor of the + * library, and has the library check what it read. + */ +#define _GNU_SOURCE +/* Inode numbers and sizes of 64 bits, also where long has 32. */ +#define _FILE_OFFSET_BITS 64 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define _cleanup_(f) __attribute__((cleanup(f))) + +/* The first name of a file with several, by its token in the manifest. */ +struct link { + uapi16_inode_token_t token; + char *name; +}; + +static void closep(int *fd) { + if (*fd >= 0) + close(*fd); +} + +static int compare_links(const void *a, const void *b) { + const struct link *x = a, *y = b; + + return x->token < y->token ? -1 : x->token > y->token; +} + +static void free_link(void *p) { + struct link *link = p; + + free(link->name); + free(link); +} + +static int write_all(int fd, const void *data, size_t size) { + const char *p = data; + + while (size > 0) { + ssize_t n = write(fd, p, size); + + if (n < 0 && errno == EINTR) + continue; + if (n <= 0) + return n < 0 ? -errno : -EIO; + p += n; + size -= (size_t) n; + } + return 0; +} + +/* Copies the data of `o` from `in`, where it starts at `offset`, to `out`. + * The check sees every byte before it is written on. */ +static int copy_checked(int in, uint64_t offset, int out, + const uapi16_file_object *o, uapi16_error **reterr) { + _cleanup_(uapi16_data_check_freep) uapi16_data_check *check = NULL; + static char buffer[1 << 16]; + uint64_t left = UINT64_MAX; + int r; + + /* Without a size the data reaches to the end of its file. */ + (void) uapi16_file_object_size(o, &left); + r = uapi16_data_check_new(o, &check); + if (r < 0) + return r; + + while (left > 0) { + size_t want = left < sizeof(buffer) + ? (size_t) left + : sizeof(buffer); + ssize_t n = pread(in, buffer, want, (off_t) offset); + + if (n < 0 && errno == EINTR) + continue; + if (n < 0) + return -errno; + if (n == 0) + break; /* the end of the file: the finish says if + * that is too early */ + r = uapi16_data_check_update(check, buffer, (size_t) n, reterr); + if (r < 0) + return r; + r = write_all(out, buffer, (size_t) n); + if (r < 0) + return r; + offset += (uint64_t) n; + left -= (uint64_t) n; + } + + /* The size and the hash the manifest gives for the file. If this + * fails, what `out` got is not the data of the file. */ + return uapi16_data_check_finish(check, NULL, reterr); +} + +/* Makes the regular file `o` in the image. */ +static int place_file(int image_fd, const uapi16_directory *source, + const uapi16_file_object *o, uapi16_error **reterr) { + _cleanup_(closep) int in = -1; + _cleanup_(closep) int out = -1; + const char *name = uapi16_file_object_name(o); + uint64_t offset, mtime; + const void *literal; + uint32_t mode; + size_t size; + int r; + + out = openat(image_fd, name, + O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, + 0600); + if (out < 0) + return -errno; + + switch (uapi16_file_object_data_location(o)) { + case UAPI16_DATA_LOCATION_LITERAL: + /* The manifest carries the data, and the reader has checked + * it against the hash. */ + literal = uapi16_file_object_literal(o, &size); + r = write_all(out, literal, size); + break; + case UAPI16_DATA_LOCATION_EXTERNAL: + /* The file is opened below the directory and nowhere else, + * whatever its name is. */ + r = uapi16_directory_open_data(source, o, &in, &offset, reterr); + if (r >= 0) + r = copy_checked(in, offset, out, o, reterr); + break; + default: + /* Data at a URL or in an encoding. */ + r = -EOPNOTSUPP; + break; + } + if (r < 0) + return r; + + /* A getter of a field the object does not have fails with -ENODATA. */ + if (uapi16_file_object_mode(o, &mode) >= 0 && fchmod(out, mode) < 0) + return -errno; + if (uapi16_file_object_mtime_nsec(o, &mtime) >= 0) { + struct timespec times[2] = { + { .tv_nsec = UTIME_OMIT }, + { .tv_sec = (time_t) (mtime / 1000000000), + .tv_nsec = (long) (mtime % 1000000000) }, + }; + + if (futimens(out, times) < 0) + return -errno; + } + return 0; +} + +/* Makes the file `o` in the image. */ +static int place(int image_fd, const uapi16_directory *source, void **links, + const uapi16_file_object *o, uapi16_error **reterr) { + const char *name = uapi16_file_object_name(o); + const void *target; + char buffer[4096]; + uapi16_inode_token_t token; + size_t size; + + /* -ENODATA says that the file has no other name. */ + if (uapi16_file_object_inode_token(o, &token) >= 0) { + struct link key = { .token = token }, *link; + void *found = tfind(&key, links, compare_links); + + if (found) { + /* A later name of a file that is there already. */ + link = *(struct link **) found; + return linkat(image_fd, link->name, + image_fd, name, 0) < 0 ? -errno : 0; + } + link = malloc(sizeof(*link)); + if (!link) + return -ENOMEM; + link->token = token; + link->name = strdup(name); + if (!link->name || !tsearch(link, links, compare_links)) { + free_link(link); + return -ENOMEM; + } + } + + switch (uapi16_file_object_type(o)) { + case S_IFDIR: + return mkdirat(image_fd, name, 0700) < 0 ? -errno : 0; + case S_IFREG: + return place_file(image_fd, source, o, reterr); + case S_IFLNK: + /* The target is the data of a symbolic link. No NUL ends it. */ + target = uapi16_file_object_literal(o, &size); + if (!target || size >= sizeof(buffer)) + return -EOPNOTSUPP; + memcpy(buffer, target, size); + buffer[size] = 0; + return symlinkat(buffer, image_fd, name) < 0 ? -errno : 0; + default: + /* This image holds no device nodes, FIFOs or sockets. */ + return -EOPNOTSUPP; + } +} + +int main(int argc, char *argv[]) { + /* The directory borrows its descriptor until it is freed. So the + * descriptor is declared first, and is closed last. */ + _cleanup_(closep) int source_fd = -1; + _cleanup_(closep) int image_fd = -1; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_directory_freep) uapi16_directory *source = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *error = NULL; + void *links = NULL; + struct timespec ts; + uint64_t now; + int r; + + if (argc != 3) { + fprintf(stderr, "usage: %s SOURCE-DIR IMAGE-DIR\n", argv[0]); + return 2; + } + source_fd = open(argv[1], O_PATH | O_DIRECTORY | O_CLOEXEC); + if (source_fd < 0 || mkdir(argv[2], 0700) < 0) { + perror("assemble"); + return 1; + } + image_fd = open(argv[2], O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (image_fd < 0) { + perror(argv[2]); + return 1; + } + clock_gettime(CLOCK_REALTIME, &ts); + now = (uint64_t) ts.tv_sec * 1000000 + (uint64_t) ts.tv_nsec / 1000; + + /* The reader reads its descriptor once, so the manifest can come + * through a pipe. It borrows the descriptor and never closes it. + * This reads and checks the root. */ + r = uapi16_reader_open(STDIN_FILENO, &reader, &error); + /* Two checks are the caller's. The loop below relies on the order, + * so the manifest has to declare it. And the manifest may be used + * now. */ + if (r >= 0) + r = uapi16_reader_require_order( + reader, UAPI16_ORDER_CODEPOINT, &error); + if (r >= 0) + r = uapi16_reader_check_validity(reader, now, &error); + /* The files next to the manifest. Without a flag, a name that leads + * through a symbolic link fails. */ + if (r >= 0) + r = uapi16_directory_new(source_fd, UAPI16_DIRECTORY_NONE, + &source, &error); + + /* One file object serves the whole loop, as the buffer of getline() + * does: the first call makes it, and every later call clears it and + * fills it again. */ + while (r >= 0) { + /* What the call returns says what it read. */ + r = uapi16_reader_next(reader, &o, &error); + if (r != UAPI16_READ_FILE) + break; + + /* The reader has checked the record: its fields, where it + * comes and its order. A directory comes before what is in + * it, so its directory is there when a file comes. */ + r = uapi16_file_object_check_validity(o, now, &error); + if (r >= 0) + r = place(image_fd, source, &links, o, &error); + if (r < 0 && !error) + fprintf(stderr, "'%s': ", uapi16_file_object_name(o)); + } + tdestroy(links, free_link); + + /* Signature objects follow the file objects. This tool has no use + * for them: the next call passes over them, and checks them. */ + if (r == UAPI16_READ_SIGNATURES) + r = uapi16_reader_next(reader, &o, &error); + + if (r < 0) { + fprintf(stderr, "%s", strerror(-r)); + if (error) { + const char *path = uapi16_error_path(error); + const char *problem = uapi16_error_problem(error); + const char *field = uapi16_error_field(error); + uint64_t record; + + /* -ENODATA says that the error is about no record. */ + if (uapi16_error_record(error, &record) >= 0) + fprintf(stderr, ", record %llu", + (unsigned long long) record); + if (path) + fprintf(stderr, ", file '%s'", path); + if (problem) + fprintf(stderr, ", %s", problem); + if (field) + fprintf(stderr, ", field %s", field); + } + fputc('\n', stderr); + /* A real tool removes the image it made. */ + return 1; + } + /* UAPI16_READ_END: the trailer was read and checked, and the + * manifest is complete. A later library can return a number that + * this program does not know, which is an error here. */ + if (r != UAPI16_READ_END) { + fprintf(stderr, + "uapi16_reader_next() returned %d, which this program " + "does not know\n", + r); + return 1; + } + return 0; +} diff --git a/src/uapi16/examples/build.c b/src/uapi16/examples/build.c new file mode 100644 index 0000000..cb62a1a --- /dev/null +++ b/src/uapi16/examples/build.c @@ -0,0 +1,433 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +/* + * Copies a tree into an image and writes the manifest of the image while + * it does, as a mkfs tool does for an option like --write-manifest: + * build SOURCE-DIR IMAGE-DIR, with the manifest on standard output. + * + * The image is a new directory here. It stands in for the file system a + * tool makes. Every file goes into the manifest when it has gone into the + * image, with the hash of the data that was copied. + */ +#define _GNU_SOURCE +/* Inode numbers and sizes of 64 bits, also where long has 32. */ +#define _FILE_OFFSET_BITS 64 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define _cleanup_(f) __attribute__((cleanup(f))) + +/* A file with more than one name: its inode in the source, and its file + * object, which goes into the manifest again under every later name. */ +struct link { + dev_t dev; + ino_t ino; + uapi16_file_object *object; +}; + +struct build { + uapi16_manifest_writer *manifest; + int image_fd; + void *links; /* the links, in a tree of tsearch() */ + uapi16_inode_token_t tokens; +}; + +static void closep(int *fd) { + if (*fd >= 0) + close(*fd); +} + +static void closedirp(DIR **d) { + if (*d) + closedir(*d); +} + +static int compare_links(const void *a, const void *b) { + const struct link *x = a, *y = b; + + if (x->dev != y->dev) + return x->dev < y->dev ? -1 : 1; + if (x->ino != y->ino) + return x->ino < y->ino ? -1 : 1; + return 0; +} + +static void free_link(void *p) { + struct link *link = p; + + uapi16_file_object_free(link->object); + free(link); +} + +/* Copies the `size` bytes of `in` to `out` and stores their hash. A hole is + * not read: it stays a hole in the image and goes into the hash as zeros. */ +static int copy_and_hash(int in, int out, off_t size, + uapi16_sha256_digest_t *ret_hash) { + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *sha = NULL; + static char buffer[1 << 16]; + off_t at = 0; + int r; + + sha = uapi16_sha256_new(); + while (at < size) { + off_t data, end; + + data = lseek(in, at, SEEK_DATA); + if (data < 0 && errno != ENXIO) + return -errno; + if (data < 0 || data > size) + data = size; /* a hole up to the end */ + if (data > at) { + r = uapi16_sha256_update_zeros(sha, + (uint64_t) (data - at)); + if (r < 0) + return r; + at = data; + continue; + } + end = lseek(in, at, SEEK_HOLE); + if (end < 0) + return -errno; + if (end > size) + end = size; + while (at < end) { + size_t want = (size_t) (end - at) < sizeof(buffer) + ? (size_t) (end - at) + : sizeof(buffer); + ssize_t n = pread(in, buffer, want, at); + + if (n < 0 && errno == EINTR) + continue; + if (n < 0) + return -errno; + if (n == 0) + return -ESTALE; /* the file changed */ + for (ssize_t done = 0; done < n;) { + ssize_t w = pwrite(out, buffer + done, + (size_t) (n - done), + at + done); + + if (w < 0 && errno == EINTR) + continue; + if (w <= 0) + return w < 0 ? -errno : -EIO; + done += w; + } + r = uapi16_sha256_update(sha, buffer, (size_t) n); + if (r < 0) + return r; + at += n; + } + } + if (ftruncate(out, size) < 0) + return -errno; + return uapi16_sha256_finish(sha, ret_hash); +} + +/* Makes the file object of `name` from what stat() says of the file. */ +static int describe(const char *name, const struct stat *st, + uapi16_file_object **ret, uapi16_error **reterr) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = NULL; + int r; + + /* A name that a manifest can't hold fails here, and + * uapi16_error_name_problem() says why. */ + r = uapi16_file_object_new(name, &o, reterr); + if (r < 0) + return r; + + /* The setters store what they get, and fail only for a call that + * is not valid. The root is a directory already. A symbolic link + * has no mode. The IDs 65535 and 4294967295 and a time before 1970 + * are not what a manifest holds, so they are left out. */ + r = 0; + if (*name) + r = uapi16_file_object_set_type(o, st->st_mode); + if (r >= 0 && !S_ISLNK(st->st_mode)) + r = uapi16_file_object_set_mode(o, st->st_mode); + if (r >= 0 && st->st_uid != 65535 && st->st_uid != UINT32_MAX) + r = uapi16_file_object_set_uid(o, st->st_uid); + if (r >= 0 && st->st_gid != 65535 && st->st_gid != UINT32_MAX) + r = uapi16_file_object_set_gid(o, st->st_gid); + /* A time after 2554 is left out too, since its nanoseconds don't + * fit in 64 bits. */ + if (r >= 0 && st->st_mtim.tv_sec >= 0 && + (uint64_t) st->st_mtim.tv_sec <= + (UINT64_MAX - (uint64_t) st->st_mtim.tv_nsec) / 1000000000) + r = uapi16_file_object_set_mtime_nsec( + o, + (uint64_t) st->st_mtim.tv_sec * 1000000000 + + (uint64_t) st->st_mtim.tv_nsec); + if (r >= 0 && (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))) { + r = uapi16_file_object_set_major(o, major(st->st_rdev)); + if (r >= 0) + r = uapi16_file_object_set_minor(o, minor(st->st_rdev)); + } + if (r < 0) + return r; + + *ret = o; + o = NULL; + return 0; +} + +static int add_directory(struct build *b, int dir_fd, const char *name, + uapi16_error **reterr); + +/* Puts the file `component` of the directory `dir_fd` into the image as + * `name`, and adds its file object to the manifest. */ +static int add_file(struct build *b, int dir_fd, const char *component, + const char *name, uapi16_error **reterr) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = NULL; + struct link key = { 0 }, *link; + struct stat st; + int r; + + if (fstatat(dir_fd, component, &st, AT_SYMLINK_NOFOLLOW) < 0) + return -errno; + key.dev = st.st_dev; + key.ino = st.st_ino; + + if (!S_ISDIR(st.st_mode) && st.st_nlink > 1) { + void *found = tfind(&key, &b->links, compare_links); + + if (found) { + /* A later name of a file. The image gets a link, and + * the manifest the same object under the new name. + * Nothing is read again. */ + link = *(struct link **) found; + if (linkat(b->image_fd, + uapi16_file_object_name(link->object), + b->image_fd, name, 0) < 0) + return -errno; + r = uapi16_file_object_set_name( + link->object, name, reterr); + if (r < 0) + return r; + return uapi16_manifest_writer_add_object( + b->manifest, link->object, reterr); + } + } + + r = describe(name, &st, &o, reterr); + if (r < 0) + return r; + + if (S_ISDIR(st.st_mode)) { + int fd; + + if (mkdirat(b->image_fd, name, 0700) < 0) + return -errno; + r = uapi16_manifest_writer_add_object(b->manifest, o, reterr); + if (r < 0) + return r; + fd = openat(dir_fd, component, + O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + if (fd < 0) + return -errno; + /* add_directory() closes the descriptor. */ + return add_directory(b, fd, name, reterr); + } + + if (S_ISREG(st.st_mode)) { + _cleanup_(closep) int in = -1; + _cleanup_(closep) int out = -1; + uapi16_sha256_digest_t hash; + + in = openat(dir_fd, component, + O_RDONLY | O_NOFOLLOW | O_CLOEXEC); + out = openat(b->image_fd, name, + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600); + if (in < 0 || out < 0) + return -errno; + r = copy_and_hash(in, out, st.st_size, &hash); + if (r < 0) + return r; + r = uapi16_file_object_set_size(o, (uint64_t) st.st_size); + if (r >= 0) + r = uapi16_file_object_set_sha256(o, &hash); + if (r < 0) + return r; + } else if (S_ISLNK(st.st_mode)) { + char target[4096]; + ssize_t n; + + n = readlinkat(dir_fd, component, target, sizeof(target) - 1); + if (n < 0) + return -errno; + target[n] = 0; + if (symlinkat(target, b->image_fd, name) < 0) + return -errno; + /* The target is bytes with a size. No NUL ends it. */ + r = uapi16_file_object_set_target(o, target, (size_t) n); + if (r >= 0) + r = uapi16_file_object_set_size(o, (uint64_t) n); + if (r < 0) + return r; + } else if (mknodat(b->image_fd, name, st.st_mode, st.st_rdev) < 0) + return -errno; + + if (st.st_nlink > 1) { + /* The first name of a file with several. Its names share + * one token, which is any number: the manifest gets its + * own. The object is kept for the later names. */ + r = uapi16_file_object_set_inode_token(o, ++b->tokens); + if (r < 0) + return r; + link = malloc(sizeof(*link)); + if (!link) + return -ENOMEM; + *link = key; + if (!tsearch(link, &b->links, compare_links)) { + free(link); + return -ENOMEM; + } + link->object = o; + o = NULL; + return uapi16_manifest_writer_add_object( + b->manifest, link->object, reterr); + } + + /* The writer keeps a copy, so the object can go. */ + return uapi16_manifest_writer_add_object(b->manifest, o, reterr); +} + +/* Copies what is in the directory `dir_fd`, whose name in the image is + * `name`, and closes the descriptor. */ +static int add_directory(struct build *b, int dir_fd, const char *name, + uapi16_error **reterr) { + _cleanup_(closedirp) DIR *d = NULL; + struct dirent *entry; + + d = fdopendir(dir_fd); + if (!d) { + int e = errno; + + close(dir_fd); + return -e; + } + for (;;) { + char child[4096]; + int r; + + errno = 0; + entry = readdir(d); + if (!entry) + return -errno; + if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) + continue; + r = snprintf(child, sizeof(child), "%s%s%s", name, + *name ? "/" : "", entry->d_name); + if (r < 0 || (size_t) r >= sizeof(child)) + return -ENAMETOOLONG; + r = add_file(b, dirfd(d), entry->d_name, child, reterr); + if (r < 0) + return r; + } +} + +int main(int argc, char *argv[]) { + static const uapi16_uuid_t uuid = { .bytes = { + 0x6f, 0x1d, 0x0a, 0x42, 0x9c, 0x1e, 0x4b, 0x7a, + 0x8d, 0x33, 0x52, 0x0c, 0x7e, 0x11, 0xa9, 0x05 + } }; + _cleanup_(uapi16_manifest_options_freep) + uapi16_manifest_options *options = NULL; + _cleanup_(uapi16_manifest_writer_freep) + uapi16_manifest_writer *manifest = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *root = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *error = NULL; + _cleanup_(closep) int source_fd = -1; + _cleanup_(closep) int image_fd = -1; + uapi16_features_t features = UAPI16_FEATURES_EMPTY; + struct build b = { .image_fd = -1 }; + struct stat st; + int r; + + if (argc != 3) { + fprintf(stderr, "usage: %s SOURCE-DIR IMAGE-DIR\n", argv[0]); + return 2; + } + source_fd = open(argv[1], O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (source_fd < 0 || fstat(source_fd, &st) < 0 || + mkdir(argv[2], 0700) < 0) { + perror("build"); + return 1; + } + image_fd = open(argv[2], O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (image_fd < 0) { + perror(argv[2]); + return 1; + } + + /* What this tool records: the default features, the times, and the + * identity of the file system it makes. */ + options = uapi16_manifest_options_new(); + r = uapi16_features_default(&features); + if (r >= 0) + r = uapi16_features_add(&features, UAPI16_FEATURE_MTIME); + if (r >= 0) + r = uapi16_features_add(&features, UAPI16_FEATURE_FS_UUID); + if (r >= 0) + r = uapi16_features_add(&features, UAPI16_FEATURE_FS_LABEL); + if (r >= 0) + r = uapi16_manifest_options_set_features(options, &features); + /* Nothing is written to standard output before the finish. */ + if (r >= 0) + r = uapi16_manifest_writer_open(options, STDOUT_FILENO, + &manifest, &error); + + /* The root is the object with the empty name. It has the attributes + * of the top directory, and the identity the tool gave the file + * system. The adds can come in any order. */ + if (r >= 0) + r = describe("", &st, &root, &error); + if (r >= 0) + r = uapi16_file_object_set_fs_uuid(root, &uuid); + if (r >= 0) + r = uapi16_file_object_set_fs_label(root, "example"); + if (r >= 0) + r = uapi16_manifest_writer_add_object(manifest, root, &error); + + if (r >= 0) { + b.manifest = manifest; + b.image_fd = image_fd; + r = add_directory(&b, source_fd, "", &error); + source_fd = -1; /* add_directory() closed it */ + tdestroy(b.links, free_link); + } + + /* What the adds left open fails here, such as two different files + * of one name. The manifest is complete once this returns 0. */ + if (r >= 0) + r = uapi16_manifest_writer_finish(manifest, NULL, &error); + if (r < 0) { + fprintf(stderr, "%s: %s", argv[0], strerror(-r)); + if (error) { + const char *path = uapi16_error_path(error); + const char *problem = uapi16_error_problem(error); + const char *field = uapi16_error_field(error); + + if (path) + fprintf(stderr, ", file '%s'", path); + if (problem) + fprintf(stderr, ", %s", problem); + if (field) + fprintf(stderr, ", field %s", field); + } + fputc('\n', stderr); + return 1; + } + return 0; +} diff --git a/src/uapi16/examples/generate.c b/src/uapi16/examples/generate.c new file mode 100644 index 0000000..e083f00 --- /dev/null +++ b/src/uapi16/examples/generate.c @@ -0,0 +1,109 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +/* + * Writes the manifest of a directory to a new file: + * generate DIR OUT-DIR NAME + */ +#define _GNU_SOURCE +/* Inode numbers and sizes of 64 bits, also where long has 32. */ +#define _FILE_OFFSET_BITS 64 +#include +#include +#include +#include +#include + +#include + +#define _cleanup_(f) __attribute__((cleanup(f))) + +static void closep(int *fd) { + if (*fd >= 0) + close(*fd); +} + +int main(int argc, char *argv[]) { + /* What this tool records besides the default features. */ + static const uapi16_features_t more = + UAPI16_FEATURES_SET(UAPI16_FEATURE_MTIME, + UAPI16_FEATURE_USER_XATTR); + uapi16_features_t features = UAPI16_FEATURES_EMPTY; + _cleanup_(uapi16_manifest_options_freep) + uapi16_manifest_options *options = NULL; + _cleanup_(uapi16_manifest_report_freep) + uapi16_manifest_report *report = NULL; + /* `reterr` has to point to NULL before a call. */ + _cleanup_(uapi16_error_freep) uapi16_error *error = NULL; + _cleanup_(closep) int top_fd = -1; + _cleanup_(closep) int out_fd = -1; + int r; + + if (argc != 4) { + fprintf(stderr, "usage: %s DIR OUT-DIR NAME\n", argv[0]); + return 2; + } + + /* The tree is read through the descriptor of its top, and the new + * file is made below the descriptor of its directory. */ + top_fd = open(argv[1], O_PATH | O_DIRECTORY | O_CLOEXEC); + out_fd = open(argv[2], O_PATH | O_DIRECTORY | O_CLOEXEC); + if (top_fd < 0 || out_fd < 0) { + perror("open"); + return 1; + } + + /* A setter of options fails only for a call that is not valid. */ + options = uapi16_manifest_options_new(); + r = uapi16_features_default(&features); + if (r >= 0) { + uapi16_features_union(&features, &more); + r = uapi16_manifest_options_set_features(options, &features); + } + if (r >= 0) + /* The file is on disk before it has its name. */ + r = uapi16_manifest_options_set_sync(options, true); + if (r < 0) { + fprintf(stderr, "options: %s\n", strerror(-r)); + return 1; + } + + /* Nothing has the name until the whole manifest is in the file. */ + r = uapi16_manifest_generate_at(options, out_fd, argv[3], top_fd, + UAPI16_ADD_GRACEFUL, &report, &error); + if (r < 0) { + /* The library has no messages. The return value is the + * errno, and the error has the kind and the file. */ + const char *path = uapi16_error_path(error); + + switch (uapi16_error_kind(error)) { + case UAPI16_ERROR_EXISTS: + fprintf(stderr, + "%s: there is a file of that name already\n", + argv[3]); + break; + case UAPI16_ERROR_CHANGED: + fprintf(stderr, "%s/%s: changed while it was read\n", + argv[1], path ? path : ""); + break; + default: + /* An enum grows, so a switch has a default. */ + fprintf(stderr, "%s/%s: %s\n", argv[1], + path ? path : "", strerror(-r)); + break; + } + return 1; + } + + printf("%" PRIu64 " files, %" PRIu64 " directories, %" PRIu64 + " others, %" PRIu64 " bytes\n", + uapi16_manifest_report_files(report), + uapi16_manifest_report_directories(report), + uapi16_manifest_report_others(report), + uapi16_manifest_report_bytes(report)); + if (uapi16_manifest_report_entries_omitted(report) > 0) + fprintf(stderr, + "%" PRIu64 " files have names a manifest can't hold " + "and were left out\n", + uapi16_manifest_report_entries_omitted(report)); + return 0; +} diff --git a/src/uapi16/examples/listing.c b/src/uapi16/examples/listing.c new file mode 100644 index 0000000..cd251ba --- /dev/null +++ b/src/uapi16/examples/listing.c @@ -0,0 +1,197 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +/* + * Writes the manifest of a store from the records a tool has of its files, + * as an image builder does that keeps the data of every file under the + * name of its hash: listing OUT-DIR NAME + * + * The records come in no order. The manifest lists them in its own. + */ +#define _GNU_SOURCE +/* Inode numbers and sizes of 64 bits, also where long has 32. */ +#define _FILE_OFFSET_BITS 64 +#include +#include +#include +#include +#include +#include +#include + +#include + +#define _cleanup_(f) __attribute__((cleanup(f))) + +/* One record of the tool. */ +struct record { + const char *name; /* the empty name is the root */ + uint32_t type; /* S_IFREG, S_IFDIR or S_IFLNK */ + uint32_t mode; + uint64_t size; + const char *sha256; /* 64 hex digits, for a regular file with data */ + const char *target; /* for a symbolic link */ + uint64_t inode; /* the same number for the names of one file, + * or 0 */ +}; + +static const struct record records[] = { + { "usr/bin/tool", S_IFREG, 0755, 5, + "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", + NULL, 7 }, + { "usr/bin/alias", S_IFLNK, 0, 4, NULL, "tool", 0 }, + { "usr/bin", S_IFDIR, 0755, 0, NULL, NULL, 0 }, + { "usr/libexec/tool", S_IFREG, 0755, 5, + "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", + NULL, 7 }, + { "usr/libexec", S_IFDIR, 0755, 0, NULL, NULL, 0 }, + { "usr", S_IFDIR, 0755, 0, NULL, NULL, 0 }, + { "", S_IFDIR, 0755, 0, NULL, NULL, 0 }, +}; + +static void closep(int *fd) { + if (*fd >= 0) + close(*fd); +} + +static int unhex(const char *hex, uapi16_sha256_digest_t *ret) { + for (size_t i = 0; i < UAPI16_SHA256_SIZE; i++) { + unsigned byte; + + if (sscanf(hex + 2 * i, "%2x", &byte) != 1) + return -1; + ret->bytes[i] = (uint8_t) byte; + } + return 0; +} + +/* Makes the file object of one record and adds it. */ +static int add(uapi16_manifest_writer *writer, const struct record *record, + uapi16_error **reterr) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = NULL; + int r; + + /* A name that a manifest can't hold fails here. */ + r = uapi16_file_object_new(record->name, &o, reterr); + if (r < 0) + return r; + + /* The setters store what they get. The add checks the object. The + * root is a directory already, and a symbolic link has no mode. */ + r = 0; + if (*record->name) + r = uapi16_file_object_set_type(o, record->type); + if (r >= 0 && !S_ISLNK(record->type)) + r = uapi16_file_object_set_mode(o, record->mode); + if (r >= 0) + r = uapi16_file_object_set_uid(o, 0); + if (r >= 0) + r = uapi16_file_object_set_gid(o, 0); + if (r >= 0 && !S_ISDIR(record->type)) + r = uapi16_file_object_set_size(o, record->size); + if (r >= 0 && record->target) + r = uapi16_file_object_set_target(o, record->target, + strlen(record->target)); + if (r >= 0 && record->inode) + /* Any number will do: the manifest gets its own. */ + r = uapi16_file_object_set_inode_token(o, record->inode); + if (r < 0) + return r; + + if (record->sha256) { + char blob[sizeof("blobs/") + 2 * UAPI16_SHA256_SIZE]; + uapi16_sha256_digest_t hash; + + if (unhex(record->sha256, &hash) < 0) + return -EINVAL; + r = uapi16_file_object_set_sha256(o, &hash); + if (r < 0) + return r; + /* The store has the data under the name of its hash, next to + * the manifest. */ + snprintf(blob, sizeof(blob), "blobs/%s", record->sha256); + r = uapi16_file_object_set_contents_file(o, blob, reterr); + if (r < 0) + return r; + } + + /* An object that is refused is not added, and the writer goes on. */ + return uapi16_manifest_writer_add_object(writer, o, reterr); +} + +int main(int argc, char *argv[]) { + /* What this tool records of every file. */ + static const uapi16_features_t features = + UAPI16_FEATURES_SET(UAPI16_FEATURE_MODE, UAPI16_FEATURE_UID, + UAPI16_FEATURE_GID, UAPI16_FEATURE_SIZE, + UAPI16_FEATURE_SHA256, + UAPI16_FEATURE_SYMLINK, + UAPI16_FEATURE_HARDLINK); + /* The writer borrows the descriptor of the directory until it is + * freed. So the descriptor is declared first, and is closed last. */ + _cleanup_(closep) int out_fd = -1; + _cleanup_(uapi16_manifest_options_freep) + uapi16_manifest_options *options = NULL; + _cleanup_(uapi16_manifest_writer_freep) + uapi16_manifest_writer *writer = NULL; + _cleanup_(uapi16_manifest_report_freep) + uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *error = NULL; + int r; + + if (argc != 3) { + fprintf(stderr, "usage: %s OUT-DIR NAME\n", argv[0]); + return 2; + } + out_fd = open(argv[1], O_PATH | O_DIRECTORY | O_CLOEXEC); + if (out_fd < 0) { + perror(argv[1]); + return 1; + } + + options = uapi16_manifest_options_new(); + r = uapi16_manifest_options_set_features(options, &features); + if (r < 0) { + fprintf(stderr, "options: %s\n", strerror(-r)); + return 1; + } + + /* The file appears when the finish gives it its name. A writer that + * is freed before that leaves nothing behind. */ + r = uapi16_manifest_writer_create_at(options, out_fd, argv[2], + &writer, &error); + for (size_t i = 0; r >= 0 && i < sizeof(records) / sizeof(records[0]); + i++) { + r = add(writer, &records[i], &error); + if (r < 0) + fprintf(stderr, "'%s': ", records[i].name); + } + /* Two different records of one name, and a directory that is + * missing, fail here. */ + if (r >= 0) + r = uapi16_manifest_writer_finish(writer, &report, &error); + if (r < 0) { + fprintf(stderr, "%s", strerror(-r)); + /* A call that takes a `reterr` stored an error. A setter + * takes none and fails with its return value alone. */ + if (error) { + const char *path = uapi16_error_path(error); + const char *field = uapi16_error_field(error); + const char *problem = uapi16_error_problem(error); + + if (path) + fprintf(stderr, ", file '%s'", path); + if (problem) + fprintf(stderr, ", %s", problem); + if (field) + fprintf(stderr, ", field %s", field); + } + fputc('\n', stderr); + return 1; + } + + printf("%" PRIu64 " records\n", + uapi16_manifest_report_files(report) + + uapi16_manifest_report_directories(report) + + uapi16_manifest_report_others(report)); + return 0; +} diff --git a/src/uapi16/examples/mkmanifest.rs b/src/uapi16/examples/mkmanifest.rs new file mode 100644 index 0000000..545dff3 --- /dev/null +++ b/src/uapi16/examples/mkmanifest.rs @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! Writes the manifest of a directory and everything below it to a new +//! file, and says what it lists: +//! +//! cargo run --example mkmanifest -- DIRECTORY OUTPUT + +use std::fs::File; +use std::path::Path; +use std::process::ExitCode; + +use uapi16::{AddFlags, Error, Features, ManifestOptions, ManifestReport}; + +fn main() -> ExitCode { + let args: Vec<_> = std::env::args_os().skip(1).collect(); + let [tree, output] = &args[..] else { + eprintln!("usage: mkmanifest DIRECTORY OUTPUT"); + return ExitCode::FAILURE; + }; + match mkmanifest(Path::new(tree), Path::new(output)) { + Ok(report) => { + println!( + "{} files, {} directories, {} other files, {} bytes", + report.files(), + report.directories(), + report.others(), + report.bytes() + ); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("mkmanifest: {e}"); + ExitCode::FAILURE + } + } +} + +/// Writes the manifest of the directory `tree` to the new file `output`, +/// with the default features and the modification times. +fn mkmanifest(tree: &Path, output: &Path) -> Result { + // The new file is a name in a directory: the one `output` is in, or + // the current one. + let dir = match output.parent() { + Some(dir) if !dir.as_os_str().is_empty() => dir, + _ => Path::new("."), + }; + let name = Path::new(output.file_name().unwrap_or_default()); + ManifestOptions::new() + .features(Features::DEFAULT | Features::MTIME) + .generate_at(File::open(dir)?, name, File::open(tree)?, AddFlags::NONE) +} diff --git a/src/uapi16/examples/signed.c b/src/uapi16/examples/signed.c new file mode 100644 index 0000000..f1bde38 --- /dev/null +++ b/src/uapi16/examples/signed.c @@ -0,0 +1,224 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +/* + * Writes a manifest with a signature object, then reads it back with what + * the signature objects sign: signed MANIFEST + * + * The library reads and writes signature objects. It neither makes nor + * verifies a signature: sign() stands in for an OpenPGP or an X.509 + * implementation here. + */ +#define _GNU_SOURCE +/* Inode numbers and sizes of 64 bits, also where long has 32. */ +#define _FILE_OFFSET_BITS 64 +#include +#include +#include +#include +#include +#include +#include + +#include + +#define _cleanup_(f) __attribute__((cleanup(f))) + +static void closep(int *fd) { + if (*fd >= 0) + close(*fd); +} + +/* Stands in for a signer: what it stores is no signature. */ +static void sign(const uapi16_sha256_digest_t *digest, + uint8_t ret[UAPI16_SHA256_SIZE]) { + for (size_t i = 0; i < UAPI16_SHA256_SIZE; i++) + ret[i] = digest->bytes[UAPI16_SHA256_SIZE - 1 - i]; +} + +/* Hashes the first `size` bytes of the file `fd`. */ +static int hash_start(int fd, uint64_t size, uapi16_sha256_digest_t *ret) { + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *sha = NULL; + static char buffer[1 << 16]; + uint64_t at = 0; + int r; + + sha = uapi16_sha256_new(); + while (at < size) { + size_t want = size - at < sizeof(buffer) + ? (size_t) (size - at) + : sizeof(buffer); + ssize_t n = pread(fd, buffer, want, (off_t) at); + + if (n < 0 && errno == EINTR) + continue; + if (n < 0) + return -errno; + if (n == 0) + return -EIO; /* the file is shorter than that */ + r = uapi16_sha256_update(sha, buffer, (size_t) n); + if (r < 0) + return r; + at += (uint64_t) n; + } + return uapi16_sha256_finish(sha, ret); +} + +static int write_signed(const char *path, uapi16_error **reterr) { + static const uapi16_sha256_digest_t hello = { .bytes = { + 0x2c, 0xf2, 0x4d, 0xba, 0x5f, 0xb0, 0xa3, 0x0e, + 0x26, 0xe8, 0x3b, 0x2a, 0xc5, 0xb9, 0xe2, 0x9e, + 0x1b, 0x16, 0x1e, 0x5c, 0x1f, 0xa7, 0x42, 0x5e, + 0x73, 0x04, 0x33, 0x62, 0x93, 0x8b, 0x98, 0x24 + } }; + /* The writer borrows the descriptor until it is freed. So the + * descriptor is declared first, and is closed last. */ + _cleanup_(closep) int fd = -1; + _cleanup_(uapi16_manifest_options_freep) + uapi16_manifest_options *options = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *writer = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = NULL; + _cleanup_(uapi16_signature_freep) uapi16_signature *signature = NULL; + uapi16_sha256_digest_t digest; + uint8_t signed_digest[UAPI16_SHA256_SIZE]; + struct stat st; + int r; + + fd = open(path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (fd < 0) + return -errno; + + /* The default features record sizes and hashes. */ + options = uapi16_manifest_options_new(); + r = uapi16_writer_begin(options, fd, NULL, &writer, reterr); + if (r < 0) + return r; + r = uapi16_file_object_new("hello.txt", &file, reterr); + if (r < 0) + return r; + r = uapi16_file_object_set_size(file, 5); + if (r >= 0) + r = uapi16_file_object_set_sha256(file, &hello); + if (r >= 0) + r = uapi16_writer_file(writer, file, reterr); + if (r < 0) + return r; + + /* Every record is written before its call returns. So the file + * holds the manifest up to here, and that is what the signature + * objects sign. */ + if (fstat(fd, &st) < 0) + return -errno; + r = hash_start(fd, (uint64_t) st.st_size, &digest); + if (r < 0) + return r; + sign(&digest, signed_digest); + + r = uapi16_signature_new("openpgp", &signature); + if (r >= 0) + r = uapi16_signature_set_key(signature, "an example key", + strlen("an example key")); + if (r >= 0) + r = uapi16_signature_set_data(signature, signed_digest, + sizeof(signed_digest)); + /* No file object can follow a signature object. */ + if (r >= 0) + r = uapi16_writer_signature(writer, signature, reterr); + /* The trailer ends the manifest. */ + if (r >= 0) + r = uapi16_writer_finish(writer, reterr); + return r; +} + +static int read_signed(const char *path, uapi16_error **reterr) { + /* The reader borrows the descriptor until it is freed. */ + _cleanup_(closep) int fd = -1; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = NULL; + _cleanup_(uapi16_signature_freep) uapi16_signature *s = NULL; + uapi16_sha256_digest_t digest; + uint8_t expected[UAPI16_SHA256_SIZE]; + uint64_t signed_len; + int r; + + fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) + return -errno; + r = uapi16_reader_open(fd, &reader, reterr); + if (r < 0) + return r; + + /* The file objects come first. One object serves the whole loop: + * each call clears it and fills it again. */ + while ((r = uapi16_reader_next(reader, &o, reterr)) == UAPI16_READ_FILE) + printf("%s\n", uapi16_file_object_name(o)); + if (r < 0) + return r; + if (r == UAPI16_READ_END) { + /* The trailer was read: the manifest is complete. */ + printf("no signature object\n"); + return 0; + } + /* A later library can return a number that this program does not + * know, which is an error here. */ + if (r != UAPI16_READ_SIGNATURES) { + fprintf(stderr, + "uapi16_reader_next() returned %d, which this program " + "does not know\n", + r); + return -EOPNOTSUPP; + } + + /* UAPI16_READ_SIGNATURES: signature objects follow, and the reader + * has what they sign. That is the start of the manifest, up to the + * first of them. pread() leaves alone where the reader reads on. */ + r = uapi16_reader_signed_len(reader, &signed_len); + if (r >= 0) + r = hash_start(fd, signed_len, &digest); + if (r < 0) + return r; + sign(&digest, expected); + + while ((r = uapi16_reader_next_signature(reader, &s, reterr)) == + UAPI16_READ_SIGNATURE) { + size_t size; + const void *data = uapi16_signature_data(s, &size); + + printf("a signature by %s: %s\n", uapi16_signature_mechanism(s), + data && size == sizeof(expected) && + !memcmp(data, expected, size) ? "good" : "bad"); + } + if (r < 0) + return r; + /* UAPI16_READ_END: the trailer was read and checked, and the + * manifest is complete. Any other number is one that this program + * does not know. */ + if (r != UAPI16_READ_END) { + fprintf(stderr, + "uapi16_reader_next_signature() returned %d, which " + "this program does not know\n", + r); + return -EOPNOTSUPP; + } + return 0; +} + +int main(int argc, char *argv[]) { + _cleanup_(uapi16_error_freep) uapi16_error *error = NULL; + int r; + + if (argc != 2) { + fprintf(stderr, "usage: %s MANIFEST\n", argv[0]); + return 2; + } + r = write_signed(argv[1], &error); + if (r >= 0) + r = read_signed(argv[1], &error); + if (r < 0) { + fprintf(stderr, "%s: %s", argv[1], strerror(-r)); + if (error && uapi16_error_problem(error)) + fprintf(stderr, ", %s", uapi16_error_problem(error)); + fputc('\n', stderr); + return 1; + } + return 0; +} diff --git a/src/uapi16/examples/sorted.c b/src/uapi16/examples/sorted.c new file mode 100644 index 0000000..fa2e56d --- /dev/null +++ b/src/uapi16/examples/sorted.c @@ -0,0 +1,222 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +/* + * Writes the records of a manifest in the order of the manifest, for a + * builder whose own walk is sorted already, and writes each record when + * the builder has stored the file: sorted SOURCE-DIR, with the + * manifest on standard output. + * + * Nothing is kept on disk, and every record is written before its call + * returns. + */ +#define _GNU_SOURCE +/* Inode numbers and sizes of 64 bits, also where long has 32. */ +#define _FILE_OFFSET_BITS 64 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define _cleanup_(f) __attribute__((cleanup(f))) + +struct names { + char **names; + size_t count; +}; + +static void closep(int *fd) { + if (*fd >= 0) + close(*fd); +} + +static void free_names(struct names *n) { + for (size_t i = 0; i < n->count; i++) + free(n->names[i]); + free(n->names); +} + +static int by_bytes(const void *a, const void *b) { + /* The names of one directory by their bytes: strcmp(), and not the + * order of the locale. */ + return strcmp(*(char *const *) a, *(char *const *) b); +} + +/* The names in the directory `dir_fd`, sorted by their bytes. */ +static int list(int dir_fd, struct names *ret) { + struct names n = { 0 }; + struct dirent *entry; + size_t room = 0; + int fd, r; + DIR *d; + + /* readdir() gets a descriptor of its own, which closedir() closes. */ + fd = openat(dir_fd, ".", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (fd < 0) + return -errno; + d = fdopendir(fd); + if (!d) { + r = -errno; + close(fd); + return r; + } + for (;;) { + errno = 0; + entry = readdir(d); + if (!entry) { + r = -errno; + break; + } + if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) + continue; + if (n.count == room) { + char **larger; + + room = room ? 2 * room : 64; + larger = realloc(n.names, room * sizeof(char *)); + if (!larger) { + r = -ENOMEM; + break; + } + n.names = larger; + } + n.names[n.count] = strdup(entry->d_name); + if (!n.names[n.count]) { + r = -ENOMEM; + break; + } + n.count++; + } + closedir(d); + if (r < 0) { + free_names(&n); + return r; + } + /* An empty directory has no names, and qsort() takes no NULL. */ + if (n.count > 0) + qsort(n.names, n.count, sizeof(char *), by_bytes); + *ret = n; + return 0; +} + +/* Stores what is in the directory `dir_fd`, whose name in the image is + * `name`, and writes the record of every file right after it stored it. + * This closes the descriptor. */ +static int build(uapi16_writer *writer, int dir_fd, const char *name, + uapi16_error **reterr) { + _cleanup_(closep) int fd = dir_fd; + _cleanup_(free_names) struct names n = { 0 }; + int r; + + r = list(fd, &n); + if (r < 0) + return r; + + /* Every directory is followed by what is in it. With the names of + * each directory sorted by their bytes, that is the code point + * order of the manifest. */ + for (size_t i = 0; i < n.count; i++) { + _cleanup_(uapi16_file_object_freep) + uapi16_file_object *o = NULL; + char child[4096]; + struct stat st; + + if (fstatat(fd, n.names[i], &st, AT_SYMLINK_NOFOLLOW) < 0) + return -errno; + /* This builder stores directories and regular files only. */ + if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode)) + continue; + r = snprintf(child, sizeof(child), "%s%s%s", name, + *name ? "/" : "", n.names[i]); + if (r < 0 || (size_t) r >= sizeof(child)) + return -ENAMETOOLONG; + + r = uapi16_file_object_new(child, &o, reterr); + if (r < 0) + return r; + r = uapi16_file_object_set_type(o, st.st_mode); + if (r >= 0) + r = uapi16_file_object_set_mode(o, st.st_mode); + if (r >= 0 && S_ISREG(st.st_mode)) + r = uapi16_file_object_set_size(o, + (uint64_t) st.st_size); + if (r < 0) + return r; + + /* The builder stores the file in its image here. */ + + /* The record goes out now. The writer refuses an object + * that is not where the order has it, and goes on. */ + r = uapi16_writer_file(writer, o, reterr); + if (r < 0) + return r; + + if (S_ISDIR(st.st_mode)) { + int sub = openat(fd, n.names[i], + O_RDONLY | O_DIRECTORY | + O_NOFOLLOW | O_CLOEXEC); + + if (sub < 0) + return -errno; + r = build(writer, sub, child, reterr); + if (r < 0) + return r; + } + } + return 0; +} + +int main(int argc, char *argv[]) { + static const uapi16_features_t features = + UAPI16_FEATURES_SET(UAPI16_FEATURE_MODE, UAPI16_FEATURE_SIZE); + _cleanup_(uapi16_manifest_options_freep) + uapi16_manifest_options *options = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *writer = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *error = NULL; + _cleanup_(closep) int source_fd = -1; + int r; + + if (argc != 2) { + fprintf(stderr, "usage: %s SOURCE-DIR\n", argv[0]); + return 2; + } + source_fd = open(argv[1], O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (source_fd < 0) { + perror(argv[1]); + return 1; + } + + /* The options say what the manifest records. The order is the code + * point order unless set. */ + options = uapi16_manifest_options_new(); + r = uapi16_manifest_options_set_features(options, &features); + /* This writes the root, which says nothing here. The writer borrows + * standard output until it is freed, and never closes it. */ + if (r >= 0) + r = uapi16_writer_begin(options, STDOUT_FILENO, NULL, + &writer, &error); + if (r >= 0) { + r = build(writer, source_fd, "", &error); + source_fd = -1; /* build() closed it */ + } + /* The trailer ends the manifest. A reader refuses one without it. */ + if (r >= 0) + r = uapi16_writer_finish(writer, &error); + if (r < 0) { + fprintf(stderr, "%s: %s", argv[0], strerror(-r)); + if (error && uapi16_error_path(error)) + fprintf(stderr, ", file '%s'", + uapi16_error_path(error)); + if (error && uapi16_error_problem(error)) + fprintf(stderr, ", %s", uapi16_error_problem(error)); + fputc('\n', stderr); + return 1; + } + return 0; +} diff --git a/src/uapi16/features.rs b/src/uapi16/features.rs index a995e07..af309be 100644 --- a/src/uapi16/features.rs +++ b/src/uapi16/features.rs @@ -6,6 +6,33 @@ use std::fmt; use std::ops::{BitAnd, BitOr, BitOrAssign}; use std::str::FromStr; +/// Makes the features from one table. An entry is a feature: its docs, +/// its constant, its number, counted from 1, and the name the +/// specification gives it, and the entries are in the order of the names. +/// The constants come of it, [`Features::COUNT`], which is how many +/// entries there are, and [`Features::NAMES`]. A new feature is one more +/// entry here and the field it stands for in the objects. +/// [`Features::checked`] holds the table to its order and its numbers +/// where the crate is built. +macro_rules! features { + ($($(#[$docs:meta])+ $constant:ident = $number:literal, $name:literal;)+) => { + $( + $(#[$docs])+ + pub const $constant: Features = Features::single($number); + )+ + + /// How many features there are: the entries of the table. The set + /// has a bit for each. + const COUNT: usize = [$($name),+].len(); + + /// Every single feature with its name, in the order of the names, + /// which is the order of the table. + const NAMES: [(Features, &'static str); Features::COUNT] = Features::checked([ + $((Features::$constant, $name),)+ + ]); + }; +} + /// The file system and partition table features a manifest records, which /// its root file object lists in the field `features`. /// @@ -37,7 +64,7 @@ use std::str::FromStr; /// assert_eq!(features.names().collect::>(), ["sha256", "size"]); /// ``` #[derive(Clone, Copy, PartialEq, Eq, Hash)] -pub struct Features(u32); +pub struct Features([u64; Features::WORDS]); /// A name that is not the name of a feature, see [`Features`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -52,153 +79,203 @@ impl fmt::Display for UnknownFeature { impl std::error::Error for UnknownFeature {} impl Features { - /// `mode`: the access mode, the field `mode`. - pub const MODE: Features = Features(1 << 0); - /// `uid`: the owning user, the field `uid`. - pub const UID: Features = Features(1 << 1); - /// `gid`: the owning group, the field `gid`. - pub const GID: Features = Features(1 << 2); - /// `user-name`: the name of the owning user, the field `userName`. - 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 data, the field `size`. - pub const SIZE: Features = Features(1 << 5); - /// `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 - /// `contents` then, as a literal. - pub const SYMLINK: Features = Features(1 << 7); - /// `device`: the numbers of device nodes, the fields `major` and - /// `minor`. - pub const DEVICE: Features = Features(1 << 8); - /// `hardlink`: which file objects are names of one file, the field - /// `inodeToken`. - pub const HARDLINK: Features = Features(1 << 9); - /// `mtime`: the modification time, the field `mTimeNSec`. - pub const MTIME: Features = Features(1 << 10); - /// `user-xattr`: the extended attributes of the `user` namespace, the - /// key `user` of the field `extendedAttributes`. - pub const USER_XATTR: Features = Features(1 << 11); - /// `flag-hidden`: the DOS attribute hidden, the field `flagHidden`. - pub const FLAG_HIDDEN: Features = Features(1 << 12); - /// `flag-system`: the DOS attribute system, the field `flagSystem`. - pub const FLAG_SYSTEM: Features = Features(1 << 13); - /// `flag-archive`: the DOS attribute archive, the field `flagArchive`. - pub const FLAG_ARCHIVE: Features = Features(1 << 14); - /// `flag-append-only`: the inode flag append only, the field - /// `flagAppendOnly`. - pub const FLAG_APPEND_ONLY: Features = Features(1 << 15); - /// `flag-immutable`: the inode flag immutable, the field - /// `flagImmutable`. - pub const FLAG_IMMUTABLE: Features = Features(1 << 16); - /// `flag-no-atime`: the inode flag no atime updates, the field - /// `flagNoAtime`. - pub const FLAG_NO_ATIME: Features = Features(1 << 17); - /// `flag-no-cow`: the inode flag no copy on write, the field - /// `flagNoCow`. - pub const FLAG_NO_COW: Features = Features(1 << 18); - /// `flag-no-dump`: the inode flag no dump, the field `flagNoDump`. - pub const FLAG_NO_DUMP: Features = Features(1 << 19); - /// `read-only`: whether a file is read-only, the field `readOnly`. - pub const READ_ONLY: Features = Features(1 << 20); - /// `fs-uuid`: the UUID of the file system, the field `fsUUID`. - pub const FS_UUID: Features = Features(1 << 21); - /// `fs-label`: the label of the file system, the field `fsLabel`. - pub const FS_LABEL: Features = Features(1 << 22); - /// `fat-serial`: the volume serial number of a FAT or exFAT file - /// system, the field `fatSerial`. - pub const FAT_SERIAL: Features = Features(1 << 23); - /// `gpt-label`: the label of a partition, the field `gptLabel`. - pub const GPT_LABEL: Features = Features(1 << 24); - /// `gpt-uuid`: the UUID of a partition, the field `gptUuid`. - pub const GPT_UUID: Features = Features(1 << 25); - /// `gpt-type-uuid`: the type UUID of a partition, the field - /// `gptTypeUuid`. - pub const GPT_TYPE_UUID: Features = Features(1 << 26); - /// `gpt-disk-uuid`: the disk UUID of the partition table, the field - /// `gptDiskUuid`. - pub const GPT_DISK_UUID: Features = Features(1 << 27); - /// `gpt-flags`: the attribute flags of a partition, the field - /// `gptFlags`. - pub const GPT_FLAGS: Features = Features(1 << 28); - /// `gpt-flag-no-auto`: the partition attribute flag no auto, the field - /// `gptFlagNoAuto`. - pub const GPT_FLAG_NO_AUTO: Features = Features(1 << 29); - /// `gpt-flag-grow-file-system`: the partition attribute flag grow file - /// system, the field `gptFlagGrowFileSystem`. - pub const GPT_FLAG_GROW_FILE_SYSTEM: Features = Features(1 << 30); + /// How many bits a word of the set has. + const WORD_BITS: usize = u64::BITS as usize; + /// How many words the set has: as many as its features need. + const WORDS: usize = Features::COUNT.div_ceil(Features::WORD_BITS); + + features! { + /// `device`: the numbers of device nodes, the fields `major` and + /// `minor`. + DEVICE = 9, "device"; + /// `fat-serial`: the volume serial number of a FAT or exFAT file + /// system, the field `fatSerial`. + FAT_SERIAL = 24, "fat-serial"; + /// `flag-append-only`: the inode flag append only, the field + /// `flagAppendOnly`. + FLAG_APPEND_ONLY = 16, "flag-append-only"; + /// `flag-archive`: the DOS attribute archive, the field `flagArchive`. + FLAG_ARCHIVE = 15, "flag-archive"; + /// `flag-hidden`: the DOS attribute hidden, the field `flagHidden`. + FLAG_HIDDEN = 13, "flag-hidden"; + /// `flag-immutable`: the inode flag immutable, the field + /// `flagImmutable`. + FLAG_IMMUTABLE = 17, "flag-immutable"; + /// `flag-no-atime`: the inode flag no atime updates, the field + /// `flagNoAtime`. + FLAG_NO_ATIME = 18, "flag-no-atime"; + /// `flag-no-cow`: the inode flag no copy on write, the field + /// `flagNoCow`. + FLAG_NO_COW = 19, "flag-no-cow"; + /// `flag-no-dump`: the inode flag no dump, the field `flagNoDump`. + FLAG_NO_DUMP = 20, "flag-no-dump"; + /// `flag-system`: the DOS attribute system, the field `flagSystem`. + FLAG_SYSTEM = 14, "flag-system"; + /// `fs-label`: the label of the file system, the field `fsLabel`. + FS_LABEL = 23, "fs-label"; + /// `fs-uuid`: the UUID of the file system, the field `fsUUID`. + FS_UUID = 22, "fs-uuid"; + /// `gid`: the owning group, the field `gid`. + GID = 3, "gid"; + /// `gpt-disk-uuid`: the disk UUID of the partition table, the field + /// `gptDiskUuid`. + GPT_DISK_UUID = 28, "gpt-disk-uuid"; + /// `gpt-flag-grow-file-system`: the partition attribute flag grow file + /// system, the field `gptFlagGrowFileSystem`. + GPT_FLAG_GROW_FILE_SYSTEM = 31, "gpt-flag-grow-file-system"; + /// `gpt-flag-no-auto`: the partition attribute flag no auto, the field + /// `gptFlagNoAuto`. + GPT_FLAG_NO_AUTO = 30, "gpt-flag-no-auto"; + /// `gpt-flags`: the attribute flags of a partition, the field + /// `gptFlags`. + GPT_FLAGS = 29, "gpt-flags"; + /// `gpt-label`: the label of a partition, the field `gptLabel`. + GPT_LABEL = 25, "gpt-label"; + /// `gpt-type-uuid`: the type UUID of a partition, the field + /// `gptTypeUuid`. + GPT_TYPE_UUID = 27, "gpt-type-uuid"; + /// `gpt-uuid`: the UUID of a partition, the field `gptUuid`. + GPT_UUID = 26, "gpt-uuid"; + /// `group-name`: the name of the owning group, the field `groupName`. + GROUP_NAME = 5, "group-name"; + /// `hardlink`: which file objects are names of one file, the field + /// `inodeToken`. + HARDLINK = 10, "hardlink"; + /// `mode`: the access mode, the field `mode`. + MODE = 1, "mode"; + /// `mtime`: the modification time, the field `mTimeNSec`. + MTIME = 11, "mtime"; + /// `read-only`: whether a file is read-only, the field `readOnly`. + READ_ONLY = 21, "read-only"; + /// `sha256`: the hash of the data, the field `sha256`. + SHA256 = 7, "sha256"; + /// `size`: the size of the data, the field `size`. + SIZE = 6, "size"; + /// `symlink`: the targets of symbolic links, the field `contents` of + /// file objects of the type `lnk`. Every one of them has its target in + /// `contents` then, as a literal. + SYMLINK = 8, "symlink"; + /// `uid`: the owning user, the field `uid`. + UID = 2, "uid"; + /// `user-name`: the name of the owning user, the field `userName`. + USER_NAME = 4, "user-name"; + /// `user-xattr`: the extended attributes of the `user` namespace, the + /// key `user` of the field `extendedAttributes`. + USER_XATTR = 12, "user-xattr"; + } /// No feature: the file objects carry names, inode types and the /// fields that belong to no feature. - pub const NONE: Features = Features(0); + pub const NONE: Features = Features([0; Features::WORDS]); /// What a manifest records that does not list its features, as the /// specification says: the access mode, the owner, size and hash, the /// targets of symbolic links, device numbers and hard links. - pub const DEFAULT: Features = Features( - Features::DEVICE.0 - | Features::GID.0 - | Features::HARDLINK.0 - | Features::MODE.0 - | Features::SHA256.0 - | Features::SIZE.0 - | Features::SYMLINK.0 - | Features::UID.0, - ); + pub const DEFAULT: Features = Features::DEVICE + .union(Features::GID) + .union(Features::HARDLINK) + .union(Features::MODE) + .union(Features::SHA256) + .union(Features::SIZE) + .union(Features::SYMLINK) + .union(Features::UID); /// Every feature. - pub const ALL: Features = Features((1 << Features::NAMES.len()) - 1); - - /// Every single feature with its name, in the order of the names. - const NAMES: [(Features, &'static str); 31] = [ - (Features::DEVICE, "device"), - (Features::FAT_SERIAL, "fat-serial"), - (Features::FLAG_APPEND_ONLY, "flag-append-only"), - (Features::FLAG_ARCHIVE, "flag-archive"), - (Features::FLAG_HIDDEN, "flag-hidden"), - (Features::FLAG_IMMUTABLE, "flag-immutable"), - (Features::FLAG_NO_ATIME, "flag-no-atime"), - (Features::FLAG_NO_COW, "flag-no-cow"), - (Features::FLAG_NO_DUMP, "flag-no-dump"), - (Features::FLAG_SYSTEM, "flag-system"), - (Features::FS_LABEL, "fs-label"), - (Features::FS_UUID, "fs-uuid"), - (Features::GID, "gid"), - (Features::GPT_DISK_UUID, "gpt-disk-uuid"), - (Features::GPT_FLAG_GROW_FILE_SYSTEM, "gpt-flag-grow-file-system"), - (Features::GPT_FLAG_NO_AUTO, "gpt-flag-no-auto"), - (Features::GPT_FLAGS, "gpt-flags"), - (Features::GPT_LABEL, "gpt-label"), - (Features::GPT_TYPE_UUID, "gpt-type-uuid"), - (Features::GPT_UUID, "gpt-uuid"), - (Features::GROUP_NAME, "group-name"), - (Features::HARDLINK, "hardlink"), - (Features::MODE, "mode"), - (Features::MTIME, "mtime"), - (Features::READ_ONLY, "read-only"), - (Features::SHA256, "sha256"), - (Features::SIZE, "size"), - (Features::SYMLINK, "symlink"), - (Features::UID, "uid"), - (Features::USER_NAME, "user-name"), - (Features::USER_XATTR, "user-xattr"), - ]; + pub const ALL: Features = { + let mut all = Features::NONE; + let mut number = 1; + while number <= Features::COUNT { + all = all.union(Features::single(number)); + number += 1; + } + all + }; + + /// The one feature with the number `number`, counted from 1: the bit + /// `number - 1` of the set. The table makes the constants with it, + /// and an entry with a number that no feature has does not build. + const fn single(number: usize) -> Features { + assert!(number != 0 && number <= Features::COUNT); + let bit = number - 1; + let mut words = [0; Features::WORDS]; + words[bit / Features::WORD_BITS] = 1 << (bit % Features::WORD_BITS); + Features(words) + } + + /// `names`, every feature with its name, once it is held to what the + /// table of the features promises: the names are in their order, each + /// before the next, and no two entries have one number. An entry + /// gives a number from 1 to the count of the entries, or + /// [`Features::single`] refuses it, so every such number is there + /// once. One pass over the entries. A table that breaks this does + /// not build. + const fn checked( + names: [(Features, &'static str); Features::COUNT], + ) -> [(Features, &'static str); Features::COUNT] { + let mut seen = Features::NONE; + let mut entry = 0; + while entry < names.len() { + let (feature, name) = names[entry]; + assert!(!seen.contains(feature), "two features have one number"); + seen = seen.union(feature); + if entry > 0 { + assert!( + Features::comes_before(names[entry - 1].1, name), + "the features are not in the order of their names" + ); + } + entry += 1; + } + names + } + + /// Whether the name `first` comes before the name `second` in the + /// order of their bytes, which is the order `features` lists them + /// in. + const fn comes_before(first: &str, second: &str) -> bool { + let (first, second) = (first.as_bytes(), second.as_bytes()); + let mut at = 0; + while at < first.len() && at < second.len() { + if first[at] != second[at] { + return first[at] < second[at]; + } + at += 1; + } + first.len() < second.len() + } /// Whether every feature of `features` is among these. pub const fn contains(self, features: Features) -> bool { - self.0 & features.0 == features.0 + let mut word = 0; + while word < Features::WORDS { + if self.0[word] & features.0[word] != features.0[word] { + return false; + } + word += 1; + } + true } /// These features without those of `features`. #[must_use] pub const fn without(self, features: Features) -> Features { - Features(self.0 & !features.0) + let mut words = self.0; + let mut word = 0; + while word < Features::WORDS { + words[word] &= !features.0[word]; + word += 1; + } + Features(words) } /// These features and those of `features`. #[must_use] pub const fn union(self, features: Features) -> Features { - Features(self.0 | features.0) + let mut words = self.0; + let mut word = 0; + while word < Features::WORDS { + words[word] |= features.0[word]; + word += 1; + } + Features(words) } /// The features with the names `names`, the names the specification @@ -229,6 +306,47 @@ impl Features { } } +/// Has the table of the features evaluated, and with that checked, also +/// where nothing is compiled to code, as for `cargo check`. +const _: [(Features, &str); Features::COUNT] = Features::NAMES; + +/// What the C API needs of the set beyond its public API. A set of C has +/// the words of this one: the feature with the number n is bit (n - 1) % 64 +/// of word (n - 1) / 64. +#[cfg(feature = "capi")] +impl Features { + /// How many features there are. + pub(crate) const fn count() -> usize { + Features::COUNT + } + + /// Word `index` of the set. A word the set does not have is 0. + pub(crate) const fn word(self, index: usize) -> u64 { + if index < Features::WORDS { + self.0[index] + } else { + 0 + } + } + + /// The features whose bits are set in `words`, from the first word on. + /// None where a bit is set that is the bit of no feature. + pub(crate) const fn of_words(words: &[u64]) -> Option { + let mut features = Features::NONE; + let mut index = 0; + while index < words.len() { + if words[index] & !Features::ALL.word(index) != 0 { + return None; + } + if index < Features::WORDS { + features.0[index] = words[index]; + } + index += 1; + } + Some(features) + } +} + impl Default for Features { /// [`Features::DEFAULT`]. fn default() -> Features { @@ -240,13 +358,13 @@ impl BitOr for Features { type Output = Features; fn bitor(self, other: Features) -> Features { - Features(self.0 | other.0) + self.union(other) } } impl BitOrAssign for Features { fn bitor_assign(&mut self, other: Features) { - self.0 |= other.0; + *self = self.union(other); } } @@ -256,7 +374,11 @@ impl BitAnd for Features { /// The features both have, those a tool that combines two manifests /// can keep. fn bitand(self, other: Features) -> Features { - Features(self.0 & other.0) + let mut words = self.0; + for (word, other) in words.iter_mut().zip(other.0) { + *word &= other; + } + Features(words) } } @@ -380,6 +502,109 @@ mod tests { assert_eq!(format!("{:?}", some), "Features(mtime | sha256 | size)"); } + /// The order of the names is the order of their bytes: a name comes + /// before every name it begins, and none before itself. + #[test] + fn name_order() { + for (first, second) in [ + ("", "gid"), + ("gid", "uid"), + ("gid", "gpt-uuid"), + ("gpt-flag-no-auto", "gpt-flags"), + ("size", "sizes"), + ] { + assert!(first < second, "{} {}", first, second); + assert!(Features::comes_before(first, second), "{} {}", first, second); + assert!(!Features::comes_before(second, first), "{} {}", first, second); + } + assert!(!Features::comes_before("uid", "uid")); + for names in Features::NAMES.windows(2) { + assert!(Features::comes_before(names[0].1, names[1].1), "{:?}", names); + } + } + + /// The table as it is passes its check, and comes back as it went in. + #[test] + fn a_table_in_order() { + assert_eq!(Features::checked(Features::NAMES), Features::NAMES); + } + + /// A table whose names are not in their order is refused: the check + /// that the crate is built with fails. + #[test] + #[should_panic(expected = "the features are not in the order of their names")] + fn a_table_out_of_order() { + let mut names = Features::NAMES; + names.swap(0, 1); + Features::checked(names); + } + + /// So is one with the same name twice. + #[test] + #[should_panic(expected = "the features are not in the order of their names")] + fn a_table_with_a_name_twice() { + let mut names = Features::NAMES; + names[1].1 = names[0].1; + Features::checked(names); + } + + /// And one in which two features have one number. + #[test] + #[should_panic(expected = "two features have one number")] + fn a_table_with_a_number_twice() { + let mut names = Features::NAMES; + names[1].0 = names[0].0; + Features::checked(names); + } + + /// No feature has the number 0: the numbers count from 1. + #[test] + #[should_panic(expected = "number != 0 && number <= Features::COUNT")] + fn no_feature_before_the_first() { + Features::single(0); + } + + /// And none has a number past the count of the features, so a table + /// with as many numbers as entries, each once, has no gap. + #[test] + #[should_panic(expected = "number != 0 && number <= Features::COUNT")] + fn no_feature_past_the_last() { + Features::single(Features::COUNT + 1); + } + + /// The feature with the number n is bit n - 1 of the set, the set has + /// a bit for every feature and no other, and its operations work on + /// every word of it. + #[test] + fn bits() { + let single: Vec = (1..=Features::COUNT).map(Features::single).collect(); + assert_eq!(single.len(), Features::NAMES.len()); + for (bit, feature) in single.iter().enumerate() { + let mut words = [0; Features::WORDS]; + words[bit / Features::WORD_BITS] = 1 << (bit % Features::WORD_BITS); + assert_eq!(feature.0, words, "{:?}", feature); + // It is one of the features that have a name. + assert_eq!(feature.names().count(), 1, "{:?}", feature); + } + let all = single.iter().fold(Features::NONE, |all, feature| all | *feature); + assert_eq!(all, Features::ALL); + let bits: u32 = Features::ALL.0.iter().map(|word| word.count_ones()).sum(); + assert_eq!(bits as usize, Features::COUNT); + for one in &single { + assert!(Features::ALL.contains(*one) && !Features::NONE.contains(*one)); + assert!(!Features::ALL.without(*one).contains(*one)); + assert_eq!(Features::ALL.without(*one).union(*one), Features::ALL); + for other in &single { + let both = one.union(*other); + assert!(both.contains(*one) && both.contains(*other)); + assert_eq!(one.contains(*other), one == other); + assert_eq!(both & *one, *one); + assert_eq!(both.without(*other).contains(*one), one != other); + assert_eq!((*one & *other) == Features::NONE, one != other); + } + } + } + #[test] fn orders() { assert_eq!(Order::declared("codepoint"), Some(Order::CodePoint)); diff --git a/src/uapi16/hardlink.rs b/src/uapi16/hardlink.rs new file mode 100644 index 0000000..9e76f0d --- /dev/null +++ b/src/uapi16/hardlink.rs @@ -0,0 +1,2874 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The hard links of the files that are added to a manifest: which names +//! are names of one inode, whether they show the same file, and the +//! `inodeToken` each inode gets. +//! +//! The names of an inode can come far apart, and a tree can have as many +//! inodes with several names as it has files. So what is kept for each of +//! them, a group, is kept in a hash table that moves to a scratch file once +//! it has outgrown a few megabytes. From then on memory holds a fixed +//! number of its pages and no more, however large the tree is. +//! +//! The table is made of pages of 4 KiB, each with room for a fixed number +//! of groups. A group goes into the page its key hashes to, and into the +//! next page that has room if that one is full, which is then marked as +//! having overflowed. A lookup goes on to the next page only from a page +//! with that mark. Nothing is ever removed, so there is nothing to mark as +//! removed. Once three quarters of the room are taken the table doubles: +//! its pages are read one after the other and every group is placed again +//! in a table of twice the pages. The old pages are only read for that, so +//! a doubling that fails keeps them, and the table is as it was before it +//! began. On disk the pages go through a small cache, each page in the one +//! place of the cache its number gives it. The number of places is prime, +//! so the two pages a page splits into when the table doubles never push +//! each other out. +//! +//! A table on disk doubles into a second scratch file, and gives the file +//! of the old pages back once it has. A doubling that fails gives back the +//! second file instead, and a move to disk that fails both of its files. A +//! scratch file that is given back is not closed: it is emptied and stays +//! open for as long as trees are walked for the manifest, see +//! [`OwnFiles`](crate::sys::OwnFiles). Otherwise a walk of the directory +//! the scratch files are in could come to what a file system still shows of +//! a file that was just closed. The scratch space hands such a file out +//! again before it makes a new one, see +//! [`Scratch::file`](crate::scratch::Scratch::file). So a table on disk +//! takes turns between two files for its pages, however often it doubles, +//! and has one descriptor more than it uses, for the file that is empty. +//! Where something else was handed that file meanwhile, as the sort can +//! be, the next doubling makes one more. +//! +//! A group is kept until the manifest is complete, also once as many of +//! its names came as its inode has. That costs room: the scratch file +//! grows by a few hundred bytes for every inode with several names. Giving +//! the room back would split an inode into two groups with two tokens +//! whenever the number of its names is wrong or changes while a tree is +//! read, as with a rename into a directory that is still to come or with a +//! file system that makes the number up. The specification gives one inode +//! one token. + +use std::collections::hash_map::RandomState; +use std::hash::BuildHasher; +use std::io; +use std::mem; +use std::num::NonZeroU64; + +use rustix::fs::FileType; + +use crate::digest::Sha256Context; +use crate::error::{Error, ErrorKind, Field, TreeProblem}; +use crate::object::{FileObject, FlagSet, InodeFlags}; +use crate::scratch::Scratch; +use crate::sys::ScratchFile; +use crate::tree::{DeviceNumber, Failure, Identity, MountId, Status, Subject, Timestamp}; +use crate::{Mode, Name, NameBuf, Sha256}; + +/// The size of a page of the table. +const PAGE_SIZE: usize = 4096; +/// The size of what a page starts with: how many groups it holds, in two +/// bytes, and its marks, in two more. The rest is zero. +const HEADER_SIZE: usize = 8; +/// The mark of a page that was full when a group came that belongs into +/// it, so that the group is in a page behind it. +const OVERFLOWED: u16 = 1; +/// The size of the key of a group. +const KEY_SIZE: usize = 40; +/// The size of what statx() says of a file, see [`Seen`]. +const SEEN_SIZE: usize = 52; +/// The size of what is kept of the file a group is of, see [`Likeness`]: +/// what is there, what statx() says of the file, the hash of its data and +/// the hash of the fields of its file object. +const LIKENESS_SIZE: usize = 1 + SEEN_SIZE + 2 * Sha256::SIZE; +/// The size of a group in a page: its key, its token, where its first +/// name is and how long, and what is kept of its file, padded to a +/// multiple of eight. +const SLOT_SIZE: usize = 176; +/// How many groups a page has room for. +const SLOTS: usize = (PAGE_SIZE - HEADER_SIZE) / SLOT_SIZE; +/// Where a group has its token in its slot, right behind its key. +const TOKEN_AT: usize = KEY_SIZE; +/// What the token of a group is before it has one. +const NO_TOKEN: u64 = 0; + +/// How large the table and the first names of its groups get, with the +/// pages a doubling needs for a while, before they move to scratch files. +const MEMORY_LIMIT: usize = 8 * 1024 * 1024; +/// How many pages the table starts with. +const FIRST_PAGES: u64 = 16; +/// How many pages of a table on disk are kept in memory: a prime. +const CACHED_PAGES: usize = 251; +/// How many pages are read at a time when a table on disk doubles. +const CHUNK_PAGES: usize = 256; +/// How many bytes of names are gathered before they are written out. +const NAMES_BUFFER: usize = 64 * 1024; +/// What a page costs that the table reads from its scratch file or writes +/// to it to hand out a token, in bytes of the budget of whoever asks for +/// the token: as many as the page has. So a step that asks a table on disk +/// for tokens reads and writes about what its budget says, as a step does +/// that asks for none. +const PAGE_COST: u64 = PAGE_SIZE as u64; + +/// An error for a scratch file that does not hold what was written to it. +fn damaged() -> io::Error { + io::Error::new( + io::ErrorKind::InvalidData, + "a scratch file of the hard links was changed", + ) +} + +/// Writes the parts of a group one behind the other. +struct Encoder<'a> { + bytes: &'a mut [u8], + at: usize, +} + +impl Encoder<'_> { + fn bytes(&mut self, bytes: &[u8]) { + self.bytes[self.at..self.at + bytes.len()].copy_from_slice(bytes); + self.at += bytes.len(); + } + + fn u8(&mut self, value: u8) { + self.bytes(&[value]); + } + + fn u16(&mut self, value: u16) { + self.bytes(&value.to_le_bytes()); + } + + fn u32(&mut self, value: u32) { + self.bytes(&value.to_le_bytes()); + } + + fn u64(&mut self, value: u64) { + self.bytes(&value.to_le_bytes()); + } + + fn i64(&mut self, value: i64) { + self.bytes(&value.to_le_bytes()); + } +} + +/// Reads the parts of a group one behind the other. What is read comes +/// from a scratch file, so nothing about it is taken for granted. +struct Decoder<'a> { + bytes: &'a [u8], +} + +impl Decoder<'_> { + fn array(&mut self) -> io::Result<[u8; SIZE]> { + let (array, rest) = self.bytes.split_first_chunk().ok_or_else(damaged)?; + self.bytes = rest; + Ok(*array) + } + + fn u8(&mut self) -> io::Result { + Ok(u8::from_le_bytes(self.array()?)) + } + + fn u16(&mut self) -> io::Result { + Ok(u16::from_le_bytes(self.array()?)) + } + + fn u32(&mut self) -> io::Result { + Ok(u32::from_le_bytes(self.array()?)) + } + + fn u64(&mut self) -> io::Result { + Ok(u64::from_le_bytes(self.array()?)) + } + + fn i64(&mut self) -> io::Result { + Ok(i64::from_le_bytes(self.array()?)) + } +} + +/// What tells the groups of hard links apart. +/// +/// The names of the files of a tree are in one group if they are names of +/// one inode reached through one mount. The file objects a caller hands in +/// are in one group if they have the same `inodeToken`, and they never +/// share a group with the files of a tree: the tokens of a caller are +/// numbers of its own. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum GroupKey { + /// A file of a tree. + Walked(Identity), + /// A file object of a caller, with its `inodeToken`. + Given(NonZeroU64), +} + +impl GroupKey { + /// A file of a tree whose mount ID no other mount ever gets. + const WALKED_UNIQUE: u8 = 1; + /// A file of a tree whose mount ID is the one of /proc/self/mountinfo. + const WALKED_REUSABLE: u8 = 2; + /// A file object of a caller. + const GIVEN: u8 = 3; + + /// The key as the table has it: what kind of key it is, whether a + /// file is in a subvolume, and the numbers. No key starts with a zero, + /// which is how an empty slot starts. + pub(crate) fn encode(&self) -> [u8; KEY_SIZE] { + let mut key = [0; KEY_SIZE]; + let mut encoder = Encoder { bytes: &mut key, at: 0 }; + match self { + GroupKey::Walked(identity) => { + let (kind, mount) = match identity.mount { + MountId::Unique(mount) => (GroupKey::WALKED_UNIQUE, mount), + MountId::Reusable(mount) => (GroupKey::WALKED_REUSABLE, mount), + }; + encoder.u8(kind); + encoder.u8(u8::from(identity.subvolume.is_some())); + encoder.bytes(&[0; 6]); + encoder.u64(mount); + encoder.u32(identity.device.major); + encoder.u32(identity.device.minor); + encoder.u64(identity.inode); + encoder.u64(identity.subvolume.unwrap_or_default()); + } + GroupKey::Given(token) => { + encoder.u8(GroupKey::GIVEN); + encoder.bytes(&[0; 7]); + encoder.u64(token.get()); + } + } + key + } + + /// The key `key` is the form of in the table. + pub(crate) fn decode(key: &[u8; KEY_SIZE]) -> io::Result { + let mut decoder = Decoder { bytes: key }; + let (kind, in_subvolume) = (decoder.u8()?, decoder.u8()?); + let _: [u8; 6] = decoder.array()?; + let number = decoder.u64()?; + let mount = match kind { + GroupKey::WALKED_UNIQUE => MountId::Unique(number), + GroupKey::WALKED_REUSABLE => MountId::Reusable(number), + GroupKey::GIVEN => return NonZeroU64::new(number).map(GroupKey::Given).ok_or_else(damaged), + _ => return Err(damaged()), + }; + let device = DeviceNumber { + major: decoder.u32()?, + minor: decoder.u32()?, + }; + let (inode, subvolume) = (decoder.u64()?, decoder.u64()?); + let subvolume = match in_subvolume { + 0 => None, + 1 => Some(subvolume), + _ => return Err(damaged()), + }; + Ok(GroupKey::Walked(Identity { + mount, + device, + inode, + subvolume, + })) + } +} + +/// What statx() says of a file that all of its names have to agree in: its +/// type, its mode, its owner, the device it stands for, its size, its +/// modification time and its birth time. The change time is not among +/// them: making or removing another name of the file moves it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Seen { + file_type: FileType, + mode: Mode, + uid: u32, + gid: u32, + rdev: DeviceNumber, + size: u64, + mtime: Timestamp, + btime: Option, +} + +impl Seen { + /// The birth time of the file is there. + const HAS_BTIME: u8 = 1 << 0; + /// The types of files, each with the number it has in the bytes. + const FILE_TYPES: [(FileType, u8); 8] = [ + (FileType::Unknown, 0), + (FileType::RegularFile, 1), + (FileType::Directory, 2), + (FileType::Symlink, 3), + (FileType::Fifo, 4), + (FileType::CharacterDevice, 5), + (FileType::BlockDevice, 6), + (FileType::Socket, 7), + ]; + /// A time that is not there, in the bytes. + const NO_TIME: Timestamp = Timestamp { + seconds: 0, + nanoseconds: 0, + }; + + /// What the status `status` says of its file that all names of the + /// file have to agree in. + pub(crate) fn of(status: &Status) -> Seen { + Seen { + file_type: status.file_type, + mode: status.mode, + uid: status.uid, + gid: status.gid, + rdev: status.rdev, + size: status.size, + mtime: status.mtime, + btime: status.btime, + } + } + + /// Whether this and `other` can be of one file. The birth time only + /// counts where both have one. + pub(crate) fn same_file(&self, other: &Seen) -> bool { + let btime = match (self.btime, other.btime) { + (Some(one), Some(another)) => one == another, + _ => true, + }; + btime + && (self.file_type, self.mode, self.uid, self.gid) == (other.file_type, other.mode, other.uid, other.gid) + && (self.rdev, self.size, self.mtime) == (other.rdev, other.size, other.mtime) + } + + /// Writes this into `bytes`, as a slot of the table has it. + fn encode(&self, bytes: &mut [u8; SEEN_SIZE]) { + let file_type = Seen::FILE_TYPES + .iter() + .find(|(file_type, _)| *file_type == self.file_type) + .map_or(0, |&(_, number)| number); + let btime = self.btime.unwrap_or(Seen::NO_TIME); + let mut encoder = Encoder { bytes, at: 0 }; + encoder.u8(if self.btime.is_some() { Seen::HAS_BTIME } else { 0 }); + encoder.u8(file_type); + // A mode has twelve bits. + encoder.u16(self.mode.bits() as u16); + encoder.u32(self.uid); + encoder.u32(self.gid); + encoder.u32(self.rdev.major); + encoder.u32(self.rdev.minor); + encoder.u64(self.size); + encoder.i64(self.mtime.seconds); + encoder.u32(self.mtime.nanoseconds); + encoder.i64(btime.seconds); + encoder.u32(btime.nanoseconds); + debug_assert_eq!(encoder.at, SEEN_SIZE); + } + + /// What `bytes` holds, which [`Seen::encode`] wrote. + fn decode(bytes: &[u8; SEEN_SIZE]) -> io::Result { + let mut decoder = Decoder { bytes }; + let (marks, file_type) = (decoder.u8()?, decoder.u8()?); + if marks & !Seen::HAS_BTIME != 0 { + return Err(damaged()); + } + let file_type = Seen::FILE_TYPES + .iter() + .find(|(_, number)| *number == file_type) + .map(|&(file_type, _)| file_type) + .ok_or_else(damaged)?; + let mode = Mode::new(u32::from(decoder.u16()?)).map_err(|_| damaged())?; + let (uid, gid) = (decoder.u32()?, decoder.u32()?); + let rdev = DeviceNumber { + major: decoder.u32()?, + minor: decoder.u32()?, + }; + let size = decoder.u64()?; + let mtime = Timestamp { + seconds: decoder.i64()?, + nanoseconds: decoder.u32()?, + }; + let btime = Timestamp { + seconds: decoder.i64()?, + nanoseconds: decoder.u32()?, + }; + let btime = match (marks & Seen::HAS_BTIME != 0, btime) { + (true, btime) => Some(btime), + (false, Seen::NO_TIME) => None, + (false, _) => return Err(damaged()), + }; + Ok(Seen { + file_type, + mode, + uid, + gid, + rdev, + size, + mtime, + btime, + }) + } +} + +/// What the names of one inode have to be alike in to be names of the +/// same file. The first name of a group gives it, and every other name is +/// held against it. +/// +/// For a file of a tree that is what statx() says of it, the hash of its +/// data if it is a regular file, and a hash of the fields the manifest +/// records for it. For a file object of a caller it is only the last one. +/// The specification asks all file objects of one `inodeToken` to have the +/// same type, mode, owner, names of the owner, modification time, size, +/// hash, device numbers, extended attributes and inode flags, and these +/// are the fields that hash is over. So a group whose extended attributes +/// change between two of its names does not go out with two versions of +/// them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Likeness { + seen: Option, + data: Option, + fields: Sha256, +} + +impl Likeness { + /// What statx() said of the file is there. + const HAS_SEEN: u8 = 1 << 0; + /// The hash of the data of the file is there. + const HAS_DATA: u8 = 1 << 1; + + /// What a file of a tree has to be alike in with its other names, + /// where `seen` is what statx() says of it, `data` is the hash of its + /// data, if it is a regular file, and `object` is the file object the + /// manifest gets for this name. + pub(crate) fn walked(seen: Seen, data: Option, object: &FileObject) -> Likeness { + Likeness { + seen: Some(seen), + data, + fields: Likeness::fields(object), + } + } + + /// What the file object `object` of a caller has to be alike in with + /// the other file objects of its `inodeToken`. + pub(crate) fn given(object: &FileObject) -> Likeness { + Likeness { + seen: None, + data: None, + fields: Likeness::fields(object), + } + } + + /// A hash over the fields of `object` that the specification asks to be + /// the same on all file objects of one `inodeToken`: the type, `mode`, + /// `uid`, `gid`, `userName`, `groupName`, `mTimeNSec`, `size`, + /// `sha256`, `major`, `minor`, `extendedAttributes` and the inode + /// flags. They go in as the record of the object has them: a field a + /// reader filled in or a flag that is cleared is not in the record. + /// Every field goes in with whether it is there and with its length, so + /// that no two sets of fields give the same bytes. + fn fields(object: &FileObject) -> Sha256 { + let mut hash = Sha256Context::new(); + let mut field = |value: Option<&[u8]>| { + hash.update(&[u8::from(value.is_some())]); + let value = value.unwrap_or_default(); + hash.update(&(value.len() as u64).to_le_bytes()); + hash.update(value); + }; + let filled_in = object.filled_in(); + let inode = object.inode(); + let number = |value: Option| value.map(u64::to_le_bytes); + field(Some(object.inode_type().as_str().as_bytes())); + field( + number(inode.mode().map(|mode| u64::from(mode.bits()))) + .as_ref() + .map(|n| &n[..]), + ); + field(number(inode.uid().map(u64::from)).as_ref().map(|n| &n[..])); + field(number(inode.gid().map(u64::from)).as_ref().map(|n| &n[..])); + field(inode.user_name().map(str::as_bytes)); + field(inode.group_name().map(str::as_bytes)); + field(number(inode.mtime_nsec()).as_ref().map(|n| &n[..])); + let size = object.size().filter(|_| !filled_in.contains(Field::Size)); + field(number(size).as_ref().map(|n| &n[..])); + let sha256 = object.sha256().filter(|_| !filled_in.contains(Field::Sha256)); + field(sha256.as_ref().map(|sha256| &sha256.as_bytes()[..])); + field(number(object.major()).as_ref().map(|n| &n[..])); + field(number(object.minor()).as_ref().map(|n| &n[..])); + // A record has no `extendedAttributes` where there are none, so no + // attributes and none that are listed are the same here. + for (name, value) in inode.user_xattrs().into_iter().flatten() { + field(Some(name.as_bytes())); + field(Some(value)); + } + field(None); + for &(flag, _, _) in InodeFlags::FIELDS { + field(Some(&[u8::from(inode.flags().get(flag) == Some(true))])); + } + hash.finalize() + } + + /// Whether this and `other` can be of one file. The hashes of the data + /// only count where both have one: a file that is not a regular file + /// has none, and neither has a file object of a caller. + fn same_file(&self, other: &Likeness) -> bool { + let seen = match (&self.seen, &other.seen) { + (Some(one), Some(another)) => one.same_file(another), + (None, None) => true, + _ => false, + }; + let data = match (self.data, other.data) { + (Some(one), Some(another)) => one == another, + _ => true, + }; + seen && data && self.fields == other.fields + } + + /// Writes this into `bytes`, as a slot of the table has it. + fn encode(&self, bytes: &mut [u8; LIKENESS_SIZE]) { + let mut seen = [0; SEEN_SIZE]; + if let Some(of_file) = &self.seen { + of_file.encode(&mut seen); + } + let marks = [ + (self.seen.is_some(), Likeness::HAS_SEEN), + (self.data.is_some(), Likeness::HAS_DATA), + ]; + let marks = marks + .into_iter() + .filter(|(there, _)| *there) + .fold(0, |marks, (_, mark)| marks | mark); + let mut encoder = Encoder { bytes, at: 0 }; + encoder.u8(marks); + encoder.bytes(&seen); + encoder.bytes(self.data.unwrap_or(Sha256::EMPTY).as_bytes()); + encoder.bytes(self.fields.as_bytes()); + debug_assert_eq!(encoder.at, LIKENESS_SIZE); + } + + /// What `bytes` holds, which [`Likeness::encode`] wrote. + fn decode(bytes: &[u8; LIKENESS_SIZE]) -> io::Result { + let mut decoder = Decoder { bytes }; + let marks = decoder.u8()?; + if marks & !(Likeness::HAS_SEEN | Likeness::HAS_DATA) != 0 { + return Err(damaged()); + } + let seen = Seen::decode(&decoder.array()?)?; + let data = Sha256::from(decoder.array()?); + let fields = Sha256::from(decoder.array()?); + Ok(Likeness { + seen: (marks & Likeness::HAS_SEEN != 0).then_some(seen), + data: (marks & Likeness::HAS_DATA != 0).then_some(data), + fields, + }) + } +} + +/// Where the first name of a group is among the names, and how long it is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct NameAt { + offset: u64, + len: u16, +} + +/// A group as a slot of the table has it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Group { + key: [u8; KEY_SIZE], + /// The token of the group, [`NO_TOKEN`] until it gets one. + token: u64, + name: NameAt, + likeness: Likeness, +} + +impl Group { + fn encode(&self) -> [u8; SLOT_SIZE] { + let mut slot = [0; SLOT_SIZE]; + let mut likeness = [0; LIKENESS_SIZE]; + self.likeness.encode(&mut likeness); + let mut encoder = Encoder { + bytes: &mut slot, + at: 0, + }; + encoder.bytes(&self.key); + encoder.u64(self.token); + encoder.u64(self.name.offset); + encoder.u16(self.name.len); + encoder.bytes(&likeness); + slot + } + + fn decode(slot: &[u8]) -> io::Result { + let mut decoder = Decoder { bytes: slot }; + let key = decoder.array()?; + let token = decoder.u64()?; + let name = NameAt { + offset: decoder.u64()?, + len: decoder.u16()?, + }; + let likeness = Likeness::decode(&decoder.array()?)?; + Ok(Group { + key, + token, + name, + likeness, + }) + } +} + +/// A page of the table: how many groups it holds, whether it overflowed, +/// and its slots, of which the first ones are taken. +struct Page; + +impl Page { + /// How many groups the page `page` holds. + fn count(page: &[u8]) -> io::Result { + let count = usize::from(u16::from_le_bytes([page[0], page[1]])); + if count > SLOTS { + return Err(damaged()); + } + Ok(count) + } + + /// How many groups the page `page` holds, and whether it was full when + /// a group came for it. Only a full page is ever marked as that, so a + /// lookup that finds the mark on another page is not sent on through + /// the whole table by it. + fn state(page: &[u8]) -> io::Result<(usize, bool)> { + let count = Page::count(page)?; + let overflowed = u16::from_le_bytes([page[2], page[3]]) & OVERFLOWED != 0; + if overflowed && count < SLOTS { + return Err(damaged()); + } + Ok((count, overflowed)) + } + + /// Marks the page `page` as one that overflowed. + fn set_overflowed(page: &mut [u8]) { + page[2..4].copy_from_slice(&OVERFLOWED.to_le_bytes()); + } + + /// The slot `index` of the page `page`. + fn slot(page: &[u8], index: usize) -> &[u8] { + let at = HEADER_SIZE + index * SLOT_SIZE; + &page[at..at + SLOT_SIZE] + } + + /// Puts `slot` into the first free slot of the page `page`, which + /// holds `count` groups and has room for one more. + fn push(page: &mut [u8], count: usize, slot: &[u8]) { + let at = HEADER_SIZE + count * SLOT_SIZE; + page[at..at + SLOT_SIZE].copy_from_slice(slot); + // A page has room for fewer groups than two bytes count. + page[0..2].copy_from_slice(&(count as u16 + 1).to_le_bytes()); + } +} + +/// The pages of a table in a scratch file, with those of them that memory +/// holds. A page that is asked for takes the place its number gives it, and +/// the page that was there is written out first if it changed. +#[derive(Debug)] +struct DiskPages { + file: ScratchFile, + /// How many pages the file has. + pages: u64, + /// The pages memory holds, one after the other. + cache: Vec, + /// The number of the page in each place, [`DiskPages::NONE`] for + /// none. + numbers: Vec, + /// Whether the page in each place changed since it was read. + changed: Vec, + /// How many pages were read from the file and written to it. + transfers: u64, +} + +impl DiskPages { + /// The number of no page. + const NONE: u64 = u64::MAX; + + /// The table of `pages` pages in `file`, with `cached` of them in + /// memory at a time. + fn new(file: ScratchFile, pages: u64, cached: usize) -> DiskPages { + DiskPages::with_cache(file, pages, vec![0; cached * PAGE_SIZE]) + } + + /// The table of `pages` pages in `file`, with as many of them in + /// memory at a time as `cache` has room for, which holds none yet. + fn with_cache(file: ScratchFile, pages: u64, cache: Vec) -> DiskPages { + let cached = cache.len() / PAGE_SIZE; + DiskPages { + file, + pages, + cache, + numbers: vec![DiskPages::NONE; cached], + changed: vec![false; cached], + transfers: 0, + } + } + + /// Where the page `number` is in the file. + fn offset(number: u64) -> u64 { + number * PAGE_SIZE as u64 + } + + /// Writes the page in the place `place` out, if it changed. + fn write_out(&mut self, place: usize) -> io::Result<()> { + if self.changed[place] { + let page = &self.cache[place * PAGE_SIZE..(place + 1) * PAGE_SIZE]; + self.file.write_all_at(page, DiskPages::offset(self.numbers[place]))?; + self.changed[place] = false; + self.transfers += 1; + } + Ok(()) + } + + /// Writes every page that changed out. + fn flush(&mut self) -> io::Result<()> { + (0..self.numbers.len()).try_for_each(|place| self.write_out(place)) + } + + /// Hands the memory the pages are kept in over, to the table this one + /// doubles into, once every page that changed was written out: memory + /// holds none of these pages from then on, and the memory comes back + /// where the doubling fails, see [`Store::take_back_cache`]. + fn lend_cache(&mut self) -> io::Result> { + self.flush()?; + self.numbers.fill(DiskPages::NONE); + Ok(mem::take(&mut self.cache)) + } + + /// The place of the page `number` in memory, read from the file if it + /// is not there. + fn load(&mut self, number: u64) -> io::Result { + // The remainder is less than the number of places. + let place = (number % self.numbers.len() as u64) as usize; + if self.numbers[place] != number { + self.write_out(place)?; + // The place holds no page until the read went through. + self.numbers[place] = DiskPages::NONE; + let page = &mut self.cache[place * PAGE_SIZE..(place + 1) * PAGE_SIZE]; + self.file.read_exact_at(page, DiskPages::offset(number))?; + self.numbers[place] = number; + self.transfers += 1; + } + Ok(place) + } +} + +/// The pages of the table, where they are. +#[derive(Debug)] +enum Store { + /// In memory, one after the other. + Memory(Vec), + /// In a scratch file. + Disk(DiskPages), +} + +impl Store { + /// Takes back the memory this table lent to the pages it doubled into, + /// `doubled`, which are given up: the doubling did not finish. Their + /// scratch file goes back to `scratch`. A table in memory lent nothing + /// and doubled into no file. + fn take_back_cache(&mut self, doubled: Store, scratch: &mut Scratch) { + if let (Store::Disk(pages), Store::Disk(doubled)) = (self, doubled) { + pages.cache = doubled.cache; + scratch.take_back(doubled.file); + } + } + + /// Gives the pages up: their scratch file goes back to `scratch`, if + /// they are in one. + fn give_back(self, scratch: &mut Scratch) { + if let Store::Disk(pages) = self { + scratch.take_back(pages.file); + } + } + + /// How many pages were read from a scratch file and written to it for + /// these pages: none for pages in memory. + fn transfers(&self) -> u64 { + match self { + Store::Memory(_) => 0, + Store::Disk(disk) => disk.transfers, + } + } + + /// How many pages there are: none, or a power of two. + fn pages(&self) -> u64 { + match self { + Store::Memory(pages) => (pages.len() / PAGE_SIZE) as u64, + Store::Disk(disk) => disk.pages, + } + } + + /// The page `number`, which there is, to look at. + fn page(&mut self, number: u64) -> io::Result<&[u8]> { + match self { + Store::Memory(pages) => { + let at = usize::try_from(number).map_err(|_| damaged())? * PAGE_SIZE; + pages.get(at..at + PAGE_SIZE).ok_or_else(damaged) + } + Store::Disk(disk) => { + let place = disk.load(number)?; + Ok(&disk.cache[place * PAGE_SIZE..(place + 1) * PAGE_SIZE]) + } + } + } + + /// The page `number`, which there is, to change. + fn page_mut(&mut self, number: u64) -> io::Result<&mut [u8]> { + match self { + Store::Memory(pages) => { + let at = usize::try_from(number).map_err(|_| damaged())? * PAGE_SIZE; + pages.get_mut(at..at + PAGE_SIZE).ok_or_else(damaged) + } + Store::Disk(disk) => { + let place = disk.load(number)?; + disk.changed[place] = true; + Ok(&mut disk.cache[place * PAGE_SIZE..(place + 1) * PAGE_SIZE]) + } + } + } + + /// Puts the group `slot` into the page `home`, or into the next page + /// behind it that has room. + fn place(&mut self, home: u64, slot: &[u8]) -> io::Result<()> { + let pages = self.pages(); + let mut number = home; + for _ in 0..pages { + let page = self.page(number)?; + let (count, overflowed) = Page::state(page)?; + if count < SLOTS { + Page::push(self.page_mut(number)?, count, slot); + return Ok(()); + } + if !overflowed { + Page::set_overflowed(self.page_mut(number)?); + } + number = (number + 1) % pages; + } + // A table doubles long before every page is full. + Err(damaged()) + } +} + +/// The first names of the groups, one behind the other, which an error +/// about another name of a group names. +#[derive(Debug)] +enum Names { + /// In memory. + Memory(Vec), + /// In a scratch file, but for the last ones, which are gathered in + /// memory and written out together. + Disk { + file: ScratchFile, + /// How many bytes the file holds. + written: u64, + /// The names that are still to be written. + pending: Vec, + }, +} + +impl Names { + /// How many bytes of names memory holds. + fn in_memory(&self) -> usize { + match self { + Names::Memory(names) => names.len(), + Names::Disk { pending, .. } => pending.len(), + } + } + + /// Adds `name` and returns where it is. + fn push(&mut self, name: &Name) -> io::Result { + let bytes = name.as_str().as_bytes(); + // A name is at most Name::MAX_LEN bytes long. + let len = u16::try_from(bytes.len()).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + match self { + Names::Memory(names) => { + let offset = names.len() as u64; + names.extend_from_slice(bytes); + Ok(NameAt { offset, len }) + } + Names::Disk { file, written, pending } => { + if pending.len() + bytes.len() > NAMES_BUFFER { + file.write_all_at(pending, *written)?; + *written += pending.len() as u64; + pending.clear(); + } + let offset = *written + pending.len() as u64; + pending.extend_from_slice(bytes); + Ok(NameAt { offset, len }) + } + } + } + + /// The name at `at`. + fn get(&self, at: NameAt) -> io::Result { + let len = usize::from(at.len); + let mut bytes = vec![0; len]; + match self { + Names::Memory(names) => { + let start = usize::try_from(at.offset).map_err(|_| damaged())?; + bytes.copy_from_slice( + names + .get(start..) + .and_then(|rest| rest.get(..len)) + .ok_or_else(damaged)?, + ); + } + Names::Disk { file, written, pending } => match at.offset.checked_sub(*written) { + Some(start) => { + let start = usize::try_from(start).map_err(|_| damaged())?; + bytes.copy_from_slice( + pending + .get(start..) + .and_then(|rest| rest.get(..len)) + .ok_or_else(damaged)?, + ); + } + None => file.read_exact_at(&mut bytes, at.offset)?, + }, + } + let name = String::from_utf8(bytes).map_err(|_| damaged())?; + // The name of the root is a name as well, the one without bytes. + if name.is_empty() { + return Ok(NameBuf::default()); + } + NameBuf::new(name).map_err(|_| damaged()) + } +} + +/// What the table is doing to make room. +#[derive(Debug)] +enum Growth { + /// Nothing. + None, + /// Its pages and its names, which were in memory, are written to + /// scratch files as they are: so many bytes of the pages, and then of + /// the names, are there. + Moving { + pages: ScratchFile, + names: ScratchFile, + written: usize, + }, + /// The groups of the pages it had are placed in twice the pages: those + /// of so many of the old pages are. + Doubling { old: Store, placed: u64 }, +} + +/// What it comes to that a name of a group was noted. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Noted { + /// It is the first name of its group. + First, + /// It is another name of a group, of the same file as the first one. + Again, + /// It is another name of a group, and it does not show the file the + /// first name of the group showed, which is this one. + Differs(NameBuf), +} + +impl Noted { + /// Fails for the name `name`, which was noted, if it does not show the + /// file the first name of its group showed. Two names of one inode + /// that differ are a hard-link mismatch that names both, also where + /// `name` was noted before: a group keeps its first name and no other. + /// The first name itself, noted again, names a file that changed. + pub(crate) fn check(self, name: &Name) -> Result<(), Error> { + match self { + Noted::First | Noted::Again => Ok(()), + Noted::Differs(first) if first == *name => Err(Failure::Changed.into_error(name)), + Noted::Differs(first) => { + let message = format!( + "{}: is a name of the inode of '{}', but does not show the same file", + Subject(name), + first.as_str().escape_debug() + ); + Err(Error::new(ErrorKind::Tree(TreeProblem::HardlinkMismatch), message) + .named(name.as_str()) + .linked(first)) + } + } + } +} + +/// How large a table gets in memory and how much of it memory holds once +/// it is on disk. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Limits { + /// How many bytes the pages and the names take in memory at most, + /// while a table doubles as well. + pub(crate) memory: usize, + /// How many pages the table starts with, a power of two. + pub(crate) first_pages: u64, + /// How many pages of a table on disk memory holds. + pub(crate) cached_pages: usize, +} + +/// The table of the groups of hard links, see the documentation of this +/// module. +#[derive(Debug)] +pub(crate) struct HardlinkTable { + store: Store, + names: Names, + /// How many groups the table holds. + groups: u64, + /// How many groups have a token. + tokens: u64, + /// How many pages were read from the scratch file of the pages and + /// written to it to hand out tokens. + token_transfers: u64, + growth: Growth, + /// What the pages of a table on disk are read into when it doubles. + chunk: Vec, + /// What hashes the keys. Its keys are random, so that a tree cannot + /// pick inode numbers that all go to one page. + hasher: RandomState, + limits: Limits, +} + +impl HardlinkTable { + /// A table without groups, which takes no room yet. + pub(crate) fn new() -> HardlinkTable { + HardlinkTable::with_limits(Limits { + memory: MEMORY_LIMIT, + first_pages: FIRST_PAGES, + cached_pages: CACHED_PAGES, + }) + } + + /// A table that takes as much memory as `limits` says. + pub(crate) fn with_limits(limits: Limits) -> HardlinkTable { + HardlinkTable { + store: Store::Memory(Vec::new()), + names: Names::Memory(Vec::new()), + groups: 0, + tokens: 0, + token_transfers: 0, + growth: Growth::None, + chunk: Vec::new(), + hasher: RandomState::new(), + limits, + } + } + + /// The page the key `key` belongs into, in a table of `pages` pages + /// whose keys `hasher` hashes. + fn home(hasher: &RandomState, key: &[u8], pages: u64) -> u64 { + hasher.hash_one(key) % pages + } + + /// Whether one more group takes the table over three quarters of its + /// room. + fn is_full(&self) -> bool { + (self.groups + 1) * 4 > self.store.pages() * SLOTS as u64 * 3 + } + + /// Does a part of what is to do before the table takes another group, + /// and returns whether it is done: the table has room, and what does + /// not fit into memory is on disk. `budget` is about how many bytes are + /// read and written for it now. A doubling of a table on disk that + /// begins writes out the pages memory holds of it first, whatever the + /// budget, which are a megabyte at most. The scratch files it takes + /// come from `scratch`, and those it is done with go back to it. + /// + /// A caller that works in steps calls this until it returns true + /// before it notes a name. [`HardlinkTable::note`] does all that is + /// left of it at once. + /// + /// Where a scratch file cannot be made, read or written this fails, and + /// the table is as it was. That holds for a doubling that fails half + /// way, as on a disk that is full: it keeps the pages it had, and the + /// next call begins it again. + pub(crate) fn make_room(&mut self, scratch: &mut Scratch, budget: u64) -> io::Result { + // A table without groups takes no room before the first one comes, + // which a tree without hard links never has. + if self.store.pages() == 0 { + return Ok(true); + } + self.grow(scratch, budget) + } + + /// Does a part of what [`HardlinkTable::make_room`] began and did not + /// finish, and returns whether it is done. `budget` is about how many + /// bytes are read and written for it now. A scratch file it is done + /// with goes back to `scratch`. + /// + /// Unlike [`HardlinkTable::make_room`] this begins nothing. It is what + /// is left to do once no more names come and the groups get their + /// tokens. [`HardlinkTable::token`] does all that is left of it at + /// once. + pub(crate) fn settle(&mut self, scratch: &mut Scratch, budget: u64) -> io::Result { + let mut left = budget; + self.advance(scratch, &mut left) + } + + /// What [`HardlinkTable::make_room`] does: one thing after the other + /// begins and is finished, until the table has room or the budget is + /// used up. + fn grow(&mut self, scratch: &mut Scratch, budget: u64) -> io::Result { + let mut left = budget; + loop { + if !self.advance(scratch, &mut left)? { + return Ok(false); + } + if !self.begin(scratch)? { + return Ok(true); + } + } + } + + /// Begins what is to do before the table takes another group, and + /// returns whether there was something: a table that does not fit into + /// memory any more moves to disk, and one that is full doubles. + fn begin(&mut self, scratch: &mut Scratch) -> io::Result { + if self.store.pages() == 0 { + // The first group: the first pages. + let size = usize::try_from(self.limits.first_pages).map_err(|_| damaged())? * PAGE_SIZE; + self.store = Store::Memory(vec![0; size]); + } + let full = self.is_full(); + // In memory there has to be room for one more name, and while the + // table doubles for the pages it has and for twice as many new + // ones. + let in_pages = match &self.store { + Store::Memory(pages) => pages.len(), + Store::Disk(_) => 0, + }; + let needed = self.names.in_memory() + Name::MAX_LEN + if full { in_pages * 3 } else { in_pages }; + if in_pages > 0 && needed > self.limits.memory { + let pages = scratch.file()?; + let names = match scratch.file() { + Ok(names) => names, + Err(e) => { + // The first file goes back: the table took neither. + scratch.take_back(pages); + return Err(e); + } + }; + self.growth = Growth::Moving { + pages, + names, + written: 0, + }; + } else if full { + let doubled = match &mut self.store { + Store::Memory(old) => Store::Memory(vec![0; old.len() * 2]), + Store::Disk(old) => { + // The pages are read from the file from here on, and + // what held some of them holds those of the new table + // while it doubles. + let file = scratch.file()?; + let sized = file.set_len(DiskPages::offset(old.pages * 2)); + match sized.and_then(|()| old.lend_cache()) { + Ok(cache) => Store::Disk(DiskPages::with_cache(file, old.pages * 2, cache)), + Err(e) => { + // The file goes back, and the table is as it + // was: it doubles into none. + scratch.take_back(file); + return Err(e); + } + } + } + }; + let old = mem::replace(&mut self.store, doubled); + self.growth = Growth::Doubling { old, placed: 0 }; + } else { + return Ok(false); + } + Ok(true) + } + + /// Goes on with what began until it is finished or `left` is used up, + /// and returns whether it is finished. `left` is how many bytes may + /// still be read and written. The scratch file of the pages a doubling + /// is done with goes back to `scratch`, and so do the files of a + /// doubling or of a move to disk that fails. + fn advance(&mut self, scratch: &mut Scratch, left: &mut u64) -> io::Result { + loop { + match mem::replace(&mut self.growth, Growth::None) { + Growth::None => return Ok(true), + Growth::Moving { pages, names, written } => { + let (Store::Memory(table), Names::Memory(first)) = (&self.store, &self.names) else { + return Err(damaged()); + }; + if *left == 0 { + self.growth = Growth::Moving { pages, names, written }; + return Ok(false); + } + // A page at least, as for a table that doubles. + let most = usize::try_from(*left).unwrap_or(usize::MAX).max(PAGE_SIZE); + let (moved, done) = match written.checked_sub(table.len()) { + None => { + let end = table.len().min(written.saturating_add(most)); + (pages.write_all_at(&table[written..end], written as u64), end) + } + Some(at) => { + let end = first.len().min(at.saturating_add(most)); + (names.write_all_at(&first[at..end], at as u64), table.len() + end) + } + }; + if let Err(e) = moved { + // The move is given up, and both of its files go + // back: the table is in memory as it was. + scratch.take_back(names); + scratch.take_back(pages); + return Err(e); + } + *left = left.saturating_sub((done - written) as u64); + if done < table.len() + first.len() { + self.growth = Growth::Moving { + pages, + names, + written: done, + }; + continue; + } + let count = (table.len() / PAGE_SIZE) as u64; + let named = first.len() as u64; + self.store = Store::Disk(DiskPages::new(pages, count, self.limits.cached_pages)); + self.names = Names::Disk { + file: names, + written: named, + pending: Vec::with_capacity(NAMES_BUFFER), + }; + } + Growth::Doubling { old, placed } => { + if *left == 0 { + self.growth = Growth::Doubling { old, placed }; + return Ok(false); + } + let now = (*left / PAGE_SIZE as u64) + .clamp(1, CHUNK_PAGES as u64) + .min(old.pages() - placed); + if let Err(e) = self.place_again(&old, placed, now) { + // Some of the groups are in the new pages, and the + // old ones have them all. So the table goes back to + // those, with the memory they lent the new ones, + // whose scratch file goes back. + let doubled = mem::replace(&mut self.store, old); + self.store.take_back_cache(doubled, scratch); + return Err(e); + } + *left = left.saturating_sub(now * PAGE_SIZE as u64); + // Once every page is placed the old ones are given up: + // their scratch file goes back, which empties it, and + // the next doubling is handed it again, see the + // documentation of this module. + if placed + now < old.pages() { + self.growth = Growth::Doubling { + old, + placed: placed + now, + }; + } else { + old.give_back(scratch); + } + } + } + } + } + + /// Places the groups of the pages `first` to `first + count` of `old` + /// in the table, which has twice the pages of `old`. + fn place_again(&mut self, old: &Store, first: u64, count: u64) -> io::Result<()> { + // At most CHUNK_PAGES pages are placed at a time. + let size = usize::try_from(count).map_err(|_| damaged())? * PAGE_SIZE; + let chunk = match old { + Store::Memory(pages) => { + let at = usize::try_from(first).map_err(|_| damaged())? * PAGE_SIZE; + pages.get(at..at + size).ok_or_else(damaged)? + } + Store::Disk(disk) => { + self.chunk.resize(CHUNK_PAGES * PAGE_SIZE, 0); + disk.file + .read_exact_at(&mut self.chunk[..size], DiskPages::offset(first))?; + &self.chunk[..size] + } + }; + let pages = self.store.pages(); + for page in chunk.chunks_exact(PAGE_SIZE) { + for index in 0..Page::count(page)? { + let slot = Page::slot(page, index); + let home = HardlinkTable::home(&self.hasher, &slot[..KEY_SIZE], pages); + self.store.place(home, slot)?; + } + } + Ok(()) + } + + /// Where the group of the key `key` is: its page and its slot there. + fn find(&mut self, key: &[u8; KEY_SIZE]) -> io::Result> { + let pages = self.store.pages(); + if pages == 0 { + return Ok(None); + } + let mut number = HardlinkTable::home(&self.hasher, key, pages); + for _ in 0..pages { + let page = self.store.page(number)?; + let (count, overflowed) = Page::state(page)?; + if let Some(index) = (0..count).find(|&index| Page::slot(page, index)[..KEY_SIZE] == key[..]) { + return Ok(Some((number, index))); + } + if !overflowed { + return Ok(None); + } + number = (number + 1) % pages; + } + Ok(None) + } + + /// Notes that the file `name` is a name of the group `key`, a file + /// that is `likeness`. The first name of a group makes the group. Every + /// other one is held against the first: it is a name of the same + /// file, or it is not, and then the first name comes back for the + /// error. + pub(crate) fn note( + &mut self, + scratch: &mut Scratch, + key: &GroupKey, + name: &Name, + likeness: &Likeness, + ) -> io::Result { + // Every group is where a lookup finds it once what began is + // finished. + while !self.settle(scratch, u64::MAX)? {} + let key = key.encode(); + if let Some((number, index)) = self.find(&key)? { + let group = Group::decode(Page::slot(self.store.page(number)?, index))?; + if group.likeness.same_file(likeness) { + return Ok(Noted::Again); + } + return Ok(Noted::Differs(self.names.get(group.name)?)); + } + while !self.grow(scratch, u64::MAX)? {} + let group = Group { + key, + token: NO_TOKEN, + name: self.names.push(name)?, + likeness: *likeness, + }; + let home = HardlinkTable::home(&self.hasher, &key, self.store.pages()); + self.store.place(home, &group.encode())?; + self.groups += 1; + Ok(Noted::First) + } + + /// The `inodeToken` of the group `key`, which has to be there. A group + /// gets its token when it is first asked for, the next number from 1 + /// on. So asked in the order of the manifest, the groups are numbered + /// in the order the specification wants. + /// + /// A table on disk reads the page of the group from its scratch file + /// where memory does not hold it, and writes out the page that makes + /// room for it if that one changed. [`HardlinkTable::token_cost`] says + /// what that comes to. What is left to finish of what made room is + /// finished first, with `scratch`, see [`HardlinkTable::settle`]. + pub(crate) fn token(&mut self, scratch: &mut Scratch, key: &GroupKey) -> io::Result { + while !self.settle(scratch, u64::MAX)? {} + let before = self.store.transfers(); + let token = self.token_of(key); + self.token_transfers += self.store.transfers() - before; + token + } + + /// What the tokens that were handed out so far cost, in bytes of a + /// budget: [`PAGE_COST`] for every page that was read from the scratch + /// file of the table or written to it for them. A token that the pages + /// in memory answer costs nothing, and so no token of a table in memory + /// does. + pub(crate) fn token_cost(&self) -> u64 { + self.token_transfers * PAGE_COST + } + + /// What [`HardlinkTable::token`] does, once nothing is left to finish. + fn token_of(&mut self, key: &GroupKey) -> io::Result { + let (number, index) = self.find(&key.encode())?.ok_or_else(damaged)?; + let at = HEADER_SIZE + index * SLOT_SIZE + TOKEN_AT; + let page = self.store.page(number)?; + let token = u64::from_le_bytes(*page[at..].first_chunk().ok_or_else(damaged)?); + if let Some(token) = NonZeroU64::new(token) { + // No group has a token that was not handed out. + return if token.get() <= self.tokens { + Ok(token) + } else { + Err(damaged()) + }; + } + let next = NonZeroU64::new(self.tokens + 1).ok_or_else(damaged)?; + self.store.page_mut(number)?[at..at + size_of::()].copy_from_slice(&next.get().to_le_bytes()); + self.tokens = next.get(); + Ok(next) + } + + /// Gives the table up, with every scratch file it has: those of its + /// pages and of its names, and those of a move to disk or of a doubling + /// that is not finished. They go back to `scratch`, which empties them. + /// Whoever has the table calls this where the manifest is written or + /// given up. A table that is dropped leaves its files as they are. + pub(crate) fn give_back(self, scratch: &mut Scratch) { + match self.growth { + Growth::None => {} + Growth::Moving { pages, names, .. } => { + scratch.take_back(names); + scratch.take_back(pages); + } + Growth::Doubling { old, .. } => old.give_back(scratch), + } + self.store.give_back(scratch); + if let Names::Disk { file, .. } = self.names { + scratch.take_back(file); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{name, OpenFile, TempDir}; + use crate::tree::InodeId; + use crate::InodeType; + use std::collections::{HashMap, HashSet}; + use std::env; + use std::fs; + use std::io::Write; + use std::path::{Path, PathBuf}; + use std::process::Command; + use std::time::Instant; + + /// Scratch space in a directory of its own. + fn scratch(name: &str) -> (TempDir, Scratch) { + let tmp = TempDir::new(name); + let directory = ScratchFile::open_directory(&tmp.0).unwrap(); + (tmp, Scratch::beside(directory.into())) + } + + /// A table that leaves memory and doubles after a few groups, and that + /// holds few of its pages in memory then. + fn small() -> HardlinkTable { + HardlinkTable::with_limits(Limits { + memory: 8 * PAGE_SIZE, + first_pages: 1, + cached_pages: 3, + }) + } + + /// The key of the inode `inode` of a file system a test makes up. + fn walked(inode: u64) -> GroupKey { + GroupKey::Walked(Identity { + mount: MountId::Unique(7), + device: DeviceNumber { major: 8, minor: 1 }, + inode, + subvolume: None, + }) + } + + /// The status of a regular file with two names. + fn status() -> Status { + let time = Timestamp { + seconds: 1_700_000_000, + nanoseconds: 123_456_789, + }; + Status { + identity: Identity { + mount: MountId::Unique(7), + device: DeviceNumber { major: 8, minor: 1 }, + inode: 2, + subvolume: None, + }, + file_type: FileType::RegularFile, + mode: Mode::from_st_mode(0o644), + nlink: 2, + uid: 3, + gid: 4, + size: 5, + mtime: time, + ctime: time, + btime: Some(time), + rdev: DeviceNumber { major: 0, minor: 0 }, + } + } + + /// What a regular file of the size `size` with the data `data` has to + /// be alike in with its other names. + fn likeness(size: u64, data: &[u8]) -> Likeness { + let mut status = status(); + status.size = size; + let mut object = FileObject::new(name("file")); + object.set_size(Some(size)); + Likeness::walked(Seen::of(&status), Some(Sha256::digest(data)), &object) + } + + /// A key is in the table as it comes back from it, and no two keys + /// are there the same way. Bytes that are no key are refused. + #[test] + fn keys() { + let identity = |mount, inode, subvolume| Identity { + mount, + device: DeviceNumber { major: 8, minor: 1 }, + inode, + subvolume, + }; + let keys = [ + GroupKey::Walked(identity(MountId::Unique(5), 5, None)), + GroupKey::Walked(identity(MountId::Reusable(5), 5, None)), + GroupKey::Walked(identity(MountId::Unique(5), 5, Some(0))), + GroupKey::Walked(identity(MountId::Unique(5), 5, Some(5))), + GroupKey::Walked(identity(MountId::Unique(5), 6, None)), + GroupKey::Walked(identity(MountId::Unique(6), 5, None)), + GroupKey::Walked(identity(MountId::Unique(u64::MAX), u64::MAX, Some(u64::MAX))), + GroupKey::Given(NonZeroU64::new(5).unwrap()), + GroupKey::Given(NonZeroU64::MAX), + ]; + let mut device = identity(MountId::Unique(5), 5, None); + device.device.minor = 2; + let encoded: Vec<_> = keys + .iter() + .chain([&GroupKey::Walked(device)]) + .map(GroupKey::encode) + .collect(); + for (key, encoded) in keys.iter().zip(&encoded) { + assert_eq!(GroupKey::decode(encoded).unwrap(), *key); + assert_ne!(encoded[0], 0); + } + for (index, one) in encoded.iter().enumerate() { + assert!(!encoded[..index].contains(one), "{:?}", one); + } + let mut no_kind = encoded[0]; + no_kind[0] = 0; + let mut unknown_kind = encoded[0]; + unknown_kind[0] = 9; + let mut subvolume = encoded[0]; + subvolume[1] = 2; + let mut no_token = encoded[7]; + no_token[8..16].fill(0); + for bytes in [no_kind, unknown_kind, subvolume, no_token] { + assert_eq!(GroupKey::decode(&bytes).unwrap_err().kind(), io::ErrorKind::InvalidData); + } + } + + /// What a file has to be alike in with its other names is in the table + /// as it comes back from it. Bytes that are none are refused. + #[test] + fn likenesses() { + let mut other = status(); + other.btime = None; + other.file_type = FileType::Symlink; + other.mtime.seconds = -5; + other.rdev = DeviceNumber { + major: u32::MAX, + minor: 7, + }; + other.mode = Mode::from_st_mode(0o7777); + let object = FileObject::new(name("a")); + let all = [ + likeness(5, b"hello"), + Likeness::walked(Seen::of(&other), None, &object), + Likeness::walked(Seen::of(&status()), None, &object), + Likeness::given(&object), + ]; + for likeness in &all { + let mut bytes = [0xff; LIKENESS_SIZE]; + likeness.encode(&mut bytes); + assert_eq!(Likeness::decode(&bytes).unwrap(), *likeness); + } + // Marks nobody has, a type of file there is none of, a mode with + // more than its twelve bits, and a birth time that is not there + // and is not zero. + let mut bytes = [0; LIKENESS_SIZE]; + all[0].encode(&mut bytes); + let mut without_btime = [0; LIKENESS_SIZE]; + all[1].encode(&mut without_btime); + let changed = [ + (bytes, 0, 0x80), + (bytes, 0, 0x04), + (bytes, 1, 0x02), + (bytes, 2, 8), + (bytes, 4, 0x10), + ]; + for (mut bytes, at, bits) in + changed + .into_iter() + .chain([(without_btime, LIKENESS_SIZE - 2 * Sha256::SIZE - 1, 1)]) + { + bytes[at] |= bits; + assert_eq!( + Likeness::decode(&bytes).unwrap_err().kind(), + io::ErrorKind::InvalidData, + "{}", + at + ); + } + // What statx() says of a file alone comes back the same way. + for status in [status(), other] { + let seen = Seen::of(&status); + let mut bytes = [0xff; SEEN_SIZE]; + seen.encode(&mut bytes); + assert_eq!(Seen::decode(&bytes).unwrap(), seen); + } + } + + /// The names of one inode show the same file if statx() says the same + /// of it, but for the change time and for a birth time only one of + /// them has, if the fields its file objects have to agree in are the + /// same, and if its data is, where both have a hash of it. + #[test] + fn what_shows_the_same_file() { + let before = status(); + let object = FileObject::new(name("file")); + let hash = Some(Sha256::digest(b"data")); + let first = Likeness::walked(Seen::of(&before), hash, &object); + assert!(first.same_file(&first)); + type Change = fn(&mut Status); + let changes: [(&str, Change, bool); 13] = [ + ("type", |s| s.file_type = FileType::Fifo, false), + ("mode", |s| s.mode = Mode::from_st_mode(0o600), false), + ("uid", |s| s.uid ^= 1, false), + ("gid", |s| s.gid ^= 1, false), + ("rdev", |s| s.rdev.minor ^= 1, false), + ("size", |s| s.size ^= 1, false), + ("mtime", |s| s.mtime.nanoseconds ^= 1, false), + ("mtime seconds", |s| s.mtime.seconds ^= 1, false), + ( + "btime", + |s| s.btime = Some(s.mtime).map(|mut t| (t.seconds ^= 1, t).1), + false, + ), + ("no btime", |s| s.btime = None, true), + ("ctime", |s| s.ctime.seconds ^= 1, true), + ("nlink", |s| s.nlink += 1, true), + ("identity", |s| s.identity.inode ^= 1, true), + ]; + for (what, change, same) in changes { + let mut later = before; + change(&mut later); + let later = Likeness::walked(Seen::of(&later), hash, &object); + assert_eq!(first.same_file(&later), same, "{}", what); + assert_eq!(later.same_file(&first), same, "{}", what); + } + let other_data = Likeness::walked(Seen::of(&before), Some(Sha256::digest(b"other")), &object); + let no_data = Likeness::walked(Seen::of(&before), None, &object); + let mut recorded = object.clone(); + recorded.inode_mut().set_uid(Some(3)); + let other_fields = Likeness::walked(Seen::of(&before), hash, &recorded); + let given = Likeness::given(&object); + assert!(first.same_file(&no_data) && no_data.same_file(&first)); + for other in [other_data, other_fields, given] { + assert!(!first.same_file(&other) && !other.same_file(&first), "{:?}", other); + } + assert!(given.same_file(&Likeness::given(&object))); + assert!(!given.same_file(&Likeness::given(&recorded))); + } + + /// The fields that have to be the same on all file objects of one + /// `inodeToken` are those the specification names, as a record has + /// them. Nothing else of an object counts. + #[test] + fn fields_that_have_to_agree() { + let mut base = FileObject::new(name("first")); + base.inode_mut().set_mode(Some(Mode::from_st_mode(0o644))); + base.set_size(Some(5)); + let fields = Likeness::fields(&base); + type Change = fn(&mut FileObject); + let counted: [(&str, Change); 20] = [ + ("type", |o| o.set_inode_type(InodeType::Fifo)), + ("mode", |o| o.inode_mut().set_mode(Some(Mode::from_st_mode(0o600)))), + ("no mode", |o| o.inode_mut().set_mode(None)), + ("uid", |o| o.inode_mut().set_uid(Some(0))), + ("gid", |o| o.inode_mut().set_gid(Some(0))), + ("userName", |o| o.inode_mut().set_user_name(Some("root".into()))), + ("groupName", |o| o.inode_mut().set_group_name(Some("root".into()))), + ("mTimeNSec", |o| o.inode_mut().set_mtime_nsec(Some(0))), + ("size", |o| o.set_size(Some(6))), + ("no size", |o| o.set_size(None)), + ("sha256", |o| o.set_sha256(Some(Sha256::digest(b"hello")))), + ("major", |o| o.set_major(Some(0))), + ("minor", |o| o.set_minor(Some(0))), + ("an attribute", |o| drop(o.inode_mut().insert_user_xattr("a", "b"))), + ("flagAppendOnly", |o| o.inode_mut().set_flag_append_only(Some(true))), + ("flagImmutable", |o| o.inode_mut().set_flag_immutable(Some(true))), + ("flagNoAtime", |o| o.inode_mut().set_flag_no_atime(Some(true))), + ("flagNoCow", |o| o.inode_mut().set_flag_no_cow(Some(true))), + ("flagNoDump", |o| o.inode_mut().set_flag_no_dump(Some(true))), + ("uid for gid", |o| { + o.inode_mut().set_uid(Some(4)); + o.inode_mut().set_gid(None); + }), + ]; + let mut seen = vec![fields]; + for (what, change) in counted { + let mut changed = base.clone(); + change(&mut changed); + let fields = Likeness::fields(&changed); + assert!(!seen.contains(&fields), "{}", what); + seen.push(fields); + } + // Where an attribute ends and its value starts counts, and so does + // which attribute has which value. + let attributes = |pairs: &[(&str, &str)]| { + let mut object = base.clone(); + for (name, value) in pairs { + object.inode_mut().insert_user_xattr(*name, *value); + } + Likeness::fields(&object) + }; + let different = [ + attributes(&[("ab", "c")]), + attributes(&[("a", "bc")]), + attributes(&[("a", "b"), ("c", "")]), + attributes(&[("a", ""), ("c", "b")]), + attributes(&[("a", ""), ("b", "c")]), + ]; + for (index, one) in different.iter().enumerate() { + assert!(!different[..index].contains(one) && !seen.contains(one), "{}", index); + } + let ignored: [(&str, Change); 10] = [ + ("name", |o| o.set_name(name("second"))), + ("inodeToken", |o| o.set_inode_token(NonZeroU64::new(7))), + ("validity", |o| o.validity_mut().since_usec = 1), + ("readOnly", |o| o.inode_mut().set_read_only(Some(false))), + ("flagHidden", |o| o.set_flag_hidden(Some(true))), + ("a cleared flag", |o| o.inode_mut().set_flag_immutable(Some(false))), + ("no attributes", |o| { + o.inode_mut().set_user_xattrs(Some(Default::default())) + }), + ("a filled-in hash", |o| { + o.set_sha256(Some(Sha256::EMPTY)); + let mut marks = o.marks(); + marks.insert(Field::Sha256); + o.set_marks(marks); + }), + ("contents", |o| o.put_contents(vec![crate::ContentsObject::default()])), + ("gptLabel", |o| o.set_gpt(Some(Default::default()))), + ]; + for (what, change) in ignored { + let mut changed = base.clone(); + change(&mut changed); + assert_eq!(Likeness::fields(&changed), fields, "{}", what); + } + // A size a reader filled in is not in the record. + let mut filled = base.clone(); + let mut marks = filled.marks(); + marks.insert(Field::Size); + filled.set_marks(marks); + let mut without = base.clone(); + without.set_size(None); + assert_eq!(Likeness::fields(&filled), Likeness::fields(&without)); + } + + /// The first name of a group makes the group. Another name of the same + /// file is one of the group, and one of another file gets the first + /// name back. That holds for groups in memory and for groups on disk, + /// while the table doubles many times over, with only a few of its + /// pages in memory. Groups of files of a tree and groups of file + /// objects of a caller are apart. + #[test] + fn groups() { + let (tmp, mut scratch) = scratch("hardlink-groups"); + let mut table = small(); + assert_eq!(table.store.pages(), 0); + let count = 6000; + let key = |index: u64| match index % 3 { + 0 => GroupKey::Given(NonZeroU64::new(index + 1).unwrap()), + _ => walked(index + 1), + }; + let first = |index: u64| { + name(&format!( + "dir/{}/first-{}", + "x".repeat((index % 200) as usize + 1), + index + )) + }; + let mut model = HashMap::new(); + for index in 0..count { + let likeness = likeness(index, &index.to_le_bytes()); + let noted = table.note(&mut scratch, &key(index), &first(index), &likeness).unwrap(); + assert_eq!(noted, Noted::First, "{}", index); + model.insert(key(index), (first(index), likeness)); + // Every group so far is found as it went in, now and then. + if index % 500 == 0 || index + 1 == count { + for (key, (first, likeness)) in &model { + let again = table.note(&mut scratch, key, &name("another"), likeness).unwrap(); + assert_eq!(again, Noted::Again); + let other = self::likeness(u64::MAX, b"other"); + let differs = table.note(&mut scratch, key, &name("another"), &other).unwrap(); + assert_eq!(differs, Noted::Differs(first.clone())); + } + } + } + assert_eq!(table.groups, count); + let Store::Disk(disk) = &table.store else { + panic!("{:?}", table.store); + }; + assert!(disk.pages.is_power_of_two() && disk.pages * SLOTS as u64 * 3 >= count * 4); + assert!(matches!(table.names, Names::Disk { .. })); + // The same token for a number and for an inode number are two + // groups. + assert!(model.contains_key(&walked(2)) && model.contains_key(&GroupKey::Given(NonZeroU64::new(1).unwrap()))); + // Nothing has a name in the directory of the scratch files. + assert_eq!(fs::read_dir(&tmp.0).unwrap().count(), 0); + } + + /// A table stays in memory until its pages and the first names of its + /// groups, with the pages a doubling takes for a while, would take + /// more than their limit. Then it moves to scratch files as it is, and + /// only then is a scratch file made. + #[test] + fn moves_to_disk_once() { + let (_tmp, mut scratch) = scratch("hardlink-move"); + let mut table = HardlinkTable::new(); + let likeness = likeness(1, b"1"); + // A table of half the limit cannot double in memory any more, and + // it is full at three quarters of its slots. + let in_memory = (MEMORY_LIMIT / 2 / PAGE_SIZE * SLOTS * 3 / 4) as u64; + for index in 0..in_memory { + let noted = table.note(&mut scratch, &walked(index), &name("n"), &likeness).unwrap(); + assert_eq!(noted, Noted::First); + assert!(matches!(table.store, Store::Memory(_)), "{}", index); + } + let Store::Memory(pages) = &table.store else { + unreachable!(); + }; + assert_eq!(pages.len(), MEMORY_LIMIT / 2); + table + .note(&mut scratch, &walked(in_memory), &name("n"), &likeness) + .unwrap(); + let Store::Disk(disk) = &table.store else { + panic!("{:?}", table.growth); + }; + assert_eq!(disk.pages as usize * PAGE_SIZE, MEMORY_LIMIT); + assert_eq!(disk.cache.len(), CACHED_PAGES * PAGE_SIZE); + // Long names move a table earlier. + let mut table = HardlinkTable::new(); + let long = name(&"n".repeat(Name::MAX_LEN)); + let mut noted = 0; + while matches!(table.store, Store::Memory(_)) { + table.note(&mut scratch, &walked(noted), &long, &likeness).unwrap(); + noted += 1; + } + assert!(noted < in_memory / 4, "{}", noted); + assert!((noted as usize) * Name::MAX_LEN <= MEMORY_LIMIT); + let other = self::likeness(2, b"2"); + let differs = table.note(&mut scratch, &walked(0), &name("m"), &other).unwrap(); + assert_eq!(differs, Noted::Differs(long)); + } + + /// The first names come back from memory and from disk, short and as + /// long as a name gets, also those that were not written out yet. + #[test] + fn first_names() { + let (_tmp, mut scratch) = scratch("hardlink-names"); + let mut table = small(); + let likeness = likeness(1, b"1"); + let other = self::likeness(2, b"2"); + let first = |index: u64| match index % 7 { + 0 => name(&format!("{}{}", "long/".repeat(818), "names")), + 1 => name("a"), + 2 => NameBuf::default(), + _ => name(&format!("{}/\u{fc}-{}", "d".repeat((index % 97) as usize + 1), index)), + }; + let count = 3000; + for index in 0..count { + table + .note(&mut scratch, &walked(index), &first(index), &likeness) + .unwrap(); + for earlier in [0, index / 2, index] { + let differs = table.note(&mut scratch, &walked(earlier), &name("x"), &other).unwrap(); + assert_eq!(differs, Noted::Differs(first(earlier)), "{} {}", index, earlier); + } + } + let Names::Disk { written, pending, .. } = &table.names else { + panic!("{:?}", table.names); + }; + assert!(*written > NAMES_BUFFER as u64 && pending.len() <= NAMES_BUFFER); + } + + /// The groups get their tokens in the order they are asked for them, + /// from 1 on, and keep them, while the table doubles as well. A group + /// that is not in the table has none. + #[test] + fn tokens() { + let (_tmp, mut scratch) = scratch("hardlink-tokens"); + let mut table = small(); + let likeness = likeness(1, b"1"); + let count = 2000; + for index in 0..count { + table.note(&mut scratch, &walked(index), &name("n"), &likeness).unwrap(); + } + // Not in the order the groups were made in. + let order: Vec = (0..count).map(|index| index * 7919 % count).collect(); + for (asked, index) in order.iter().enumerate() { + let token = table.token(&mut scratch, &walked(*index)).unwrap(); + assert_eq!(token.get(), asked as u64 + 1); + assert_eq!(table.token(&mut scratch, &walked(*index)).unwrap(), token); + } + for index in count..2 * count { + table.note(&mut scratch, &walked(index), &name("n"), &likeness).unwrap(); + } + for (asked, index) in order.iter().enumerate() { + let token = table.token(&mut scratch, &walked(*index)).unwrap(); + assert_eq!(token.get(), asked as u64 + 1); + } + assert_eq!(table.token(&mut scratch, &walked(count)).unwrap().get(), count + 1); + let unknown = table.token(&mut scratch, &walked(u64::MAX)).unwrap_err(); + assert_eq!(unknown.kind(), io::ErrorKind::InvalidData); + let unknown = HardlinkTable::new().token(&mut scratch, &walked(1)).unwrap_err(); + assert_eq!(unknown.kind(), io::ErrorKind::InvalidData); + } + + /// Room is made a part at a time, with as much reading and writing as + /// the budget of each step allows, and the groups are all there once + /// it is made. Without a budget nothing is done, and where there is + /// room nothing is to do. + #[test] + fn makes_room_in_steps() { + for (budget, memory) in [ + (1, 8 * PAGE_SIZE), + (PAGE_SIZE as u64, 8 * PAGE_SIZE), + (3 * PAGE_SIZE as u64 + 1, usize::MAX), + ] { + let (_tmp, mut scratch) = scratch("hardlink-steps"); + let mut table = HardlinkTable::with_limits(Limits { + memory, + first_pages: 1, + cached_pages: 3, + }); + let likeness = likeness(1, b"1"); + let (mut steps, mut most) = (0, 0); + for index in 0..3000 { + let mut now = 0; + while !table.make_room(&mut scratch, budget).unwrap() { + assert!(!table.make_room(&mut scratch, 0).unwrap()); + now += 1; + } + assert!(table.make_room(&mut scratch, 0).unwrap()); + (steps, most) = (steps + now, most.max(now)); + let noted = table.note(&mut scratch, &walked(index), &name("n"), &likeness).unwrap(); + assert_eq!(noted, Noted::First); + } + // The last doubling alone took a step for every page the + // budget pays for, and a part of a page is paid in full. + let pages_a_step = budget.div_ceil(PAGE_SIZE as u64); + assert!( + most + 1 >= table.store.pages() / 2 / pages_a_step, + "{} {}", + budget, + most + ); + assert!(steps > most); + assert_eq!(matches!(table.store, Store::Memory(_)), memory == usize::MAX); + for index in 0..3000 { + let again = table.note(&mut scratch, &walked(index), &name("m"), &likeness).unwrap(); + assert_eq!(again, Noted::Again, "{}", index); + } + } + // A name is noted whatever is left to do before. + let (_tmp, mut scratch) = scratch("hardlink-steps"); + let mut table = small(); + let likeness = likeness(1, b"1"); + for index in 0..3000 { + let _ = table.make_room(&mut scratch, 1).unwrap(); + table.note(&mut scratch, &walked(index), &name("n"), &likeness).unwrap(); + } + assert_eq!(table.groups, 3000); + } + + /// Once no more names come, what was begun to make room is finished a + /// part at a time as well, and nothing else begins: a table that is + /// full stays as large as it is. A table without groups never took + /// room. + #[test] + fn settles_in_steps() { + let (_tmp, mut scratch) = scratch("hardlink-settles"); + let mut table = small(); + let likeness = likeness(1, b"1"); + let mut count = 0; + // Up to the group before one that doubles a table of many pages + // on disk. + while !(table.store.pages() >= 64 && table.is_full()) { + table.note(&mut scratch, &walked(count), &name("n"), &likeness).unwrap(); + count += 1; + } + assert!(matches!(table.store, Store::Disk(_))); + let pages = table.store.pages(); + // Full as it is, there is nothing to finish. + assert!(table.settle(&mut scratch, 0).unwrap() && table.settle(&mut scratch, u64::MAX).unwrap()); + assert_eq!(table.store.pages(), pages); + // The table begins to double and gets as far as its first page. + assert!(!table.make_room(&mut scratch, 1).unwrap()); + assert_eq!(table.store.pages(), 2 * pages); + let mut steps = 0; + while !table.settle(&mut scratch, 1).unwrap() { + assert!(!table.settle(&mut scratch, 0).unwrap()); + steps += 1; + } + // A page a step, but for the first one and the last one. + assert_eq!(steps, pages - 2); + assert!(matches!(table.growth, Growth::None)); + assert_eq!(table.store.pages(), 2 * pages); + // Every group is there, and gets its token whatever was left to + // finish. + for index in 0..count { + assert_eq!(table.token(&mut scratch, &walked(index)).unwrap().get(), index + 1); + } + let with_tokens = count; + while !table.is_full() { + table.note(&mut scratch, &walked(count), &name("n"), &likeness).unwrap(); + count += 1; + } + let pages = table.store.pages(); + assert!(!table.make_room(&mut scratch, 1).unwrap()); + let token = table.token(&mut scratch, &walked(count - 1)).unwrap(); + assert_eq!(token.get(), with_tokens + 1); + assert!(matches!(table.growth, Growth::None)); + assert_eq!(table.store.pages(), 2 * pages); + let mut none = HardlinkTable::new(); + assert!(none.make_room(&mut scratch, u64::MAX).unwrap() && none.settle(&mut scratch, u64::MAX).unwrap()); + assert_eq!(none.store.pages(), 0); + assert!(scratch.file().is_ok()); + } + + /// The tokens of a table in memory cost nothing. Those of a table on + /// disk cost a page for every page that is read from its scratch file + /// or written to it for them, and nothing where memory holds the page + /// of the group. So with room in memory for every page a page is read + /// once at most and none is written, and with room for one page nearly + /// every token reads its page, and writes out the page of the token + /// before it where that token was new. A page costs as many bytes as + /// it has, no more and no less: with room for one page, a token costs + /// the page that is read for it, and the page that is written out to + /// make room for that one if it changed. + #[test] + fn what_tokens_cost() { + /// How many groups each table has. + const GROUPS: u64 = 2_000; + /// Room for every page of a table of that many groups: a prime. + const EVERY_PAGE: usize = 1021; + let likeness = likeness(1, b"1"); + let (_tmp, mut scratch) = scratch("hardlink-cost"); + let mut in_memory = HardlinkTable::new(); + for index in 0..GROUPS { + in_memory + .note(&mut scratch, &walked(index), &name("n"), &likeness) + .unwrap(); + } + for index in 0..GROUPS { + assert_eq!(in_memory.token(&mut scratch, &walked(index)).unwrap().get(), index + 1); + } + assert!(matches!(in_memory.store, Store::Memory(_))); + assert_eq!(in_memory.token_cost(), 0); + for cached_pages in [1, EVERY_PAGE] { + let mut table = HardlinkTable::with_limits(Limits { + memory: 8 * PAGE_SIZE, + first_pages: 1, + cached_pages, + }); + for index in 0..GROUPS { + table.note(&mut scratch, &walked(index), &name("n"), &likeness).unwrap(); + } + assert!(matches!(table.store, Store::Disk(_))); + let pages = table.store.pages(); + assert!(pages < EVERY_PAGE as u64); + // What the names cost is none of this. + assert_eq!(table.token_cost(), 0); + let mut costs = [0; 2]; + for cost in &mut costs { + let before = table.token_cost(); + for index in 0..GROUPS { + assert_eq!(table.token(&mut scratch, &walked(index)).unwrap().get(), index + 1); + } + *cost = table.token_cost() - before; + } + let [new, again] = costs.map(|cost| cost / PAGE_COST); + if cached_pages == EVERY_PAGE { + assert!(new <= pages && again == 0, "{} {}", new, again); + } else { + // A read for nearly every token, and a write as well where + // the tokens are new. + assert!((GROUPS / 2..=2 * GROUPS).contains(&again), "{}", again); + assert!((again + GROUPS / 2..=4 * GROUPS).contains(&new), "{} {}", new, again); + } + } + /// The bytes of a page. + const PAGE: u64 = PAGE_SIZE as u64; + let mut table = HardlinkTable::with_limits(Limits { + memory: 8 * PAGE_SIZE, + first_pages: 1, + cached_pages: 1, + }); + for index in 0..GROUPS { + table.note(&mut scratch, &walked(index), &name("n"), &likeness).unwrap(); + } + // Two groups of two pages, each in the page its key belongs into, + // so that one page is read to find it. + let pages = table.store.pages(); + let mut at_home = Vec::new(); + for index in 0..GROUPS { + let key = walked(index).encode(); + let home = HardlinkTable::home(&table.hasher, &key, pages); + let found = table.find(&key).unwrap().unwrap().0; + if found == home && at_home.iter().all(|&(_, other)| other != home) { + at_home.push((index, home)); + } + if at_home.len() == 2 { + break; + } + } + let [(one, _), (other, _)] = at_home[..] else { + panic!("no two groups in pages of their own: {:?}", at_home); + }; + let mut cost = |index: u64| { + let before = table.token_cost(); + table.token(&mut scratch, &walked(index)).unwrap(); + table.token_cost() - before + }; + // The first token is new, so its page changes and is written out + // for the page of the second one, which is new as well. + cost(one); + assert_eq!(cost(other), 2 * PAGE); + assert_eq!(cost(one), 2 * PAGE); + // Neither page changes any more. + assert_eq!(cost(other), PAGE); + assert_eq!(cost(other), 0); + assert_eq!(cost(one), PAGE); + } + + /// A table that has doubled on disk gives back the scratch file of its + /// old pages. That file is emptied, and it stays open and one of the + /// files of the manifest's own, with the inode it had. The next + /// doubling goes into it. So the table takes turns between two files + /// for its pages and makes no file after its first doubling on disk, + /// however often it doubles: it has three files open while it doubles + /// and between doublings. A table that is dropped leaves them as they + /// are, and all of them are closed once the scratch space is dropped. + #[test] + fn doubled_tables_take_turns_between_two_files() { + /// How many times the table doubles on disk here. + const DOUBLINGS: usize = 6; + /// The files the table has: two for its pages, and the names. + const FILES: usize = 3; + let (tmp, mut scratch) = scratch("hardlink-kept"); + let mut table = small(); + let likeness = likeness(1, b"1"); + // The file among `files` that holds the pages of the table. + let pages_of = |files: &[OpenFile], table: &HardlinkTable| { + let size = DiskPages::offset(table.store.pages()); + let pages: Vec<_> = files.iter().filter(|file| file.size == size).collect(); + assert_eq!(pages.len(), 1, "{:?}", files); + pages[0].inode + }; + let inodes = |files: &[OpenFile]| -> HashSet { files.iter().map(|file| file.inode).collect() }; + let mut count = 0; + let mut doublings = 0; + // The file of the pages and the empty one after the last doubling. + let mut last: Option<(InodeId, InodeId)> = None; + while doublings < DOUBLINGS { + let before = table.store.pages(); + if let Some((pages, empty)) = last.filter(|_| table.is_full()) { + // The doubling begins, into the file that was empty. + assert!(!table.make_room(&mut scratch, 0).unwrap()); + let files = OpenFile::made_in(&tmp.0); + assert_eq!(files.len(), FILES, "{:?}", files); + assert!(files.iter().all(|file| file.size > 0), "{:?}", files); + assert_eq!(pages_of(&files, &table), empty); + assert!(inodes(&files).contains(&pages)); + } + table.note(&mut scratch, &walked(count), &name("n"), &likeness).unwrap(); + count += 1; + if !matches!(table.store, Store::Disk(_)) { + assert!(OpenFile::made_in(&tmp.0).is_empty()); + continue; + } + if table.store.pages() == before { + continue; + } + // The table moved to disk and doubled there, or doubled there. + doublings += 1; + let files = OpenFile::made_in(&tmp.0); + // The pages, the names, and the file of the pages the table + // had, which is the one that is empty. + assert_eq!(files.len(), FILES, "{:?}", files); + let empty: Vec<_> = files + .iter() + .filter(|file| file.size == 0) + .map(|file| file.inode) + .collect(); + assert_eq!(empty.len(), 1, "{:?}", files); + let pages = pages_of(&files, &table); + // The two files of the pages changed places, and no file was + // made. + if let Some((had, was_empty)) = last { + assert_eq!((pages, empty[0]), (was_empty, had), "{:?}", files); + } + last = Some((pages, empty[0])); + let own = scratch.own_files(); + assert!(files.iter().all(|file| own.contains(&file.status).unwrap())); + } + // A table that is dropped leaves its files as they are. Nothing but + // the scratch space empties one, and all are closed with it. + drop(table); + let files = OpenFile::made_in(&tmp.0); + assert_eq!(files.len(), FILES); + assert_eq!(files.iter().filter(|file| file.size == 0).count(), 1, "{:?}", files); + let own = scratch.own_files(); + assert!(files.iter().all(|file| own.contains(&file.status).unwrap())); + drop(scratch); + assert!(OpenFile::made_in(&tmp.0).is_empty()); + } + + /// A scratch file that does not hold what was written to it is an + /// error, whatever it holds instead. + #[test] + fn changed_scratch_files() { + type Damage = fn(&mut HardlinkTable); + let damages: [(&str, Damage); 5] = [ + ("marks", |table| { + let Store::Disk(disk) = &mut table.store else { + unreachable!() + }; + // Every page is marked as one that overflowed, full or + // not. + for page in 0..disk.pages { + let at = DiskPages::offset(page) + size_of::() as u64; + disk.file.write_all_at(&OVERFLOWED.to_le_bytes(), at).unwrap(); + } + }), + ("counts", |table| { + let Store::Disk(disk) = &mut table.store else { + unreachable!() + }; + for page in 0..disk.pages { + disk.file + .write_all_at(&[0xff; HEADER_SIZE], DiskPages::offset(page)) + .unwrap(); + } + }), + ("slots", |table| { + let Store::Disk(disk) = &mut table.store else { + unreachable!() + }; + for page in 0..disk.pages { + let at = DiskPages::offset(page) + (HEADER_SIZE + KEY_SIZE) as u64; + disk.file.write_all_at(&[0xff; SLOT_SIZE - KEY_SIZE], at).unwrap(); + } + }), + ("a shorter file", |table| { + let Store::Disk(disk) = &mut table.store else { + unreachable!() + }; + disk.file.set_len(0).unwrap(); + }), + ("names", |table| { + let Names::Disk { file, .. } = &mut table.names else { + unreachable!() + }; + file.write_all_at(&[0xff; 4 * NAMES_BUFFER], 0).unwrap(); + }), + ]; + for (what, damage) in damages { + let (_tmp, mut scratch) = scratch("hardlink-damage"); + let mut table = small(); + let likeness = likeness(1, b"1"); + let other = self::likeness(2, b"2"); + let count = 3000; + for index in 0..count { + let first = name(&format!("{}/{}", "d".repeat(100), index)); + table.note(&mut scratch, &walked(index), &first, &likeness).unwrap(); + } + let Store::Disk(disk) = &mut table.store else { + unreachable!() + }; + disk.flush().unwrap(); + disk.numbers.fill(DiskPages::NONE); + damage(&mut table); + let failed = (0..count) + .filter(|&index| { + let noted = table.note(&mut scratch, &walked(index), &name("m"), &other); + let token = table.token(&mut scratch, &walked(index)); + noted.is_err() || token.is_err() + }) + .count(); + assert!(failed > 0, "{}", what); + // Whatever is there, a group that seems new still goes in or + // fails. It fails where the marks say that every page was + // full, and is not looked for in all of the table first. + let new = table.note(&mut scratch, &walked(count), &name("new"), &likeness); + assert!(what != "marks" || new.is_err(), "{:?}", new); + } + } + + /// The variable that tells the test binary, run again by + /// [`memory_stays_flat`], how many names to note. + const NAMES: &str = "UAPI16_TEST_HARDLINK_NAMES"; + + /// What the line starts with that says what was measured. + const MEASURED: &str = "hard links:"; + + /// The resident memory of this process that is its own, in bytes, which + /// the kernel reports in kilobytes: RssAnon, without the pages of the + /// files it has mapped. Those of the test binary come and go with the + /// file system it is on, and are none of the table's. A kernel before + /// Linux 4.5 does not tell the two apart, and all that is resident is + /// taken there. + fn resident() -> u64 { + let status = fs::read_to_string("/proc/self/status").unwrap(); + let field = |name: &str| status.lines().find_map(|line| line.strip_prefix(name)); + let line = field("RssAnon:").or_else(|| field("VmRSS:")).unwrap(); + let kilobytes: u64 = line.trim().trim_end_matches("kB").trim().parse().unwrap(); + kilobytes * 1024 + } + + /// Notes `names` names of half as many inodes, every inode first and + /// then every inode again, which is as far apart as the names of an + /// inode get, and checks that the memory of the process stops growing + /// once the table is on disk. + fn note_names(names: u64) { + let (_tmp, mut scratch) = scratch("hardlink-flat"); + let mut table = HardlinkTable::new(); + let likeness = likeness(1, b"1"); + let inodes = names / 2; + // By then the table is on disk, has doubled there and has every + // buffer it ever takes. + let settled = 20_000.min(inodes - 1); + let started = Instant::now(); + let (mut before, mut most) = (0, 0); + for round in 0..2 { + for inode in 0..inodes { + let first = name(&format!("usr/lib/{:03}/{:07}", inode % 1000, inode)); + let noted = table.note(&mut scratch, &walked(inode), &first, &likeness).unwrap(); + assert_eq!(noted == Noted::First, round == 0); + if round == 0 && inode == settled { + before = resident(); + } + if inode % 4096 == 0 && (round == 1 || inode > settled) { + most = most.max(resident()); + } + } + } + most = most.max(resident()); + let Store::Disk(disk) = &table.store else { + panic!("{} names stayed in memory", names); + }; + let Names::Disk { written, .. } = &table.names else { + unreachable!(); + }; + println!( + "{} {} names, {} inodes, {:.2} s, resident {} KiB once on disk and {} KiB at most after, \ + table {} MiB, first names {} MiB", + MEASURED, + names, + inodes, + started.elapsed().as_secs_f64(), + before / 1024, + most / 1024, + DiskPages::offset(disk.pages) >> 20, + written >> 20, + ); + // A table in memory would have grown by megabytes for every + // doubling since. + const SLACK: u64 = 2 * 1024 * 1024; + assert!(most <= before + SLACK, "{} -> {}", before, most); + } + + /// Runs the test binary again to note `names` names in a process that + /// does nothing else, so that its memory is that of the table. + fn stays_flat(names: u64) { + let output = Command::new(env::current_exe().unwrap()) + .args(["--exact", "hardlink::tests::memory_stays_flat", "--nocapture"]) + .env(NAMES, names.to_string()) + .output() + .unwrap(); + let said = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success(), + "{}\n{}", + said, + String::from_utf8_lossy(&output.stderr) + ); + // The harness can have its own words in front on the same line. + if let Some(measured) = said.lines().find_map(|line| line.find(MEASURED).map(|at| &line[at..])) { + println!("{}", measured); + } + } + + /// The memory of the table does not grow with the number of names + /// once it is on disk. + #[test] + fn memory_stays_flat() { + match env::var(NAMES) { + Ok(names) => note_names(names.parse().unwrap()), + Err(_) => stays_flat(100_000), + } + } + + /// The same for a million names. + #[test] + #[ignore = "notes a million names"] + fn memory_stays_flat_for_a_million_names() { + stays_flat(1_000_000); + } + + /// The same for ten million names, with a scratch file of gigabytes. + #[test] + #[ignore = "notes ten million names"] + fn memory_stays_flat_for_ten_million_names() { + stays_flat(10_000_000); + } + + /// Every name of an inode is held against the first name that was + /// noted of it. A name that does not show the file the first name + /// showed is a hard-link mismatch that names both, also a name that was + /// noted before and shows another file now. The first name itself, + /// noted again, is a file that changed. + #[test] + fn errors() { + let (_tmp, mut scratch) = scratch("hardlink-errors"); + let mut table = HardlinkTable::new(); + let (first, second) = (name("a/first \"name\""), name("b/second")); + let noted = table + .note(&mut scratch, &walked(1), &first, &likeness(1, b"1")) + .unwrap(); + noted.check(&first).unwrap(); + let again = table + .note(&mut scratch, &walked(1), &second, &likeness(1, b"1")) + .unwrap(); + again.check(&second).unwrap(); + let differs = table + .note(&mut scratch, &walked(1), &second, &likeness(1, b"2")) + .unwrap(); + let e = differs.check(&second).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::HardlinkMismatch)); + assert_eq!( + (e.name(), e.hardlink_name()), + (Some("b/second"), Some("a/first \"name\"")) + ); + assert_eq!( + e.to_string(), + r#"b/second: is a name of the inode of 'a/first \"name\"', but does not show the same file"# + ); + let differs = table + .note(&mut scratch, &walked(1), &first, &likeness(1, b"2")) + .unwrap(); + let e = differs.check(&first).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::Changed)); + assert_eq!((e.name(), e.hardlink_name()), (Some(first.as_str()), None)); + } + + /// A scratch file that cannot be read fails what needs it and leaves + /// the table as it was. + #[test] + fn failures() { + let (_tmp, mut scratch) = scratch("hardlink-failed"); + let mut table = small(); + let likeness = likeness(1, b"1"); + let mut count = 0; + // Up to the group before one that doubles a table on disk. + while !(matches!(table.store, Store::Disk(_)) && table.is_full()) { + table.note(&mut scratch, &walked(count), &name("n"), &likeness).unwrap(); + count += 1; + } + let shorten = |table: &mut HardlinkTable, len: Option| { + let Store::Disk(disk) = &mut table.store else { + unreachable!() + }; + disk.flush().unwrap(); + disk.numbers.fill(DiskPages::NONE); + disk.file.set_len(len.unwrap_or(DiskPages::offset(disk.pages))).unwrap(); + }; + shorten(&mut table, Some(0)); + let failed = table.note(&mut scratch, &walked(0), &name("n"), &likeness).unwrap_err(); + assert_eq!(failed.kind(), io::ErrorKind::UnexpectedEof); + assert!(table.token(&mut scratch, &walked(0)).is_err()); + // With the file as long as it was the table is used again. Its + // pages read as zeroes now: no group is there. + shorten(&mut table, None); + let noted = table.note(&mut scratch, &walked(0), &name("n"), &likeness).unwrap(); + assert_eq!(noted, Noted::First); + } + + /// A table that cannot finish doubling, because the second half of the + /// pages it doubles into or of the pages it had cannot be read, fails + /// with that error and keeps the pages it had: every group is there + /// with its first name, and the next group doubles the table. The file + /// it could not double into is given back, which empties it and leaves + /// it open, and the next doubling goes into it again: no file is made + /// for it. + #[test] + fn failed_doublings() { + let (likeness, other) = (likeness(1, b"1"), likeness(1, b"2")); + let first = |index: u64| name(&format!("n{}", index)); + let all_there = |table: &mut HardlinkTable, scratch: &mut Scratch, count: u64| { + for index in 0..count { + let again = table.note(scratch, &walked(index), &name("again"), &likeness).unwrap(); + let differs = table.note(scratch, &walked(index), &name("again"), &other).unwrap(); + assert_eq!((again, differs), (Noted::Again, Noted::Differs(first(index)))); + } + }; + for old_pages in [false, true] { + let (tmp, mut scratch) = scratch("hardlink-doubling"); + let mut table = small(); + let mut count = 0; + // Up to the group before one that doubles a table on disk. + while !(matches!(table.store, Store::Disk(_)) && table.is_full()) { + table + .note(&mut scratch, &walked(count), &first(count), &likeness) + .unwrap(); + count += 1; + } + let pages = table.store.pages(); + let (half, end) = (DiskPages::offset(pages / 2), DiskPages::offset(pages)); + // The doubling begins. The pages it had come back once it + // failed. + assert!(!table.make_room(&mut scratch, 0).unwrap()); + let mut kept = vec![0; usize::try_from(end - half).unwrap()]; + if old_pages { + let Growth::Doubling { + old: Store::Disk(had), .. + } = &mut table.growth + else { + unreachable!() + }; + had.file.read_exact_at(&mut kept, half).unwrap(); + had.file.set_len(half).unwrap(); + } else { + let Store::Disk(doubled) = &mut table.store else { + unreachable!() + }; + doubled.file.set_len(end).unwrap(); + } + let e = loop { + match table.make_room(&mut scratch, PAGE_SIZE as u64) { + Ok(done) => assert!(!done), + Err(e) => break e, + } + }; + assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof); + assert!(matches!(table.growth, Growth::None)); + assert_eq!(table.store.pages(), pages); + // The pages, the names, and the file the table could not + // double into, which is the one it moved to and is empty again. + let files = OpenFile::made_in(&tmp.0); + assert_eq!(files.len(), 3, "{:?}", files); + assert_eq!(files.iter().filter(|file| file.size == 0).count(), 1, "{:?}", files); + let own = scratch.own_files(); + assert!(files.iter().all(|file| own.contains(&file.status).unwrap())); + let made: HashSet = files.iter().map(|file| file.inode).collect(); + if old_pages { + let Store::Disk(had) = &mut table.store else { + unreachable!() + }; + had.file.set_len(end).unwrap(); + had.file.write_all_at(&kept, half).unwrap(); + } + all_there(&mut table, &mut scratch, count); + table + .note(&mut scratch, &walked(count), &first(count), &likeness) + .unwrap(); + count += 1; + assert_eq!(table.store.pages(), 2 * pages); + let files = OpenFile::made_in(&tmp.0); + assert_eq!(files.iter().map(|file| file.inode).collect::>(), made); + all_there(&mut table, &mut scratch, count); + for index in 0..count { + assert_eq!(table.token(&mut scratch, &walked(index)).unwrap().get(), index + 1); + } + } + } + + /// The variable that tells the test binary, run again by + /// [`gives_back_the_files_it_cannot_use`], to do the checks. + const UNUSABLE_FILES: &str = "UAPI16_TEST_HARDLINK_UNUSABLE_FILES"; + + /// How far into a file this process may write at most, as prlimit(1) + /// prints the hard limit of RLIMIT_FSIZE, if it can be asked. + fn hard_write_limit() -> Option { + let pid = std::process::id().to_string(); + let output = Command::new("prlimit") + .args(["--pid", &pid, "--fsize", "--noheadings", "--raw", "--output", "HARD"]) + .output() + .ok()?; + let limit = String::from_utf8_lossy(&output.stdout).trim().to_string(); + (output.status.success() && !limit.is_empty()).then_some(limit) + } + + /// Sets how far into a file this process may write, with prlimit(1): + /// with "0" every write to a file fails with EFBIG, where SIGXFSZ is + /// ignored, and with the hard limit none does that did not before. + /// Returns whether it is set. + fn write_limit(soft: &str) -> bool { + Command::new("prlimit") + .args(["--pid", &std::process::id().to_string(), &format!("--fsize={}:", soft)]) + .status() + .is_ok_and(|status| status.success()) + } + + /// A table gives back the scratch files it took and can't use, and + /// takes them again once it can: the first file of a move to disk + /// whose second file can't be made, both files of a move that can't be + /// written, and the file of a doubling that can't be made as long as + /// it has to be. Each of them fails the name that is noted and leaves + /// the table as it was. So a table whose move and whose every doubling + /// failed once has three files in the end, its pages, its names and + /// the file its next doubling goes into, and it made no other. The + /// test binary runs this test again in a process of its own, which + /// ignores SIGXFSZ, has few descriptors and sets its own limit with + /// prlimit(1). It is skipped where that can't be done, and where a + /// write past the limit does not fail. + #[test] + fn gives_back_the_files_it_cannot_use() { + if env::var_os(UNUSABLE_FILES).is_some() { + return check_unusable_files(); + } + let script = concat!( + r#"trap '' XFSZ; ulimit -n 256 || exit 1; "#, + r#"exec "$1" --exact hardlink::tests::gives_back_the_files_it_cannot_use --nocapture"# + ); + let output = Command::new("sh") + .args(["-c", script, "sh"]) + .arg(env::current_exe().unwrap()) + .env(UNUSABLE_FILES, "1") + .output() + .unwrap(); + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + eprint!("{}", String::from_utf8_lossy(&output.stderr)); + } + + /// The checks of [`gives_back_the_files_it_cannot_use`]. + fn check_unusable_files() { + /// How many groups the table gets: it doubles on disk four times. + const GROUPS: u64 = 200; + /// How many names fail once: the one that moves the table to disk, + /// and the one that begins each of its doublings. + const FAILURES: u64 = 5; + /// The files of a table on disk: its pages, its names, and the + /// file its next doubling goes into. + const FILES: usize = 3; + let Some(hard) = hard_write_limit().filter(|hard| write_limit(hard)) else { + eprintln!("skipping: prlimit(1) can't set the limit of this process"); + return; + }; + // A file system that takes a write past the limit fails nothing. + let probe = TempDir::new("hardlink-unusable-probe"); + assert!(write_limit("0")); + let written = fs::write(probe.0.join("probe"), b"x"); + assert!(write_limit(&hard)); + if written.map_err(|e| e.raw_os_error()) != Err(Some(libc::EFBIG)) { + eprintln!("skipping: a write past the limit on the size of a file does not fail with EFBIG here"); + return; + } + let (tmp, mut scratch) = scratch("hardlink-unusable"); + // Every page of the table is in memory, and its names are short + // and stay there. So it writes to a file only where it moves to + // disk and where it doubles. + let mut table = HardlinkTable::with_limits(Limits { + memory: 1, + first_pages: 1, + cached_pages: 64, + }); + let likeness = likeness(1, b"1"); + // One descriptor is left, which the first file of the move takes. + let mut taken = Vec::new(); + loop { + let flags = rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC; + match rustix::fs::open("/dev/null", flags, rustix::fs::Mode::empty()) { + Ok(descriptor) => taken.push(descriptor), + Err(rustix::io::Errno::MFILE) => break, + Err(e) => panic!("{}", e), + } + } + taken.pop(); + let failed = table.note(&mut scratch, &walked(0), &name("n"), &likeness); + drop(taken); + assert_eq!(failed.unwrap_err().raw_os_error(), Some(libc::EMFILE)); + assert!(matches!(table.growth, Growth::None) && matches!(table.store, Store::Memory(_))); + assert_eq!(OpenFile::made_in(&tmp.0).len(), 1); + // No write goes through, and a name that fails for it is noted + // again with the writes going through. + let mut failed = 0; + assert!(write_limit("0")); + for index in 0..GROUPS { + let pages = table.store.pages(); + if let Err(e) = table.note(&mut scratch, &walked(index), &name("n"), &likeness) { + assert_eq!(e.raw_os_error(), Some(libc::EFBIG), "{}", index); + assert!(matches!(table.growth, Growth::None) && table.store.pages() == pages); + assert!(write_limit(&hard)); + let noted = table.note(&mut scratch, &walked(index), &name("n"), &likeness); + assert_eq!(noted.unwrap(), Noted::First); + assert!(write_limit("0")); + failed += 1; + } + } + assert!(write_limit(&hard)); + assert_eq!(failed, FAILURES); + let files = OpenFile::made_in(&tmp.0); + assert_eq!(files.len(), FILES, "{:?}", files); + } + + /// The variable that tells the test binary, run again inside the + /// namespaces of [`doublings_on_a_full_file_system`], where the tmpfs + /// is mounted. + const FULL_DIR: &str = "UAPI16_TEST_HARDLINK_FULL_DIR"; + + /// How much room the tmpfs of [`doublings_on_a_full_file_system`] has, + /// in bytes: more than the files of the table take, and little to fill. + const FULL_ROOM: u64 = 1024 * 1024; + + /// A file that takes the room its file system has left, and gives it + /// back. It is open only while it grows, so it is none of the open + /// files a test finds in its directory. It is removed when it is + /// dropped. + #[derive(Debug)] + struct Filler(PathBuf); + + impl Filler { + /// Fills the file system: the file grows until a write finds no + /// room. The tmpfs of the test has room for [`FULL_ROOM`] bytes. A + /// file that grows past that is on another file system, which the + /// variable names by mistake. This fails then, and fills no more + /// of it. + fn fill(&self) { + let mut file = fs::OpenOptions::new().create(true).append(true).open(&self.0).unwrap(); + let mut size = file.metadata().unwrap().len(); + let full = loop { + if let Err(e) = file.write_all(&[0; PAGE_SIZE]) { + break e; + } + size += PAGE_SIZE as u64; + assert!(size <= FULL_ROOM, "{:?} is not on the tmpfs of the test", self.0); + }; + assert_eq!(full.raw_os_error(), Some(libc::ENOSPC)); + } + + /// Gives the room back. + fn empty(&self) { + fs::remove_file(&self.0).unwrap(); + } + } + + impl Drop for Filler { + /// Removes the file, also where the test fails. + fn drop(&mut self) { + let _ = fs::remove_file(&self.0); + } + } + + /// A table that doubles on disk writes out the pages memory holds once + /// the file it doubles into is as long as it has to be. On a file + /// system that is full the length takes no room, and the pages find + /// none unless their file has them already. The name that is noted + /// fails with ENOSPC then and leaves the table as it was, and the file + /// the doubling took is given back: it is empty, and the doubling goes + /// into it once there is room, so that no file is made for it. The + /// table here holds every page in memory. So its first doubling on disk + /// fails nothing, as the file of its pages has them since the table + /// moved to disk, and each later one fails once, as the file it doubled + /// into before has none of them. The test binary runs this test again + /// in a user and a mount namespace from unshare(1), with its directory + /// on a tmpfs of a fixed size, which is full for every name once the + /// table is on disk. It is skipped where unshare can't make the + /// namespaces or no tmpfs can be mounted in them. + #[test] + fn doublings_on_a_full_file_system() { + if let Some(dir) = env::var_os(FULL_DIR) { + return check_full_file_system(Path::new(&dir)); + } + let tmp = TempDir::new("hardlink-full"); + let room = format!("size={}", FULL_ROOM); + let test = "hardlink::tests::doublings_on_a_full_file_system"; + tmp.rerun_on("tmpfs", Some(&room), test, FULL_DIR); + } + + /// The checks of [`doublings_on_a_full_file_system`], with the scratch + /// files in `dir`, where the tmpfs is mounted. + fn check_full_file_system(dir: &Path) { + /// How many groups the table gets: it doubles on disk four times. + const GROUPS: u64 = 200; + /// How many names fail once: the one that begins each doubling on + /// disk but the first. + const FAILURES: u64 = 3; + /// The files of a table on disk: its pages, its names, and the + /// file its next doubling goes into. + const FILES: usize = 3; + let directory = ScratchFile::open_directory(dir).unwrap(); + let mut scratch = Scratch::beside(directory.into()); + // Every page of the table is in memory, and its names are short + // and stay there. So it writes to a file only where it moves to + // disk and where it doubles. + let mut table = HardlinkTable::with_limits(Limits { + memory: 1, + first_pages: 1, + cached_pages: 64, + }); + let likeness = likeness(1, b"1"); + // The first name moves the table to disk, which takes room. + let noted = table.note(&mut scratch, &walked(0), &name("n"), &likeness); + assert_eq!(noted.unwrap(), Noted::First); + assert!(matches!(table.store, Store::Disk(_))); + // From here on the file system is full for every name, and a name + // that fails for it is noted again once there is room. + let filler = Filler(dir.join("filler")); + let mut failed = 0; + for index in 1..GROUPS { + filler.fill(); + let pages = table.store.pages(); + if let Err(e) = table.note(&mut scratch, &walked(index), &name("n"), &likeness) { + assert_eq!(e.raw_os_error(), Some(libc::ENOSPC), "{}", index); + assert!(matches!(table.growth, Growth::None) && table.store.pages() == pages); + // The pages, and two files that are empty: the names, which + // memory holds, and the file the doubling took. + let mut sizes: Vec = OpenFile::made_in(dir).iter().map(|file| file.size).collect(); + sizes.sort_unstable(); + assert_eq!(sizes, [0, 0, DiskPages::offset(pages)], "{}", index); + filler.empty(); + let noted = table.note(&mut scratch, &walked(index), &name("n"), &likeness); + assert_eq!(noted.unwrap(), Noted::First); + // The doubling went into that file: none was made for it. + assert_eq!(OpenFile::made_in(dir).len(), FILES, "{}", index); + failed += 1; + } + } + assert_eq!(failed, FAILURES); + // Every group is there. + for index in 0..GROUPS { + let again = table.note(&mut scratch, &walked(index), &name("again"), &likeness); + assert_eq!(again.unwrap(), Noted::Again, "{}", index); + } + } + + /// A table that is given up gives every scratch file it has back, also + /// those of a move to disk and of a doubling there that are under way: + /// each is empty then, and the scratch space hands it out again before + /// it makes a new one. + #[test] + fn gives_its_files_back() { + let likeness = likeness(1, b"1"); + // A move has the file of the pages and that of the names, and a + // doubling on disk those of the old pages, of the new ones and of + // the names. + for (doubling, files) in [(false, 2), (true, 3)] { + let (tmp, mut scratch) = scratch("hardlink-given-back"); + let mut table = small(); + let under_way = |table: &HardlinkTable| match &table.growth { + Growth::None => false, + Growth::Moving { .. } => !doubling, + Growth::Doubling { old, .. } => doubling && matches!(old, Store::Disk(_)), + }; + // Names until the step that makes room for the next one + // begins the one or the other and does not finish it. + let mut count = 0; + while !under_way(&table) { + if table.make_room(&mut scratch, 1).unwrap() { + table.note(&mut scratch, &walked(count), &name("n"), &likeness).unwrap(); + count += 1; + } + } + let open = OpenFile::made_in(&tmp.0); + assert_eq!(open.len(), files, "{:?}", open); + assert!(open.iter().any(|file| file.size > 0), "{:?}", open); + table.give_back(&mut scratch); + let _handed_out: Vec = (0..files).map(|_| scratch.file().unwrap()).collect(); + let open = OpenFile::made_in(&tmp.0); + assert_eq!(open.len(), files, "{:?}", open); + assert!(open.iter().all(|file| file.size == 0), "{:?}", open); + } + } + + /// A table can go to another thread. + #[test] + fn send() { + fn send() {} + send::(); + send::(); + send::(); + } +} diff --git a/src/uapi16/install.sh b/src/uapi16/install.sh new file mode 100755 index 0000000..7328b82 --- /dev/null +++ b/src/uapi16/install.sh @@ -0,0 +1,116 @@ +#!/bin/sh +# SPDX-License-Identifier: LGPL-2.1-or-later +# +# Installs the C library of uapi16: the shared library with its links, the +# static library, uapi16.h and uapi16.pc. build.sh builds the two +# libraries. + +set -eu + +usage() { + cat <&2 + exit 1 + ;; + esac +done +libdir=${libdir:-$prefix/lib} +includedir=${includedir:-$prefix/include} +pkgconfigdir=${pkgconfigdir:-$libdir/pkgconfig} +destdir=${DESTDIR:-} + +fail() { + echo "$0: $*" >&2 + exit 1 +} + +# A path as uapi16.pc has it: with a backslash before a space, which is how +# pkg-config reads a path with a space in it, and how meson writes one. +pc_path() { + printf '%s\n' "$1" | sed 's/ /\\ /g' +} + +shared=$builddir/libuapi16.so +static=$builddir/libuapi16.a +libs=$builddir/libuapi16.libs +for built in "$shared" "$static" "$libs"; do + [ -f "$built" ] || fail "$built is missing, build.sh builds it" +done + +# The version of the crate is the version of the file of the shared +# library and of uapi16.pc. +version=$(sed -n 's/^version = "\(.*\)"$/\1/p' "$here/Cargo.toml" | head -n 1) +[ -n "$version" ] || fail "$here/Cargo.toml has no version" + +# The name the shared library was linked with is the name of its first +# link. A shared library that cargo built has none, and no symbol versions +# either. +command -v readelf > /dev/null || fail "readelf is missing, which reads the name of $shared" +soname=$(readelf -d "$shared" | sed -n 's/.*(SONAME).*\[\(.*\)\]/\1/p') +[ -n "$soname" ] || fail "$shared has no SONAME: build.sh did not link it" + +# What a program that links the static library links as well, as rustc +# listed it when it built the library. +static_libs=$(cat "$libs") + +install -d "$destdir$libdir" "$destdir$includedir" "$destdir$pkgconfigdir" +install -m 0755 "$shared" "$destdir$libdir/libuapi16.so.$version" +ln -sf "libuapi16.so.$version" "$destdir$libdir/$soname" +ln -sf "libuapi16.so.$version" "$destdir$libdir/libuapi16.so" +install -m 0644 "$static" "$destdir$libdir/libuapi16.a" +install -m 0644 "$here/uapi16.h" "$destdir$includedir/uapi16.h" +cat > "$destdir$pkgconfigdir/uapi16.pc" < Plain for [u8; SIZE] { + const ZERO: [u8; SIZE] = [0; SIZE]; +} + +/// The ioctl `_IOR(GROUP, NUMBER, T)`: one that takes nothing, and that +/// writes a `T` at most through the pointer it is given. This is the `T` it +/// writes into. +struct Read(T); + +/// `FAT_IOCTL_GET_ATTRIBUTES`, `_IOR('r', 0x10, __u32)`. +type FatGetAttributes = Read; +/// `FAT_IOCTL_GET_VOLUME_ID`, `_IOR('r', 0x13, __u32)`. +type FatGetVolumeId = Read; +/// `FS_IOC_GETFSLABEL`, `_IOR(0x94, 49, char[FSLABEL_MAX])`. +type GetFsLabel = Read; +/// `FS_IOC_GETFSUUID`, `_IOR(0x15, 0, struct fsuuid2)`. The struct is +/// bytes only, so an array of as many stands in for it. +type GetFsUuid = Read; + +// SAFETY: What the trait asks for holds as follows. +// - as_ptr() gives a pointer to the `T` this value owns. It is valid for +// writes of size_of::() bytes and aligned for a `T` for as long as the +// value is neither moved nor dropped, and rustix::ioctl::ioctl() does +// neither between as_ptr() and output_from_ptr(). +// - output_from_ptr() reads that `T` back through the pointer of as_ptr(), +// and does so only after the call. +// - opcode() is `_IOR(GROUP, NUMBER, T)`, so the size the opcode carries +// is that of the `T` the pointer leads to. The two cannot disagree. +// - IS_MUTATING is true: the kernel writes through the pointer. +// That the ioctl of this opcode writes no more than a `T` is up to whoever +// makes the call, see Read::call(). +unsafe impl Ioctl for Read { + type Output = T; + + const IS_MUTATING: bool = true; + + fn opcode(&self) -> Opcode { + opcode::read::(GROUP, NUMBER) + } + + fn as_ptr(&mut self) -> *mut c_void { + ptr::from_mut(&mut self.0).cast() + } + + unsafe fn output_from_ptr(_: IoctlOutput, value: *mut c_void) -> rustix::io::Result { + // SAFETY: The caller passes the pointer as_ptr() returned for a + // `Read` that is still alive, so it points to a `T`, is aligned for + // one and nothing else reads or writes it now. That `T` was a value + // before the call, the kernel wrote at most its size_of::() + // bytes, and a `Plain` type takes any bytes. So it is a value. + Ok(unsafe { value.cast::().read() }) + } +} + +impl Read { + /// Issues the ioctl on `fd` and returns what the kernel wrote, with + /// zeroes wherever it wrote nothing. + /// + /// # Safety + /// + /// For the file `fd` refers to, the ioctl `_IOR(GROUP, NUMBER, T)` does + /// nothing but write at most `size_of::()` bytes through the pointer + /// it is given, or fails. + unsafe fn call(fd: BorrowedFd<'_>) -> rustix::io::Result { + // SAFETY: `Read` implements `Ioctl` as that trait asks, see there. + // What the ioctl does to the memory of the process is what the + // caller guarantees: it writes into the `T` of the `Read` and + // nowhere else. + unsafe { ioctl::ioctl(fd, Read::(T::ZERO)) } + } +} + +/// Checks that `fd` refers to a regular file or a directory. The ioctls +/// of one go to its file system. Those of anything else go to a driver, +/// which can make something else of the same number, so on anything else +/// they fail here with ENOTTY, as an ioctl a file does not have, and are +/// not issued. +fn check_file_or_directory(fd: BorrowedFd<'_>) -> rustix::io::Result<()> { + let stat = rustix::fs::fstat(fd)?; + match FileType::from_raw_mode(stat.st_mode) { + FileType::RegularFile | FileType::Directory => Ok(()), + _ => Err(Errno::NOTTY), + } +} + +/// The DOS attributes of a file, as `FAT_IOCTL_GET_ATTRIBUTES` gives them: +/// the attribute byte of its directory entry. Only the four bits that are +/// read here count, whatever else the answer has. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct DosAttributes(u32); + +impl DosAttributes { + /// `ATTR_RO`, include/uapi/linux/msdos_fs.h: the file is read-only. + const READ_ONLY: u32 = 0x01; + /// `ATTR_HIDDEN`: the file is hidden. + pub(crate) const HIDDEN: u32 = 0x02; + /// `ATTR_SYS`: the file is a system file. + pub(crate) const SYSTEM: u32 = 0x04; + /// `ATTR_ARCH`: the file changed since it was archived. + pub(crate) const ARCHIVE: u32 = 0x20; + /// Each of the attributes that have a flag of their own in a manifest, + /// with that flag. + const FLAGS: [(u32, DosFlags); 3] = [ + (DosAttributes::HIDDEN, DosFlags::HIDDEN), + (DosAttributes::SYSTEM, DosFlags::SYSTEM), + (DosAttributes::ARCHIVE, DosFlags::ARCHIVE), + ]; + + /// The attributes of the answer `raw` of the kernel. + pub(crate) fn from_raw(raw: u32) -> DosAttributes { + DosAttributes(raw) + } + + /// Whether the read-only attribute is set. + pub(crate) fn is_read_only(self) -> bool { + self.0 & DosAttributes::READ_ONLY != 0 + } + + /// The attributes hidden, system and archive that are set. + pub(crate) fn flags(self) -> DosFlags { + DosAttributes::FLAGS + .into_iter() + .filter(|(attribute, _)| self.0 & attribute != 0) + .fold(DosFlags::default(), |flags, (_, flag)| flags | flag) + } +} + +/// The label of a file system, as `FS_IOC_GETFSLABEL` gives it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum FsLabel { + /// The file system has no label: its label is empty. + Empty, + /// The label, a string a manifest can hold. + Label(String), + /// A label a manifest cannot hold: it does not end inside the buffer + /// of the ioctl, it is not UTF-8, or it has a control character or a + /// noncharacter. + Unwritable, +} + +impl FsLabel { + /// The label in the buffer `raw` the kernel wrote it into, which was + /// zeroed before. The label ends at the first NUL. + fn from_raw(raw: &[u8; FSLABEL_MAX]) -> FsLabel { + let Ok(label) = CStr::from_bytes_until_nul(raw) else { + return FsLabel::Unwritable; + }; + match label.to_str() { + Ok("") => FsLabel::Empty, + Ok(label) if FileSystemIdentity::is_valid_label(label) => FsLabel::Label(label.to_owned()), + _ => FsLabel::Unwritable, + } + } +} + +/// What a file system identifies itself with, as `FS_IOC_GETFSUUID` gives +/// it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FsUuid { + /// A UUID. + Uuid(Uuid), + /// The UUID of all zeroes, which is none. + Null, + /// Something of another size than a UUID, of this many bytes: the 4 of + /// the volume serial number of FAT, the 8 of that of NTFS, or a size + /// that `struct fsuuid2` has no room for. + NotUuid(u8), +} + +impl FsUuid { + /// The identifier in the `struct fsuuid2` `raw` the kernel wrote, which + /// was zeroed before: a size, and as many bytes. + fn from_raw(raw: &[u8; FSUUID2_SIZE]) -> FsUuid { + let [len, uuid @ ..] = *raw; + if usize::from(len) != Uuid::SIZE { + return FsUuid::NotUuid(len); + } + if uuid == [0; Uuid::SIZE] { + return FsUuid::Null; + } + FsUuid::Uuid(Uuid::new(uuid)) + } +} + +/// The DOS attributes of the regular file or the directory `fd` is open +/// on for reading. A file system that has none fails with ENOTTY. +pub(crate) fn dos_attributes(fd: BorrowedFd<'_>) -> rustix::io::Result { + check_file_or_directory(fd)?; + // SAFETY: `fd` is a regular file or a directory, so the ioctl goes to + // its file system. include/uapi/linux/msdos_fs.h defines the opcode as + // one that reads a `__u32`, which is the `u32` it is issued with. fat + // and exfat answer it with put_user() of a `u32`, FUSE cuts what its + // server answers to the size in the opcode, and a file system that + // does not know the opcode fails without writing. + unsafe { FatGetAttributes::call(fd) }.map(DosAttributes::from_raw) +} + +/// The volume serial number of the FAT file system the regular file or the +/// directory `fd` is open on for reading is in. Any other file system fails +/// with ENOTTY. +pub(crate) fn fat_serial(fd: BorrowedFd<'_>) -> rustix::io::Result { + check_file_or_directory(fd)?; + // SAFETY: As for the DOS attributes: the opcode reads a `__u32`, fat + // answers it with put_user() of a `u32`, and every bit pattern is a + // serial number. + unsafe { FatGetVolumeId::call(fd) }.map(FatSerial::new) +} + +/// The label of the file system the regular file or the directory `fd` is +/// open on for reading is in. A file system that cannot say fails with +/// ENOTTY. +pub(crate) fn fs_label(fd: BorrowedFd<'_>) -> rustix::io::Result { + check_file_or_directory(fd)?; + // SAFETY: `fd` is a regular file or a directory. include/uapi/linux/fs.h + // defines the opcode as one that reads a `char[FSLABEL_MAX]`, and the + // array it is issued with has FSLABEL_MAX bytes. A file system writes + // its label and at most that many bytes, often fewer. + let raw = unsafe { GetFsLabel::call(fd) }?; + Ok(FsLabel::from_raw(&raw)) +} + +/// What the file system the regular file or the directory `fd` is open on +/// for reading is in identifies itself with. A file system without an +/// identifier fails with ENOTTY, and so does a kernel before Linux 6.9, +/// which does not have the ioctl. +pub(crate) fn fs_uuid(fd: BorrowedFd<'_>) -> rustix::io::Result { + check_file_or_directory(fd)?; + // SAFETY: `fd` is a regular file or a directory. include/uapi/linux/fs.h + // defines the opcode as one that reads a `struct fsuuid2`, 17 bytes + // without padding, and the array it is issued with has as many. The + // kernel answers it for every file system with copy_to_user() of one + // such struct. + let raw = unsafe { GetFsUuid::call(fd) }?; + Ok(FsUuid::from_raw(&raw)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::TempDir; + use rustix::fs::{Mode, OFlags, CWD}; + use std::fs::{self, File}; + use std::os::fd::AsFd; + use std::os::unix::fs::symlink; + use std::path::Path; + + /// The four opcodes are the numbers the headers of the kernel give + /// them. Most architectures put the direction into the upper two bits. + /// powerpc, sparc and mips put it into the upper three, with other + /// values. The type of an opcode differs between the targets, and so + /// does whether it has a sign, so its 32 bits are compared. + #[test] + fn opcodes() { + let bits = |opcode: Opcode| i128::from(opcode) & i128::from(u32::MAX); + let opcodes = [ + bits(FatGetAttributes::opcode(&Read(0))), + bits(FatGetVolumeId::opcode(&Read(0))), + bits(GetFsLabel::opcode(&Read([0; FSLABEL_MAX]))), + bits(GetFsUuid::opcode(&Read([0; FSUUID2_SIZE]))), + ]; + let expected: [i128; 4] = if cfg!(any( + target_arch = "powerpc", + target_arch = "powerpc64", + target_arch = "sparc", + target_arch = "sparc64", + target_arch = "mips", + target_arch = "mips64" + )) { + [0x4004_7210, 0x4004_7213, 0x4100_9431, 0x4011_1500] + } else { + [0x8004_7210, 0x8004_7213, 0x8100_9431, 0x8011_1500] + }; + assert_eq!(opcodes, expected); + assert_eq!(FSUUID2_SIZE, 17); + } + + /// Of the DOS attributes only the four bits that are read count: the + /// attributes for a directory and for a volume label that FAT has next + /// to them do not, nor does anything above the attribute byte. + #[test] + fn dos_attributes_are_the_bits_that_are_read() { + let none = DosAttributes::from_raw(0); + assert!(!none.is_read_only()); + assert_eq!(none.flags(), DosFlags::default()); + let cases = [ + (0x01, true, DosFlags::default()), + (0x02, false, DosFlags::HIDDEN), + (0x04, false, DosFlags::SYSTEM), + (0x20, false, DosFlags::ARCHIVE), + (0x27, true, DosFlags::ALL), + (0x08 | 0x10 | 0x40 | 0x80, false, DosFlags::default()), + (0xffff_ff00, false, DosFlags::default()), + (u32::MAX, true, DosFlags::ALL), + (0x10 | 0x20, false, DosFlags::ARCHIVE), + ]; + for (raw, read_only, flags) in cases { + let attributes = DosAttributes::from_raw(raw); + assert_eq!(attributes.is_read_only(), read_only, "{:#x}", raw); + assert_eq!(attributes.flags(), flags, "{:#x}", raw); + } + } + + /// A label is what comes before the first NUL of the buffer. Without a + /// NUL in the buffer it has no end, and a manifest holds it only if it + /// is a string without control characters and noncharacters. + #[test] + fn labels() { + let label = |text: &[u8]| { + let mut raw = [0; FSLABEL_MAX]; + raw[..text.len()].copy_from_slice(text); + FsLabel::from_raw(&raw) + }; + assert_eq!(label(b""), FsLabel::Empty); + assert_eq!(label(b"ESP"), FsLabel::Label("ESP".into())); + assert_eq!( + label("r\u{f6}\u{f6}t \u{221e}".as_bytes()), + FsLabel::Label("r\u{f6}\u{f6}t \u{221e}".into()) + ); + // What follows the first NUL is not the label. + assert_eq!(label(b"boot\0junk\xff"), FsLabel::Label("boot".into())); + assert_eq!(label(b"\0junk"), FsLabel::Empty); + // The longest label that ends inside the buffer, and one that fills + // it. + assert_eq!( + label(&[b'a'; FSLABEL_MAX - 1]), + FsLabel::Label("a".repeat(FSLABEL_MAX - 1)) + ); + assert_eq!(label(&[b'a'; FSLABEL_MAX]), FsLabel::Unwritable); + for text in [&b"a\xffb"[..], b"\xc3", b"a\tb", b"a\nb", b"\x7f", b"\x1b[0m"] { + assert_eq!(label(text), FsLabel::Unwritable, "{:?}", text); + } + assert_eq!(label("a\u{fffe}".as_bytes()), FsLabel::Unwritable); + assert_eq!(label("\u{fdd0}".as_bytes()), FsLabel::Unwritable); + } + + /// Only 16 bytes that are not all zeroes are a UUID. + #[test] + fn uuids() { + let identifier = |len: u8, bytes: [u8; Uuid::SIZE]| { + let mut raw = [0; FSUUID2_SIZE]; + raw[0] = len; + raw[1..].copy_from_slice(&bytes); + FsUuid::from_raw(&raw) + }; + let bytes: [u8; Uuid::SIZE] = std::array::from_fn(|i| i as u8 + 1); + assert_eq!(identifier(16, bytes), FsUuid::Uuid(Uuid::new(bytes))); + assert_eq!(identifier(16, [0; Uuid::SIZE]), FsUuid::Null); + let mut last = [0; Uuid::SIZE]; + last[Uuid::SIZE - 1] = 1; + assert_eq!(identifier(16, last), FsUuid::Uuid(Uuid::new(last))); + for len in [0, 4, 8, 15, 17, 32, u8::MAX] { + assert_eq!(identifier(len, bytes), FsUuid::NotUuid(len), "{}", len); + } + } + + /// Opens `path` for reading without following a symbolic link. + fn open(path: &Path, flags: OFlags) -> File { + let flags = flags | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC; + File::from(rustix::fs::open(path, flags, Mode::empty()).unwrap()) + } + + /// The ioctls are only issued on a regular file or a directory. + /// Anything else fails with ENOTTY before that, also a handle, on which + /// the kernel refuses every ioctl with EBADF. + #[test] + fn only_files_and_directories_are_asked() { + let tmp = TempDir::new("ioctl-types"); + let dir = &tmp.0; + symlink("target", dir.join("link")).unwrap(); + rustix::fs::mknodat(CWD, dir.join("fifo"), FileType::Fifo, Mode::RUSR | Mode::WUSR, 0).unwrap(); + let others = [ + open(&dir.join("link"), OFlags::PATH), + open(&dir.join("fifo"), OFlags::PATH), + open(&dir.join("fifo"), OFlags::RDONLY), + open(Path::new("/dev/null"), OFlags::RDONLY), + ]; + for file in &others { + let fd = file.as_fd(); + assert_eq!(dos_attributes(fd), Err(Errno::NOTTY)); + assert_eq!(fat_serial(fd), Err(Errno::NOTTY)); + assert_eq!(fs_label(fd), Err(Errno::NOTTY)); + assert_eq!(fs_uuid(fd), Err(Errno::NOTTY)); + } + // A handle of a directory is a directory, and the kernel refuses + // the ioctl on it. + let handle = open(dir, OFlags::PATH); + assert_eq!(dos_attributes(handle.as_fd()), Err(Errno::BADF)); + assert_eq!(fs_uuid(handle.as_fd()), Err(Errno::BADF)); + } + + /// What a file system the tests can write to answers: no DOS attributes + /// and no volume serial number unless it is FAT, and a label and a UUID + /// or none, as it has them. A file and its directory are in the same + /// file system and get the same answers. + #[test] + fn what_a_file_system_answers() { + let tmp = TempDir::new("ioctl-answers"); + let dir = &tmp.0; + fs::write(dir.join("file"), b"data").unwrap(); + let directory = open(dir, OFlags::RDONLY | OFlags::DIRECTORY); + let file = open(&dir.join("file"), OFlags::RDONLY); + let unsupported = |errno| matches!(errno, Errno::NOTTY | Errno::OPNOTSUPP | Errno::NOSYS | Errno::INVAL); + for fd in [directory.as_fd(), file.as_fd()] { + match dos_attributes(fd) { + // FAT: every file has the attributes of its type. + Ok(_) => assert!(fat_serial(fd).is_ok() || fat_serial(fd).is_err_and(unsupported)), + Err(e) => { + assert!(unsupported(e), "{}", e); + assert!(fat_serial(fd).is_err_and(unsupported)); + } + } + } + let label = fs_label(directory.as_fd()); + assert_eq!(label, fs_label(file.as_fd())); + match label { + Ok(FsLabel::Label(label)) => assert!(FileSystemIdentity::is_valid_label(&label)), + Ok(FsLabel::Empty | FsLabel::Unwritable) => {} + Err(e) => assert!(unsupported(e), "{}", e), + } + let uuid = fs_uuid(directory.as_fd()); + assert_eq!(uuid, fs_uuid(file.as_fd())); + match uuid { + Ok(FsUuid::Uuid(uuid)) => assert_ne!(uuid.as_bytes(), &[0; Uuid::SIZE]), + Ok(FsUuid::Null | FsUuid::NotUuid(_)) => {} + Err(e) => assert!(unsupported(e), "{}", e), + } + // procfs has no label, no UUID and nothing of FAT. + if rustix::fs::statfs("/proc").is_ok_and(|proc| proc.f_type == rustix::fs::PROC_SUPER_MAGIC) { + let process = open(Path::new("/proc/self/task"), OFlags::RDONLY | OFlags::DIRECTORY); + let status = open(Path::new("/proc/self/status"), OFlags::RDONLY); + for fd in [process.as_fd(), status.as_fd()] { + assert_eq!(dos_attributes(fd), Err(Errno::NOTTY)); + assert_eq!(fat_serial(fd), Err(Errno::NOTTY)); + assert_eq!(fs_label(fd), Err(Errno::NOTTY)); + assert_eq!(fs_uuid(fd), Err(Errno::NOTTY)); + } + } + } + + /// The variable that names a directory of a mounted FAT file system + /// for [`fat`]. Mounting one takes privileges, so the test is skipped + /// without it. + const FAT_DIR: &str = "UAPI16_TEST_FAT_DIR"; + + /// On a FAT file system a directory has no attribute but the ones that + /// are not read, unless it was given some, a file system has a volume + /// serial number, and it identifies itself with the 4 bytes of that + /// number where the kernel has `FS_IOC_GETFSUUID`. + #[test] + fn fat() { + let Some(dir) = std::env::var_os(FAT_DIR) else { + eprintln!("skipping: {} names no directory of a FAT file system", FAT_DIR); + return; + }; + let directory = open(Path::new(&dir), OFlags::RDONLY | OFlags::DIRECTORY); + let fd = directory.as_fd(); + dos_attributes(fd).unwrap(); + let serial = fat_serial(fd).unwrap(); + match fs_uuid(fd) { + Ok(identifier) => assert_eq!(identifier, FsUuid::NotUuid(4)), + Err(e) => assert_eq!(e, Errno::NOTTY), + } + // The same serial number through any file of the file system. + for entry in fs::read_dir(Path::new(&dir)).unwrap() { + let path = entry.unwrap().path(); + let meta = fs::symlink_metadata(&path).unwrap(); + if !meta.is_file() && !meta.is_dir() { + continue; + } + let file = open(&path, OFlags::RDONLY); + let attributes = dos_attributes(file.as_fd()).unwrap(); + assert_eq!(fat_serial(file.as_fd()).unwrap(), serial); + // The mode of a file with the read-only attribute gives nobody + // write permission. + if meta.is_file() && attributes.is_read_only() { + assert!(meta.permissions().readonly(), "{:?}", path); + } + } + } +} diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index df8978e..6085c9f 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -14,11 +14,15 @@ //! where it comes: right after the object of its directory, in the order //! the manifest declares, and with the fields of the [`Features`] the //! manifest records. -//! - [`Decoder`] does the same with the bytes it is fed, and does no I/O. //! - [`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 [`Sha256Context::finalize`] returns it. +//! checks it the way the reader does. [`Sha256Context`] computes the +//! hash of data the caller passes it, such as a file while the caller +//! copies it, and does no I/O of its own. [`Sha256Context::finalize`] +//! returns the hash. +//! - [`ManifestOptions`] builds the manifest of a tree of files on the +//! host, which it reads through descriptors, and [`ManifestWriter`] one +//! of file objects that the caller made. [`ManifestReport`] says what it +//! lists. //! - [`RootObject`], [`FileObject`], [`ContentsObject`] and //! [`SignatureObject`] are the objects, and [`Name`], [`InodeType`], //! [`Mode`], [`Sha256`] and [`Uuid`] what their fields hold. Each field @@ -31,44 +35,54 @@ //! [`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`]." -)] +//! that carries it all. [`DirectoryProvider`] takes it from the files +//! next to the 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::process`] -//! says what comes next. When it asks for more of the manifest with -//! [`Step::Input`], [`Decoder::feed`] takes the bytes that came, up to the -//! end of the record it reads, and returns how many it took. The others go -//! in with a later call. [`Decoder::end_feed`] says that there are no more. -//! The other steps hand out the root file object, the objects after it, and -//! the end of the manifest. A record ends where the next one starts, so an -//! object comes once the separator of the record after it was fed, or the -//! input ended, and the end of the manifest once the input ended. A step -//! reads a whole record, of up to [`MAX_RECORD_SIZE`] bytes with its record -//! separator, at once. -//! -//! A manifest that does not go to a [`Write`] is put together by an -//! [`Encoder`]: [`Encoder::begin`], [`Encoder::file`], -//! [`Encoder::signature`] and [`Encoder::finish`] append its records to a -//! string, and the caller sends them on. -//! //! 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. //! +//! The manifest of a tree of files on the host is written by a +//! [`ManifestWriter`]. [`ManifestOptions`] says what it records and makes +//! the writer: [`ManifestOptions::create_at`] for a new file, and +//! [`ManifestOptions::open`] for a [`Write`]. The writer takes the file +//! objects of a caller in any order, with [`ManifestWriter::add_root`] and +//! [`ManifestWriter::add_object`], and [`ManifestWriter::finish`] writes the +//! manifest. [`ManifestOptions::generate_at`] does all of that for a +//! directory and everything below it: +//! +//! ```no_run +//! use std::fs::File; +//! use std::path::Path; +//! use uapi16::{AddFlags, Features, ManifestOptions}; +//! +//! let esp = File::open("/efi")?; +//! let out_dir = File::open("/var/lib/manifests")?; +//! let report = ManifestOptions::new() +//! .features(Features::DEFAULT | Features::MTIME) +//! .generate_at(&out_dir, Path::new("esp.manifest"), &esp, AddFlags::NONE)?; +//! println!("{} files, {} bytes", report.files(), report.bytes()); +//! # Ok::<(), uapi16::Error>(()) +//! ``` +//! +//! The new file appears once the manifest is complete. +//! +//! The feature `capi` adds the C API of the crate, which uapi16.h +//! declares. build.sh and install.sh, which come with the crate, build it +//! as the C library libuapi16 and install it, see the README. The feature +//! adds nothing to the Rust API. +//! //! 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 //! separator and the name of the file object before it in memory: less //! than [`MAX_RECORD_SIZE`] and at most [`Name::MAX_LEN`] bytes. Nothing //! grows with the manifest. Writing one keeps the record it puts together, //! its separator included, and the name of the file object before it. +//! Building a large manifest takes room on disk instead of memory, see +//! [`ManifestOptions::create_at`] and [`ManifestOptions::open`]. //! //! Two checks are up to the caller: whether a manifest declares the order //! of its file objects, [`RootObject::require_order`], and whether an @@ -107,44 +121,66 @@ #![deny(unsafe_code)] #![warn(missing_docs)] -#[cfg(not(any(target_os = "linux", target_os = "android")))] -compile_error!("uapi16 supports Linux and Android only"); +#[cfg(not(target_os = "linux"))] +compile_error!("uapi16 supports Linux only"); mod base64; mod blocking; +// The C API, which is unsafe code as well: C hands over pointers that nothing +// checks. The module says what it relies on. +#[cfg(feature = "capi")] +#[allow(unsafe_code)] +mod capi; mod content; mod decode; mod digest; -#[cfg(target_os = "linux")] mod directory; mod error; mod features; +mod hardlink; mod hex; +// The ioctls rustix has no call for and the lookups in the user database +// are the only unsafe code of the crate without the C API, but for the one +// cast of the module name. Each is in a module of its own, which says what +// it makes sure of. Only the module sys calls them. +#[allow(unsafe_code)] +mod ioctl; +mod listing; +mod manifest; mod metadata; mod name; +#[allow(unsafe_code)] +mod nss; mod object; +mod optional; mod reader; +mod record; +mod scratch; mod sequence; +mod sort; mod strict; +mod sys; +mod tree; +mod walk; mod writer; pub use blocking::{Reader, Writer}; -#[cfg(target_os = "linux")] -pub use content::DirectoryProvider; -pub use content::{DataCheck, DataLocation, DataProvider, ExternalFile, StreamProvider}; +pub use content::{DataCheck, DataLocation, DataProvider, DirectoryProvider, 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 error::{ + DataProblem, Error, ErrorKind, Field, Problem, SourceProblem, TreeProblem, UnsupportedData, ValidityProblem, +}; pub use features::{Features, Order, UnknownFeature}; +pub use manifest::{ManifestOptions, ManifestReport, ManifestWriter}; pub use name::{Name, NameBuf, NameError, NameProblem}; pub use object::{ 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; +pub use reader::Object; +pub use walk::AddFlags; /// The media type of a manifest, which its first object carries. pub const MEDIA_TYPE: &str = "application/vnd.uapi.16.manifest"; @@ -181,23 +217,48 @@ pub(crate) const STRING_RULES: strict::StringRules = #[cfg(test)] pub(crate) mod testing { use super::blocking::READ_SIZE; - use super::object::{DosFlags, InodeFlags}; use super::{ ContentsObject, ContentsSource, Error, Features, FileObject, GptPartition, InodeType, Mode, NameBuf, Object, Reader, RootObject, Sha256, SignatureObject, Uuid, Validity, Writer, RECORD_END, RECORD_SEPARATOR, }; use crate::strict::{ParseError, Skip, Strict}; + use crate::tree::{InodeId, Status}; + use rustix::fs::OFlags; use serde_core::de::DeserializeSeed; use std::collections::BTreeMap; use std::fs; use std::num::NonZeroU64; - use std::path::PathBuf; + use std::os::fd::{AsFd, AsRawFd, RawFd}; + use std::path::{Path, PathBuf}; + use std::process::Command; + use std::sync::{Mutex, PoisonError}; + + /// Whether the kernel has O_EMPTYPATH, asked of the kernel itself. What + /// the process found out about it is no answer while tests run: those + /// that open a file both ways set it for a while. + pub(crate) fn has_empty_path() -> bool { + use rustix::fs::{Mode, OFlags}; + let handle = rustix::fs::open(".", OFlags::PATH | OFlags::CLOEXEC, Mode::empty()).unwrap(); + let flags = OFlags::RDONLY | OFlags::CLOEXEC | OFlags::from_bits_retain(crate::sys::EmptyPath::FLAG); + match rustix::fs::openat(&handle, "", flags, Mode::empty()) { + Ok(_) => true, + Err(rustix::io::Errno::NOENT) => false, + Err(e) => panic!("{}", e), + } + } /// 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); + /// The unit `st_blocks` counts the room of a file in, in bytes. + pub(crate) const ST_BLOCKS_UNIT: u64 = 512; + impl TempDir { + /// What the script of [`TempDir::rerun_on`] exits with where it + /// cannot mount the file system. + const NOT_MOUNTED: i32 = 77; + 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 @@ -206,6 +267,45 @@ pub(crate) mod testing { fs::create_dir(&path).unwrap(); TempDir(path) } + + /// Runs the test `test` of the test binary again in a process for + /// which a file system of the type `file_system` is mounted over + /// this directory, with the mount options `options` if there are + /// any, and with the directory as the value of the variable + /// `variable`. + /// + /// The mount takes a user and a mount namespace, which unshare(1) + /// makes. Where it cannot, or where the file system can't be + /// mounted in them, the test is skipped. + pub(crate) fn rerun_on(&self, file_system: &str, options: Option<&str>, test: &str, variable: &str) { + let works = Command::new("unshare").args(["-Urm", "true"]).output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urm does not work here"); + return; + } + // What is mounted has the name of its type, as for every file + // system without a device, and -o is there only with options. + let script = format!( + r#"mount -t "$1" ${{2:+-o "$2"}} "$1" "$3" || exit {}; exec "$4" --exact "$5" --nocapture"#, + TempDir::NOT_MOUNTED + ); + let output = Command::new("unshare") + .args(["-Urm", "sh", "-c", &script, "sh", file_system]) + .arg(options.unwrap_or_default()) + .arg(&self.0) + .arg(std::env::current_exe().unwrap()) + .arg(test) + .env(variable, &self.0) + .output() + .unwrap(); + if output.status.code() == Some(TempDir::NOT_MOUNTED) { + eprintln!("skipping: no {} can be mounted here", file_system); + return; + } + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } } impl Drop for TempDir { @@ -214,6 +314,58 @@ pub(crate) mod testing { } } + /// A file this process has open: its status, as a walk finds it, with + /// the inode and the size the status has. + #[derive(Clone, Copy, Debug)] + pub(crate) struct OpenFile { + pub(crate) inode: InodeId, + pub(crate) size: u64, + pub(crate) status: Status, + /// The descriptor the process has of it. + pub(crate) descriptor: RawFd, + } + + impl OpenFile { + /// The files this process has open that were made in the directory + /// `dir`, which are the scratch files made there where a test opens + /// nothing else in it. procfs says of every descriptor where its + /// file was made. + /// + /// Looking takes a handle of every file the process has open, for + /// a moment. So one test looks at a time: another one would take + /// such a handle for one more descriptor of a file of its own. + pub(crate) fn made_in(dir: &Path) -> Vec { + static LOOKING: Mutex<()> = Mutex::new(()); + let _looking = LOOKING.lock().unwrap_or_else(PoisonError::into_inner); + let dir = fs::canonicalize(dir).unwrap(); + let flags = OFlags::PATH | OFlags::CLOEXEC; + let mut files = Vec::new(); + for entry in fs::read_dir("/proc/self/fd").unwrap() { + let entry = entry.unwrap(); + // Other tests close their descriptors meanwhile. A handle + // of the file stays the file it is while it is looked at. + let Ok(handle) = rustix::fs::open(entry.path(), flags, rustix::fs::Mode::empty()) else { + continue; + }; + // Another test can have a file open that is so deep in a + // tree that procfs cannot say where: that is none of these. + let Ok(made_at) = fs::read_link(format!("/proc/self/fd/{}", handle.as_raw_fd())) else { + continue; + }; + if made_at.parent() == Some(dir.as_path()) { + let status = Status::of(handle.as_fd()).unwrap(); + files.push(OpenFile { + inode: status.identity.inode_id(), + size: status.size, + status, + descriptor: entry.file_name().to_str().unwrap().parse().unwrap(), + }); + } + } + files + } + } + /// 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"}"#; /// The trailer object. @@ -363,7 +515,7 @@ pub(crate) mod testing { /// A directory that says nothing else about itself. pub(crate) fn directory(name_of: &str) -> FileObject { let mut directory = FileObject::new(name(name_of)); - directory.inode_type = InodeType::Directory; + directory.set_inode_type(InodeType::Directory); directory } @@ -373,10 +525,10 @@ pub(crate) mod testing { pub(crate) fn record(object: &FileObject) -> String { let (root, root_text) = recording_all(); let directories: Vec = object - .name + .name() .as_str() .match_indices('/') - .map(|(end, _)| directory(&object.name.as_str()[..end])) + .map(|(end, _)| directory(&object.name().as_str()[..end])) .collect(); let mut records = written(&root, |writer| { for directory in &directories { @@ -406,15 +558,15 @@ pub(crate) mod testing { encoded.original_sha256 = Some(Sha256::digest(b"original")); encoded.offset = 4; let mut object = FileObject::new(name("a/\u{e9} \"quoted\"\\")); - object.size = Some(5); - 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()); - object.inode.group_name = Some("group".into()); - object.inode.mtime_nsec = Some(u64::MAX); - object.inode_token = NonZeroU64::new(3); - object.inode.user_xattrs = Some(Box::new(BTreeMap::from([ + object.set_size(Some(5)); + object.inode_mut().set_mode(Some(Mode::new(0o440).unwrap())); + object.inode_mut().set_uid(Some(1)); + object.inode_mut().set_gid(Some(2)); + object.inode_mut().set_user_name(Some("user".into())); + object.inode_mut().set_group_name(Some("group".into())); + object.inode_mut().set_mtime_nsec(Some(u64::MAX)); + object.set_inode_token(NonZeroU64::new(3)); + object.inode_mut().set_user_xattrs(Some(BTreeMap::from([ ("text".to_string(), b"value".to_vec()), ("empty".to_string(), Vec::new()), ("binary".to_string(), vec![0xff, 0x00]), @@ -422,15 +574,15 @@ pub(crate) mod testing { ("noncharacter".to_string(), "a\u{fffe}".as_bytes().to_vec()), ]))); // Flags of both kinds, which mix in the order of their names. - object.inode.flags.put(InodeFlags::APPEND_ONLY, Some(true)); - object.dos_flags.put(DosFlags::ARCHIVE, Some(false)); - object.dos_flags.put(DosFlags::HIDDEN, Some(true)); - object.inode.flags.put(InodeFlags::IMMUTABLE, Some(true)); - object.inode.flags.put(InodeFlags::NO_COW, Some(false)); - object.dos_flags.put(DosFlags::SYSTEM, Some(true)); + object.inode_mut().set_flag_append_only(Some(true)); + object.set_flag_archive(Some(false)); + object.set_flag_hidden(Some(true)); + object.inode_mut().set_flag_immutable(Some(true)); + object.inode_mut().set_flag_no_cow(Some(false)); + object.set_flag_system(Some(true)); // The partition is read-only, which gptFlags says as well where the // manifest records both. - object.gpt = Some(Box::new(GptPartition { + object.set_gpt(Some(GptPartition { label: Some("label".into()), uuid: Some(uuid(1)), type_uuid: Some(uuid(2)), @@ -440,8 +592,8 @@ pub(crate) mod testing { no_auto: Some(true), grow_file_system: Some(true), })); - object.inode.read_only = Some(true); - object.contents = vec![ + object.inode_mut().set_read_only(Some(true)); + object.put_contents(vec![ encoded, ContentsObject { http_headers: vec![ @@ -452,11 +604,11 @@ pub(crate) mod testing { }, ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())), ContentsObject::default(), - ]; - object.sha256 = HELLO.parse().ok(); - object.validity.since_usec = 6; - object.validity.until_usec = Some(7); - object.validity.state = Validity::Revoked; + ]); + object.set_sha256(HELLO.parse().ok()); + object.validity_mut().since_usec = 6; + object.validity_mut().until_usec = Some(7); + object.validity_mut().state = Validity::Revoked; object } } diff --git a/src/uapi16/libuapi16.sym b/src/uapi16/libuapi16.sym new file mode 100644 index 0000000..31b71fe --- /dev/null +++ b/src/uapi16/libuapi16.sym @@ -0,0 +1,152 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +/* + * The symbols of libuapi16.so: the functions uapi16.h declares, each under + * the node of the release that added it. Nothing else is exported. + * + * A node is never changed once it is released. A release that adds + * functions adds a node for them, which names the node before it: + * + * LIBUAPI16_0.1.1 { + * global: + * uapi16_...; + * } LIBUAPI16_0.1.0; + */ + +LIBUAPI16_0.1.0 { +global: + uapi16_manifest_options_new; + uapi16_manifest_options_set_features; + uapi16_manifest_options_set_order; + uapi16_manifest_options_set_sync; + uapi16_manifest_options_free; + uapi16_manifest_generate_at; + uapi16_manifest_generate; + uapi16_manifest_writer_create_at; + uapi16_manifest_writer_open; + uapi16_manifest_writer_add_object; + uapi16_manifest_writer_finish; + uapi16_manifest_writer_free; + uapi16_manifest_report_files; + uapi16_manifest_report_directories; + uapi16_manifest_report_others; + uapi16_manifest_report_bytes; + uapi16_manifest_report_entries_omitted; + uapi16_manifest_report_fields_omitted; + uapi16_manifest_report_free; + uapi16_reader_open; + uapi16_reader_root; + uapi16_reader_has_feature; + uapi16_reader_features; + uapi16_reader_order; + uapi16_reader_require_order; + uapi16_reader_check_validity; + uapi16_reader_next; + uapi16_reader_next_signature; + uapi16_reader_signed_len; + uapi16_reader_free; + uapi16_writer_begin; + uapi16_writer_file; + uapi16_writer_signature; + uapi16_writer_finish; + uapi16_writer_free; + uapi16_signature_new; + uapi16_signature_mechanism; + uapi16_signature_set_key; + uapi16_signature_key; + uapi16_signature_set_data; + uapi16_signature_data; + uapi16_signature_free; + uapi16_file_object_new; + uapi16_file_object_free; + uapi16_file_object_set_name; + uapi16_file_object_name; + uapi16_file_object_set_type; + uapi16_file_object_type; + uapi16_file_object_set_mode; + uapi16_file_object_mode; + uapi16_file_object_set_uid; + uapi16_file_object_uid; + uapi16_file_object_set_gid; + uapi16_file_object_gid; + uapi16_file_object_set_user_name; + uapi16_file_object_user_name; + uapi16_file_object_set_group_name; + uapi16_file_object_group_name; + uapi16_file_object_set_mtime_nsec; + uapi16_file_object_mtime_nsec; + uapi16_file_object_set_size; + uapi16_file_object_size; + uapi16_file_object_set_sha256; + uapi16_file_object_sha256; + uapi16_file_object_set_major; + uapi16_file_object_major; + uapi16_file_object_set_minor; + uapi16_file_object_minor; + uapi16_file_object_set_inode_token; + uapi16_file_object_inode_token; + uapi16_file_object_set_user_xattrs; + uapi16_file_object_add_user_xattr; + uapi16_file_object_user_xattrs; + uapi16_file_object_user_xattr; + uapi16_file_object_set_read_only; + uapi16_file_object_read_only; + uapi16_file_object_set_inode_flags; + uapi16_file_object_inode_flags; + uapi16_file_object_set_dos_attributes; + uapi16_file_object_dos_attributes; + uapi16_file_object_set_target; + uapi16_file_object_set_contents_file; + uapi16_file_object_contents_file; + uapi16_file_object_data_location; + uapi16_file_object_literal; + uapi16_file_object_set_fs_label; + uapi16_file_object_fs_label; + uapi16_file_object_set_fs_uuid; + uapi16_file_object_fs_uuid; + uapi16_file_object_set_fat_serial; + uapi16_file_object_fat_serial; + uapi16_file_object_has_stated_feature; + uapi16_file_object_stated_features; + uapi16_file_object_retain_features; + uapi16_file_object_check_validity; + uapi16_directory_new; + uapi16_directory_open_data; + uapi16_directory_free; + uapi16_data_check_new; + uapi16_data_check_update; + uapi16_data_check_update_zeros; + uapi16_data_check_finish; + uapi16_data_check_free; + uapi16_sha256_new; + uapi16_sha256_update; + uapi16_sha256_update_zeros; + uapi16_sha256_finish; + uapi16_sha256_free; + uapi16_name_compare; + uapi16_features_add; + uapi16_features_remove; + uapi16_features_has; + uapi16_features_next; + uapi16_features_union; + uapi16_features_intersect; + uapi16_features_subtract; + uapi16_features_equal; + uapi16_feature_name; + uapi16_feature_from_name; + uapi16_features_default; + uapi16_features_known; + uapi16_error_kind; + uapi16_error_errno; + uapi16_error_path; + uapi16_error_hardlink_path; + uapi16_error_feature; + uapi16_error_raw_name; + uapi16_error_name_problem; + uapi16_error_field; + uapi16_error_record; + uapi16_error_problem; + uapi16_error_free; +local: + *; +}; diff --git a/src/uapi16/listing.rs b/src/uapi16/listing.rs new file mode 100644 index 0000000..a7e5e17 --- /dev/null +++ b/src/uapi16/listing.rs @@ -0,0 +1,2495 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The file objects of a manifest that is being built. They are added in +//! any order, and they are written in the order of the manifest. +//! +//! A [`Listing`] takes what is added: the root of a tree, the files of a +//! tree, and file objects a caller made. It sorts them by their names, in +//! memory while they fit and through a scratch file once they do not, see +//! the module sort, and notes the hard links among them, see the module +//! hardlink. Once nothing more is added it becomes a [`Writing`], which +//! puts the manifest together a part at a time: it merges what was sorted +//! and decides what the adds left open, since only now every object is next +//! to the others of its name and behind those of its directory. +//! +//! - A name that was added more than once is one file object. Directories +//! merge, and the first one added says what the directory is like. Two +//! files of a tree collapse if their file objects are equal, and are a +//! file that changed if they are not: a walk comes to a name twice only +//! where its directory changed while it was listed. Two file objects of +//! a caller collapse if they are equal. Anything else is two different +//! files for one name, an error. +//! - A directory that files were added below but that was not added itself +//! is made up as a plain one, which says nothing but that it is a +//! directory. Where the features of the manifest give a missing field a +//! meaning, that would claim what nobody read, and is an error instead. +//! - The names of one inode get their `inodeToken`, a counter in the order +//! of the manifest, as the specification asks. The file objects of a +//! caller that share a token are numbered with them. +//! +//! Neither of the two does an unbounded amount of work at once: making +//! room for an add and writing the manifest both take a budget and say +//! whether they are done. What a step does is bounded, though not always +//! by its budget: the records the sort holds in memory, 32 MiB and at most +//! one record more, are sorted in one go before they are written as a run +//! and once nothing more is added, a merge of many runs reads what the +//! buffers of the runs need on top of its budget, see the module sort, and +//! a table of the hard links on disk that begins to double writes out the +//! pages memory holds of it first, see the module hardlink. And neither +//! writes anywhere: the manifest is appended to a string, through the +//! [`Encoder`], and whoever drives this sends it on. That is the shape of +//! the reader's [`Decoder`], which is fed and stepped by its caller. +//! +//! [`Decoder`]: crate::reader::Decoder + +use std::cmp::Ordering; +use std::io; +use std::iter; +use std::ops::ControlFlow; + +use crate::error::{Error, ErrorKind, Field, Problem, TreeProblem}; +use crate::hardlink::{GroupKey, HardlinkTable, Likeness, Noted, Seen}; +use crate::object::{FileObject, FileSystemIdentity, InodeAttributes, InodeType, RootObject, ValidityWindow}; +use crate::record::{RecordReader, RecordWriter}; +use crate::scratch::Scratch; +use crate::sort::{Merge, Sorter, MAX_BODY}; +use crate::sys::OwnFiles; +use crate::tree::{Failure, Status, Subject}; +use crate::writer::Encoder; +use crate::{Features, Name, NameBuf, Order, Sha256, MAX_CONTENTS}; + +/// What separates the components of a name. +const SEPARATOR: u8 = b'/'; +/// What stands for the separator in the key a file object is sorted by, see +/// [`Order::sort_key`]. +const KEY_SEPARATOR: u8 = 0; + +/// The record is of a file of a tree that is not a directory. +const WALKED: u8 = 1 << 0; +/// The file has more names than one and gets an `inodeToken`: the key of +/// its inode is in front of its object. +const LINKED: u8 = 1 << 1; +/// The size statx() gave of the file is in front of its object, which has +/// none, as the manifest does not record sizes. +const SIZED: u8 = 1 << 2; +/// The record is of the root of a tree: its inode attributes and the +/// identity of its file system instead of an object. +const ROOT: u8 = 1 << 3; +/// Every mark a record can have. +const MARKS: u8 = WALKED | LINKED | SIZED | ROOT; + +/// The features that give a field a directory does not have a meaning: it +/// is not read-only, it has no extended attributes, or a flag of it is +/// cleared. A directory that is made up cannot say that. +const SAID_BY_ABSENCE: Features = Features::READ_ONLY + .union(Features::USER_XATTR) + .union(Features::FLAG_HIDDEN) + .union(Features::FLAG_SYSTEM) + .union(Features::FLAG_ARCHIVE) + .union(Features::FLAG_APPEND_ONLY) + .union(Features::FLAG_IMMUTABLE) + .union(Features::FLAG_NO_ATIME) + .union(Features::FLAG_NO_COW) + .union(Features::FLAG_NO_DUMP); +/// How many bytes are kept for the body of the next record once one was +/// put together. An object that needed more does not hold on to them. +const BODY_KEPT: usize = 64 * 1024; + +/// An error for a record of the sort that is not what was written. +fn damaged() -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, "a scratch file of the sort was changed") +} + +impl RootObject { + /// The root file object of the manifest of a listing: that of a root + /// with the inode attributes `inode` in the file system `file_system`, + /// in a manifest that records `features` in the order `order`. + fn listed(inode: InodeAttributes, file_system: FileSystemIdentity, features: Features, order: Order) -> RootObject { + RootObject { + inode, + file_system, + gpt_disk_uuid: None, + order: Some(order), + features: Some(features), + validity: ValidityWindow::default(), + } + } +} + +impl Order { + /// Writes the key a file object with the name `name` is sorted by into + /// `key`: the keys are in the order of their bytes where the names are + /// in this order. + fn sort_key(self, name: &Name, key: &mut Vec) { + key.clear(); + let name = name.as_str().bytes(); + match self { + // The order of the names takes the end of a name before the + // separator and the separator before any other byte. A name + // has no NUL, so the keys have a NUL for the separator. + Order::CodePoint => key.extend(name.map(|byte| if byte == SEPARATOR { KEY_SEPARATOR } else { byte })), + } + } + + /// The name the key `key` was made of. + fn name_of(self, key: &[u8]) -> io::Result { + let name: Vec = match self { + Order::CodePoint => key + .iter() + .map(|&byte| if byte == KEY_SEPARATOR { SEPARATOR } else { byte }) + .collect(), + }; + let name = String::from_utf8(name).map_err(|_| damaged())?; + if name.is_empty() { + return Ok(NameBuf::default()); + } + NameBuf::new(name).map_err(|_| damaged()) + } +} + +/// What is kept of a file of a tree that is not a directory besides its +/// object. +#[derive(Debug)] +struct Walked { + /// The key of its inode in the table of the hard links, where the file + /// has more names than one and gets an `inodeToken`. + key: Option, + /// The size statx() gave of a regular file whose object has none. What + /// a manifest lists is counted also where it records no sizes. + size: Option, +} + +/// What was added under one name. +#[derive(Debug)] +enum Added { + /// The root of a tree. + Root(Box<(InodeAttributes, FileSystemIdentity)>), + /// A file object: of a file of a tree that is not a directory, with + /// what else is known of it, or of a directory of a tree or of a + /// caller, without. + File(Box, Option), +} + +impl Added { + /// What the record with the key `key` and the body `body` is of, in a + /// sort for the order `order`. + fn decode(order: Order, key: &[u8], body: &[u8]) -> io::Result { + let name = order.name_of(key)?; + let mut record = RecordReader(body); + let marks = record.u8()?; + let has = |mark: u8| marks & mark != 0; + // The marks of a file of a tree go together, and the root has + // none of them. Only the root has the name of the root. + let consistent = if has(ROOT) { + marks == ROOT && name.is_root() + } else { + !name.is_root() && (has(WALKED) || !(has(LINKED) || has(SIZED))) + }; + if marks & !MARKS != 0 || !consistent { + return Err(damaged()); + } + if has(ROOT) { + let inode = InodeAttributes::from_record(&mut record)?; + let file_system = FileSystemIdentity::from_record(&mut record)?; + if !record.is_empty() { + return Err(damaged()); + } + return Ok(Added::Root(Box::new((inode, file_system)))); + } + let walked = if has(WALKED) { + let key = if has(LINKED) { + Some(GroupKey::decode(&record.array()?)?) + } else { + None + }; + let size = if has(SIZED) { Some(record.u64()?) } else { None }; + Some(Walked { key, size }) + } else { + None + }; + let object = FileObject::from_record(name, &mut record)?; + Ok(Added::File(Box::new(object), walked)) + } + + /// The name this was added under. + fn name(&self) -> &Name { + match self { + Added::Root(_) => Name::ROOT, + Added::File(object, _) => object.name(), + } + } + + /// Whether this is a directory. + fn is_directory(&self) -> bool { + match self { + Added::Root(_) => true, + Added::File(object, _) => object.inode_type() == InodeType::Directory, + } + } + + /// What it comes to that `later` was added under the name this was + /// added under before. Two directories are one, as the first one says. + /// Two files of a tree are one if their file objects are equal, and a + /// file that changed if they are not: a walk comes to a name twice only + /// where its directory changed while it was listed. Two file objects of + /// a caller are one if they are equal. Everything else is two different + /// files. + fn or(self, later: Added) -> Result { + let duplicate = |name: &Name| { + let message = format!("{}: was added twice, for two different files", Subject(name)); + Error::new(ErrorKind::Tree(TreeProblem::Duplicate), message).named(name.as_str()) + }; + if self.is_directory() && later.is_directory() { + return Ok(self); + } + let same = match (&self, &later) { + (Added::File(first, Some(one)), Added::File(second, Some(other))) => { + if first != second { + return Err(Failure::Changed.into_error(first.name())); + } + // A file that got or lost a name between the two has the + // key of its inode in one of them only. That one stays, so + // that the file gets its token. + if one.key.is_none() && other.key.is_some() { + return Ok(later); + } + true + } + (Added::File(first, None), Added::File(second, None)) => first == second, + _ => false, + }; + if same { + Ok(self) + } else { + Err(duplicate(self.name())) + } + } +} + +/// What a manifest lists, counted per file object. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Totals { + /// The regular files. + pub(crate) files: u64, + /// The directories, the root and those that were made up included. + pub(crate) directories: u64, + /// Everything else: symbolic links, FIFOs, device nodes and sockets. + pub(crate) others: u64, + /// The sizes of the regular files, added up. A file with several names + /// counts once for each. A sum that is too large for the number is the + /// largest number. + pub(crate) bytes: u64, +} + +/// Takes the file objects of a manifest in any order, see the +/// documentation of this module. +#[derive(Debug)] +pub(crate) struct Listing { + features: Features, + order: Order, + scratch: Scratch, + sorter: Sorter, + links: HardlinkTable, + /// The key and the body of a record while it is put together. + key: Vec, + body: Vec, +} + +impl Listing { + /// A listing for a manifest that records `features` and lists its file + /// objects in `order`, with `scratch` for what does not fit into + /// memory. + pub(crate) fn new(features: Features, order: Order, scratch: Scratch) -> Listing { + Listing::with_parts(features, order, scratch, Sorter::new(), HardlinkTable::new()) + } + + fn with_parts(features: Features, order: Order, scratch: Scratch, sorter: Sorter, links: HardlinkTable) -> Listing { + Listing { + features, + order, + scratch, + sorter, + links, + key: Vec::new(), + body: Vec::new(), + } + } + + /// The files the manifest made itself and has open, which its scratch + /// files are among, for whoever walks a tree for the manifest and + /// passes over them. + pub(crate) fn own_files(&self) -> &OwnFiles { + self.scratch.own_files() + } + + /// The same files, for whoever has the manifest pass over one more + /// file, which is kept with them. + pub(crate) fn own_files_mut(&mut self) -> &mut OwnFiles { + self.scratch.own_files_mut() + } + + /// Does a part of what is to do before the next add, and returns + /// whether it is done: the table of the hard links doubles or moves to + /// disk, and the sort writes a run. `budget` is about how many bytes are + /// read and written for each of the two now: a step is bounded, but not + /// held to its budget, see the documentation of this module. + /// + /// A caller that works in steps calls this until it returns true + /// before it adds. An add does all that is left of it at once. + pub(crate) fn make_room(&mut self, budget: u64) -> Result { + let room = + self.links.make_room(&mut self.scratch, budget)? && self.sorter.make_room(&mut self.scratch, budget)?; + Ok(room) + } + + /// Refuses the file object `object` if it is one that no manifest + /// holds whatever else it says, and that is not kept for that reason: + /// an object without a name, which would be taken for the root, and + /// one with more contents objects than there may be, each of which + /// takes far more memory than bytes in a scratch file. + /// + /// A writer refuses both as well. It names the fault of an object that + /// a reader finds first, which can be another one for an object with + /// several. + fn check(object: &FileObject) -> Result<(), Error> { + let name = object.name(); + if name.is_root() { + let message = "a file object has no name".to_owned(); + return Err(Error::manifest(Problem::NoName, message).at(Field::Name)); + } + if object.contents().len() > MAX_CONTENTS { + return Err(Error::too_many_contents(Subject(name)).named(name.as_str())); + } + Ok(()) + } + + /// Puts the body of a record together: the marks `marks` and what + /// `write` writes. The record is of the name `name`. + /// + /// A body that would be longer than the sort takes is not put + /// together. It is of a file object whose record is larger than a + /// record of a manifest may be, see [`MAX_BODY`], and is refused as + /// that. + fn fill(&mut self, name: &Name, marks: u8, write: impl FnOnce(&mut RecordWriter<'_>)) -> Result<(), Error> { + self.body.clear(); + let mut record = RecordWriter::new(&mut self.body, MAX_BODY); + record.u8(marks); + write(&mut record); + if record.is_cut() { + self.body.clear(); + self.body.shrink_to(BODY_KEPT); + let too_large = Error::record_too_large(); + return Err(if name.is_root() { + too_large + } else { + too_large.named(name.as_str()) + }); + } + Ok(()) + } + + /// Hands the record that was put together, which is of the name `name`, + /// to the sort. + fn push(&mut self, name: &Name) -> Result<(), Error> { + self.order.sort_key(name, &mut self.key); + let pushed = self.sorter.push(&mut self.scratch, &self.key, &self.body); + self.body.clear(); + self.body.shrink_to(BODY_KEPT); + Ok(pushed?) + } + + /// Adds the root of a tree: `inode` are its inode attributes and + /// `file_system` is the identity of its file system. Everything else a + /// root file object says is what the listing was made with. + pub(crate) fn add_root(&mut self, inode: &InodeAttributes, file_system: &FileSystemIdentity) -> Result<(), Error> { + self.fill(Name::ROOT, ROOT, |record| { + inode.to_record(record); + file_system.to_record(record); + })?; + self.push(Name::ROOT) + } + + /// Adds the root as a caller describes it: `inode` are its inode + /// attributes and `file_system` is the identity of its file system. + /// + /// The root is checked as a writer checks the root file object it + /// begins a manifest with, see [`RootObject::check_alone`], and one + /// that is refused is not added. The body of its record is put together + /// first, as for a file object of a caller, see + /// [`Listing::add_given`]. + pub(crate) fn add_given_root( + &mut self, + inode: &InodeAttributes, + file_system: &FileSystemIdentity, + ) -> Result<(), Error> { + self.fill(Name::ROOT, ROOT, |record| { + inode.to_record(record); + file_system.to_record(record); + })?; + RootObject::listed(inode.clone(), file_system.clone(), self.features, self.order).check_alone()?; + self.push(Name::ROOT) + } + + /// Adds a file of a tree that is not its root: `object` is its file + /// object, without an `inodeToken`, `status` what statx() said of it, + /// and `data` the hash of its data, if it was hashed. + /// + /// A file with more names than one that is not a directory is a hard + /// link, where the manifest records hard links. It is held against the + /// first name of its inode, and fails if it does not show the same + /// file. + pub(crate) fn add_walked( + &mut self, + object: &FileObject, + status: &Status, + data: Option, + ) -> Result<(), Error> { + let name = object.name(); + debug_assert!(object.inode_token().is_none(), "the listing hands out the tokens"); + Listing::check(object)?; + if object.inode_type() == InodeType::Directory { + self.fill(name, 0, |record| object.to_record(record))?; + return self.push(name); + } + let linked = status.nlink > 1 && self.features.contains(Features::HARDLINK); + let key = linked.then_some(GroupKey::Walked(status.identity)); + // The sizes of the regular files are counted, and an object has + // none where the manifest records no sizes. + let sizeless = object.inode_type() == InodeType::Regular && object.size().is_none(); + let size = sizeless.then_some(status.size); + let marks = [(key.is_some(), LINKED), (size.is_some(), SIZED)]; + let marks = marks + .into_iter() + .filter(|(there, _)| *there) + .fold(WALKED, |marks, (_, mark)| marks | mark); + self.fill(name, marks, |record| { + if let Some(key) = &key { + record.raw(&key.encode()); + } + if let Some(size) = size { + record.u64(size); + } + object.to_record(record); + })?; + if let Some(key) = &key { + // The hash is in the object where the manifest records it. + let likeness = Likeness::walked(Seen::of(status), data.or(object.sha256()), object); + let noted = self.links.note(&mut self.scratch, key, name, &likeness)?; + noted.check(name)?; + } + self.push(name) + } + + /// Adds the file object `object` a caller made. One with an + /// `inodeToken` is a hard link of the other file objects of that + /// token. It is held against the first of them, and fails if it does + /// not have the fields the specification wants them to share. + /// + /// The object is checked as a writer checks it, but for where it + /// comes, see [`FileObject::check_alone`], and one that is refused is + /// not added. Where it comes shows when the manifest is written, which + /// checks every object as a writer does. The body of its record is put + /// together first, which refuses an object that is far too large + /// without writing its record out in full. + pub(crate) fn add_given(&mut self, object: &FileObject) -> Result<(), Error> { + let name = object.name(); + Listing::check(object)?; + self.fill(name, 0, |record| object.to_record(record))?; + object.check_alone(self.features, self.order)?; + if let Some(token) = object + .inode_token() + .filter(|_| object.inode_type() != InodeType::Directory) + { + let key = GroupKey::Given(token); + match self + .links + .note(&mut self.scratch, &key, name, &Likeness::given(object))? + { + // The same name again with another object: what that + // comes to shows when the two are next to each other. + Noted::Differs(first) if first == *name => {} + noted => noted.check(name)?, + } + } + self.push(name) + } + + /// Ends the listing: nothing more is added, and the manifest is + /// written from what was. Nothing is done for that yet: the first step + /// of the [`Writing`] sorts what the sort still has in memory, which + /// is never more than it holds there. Nothing is closed either: the + /// scratch space goes on to the [`Writing`], with the files of the + /// manifest's own. + pub(crate) fn finish(self) -> Writing { + Writing { + features: self.features, + order: self.order, + links: self.links, + merge: self.sorter.finish(), + scratch: self.scratch, + encoder: None, + held: None, + next: None, + last: NameBuf::default(), + last_is_directory: true, + totals: Totals::default(), + over: false, + } + } +} + +/// Writes the manifest of a [`Listing`], see the documentation of this +/// module. +#[derive(Debug)] +pub(crate) struct Writing { + features: Features, + order: Order, + links: HardlinkTable, + merge: Merge, + /// The scratch space of the listing, which nothing is made in any + /// more. It takes back the file the table of the hard links is done + /// with, and keeps the files of the manifest's own open, also those the + /// listing was done with, until the manifest is written or given up: + /// they are closed with this, and none before. + scratch: Scratch, + /// What puts the records together, once the root file object went + /// out. + encoder: Option, + /// What was added under the name the merge is at, as far as it came. + held: Option, + /// What was added under the name before that one, all of it. It goes + /// out next, behind the directories it is in that were not added. + next: Option, + /// The name of the last file object that went out, and whether it is a + /// directory. Every directory that name is in went out as one. + last: NameBuf, + last_is_directory: bool, + totals: Totals, + /// Whether the manifest ended or failed. Nothing more of it is written + /// then. + over: bool, +} + +impl Writing { + /// Appends the next part of the manifest to `text` and returns whether + /// that was the end of it. Then it breaks with what the manifest lists. + /// + /// `budget` is about how many bytes it takes from the sort and appends + /// before it returns. It does one thing at a time, takes a record from + /// the sort or appends one, and goes on while there is budget left. So + /// with any budget it gets further, and without one it does nothing. A + /// hard link is appended with its token, and what the table of the hard + /// links reads from its scratch file and writes to it for that token + /// comes out of the budget as well, see [`HardlinkTable::token_cost`]. + /// What the sort has to do before it hands out its first record is + /// done the same way, a part in each step and for the same budget: it + /// writes a run it was still writing to its end, sorts what it has in + /// memory, and merges its runs in passes where they are too many for + /// one merge, see the module sort. A step is bounded, but not held to + /// its budget: what is in memory is sorted in one go, what the table + /// of the hard links has left to do, the passes and the records each + /// take all of the budget, so the step in which one of them ends does + /// more, and the passes read more than their budget besides, see + /// [`Merge::prepare`]. + /// + /// The errors of what was added come from here if they did not come + /// from the add: a name that was added for two different files, a + /// directory that was not added and cannot be made up, a file where a + /// directory is needed, and everything a writer refuses in a file + /// object. After an error and after the end every call fails. + pub(crate) fn step(&mut self, budget: u64, text: &mut String) -> Result, Error> { + if self.over { + let over = io::Error::other("the manifest ended or failed, and nothing more of it is written"); + return Err(over.into()); + } + let step = self.turns(budget, text); + self.over = !matches!(step, Ok(ControlFlow::Continue(()))); + step + } + + /// What [`Writing::step`] does. + fn turns(&mut self, budget: u64, text: &mut String) -> Result, Error> { + // What the table of the hard links was at when the last name + // came is finished before it hands out a token. + if !self.links.settle(&mut self.scratch, budget)? { + return Ok(ControlFlow::Continue(())); + } + // The sort hands out its first record once its runs are few enough + // for one merge. + if !self.merge.prepare(budget)? { + return Ok(ControlFlow::Continue(())); + } + let mut left = budget; + while left > 0 { + let (before, tokens) = (text.len(), self.links.token_cost()); + let ControlFlow::Continue(taken) = self.turn(text)? else { + return Ok(ControlFlow::Break(self.totals)); + }; + // Every turn counts, also one that only found the end of the + // sort. + let cost = (taken + (text.len() - before)).max(1) as u64; + let tokens = self.links.token_cost() - tokens; + left = left.saturating_sub(cost.saturating_add(tokens)); + } + Ok(ControlFlow::Continue(())) + } + + /// Does one thing: takes a record from the sort, appends a file object + /// to `text`, or ends the manifest. Returns how many bytes it took from + /// the sort, and breaks at the end of the manifest. + fn turn(&mut self, text: &mut String) -> Result, Error> { + if let Some(next) = self.next.take() { + self.write(next, text)?; + return Ok(ControlFlow::Continue(0)); + } + let Some((key, body)) = self.merge.next()? else { + // What the last name was added as, and then the end. + if self.held.is_some() { + self.next = self.held.take(); + return Ok(ControlFlow::Continue(0)); + } + self.encoder(text)?.finish(text)?; + return Ok(ControlFlow::Break(())); + }; + let taken = key.len() + body.len(); + let added = Added::decode(self.order, key, body)?; + self.held = match self.held.take() { + None => Some(added), + Some(first) => match first.name().cmp(added.name()) { + Ordering::Less => { + self.next = Some(first); + Some(added) + } + Ordering::Equal => Some(first.or(added)?), + // The sort hands the names out in their order. + Ordering::Greater => return Err(damaged().into()), + }, + }; + Ok(ControlFlow::Continue(taken)) + } + + /// What puts the records together. Before the first record this starts + /// the manifest with a plain root file object, as no root was added. + fn encoder(&mut self, text: &mut String) -> Result<&mut Encoder, Error> { + match self.encoder { + Some(ref mut encoder) => Ok(encoder), + None => { + // A root that is made up says that it has no label, and + // whatever a directory that is made up says. It has no + // UUID and no volume serial number, which a root need not + // have. + self.make_up(Name::ROOT, SAID_BY_ABSENCE.union(Features::FS_LABEL))?; + self.start(InodeAttributes::default(), FileSystemIdentity::default(), text) + } + } + } + + /// Starts the manifest: appends the root file object, for a root with + /// the inode attributes `inode` in the file system `file_system`. + fn start( + &mut self, + inode: InodeAttributes, + file_system: FileSystemIdentity, + text: &mut String, + ) -> Result<&mut Encoder, Error> { + let root = RootObject::listed(inode, file_system, self.features, self.order); + let encoder = Encoder::begin(&root, text)?; + self.totals.directories += 1; + Ok(self.encoder.insert(encoder)) + } + + /// Checks that the directory `name`, which was not added, can be made + /// up as one that says nothing: the manifest records none of + /// `features`, which give what a directory does not say a meaning. + fn make_up(&self, name: &Name, features: Features) -> Result<(), Error> { + let Some(feature) = (self.features & features).names().next() else { + return Ok(()); + }; + let message = format!( + "{}: the directory was not added, and one that is made up for it cannot say what '{}' records", + Subject(name), + feature + ); + Err(Error::new(ErrorKind::Tree(TreeProblem::MissingParent), message).named(name.as_str())) + } + + /// The first of the directories `name` is in that did not go out, if + /// there is one. The last file object went out with every directory it + /// is in, and `name` comes behind it in the order of the manifest. So + /// the directories of `name` that went out are those the two names + /// share, and the last file object itself if `name` is in it. It has + /// to be a directory then. + fn missing_parent(&self, name: &Name) -> Result, Error> { + let (bytes, last) = (name.as_str().as_bytes(), self.last.as_str().as_bytes()); + let common = iter::zip(bytes, last).take_while(|(one, other)| one == other).count(); + let in_last = common == last.len() && bytes.get(common) == Some(&SEPARATOR); + if in_last && !self.last_is_directory { + let message = format!( + "{}: is not a directory, and files were added below it", + Subject(&self.last) + ); + return Err(Error::new(ErrorKind::Tree(TreeProblem::NotDirectory), message).named(self.last.as_str())); + } + // Where the name goes on behind what went out, and where the next + // directory it is in ends from there. + let from = if in_last { common + 1 } else { common }; + let Some(end) = bytes[from..].iter().position(|&byte| byte == SEPARATOR) else { + return Ok(None); + }; + // What a name starts with up to a separator is a name. + let parent = NameBuf::new(&name.as_str()[..from + end]).map_err(|_| damaged())?; + Ok(Some(parent)) + } + + /// Appends the record of `object`, whose directory went out. + fn put(&mut self, object: FileObject, text: &mut String) -> Result<(), Error> { + self.encoder(text)?.file(&object, text)?; + match object.inode_type() { + InodeType::Regular => self.totals.files += 1, + InodeType::Directory => self.totals.directories += 1, + _ => self.totals.others += 1, + } + self.last_is_directory = object.inode_type() == InodeType::Directory; + self.last = object.into_name(); + Ok(()) + } + + /// Appends what was added under one name, with its `inodeToken` if it + /// is a hard link. If a directory it is in was not added, the first + /// such directory is appended instead, as a plain one, and the turn of + /// what was added comes again. + fn write(&mut self, added: Added, text: &mut String) -> Result<(), Error> { + let (mut object, walked) = match added { + Added::Root(root) => { + // The root comes before every other name, once. + if self.encoder.is_some() { + return Err(damaged().into()); + } + let (inode, file_system) = *root; + return self.start(inode, file_system, text).map(drop); + } + Added::File(object, walked) => (object, walked), + }; + self.encoder(text)?; + if let Some(parent) = self.missing_parent(object.name())? { + self.next = Some(Added::File(object, walked)); + self.make_up(&parent, SAID_BY_ABSENCE)?; + let mut directory = FileObject::new(parent); + directory.set_inode_type(InodeType::Directory); + return self.put(directory, text); + } + let key = match &walked { + Some(walked) => walked.key, + None if object.inode_type() == InodeType::Directory => None, + None => object.inode_token().map(GroupKey::Given), + }; + if let Some(key) = key { + object.set_inode_token(Some(self.links.token(&mut self.scratch, &key)?)); + } + if object.inode_type() == InodeType::Regular { + // What its object says, or else what statx() said of a file + // of a tree. + let size = object.size().or(walked.and_then(|walked| walked.size)); + self.totals.bytes = self.totals.bytes.saturating_add(size.unwrap_or_default()); + } + self.put(*object, text) + } + + /// Gives the scratch files of the manifest back to the scratch space, + /// which empties them: those of the table of the hard links and that + /// of the sort. They are closed with this then. Whoever writes the + /// manifest calls this once it is written or failed, and so does + /// whoever gives up a manifest that is not written. A Writing that is + /// dropped closes the files as they are. + pub(crate) fn give_back(mut self) { + self.links.give_back(&mut self.scratch); + self.merge.give_back(&mut self.scratch); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::hardlink::Limits as TableLimits; + use crate::object::{ContentsObject, ContentsSource, Mode}; + use crate::sort::Limits as SortLimits; + use crate::sys::ScratchFile; + use crate::testing::{name, read_whole, write_whole, OpenFile, TempDir, Whole}; + use crate::tree::{DeviceNumber, Identity, MountId, Timestamp}; + use crate::{MAX_RECORD_SIZE, RECORD_SEPARATOR}; + use rustix::fs::FileType; + use std::env; + use std::fs; + use std::num::NonZeroU64; + use std::process::Command; + use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + use std::time::Instant; + + /// What a test adds to a listing. + #[derive(Clone, Debug)] + enum Add { + Root(Box), + Walked(Box, Status, Option), + Given(Box), + } + + /// How a test has a listing keep what it is given: all of it in + /// memory, or as little as there can be. With little, every record is + /// a run of its own and a merge takes two runs, so that the sort merges + /// in as many passes as there can be. + #[derive(Clone, Copy, Debug, PartialEq)] + enum Memory { + All, + Little, + } + + /// A listing for `features` that keeps what it is given as `memory` + /// says, with its scratch files in `tmp`. + fn listing(features: Features, memory: Memory, tmp: &TempDir) -> Listing { + let scratch = Scratch::beside(ScratchFile::open_directory(&tmp.0).unwrap().into()); + let (sorter, links) = match memory { + Memory::All => (Sorter::new(), HardlinkTable::new()), + Memory::Little => ( + Sorter::with_limits(SortLimits { + memory: 1, + run_buffer: 1, + write_buffer: 1, + runs: 2, + hole: 1, + }), + HardlinkTable::with_limits(TableLimits { + memory: 1, + first_pages: 1, + cached_pages: 1, + }), + ), + }; + Listing::with_parts(features, Order::CodePoint, scratch, sorter, links) + } + + /// Adds `add` to `listing`. + fn add(listing: &mut Listing, add: &Add) -> Result<(), Error> { + match add { + Add::Root(root) => listing.add_root(&root.inode, &root.file_system), + Add::Walked(object, status, data) => listing.add_walked(object, status, *data), + Add::Given(object) => listing.add_given(object), + } + } + + /// Writes all of the manifest of `listing`, with the budget `budget` + /// for a step, and returns it with what it lists, with how many steps + /// it took and with how many records the step appended that appended + /// the most. + fn write(listing: Listing, budget: u64) -> Result<(String, Totals, u64, usize), Error> { + let mut writing = listing.finish(); + let (mut text, mut steps, mut most) = (String::new(), 0, 0); + loop { + steps += 1; + let before = text.len(); + let step = writing.step(budget, &mut text)?; + most = most.max(text[before..].matches(char::from(RECORD_SEPARATOR)).count()); + if let ControlFlow::Break(totals) = step { + return Ok((text, totals, steps, most)); + } + } + } + + /// The manifest of `adds` for `features`, and what it lists. + fn manifest(features: Features, adds: &[Add], memory: Memory) -> Result<(String, Totals), Error> { + // The tests run next to each other, each with directories of its + // own. + static NEXT: AtomicUsize = AtomicUsize::new(0); + let tmp = TempDir::new(&format!("listing-{}", NEXT.fetch_add(1, Relaxed))); + let mut listing = listing(features, memory, &tmp); + for one in adds { + add(&mut listing, one)?; + } + write(listing, u64::MAX).map(|(text, totals, _, _)| (text, totals)) + } + + /// What statx() says of the inode `inode` of a file system a test + /// makes up, a file of the type `file_type` with `nlink` names. + fn status(file_type: FileType, inode: u64, nlink: u32) -> Status { + let time = Timestamp { + seconds: 1_700_000_000, + nanoseconds: 0, + }; + Status { + identity: Identity { + mount: MountId::Unique(1), + device: DeviceNumber { major: 8, minor: 1 }, + inode, + subvolume: None, + }, + file_type, + mode: Mode::from_st_mode(0o644), + nlink, + uid: 0, + gid: 0, + size: 0, + mtime: time, + ctime: time, + btime: Some(time), + rdev: DeviceNumber { major: 0, minor: 0 }, + } + } + + /// The regular file `file_name` of a tree with the data `data`, which + /// is the inode `inode` and has `nlink` names. + fn file(file_name: &str, data: &[u8], inode: u64, nlink: u32) -> Add { + let mut status = status(FileType::RegularFile, inode, nlink); + status.size = data.len() as u64; + let mut object = FileObject::new(name(file_name)); + object.set_size(Some(status.size)); + object.set_sha256(Some(Sha256::digest(data))); + object.inode_mut().set_mode(Some(status.mode)); + Add::Walked(Box::new(object), status, object_hash(data)) + } + + /// The hash of the data `data`, as an add gets it. + fn object_hash(data: &[u8]) -> Option { + Some(Sha256::digest(data)) + } + + /// The directory `directory_name` of a tree with the mode `mode`, + /// which is the inode `inode`. + fn directory(directory_name: &str, mode: u32, inode: u64) -> Add { + let mut status = status(FileType::Directory, inode, 2); + status.mode = Mode::from_st_mode(mode); + let mut object = FileObject::new(name(directory_name)); + object.set_inode_type(InodeType::Directory); + object.inode_mut().set_mode(Some(status.mode)); + Add::Walked(Box::new(object), status, None) + } + + /// The symbolic link `link_name` of a tree to `target`. + fn symlink(link_name: &str, target: &str, inode: u64) -> Add { + let mut status = status(FileType::Symlink, inode, 1); + status.size = target.len() as u64; + let mut object = FileObject::new(name(link_name)); + object.set_inode_type(InodeType::Symlink); + object.set_size(Some(status.size)); + object.put_contents(vec![ContentsObject::new(ContentsSource::Literal(target.into()))]); + Add::Walked(Box::new(object), status, None) + } + + /// A file object a caller made for `given_name`, with the token + /// `token` if it has one. + fn given(given_name: &str, token: u64) -> Add { + let mut object = FileObject::new(name(given_name)); + object.set_size(Some(3)); + object.set_inode_token(NonZeroU64::new(token)); + Add::Given(Box::new(object)) + } + + /// The root of a tree with the mode `mode`. + fn root(mode: u32) -> Add { + let mut root = RootObject::default(); + root.inode.set_mode(Some(Mode::from_st_mode(mode))); + Add::Root(Box::new(root)) + } + + /// The file object of `add`, which is not the root, as the manifest + /// has it, with the token `token` if it has one. + fn listed(add: &Add, token: u64) -> FileObject { + let (Add::Walked(object, _, _) | Add::Given(object)) = add else { + panic!("{:?}", add); + }; + let mut object = (**object).clone(); + object.set_inode_token(NonZeroU64::new(token)); + object + } + + /// A plain directory, as the manifest has one that was made up. + fn plain(directory_name: &str) -> FileObject { + let mut object = FileObject::new(name(directory_name)); + object.set_inode_type(InodeType::Directory); + object + } + + /// The manifest a writer writes for `root` and `objects`, in the code + /// point order. + fn expected(root: &Add, objects: Vec) -> String { + let Add::Root(root) = root else { + panic!("{:?}", root); + }; + let mut root = (**root).clone(); + root.order = Some(Order::CodePoint); + root.features = Some(Features::DEFAULT); + let whole = Whole { + root, + objects, + signatures: Vec::new(), + }; + String::from_utf8(write_whole(&whole).unwrap()).unwrap() + } + + /// The numbers from 0 up to `count` in an order that the number + /// `seed` picks. + fn shuffled(count: usize, seed: u64) -> Vec { + let mut order: Vec = (0..count).collect(); + let mut state = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + for at in (1..count).rev() { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + order.swap(at, (state % (at as u64 + 1)) as usize); + } + order + } + + /// Every order of the numbers from 0 up to `count`. + fn permutations(count: usize) -> Vec> { + let mut all = vec![Vec::new()]; + for number in 0..count { + all = all + .iter() + .flat_map(|order: &Vec| { + (0..=order.len()).map(move |at| { + let mut order = order.clone(); + order.insert(at, number); + order + }) + }) + .collect(); + } + all + } + + /// A tree with everything a listing decides: a root, directories that + /// were added and directories that were not, hard links of files of + /// the tree and of file objects of a caller, an inode with one of its + /// names in the tree, and a symbolic link. Returns what is added for + /// it and the manifest that comes of it. + fn tree() -> (Vec, String) { + let adds = vec![ + root(0o755), + directory("a", 0o750, 10), + file("a/x", b"hello", 11, 1), + symlink("a/l", "x", 12), + file("b/deep/file", b"", 13, 1), + file("h1", b"linked", 14, 2), + file("a/h2", b"linked", 14, 2), + file("z", b"alone", 15, 3), + given("g1", 7), + given("a/g2", 7), + given("c", 0), + ]; + let objects = vec![ + listed(&adds[1], 0), + listed(&adds[9], 1), + listed(&adds[6], 2), + listed(&adds[3], 0), + listed(&adds[2], 0), + plain("b"), + plain("b/deep"), + listed(&adds[4], 0), + listed(&adds[10], 0), + listed(&adds[8], 1), + listed(&adds[5], 2), + listed(&adds[7], 3), + ]; + let expected = expected(&adds[0], objects); + (adds, expected) + } + + /// Whatever order the files of a tree are added in, the manifest is + /// the same, byte for byte, with all of them in memory and with every + /// one of them in a run of its own. It is the manifest a writer writes + /// for the file objects in the order of their names, with the + /// directories that were not added made up and the tokens counted in + /// that order, and a reader takes it as one in the code point order. + #[test] + fn every_order_gives_the_same_manifest() { + let (adds, expected) = tree(); + let features = Features::DEFAULT; + let (text, totals) = manifest(features, &adds, Memory::All).unwrap(); + assert_eq!(text, expected); + assert_eq!( + totals, + Totals { + files: 8, + directories: 4, + others: 1, + bytes: 5 + 6 + 6 + 5 + 3 + 3 + 3 + } + ); + let whole = read_whole(text.as_bytes()).unwrap(); + whole.root.require_order(Order::CodePoint).unwrap(); + assert_eq!(whole.objects.len(), 12); + for seed in 0..300 { + let order = shuffled(adds.len(), seed); + let shuffled: Vec = order.iter().map(|&index| adds[index].clone()).collect(); + let memory = if seed % 3 == 0 { Memory::Little } else { Memory::All }; + let (text, shuffled_totals) = manifest(features, &shuffled, memory).unwrap(); + assert!(text == expected, "{:?}", order); + assert_eq!(shuffled_totals, totals, "{:?}", order); + } + // Every order there is of the files that decide the most: the + // names of the two inodes with tokens and what is below the + // directories that are made up. + let few = [4, 5, 6, 8, 9, 3, 1]; + for order in permutations(few.len()) { + let mut permuted: Vec = order.iter().map(|&index| adds[few[index]].clone()).collect(); + permuted.extend([0, 2, 7, 10].map(|index| adds[index].clone())); + let (text, _) = manifest(features, &permuted, Memory::All).unwrap(); + assert!(text == expected, "{:?}", order); + } + } + + /// The same for a tree of thousands of files that are added in an + /// order of no use, with hard links in every directory. + #[test] + fn a_large_tree_in_any_order() { + let mut adds = vec![root(0o755)]; + let mut inode = 100; + for directory_index in 0..40 { + let directory_name = format!("d{:02}", directory_index); + adds.push(directory(&directory_name, 0o755, inode)); + for file_index in 0..50u64 { + inode += 1; + let file_name = format!("{}/sub{}/f{:02}", directory_name, file_index % 3, file_index); + let data = inode.to_le_bytes(); + // Every fifth file has a second name in the next + // directory. + if file_index % 5 == 0 { + adds.push(file(&file_name, &data, inode, 2)); + let other = format!("d{:02}/link{:02}", (directory_index + 1) % 40, file_index); + adds.push(file(&other, &data, inode, 2)); + } else { + adds.push(file(&file_name, &data, inode, 1)); + } + } + inode += 1; + } + let features = Features::DEFAULT; + let (sorted, totals) = manifest(features, &adds, Memory::All).unwrap(); + assert_eq!((totals.files, totals.directories), (40 * 60, 1 + 40 + 40 * 3)); + for (seed, memory) in [(1, Memory::All), (2, Memory::Little), (3, Memory::Little)] { + let order = shuffled(adds.len(), seed); + let shuffled: Vec = order.iter().map(|&index| adds[index].clone()).collect(); + let (text, shuffled_totals) = manifest(features, &shuffled, memory).unwrap(); + assert!(text == sorted, "{}", seed); + assert_eq!(shuffled_totals, totals); + } + // A reader takes it, and the tokens count up in its order: 1 to + // 400, each on two names. + let whole = read_whole(sorted.as_bytes()).unwrap(); + whole.root.require_order(Order::CodePoint).unwrap(); + let tokens: Vec = whole + .objects + .iter() + .filter_map(|object| object.inode_token().map(NonZeroU64::get)) + .collect(); + assert_eq!(tokens.len(), 800); + let mut highest = 0; + for token in &tokens { + assert!(*token <= highest + 1, "{} after {}", token, highest); + highest = highest.max(*token); + } + assert_eq!(highest, 400); + assert!((1..=400).all(|token| tokens.iter().filter(|&&other| other == token).count() == 2)); + } + + /// A manifest is written a part at a time, and the parts are the + /// manifest. A step does one thing at a time while it has budget left: + /// it takes a record from the sort or appends one to the manifest. So + /// the smallest budget does one thing in a step, and without a budget + /// a step does nothing. The steps before those are the sort's: it + /// merges its runs in passes, a part in each step, and nothing of the + /// manifest is written until it is done. + #[test] + fn writes_in_steps() { + let (adds, expected) = tree(); + let tmp = TempDir::new("listing-steps"); + // Eleven records to take and thirteen to append, two of them for + // directories that are made up, and the two turns that find the + // end of the sort. + let turns = 11 + 13 + 2; + let added = || { + let mut listing = listing(Features::DEFAULT, Memory::Little, &tmp); + for one in &adds { + while !listing.make_room(64).unwrap() { + assert!(!listing.make_room(0).unwrap()); + } + add(&mut listing, one).unwrap(); + } + listing + }; + for (budget, fewest, most) in [(1, turns, turns), (100, 6, turns - 1), (u64::MAX, 1, 1)] { + // How many steps the sort takes before its first record: ten + // runs, two of which it merges at a time, are three passes. + // The smallest budget moves one record in a step, and each of + // the last two passes moves all that are in a run. + let mut writing = added().finish(); + let mut before = 0u64; + while !writing.merge.prepare(budget).unwrap() { + before += 1; + } + assert_eq!(before > 0, budget < u64::MAX, "{}", before); + assert!(budget > 1 || before > 2 * (adds.len() as u64 - 1), "{}", before); + let (text, _, steps, records) = write(added(), budget).unwrap(); + assert_eq!(text, expected); + assert!( + (before + fewest..=before + most).contains(&steps), + "{} {}", + budget, + steps + ); + assert!(budget > 1 || records == 1, "{}", records); + } + // A name as deep as a name goes takes a step for each directory + // that is made up for it. The root is made up with the first. + let deepest = "d/".repeat(2047) + "f"; + let mut deep = listing(Features::DEFAULT, Memory::All, &tmp); + add(&mut deep, &file(&deepest, b"", 54, 1)).unwrap(); + let (text, totals, steps, records) = write(deep, 1).unwrap(); + assert_eq!((totals.directories, totals.files), (2048, 1)); + assert_eq!((steps, records), (1 + 2048 + 2, 2)); + assert_eq!(read_whole(text.as_bytes()).unwrap().objects.len(), 2048); + // Without a budget nothing happens, and after the end nothing can. + let mut listing = listing(Features::DEFAULT, Memory::All, &tmp); + add(&mut listing, &adds[0]).unwrap(); + let mut writing = listing.finish(); + let mut text = String::new(); + assert_eq!(writing.step(0, &mut text).unwrap(), ControlFlow::Continue(())); + assert!(text.is_empty()); + assert!(matches!( + writing.step(u64::MAX, &mut text).unwrap(), + ControlFlow::Break(_) + )); + let written = text.clone(); + for budget in [0, 1, u64::MAX] { + let after = writing.step(budget, &mut text).unwrap_err(); + assert_eq!(after.kind(), ErrorKind::Io); + assert_eq!(text, written); + } + } + + /// What the table of the hard links was at when the last name came is + /// finished a part at a time as well, before the first record goes + /// out. + #[test] + fn settles_the_table_in_steps() { + let tmp = TempDir::new("listing-settles"); + let scratch = Scratch::beside(ScratchFile::open_directory(&tmp.0).unwrap().into()); + let table = HardlinkTable::with_limits(TableLimits { + memory: 1, + first_pages: 1, + cached_pages: 1, + }); + let features = Features::DEFAULT; + let mut listing = Listing::with_parts(features, Order::CodePoint, scratch, Sorter::new(), table); + // Hard links are added until the table begins to double, which it + // does a page at a time with this budget. The sort has room. + let mut adds = Vec::new(); + while adds.len() < 500 || listing.make_room(1).unwrap() { + let inode = adds.len() as u64; + adds.push(file(&format!("f{:05}", inode), b"x", 5000 + inode, 2)); + add(&mut listing, &adds[adds.len() - 1]).unwrap(); + } + let mut writing = listing.finish(); + let (mut text, mut steps) = (String::new(), 0); + while text.is_empty() { + assert_eq!(writing.step(1, &mut text).unwrap(), ControlFlow::Continue(())); + steps += 1; + } + // Two records are taken before the first one goes out, and the + // table has dozens of pages. + assert!(steps > 3 + 16, "{}", steps); + while writing.step(u64::MAX, &mut text).unwrap().is_continue() {} + let (expected, _) = manifest(features, &adds, Memory::All).unwrap(); + assert!(text == expected); + } + + /// A step pays for the pages the table of the hard links reads from its + /// scratch file and writes to it for the tokens it hands out. So a step + /// over a table on disk that holds one page in memory reads and writes + /// about its budget for them, and appends few hard links. The tokens of + /// a table in memory cost nothing, and a step over one appends what its + /// budget says. + #[test] + fn steps_pay_for_the_pages_of_the_hard_links() { + /// How many hard links the manifest lists. + const LINKS: u64 = 2_000; + /// The budget of a step, which a manifest of that many takes many + /// of. + const BUDGET: u64 = 64 * 1024; + /// How much more than its budget a step pays for tokens at most: + /// its last turn begins with budget left and pays for all the pages + /// its token takes, more than two where pages overflowed. + const OVER: u64 = BUDGET; + /// What a page of the table costs: as many bytes as it has. + const PAGE: u64 = 4096; + let adds: Vec = (0..LINKS) + .map(|inode| file(&format!("f{:05}", inode), b"x", 5000 + inode, 2)) + .collect(); + let features = Features::DEFAULT; + let (expected, _) = manifest(features, &adds, Memory::All).unwrap(); + for on_disk in [false, true] { + let tmp = TempDir::new(&format!("listing-token-cost-{}", on_disk)); + let scratch = Scratch::beside(ScratchFile::open_directory(&tmp.0).unwrap().into()); + let table = if on_disk { + HardlinkTable::with_limits(TableLimits { + memory: 1, + first_pages: 1, + cached_pages: 1, + }) + } else { + HardlinkTable::new() + }; + let mut listing = Listing::with_parts(features, Order::CodePoint, scratch, Sorter::new(), table); + for one in &adds { + add(&mut listing, one).unwrap(); + } + // What the table has left to do is none of this. + while !listing.make_room(u64::MAX).unwrap() {} + let mut writing = listing.finish(); + let mut text = String::new(); + let (mut steps, mut paid) = (0, 0); + loop { + let (before, tokens) = (text.len(), writing.links.token_cost()); + let step = writing.step(BUDGET, &mut text).unwrap(); + let (appended, tokens) = ((text.len() - before) as u64, writing.links.token_cost() - tokens); + steps += 1; + paid += tokens; + assert!(tokens <= BUDGET + OVER, "{} at step {}", tokens, steps); + if step.is_break() { + break; + } + // The first step sorts, and appends nothing yet. + if !on_disk && steps > 1 { + assert!( + tokens == 0 && appended >= BUDGET / 4, + "{} {} at step {}", + tokens, + appended, + steps + ); + } + } + assert!(text == expected); + if on_disk { + // A page read for nearly every token, and one written. + assert!(paid >= LINKS * PAGE, "{}", paid); + assert!(steps >= paid / (BUDGET + OVER), "{} {}", steps, paid); + } + } + } + + /// A manifest that failed fails from there on: no later step goes on + /// with what is left and ends a manifest that lacks what failed. + #[test] + fn nothing_follows_an_error() { + let tmp = TempDir::new("listing-errors"); + let mut listing = listing(Features::DEFAULT, Memory::All, &tmp); + for one in [ + file("a", b"", 80, 1), + file("b", b"", 81, 1), + given("b", 0), + file("c", b"", 83, 1), + ] { + add(&mut listing, &one).unwrap(); + } + let mut writing = listing.finish(); + let mut text = String::new(); + let first = loop { + match writing.step(1, &mut text) { + Ok(step) => assert_eq!(step, ControlFlow::Continue(())), + Err(e) => break e, + } + }; + assert_eq!(first.kind(), ErrorKind::Tree(TreeProblem::Duplicate)); + assert_eq!(first.name(), Some("b")); + let written = text.clone(); + for _ in 0..3 { + assert_eq!(writing.step(u64::MAX, &mut text).unwrap_err().kind(), ErrorKind::Io); + assert_eq!(text, written); + } + // What was written before is no manifest: it has no trailer. + assert!(read_whole(text.as_bytes()).is_err()); + } + + /// The order of the manifest is that of the names and not that of + /// their bytes: a directory comes right before what is below it, also + /// where other names have a byte that is smaller than the separator. + #[test] + fn the_order_of_the_names() { + let names = [ + "a", + "a/b", + "a/b/c", + "a/b c", + "a/b-c", + "a/b.c", + "a/b0", + "a b", + "a-b", + "a.b", + "a0", + "a\u{1F600}", + ]; + let adds: Vec = (0u64..) + .zip(names) + .map(|(inode, name)| match name { + "a" | "a/b" => directory(name, 0o755, 90 + inode), + _ => file(name, b"", 90 + inode, 1), + }) + .collect(); + for seed in 0..20 { + let order = shuffled(adds.len(), seed); + let shuffled: Vec = order.iter().map(|&index| adds[index].clone()).collect(); + let memory = if seed % 2 == 0 { Memory::Little } else { Memory::All }; + let (text, _) = manifest(Features::DEFAULT, &shuffled, memory).unwrap(); + let whole = read_whole(text.as_bytes()).unwrap(); + whole.root.require_order(Order::CodePoint).unwrap(); + let listed: Vec<&str> = whole.objects.iter().map(|object| object.name().as_str()).collect(); + assert_eq!(listed, names); + } + } + + /// A manifest nothing was added to is that of an empty tree, with a + /// plain root. + #[test] + fn nothing_added() { + let (text, totals) = manifest(Features::DEFAULT, &[], Memory::All).unwrap(); + assert_eq!( + text, + concat!( + "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", + "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + ) + ); + assert_eq!( + totals, + Totals { + directories: 1, + ..Totals::default() + } + ); + // The features the listing was made for are those of the manifest. + let tmp = TempDir::new("listing-options"); + let scratch = Scratch::beside(ScratchFile::open_directory(&tmp.0).unwrap().into()); + let features = Features::DEFAULT | Features::MTIME; + let listing = Listing::new(features, Order::CodePoint, scratch); + let (text, _, _, _) = write(listing, u64::MAX).unwrap(); + let whole = read_whole(text.as_bytes()).unwrap(); + assert_eq!(whole.root.features(), Some(features)); + } + + /// The `inodeToken`s count up in the order of the manifest, over the + /// inodes of a tree and the tokens of a caller alike, whatever the + /// tokens of the caller were. A file with other names outside the tree + /// has a token of its own. Without the feature nothing has a token. + #[test] + fn tokens_in_the_order_of_the_manifest() { + let adds = [ + file("c", b"A", 20, 2), + file("a", b"A", 20, 2), + file("b", b"B", 21, 5), + given("d", 900), + given("aa", 900), + given("e", 3), + file("f", b"F", 22, 1), + ]; + let tokens = |features, adds: &[Add]| { + let (text, _) = manifest(features, adds, Memory::All).unwrap(); + let whole = read_whole(text.as_bytes()).unwrap(); + let tokens = whole.objects.iter().map(|object| { + let token = object.inode_token().map_or(0, NonZeroU64::get); + (object.name().as_str().to_owned(), token) + }); + tokens.collect::>() + }; + let named = |pairs: &[(&str, u64)]| -> Vec<(String, u64)> { + pairs.iter().map(|(name, token)| (name.to_string(), *token)).collect() + }; + assert_eq!( + tokens(Features::DEFAULT, &adds), + named(&[("a", 1), ("aa", 2), ("b", 3), ("c", 1), ("d", 2), ("e", 4), ("f", 0)]) + ); + // Without hard links recorded, the files of a tree have no token, + // and a file object with one is refused when it is added. + let without = Features::DEFAULT.without(Features::HARDLINK); + assert_eq!(tokens(without, &adds[..3]), named(&[("a", 0), ("b", 0), ("c", 0)])); + let refused = manifest(without, &adds, Memory::All).unwrap_err(); + assert_eq!(refused.kind(), ErrorKind::Manifest(Problem::UnlistedFeature)); + assert_eq!(refused.name(), Some("d")); + } + + /// A name of an inode that does not show the file its first name + /// showed fails when it is added, and names both. So does a file + /// object that does not agree with the first one of its token. + #[test] + fn hard_links_that_differ() { + let tmp = TempDir::new("listing-links"); + for memory in [Memory::All, Memory::Little] { + let mut listing = listing(Features::DEFAULT, memory, &tmp); + add(&mut listing, &file("first", b"data", 30, 2)).unwrap(); + add(&mut listing, &file("second", b"data", 30, 2)).unwrap(); + let e = add(&mut listing, &file("third", b"other", 30, 2)).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::HardlinkMismatch)); + assert_eq!((e.name(), e.hardlink_name()), (Some("third"), Some("first"))); + // The first name again, as another file. + let e = add(&mut listing, &file("first", b"other", 30, 2)).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::Changed)); + // Another inode is another file. + add(&mut listing, &file("fourth", b"other", 31, 2)).unwrap(); + add(&mut listing, &given("g1", 5)).unwrap(); + let Add::Given(mut other) = given("g2", 5) else { + unreachable!() + }; + other.set_size(Some(4)); + let e = listing.add_given(&other).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::HardlinkMismatch)); + assert_eq!((e.name(), e.hardlink_name()), (Some("g2"), Some("g1"))); + // The token of a caller and the inode of a tree are apart. + add(&mut listing, &given("g3", 30)).unwrap(); + } + // What is not a hard link is not held against anything: a + // directory, a file with one name, and any file where the + // manifest records no hard links. + let mut listing = listing(Features::DEFAULT.without(Features::HARDLINK), Memory::All, &tmp); + add(&mut listing, &file("first", b"data", 30, 2)).unwrap(); + add(&mut listing, &file("second", b"other", 30, 2)).unwrap(); + } + + /// The same name added twice is one file object if it is one file: + /// two directories, two files of a tree whose file objects are equal, + /// or two equal file objects of a caller. Two files of a tree that are + /// not equal are a file that changed, since a walk comes to a name + /// twice only where its directory changed while it was listed, and + /// anything else is two files with one name. + #[test] + fn the_same_name_twice() { + let features = Features::DEFAULT; + let first = |adds: &[Add]| manifest(features, adds, Memory::All).map(|(text, _)| text); + let kind = |adds: &[Add]| { + let e = first(adds).unwrap_err(); + assert_eq!(e.name(), Some("n"), "{}", e); + e.kind() + }; + let once = first(&[file("n", b"data", 40, 1)]).unwrap(); + // Two files of a tree with equal file objects are one file, + // whichever inodes they are, also with more names than one. + assert_eq!( + first(&[file("n", b"data", 40, 1), file("n", b"data", 40, 1)]).unwrap(), + once + ); + assert_eq!(first(&vec![file("n", b"data", 40, 1); 5]).unwrap(), once); + assert_eq!( + first(&[file("n", b"data", 40, 1), file("n", b"data", 41, 1)]).unwrap(), + once + ); + let linked = first(&[file("n", b"data", 40, 2)]).unwrap(); + assert_eq!( + first(&[file("n", b"data", 40, 2), file("n", b"data", 40, 2)]).unwrap(), + linked + ); + // A file that got or lost a name between the two has more names + // than one in one of them only. That one stays, whichever came + // first, so the file has its token. + for nlinks in [[1, 2], [2, 1]] { + let twice = nlinks.map(|nlink| file("n", b"data", 40, nlink)); + assert_eq!(first(&twice).unwrap(), linked, "{:?}", nlinks); + } + // With file objects that are not equal they are a file that + // changed: other data, another mode, another type. + let changed = ErrorKind::Tree(TreeProblem::Changed); + assert_eq!(kind(&[file("n", b"data", 40, 1), file("n", b"DATA", 40, 1)]), changed); + assert_eq!(kind(&[file("n", b"data", 40, 1), file("n", b"DATA", 41, 1)]), changed); + // Also where only one of the two has more names than one. + assert_eq!(kind(&[file("n", b"data", 40, 1), file("n", b"DATA", 40, 2)]), changed); + assert_eq!(kind(&[file("n", b"data", 40, 2), file("n", b"DATA", 40, 1)]), changed); + let Add::Walked(mut object, status, data) = file("n", b"data", 40, 1) else { + unreachable!() + }; + object.inode_mut().set_mode(Some(Mode::from_st_mode(0o600))); + assert_eq!( + kind(&[file("n", b"data", 40, 1), Add::Walked(object, status, data)]), + changed + ); + assert_eq!(kind(&[file("n", b"data", 40, 1), symlink("n", "data", 40)]), changed); + // Directories are one, as the first one that was added says. + let merged = first(&[directory("n", 0o700, 42), directory("n", 0o755, 43)]).unwrap(); + assert_eq!(merged, first(&[directory("n", 0o700, 42)]).unwrap()); + assert_ne!( + merged, + first(&[directory("n", 0o755, 43), directory("n", 0o700, 42)]).unwrap() + ); + let Add::Given(mut made) = given("n", 0) else { + unreachable!() + }; + made.set_inode_type(InodeType::Directory); + made.set_size(None); + assert_eq!( + first(&[directory("n", 0o700, 42), Add::Given(made.clone())]).unwrap(), + merged + ); + // A directory and a file, and a file of a tree and a file object + // of a caller. + let duplicate = ErrorKind::Tree(TreeProblem::Duplicate); + assert_eq!(kind(&[directory("n", 0o700, 42), file("n", b"data", 40, 1)]), duplicate); + assert_eq!(kind(&[file("n", b"data", 40, 1), Add::Given(made)]), duplicate); + assert_eq!(kind(&[file("n", b"data", 40, 1), given("n", 0)]), duplicate); + // File objects of a caller are one if they are equal. + let made = first(&[given("n", 0)]).unwrap(); + assert_eq!(first(&[given("n", 0), given("n", 0)]).unwrap(), made); + let Add::Given(mut other) = given("n", 0) else { + unreachable!() + }; + other.inode_mut().set_uid(Some(1)); + assert_eq!(kind(&[given("n", 0), Add::Given(other)]), duplicate); + assert_eq!(kind(&[given("n", 5), given("n", 6)]), duplicate); + // With a token they are held against each other when they are + // added, and what that leaves open shows when they are written. + let tokened = first(&[given("n", 5)]).unwrap(); + assert_eq!(first(&[given("n", 5), given("n", 5)]).unwrap(), tokened); + let Add::Given(mut other) = given("n", 5) else { + unreachable!() + }; + other.set_size(Some(4)); + assert_eq!(kind(&[given("n", 5), Add::Given(other)]), duplicate); + } + + /// The record of a file of a tree that is not a directory is its file + /// object behind a mark. The key of its inode is in between where the + /// file has more names than one and the manifest records hard links, + /// and its size where it is a regular file whose object has none. + /// Nothing else that statx() says of it is kept. A directory of a tree + /// and a file object of a caller are their file objects alone. + #[test] + fn records_of_the_files_of_a_tree() { + let tmp = TempDir::new("listing-records"); + let record = |features: Features, add: &Add| { + let mut listing = listing(features, Memory::All, &tmp); + self::add(&mut listing, add).unwrap(); + let mut writing = listing.finish(); + while !writing.merge.prepare(u64::MAX).unwrap() {} + let (_, body) = writing.merge.next().unwrap().unwrap(); + body.to_vec() + }; + let bytes = |object: &FileObject| { + let mut bytes = Vec::new(); + object.to_record(&mut RecordWriter::new(&mut bytes, MAX_BODY)); + bytes + }; + let features = Features::DEFAULT; + let Add::Walked(object, status, data) = file("n", b"data", 40, 2) else { + unreachable!() + }; + let mut unsized_object = object.clone(); + unsized_object.set_size(None); + let once = Status { nlink: 1, ..status }; + let key = GroupKey::Walked(status.identity).encode(); + let size = status.size.to_le_bytes(); + let unlinked = features.without(Features::HARDLINK); + let cases: [(Features, &FileObject, Status, Vec<&[u8]>); 5] = [ + (features, &object, once, vec![&[WALKED]]), + (features, &object, status, vec![&[WALKED | LINKED], &key]), + (unlinked, &object, status, vec![&[WALKED]]), + (features, &unsized_object, once, vec![&[WALKED | SIZED], &size]), + ( + features, + &unsized_object, + status, + vec![&[WALKED | LINKED | SIZED], &key, &size], + ), + ]; + for (features, object, status, front) in cases { + let add = Add::Walked(Box::new(object.clone()), status, data); + assert_eq!(record(features, &add), [front.concat(), bytes(object)].concat()); + } + // A symbolic link whose object has no size keeps none either. + let Add::Walked(mut link, link_status, _) = symlink("l", "target", 41) else { + unreachable!() + }; + link.set_size(None); + let add = Add::Walked(link.clone(), link_status, None); + assert_eq!(record(features, &add), [vec![WALKED], bytes(&link)].concat()); + for add in [directory("d", 0o755, 42), given("g", 0), given("h", 7)] { + let (Add::Walked(object, ..) | Add::Given(object)) = &add else { + unreachable!() + }; + assert_eq!(record(features, &add), [vec![0], bytes(object)].concat()); + } + } + + /// A file object of a caller is checked when it is added, as a writer + /// checks it but for where it comes, and one that a writer refuses is + /// not added: one for each fault a writer finds, those of its contents + /// objects in the field they are in, and a second directory object for + /// a name, which the first one would otherwise hide. What the listing + /// writes after that is what it writes without them. + #[test] + fn file_objects_of_a_caller_that_are_refused() { + type Give = fn(&mut FileObject); + let cases: [(Give, Problem); 9] = [ + ( + |o| { + o.put_contents(vec![ContentsObject::new(ContentsSource::Literal(vec![ + 0; + MAX_RECORD_SIZE + ]))]) + }, + Problem::RecordTooLarge, + ), + ( + |o| o.inode_mut().set_user_name(Some("u\u{fdd0}".into())), + Problem::InvalidString, + ), + ( + |o| { + o.put_contents(vec![ContentsObject { + http_headers: vec![("A".into(), "b".into()), ("A".into(), "c".into())], + ..ContentsObject::new(ContentsSource::Url("https://example.com/x".into())) + }]); + }, + Problem::DuplicateKey, + ), + ( + |o| { + o.put_contents(vec![ContentsObject { + http_headers: vec![("A".into(), "b".into())], + ..ContentsObject::new(ContentsSource::File(name("a"))) + }]); + }, + Problem::InvalidContents, + ), + (|o| o.inode_mut().set_uid(Some(65535)), Problem::FieldOutOfRange), + (|o| o.set_inode_type(InodeType::Fifo), Problem::FieldNotPermitted), + ( + |o| { + o.inode_mut().set_mode(Some(Mode::from_st_mode(0o644))); + o.inode_mut().set_read_only(Some(true)); + }, + Problem::Contradiction, + ), + (|o| o.inode_mut().set_read_only(Some(false)), Problem::UnlistedFeature), + ( + |o| { + o.set_inode_type(InodeType::Symlink); + o.set_size(None); + }, + Problem::NoTarget, + ), + ]; + let features = Features::DEFAULT | Features::MODE; + let kept = [root(0o755), directory("n", 0o700, 42), given("x", 0)]; + let (expected, _) = manifest(features, &kept, Memory::All).unwrap(); + let tmp = TempDir::new("listing-refused"); + let mut listing = listing(features, Memory::All, &tmp); + for one in &kept { + add(&mut listing, one).unwrap(); + } + for (give, problem) in cases { + let Add::Given(mut object) = given("refused", 0) else { + unreachable!() + }; + give(&mut object); + let e = listing.add_given(&object).unwrap_err(); + assert_eq!( + (e.kind(), e.name()), + (ErrorKind::Manifest(problem), Some("refused")), + "{}", + e + ); + assert_eq!(e.record_number(), None, "{}", e); + } + // A literal that is not the data its hash is of, and a contents + // object that refers to the root. + let contents: [(Give, Problem, Field); 2] = [ + ( + |o| { + o.put_contents(vec![ContentsObject { + original_sha256: Some(Sha256::digest(b"abc")), + ..ContentsObject::new(ContentsSource::Literal(b"xyz".to_vec())) + }]); + }, + Problem::Contradiction, + Field::Literal, + ), + ( + |o| o.put_contents(vec![ContentsObject::new(ContentsSource::File(NameBuf::default()))]), + Problem::InvalidContents, + Field::File, + ), + ]; + for (give, problem, field) in contents { + let Add::Given(mut object) = given("refused", 0) else { + unreachable!() + }; + give(&mut object); + let e = listing.add_given(&object).unwrap_err(); + assert_eq!( + (e.kind(), e.field(), e.name()), + (ErrorKind::Manifest(problem), Some(field), Some("refused")), + "{}", + e + ); + } + // A second directory object of a caller for a name, with an ID the + // specification does not permit. + let Add::Given(mut second) = given("n", 0) else { + unreachable!() + }; + second.set_inode_type(InodeType::Directory); + second.set_size(None); + second.inode_mut().set_uid(Some(65535)); + let e = listing.add_given(&second).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::FieldOutOfRange), "{}", e); + assert!(e.to_string().starts_with("file object (n): "), "{}", e); + let (text, _, _, _) = write(listing, u64::MAX).unwrap(); + assert_eq!(text, expected); + } + + /// A directory that files were added below and that was not added is + /// made up, however deep, unless the manifest records a feature that + /// gives what a plain directory does not say a meaning. The root is + /// made up the same way. It cannot say that its file system has no + /// label then, and it has no UUID and no volume serial number, which a + /// root need not have. + #[test] + fn directories_that_were_not_added() { + let deep = [ + file("a/b/c/d", b"", 50, 1), + file("a/b/e", b"", 51, 1), + file("a/f/g", b"", 52, 1), + ]; + let (text, totals) = manifest(Features::DEFAULT, &deep, Memory::All).unwrap(); + let whole = read_whole(text.as_bytes()).unwrap(); + let names: Vec<&str> = whole.objects.iter().map(|object| object.name().as_str()).collect(); + assert_eq!(names, ["a", "a/b", "a/b/c", "a/b/c/d", "a/b/e", "a/f", "a/f/g"]); + assert_eq!(whole.objects[1], plain("a/b")); + assert_eq!(whole.root, { + let mut root = RootObject::default(); + root.set_order(Some(Order::CodePoint)); + root + }); + assert_eq!((totals.files, totals.directories), (3, 5)); + // A directory that was added is not made up, wherever it comes. + let mut with = deep.to_vec(); + with.push(directory("a/b", 0o700, 53)); + let (text, _) = manifest(Features::DEFAULT, &with, Memory::All).unwrap(); + let whole = read_whole(text.as_bytes()).unwrap(); + assert_eq!(whole.objects[1].inode().mode(), Some(Mode::from_st_mode(0o700))); + let said_by_absence = [ + Features::READ_ONLY, + Features::USER_XATTR, + Features::FLAG_HIDDEN, + Features::FLAG_SYSTEM, + Features::FLAG_ARCHIVE, + Features::FLAG_APPEND_ONLY, + Features::FLAG_IMMUTABLE, + Features::FLAG_NO_ATIME, + Features::FLAG_NO_COW, + Features::FLAG_NO_DUMP, + ]; + for feature in said_by_absence { + let features = Features::DEFAULT | feature; + // The root comes first, and then the first directory. + let e = manifest(features, &deep, Memory::All).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::MissingParent), "{:?}", feature); + assert_eq!(e.name(), Some("")); + let mut rooted = deep.to_vec(); + rooted.push(root(0o755)); + let e = manifest(features, &rooted, Memory::All).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::MissingParent), "{:?}", feature); + assert_eq!(e.name(), Some("a")); + rooted.extend([directory("a", 0o755, 55), directory("a/b", 0o755, 56)]); + let e = manifest(features, &rooted, Memory::All).unwrap_err(); + assert_eq!(e.name(), Some("a/b/c"), "{:?}", feature); + rooted.extend([directory("a/b/c", 0o755, 57), directory("a/f", 0o755, 58)]); + manifest(features, &rooted, Memory::All).unwrap(); + } + // A root that is made up says that its file system has no label. + // Other directories have none. + let labelled = Features::DEFAULT | Features::FS_LABEL; + let e = manifest(labelled, &deep, Memory::All).unwrap_err(); + assert_eq!( + (e.kind(), e.name()), + (ErrorKind::Tree(TreeProblem::MissingParent), Some("")) + ); + let mut rooted = deep.to_vec(); + rooted.push(root(0o755)); + manifest(labelled, &rooted, Memory::All).unwrap(); + // A root need not have the UUID or the volume serial number of its + // file system where the manifest records them: one that is made up + // has neither, and one that was added without them is taken. + for feature in [Features::FS_UUID, Features::FAT_SERIAL] { + let features = Features::DEFAULT | feature; + for adds in [&deep[..], &[], &rooted[..]] { + let (text, _) = manifest(features, adds, Memory::All).unwrap(); + let root = read_whole(text.as_bytes()).unwrap().root; + assert_eq!( + (root.features(), root.file_system()), + (Some(features), &FileSystemIdentity::default()) + ); + } + } + } + + /// A file that is not a directory cannot have files below it, + /// whether it is a file of a tree or a file object of a caller. + #[test] + fn files_below_a_file() { + for below in ["a/b", "a/b/c/d"] { + for parent in [file("a", b"", 60, 1), symlink("a", "elsewhere", 61), given("a", 0)] { + let adds = [file(below, b"", 62, 1), parent, file("a-sibling", b"", 63, 1)]; + let e = manifest(Features::DEFAULT, &adds, Memory::All).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::NotDirectory), "{}", below); + assert_eq!(e.name(), Some("a")); + } + } + // A directory of the same name next to it is another matter. + let adds = [ + file("a/b", b"", 62, 1), + file("a.txt", b"", 60, 1), + file("a0", b"", 64, 1), + ]; + manifest(Features::DEFAULT, &adds, Memory::All).unwrap(); + } + + /// What a writer refuses in a file object of a caller is refused when + /// the manifest is written, with the name of the object. An object + /// without a name is refused when it is added. + #[test] + fn file_objects_a_writer_refuses() { + let Add::Given(mut dated) = given("dated", 0) else { + unreachable!() + }; + dated.inode_mut().set_mtime_nsec(Some(1)); + let e = manifest(Features::DEFAULT, &[Add::Given(dated.clone())], Memory::All).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::UnlistedFeature)); + assert_eq!(e.name(), Some("dated")); + manifest(Features::DEFAULT | Features::MTIME, &[Add::Given(dated)], Memory::All).unwrap(); + // An object without a name is not the root. It is refused when it + // is added, whatever it is, and leaves the root alone that was + // added. + let tmp = TempDir::new("listing-nameless"); + let mut listing = listing(Features::DEFAULT | Features::READ_ONLY, Memory::All, &tmp); + add(&mut listing, &root(0o755)).unwrap(); + let mut nameless = FileObject::new(NameBuf::default()); + for inode_type in [InodeType::Regular, InodeType::Directory] { + nameless.set_inode_type(inode_type); + for token in [0, 5] { + nameless.set_inode_token(NonZeroU64::new(token)); + let e = listing.add_given(&nameless).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::NoName), "{:?}", inode_type); + assert_eq!((e.name(), e.field()), (None, Some(Field::Name))); + } + } + let (text, totals, _, _) = write(listing, u64::MAX).unwrap(); + let whole = read_whole(text.as_bytes()).unwrap(); + assert_eq!(whole.root.inode().mode(), Some(Mode::from_st_mode(0o755))); + assert_eq!((whole.objects.len(), totals.directories), (0, 1)); + } + + /// A file object whose record is as large as a record of a manifest + /// may be is taken, and one that is larger is refused: when it is + /// written, or already when it is added if it is larger than anything + /// a writer takes, for what a writer refuses it for. + #[test] + fn large_file_objects() { + let literal = |size: usize| { + let Add::Given(mut large) = given("large", 0) else { + unreachable!() + }; + large.set_size(Some(size as u64)); + large.put_contents(vec![ContentsObject::new(ContentsSource::Literal(vec![b'a'; size]))]); + Add::Given(large) + }; + // Three bytes of a literal are four in a record, and the size of a + // large one has seven digits where that of three bytes has one. + let (small, _) = manifest(Features::DEFAULT, &[literal(3)], Memory::All).unwrap(); + let record = small.split_inclusive(char::from(crate::RECORD_END)).nth(1).unwrap(); + let fits = (MAX_RECORD_SIZE - (record.len() - 4 + 6)) / 4 * 3; + for memory in [Memory::All, Memory::Little] { + let (text, _) = manifest(Features::DEFAULT, &[literal(fits), file("z", b"", 72, 1)], memory).unwrap(); + let largest = text.split_inclusive(char::from(crate::RECORD_END)).nth(1).unwrap(); + assert!(MAX_RECORD_SIZE - largest.len() < 4, "{}", largest.len()); + let whole = read_whole(text.as_bytes()).unwrap(); + let read = &whole.objects[0]; + assert_eq!( + (read.name().as_str(), read.size(), read.contents().len()), + ("large", Some(fits as u64), 1) + ); + assert!(read.contents()[0].source == ContentsSource::Literal(vec![b'a'; fits])); + // The next larger one is refused when it is added. + let tmp = TempDir::new("listing-large"); + let mut listing = listing(Features::DEFAULT, memory, &tmp); + let e = add(&mut listing, &literal(fits + 3)).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::RecordTooLarge)); + assert_eq!(e.name(), Some("large")); + } + // What is larger than the sort takes is refused when it is added, + // and so is an object with more contents objects than a manifest + // may have, however small. Neither takes memory beyond that. + let tmp = TempDir::new("listing-largest"); + let mut listing = listing(Features::DEFAULT, Memory::All, &tmp); + for size in [MAX_BODY, 3 * MAX_BODY] { + let e = add(&mut listing, &literal(size)).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::RecordTooLarge)); + assert_eq!(e.name(), Some("large")); + assert!(listing.body.capacity() <= BODY_KEPT, "{}", listing.body.capacity()); + } + let Add::Given(mut many) = given("many", 0) else { + unreachable!() + }; + many.put_contents(vec![ContentsObject::default(); MAX_CONTENTS + 1]); + let e = listing.add_given(&many).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::InvalidContents)); + assert_eq!((e.name(), e.field()), (Some("many"), Some(Field::Contents))); + // An object that is taken gives back what it needed, too. + add(&mut listing, &literal(fits)).unwrap(); + assert!(listing.body.capacity() <= BODY_KEPT, "{}", listing.body.capacity()); + // None of those that were refused left anything behind. + let (text, totals, _, _) = write(listing, u64::MAX).unwrap(); + assert_eq!(read_whole(text.as_bytes()).unwrap().objects.len(), 1); + assert_eq!(totals.files, 1); + } + + /// What a manifest lists is counted for each file object, and the + /// sizes of the regular files are added up as far as a number goes. + #[test] + fn totals() { + let sized = |name: &str, size: u64, inode: u64| { + let Add::Walked(mut object, mut status, data) = file(name, b"", inode, 1) else { + unreachable!() + }; + object.set_size(Some(size)); + status.size = size; + // No test has that much data to hash. + object.set_sha256(Some(Sha256::digest(name.as_bytes()))); + let data = data.and(object.sha256()); + Add::Walked(object, status, data) + }; + let adds = [ + sized("a", 5, 100), + sized("d/b", 7, 101), + symlink("l", "a", 102), + given("g", 0), + directory("e", 0o755, 103), + ]; + let (_, totals) = manifest(Features::DEFAULT, &adds, Memory::All).unwrap(); + assert_eq!( + totals, + Totals { + files: 3, + directories: 3, + others: 1, + bytes: 5 + 7 + 3 + } + ); + // Three files as large as a file gets. + let largest = i64::MAX as u64; + let adds = [ + sized("a", largest, 100), + sized("b", largest, 101), + sized("c", largest, 102), + ]; + let (_, totals) = manifest(Features::DEFAULT, &adds[..2], Memory::All).unwrap(); + assert_eq!(totals.bytes, 2 * largest); + let (_, totals) = manifest(Features::DEFAULT, &adds, Memory::All).unwrap(); + assert_eq!((totals.files, totals.bytes), (3, u64::MAX)); + } + + /// The root of a tree that was added is the root of the manifest, with + /// its inode attributes and the identity of its file system. Added + /// again it is one root, as the first one says. + #[test] + fn roots() { + let features = Features::DEFAULT | Features::FS_LABEL | Features::FS_UUID | Features::MTIME; + let mut first = RootObject::default(); + first.inode.set_mode(Some(Mode::from_st_mode(0o700))); + first.inode.set_mtime_nsec(Some(7)); + first.file_system.label = Some("ESP".into()); + first.file_system.uuid = Some(crate::Uuid::new([9; 16])); + let adds = [Add::Root(Box::new(first.clone())), root(0o755), file("f", b"", 70, 1)]; + let (text, totals) = manifest(features, &adds, Memory::Little).unwrap(); + let whole = read_whole(text.as_bytes()).unwrap(); + first.order = Some(Order::CodePoint); + first.features = Some(features); + assert_eq!(whole.root, first); + assert_eq!((totals.directories, totals.files), (1, 1)); + } + + /// The variable that tells the test binary, run again by [`measured`], + /// how many files to list. + const FILES: &str = "UAPI16_TEST_LISTING_FILES"; + /// What the line starts with that says what was measured, which the + /// harness does not say of a test of this module. + const MEASURED: &str = "listed:"; + /// How many files a directory of the tree that is measured has. + const FILES_IN_DIRECTORY: u64 = 20; + + /// The resident memory of this process that is its own, in bytes, which + /// the kernel reports in kilobytes: RssAnon, without the pages of the + /// files it has mapped. Those of the test binary come and go with the + /// file system it is on, and are none of the listing's. A kernel before + /// Linux 4.5 does not tell the two apart, and all that is resident is + /// taken there. + fn resident() -> u64 { + let status = fs::read_to_string("/proc/self/status").unwrap(); + let field = |name: &str| status.lines().find_map(|line| line.strip_prefix(name)); + let line = field("RssAnon:").or_else(|| field("VmRSS:")).unwrap(); + let kilobytes: u64 = line.trim().trim_end_matches("kB").trim().parse().unwrap(); + kilobytes * 1024 + } + + /// Lists a tree of `count` regular files, twenty to a directory and + /// every fourth of them a hard link, which are added in an order that + /// is as good as random, and writes its manifest. Checks that the + /// manifest lists the tree and that the memory of the process stays + /// within what the sort and the table of the hard links take. + fn list_files(count: u64) { + // A number that count has no factor in common with, so that the + // multiples of it go through all the files. + const STRIDE: u64 = 1_000_003; + assert!(count % FILES_IN_DIRECTORY == 0 && count % STRIDE != 0); + let tmp = TempDir::new("listing-measure"); + let scratch = Scratch::beside(ScratchFile::open_directory(&tmp.0).unwrap().into()); + let before = resident(); + let mut listing = Listing::new(Features::DEFAULT, Order::CodePoint, scratch); + let started = Instant::now(); + let hash = Sha256::digest(b"data"); + let mut most = 0; + for index in 0..count { + let number = index * STRIDE % count; + let name = format!("usr/share/p{:06}/f{:08}", number / FILES_IN_DIRECTORY, number); + // The files 8n and 8n + 1 are the two names of one inode. + let (inode, nlink) = match number % 8 { + 0 => (number, 2), + 1 => (number - 1, 2), + _ => (number, 1), + }; + let mut status = status(FileType::RegularFile, inode, nlink); + status.size = 4; + let mut object = FileObject::new(NameBuf::new(name).unwrap()); + object.set_size(Some(status.size)); + object.set_sha256(Some(hash)); + object.inode_mut().set_mode(Some(status.mode)); + listing.add_walked(&object, &status, Some(hash)).unwrap(); + if index % 4096 == 0 { + most = most.max(resident()); + } + } + let directories = count / FILES_IN_DIRECTORY; + for number in (0..directories).rev() { + let Add::Walked(object, status, _) = directory(&format!("usr/share/p{:06}", number), 0o755, count + number) + else { + unreachable!() + }; + listing.add_walked(&object, &status, None).unwrap(); + } + let added = started.elapsed(); + let mut writing = listing.finish(); + // A megabyte of the manifest at a time, which goes nowhere. + let (mut text, mut size, mut records) = (String::new(), 0, 0u64); + let totals = loop { + text.clear(); + let step = writing.step(1024 * 1024, &mut text).unwrap(); + size += text.len(); + records += text.matches(char::from(RECORD_SEPARATOR)).count() as u64; + most = most.max(resident()); + if let ControlFlow::Break(totals) = step { + break totals; + } + }; + // The root, "usr" and "usr/share" are made up, and a trailer ends + // the manifest. + assert_eq!(records, count + directories + 4); + assert_eq!( + totals, + Totals { + files: count, + directories: directories + 3, + others: 0, + bytes: count * 4 + } + ); + println!( + "{} {} files, {} of them hard links, in {} directories, {:.2} s to add them and {:.2} s to write {} MiB, \ + resident {} KiB before and {} KiB at most", + MEASURED, + count, + count / 4, + directories, + added.as_secs_f64(), + (started.elapsed() - added).as_secs_f64(), + size >> 20, + before / 1024, + most / 1024, + ); + // The records of the sort and the table of the hard links in + // memory, a buffer for each run, the part of the manifest that is + // written, and room for what an allocator keeps around. + const ALLOWED: u64 = 72 * 1024 * 1024; + assert!(most <= before + ALLOWED, "{} -> {}", before, most); + } + + /// Runs the test binary again to list `count` files in a process that + /// does nothing else, so that its memory is that of the listing. + fn measured(count: u64) { + let output = Command::new(env::current_exe().unwrap()) + .args(["--exact", "listing::tests::memory_is_bounded", "--nocapture"]) + .env(FILES, count.to_string()) + .output() + .unwrap(); + let said = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success(), + "{}\n{}", + said, + String::from_utf8_lossy(&output.stderr) + ); + // The harness can have its own words in front on the same line. + if let Some(measured) = said.lines().find_map(|line| line.find(MEASURED).map(|at| &line[at..])) { + println!("{}", measured); + } + } + + /// The memory of a listing is that of its sort and of its table of + /// hard links, however many files it lists. + #[test] + fn memory_is_bounded() { + match env::var(FILES) { + Ok(count) => list_files(count.parse().unwrap()), + Err(_) => measured(20_000), + } + } + + /// The same for a million files. + #[test] + #[ignore = "lists a million files"] + fn memory_is_bounded_for_a_million_files() { + measured(1_000_000); + } + + /// The same for ten million files, with scratch files of gigabytes. + #[test] + #[ignore = "lists ten million files"] + fn memory_is_bounded_for_ten_million_files() { + measured(10_000_000); + } + + /// The listing hands on the files of the manifest's own that its + /// scratch space makes its files for, and none of its own: a scratch + /// file of that scratch space is one of them, and one of another + /// scratch space is not. + #[test] + fn own_files() { + let tmp = TempDir::new("listing-own"); + let scratch_in = || Scratch::beside(ScratchFile::open_directory(&tmp.0).unwrap().into()); + let (mut scratch, mut other) = (scratch_in(), scratch_in()); + let _file = scratch.file().unwrap(); + let made = OpenFile::made_in(&tmp.0); + assert_eq!(made.len(), 1); + let _other_file = other.file().unwrap(); + let both = OpenFile::made_in(&tmp.0); + let others: Vec<_> = both.iter().filter(|file| file.inode != made[0].inode).collect(); + assert_eq!(others.len(), 1); + let listing = Listing::new(Features::DEFAULT, Order::CodePoint, scratch); + let own = listing.own_files(); + assert!(own.contains(&made[0].status).unwrap() && !own.contains(&others[0].status).unwrap()); + assert!(other.own_files().contains(&others[0].status).unwrap()); + } + + /// Ending a listing closes nothing. What writes its manifest keeps the + /// scratch space, and the files of the manifest's own stay open with + /// it, also one that was dropped before, until it is dropped itself. + #[test] + fn the_writing_keeps_the_own_files_open() { + let tmp = TempDir::new("listing-kept"); + let mut scratch = Scratch::beside(ScratchFile::open_directory(&tmp.0).unwrap().into()); + drop(scratch.file().unwrap()); + let listing = Listing::new(Features::DEFAULT, Order::CodePoint, scratch); + let open = OpenFile::made_in(&tmp.0); + assert_eq!(open.len(), 1); + let writing = listing.finish(); + let kept = OpenFile::made_in(&tmp.0); + assert_eq!(kept.len(), 1); + assert_eq!(kept[0].inode, open[0].inode); + drop(writing); + assert!(OpenFile::made_in(&tmp.0).is_empty()); + } + + /// A listing and what writes its manifest can go to another thread. + #[test] + fn send() { + fn send() {} + send::(); + send::(); + send::(); + } + + /// The variable that tells the test binary, run again by + /// [`adds_that_fail_for_the_table`], to do the checks. + const FAILING_WRITES: &str = "UAPI16_TEST_LISTING_FAILING_WRITES"; + + /// How far into a file this process may write at most, as prlimit(1) + /// prints the hard limit of RLIMIT_FSIZE, if it can be asked. + fn hard_write_limit() -> Option { + let pid = std::process::id().to_string(); + let output = Command::new("prlimit") + .args(["--pid", &pid, "--fsize", "--noheadings", "--raw", "--output", "HARD"]) + .output() + .ok()?; + let limit = String::from_utf8_lossy(&output.stdout).trim().to_string(); + (output.status.success() && !limit.is_empty()).then_some(limit) + } + + /// Sets how far into a file this process may write, with prlimit(1): + /// with "0" every write to a file fails with EFBIG, where SIGXFSZ is + /// ignored, and with the hard limit none does that did not before. + /// Returns whether it is set. + fn write_limit(soft: &str) -> bool { + Command::new("prlimit") + .args(["--pid", &std::process::id().to_string(), &format!("--fsize={}:", soft)]) + .status() + .is_ok_and(|status| status.success()) + } + + /// An add of a file object of a caller that fails for the scratch files + /// of the table of the hard links adds nothing and leaves the listing + /// as it was: the adds go on, and the manifest is that of the adds that + /// went through. Here every write to a file fails for every third add, + /// once with one page of the table in memory and once with all of + /// them, so that an add fails where the table writes a page out for + /// the one it needs and where it writes the first names of its groups + /// out. The sort keeps its records in memory, so that the table alone + /// writes. The test binary runs this test again in a process of its + /// own, which ignores SIGXFSZ and sets its own limit with prlimit(1). + /// It is skipped where that can't be done, and where a write past the + /// limit does not fail. + #[test] + fn adds_that_fail_for_the_table() { + if env::var_os(FAILING_WRITES).is_some() { + return check_adds_that_fail_for_the_table(); + } + let script = r#"trap '' XFSZ; exec "$1" --exact listing::tests::adds_that_fail_for_the_table --nocapture"#; + let output = Command::new("sh") + .args(["-c", script, "sh"]) + .arg(env::current_exe().unwrap()) + .env(FAILING_WRITES, "1") + .output() + .unwrap(); + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + eprint!("{}", String::from_utf8_lossy(&output.stderr)); + } + + /// The checks of [`adds_that_fail_for_the_table`]. + fn check_adds_that_fail_for_the_table() { + let Some(hard) = hard_write_limit().filter(|hard| write_limit(hard)) else { + eprintln!("skipping: prlimit(1) can't set the limit of this process"); + return; + }; + // A file system that takes a write past the limit fails no add. + let probe = TempDir::new("listing-failing-writes-probe"); + assert!(write_limit("0")); + let written = fs::write(probe.0.join("probe"), b"x"); + assert!(write_limit(&hard)); + if written.map_err(|e| e.raw_os_error()) != Err(Some(libc::EFBIG)) { + eprintln!("skipping: a write past the limit on the size of a file does not fail with EFBIG here"); + return; + } + // With one page of the table in memory an add fails where a page + // is written out for the one it needs. With all of them in memory + // it fails where the first names are written out, which only a + // few adds do. So each of the two has to fail adds by itself. + let failed = check_failing_writes(&hard, 1); + assert!(failed > 20, "{}", failed); + let failed = check_failing_writes(&hard, 64); + assert!(failed > 0, "{}", failed); + } + + /// The checks of [`adds_that_fail_for_the_table`] for a table that has + /// `cached_pages` of its pages in memory, where `hard` is the limit + /// the writes go through with. Returns how many adds failed. + fn check_failing_writes(hard: &str, cached_pages: usize) -> u64 { + let tmp = TempDir::new("listing-failing-writes"); + let clean_tmp = TempDir::new("listing-failing-writes-clean"); + let scratch = Scratch::beside(ScratchFile::open_directory(&tmp.0).unwrap().into()); + let table = HardlinkTable::with_limits(TableLimits { + memory: 1, + first_pages: 1, + cached_pages, + }); + let mut faulted = Listing::with_parts(Features::DEFAULT, Order::CodePoint, scratch, Sorter::new(), table); + // The same adds without a fault, with everything in memory. + let mut clean = listing(Features::DEFAULT, Memory::All, &clean_tmp); + let (mut failed, mut refused) = (0, 0); + // The names are nearly as long as a name can be, in directories + // that are not added, so that the table writes the first names of + // its groups out every few adds, and some of those writes fail. + let deep = format!("{}/", "y".repeat(200)).repeat(19); + // Another name of the token `token` that does not have the size + // its names have, which is refused with the first name of the + // token where a name of it was added. + let other = |name: String, token: u64| { + let Add::Given(mut object) = given(&name, token) else { + unreachable!() + }; + object.set_size(Some(4)); + Add::Given(object) + }; + const ADDS: u64 = 600; + // The adds, and then one more name for every token with the + // writes going through: every first name is still there. + for index in 0..ADDS + ADDS / 2 { + // Two names for every token, and now and then another name of + // a token of before. + let add = if index >= ADDS { + other(format!("{}check{}", deep, index), 1 + index - ADDS) + } else if index % 7 == 6 { + other(format!("{}late{}", deep, index), 1 + index / 4) + } else { + given(&format!("{}n{}", deep, index), 1 + index / 2) + }; + let Add::Given(object) = &add else { unreachable!() }; + let off = (40..ADDS).contains(&index) && index % 3 == 0; + if off { + assert!(write_limit("0")); + } + // As an add does it: room first, then the object. + let room = loop { + match faulted.make_room(u64::MAX) { + Ok(true) => break Ok(()), + Ok(false) => {} + Err(e) => break Err(e), + } + }; + let result = room.and_then(|()| faulted.add_given(object)); + if off { + assert!(write_limit(hard)); + } + match result { + Ok(()) => clean.add_given(object).unwrap(), + Err(e) if e.io_error().and_then(io::Error::raw_os_error) == Some(libc::EFBIG) => failed += 1, + Err(e) => { + // Refused for what it is: without the fault as well, + // and with the same words. + let other = clean.add_given(object).unwrap_err(); + assert_eq!(e.to_string(), other.to_string(), "{}", index); + refused += 1; + } + } + } + assert!(refused > 20, "{}", refused); + let (text, totals, _, _) = write(faulted, u64::MAX).unwrap(); + let (expected, expected_totals, _, _) = write(clean, u64::MAX).unwrap(); + assert!( + text == expected, + "{} bytes, {} bytes without a fault", + text.len(), + expected.len() + ); + assert_eq!(totals, expected_totals); + eprintln!( + "adds_that_fail_for_the_table: {} pages in memory: {} adds failed with EFBIG, {} were refused", + cached_pages, failed, refused + ); + failed + } +} diff --git a/src/uapi16/manifest.rs b/src/uapi16/manifest.rs new file mode 100644 index 0000000..276ea5d --- /dev/null +++ b/src/uapi16/manifest.rs @@ -0,0 +1,2516 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! Building the manifest of a tree of files on the host. + +use std::fmt; +use std::fs::File; +use std::io::{self, Write}; +use std::ops::ControlFlow; +#[cfg(feature = "capi")] +use std::os::fd::OwnedFd; +use std::os::fd::{AsFd, BorrowedFd}; +use std::path::Path; +#[cfg(feature = "capi")] +use std::sync::Arc; + +use crate::error::{Error, ErrorKind, TreeProblem}; +use crate::listing::{Listing, Totals, Writing}; +use crate::scratch::Scratch; +use crate::sys::NewFile; +use crate::tree::Failure; +use crate::walk::{Add, AddFlags, Omitted, Walker, STEP_BUDGET}; +use crate::{Features, FileObject, FileSystemIdentity, InodeAttributes, Order}; + +/// How to write the manifest of a tree of files on the host: the features +/// it records and the order of its file objects. +/// [`ManifestOptions::new`] gives the default features of the +/// specification, [`Features::DEFAULT`], and the code point order. +/// +/// [`ManifestOptions::create_at`] writes a manifest to a new file, and +/// [`ManifestOptions::open`] to any [`Write`]. Both give a +/// [`ManifestWriter`], which takes the files the manifest lists, and whose +/// [`ManifestWriter::finish`] writes it. [`ManifestOptions::generate_at`] and +/// [`ManifestOptions::generate`] do all of that for one directory. +/// +/// Every feature that systemd-manifest make records can be asked for. +/// [`Features::USER_XATTR`] reads the extended attributes of every file but +/// symbolic links, which have none. A file whose attributes make its record +/// larger than [`MAX_RECORD_SIZE`](crate::MAX_RECORD_SIZE) is +/// [`Problem::RecordTooLarge`](crate::Problem::RecordTooLarge), naming the +/// file: the walk fails where the attributes alone take more than that, and +/// [`ManifestWriter::finish`] otherwise. [`Features::READ_ONLY`] takes the +/// read-only attribute of a regular file on FAT, and the access mode of +/// anything else. The root has no DOS attributes. The label, the UUID and +/// the volume serial number of the file system are read from the directory +/// that is the root, and an empty label gives none. +/// +/// No file is opened for its extended attributes. Those of a file that is +/// open anyway are read from the open file: a directory that is walked +/// into, a regular file whose data is hashed, and a regular file or a +/// directory that is opened for its inode flags, its DOS attributes or the +/// identity of its file system. Those of any other file are read through +/// /proc. Without a /proc they can't be read, and it has to be the one of +/// the kernel: whoever can mount something else there can have such a file +/// recorded with the attributes of another one. +/// +/// The data of a regular file of more than 1 TiB is not hashed. Where the +/// manifest records hashes, or hard links and the file has more than one +/// name, the walk fails at such a file with an [`ErrorKind::Io`] error of +/// EFBIG, before anything is read of it. A sparse file is read in full. +/// +/// A feature that can't be read of a file fails the walk at that file, +/// naming the feature, such as [`Features::FLAG_HIDDEN`] of a file system +/// without DOS attributes. Three things are left out instead, and counted +/// in [`ManifestReport::fields_omitted`]: the name of an owner that the +/// user database of the host does not have, the user and group IDs 65535 +/// and 4294967295, which the specification does not permit, and a +/// modification time before 1970 or after 2554, which `mTimeNSec` can't +/// express. The names of owners are those of the host. +/// [`Features::FS_UUID`] and [`Features::FAT_SERIAL`] are read from the +/// root. A root whose file system has no UUID is written without one, and +/// so is one whose volume serial number can't be read, which only FAT +/// gives. Before Linux 6.9 no UUID can be read. Each is counted in +/// [`ManifestReport::fields_omitted`] as well. A manifest without a root +/// has neither. The features of partitions, such as +/// [`Features::GPT_LABEL`], don't apply to a tree of files: +/// [`ManifestOptions::create_at`], [`ManifestOptions::open`] and the +/// generate functions fail with [`TreeProblem::FeatureNotForTrees`] for +/// them. +/// +/// Building a manifest needs Linux 5.10 or newer. +/// +/// ```no_run +/// use std::fs::File; +/// use std::os::fd::AsFd; +/// use std::path::Path; +/// use uapi16::{AddFlags, Features, ManifestOptions}; +/// +/// let esp = File::open("/efi")?; +/// let out_dir = File::open("/var/lib/manifests")?; +/// let report = ManifestOptions::new() +/// .features(Features::DEFAULT | Features::MTIME) +/// .generate_at(out_dir.as_fd(), Path::new("esp.manifest"), &esp, AddFlags::NONE)?; +/// println!("{} files", report.files()); +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Clone, Debug)] +pub struct ManifestOptions { + features: Features, + order: Order, + sync: bool, +} + +impl ManifestOptions { + /// The features of partitions, in the order of their names, the first + /// of which an error names. + const FOR_PARTITIONS: [Features; 7] = [ + Features::GPT_DISK_UUID, + Features::GPT_FLAG_GROW_FILE_SYSTEM, + Features::GPT_FLAG_NO_AUTO, + Features::GPT_FLAGS, + Features::GPT_LABEL, + Features::GPT_TYPE_UUID, + Features::GPT_UUID, + ]; + + /// Options with the default features of the specification and the code + /// point order. + pub fn new() -> ManifestOptions { + ManifestOptions { + features: Features::DEFAULT, + order: Order::CodePoint, + sync: false, + } + } + + /// The features to record, [`Features::DEFAULT`] unless set. + pub fn features(&mut self, features: Features) -> &mut Self { + self.features = features; + self + } + + /// The order of the file objects, [`Order::CodePoint`], the only one, + /// unless set. + pub fn order(&mut self, order: Order) -> &mut Self { + self.order = order; + self + } + + /// Whether the new file of [`ManifestOptions::create_at`] and + /// [`ManifestOptions::generate_at`] is written to disk before + /// [`ManifestWriter::finish`] returns, so that a crash after that does + /// not lose it. False unless set. The file is synced before it gets its + /// name, so that the name never leads to a manifest that is not all on + /// disk, and once more after it got it, with the directory it is in, so + /// that the name is on disk as well. Nothing else is synced, and + /// [`ManifestOptions::open`] and [`ManifestOptions::generate`] write to + /// a writer of the caller, which the caller syncs. + pub fn sync(&mut self, sync: bool) -> &mut Self { + self.sync = sync; + self + } + + /// A new manifest file `name` in the directory `dir`. It appears at + /// [`ManifestWriter::finish`], with the whole manifest in it. Until then + /// nothing has the name, and a writer that is dropped instead leaves + /// nothing behind. + /// + /// A name with more than one component names a file in a directory + /// below `dir`. The components on the way are opened one at a time, + /// each without following a symbolic link, and the file goes into the + /// directory its last component is in. A symbolic link on the way fails + /// with an [`ErrorKind::Io`] error of ELOOP, and an absolute name and + /// one with `.` or `..` on the way with one of EINVAL. For a file in a + /// directory that is not below `dir`, open that directory and pass it + /// as `dir`. + /// + /// This never replaces a file: where something has the name already, + /// this fails with an [`ErrorKind::Io`] error of EEXIST. To write over + /// a file, open it and use [`ManifestOptions::open`]. + /// + /// On FAT the new file gets the mode the mount gives every file, and + /// it can't be larger than 4 GiB, so a manifest there holds about 2e7 + /// file objects at most: [`ManifestWriter::finish`] fails with EFBIG + /// for more. A tree with more than about 9e6 files that have several + /// names fails with EFBIG already while it is added. + /// + /// A manifest of a large tree takes room on disk while it is built, in + /// the directory the file is in. On a file system without O_TMPFILE, + /// such as FAT, the new file is in that directory under a temporary + /// name until [`ManifestWriter::finish`]. + pub fn create_at(&self, dir: impl AsFd, name: &Path) -> Result, Error> { + self.create_at_dir(dir.as_fd(), name) + } + + /// A manifest that is written to `out`. Nothing is written to `out` + /// before [`ManifestWriter::finish`], and the manifest is complete once + /// that returns. A manifest that `finish()` fails to write is + /// incomplete, and readers refuse it, unless all it lacks is the + /// newline at its end. + /// + /// A manifest of a large tree takes room on disk while it is built, in + /// the directory `TMPDIR` names, or in /var/tmp where it names none. + /// Where it is on FAT, which can't hold a file of more than 4 GiB, a + /// manifest of more than about 3e7 file objects fails with EFBIG, and + /// a tree with more than about 9e6 files that have several names fails + /// with EFBIG already while it is added. A `TMPDIR` that is set is used + /// as it is. It has to be a directory the caller trusts, since whoever + /// controls it can change the manifest. + pub fn open(&self, out: W) -> Result, Error> { + let walker = self.walker(Scratch::temporary())?; + Ok(ManifestWriter { + walker, + out, + new_file: None, + }) + } + + /// The manifest of the directory `top` and everything below it, with + /// `top` as the root, in a new file `name` in the directory `dir`: what + /// [`ManifestOptions::create_at`], a walk of `top` and + /// [`ManifestWriter::finish`] do. + /// + /// The name is checked now, so that a name that is taken fails before + /// the tree is read, and again when the file gets its name. + /// + /// Where the features record [`Features::FLAG_HIDDEN`], + /// [`Features::FLAG_SYSTEM`] or [`Features::FLAG_ARCHIVE`], a tree on a + /// file system without DOS attributes fails before anything is read. + /// + /// A file below `top` is listed as what it is: a regular file, a + /// directory, a symbolic link, a device node, a FIFO or a socket. + /// + /// The walk does not leave the mount `top` is on unless `flags` has + /// [`AddFlags::CROSS_MOUNTS`]. A mount point, a bind mount as well, is + /// found by the mount ID statx() gives. A mount point that is a + /// directory and is not crossed is an empty directory with the + /// attributes of the mounted root. A file that is mounted over another + /// one is the file the mount shows, as there is nothing to walk into: a + /// regular file with its attributes and the hash of its data, and a + /// device node with its attributes and its device numbers. A btrfs + /// subvolume is a directory like any other. Where the walk crosses + /// mount points, a mount can show a directory again inside itself: a + /// directory that is one of the directories it is in is + /// [`TreeProblem::Loop`], naming the one below. + /// + /// The walk mounts nothing. An automount point that nothing is mounted + /// on yet, such as the mount point of a systemd automount unit that was + /// not used so far, is an empty directory with its own attributes, + /// whether mount points are crossed or not. It is not opened, so what + /// is read from the open file, such as an inode flag, can't be read of + /// it. There is one known limit. The walk looks at a directory before it + /// opens it, and a directory that becomes an automount point in between + /// has its file system mounted by that open. The walk fails with + /// [`TreeProblem::Changed`] then. That takes someone who can mount in + /// the mount namespace of the caller, or an automount unit that is + /// started at that moment. + /// + /// Symbolic links are listed with their targets and never followed. A + /// target that can't be read is an error. + /// + /// A file with more than one name that is not a directory is identified + /// by its mount, its device and its inode, and its subvolume where + /// statx() reports one. Its names get one `inodeToken`, numbered in the + /// order of the manifest. Every name of it after the first is held + /// against the first: its type, mode, owner, device numbers, size, + /// modification time and birth time have to be the same, but not its + /// change time, and so do the hash of its data and the fields the + /// specification wants the names of one inode to share. A name that is + /// not the same is [`TreeProblem::HardlinkMismatch`]. A file reached + /// through a bind mount is another file than the one reached through + /// its source. On a file system that gives two files the same device + /// and inode, as NFS can for btrfs snapshots, two files that are the + /// same in everything held against each other are taken for one, and + /// two that are not are [`TreeProblem::HardlinkMismatch`]. An overlayfs + /// over btrfs before Linux 6.10 does that as well: it reports its own + /// device with the inode numbers of btrfs, which repeat from one + /// subvolume to the next, and no subvolume. Where the walk crosses + /// mount points there, a subvolume below another one is + /// [`TreeProblem::Loop`], since the roots of all subvolumes have the + /// same inode number. + /// + /// A name a manifest can't hold, one that is not UTF-8, that is too long, + /// or that has a control character or a noncharacter, is + /// [`TreeProblem::UnwritableName`], unless `flags` has + /// [`AddFlags::GRACEFUL`]. The names the specification reserves for the + /// manifest at the top of a tree, such as `Uapi16Manifest`, are passed + /// over. + /// + /// A file that changes while it is read is [`TreeProblem::Changed`], + /// where the change shows: its size, its modification time, its change + /// time and how many names it has are compared before and after, and + /// the data of a regular file has to end at its size. A directory is + /// compared before each of its entries and once more at the end of its + /// listing, so a rename in it that moves its times stops the walk + /// before the next entry, and then nothing is read twice. A file that + /// its directory lists and that is gone when it is opened is + /// [`TreeProblem::Changed`] as well. [`Changed`](TreeProblem::Changed) + /// is a best effort. A tree that other processes change while it is + /// walked can also fail the walk with another error, such as an + /// [`Io`](ErrorKind::Io) error of ENOENT or ESTALE. + /// + /// Not every change shows in these fields. FAT keeps its times in steps + /// of two seconds and never updates the times of its root directory. + /// FAT also has no change time of its own, so a change that keeps the + /// size of a file and sets its modification time back doesn't show + /// there. On a file system without fine-grained timestamps, such as + /// ramfs, and on every file system before Linux 6.13, two changes + /// within one tick of the clock can leave the same times. A write + /// through a shared mapping to a page that is already dirty moves no + /// time at all. Such a change goes unnoticed: a file can be recorded + /// with the hash of data it never held as a whole, and a directory can + /// list a renamed file twice or not at all. + /// + /// A walk of the directory the new file is in passes over what the + /// manifest keeps there, and over the new file under its temporary + /// name. A manifest that is created inside the tree it describes can + /// make a large walk fail with [`TreeProblem::Changed`] there, since + /// the room it takes changes its own directory while the walk reads it. + pub fn generate_at( + &self, + dir: impl AsFd, + name: &Path, + top: impl AsFd, + flags: AddFlags, + ) -> Result { + self.generate_at_dir(dir.as_fd(), name, top.as_fd(), flags) + } + + /// The manifest of the directory `top` and everything below it, with + /// `top` as the root, written to `out`: what [`ManifestOptions::open`], + /// the walk of [`ManifestOptions::generate_at`] and + /// [`ManifestWriter::finish`] do. + pub fn generate(&self, out: W, top: impl AsFd, flags: AddFlags) -> Result<(W, ManifestReport), Error> { + self.open(out)?.generate(top.as_fd(), flags) + } + + /// Fails for a feature of partitions, which a tree of files does not + /// have. Every way to make a writer asks this before it takes a + /// descriptor, so that it fails the same way where the process has none + /// left. + pub(crate) fn check(&self) -> Result<(), Error> { + let Some(feature) = ManifestOptions::FOR_PARTITIONS + .into_iter() + .find(|&feature| self.features.contains(feature)) + else { + return Ok(()); + }; + let message = format!( + "'{}' is a feature of partitions and does not apply to a tree of files", + feature.names().next().unwrap_or_default() + ); + Err(Error::new(ErrorKind::Tree(TreeProblem::FeatureNotForTrees), message).about(feature)) + } + + /// The walker of a manifest that keeps in `scratch` what does not fit + /// into memory. + fn walker(&self, scratch: Scratch) -> Result { + self.check()?; + let listing = Listing::new(self.features, self.order, scratch); + Ok(Walker::new(self.features, listing)) + } + + /// What [`ManifestOptions::create_at`] does. + fn create_at_dir(&self, dir: BorrowedFd<'_>, name: &Path) -> Result, Error> { + self.create_with(NewFile::create_at, dir, name) + } + + /// [`ManifestOptions::create_at`] for a caller of the C API, which + /// lends the library its directory `dir` until the writer is dropped, + /// see [`NewFile::create_at_lent`]. + #[cfg(feature = "capi")] + pub(crate) fn create_at_lent(&self, dir: &Arc, name: &Path) -> Result, Error> { + self.create_with(NewFile::create_at_lent, dir, name) + } + + /// What [`ManifestOptions::create_at`] does, for a directory of any + /// kind: `create` makes the new file `name` below `dir`, and is told + /// whether the file is synced. + fn create_with( + &self, + create: impl FnOnce(D, &Path, bool) -> io::Result<(File, NewFile)>, + dir: D, + name: &Path, + ) -> Result, Error> { + self.check()?; + let (out, new_file) = create(dir, name, self.sync)?; + let mut walker = self.walker(Scratch::beside(new_file.directory()))?; + // A file with a name of its own until it is complete is in the + // directory it is created in, which can be in the tree. + let named = new_file.named_file().map_err(Failure::into_unnamed_error)?; + if let Some((inode, file)) = named { + walker.pass_over(inode, file); + } + Ok(ManifestWriter { + walker, + out, + new_file: Some(new_file), + }) + } + + /// What [`ManifestOptions::generate_at`] does. + fn generate_at_dir( + &self, + dir: BorrowedFd<'_>, + name: &Path, + top: BorrowedFd<'_>, + flags: AddFlags, + ) -> Result { + self.generate_with(NewFile::create_at, dir, name, top, flags) + } + + /// [`ManifestOptions::generate_at`] for a caller of the C API, which + /// lends the library its directory `dir` for the call. + #[cfg(feature = "capi")] + pub(crate) fn generate_at_lent( + &self, + dir: &Arc, + name: &Path, + top: BorrowedFd<'_>, + flags: AddFlags, + ) -> Result { + self.generate_with(NewFile::create_at_lent, dir, name, top, flags) + } + + /// What [`ManifestOptions::generate_at`] does, for a directory of any + /// kind, as [`ManifestOptions::create_with`] takes one. + fn generate_with( + &self, + create: impl FnOnce(D, &Path, bool) -> io::Result<(File, NewFile)>, + dir: D, + name: &Path, + top: BorrowedFd<'_>, + flags: AddFlags, + ) -> Result { + let writer = self.create_with(create, dir, name)?; + writer.generate(top, flags).map(|(_, report)| report) + } +} + +impl Default for ManifestOptions { + /// [`ManifestOptions::new`]. + fn default() -> ManifestOptions { + ManifestOptions::new() + } +} + +/// Takes the files a manifest lists, and writes the manifest once it has +/// them all, see [`ManifestOptions`]. +/// +/// [`ManifestWriter::add_object`] takes a file object that the caller made, +/// and [`ManifestWriter::add_root`] the root directory, as the caller +/// describes it. +/// +/// The manifest lists its file objects in the order the options ask for, +/// and declares it in `order`, whatever order the adds came in. No add is +/// refused because of its order. The same name can be added more than +/// once. A file object equal to one added before is listed once. A +/// directory added more than once is listed with what the first add said +/// of it, and a directory that was added beats one that is only there +/// because files were added below it. Two other files with one name are +/// [`TreeProblem::Duplicate`], from [`ManifestWriter::finish`]. +/// +/// The root file object comes from [`ManifestWriter::add_root`], with the +/// attributes of the root directory and the identity of its file system. +/// A manifest without one has a root that only says that it is a +/// directory, as has every directory files were added below that was not +/// added itself. Where the features give a missing field a meaning, such +/// as [`Features::READ_ONLY`], [`Features::USER_XATTR`], the flags and, +/// for the root, [`Features::FS_LABEL`], such a directory would claim what +/// nobody read, and [`ManifestWriter::finish`] fails with +/// [`TreeProblem::MissingParent`] instead. +/// +/// An add that fails leaves the writer as it was, as if the add had not +/// been. A writer that is dropped before [`ManifestWriter::finish`] writes +/// nothing. +pub struct ManifestWriter { + walker: Walker, + out: W, + /// The file of [`ManifestOptions::create_at`], which gets its name once + /// the manifest is complete. + new_file: Option, +} + +impl fmt::Debug for ManifestWriter { + /// The writer the manifest goes to, but not what the writer keeps of + /// the files until the manifest is written. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ManifestWriter") + .field("out", &self.out) + .finish_non_exhaustive() + } +} + +impl ManifestWriter { + /// The directory `top` as the root, and everything below it: the walk + /// of [`ManifestOptions::generate_at`] and [`ManifestOptions::generate`]. + fn add_all(&mut self, top: BorrowedFd<'_>, flags: AddFlags) -> Result<(), Error> { + self.run(Add::Tree { top, flags }) + } + + /// What the generate functions do with their writer: the walk of `top`, + /// and [`ManifestWriter::finish`]. A walk that fails ends the writer. + /// What would have written its manifest gives the scratch files back + /// first, see [`Writing::give_back`]. + fn generate(mut self, top: BorrowedFd<'_>, flags: AddFlags) -> Result<(W, ManifestReport), Error> { + if let Err(e) = self.add_all(top, flags) { + let (writing, _) = self.walker.finish(); + writing.give_back(); + return Err(e); + } + self.finish() + } + + /// The root directory, as a caller describes it: its inode attributes + /// and the identity of its file system. The order and the features of + /// the root file object are those of the options. A root is checked as + /// [`ManifestWriter::add_object`] checks a file object: one with a field + /// of a feature the manifest does not record is refused. A root that is + /// refused is not added, and the writer is as it was. The first root + /// that is added says what the root is like, as for every directory. + pub fn add_root(&mut self, inode: &InodeAttributes, file_system: &FileSystemIdentity) -> Result<(), Error> { + self.run(Add::Root { inode, file_system }) + } + + /// The file object `object`, which a caller made. It is held to what + /// [`Writer::file`](crate::Writer::file) holds a file object to here, + /// but for where it comes, which [`ManifestWriter::finish`] checks. An + /// object that is refused is not added, and the writer is as it was. + /// Its `inodeToken` says which of the other file objects of a caller it + /// shares an inode with, and the manifest numbers them in its own + /// order. Those file objects have to have the fields the specification + /// wants the names of one inode to share. One that doesn't fails the add + /// with [`TreeProblem::HardlinkMismatch`], and [`Error::hardlink_name`] + /// names the first of them. + pub fn add_object(&mut self, object: &FileObject) -> Result<(), Error> { + self.run(Add::Object(object)) + } + + /// Does the add `add` from its beginning to its end, a step at a time. + /// The add borrows what it was given for that long, and duplicates + /// none of it: it takes no descriptor but for what it opens of the + /// tree. + fn run(&mut self, add: Add<'_>) -> Result<(), Error> { + let mut task = Walker::begin(add); + while self.walker.step(&mut task, STEP_BUDGET)?.is_continue() {} + Ok(()) + } + + /// Writes the manifest and returns what it was written to and what it + /// lists. With [`ManifestOptions::create_at`] the file gets its name + /// now, unless something else took it since, which is an + /// [`ErrorKind::Io`] error of EEXIST. Where something fails once the + /// file has its name, such as the sync of its directory, the file keeps + /// the name, and this fails all the same. + /// + /// What the adds left open fails here: two files with one name, a + /// directory that is missing, see [`ManifestWriter`], a file that is + /// not a directory below which files were added, which is + /// [`TreeProblem::NotDirectory`], a record that is larger than + /// [`MAX_RECORD_SIZE`](crate::MAX_RECORD_SIZE), which is + /// [`Problem::RecordTooLarge`](crate::Problem::RecordTooLarge), and + /// what [`Writer::file`](crate::Writer::file) refuses of a file object + /// of a caller where it comes. + pub fn finish(self) -> Result<(W, ManifestReport), Error> { + let ManifestWriter { + walker, + mut out, + mut new_file, + } = self; + // No add comes any more. The walker goes here, and nothing is + // closed with it: the scratch files the adds were done with stay + // open until the manifest is written. + let (mut writing, omitted) = walker.finish(); + let written = Self::write(&mut writing, &mut out, &mut new_file); + // The manifest is written, or it failed. Either way the scratch + // files go back before they are closed, which empties them: a file + // system can keep an unlinked file in its directory until it is + // released, with what it holds. + writing.give_back(); + // A new file that is still here was never to get its name: the + // manifest failed first. What was written of it goes as well. + if let Some(new_file) = &new_file { + new_file.give_up(); + } + Ok((out, ManifestReport::new(written?, omitted))) + } + + /// What [`ManifestWriter::finish`] does with what writes the manifest, + /// `writing`: writes the manifest to `out`, a step at a time, and gives + /// the file of `new_file` its name, which takes it from there. Returns + /// what the manifest lists. + fn write(writing: &mut Writing, out: &mut W, new_file: &mut Option) -> Result { + // A write that fails says which file it is of, where the writer + // knows the file. + let failed = |error| match &new_file { + Some(new_file) => new_file.failed(error), + None => error, + }; + let mut text = String::new(); + let totals = loop { + let step = writing.step(STEP_BUDGET, &mut text)?; + out.write_all(text.as_bytes()).map_err(failed)?; + text.clear(); + if let ControlFlow::Break(totals) = step { + break totals; + } + }; + out.flush().map_err(failed)?; + if let Some(new_file) = new_file.take() { + new_file.link()?; + } + Ok(totals) + } + + /// Drops the writer in a process that did not make it, such as the child + /// of a fork() of a caller of the C API. Nothing changes for the process + /// that made the writer, which has the writer still. Where the file of + /// [`ManifestOptions::create_at`] has a name until it is complete, the + /// name is left alone: that process removes it or gives the file its + /// own. The files the writer keeps on disk are closed and not emptied, + /// as with every writer that is dropped, so that process reads them + /// still. + #[cfg(feature = "capi")] + pub(crate) fn abandon(mut self) { + if let Some(new_file) = self.new_file.take() { + new_file.abandon(); + } + } +} + +/// What a manifest lists, counted per file object: a file with three names +/// counts three times. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ManifestReport { + files: u64, + directories: u64, + others: u64, + bytes: u64, + entries_omitted: u64, + fields_omitted: u64, +} + +impl ManifestReport { + /// The report of a manifest that lists `totals`, of adds that left out + /// `omitted`. + fn new(totals: Totals, omitted: Omitted) -> ManifestReport { + ManifestReport { + files: totals.files, + directories: totals.directories, + others: totals.others, + bytes: totals.bytes, + entries_omitted: omitted.entries, + fields_omitted: omitted.fields, + } + } + + /// How many regular files the manifest lists. + pub fn files(&self) -> u64 { + self.files + } + + /// How many directories the manifest lists, the root among them. + pub fn directories(&self) -> u64 { + self.directories + } + + /// How many other files the manifest lists: symbolic links, FIFOs, + /// device nodes and sockets. + pub fn others(&self) -> u64 { + self.others + } + + /// The sizes of the regular files, added up: those statx() gives for + /// the files of a tree, also where the manifest does not record sizes, + /// and those of the file objects of a caller. The data of a file with + /// more than one name counts for each. + pub fn bytes(&self) -> u64 { + self.bytes + } + + /// How many files [`AddFlags::GRACEFUL`] left out, a directory with + /// everything below it as one. + pub fn entries_omitted(&self) -> u64 { + self.entries_omitted + } + + /// How many fields were left out of the file objects: the names of + /// owners that the user database does not have, the user and group IDs + /// 65535 and 4294967295, modification times before 1970 or after 2554, + /// and the UUID or the volume serial number of a file system that gives + /// none. + pub fn fields_omitted(&self) -> u64 { + self.fields_omitted + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sys::FsUuid; + use crate::testing::{self, read_whole, OpenFile, TempDir}; + use crate::tree::{Entry, InodeId, Status}; + use crate::RootObject; + use rustix::fs::OFlags; + use std::fs; + use std::io; + use std::os::fd::OwnedFd; + use std::os::unix::fs::{symlink, MetadataExt, PermissionsExt}; + use std::process::Command; + use std::sync::Arc; + + /// Opens `path` as a handle, the link itself where it is a symbolic + /// link. + fn open_path(path: &Path) -> OwnedFd { + let flags = OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC; + rustix::fs::open(path, flags, rustix::fs::Mode::empty()).unwrap() + } + + /// The names of the files in the directory `dir`, sorted. + fn names_in(dir: &Path) -> Vec { + let mut names: Vec = fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect(); + names.sort(); + names + } + + /// The errno of the I/O error `e`. + fn errno(e: &Error) -> Option { + assert_eq!(e.kind(), ErrorKind::Io, "{}", e); + e.io_error().and_then(io::Error::raw_os_error) + } + + /// A tree with a directory, files, a hard link and a symbolic link. + fn tree(name: &str) -> TempDir { + let tmp = TempDir::new(name); + let dir = &tmp.0; + fs::create_dir(dir.join("a")).unwrap(); + fs::write(dir.join("a/file"), b"hello").unwrap(); + fs::write(dir.join("linked"), b"twice").unwrap(); + fs::hard_link(dir.join("linked"), dir.join("a/linked-too")).unwrap(); + symlink("a", dir.join("link")).unwrap(); + tmp + } + + /// A new manifest file appears once it is complete, as what the same + /// manifest written to a stream holds, and the file that comes back is + /// it. Until then nothing has its name, and the descriptor of the + /// directory need not stay open. + #[test] + fn creates_the_file_once_complete() { + let tree = tree("manifest-create"); + let out = TempDir::new("manifest-create-out"); + let options = ManifestOptions::new(); + let dir = File::open(&out.0).unwrap(); + let mut writer = options.create_at(&dir, Path::new("m")).unwrap(); + drop(dir); + writer.add_all(open_path(&tree.0).as_fd(), AddFlags::NONE).unwrap(); + assert!(!out.0.join("m").exists()); + let (file, report) = writer.finish().unwrap(); + let written = fs::read(out.0.join("m")).unwrap(); + let (streamed, streamed_report) = options + .generate(Vec::new(), open_path(&tree.0), AddFlags::NONE) + .unwrap(); + assert_eq!((&written, report), (&streamed, streamed_report)); + let meta = fs::metadata(out.0.join("m")).unwrap(); + assert_eq!(file.metadata().unwrap().ino(), meta.ino()); + assert_eq!(meta.len(), written.len() as u64); + // Read and write for everybody, less what the umask takes away. + let created = out.0.join("created"); + File::create(&created).unwrap(); + assert_eq!(meta.mode(), fs::metadata(&created).unwrap().mode()); + // generate_at() is the same. + let report = options + .generate_at( + File::open(&out.0).unwrap(), + Path::new("again"), + open_path(&tree.0), + AddFlags::NONE, + ) + .unwrap(); + assert_eq!( + (fs::read(out.0.join("again")).unwrap(), report), + (written, streamed_report) + ); + } + + /// A new manifest file never replaces anything: a name that is taken + /// fails when the writer is made, and one that is taken while the + /// manifest is written fails at the end, leaving the file that took it. + /// A writer that is dropped leaves nothing. + #[test] + fn never_replaces() { + let tree = tree("manifest-replace"); + let out = TempDir::new("manifest-replace-out"); + let dir = &out.0; + fs::write(dir.join("file"), b"mine").unwrap(); + fs::create_dir(dir.join("directory")).unwrap(); + symlink("nowhere", dir.join("dangling")).unwrap(); + let options = ManifestOptions::new(); + let taken = ["file", "directory", "dangling"]; + for name in taken { + let created = options.create_at(File::open(dir).unwrap(), Path::new(name)); + let e = created.map(drop).unwrap_err(); + assert_eq!(errno(&e), Some(libc::EEXIST), "{}", name); + let message = format!( + "the manifest file '{}': {}", + name, + io::Error::from_raw_os_error(libc::EEXIST) + ); + assert_eq!(e.to_string(), message); + } + let generated = options.generate_at( + File::open(dir).unwrap(), + Path::new("file"), + open_path(&tree.0), + AddFlags::NONE, + ); + let e = generated.unwrap_err(); + assert_eq!(errno(&e), Some(libc::EEXIST)); + let message = format!( + "the manifest file 'file': {}", + io::Error::from_raw_os_error(libc::EEXIST) + ); + assert_eq!(e.to_string(), message); + let mut writer = options.create_at(File::open(dir).unwrap(), Path::new("later")).unwrap(); + writer.add_all(open_path(&tree.0).as_fd(), AddFlags::NONE).unwrap(); + fs::write(dir.join("later"), b"mine as well").unwrap(); + let e = writer.finish().unwrap_err(); + assert_eq!(errno(&e), Some(libc::EEXIST)); + let message = format!( + "the manifest file 'later': {}", + io::Error::from_raw_os_error(libc::EEXIST) + ); + assert_eq!(e.to_string(), message); + assert_eq!(fs::read(dir.join("later")).unwrap(), b"mine as well"); + let mut writer = options + .create_at(File::open(dir).unwrap(), Path::new("dropped")) + .unwrap(); + writer.add_all(open_path(&tree.0).as_fd(), AddFlags::NONE).unwrap(); + drop(writer); + assert_eq!(names_in(dir), ["dangling", "directory", "file", "later"]); + } + + /// A name with more than one component names a file in a directory + /// below the directory, which is opened one component at a time. A + /// symbolic link on the way is not followed, wherever it leads, and an + /// absolute name and one with `.` or `..` on the way are no names below + /// a directory. So no name sends a manifest, or what is kept next to it + /// while it is built, out of the directory, also not one the owner of + /// the tree made. A name that is empty or that ends in a slash, `.` or + /// `..` is no name of a file, and a directory that is not there, or + /// that is none, fails. Each error says which file it is of. + #[test] + fn names_of_new_files() { + let out = TempDir::new("manifest-names"); + let elsewhere = TempDir::new("manifest-names-elsewhere"); + let dir = &out.0; + fs::create_dir_all(dir.join("sub/deeper")).unwrap(); + fs::write(dir.join("file"), b"").unwrap(); + symlink(&elsewhere.0, dir.join("meta")).unwrap(); + symlink("sub", dir.join("inside")).unwrap(); + let options = ManifestOptions::new(); + for name in ["sub/m", "sub/deeper/m", "sub//deeper///again"] { + let writer = options.create_at(File::open(dir).unwrap(), Path::new(name)).unwrap(); + writer.finish().unwrap(); + } + assert_eq!(names_in(&dir.join("sub")), ["deeper", "m"]); + assert_eq!(names_in(&dir.join("sub/deeper")), ["again", "m"]); + let absolute = elsewhere.0.join("absolute"); + let failures = [ + ("", libc::EINVAL), + ("x/", libc::EINVAL), + (".", libc::EINVAL), + ("..", libc::EINVAL), + ("sub/.", libc::EINVAL), + ("sub/..", libc::EINVAL), + ("./m", libc::EINVAL), + ("sub/./m", libc::EINVAL), + ("../m", libc::EINVAL), + ("sub/../m", libc::EINVAL), + ("sub/deeper/../../../elsewhere/m", libc::EINVAL), + (absolute.to_str().unwrap(), libc::EINVAL), + ("meta/m", libc::ELOOP), + ("inside/m", libc::ELOOP), + ("sub/../meta/m", libc::EINVAL), + ("file/m", libc::ENOTDIR), + ("missing/m", libc::ENOENT), + ("sub/missing/m", libc::ENOENT), + ]; + for (name, expected) in failures { + let created = options.create_at(File::open(dir).unwrap(), Path::new(name)); + let e = created.map(drop).unwrap_err(); + assert_eq!(errno(&e), Some(expected), "{:?}", name); + let message = format!( + "the manifest file '{}': {}", + name, + io::Error::from_raw_os_error(expected) + ); + assert_eq!(e.to_string(), message); + } + assert!(names_in(&elsewhere.0).is_empty()); + assert_eq!(names_in(dir), ["file", "inside", "meta", "sub"]); + // The owner of a tree can't send its manifest elsewhere with a + // directory of the tree that became a symbolic link. + let tree = tree("manifest-names-tree"); + symlink(&elsewhere.0, tree.0.join("meta")).unwrap(); + let top = || open_path(&tree.0); + for (name, expected) in [ + ("meta/root.manifest", libc::ELOOP), + ("a/../../elsewhere/root.manifest", libc::EINVAL), + (absolute.to_str().unwrap(), libc::EINVAL), + ] { + let generated = options.generate_at(top(), Path::new(name), top(), AddFlags::NONE); + assert_eq!(errno(&generated.unwrap_err()), Some(expected), "{:?}", name); + } + assert!(names_in(&elsewhere.0).is_empty()); + assert_eq!(names_in(&tree.0), ["a", "link", "linked", "meta"]); + } + + /// The variable that tells the test binary, run again by + /// [`refuses_the_current_directory`], where the directory of the test + /// is, which is the current directory of that process. + const CURRENT_DIR: &str = "UAPI16_TEST_MANIFEST_CURRENT_DIR"; + + /// rustix's `CWD` is no descriptor: it is AT_FDCWD, which stands for + /// the current directory only where a path is looked up. A new file + /// below it is refused with EBADF, whether its name has one component + /// or more, and so is a walk of it, and nothing is made in the current + /// directory. That is the directory of the process, so the test binary + /// runs this test again in a process of its own, whose current + /// directory is the directory of the test. + #[test] + fn refuses_the_current_directory() { + let Some(dir) = std::env::var_os(CURRENT_DIR) else { + let tmp = TempDir::new("manifest-current-directory"); + let dir = fs::canonicalize(&tmp.0).unwrap(); + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "manifest::tests::refuses_the_current_directory", + "--nocapture", + ]) + .env(CURRENT_DIR, &dir) + .current_dir(&dir) + .output() + .unwrap(); + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + return; + }; + let dir = Path::new(&dir); + assert_eq!(std::env::current_dir().unwrap(), dir); + fs::create_dir_all(dir.join("sub/deeper")).unwrap(); + fs::create_dir(dir.join("tree")).unwrap(); + fs::write(dir.join("tree/file"), b"hello").unwrap(); + let options = ManifestOptions::new(); + for name in ["m", "sub/m", "sub/deeper/m"] { + let name = Path::new(name); + let created = options.create_at(rustix::fs::CWD, name).map(drop); + let top = open_path(&dir.join("tree")); + let generated = options + .generate_at(rustix::fs::CWD, name, top, AddFlags::NONE) + .map(drop); + for e in [created.unwrap_err(), generated.unwrap_err()] { + assert_eq!(errno(&e), Some(libc::EBADF), "{:?}", name); + let message = format!( + "the manifest file '{}': {}", + name.display(), + io::Error::from_raw_os_error(libc::EBADF) + ); + assert_eq!(e.to_string(), message); + } + } + // The top of a walk is a descriptor as well. + let walked = options.generate(Vec::new(), rustix::fs::CWD, AddFlags::NONE).map(drop); + let sub = File::open(dir.join("sub")).unwrap(); + let generated = options + .generate_at(sub, Path::new("m"), rustix::fs::CWD, AddFlags::NONE) + .map(drop); + for e in [walked.unwrap_err(), generated.unwrap_err()] { + assert_eq!(errno(&e), Some(libc::EBADF)); + let message = format!("the root of the tree: {}", io::Error::from_raw_os_error(libc::EBADF)); + assert_eq!(e.to_string(), message); + } + assert_eq!(names_in(dir), ["sub", "tree"]); + assert_eq!(names_in(&dir.join("sub")), ["deeper"]); + assert!(names_in(&dir.join("sub/deeper")).is_empty()); + assert_eq!(names_in(&dir.join("tree")), ["file"]); + } + + /// The scratch files of a manifest that is created as a file are made + /// through the descriptor the new file has of its directory: the two + /// share it, and no second one is taken. + #[test] + fn shares_the_directory_of_the_new_file() { + let out = TempDir::new("manifest-shared-directory"); + let options = ManifestOptions::new(); + let writer = options.create_at(File::open(&out.0).unwrap(), Path::new("m")).unwrap(); + let directory = writer.new_file.as_ref().unwrap().directory(); + // The new file, the scratch space and this one. + assert_eq!(Arc::strong_count(&directory), 3); + } + + /// The variable that tells the test binary, run again by + /// [`write_errors_name_the_file`] with a limit on the size of files, + /// where its directories are. + const FILE_SIZE_LIMIT_DIR: &str = "UAPI16_TEST_MANIFEST_FILE_SIZE_LIMIT_DIR"; + + /// A write of the manifest that fails says which file it is of, where + /// the writer made the file, and nothing has the name then. A writer of + /// the caller is not named. The test binary runs this test again with a + /// limit on the size of files that a manifest of a few files is over, + /// and with SIGXFSZ ignored, so that the write fails with EFBIG. + #[test] + fn write_errors_name_the_file() { + if let Some(dir) = std::env::var_os(FILE_SIZE_LIMIT_DIR) { + return check_write_errors_name_the_file(Path::new(&dir)); + } + let tmp = TempDir::new("manifest-write-errors"); + let dir = &tmp.0; + fs::create_dir(dir.join("out")).unwrap(); + fs::create_dir(dir.join("tree")).unwrap(); + for number in 0..64 { + fs::write(dir.join(format!("tree/file-{}", number)), b"").unwrap(); + } + let script = concat!( + r#"trap '' XFSZ; ulimit -f 1 || exit 1; "#, + r#"exec "$1" --exact manifest::tests::write_errors_name_the_file"# + ); + let output = Command::new("sh") + .args(["-c", script, "sh"]) + .arg(std::env::current_exe().unwrap()) + .env(FILE_SIZE_LIMIT_DIR, dir) + .output() + .unwrap(); + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } + + /// The checks of [`write_errors_name_the_file`] below `dir`. + fn check_write_errors_name_the_file(dir: &Path) { + let (out, tree) = (dir.join("out"), dir.join("tree")); + let too_large = io::Error::from_raw_os_error(libc::EFBIG).to_string(); + let options = ManifestOptions::new(); + let generated = options.generate_at( + File::open(&out).unwrap(), + Path::new("m"), + open_path(&tree), + AddFlags::NONE, + ); + let e = generated.unwrap_err(); + assert_eq!(errno(&e), Some(libc::EFBIG)); + assert_eq!(e.to_string(), format!("the manifest file 'm': {}", too_large)); + assert!(names_in(&out).is_empty()); + let file = File::create(out.join("stream")).unwrap(); + let e = options.generate(file, open_path(&tree), AddFlags::NONE).unwrap_err(); + assert_eq!(errno(&e), Some(libc::EFBIG)); + assert_eq!(e.to_string(), too_large); + } + + /// The variable that tells the test binary, run again inside the + /// namespaces of [`new_files_below_mount_points`], where the directory + /// with the mount is. + const MOUNT_DIR: &str = "UAPI16_TEST_MANIFEST_MOUNT_DIR"; + + /// A mount point on the way to a new file is gone through: the file + /// can be in a directory of another file system below the directory. + /// The mount needs a user and a mount namespace, which unshare(1) + /// makes, and the test binary runs this test again inside them. + #[test] + fn new_files_below_mount_points() { + if let Some(dir) = std::env::var_os(MOUNT_DIR) { + let dir = Path::new(&dir); + let options = ManifestOptions::new(); + let writer = options.create_at(File::open(dir).unwrap(), Path::new("mount/sub/m")); + writer.unwrap().finish().unwrap(); + assert_eq!(names_in(&dir.join("mount/sub")), ["m"]); + return; + } + let tmp = TempDir::new("manifest-mount"); + let dir = &tmp.0; + fs::create_dir(dir.join("mount")).unwrap(); + let works = Command::new("unshare").args(["-Urm", "true"]).output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urm does not work here"); + return; + } + let script = concat!( + r#"set -e; mount -t tmpfs tmpfs "$1/mount"; mkdir "$1/mount/sub"; "#, + r#"exec "$2" --exact manifest::tests::new_files_below_mount_points"# + ); + let output = Command::new("unshare") + .args(["-Urm", "sh", "-c", script, "sh"]) + .arg(dir) + .arg(std::env::current_exe().unwrap()) + .env(MOUNT_DIR, dir) + .output() + .unwrap(); + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } + + /// The variable that names an automount point for + /// [`new_files_below_automount_points`], which the test has something + /// mounted on. + const AUTOMOUNT_OUT: &str = "UAPI16_TEST_AUTOMOUNT_OUT"; + + /// An automount point on the way to a new file has its file system + /// mounted, as for any path a file is created at, and the file is in + /// what is mounted. Only root can make an automount point, so the test + /// takes one that is there: `UAPI16_TEST_AUTOMOUNT_OUT` names a + /// directory that is one, that nothing is mounted on yet, and that + /// mounts a file system files can be created in, such as the mount + /// point of an automount unit of systemd for a tmpfs. Without the + /// variable the test is skipped. + #[test] + fn new_files_below_automount_points() { + let Some(point) = std::env::var_os(AUTOMOUNT_OUT) else { + eprintln!("skipping: {} names no automount point", AUTOMOUNT_OUT); + return; + }; + let point = Path::new(&point); + let parent = File::open(point.parent().unwrap()).unwrap(); + let name = Path::new(point.file_name().unwrap()); + let mounted = || { + let handle = rustix::fs::openat( + &parent, + name, + OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC, + rustix::fs::Mode::empty(), + ); + let attributes = rustix::fs::statx( + handle.unwrap(), + c"", + rustix::fs::AtFlags::EMPTY_PATH, + rustix::fs::StatxFlags::MNT_ID, + ); + attributes.unwrap().stx_mnt_id + }; + let before = mounted(); + let options = ManifestOptions::new(); + let writer = options.create_at(&parent, &name.join("m")).unwrap(); + assert_ne!(mounted(), before, "nothing was mounted on {}", point.display()); + writer.finish().unwrap(); + assert!(names_in(point).contains(&"m".to_owned())); + fs::remove_file(point.join("m")).unwrap(); + } + + /// What a test writes to, which counts the writes. + #[derive(Default)] + struct Counted { + data: Vec, + writes: usize, + /// The most bytes one write brought. + largest: usize, + flushes: usize, + } + + impl Write for Counted { + fn write(&mut self, data: &[u8]) -> io::Result { + self.writes += 1; + self.largest = self.largest.max(data.len()); + self.data.extend_from_slice(data); + Ok(data.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.flushes += 1; + Ok(()) + } + } + + /// A manifest written to a stream gets nothing before finish(), and the + /// whole manifest then. It lists its file objects in the order of their + /// names whatever the order of the adds, and declares the order. + #[test] + fn writes_nothing_before_the_end() { + let mut writer = ManifestOptions::new().open(Counted::default()).unwrap(); + for name in ["linked", "a/file", "link", "a/linked-too"] { + writer.add_object(&FileObject::new(testing::name(name))).unwrap(); + } + assert_eq!(writer.out.writes, 0); + let (out, report) = writer.finish().unwrap(); + let whole = read_whole(&out.data).unwrap(); + let names: Vec<&str> = whole.objects.iter().map(|object| object.name().as_str()).collect(); + assert_eq!(names, ["a", "a/file", "a/linked-too", "link", "linked"]); + assert_eq!(whole.root.order(), Some(Order::CodePoint)); + assert_eq!((report.files(), report.directories(), report.others()), (4, 2, 0)); + } + + /// The end writes the manifest a slice at a time, none larger than a + /// step puts together, so that it never has more of the manifest in + /// memory than that, and flushes what it wrote to once. + #[test] + fn writes_a_slice_at_a_time() { + /// How many directories the tree has, how many files each of them + /// has, and how long the names of the files are: a manifest of + /// several slices, and of more than a step's budget. The files are + /// in several directories, since a directory of FAT has room for + /// 65,536 entries and a name that long takes 17 of them. + const DIRECTORIES: usize = 4; + const FILES: usize = 2_000; + const NAME: usize = 200; + let tmp = TempDir::new("manifest-slices"); + for directory in 0..DIRECTORIES { + let directory = tmp.0.join(directory.to_string()); + fs::create_dir(&directory).unwrap(); + for number in 0..FILES { + fs::write(directory.join(format!("{:0width$}", number, width = NAME)), b"").unwrap(); + } + } + let (out, report) = ManifestOptions::new() + .generate(Counted::default(), open_path(&tmp.0), AddFlags::NONE) + .unwrap(); + assert_eq!(report.files(), (DIRECTORIES * FILES) as u64); + assert!(out.data.len() > STEP_BUDGET as usize, "{}", out.data.len()); + assert!( + out.writes > 2 && out.largest <= STEP_BUDGET as usize, + "{} {}", + out.writes, + out.largest + ); + assert_eq!(out.flushes, 1); + } + + /// The features of partitions don't apply to a tree, and nothing is made + /// for them. The error names the first of them. + #[test] + fn features_of_partitions() { + let tree = tree("manifest-gpt"); + let out = TempDir::new("manifest-gpt-out"); + let top = || open_path(&tree.0); + for feature in ManifestOptions::FOR_PARTITIONS { + let mut options = ManifestOptions::new(); + options.features(Features::DEFAULT | feature); + let dir = || File::open(&out.0).unwrap(); + let errors = [ + options.create_at(dir(), Path::new("m")).map(drop).unwrap_err(), + options.open(Vec::new()).map(drop).unwrap_err(), + options + .generate_at(dir(), Path::new("m"), top(), AddFlags::NONE) + .map(drop) + .unwrap_err(), + options + .generate(Vec::new(), top(), AddFlags::NONE) + .map(drop) + .unwrap_err(), + ]; + for e in errors { + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::FeatureNotForTrees)); + assert_eq!(e.feature(), Some(feature)); + } + } + let mut options = ManifestOptions::new(); + options.features(Features::DEFAULT | Features::GPT_UUID | Features::GPT_LABEL); + let e = options.open(Vec::new()).map(drop).unwrap_err(); + assert_eq!(e.feature(), Some(Features::GPT_LABEL)); + assert!(names_in(&out.0).is_empty()); + } + + /// The options start with the default features and the code point + /// order, and say what the root file object says of the manifest. + #[test] + fn options() { + assert_eq!( + format!("{:?}", ManifestOptions::default()), + format!("{:?}", ManifestOptions::new()) + ); + let tree = tree("manifest-options"); + let (out, _) = ManifestOptions::new() + .generate(Vec::new(), open_path(&tree.0), AddFlags::NONE) + .unwrap(); + let root = read_whole(&out).unwrap().root; + assert_eq!((root.features(), root.order()), (None, Some(Order::CodePoint))); + let (out, _) = ManifestOptions::new() + .features(Features::DEFAULT | Features::MTIME) + .order(Order::CodePoint) + .generate(Vec::new(), open_path(&tree.0), AddFlags::NONE) + .unwrap(); + let root: RootObject = read_whole(&out).unwrap().root; + assert_eq!(root.features(), Some(Features::DEFAULT | Features::MTIME)); + assert!(root.inode().mtime().is_some()); + } + + /// The report counts every name of a file, the root among the + /// directories, and what was left out. + #[test] + fn reports() { + let tree = tree("manifest-report"); + let dir = &tree.0; + fs::write(dir.join("\u{1}control"), b"").unwrap(); + let old = std::time::UNIX_EPOCH - std::time::Duration::from_secs(1); + File::options() + .write(true) + .open(dir.join("a/file")) + .unwrap() + .set_modified(old) + .unwrap(); + let mut options = ManifestOptions::new(); + options.features(Features::DEFAULT | Features::MTIME); + let graceful = AddFlags::GRACEFUL; + let (_, report) = options.generate(Vec::new(), open_path(dir), graceful).unwrap(); + assert_eq!( + (report.files(), report.directories(), report.others(), report.bytes()), + (3, 2, 1, 5 + 5 + 5) + ); + assert_eq!((report.entries_omitted(), report.fields_omitted()), (1, 1)); + let e = options + .generate(Vec::new(), open_path(dir), AddFlags::NONE) + .unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::UnwritableName)); + // generate_at() walks with the flags it is given as well, and a + // walk that fails leaves no file. + let out = TempDir::new("manifest-report-out"); + let e = options + .generate_at( + File::open(&out.0).unwrap(), + Path::new("m"), + open_path(dir), + AddFlags::NONE, + ) + .unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::UnwritableName)); + assert!(names_in(&out.0).is_empty()); + let in_file = options + .generate_at(File::open(&out.0).unwrap(), Path::new("m"), open_path(dir), graceful) + .unwrap(); + assert_eq!(in_file, report); + assert_eq!(names_in(&out.0), ["m"]); + } + + /// Two different files with one name are an error, the same file twice + /// is one, and a directory that was not added fails where the features + /// need what it would say. + #[test] + fn what_finish_decides() { + let file = FileObject::new(testing::name("x")); + let mut writer = ManifestOptions::new().open(Vec::new()).unwrap(); + writer.add_object(&file).unwrap(); + writer.add_object(&file).unwrap(); + let (out, report) = writer.finish().unwrap(); + assert_eq!((read_whole(&out).unwrap().objects.len(), report.files()), (1, 1)); + let mut other = FileObject::new(testing::name("x")); + other.set_size(Some(1)); + let mut writer = ManifestOptions::new().open(Vec::new()).unwrap(); + writer.add_object(&file).unwrap(); + writer.add_object(&other).unwrap(); + let e = writer.finish().unwrap_err(); + assert_eq!( + (e.kind(), e.name()), + (ErrorKind::Tree(TreeProblem::Duplicate), Some("x")) + ); + let mut options = ManifestOptions::new(); + options.features(Features::DEFAULT | Features::READ_ONLY); + let mut writer = options.open(Vec::new()).unwrap(); + writer.add_object(&FileObject::new(testing::name("parent/x"))).unwrap(); + let e = writer.finish().unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::MissingParent)); + } + + /// The variable that names a directory without O_TMPFILE, the one + /// fuse-overlayfs mounts, in which the test binary runs + /// [`created_in_the_tree`] again. + const NO_TMPFILE_DIR: &str = "UAPI16_TEST_NO_TMPFILE_DIR"; + + /// A manifest that is created in the tree it lists, on a file system + /// without O_TMPFILE, has a name of its own until it is complete, which + /// the walk passes over. The test binary runs this test again in a user + /// and mount namespace from unshare(1), on a mount of fuse-overlayfs, + /// which has no O_TMPFILE. It is skipped where there is none. + #[test] + fn created_in_the_tree() { + if let Some(dir) = std::env::var_os(NO_TMPFILE_DIR) { + return check_created_in_the_tree(Path::new(&dir)); + } + let tmp = TempDir::new("manifest-in-the-tree"); + let dir = &tmp.0; + for part in ["lower/a", "upper", "work", "merged"] { + fs::create_dir_all(dir.join(part)).unwrap(); + } + fs::write(dir.join("lower/a/file"), b"hello").unwrap(); + fs::write(dir.join("lower/file"), b"world").unwrap(); + let works = Command::new("unshare").args(["-Urm", "true"]).output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urm does not work here"); + return; + } + // The script exits with 77 where it can't mount the file system, + // and unmounts it once the test is done, which ends fuse-overlayfs. + let script = concat!( + r#"d=$1; "#, + r#"fuse-overlayfs -o "lowerdir=$d/lower,upperdir=$d/upper,workdir=$d/work" "$d/merged" || exit 77; "#, + r#""$2" --exact manifest::tests::created_in_the_tree; status=$?; "#, + r#"umount "$d/merged"; exit $status"# + ); + let output = Command::new("unshare") + .args(["-Urm", "sh", "-c", script, "sh"]) + .arg(dir) + .arg(std::env::current_exe().unwrap()) + .env(NO_TMPFILE_DIR, dir.join("merged")) + .output() + .unwrap(); + if output.status.code() == Some(77) { + eprintln!("skipping: fuse-overlayfs can't mount a file system here"); + return; + } + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } + + /// The variable that names the merged directory of fuse-overlayfs in + /// which the test binary runs [`files_with_the_inode_of_the_manifest`] + /// again. + const SAME_INODE_DIR: &str = "UAPI16_TEST_SAME_INODE_DIR"; + + /// How many files the lower layer of that test has: more than the + /// upper layer has inodes by the time the manifest is made there, so + /// that one of them has the inode number the manifest gets. + const LOWER_FILES: usize = 40; + + /// A file of the tree that has the device and the inode number of the + /// manifest is listed, where the manifest itself is passed over. On + /// fuse-overlayfs the files of both layers show under one device with + /// the inode numbers they have in their layers. So with each layer on + /// a file system of its own, a manifest that is created in the tree, + /// which is made in the upper layer and has a name of its own there + /// until it is complete, gets the number of a file of the lower one. + /// The test binary runs this test again in a user and mount namespace + /// from unshare(1), where the two layers are a tmpfs each. It is + /// skipped where there is no fuse-overlayfs, and where no file has the + /// number of the manifest. + #[test] + fn files_with_the_inode_of_the_manifest() { + if let Some(dir) = std::env::var_os(SAME_INODE_DIR) { + return check_same_inode(Path::new(&dir)); + } + let tmp = TempDir::new("manifest-same-inode"); + rerun_on_two_layers( + &tmp.0, + "manifest::tests::files_with_the_inode_of_the_manifest", + SAME_INODE_DIR, + ); + } + + /// Runs the test `test` of the test binary again in a user and mount + /// namespace from unshare(1), on a mount of fuse-overlayfs below the + /// directory `dir` whose two layers are a tmpfs each, with + /// [`LOWER_FILES`] files in the lower one, and with the merged + /// directory as the value of the variable `variable`. The test is + /// skipped where that can't be mounted. + fn rerun_on_two_layers(dir: &Path, test: &str, variable: &str) { + for part in ["lower", "upper", "merged"] { + fs::create_dir(dir.join(part)).unwrap(); + } + let works = Command::new("unshare").args(["-Urm", "true"]).output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urm does not work here"); + return; + } + // The script exits with 77 where it can't mount the file systems. + // The files of the lower layer are made on its tmpfs, where a new + // file system numbers them from its first inodes on. + let script = concat!( + r#"d=$1; mount -t tmpfs tmpfs "$d/lower" && mount -t tmpfs tmpfs "$d/upper" || exit 77; "#, + r#"mkdir "$d/lower/files" "$d/upper/files" "$d/upper/work" || exit 77; "#, + r#"i=0; while [ "$i" -lt "$3" ]; do echo "$i" > "$d/lower/files/f$i"; i=$((i + 1)); done; "#, + r#"fuse-overlayfs -o "lowerdir=$d/lower/files,upperdir=$d/upper/files,workdir=$d/upper/work" "$d/merged" "#, + r#"|| exit 77; "#, + r#""$2" --exact "$4" --nocapture; status=$?; "#, + r#"umount "$d/merged"; exit $status"# + ); + let output = Command::new("unshare") + .args(["-Urm", "sh", "-c", script, "sh"]) + .arg(dir) + .arg(std::env::current_exe().unwrap()) + .arg(LOWER_FILES.to_string()) + .arg(test) + .env(variable, dir.join("merged")) + .output() + .unwrap(); + if output.status.code() == Some(77) { + eprintln!("skipping: fuse-overlayfs can't mount a file system here"); + return; + } + // What the test said where it ran again, such as that it skipped. + let said = String::from_utf8_lossy(&output.stderr); + if let Some(skipped) = said.lines().find(|line| line.starts_with("skipping")) { + eprintln!("{}", skipped); + } + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } + + /// The checks of [`files_with_the_inode_of_the_manifest`] in `dir`. + fn check_same_inode(dir: &Path) { + let report = ManifestOptions::new() + .generate_at(File::open(dir).unwrap(), Path::new("m"), open_path(dir), AddFlags::NONE) + .unwrap(); + // The manifest has the inode it was made with, under its name now. + let numbers = |name: &str| { + let meta = fs::symlink_metadata(dir.join(name)).unwrap(); + (meta.dev(), meta.ino()) + }; + let mut files: Vec = (0..LOWER_FILES).map(|i| format!("f{}", i)).collect(); + files.sort(); + let same: Vec<&String> = files.iter().filter(|name| numbers(name) == numbers("m")).collect(); + if same.is_empty() { + eprintln!("skipping: no file of the lower layer has the inode number of the manifest here"); + return; + } + let names: Vec = read_whole(&fs::read(dir.join("m")).unwrap()) + .unwrap() + .objects + .iter() + .map(|object| object.name().to_string()) + .collect(); + assert_eq!(names, files, "{:?}", same); + assert_eq!((report.files(), report.directories()), (LOWER_FILES as u64, 1)); + } + + /// The variable that names the merged directory of fuse-overlayfs in + /// which the test binary runs + /// [`own_files_with_the_inode_of_the_manifest`] again. + const OWN_SAME_INODE_DIR: &str = "UAPI16_TEST_OWN_SAME_INODE_DIR"; + + /// Two files of the manifest's own that have one device and one inode + /// number are both passed over, and both are kept open. On + /// fuse-overlayfs with each layer on a file system of its own, a + /// manifest that is created in the tree gets the number of a file of + /// the lower layer, see [`files_with_the_inode_of_the_manifest`]. Here + /// that file is made a file of the manifest's own as well, as a scratch + /// file with the number of the manifest would be. The walk lists + /// neither of the two, and every other file. The test binary runs this + /// test again as it does that one, and it is skipped where that one + /// is. + #[test] + fn own_files_with_the_inode_of_the_manifest() { + if let Some(dir) = std::env::var_os(OWN_SAME_INODE_DIR) { + return check_own_same_inode(Path::new(&dir)); + } + let tmp = TempDir::new("manifest-own-same-inode"); + rerun_on_two_layers( + &tmp.0, + "manifest::tests::own_files_with_the_inode_of_the_manifest", + OWN_SAME_INODE_DIR, + ); + } + + /// The checks of [`own_files_with_the_inode_of_the_manifest`] in `dir`. + fn check_own_same_inode(dir: &Path) { + let mut writer = ManifestOptions::new() + .create_at(File::open(dir).unwrap(), Path::new("m")) + .unwrap(); + // The inode the manifest is kept with, under the name it has until + // it is complete. + let new_file = writer.new_file.as_ref().unwrap(); + let (inode, _) = new_file.named_file().unwrap().expect("fuse-overlayfs has no O_TMPFILE"); + let inode_of = |name: &str| { + let status = Status::of(open_path(&dir.join(name)).as_fd()).unwrap(); + status.identity.inode_id() + }; + let mut files: Vec = (0..LOWER_FILES).map(|i| format!("f{}", i)).collect(); + files.sort(); + let Some(same) = files.iter().position(|name| inode_of(name) == inode) else { + eprintln!("skipping: no file of the lower layer has the inode number of the manifest here"); + return; + }; + let same = files.remove(same); + let other = Arc::new(File::open(dir.join(&same)).unwrap()); + writer.walker.pass_over(inode, Arc::clone(&other)); + writer.add_all(open_path(dir).as_fd(), AddFlags::NONE).unwrap(); + // What the writer has of that file, next to the test. + let held = Arc::strong_count(&other) - 1; + let (_, report) = writer.finish().unwrap(); + let names: Vec = read_whole(&fs::read(dir.join("m")).unwrap()) + .unwrap() + .objects + .iter() + .map(|object| object.name().to_string()) + .collect(); + assert_eq!(names, files, "{:?}", same); + assert_eq!((report.files(), report.directories()), (LOWER_FILES as u64 - 1, 1)); + assert_eq!(held, 1); + } + + /// The checks of [`created_in_the_tree`] in `dir`. + fn check_created_in_the_tree(dir: &Path) { + let flags = OFlags::TMPFILE | OFlags::RDWR | OFlags::CLOEXEC; + let unnamed = rustix::fs::open(dir, flags, rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR); + assert_eq!(unnamed.unwrap_err(), rustix::io::Errno::OPNOTSUPP); + let report = ManifestOptions::new() + .sync(true) + .generate_at(File::open(dir).unwrap(), Path::new("m"), open_path(dir), AddFlags::NONE) + .unwrap(); + let names: Vec = read_whole(&fs::read(dir.join("m")).unwrap()) + .unwrap() + .objects + .iter() + .map(|object| object.name().to_string()) + .collect(); + assert_eq!(names, ["a", "a/file", "file"]); + assert_eq!((report.files(), report.directories()), (2, 2)); + assert_eq!(names_in(dir), ["a", "file", "m"]); + } + + /// The variable that tells the test binary, run again by + /// [`no_descriptor_left`] with few descriptors, where the tree is. + const NO_DESCRIPTORS_DIR: &str = "UAPI16_TEST_MANIFEST_NO_DESCRIPTORS_DIR"; + + /// Where the process has no descriptor left, an add that opens nothing + /// is done all the same, as that of a file object of a caller, and a + /// walk fails with EMFILE where it first opens something, which is the + /// directory it starts at. What fails for a reason of its own fails for + /// it there as well: options with a feature of partitions fail with + /// TreeProblem::FeatureNotForTrees, whichever way the writer is made, + /// before a descriptor is taken. The test binary runs this test again + /// with 64 descriptors at most, and the test takes what is left of + /// them. + #[test] + fn no_descriptor_left() { + if let Some(dir) = std::env::var_os(NO_DESCRIPTORS_DIR) { + return check_no_descriptor_left(Path::new(&dir)); + } + let tree = tree("manifest-no-descriptors"); + let dir = &tree.0; + let script = r#"ulimit -n 64 || exit 1; exec "$1" --exact manifest::tests::no_descriptor_left"#; + let output = Command::new("sh") + .args(["-c", script, "sh"]) + .arg(std::env::current_exe().unwrap()) + .env(NO_DESCRIPTORS_DIR, dir) + .output() + .unwrap(); + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } + + /// The checks of [`no_descriptor_left`] in the tree `dir`. + fn check_no_descriptor_left(dir: &Path) { + let top = open_path(dir); + let mut partitions = ManifestOptions::new(); + partitions.features(Features::DEFAULT | Features::GPT_LABEL); + let mut usable = ManifestOptions::new().open(Vec::new()).unwrap(); + let mut taken = Vec::new(); + loop { + match rustix::fs::open("/dev/null", OFlags::RDONLY | OFlags::CLOEXEC, rustix::fs::Mode::empty()) { + Ok(fd) => taken.push(fd), + Err(rustix::io::Errno::MFILE) => break, + Err(e) => panic!("{}", e), + } + } + usable.add_object(&FileObject::new(testing::name("given"))).unwrap(); + // The directory a walk starts at is opened for its listing. + let no_listing = ManifestOptions::new().generate(Vec::new(), &top, AddFlags::NONE); + let refused = [ + partitions.open(Vec::new()).map(drop), + partitions.generate(Vec::new(), &top, AddFlags::NONE).map(drop), + partitions.create_at(&top, Path::new("m")).map(drop), + partitions + .generate_at(&top, Path::new("m"), &top, AddFlags::NONE) + .map(drop), + ]; + drop(taken); + let e = no_listing.unwrap_err(); + assert_eq!((errno(&e), e.name()), (Some(libc::EMFILE), Some("")), "{}", e); + let (out, report) = usable.finish().unwrap(); + let names: Vec = read_whole(&out) + .unwrap() + .objects + .iter() + .map(|object| object.name().to_string()) + .collect(); + assert_eq!(names, ["given"]); + assert_eq!((report.directories(), report.files()), (1, 1)); + for e in refused { + assert_eq!(e.unwrap_err().kind(), ErrorKind::Tree(TreeProblem::FeatureNotForTrees)); + } + } + + /// A file object of a caller that a writer refuses is refused when it + /// is added, and the writer is as it was: it takes the next file + /// object, and what it writes then is what it writes without the one + /// it refused. That holds for what its contents objects say of + /// themselves as well: a literal that is not the data its hash is of, + /// and a file that is the root. + #[test] + fn refused_file_objects() { + let mut refused = FileObject::new(testing::name("x")); + refused.inode_mut().set_uid(Some(65535)); + let mut writer = ManifestOptions::new().open(Vec::new()).unwrap(); + let e = writer.add_object(&refused).unwrap_err(); + assert_eq!( + (e.kind(), e.name()), + (ErrorKind::Manifest(crate::Problem::FieldOutOfRange), Some("x")) + ); + let literal = crate::ContentsObject { + original_sha256: Some(crate::Sha256::digest(b"abc")), + ..crate::ContentsObject::new(crate::ContentsSource::Literal(b"xyz".to_vec())) + }; + let root = crate::ContentsObject::new(crate::ContentsSource::File(crate::NameBuf::default())); + let contents = [ + (literal, crate::Problem::Contradiction, crate::Field::Literal), + (root, crate::Problem::InvalidContents, crate::Field::File), + ]; + for (contents, problem, field) in contents { + let mut refused = FileObject::new(testing::name("x")); + refused.set_size(Some(3)); + refused.put_contents(vec![contents]); + let e = writer.add_object(&refused).unwrap_err(); + assert_eq!( + (e.kind(), e.field(), e.name()), + (ErrorKind::Manifest(problem), Some(field), Some("x")), + "{}", + e + ); + } + // A name of an inode that does not have what the first name of + // that inode has is refused as well, and the first name stays. + let linked = |name: &str, size| { + let mut object = FileObject::new(testing::name(name)); + object.set_inode_token(std::num::NonZeroU64::new(1)); + object.set_size(Some(size)); + object + }; + writer.add_object(&linked("first", 1)).unwrap(); + let e = writer.add_object(&linked("other", 2)).unwrap_err(); + assert_eq!( + (e.kind(), e.name(), e.hardlink_name()), + ( + ErrorKind::Tree(TreeProblem::HardlinkMismatch), + Some("other"), + Some("first") + ) + ); + let added = FileObject::new(testing::name("added")); + writer.add_object(&added).unwrap(); + let (out, _) = writer.finish().unwrap(); + let mut clean = ManifestOptions::new().open(Vec::new()).unwrap(); + clean.add_object(&linked("first", 1)).unwrap(); + clean.add_object(&added).unwrap(); + let (clean, _) = clean.finish().unwrap(); + assert_eq!(out, clean); + } + + /// The root a caller describes is the root file object of the manifest, + /// with the features and the order of the options, and the first root + /// that is added says what the root is like. A root with a field of a + /// feature the manifest does not record is refused when it is added, + /// and so is one with a field or a string no manifest may have, and one + /// whose record is too large. The writer is as it was then: what it + /// writes is what it writes without the roots it refused. + #[test] + fn roots_of_a_caller() { + let mode = |bits| { + let mut inode = InodeAttributes::default(); + inode.set_mode(Some(crate::Mode::new(bits).unwrap())); + inode + }; + let labeled = |label: &str| FileSystemIdentity { + label: Some(label.to_string()), + ..FileSystemIdentity::default() + }; + let unlabeled = FileSystemIdentity::default(); + let features = Features::MODE | Features::MTIME | Features::FS_LABEL; + let mut options = ManifestOptions::new(); + options.features(features); + let mut inode = mode(0o750); + inode.set_mtime_nsec(Some(1_000_000_007)); + let file = FileObject::new(testing::name("x")); + let mut writer = options.open(Vec::new()).unwrap(); + writer.add_object(&file).unwrap(); + writer.add_root(&inode, &labeled("ESP")).unwrap(); + writer.add_root(&mode(0o700), &labeled("other")).unwrap(); + let (out, report) = writer.finish().unwrap(); + let whole = read_whole(&out).unwrap(); + assert!(whole.root.inode().eq_ignore_filled_in(&inode)); + assert_eq!(whole.root.file_system(), &labeled("ESP")); + assert_eq!( + (whole.root.features(), whole.root.order()), + (Some(features), Some(Order::CodePoint)) + ); + assert_eq!((whole.objects.len(), report.files(), report.directories()), (1, 1, 1)); + // Roots that are refused: the label is recorded and the + // modification time is not. + options.features(Features::MODE | Features::UID | Features::FS_LABEL | Features::USER_XATTR); + let mut owned = mode(0o755); + owned.set_uid(Some(65535)); + let mut large = mode(0o755); + large.set_user_xattrs(Some([("large".to_string(), vec![0; crate::MAX_RECORD_SIZE])].into())); + let refused = [ + ( + &inode, + &unlabeled, + crate::Problem::UnlistedFeature, + Some(crate::Field::MTimeNSec), + ), + ( + &owned, + &unlabeled, + crate::Problem::FieldOutOfRange, + Some(crate::Field::Uid), + ), + ( + &mode(0o755), + &labeled("a\0b"), + crate::Problem::InvalidString, + Some(crate::Field::FsLabel), + ), + (&large, &unlabeled, crate::Problem::RecordTooLarge, None), + ]; + let mut writer = options.open(Vec::new()).unwrap(); + for (inode, file_system, problem, field) in refused { + let e = writer.add_root(inode, file_system).unwrap_err(); + assert_eq!( + (e.kind(), e.field(), e.name(), e.record_number()), + (ErrorKind::Manifest(problem), field, None, None), + "{}", + e + ); + } + writer.add_root(&mode(0o711), &labeled("ESP")).unwrap(); + writer.add_object(&file).unwrap(); + let (out, _) = writer.finish().unwrap(); + let mut clean = options.open(Vec::new()).unwrap(); + clean.add_root(&mode(0o711), &labeled("ESP")).unwrap(); + clean.add_object(&file).unwrap(); + assert_eq!(out, clean.finish().unwrap().0); + assert_eq!(read_whole(&out).unwrap().root.inode().mode(), mode(0o711).mode()); + // A root whose record is as large as a record may be is taken, and + // one byte more is refused when it is added: the record that is + // checked is the one the manifest gets, with the features and the + // order of the options. + let sized = |value: usize| { + let mut inode = mode(0o755); + inode.set_user_xattrs(Some([("large".to_string(), vec![b'a'; value])].into())); + inode + }; + let root_record = |out: &[u8]| out.iter().position(|&byte| byte == crate::RECORD_END).unwrap() + 1; + let mut writer = options.open(Vec::new()).unwrap(); + writer.add_root(&sized(1), &unlabeled).unwrap(); + let fits = crate::MAX_RECORD_SIZE - (root_record(&writer.finish().unwrap().0) - 1); + let mut writer = options.open(Vec::new()).unwrap(); + let e = writer.add_root(&sized(fits + 1), &unlabeled).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(crate::Problem::RecordTooLarge)); + writer.add_root(&sized(fits), &unlabeled).unwrap(); + assert_eq!(root_record(&writer.finish().unwrap().0), crate::MAX_RECORD_SIZE); + } + + /// A manifest that records the UUID or the volume serial number of its + /// file system need not have one. Without a root it is written with a + /// plain one, a root a caller describes without them is taken as it + /// is, and the walk of a tree leaves out the one its file system does + /// not have. Only the walk counts what it leaves out. + #[test] + fn roots_without_a_uuid_or_a_serial() { + let features = Features::DEFAULT | Features::FS_UUID | Features::FAT_SERIAL; + let mut options = ManifestOptions::new(); + options.features(features); + let file = FileObject::new(testing::name("x")); + let root_of = |out: &[u8]| read_whole(out).unwrap().root; + let mut writer = options.open(Vec::new()).unwrap(); + writer.add_object(&file).unwrap(); + let (plain, report) = writer.finish().unwrap(); + assert_eq!( + (root_of(&plain).features(), root_of(&plain).file_system()), + (Some(features), &FileSystemIdentity::default()) + ); + assert_eq!(report.fields_omitted(), 0); + let mut writer = options.open(Vec::new()).unwrap(); + writer + .add_root(&InodeAttributes::default(), &FileSystemIdentity::default()) + .unwrap(); + writer.add_object(&file).unwrap(); + let (given, report) = writer.finish().unwrap(); + assert_eq!((&given, report.fields_omitted()), (&plain, 0)); + // A root with one of the two has it. + let with_uuid = FileSystemIdentity { + uuid: Some("1234abcd-5678-4ef0-9abc-def012345678".parse().unwrap()), + ..FileSystemIdentity::default() + }; + let mut writer = options.open(Vec::new()).unwrap(); + writer.add_root(&InodeAttributes::default(), &with_uuid).unwrap(); + assert_eq!(root_of(&writer.finish().unwrap().0).file_system(), &with_uuid); + // The walk of a tree records what its file system has of the two, + // and fails for neither: a file system with a UUID is no FAT, and + // FAT has none. It counts each one that it leaves out, and none + // that the manifest does not record. + let tree = tree("manifest-identity"); + let walk = |recorded| { + let mut options = ManifestOptions::new(); + options.features(recorded); + let (out, report) = options + .generate(Vec::new(), open_path(&tree.0), AddFlags::NONE) + .unwrap(); + (root_of(&out), report.fields_omitted()) + }; + let (root, omitted) = walk(features); + assert_eq!((root.features(), root.file_system().label()), (Some(features), None)); + let (uuid, serial) = (root.file_system().uuid(), root.file_system().fat_serial()); + let (no_uuid, no_serial) = (u64::from(uuid.is_none()), u64::from(serial.is_none())); + assert_eq!(omitted, no_uuid + no_serial); + let (root, omitted) = walk(Features::DEFAULT | Features::FS_UUID); + assert_eq!((root.file_system().uuid(), omitted), (uuid, no_uuid)); + let (root, omitted) = walk(Features::DEFAULT | Features::FAT_SERIAL); + assert_eq!((root.file_system().fat_serial(), omitted), (serial, no_serial)); + assert_eq!(walk(Features::DEFAULT).1, 0); + } + + /// The variable that tells the test binary, run again inside the + /// namespaces of [`trees_without_a_uuid_or_a_serial`], where the + /// directory with the mount is. + const RAMFS_DIR: &str = "UAPI16_TEST_MANIFEST_RAMFS_DIR"; + + /// The walk of a tree whose file system has neither a UUID nor a volume + /// serial number leaves out both, and the report counts each of them. + /// A ramfs is such a file system. Mounting one takes a user and a + /// mount namespace, which unshare(1) makes, and the test binary runs + /// this test again inside them. It is skipped where the kernel gives a + /// ramfs a UUID, which the mount is asked for first. + #[test] + fn trees_without_a_uuid_or_a_serial() { + if let Some(dir) = std::env::var_os(RAMFS_DIR) { + let tree = Path::new(&dir).join("mount"); + // The mount is asked as a walk asks the root of a tree. + let asked = Entry::of(open_path(&tree).as_fd()).unwrap().reopen(None).unwrap(); + if matches!(asked.fs_uuid().unwrap(), Some(FsUuid::Uuid(_))) { + eprintln!("skipping: a ramfs has a UUID here"); + return; + } + fs::write(tree.join("file"), b"hello").unwrap(); + for (features, left_out) in [ + (Features::FS_UUID, 1), + (Features::FAT_SERIAL, 1), + (Features::FS_UUID | Features::FAT_SERIAL, 2), + (Features::NONE, 0), + ] { + let mut options = ManifestOptions::new(); + options.features(features); + let (out, report) = options.generate(Vec::new(), open_path(&tree), AddFlags::NONE).unwrap(); + let root: RootObject = read_whole(&out).unwrap().root; + assert_eq!( + (root.file_system(), report.fields_omitted(), report.files()), + (&FileSystemIdentity::default(), left_out, 1), + "{:?}", + features + ); + } + return; + } + let tmp = TempDir::new("manifest-ramfs"); + let dir = &tmp.0; + fs::create_dir(dir.join("mount")).unwrap(); + let works = Command::new("unshare").args(["-Urm", "true"]).output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urm does not work here"); + return; + } + let script = concat!( + r#"set -e; mount -t ramfs ramfs "$1/mount"; "#, + r#"exec "$2" --exact manifest::tests::trees_without_a_uuid_or_a_serial --nocapture"# + ); + let output = Command::new("unshare") + .args(["-Urm", "sh", "-c", script, "sh"]) + .arg(dir) + .arg(std::env::current_exe().unwrap()) + .env(RAMFS_DIR, dir) + .output() + .unwrap(); + // What the test said where it ran again, such as that it skipped. + let said = String::from_utf8_lossy(&output.stderr); + if let Some(skipped) = said.lines().find(|line| line.starts_with("skipping")) { + eprintln!("{}", skipped); + } + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } + + /// A writer shows what it writes to. + #[test] + fn debug() { + let tree = tree("manifest-debug"); + let writer = ManifestOptions::new().open(Vec::::new()).unwrap(); + assert_eq!(format!("{:?}", writer), "ManifestWriter { out: [], .. }"); + let out = TempDir::new("manifest-debug-out"); + let writer = ManifestOptions::new() + .create_at(File::open(&out.0).unwrap(), Path::new("m")) + .unwrap(); + let shown = format!("{:?}", writer); + assert!(shown.starts_with("ManifestWriter { out: File {"), "{}", shown); + assert!(shown.ends_with(" }, .. }"), "{}", shown); + drop(tree); + } + + /// A manifest file is not synced unless asked for, and one that is + /// comes out the same, from create_at() and from generate_at(). + #[test] + fn synced_files() { + assert!(!ManifestOptions::new().sync); + assert!(!ManifestOptions::default().sync); + let tree = tree("manifest-sync"); + let out = TempDir::new("manifest-sync-out"); + let (expected, _) = ManifestOptions::new() + .generate(Vec::new(), open_path(&tree.0), AddFlags::NONE) + .unwrap(); + let mut options = ManifestOptions::new(); + options.sync(true); + let mut writer = options.create_at(File::open(&out.0).unwrap(), Path::new("m")).unwrap(); + writer.add_all(open_path(&tree.0).as_fd(), AddFlags::NONE).unwrap(); + writer.finish().unwrap(); + assert_eq!(fs::read(out.0.join("m")).unwrap(), expected); + options + .generate_at( + File::open(&out.0).unwrap(), + Path::new("again"), + open_path(&tree.0), + AddFlags::NONE, + ) + .unwrap(); + assert_eq!(fs::read(out.0.join("again")).unwrap(), expected); + } + + /// A finish() that fails after the call that gave the file its name + /// leaves the manifest in the file, which keeps the name. Here the + /// directory takes the name and can't be opened for the sync of it, + /// since it may not be read. It is skipped where the tests may read any + /// directory. + #[test] + fn keeps_the_manifest_where_the_sync_fails() { + let tmp = TempDir::new("manifest-sync-fails"); + let dir = &tmp.0; + let mut options = ManifestOptions::new(); + options.sync(true); + let mut writer = options.create_at(File::open(dir).unwrap(), Path::new("m")).unwrap(); + writer.add_object(&FileObject::new(testing::name("file"))).unwrap(); + // A directory that may be written and searched, and not read. + let locked = fs::set_permissions(dir, fs::Permissions::from_mode(0o300)).is_ok() && fs::read_dir(dir).is_err(); + let finished = writer.finish(); + let manifest = fs::read(dir.join("m")); + fs::set_permissions(dir, fs::Permissions::from_mode(0o700)).unwrap(); + if !locked { + eprintln!("skipping the directory that can't be synced: the tests may read any"); + return; + } + assert_eq!(errno(&finished.unwrap_err()), Some(libc::EACCES)); + let whole = read_whole(&manifest.unwrap()).unwrap(); + let listed: Vec<&str> = whole.objects.iter().map(|object| object.name().as_str()).collect(); + assert_eq!((listed, names_in(dir)), (vec!["file"], vec!["m".to_string()])); + } + + /// The variable that names a directory of a FAT file system, as for + /// the tests of the optional features. + const FAT_DIR: &str = "UAPI16_TEST_FAT_DIR"; + + /// File objects of a caller that take more room than the 32 MiB the + /// sort keeps in memory, so that a manifest that lists them writes + /// runs to a scratch file. + fn large_objects() -> Vec { + (0..40u8) + .map(|i| { + let mut object = FileObject::new(testing::name(&format!("large/{:02}", i))); + let data = vec![i; 1 << 20]; + object.set_size(Some(data.len() as u64)); + object.put_contents(vec![crate::ContentsObject::new(crate::ContentsSource::Literal(data))]); + object + }) + .collect() + } + + /// On FAT, which has no O_TMPFILE, a new manifest file has a name of + /// its own until it is complete and gets its own with RENAME_NOREPLACE, + /// and the scratch files get names that they lose right away. File + /// objects that take more room than the sort keeps in memory make it + /// write runs to them. The manifest is the one written to a stream, and + /// nothing else is left behind. FAT has a volume serial number and no + /// UUID, which the walk of a tree there leaves out and counts. + #[test] + fn on_fat() { + let Some(dir) = std::env::var_os(FAT_DIR) else { + eprintln!("skipping: {} names no directory of a FAT file system", FAT_DIR); + return; + }; + fn fill(writer: &mut ManifestWriter, tree: &Path, large: &[FileObject]) { + writer.add_all(open_path(tree).as_fd(), AddFlags::NONE).unwrap(); + for object in large { + writer.add_object(object).unwrap(); + } + } + let fat = Path::new(&dir).join("manifest-on-fat"); + let _ = fs::remove_dir_all(&fat); + let tree = fat.join("tree"); + fs::create_dir_all(tree.join("a")).unwrap(); + fs::write(tree.join("a/file"), b"hello").unwrap(); + fs::write(tree.join("file"), b"world").unwrap(); + let large = large_objects(); + let mut options = ManifestOptions::new(); + options.sync(true); + let mut writer = options.create_at(File::open(&fat).unwrap(), Path::new("m")).unwrap(); + fill(&mut writer, &tree, &large); + writer.finish().unwrap(); + let mut writer = options.open(Vec::new()).unwrap(); + fill(&mut writer, &tree, &large); + let (streamed, report) = writer.finish().unwrap(); + assert_eq!((report.files(), report.directories()), (42, 3)); + assert_eq!(fs::read(fat.join("m")).unwrap(), streamed); + assert_eq!(names_in(&fat), ["m", "tree"]); + let scratch = std::env::temp_dir(); + assert!(names_in(&scratch).iter().all(|name| !name.starts_with(".uapi16-"))); + for (features, left_out) in [ + (Features::FS_UUID, 1), + (Features::FS_UUID | Features::FAT_SERIAL, 1), + (Features::FAT_SERIAL, 0), + ] { + let mut options = ManifestOptions::new(); + options.features(Features::DEFAULT | features); + let (out, report) = options.generate(Vec::new(), open_path(&tree), AddFlags::NONE).unwrap(); + let root: RootObject = read_whole(&out).unwrap().root; + let identity = root.file_system(); + assert_eq!( + ( + identity.uuid(), + identity.fat_serial().is_some(), + report.fields_omitted() + ), + (None, features.contains(Features::FAT_SERIAL), left_out), + "{:?}", + features + ); + } + fs::remove_dir_all(&fat).unwrap(); + } + + /// The variable that names a directory of a file system that keeps a + /// file that is unlinked while it is open in its directory, under a + /// name of its own, until the file is closed: NFS does, and so does + /// libfuse for a FUSE file system on its high-level interface that does + /// not set hard_remove. + const SILLY_RENAME_DIR: &str = "UAPI16_TEST_SILLY_RENAME_DIR"; + + /// Whether the directory `dir` comes to hold the names `names` and no + /// others. A file system that keeps a file that was unlinked takes a + /// moment to remove it once it was closed. + fn comes_to_hold(dir: &Path, names: &[&str]) -> bool { + const TRIES: u32 = 500; + const PAUSE: std::time::Duration = std::time::Duration::from_millis(10); + (0..TRIES).any(|_| { + let there = names_in(dir) == names; + if !there { + std::thread::sleep(PAUSE); + } + there + }) + } + + /// A manifest lists none of the files it made itself. On a file system + /// that keeps a file that was unlinked while it is open, the scratch + /// files of a manifest that is created in the tree it lists are in a + /// directory of that tree, under the names the file system gave them. + /// The walk passes over them, and over the manifest, which has a name + /// of its own there until it is complete. Nothing but the manifest is + /// left behind. It is skipped unless the variable names a directory of + /// such a file system. + #[test] + fn scratch_files_in_the_tree() { + let Some(dir) = std::env::var_os(SILLY_RENAME_DIR) else { + eprintln!( + "skipping: {} names no directory of a file system that keeps unlinked files", + SILLY_RENAME_DIR + ); + return; + }; + let top = Path::new(&dir).join("manifest-scratch-in-the-tree"); + let out = top.join("out"); + // What an earlier run left behind: its directories, where the file + // system removes none, see below. + let _ = fs::remove_file(out.join("m")); + let _ = fs::remove_dir_all(&top); + fs::create_dir_all(top.join("a")).unwrap(); + fs::create_dir_all(&out).unwrap(); + fs::write(top.join("a/file"), b"hello").unwrap(); + // The file system is one that keeps such a file, until it is closed. + let unlinked = File::create(out.join("unlinked")).unwrap(); + fs::remove_file(out.join("unlinked")).unwrap(); + assert_eq!(names_in(&out).len(), 1, "{:?} keeps no file that was unlinked", out); + drop(unlinked); + assert!(comes_to_hold(&out, &[])); + let mut writer = ManifestOptions::new() + .create_at(File::open(&out).unwrap(), Path::new("m")) + .unwrap(); + for object in &large_objects() { + writer.add_object(object).unwrap(); + } + // The scratch file of the sort is in the directory now, next to + // the manifest where that has a name of its own. + let kept = names_in(&out); + assert!(kept.iter().any(|name| !name.starts_with(".#uapi16-")), "{:?}", kept); + writer.add_all(open_path(&top).as_fd(), AddFlags::NONE).unwrap(); + let (_, report) = writer.finish().unwrap(); + let whole = read_whole(&fs::read(out.join("m")).unwrap()).unwrap(); + let listed: Vec<&str> = whole + .objects + .iter() + .map(|object| object.name().as_str()) + .filter(|name| !name.starts_with("large")) + .collect(); + assert_eq!(listed, ["a", "a/file", "out"]); + assert_eq!((report.files(), report.directories()), (41, 4)); + assert!(comes_to_hold(&out, &["m"])); + // A FUSE file system need not be able to remove a directory, which + // is ENOSYS then. The files go, and the directories are left behind. + fs::remove_file(out.join("m")).unwrap(); + fs::remove_file(top.join("a/file")).unwrap(); + if let Err(e) = fs::remove_dir_all(&top) { + assert_eq!(e.raw_os_error(), Some(libc::ENOSYS), "{}", e); + } + } + + /// Two file objects of a caller that are hard links of each other, by + /// the token `token`. + fn linked(token: u64) -> [FileObject; 2] { + ["a", "b"].map(|side| { + let mut object = FileObject::new(testing::name(&format!("links/{}-{}", token, side))); + object.set_inode_token(std::num::NonZeroU64::new(token)); + object + }) + } + + /// The files this process has open that were made in the directory + /// `dir`, but for the files `others`: the scratch files of a writer + /// that makes them there, where `others` is its new file. + fn open_but(dir: &Path, others: &[OpenFile]) -> Vec { + let mut files = OpenFile::made_in(dir); + files.retain(|file| others.iter().all(|other| other.inode != file.inode)); + files + } + + /// A writer has every scratch file it made open for as long as it is + /// there, also the ones it is done with. The table of the hard links + /// gives back the file of its old pages once it has doubled on disk. + /// That file is empty and open from then on, and the next doubling goes + /// into it. So the table has three scratch files however often it + /// doubles. A writer that is dropped closes all of them, and so does + /// finish(). + #[test] + fn keeps_its_scratch_files_open() { + /// Far more hard links than move the table of the hard links to + /// disk and double it there. + const MOST: u64 = 500_000; + /// How many hard links are added before the scratch files are + /// looked at again. + const BATCH: u64 = 1000; + /// The scratch files of a table on disk: its pages, its names, and + /// the pages it had, which is the file it doubles into next. + const FILES: usize = 3; + let tmp = TempDir::new("manifest-kept"); + let dir = &tmp.0; + for finish in [false, true] { + let mut writer = ManifestOptions::new() + .create_at(File::open(dir).unwrap(), Path::new("m")) + .unwrap(); + // What the writer has open in the directory but for the new + // file, which is all it has there before the first add. + let new_file = OpenFile::made_in(dir); + let scratch_files = || open_but(dir, &new_file); + assert!(scratch_files().is_empty()); + // Until the table is on disk and has doubled there twice: the + // file that is empty is another one after each doubling. + let mut token = 0; + let mut emptied: Vec = Vec::new(); + let files = loop { + let files = scratch_files(); + assert!(files.len() <= FILES, "{:?}", files); + let empty: Vec<_> = files.iter().filter(|file| file.size == 0).collect(); + assert!(empty.len() <= 1, "{:?}", files); + if let Some(empty) = empty.first().filter(|empty| emptied.last() != Some(&empty.inode)) { + emptied.push(empty.inode); + } + if emptied.len() == 2 { + break files; + } + assert!(token < MOST, "{:?}", files); + for _ in 0..BATCH { + token += 1; + for object in linked(token) { + writer.add_object(&object).unwrap(); + } + } + }; + // The pages and the names of the table, and the file of the + // pages it had before, which the second doubling made no new + // file for. + assert_eq!(files.len(), FILES, "{:?}", files); + if finish { + writer.finish().unwrap(); + assert!(OpenFile::made_in(dir).is_empty()); + assert!(comes_to_hold(dir, &["m"])); + fs::remove_file(dir.join("m")).unwrap(); + } else { + drop(writer); + assert!(OpenFile::made_in(dir).is_empty()); + assert!(comes_to_hold(dir, &[])); + } + } + } + + /// The variable that tells the test binary, run again by + /// [`gives_its_scratch_files_back`], where the directory of the test + /// is, which is the temporary directory of that process. + const GIVEN_BACK_DIR: &str = "UAPI16_TEST_MANIFEST_GIVEN_BACK_DIR"; + + /// How the writer of [`gives_its_scratch_files_back`] ends. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum End { + Finished, + StepFailed, + NameTaken, + WalkFailed, + Dropped, + } + + /// finish() gives the scratch files of its writer back before it closes + /// them, which empties them, also where it fails, and so does a + /// generate function whose walk fails. A finish() that fails before the + /// new file has its name empties it as well. A writer that is dropped + /// closes its files as they are. A writer of open(), which has no new + /// file, gives its scratch files back as one of create_at() does. It + /// keeps them in the temporary directory, where other tests have + /// theirs. So the test binary runs this test again in a process of its + /// own, whose temporary directory is the directory of the test. The + /// test has a handle of its own of each of the files, which keeps the + /// file, and so sees what they are left with. The writer of + /// generate_at() is nobody's but its own, so another thread takes the + /// handles of its files while it walks a tree, and fails the walk then. + #[test] + fn gives_its_scratch_files_back() { + /// More hard links than take the table of the hard links to disk. + const LINKS: u64 = 20_000; + /// The scratch files of the table that hold something then: its + /// pages and its names. + const FILES: usize = 2; + /// The variable that names the temporary directory. + const TMPDIR: &str = "TMPDIR"; + /// The size of a sparse file that takes a walk seconds to hash, and + /// a minute in a build that is not optimized. + const BRAKE: u64 = 4 << 30; + /// How long the thread that looks at the descriptors of the process + /// waits between two looks. + const PAUSE: std::time::Duration = std::time::Duration::from_millis(1); + let Some(dir) = std::env::var_os(GIVEN_BACK_DIR) else { + let tmp = TempDir::new("manifest-given-back"); + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "manifest::tests::gives_its_scratch_files_back", + "--nocapture", + ]) + .env(GIVEN_BACK_DIR, &tmp.0) + .env(TMPDIR, &tmp.0) + .output() + .unwrap(); + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + return; + }; + let dir = Path::new(&dir); + let handle = |file: &OpenFile| { + let descriptor = format!("/proc/self/fd/{}", file.descriptor); + rustix::fs::open(descriptor, OFlags::PATH | OFlags::CLOEXEC, rustix::fs::Mode::empty()).unwrap() + }; + let size = |handle: &OwnedFd| Status::of(handle.as_fd()).unwrap().size; + // Every end of a writer of create_at(), and two of a writer of + // open(), which give back where there is no new file: a finish() + // that returns, and a walk that fails. + for case @ (created, end) in [ + (true, End::Finished), + (true, End::StepFailed), + (true, End::NameTaken), + (true, End::WalkFailed), + (true, End::Dropped), + (false, End::Finished), + (false, End::WalkFailed), + ] { + let options = ManifestOptions::new(); + let mut writer = if created { + options.create_at(File::open(dir).unwrap(), Path::new("m")).unwrap() + } else { + // What it writes is not looked at. + options.open(File::create("/dev/null").unwrap()).unwrap() + }; + // The new file, which is all a writer has open in the directory + // before the first add: a writer of open() has nothing there. + let new_file = OpenFile::made_in(dir); + assert_eq!(new_file.is_empty(), !created); + for object in (1..=LINKS).flat_map(linked) { + writer.add_object(&object).unwrap(); + } + // One of them has the scratch file of the sort as well. That + // takes file objects of more than 32 MiB, and a while. + let runs = created && end == End::WalkFailed; + if runs { + for object in &large_objects() { + writer.add_object(object).unwrap(); + } + } + let held: Vec = open_but(dir, &new_file).iter().map(handle).collect(); + let manifest = new_file.first().map(handle); + let sizes = || -> Vec { held.iter().map(size).collect() }; + let before = sizes(); + let with_data = before.iter().filter(|&&size| size > 0).count(); + assert_eq!(with_data, FILES + usize::from(runs), "{:?}", before); + match end { + End::Finished => drop(writer.finish().unwrap()), + End::StepFailed => { + // Two files with one name, which the last step of the + // manifest comes to, once most of it is written. + for size in [1, 2] { + let mut object = FileObject::new(testing::name("twice")); + object.set_size(Some(size)); + writer.add_object(&object).unwrap(); + } + let e = writer.finish().unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::Duplicate)); + assert_eq!(manifest.as_ref().map(size), Some(0)); + } + End::NameTaken => { + // Something else has the name by now. So finish() + // writes the manifest and fails where the file is to + // get the name. + fs::write(dir.join("m"), b"").unwrap(); + assert_eq!(errno(&writer.finish().unwrap_err()), Some(libc::EEXIST)); + assert_eq!(manifest.as_ref().map(size), Some(0)); + } + End::WalkFailed => { + // What is no directory is no tree to walk. + let top = File::open("/dev/null").unwrap(); + let e = writer.generate(top.as_fd(), AddFlags::NONE).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::NotDirectory)); + } + End::Dropped => drop(writer), + } + if end == End::Dropped { + assert_eq!(sizes(), before); + } else { + assert!(sizes().iter().all(|&size| size == 0), "{:?}: {:?}", case, sizes()); + } + let _ = fs::remove_file(dir.join("m")); + } + // generate_at() has its writer to itself, so another thread takes + // the handles while it walks a tree. The tree has two directories. + // The one readdir() gives first has the files with two names, which + // take the table to disk, and the other one a sparse file that + // takes long to hash. So the scratch files hold something from + // then on, and the walk can't be over before the thread looked at + // the descriptors once. It takes its handles and only then fails + // the walk: with a file it puts into the tree, for a walk that is + // still at the files with two names and comes back to the top, and + // by cutting the sparse file off, for one that hashes it. + let top = dir.join("tree/top"); + for half in ["a", "b"] { + fs::create_dir_all(top.join(half)).unwrap(); + } + let halves: Vec<_> = fs::read_dir(&top).unwrap().map(|half| half.unwrap().path()).collect(); + let (links, brake) = (&halves[0], halves[1].join("brake")); + // The sparse file is made before the links: FAT takes neither, and + // this is skipped there. + if let Err(e) = File::create(&brake).unwrap().set_len(BRAKE) { + eprintln!( + "skipping generate_at(): the temporary directory takes no file of that size: {}", + e + ); + return; + } + for number in 0..LINKS { + let name = links.join(number.to_string()); + fs::write(&name, b"").unwrap(); + fs::hard_link(&name, name.with_extension("b")).unwrap(); + } + let over = std::sync::atomic::AtomicBool::new(false); + let (walked, held) = std::thread::scope(|scope| { + let looking = scope.spawn(|| { + while !over.load(std::sync::atomic::Ordering::Relaxed) { + let files = OpenFile::made_in(dir); + if files.iter().filter(|file| file.size > 0).count() >= FILES { + let held: Vec = files.iter().map(handle).collect(); + File::create(top.join("late")).unwrap(); + File::create(&brake).unwrap(); + return Some(held); + } + std::thread::sleep(PAUSE); + } + None + }); + let (into, tree) = (File::open(dir).unwrap(), File::open(&top).unwrap()); + let walked = ManifestOptions::new().generate_at(into, Path::new("m"), tree, AddFlags::NONE); + over.store(true, std::sync::atomic::Ordering::Relaxed); + (walked, looking.join().unwrap()) + }); + assert_eq!(walked.unwrap_err().kind(), ErrorKind::Tree(TreeProblem::Changed)); + // The new file and the scratch files, each as the walk left it. + let held = held.expect("the scratch files of the walk never held anything"); + let left: Vec = held.iter().map(size).collect(); + assert!(left.len() > FILES && left.iter().all(|&size| size == 0), "{:?}", left); + } + + /// A writer can go to another thread where what it writes to can, and + /// so can the options, the report and the errors. + #[test] + fn send_and_sync() { + fn send() {} + fn send_sync() {} + fn send_sync_static() {} + send::>(); + send::>>(); + send_sync::(); + send_sync::(); + send_sync::(); + send_sync_static::(); + } +} diff --git a/src/uapi16/metadata.rs b/src/uapi16/metadata.rs index 37461f9..4c5d533 100644 --- a/src/uapi16/metadata.rs +++ b/src/uapi16/metadata.rs @@ -13,9 +13,10 @@ impl FileObject { /// [`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. + /// except on a symbolic link, the user and the group ID of the owner + /// where a manifest can record them, 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 @@ -28,30 +29,33 @@ impl FileObject { /// /// [`RootObject::recorded_features`]: crate::RootObject::recorded_features pub fn from_metadata(name: NameBuf, meta: &Metadata, features: Features) -> Result { + let inode_type = InodeType::try_from(meta.file_type())?; 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())); + object.set_inode_type(inode_type); + let inode = object.inode_mut(); + if features.contains(Features::MODE) && inode_type != InodeType::Symlink { + inode.set_mode(Some(Mode::from_st_mode(meta.mode()))); } + // A manifest can't record the two IDs that stand for no ID, and a + // writer refuses them. if features.contains(Features::UID) { - inode.uid = Some(meta.uid()); + inode.set_uid(Some(meta.uid()).filter(|&uid| FileObject::is_valid_id(uid))); } if features.contains(Features::GID) { - inode.gid = Some(meta.gid()); + inode.set_gid(Some(meta.gid()).filter(|&gid| FileObject::is_valid_id(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::SIZE) && inode_type == InodeType::Regular { + object.set_size(Some(meta.len())); } - if features.contains(Features::DEVICE) && object.inode_type.is_device() { + if features.contains(Features::DEVICE) && 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))); + object.set_major(Some(u64::from(rustix::fs::major(device)))); + object.set_minor(Some(u64::from(rustix::fs::minor(device)))); } Ok(object) } @@ -62,13 +66,14 @@ mod tests { use super::*; use crate::object::{ContentsObject, ContentsSource, InodeAttributes}; use crate::testing::TempDir; - use crate::{RootObject, Writer}; + use crate::{ErrorKind, Field, ManifestOptions, Problem, 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::fs::{symlink, PermissionsExt}; use std::os::unix::net::UnixListener; - use std::path::PathBuf; + use std::path::{Path, PathBuf}; + use std::process::Command; /// 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 @@ -101,13 +106,11 @@ mod tests { let mut object = FileObject::from_metadata(NameBuf::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() - }; + let mut inode = InodeAttributes::default(); + let mode = has(Features::MODE) && *inode_type != InodeType::Symlink; + inode.set_mode(mode.then(|| Mode::from_st_mode(meta.mode()))); + inode.set_uid(has(Features::UID).then(|| meta.uid())); + inode.set_gid(has(Features::GID).then(|| meta.gid())); if has(Features::MTIME) { inode.set_mtime(meta.modified().unwrap()); } @@ -138,4 +141,142 @@ mod tests { writer.finish().unwrap(); } } + + /// The variable that names the file the test binary looks at where it + /// runs [`owners_a_manifest_cannot_record`] again in a user namespace. + const NO_OWNER_FILE: &str = "UAPI16_TEST_METADATA_NO_OWNER_FILE"; + + /// The variable that says which IDs of the test that user namespace + /// maps: its user, its group, or both. + const NO_OWNER_MAPS: &str = "UAPI16_TEST_METADATA_NO_OWNER_MAPS"; + + /// The ID a user namespace of the test maps the user or the group of + /// the test to: the one of the two IDs that stand for no ID that a file + /// can have. + const NO_ID: u32 = u16::MAX as u32; + + /// A file whose owner has the user or the group ID 65535 gets an + /// object without that ID, since a manifest can't record it, and with + /// the other one. A writer takes the object, and refuses it with the ID + /// that was left out. So does the builder, as a file object of a + /// caller. The file is one of the test's own, seen from a user + /// namespace that maps the user of the test to that ID, its group, or + /// both. The one that is not mapped shows as the overflow ID, which a + /// manifest can record, so that the user ID is told by itself and not + /// by the group ID, and the other way round. unshare(1) makes the + /// namespaces, and the test binary runs this test again in each. It is + /// skipped where unshare can't do that. + /// + /// No stat() gives the other ID a manifest can't record, 4294967295: + /// the kernel shows an owner it can't map as the overflow ID. So what + /// tells the two IDs from all others is asked for it directly. + #[test] + fn owners_a_manifest_cannot_record() { + if let Some(file) = std::env::var_os(NO_OWNER_FILE) { + let maps = std::env::var(NO_OWNER_MAPS).unwrap(); + return check_no_owner(Path::new(&file), maps.contains("user"), maps.contains("group")); + } + for id in [NO_ID, u32::MAX] { + assert!(!FileObject::is_valid_id(id), "{}", id); + } + for id in [0, NO_ID - 1, NO_ID + 1, u32::MAX - 1] { + assert!(FileObject::is_valid_id(id), "{}", id); + } + let tmp = TempDir::new("metadata-no-owner"); + // A setgid directory hands its group down to the file. The group + // unshare maps is that of this process. + fs::set_permissions(&tmp.0, fs::Permissions::from_mode(0o700)).unwrap(); + let file = tmp.0.join("file"); + fs::write(&file, b"hello").unwrap(); + for maps in [&["user", "group"][..], &["user"], &["group"]] { + let mut map = vec!["--user".to_owned()]; + map.extend(maps.iter().map(|id| format!("--map-{}={}", id, NO_ID))); + let works = Command::new("unshare").args(&map).arg("true").output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare {} does not work here", map.join(" ")); + return; + } + let output = Command::new("unshare") + .args(&map) + .arg(std::env::current_exe().unwrap()) + .args(["--exact", "metadata::tests::owners_a_manifest_cannot_record"]) + .env(NO_OWNER_FILE, &file) + .env(NO_OWNER_MAPS, maps.join(" ")) + .output() + .unwrap(); + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}: {:?}", maps, output); + } + } + + /// The checks of [`owners_a_manifest_cannot_record`] for `file`, in a + /// user namespace that maps the user of the test to [`NO_ID`] if + /// `user` says so, and its group if `group` does. + fn check_no_owner(file: &Path, user: bool, group: bool) { + let meta = fs::metadata(file).unwrap(); + assert!(!user || meta.uid() == NO_ID, "{}", meta.uid()); + assert!(!group || meta.gid() == NO_ID, "{}", meta.gid()); + // The ID a manifest can't record is left out, and no other. + let kept = |id: u32| Some(id).filter(|&id| id != NO_ID); + for features in [Features::UID | Features::GID, Features::ALL] { + let name = NameBuf::new("file").unwrap(); + let object = FileObject::from_metadata(name, &meta, features).unwrap(); + assert_eq!( + (object.inode().uid(), object.inode().gid()), + (kept(meta.uid()), kept(meta.gid())) + ); + // What a manifest can record of the file is there. + let all = features == Features::ALL; + assert_eq!(object.inode().mode().is_some(), all); + assert_eq!(object.size(), all.then_some(5)); + let mut root = RootObject::default(); + root.set_features(Some(features)); + let mut writer = Writer::begin(Vec::new(), &root).unwrap(); + writer.file(&object).unwrap(); + // With the ID that was left out, the writer refuses the object. + for (field, left_out) in [(Field::Uid, meta.uid()), (Field::Gid, meta.gid())] { + if left_out != NO_ID { + continue; + } + let mut refused = object.clone(); + refused.set_name(NameBuf::new("refused").unwrap()); + match field { + Field::Uid => refused.inode_mut().set_uid(Some(meta.uid())), + _ => refused.inode_mut().set_gid(Some(meta.gid())), + } + let e = writer.file(&refused).unwrap_err(); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::FieldOutOfRange), Some(field)) + ); + } + writer.finish().unwrap(); + } + // The builder takes the object as a file object of a caller, and + // refuses it with the ID that was left out, as the writer does. + let features = Features::DEFAULT | Features::UID | Features::GID; + let object = FileObject::from_metadata(NameBuf::new("file").unwrap(), &meta, features).unwrap(); + let mut options = ManifestOptions::new(); + options.features(features); + let mut writer = options.open(Vec::new()).unwrap(); + writer.add_object(&object).unwrap(); + for (field, left_out) in [(Field::Uid, meta.uid()), (Field::Gid, meta.gid())] { + if left_out != NO_ID { + continue; + } + let mut refused = object.clone(); + refused.set_name(NameBuf::new("refused").unwrap()); + match field { + Field::Uid => refused.inode_mut().set_uid(Some(left_out)), + _ => refused.inode_mut().set_gid(Some(left_out)), + } + let e = writer.add_object(&refused).unwrap_err(); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::FieldOutOfRange), Some(field)) + ); + } + writer.finish().unwrap(); + } } diff --git a/src/uapi16/name.rs b/src/uapi16/name.rs index 2aa26da..06c2783 100644 --- a/src/uapi16/name.rs +++ b/src/uapi16/name.rs @@ -2,16 +2,20 @@ //! The names of file objects: [`Name`] borrows one, and [`NameBuf`] owns //! one. //! -//! The crate denies unsafe code, with one exception that is here: the cast -//! that makes a `&Name` of a `&str`, in `Name::from_str_unchecked()`. +//! The crate denies unsafe code. One of the exceptions is here: the cast +//! that makes a `&Name` of a `&str`, in `Name::from_str_unchecked()`. The +//! others are the modules ioctl and nss, and the module capi where the +//! feature of that name is on. use std::borrow::Borrow; use std::cmp::Ordering; +use std::ffi::OsStr; use std::fmt; use std::hash::{Hash, Hasher}; use std::iter; use std::ops::Deref; -use std::str::FromStr; +use std::os::unix::ffi::OsStrExt; +use std::str::{self, FromStr}; use crate::strict::StringRules; use crate::{InodeType, FILENAME, STRING_RULES}; @@ -29,6 +33,8 @@ const PARENT: &str = ".."; /// What follows [`FILENAME`] in the name of a file that belongs to the /// manifest, such as its signature or a compressed copy. const SUFFIX_SEPARATOR: char = '.'; +/// The same as the one byte it is in UTF-8. +const SUFFIX_SEPARATOR_BYTE: u8 = SUFFIX_SEPARATOR as u8; /// The control characters a name may not have are the bytes below the /// space, ASCII 0 to 31, and delete, ASCII 127. const SPACE: u8 = b' '; @@ -98,10 +104,15 @@ pub struct Name(str); #[derive(Clone, Default, PartialEq, Eq)] pub struct NameBuf(String); -/// Why a string is not the name of a file object, see [`Name`]. +/// Why a string or the name of a file is not the name of a file object, see +/// [`Name`]. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum NameProblem { + /// The name of a file on the host is not UTF-8, which every name of a + /// manifest is, see [`Name::join_os`]. A name made from a string never + /// has this problem. + NotUtf8, /// The string is empty. No file object has that name: [`Name::ROOT`] /// only stands in for the root file object, which has no name. Empty, @@ -129,6 +140,7 @@ pub enum NameProblem { impl fmt::Display for NameProblem { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + NameProblem::NotUtf8 => f.write_str("name is not UTF-8"), NameProblem::Empty => f.write_str("name is empty"), NameProblem::TooLong => write!(f, "name is longer than {} bytes", Name::MAX_LEN), NameProblem::Reserved => f.write_str("name is reserved for the manifest"), @@ -256,6 +268,16 @@ impl Name { Ok(NameBuf(name)) } + /// The name of the entry `component` of the directory this name is + /// the name of, where `component` is the name of a file on the host, + /// which is bytes. One that is not UTF-8 fails with + /// [`NameProblem::NotUtf8`], and anything else is checked as + /// [`Name::join`] checks it. + pub fn join_os(&self, component: &OsStr) -> Result { + let component = str::from_utf8(component.as_bytes()).map_err(|_| NameProblem::NotUtf8)?; + self.join(component) + } + /// Checks that `text` can be in a name: it has no control characters, /// and nothing that the strings of a manifest may not hold. fn check_text(text: &str) -> Result<(), NameProblem> { @@ -323,6 +345,15 @@ impl Name { .is_some_and(|rest| rest.is_empty() || rest.starts_with(SUFFIX_SEPARATOR) || rest.starts_with(SEPARATOR)) } + /// Whether `component`, the name of a file at the top of a tree as its + /// directory has it, is one [`Name::is_reserved`] reserves. It need not + /// be UTF-8. + pub(crate) fn is_reserved_component(component: &[u8]) -> bool { + component + .strip_prefix(FILENAME.as_bytes()) + .is_some_and(|rest| rest.is_empty() || rest.first() == Some(&SUFFIX_SEPARATOR_BYTE)) + } + /// Whether this is the name of the root file object. pub fn is_root(&self) -> bool { self.0.is_empty() @@ -731,6 +762,7 @@ mod tests { #[test] fn messages() { for (reason, text) in [ + (NameProblem::NotUtf8, "name is not UTF-8"), (NameProblem::Empty, "name is empty"), (NameProblem::TooLong, "name is longer than 4095 bytes"), (NameProblem::Reserved, "name is reserved for the manifest"), @@ -1077,6 +1109,38 @@ mod tests { } } + /// A component at the top of a tree is reserved as a name of it is, also + /// where it is not UTF-8. + #[test] + fn reserved_components() { + for component in [ + &b"Uapi16Manifest"[..], + b"Uapi16Manifest.", + b"Uapi16Manifest.sig", + b"Uapi16Manifest.\xff", + ] { + assert!(Name::is_reserved_component(component), "{:?}", component); + } + for component in [ + &b""[..], + b"Uapi16Manifest2", + b"Uapi16Manifes", + b"Uapi16Manifest\xff", + b"x.Uapi16Manifest", + b"\xffUapi16Manifest", + ] { + assert!(!Name::is_reserved_component(component), "{:?}", component); + } + for name in ["Uapi16Manifest", "Uapi16Manifest.sig", "Uapi16Manifest2", "x"] { + assert_eq!( + Name::is_reserved_component(name.as_bytes()), + Name::is_reserved(name), + "{}", + name + ); + } + } + /// Joining gives the name the whole path gives, and refuses what the /// whole path is refused for, for the same reason. A component with a /// separator is more than one and refused. @@ -1385,4 +1449,34 @@ mod tests { send_and_sync::(); send_and_sync::(); } + + /// The name of a file on the host joins as the string of its bytes + /// does. One that is not UTF-8 is refused for that before anything + /// else, also when it is too long or has a slash. + #[test] + fn joining_names_of_files() { + let parents = [Name::ROOT, Name::new("a").unwrap(), Name::new("a/b c").unwrap()]; + let too_long: Vec = iter::repeat_n(b'x', Name::MAX_LEN).chain([0xff]).collect(); + for parent in &parents { + for component in [ + "c", + "...", + "\u{e9}", + "", + ".", + "..", + "a/b", + "a\tb", + "a\u{fffe}", + "Uapi16Manifest", + ] { + let joined = parent.join_os(OsStr::new(component)); + assert_eq!(joined, parent.join(component), "{:?} {:?}", parent, component); + } + for bytes in [&b"\x80"[..], b"\xff", b"a\xe2\x82", b"a/\xff", &too_long] { + let joined = parent.join_os(OsStr::from_bytes(bytes)); + assert_eq!(joined, Err(NameProblem::NotUtf8), "{:?} {:?}", parent, bytes); + } + } + } } diff --git a/src/uapi16/nss.rs b/src/uapi16/nss.rs new file mode 100644 index 0000000..7e84273 --- /dev/null +++ b/src/uapi16/nss.rs @@ -0,0 +1,340 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The names of users and groups in the user database of the host, which +//! getpwuid_r() and getgrgid_r() of the C library look up. Only the module +//! sys calls them. +//! +//! This module and the module ioctl have the unsafe code of the crate, but +//! for the one cast of the module name and for the C API, the module capi +//! of the feature of that name. The two functions write an entry into a +//! struct of the caller and its strings into a buffer of the caller, and +//! point from the one into the other. Nothing is read through such a +//! pointer here. It only says where in the buffer the name starts, and the +//! name is read from the buffer, which has to hold it up to its end. A name +//! that a manifest cannot hold is none. + +#![deny(unsafe_op_in_unsafe_fn)] + +use std::ffi::CStr; +use std::mem; +use std::ptr; + +use libc::{c_char, c_int}; + +use crate::object::FileObject; +use crate::STRING_RULES; + +/// How large the buffer for an entry is where sysconf() gives no size, the +/// same as for systemd. +const DEFAULT_BUFFER_SIZE: usize = 4096; +/// The largest buffer an entry is looked up with. An entry that needs +/// more, such as a group of very many members, has no name here. +const MAX_BUFFER_SIZE: usize = 16 * 1024 * 1024; + +/// An entry of the user database: `struct passwd` or `struct group`. +trait Record: Sized { + /// What sysconf() is asked for the size a buffer for an entry needs. + const BUFFER_SIZE: c_int; + + /// Looks up the entry of the ID `id`, as getpwuid_r() and getgrgid_r() + /// do: writes it into `record` and its strings into `buffer`, and + /// stores `record` in `found`, or null if there is none. Returns 0 or + /// an error number. + /// + /// # Safety + /// + /// `record` and `found` are valid for writes, and `buffer` is valid for + /// writes of `size` bytes. + unsafe fn look_up(id: u32, record: *mut Self, buffer: *mut c_char, size: usize, found: *mut *mut Self) -> c_int; + + /// Where the entry says its name is. + fn name(&self) -> *const c_char; +} + +impl Record for libc::passwd { + const BUFFER_SIZE: c_int = libc::_SC_GETPW_R_SIZE_MAX; + + unsafe fn look_up(id: u32, record: *mut Self, buffer: *mut c_char, size: usize, found: *mut *mut Self) -> c_int { + // SAFETY: getpwuid_r() writes one `struct passwd` through `record`, + // at most `size` bytes through `buffer` and one pointer through + // `found`, all of which the caller guarantees to be valid for + // that. It keeps none of them. + unsafe { libc::getpwuid_r(id, record, buffer, size, found) } + } + + fn name(&self) -> *const c_char { + self.pw_name + } +} + +impl Record for libc::group { + const BUFFER_SIZE: c_int = libc::_SC_GETGR_R_SIZE_MAX; + + unsafe fn look_up(id: u32, record: *mut Self, buffer: *mut c_char, size: usize, found: *mut *mut Self) -> c_int { + // SAFETY: getgrgid_r() writes one `struct group` through `record`, + // at most `size` bytes through `buffer` and one pointer through + // `found`, all of which the caller guarantees to be valid for + // that. It keeps none of them. + unsafe { libc::getgrgid_r(id, record, buffer, size, found) } + } + + fn name(&self) -> *const c_char { + self.gr_name + } +} + +/// The user database of the host, as the C library sees it: /etc/passwd +/// and /etc/group, and whatever else its name service switch is set up +/// with. It keeps the buffer the entries are read into from one lookup to +/// the next. +#[derive(Debug, Default)] +pub(crate) struct UserDatabase { + /// What an entry is read into: nothing before the first lookup, then + /// as much as the largest entry so far took. + buffer: Vec, +} + +impl UserDatabase { + /// The user database, with nothing looked up yet. + pub(crate) fn new() -> UserDatabase { + UserDatabase::default() + } + + /// The name of the user `uid`, as a manifest can hold it. A user that + /// the database does not have or that cannot be looked up has none, + /// and neither has one whose name is not a `userName` of a manifest. + pub(crate) fn user_name(&mut self, uid: u32) -> Option { + self.name_of::(uid, MAX_BUFFER_SIZE) + } + + /// The name of the group `gid`, as [`UserDatabase::user_name`] gives + /// that of a user. + pub(crate) fn group_name(&mut self, gid: u32) -> Option { + self.name_of::(gid, MAX_BUFFER_SIZE) + } + + /// How large a buffer the lookup of an entry starts with: what + /// sysconf() says, which is a first guess and not a limit. + fn first_buffer_size() -> usize { + // SAFETY: sysconf() takes a number and returns one, and reads and + // writes no memory of its caller. + let size = unsafe { libc::sysconf(R::BUFFER_SIZE) }; + match usize::try_from(size) { + Ok(size) if size > 0 => size.min(MAX_BUFFER_SIZE), + _ => DEFAULT_BUFFER_SIZE, + } + } + + /// The name of the entry of the ID `id`, looked up with a buffer of at + /// most `max_size` bytes. The buffer doubles while the entry does not + /// fit into it, as for systemd's getpwuid_malloc(). + fn name_of(&mut self, id: u32, max_size: usize) -> Option { + // The two IDs that stand for no ID are not looked up. + if !FileObject::is_valid_id(id) { + return None; + } + if self.buffer.is_empty() { + self.buffer + .resize(UserDatabase::first_buffer_size::().min(max_size), 0); + } + loop { + // SAFETY: `struct passwd` and `struct group` are integers and + // pointers, for which all zeroes are a value: 0 and the null + // pointer. + let mut record: R = unsafe { mem::zeroed() }; + let mut found: *mut R = ptr::null_mut(); + // SAFETY: `record` and `found` are locals, valid for writes + // through the call, and the buffer is valid for writes of the + // bytes it holds, whose number is the size passed. + let error = unsafe { + R::look_up( + id, + &mut record, + self.buffer.as_mut_ptr().cast(), + self.buffer.len(), + &mut found, + ) + }; + match error { + // Found: the entry is the one that was passed in. + 0 if ptr::eq(found, &record) => return self.name_at(record.name()), + libc::ERANGE if self.buffer.len() < max_size => { + let size = self.buffer.len().saturating_mul(2).min(max_size); + self.buffer.resize(size, 0); + } + libc::EINTR => {} + // No entry, or an error, which systemd passes over as + // well. + _ => return None, + } + } + } + + /// The name an entry says starts at `name`, which is a pointer into the + /// buffer. It is not read through: it has to lead into the buffer, the + /// name is read from there, and it has to end inside the buffer. + fn name_at(&self, name: *const c_char) -> Option { + let start = name.addr().checked_sub(self.buffer.as_ptr().addr())?; + let name = CStr::from_bytes_until_nul(self.buffer.get(start..)?).ok()?; + UserDatabase::checked(name.to_str().ok()?) + } + + /// `name` if a manifest can hold it as the name of a user or of a + /// group: one systemd's relaxed rules take, without what the strings of + /// a manifest may not have. + fn checked(name: &str) -> Option { + (FileObject::is_owner_name(name) && STRING_RULES.admits(name)).then(|| name.to_owned()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + use std::fs; + use std::process::Command; + + /// The names the file `path` gives the IDs it lists, /etc/passwd or + /// /etc/group: the first entry of each ID, which is the one a lookup + /// finds where the C library looks into these files first. + fn listed(path: &str) -> BTreeMap { + let mut names = BTreeMap::new(); + for line in fs::read_to_string(path).unwrap_or_default().lines() { + let mut fields = line.split(':'); + let (Some(name), Some(_), Some(id)) = (fields.next(), fields.next(), fields.next()) else { + continue; + }; + if let Ok(id) = id.parse() { + names.entry(id).or_insert_with(|| name.to_owned()); + } + } + names + } + + /// An ID that the user database has no user for, found by asking id(1), + /// which looks users up as this module does, from an unlikely one on. + fn unknown_id() -> u32 { + let known = |id: &u32| { + let output = Command::new("id").args(["-u", &id.to_string()]).output(); + output.is_ok_and(|output| output.status.success()) + }; + (4_000_000_000..4_000_000_100) + .find(|id| !known(id)) + .expect("an ID without a user") + } + + /// The users and the groups /etc/passwd and /etc/group list have the + /// names these files give them, if a manifest can hold them. An ID + /// nobody has and the two IDs that stand for none have no name. + #[test] + fn names() { + let mut database = UserDatabase::new(); + let (users, groups) = (listed("/etc/passwd"), listed("/etc/group")); + if users.is_empty() || groups.is_empty() { + eprintln!("skipping: /etc/passwd or /etc/group lists nothing"); + } + // Twice: the second lookup goes through the buffer of the first. + for _ in 0..2 { + for (&uid, name) in &users { + assert_eq!(database.user_name(uid), UserDatabase::checked(name), "{}", uid); + } + for (&gid, name) in &groups { + assert_eq!(database.group_name(gid), UserDatabase::checked(name), "{}", gid); + } + } + assert_eq!(database.user_name(unknown_id()), None); + for invalid in [u32::MAX, u32::from(u16::MAX)] { + assert_eq!(database.user_name(invalid), None); + assert_eq!(database.group_name(invalid), None); + } + } + + /// An entry that does not fit into the buffer is looked up again with + /// twice the buffer, until it fits or the buffer may not grow any + /// more. Then it has no name. + #[test] + fn buffers_grow() { + let users = listed("/etc/passwd"); + let groups = listed("/etc/group"); + let (Some((&uid, user)), Some((&gid, group))) = (users.iter().next(), groups.iter().next()) else { + eprintln!("skipping: /etc/passwd or /etc/group lists nothing"); + return; + }; + for first in [1, 2, 3, 7] { + let mut database = UserDatabase { buffer: vec![0; first] }; + assert_eq!(database.user_name(uid), UserDatabase::checked(user), "{}", first); + assert!(database.buffer.len() > first); + let mut database = UserDatabase { buffer: vec![0; first] }; + assert_eq!(database.group_name(gid), UserDatabase::checked(group), "{}", first); + assert!(database.buffer.len() > first); + } + // A buffer that may not grow to the size of the entry. + let mut database = UserDatabase { buffer: vec![0; 1] }; + assert_eq!(database.name_of::(uid, 2), None); + assert_eq!(database.buffer.len(), 2); + assert_eq!(database.name_of::(gid, 2), None); + assert_eq!(database.buffer.len(), 2); + } + + /// A name is only read from the buffer: a pointer that leads elsewhere + /// or to a name that does not end in the buffer gives none. + #[test] + fn names_come_from_the_buffer() { + let mut database = UserDatabase { + buffer: b"root\0bin\0no end".to_vec(), + }; + let at = + |database: &UserDatabase, offset: usize| database.buffer.as_ptr().wrapping_add(offset).cast::(); + assert_eq!(database.name_at(at(&database, 0)).as_deref(), Some("root")); + assert_eq!(database.name_at(at(&database, 2)).as_deref(), Some("ot")); + assert_eq!(database.name_at(at(&database, 5)).as_deref(), Some("bin")); + // The empty name, the name without an end, and the end of the + // buffer. + assert_eq!(database.name_at(at(&database, 4)), None); + assert_eq!(database.name_at(at(&database, 9)), None); + assert_eq!(database.name_at(at(&database, database.buffer.len())), None); + assert_eq!(database.name_at(at(&database, database.buffer.len() + 1)), None); + assert_eq!(database.name_at(database.buffer.as_ptr().wrapping_sub(1).cast()), None); + assert_eq!(database.name_at(ptr::null()), None); + let elsewhere = c"elsewhere"; + assert_eq!(database.name_at(elsewhere.as_ptr()), None); + // Bytes that are not UTF-8 are not a name. + database.buffer = b"\xff\xfe\0".to_vec(); + assert_eq!(database.name_at(at(&database, 0)), None); + } + + /// The names a manifest holds are those systemd's relaxed rules take, + /// which its reader holds `userName` and `groupName` to, without + /// noncharacters. + #[test] + fn names_a_manifest_holds() { + for name in [ + "root", + "systemd-network", + "user@example.com", + "a b", + "J\u{f6}rg", + "_apt", + "0day", + "1.5", + ] { + assert_eq!(UserDatabase::checked(name).as_deref(), Some(name)); + } + for name in [ + "", + " a", + "a ", + ".", + "..", + "0", + "12345", + "-1", + "a:b", + "a/b", + "a\nb", + "a\u{7f}", + "a\u{fffe}", + ] { + assert_eq!(UserDatabase::checked(name), None, "{:?}", name); + } + } +} diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 53bd945..a1f3322 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -10,7 +10,7 @@ use std::os::unix::fs::FileTypeExt; use std::str::FromStr; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use crate::decode::ROOT_RECORD; +use crate::decode::{SizeAndHash, ROOT_RECORD}; use crate::error::{Error, ErrorKind, Field, Problem, ValidityProblem}; use crate::hex::Hex; use crate::{Features, Name, NameBuf, Order, Sha256, STRING_RULES}; @@ -529,6 +529,44 @@ impl GptPartition { || self.no_auto.is_some() || self.grow_file_system.is_some() } + + /// Whether the partition has `field`, one of the fields of a partition + /// among [`FileObject::FEATURE_FIELDS`]. + fn has_feature_field(&self, field: Field) -> bool { + match field { + Field::GptFlagGrowFileSystem => self.grow_file_system.is_some(), + Field::GptFlagNoAuto => self.no_auto.is_some(), + Field::GptFlags => self.flags.is_some(), + Field::GptLabel => self.label.is_some(), + Field::GptTypeUuid => self.type_uuid.is_some(), + Field::GptUuid => self.uuid.is_some(), + _ => false, + } + } + + /// The features whose fields the partition has. Its fields are asked + /// for them: a partition is handed out to change, see + /// [`FileObject::gpt_mut`], and few file objects describe one. + fn stated_features(&self) -> Features { + FileObject::FEATURE_FIELDS + .into_iter() + .filter(|(field, _)| self.has_feature_field(*field)) + .fold(Features::NONE, |features, (_, feature)| features | feature) + } + + /// Takes away `field`, one of the fields of a partition among + /// [`FileObject::FEATURE_FIELDS`], as its setter does with None. + fn take_feature_field(&mut self, field: Field) { + match field { + Field::GptFlagGrowFileSystem => self.set_grow_file_system(None), + Field::GptFlagNoAuto => self.set_no_auto(None), + Field::GptFlags => self.set_flags(None), + Field::GptLabel => self.set_label(None), + Field::GptTypeUuid => self.set_type_uuid(None), + Field::GptUuid => self.set_uuid(None), + _ => {} + } + } } /// A set of flags of one kind that the specification has a field for each: @@ -585,6 +623,22 @@ macro_rules! flag_set { pub(crate) const fn without(self, flags: $flags) -> $flags { $flags(self.0 & !flags.0) } + + /// The flags as bits, as the manifest builder keeps them while + /// it sorts. + pub(crate) const fn bits(self) -> u8 { + self.0 + } + + /// The flags the bits `bits` are, if each is the bit of a + /// flag. + pub(crate) const fn from_bits(bits: u8) -> Option<$flags> { + if bits & !$flags::ALL.0 == 0 { + Some($flags(bits)) + } else { + None + } + } } impl BitOr for $flags { @@ -744,6 +798,15 @@ impl FlagStates { } } + /// Keeps what the object says about `flags` and takes away what it + /// says about every other flag, also where a reader filled it in: + /// nothing is known about those then. + fn retain(&mut self, flags: F) { + self.stated = self.stated & flags; + self.set = self.set & flags; + self.filled = self.filled & flags; + } + /// The flags the record of the object gives: those it states but a /// reader did not fill in. fn given(&self) -> F { @@ -805,6 +868,41 @@ impl FlagStates { } } +/// The features an object states with the fields it has, see +/// [`FileObject::stated_features`]. Whatever gives the object a field or +/// takes one away keeps them in step with the fields, so that they are read +/// and not gathered from the fields. A new object states none, where the +/// default of [`Features`] is [`Features::DEFAULT`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct StatedFeatures(Features); + +impl Default for StatedFeatures { + fn default() -> StatedFeatures { + StatedFeatures(Features::NONE) + } +} + +impl StatedFeatures { + /// States `feature` where `stated` says that the object has a field of + /// it, and takes it back where it has none. + fn put(&mut self, feature: Features, stated: bool) { + self.0 = if stated { + self.0.union(feature) + } else { + self.0.without(feature) + }; + } + + /// States the features of the flags `states` gives, and takes back + /// those of the other flags of their kind. + fn put_flags(&mut self, states: &FlagStates) { + let given = states.given(); + for &(flag, _, feature) in F::FIELDS { + self.put(feature, (given & flag) == flag); + } + } +} + /// 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, `readOnly` and the flags, which are false @@ -897,6 +995,17 @@ impl FilledIn { pub(crate) const fn union(self, other: FilledIn) -> FilledIn { FilledIn(self.0 | other.0) } + + /// The marks as bits, one for each field that can be filled in, as the + /// manifest builder keeps them while it sorts. + pub(crate) const fn bits(self) -> u16 { + self.0 + } + + /// The marks the bits `bits` are. + pub(crate) const fn from_bits(bits: u16) -> FilledIn { + FilledIn(bits) + } } impl fmt::Debug for FilledIn { @@ -1331,24 +1440,28 @@ impl ContentsObject { #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct InodeAttributes { - 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, + mode: Option, + uid: Option, + gid: Option, + user_name: Option>, + group_name: Option>, + 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, + user_xattrs: Option>>>, + read_only: Option, /// `flagAppendOnly` and the other fields of the inode flags: the /// flags the object states. - pub(crate) flags: FlagStates, + 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, + filled_in: FilledIn, + /// The features of the fields the attributes have. The fields are + /// private to this module, so that nothing changes one without what + /// keeps its feature in step. + stated: StatedFeatures, } impl InodeAttributes { @@ -1391,17 +1504,83 @@ impl InodeAttributes { .chain(self.flags.feature_fields()) } + /// Takes away `field`, one of [`InodeAttributes::FEATURE_FIELDS`], as + /// its setter does with None, also where a reader filled it in. + fn take_feature_field(&mut self, field: Field) { + match field { + Field::ExtendedAttributes => self.set_user_xattrs(None), + Field::Gid => self.set_gid(None), + Field::GroupName => self.set_group_name(None), + Field::MTimeNSec => self.set_mtime_nsec(None), + Field::Mode => self.set_mode(None), + Field::ReadOnly => self.set_read_only(None), + Field::Uid => self.set_uid(None), + Field::UserName => self.set_user_name(None), + _ => {} + } + } + + /// Takes away the fields of every feature that is not in `features`, + /// those of the inode flags among them, see + /// [`FileObject::retain_features`]. + fn retain_features(&mut self, features: Features) { + for (field, feature) in InodeAttributes::FEATURE_FIELDS { + if !features.contains(feature) { + self.take_feature_field(field); + } + } + self.flags.retain(InodeFlags::recorded_by(features)); + self.stated.put_flags(&self.flags); + } + /// `readOnly` as the record of the object has it: None where a reader /// filled it in. pub(crate) fn stated_read_only(&self) -> Option { self.read_only.filter(|_| !self.filled_in.contains(Field::ReadOnly)) } + /// What the attributes say about the inode flags: which of them they + /// state, which of those are set and which a reader filled in. + pub(crate) fn flags(&self) -> FlagStates { + self.flags + } + + /// Sets what the attributes say about the inode flags. + pub(crate) fn set_flags(&mut self, states: FlagStates) { + self.flags = states; + self.stated.put_flags(&self.flags); + } + + /// States the inode flag `flag` as set or cleared, or as not known, see + /// [`FlagStates::put`]. + pub(crate) fn put_flag(&mut self, flag: InodeFlags, state: Option) { + self.flags.put(flag, state); + self.stated.put_flags(&self.flags); + } + + /// `readOnly` and `extendedAttributes`, where a reader filled them in: + /// the marks the attributes keep themselves, without those of the + /// inode flags, which [`InodeAttributes::flags`] has. + pub(crate) fn marks(&self) -> FilledIn { + self.filled_in + } + + /// Notes `readOnly` and `extendedAttributes` as filled in by a reader + /// where `marks` has them, and as given where it does not. + pub(crate) fn set_marks(&mut self, marks: FilledIn) { + self.filled_in = marks; + self.stated + .put(Features::READ_ONLY, self.has_feature_field(Field::ReadOnly)); + self.stated + .put(Features::USER_XATTR, self.has_feature_field(Field::ExtendedAttributes)); + } + /// 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`, and it has no extended attributes - /// if the manifest records them. Each is noted as filled in. + /// if the manifest records them. Each is noted as filled in, and what + /// is filled in states no feature. 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() { @@ -1422,6 +1601,7 @@ impl InodeAttributes { /// Sets `mode`. pub fn set_mode(&mut self, mode: Option) { self.mode = mode; + self.stated.put(Features::MODE, mode.is_some()); } /// `uid`: the owning user. @@ -1432,6 +1612,7 @@ impl InodeAttributes { /// Sets `uid`. pub fn set_uid(&mut self, uid: Option) { self.uid = uid; + self.stated.put(Features::UID, uid.is_some()); } /// `gid`: the owning group. @@ -1442,6 +1623,7 @@ impl InodeAttributes { /// Sets `gid`. pub fn set_gid(&mut self, gid: Option) { self.gid = gid; + self.stated.put(Features::GID, gid.is_some()); } /// `userName`: the name of the owning user. @@ -1452,6 +1634,7 @@ impl InodeAttributes { /// Sets `userName`. pub fn set_user_name(&mut self, name: Option) { self.user_name = name.map(String::into_boxed_str); + self.stated.put(Features::USER_NAME, self.user_name.is_some()); } /// `groupName`: the name of the owning group. @@ -1462,6 +1645,7 @@ impl InodeAttributes { /// Sets `groupName`. pub fn set_group_name(&mut self, name: Option) { self.group_name = name.map(String::into_boxed_str); + self.stated.put(Features::GROUP_NAME, self.group_name.is_some()); } /// `mTimeNSec`: the modification time in nanoseconds since the epoch, @@ -1474,6 +1658,7 @@ impl InodeAttributes { /// the time away. pub fn set_mtime_nsec(&mut self, nsec: Option) { self.mtime_nsec = nsec; + self.stated.put(Features::MTIME, nsec.is_some()); } /// `extendedAttributes`: the extended attributes of the `user` @@ -1492,10 +1677,17 @@ impl InodeAttributes { self.user_xattrs.as_deref()?.get(name).map(Vec::as_slice) } + /// The extended attributes of the `user` namespace as the map that + /// holds them, by their names. + pub(crate) fn user_xattr_map(&self) -> Option<&BTreeMap>> { + self.user_xattrs.as_deref() + } + /// 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); + self.stated.put(Features::USER_XATTR, self.user_xattrs.is_some()); } /// Sets the extended attribute of the `user` namespace whose name @@ -1504,6 +1696,7 @@ impl InodeAttributes { /// 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.stated.put(Features::USER_XATTR, true); self.user_xattrs .get_or_insert_with(Box::default) .insert(name.into(), value.into()) @@ -1514,6 +1707,7 @@ impl InodeAttributes { /// [`BTreeMap::remove`]. pub fn remove_user_xattr(&mut self, name: &str) -> Option> { self.filled_in.remove(Field::ExtendedAttributes); + self.stated.put(Features::USER_XATTR, self.user_xattrs.is_some()); self.user_xattrs.as_deref_mut()?.remove(name) } @@ -1528,6 +1722,7 @@ impl InodeAttributes { pub fn set_read_only(&mut self, read_only: Option) { self.filled_in.remove(Field::ReadOnly); self.read_only = read_only; + self.stated.put(Features::READ_ONLY, read_only.is_some()); } /// `readOnly`, the inode flags and `extendedAttributes`, where a reader @@ -1553,6 +1748,7 @@ impl InodeAttributes { read_only, flags, filled_in: _, + stated: _, } = self; *mode == other.mode && *uid == other.uid @@ -1574,10 +1770,8 @@ impl InodeAttributes { /// nanoseconds since the epoch in 64 bits, which ends in the year /// 2554. A time it cannot express leaves the attributes without one. pub fn set_mtime(&mut self, time: SystemTime) { - self.mtime_nsec = time - .duration_since(UNIX_EPOCH) - .ok() - .and_then(|since| u64::try_from(since.as_nanos()).ok()); + let since = time.duration_since(UNIX_EPOCH).ok(); + self.set_mtime_nsec(since.and_then(|since| u64::try_from(since.as_nanos()).ok())); } /// Whether the file gets the read-only attribute in a file system with @@ -1611,7 +1805,7 @@ impl InodeAttributes { /// `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); + self.put_flag(InodeFlags::APPEND_ONLY, append_only); } /// `flagImmutable`: whether the inode flag `FS_IMMUTABLE_FL` is set. None @@ -1626,7 +1820,7 @@ impl InodeAttributes { /// `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); + self.put_flag(InodeFlags::IMMUTABLE, immutable); } /// `flagNoAtime`: whether the inode flag `FS_NOATIME_FL` is set. None says @@ -1641,7 +1835,7 @@ impl InodeAttributes { /// `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); + self.put_flag(InodeFlags::NO_ATIME, no_atime); } /// `flagNoCow`: whether the inode flag `FS_NOCOW_FL` is set. None says @@ -1656,7 +1850,7 @@ impl InodeAttributes { /// `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); + self.put_flag(InodeFlags::NO_COW, no_cow); } /// `flagNoDump`: whether the inode flag `FS_NODUMP_FL` is set. None says @@ -1671,7 +1865,7 @@ impl InodeAttributes { /// `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); + self.put_flag(InodeFlags::NO_DUMP, no_dump); } } @@ -1700,23 +1894,29 @@ impl InodeAttributes { #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct FileObject { - pub(crate) name: NameBuf, - 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>, + name: NameBuf, + inode_type: InodeType, + size: Option, + sha256: Option, + contents: Vec, + inode_token: Option, + major: Option, + minor: Option, + gpt: Option>, /// `flagHidden`, `flagSystem` and `flagArchive`: the DOS attributes the /// object states. - pub(crate) dos_flags: FlagStates, - pub(crate) inode: InodeAttributes, - pub(crate) validity: ValidityWindow, + dos_flags: FlagStates, + inode: InodeAttributes, + 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, + filled_in: FilledIn, + /// The features of the fields the object has itself. Its inode + /// attributes keep theirs, and a partition is asked for those of its + /// fields, see [`GptPartition::stated_features`]. The fields are + /// private to this module, so that nothing changes one without what + /// keeps its feature in step. + stated: StatedFeatures, } impl FileObject { @@ -1756,6 +1956,7 @@ impl FileObject { inode: InodeAttributes::default(), validity: ValidityWindow::default(), filled_in: FilledIn::default(), + stated: StatedFeatures::default(), } } @@ -1783,6 +1984,7 @@ impl FileObject { /// Sets `type`. pub fn set_inode_type(&mut self, inode_type: InodeType) { self.inode_type = inode_type; + self.state_target(); } /// `size`: the size of the data in bytes. For a symbolic link that is @@ -1796,6 +1998,7 @@ impl FileObject { pub fn set_size(&mut self, size: Option) { self.drop_filled_in(); self.size = size; + self.stated.put(Features::SIZE, size.is_some()); } /// `sha256`: the hash of the data. @@ -1807,6 +2010,7 @@ impl FileObject { pub fn set_sha256(&mut self, sha256: Option) { self.drop_filled_in(); self.sha256 = sha256; + self.stated.put(Features::SHA256, sha256.is_some()); } /// `contents`: where the data can be taken from. A regular file without @@ -1832,18 +2036,59 @@ impl FileObject { /// [`MAX_CONTENTS`]: crate::MAX_CONTENTS pub fn set_contents(&mut self, contents: Vec) { self.drop_filled_in(); - self.contents = contents; + self.put_contents(contents); self.fill_in_from_contents(); } + /// Sets `contents` as they are: nothing is filled in from them, and + /// what a reader filled in stays. A reader does so with the contents + /// objects of a record, which it checks and fills in with the rest of + /// the object, a walk with the target of a symbolic link, and the + /// manifest builder with those of an object it kept. + pub(crate) fn put_contents(&mut self, contents: Vec) { + self.contents = contents; + self.state_target(); + } + + /// The contents objects, to change what each of them says. How many + /// they are stays, which the feature `symlink` of a symbolic link + /// follows from. + pub(crate) fn contents_mut(&mut self) -> &mut [ContentsObject] { + &mut self.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(); + self.stated.put(Features::SYMLINK, false); std::mem::take(&mut self.contents) } + /// States the feature `symlink` where the object is a symbolic link + /// with contents objects, which are its target then, and takes it back + /// where it is not. + fn state_target(&mut self) { + self.stated + .put(Features::SYMLINK, self.has_feature_field(Field::Contents)); + } + + /// Fills in the size and the hash of the data, `data` from + /// [`FileObject::check_consistency`], where the object does not give + /// them, and notes them as filled in. What the object gives stays as + /// it is, and what is filled in states no feature. + pub(crate) fn fill_in_data(&mut self, data: SizeAndHash) { + if self.size.is_none() && data.size.is_some() { + self.size = data.size; + self.filled_in.insert(Field::Size); + } + if self.sha256.is_none() && data.sha256.is_some() { + self.sha256 = data.sha256; + self.filled_in.insert(Field::Sha256); + } + } + /// `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 { @@ -1853,6 +2098,7 @@ impl FileObject { /// Sets `inodeToken`. pub fn set_inode_token(&mut self, token: Option) { self.inode_token = token; + self.stated.put(Features::HARDLINK, token.is_some()); } /// `major`: the major number of a device node. @@ -1863,6 +2109,7 @@ impl FileObject { /// Sets `major`. pub fn set_major(&mut self, major: Option) { self.major = major; + self.state_device(); } /// `minor`: the minor number of a device node. @@ -1873,6 +2120,14 @@ impl FileObject { /// Sets `minor`. pub fn set_minor(&mut self, minor: Option) { self.minor = minor; + self.state_device(); + } + + /// States the feature `device` where the object has one of the device + /// numbers, and takes it back where it has neither. + fn state_device(&mut self) { + self.stated + .put(Features::DEVICE, self.major.is_some() || self.minor.is_some()); } /// The `gpt` fields, if the object describes a partition. @@ -1885,6 +2140,12 @@ impl FileObject { self.gpt.as_deref_mut() } + /// The `gpt` fields to change in place, made first where the object + /// has none. + pub(crate) fn gpt_or_default(&mut self) -> &mut GptPartition { + self.gpt.get_or_insert_with(Box::default) + } + /// Sets the `gpt` fields. pub fn set_gpt(&mut self, gpt: Option) { self.gpt = gpt.map(Box::new); @@ -1916,6 +2177,27 @@ impl FileObject { self.validity = validity; } + /// `validSinceUSec`, `validUntilUSec` and `validity`, to change them in + /// place. + pub(crate) fn validity_mut(&mut self) -> &mut ValidityWindow { + &mut self.validity + } + + /// The size and the hash, where a reader filled them in: the marks the + /// object keeps itself, without those of its DOS attributes, which + /// [`FileObject::dos_flags`] has, and of its inode attributes. + pub(crate) fn marks(&self) -> FilledIn { + self.filled_in + } + + /// Notes the size and the hash as filled in by a reader where `marks` + /// has them, and as given where it does not. + pub(crate) fn set_marks(&mut self, marks: FilledIn) { + self.filled_in = marks; + self.stated.put(Features::SIZE, self.has_feature_field(Field::Size)); + self.stated.put(Features::SHA256, self.has_feature_field(Field::Sha256)); + } + /// 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. @@ -1967,6 +2249,7 @@ impl FileObject { inode, validity, filled_in: _, + stated: _, } = self; *name == other.name && *inode_type == other.inode_type @@ -2003,21 +2286,57 @@ impl FileObject { /// other than one a reader filled in. `contents` belongs to a feature on /// a symbolic link only. fn has_feature_field(&self, field: Field) -> bool { - let gpt = self.gpt.as_deref(); match field { Field::Contents => self.inode_type == InodeType::Symlink && !self.contents.is_empty(), - Field::GptFlagGrowFileSystem => gpt.is_some_and(|gpt| gpt.grow_file_system.is_some()), - Field::GptFlagNoAuto => gpt.is_some_and(|gpt| gpt.no_auto.is_some()), - Field::GptFlags => gpt.is_some_and(|gpt| gpt.flags.is_some()), - Field::GptLabel => gpt.is_some_and(|gpt| gpt.label.is_some()), - Field::GptTypeUuid => gpt.is_some_and(|gpt| gpt.type_uuid.is_some()), - Field::GptUuid => gpt.is_some_and(|gpt| gpt.uuid.is_some()), Field::InodeToken => self.inode_token.is_some(), Field::Major => self.major.is_some(), Field::Minor => self.minor.is_some(), Field::Sha256 => self.sha256.is_some() && !self.filled_in.contains(field), Field::Size => self.size.is_some() && !self.filled_in.contains(field), - _ => false, + // The other fields are those of a partition. + _ => self.gpt.as_deref().is_some_and(|gpt| gpt.has_feature_field(field)), + } + } + + /// Takes away `field`, one of [`FileObject::FEATURE_FIELDS`], as its + /// setter does with None, also where a reader filled it in. Taking + /// away the size, the hash or the contents objects drops the size and + /// the hash a reader filled in, which follow from them. So each of the + /// three is taken only where the object has it, and what a reader + /// filled in stays where there is nothing to take. + fn take_feature_field(&mut self, field: Field) { + match field { + // The contents objects belong to a feature on a symbolic link + // only. + Field::Contents => { + if self.has_feature_field(field) { + self.take_contents(); + } + } + Field::InodeToken => self.set_inode_token(None), + Field::Major => self.set_major(None), + Field::Minor => self.set_minor(None), + Field::Sha256 => { + if self.sha256.is_some() { + self.set_sha256(None); + } + } + Field::Size => { + if self.size.is_some() { + self.set_size(None); + } + } + // The other fields are those of a partition, which goes with + // the last of its fields: a reader has none for a file without + // any of them. + _ => { + if let Some(gpt) = self.gpt.as_deref_mut().filter(|gpt| gpt.describes_partition()) { + gpt.take_feature_field(field); + if !gpt.describes_partition() { + self.gpt = None; + } + } + } } } @@ -2037,8 +2356,28 @@ impl FileObject { /// manifest records them all or the object is not one of its file /// objects. 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) + let stated = self.stated.0 | self.inode.stated.0; + match self.gpt.as_deref() { + Some(gpt) => stated | gpt.stated_features(), + None => stated, + } + } + + /// Takes away the fields of every feature that is not in `features`, + /// those of the inode attributes among them. So a caller sets all it + /// knows of a file and keeps what its manifest records. The name, the + /// type and the fields that belong to no feature stay. An object whose + /// data starts at an offset in a file reaches to the end of it once its + /// size goes, and a hash that stays no longer fits. + pub fn retain_features(&mut self, features: Features) { + for (field, feature) in FileObject::FEATURE_FIELDS { + if !features.contains(feature) { + self.take_feature_field(field); + } + } + self.dos_flags.retain(DosFlags::recorded_by(features)); + self.stated.put_flags(&self.dos_flags); + self.inode.retain_features(features); } /// Fills in what `features`, which its manifest records, say about the @@ -2046,12 +2385,31 @@ impl FileObject { /// cleared, the file is not read-only if the manifest records /// `readOnly`, and it has no extended attributes if the manifest /// records them. The `gpt` fields are not filled in, see - /// [`GptPartition`]. + /// [`GptPartition`]. What is filled in states no feature. pub(crate) fn fill_in(&mut self, features: Features) { self.dos_flags.fill_in(features, self.inode_type); self.inode.fill_in(features, self.inode_type); } + /// What the object says about the DOS attributes: which of them it + /// states, which of those are set and which a reader filled in. + pub(crate) fn dos_flags(&self) -> FlagStates { + self.dos_flags + } + + /// Sets what the object says about the DOS attributes. + pub(crate) fn set_dos_flags(&mut self, states: FlagStates) { + self.dos_flags = states; + self.stated.put_flags(&self.dos_flags); + } + + /// States the DOS attribute `flag` as set or cleared, or as not known, + /// see [`FlagStates::put`]. + pub(crate) fn put_dos_flag(&mut self, flag: DosFlags, state: Option) { + self.dos_flags.put(flag, state); + self.stated.put_flags(&self.dos_flags); + } + /// The field of the first flag the object states that it cannot have: /// only regular files and directories have flags. pub(crate) fn unpermitted_flag(&self) -> Option { @@ -2084,7 +2442,7 @@ impl FileObject { /// `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); + self.put_dos_flag(DosFlags::ARCHIVE, archive); } /// `flagHidden`: whether the DOS attribute `ATTR_HIDDEN` is set. None says @@ -2099,7 +2457,7 @@ impl FileObject { /// `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); + self.put_dos_flag(DosFlags::HIDDEN, hidden); } /// `flagSystem`: whether the DOS attribute `ATTR_SYSTEM` is set. None says @@ -2114,7 +2472,7 @@ impl FileObject { /// `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); + self.put_dos_flag(DosFlags::SYSTEM, system); } } @@ -2267,8 +2625,37 @@ impl RootObject { /// 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) + RootObject::FEATURE_FIELDS + .into_iter() + .filter(|(field, _)| self.has_feature_field(*field)) + .fold(self.inode.stated.0, |features, (_, feature)| features | feature) + } + + /// Takes away `field`, one of [`RootObject::FEATURE_FIELDS`], as its + /// setter does with None. + #[cfg(feature = "capi")] + fn take_feature_field(&mut self, field: Field) { + match field { + Field::FatSerial => self.file_system.set_fat_serial(None), + Field::FsLabel => self.file_system.set_label(None), + Field::FsUuid => self.file_system.set_uuid(None), + Field::GptDiskUuid => self.set_gpt_disk_uuid(None), + _ => {} + } + } + + /// Takes away the fields of every feature that is not in `features`, + /// those of the inode attributes among them, as + /// [`FileObject::retain_features`] does for a file object. The C API + /// has one function for the two. + #[cfg(feature = "capi")] + pub(crate) fn retain_features(&mut self, features: Features) { + for (field, feature) in RootObject::FEATURE_FIELDS { + if !features.contains(feature) { + self.take_feature_field(field); + } + } + self.inode.retain_features(features); } /// What the manifest records: the features the root file object lists @@ -2376,6 +2763,14 @@ mod tests { /// Gives an object a field. type Give = fn(&mut T); + /// The features `object` states, gathered from its fields with the + /// tables. What the object keeps is held against them. + fn stated_by_the_fields(object: &FileObject) -> Features { + object + .feature_fields() + .fold(Features::NONE, |features, (_, feature)| features | feature) + } + #[test] fn inode_types() { for (name, inode_type) in [ @@ -2531,18 +2926,18 @@ mod tests { fn read_only() { let mut inode = InodeAttributes::default(); assert!(!inode.is_read_only()); - inode.mode = Some(Mode::new(0o444).unwrap()); + inode.set_mode(Some(Mode::new(0o444).unwrap())); assert!(inode.is_read_only()); - inode.mode = Some(Mode::new(0o464).unwrap()); + inode.set_mode(Some(Mode::new(0o464).unwrap())); assert!(!inode.is_read_only()); - inode.read_only = Some(true); + inode.set_read_only(Some(true)); assert!(inode.is_read_only()); - inode.mode = None; + inode.set_mode(None); assert!(inode.is_read_only()); - inode.read_only = Some(false); + inode.set_read_only(Some(false)); assert!(!inode.is_read_only()); // What readOnly says counts, the false a reader fills in too. - inode.mode = Some(Mode::new(0o444).unwrap()); + inode.set_mode(Some(Mode::new(0o444).unwrap())); assert!(!inode.is_read_only()); } @@ -2744,29 +3139,23 @@ mod tests { let partition = |set: Give| { let mut gpt = GptPartition::default(); set(&mut gpt); - Some(Box::new(gpt)) + Some(gpt) }; let cases: [(Give, Features); 14] = [ - (|o| o.size = Some(1), Features::SIZE), - (|o| o.sha256 = Some(Sha256::EMPTY), Features::SHA256), - (|o| o.inode_token = NonZeroU64::new(1), Features::HARDLINK), - (|o| o.major = Some(1), Features::DEVICE), - (|o| o.minor = Some(1), Features::DEVICE), - ( - |o| o.dos_flags.put(DosFlags::HIDDEN, Some(false)), - Features::FLAG_HIDDEN, - ), - (|o| o.dos_flags.put(DosFlags::SYSTEM, Some(true)), Features::FLAG_SYSTEM), - ( - |o| o.dos_flags.put(DosFlags::ARCHIVE, Some(true)), - Features::FLAG_ARCHIVE, - ), - (|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), - (|o| o.inode.user_xattrs = Some(Box::default()), Features::USER_XATTR), - (|o| o.inode.read_only = Some(false), Features::READ_ONLY), + (|o| o.set_size(Some(1)), Features::SIZE), + (|o| o.set_sha256(Some(Sha256::EMPTY)), Features::SHA256), + (|o| o.set_inode_token(NonZeroU64::new(1)), Features::HARDLINK), + (|o| o.set_major(Some(1)), Features::DEVICE), + (|o| o.set_minor(Some(1)), Features::DEVICE), + (|o| o.set_flag_hidden(Some(false)), Features::FLAG_HIDDEN), + (|o| o.set_flag_system(Some(true)), Features::FLAG_SYSTEM), + (|o| o.set_flag_archive(Some(true)), Features::FLAG_ARCHIVE), + (|o| o.inode.set_mode(Mode::new(0o644).ok()), Features::MODE), + (|o| o.inode.set_uid(Some(0)), Features::UID), + (|o| o.inode.set_user_name(Some("u".into())), Features::USER_NAME), + (|o| o.inode.set_mtime_nsec(Some(0)), Features::MTIME), + (|o| o.inode.set_user_xattrs(Some(BTreeMap::new())), Features::USER_XATTR), + (|o| o.inode.set_read_only(Some(false)), Features::READ_ONLY), ]; for (set, feature) in cases { let mut object = FileObject::new(NameBuf::new("f").unwrap()); @@ -2786,30 +3175,35 @@ mod tests { ]; for (set, feature) in partitions { let mut object = FileObject::new(NameBuf::new("f").unwrap()); - object.gpt = partition(set); + object.set_gpt(partition(set)); assert_eq!(object.stated_features(), feature, "{:?}", object); } let mut object = FileObject::new(NameBuf::new("f").unwrap()); - (object.inode.gid, object.inode.group_name) = (Some(0), Some("g".into())); + object.inode.set_gid(Some(0)); + object.inode.set_group_name(Some("g".into())); assert_eq!(object.stated_features(), Features::GID | Features::GROUP_NAME); for &(flag, _, feature) in InodeFlags::FIELDS { let mut object = FileObject::new(NameBuf::new("f").unwrap()); - object.inode.flags.put(flag, Some(true)); + object.inode.put_flag(flag, Some(true)); assert_eq!(object.stated_features(), feature, "{:?}", flag); } // The contents of a symbolic link are its target, which a feature // records. Those of other files are not. let mut object = FileObject::new(NameBuf::new("f").unwrap()); - object.contents = vec![ContentsObject::new(ContentsSource::Literal(b"t".to_vec()))]; + object.put_contents(vec![ContentsObject::new(ContentsSource::Literal(b"t".to_vec()))]); assert_eq!(object.stated_features(), Features::NONE); - object.inode_type = InodeType::Symlink; + object.set_inode_type(InodeType::Symlink); assert_eq!(object.stated_features(), Features::SYMLINK); // What a reader filled in does not count. let mut object = FileObject::new(NameBuf::new("f").unwrap()); - (object.size, object.sha256) = (Some(0), Some(Sha256::EMPTY)); - object.filled_in.insert(Field::Size); + object.set_size(Some(0)); + object.set_sha256(Some(Sha256::EMPTY)); + let mut marks = FilledIn::default(); + marks.insert(Field::Size); + object.set_marks(marks); assert_eq!(object.stated_features(), Features::SHA256); - object.filled_in.insert(Field::Sha256); + marks.insert(Field::Sha256); + object.set_marks(marks); assert_eq!(object.stated_features(), Features::NONE); // The fields of the root file object, its inode attributes among // them. @@ -2819,11 +3213,8 @@ mod tests { (|r| r.file_system.label = Some("ESP".into()), Features::FS_LABEL), (|r| r.file_system.fat_serial = Some(FatSerial(1)), Features::FAT_SERIAL), (|r| r.gpt_disk_uuid = Some(UUID), Features::GPT_DISK_UUID), - (|r| r.inode.mtime_nsec = Some(0), Features::MTIME), - ( - |r| r.inode.flags.put(InodeFlags::NO_COW, Some(false)), - Features::FLAG_NO_COW, - ), + (|r| r.inode.set_mtime_nsec(Some(0)), Features::MTIME), + (|r| r.inode.set_flag_no_cow(Some(false)), Features::FLAG_NO_COW), ]; for (set, feature) in cases { let mut root = RootObject::default(); @@ -2837,6 +3228,782 @@ mod tests { assert_eq!(root.stated_features(), Features::NONE); } + /// What an object keeps as the features it states is what its fields + /// state. Every combination of the fields of the inode attributes, of + /// the fields the object has itself and of the fields of a partition is + /// given the way a caller gives it: in the order of the table to an + /// object that has none of the other fields, and the other way around + /// to one that has them all. The object is asked as it is, with what a + /// reader fills in for the fields it lacks, and as each field is taken + /// away again. + #[test] + fn keeps_the_features_of_every_combination_of_fields() { + const UUID: Uuid = Uuid::new([1; Uuid::SIZE]); + /// A field: its feature, how a caller gives it and how it takes it + /// away. + type Part = (Features, Give, Give); + /// Gives the partition of `object` a field. + fn partition(object: &mut FileObject, give: Give) { + let mut gpt = object.take_gpt().unwrap_or_default(); + give(&mut gpt); + object.set_gpt(Some(gpt)); + } + /// Takes a field of the partition of `object` away. + fn unpartition(object: &mut FileObject, take: Give) { + take(object.gpt_mut().unwrap()); + } + let inode: [Part; 13] = [ + ( + Features::MODE, + |o| o.inode_mut().set_mode(Mode::new(0o644).ok()), + |o| o.inode_mut().set_mode(None), + ), + ( + Features::UID, + |o| o.inode_mut().set_uid(Some(1)), + |o| o.inode_mut().set_uid(None), + ), + ( + Features::GID, + |o| o.inode_mut().set_gid(Some(2)), + |o| o.inode_mut().set_gid(None), + ), + ( + Features::USER_NAME, + |o| o.inode_mut().set_user_name(Some("u".into())), + |o| o.inode_mut().set_user_name(None), + ), + ( + Features::GROUP_NAME, + |o| o.inode_mut().set_group_name(Some("g".into())), + |o| o.inode_mut().set_group_name(None), + ), + ( + Features::MTIME, + |o| o.inode_mut().set_mtime(UNIX_EPOCH), + |o| o.inode_mut().set_mtime_nsec(None), + ), + ( + Features::USER_XATTR, + |o| drop(o.inode_mut().insert_user_xattr("a", b"b")), + |o| o.inode_mut().set_user_xattrs(None), + ), + ( + Features::READ_ONLY, + |o| o.inode_mut().set_read_only(Some(false)), + |o| o.inode_mut().set_read_only(None), + ), + ( + Features::FLAG_APPEND_ONLY, + |o| o.inode_mut().set_flag_append_only(Some(true)), + |o| o.inode_mut().set_flag_append_only(None), + ), + ( + Features::FLAG_IMMUTABLE, + |o| o.inode_mut().set_flag_immutable(Some(false)), + |o| o.inode_mut().set_flag_immutable(None), + ), + ( + Features::FLAG_NO_ATIME, + |o| o.inode_mut().set_flag_no_atime(Some(true)), + |o| o.inode_mut().set_flag_no_atime(None), + ), + ( + Features::FLAG_NO_COW, + |o| o.inode_mut().set_flag_no_cow(Some(false)), + |o| o.inode_mut().set_flag_no_cow(None), + ), + ( + Features::FLAG_NO_DUMP, + |o| o.inode_mut().set_flag_no_dump(Some(true)), + |o| o.inode_mut().set_flag_no_dump(None), + ), + ]; + // The contents objects are a field of a feature on a symbolic link + // only. What makes the object one is a part of its own, which + // belongs to no feature. + let own: [Part; 10] = [ + (Features::SIZE, |o| o.set_size(Some(6)), |o| o.set_size(None)), + ( + Features::SHA256, + |o| o.set_sha256(Some(Sha256::digest(b"target"))), + |o| o.set_sha256(None), + ), + ( + Features::SYMLINK, + |o| o.set_contents(vec![ContentsObject::new(ContentsSource::Literal(b"target".to_vec()))]), + |o| drop(o.take_contents()), + ), + ( + Features::NONE, + |o| o.set_inode_type(InodeType::Symlink), + |o| o.set_inode_type(InodeType::Regular), + ), + ( + Features::HARDLINK, + |o| o.set_inode_token(NonZeroU64::new(1)), + |o| o.set_inode_token(None), + ), + (Features::DEVICE, |o| o.set_major(Some(8)), |o| o.set_major(None)), + (Features::DEVICE, |o| o.set_minor(Some(1)), |o| o.set_minor(None)), + ( + Features::FLAG_ARCHIVE, + |o| o.set_flag_archive(Some(true)), + |o| o.set_flag_archive(None), + ), + ( + Features::FLAG_HIDDEN, + |o| o.set_flag_hidden(Some(false)), + |o| o.set_flag_hidden(None), + ), + ( + Features::FLAG_SYSTEM, + |o| o.set_flag_system(Some(true)), + |o| o.set_flag_system(None), + ), + ]; + let partitions: [Part; 6] = [ + ( + Features::GPT_LABEL, + |o| partition(o, |gpt| gpt.set_label(Some("esp".into()))), + |o| unpartition(o, |gpt| gpt.set_label(None)), + ), + ( + Features::GPT_UUID, + |o| partition(o, |gpt| gpt.set_uuid(Some(UUID))), + |o| unpartition(o, |gpt| gpt.set_uuid(None)), + ), + ( + Features::GPT_TYPE_UUID, + |o| partition(o, |gpt| gpt.set_type_uuid(Some(UUID))), + |o| unpartition(o, |gpt| gpt.set_type_uuid(None)), + ), + ( + Features::GPT_FLAGS, + |o| partition(o, |gpt| gpt.set_flags(Some(0))), + |o| unpartition(o, |gpt| gpt.set_flags(None)), + ), + ( + Features::GPT_FLAG_NO_AUTO, + |o| partition(o, |gpt| gpt.set_no_auto(Some(false))), + |o| unpartition(o, |gpt| gpt.set_no_auto(None)), + ), + ( + Features::GPT_FLAG_GROW_FILE_SYSTEM, + |o| partition(o, |gpt| gpt.set_grow_file_system(Some(true))), + |o| unpartition(o, |gpt| gpt.set_grow_file_system(None)), + ), + ]; + // One table of them all, with a bit for each in what is given. + let fields: Vec = [&inode[..], &own[..], &partitions[..]].concat(); + let parts = [ + 0..inode.len(), + inode.len()..inode.len() + own.len(), + inode.len() + own.len()..fields.len(), + ]; + let bit = |feature: Features| 1 << fields.iter().position(|part| part.0 == feature).unwrap(); + let (contents, symlink): (usize, usize) = (bit(Features::SYMLINK), bit(Features::NONE)); + // Every feature a file object has a field of is in the table. + let every = fields.iter().fold(Features::NONE, |every, part| every | part.0); + let of_the_root = RootObject::FEATURE_FIELDS + .iter() + .fold(Features::NONE, |every, (_, feature)| every | *feature); + assert_eq!(every, Features::ALL.without(of_the_root)); + // The features the fields `given` state. + let stated = |given: usize| { + fields + .iter() + .enumerate() + .filter(|(index, _)| given & (1 << index) != 0) + .filter(|(index, _)| 1 << index != contents || given & symlink != 0) + .fold(Features::NONE, |stated, (_, part)| stated | part.0) + }; + let check = |object: &FileObject, given: usize| { + assert_eq!(object.stated_features(), stated(given), "{:#x}: {:?}", given, object); + assert_eq!(object.stated_features(), stated_by_the_fields(object), "{:#x}", given); + }; + // Miri runs the tests of this file too, and takes long for every + // object: there it gets every 61st combination of each part. + let stride = if cfg!(miri) { 61 } else { 1 }; + for part in parts { + let own = ((1 << part.len()) - 1) << part.start; + let others = ((1 << fields.len()) - 1) & !own; + for combination in (0..1 << part.len()).step_by(stride) { + for rest in [0, others] { + let mut given: usize = rest | (combination << part.start); + let mut object = FileObject::new(NameBuf::new("f").unwrap()); + // The type of a symbolic link comes after its target + // the one way and before it the other. + let mut order: Vec = (0..fields.len()).collect(); + if rest != 0 { + order.reverse(); + } + for index in order { + if given & (1 << index) != 0 { + fields[index].1(&mut object); + } + } + check(&object, given); + // What a reader fills in states nothing. + object.fill_in(Features::ALL); + object.fill_in_data(SizeAndHash { + size: Some(6), + sha256: Some(Sha256::digest(b"target")), + }); + check(&object, given); + assert_eq!(object.clone(), object); + for index in part.clone() { + if given & (1 << index) != 0 { + fields[index].2(&mut object); + given &= !(1 << index); + check(&object, given); + } + } + } + } + } + } + + /// The features an object keeps stay those of its fields through any + /// sequence of calls that change it: the setters and takers of a file + /// object, of its inode attributes and of a partition, what a reader, + /// a walk and the manifest builder set and fill in, retain_features(), + /// fill_in(), a part that is put in whole and a clone. The calls are + /// the same every time. + #[test] + fn keeps_the_features_through_any_sequence_of_calls() { + const TYPES: [InodeType; 7] = [ + InodeType::Regular, + InodeType::Directory, + InodeType::Symlink, + InodeType::Fifo, + InodeType::CharDevice, + InodeType::BlockDevice, + InodeType::Socket, + ]; + const STATES: [Option; 3] = [None, Some(false), Some(true)]; + const UUID: Uuid = Uuid::new([1; Uuid::SIZE]); + /// What a call draws on: the numbers of xorshift64, which are the + /// same every time. + struct Numbers(u64); + impl Numbers { + /// The next number, below `below`. + fn below(&mut self, below: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % below as u64) as usize + } + /// One of two. + fn some(&mut self) -> bool { + self.below(2) == 0 + } + /// A value, or none where a setter is to take one away. + fn value(&mut self, value: T) -> Option { + (self.below(3) != 0).then_some(value) + } + /// A state of a flag, or none. + fn flag(&mut self) -> Option { + STATES[self.below(STATES.len())] + } + /// Some of the features. + fn features(&mut self) -> Features { + Features::ALL + .names() + .map(|name| name.parse().unwrap()) + .filter(|_| self.some()) + .fold(Features::NONE, |features, feature: Features| features | feature) + } + /// What an object says about the flags of one kind: some + /// given, some filled in. + fn states(&mut self) -> FlagStates { + let mut states = FlagStates::default(); + for &(flag, _, feature) in F::FIELDS { + match self.flag() { + Some(set) => states.put(flag, self.value(set)), + None => states.fill_in(feature, InodeType::Regular), + } + } + states + } + /// Some of the marks of `fields`. + fn marks(&mut self, fields: [Field; 2]) -> FilledIn { + let mut marks = FilledIn::default(); + for field in fields { + if self.some() { + marks.insert(field); + } + } + marks + } + /// A target of a symbolic link, or no contents objects. + fn contents(&mut self) -> Vec { + let target = ContentsObject::new(ContentsSource::Literal(b"t".to_vec())); + self.value(target).into_iter().collect() + } + } + /// Changes the partition of `object`, where it has one. + fn partition(object: &mut FileObject, change: impl FnOnce(&mut GptPartition)) { + if let Some(gpt) = object.gpt_mut() { + change(gpt); + } + } + type Call = fn(&mut FileObject, &mut Numbers); + let calls: [Call; 55] = [ + // What a caller calls of a file object. + |o, n| o.set_inode_type(TYPES[n.below(TYPES.len())]), + |o, n| o.set_size(n.value(1)), + |o, n| o.set_sha256(n.value(Sha256::digest(b"t"))), + |o, n| o.set_contents(n.contents()), + |o, _| drop(o.take_contents()), + |o, n| o.set_inode_token(n.value(NonZeroU64::MIN)), + |o, n| o.set_major(n.value(1)), + |o, n| o.set_minor(n.value(1)), + |o, n| o.set_gpt(n.value(GptPartition::default())), + |o, _| drop(o.take_gpt()), + |o, n| o.set_flag_archive(n.flag()), + |o, n| o.set_flag_hidden(n.flag()), + |o, n| o.set_flag_system(n.flag()), + |o, n| o.retain_features(n.features()), + |o, _| o.set_name(NameBuf::new("g").unwrap()), + |o, n| { + o.set_validity(ValidityWindow { + since_usec: n.below(2) as u64, + ..ValidityWindow::default() + }) + }, + |o, _| *o = o.clone(), + // Of its partition, where it has one. + |o, n| partition(o, |gpt| gpt.set_label(n.value("l".into()))), + |o, n| partition(o, |gpt| gpt.set_uuid(n.value(UUID))), + |o, n| partition(o, |gpt| gpt.set_type_uuid(n.value(UUID))), + |o, n| partition(o, |gpt| gpt.set_flags(n.value(0))), + |o, n| partition(o, |gpt| gpt.set_no_auto(n.flag())), + |o, n| partition(o, |gpt| gpt.set_grow_file_system(n.flag())), + // Of its inode attributes. + |o, n| o.inode_mut().set_mode(n.value(Mode::from_st_mode(0o644))), + |o, n| o.inode_mut().set_uid(n.value(1)), + |o, n| o.inode_mut().set_gid(n.value(1)), + |o, n| o.inode_mut().set_user_name(n.value("u".into())), + |o, n| o.inode_mut().set_group_name(n.value("g".into())), + |o, n| o.inode_mut().set_mtime_nsec(n.value(1)), + // A time before the epoch leaves the attributes without one. + |o, n| { + let time = [UNIX_EPOCH, UNIX_EPOCH - Duration::from_secs(1)][n.below(2)]; + o.inode_mut().set_mtime(time); + }, + |o, n| o.inode_mut().set_user_xattrs(n.value(BTreeMap::new())), + |o, _| drop(o.inode_mut().insert_user_xattr("a", b"v")), + |o, _| drop(o.inode_mut().remove_user_xattr("a")), + |o, n| o.inode_mut().set_read_only(n.flag()), + |o, n| o.inode_mut().set_flag_append_only(n.flag()), + |o, n| o.inode_mut().set_flag_immutable(n.flag()), + |o, n| o.inode_mut().set_flag_no_atime(n.flag()), + |o, n| o.inode_mut().set_flag_no_cow(n.flag()), + |o, n| o.inode_mut().set_flag_no_dump(n.flag()), + // Inode attributes that are put in whole bring their own. + |o, n| { + let mut inode = InodeAttributes::default(); + inode.set_uid(n.value(2)); + inode.set_flag_no_dump(n.flag()); + *o.inode_mut() = inode; + }, + // What a reader, a walk and the manifest builder call. + |o, n| o.fill_in(n.features()), + |o, n| o.put_contents(n.contents()), + |o, n| { + if let Some(contents) = o.contents_mut().first_mut() { + contents.set_offset(n.below(2) as u64); + } + }, + |o, n| { + o.fill_in_data(SizeAndHash { + size: n.value(1), + sha256: n.value(Sha256::digest(b"t")), + }) + }, + |o, _| o.fill_in_from_contents(), + |o, n| o.set_dos_flags(n.states()), + |o, n| o.inode_mut().set_flags(n.states()), + |o, n| o.set_marks(n.marks([Field::Size, Field::Sha256])), + |o, n| { + o.inode_mut() + .set_marks(n.marks([Field::ReadOnly, Field::ExtendedAttributes])) + }, + |o, n| o.gpt_or_default().set_flags(n.value(0)), + |o, n| o.validity_mut().set_since_usec(n.below(2) as u64), + // The types that a target counts on and does not, the size and + // the target itself, once more each: they are called most. + |o, _| o.set_inode_type(InodeType::Symlink), + |o, _| o.set_inode_type(InodeType::Regular), + |o, _| o.set_size(Some(1)), + |o, _| o.set_contents(vec![ContentsObject::new(ContentsSource::Literal(b"t".to_vec()))]), + ]; + // Miri runs the tests of this file too, and takes long for every + // call. + let (objects, calls_of_each) = if cfg!(miri) { (4, 100) } else { (400, 250) }; + let mut numbers = Numbers(0x9e37_79b9_7f4a_7c15); + let mut count = 0; + for _ in 0..objects { + let mut object = FileObject::new(NameBuf::new("f").unwrap()); + for _ in 0..calls_of_each { + let call = numbers.below(calls.len()); + calls[call](&mut object, &mut numbers); + count += 1; + assert_eq!( + object.stated_features(), + stated_by_the_fields(&object), + "after {} calls, the last one call {}: {:?}", + count, + call, + object + ); + // A root file object with these inode attributes states + // the same for them, and is asked for its own fields. + let mut root = RootObject::default(); + *root.inode_mut() = object.inode().clone(); + root.file_system_mut().set_uuid(numbers.value(UUID)); + root.file_system_mut().set_label(numbers.value("l".into())); + root.file_system_mut().set_fat_serial(numbers.value(FatSerial::new(1))); + root.set_gpt_disk_uuid(numbers.value(UUID)); + let by_the_fields = root + .feature_fields() + .fold(Features::NONE, |features, (_, feature)| features | feature); + assert_eq!( + root.stated_features(), + by_the_fields, + "after {} calls: {:?}", + count, + root + ); + } + } + } + + /// retain_features() leaves an object that has every field with the + /// fields of the features it is given: the object of a caller that set + /// those fields alone. Every feature is dropped on its own and kept on + /// its own. + #[test] + fn retains_the_fields_of_the_features() { + const UUID: Uuid = Uuid::new([1; Uuid::SIZE]); + /// Gives the partition of `object` a field. + fn partition(object: &mut FileObject, give: Give) { + let mut gpt = object.take_gpt().unwrap_or_default(); + give(&mut gpt); + object.set_gpt(Some(gpt)); + } + // Every field of a file object that belongs to a feature, set the + // way a caller sets it. + let fields: [(Features, Give); 27] = [ + (Features::SIZE, |o| o.set_size(Some(5))), + (Features::SHA256, |o| o.set_sha256(Some(Sha256::digest(b"hello")))), + (Features::HARDLINK, |o| o.set_inode_token(NonZeroU64::new(1))), + (Features::DEVICE, |o| o.set_major(Some(8))), + (Features::DEVICE, |o| o.set_minor(Some(1))), + (Features::GPT_LABEL, |o| { + partition(o, |gpt| gpt.set_label(Some("esp".into()))) + }), + (Features::GPT_UUID, |o| partition(o, |gpt| gpt.set_uuid(Some(UUID)))), + (Features::GPT_TYPE_UUID, |o| { + partition(o, |gpt| gpt.set_type_uuid(Some(UUID))) + }), + (Features::GPT_FLAGS, |o| partition(o, |gpt| gpt.set_flags(Some(0)))), + (Features::GPT_FLAG_NO_AUTO, |o| { + partition(o, |gpt| gpt.set_no_auto(Some(false))) + }), + (Features::GPT_FLAG_GROW_FILE_SYSTEM, |o| { + partition(o, |gpt| gpt.set_grow_file_system(Some(true))) + }), + (Features::FLAG_ARCHIVE, |o| o.set_flag_archive(Some(true))), + (Features::FLAG_HIDDEN, |o| o.set_flag_hidden(Some(false))), + (Features::FLAG_SYSTEM, |o| o.set_flag_system(Some(true))), + (Features::MODE, |o| o.inode_mut().set_mode(Mode::new(0o644).ok())), + (Features::UID, |o| o.inode_mut().set_uid(Some(1))), + (Features::GID, |o| o.inode_mut().set_gid(Some(2))), + (Features::USER_NAME, |o| o.inode_mut().set_user_name(Some("u".into()))), + (Features::GROUP_NAME, |o| o.inode_mut().set_group_name(Some("g".into()))), + (Features::MTIME, |o| o.inode_mut().set_mtime_nsec(Some(3))), + (Features::USER_XATTR, |o| { + o.inode_mut().insert_user_xattr("a", b"b"); + }), + (Features::READ_ONLY, |o| o.inode_mut().set_read_only(Some(false))), + (Features::FLAG_APPEND_ONLY, |o| { + o.inode_mut().set_flag_append_only(Some(true)) + }), + (Features::FLAG_IMMUTABLE, |o| { + o.inode_mut().set_flag_immutable(Some(false)) + }), + (Features::FLAG_NO_ATIME, |o| o.inode_mut().set_flag_no_atime(Some(true))), + (Features::FLAG_NO_COW, |o| o.inode_mut().set_flag_no_cow(Some(false))), + (Features::FLAG_NO_DUMP, |o| o.inode_mut().set_flag_no_dump(Some(true))), + ]; + // The object of a caller that set the fields of `features` alone. + let with = |features: Features| { + let mut object = FileObject::new(NameBuf::new("f").unwrap()); + for (feature, give) in fields { + if features.contains(feature) { + give(&mut object); + } + } + object + }; + // With every feature it has every field of the tables but the + // target, which only a symbolic link has, and it states every flag. + let full = with(Features::ALL); + for (field, _) in FileObject::FEATURE_FIELDS { + assert_eq!(full.has_feature_field(field), field != Field::Contents, "{}", field); + } + for (field, _) in InodeAttributes::FEATURE_FIELDS { + assert!(full.inode.has_feature_field(field), "{}", field); + } + assert_eq!( + (full.dos_flags.stated, full.inode.flags.stated), + (DosFlags::ALL, InodeFlags::ALL) + ); + let single = Features::ALL.names().map(|name| name.parse::().unwrap()); + for feature in single { + let others = Features::ALL.without(feature); + let mut dropped = full.clone(); + dropped.retain_features(others); + assert_eq!(dropped, with(others), "{:?}", feature); + let mut kept = full.clone(); + kept.retain_features(feature); + assert_eq!(kept, with(feature), "{:?}", feature); + } + // Several features, all of them and none of them. + let mut default = full.clone(); + default.retain_features(Features::DEFAULT); + assert_eq!(default, with(Features::DEFAULT)); + assert_eq!(default.stated_features(), Features::DEFAULT.without(Features::SYMLINK)); + let mut all = full.clone(); + all.retain_features(Features::ALL); + assert_eq!(all, full); + let mut none = full.clone(); + none.retain_features(Features::NONE); + assert_eq!(none, FileObject::new(NameBuf::new("f").unwrap())); + } + + /// The name, the type, the validity window and the contents objects of + /// a file that is no symbolic link belong to no feature, and + /// retain_features() leaves them. The contents objects of a symbolic + /// link are its target, which goes without the feature `symlink`. + #[test] + fn retains_what_belongs_to_no_feature() { + use crate::testing::everything; + + let full = everything(); + let mut object = full.clone(); + object.retain_features(Features::NONE); + let mut bare = FileObject::new(full.name().to_owned()); + bare.set_validity(full.validity); + bare.put_contents(full.contents.clone()); + assert_eq!(object, bare); + assert_eq!( + (object.contents().len(), object.validity().state()), + (4, Validity::Revoked) + ); + let mut link = FileObject::new(NameBuf::new("l").unwrap()); + link.set_inode_type(InodeType::Symlink); + link.put_contents(vec![ContentsObject::new(ContentsSource::Literal(b"target".to_vec()))]); + let mut kept = link.clone(); + kept.retain_features(Features::SYMLINK); + assert_eq!(kept, link); + let mut dropped = link.clone(); + dropped.retain_features(Features::ALL.without(Features::SYMLINK)); + let mut bare = FileObject::new(NameBuf::new("l").unwrap()); + bare.set_inode_type(InodeType::Symlink); + assert_eq!(dropped, bare); + // The same contents objects are no target on any other file. + for inode_type in [InodeType::Regular, InodeType::Directory] { + let mut other = link.clone(); + other.set_inode_type(inode_type); + let before = other.clone(); + other.retain_features(Features::NONE); + assert_eq!(other, before, "{}", inode_type); + } + // A partition that was given no field has none to take away. + let mut object = FileObject::new(NameBuf::new("f").unwrap()); + object.set_gpt(Some(GptPartition::default())); + object.retain_features(Features::NONE); + assert_eq!(object.gpt(), Some(&GptPartition::default())); + } + + /// What a reader filled in goes with the feature of its field, as its + /// setter takes it away, and stays with it. The size and the hash a + /// reader filled in also go with the size, the hash or the target they + /// follow from, as they do where one of those is set. + #[test] + fn retains_what_a_reader_filled_in_for_a_feature() { + use crate::testing::{manifest, read_whole, record, sequence, EMPTY, HELLO, TRAILER}; + + let read = |record: &str| read_whole(&manifest(&[record])).unwrap().objects.pop().unwrap(); + let none = FilledIn::default(); + // readOnly, the flags and the extended attributes, which a reader + // fills in for the features of its manifest. + let root = concat!( + r#"{"features":["flag-hidden","flag-no-dump","read-only","user-xattr"],"#, + r#""mediaType":"application/vnd.uapi.16.manifest"}"# + ); + let recorded = Features::FLAG_HIDDEN | Features::FLAG_NO_DUMP | Features::READ_ONLY | Features::USER_XATTR; + let whole = read_whole(&sequence(&[root, r#"{"name":"a"}"#, TRAILER])).unwrap(); + let filled = whole.objects.into_iter().next().unwrap(); + assert_eq!(filled.filled_in().iter().count(), 4); + let mut same = filled.clone(); + same.retain_features(recorded); + assert_eq!(same, filled); + let fields: [(Features, Give); 4] = [ + (Features::FLAG_HIDDEN, |o| o.set_flag_hidden(None)), + (Features::FLAG_NO_DUMP, |o| o.inode_mut().set_flag_no_dump(None)), + (Features::READ_ONLY, |o| o.inode_mut().set_read_only(None)), + (Features::USER_XATTR, |o| o.inode_mut().set_user_xattrs(None)), + ]; + for (feature, unset) in fields { + let mut object = filled.clone(); + object.retain_features(recorded.without(feature)); + let mut unset_alone = filled.clone(); + unset(&mut unset_alone); + assert_eq!(object, unset_alone, "{:?}", feature); + assert_eq!(object.filled_in().iter().count(), 3, "{:?}", feature); + } + let mut object = filled.clone(); + object.retain_features(Features::NONE); + assert_eq!(object, FileObject::new(NameBuf::new("a").unwrap())); + // The hash of no data, which a reader fills in for the size 0, and + // the size 0 for that hash: each goes with its own feature. + let empty = format!(r#"{{"name":"a","sha256":"{}"}}"#, EMPTY); + let filled = read(r#"{"name":"a","size":0}"#); + assert!(filled.filled_in().contains(Field::Sha256)); + let mut object = filled.clone(); + object.retain_features(Features::SIZE | Features::SHA256); + assert_eq!(object, filled); + object.retain_features(Features::SIZE); + assert_eq!( + (object.size(), object.sha256(), object.filled_in()), + (Some(0), None, none) + ); + let mut object = read(&empty); + assert!(object.filled_in().contains(Field::Size)); + object.retain_features(Features::SHA256); + assert_eq!( + (object.size(), object.sha256(), object.filled_in()), + (None, Some(Sha256::EMPTY), none) + ); + // And each goes with the one it follows from. + for (given, features) in [ + (r#"{"name":"a","size":0}"#, Features::SHA256), + (&*empty, Features::SIZE), + ] { + let mut object = read(given); + object.retain_features(features); + assert_eq!( + (object.size(), object.sha256(), object.filled_in()), + (None, None, none), + "{}", + given + ); + } + // The size a contents object gives. There is no hash to take away + // with the feature `sha256`, so the size stays with its own feature + // and goes with it. The contents object keeps what it says. + let filled = read(r#"{"name":"a","contents":[{"file":"blob","originalSize":3}]}"#); + assert_eq!( + (filled.size(), filled.filled_in().contains(Field::Size)), + (Some(3), true) + ); + let mut object = filled.clone(); + object.retain_features(Features::SIZE); + assert_eq!(object, filled); + object.retain_features(Features::NONE); + assert_eq!((object.size(), object.filled_in()), (None, none)); + assert_eq!(object.contents(), filled.contents()); + // The size and the hash a contents object gives. One goes with the + // other, as it does where the other is set, and the next reader + // fills both in again. + let filled = read(&format!( + r#"{{"name":"a","contents":[{{"file":"blob","originalSize":5,"originalSha256":"{}"}}]}}"#, + HELLO + )); + assert_eq!((filled.size(), filled.sha256()), (Some(5), HELLO.parse().ok())); + for features in [Features::SIZE, Features::SHA256, Features::NONE] { + let mut object = filled.clone(); + object.retain_features(features); + assert_eq!( + (object.size(), object.sha256(), object.filled_in()), + (None, None, none), + "{:?}", + features + ); + assert_eq!(object.contents(), filled.contents()); + assert_eq!(read(&record(&object)), filled); + } + // The size of the target of a symbolic link, which goes with the + // target and with its own feature. + let filled = read(r#"{"name":"l","type":"lnk","contents":[{"literal":"dGFyZ2V0"}]}"#); + assert_eq!( + (filled.size(), filled.filled_in().contains(Field::Size)), + (Some(6), true) + ); + let mut object = filled.clone(); + object.retain_features(Features::SIZE | Features::SYMLINK); + assert_eq!(object, filled); + object.retain_features(Features::SIZE); + assert_eq!( + (object.contents().len(), object.size(), object.filled_in()), + (0, None, none) + ); + let mut object = filled.clone(); + object.retain_features(Features::SYMLINK); + assert_eq!( + (object.contents(), object.size(), object.filled_in()), + (filled.contents(), None, none) + ); + } + + /// A writer refuses an object with a field of a feature its manifest + /// does not record, and takes the object once it retains the features + /// the manifest records. + #[test] + fn a_writer_takes_what_is_retained() { + use crate::testing::{directory, everything}; + use crate::Writer; + + let mut device = FileObject::new(NameBuf::new("device").unwrap()); + device.set_inode_type(InodeType::CharDevice); + device.set_major(Some(1)); + device.set_minor(Some(3)); + let mut link = FileObject::new(NameBuf::new("link").unwrap()); + link.set_inode_type(InodeType::Symlink); + link.set_contents(vec![ContentsObject::new(ContentsSource::Literal(b"target".to_vec()))]); + let objects = [directory("a"), everything(), device, link]; + let single = Features::ALL.names().map(|name| name.parse::().unwrap()); + let sets = single + .flat_map(|feature| [feature, Features::ALL.without(feature)]) + .chain([Features::NONE, Features::DEFAULT, Features::ALL]); + for features in sets { + let mut root = RootObject::default(); + root.set_features(Some(features)); + let mut writer = Writer::begin(Vec::new(), &root).unwrap(); + for object in &objects { + if !features.contains(object.stated_features()) { + let e = writer.file(object).unwrap_err(); + assert_eq!( + e.kind(), + ErrorKind::Manifest(Problem::UnlistedFeature), + "{:?}", + features + ); + } + let mut retained = object.clone(); + retained.retain_features(features); + writer + .file(&retained) + .unwrap_or_else(|e| panic!("{:?}: {}", features, e)); + } + writer.finish().unwrap(); + } + } + #[test] fn contents_objects() { let contents = ContentsObject::default(); @@ -3051,6 +4218,18 @@ mod tests { filled: InodeFlags::default(), }, filled_in: FilledIn::default(), + stated: StatedFeatures( + Features::MODE + | Features::UID + | Features::GID + | Features::USER_NAME + | Features::GROUP_NAME + | Features::MTIME + | Features::USER_XATTR + | Features::READ_ONLY + | Features::FLAG_IMMUTABLE + | Features::FLAG_NO_DUMP, + ), }; let object = FileObject { name: NameBuf::new("f").unwrap(), @@ -3070,7 +4249,10 @@ mod tests { inode: inode.clone(), validity: ValidityWindow::default(), filled_in: FilledIn::default(), + stated: StatedFeatures(Features::SIZE | Features::SHA256 | Features::HARDLINK | Features::FLAG_HIDDEN), }; + // The features the literals name are those of their fields. + assert_eq!(object.stated_features(), stated_by_the_fields(&object)); let root = RootObject { inode: inode.clone(), file_system: FileSystemIdentity::default(), @@ -3096,36 +4278,36 @@ mod tests { each_differs( &inode, &[ - |i| i.mode = None, - |i| i.uid = None, - |i| i.gid = None, - |i| i.user_name = None, - |i| i.group_name = None, - |i| i.mtime_nsec = None, - |i| i.user_xattrs = None, - |i| i.read_only = None, + |i| i.set_mode(None), + |i| i.set_uid(None), + |i| i.set_gid(None), + |i| i.set_user_name(None), + |i| i.set_group_name(None), + |i| i.set_mtime_nsec(None), + |i| i.set_user_xattrs(None), + |i| i.set_read_only(None), // A flag not known any more, and one set instead of cleared. - |i| i.flags.put(InodeFlags::NO_DUMP, None), - |i| i.flags.put(InodeFlags::NO_DUMP, Some(true)), + |i| i.set_flag_no_dump(None), + |i| i.set_flag_no_dump(Some(true)), ], InodeAttributes::eq_ignore_filled_in, ); each_differs( &object, &[ - |o| o.name = NameBuf::new("g").unwrap(), - |o| o.inode_type = InodeType::Symlink, - |o| o.size = None, - |o| o.sha256 = None, - |o| o.contents.clear(), - |o| o.contents[0].offset = 1, - |o| o.inode_token = None, - |o| o.major = Some(1), - |o| o.minor = Some(1), - |o| o.gpt = Some(Box::default()), - |o| o.dos_flags.put(DosFlags::HIDDEN, None), - |o| o.dos_flags.put(DosFlags::HIDDEN, Some(true)), - |o| o.inode.uid = None, + |o| o.set_name(NameBuf::new("g").unwrap()), + |o| o.set_inode_type(InodeType::Symlink), + |o| o.set_size(None), + |o| o.set_sha256(None), + |o| o.put_contents(Vec::new()), + |o| o.contents_mut()[0].offset = 1, + |o| o.set_inode_token(None), + |o| o.set_major(Some(1)), + |o| o.set_minor(Some(1)), + |o| o.set_gpt(Some(GptPartition::default())), + |o| o.set_flag_hidden(None), + |o| o.set_flag_hidden(Some(true)), + |o| o.inode.set_uid(None), |o| o.validity.state = Validity::Revoked, ], FileObject::eq_ignore_filled_in, @@ -3133,7 +4315,7 @@ mod tests { each_differs( &root, &[ - |r| r.inode.uid = None, + |r| r.inode.set_uid(None), |r| r.file_system.label = Some("ESP".into()), |r| r.gpt_disk_uuid = Some(Uuid::new([1; Uuid::SIZE])), |r| r.order = Some(Order::CodePoint), @@ -3147,21 +4329,25 @@ mod tests { let mut filled = contents.clone(); filled.filled_in.insert(Field::EncodedSize); assert!(filled.eq_ignore_filled_in(&contents) && filled != contents); + let (mut read_only, mut xattrs) = (FilledIn::default(), FilledIn::default()); + read_only.insert(Field::ReadOnly); + xattrs.insert(Field::ExtendedAttributes); let (mut filled, mut set) = (inode.clone(), inode.clone()); - filled.filled_in.insert(Field::ReadOnly); - filled.filled_in.insert(Field::ExtendedAttributes); - filled.flags.fill_in(Features::FLAG_NO_COW, InodeType::Regular); + filled.set_marks(read_only.union(xattrs)); + filled.fill_in(Features::FLAG_NO_COW, InodeType::Regular); set.set_flag_no_cow(Some(false)); assert!(filled.eq_ignore_filled_in(&set) && filled != set); let (mut filled, mut set) = (object.clone(), object.clone()); - filled.filled_in.insert(Field::Size); + let mut size = FilledIn::default(); + size.insert(Field::Size); + filled.set_marks(size); filled.contents[0].filled_in.insert(Field::OriginalSize); - filled.inode.filled_in.insert(Field::ReadOnly); - filled.dos_flags.fill_in(Features::FLAG_ARCHIVE, InodeType::Regular); + filled.inode.set_marks(read_only); + filled.fill_in(Features::FLAG_ARCHIVE); set.set_flag_archive(Some(false)); assert!(filled.eq_ignore_filled_in(&set) && filled != set); let mut filled = root.clone(); - filled.inode.filled_in.insert(Field::ExtendedAttributes); + filled.inode.set_marks(xattrs); assert!(filled.eq_ignore_filled_in(&root) && filled != root); } } diff --git a/src/uapi16/optional.rs b/src/uapi16/optional.rs new file mode 100644 index 0000000..6c5dfab --- /dev/null +++ b/src/uapi16/optional.rs @@ -0,0 +1,1622 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! What the features of a manifest record of a file of a tree that statx() +//! does not say: its inode flags, its DOS attributes, whether it is +//! read-only, its extended attributes and the names of its owners, and for +//! the root of the tree the identity of its file system. +//! +//! A feature that was asked for and that cannot be read is an error that +//! names the feature. A field that is missing where its feature is recorded +//! says that a flag is cleared, that a file has no extended attributes or +//! that a file system has no label, so leaving one out would claim what +//! nobody read. Three things never fail. The name of an owner that the +//! user database does not have is left out and counted, as the +//! specification gives a missing name no meaning. The UUID and the volume +//! serial number of a file system that has none are left out: the +//! specification leaves a missing one to whoever makes the file system. +//! And whether a file is read-only can always be told from its mode. + +use std::collections::HashMap; +use std::hash::Hash; + +use rustix::fs::FileType; + +use crate::object::{ + DosFlags, FileObject, FileSystemIdentity, FlagSet, FlagStates, InodeAttributes, InodeFlags, RootObject, Uuid, +}; +use crate::sys::{DosAttributes, FsLabel, FsUuid, Readable, UserDatabase, UserXattrs}; +use crate::tree::{DeviceNumber, Entry, Failure, MountId, Place, Unreadable}; +use crate::Features; + +/// Answers that are asked for again and again, kept by what was asked. It +/// keeps so many at most. Full, it forgets them all, so that no tree can +/// make it grow, and each is asked for once more. +#[derive(Debug)] +struct Cache { + answers: HashMap, + /// How many answers are kept at most. + most: usize, +} + +impl Cache { + /// A cache of at most `most` answers. + fn new(most: usize) -> Cache { + Cache { + answers: HashMap::new(), + most, + } + } + + /// The answer kept for `key`. + fn get(&self, key: &K) -> Option<&V> { + self.answers.get(key) + } + + /// Keeps `answer` for `key`. + fn insert(&mut self, key: K, answer: V) { + if self.answers.len() >= self.most { + self.answers.clear(); + } + self.answers.insert(key, answer); + } +} + +/// The names of the owners of the files of a tree, as the user database of +/// the host has them. The names are the view of the host, which need not +/// be that of the tree, so a manifest only records them where it is asked +/// to. Each ID is looked up once: what was found is kept, also that there +/// is no name, the way systemd's manifest_resolve_name() keeps it. +#[derive(Debug)] +struct OwnerNames { + database: UserDatabase, + users: Cache>>, + groups: Cache>>, +} + +impl OwnerNames { + /// How many users and how many groups are kept. + const KEPT: usize = 16384; + + fn new() -> OwnerNames { + OwnerNames { + database: UserDatabase::new(), + users: Cache::new(OwnerNames::KEPT), + groups: Cache::new(OwnerNames::KEPT), + } + } + + /// The name of the user `uid`, if it has one a manifest can hold. + fn user(&mut self, uid: u32) -> Option> { + if let Some(name) = self.users.get(&uid) { + return name.clone(); + } + let name = self.database.user_name(uid).map(String::into_boxed_str); + self.users.insert(uid, name.clone()); + name + } + + /// The name of the group `gid`, if it has one a manifest can hold. + fn group(&mut self, gid: u32) -> Option> { + if let Some(name) = self.groups.get(&gid) { + return name.clone(); + } + let name = self.database.group_name(gid).map(String::into_boxed_str); + self.groups.insert(gid, name.clone()); + name + } +} + +/// Reads what the features of a manifest record of the files of a tree +/// beyond what statx() says of each, see the documentation of this module. +/// +/// It reads through the handle of an entry where that is enough. Where it +/// takes the file itself, for its inode flags, its DOS attributes or the +/// identity of its file system, it opens the regular file or the directory, +/// see [`Entry::reopen`], unless the caller did so already, and leaves it +/// open for the caller. Nothing else is opened, and nothing is opened for +/// its extended attributes: they are read through the file where it is +/// open, and through its handle where it is not, see [`UserXattrs`]. An +/// automount point is not opened at all, see [`Entry::is_automount`], so +/// what takes the open file can't be read of it. +#[derive(Debug)] +pub(crate) struct FeatureReader { + features: Features, + /// The inode flags the features record. + inode_flags: InodeFlags, + /// The DOS attributes the features record. + dos_flags: DosFlags, + names: OwnerNames, + xattrs: UserXattrs, + /// Whether the files of a file system have DOS attributes, for the + /// file systems that were asked so far. A file system is a device as + /// one mount shows it. + dos_attributes: Cache<(MountId, DeviceNumber), bool>, +} + +impl FeatureReader { + /// The features that record the identity of a file system. + const IDENTITY: Features = Features::FAT_SERIAL.union(Features::FS_LABEL).union(Features::FS_UUID); + /// How many file systems it is kept for whether they have DOS + /// attributes. + const FILE_SYSTEMS: usize = 1024; + + /// A reader for a manifest that records `features`. + pub(crate) fn new(features: Features) -> FeatureReader { + FeatureReader { + features, + inode_flags: InodeFlags::recorded_by(features), + dos_flags: DosFlags::recorded_by(features), + names: OwnerNames::new(), + xattrs: UserXattrs::new(), + dos_attributes: Cache::new(FeatureReader::FILE_SYSTEMS), + } + } + + /// Reads what the features record of the file of `entry`, which is not + /// the root of the tree, into `object`. `place` is where the entry is, + /// which a directory is opened by, see [`Entry::reopen`]. `opened` is + /// the file opened for reading, if it is, and is filled in where this + /// opens it. Returns how many fields were left out: the names of owners + /// that have none. + pub(crate) fn read( + &mut self, + entry: &Entry<'_>, + place: Option>, + opened: &mut Option, + object: &mut FileObject, + ) -> Result { + let mut read_only = None; + // Only regular files and directories have inode flags and DOS + // attributes. + if matches!(entry.status().file_type, FileType::RegularFile | FileType::Directory) { + self.read_inode_flags(entry, place, opened, object.inode_mut())?; + read_only = self.read_dos_attributes(entry, place, opened, object)?; + } + self.read_inode(entry, opened, read_only, object.inode_mut()) + } + + /// Reads what the features record of the root of the tree, the + /// directory of `entry`, into `root`, as [`FeatureReader::read`] does + /// for the other files. The root has no DOS attributes, as the root + /// directory of a FAT file system has no directory entry to keep them + /// in, and it has the identity of its file system. It is the directory + /// of a descriptor of a caller, which has no name to be opened by. + /// Returns how many fields were left out: the names of owners that have + /// none, and the UUID and the volume serial number of a file system + /// that has none. + pub(crate) fn read_root( + &mut self, + entry: &Entry<'_>, + opened: &mut Option, + root: &mut RootObject, + ) -> Result { + debug_assert_eq!(entry.status().file_type, FileType::Directory); + self.read_inode_flags(entry, None, opened, &mut root.inode)?; + let identity = self.read_identity(entry, opened, &mut root.file_system)?; + let names = self.read_inode(entry, opened, None, &mut root.inode)?; + Ok(identity + names) + } + + /// The file of `entry`, which is at `place`, open for reading: `opened` + /// if it is, or else opened now, see [`Entry::reopen`], and kept in + /// `opened`. It is opened for `feature`, which can't be read of an + /// automount point, since that is not opened. + fn open<'a>( + entry: &Entry<'_>, + place: Option>, + opened: &'a mut Option, + feature: Features, + ) -> Result<&'a Readable, Failure> { + let readable = match opened.take() { + Some(readable) => readable, + None if entry.is_automount() => return Err(Failure::Unavailable(feature, Unreadable::Automount)), + None => entry.reopen(place)?, + }; + Ok(opened.insert(readable)) + } + + /// Fails unless the file system of the directory of `entry`, that of a + /// descriptor a caller gave, has DOS attributes, where the features + /// record one of hidden, system and archive. A walk asks that of the + /// directory it starts at before it adds anything: every file below it + /// is asked for them, and the root of a tree itself has none to be + /// asked for. The file system is asked the way its first file would + /// ask it, and is not asked again. `opened` is as for + /// [`FeatureReader::read`]. + pub(crate) fn check_dos_attributes( + &mut self, + entry: &Entry<'_>, + opened: &mut Option, + ) -> Result<(), Failure> { + debug_assert_eq!(entry.status().file_type, FileType::Directory); + let Some(feature) = FeatureReader::first_feature(self.dos_flags) else { + return Ok(()); + }; + match self.dos_attributes(entry, None, opened, feature)? { + Some(_) => Ok(()), + None => Err(Failure::Unavailable(feature, Unreadable::NoDosAttributes)), + } + } + + /// States each of the flags `recorded` in `states`: set if it is among + /// `set`, and cleared if it is not. + fn state(states: &mut FlagStates, recorded: F, set: F) { + for &(flag, _, _) in F::FIELDS { + if (recorded & flag) == flag { + states.put(flag, Some((set & flag) == flag)); + } + } + } + + /// The feature of the first of the flags `recorded`, in the order of + /// the names of their fields, which names an error about them all. + fn first_feature(recorded: F) -> Option { + F::FIELDS + .iter() + .find(|&&(flag, _, _)| (recorded & flag) == flag) + .map(|&(_, _, feature)| feature) + } + + /// Reads the inode flags the features record of the regular file or + /// the directory of `entry` into `inode`. A file system without inode + /// flags cannot say that they are cleared. + fn read_inode_flags( + &mut self, + entry: &Entry<'_>, + place: Option>, + opened: &mut Option, + inode: &mut InodeAttributes, + ) -> Result<(), Failure> { + let Some(feature) = FeatureReader::first_feature(self.inode_flags) else { + return Ok(()); + }; + match FeatureReader::open(entry, place, opened, feature)?.inode_flags()? { + Some(set) => { + let mut flags = inode.flags(); + FeatureReader::state(&mut flags, self.inode_flags, set); + inode.set_flags(flags); + } + None => return Err(Failure::Unavailable(feature, Unreadable::NoInodeFlags)), + } + Ok(()) + } + + /// The DOS attributes of the regular file or the directory of `entry`, + /// or nothing if its file system has none. A file system is asked with + /// its first file, and one that has none is not asked again. They are + /// read for `feature`. + fn dos_attributes( + &mut self, + entry: &Entry<'_>, + place: Option>, + opened: &mut Option, + feature: Features, + ) -> Result, Failure> { + let identity = &entry.status().identity; + let file_system = (identity.mount, identity.device); + let known = self.dos_attributes.get(&file_system).copied(); + if known == Some(false) { + return Ok(None); + } + let attributes = FeatureReader::open(entry, place, opened, feature)?.dos_attributes()?; + if known.is_none() { + self.dos_attributes.insert(file_system, attributes.is_some()); + } + Ok(attributes) + } + + /// Reads the DOS attributes the features record of the regular file or + /// the directory of `entry`, which is not the root, into `object`. + /// Returns whether a regular file has the read-only attribute, where + /// its file system has DOS attributes. The file system is only asked + /// where its answer is used: for one of the attributes hidden, system + /// and archive, or for whether a regular file is read-only. + fn read_dos_attributes( + &mut self, + entry: &Entry<'_>, + place: Option>, + opened: &mut Option, + object: &mut FileObject, + ) -> Result, Failure> { + let regular = entry.status().file_type == FileType::RegularFile; + let feature = FeatureReader::first_feature(self.dos_flags); + if feature.is_none() && !(regular && self.features.contains(Features::READ_ONLY)) { + return Ok(None); + } + let asked_for = feature.unwrap_or(Features::READ_ONLY); + let attributes = match (self.dos_attributes(entry, place, opened, asked_for), feature) { + (Ok(attributes), _) => attributes, + // Whether a file is read-only never fails: a file that cannot + // be asked for its attribute has its mode. + (Err(_), None) => None, + (Err(failure), Some(_)) => return Err(failure), + }; + match (attributes, feature) { + (Some(attributes), _) => { + let mut flags = object.dos_flags(); + FeatureReader::state(&mut flags, self.dos_flags, attributes.flags()); + object.set_dos_flags(flags); + Ok(regular.then_some(attributes.is_read_only())) + } + (None, Some(feature)) => Err(Failure::Unavailable(feature, Unreadable::NoDosAttributes)), + (None, None) => Ok(None), + } + } + + /// The label a manifest records for the answer `label` of a file + /// system: none for the empty one. + fn label(label: Option) -> Result, Failure> { + let unavailable = |why| Failure::Unavailable(Features::FS_LABEL, why); + match label { + Some(FsLabel::Label(label)) => Ok(Some(label)), + Some(FsLabel::Empty) => Ok(None), + Some(FsLabel::Unwritable) => Err(unavailable(Unreadable::LabelUnwritable)), + None => Err(unavailable(Unreadable::NoLabel)), + } + } + + /// The UUID a manifest records for what a file system says it + /// identifies itself with, in `identifier`. There is none where the + /// file system has no identifier or the kernel can't be asked for it, + /// and none where the identifier is no UUID: the one of all zeroes, or + /// one of another size, as the volume serial number of FAT is. + fn uuid(identifier: Option) -> Option { + match identifier { + Some(FsUuid::Uuid(uuid)) => Some(uuid), + Some(FsUuid::Null | FsUuid::NotUuid(_)) | None => None, + } + } + + /// Reads the identity of the file system the root of the tree, the + /// directory of `entry`, is in into `identity`, as far as the features + /// record it. A label that can't be read fails, since a root without + /// one says that its file system has none. The UUID and the volume + /// serial number are left out where the file system has none. An + /// automount point, which is not opened, is not asked for them. + /// Returns how many of the two were left out. + fn read_identity( + &mut self, + entry: &Entry<'_>, + opened: &mut Option, + identity: &mut FileSystemIdentity, + ) -> Result { + if (self.features & FeatureReader::IDENTITY) == Features::NONE { + return Ok(0); + } + // The root is opened for the first of them, and stays open. + let asked = !entry.is_automount(); + let mut omitted = 0; + if self.features.contains(Features::FAT_SERIAL) { + if asked { + let root = FeatureReader::open(entry, None, opened, Features::FAT_SERIAL)?; + identity.fat_serial = root.fat_serial()?; + } + omitted += u64::from(identity.fat_serial.is_none()); + } + if self.features.contains(Features::FS_LABEL) { + let root = FeatureReader::open(entry, None, opened, Features::FS_LABEL)?; + identity.label = FeatureReader::label(root.fs_label()?)?; + } + if self.features.contains(Features::FS_UUID) { + if asked { + let root = FeatureReader::open(entry, None, opened, Features::FS_UUID)?; + identity.uuid = FeatureReader::uuid(root.fs_uuid()?); + } + omitted += u64::from(identity.uuid.is_none()); + } + Ok(omitted) + } + + /// Reads what the features record of the file of `entry` that every + /// type of file can have into `inode`: whether it is read-only, its + /// extended attributes and the names of its owners. `opened` is the + /// file opened for reading, if it is, which the extended attributes + /// are read through then. `dos_read_only` says whether a regular file + /// has the read-only attribute of DOS, where its file system has one. + /// Returns how many names were left out. + /// + /// A regular file is read-only if it has that attribute, and anything + /// else, or a file in a file system without DOS attributes, if its + /// mode gives nobody write permission, as for systemd. The attribute + /// does not go against the mode: `readOnly` may not contradict `mode`, + /// and FAT and exFAT take the write permission away with the + /// attribute. A symbolic link has no mode and is never read-only. + /// `readOnly` is only stated where it is true, as the specification + /// asks. + fn read_inode( + &mut self, + entry: &Entry<'_>, + opened: &mut Option, + dos_read_only: Option, + inode: &mut InodeAttributes, + ) -> Result { + let status = entry.status(); + let symlink = status.file_type == FileType::Symlink; + if self.features.contains(Features::READ_ONLY) && !symlink { + let read_only = dos_read_only.unwrap_or(true) && !status.mode.is_writable(); + inode.set_read_only(read_only.then_some(true)); + } + if self.features.contains(Features::USER_XATTR) && !symlink { + // Through the file where it is open for reading anyway. Nothing + // is opened for its attributes. + let xattrs = match opened { + Some(file) => self.xattrs.read(file)?, + None => self.xattrs.read_unopened(entry)?, + }; + inode.set_user_xattrs(Some(xattrs)); + } + let mut omitted = 0; + if self.features.contains(Features::USER_NAME) { + inode.set_user_name(self.names.user(status.uid).map(String::from)); + omitted += u64::from(inode.user_name().is_none()); + } + if self.features.contains(Features::GROUP_NAME) { + inode.set_group_name(self.names.group(status.gid).map(String::from)); + omitted += u64::from(inode.group_name().is_none()); + } + Ok(omitted) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{self, written, TempDir}; + use crate::tree::{Handle, Status}; + use crate::{Mode, Name, NameBuf}; + use rustix::fs::{IFlags, OFlags, XattrFlags, CWD}; + use rustix::io::Errno; + use std::collections::BTreeMap; + use std::ffi::CStr; + use std::fs; + use std::os::fd::{AsFd, OwnedFd}; + use std::os::unix::ffi::OsStrExt; + use std::os::unix::fs::{symlink, PermissionsExt}; + use std::os::unix::net::UnixListener; + use std::path::Path; + use std::process::Command; + use std::time::Duration; + + /// Opens the directory `path` as a handle, the way an entry is opened. + fn open_dir(path: &Path) -> OwnedFd { + let flags = OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC; + rustix::fs::open(path, flags, rustix::fs::Mode::empty()).unwrap() + } + + /// The entry of the directory `path` itself, as the root of a tree. + fn root_entry(path: &Path) -> Entry<'static> { + let handle = open_dir(path); + let status = Status::of(handle.as_fd()).unwrap(); + Entry::new(Handle::Owned(handle), status, false) + } + + /// A tree with a file of every type a test can make: `file`, `dir`, + /// `link`, `fifo` and `socket`. + fn tree(name: &str) -> (TempDir, OwnedFd, UnixListener) { + let tmp = TempDir::new(name); + let dir = &tmp.0; + fs::write(dir.join("file"), b"data").unwrap(); + fs::create_dir(dir.join("dir")).unwrap(); + symlink("file", dir.join("link")).unwrap(); + let mode = rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR; + rustix::fs::mknodat(CWD, dir.join("fifo"), FileType::Fifo, mode, 0).unwrap(); + let socket = UnixListener::bind(dir.join("socket")).unwrap(); + let top = open_dir(dir); + (tmp, top, socket) + } + + /// The names of the files of [`tree`]. + const NAMES: [&CStr; 5] = [c"file", c"dir", c"link", c"fifo", c"socket"]; + + /// What `features` record of the entry `name` of `top`: the object, + /// whether the file was opened, and how many fields were left out. + fn read(features: Features, top: &OwnedFd, name: &CStr) -> Result<(FileObject, bool, u64), Failure> { + let entry = Entry::open_at(top.as_fd(), name).unwrap(); + read_entry(&mut FeatureReader::new(features), &entry, top, name) + } + + /// The same with the reader `reader` for the entry `entry`, which is + /// at `name` in `top`. + fn read_entry( + reader: &mut FeatureReader, + entry: &Entry<'_>, + top: &OwnedFd, + name: &CStr, + ) -> Result<(FileObject, bool, u64), Failure> { + let mut object = FileObject::new(NameBuf::new(name.to_str().unwrap()).unwrap()); + let mut opened = None; + let place = Place { dir: top.as_fd(), name }; + let omitted = reader.read(entry, Some(place), &mut opened, &mut object)?; + Ok((object, opened.is_some(), omitted)) + } + + /// What `features` record of the entry `name` of `top`, a regular file + /// or a directory that is open for reading before it is read, as a + /// file that is hashed and a directory that is listed are. + fn read_open(features: Features, top: &OwnedFd, name: &CStr) -> Result { + let entry = Entry::open_at(top.as_fd(), name).unwrap(); + let mut object = FileObject::new(NameBuf::new(name.to_str().unwrap()).unwrap()); + let place = Place { dir: top.as_fd(), name }; + let mut opened = Some(entry.reopen(Some(place))?); + FeatureReader::new(features).read(&entry, Some(place), &mut opened, &mut object)?; + assert!(opened.is_some()); + Ok(object) + } + + /// The feature and the reason of a read that failed for a feature that + /// cannot be read. + fn unavailable(read: Result) -> (Features, Unreadable) { + match read { + Err(Failure::Unavailable(feature, why)) => (feature, why), + other => panic!("{:?}", other), + } + } + + /// Whether the file system of the directory `dir` has DOS attributes, + /// as FAT has. + fn has_dos_attributes(dir: &Path) -> bool { + let entry = root_entry(dir); + entry.reopen(None).unwrap().dos_attributes().unwrap().is_some() + } + + /// A cache keeps so many answers at most, and starts over once it is + /// full. + #[test] + fn caches_are_bounded() { + let mut cache = Cache::new(3); + for key in 0..3 { + cache.insert(key, key * 10); + } + assert_eq!( + (0..3).map(|key| cache.get(&key).copied()).collect::>(), + [Some(0), Some(10), Some(20)] + ); + cache.insert(3, 30); + assert_eq!(cache.answers.len(), 1); + assert_eq!((cache.get(&0), cache.get(&3)), (None, Some(&30))); + // A key that is there is kept again without that. + cache.insert(3, 31); + cache.insert(4, 40); + assert_eq!( + (cache.get(&3), cache.get(&4), cache.answers.len()), + (Some(&31), Some(&40), 2) + ); + } + + /// The default features record nothing of what is read here: nothing + /// is opened, nothing is stated and nothing is left out. + #[test] + fn nothing_is_read_unless_asked() { + let (tmp, top, _socket) = tree("optional-default"); + for features in [Features::NONE, Features::DEFAULT, Features::DEFAULT | Features::MTIME] { + for name in NAMES { + let (object, opened, omitted) = read(features, &top, name).unwrap(); + let plain = FileObject::new(object.name().to_owned()); + assert_eq!((object, opened, omitted), (plain, false, 0), "{:?}", name); + } + let mut root = RootObject::default(); + let mut opened = None; + let read = FeatureReader::new(features).read_root(&root_entry(&tmp.0), &mut opened, &mut root); + assert_eq!( + (read.unwrap(), opened.is_some(), root), + (0, false, RootObject::default()) + ); + } + } + + /// Whether a file is read-only follows its mode where its file system + /// has no DOS attributes: it is, if nobody may write it. A symbolic + /// link never is, and `readOnly` is only stated where it is true. + #[test] + fn read_only_follows_the_mode() { + let (tmp, top, _socket) = tree("optional-read-only"); + let dir = &tmp.0; + if has_dos_attributes(dir) { + eprintln!("skipping: the temporary directory has DOS attributes"); + return; + } + let features = Features::DEFAULT | Features::READ_ONLY; + let mut reader = FeatureReader::new(features); + for (mode, read_only) in [ + (0o644, None), + (0o444, Some(true)), + (0o200, None), + (0o020, None), + (0o002, None), + (0o555, Some(true)), + (0o000, Some(true)), + ] { + for name in [c"file", c"dir", c"fifo", c"socket"] { + let path = dir.join(name.to_str().unwrap()); + fs::set_permissions(&path, fs::Permissions::from_mode(mode)).unwrap(); + let entry = Entry::open_at(top.as_fd(), name).unwrap(); + let (object, opened, _) = read_entry(&mut reader, &entry, &top, name).unwrap(); + assert_eq!(object.inode().read_only(), read_only, "{:?} {:o}", name, mode); + // Only the first regular file is opened, to ask its file + // system for DOS attributes. + assert_eq!(opened, name == c"file" && mode == 0o644, "{:?} {:o}", name, mode); + } + } + // Restore what the removal of the tree needs. + fs::set_permissions(dir.join("dir"), fs::Permissions::from_mode(0o755)).unwrap(); + let (link, opened, _) = read(features, &top, c"link").unwrap(); + assert_eq!((link.inode().read_only(), opened), (None, false)); + // The root has no DOS attributes to ask for. + for (mode, read_only) in [(0o555, Some(true)), (0o755, None)] { + fs::set_permissions(dir, fs::Permissions::from_mode(mode)).unwrap(); + let mut root = RootObject::default(); + let mut opened = None; + FeatureReader::new(features) + .read_root(&root_entry(dir), &mut opened, &mut root) + .unwrap(); + assert_eq!( + (root.inode().read_only(), opened.is_some()), + (read_only, false), + "{:o}", + mode + ); + } + } + + /// The read-only attribute of DOS makes a regular file read-only, and + /// only where its mode gives nobody write permission, which the two + /// may not contradict each other in. Without the attribute a regular + /// file is not read-only whatever its mode says, as mount options can + /// take the write permission from every file. + #[test] + fn read_only_of_dos() { + let (_tmp, top, _socket) = tree("optional-dos-read-only"); + let mut reader = FeatureReader::new(Features::READ_ONLY); + let entry = Entry::open_at(top.as_fd(), c"file").unwrap(); + let mut status = *entry.status(); + let cases = [ + (0o444, Some(true), Some(true)), + (0o444, Some(false), None), + (0o644, Some(true), None), + (0o644, Some(false), None), + (0o444, None, Some(true)), + (0o644, None, None), + ]; + for (mode, dos_read_only, read_only) in cases { + status.mode = Mode::from_st_mode(mode); + let entry = Entry::new(Handle::Borrowed(entry.handle()), status, false); + let mut inode = InodeAttributes::default(); + let read = reader.read_inode(&entry, &mut None, dos_read_only, &mut inode); + assert_eq!(read.unwrap(), 0); + assert_eq!(inode.read_only(), read_only, "{:o} {:?}", mode, dos_read_only); + } + } + + /// Only regular files and directories have inode flags. The flags the + /// features record are stated, set or cleared, and no others. A file + /// system without inode flags cannot say that they are cleared. + /// + /// What is stated is held against the flags the file system says the + /// file has. A new file need not be without flags: a directory hands + /// some of its own on to what is made in it, NOATIME and NODUMP among + /// them on ext4 and on XFS. + #[test] + fn inode_flags() { + let (tmp, top, _socket) = tree("optional-inode-flags"); + let dir = &tmp.0; + let all = Features::FLAG_APPEND_ONLY + | Features::FLAG_IMMUTABLE + | Features::FLAG_NO_ATIME + | Features::FLAG_NO_COW + | Features::FLAG_NO_DUMP; + for name in [c"link", c"fifo", c"socket"] { + let (object, opened, _) = read(all, &top, name).unwrap(); + let plain = FileObject::new(object.name().to_owned()); + assert_eq!((object, opened), (plain, false), "{:?}", name); + } + let file = Entry::open_at(top.as_fd(), c"file").unwrap().reopen(None).unwrap(); + if file.inode_flags().unwrap().is_none() { + eprintln!("skipping: the temporary directory has no inode flags"); + assert_eq!( + unavailable(read(all, &top, c"file")), + (Features::FLAG_APPEND_ONLY, Unreadable::NoInodeFlags) + ); + return; + } + // The flags the file system says the file `name` has. + let flags_of = |name: &CStr| { + let entry = Entry::open_at(top.as_fd(), name).unwrap(); + let opened = entry.reopen(Some(Place { dir: top.as_fd(), name })).unwrap(); + rustix::fs::ioctl_getflags(opened.as_fd()).unwrap() + }; + // The owner of a file may set these two, where the file system + // has them. They are added to the flags the file has, as chattr + // adds them. Set in their place, they take the flag of a file with + // extents away on ext4, which sets the two, tries to convert the + // file then and fails where it can't. + let set = |name: &CStr| { + let entry = Entry::open_at(top.as_fd(), name).unwrap(); + let opened = entry.reopen(Some(Place { dir: top.as_fd(), name })).unwrap(); + let flags = flags_of(name) | IFlags::NODUMP | IFlags::NOATIME; + let set = rustix::fs::ioctl_setflags(opened.as_fd(), flags).is_ok(); + if !set { + eprintln!("skipping the flags that are set: the temporary directory does not take them"); + } + set + }; + for (name, set) in [(c"file", set(c"file")), (c"dir", set(c"dir"))] { + let flags = flags_of(name); + let has = |flag: IFlags| Some(flags.contains(flag)); + assert!(!set || flags.contains(IFlags::NODUMP | IFlags::NOATIME), "{:?}", name); + let (object, opened, _) = read(all, &top, name).unwrap(); + assert!(opened); + let inode = object.inode(); + assert_eq!( + (inode.flag_append_only(), inode.flag_immutable(), inode.flag_no_cow()), + (has(IFlags::APPEND), has(IFlags::IMMUTABLE), has(IFlags::NOCOW)), + "{:?}", + name + ); + assert_eq!( + (inode.flag_no_atime(), inode.flag_no_dump()), + (has(IFlags::NOATIME), has(IFlags::NODUMP)), + "{:?}", + name + ); + // Only what the features record is stated. + let (object, _, _) = read(Features::FLAG_NO_DUMP | Features::FLAG_IMMUTABLE, &top, name).unwrap(); + let inode = object.inode(); + assert_eq!( + (inode.flag_no_dump(), inode.flag_immutable()), + (has(IFlags::NODUMP), has(IFlags::IMMUTABLE)) + ); + assert_eq!( + (inode.flag_append_only(), inode.flag_no_atime(), inode.flag_no_cow()), + (None, None, None) + ); + } + // The root has inode flags as well. + let mut root = RootObject { + features: Some(all), + ..RootObject::default() + }; + let mut opened = None; + FeatureReader::new(all) + .read_root(&root_entry(dir), &mut opened, &mut root) + .unwrap(); + assert!(opened.is_some()); + let of_root = rustix::fs::ioctl_getflags(fs::File::open(dir).unwrap()).unwrap(); + assert_eq!(root.inode().flag_no_dump(), Some(of_root.contains(IFlags::NODUMP))); + // A writer takes the objects for a manifest of these features, and + // writes the flags that are set. + let (file, _, _) = read(all, &top, c"file").unwrap(); + let records = written(&root, |writer| writer.file(&file).unwrap()); + let of_file = flags_of(c"file"); + let fields: Vec = [ + (IFlags::APPEND, "flagAppendOnly"), + (IFlags::IMMUTABLE, "flagImmutable"), + (IFlags::NOATIME, "flagNoAtime"), + (IFlags::NOCOW, "flagNoCow"), + (IFlags::NODUMP, "flagNoDump"), + ] + .into_iter() + .filter(|&(flag, _)| of_file.contains(flag)) + .map(|(_, field)| format!(r#""{}":true,"#, field)) + .collect(); + assert_eq!(records[1], format!(r#"{{{}"name":"file"}}"#, fields.concat())); + // procfs has no inode flags. + if rustix::fs::statfs("/proc").is_ok_and(|proc| proc.f_type == rustix::fs::PROC_SUPER_MAGIC) { + let process = open_dir(Path::new("/proc/self")); + for name in [c"task", c"status"] { + let read = read(Features::FLAG_NO_DUMP | Features::FLAG_IMMUTABLE, &process, name); + assert_eq!( + unavailable(read), + (Features::FLAG_IMMUTABLE, Unreadable::NoInodeFlags), + "{:?}", + name + ); + } + } + } + + /// A file system without DOS attributes cannot say that they are + /// cleared, for a regular file or a directory. It is asked once, with + /// its first file, and nothing is opened for it after that. Other files + /// have no DOS attributes anywhere, and the root has none. + #[test] + fn no_dos_attributes() { + let (tmp, top, _socket) = tree("optional-no-dos"); + let dir = &tmp.0; + if has_dos_attributes(dir) { + eprintln!("skipping: the temporary directory has DOS attributes"); + return; + } + let all = Features::FLAG_HIDDEN | Features::FLAG_SYSTEM | Features::FLAG_ARCHIVE; + for (features, first) in [ + (all, Features::FLAG_ARCHIVE), + (Features::FLAG_HIDDEN | Features::FLAG_SYSTEM, Features::FLAG_HIDDEN), + (Features::FLAG_SYSTEM | Features::READ_ONLY, Features::FLAG_SYSTEM), + ] { + let mut reader = FeatureReader::new(features); + for (round, name) in [c"dir", c"file", c"dir", c"file"].into_iter().enumerate() { + let entry = Entry::open_at(top.as_fd(), name).unwrap(); + let mut object = FileObject::new(NameBuf::new(name.to_str().unwrap()).unwrap()); + let mut opened = None; + let read = reader.read(&entry, Some(Place { dir: top.as_fd(), name }), &mut opened, &mut object); + assert_eq!(unavailable(read), (first, Unreadable::NoDosAttributes), "{:?}", name); + assert_eq!(opened.is_some(), round == 0, "{:?} {}", name, round); + } + for name in [c"link", c"fifo", c"socket"] { + let entry = Entry::open_at(top.as_fd(), name).unwrap(); + let (object, opened, _) = read_entry(&mut reader, &entry, &top, name).unwrap(); + assert_eq!(object.flag_hidden(), None, "{:?}", name); + assert!(!opened, "{:?}", name); + } + let mut root = RootObject::default(); + let mut opened = None; + reader.read_root(&root_entry(dir), &mut opened, &mut root).unwrap(); + assert!(opened.is_none()); + } + // Whether a file is read-only only asks with a regular file. + let mut reader = FeatureReader::new(Features::READ_ONLY); + for (name, opens) in [(c"dir", false), (c"file", true), (c"file", false), (c"dir", false)] { + let entry = Entry::open_at(top.as_fd(), name).unwrap(); + let (_, opened, _) = read_entry(&mut reader, &entry, &top, name).unwrap(); + assert_eq!(opened, opens, "{:?}", name); + } + // A file that cannot be opened is read-only by its mode, and the + // next file asks. The attributes hidden, system and archive of such + // a file cannot be read. That takes a process that the permissions + // of a file hold for. + fs::set_permissions(dir.join("file"), fs::Permissions::from_mode(0o000)).unwrap(); + if fs::File::open(dir.join("file")).is_ok() { + return; + } + fs::write(dir.join("other"), b"").unwrap(); + let mut reader = FeatureReader::new(Features::READ_ONLY); + for (name, opens, read_only) in [(c"file", false, Some(true)), (c"other", true, None)] { + let entry = Entry::open_at(top.as_fd(), name).unwrap(); + let (object, opened, _) = read_entry(&mut reader, &entry, &top, name).unwrap(); + assert_eq!((opened, object.inode().read_only()), (opens, read_only), "{:?}", name); + } + let read = read(Features::FLAG_HIDDEN | Features::READ_ONLY, &top, c"file"); + assert!( + matches!(&read, Err(Failure::Io(e)) if e.raw_os_error() == Some(libc::EACCES)), + "{:?}", + read + ); + } + + /// Sets the extended attribute `name` of `path` itself to `value`. + fn set_xattr(path: &Path, name: &[u8], value: &[u8]) -> rustix::io::Result<()> { + rustix::fs::lsetxattr(path, name, value, XattrFlags::empty()) + } + + /// The extended attributes of the user namespace of a file are read, + /// all of them, by their names without the namespace, and none of + /// another namespace. Nothing is opened for them: they are read through + /// the handle of the file, and through the file itself where it is open + /// for reading anyway, for its inode flags or by the caller. A file + /// without any has none, which is not the same as saying nothing, also + /// where it may not be opened, and a symbolic link says nothing. A file + /// that lost its name keeps its attributes. + #[test] + fn extended_attributes() { + let (tmp, top, _socket) = tree("optional-xattrs"); + let dir = &tmp.0; + let features = Features::DEFAULT | Features::USER_XATTR; + if let Err(e) = set_xattr(&dir.join("file"), b"user.first", b"1") { + assert!(matches!(e, Errno::OPNOTSUPP | Errno::NOSYS), "{}", e); + eprintln!("skipping: the temporary directory has no extended attributes"); + return; + } + let binary: Vec = (0..=u8::MAX).collect(); + set_xattr(&dir.join("file"), b"user.empty", b"").unwrap(); + set_xattr(&dir.join("file"), b"user.binary", &binary).unwrap(); + set_xattr( + &dir.join("file"), + "user.\u{fc}ml\u{e4}ut.dotted name".as_bytes(), + b"text", + ) + .unwrap(); + set_xattr(&dir.join("dir"), b"user.of the directory", b"2").unwrap(); + // Linux 7.1 and later take one on a socket, never on a FIFO. + let on_socket = set_xattr(&dir.join("socket"), b"user.of the socket", b"3").is_ok(); + assert_eq!(set_xattr(&dir.join("fifo"), b"user.no", b"4"), Err(Errno::PERM)); + let attributes = |pairs: &[(&str, &[u8])]| { + let pairs = pairs.iter().map(|(name, value)| (name.to_string(), value.to_vec())); + Some(pairs.collect::>()) + }; + let found = |object: &FileObject| { + object.inode().user_xattrs().map(|xattrs| { + xattrs + .map(|(name, value)| (name.to_owned(), value.to_vec())) + .collect::>() + }) + }; + let read_attributes = |name: &CStr| { + let (object, opened, omitted) = read(features, &top, name).unwrap(); + assert_eq!((opened, omitted), (false, 0), "{:?}", name); + found(&object) + }; + let of_file = attributes(&[ + ("binary", &binary[..]), + ("empty", &b""[..]), + ("first", &b"1"[..]), + ("\u{fc}ml\u{e4}ut.dotted name", &b"text"[..]), + ]); + let of_dir = attributes(&[("of the directory", &b"2"[..])]); + assert_eq!(read_attributes(c"file"), of_file); + assert_eq!(read_attributes(c"dir"), of_dir); + // A file that is open for reading is read through that. + assert_eq!(found(&read_open(features, &top, c"file").unwrap()), of_file); + assert_eq!(found(&read_open(features, &top, c"dir").unwrap()), of_dir); + // So is one that is opened for its inode flags. + match read(features | Features::FLAG_NO_DUMP, &top, c"file") { + Ok((object, opened, _)) => assert_eq!((found(&object), opened), (of_file.clone(), true)), + Err(Failure::Unavailable(Features::FLAG_NO_DUMP, Unreadable::NoInodeFlags)) => { + eprintln!("skipping the inode flags: the temporary directory has none"); + } + Err(e) => panic!("{:?}", e), + } + // A file that may not be opened is asked as well, and has none. + // Nobody but root reads the value of one it has. + fs::write(dir.join("closed"), b"").unwrap(); + fs::set_permissions(dir.join("closed"), fs::Permissions::from_mode(0o000)).unwrap(); + assert_eq!(read_attributes(c"closed"), attributes(&[])); + let of_socket: &[(&str, &[u8])] = if on_socket { + &[("of the socket", &b"3"[..])] + } else { + &[] + }; + assert_eq!(read_attributes(c"socket"), attributes(of_socket)); + assert_eq!(read_attributes(c"fifo"), attributes(&[])); + assert_eq!(read_attributes(c"link"), None); + // A regular file that lost its name keeps its attributes, and + // another file of its name has its own. + fs::write(dir.join("named"), b"").unwrap(); + set_xattr(&dir.join("named"), b"user.of the named file", b"5").unwrap(); + let entry = Entry::open_at(top.as_fd(), c"named").unwrap(); + fs::rename(dir.join("named"), dir.join("renamed")).unwrap(); + fs::write(dir.join("named"), b"").unwrap(); + let (object, _, _) = read_entry(&mut FeatureReader::new(features), &entry, &top, c"named").unwrap(); + assert_eq!(object.inode().user_xattr("of the named file"), Some(&b"5"[..])); + assert_eq!(read_attributes(c"named"), attributes(&[])); + // A writer takes the object, and writes its attributes. + let root = RootObject { + features: Some(features), + ..RootObject::default() + }; + let (file, _, _) = read(features, &top, c"file").unwrap(); + let records = written(&root, |writer| writer.file(&file).unwrap()); + assert!(records[1].contains(r#""first":{"text":"1"}"#), "{}", records[1]); + // A manifest lists all attributes of a file or none, so a name it + // cannot hold fails: one that is not UTF-8, and one with a control + // character. + for name in [&b"user.\xff"[..], b"user.a\nb", b"user.\x7f"] { + fs::write(dir.join("unwritable"), b"").unwrap(); + if set_xattr(&dir.join("unwritable"), name, b"").is_err() { + eprintln!( + "skipping the name {:?}, which the temporary directory does not take", + name + ); + continue; + } + let read = read(features, &top, c"unwritable"); + assert_eq!( + unavailable(read), + (Features::USER_XATTR, Unreadable::XattrName), + "{:?}", + name + ); + fs::remove_file(dir.join("unwritable")).unwrap(); + } + } + + /// The attributes of a file that take more than a record of a manifest + /// has room for fail, before they are all read. + #[test] + fn too_many_extended_attributes() { + let tmp = TempDir::new("optional-xattr-size"); + let dir = &tmp.0; + fs::write(dir.join("file"), b"").unwrap(); + let value = vec![0x5a; 60 * 1024]; + let count = crate::MAX_RECORD_SIZE / value.len() + 2; + for i in 0..count { + let name = format!("user.{:04}", i); + if let Err(e) = set_xattr(&dir.join("file"), name.as_bytes(), &value) { + eprintln!( + "skipping: the temporary directory takes no more than {} large attributes ({})", + i, e + ); + return; + } + } + let top = open_dir(dir); + let read = read(Features::USER_XATTR, &top, c"file"); + assert!(matches!(read, Err(Failure::TooLarge)), "{:?}", read); + } + + /// The variable that tells the test binary, run again by + /// [`extended_attributes_without_procfs`] with nothing in /proc, where + /// the tree is. + const NO_PROCFS_DIR: &str = "UAPI16_TEST_NO_PROCFS_DIR"; + + /// The variable that tells the test binary, run again by + /// [`extended_attributes_without_procfs`], that the kernel reopens a + /// regular file without a procfs, with O_EMPTYPATH. + const NO_PROCFS_REOPENS: &str = "UAPI16_TEST_NO_PROCFS_REOPENS"; + + /// The extended attributes of a file that is open for reading are read + /// through that descriptor, which takes no procfs. Those of a file that + /// is not open are read through the link procfs has for its handle, and + /// can't be read without it. The test binary runs this test again with + /// an empty tmpfs over /proc, in a user and a mount namespace from + /// unshare(1), and it is skipped where unshare can't make them. + /// + /// A directory is opened by its name. A regular file is opened through + /// its handle, with O_EMPTYPATH where the kernel has it and through + /// procfs where it does not, by pathrs, which panics where there is + /// none. So the regular file is left out there. + #[test] + fn extended_attributes_without_procfs() { + if let Some(dir) = std::env::var_os(NO_PROCFS_DIR) { + return check_without_procfs(Path::new(&dir)); + } + let (tmp, _, _socket) = tree("optional-no-procfs"); + let dir = &tmp.0; + if let Err(e) = set_xattr(&dir.join("file"), b"user.of the file", b"1") { + assert!(matches!(e, Errno::OPNOTSUPP | Errno::NOSYS), "{}", e); + eprintln!("skipping: the temporary directory has no extended attributes"); + return; + } + set_xattr(&dir.join("dir"), b"user.of the directory", b"2").unwrap(); + let works = Command::new("unshare").args(["-Urm", "true"]).output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urm does not work here"); + return; + } + let reopens = testing::has_empty_path(); + if !reopens { + eprintln!("skipping the regular file: the kernel has no O_EMPTYPATH"); + } + let script = concat!( + r#"mount -t tmpfs tmpfs /proc && "#, + r#"exec "$1" --exact optional::tests::extended_attributes_without_procfs --nocapture"# + ); + let mut command = Command::new("unshare"); + command + .args(["-Urm", "sh", "-c", script, "sh"]) + .arg(std::env::current_exe().unwrap()) + .env(NO_PROCFS_DIR, dir); + if reopens { + command.env(NO_PROCFS_REOPENS, "1"); + } + let output = command.output().unwrap(); + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } + + /// The checks of [`extended_attributes_without_procfs`] in `dir`, with + /// nothing in /proc. + fn check_without_procfs(dir: &Path) { + assert!(fs::read_dir("/proc").unwrap().next().is_none()); + let top = open_dir(dir); + let features = Features::USER_XATTR; + let object = read_open(features, &top, c"dir").unwrap(); + assert_eq!(object.inode().user_xattr("of the directory"), Some(&b"2"[..])); + if std::env::var_os(NO_PROCFS_REOPENS).is_some() { + let object = read_open(features, &top, c"file").unwrap(); + assert_eq!(object.inode().user_xattr("of the file"), Some(&b"1"[..])); + } + // Nothing is opened for its attributes. + for name in [c"dir", c"file", c"fifo"] { + let read = read(features, &top, name); + assert_eq!( + unavailable(read), + (Features::USER_XATTR, Unreadable::NoProcfs), + "{:?}", + name + ); + } + } + + /// The variable that names the merged directory of fuse-overlayfs in + /// which the test binary runs + /// [`extended_attributes_of_a_file_that_is_gone`] again. + const GONE_DIR: &str = "UAPI16_TEST_GONE_DIR"; + + /// The variable that names the directory of the layer the files of + /// that test are in. + const GONE_LAYER: &str = "UAPI16_TEST_GONE_LAYER"; + + /// A file that is removed behind its file system after its handle was + /// taken changed: the link procfs has for the handle leads nowhere + /// then, as it does where there is no procfs, and the handle tells the + /// two apart. fuse-overlayfs finds its files by their names, so it + /// says ENOENT of a file that was removed in its layer, and with + /// timeout=0 the kernel asks it every time. The test binary runs this + /// test again in a user and mount namespace from unshare(1), on such a + /// mount. It is skipped where there is no fuse-overlayfs, and where the + /// handle of a file that is gone still has a status. + #[test] + fn extended_attributes_of_a_file_that_is_gone() { + if let (Some(dir), Some(layer)) = (std::env::var_os(GONE_DIR), std::env::var_os(GONE_LAYER)) { + return check_gone(Path::new(&dir), Path::new(&layer)); + } + let tmp = TempDir::new("optional-gone"); + let dir = &tmp.0; + for part in ["lower", "upper", "work", "merged"] { + fs::create_dir(dir.join(part)).unwrap(); + } + for name in GONE { + fs::write(dir.join("lower").join(name.to_str().unwrap()), b"hello").unwrap(); + } + let works = Command::new("unshare").args(["-Urm", "true"]).output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urm does not work here"); + return; + } + // The script exits with 77 where it can't mount the file system, + // and unmounts it once the test is done, which ends fuse-overlayfs. + let script = concat!( + r#"d=$1; "#, + r#"fuse-overlayfs -o "lowerdir=$d/lower,upperdir=$d/upper,workdir=$d/work,timeout=0" "$d/merged" "#, + r#"|| exit 77; "#, + r#""$2" --exact optional::tests::extended_attributes_of_a_file_that_is_gone --nocapture; status=$?; "#, + r#"umount "$d/merged"; exit $status"# + ); + let output = Command::new("unshare") + .args(["-Urm", "sh", "-c", script, "sh"]) + .arg(dir) + .arg(std::env::current_exe().unwrap()) + .env(GONE_DIR, dir.join("merged")) + .env(GONE_LAYER, dir.join("lower")) + .output() + .unwrap(); + if output.status.code() == Some(77) { + eprintln!("skipping: fuse-overlayfs can't mount a file system here"); + return; + } + // What the test said where it ran again, such as that it skipped. + let said = String::from_utf8_lossy(&output.stderr); + if let Some(skipped) = said.lines().find(|line| line.starts_with("skipping")) { + eprintln!("{}", skipped); + } + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } + + /// The files of [`extended_attributes_of_a_file_that_is_gone`]. + const GONE: [&CStr; 2] = [c"one", c"other"]; + + /// The checks of [`extended_attributes_of_a_file_that_is_gone`] in + /// `dir`, whose files are in the directory `layer` behind it. + fn check_gone(dir: &Path, layer: &Path) { + let top = open_dir(dir); + for name in GONE { + let entry = Entry::open_at(top.as_fd(), name).unwrap(); + fs::remove_file(layer.join(name.to_str().unwrap())).unwrap(); + if let Ok(status) = Status::of(entry.handle()) { + eprintln!( + "skipping: a file that is gone still has a status here: {:?}", + status.file_type + ); + return; + } + // Its extended attributes are read through its handle, which + // is not open for reading. + let mut reader = FeatureReader::new(Features::USER_XATTR); + let read = read_entry(&mut reader, &entry, &top, name); + assert!( + matches!(read, Err(Failure::Changed)), + "{:?}: {:?}", + name, + read.map(|read| read.2) + ); + } + } + + /// The variable that names the merged directory of fuse-overlayfs in + /// which the test binary runs [`extended_attributes_behind_a_dead_server`] + /// again. + const DEAD_DIR: &str = "UAPI16_TEST_DEAD_DIR"; + + /// The variable that names the process of that fuse-overlayfs. + const DEAD_SERVER: &str = "UAPI16_TEST_DEAD_SERVER"; + + /// How often the test asks for the status of a file whose server it + /// killed until that fails, and how long it waits in between. + const DEAD_TRIES: u32 = 500; + const DEAD_WAIT: Duration = Duration::from_millis(10); + + /// Only a file that is gone is a change. A handle that can't be asked + /// for another reason says nothing of its file, and a link that procfs + /// does not have is a missing procfs then, as it is where the handle + /// can be asked. Here the handle is of a file on fuse-overlayfs whose + /// server the test kills, so that its status fails with ECONNABORTED + /// or ENOTCONN, and /proc is an empty tmpfs. The test binary runs this + /// test again in a user and mount namespace from unshare(1), where the + /// shell that starts it has the server in its background. It is + /// skipped where there is no fuse-overlayfs, and where the handle still + /// has a status after its server is gone. + #[test] + fn extended_attributes_behind_a_dead_server() { + if let (Some(dir), Ok(server)) = (std::env::var_os(DEAD_DIR), std::env::var(DEAD_SERVER)) { + return check_dead_server(Path::new(&dir), &server); + } + let tmp = TempDir::new("optional-dead-server"); + let dir = &tmp.0; + for part in ["lower", "upper", "work", "merged"] { + fs::create_dir(dir.join(part)).unwrap(); + } + fs::write(dir.join("lower/file"), b"hello").unwrap(); + let works = Command::new("unshare").args(["-Urm", "true"]).output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urm does not work here"); + return; + } + // The script exits with 77 where the file system does not get + // mounted, and ends the server first. The server stays in the + // foreground, so that the shell knows its process, and writes to + // nothing, so that this test waits for the script alone. What is + // left of the mount goes with the namespace. + let script = format!( + concat!( + r#"d=$1; "#, + r#"fuse-overlayfs -f -o "lowerdir=$d/lower,upperdir=$d/upper,workdir=$d/work,timeout=0" "$d/merged" "#, + r#"> /dev/null 2>&1 & "#, + r#"server=$!; tries=0; "#, + r#"until mountpoint -q "$d/merged"; do "#, + r#"tries=$((tries + 1)); "#, + r#"if [ "$tries" -gt 100 ] || ! kill -0 "$server" 2> /dev/null; then "#, + r#"kill "$server" 2> /dev/null; exit 77; fi; "#, + r#"sleep 0.05; done; "#, + r#"{}=$server "$2" --exact optional::tests::extended_attributes_behind_a_dead_server --nocapture; "#, + r#"status=$?; kill "$server" 2> /dev/null; exit $status"# + ), + DEAD_SERVER + ); + let output = Command::new("unshare") + .args(["-Urm", "sh", "-c", &script, "sh"]) + .arg(dir) + .arg(std::env::current_exe().unwrap()) + .env(DEAD_DIR, dir.join("merged")) + .output() + .unwrap(); + if output.status.code() == Some(77) { + eprintln!("skipping: fuse-overlayfs can't mount a file system here"); + return; + } + // What the test said where it ran again, such as that it skipped. + let said = String::from_utf8_lossy(&output.stderr); + if let Some(skipped) = said.lines().find(|line| line.starts_with("skipping")) { + eprintln!("{}", skipped); + } + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } + + /// The checks of [`extended_attributes_behind_a_dead_server`] in `dir`, + /// which the process `server` serves. + fn check_dead_server(dir: &Path, server: &str) { + let top = open_dir(dir); + let entry = Entry::open_at(top.as_fd(), c"file").unwrap(); + // The shell has a kill of its own, and kill(1) need not be there. + let killed = Command::new("sh") + .args(["-c", r#"kill -KILL "$1""#, "sh", server]) + .status() + .unwrap(); + assert!(killed.success()); + // The kernel answers for the server once its descriptor is closed. + let mut tries = 0; + let failed = loop { + match Status::of(entry.handle()) { + Err(failed) => break failed, + Ok(_) if tries == DEAD_TRIES => { + eprintln!("skipping: a file whose server is gone still has a status here"); + return; + } + Ok(_) => { + tries += 1; + std::thread::sleep(DEAD_WAIT); + } + } + }; + // The kernel says that the connection was aborted, or that there + // is none. + assert!( + matches!(&failed, Failure::Io(e) if matches!(e.raw_os_error(), Some(libc::ECONNABORTED | libc::ENOTCONN))), + "{:?}", + failed + ); + // Nothing is in /proc from here on. + let mounted = Command::new("mount") + .args(["-t", "tmpfs", "tmpfs", "/proc"]) + .status() + .unwrap(); + assert!(mounted.success()); + assert!(fs::read_dir("/proc").unwrap().next().is_none()); + let mut reader = FeatureReader::new(Features::USER_XATTR); + let read = read_entry(&mut reader, &entry, &top, c"file"); + assert_eq!(unavailable(read), (Features::USER_XATTR, Unreadable::NoProcfs)); + } + + /// A file system is asked for its DOS attributes once, through the + /// directory a walk starts at, and one without them fails where one of + /// hidden, system and archive is recorded. Where none of them is + /// recorded, it is not asked. + #[test] + fn checks_dos_attributes_once() { + let tmp = TempDir::new("optional-dos-check"); + let dir = &tmp.0; + if has_dos_attributes(dir) { + eprintln!("skipping: the temporary directory has DOS attributes"); + return; + } + let entry = root_entry(dir); + let mut reader = FeatureReader::new(Features::FLAG_HIDDEN | Features::READ_ONLY); + let no_attributes = (Features::FLAG_HIDDEN, Unreadable::NoDosAttributes); + // The first time asks, through the directory opened for that. Then + // the answer is known, and nothing is opened for it any more. + for asks in [true, false] { + let mut opened = None; + let check = reader.check_dos_attributes(&entry, &mut opened); + assert_eq!((unavailable(check), opened.is_some()), (no_attributes, asks)); + } + let mut opened = None; + FeatureReader::new(Features::READ_ONLY) + .check_dos_attributes(&entry, &mut opened) + .unwrap(); + assert!(opened.is_none()); + } + + /// The names of the owners of a file are those the user database has + /// for its user and its group. A name it does not have is left out and + /// counted, and found again in what was kept. + #[test] + fn owner_names() { + let (_tmp, top, _socket) = tree("optional-owners"); + let both = Features::USER_NAME | Features::GROUP_NAME; + let entry = Entry::open_at(top.as_fd(), c"file").unwrap(); + let (uid, gid) = (entry.status().uid, entry.status().gid); + let mut database = UserDatabase::new(); + let (user, group) = (database.user_name(uid), database.group_name(gid)); + let missing = u64::from(user.is_none()) + u64::from(group.is_none()); + let mut reader = FeatureReader::new(both); + for name in NAMES { + let entry = Entry::open_at(top.as_fd(), name).unwrap(); + let (object, opened, omitted) = read_entry(&mut reader, &entry, &top, name).unwrap(); + let inode = object.inode(); + assert_eq!( + (inode.user_name(), inode.group_name()), + (user.as_deref(), group.as_deref()) + ); + assert_eq!((opened, omitted), (false, missing), "{:?}", name); + } + assert_eq!(reader.names.users.get(&uid).map(Option::is_some), Some(user.is_some())); + // Only the names the features record. + let (object, _, omitted) = read(Features::GROUP_NAME, &top, c"file").unwrap(); + assert_eq!( + (object.inode().user_name(), object.inode().group_name()), + (None, group.as_deref()) + ); + assert_eq!(omitted, u64::from(group.is_none())); + // An owner nobody knows, and the two IDs that stand for none. + let unknown = (4_000_000_000..4_000_000_100) + .find(|&id| database.user_name(id).is_none() && database.group_name(id).is_none()) + .expect("an ID without a user and a group"); + for id in [unknown, u32::MAX, u32::from(u16::MAX)] { + let mut status = *entry.status(); + (status.uid, status.gid) = (id, id); + let entry = Entry::new(Handle::Borrowed(entry.handle()), status, false); + for _ in 0..2 { + let (object, _, omitted) = read_entry(&mut reader, &entry, &top, c"file").unwrap(); + assert_eq!( + (object.inode().user_name(), object.inode().group_name(), omitted), + (None, None, 2) + ); + } + assert_eq!(reader.names.users.get(&id), Some(&None)); + assert_eq!(reader.names.groups.get(&id), Some(&None)); + } + let (object, _, _) = read(both, &top, c"file").unwrap(); + let root = RootObject { + features: Some(both), + ..RootObject::default() + }; + written(&root, |writer| writer.file(&object).unwrap()); + } + + /// What a file system says of its label and of what it identifies + /// itself with, as a manifest records it: an empty label is no label, + /// and a label a manifest cannot hold cannot be recorded, and neither + /// can one the file system cannot say. An identifier that is not a UUID + /// is none, and so is one the file system cannot say. + #[test] + fn labels_and_uuids() { + assert_eq!( + FeatureReader::label(Some(FsLabel::Label("ESP".into()))).unwrap(), + Some("ESP".into()) + ); + assert_eq!(FeatureReader::label(Some(FsLabel::Empty)).unwrap(), None); + assert_eq!( + unavailable(FeatureReader::label(Some(FsLabel::Unwritable))), + (Features::FS_LABEL, Unreadable::LabelUnwritable) + ); + assert_eq!( + unavailable(FeatureReader::label(None)), + (Features::FS_LABEL, Unreadable::NoLabel) + ); + let uuid = Uuid::new([7; Uuid::SIZE]); + assert_eq!(FeatureReader::uuid(Some(FsUuid::Uuid(uuid))), Some(uuid)); + for identifier in [ + Some(FsUuid::Null), + Some(FsUuid::NotUuid(4)), + Some(FsUuid::NotUuid(8)), + None, + ] { + assert_eq!(FeatureReader::uuid(identifier), None, "{:?}", identifier); + } + } + + /// The root of a tree has the identity of its file system, as far as + /// the features record it and as the file system gives it. A label it + /// cannot give fails. A UUID or a volume serial number it does not have + /// is left out and counted, and fails nothing. + #[test] + fn identity_of_the_file_system() { + let tmp = TempDir::new("optional-identity"); + let dir = &tmp.0; + let entry = root_entry(dir); + let asked = entry.reopen(None).unwrap(); + let identity = |features| { + let mut root = RootObject::default(); + let mut opened = None; + let read = FeatureReader::new(features).read_root(&entry, &mut opened, &mut root); + read.map(|omitted| { + assert!(opened.is_some()); + (root.file_system().clone(), omitted) + }) + }; + match FeatureReader::label(asked.fs_label().unwrap()) { + // The label is never left out: a file system that has none + // says so with an empty one. + Ok(label) => { + let (labelled, omitted) = identity(Features::FS_LABEL).unwrap(); + assert_eq!((labelled.label(), omitted), (label.as_deref(), 0)); + } + Err(failure) => assert_eq!( + unavailable(identity(Features::FS_LABEL)), + unavailable::<()>(Err(failure)) + ), + } + let uuid = FeatureReader::uuid(asked.fs_uuid().unwrap()); + let serial = asked.fat_serial().unwrap(); + let (no_uuid, no_serial) = (u64::from(uuid.is_none()), u64::from(serial.is_none())); + let (with_uuid, omitted) = identity(Features::FS_UUID).unwrap(); + assert_eq!((with_uuid.uuid(), omitted), (uuid, no_uuid)); + let (with_serial, omitted) = identity(Features::FAT_SERIAL).unwrap(); + assert_eq!((with_serial.fat_serial(), omitted), (serial, no_serial)); + // Asked for both, it gives the one it has: the other one is left + // out, and counted. + let (both, omitted) = identity(Features::FS_UUID | Features::FAT_SERIAL).unwrap(); + assert_eq!( + (both.uuid(), both.fat_serial(), omitted), + (uuid, serial, no_uuid + no_serial) + ); + // Only the root has it: nothing of it is read for another file. + let top = open_dir(dir); + fs::create_dir(dir.join("dir")).unwrap(); + let (object, opened, _) = read(FeatureReader::IDENTITY, &top, c"dir").unwrap(); + assert_eq!((object, opened), (FileObject::new(NameBuf::new("dir").unwrap()), false)); + // procfs has no label, no UUID and no volume serial number: the + // label fails, and the other two are left out, and each of them is + // counted. + if rustix::fs::statfs("/proc").is_ok_and(|proc| proc.f_type == rustix::fs::PROC_SUPER_MAGIC) { + let process = root_entry(Path::new("/proc/self")); + let read = |features| { + let mut root = RootObject::default(); + let read = FeatureReader::new(features).read_root(&process, &mut None, &mut root); + read.map(|omitted| (root, omitted)) + }; + assert_eq!( + unavailable(read(Features::FS_LABEL)), + (Features::FS_LABEL, Unreadable::NoLabel) + ); + assert_eq!(unavailable(read(FeatureReader::IDENTITY)).0, Features::FS_LABEL); + for (features, left_out) in [ + (Features::FS_UUID, 1), + (Features::FAT_SERIAL, 1), + (Features::FS_UUID | Features::FAT_SERIAL, 2), + ] { + let (root, omitted) = read(features).unwrap(); + assert_eq!( + (root.file_system(), omitted), + (&FileSystemIdentity::default(), left_out), + "{:?}", + features + ); + } + } + } + + /// The variable that names a directory of a mounted FAT file system + /// for [`fat`], one with a regular file and a directory in it. Mounting + /// one takes privileges, so the test is skipped without it. + const FAT_DIR: &str = "UAPI16_TEST_FAT_DIR"; + + /// On a FAT file system a regular file and a directory have their DOS + /// attributes, a regular file is read-only if it has that attribute, + /// the root has no DOS attributes, and the file system has a volume + /// serial number, no UUID, which is left out and counted, and no label + /// that can be read. Its root directory says that it has DOS attributes + /// where a walk asks it. + #[test] + fn fat() { + let Some(dir) = std::env::var_os(FAT_DIR) else { + eprintln!("skipping: {} names no directory of a FAT file system", FAT_DIR); + return; + }; + let dir = Path::new(&dir); + let top = open_dir(dir); + let features = Features::FLAG_HIDDEN | Features::FLAG_SYSTEM | Features::FLAG_ARCHIVE | Features::READ_ONLY; + let mut reader = FeatureReader::new(features); + let (mut files, mut directories) = (0, 0); + for listed in fs::read_dir(dir).unwrap() { + let listed = listed.unwrap(); + let name = std::ffi::CString::new(listed.file_name().as_bytes()).unwrap(); + let entry = Entry::open_at(top.as_fd(), &name).unwrap(); + let mut object = FileObject::new(Name::ROOT.join_os(&listed.file_name()).unwrap()); + let mut opened = None; + let place = Place { + dir: top.as_fd(), + name: &name, + }; + reader.read(&entry, Some(place), &mut opened, &mut object).unwrap(); + let attributes = opened.unwrap().dos_attributes().unwrap().unwrap(); + let flags = attributes.flags(); + assert_eq!(object.flag_hidden(), Some(flags.contains(DosFlags::HIDDEN))); + assert_eq!(object.flag_system(), Some(flags.contains(DosFlags::SYSTEM))); + assert_eq!(object.flag_archive(), Some(flags.contains(DosFlags::ARCHIVE))); + let writable = entry.status().mode.is_writable(); + if entry.status().file_type == FileType::RegularFile { + files += 1; + let read_only = (attributes.is_read_only() && !writable).then_some(true); + assert_eq!(object.inode().read_only(), read_only); + } else { + directories += 1; + assert_eq!(object.inode().read_only(), (!writable).then_some(true)); + } + } + assert!( + files > 0 && directories > 0, + "{:?} needs a regular file and a directory", + dir + ); + let identity = |features| { + let mut root = RootObject::default(); + let read = FeatureReader::new(features).read_root(&root_entry(dir), &mut None, &mut root); + read.map(|omitted| (root, omitted)) + }; + let (root, omitted) = identity(features | Features::FAT_SERIAL).unwrap(); + assert!(root.file_system().fat_serial().is_some()); + assert_eq!(omitted, 0); + assert_eq!( + unavailable(identity(Features::FS_LABEL)), + (Features::FS_LABEL, Unreadable::NoLabel) + ); + // What FAT identifies itself with is its volume serial number, + // which is no UUID: the UUID is left out, and counted. + let (root, omitted) = identity(Features::FS_UUID).unwrap(); + assert_eq!((root.file_system().uuid(), omitted), (None, 1)); + let (root, omitted) = identity(Features::FS_UUID | Features::FAT_SERIAL).unwrap(); + assert!(root.file_system().fat_serial().is_some()); + assert_eq!((root.file_system().uuid(), omitted), (None, 1)); + // A walk asks the directory it starts at whether its file system + // has DOS attributes. The root directory of the file system has an + // answer as well, though none is recorded of the root of a tree. + let mut opened = None; + FeatureReader::new(features) + .check_dos_attributes(&root_entry(dir), &mut opened) + .unwrap(); + assert!(opened.is_some()); + } +} diff --git a/src/uapi16/reader.rs b/src/uapi16/reader.rs index 883d027..f59a697 100644 --- a/src/uapi16/reader.rs +++ b/src/uapi16/reader.rs @@ -4,7 +4,7 @@ use std::fmt; use std::io::{self, BufRead}; -use crate::decode::{DecodedObject, RecordDecoder, ROOT_RECORD}; +use crate::decode::{DecodedObject, RecordDecoder, Subject, ROOT_RECORD}; use crate::error::{Error, Problem}; use crate::object::{FileObject, RootObject, SignatureObject}; use crate::sequence::SequenceCheck; @@ -223,7 +223,7 @@ impl fmt::Debug for RecordSplitter { } /// An object of a manifest after its root file object, as a [`Reader`] -/// and a [`Decoder`] hand it out. +/// hands it out. /// /// [`Reader`]: crate::Reader #[derive(Clone, Debug, PartialEq, Eq)] @@ -251,13 +251,9 @@ 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::process`], so the caller can pass over it. Steps that come in -/// later releases only hand something out. +/// there is nothing more, and the other steps hand something out. #[derive(Clone, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub enum Step { +pub(crate) enum Step { /// More of the manifest: [`Decoder::feed`] takes it, and /// [`Decoder::end_feed`] says that the input ended. Input, @@ -292,39 +288,10 @@ pub enum Step { /// [`MAX_RECORD_SIZE`] and at most [`Name::MAX_LEN`](crate::Name::MAX_LEN) /// bytes, in whatever pieces the manifest comes. /// -/// ``` -/// use uapi16::{Decoder, Object, Step}; -/// -/// let manifest = concat!( -/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n", -/// "\x1e{\"name\":\"a\",\"size\":3}\n", -/// "\x1e{\"name\":\"b\",\"type\":\"dir\"}\n", -/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", -/// ); -/// let mut input = manifest.as_bytes(); -/// let mut decoder = Decoder::new(); -/// let mut names = Vec::new(); -/// loop { -/// match decoder.process()? { -/// Step::Input if input.is_empty() => decoder.end_feed(), -/// // The manifest comes in pieces of at most five bytes. -/// Step::Input => { -/// let taken = decoder.feed(&input[..input.len().min(5)]); -/// input = &input[taken..]; -/// } -/// Step::Object(Object::File(object)) => names.push(object.into_name()), -/// Step::End => break, -/// _ => {} -/// } -/// } -/// assert_eq!(names, ["a", "b"]); -/// # Ok::<(), uapi16::Error>(()) -/// ``` -/// /// [`Read`]: std::io::Read /// [`Reader`]: crate::Reader #[derive(Debug)] -pub struct Decoder { +pub(crate) struct Decoder { splitter: RecordSplitter, /// The number of the record that is read next. next_record: u64, @@ -335,15 +302,9 @@ pub struct Decoder { signed: Option, } -impl Default for Decoder { - fn default() -> Decoder { - Decoder::new() - } -} - impl Decoder { /// A decoder at the start of a manifest. - pub fn new() -> Decoder { + pub(crate) fn new() -> Decoder { Decoder { splitter: RecordSplitter::default(), next_record: ROOT_RECORD, @@ -359,20 +320,20 @@ impl Decoder { /// call, after the next step. #[inline] #[must_use] - pub fn feed(&mut self, input: &[u8]) -> usize { + pub(crate) fn feed(&mut self, input: &[u8]) -> usize { self.splitter.feed(input) } /// Says that the input ended, after [`Step::Input`]. #[inline] - pub fn end_feed(&mut self) { + pub(crate) fn end_feed(&mut self) { self.splitter.end_input(); } /// What comes next. Once it returned an error, it returns /// [`Step::End`]. #[inline] - pub fn process(&mut self) -> Result { + pub(crate) fn process(&mut self) -> Result { if !matches!(self.stage, Stage::Done) { // The next record goes on in input that was not fed yet, as it // does right after every object that was handed out. @@ -395,7 +356,7 @@ impl Decoder { /// The number of the record the object handed out last came from. The /// record of the root file object is number 0. Records that are empty /// do not count. - pub fn record_number(&self) -> u64 { + pub(crate) fn record_number(&self) -> u64 { self.last_record } @@ -403,13 +364,13 @@ impl Decoder { /// sign, see [`Reader::signed_len`]. /// /// [`Reader::signed_len`]: crate::Reader::signed_len - pub fn signed_len(&self) -> Option { + pub(crate) fn signed_len(&self) -> Option { self.signed } /// An error `e` of the input the manifest is read from, as an error /// about the record the decoder reads. - pub fn input_error(&self, e: io::Error) -> Error { + pub(crate) fn input_error(&self, e: io::Error) -> Error { Error::from(e).in_record(self.next_record) } @@ -473,9 +434,9 @@ impl Decoder { }; let mut object = object?; let checked = sequence_check - .check_fields(&object, number) + .check_fields(&object, Subject::new(&object, number)) .and_then(|()| sequence_check.admit(&object, number)); - checked.map_err(|e| e.in_record(number).named(object.name.as_str()))?; + checked.map_err(|e| e.in_record(number).named(object.name().as_str()))?; object.fill_in(sequence_check.features()); self.last_record = number; return Ok(Step::Object(Object::File(object))); @@ -503,7 +464,7 @@ mod tests { let mut signatures = 0; for object in Reader::open(bytes)? { match object? { - Object::File(object) => names.push(object.name.to_string()), + Object::File(object) => names.push(object.name().to_string()), Object::Signature(_) => signatures += 1, } } @@ -542,10 +503,10 @@ mod tests { ])) .unwrap(); assert_eq!( - (m.root.inode.mtime_nsec, m.root.inode.mode.map(crate::Mode::bits)), + (m.root.inode.mtime_nsec(), m.root.inode.mode().map(crate::Mode::bits)), (Some(7), Some(0o775)) ); - let names: Vec<&str> = m.objects.iter().map(|object| object.name.as_str()).collect(); + let names: Vec<&str> = m.objects.iter().map(|object| object.name().as_str()).collect(); assert_eq!( names, [ @@ -557,10 +518,10 @@ mod tests { "link" ] ); - assert_eq!(m.objects[2].sha256, Some(Sha256::digest(b"hello"))); - assert_eq!(m.objects[3].sha256, Some(Sha256::EMPTY)); - assert_eq!(m.objects[4].size, Some(5)); - assert_eq!(m.objects[5].inode_type, InodeType::Symlink); + assert_eq!(m.objects[2].sha256(), Some(Sha256::digest(b"hello"))); + assert_eq!(m.objects[3].sha256(), Some(Sha256::EMPTY)); + assert_eq!(m.objects[4].size(), Some(5)); + assert_eq!(m.objects[5].inode_type(), InodeType::Symlink); assert_eq!(m.signatures.len(), 1); assert_eq!(m.signatures[0].mechanism, "pkcs7"); assert_eq!(m.signatures[0].data.as_deref(), Some(&[0u8, 0, 0][..])); @@ -779,36 +740,36 @@ mod tests { ); // The root has the inode flags. It has no DOS attributes at all. let root = reader.root(); - assert_eq!(root.inode.flags.get(InodeFlags::NO_COW), Some(false)); - assert_eq!(root.inode.read_only, Some(false)); - assert_eq!(root.inode.user_xattrs.as_deref().map(BTreeMap::len), Some(0)); + assert_eq!(root.inode.flags().get(InodeFlags::NO_COW), Some(false)); + assert_eq!(root.inode.read_only(), Some(false)); + assert_eq!(root.inode.user_xattr_map().map(BTreeMap::len), Some(0)); let m = read_whole(&bytes).unwrap(); let a = &m.objects[0]; - assert_eq!(a.dos_flags.get(DosFlags::HIDDEN), Some(true)); - assert_eq!(a.dos_flags.get(DosFlags::SYSTEM), None); - assert_eq!(a.inode.flags.get(InodeFlags::NO_COW), Some(false)); - assert_eq!(a.inode.read_only, Some(false)); - assert_eq!(a.inode.user_xattrs.as_deref().map(BTreeMap::len), Some(0)); - assert_eq!(m.objects[1].inode.read_only, Some(true)); + assert_eq!(a.dos_flags().get(DosFlags::HIDDEN), Some(true)); + assert_eq!(a.dos_flags().get(DosFlags::SYSTEM), None); + assert_eq!(a.inode().flags().get(InodeFlags::NO_COW), Some(false)); + assert_eq!(a.inode().read_only(), Some(false)); + assert_eq!(a.inode().user_xattr_map().map(BTreeMap::len), Some(0)); + assert_eq!(m.objects[1].inode().read_only(), Some(true)); // The gpt fields are as the records have them: a missing gptFlags // is 0, but nothing fills it in, and a regular file without any // gpt field has no GptPartition. - assert_eq!(a.gpt.as_deref().map(|gpt| gpt.flags), Some(None)); - assert_eq!(m.objects[2].gpt, None); + assert_eq!(a.gpt().map(|gpt| gpt.flags), Some(None)); + assert_eq!(m.objects[2].gpt(), None); // A symbolic link has no flags. let link = &m.objects[3]; assert_eq!( - (link.dos_flags, link.inode.flags), + (link.dos_flags(), link.inode().flags()), (FlagStates::default(), FlagStates::default()) ); // Without the features nothing is known about them. let m = read_whole(&manifest(&[r#"{"name":"a"}"#])).unwrap(); let a = &m.objects[0]; assert_eq!( - (a.dos_flags, a.inode.flags), + (a.dos_flags(), a.inode().flags()), (FlagStates::default(), FlagStates::default()) ); - assert_eq!((a.inode.user_xattrs.as_deref(), a.inode.read_only), (None, None)); + assert_eq!((a.inode().user_xattr_map(), a.inode().read_only()), (None, None)); assert_eq!(m.root, RootObject::default()); } diff --git a/src/uapi16/record.rs b/src/uapi16/record.rs new file mode 100644 index 0000000..8e66794 --- /dev/null +++ b/src/uapi16/record.rs @@ -0,0 +1,857 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! File objects as the manifest builder keeps them while it sorts: in +//! bytes that are quick to write and to read back, and that say all an +//! object says. Two objects are equal if their bytes are. +//! +//! The bytes are never part of a manifest. They sit in memory or in a +//! scratch file until the objects are written in the order of the +//! manifest, and what comes back from a scratch file is checked like any +//! other input. +//! +//! An object is written into as many bytes as the one who writes it +//! allows, and no further. So an object that is larger than anything a +//! manifest holds takes no more memory here than one that fits. + +use std::collections::BTreeMap; +use std::io; +use std::num::NonZeroU64; + +use crate::object::{ + ContentsObject, ContentsSource, DosFlags, FatSerial, FileObject, FileSystemIdentity, FilledIn, FlagStates, + GptPartition, InodeAttributes, InodeFlags, InodeType, Mode, Uuid, Validity, ValidityWindow, +}; +use crate::{NameBuf, Sha256, MAX_CONTENTS}; + +/// An error for bytes that are not what was written. +fn damaged() -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, "a scratch file of the sort was changed") +} + +/// Writes the fields of an object one behind the other. Numbers are +/// little-endian, and what has no fixed length has its length in front. +pub(crate) struct RecordWriter<'a> { + /// What the bytes are appended to. + out: &'a mut Vec, + /// How long that may get. + limit: usize, + /// Whether something did not fit and was left out. + cut: bool, +} + +impl<'a> RecordWriter<'a> { + /// A writer that appends to `bytes` until they are `limit` bytes long. + /// What does not fit then is left out, all of it, and so is everything + /// that comes after it. + pub(crate) fn new(out: &'a mut Vec, limit: usize) -> RecordWriter<'a> { + RecordWriter { out, limit, cut: false } + } + + /// Whether something was left out because it did not fit. The bytes + /// are no record then. + pub(crate) fn is_cut(&self) -> bool { + self.cut + } + + pub(crate) fn raw(&mut self, bytes: &[u8]) { + if self.cut || bytes.len() > self.limit.saturating_sub(self.out.len()) { + self.cut = true; + return; + } + self.out.extend_from_slice(bytes); + } + + pub(crate) fn u8(&mut self, value: u8) { + self.raw(&[value]); + } + + pub(crate) fn u16(&mut self, value: u16) { + self.raw(&value.to_le_bytes()); + } + + pub(crate) fn u32(&mut self, value: u32) { + self.raw(&value.to_le_bytes()); + } + + pub(crate) fn u64(&mut self, value: u64) { + self.raw(&value.to_le_bytes()); + } + + /// Bytes with their length in front. + pub(crate) fn bytes(&mut self, bytes: &[u8]) { + // Nothing an object holds is as long as four gigabytes: a record + // of it is refused long before. + self.u32(u32::try_from(bytes.len()).unwrap_or(u32::MAX)); + self.raw(bytes); + } + + /// The bits of `marks` whose value is there. + fn mask(marks: [(bool, u16); BITS]) -> u16 { + marks + .into_iter() + .filter(|(there, _)| *there) + .fold(0, |mask, (_, bit)| mask | bit) + } + + fn flags(&mut self, states: &FlagStates, bits: impl Fn(F) -> u8) { + self.raw(&[bits(states.stated), bits(states.set), bits(states.filled)]); + } +} + +/// Reads the fields of an object back, and takes nothing about them for +/// granted. +pub(crate) struct RecordReader<'a>(pub(crate) &'a [u8]); + +impl<'a> RecordReader<'a> { + pub(crate) fn array(&mut self) -> io::Result<[u8; SIZE]> { + let (array, rest) = self.0.split_first_chunk().ok_or_else(damaged)?; + self.0 = rest; + Ok(*array) + } + + pub(crate) fn u8(&mut self) -> io::Result { + Ok(u8::from_le_bytes(self.array()?)) + } + + pub(crate) fn u16(&mut self) -> io::Result { + Ok(u16::from_le_bytes(self.array()?)) + } + + pub(crate) fn u32(&mut self) -> io::Result { + Ok(u32::from_le_bytes(self.array()?)) + } + + pub(crate) fn u64(&mut self) -> io::Result { + Ok(u64::from_le_bytes(self.array()?)) + } + + /// Bytes that have their length in front. + pub(crate) fn bytes(&mut self) -> io::Result<&'a [u8]> { + let len = usize::try_from(self.u32()?).map_err(|_| damaged())?; + let (bytes, rest) = self.0.split_at_checked(len).ok_or_else(damaged)?; + self.0 = rest; + Ok(bytes) + } + + fn string(&mut self) -> io::Result { + String::from_utf8(self.bytes()?.to_vec()).map_err(|_| damaged()) + } + + /// A name, which is the name of the root if it has no bytes. + fn name(&mut self) -> io::Result { + let name = self.string()?; + if name.is_empty() { + return Ok(NameBuf::default()); + } + NameBuf::new(name).map_err(|_| damaged()) + } + + /// A mask that has no bits but those of `known`. + fn mask(&mut self, known: u16) -> io::Result { + let mask = self.u16()?; + if mask & !known != 0 { + return Err(damaged()); + } + Ok(mask) + } + + /// The value `read` reads, if `mask` has the bit `bit`. + fn optional( + &mut self, + mask: u16, + bit: u16, + read: impl FnOnce(&mut RecordReader<'a>) -> io::Result, + ) -> io::Result> { + if mask & bit == 0 { + return Ok(None); + } + read(self).map(Some) + } + + fn flags>( + &mut self, + from_bits: impl Fn(u8) -> Option, + ) -> io::Result> { + let [stated, set, filled] = self.array()?; + let flags = |bits| from_bits(bits).ok_or_else(damaged); + let (stated, set, filled) = (flags(stated)?, flags(set)?, flags(filled)?); + // Only a flag that is stated is set or filled in. + if (set & stated) != set || (filled & stated) != filled { + return Err(damaged()); + } + Ok(FlagStates { stated, set, filled }) + } + + /// Whether everything was read. + pub(crate) fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +impl InodeType { + /// The inode types, each at the place of its number in the bytes. + const NUMBERED: [InodeType; 7] = [ + InodeType::Regular, + InodeType::Directory, + InodeType::Symlink, + InodeType::Fifo, + InodeType::CharDevice, + InodeType::BlockDevice, + InodeType::Socket, + ]; + + fn to_record(self, record: &mut RecordWriter<'_>) { + let number = InodeType::NUMBERED.iter().position(|&numbered| numbered == self); + // Every inode type has a number that fits into a byte. + record.u8(number.unwrap_or_default() as u8); + } + + fn from_record(record: &mut RecordReader<'_>) -> io::Result { + let number = usize::from(record.u8()?); + InodeType::NUMBERED.get(number).copied().ok_or_else(damaged) + } +} + +impl ValidityWindow { + fn to_record(self, record: &mut RecordWriter<'_>) { + record.u64(self.since_usec); + record.u8(u8::from(self.until_usec.is_some())); + record.u64(self.until_usec.unwrap_or_default()); + record.u8(u8::from(self.state == Validity::Revoked)); + } + + fn from_record(record: &mut RecordReader<'_>) -> io::Result { + let since_usec = record.u64()?; + let until_usec = match (record.u8()?, record.u64()?) { + (0, 0) => None, + (1, until_usec) => Some(until_usec), + _ => return Err(damaged()), + }; + let state = match record.u8()? { + 0 => Validity::Good, + 1 => Validity::Revoked, + _ => return Err(damaged()), + }; + Ok(ValidityWindow { + since_usec, + until_usec, + state, + }) + } +} + +impl GptPartition { + const LABEL: u16 = 1 << 0; + const UUID: u16 = 1 << 1; + const TYPE_UUID: u16 = 1 << 2; + const FLAGS: u16 = 1 << 3; + const NO_AUTO: u16 = 1 << 4; + const NO_AUTO_SET: u16 = 1 << 5; + const GROW_FILE_SYSTEM: u16 = 1 << 6; + const GROW_FILE_SYSTEM_SET: u16 = 1 << 7; + const KNOWN: u16 = (1 << 8) - 1; + + fn to_record(&self, record: &mut RecordWriter<'_>) { + record.u16(RecordWriter::mask([ + (self.label.is_some(), GptPartition::LABEL), + (self.uuid.is_some(), GptPartition::UUID), + (self.type_uuid.is_some(), GptPartition::TYPE_UUID), + (self.flags.is_some(), GptPartition::FLAGS), + (self.no_auto.is_some(), GptPartition::NO_AUTO), + (self.no_auto == Some(true), GptPartition::NO_AUTO_SET), + (self.grow_file_system.is_some(), GptPartition::GROW_FILE_SYSTEM), + (self.grow_file_system == Some(true), GptPartition::GROW_FILE_SYSTEM_SET), + ])); + if let Some(label) = &self.label { + record.bytes(label.as_bytes()); + } + for uuid in [self.uuid, self.type_uuid].into_iter().flatten() { + record.raw(uuid.as_bytes()); + } + if let Some(flags) = self.flags { + record.u64(flags); + } + } + + fn from_record(record: &mut RecordReader<'_>) -> io::Result { + let mask = record.mask(GptPartition::KNOWN)?; + let flag = |there: u16, set: u16| match (mask & there != 0, mask & set != 0) { + (true, set) => Ok(Some(set)), + (false, false) => Ok(None), + (false, true) => Err(damaged()), + }; + Ok(GptPartition { + label: record.optional(mask, GptPartition::LABEL, RecordReader::string)?, + uuid: record.optional(mask, GptPartition::UUID, |record| record.array().map(Uuid::new))?, + type_uuid: record.optional(mask, GptPartition::TYPE_UUID, |record| record.array().map(Uuid::new))?, + flags: record.optional(mask, GptPartition::FLAGS, RecordReader::u64)?, + no_auto: flag(GptPartition::NO_AUTO, GptPartition::NO_AUTO_SET)?, + grow_file_system: flag(GptPartition::GROW_FILE_SYSTEM, GptPartition::GROW_FILE_SYSTEM_SET)?, + }) + } +} + +impl ContentsObject { + /// The numbers of the sources of a contents object in the bytes. + const IMPLIED: u8 = 0; + const FILE: u8 = 1; + const URL: u8 = 2; + const LITERAL: u8 = 3; + + const ENCODING: u16 = 1 << 0; + const ENCODED_SIZE: u16 = 1 << 1; + const ENCODED_SHA256: u16 = 1 << 2; + const ORIGINAL_SIZE: u16 = 1 << 3; + const ORIGINAL_SHA256: u16 = 1 << 4; + const KNOWN: u16 = (1 << 5) - 1; + + fn to_record(&self, record: &mut RecordWriter<'_>) { + match &self.source { + ContentsSource::Implied => record.u8(ContentsObject::IMPLIED), + ContentsSource::File(name) => { + record.u8(ContentsObject::FILE); + record.bytes(name.as_str().as_bytes()); + } + ContentsSource::Url(url) => { + record.u8(ContentsObject::URL); + record.bytes(url.as_bytes()); + } + ContentsSource::Literal(literal) => { + record.u8(ContentsObject::LITERAL); + record.bytes(literal); + } + } + record.u32(u32::try_from(self.http_headers.len()).unwrap_or(u32::MAX)); + for (name, value) in &self.http_headers { + record.bytes(name.as_bytes()); + record.bytes(value.as_bytes()); + } + record.u16(RecordWriter::mask([ + (self.encoding.is_some(), ContentsObject::ENCODING), + (self.encoded_size.is_some(), ContentsObject::ENCODED_SIZE), + (self.encoded_sha256.is_some(), ContentsObject::ENCODED_SHA256), + (self.original_size.is_some(), ContentsObject::ORIGINAL_SIZE), + (self.original_sha256.is_some(), ContentsObject::ORIGINAL_SHA256), + ])); + if let Some(encoding) = &self.encoding { + record.bytes(encoding.as_bytes()); + } + if let Some(size) = self.encoded_size { + record.u64(size); + } + if let Some(sha256) = &self.encoded_sha256 { + record.raw(sha256.as_bytes()); + } + if let Some(size) = self.original_size { + record.u64(size); + } + if let Some(sha256) = &self.original_sha256 { + record.raw(sha256.as_bytes()); + } + record.u64(self.offset); + record.u16(self.filled_in.bits()); + } + + fn from_record(record: &mut RecordReader<'_>) -> io::Result { + let source = match record.u8()? { + ContentsObject::IMPLIED => ContentsSource::Implied, + ContentsObject::FILE => ContentsSource::File(record.name()?), + ContentsObject::URL => ContentsSource::Url(record.string()?), + ContentsObject::LITERAL => ContentsSource::Literal(record.bytes()?.to_vec()), + _ => return Err(damaged()), + }; + let headers = record.u32()?; + let mut http_headers = Vec::new(); + for _ in 0..headers { + http_headers.push((record.string()?, record.string()?)); + } + let mask = record.mask(ContentsObject::KNOWN)?; + let sha256 = |record: &mut RecordReader<'_>| record.array().map(Sha256::from); + Ok(ContentsObject { + source, + http_headers, + encoding: record.optional(mask, ContentsObject::ENCODING, RecordReader::string)?, + encoded_size: record.optional(mask, ContentsObject::ENCODED_SIZE, RecordReader::u64)?, + encoded_sha256: record.optional(mask, ContentsObject::ENCODED_SHA256, sha256)?, + original_size: record.optional(mask, ContentsObject::ORIGINAL_SIZE, RecordReader::u64)?, + original_sha256: record.optional(mask, ContentsObject::ORIGINAL_SHA256, sha256)?, + offset: record.u64()?, + filled_in: FilledIn::from_bits(record.u16()?), + }) + } +} + +impl InodeAttributes { + const MODE: u16 = 1 << 0; + const UID: u16 = 1 << 1; + const GID: u16 = 1 << 2; + const USER_NAME: u16 = 1 << 3; + const GROUP_NAME: u16 = 1 << 4; + const MTIME: u16 = 1 << 5; + const XATTRS: u16 = 1 << 6; + const READ_ONLY: u16 = 1 << 7; + const READ_ONLY_SET: u16 = 1 << 8; + const FLAGS: u16 = 1 << 9; + const FILLED_IN: u16 = 1 << 10; + const KNOWN: u16 = (1 << 11) - 1; + + /// Writes the inode attributes, which a file object and the root file + /// object both have. + pub(crate) fn to_record(&self, record: &mut RecordWriter<'_>) { + record.u16(RecordWriter::mask([ + (self.mode().is_some(), InodeAttributes::MODE), + (self.uid().is_some(), InodeAttributes::UID), + (self.gid().is_some(), InodeAttributes::GID), + (self.user_name().is_some(), InodeAttributes::USER_NAME), + (self.group_name().is_some(), InodeAttributes::GROUP_NAME), + (self.mtime_nsec().is_some(), InodeAttributes::MTIME), + (self.user_xattr_map().is_some(), InodeAttributes::XATTRS), + (self.read_only().is_some(), InodeAttributes::READ_ONLY), + (self.read_only() == Some(true), InodeAttributes::READ_ONLY_SET), + (self.flags() != FlagStates::default(), InodeAttributes::FLAGS), + (!self.marks().is_empty(), InodeAttributes::FILLED_IN), + ])); + if let Some(mode) = self.mode() { + // A mode has twelve bits. + record.u16(mode.bits() as u16); + } + for id in [self.uid(), self.gid()].into_iter().flatten() { + record.u32(id); + } + for name in [self.user_name(), self.group_name()].into_iter().flatten() { + record.bytes(name.as_bytes()); + } + if let Some(mtime) = self.mtime_nsec() { + record.u64(mtime); + } + if let Some(xattrs) = self.user_xattr_map() { + record.u32(u32::try_from(xattrs.len()).unwrap_or(u32::MAX)); + for (name, value) in xattrs.iter() { + record.bytes(name.as_bytes()); + record.bytes(value); + } + } + if self.flags() != FlagStates::default() { + record.flags(&self.flags(), InodeFlags::bits); + } + if !self.marks().is_empty() { + record.u16(self.marks().bits()); + } + } + + /// Reads the inode attributes back. + pub(crate) fn from_record(record: &mut RecordReader<'_>) -> io::Result { + let mask = record.mask(InodeAttributes::KNOWN)?; + let mode = record.optional(mask, InodeAttributes::MODE, RecordReader::u16)?; + let mode = mode + .map(|mode| Mode::new(u32::from(mode))) + .transpose() + .map_err(|_| damaged())?; + let uid = record.optional(mask, InodeAttributes::UID, RecordReader::u32)?; + let gid = record.optional(mask, InodeAttributes::GID, RecordReader::u32)?; + let user_name = record.optional(mask, InodeAttributes::USER_NAME, RecordReader::string)?; + let group_name = record.optional(mask, InodeAttributes::GROUP_NAME, RecordReader::string)?; + let mtime_nsec = record.optional(mask, InodeAttributes::MTIME, RecordReader::u64)?; + let user_xattrs = record.optional(mask, InodeAttributes::XATTRS, |record| { + let mut xattrs = BTreeMap::new(); + for _ in 0..record.u32()? { + // The attributes are written in the order of their names, + // each name once. + let (name, value) = (record.string()?, record.bytes()?.to_vec()); + if xattrs.last_key_value().is_some_and(|(last, _)| *last >= name) { + return Err(damaged()); + } + xattrs.insert(name, value); + } + Ok(xattrs) + })?; + let read_only = match ( + mask & InodeAttributes::READ_ONLY != 0, + mask & InodeAttributes::READ_ONLY_SET != 0, + ) { + (true, set) => Some(set), + (false, false) => None, + (false, true) => return Err(damaged()), + }; + let flags = record.optional(mask, InodeAttributes::FLAGS, |record| { + record.flags(InodeFlags::from_bits) + })?; + let filled_in = record.optional(mask, InodeAttributes::FILLED_IN, RecordReader::u16)?; + if flags == Some(FlagStates::default()) || filled_in == Some(0) { + return Err(damaged()); + } + let mut inode = InodeAttributes::default(); + inode.set_mode(mode); + inode.set_uid(uid); + inode.set_gid(gid); + inode.set_user_name(user_name); + inode.set_group_name(group_name); + inode.set_mtime_nsec(mtime_nsec); + inode.set_user_xattrs(user_xattrs); + inode.set_read_only(read_only); + inode.set_flags(flags.unwrap_or_default()); + // What a reader filled in comes last: a setter takes the mark of + // its field away. + inode.set_marks(FilledIn::from_bits(filled_in.unwrap_or_default())); + Ok(inode) + } +} + +impl FileSystemIdentity { + const UUID: u16 = 1 << 0; + const LABEL: u16 = 1 << 1; + const FAT_SERIAL: u16 = 1 << 2; + const KNOWN: u16 = (1 << 3) - 1; + + /// Writes the identity of a file system, which the root of a tree + /// has. + pub(crate) fn to_record(&self, record: &mut RecordWriter<'_>) { + record.u16(RecordWriter::mask([ + (self.uuid.is_some(), FileSystemIdentity::UUID), + (self.label.is_some(), FileSystemIdentity::LABEL), + (self.fat_serial.is_some(), FileSystemIdentity::FAT_SERIAL), + ])); + if let Some(uuid) = &self.uuid { + record.raw(uuid.as_bytes()); + } + if let Some(label) = &self.label { + record.bytes(label.as_bytes()); + } + if let Some(serial) = self.fat_serial { + record.u32(serial.get()); + } + } + + /// Reads the identity of a file system back. + pub(crate) fn from_record(record: &mut RecordReader<'_>) -> io::Result { + let mask = record.mask(FileSystemIdentity::KNOWN)?; + Ok(FileSystemIdentity { + uuid: record.optional(mask, FileSystemIdentity::UUID, |record| record.array().map(Uuid::new))?, + label: record.optional(mask, FileSystemIdentity::LABEL, RecordReader::string)?, + fat_serial: record.optional(mask, FileSystemIdentity::FAT_SERIAL, |record| { + record.u32().map(FatSerial::new) + })?, + }) + } +} + +impl FileObject { + const SIZE: u16 = 1 << 0; + const SHA256: u16 = 1 << 1; + const INODE_TOKEN: u16 = 1 << 2; + const MAJOR: u16 = 1 << 3; + const MINOR: u16 = 1 << 4; + const GPT: u16 = 1 << 5; + const CONTENTS: u16 = 1 << 6; + const DOS_FLAGS: u16 = 1 << 7; + const VALIDITY: u16 = 1 << 8; + const FILLED_IN: u16 = 1 << 9; + const KNOWN: u16 = (1 << 10) - 1; + + /// Writes everything the object says but its name, which is what it + /// is sorted by and is kept in front of this. What most objects do not + /// have takes no room. + /// + /// An object with more contents objects than a manifest may have does + /// not come back from what this writes. No writer takes it, and + /// whoever keeps objects refuses it before. + pub(crate) fn to_record(&self, record: &mut RecordWriter<'_>) { + self.inode_type().to_record(record); + record.u16(RecordWriter::mask([ + (self.size().is_some(), FileObject::SIZE), + (self.sha256().is_some(), FileObject::SHA256), + (self.inode_token().is_some(), FileObject::INODE_TOKEN), + (self.major().is_some(), FileObject::MAJOR), + (self.minor().is_some(), FileObject::MINOR), + (self.gpt().is_some(), FileObject::GPT), + (!self.contents().is_empty(), FileObject::CONTENTS), + (self.dos_flags() != FlagStates::default(), FileObject::DOS_FLAGS), + (self.validity() != ValidityWindow::default(), FileObject::VALIDITY), + (!self.marks().is_empty(), FileObject::FILLED_IN), + ])); + if let Some(size) = self.size() { + record.u64(size); + } + if let Some(sha256) = self.sha256() { + record.raw(sha256.as_bytes()); + } + if let Some(token) = self.inode_token() { + record.u64(token.get()); + } + for number in [self.major(), self.minor()].into_iter().flatten() { + record.u64(number); + } + if let Some(gpt) = self.gpt() { + gpt.to_record(record); + } + if !self.contents().is_empty() { + record.u32(u32::try_from(self.contents().len()).unwrap_or(u32::MAX)); + for contents in self.contents() { + contents.to_record(record); + } + } + if self.dos_flags() != FlagStates::default() { + record.flags(&self.dos_flags(), DosFlags::bits); + } + if self.validity() != ValidityWindow::default() { + self.validity().to_record(record); + } + if !self.marks().is_empty() { + record.u16(self.marks().bits()); + } + self.inode().to_record(record); + } + + /// Reads the object with the name `name` back, from all of `record`. + pub(crate) fn from_record(name: NameBuf, record: &mut RecordReader<'_>) -> io::Result { + let inode_type = InodeType::from_record(record)?; + let mask = record.mask(FileObject::KNOWN)?; + let size = record.optional(mask, FileObject::SIZE, RecordReader::u64)?; + let sha256 = record.optional(mask, FileObject::SHA256, |record| record.array().map(Sha256::from))?; + let inode_token = record.optional(mask, FileObject::INODE_TOKEN, |record| { + NonZeroU64::new(record.u64()?).ok_or_else(damaged) + })?; + let major = record.optional(mask, FileObject::MAJOR, RecordReader::u64)?; + let minor = record.optional(mask, FileObject::MINOR, RecordReader::u64)?; + let gpt = record.optional(mask, FileObject::GPT, GptPartition::from_record)?; + let contents = record.optional(mask, FileObject::CONTENTS, |record| { + // A contents object is much larger in memory than its bytes + // are, and no object that was kept has more of them than + // this. + let count = usize::try_from(record.u32()?).map_err(|_| damaged())?; + if count > MAX_CONTENTS { + return Err(damaged()); + } + let mut contents = Vec::with_capacity(count); + for _ in 0..count { + contents.push(ContentsObject::from_record(record)?); + } + Ok(contents) + })?; + let dos_flags = record.optional(mask, FileObject::DOS_FLAGS, |record| record.flags(DosFlags::from_bits))?; + let validity = record.optional(mask, FileObject::VALIDITY, ValidityWindow::from_record)?; + let filled_in = record.optional(mask, FileObject::FILLED_IN, RecordReader::u16)?; + // What is there says something: nothing is written that an + // object without it would not say as well. + if contents.as_ref().is_some_and(Vec::is_empty) + || dos_flags == Some(FlagStates::default()) + || validity == Some(ValidityWindow::default()) + || filled_in == Some(0) + { + return Err(damaged()); + } + let mut object = FileObject::new(name); + object.set_inode_type(inode_type); + object.set_size(size); + object.set_sha256(sha256); + object.put_contents(contents.unwrap_or_default()); + object.set_inode_token(inode_token); + object.set_major(major); + object.set_minor(minor); + object.set_gpt(gpt); + object.set_dos_flags(dos_flags.unwrap_or_default()); + *object.inode_mut() = InodeAttributes::from_record(record)?; + object.set_validity(validity.unwrap_or_default()); + // What a reader filled in comes last: a setter takes the mark of + // its field away. + object.set_marks(FilledIn::from_bits(filled_in.unwrap_or_default())); + if !record.is_empty() { + return Err(damaged()); + } + Ok(object) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{everything, name}; + + /// The bytes of `object`. + fn bytes(object: &FileObject) -> Vec { + let mut bytes = Vec::new(); + let mut record = RecordWriter::new(&mut bytes, usize::MAX); + object.to_record(&mut record); + assert!(!record.is_cut()); + bytes + } + + /// The object of the bytes `bytes`, named as `object` is. + fn read(object: &FileObject, bytes: &[u8]) -> io::Result { + FileObject::from_record(object.name().to_owned(), &mut RecordReader(bytes)) + } + + /// Objects that differ from one another in one thing each, from one + /// that says nothing to one that says everything. + fn objects() -> Vec { + let mut objects = vec![FileObject::new(name("plain")), everything()]; + type Change = fn(&mut FileObject); + let changes: [Change; 32] = [ + |o| o.set_inode_type(InodeType::Socket), + |o| o.set_size(Some(0)), + |o| o.set_size(Some(u64::MAX)), + |o| o.set_sha256(Some(Sha256::EMPTY)), + |o| o.set_inode_token(NonZeroU64::new(1)), + |o| o.set_inode_token(Some(NonZeroU64::MAX)), + |o| o.set_major(Some(0)), + |o| o.set_minor(Some(0)), + |o| o.set_gpt(Some(GptPartition::default())), + |o| o.gpt_or_default().no_auto = Some(false), + |o| o.gpt_or_default().grow_file_system = Some(true), + |o| o.gpt_or_default().label = Some(String::new()), + |o| o.put_contents(vec![ContentsObject::default()]), + |o| o.put_contents(vec![ContentsObject::new(ContentsSource::Literal(Vec::new()))]), + |o| o.put_contents(vec![ContentsObject::new(ContentsSource::Url(String::new()))]), + |o| o.put_contents(vec![ContentsObject::new(ContentsSource::File(name("f")))]), + |o| o.put_contents(vec![ContentsObject::new(ContentsSource::File(NameBuf::default()))]), + |o| o.set_flag_hidden(Some(false)), + |o| o.set_flag_hidden(Some(true)), + |o| o.inode_mut().set_flag_no_dump(Some(false)), + |o| { + let mut flags = o.inode().flags(); + flags.fill_in(crate::Features::FLAG_NO_COW, InodeType::Regular); + o.inode_mut().set_flags(flags); + }, + |o| o.inode_mut().set_mode(Some(Mode::from_st_mode(0))), + |o| o.inode_mut().set_uid(Some(0)), + |o| o.inode_mut().set_gid(Some(0)), + |o| o.inode_mut().set_user_name(Some("".into())), + |o| o.inode_mut().set_group_name(Some("".into())), + |o| o.inode_mut().set_mtime_nsec(Some(0)), + |o| o.inode_mut().set_user_xattrs(Some(BTreeMap::new())), + |o| o.inode_mut().set_read_only(Some(false)), + |o| o.fill_in(crate::Features::READ_ONLY | crate::Features::USER_XATTR), + |o| o.validity_mut().until_usec = Some(0), + |o| { + let mut marks = o.marks(); + marks.insert(crate::Field::Size); + o.set_marks(marks); + }, + ]; + for change in changes { + let mut object = FileObject::new(name("plain")); + change(&mut object); + objects.push(object); + } + let mut revoked = FileObject::new(name("plain")); + revoked.validity_mut().state = Validity::Revoked; + revoked.validity_mut().since_usec = 1; + objects.push(revoked); + objects + } + + /// An object comes back from its bytes as it went in, with what a + /// reader filled in, and no two objects that differ have the same + /// bytes. + #[test] + fn objects_come_back() { + let objects = objects(); + let all: Vec> = objects.iter().map(bytes).collect(); + for (index, (object, bytes)) in objects.iter().zip(&all).enumerate() { + assert_eq!(read(object, bytes).unwrap(), *object, "{}", index); + assert!(!all[..index].contains(bytes), "{}", index); + } + // The name is not in the bytes: it is what an object is sorted by. + let mut renamed = everything(); + renamed.set_name(name("other")); + assert_eq!(bytes(&renamed), bytes(&everything())); + // An object that says nothing takes a few bytes. + assert_eq!(bytes(&FileObject::new(name("plain"))).len(), 5); + // As many contents objects as a manifest may have come back, and + // more do not. + let mut many = FileObject::new(name("plain")); + many.put_contents(vec![ContentsObject::default(); MAX_CONTENTS]); + assert!(read(&many, &bytes(&many)).unwrap() == many); + many.put_contents(vec![ContentsObject::default(); MAX_CONTENTS + 1]); + let more = read(&many, &bytes(&many)).unwrap_err(); + assert_eq!(more.kind(), io::ErrorKind::InvalidData); + } + + /// A writer stops at its limit: what does not fit is left out with + /// everything behind it, and the writer says so. + #[test] + fn writes_up_to_a_limit() { + let object = everything(); + let whole = bytes(&object); + for limit in [0, 1, 4, whole.len() / 2, whole.len() - 1] { + let mut bytes = Vec::new(); + let mut record = RecordWriter::new(&mut bytes, limit); + object.to_record(&mut record); + assert!(record.is_cut(), "{}", limit); + assert!(bytes.len() <= limit && whole.starts_with(&bytes), "{}", limit); + } + for limit in [whole.len(), whole.len() + 1] { + let mut bytes = Vec::new(); + let mut record = RecordWriter::new(&mut bytes, limit); + object.to_record(&mut record); + assert!(!record.is_cut() && bytes == whole, "{}", limit); + } + // Something small still fits behind something that did not, and + // is left out all the same. + let mut bytes = Vec::new(); + let mut record = RecordWriter::new(&mut bytes, 4); + record.u16(1); + record.u32(2); + record.u8(3); + assert!(record.is_cut()); + assert_eq!(bytes, [1, 0]); + // Bytes that are longer than the limit to begin with take nothing. + let mut bytes = vec![0; 8]; + let mut record = RecordWriter::new(&mut bytes, 4); + record.u8(1); + assert!(record.is_cut()); + assert_eq!(bytes.len(), 8); + } + + /// Bytes that are cut short, that go on after the object or that were + /// changed never come back as the object, and never as a panic: they + /// are another object or an error. + #[test] + fn changed_bytes_are_refused() { + for object in objects() { + let bytes = bytes(&object); + for len in 0..bytes.len() { + assert!(read(&object, &bytes[..len]).is_err(), "{:?} cut to {}", object, len); + } + let mut longer = bytes.clone(); + longer.push(0); + assert_eq!(read(&object, &longer).unwrap_err().kind(), io::ErrorKind::InvalidData); + for at in 0..bytes.len() { + for bit in 0..8 { + let mut changed = bytes.clone(); + changed[at] ^= 1 << bit; + if let Ok(read) = read(&object, &changed) { + assert_ne!(read, object, "{} bit {}", at, bit); + } + } + } + } + } + + /// The identity of a file system comes back as it went in. + #[test] + fn identities_come_back() { + let identities = [ + FileSystemIdentity::default(), + FileSystemIdentity { + uuid: Some(Uuid::new([7; Uuid::SIZE])), + label: Some("ESP".into()), + fat_serial: Some(FatSerial::new(0x1234_abcd)), + }, + FileSystemIdentity { + uuid: None, + label: Some(String::new()), + fat_serial: Some(FatSerial::new(0)), + }, + ]; + for identity in &identities { + let mut bytes = Vec::new(); + identity.to_record(&mut RecordWriter::new(&mut bytes, usize::MAX)); + let mut reader = RecordReader(&bytes); + assert_eq!(FileSystemIdentity::from_record(&mut reader).unwrap(), *identity); + assert!(reader.is_empty()); + for len in 0..bytes.len() { + assert!(FileSystemIdentity::from_record(&mut RecordReader(&bytes[..len])).is_err()); + } + } + } +} diff --git a/src/uapi16/scratch.rs b/src/uapi16/scratch.rs new file mode 100644 index 0000000..38af4af --- /dev/null +++ b/src/uapi16/scratch.rs @@ -0,0 +1,375 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! Where a manifest that is being built keeps what it cannot keep in +//! memory: in files without names, which are made when they are first +//! needed. A manifest of a small tree never needs one, and nothing is +//! opened for it. +//! +//! A manifest that is created as a file keeps them in the directory it is +//! created in, which has the room for the manifest as well, through the +//! descriptor the file has of that directory. Any other keeps them in the +//! directory `TMPDIR` names, and in /var/tmp where that names none: /tmp is +//! often memory, and what goes here is what did not fit into memory. A +//! `TMPDIR` that is set is used as it is, also where it is in memory, which +//! is its user's choice. +//! +//! Either directory can be in a tree the manifest lists, and a file +//! system can show a file without a name in its directory all the same. So +//! every scratch file is one of the files of the manifest's own, which a +//! walk passes over, and it stays open with them once it is given back, see +//! [`OwnFiles`]. A file that was given back is handed out again before a +//! new one is made. So no more files are made than are used at one time. + +use std::env; +use std::ffi::OsString; +use std::io; +use std::os::fd::{AsFd, OwnedFd}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use crate::error::Error; +use crate::sys::{OwnFiles, ScratchFile}; + +/// The scratch space of a manifest that is being built: the directory its +/// scratch files are made in, and the files of the manifest's own, which +/// they are among. +#[derive(Debug)] +pub(crate) struct Scratch { + /// The directory, if it was given or if a file was made already. One + /// that was given is shared with whoever gave it. + directory: Option>, + /// The files the manifest made itself and has open. Every file made + /// here is one of them, and they keep it open and hand it out again + /// once it was given back. + own: OwnFiles, +} + +impl Scratch { + /// The variable that names the directory for temporary files. + const TMPDIR: &'static str = "TMPDIR"; + /// Where temporary files go that can be large, without that variable. + const VAR_TMP: &'static str = "/var/tmp"; + + /// Scratch space in `directory`, the directory a manifest is created + /// in, which the new file keeps open as well. + pub(crate) fn beside(directory: Arc) -> Scratch { + Scratch { + directory: Some(directory), + own: OwnFiles::default(), + } + } + + /// Scratch space in the directory for temporary files. The directory + /// is looked for and opened when the first file is made, so one that + /// is not there only fails a manifest that needs it. + pub(crate) fn temporary() -> Scratch { + Scratch { + directory: None, + own: OwnFiles::default(), + } + } + + /// The files the manifest made itself and has open, for whoever walks a + /// tree for the manifest and passes over them. They are there, and the + /// scratch files among them open, until this scratch space is dropped. + pub(crate) fn own_files(&self) -> &OwnFiles { + &self.own + } + + /// The same files, for whoever has one more file of the manifest's own + /// to keep with them. + pub(crate) fn own_files_mut(&mut self) -> &mut OwnFiles { + &mut self.own + } + + /// The directory for temporary files, where `tmpdir` is the value of + /// `TMPDIR`: the one it names, or /var/tmp if it is not set or empty. + fn temporary_directory(tmpdir: Option) -> PathBuf { + match tmpdir { + Some(directory) if !directory.is_empty() => PathBuf::from(directory), + _ => PathBuf::from(Scratch::VAR_TMP), + } + } + + /// Hands out a scratch file, which is empty, and one of the files of + /// the manifest's own: one that was made here and given back since, if + /// there is one, and a new one otherwise. A file that could not be + /// emptied when it was given back is not handed out again. The first + /// file in the directory for temporary files opens the directory, and + /// where it can't be opened or the file can't be made in it, the error + /// says which directory it is. + pub(crate) fn file(&mut self) -> io::Result { + if let Some(file) = self.own.hand_out() { + return Ok(file); + } + if let Some(directory) = &self.directory { + return ScratchFile::create_in(directory.as_fd(), &mut self.own); + } + let tmpdir = env::var_os(Scratch::TMPDIR); + let named = tmpdir.as_ref().is_some_and(|tmpdir| !tmpdir.is_empty()); + let path = Scratch::temporary_directory(tmpdir); + let first = ScratchFile::open_directory(&path).and_then(|directory| { + let file = ScratchFile::create_in(directory.as_fd(), &mut self.own)?; + Ok((directory, file)) + }); + let (directory, file) = first.map_err(|e| Error::io_about(Scratch::unusable(named, &path), e))?; + self.directory = Some(Arc::new(directory)); + Ok(file) + } + + /// Takes back the scratch file `file`, which was made here and which + /// whoever had it is done with. It is emptied, which gives its room + /// back, and handed out again before a new file is made. A file that is + /// dropped instead is left as it is, and is closed with the others. + pub(crate) fn take_back(&mut self, file: ScratchFile) { + self.own.take_back(file); + } + + /// What an error says of `path`, the directory for temporary files, + /// which can't be used, where `named` says whether `TMPDIR` names it. + fn unusable(named: bool, path: &Path) -> String { + if named { + format!( + "the directory {} names, '{}', cannot be used", + Scratch::TMPDIR, + path.display() + ) + } else { + format!( + "{} names no directory, and '{}' cannot be used", + Scratch::TMPDIR, + path.display() + ) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{OpenFile, TempDir}; + use crate::tree::InodeId; + use std::collections::HashSet; + use std::fs; + use std::os::fd::AsRawFd; + use std::os::unix::fs::MetadataExt; + use std::path::Path; + use std::process::Command; + + /// The variable that tells the test binary, run again by + /// [`temporary_directory_of_the_environment`], which directory the + /// scratch space has to be in, or that there has to be none. + const EXPECTED: &str = "UAPI16_TEST_SCRATCH_DIR"; + /// What that variable says where no directory can be opened. + const NONE: &str = "none"; + + /// The device and the inode number of the directory `scratch` makes + /// its files in. + fn directory_of(scratch: &Scratch) -> (u64, u64) { + let directory = scratch.directory.as_ref().unwrap(); + let meta = fs::metadata(format!("/proc/self/fd/{}", directory.as_raw_fd())).unwrap(); + (meta.dev(), meta.ino()) + } + + /// The device and the inode number of the directory `path`. + fn identity(path: &Path) -> (u64, u64) { + let meta = fs::metadata(path).unwrap(); + (meta.dev(), meta.ino()) + } + + /// The directory for temporary files is the one `TMPDIR` names, and + /// /var/tmp without one. + #[test] + fn temporary_directories() { + let directory = |tmpdir: Option<&str>| Scratch::temporary_directory(tmpdir.map(OsString::from)); + assert_eq!(directory(None), Path::new("/var/tmp")); + assert_eq!(directory(Some("")), Path::new("/var/tmp")); + assert_eq!(directory(Some("/tmp")), Path::new("/tmp")); + assert_eq!(directory(Some("relative/dir")), Path::new("relative/dir")); + } + + /// Scratch space next to a manifest makes its files in the directory + /// it was given, without a name, and every file is a new one. + #[test] + fn beside_a_manifest() { + let tmp = TempDir::new("scratch-beside"); + let directory = ScratchFile::open_directory(&tmp.0).unwrap(); + let mut scratch = Scratch::beside(directory.into()); + assert_eq!(directory_of(&scratch), identity(&tmp.0)); + let first = scratch.file().unwrap(); + let second = scratch.file().unwrap(); + first.write_all_at(b"first", 0).unwrap(); + second.write_all_at(b"second", 0).unwrap(); + let mut read = [0; 5]; + first.read_exact_at(&mut read, 0).unwrap(); + assert_eq!(&read, b"first"); + assert_eq!(fs::read_dir(&tmp.0).unwrap().count(), 0); + assert_eq!(directory_of(&scratch), identity(&tmp.0)); + } + + /// Every file of the scratch space is one of the files of its manifest, + /// by the inode and the status a walk finds for it. One that is given + /// back is emptied, and it stays open and one of them until the scratch + /// space is dropped. Then it is closed. Until then it is handed out + /// again, empty, before a new file is made. + #[test] + fn files_are_own_files() { + let tmp = TempDir::new("scratch-own"); + let directory = ScratchFile::open_directory(&tmp.0).unwrap(); + let mut scratch = Scratch::beside(directory.into()); + assert!(OpenFile::made_in(&tmp.0).is_empty()); + const DATA: &[u8] = b"data"; + let first = scratch.file().unwrap(); + first.write_all_at(DATA, 0).unwrap(); + let one = OpenFile::made_in(&tmp.0); + assert_eq!(one.len(), 1); + let own = scratch.own_files(); + assert!(own.contains(&one[0].status).unwrap() && one[0].size == DATA.len() as u64); + let second = scratch.file().unwrap(); + second.write_all_at(DATA, 0).unwrap(); + let both = OpenFile::made_in(&tmp.0); + assert_eq!(both.len(), 2); + let own = scratch.own_files(); + assert!(both.iter().all(|file| own.contains(&file.status).unwrap())); + scratch.take_back(first); + let mut left = OpenFile::made_in(&tmp.0); + left.sort_by_key(|file| file.size); + assert_eq!(left.len(), 2); + assert_eq!((left[0].inode, left[0].size), (one[0].inode, 0)); + assert_eq!(left[1].size, DATA.len() as u64); + let own = scratch.own_files(); + assert!(left.iter().all(|file| own.contains(&file.status).unwrap())); + scratch.take_back(second); + let left = OpenFile::made_in(&tmp.0); + assert_eq!(left.len(), 2); + let own = scratch.own_files(); + assert!(left + .iter() + .all(|file| file.size == 0 && own.contains(&file.status).unwrap())); + // The two that were given back are handed out again before a new + // file is made, which the next one is. + let inodes = |files: &[OpenFile]| -> HashSet { files.iter().map(|file| file.inode).collect() }; + let (third, fourth) = (scratch.file().unwrap(), scratch.file().unwrap()); + third.write_all_at(DATA, 0).unwrap(); + let mut open = OpenFile::made_in(&tmp.0); + open.sort_by_key(|file| file.size); + assert_eq!(inodes(&open), inodes(&left)); + assert_eq!((open[0].size, open[1].size), (0, DATA.len() as u64)); + let fifth = scratch.file().unwrap(); + let made = OpenFile::made_in(&tmp.0); + assert_eq!(made.len(), 3); + let own = scratch.own_files(); + assert!(made.iter().all(|file| own.contains(&file.status).unwrap())); + // The scratch space of another manifest has files of its own, and + // hands out none of these. + let mut other = Scratch::beside(ScratchFile::open_directory(&tmp.0).unwrap().into()); + assert!(made + .iter() + .all(|file| !other.own_files().contains(&file.status).unwrap())); + scratch.take_back(third); + let of_other = other.file().unwrap(); + assert_eq!(OpenFile::made_in(&tmp.0).len(), 4); + drop((of_other, other)); + assert_eq!(inodes(&OpenFile::made_in(&tmp.0)), inodes(&made)); + // A file that is still used outlives its scratch space, which + // closes the others. + drop(fourth); + drop(scratch); + assert_eq!(OpenFile::made_in(&tmp.0).len(), 1); + drop(fifth); + assert!(OpenFile::made_in(&tmp.0).is_empty()); + } + + /// Scratch space for temporary files opens nothing until a file is + /// made. Then it is in the directory the environment names, or in + /// /var/tmp, and a directory that is not there fails with its own + /// error, which names it, instead of falling back to another one. The + /// environment is that of a process, so the test binary runs this test + /// again in one of its own for each case. + #[test] + fn temporary_directory_of_the_environment() { + if let Some(expected) = env::var_os(EXPECTED) { + let expected = Path::new(&expected); + // The files this process makes in the directory are those it + // has open there that it did not have open before: a descriptor + // it inherited can be of a file in the directory as well. + let inherited = if expected.is_dir() { + OpenFile::made_in(expected) + } else { + Vec::new() + }; + let made = || { + let mut open = OpenFile::made_in(expected); + open.retain(|file| inherited.iter().all(|other| other.inode != file.inode)); + open + }; + let mut scratch = Scratch::temporary(); + assert!(scratch.directory.is_none()); + match scratch.file() { + Ok(file) => { + assert_eq!(directory_of(&scratch), identity(expected)); + // The first file, which opened the directory, is one of + // the files of the manifest's own as well, and stays + // one, and open, once it is given back. + let first = made(); + assert_eq!(first.len(), 1); + assert!(scratch.own_files().contains(&first[0].status).unwrap()); + scratch.take_back(file); + let left = made(); + assert_eq!(left.len(), 1); + assert_eq!((left[0].inode, left[0].size), (first[0].inode, first[0].size)); + assert!(scratch.own_files().contains(&left[0].status).unwrap()); + } + Err(e) => { + assert_eq!(expected, Path::new(NONE), "{}", e); + let e = Error::from(e); + assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::ENOENT)); + let said = match env::var_os(Scratch::TMPDIR).filter(|tmpdir| !tmpdir.is_empty()) { + Some(tmpdir) => format!( + "the directory TMPDIR names, '{}', cannot be used", + Path::new(&tmpdir).display() + ), + None => "TMPDIR names no directory, and '/var/tmp' cannot be used".to_string(), + }; + let enoent = io::Error::from_raw_os_error(libc::ENOENT); + assert_eq!(e.to_string(), format!("{}: {}", said, enoent)); + assert!(scratch.directory.is_none()); + } + } + return; + } + let tmp = TempDir::new("scratch-environment"); + let run = |tmpdir: Option<&Path>, expected: &Path| { + let mut test = Command::new(env::current_exe().unwrap()); + test.args(["--exact", "scratch::tests::temporary_directory_of_the_environment"]); + test.env(EXPECTED, expected); + match tmpdir { + Some(tmpdir) => test.env(Scratch::TMPDIR, tmpdir), + None => test.env_remove(Scratch::TMPDIR), + }; + let output = test.output().unwrap(); + assert!(output.status.success(), "{:?} {:?}: {:?}", tmpdir, expected, output); + }; + run(Some(&tmp.0), &tmp.0); + run(Some(&tmp.0.join("missing")), Path::new(NONE)); + // Without the variable, and with an empty one, /var/tmp, where + // there is one that takes files. + let var_tmp = Path::new(Scratch::VAR_TMP); + let expected = match ScratchFile::open_directory(var_tmp) { + Ok(directory) if ScratchFile::create_in(directory.as_fd(), &mut OwnFiles::default()).is_ok() => var_tmp, + Ok(_) => { + eprintln!("skipping /var/tmp, which takes no files"); + return; + } + Err(_) => Path::new(NONE), + }; + run(None, expected); + run(Some(Path::new("")), expected); + } + + /// The scratch space of a manifest can go to another thread. + #[test] + fn send() { + fn send() {} + send::(); + } +} diff --git a/src/uapi16/sequence.rs b/src/uapi16/sequence.rs index 32b9c81..48a3aad 100644 --- a/src/uapi16/sequence.rs +++ b/src/uapi16/sequence.rs @@ -53,21 +53,30 @@ impl SequenceCheck { /// features the manifest records. The error names the first field of a /// feature the manifest does not record. pub(crate) fn check_root_fields(&self, root: &RootObject) -> Result<(), Error> { + // As for a file object, see SequenceCheck::check_fields(). + if self.features.contains(root.stated_features()) { + return Ok(()); + } self.check_features_listed(root.feature_fields(), Subject::root()) } - /// Checks the fields of `object`, the one of the record with the number - /// `record_number`, against what the manifest records: they have to be - /// of features the manifest records, the fields a reader filled in - /// aside, a symbolic link has its target in a manifest that records - /// them, and the flags of a partition agree, see - /// [`FileObject::check_partition_flags`]. The error names the first - /// field of a feature the manifest does not record. - pub(crate) fn check_fields(&self, object: &FileObject, record_number: u64) -> Result<(), Error> { - let subject = Subject::new(object, record_number); - self.check_features_listed(object.feature_fields(), subject)?; - let target = object.contents.iter().any(|contents| contents.literal().is_some()); - if self.features.contains(Features::SYMLINK) && object.inode_type == InodeType::Symlink && !target { + /// Checks the fields of `object`, which `subject` names, against what + /// the manifest records: they have to be of features the manifest + /// records, the fields a reader filled in aside, a symbolic link has + /// its target in a manifest that records them, and the flags of a + /// partition agree, see [`FileObject::check_partition_flags`]. The + /// error names the first field of a feature the manifest does not + /// record. + pub(crate) fn check_fields(&self, object: &FileObject, subject: Subject<'_>) -> Result<(), Error> { + // An object keeps the features it states, so they are held against + // those of the manifest all at once. Its fields are gone through + // only to name the first one of a feature the manifest does not + // record. + if !self.features.contains(object.stated_features()) { + self.check_features_listed(object.feature_fields(), subject)?; + } + let target = object.contents().iter().any(|contents| contents.literal().is_some()); + if self.features.contains(Features::SYMLINK) && object.inode_type() == InodeType::Symlink && !target { return Err(Error::manifest( Problem::NoTarget, format!( @@ -107,8 +116,8 @@ impl SequenceCheck { /// `record_number`, which comes after the root file object, may come /// next, and makes it the last one. pub(crate) fn admit(&mut self, object: &FileObject, record_number: u64) -> Result<(), Error> { - let name = object.name.as_str(); - if object.name.is_root() { + let name = object.name().as_str(); + if object.name().is_root() { return Ok(()); } let subject = Subject::new(object, record_number); @@ -117,7 +126,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().as_str(); + let directory = object.name().parent().unwrap_or_default().as_str(); return Err(Error::manifest( Problem::Misplaced, format!( @@ -148,7 +157,7 @@ impl SequenceCheck { } self.last.clear(); self.last.push_str(name); - self.last_type = object.inode_type; + self.last_type = object.inode_type(); Ok(()) } } @@ -157,7 +166,6 @@ impl SequenceCheck { mod tests { use super::*; use crate::error::ErrorKind; - use crate::object::{DosFlags, InodeFlags}; use crate::testing::full_tree_names; use crate::{ContentsObject, ContentsSource, FatSerial, Mode, Name, NameBuf, Uuid}; use std::num::NonZeroU64; @@ -167,7 +175,7 @@ mod tests { fn object(name: &str, inode_type: InodeType) -> FileObject { let mut object = FileObject::new(NameBuf::new(name).unwrap()); - object.inode_type = inode_type; + object.set_inode_type(inode_type); object } @@ -306,11 +314,11 @@ mod tests { fn fields() { let check = SequenceCheck::new(Features::SIZE | Features::SYMLINK, None); let mut file = object("f", InodeType::Regular); - file.size = Some(1); - assert!(check.check_fields(&file, 1).is_ok()); + file.set_size(Some(1)); + assert!(check.check_fields(&file, Subject::new(&file, 1)).is_ok()); // A field of a feature the manifest does not record is named. - file.inode.mtime_nsec = Some(1); - let e = check.check_fields(&file, 1).unwrap_err(); + file.inode_mut().set_mtime_nsec(Some(1)); + let e = check.check_fields(&file, Subject::new(&file, 1)).unwrap_err(); assert_eq!( (e.kind(), e.field()), (ErrorKind::Manifest(Problem::UnlistedFeature), Some(Field::MTimeNSec)) @@ -325,53 +333,53 @@ mod tests { let cases: [(InodeType, Give, Field); 8] = [ ( InodeType::Regular, - |o| o.inode.mode = Some(Mode::new(0o644).unwrap()), + |o| o.inode_mut().set_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), + (InodeType::CharDevice, |o| o.set_major(Some(1)), Field::Major), + (InodeType::BlockDevice, |o| o.set_minor(Some(1)), Field::Minor), ( InodeType::Regular, - |o| o.inode.user_xattrs = Some(Box::default()), + |o| o.inode_mut().set_user_xattrs(Some(Default::default())), Field::ExtendedAttributes, ), ( InodeType::Regular, - |o| o.dos_flags.put(DosFlags::HIDDEN, Some(false)), + |o| o.set_flag_hidden(Some(false)), Field::FlagHidden, ), ( InodeType::Regular, - |o| o.inode_token = NonZeroU64::new(1), + |o| o.set_inode_token(NonZeroU64::new(1)), Field::InodeToken, ), ( InodeType::Directory, - |o| o.inode.group_name = Some("g".into()), + |o| o.inode_mut().set_group_name(Some("g".into())), Field::GroupName, ), ( InodeType::Symlink, - |o| o.contents = vec![ContentsObject::new(ContentsSource::Literal(b"t".to_vec()))], + |o| o.put_contents(vec![ContentsObject::new(ContentsSource::Literal(b"t".to_vec()))]), Field::Contents, ), ]; for (inode_type, set, field) in cases { let mut o = object("o", inode_type); set(&mut o); - let e = none.check_fields(&o, 1).unwrap_err(); + let e = none.check_fields(&o, Subject::new(&o, 1)).unwrap_err(); assert_eq!(e.field(), Some(field), "{:?}", o); } let link = object("l", InodeType::Symlink); - let e = check.check_fields(&link, 2).unwrap_err(); + let e = check.check_fields(&link, Subject::new(&link, 2)).unwrap_err(); assert_eq!(e.kind(), ErrorKind::Manifest(Problem::NoTarget)); assert!(e.to_string().starts_with("manifest object 2 (l): "), "{}", e); let quiet = SequenceCheck::new(Features::SIZE, None); - assert!(quiet.check_fields(&link, 2).is_ok()); + assert!(quiet.check_fields(&link, Subject::new(&link, 2)).is_ok()); // The root file object has the fields of features too. let mut root = RootObject::default(); assert!(none.check_root_fields(&root).is_ok()); - root.inode.uid = Some(0); + root.inode.set_uid(Some(0)); let e = none.check_root_fields(&root).unwrap_err(); assert_eq!( (e.kind(), e.field()), @@ -393,48 +401,40 @@ mod tests { let none = SequenceCheck::new(Features::NONE, None); let mut object = object("o", InodeType::Regular); let fields: [(Give, Field); 14] = [ + (|o| o.inode_mut().set_flag_no_dump(Some(true)), Field::FlagNoDump), ( - |o| o.inode.flags.put(InodeFlags::NO_DUMP, Some(true)), - Field::FlagNoDump, - ), - ( - |o| o.inode.flags.put(InodeFlags::APPEND_ONLY, Some(false)), + |o| o.inode_mut().set_flag_append_only(Some(false)), Field::FlagAppendOnly, ), - (|o| o.inode.user_name = Some("u".into()), Field::UserName), - (|o| o.inode.read_only = Some(true), Field::ReadOnly), - (|o| o.inode.mode = Some(Mode::new(0o444).unwrap()), Field::Mode), + (|o| o.inode_mut().set_user_name(Some("u".into())), Field::UserName), + (|o| o.inode_mut().set_read_only(Some(true)), Field::ReadOnly), + (|o| o.inode_mut().set_mode(Some(Mode::new(0o444).unwrap())), Field::Mode), ( - |o| o.inode.user_xattrs = Some(Box::default()), + |o| o.inode_mut().set_user_xattrs(Some(Default::default())), Field::ExtendedAttributes, ), - (|o| o.dos_flags.put(DosFlags::SYSTEM, Some(true)), Field::FlagSystem), - (|o| o.dos_flags.put(DosFlags::ARCHIVE, Some(false)), Field::FlagArchive), - (|o| o.size = Some(1), Field::Size), - (|o| o.major = Some(1), Field::Major), - (|o| o.inode_token = NonZeroU64::new(1), Field::InodeToken), - ( - |o| o.gpt.get_or_insert_with(Box::default).label = Some("l".into()), - Field::GptLabel, - ), - ( - |o| o.gpt.get_or_insert_with(Box::default).flags = Some(0), - Field::GptFlags, - ), + (|o| o.set_flag_system(Some(true)), Field::FlagSystem), + (|o| o.set_flag_archive(Some(false)), Field::FlagArchive), + (|o| o.set_size(Some(1)), Field::Size), + (|o| o.set_major(Some(1)), Field::Major), + (|o| o.set_inode_token(NonZeroU64::new(1)), Field::InodeToken), + (|o| o.gpt_or_default().label = Some("l".into()), Field::GptLabel), + (|o| o.gpt_or_default().flags = Some(0), Field::GptFlags), ( - |o| o.gpt.get_or_insert_with(Box::default).grow_file_system = Some(false), + |o| o.gpt_or_default().grow_file_system = Some(false), Field::GptFlagGrowFileSystem, ), ]; for (give, field) in fields { give(&mut object); - assert_eq!(none.check_fields(&object, 1).unwrap_err().field(), Some(field)); + let subject = Subject::new(&object, 1); + assert_eq!(none.check_fields(&object, subject).unwrap_err().field(), Some(field)); } let mut root = RootObject::default(); let fields: [(Give, Field); 6] = [ - (|r| r.inode.flags.put(InodeFlags::NO_COW, Some(true)), Field::FlagNoCow), - (|r| r.inode.uid = Some(0), Field::Uid), - (|r| r.inode.read_only = Some(false), Field::ReadOnly), + (|r| r.inode.set_flag_no_cow(Some(true)), Field::FlagNoCow), + (|r| r.inode.set_uid(Some(0)), Field::Uid), + (|r| r.inode.set_read_only(Some(false)), Field::ReadOnly), ( |r| r.gpt_disk_uuid = Some(Uuid::new([1; Uuid::SIZE])), Field::GptDiskUuid, diff --git a/src/uapi16/sort.rs b/src/uapi16/sort.rs new file mode 100644 index 0000000..51ee3c7 --- /dev/null +++ b/src/uapi16/sort.rs @@ -0,0 +1,2267 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The sort of the manifest builder: records that come in any order go +//! out in the order of their keys, and records with the same key in the +//! order they came. +//! +//! It is an external merge sort. The records gather in memory, up to a +//! fixed size. Where a manifest is complete before that, they are sorted +//! there and nothing touches a disk. Otherwise they are sorted and written +//! to a scratch file as a run, and the next ones gather. In the end the +//! runs and what is still in memory are merged: the next record is always +//! the smallest of those the runs have next, which a heap of the runs +//! finds. Each run is read through a buffer of its own. +//! +//! A merge takes so many runs at once that their buffers fit into the +//! memory the records took. A sort that wrote more runs merges them in +//! passes first: runs that follow each other become one longer run, which +//! is appended to the scratch file and stands where they stood. A pass +//! does not merge every run. It merges just enough of them for the merges +//! after it to be full ones, in a smaller merge first and then in full +//! ones, and leaves the other runs as they are. So the memory is the fixed +//! size and as much again for the buffers, however many records there are. +//! A record is written once and read once, and once more for every pass it +//! is in. +//! +//! Records with the same key stay in the order they came through all of +//! this: a merge takes the record of the earlier run first, a pass merges +//! only runs that follow each other, and what was in memory at the end +//! came last. +//! +//! What a merge has read of a run is not read again, and its room is given +//! back to the file system while the merge goes on, as holes in the scratch +//! file. So the data of the scratch file takes about the room of the +//! records also while a pass writes them again, and it gives that room back +//! while the manifest is written. A file system can take more room for the +//! file than its data takes: xfs takes up to 8 GiB past the end of a file +//! that grows at its end, for what it expects to be written there. Once the +//! passes are over nothing is, and a hole past the end of the file gives +//! that room back before the last merge. A file system that cannot punch +//! holes keeps the room until the file is closed, and what every pass +//! writes comes on top of it: the room of the records once more for every +//! pass they are in. +//! +//! Nothing here does an unbounded amount of work at once. Writing a run can +//! be done in parts, and so can what is to do before the first record goes +//! out. Then the merge hands out one record at a time. The records in +//! memory are sorted in one go, before they are written as a run and at the +//! end. That takes longer than a part of a run, but there are never more of +//! them than the fixed size of memory holds and the one record that went +//! over it. And a step of a merge reads more than its budget where the +//! buffers of its runs run low, a buffer of every run at most, see +//! [`Merge::prepare`]. + +use std::io; +use std::mem; +use std::num::NonZeroU64; +use std::ops::Range; + +use crate::scratch::Scratch; +use crate::sys::ScratchFile; +use crate::{Name, MAX_RECORD_SIZE}; + +/// How many bytes of records gather in memory before they are written out +/// as a run, with what says where each starts. +const MEMORY_LIMIT: usize = 32 * 1024 * 1024; +/// How many bytes of a run memory holds while runs are merged. +const RUN_BUFFER: usize = 64 * 1024; +/// How many runs are merged at once at most: as many as have their buffers +/// in the memory the records take. +const MOST_RUNS: usize = MEMORY_LIMIT / RUN_BUFFER; +/// How many runs a merge takes at least: with fewer it leaves as many runs +/// as it found. +const FEWEST_RUNS: usize = 2; +/// How many bytes of a run are put together before they are written. +const WRITE_BUFFER: usize = 256 * 1024; +/// How many bytes of a run a merge reads before it gives their room back to +/// the file system. A hole is a system call and work for the file system, +/// and until it is punched the room of what was read is held back: by a +/// merge about that much for each of its runs. +const HOLE_SIZE: u64 = 1024 * 1024; +/// What memory is first taken for records. +const FIRST_MEMORY: usize = 64 * 1024; +/// The size of what a record starts with: the length of its body in four +/// bytes and that of its key in two. +const HEADER_SIZE: usize = 6; +/// The longest key: a name. +const MAX_KEY: usize = Name::MAX_LEN; +/// The longest body: twice what a record of a manifest may take. A file +/// object a writer takes is shorter than that, see the module record: what +/// it has for a field is never a third longer here than in the record of +/// the manifest, but for the fixed part of a contents object, and an +/// object has few of those. +pub(crate) const MAX_BODY: usize = 2 * MAX_RECORD_SIZE; + +/// An error for a scratch file that does not hold what was written to it. +fn damaged() -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, "a scratch file of the sort was changed") +} + +/// The lengths of the body and of the key of the record that starts with +/// `header`. +fn lengths(header: [u8; HEADER_SIZE]) -> (usize, usize) { + let [b0, b1, b2, b3, k0, k1] = header; + ( + u32::from_le_bytes([b0, b1, b2, b3]) as usize, + usize::from(u16::from_le_bytes([k0, k1])), + ) +} + +/// The key and the body of the record that starts at `start` in `records`, +/// which this module wrote there. +fn record_at(records: &[u8], start: u32) -> (&[u8], &[u8]) { + let record = &records[start as usize..]; + let (header, rest) = record.split_first_chunk().expect("a record has its header"); + let (body, key) = lengths(*header); + (&rest[..key], &rest[key..key + body]) +} + +/// A run: records in order, from `start` to `end` in the scratch file. +#[derive(Clone, Copy, Debug)] +struct Run { + start: u64, + end: u64, +} + +/// A run that is being written. +#[derive(Debug)] +struct Spill { + /// How many of the records, in order, are in the file. + written: usize, + /// Where the next ones go in the file. + at: u64, + /// The records that are written next. + pending: Vec, +} + +/// How much memory a sort takes, and how it merges. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Limits { + /// How many bytes of records gather in memory. + pub(crate) memory: usize, + /// How many bytes of each run memory holds in a merge. + pub(crate) run_buffer: usize, + /// How many bytes of a run are written at a time. + pub(crate) write_buffer: usize, + /// How many runs are merged at once at most. + pub(crate) runs: usize, + /// How many bytes of a run a merge reads before it gives their room + /// back to the file system. + pub(crate) hole: u64, +} + +impl Limits { + /// How many bytes of a run a merge holds in memory: what the limits + /// say, and the header and the key of a record at least. + fn buffer_size(&self) -> usize { + self.run_buffer.max(HEADER_SIZE + MAX_KEY) + } + + /// How many runs a merge takes at once at most: what the limits say, + /// and as many as a merge takes at least. + fn most_runs(&self) -> usize { + self.runs.max(FEWEST_RUNS) + } +} + +/// Takes records in any order, see the documentation of this module. +#[derive(Debug)] +pub(crate) struct Sorter { + /// The records that are not in a run yet, one behind the other: each + /// with its header, its key and its body. + records: Vec, + /// Where each of them starts. + starts: Vec, + /// The scratch file of the runs, once there is a run. + file: Option, + /// The runs, in the order they were written. + runs: Vec, + spill: Option, + limits: Limits, +} + +impl Sorter { + /// A sort without records, which takes no room yet. + pub(crate) fn new() -> Sorter { + Sorter::with_limits(Limits { + memory: MEMORY_LIMIT, + run_buffer: RUN_BUFFER, + write_buffer: WRITE_BUFFER, + runs: MOST_RUNS, + hole: HOLE_SIZE, + }) + } + + /// A sort that takes as much memory as `limits` says. + pub(crate) fn with_limits(limits: Limits) -> Sorter { + Sorter { + records: Vec::new(), + starts: Vec::new(), + file: None, + runs: Vec::new(), + spill: None, + limits, + } + } + + /// Sorts where the records start by their keys. Records with the same + /// key stay in the order they came, which is that of where they + /// start. + fn sort(records: &[u8], starts: &mut [u32]) { + starts.sort_unstable_by(|&one, &other| { + let (key, other_key) = (record_at(records, one).0, record_at(records, other).0); + key.cmp(other_key).then(one.cmp(&other)) + }); + } + + /// Whether the records in memory have reached their limit. + fn is_full(&self) -> bool { + self.records.len() + size_of_val(&self.starts[..]) >= self.limits.memory + } + + /// Does a part of what is to do before another record is taken, and + /// returns whether it is done: once the records in memory have reached + /// their limit, they are sorted and written to the scratch file as a + /// run. `budget` is about how many bytes are written for it now: the + /// records are sorted in one go before the first of them are written, + /// see the documentation of this module. The scratch file comes from + /// `scratch` when the first run is written. + /// + /// A caller that works in steps calls this until it returns true + /// before it pushes a record. [`Sorter::push`] does all that is left of + /// it at once. A scratch file that cannot be made or written fails + /// this and leaves the sort as it was. + pub(crate) fn make_room(&mut self, scratch: &mut Scratch, budget: u64) -> io::Result { + if self.spill.is_none() { + if !self.is_full() { + return Ok(true); + } + // Without a budget nothing is done, also not the sorting. + if budget == 0 { + return Ok(false); + } + if self.file.is_none() { + self.file = Some(scratch.file()?); + } + Sorter::sort(&self.records, &mut self.starts); + self.spill = Some(Spill { + written: 0, + at: self.runs.last().map_or(0, |run| run.end), + pending: Vec::with_capacity(self.limits.write_buffer), + }); + } + let mut left = budget; + self.write_run(&mut left) + } + + /// Goes on writing the run that is being written until it is written to + /// its end or `left` is used up, and returns whether it is written. + /// `left` is how many bytes may still be written. + fn write_run(&mut self, left: &mut u64) -> io::Result { + let (Some(spill), Some(file)) = (&mut self.spill, &self.file) else { + return Err(damaged()); + }; + while spill.written < self.starts.len() { + if *left == 0 { + return Ok(false); + } + // Something is always written, however small the budget. + let most = usize::try_from(*left) + .unwrap_or(usize::MAX) + .min(self.limits.write_buffer); + spill.pending.clear(); + let mut gathered = spill.written; + while gathered < self.starts.len() && (spill.pending.len() < most || gathered == spill.written) { + let (key, body) = record_at(&self.records, self.starts[gathered]); + let start = self.starts[gathered] as usize; + spill + .pending + .extend_from_slice(&self.records[start..start + HEADER_SIZE + key.len() + body.len()]); + gathered += 1; + } + file.write_all_at(&spill.pending, spill.at)?; + spill.at += spill.pending.len() as u64; + spill.written = gathered; + *left = left.saturating_sub(spill.pending.len() as u64); + } + self.runs.push(Run { + start: self.runs.last().map_or(0, |run| run.end), + end: spill.at, + }); + self.spill = None; + self.records.clear(); + self.records.shrink_to(self.limits.memory); + self.starts.clear(); + Ok(true) + } + + /// Takes the record with the key `key` and the body `body`. The key is + /// at most as long as a name and the body at most [`MAX_BODY`] bytes. + /// Longer ones are refused as invalid input. + pub(crate) fn push(&mut self, scratch: &mut Scratch, key: &[u8], body: &[u8]) -> io::Result<()> { + let (Ok(key_len), Ok(body_len)) = (u16::try_from(key.len()), u32::try_from(body.len())) else { + return Err(io::ErrorKind::InvalidInput.into()); + }; + if key.len() > MAX_KEY || body.len() > MAX_BODY { + return Err(io::ErrorKind::InvalidInput.into()); + } + while !self.make_room(scratch, u64::MAX)? {} + let start = u32::try_from(self.records.len()).map_err(|_| io::Error::from(io::ErrorKind::OutOfMemory))?; + // The memory for the records doubles up to its limit, and takes + // what the one record needs that goes over it. + let size = HEADER_SIZE + key.len() + body.len(); + if self.records.capacity() - self.records.len() < size { + let doubled = (self.records.capacity() * 2).clamp(FIRST_MEMORY, self.limits.memory.max(FIRST_MEMORY)); + let capacity = doubled.max(self.records.len() + size); + self.records.reserve_exact(capacity - self.records.len()); + } + self.records.extend_from_slice(&body_len.to_le_bytes()); + self.records.extend_from_slice(&key_len.to_le_bytes()); + self.records.extend_from_slice(key); + self.records.extend_from_slice(body); + self.starts.push(start); + Ok(()) + } + + /// Ends the sort: no more records come, and those that came go out + /// through the merge this returns. Nothing is done for that yet. A run + /// that is half written is written to its end, what is still in memory + /// is sorted there, and the runs are read by [`Merge::prepare`]. + pub(crate) fn finish(self) -> Merge { + Merge { + limits: self.limits, + sorter: Some(self), + file: None, + passes: None, + last: RunMerge::default(), + memory: InMemory::default(), + taken: None, + body: Vec::new(), + failed: false, + } + } +} + +/// The scratch file of the runs while they are merged. What a merge has +/// read of a run is not read again, and its room is given back to the file +/// system where the file system can do that. +#[derive(Debug)] +struct RunFile { + scratch: ScratchFile, + /// The size of a block of the file, while holes are punched into it. + /// There is none where the file system does not say one, and from the + /// first hole on that could not be punched. + block: Option, + /// How many bytes of a run are read before their room is given back. + hole: u64, +} + +impl RunFile { + /// How far past its end a file system can have taken room for a file + /// that grows at its end, for what it expects to be written there: xfs + /// takes up to 2^21 blocks, 8 GiB with blocks of 4 KiB and 128 GiB with + /// the largest ones. + const AHEAD: u64 = 128 * 1024 * 1024 * 1024; + + /// The scratch file `scratch`, whose runs are merged as `limits` says. + fn new(scratch: ScratchFile, limits: &Limits) -> RunFile { + RunFile { + block: scratch.block_size().ok().and_then(NonZeroU64::new), + scratch, + hole: limits.hole, + } + } + + /// Gives the room of a run back as far as the run was read, and + /// returns up to where it is given back then. `released` is up to + /// where it was given back before, which is where the run starts at + /// first, `read` up to where the run was read, and `ended` whether that + /// is all of it. + /// + /// Only whole blocks are given back: of a block that is not all in the + /// hole a file system merely writes over the part that is, and what a + /// run shares a block with is another run. They are given back once + /// they are as many bytes as a hole is to have, or once the run ended. + /// + /// A hole that cannot be punched is no error, and it is the last one + /// that is tried: the file system cannot punch holes, or cannot punch + /// this one, and the room stays taken until the file is closed. + fn release(&mut self, released: u64, read: u64, ended: bool) -> u64 { + let Some(block) = self.block else { + return released; + }; + let Some(start) = released.checked_next_multiple_of(block.get()) else { + return released; + }; + let end = read - read % block; + if end <= start || (end - start < self.hole && !ended) { + return released; + } + match self.scratch.punch_hole(start, end - start) { + Ok(()) => end, + Err(_) => { + self.block = None; + released + } + } + } + + /// Gives back the room the file system took for the file past `end`, + /// where the runs end, for what it expected to be written there. Once + /// the passes are over nothing is. That is a hole past the end of the + /// file, which stays as long as it is, and it is tried as the holes of + /// the runs are, see [`RunFile::release`]. + fn release_past(&mut self, end: u64) { + let Some(block) = self.block else { + return; + }; + let Some(start) = end.checked_next_multiple_of(block.get()) else { + return; + }; + if self.scratch.punch_hole(start, RunFile::AHEAD).is_err() { + self.block = None; + } + } +} + +/// The passes of a sort that wrote more runs than a merge takes at once, +/// see the documentation of this module. A pass goes over the runs in the +/// order of their records and merges runs that follow each other into one +/// run each, from the first run on, until as many runs are left as it is +/// to leave. The runs behind those stay as they are. +#[derive(Debug)] +struct Passes { + /// The runs in the order of their records. While a pass is under way, + /// the runs it made come first, up to `made`, and the runs it did not + /// get to yet start at `next`. Those in between were merged. + runs: Vec, + made: usize, + next: usize, + /// How many runs the pass that is under way leaves. + target: usize, + /// How many runs a merge takes at once at most. + most: usize, + /// The merge that is under way. + merge: Option, + /// Where the next run goes in the scratch file: behind all the others. + end: u64, +} + +impl Passes { + /// The passes over the runs `runs`, which follow each other in the + /// scratch file, of a sort that merges as `limits` says. There are none + /// where the runs are few enough for one merge. + fn new(runs: Vec, limits: &Limits) -> Passes { + Passes { + // No pass is under way: the first one begins with the first + // merge that is asked for. + target: runs.len(), + end: runs.last().map_or(0, |run| run.end), + runs, + made: 0, + next: 0, + most: limits.most_runs(), + merge: None, + } + } + + /// How many runs there are: those the pass that is under way made, and + /// those it did not get to yet. + fn count(&self) -> usize { + self.made + (self.runs.len() - self.next) + } + + /// How many runs a pass leaves that finds `runs` runs, which are more + /// than `most`, the most a merge takes at once: the largest power of + /// `most` below `runs`. Then every merge after the pass is a full one: + /// the last merge of `most` runs, the `most` merges of a pass before + /// it, and so on. + fn target(runs: usize, most: usize) -> usize { + let mut target = most; + while let Some(larger) = target.checked_mul(most).filter(|&larger| larger < runs) { + target = larger; + } + target + } + + /// Which of the runs the next merge takes, or nothing once the runs + /// are few enough for one merge. + /// + /// A merge of n runs leaves n - 1 runs fewer. So a pass gets to the + /// number of runs it leaves in full merges, but for what the runs it + /// has to lose are not a multiple of: a smaller merge loses those, and + /// it comes first. + fn next_merge(&mut self) -> Option> { + if self.count() == self.target { + // The pass is over. The runs it made stand where those stood + // that they were made of. + self.runs.drain(self.made..self.next); + (self.made, self.next) = (0, 0); + if self.runs.len() <= self.most { + return None; + } + self.target = Passes::target(self.runs.len(), self.most); + } + let over = self.count() - self.target; + let size = match over % (self.most - 1) { + 0 => self.most, + rest => rest + 1, + }; + let merged = self.next..self.next + size; + self.next = merged.end; + Some(merged) + } + + /// Takes the run `run`, which a merge made and wrote behind all the + /// others, in place of the runs that merge took. + fn put(&mut self, run: Run) { + self.runs[self.made] = run; + self.made += 1; + self.end = run.end; + } + + /// Goes on with the passes until they are over or `left` is used up, + /// and returns the runs that are left once they are over: few enough + /// for one merge, in the order of their records. `left` is how many + /// bytes may still be read from the runs. + fn advance(&mut self, file: &mut Option, limits: &Limits, left: &mut u64) -> io::Result>> { + loop { + let mut merge = match self.merge.take() { + Some(merge) => merge, + None => match self.next_merge() { + Some(merged) => PassMerge::new(&self.runs[merged], self.end, limits), + None => return Ok(Some(mem::take(&mut self.runs))), + }, + }; + match merge.advance(file, limits, left)? { + Some(run) => self.put(run), + None => { + self.merge = Some(merge); + return Ok(None); + } + } + } + } +} + +/// A merge of a pass: runs that follow each other become one run, which is +/// written to the scratch file behind all the others. +#[derive(Debug)] +struct PassMerge { + runs: RunMerge, + /// The run that is written, as far as it is written. + made: Run, + /// The records that are written next. + pending: Vec, +} + +impl PassMerge { + /// A merge of the runs `runs` into a run that starts at `start` in the + /// scratch file. + fn new(runs: &[Run], start: u64, limits: &Limits) -> PassMerge { + PassMerge { + runs: RunMerge::new(runs, limits), + made: Run { start, end: start }, + pending: Vec::with_capacity(limits.write_buffer), + } + } + + /// Goes on with the merge until all records are in the new run or + /// `left` is used up, and returns the run once they are. `left` is how + /// many bytes may still be read from the runs. Each record is read and + /// written once. + fn advance(&mut self, file: &mut Option, limits: &Limits, left: &mut u64) -> io::Result> { + if !self.runs.open(file, left)? { + return Ok(None); + } + let file = file.as_mut().ok_or_else(damaged)?; + while *left > 0 { + let most = usize::try_from(*left).unwrap_or(usize::MAX).min(limits.write_buffer); + self.pending.clear(); + // Something is always written, however small the budget. + while self.pending.len() < most || self.pending.is_empty() { + let Some(run) = self.runs.top() else { + break; + }; + self.runs.readers[run].copy_record(file, &mut self.pending)?; + self.runs.advance_top(file)?; + } + // No record was left. + if self.pending.is_empty() { + return Ok(Some(self.made)); + } + file.scratch.write_all_at(&self.pending, self.made.end)?; + self.made.end += self.pending.len() as u64; + *left = left.saturating_sub(self.pending.len() as u64); + } + Ok(None) + } +} + +/// A run as a merge reads it: from front to back, a buffer at a time. +#[derive(Debug)] +struct RunReader { + /// Where the bytes behind those of the buffer are in the file. + at: u64, + /// Where the run ends in the file. + end: u64, + /// Up to where the room of the run was given back to the file system. + released: u64, + /// The bytes of the run that were read and not used yet, from `read` + /// on. + buffer: Vec, + read: usize, + /// How many bytes the buffer holds at most. + size: usize, + /// The header and the key of the record the run has next. + header: [u8; HEADER_SIZE], + key: Vec, + /// The length of its body, which comes next in the run. + body: usize, +} + +impl RunReader { + /// What reads the run `run` through a buffer of `size` bytes. + fn new(run: Run, size: usize) -> RunReader { + RunReader { + at: run.start, + end: run.end, + released: run.start, + buffer: Vec::new(), + read: 0, + size, + header: [0; HEADER_SIZE], + key: Vec::new(), + body: 0, + } + } + + /// How many bytes of the run are not used yet. + fn left(&self) -> u64 { + (self.buffer.len() - self.read) as u64 + (self.end - self.at) + } + + /// Gives the room of what was read of the run back to the file system, + /// see [`RunFile::release`]. All that was read is in memory or went + /// out. + fn release(&mut self, file: &mut RunFile) { + self.released = file.release(self.released, self.at, self.at == self.end); + } + + /// Makes the buffer hold the next `size` bytes of the run, which is at + /// most what a buffer holds. A run that ends before that was changed. + fn fill(&mut self, file: &mut RunFile, size: usize) -> io::Result<()> { + if self.buffer.len() - self.read >= size { + return Ok(()); + } + if self.left() < size as u64 { + return Err(damaged()); + } + self.buffer.drain(..self.read); + self.read = 0; + let have = self.buffer.len(); + // As much as the buffer holds, or what is left of the run. + let more = (self.size - have).min(usize::try_from(self.end - self.at).unwrap_or(usize::MAX)); + self.buffer.resize(have + more, 0); + file.scratch.read_exact_at(&mut self.buffer[have..], self.at)?; + self.at += more as u64; + self.release(file); + Ok(()) + } + + /// Reads the header and the key of the next record, and returns + /// whether there is one. + fn next_key(&mut self, file: &mut RunFile) -> io::Result { + if self.left() == 0 { + return Ok(false); + } + self.fill(file, HEADER_SIZE)?; + let header = self.buffer[self.read..].first_chunk().ok_or_else(damaged)?; + let (body, key) = lengths(*header); + if key > MAX_KEY || body > MAX_BODY { + return Err(damaged()); + } + self.header = *header; + self.read += HEADER_SIZE; + self.fill(file, key)?; + self.key.clear(); + self.key.extend_from_slice(&self.buffer[self.read..self.read + key]); + self.read += key; + if self.left() < body as u64 { + return Err(damaged()); + } + self.body = body; + Ok(true) + } + + /// Appends the body of the record whose key was read to `records`. + /// What of it the buffer does not hold is read from the file directly, + /// so the buffer never grows for a large record. + fn append_body(&mut self, file: &mut RunFile, records: &mut Vec) -> io::Result<()> { + let buffered = (self.buffer.len() - self.read).min(self.body); + records.extend_from_slice(&self.buffer[self.read..self.read + buffered]); + self.read += buffered; + let rest = self.body - buffered; + if rest > 0 { + let have = records.len(); + records.resize(have + rest, 0); + file.scratch.read_exact_at(&mut records[have..], self.at)?; + self.at += rest as u64; + self.release(file); + } + self.body = 0; + Ok(()) + } + + /// Appends the record whose key was read to `records` as the run has + /// it: its header, its key and its body. + fn copy_record(&mut self, file: &mut RunFile, records: &mut Vec) -> io::Result<()> { + records.extend_from_slice(&self.header); + records.extend_from_slice(&self.key); + self.append_body(file, records) + } +} + +/// The runs a merge reads at once, and which of them has the record that +/// goes out next. +#[derive(Debug, Default)] +struct RunMerge { + /// The runs in the order of their records. + readers: Vec, + /// The runs that have a record, as a heap: the one whose next record + /// goes out first is at the top. + heap: Vec, + /// How many of the runs were looked at for their first record. The + /// heap is in order once all of them were. + opened: usize, +} + +impl RunMerge { + /// A merge of the runs `runs`, each read as `limits` says. + fn new(runs: &[Run], limits: &Limits) -> RunMerge { + let size = limits.buffer_size(); + RunMerge { + readers: runs.iter().map(|run| RunReader::new(*run, size)).collect(), + heap: Vec::new(), + opened: 0, + } + } + + /// Whether the next record of the run `one` goes out before that of + /// the run `other`: its key is smaller, or it is the same and the run + /// is the earlier one. + fn before(&self, one: usize, other: usize) -> bool { + let (key, other_key) = (&self.readers[one].key, &self.readers[other].key); + key.cmp(other_key).then(one.cmp(&other)).is_lt() + } + + /// Moves the run at `at` in the heap down to where it belongs. + fn sift_down(&mut self, mut at: usize) { + loop { + let mut first = at; + for child in [2 * at + 1, 2 * at + 2] { + if child < self.heap.len() && self.before(self.heap[child], self.heap[first]) { + first = child; + } + } + if first == at { + break; + } + self.heap.swap(at, first); + at = first; + } + } + + /// Looks at the first record of the runs that were not looked at yet, + /// one run after the other until `left` is used up, and returns whether + /// all of them were looked at now. `left` is how many bytes may still + /// be read from the runs, and a run takes what its buffer holds of it. + fn open(&mut self, file: &mut Option, left: &mut u64) -> io::Result { + while self.opened < self.readers.len() { + if *left == 0 { + return Ok(false); + } + let reader = &mut self.readers[self.opened]; + if reader.next_key(file.as_mut().ok_or_else(damaged)?)? { + self.heap.push(self.opened); + } + // Every run counts, also one without a record. + *left = left.saturating_sub((reader.buffer.len() as u64).max(1)); + self.opened += 1; + if self.opened == self.readers.len() { + for at in (0..self.heap.len() / 2).rev() { + self.sift_down(at); + } + } + } + Ok(true) + } + + /// The run whose next record goes out next, or nothing once all went + /// out. The first record of every run was looked at. + fn top(&self) -> Option { + self.heap.first().copied() + } + + /// Moves the run at the top of the heap on to its next record: the one + /// it had went out. + fn advance_top(&mut self, file: &mut RunFile) -> io::Result<()> { + let Some(&run) = self.heap.first() else { + return Ok(()); + }; + if !self.readers[run].next_key(file)? { + self.heap.swap_remove(0); + } + self.sift_down(0); + Ok(()) + } +} + +/// The records that were still in memory when a sort ended, in order. +#[derive(Debug, Default)] +struct InMemory { + /// The records, one behind the other, and where each starts, in the + /// order of their keys. + records: Vec, + starts: Vec, + /// How many of them went out. + next: usize, +} + +impl InMemory { + /// The key and the body of the record that goes out next, if all did + /// not go out yet. + fn record(&self) -> Option<(&[u8], &[u8])> { + let start = self.starts.get(self.next)?; + Some(record_at(&self.records, *start)) + } +} + +/// Where the record came from that a merge handed out. +#[derive(Clone, Copy, Debug)] +enum Taken { + /// From the run at the top of the heap. + Run(usize), + /// From the records in memory. + Memory, +} + +/// The records of a sort in the order of their keys, one at a time, see +/// the documentation of this module. +#[derive(Debug)] +pub(crate) struct Merge { + /// The sort as it ended, until the run it was writing is written to its + /// end and what it has in memory is sorted. A sort whose run cannot be + /// written stays here as well, with the scratch file of the runs. + sorter: Option, + /// The scratch file of the runs, if the sort wrote one. + file: Option, + limits: Limits, + /// The passes over the runs, once the sort is wound up and until they + /// are over. + passes: Option, + /// The last merge: of the runs the passes left, which it has once they + /// are over. + last: RunMerge, + /// The records that were still in memory when the sort ended. They + /// came last, and the last merge takes them with the runs. + memory: InMemory, + /// Where the record came from that went out last. That one has to move + /// on before the next record goes out. + taken: Option, + /// The body of the record that went out last, if it came from a run. + body: Vec, + /// Whether a run could not be read or written. The merge fails from + /// there on: it does not know any more where it is in that run. + failed: bool, +} + +impl Merge { + /// Fails if the merge failed before. + fn check(&self) -> io::Result<()> { + if self.failed { + return Err(io::Error::other("the sort failed before")); + } + Ok(()) + } + + /// Winds the sort up, which ended with a run half written and with + /// records in memory, and returns whether that is done: the run is + /// written to its end, as far as `left` allows, and then the records in + /// memory are sorted, in one go. Without anything left nothing is done, + /// also not the sorting. + fn wind_up(&mut self, left: &mut u64) -> io::Result { + let Some(sorter) = &mut self.sorter else { + return Ok(true); + }; + // The sort stays where it is until it is wound up, also where its + // run can't be written: it has the scratch file of the runs. + if (sorter.spill.is_some() && !sorter.write_run(left)?) || *left == 0 { + return Ok(false); + } + Sorter::sort(&sorter.records, &mut sorter.starts); + self.file = sorter.file.take().map(|file| RunFile::new(file, &self.limits)); + self.passes = Some(Passes::new(mem::take(&mut sorter.runs), &self.limits)); + self.memory = InMemory { + records: mem::take(&mut sorter.records), + starts: mem::take(&mut sorter.starts), + next: 0, + }; + self.sorter = None; + Ok(true) + } + + /// Goes on with what is to do before the first record goes out until + /// it is done or `left` is used up, and returns whether it is done. + fn advance(&mut self, left: &mut u64) -> io::Result { + if !self.wind_up(left)? { + return Ok(false); + } + if let Some(passes) = &mut self.passes { + let Some(runs) = passes.advance(&mut self.file, &self.limits, left)? else { + return Ok(false); + }; + // Nothing is written to the scratch file from here on. + if let Some(file) = &mut self.file { + file.release_past(passes.end); + } + self.last = RunMerge::new(&runs, &self.limits); + self.passes = None; + } + self.last.open(&mut self.file, left) + } + + /// Does a part of what is to do before the first record goes out, and + /// returns whether it is done. First the sort is wound up: a run it + /// was still writing is written to its end, and what it has in memory + /// is sorted. Where the sort wrote more runs than a merge takes at + /// once, passes merge them into fewer and longer ones, see the + /// documentation of this module. Then the first record of every run + /// that is left is looked at. + /// + /// `budget` is about how many bytes of records are written to the run + /// and read from the runs for it now, each of which a pass writes + /// again. The records in memory are sorted in one go, whatever the + /// budget. A run whose buffer runs low on the way reads as much as the + /// buffer holds on top of that, so a step of a merge of many runs reads + /// up to a buffer of each more: the step is bounded, but not held to + /// its budget. With any budget it gets further, and without one nothing + /// is sorted, read or written. + /// + /// A caller that works in steps calls this until it returns true + /// before it takes a record. [`Merge::next`] does all that is left of + /// it at once. Once it failed it fails whenever it is asked again, and + /// so does [`Merge::next`]. + pub(crate) fn prepare(&mut self, budget: u64) -> io::Result { + self.check()?; + let mut left = budget; + let prepared = self.advance(&mut left); + self.failed = prepared.is_err(); + prepared + } + + /// Moves on to the next record and returns where it comes from, or + /// nothing once all went out. The body of a record of a run is read + /// into the merge. + fn move_on(&mut self) -> io::Result> { + while !self.prepare(u64::MAX)? {} + match self.taken.take() { + Some(Taken::Run(_)) => self.last.advance_top(self.file.as_mut().ok_or_else(damaged)?)?, + Some(Taken::Memory) => self.memory.next += 1, + None => {} + } + let taken = match (self.last.top(), self.memory.record()) { + (None, None) => return Ok(None), + (Some(run), None) => Taken::Run(run), + (None, Some(_)) => Taken::Memory, + // What was in memory at the end came after every run, so a + // run goes first where the keys are the same. + (Some(run), Some((key, _))) if self.last.readers[run].key.as_slice() <= key => Taken::Run(run), + (Some(_), Some(_)) => Taken::Memory, + }; + if let Taken::Run(run) = taken { + self.body.clear(); + let file = self.file.as_mut().ok_or_else(damaged)?; + self.last.readers[run].append_body(file, &mut self.body)?; + } + self.taken = Some(taken); + Ok(Some(taken)) + } + + /// The key and the body of the next record, or nothing once all went + /// out. Once [`Merge::prepare`] is done it reads at most a buffer of + /// one run and the body of one record from the scratch file. Before + /// that it does what is left of it first. Once it failed it fails + /// whenever it is asked again. + pub(crate) fn next(&mut self) -> io::Result> { + self.check()?; + let taken = match self.move_on() { + Ok(Some(taken)) => taken, + Ok(None) => return Ok(None), + Err(e) => { + self.failed = true; + return Err(e); + } + }; + match taken { + Taken::Run(run) => Ok(Some((&self.last.readers[run].key, &self.body))), + Taken::Memory => Ok(self.memory.record()), + } + } + + /// Gives the merge up: the scratch file of the runs goes back to + /// `scratch`, which empties it, if the sort wrote one. The sort has the + /// file until it is wound up, also where that failed, and the merge + /// from then on. A merge that is dropped leaves the file as it is. + pub(crate) fn give_back(self, scratch: &mut Scratch) { + let of_sort = self.sorter.and_then(|sorter| sorter.file); + let file = of_sort.or(self.file.map(|file| file.scratch)); + if let Some(file) = file { + scratch.take_back(file); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{OpenFile, TempDir, ST_BLOCKS_UNIT}; + use rustix::fs::SeekFrom; + use std::env; + use std::fmt; + use std::fs; + use std::os::unix::fs::MetadataExt; + use std::path::Path; + use std::process::Command; + use std::str::FromStr; + use std::time::{Duration, Instant}; + + /// Scratch space in the directory `dir`. + fn scratch_in(dir: &Path) -> Scratch { + Scratch::beside(ScratchFile::open_directory(dir).unwrap().into()) + } + + /// Scratch space in a directory of its own. + fn scratch(name: &str) -> (TempDir, Scratch) { + let tmp = TempDir::new(name); + let scratch = scratch_in(&tmp.0); + (tmp, scratch) + } + + /// A sort that writes a run for every few records, merges `runs` of + /// them at once through buffers of the smallest size, and gives back + /// every block it has read. + fn small(memory: usize, runs: usize) -> Sorter { + Sorter::with_limits(Limits { + memory, + run_buffer: 1, + write_buffer: 64, + runs, + hole: 1, + }) + } + + /// A number that is as good as random, from the number `seed`. + fn mix(seed: u64) -> u64 { + let mut x = seed.wrapping_add(0x9e37_79b9_7f4a_7c15); + x = (x ^ (x >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + x = (x ^ (x >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + x ^ (x >> 31) + } + + /// Everything a merge hands out, each key with its body. + fn drain(mut merge: Merge) -> Vec<(Vec, Vec)> { + let mut all = Vec::new(); + while let Some((key, body)) = merge.next().unwrap() { + all.push((key.to_vec(), body.to_vec())); + } + assert!(merge.next().unwrap().is_none()); + all + } + + /// Records go out in the order of their keys, and those with the same + /// key in the order they came, whether they all fit into memory, take + /// a few runs or take so many that passes merge them first, a few at a + /// time or two at a time, and whatever sizes the records have. So the + /// same records go out the same however they were kept. + #[test] + fn sorts() { + let (tmp, mut scratch) = scratch("sort-sorts"); + for (memory, count, most, runs, passes) in [ + (usize::MAX, 3000, MOST_RUNS, false, false), + (4096, 3000, MOST_RUNS, true, false), + (4096, 3000, 5, true, true), + (4096, 3000, 2, true, true), + (1, 300, MOST_RUNS, true, false), + (1, 300, 298, true, true), + (1, 300, 17, true, true), + (1, 300, 3, true, true), + (1, 300, 2, true, true), + (1, 300, 0, true, true), + (100_000, 3000, 2, true, true), + ] { + let mut sorter = small(memory, most); + let mut expected = Vec::new(); + for index in 0..count { + // Few keys, so that many records have the same one, and a + // body that says in which order they came. + let random = mix(index); + let key = format!("{:03}", random % 97).into_bytes(); + let key = &key[..(random % 4) as usize]; + let mut body = index.to_le_bytes().to_vec(); + body.resize(8 + (random >> 8) as usize % 300, 0xab); + if index % 1000 == 999 { + body.resize(200_000, 0xcd); + } + sorter.push(&mut scratch, key, &body).unwrap(); + expected.push((key.to_vec(), body)); + } + assert_eq!(!sorter.runs.is_empty(), runs, "{}", memory); + assert_eq!(sorter.file.is_some(), runs); + assert_eq!(sorter.runs.len() > most.max(FEWEST_RUNS), passes, "{} {}", memory, most); + // A stable sort is what this comes to. + expected.sort_by(|one, other| one.0.cmp(&other.0)); + let sorted = drain(sorter.finish()); + assert_eq!(sorted.len(), expected.len()); + assert!(sorted == expected, "{} {}", memory, most); + } + // Nothing has a name in the directory of the scratch file. + assert_eq!(fs::read_dir(&tmp.0).unwrap().count(), 0); + } + + /// A sort without records hands out nothing, and one record comes back + /// as it went in, also the largest one and one without a key or a + /// body. A key or a body that is too long is refused. + #[test] + fn records() { + let (_tmp, mut scratch) = scratch("sort-records"); + assert!(drain(Sorter::new().finish()).is_empty()); + assert!(drain(small(1, MOST_RUNS).finish()).is_empty()); + let largest = (vec![b'k'; MAX_KEY], vec![b'b'; MAX_BODY]); + let records = [ + (Vec::new(), Vec::new()), + (b"key".to_vec(), Vec::new()), + (Vec::new(), b"body".to_vec()), + largest, + ]; + for memory in [usize::MAX, 1] { + for (key, body) in &records { + // Four records: with as little memory that is three runs + // and a record in memory, and with two runs in a merge a + // pass that merges two of them. + for most in [MOST_RUNS, FEWEST_RUNS] { + let mut sorter = small(memory, most); + for _ in 0..4 { + sorter.push(&mut scratch, key, body).unwrap(); + } + assert_eq!(sorter.runs.len(), if memory == 1 { 3 } else { 0 }); + let sorted = drain(sorter.finish()); + assert!(sorted == vec![(key.clone(), body.clone()); 4]); + } + } + } + let mut sorter = Sorter::new(); + let too_long = sorter.push(&mut scratch, &vec![0; MAX_KEY + 1], b"").unwrap_err(); + assert_eq!(too_long.kind(), io::ErrorKind::InvalidInput); + let too_long = sorter.push(&mut scratch, b"", &vec![0; MAX_BODY + 1]).unwrap_err(); + assert_eq!(too_long.kind(), io::ErrorKind::InvalidInput); + assert!(drain(sorter.finish()).is_empty()); + } + + /// The records in memory take what they need up to their limit and + /// what the one record takes that goes over it, and give that back + /// once they are written. A sort that fits never makes a scratch + /// file. + #[test] + fn memory() { + let (_tmp, mut scratch) = scratch("sort-memory"); + let limit = 1024 * 1024; + let mut sorter = Sorter::with_limits(Limits { + memory: limit, + run_buffer: RUN_BUFFER, + write_buffer: WRITE_BUFFER, + runs: MOST_RUNS, + hole: HOLE_SIZE, + }); + let mut most = 0; + for index in 0u64..40_000 { + sorter.push(&mut scratch, &index.to_be_bytes(), &[0; 100]).unwrap(); + assert!(sorter.records.len() + size_of_val(&sorter.starts[..]) < limit + 200); + most = most.max(sorter.records.capacity()); + } + assert!(most <= limit + 200, "{}", most); + assert!(sorter.runs.len() >= 4, "{:?}", sorter.runs); + // A record of several megabytes goes over the limit alone, and the + // next push writes it out. + sorter.push(&mut scratch, b"large", &vec![0; MAX_BODY]).unwrap(); + assert!(sorter.records.capacity() > MAX_BODY); + sorter.push(&mut scratch, b"small", b"").unwrap(); + assert!(sorter.records.capacity() <= limit, "{}", sorter.records.capacity()); + assert_eq!(drain(sorter.finish()).len(), 40_002); + let mut sorter = Sorter::new(); + for index in 0u64..1000 { + sorter.push(&mut scratch, &index.to_be_bytes(), &[0; 100]).unwrap(); + } + assert!(sorter.file.is_none() && sorter.runs.is_empty()); + assert_eq!(sorter.records.capacity(), 128 * 1024); + } + + /// The merges of the passes over `count` runs where a merge takes + /// `most` runs at once: how many runs each takes, pass by pass. The + /// runs it is tried with are one byte long each, so that what a merge + /// makes of them shows which ones it took. + fn merges(count: usize, most: usize) -> Vec> { + let runs = (0..count as u64).map(|start| Run { start, end: start + 1 }); + let limits = Limits { + memory: MEMORY_LIMIT, + run_buffer: RUN_BUFFER, + write_buffer: WRITE_BUFFER, + runs: most, + hole: HOLE_SIZE, + }; + let mut passes = Passes::new(runs.collect(), &limits); + let mut sizes: Vec> = Vec::new(); + loop { + let begins = passes.count() == passes.target; + let Some(merged) = passes.next_merge() else { + break; + }; + if begins { + sizes.push(Vec::new()); + } + sizes.last_mut().unwrap().push(merged.len()); + let merged = &passes.runs[merged]; + // The runs of a merge follow each other. + assert!(merged.windows(2).all(|pair| pair[0].end == pair[1].start)); + let (first, last) = (merged[0], merged[merged.len() - 1]); + passes.put(Run { + start: first.start, + end: last.end, + }); + } + // The runs that are left are all the runs in their order, and few + // enough for one merge: a full one where there were more. + let left = passes.runs; + assert!(left.windows(2).all(|pair| pair[0].end == pair[1].start)); + assert_eq!(left.first().map_or(0, |run| run.start), 0); + assert_eq!(left.last().map_or(0, |run| run.end), count as u64); + assert_eq!(left.len(), count.min(most.max(FEWEST_RUNS)), "{} {}", count, most); + sizes + } + + /// A pass merges just enough runs for the merges after it to be full + /// ones: a smaller merge first, then full ones. Runs that are few + /// enough for one merge get no pass. Runs that are too many for a pass + /// of full merges to leave few enough get another pass before it. + #[test] + fn passes() { + assert_eq!(MOST_RUNS, 512); + for few in [0, 1, 2, 511, 512] { + assert!(merges(few, MOST_RUNS).is_empty(), "{}", few); + } + assert_eq!(merges(513, MOST_RUNS), [[2]]); + assert_eq!(merges(600, MOST_RUNS), [[89]]); + assert_eq!(merges(1023, MOST_RUNS), [[512]]); + assert_eq!(merges(1024, MOST_RUNS), [[2, 512]]); + let ten_thousand = merges(10_000, MOST_RUNS); + assert_eq!(ten_thousand.len(), 1); + assert_eq!((ten_thousand[0][0], &ten_thousand[0][1..]), (291, &[512; 18][..])); + // As many runs as a pass of full merges takes, and one more. + assert_eq!(merges(512 * 512, MOST_RUNS), [vec![512; 512]]); + let another = merges(512 * 512 + 1, MOST_RUNS); + assert_eq!(another, [vec![2], vec![512; 512]]); + // Two runs at a time. + assert_eq!(merges(11, 2), [vec![2; 3], vec![2; 4], vec![2; 2]]); + assert_eq!(merges(3, 2), [[2]]); + // A merge never takes fewer than two runs, whatever it is told. + assert_eq!(merges(5, 0), merges(5, 2)); + for most in 2..=9 { + for count in 0..=1000 { + let sizes = merges(count, most); + for (pass, sizes) in sizes.iter().enumerate() { + // Only the first merge of the first pass is smaller. + let full = sizes.iter().skip(usize::from(pass == 0)); + assert!(full.clone().all(|&size| size == most), "{} {} {:?}", count, most, sizes); + assert!( + (FEWEST_RUNS..=most).contains(&sizes[0]), + "{} {} {:?}", + count, + most, + sizes + ); + } + // A pass before the last one leaves a power of what a + // merge takes: the next pass takes all of them. + let mut runs = count; + for (pass, sizes) in sizes.iter().enumerate() { + let merged: usize = sizes.iter().sum(); + if pass > 0 { + assert_eq!(merged, runs, "{} {}", count, most); + } + runs -= merged - sizes.len(); + } + } + } + } + + /// The passes are done a part at a time, with as much reading and + /// writing as the budget of each step allows, and nothing is read or + /// written without a budget. No merge takes more runs than it may, and + /// each run is read through a buffer of the one size, however many + /// runs there are. What a pass makes is appended to the scratch file. + #[test] + fn merges_in_steps() { + /// How many bytes a record of this test takes in a run. + const RECORD: u64 = (HEADER_SIZE + size_of::() + BODY) as u64; + const BODY: usize = 40; + let (_tmp, mut scratch) = scratch("sort-passes"); + let size = HEADER_SIZE + MAX_KEY; + for (most, budget) in [(2, 1), (3, 100), (4, 10_000), (7, 1_000_000), (2, u64::MAX)] { + let mut sorter = small(2000, most); + let mut expected = Vec::new(); + for index in 0u64..2000 { + // Few keys, so that many records have the same one. + let key = (mix(index) % 500).to_be_bytes(); + sorter.push(&mut scratch, &key, &[index as u8; BODY]).unwrap(); + expected.push((key.to_vec(), vec![index as u8; BODY])); + } + expected.sort_by(|one, other| one.0.cmp(&other.0)); + let (runs, written) = (sorter.runs.len(), sorter.runs.last().unwrap().end); + // More runs than a pass of full merges takes, also for the + // widest merge: two passes at least. + assert!(runs > 7 * 7, "{}", runs); + let mut merge = sorter.finish(); + // Where the scratch file ends, with what a merge has written + // of the run it makes. + let end = |merge: &Merge| { + let passes = merge.passes.as_ref()?; + Some(passes.merge.as_ref().map_or(passes.end, |under_way| under_way.made.end)) + }; + // Without a budget the sort is not even wound up. + assert!(!merge.prepare(0).unwrap()); + assert!(merge.sorter.is_some() && end(&merge).is_none()); + let (mut steps, mut last) = (0u64, written); + while !merge.prepare(budget).unwrap() { + steps += 1; + assert!(!merge.prepare(0).unwrap()); + let Some(passes) = &merge.passes else { + continue; + }; + // A step writes what its budget allows, and less than one + // record more. + let now = end(&merge).unwrap(); + assert!( + now >= last && now - last < budget.saturating_add(RECORD), + "{} {}", + budget, + now - last + ); + last = now; + if let Some(under_way) = &passes.merge { + let readers = &under_way.runs.readers; + assert!((FEWEST_RUNS..=most).contains(&readers.len()), "{}", readers.len()); + assert!(readers.iter().all(|reader| reader.buffer.capacity() <= size)); + assert!(under_way.made.start >= written); + } + } + // The passes wrote every record once more for each pass that + // took it, behind the runs of the sort, and left a full merge. + assert!(merge.passes.is_none()); + assert_eq!(merge.last.readers.len(), most); + let end = merge.last.readers.iter().map(|reader| reader.end).max().unwrap(); + assert!(end >= last && end >= 2 * written, "{} {} {}", written, last, end); + // The smallest budget looks at one run or moves one record in + // a step, and the largest does it all in one. + match budget { + 1 => assert!(steps > (end - written) / RECORD, "{}", steps), + u64::MAX => assert_eq!(steps, 0), + _ => assert!(steps >= (end - written) / (budget + RECORD), "{} {}", budget, steps), + } + let (mut sorted, mut most_buffer) = (Vec::new(), 0); + while let Some((key, body)) = merge.next().unwrap() { + sorted.push((key.to_vec(), body.to_vec())); + let buffers = merge.last.readers.iter().map(|reader| reader.buffer.capacity()); + most_buffer = most_buffer.max(buffers.max().unwrap()); + } + assert_eq!(most_buffer, size); + assert!(sorted == expected, "{}", most); + } + } + + /// Every run is merged through a buffer of the size the limits say, + /// whether the runs are few or so many that passes merge them, and a + /// merge never has more of them than it may. So the buffers of a merge + /// together take no more than that many buffers. + #[test] + fn buffers_of_the_runs() { + let (_tmp, mut scratch) = scratch("sort-buffers"); + for (memory, most, passes) in [(1024 * 1024, 16, false), (256 * 1024, 8, true), (16 * 1024, 4, true)] { + let mut sorter = Sorter::with_limits(Limits { + memory, + run_buffer: RUN_BUFFER, + write_buffer: WRITE_BUFFER, + runs: most, + hole: HOLE_SIZE, + }); + for index in 0u64..3000 { + sorter + .push(&mut scratch, &mix(index).to_be_bytes(), &[0; 1000]) + .unwrap(); + } + let runs = sorter.runs.len(); + assert_eq!(runs > most, passes, "{} {}", memory, runs); + let mut merge = sorter.finish(); + // How many bytes the buffers of a merge take together. None is + // larger than a buffer may be, and a run that is shorter than + // that has a smaller one. + let buffers = |readers: &[RunReader]| { + assert!(readers.len() <= most, "{} {}", memory, readers.len()); + let sizes = readers.iter().map(|reader| reader.buffer.capacity()); + assert!(sizes.clone().all(|size| size <= RUN_BUFFER), "{}", memory); + sizes.sum::() + }; + let mut largest = 0; + while !merge.prepare(100_000).unwrap() { + let under_way = merge.passes.as_ref().and_then(|passes| passes.merge.as_ref()); + largest = largest.max(under_way.map_or(0, |under_way| buffers(&under_way.runs.readers))); + // The last merge has no run before the passes are over. + assert!(merge.passes.is_none() || merge.last.readers.is_empty()); + } + assert_eq!(largest > 0, passes); + assert_eq!(merge.last.readers.len(), runs.min(most)); + let (mut last, mut count) = (Vec::new(), 0); + while let Some((key, _)) = merge.next().unwrap() { + assert!(last.as_slice() < key); + (last, count) = (key.to_vec(), count + 1); + largest = largest.max(buffers(&merge.last.readers)); + } + assert_eq!(count, 3000); + assert_eq!(largest, runs.min(most) * RUN_BUFFER, "{}", memory); + } + } + + /// A run that cannot be written fails the step and loses nothing: the + /// records of the write that failed are written when the run is + /// written on, and all of them go out in the end. Here every part of a + /// run fails once, with the run moved to where no file reaches. + #[test] + fn failed_writes_of_a_run() { + /// An offset no file has. + const NOWHERE: u64 = i64::MAX as u64; + let (_tmp, mut scratch) = scratch("sort-failed-write"); + let mut sorter = small(4000, MOST_RUNS); + let (mut expected, mut failed) = (Vec::new(), 0); + for index in 0u64..1500 { + loop { + let moved = sorter.spill.as_mut().map(|spill| mem::replace(&mut spill.at, NOWHERE)); + if let Some(at) = moved { + assert!(sorter.make_room(&mut scratch, 100).is_err()); + sorter.spill.as_mut().unwrap().at = at; + failed += 1; + } + if sorter.make_room(&mut scratch, 100).unwrap() { + break; + } + } + let key = (mix(index) % 400).to_be_bytes(); + sorter.push(&mut scratch, &key, &index.to_le_bytes()).unwrap(); + expected.push((key.to_vec(), index.to_le_bytes().to_vec())); + } + assert!( + failed > 100 && sorter.runs.len() > 3, + "{} {}", + failed, + sorter.runs.len() + ); + expected.sort_by(|one, other| one.0.cmp(&other.0)); + assert!(drain(sorter.finish()) == expected); + } + + /// A merge keeps the sort where the rest of a run that was half + /// written cannot be written, and the scratch file of the runs with + /// it: the file stays open as it is, and the merge fails from there + /// on. A merge that is given up gives the file back from there, which + /// empties it, and so does one that is wound up, which has the file + /// itself. + #[test] + fn failed_wind_ups() { + /// An offset no file has. + const NOWHERE: u64 = i64::MAX as u64; + let (tmp, mut scratch) = scratch("sort-failed-wind-up"); + let mut sorter = small(2000, MOST_RUNS); + // Until a run is begun, of which this budget writes one record. + while sorter.make_room(&mut scratch, 1).unwrap() { + sorter.push(&mut scratch, b"key", b"").unwrap(); + } + sorter.spill.as_mut().unwrap().at = NOWHERE; + let mut merge = sorter.finish(); + assert!(merge.prepare(u64::MAX).is_err()); + assert!(merge.sorter.as_ref().is_some_and(|sorter| sorter.file.is_some())); + assert!(merge.prepare(u64::MAX).is_err()); + let files = OpenFile::made_in(&tmp.0); + assert!(files.len() == 1 && files[0].size > 0, "{:?}", files); + merge.give_back(&mut scratch); + let files = OpenFile::made_in(&tmp.0); + assert!(files.len() == 1 && files[0].size == 0, "{:?}", files); + // The next sort takes the file that was given back, and its merge + // has it once it is wound up. + let mut sorter = small(2000, MOST_RUNS); + while sorter.runs.is_empty() { + sorter.push(&mut scratch, b"key", b"").unwrap(); + } + let mut merge = sorter.finish(); + assert!(merge.prepare(u64::MAX).unwrap() && merge.file.is_some()); + assert!(OpenFile::made_in(&tmp.0).iter().all(|file| file.size > 0)); + merge.give_back(&mut scratch); + let files = OpenFile::made_in(&tmp.0); + assert!(files.len() == 1 && files[0].size == 0, "{:?}", files); + } + + /// A run is written a part at a time, with as much writing as the + /// budget of each step allows, and nothing is written without a + /// budget. A record is taken whatever is left to write before. + #[test] + fn writes_runs_in_steps() { + let (_tmp, mut scratch) = scratch("sort-steps"); + for budget in [1, 100, 10_000] { + let mut sorter = small(20_000, MOST_RUNS); + let mut expected = Vec::new(); + let (mut steps, mut most) = (0, 0); + for index in 0u64..2000 { + let mut now = 0; + while !sorter.make_room(&mut scratch, budget).unwrap() { + assert!(!sorter.make_room(&mut scratch, 0).unwrap()); + now += 1; + } + (steps, most) = (steps + now, most.max(now)); + let key = mix(index).to_be_bytes(); + sorter.push(&mut scratch, &key, &[index as u8; 40]).unwrap(); + expected.push((key.to_vec(), vec![index as u8; 40])); + } + // A run of about 20000 bytes takes a step for every record + // with the smallest budget, and two steps with the largest. + assert!(most >= 20_000 / budget.max(64) / 2, "{} {}", budget, most); + assert!(steps >= most * 3, "{} {} {}", budget, steps, most); + expected.sort(); + assert!(drain(sorter.finish()) == expected); + } + // Without a budget a run is not begun either: nothing is sorted, + // and no scratch file is made. + let mut sorter = small(2000, MOST_RUNS); + while !sorter.is_full() { + sorter.push(&mut scratch, b"key", b"").unwrap(); + } + assert!(!sorter.make_room(&mut scratch, 0).unwrap()); + assert!(sorter.spill.is_none() && sorter.file.is_none()); + assert!(!sorter.make_room(&mut scratch, 1).unwrap()); + assert!(sorter.spill.is_some() && sorter.file.is_some()); + let mut sorter = small(2000, MOST_RUNS); + for index in 0u64..2000 { + let _ = sorter.make_room(&mut scratch, 1).unwrap(); + sorter.push(&mut scratch, &mix(index).to_be_bytes(), b"").unwrap(); + } + // The sort ends with a run half written. Ending it does nothing: + // the merge writes the run to its end, a part in each step, and + // sorts what is in memory once it is written, and nothing without + // a budget. + while sorter.make_room(&mut scratch, 1).unwrap() { + sorter.push(&mut scratch, b"more", b"").unwrap(); + } + assert!(sorter.spill.is_some()); + let written = |merge: &Merge| { + let spill = merge.sorter.as_ref()?.spill.as_ref()?; + Some(spill.written) + }; + let mut merge = sorter.finish(); + let (begun, mut steps) = (written(&merge).unwrap(), 0); + assert!(!merge.prepare(0).unwrap()); + assert_eq!(written(&merge), Some(begun)); + while let Some(before) = written(&merge) { + let _ = merge.prepare(1).unwrap(); + assert!(written(&merge).is_none_or(|now| now == before + 1)); + steps += 1; + } + assert!(steps > 1, "{}", steps); + // The step that wrote the last of the run has no budget left, and + // the next one that has winds the sort up. + assert!(merge.sorter.is_some() && merge.passes.is_none()); + assert!(!merge.prepare(0).unwrap()); + assert!(merge.sorter.is_some()); + let _ = merge.prepare(1).unwrap(); + assert!(merge.sorter.is_none()); + let sorted = drain(merge); + assert!(sorted.len() > 2000 && sorted.is_sorted()); + } + + /// Checks the blocks of `block` bytes of the scratch file `file` that + /// are all in the run `run`: those in front of `released` are holes, + /// and the others are not. A block that a run shares with the run next + /// to it is none of its own. + fn check_blocks(file: &ScratchFile, block: u64, run: Run, released: u64) { + let whole = run.start.next_multiple_of(block)..run.end - run.end % block; + let mut data = vec![0; usize::try_from(block).unwrap()]; + for start in whole.step_by(data.len()) { + file.read_exact_at(&mut data, start).unwrap(); + let hole = data.iter().all(|&byte| byte == 0); + assert_eq!( + hole, + start < released, + "{:?} at {}, given back up to {}", + run, + start, + released + ); + } + } + + /// Checks what the reader `reader` of the run `run` gave back of it in + /// the scratch file `file`, whose blocks are `block` bytes, where a hole + /// is to have `hole` bytes, 1 or more than any run: with `punched` + /// every whole block it has read once that makes a hole or the run + /// ended, and without it nothing. Returns whether the reader has read + /// enough for a hole to be tried, punched or not. + fn check_reader(file: &ScratchFile, block: u64, run: Run, reader: &RunReader, punched: bool, hole: u64) -> bool { + assert_eq!(reader.end, run.end); + let read = reader.at - reader.at % block; + let start = run.start.next_multiple_of(block); + let ended = reader.at == reader.end; + let tried = read > start && (read - start >= hole || ended); + let released = if punched && tried { read } else { run.start }; + assert_eq!(reader.released, released, "{:?} read up to {}", run, reader.at); + check_blocks(file, block, run, released); + tried + } + + /// Sorts records in the directory `dir` whose runs take several blocks + /// of the scratch file each: ten runs, of which a pass merges four and + /// four, and a last merge of what they made and of the two runs that + /// are left. It checks the scratch file all along. With `punched` the + /// file system can punch holes, and what a merge has read of a run is + /// a hole up to the last whole block, while the rest of the run is + /// there. Without it the first hole that cannot be punched is the last + /// one tried, every run stays as it was written, and the records go out + /// all the same. A hole is to have `hole` bytes: 1, which gives back + /// every block as soon as it was read, or more than any run, which gives + /// back a run only once it ended. + fn merge_with_holes(dir: &Path, punched: bool, hole: u64) { + const COUNT: usize = 10; + const MOST: usize = 4; + let mut scratch = scratch_in(dir); + let probe = scratch.file().unwrap(); + let block = probe.block_size().unwrap(); + scratch.take_back(probe); + // A record takes a quarter of a block and a run six blocks and a + // bit, so that the runs start and end anywhere in a block. + let body = usize::try_from(block / 4).unwrap(); + if body > MAX_BODY { + eprintln!("skipping: blocks of {} bytes are too large for a record", block); + return; + } + let mut sorter = Sorter::with_limits(Limits { + memory: 6 * usize::try_from(block).unwrap(), + run_buffer: 1, + write_buffer: 1, + runs: MOST, + hole, + }); + // No record has a block of zeroes. A few records stay in memory. + let mut count = 0u64; + while sorter.runs.len() < COUNT || sorter.starts.len() < MOST { + sorter + .push(&mut scratch, &mix(count).to_be_bytes(), &vec![count as u8 | 1; body]) + .unwrap(); + count += 1; + } + let mut runs = sorter.runs.clone(); + assert_eq!(runs.len(), COUNT); + let written = runs[COUNT - 1].end; + let run_of = |runs: &[Run], reader: &RunReader| *runs.iter().find(|run| run.end == reader.end).unwrap(); + let mut merge = sorter.finish(); + // The size of a block is known once the sort is wound up, until a + // hole fails. Without holes, the first one that fails is the last + // one tried, so once a reader has read enough for one the scratch + // file has no block size any more. + let mut tried = false; + while !merge.prepare(block).unwrap() { + let file = merge.file.as_ref().unwrap(); + let under_way = merge.passes.as_ref().and_then(|passes| passes.merge.as_ref()); + for reader in under_way.iter().flat_map(|under_way| &under_way.runs.readers) { + tried |= check_reader(&file.scratch, block, run_of(&runs, reader), reader, punched, hole); + } + assert_eq!(file.block.map(NonZeroU64::get), (punched || !tried).then_some(block)); + } + assert!(tried); + // The pass read the first eight runs to their ends, and the last + // merge looked at the two runs the pass made and at the two it + // left. + let file = merge.file.as_ref().unwrap(); + assert_eq!(file.block.is_some(), punched); + let last = &merge.last.readers; + assert_eq!(last.len(), MOST); + runs.push(Run { + start: written, + end: last[0].end, + }); + runs.push(Run { + start: last[0].end, + end: last[1].end, + }); + assert!(written < last[0].end && last[0].end < last[1].end); + for run in &runs[..COUNT - 2] { + check_blocks(&file.scratch, block, *run, if punched { run.end } else { run.start }); + } + for reader in last { + check_reader(&file.scratch, block, run_of(&runs, reader), reader, punched, hole); + } + let mut last_key = Vec::new(); + let mut merged = 0; + while let Some((key, record)) = merge.next().unwrap() { + assert!(last_key.as_slice() < key && record.len() == body); + last_key = key.to_vec(); + merged += 1; + } + assert_eq!(merged, count); + // Every run was read to its end now, also those the pass made. + let file = merge.file.as_ref().unwrap(); + assert_eq!(file.block.is_some(), punched); + for run in &runs { + check_blocks(&file.scratch, block, *run, if punched { run.end } else { run.start }); + } + } + + /// What a merge has read of a run it gives back to the file system as + /// it goes: the blocks it has read are holes in the scratch file, in + /// a pass and in the last merge, and the blocks it has not read are + /// there. Where a hole is to have more bytes than a run has, a run is + /// given back once it ended. Where the temporary directory cannot punch + /// holes, the same is tried without them. + #[test] + fn gives_room_back() { + let tmp = TempDir::new("sort-holes"); + let probe = scratch_in(&tmp.0).file().unwrap(); + let block = probe.block_size().unwrap(); + probe.write_all_at(&[1], block).unwrap(); + let punched = probe.punch_hole(0, block).is_ok(); + if !punched { + eprintln!("skipping the holes: the temporary directory cannot punch them"); + } + for hole in [1, u64::MAX] { + merge_with_holes(&tmp.0, punched, hole); + } + } + + /// The variable that names a directory of a file system that cannot + /// punch holes, in which the test binary runs + /// [`keeps_room_without_holes`] again. + const NO_HOLES_DIR: &str = "UAPI16_TEST_SORT_NO_HOLES_DIR"; + + /// A scratch file that no hole can be punched into keeps its room, and + /// the sort goes on as it does with holes: the first hole that fails is + /// the last one it tries. The test binary runs this test again with its + /// directory on a ramfs, which cannot punch holes, and it is skipped + /// where that cannot be mounted. + #[test] + fn keeps_room_without_holes() { + let Some(dir) = env::var_os(NO_HOLES_DIR) else { + let tmp = TempDir::new("sort-no-holes"); + tmp.rerun_on("ramfs", None, "sort::tests::keeps_room_without_holes", NO_HOLES_DIR); + return; + }; + for hole in [1, u64::MAX] { + merge_with_holes(Path::new(&dir), false, hole); + } + } + + /// The variable that names the directory in which the test binary runs + /// [`gives_back_the_room_past_the_end`] again. + const PAST_THE_END_DIR: &str = "UAPI16_TEST_SORT_PAST_THE_END_DIR"; + + /// Once the passes are over nothing is written to the scratch file any + /// more, and the room the file system took past its end for what it + /// expected to be written there is given back before the last merge + /// begins. The test takes such room itself, 4 MiB with fallocate() and + /// FALLOC_FL_KEEP_SIZE, far past what the runs and the passes take, and + /// takes it again once the last merge begins, which takes room again + /// only where it was given back. It runs again in a process of its own, + /// in which the scratch file is the one file without a name, and it is + /// skipped where the file system can't take room past the end of a + /// file, can't punch holes, or leaves a hole past the end of a file + /// alone, as ext4 does. + #[test] + fn gives_back_the_room_past_the_end() { + let Some(dir) = env::var_os(PAST_THE_END_DIR) else { + let tmp = TempDir::new("sort-past-the-end"); + let output = Command::new(env::current_exe().unwrap()) + .args([ + "--exact", + "sort::tests::gives_back_the_room_past_the_end", + "--nocapture", + ]) + .env(PAST_THE_END_DIR, &tmp.0) + .output() + .unwrap(); + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + for line in String::from_utf8_lossy(&output.stderr).lines() { + if line.starts_with("skipping") { + eprintln!("{}", line); + } + } + return; + }; + const TAKEN: u64 = 4 * 1024 * 1024; + let dir = Path::new(&dir); + let mut scratch = scratch_in(dir); + // A file of a scratch space of its own, which is closed once it is + // dropped: one of the scratch space of the sort would stay open. + let probe = scratch_in(dir).file().unwrap(); + let block = probe.block_size().unwrap(); + probe.write_all_at(&[1], block).unwrap(); + if probe.punch_hole(0, block).is_err() { + eprintln!("skipping: the temporary directory cannot punch holes"); + return; + } + // The one file without a name this process has in the directory, + // opened again through procfs. + let device = fs::metadata(dir).unwrap().dev(); + let unnamed = || { + let unnamed: Vec<_> = fs::read_dir("/proc/self/fd") + .unwrap() + .filter_map(|entry| { + let path = entry.unwrap().path(); + let file = fs::metadata(&path).ok()?; + (file.is_file() && file.nlink() == 0 && file.dev() == device).then_some(path) + }) + .collect(); + assert_eq!(unnamed.len(), 1, "{:?}", unnamed); + fs::OpenOptions::new().write(true).open(&unnamed[0]).unwrap() + }; + let take = |file: &fs::File, past: u64| { + rustix::fs::fallocate(file, rustix::fs::FallocateFlags::KEEP_SIZE, past, TAKEN) + }; + // Not every file system gives the room a file has past its end back + // to a hole there: ext4 leaves a hole past the end of a file alone. + let past = (16 * TAKEN).next_multiple_of(block); + if let Err(e) = take(&unnamed(), past) { + eprintln!( + "skipping: the temporary directory takes no room past the end of a file: {}", + e + ); + return; + } + let taken = room(dir); + probe.punch_hole(past, TAKEN).unwrap(); + if room(dir) + TAKEN > taken { + eprintln!("skipping: the temporary directory gives no room past the end of a file back"); + return; + } + drop(probe); + // Four runs to a merge, of which there are ten: a pass before the + // last merge. + let mut sorter = small(24 * 1024, 4); + let mut count = 0u64; + while sorter.runs.len() < 10 { + sorter + .push(&mut scratch, &mix(count).to_be_bytes(), &[0x5a; 100]) + .unwrap(); + count += 1; + } + let written = sorter.runs.last().unwrap().end; + let mut merge = sorter.finish(); + let file = unnamed(); + let past = (16 * (written + TAKEN)).next_multiple_of(block); + let before = room(dir); + take(&file, past).unwrap(); + let taken = room(dir); + assert!(taken >= before + TAKEN, "{} bytes of room, {} before", taken, before); + while !merge.prepare(u64::MAX).unwrap() {} + let left = room(dir); + take(&file, past).unwrap(); + let again = room(dir); + assert!( + again >= left + TAKEN, + "{} bytes of room taken again, {} before", + again, + left + ); + assert_eq!(drain(merge).len() as u64, count); + } + + /// A pass that failed fails every step after it, whatever the budget, + /// without reading anything again, and so does the merge. + #[test] + fn failed_passes() { + let (_tmp, mut scratch) = scratch("sort-failed-pass"); + let mut sorter = small(1000, 3); + for index in 0u64..500 { + sorter.push(&mut scratch, &mix(index).to_be_bytes(), &[7; 50]).unwrap(); + } + assert!(sorter.runs.len() > 3); + let len = sorter.runs.last().unwrap().end; + let lengths = vec![0xff; usize::try_from(len).unwrap()]; + sorter.file.as_ref().unwrap().write_all_at(&lengths, 0).unwrap(); + let mut merge = sorter.finish(); + let e = loop { + match merge.prepare(64) { + Ok(done) => assert!(!done), + Err(e) => break e, + } + }; + assert_eq!(e.kind(), io::ErrorKind::InvalidData); + for budget in [u64::MAX, 0, 64] { + let e = merge.prepare(budget).unwrap_err(); + assert_eq!( + (e.kind(), e.to_string()), + (io::ErrorKind::Other, "the sort failed before".to_string()) + ); + } + assert_eq!(merge.next().unwrap_err().kind(), io::ErrorKind::Other); + } + + /// A scratch file that does not hold what was written to it is an + /// error, whatever it holds instead, and never more than that: in the + /// last merge and in a pass before it. + #[test] + fn changed_scratch_files() { + type Damage = fn(&ScratchFile, u64); + let damages: [(&str, Damage); 4] = [ + ("lengths", |file, len| { + file.write_all_at(&vec![0xff; len as usize], 0).unwrap() + }), + ("zeroes", |file, len| { + file.write_all_at(&vec![0; len as usize], 0).unwrap() + }), + ("a shorter file", |file, len| file.set_len(len / 2).unwrap()), + ("an empty file", |file, _| file.set_len(0).unwrap()), + ]; + for (what, damage) in damages { + for most in [MOST_RUNS, 3] { + let (_tmp, mut scratch) = scratch("sort-damage"); + let mut sorter = small(1000, most); + for index in 0u64..500 { + sorter.push(&mut scratch, &mix(index).to_be_bytes(), &[7; 50]).unwrap(); + } + let len = sorter.runs.last().unwrap().end; + let passes = sorter.runs.len() > most; + assert_eq!(passes, most == 3); + damage(sorter.file.as_ref().unwrap(), len); + let mut merge = sorter.finish(); + let mut read = 0; + let failed = loop { + match merge.next() { + Ok(Some(_)) => read += 1, + Ok(None) => break false, + Err(_) => break true, + } + // No record takes less than its header. + assert!(read <= len, "{}", what); + }; + // Zeroes are records without keys and bodies, which fail + // only where a run does not end with one. A file that a + // pass appends to has zeroes where it was cut off. + let zeroes = what == "zeroes" || passes && what.ends_with("file"); + assert!(failed || zeroes, "{} after {} records", what, read); + // A merge that failed does not go on with what it has. + for _ in 0..3 { + match merge.next() { + Err(e) => assert_eq!((failed, e.kind()), (true, io::ErrorKind::Other), "{}", what), + Ok(next) => assert!(!failed && next.is_none(), "{}", what), + } + match merge.prepare(u64::MAX) { + Err(e) => assert_eq!((failed, e.kind()), (true, io::ErrorKind::Other), "{}", what), + Ok(prepared) => assert!(!failed && prepared, "{}", what), + } + } + } + } + } + + /// The variables that tell the test binary, run again by [`measured`], + /// how many records to sort, how many bytes of them to keep in memory + /// and how many runs to merge at once. + const RECORDS: &str = "UAPI16_TEST_SORT_RECORDS"; + const MEMORY: &str = "UAPI16_TEST_SORT_MEMORY"; + const RUNS: &str = "UAPI16_TEST_SORT_RUNS"; + /// What the line starts with that says what was measured, which the + /// harness does not say of a test of this module, such as one that has + /// been running for over 60 seconds. + const MEASURED: &str = "sorted:"; + /// How many bytes of the runs a step of the measured sort reads before + /// its first record. + const STEP: u64 = 4 * 1024 * 1024; + + /// The resident memory of this process that is its own, in bytes, which + /// the kernel reports in kilobytes: RssAnon, without the pages of the + /// files it has mapped. Those of the test binary come and go with the + /// file system it is on, and are none of the sort's. A kernel before + /// Linux 4.5 does not tell the two apart, and all that is resident is + /// taken there. + fn resident() -> u64 { + let status = fs::read_to_string("/proc/self/status").unwrap(); + let field = |name: &str| status.lines().find_map(|line| line.strip_prefix(name)); + let line = field("RssAnon:").or_else(|| field("VmRSS:")).unwrap(); + let kilobytes: u64 = line.trim().trim_end_matches("kB").trim().parse().unwrap(); + kilobytes * 1024 + } + + /// How many bytes of room the files without a name take that this + /// process has open in the file system of the directory `dir`: its + /// scratch files there. + fn room(dir: &Path) -> u64 { + let device = fs::metadata(dir).unwrap().dev(); + let open = fs::read_dir("/proc/self/fd").unwrap(); + // The descriptor of the listing itself is gone by the time it is + // looked at. + let files = open.filter_map(|entry| fs::metadata(entry.unwrap().path()).ok()); + files + .filter(|file| file.is_file() && file.nlink() == 0 && file.dev() == device) + .map(|file| file.blocks() * ST_BLOCKS_UNIT) + .sum() + } + + /// How many bytes of data the files without a name hold that this + /// process has open in the file system of the directory `dir`, as + /// SEEK_DATA and SEEK_HOLE find them: what of its scratch files there + /// is not a hole. Unlike their room it leaves out what the file system + /// took for them past their ends. + fn data(dir: &Path) -> u64 { + let device = fs::metadata(dir).unwrap().dev(); + let open = fs::read_dir("/proc/self/fd").unwrap(); + // The descriptor of the listing itself is gone by the time it is + // looked at. + let files = open.filter_map(|entry| { + let path = entry.unwrap().path(); + let file = fs::metadata(&path).ok()?; + let scratch = file.is_file() && file.nlink() == 0 && file.dev() == device; + scratch.then(|| fs::File::open(&path).ok()).flatten() + }); + let mut total = 0; + for file in files { + let mut at = 0; + while let Ok(start) = rustix::fs::seek(&file, SeekFrom::Data(at)) { + let end = rustix::fs::seek(&file, SeekFrom::Hole(start)).unwrap(); + total += end - start; + at = end; + } + } + total + } + + /// Sorts `count` records with a key of 25 bytes and a body of 140 + /// bytes, which come in an order that is as good as random, with + /// `memory` bytes of them in memory and `most` runs in a merge. Checks + /// that they go out in order and that the memory of the process stays + /// within what the records in memory and the buffers of a merge take, + /// however many runs and passes that comes to. Where the scratch file + /// takes holes, its data stays within that of the records and what the + /// merges did not give back yet. + fn sort_records(count: u64, memory: usize, most: usize) { + let (tmp, mut scratch) = scratch("sort-measure"); + let before = resident(); + let mut sorter = Sorter::with_limits(Limits { + memory, + run_buffer: RUN_BUFFER, + write_buffer: WRITE_BUFFER, + runs: most, + hole: HOLE_SIZE, + }); + let started = Instant::now(); + let (mut most_resident, mut most_room, mut most_data) = (0, 0, 0); + let mut key = Vec::new(); + for index in 0..count { + let random = mix(index); + key.clear(); + key.extend_from_slice(format!("usr\0share\0p{:05}\0f{:07}", random % 50_000, random >> 40).as_bytes()); + sorter.push(&mut scratch, &key, &[0x5a; 140]).unwrap(); + if index % 4096 == 0 { + most_resident = most_resident.max(resident()); + } + } + let pushed = started.elapsed(); + let runs = sorter.runs.len(); + let written = sorter.runs.last().map_or(0, |run| run.end); + most_room = most_room.max(room(&tmp.0)); + most_data = most_data.max(data(&tmp.0)); + let mut merge = sorter.finish(); + // The passes, a step at a time. What is measured between the steps + // takes time of its own, which is not that of the passes: data() + // seeks through every hole of the scratch file. + let (mut passed, mut again) = (pushed, written); + let (mut measuring_passes, mut measuring_merge) = (Duration::ZERO, Duration::ZERO); + while !merge.prepare(STEP).unwrap() { + let measuring = Instant::now(); + most_resident = most_resident.max(resident()); + most_room = most_room.max(room(&tmp.0)); + most_data = most_data.max(data(&tmp.0)); + if let Some(passes) = &merge.passes { + again = passes.merge.as_ref().map_or(passes.end, |under_way| under_way.made.end); + measuring_passes += measuring.elapsed(); + passed = started.elapsed(); + } + } + let last_merge = room(&tmp.0); + let mut last = Vec::new(); + let mut merged = 0u64; + while let Some((key, body)) = merge.next().unwrap() { + assert!(last.as_slice() <= key && body.len() == 140); + last.clear(); + last.extend_from_slice(key); + merged += 1; + if merged % 4096 == 0 { + most_resident = most_resident.max(resident()); + } + if merged % (1 << 20) == 0 { + let measuring = Instant::now(); + most_room = most_room.max(room(&tmp.0)); + most_data = most_data.max(data(&tmp.0)); + measuring_merge += measuring.elapsed(); + } + } + assert_eq!(merged, count); + let holes = merge.file.as_ref().is_some_and(|file| file.block.is_some()); + println!( + "{} {} records, {} runs of which a merge takes {}, {} MiB written and {} MiB again in passes, \ + {:.2} s to take them, {:.2} s for the passes and {:.2} s to merge, \ + resident {} KiB before and {} KiB at most, scratch file with {} MiB of data at most, \ + in {} MiB of room at most, {} MiB as the last merge began and {} MiB at the end, {}", + MEASURED, + count, + runs, + most, + written >> 20, + (again - written) >> 20, + pushed.as_secs_f64(), + (passed - pushed - measuring_passes).as_secs_f64(), + (started.elapsed() - passed - measuring_merge).as_secs_f64(), + before / 1024, + most_resident / 1024, + most_data >> 20, + most_room >> 20, + last_merge >> 20, + room(&tmp.0) >> 20, + if holes { "with holes" } else { "without holes" }, + ); + // The data of the records, and what the readers of a merge did not + // give back yet: what each read since its last hole, and a block at + // either end of every run, of which a pass makes fewer than it + // reads. + if holes { + let block = merge + .file + .as_ref() + .and_then(|file| file.block) + .map_or(0, NonZeroU64::get); + let held = runs.min(most) as u64 * (HOLE_SIZE + 2 * block) + 4 * runs as u64 * block; + assert!( + most_data <= written + held, + "{} bytes of data for {} of records", + most_data, + written + ); + } + // The records in memory with where they start, a buffer and a key + // for each run of a merge, what a pass writes at a time, and room + // for what an allocator keeps around. + let buffers = runs.min(most) * (RUN_BUFFER + MAX_KEY); + let allowed = (memory + FIRST_MEMORY + buffers + WRITE_BUFFER) as u64; + const SLACK: u64 = 8 * 1024 * 1024; + assert!( + most_resident <= before + allowed + SLACK, + "{} -> {}", + before, + most_resident + ); + } + + /// The number the variable `variable` says, if it is set. + fn number>(variable: &str) -> Option { + env::var(variable).ok().map(|value| value.parse().unwrap()) + } + + /// Runs the test binary again to sort `count` records in a process + /// that does nothing else, so that its memory is that of the sort. It + /// keeps `memory` bytes of records in memory and merges `most` runs at + /// once. + fn measured(count: u64, memory: usize, most: usize) { + let output = Command::new(env::current_exe().unwrap()) + .args(["--exact", "sort::tests::memory_is_bounded", "--nocapture"]) + .env(RECORDS, count.to_string()) + .env(MEMORY, memory.to_string()) + .env(RUNS, most.to_string()) + .output() + .unwrap(); + let said = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success(), + "{}\n{}", + said, + String::from_utf8_lossy(&output.stderr) + ); + // The harness can have its own words in front on the same line. + if let Some(measured) = said.lines().find_map(|line| line.find(MEASURED).map(|at| &line[at..])) { + println!("{}", measured); + } + } + + /// The memory of a sort is that of the records it holds and of a + /// buffer for each run of a merge, however many records it sorts. + #[test] + fn memory_is_bounded() { + match number(RECORDS) { + Some(count) => sort_records( + count, + number(MEMORY).unwrap_or(MEMORY_LIMIT), + number(RUNS).unwrap_or(MOST_RUNS), + ), + None => measured(250_000, MEMORY_LIMIT, MOST_RUNS), + } + } + + /// The same where the runs are so many that three passes merge them + /// before the last merge: a quarter of a megabyte of records in + /// memory, and four runs in a merge. + #[test] + fn memory_is_bounded_through_passes() { + measured(250_000, 256 * 1024, 4); + } + + /// The same for a million records. + #[test] + #[ignore = "sorts a million records"] + fn memory_is_bounded_for_a_million_records() { + measured(1_000_000, MEMORY_LIMIT, MOST_RUNS); + } + + /// The same for ten million records, with a scratch file of + /// gigabytes. + #[test] + #[ignore = "sorts ten million records"] + fn memory_is_bounded_for_ten_million_records() { + measured(10_000_000, MEMORY_LIMIT, MOST_RUNS); + } + + /// The same for ten million records in runs of a megabyte, eight of + /// which a merge takes: three passes before the last merge. + #[test] + #[ignore = "sorts ten million records in three passes"] + fn memory_is_bounded_for_ten_million_records_through_passes() { + measured(10_000_000, 1024 * 1024, 8); + } + + /// The same for a hundred and twenty million records, which are more + /// runs than a merge takes at once: a pass before the last merge, and + /// a scratch file of twenty gigabytes. + #[test] + #[ignore = "sorts a hundred and twenty million records"] + fn memory_is_bounded_for_more_runs_than_a_merge_takes() { + measured(120_000_000, MEMORY_LIMIT, MOST_RUNS); + } + + /// A sort and a merge can go to another thread. + #[test] + fn send() { + fn send() {} + send::(); + send::(); + } +} diff --git a/src/uapi16/sys.rs b/src/uapi16/sys.rs new file mode 100644 index 0000000..405f916 --- /dev/null +++ b/src/uapi16/sys.rs @@ -0,0 +1,4047 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The system calls that read the files of the host, for the manifest +//! builder and for PinnedDirectory. Each takes the descriptors and the +//! buffers it works on and returns what it found. None keeps any state of +//! its own, but for what the process found out about O_EMPTYPATH and about +//! open_tree(). +//! +//! A system call that fails with EINTR is made again, which a FUSE server +//! can answer any of them with. close() never is: Linux closes the +//! descriptor also when close() fails with EINTR, and by then its number +//! can be another file's. +//! +//! A file of a tree is opened by its name in its directory as a handle, +//! with O_PATH, which opens nothing behind it, and everything else is read +//! through that handle. The data of a regular file is read through the +//! handle opened again, never through the name: by then the name can lead +//! to another file, such as a device node, which would do what its driver +//! does on open. A directory is opened by its name in its directory +//! instead, with O_DIRECTORY and O_NOFOLLOW, which open nothing but a +//! directory, and it has to be the file of its handle. Nothing else is ever +//! opened. +//! +//! Nothing here mounts anything. The kernel mounts a file system on an +//! automount point when the directory is opened by its name or a name is +//! looked up in it, but not when its handle is taken. So an entry says +//! whether it is an automount point, see [`Entry::is_automount`], and one +//! that is one is not opened and has nothing opened in it. That leaves a +//! directory that becomes an automount point after its entry was looked at +//! and before it is opened by its name, see [`Entry::reopen`]. +//! +//! The ioctls rustix has no call for and the lookups in the user database +//! are in the modules ioctl and nss, which have the unsafe code for them. +//! They are called from here and handed on from here, so that this module +//! stays the one place that talks to the host. + +use std::collections::hash_map::RandomState; +use std::collections::{BTreeMap, HashMap}; +use std::ffi::{CStr, CString}; +use std::fs::File; +use std::hash::BuildHasher; +use std::io; +use std::ops::ControlFlow; +use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd}; +use std::os::unix::ffi::OsStrExt; +use std::path::{Path, PathBuf}; +use std::str; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::Arc; + +use pathrs::error::{Error as PathrsError, ErrorKind as PathrsErrorKind}; +use pathrs::flags::OpenFlags; +use pathrs::HandleRef; +use rustix::fs::{ + AtFlags, FallocateFlags, FileType, FsWord, IFlags, OFlags, RawDir, RenameFlags, Statx, StatxAttributes, StatxFlags, + StatxTimestamp, CWD, +}; +use rustix::io::{retry_on_intr, Errno}; +use rustix::mount::OpenTreeFlags; + +use crate::digest::Sha256Context; +use crate::error::Error; +use crate::ioctl; +pub(crate) use crate::ioctl::{DosAttributes, FsLabel, FsUuid}; +pub(crate) use crate::nss::UserDatabase; +use crate::object::{FatSerial, FileObject, InodeFlags}; +use crate::tree::{ + DataFailure, DeviceNumber, Entry, Failure, Handle, Identity, InodeId, MountId, Place, Status, Timestamp, Unreadable, +}; +use crate::{Features, Mode, Sha256, MAX_RECORD_SIZE, STRING_RULES, USER_NAMESPACE}; + +/// How much of a file is read at a time for its hash: the size of the +/// buffer the data is read through. +pub(crate) const DATA_BUFFER_SIZE: usize = 1024 * 1024; + +/// 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. +pub(crate) 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. + pub(crate) const FLAG: u32 = 1 << 26; + /// Not tried yet. + pub(crate) 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. + pub(crate) const MISSING: u8 = 2; +} + +/// The state of [`EmptyPath`] for this process. +pub(crate) static EMPTYPATH: AtomicU8 = AtomicU8::new(EmptyPath::UNKNOWN); + +/// What this process found out about open_tree(): whether it can be +/// called. Linux has it since 5.2, and a seccomp filter can refuse it, as +/// the default one of a container runtime does for a process that may not +/// mount. +struct OpenTree; + +impl OpenTree { + /// Nothing refused it so far, and it is called. + const CALLED: u8 = 0; + /// The kernel does not have the call, or a filter refused it, and it + /// is not called again. + const REFUSED: u8 = 1; +} + +/// The state of [`OpenTree`] for this process. +static OPEN_TREE: AtomicU8 = AtomicU8::new(OpenTree::CALLED); + +/// A regular file or a directory pinned by a handle, a descriptor opened +/// with O_PATH, through which it is opened for reading: without its name, +/// so that no other file can take its place. +#[derive(Clone, Copy, Debug)] +pub(crate) struct PinnedFile<'fd>(BorrowedFd<'fd>); + +impl<'fd> PinnedFile<'fd> { + /// How the file is opened: for reading, without waiting for anything, + /// without becoming the controlling terminal, and not inherited across + /// exec. + const READ_FLAGS: OFlags = OFlags::RDONLY + .union(OFlags::NONBLOCK) + .union(OFlags::NOCTTY) + .union(OFlags::CLOEXEC); + /// The same for the checked reopen of pathrs, which adds O_CLOEXEC on + /// its own. + const PATHRS_READ_FLAGS: OpenFlags = OpenFlags::O_RDONLY + .union(OpenFlags::O_NONBLOCK) + .union(OpenFlags::O_NOCTTY); + /// The regular file or the directory `handle` refers to. It has to be + /// one of the two: the file is opened whatever it is, a device node + /// with what its driver does on open. + pub(crate) fn new(handle: BorrowedFd<'fd>) -> PinnedFile<'fd> { + PinnedFile(handle) + } + + /// Opens the file for reading: through O_EMPTYPATH where the kernel + /// has it, probed the way systemd's fd_reopen() does, and through + /// procfs where it does not, with the checked reopen of pathrs. + pub(crate) fn reopen(self) -> io::Result { + let state = EMPTYPATH.load(Ordering::Relaxed); + if state != EmptyPath::MISSING { + match self.reopen_empty_path() { + Ok(file) => { + EMPTYPATH.store(EmptyPath::WORKS, Ordering::Relaxed); + return Ok(file); + } + // 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()), + } + } + self.reopen_procfs() + } + + /// The reopen through O_EMPTYPATH. + fn reopen_empty_path(self) -> rustix::io::Result { + let flags = PinnedFile::READ_FLAGS | OFlags::from_bits_retain(EmptyPath::FLAG); + let fd = retry_on_intr(|| rustix::fs::openat(self.0, "", flags, rustix::fs::Mode::empty()))?; + Ok(File::from(fd)) + } + + /// The checked reopen of pathrs, through a procfs of its own. + fn reopen_procfs(self) -> io::Result { + loop { + let reopened = HandleRef::from_fd(self.0) + .reopen(PinnedFile::PATHRS_READ_FLAGS) + .map_err(pathrs_io_error); + match reopened { + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + reopened => return reopened, + } + } + } +} + +/// The link procfs has for a descriptor of the calling thread, +/// /proc/thread-self/fd/N, which leads to the file of the descriptor. It is +/// the link of the thread and not that of /proc/self, the thread group +/// leader: a thread that took a descriptor table of its own has other +/// descriptors than the leader. +/// +/// What goes through the link is checked to be the inode of the descriptor, +/// by its device, its inode number and its subvolume: a /proc that is not +/// what it should be could lead elsewhere. What takes the path of the link +/// checks it before and after, see [`FdLink::check`]. That narrows what +/// such a /proc can do, but it doesn't close it: it can lead to the file +/// for the two checks and elsewhere in between. So only the extended +/// attributes of a file that is not open for reading are read through the +/// path, see [`UserXattrs`]. A link that a new file gets through it is +/// checked at the name the link made instead, see +/// [`NewFile::link_through`]. +#[derive(Debug)] +pub(crate) struct FdLink<'fd> { + fd: BorrowedFd<'fd>, + path: String, +} + +impl<'fd> FdLink<'fd> { + /// Where procfs has a link for every descriptor of the calling thread. + const THREAD_SELF_FD: &'static str = "/proc/thread-self/fd"; + + /// The link of the descriptor `fd`. + pub(crate) fn new(fd: BorrowedFd<'fd>) -> FdLink<'fd> { + FdLink { + fd, + path: format!("{}/{}", FdLink::THREAD_SELF_FD, fd.as_raw_fd()), + } + } + + /// The error for a link that leads to another file than that of the + /// descriptor. + fn elsewhere() -> io::Error { + io::Error::other("the link of /proc/thread-self/fd leads to another file") + } + + /// The path of the link, for what goes through it once it was checked. + pub(crate) fn path(&self) -> &str { + &self.path + } + + /// Checks that the link leads to the file of the descriptor, before the + /// path of the link is used and once more after, see [`FdLink`]. + pub(crate) fn check(&self) -> io::Result<()> { + let statx = + retry_on_intr(|| rustix::fs::statx(CWD, self.path.as_str(), AtFlags::NO_AUTOMOUNT, InodeId::REQUEST))?; + if InodeId::from_statx(&statx) != InodeId::of(self.fd)? { + return Err(FdLink::elsewhere()); + } + Ok(()) + } +} + +/// 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. +pub(crate) fn pathrs_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 InodeId { + /// What statx() is asked for to tell the inode of a file, which takes + /// no mount ID. + const REQUEST: StatxFlags = StatxFlags::INO.union(Status::SUBVOL); + + /// The inode of the file `fd` refers to. + fn of(fd: BorrowedFd<'_>) -> rustix::io::Result { + let statx = retry_on_intr(|| rustix::fs::statx(fd, c"", Status::OF_DESCRIPTOR, InodeId::REQUEST))?; + Ok(InodeId::from_statx(&statx)) + } + + /// The inode `statx` is of, with its subvolume where the mask has it. + fn from_statx(statx: &Statx) -> InodeId { + let mask = StatxFlags::from_bits_retain(statx.stx_mask); + InodeId { + device: DeviceNumber { + major: statx.stx_dev_major, + minor: statx.stx_dev_minor, + }, + inode: statx.stx_ino, + subvolume: mask.contains(Status::SUBVOL).then_some(statx.stx_subvol), + } + } +} + +impl Status { + /// STATX_MNT_ID_UNIQUE, include/uapi/linux/stat.h, which rustix has no + /// name for. A kernel before 6.8 does not know the bit and passes over + /// it. + const MNT_ID_UNIQUE: StatxFlags = StatxFlags::from_bits_retain(0x4000); + /// STATX_SUBVOL, include/uapi/linux/stat.h, which rustix has no name + /// for either. A kernel before 6.10 passes over it. + const SUBVOL: StatxFlags = StatxFlags::from_bits_retain(0x8000); + /// What statx() is asked for: the fields of `struct stat` but the + /// access time and the blocks, the birth time, the mount ID, the unique + /// one where the kernel has it, and the subvolume. A kernel since 5.8 + /// gives the mount ID unasked. + const REQUEST: StatxFlags = StatxFlags::TYPE + .union(StatxFlags::MODE) + .union(StatxFlags::NLINK) + .union(StatxFlags::UID) + .union(StatxFlags::GID) + .union(StatxFlags::MTIME) + .union(StatxFlags::CTIME) + .union(StatxFlags::INO) + .union(StatxFlags::SIZE) + .union(StatxFlags::BTIME) + .union(StatxFlags::MNT_ID) + .union(Status::MNT_ID_UNIQUE) + .union(Status::SUBVOL); + /// How statx() looks at the file a descriptor refers to: at the file + /// itself, a symbolic link too. + const OF_DESCRIPTOR: AtFlags = AtFlags::EMPTY_PATH.union(AtFlags::SYMLINK_NOFOLLOW); + + /// The status of the file `fd` refers to. + pub(crate) fn of(fd: BorrowedFd<'_>) -> Result { + Status::from_statx(&retry_on_intr(|| { + rustix::fs::statx(fd, c"", Status::OF_DESCRIPTOR, Status::REQUEST) + })?) + } + + /// The status `statx` gives. Without a mount ID there is none: the + /// kernel is older than 5.8. + /// + /// The fields of `struct stat` are taken whatever `stx_mask` says, as + /// stat() takes them. Every file system fills them in, and only a FUSE + /// server can leave some out of the mask. The other fields are taken + /// where the mask has them. + fn from_statx(statx: &Statx) -> Result { + let mask = StatxFlags::from_bits_retain(statx.stx_mask); + // Asked for the unique ID, a kernel that has it gives that one and + // says so instead of STATX_MNT_ID. + let mount = if mask.contains(Status::MNT_ID_UNIQUE) { + MountId::Unique(statx.stx_mnt_id) + } else if mask.contains(StatxFlags::MNT_ID) { + MountId::Reusable(statx.stx_mnt_id) + } else { + return Err(Failure::NoMountId); + }; + let mode = u32::from(statx.stx_mode); + Ok(Status { + identity: Identity { + mount, + device: DeviceNumber { + major: statx.stx_dev_major, + minor: statx.stx_dev_minor, + }, + inode: statx.stx_ino, + subvolume: mask.contains(Status::SUBVOL).then_some(statx.stx_subvol), + }, + file_type: FileType::from_raw_mode(mode), + mode: Mode::from_st_mode(mode), + nlink: statx.stx_nlink, + uid: statx.stx_uid, + gid: statx.stx_gid, + size: statx.stx_size, + mtime: statx.stx_mtime.into(), + ctime: statx.stx_ctime.into(), + btime: mask.contains(StatxFlags::BTIME).then(|| statx.stx_btime.into()), + rdev: DeviceNumber { + major: statx.stx_rdev_major, + minor: statx.stx_rdev_minor, + }, + }) + } +} + +impl<'fd> Entry<'fd> { + /// How an entry is opened: as a handle, which needs no permission on + /// the file and opens nothing behind it, the symbolic link itself where + /// it is one, and not inherited across exec. + const HANDLE_FLAGS: OFlags = OFlags::PATH.union(OFlags::NOFOLLOW).union(OFlags::CLOEXEC); + /// The same for open_tree(), which opens such a handle and is told + /// outright not to mount anything on an automount point. + const TREE_FLAGS: OpenTreeFlags = OpenTreeFlags::AT_NO_AUTOMOUNT + .union(OpenTreeFlags::AT_SYMLINK_NOFOLLOW) + .union(OpenTreeFlags::OPEN_TREE_CLOEXEC); + /// `AUTOFS_SUPER_MAGIC`, include/uapi/linux/magic.h: the type statfs() + /// gives for autofs, the file system of the automount points an + /// automount unit of systemd or automount(8) makes. + const AUTOFS_SUPER_MAGIC: FsWord = 0x0187; + /// How a directory is opened by its name for reading: as a directory + /// and nothing else, not through a symbolic link, and not inherited + /// across exec. + const DIRECTORY_FLAGS: OFlags = OFlags::RDONLY + .union(OFlags::DIRECTORY) + .union(OFlags::NOFOLLOW) + .union(OFlags::CLOEXEC); + + /// Opens the entry `name` of the directory `dir`, one component and + /// neither `.` nor `..`, such as a name of the listing of `dir`. `dir` + /// is no automount point: nothing is looked up in one. + /// + /// Taking the handle mounts nothing on an automount point: open_tree() + /// is told not to, and where it can't be called, openat() with O_PATH + /// doesn't either for the last component of a name, which is all there + /// is of this one. + pub(crate) fn open_at(dir: BorrowedFd<'_>, name: &CStr) -> Result, Failure> { + debug_assert!(!matches!(name.to_bytes(), b"" | b"." | b"..") && !name.to_bytes().contains(&b'/')); + let handle = Entry::handle_at(dir, name)?; + Entry::of_handle(Handle::Owned(handle), true) + } + + /// The entry of the file `handle` refers to, a descriptor that a caller + /// gave: a handle, or the file open for reading. The entry borrows the + /// descriptor, and neither duplicates nor closes it. + pub(crate) fn of(handle: BorrowedFd<'fd>) -> Result, Failure> { + Entry::of_handle(Handle::Borrowed(handle), false) + } + + /// Takes the handle of the entry `name` of the directory `dir` with + /// open_tree(), and with openat() where open_tree() can't be called: + /// the kernel fails it with ENOSYS where it does not have it, and a + /// seccomp filter refuses it with that or with EPERM, also one that the + /// process got after open_tree() worked. openat() takes the same + /// handle, so an EPERM that was the file's own after all is what + /// openat() fails with as well. + fn handle_at(dir: BorrowedFd<'_>, name: &CStr) -> rustix::io::Result { + if OPEN_TREE.load(Ordering::Relaxed) != OpenTree::REFUSED { + match retry_on_intr(|| rustix::mount::open_tree(dir, name, Entry::TREE_FLAGS)) { + Err(Errno::NOSYS | Errno::PERM) => OPEN_TREE.store(OpenTree::REFUSED, Ordering::Relaxed), + taken => return taken, + } + } + retry_on_intr(|| rustix::fs::openat(dir, name, Entry::HANDLE_FLAGS, rustix::fs::Mode::empty())) + } + + /// The entry of the handle `handle`, with its status and whether it is + /// an automount point, see [`Entry::is_automount`]. Both are told from + /// the handle, before anything is opened. + /// + /// A file system that mounts something on a directory of its own, as + /// NFS, SMB, AFS and debugfs do, says so in statx(), with + /// STATX_ATTR_AUTOMOUNT. autofs does not, and every directory of it can + /// be one. So a directory is one as well where statfs() says that its + /// file system is autofs, as for systemd's CHASE_NO_AUTOFS. + /// + /// `opened_here` says that the handle was opened in a directory that is + /// no automount point, as [`Entry::open_at`] opens one. Such a + /// directory is not on autofs, and what is in it is on its file system, + /// unless something is mounted there, which the handle is the root of + /// then. So only the root of a mount can be on autofs, and only that is + /// asked for its file system then, where statx() tells one, which it + /// does since Linux 5.8. + fn of_handle(handle: Handle<'fd>, opened_here: bool) -> Result, Failure> { + let statx = retry_on_intr(|| rustix::fs::statx(&handle, c"", Status::OF_DESCRIPTOR, Status::REQUEST))?; + let status = Status::from_statx(&statx)?; + let mut automount = false; + if status.file_type == FileType::Directory { + let tells_root = statx.stx_attributes_mask.contains(StatxAttributes::MOUNT_ROOT); + let root = statx.stx_attributes.contains(StatxAttributes::MOUNT_ROOT); + automount = statx.stx_attributes.contains(StatxAttributes::AUTOMOUNT); + if !automount && (root || !tells_root || !opened_here) { + let file_system = retry_on_intr(|| rustix::fs::fstatfs(&handle))?; + automount = file_system.f_type == Entry::AUTOFS_SUPER_MAGIC; + } + } + Ok(Entry::new(handle, status, automount)) + } + + /// The target of the symbolic link of the entry, read through its + /// handle. It is the bytes of the link, which need not be UTF-8. + pub(crate) fn target(&self) -> Result, Failure> { + Ok(retry_on_intr(|| rustix::fs::readlinkat(self.handle(), c"", Vec::new()))?.into_bytes()) + } + + /// Opens the regular file or the directory of the entry for reading, so + /// that no other file takes its place. A regular file is opened through + /// its handle and never through its name, as [`PinnedFile`] opens one. + /// A directory is opened by its name in its directory, `place`, with + /// O_DIRECTORY and O_NOFOLLOW, which refuse anything else with ENOTDIR + /// before it is opened, and what is opened has to be the file of the + /// entry. That takes no procfs, and nothing but the permission to read + /// the directory, which its listing takes anyway. A directory without a + /// place, that of a descriptor a caller gave, such as the top directory + /// of a walk, has no name to be opened by, and is opened through its + /// handle as a regular file is. Anything else fails with EINVAL and is + /// not opened: a FIFO or a device node would do what its driver does on + /// open, and an automount point opened by its name would have a file + /// system mounted on it, see [`Entry::is_automount`]. + /// + /// Whether the entry is an automount point was told when its handle was + /// taken. A directory that becomes one after that and before it is + /// opened by its name has its file system mounted by that open, which + /// then is the root of that file system and not the file of the entry: + /// the tree changed. This is a known limit, and nothing here closes it. + /// It takes someone who can mount in the mount namespace of the + /// process, or an automount unit that is started at that moment. + pub(crate) fn reopen(&self, place: Option>) -> Result { + match (self.status().file_type, place) { + (FileType::Directory, _) if self.is_automount() => Err(Errno::INVAL.into()), + (FileType::Directory, Some(place)) => self.reopen_directory(place), + (FileType::RegularFile | FileType::Directory, _) => Ok(Readable(PinnedFile::new(self.handle()).reopen()?)), + _ => Err(Errno::INVAL.into()), + } + } + + /// Opens the directory of the entry by its name in its directory, + /// `place`. Where the name leads to nothing by then, to something that + /// is not a directory or to another directory, the tree changed. + fn reopen_directory(&self, place: Place<'_>) -> Result { + let opened = retry_on_intr(|| { + rustix::fs::openat(place.dir, place.name, Entry::DIRECTORY_FLAGS, rustix::fs::Mode::empty()) + }); + let directory = match opened { + Ok(directory) => directory, + Err(Errno::NOENT | Errno::NOTDIR) => return Err(Failure::Changed), + Err(e) => return Err(e.into()), + }; + if Status::of(directory.as_fd())?.identity != self.status().identity { + return Err(Failure::Changed); + } + Ok(Readable(File::from(directory))) + } +} + +/// A regular file or a directory of a tree, opened for reading, see +/// [`Entry::reopen`]. The data of a regular file is read through it, the +/// entries of a directory are listed through it, and the inode flags, the +/// DOS attributes, the extended attributes and the identity of the file +/// system are read through it, which a handle cannot be asked for. +#[derive(Debug)] +pub(crate) struct Readable(File); + +impl Readable { + /// What a file system fails an ioctl with that it does not have: ENOTTY + /// as a rule, and what systemd takes for the same besides. + const NOT_SUPPORTED: [Errno; 4] = [Errno::NOTTY, Errno::OPNOTSUPP, Errno::NOSYS, Errno::INVAL]; + /// The inode flags the specification has a field for, as the kernel + /// has them, each with its flag in a manifest. + const INODE_FLAGS: [(IFlags, InodeFlags); 5] = [ + (IFlags::APPEND, InodeFlags::APPEND_ONLY), + (IFlags::IMMUTABLE, InodeFlags::IMMUTABLE), + (IFlags::NOATIME, InodeFlags::NO_ATIME), + (IFlags::NOCOW, InodeFlags::NO_COW), + (IFlags::NODUMP, InodeFlags::NO_DUMP), + ]; + + /// The descriptor, which the entries of a directory are listed + /// through. + pub(crate) fn as_fd(&self) -> BorrowedFd<'_> { + self.0.as_fd() + } + + /// What the file system answers the ioctl `ask` makes with, or nothing + /// if it does not have the ioctl. + fn answer(ask: impl FnMut() -> rustix::io::Result) -> io::Result> { + match retry_on_intr(ask) { + Ok(answer) => Ok(Some(answer)), + Err(e) if Readable::NOT_SUPPORTED.contains(&e) => Ok(None), + Err(e) => Err(e.into()), + } + } + + /// Those of the inode flags the specification has a field for that are + /// set on the file, or nothing if its file system has no inode flags. + pub(crate) fn inode_flags(&self) -> io::Result> { + let Some(set) = Readable::answer(|| rustix::fs::ioctl_getflags(&self.0))? else { + return Ok(None); + }; + let flags = Readable::INODE_FLAGS + .into_iter() + .filter(|(flag, _)| set.contains(*flag)) + .fold(InodeFlags::default(), |flags, (_, flag)| flags | flag); + Ok(Some(flags)) + } + + /// The DOS attributes of the file, or nothing if its file system has + /// none. Whatever answers the ioctl has them: FAT and exFAT, and a + /// FUSE server that implements it. + pub(crate) fn dos_attributes(&self) -> io::Result> { + Readable::answer(|| ioctl::dos_attributes(self.as_fd())) + } + + /// The volume serial number of the FAT file system the file is in, or + /// nothing if it is in another file system. + pub(crate) fn fat_serial(&self) -> io::Result> { + Readable::answer(|| ioctl::fat_serial(self.as_fd())) + } + + /// The label of the file system the file is in, or nothing if the file + /// system cannot say. + pub(crate) fn fs_label(&self) -> io::Result> { + Readable::answer(|| ioctl::fs_label(self.as_fd())) + } + + /// What the file system the file is in identifies itself with, or + /// nothing if it has no identifier or the kernel is older than Linux + /// 6.9. + pub(crate) fn fs_uuid(&self) -> io::Result> { + Readable::answer(|| ioctl::fs_uuid(self.as_fd())) + } + + /// The entries of the directory this is, which lists them from the + /// first one on. + pub(crate) fn entries(self) -> Entries { + Entries { + dir: OwnedFd::from(self.0), + names: Vec::new(), + next: 0, + size: Entries::FIRST_SIZE, + done: false, + } + } +} + +/// The entries of a directory of a tree, in the order getdents() gives +/// them, read through the directory opened for reading, see +/// [`Entry::reopen`] and [`Readable::entries`]. The entries are opened in +/// the directory as well, so it is the one descriptor a walk keeps of a +/// directory it is in. +#[derive(Debug)] +pub(crate) struct Entries { + dir: OwnedFd, + /// The names of the entries getdents() gave the last time, each with + /// its NUL, and where the next one to hand out starts. + names: Vec, + next: usize, + /// How many bytes getdents() reads into the next time. + size: usize, + /// Whether getdents() said that there are no more entries, or failed. + done: bool, +} + +impl Entries { + /// The names a directory has for itself and for the one above it. + const ITSELF_AND_PARENT: [&'static [u8]; 2] = [b".", b".."]; + /// How many bytes getdents() reads into the first time, and the most it + /// reads into. It reads twice as much each time up to that, so that a + /// small directory takes little memory while a walk is below it, and a + /// large one takes few calls, as rustix's Dir does. + /// + /// The first is room for an entry with the longest name there is, one + /// of FUSE with 4095 bytes, whose entry takes 4120, and whose entry for + /// the server takes 4248 with READDIRPLUS. FUSE asks its server for as + /// many bytes as getdents() has room for, and for a page at least. A + /// server that can't fit the first entry into that replies with + /// nothing, and getdents() returns that as 0, which nobody can tell + /// from the end of the directory. So the room has to be enough from the + /// first call on, and 8 KiB is, whatever the size of a page. That holds + /// for what FUSE means to ask for. It reads into pages it allocates for + /// the request, and where it gets fewer than it asked for, + /// fuse_readdir_alloc_buf() makes the request as small as the pages it + /// got, down to one. So under memory pressure a name of 4073 bytes or + /// more can still end the listing of its directory on 4 KiB pages, + /// whatever room getdents() has, and nothing here can tell. Other file + /// systems fail getdents() with EINVAL where the first entry does not + /// fit, and the room grows then, see [`Entries::read`]. + const FIRST_SIZE: usize = 8 * 1024; + const MOST_SIZE: usize = 32 * 1024; + + /// The descriptor of the directory, which its entries are opened in. + pub(crate) fn as_fd(&self) -> BorrowedFd<'_> { + self.dir.as_fd() + } + + /// The status of the directory now. + pub(crate) fn status(&self) -> Result { + Status::of(self.as_fd()) + } + + /// Reads the names of the next entries with getdents(), and again where + /// it fails with EINTR: a getdents() that fails gave no entries and + /// did not move on in the directory. Unlike RawDir, rustix's Dir ends a + /// listing at the first error with the libc backend, as on powerpc and + /// s390x, and can't be asked again. Where the first entry getdents() + /// would give does not fit, it fails with EINVAL, and it is asked again + /// with twice the room, up to the most there is. + fn read(&mut self) -> rustix::io::Result<()> { + self.names.clear(); + self.next = 0; + loop { + let size = self.size; + // The names take less room than the entries they are of. + self.names.reserve(size); + let mut buffer = Vec::with_capacity(size); + self.size = (size * 2).min(Entries::MOST_SIZE); + let mut dir = RawDir::new(&self.dir, buffer.spare_capacity_mut()); + loop { + match dir.next() { + None => { + self.done = true; + return Ok(()); + } + Some(Err(Errno::INTR)) => {} + Some(Err(Errno::INVAL)) if self.names.is_empty() && size < Entries::MOST_SIZE => break, + Some(Err(e)) => return Err(e), + Some(Ok(entry)) => { + self.names.extend_from_slice(entry.file_name().to_bytes_with_nul()); + if dir.is_buffer_empty() { + return Ok(()); + } + } + } + } + } + } +} + +impl Iterator for Entries { + type Item = Result; + + /// The next entry of the directory, passing over `.` and `..`, or + /// nothing after the last one. Once reading failed, nothing comes. + fn next(&mut self) -> Option> { + loop { + let rest = &self.names[self.next..]; + if let Some(len) = rest.iter().position(|&byte| byte == 0) { + self.next += len + 1; + let name = &rest[..len]; + if !Entries::ITSELF_AND_PARENT.contains(&name) { + let name = CString::new(name).expect("a name getdents() gives ends at its NUL"); + return Some(Ok(Listed(name))); + } + continue; + } + if self.done { + return None; + } + if let Err(e) = self.read() { + self.done = true; + return Some(Err(e.into())); + } + } + } +} + +/// An entry of a directory as its listing has it: its name, and nothing +/// else that is used, since that is read through its handle. +#[derive(Debug)] +pub(crate) struct Listed(CString); + +impl Listed { + /// The name of the entry in the directory, which need not be UTF-8. + pub(crate) fn name(&self) -> &CStr { + &self.0 + } +} + +/// Reads the extended attributes of the user namespace of the files of a +/// tree. Those of a file that is open for reading anyway are read through +/// that descriptor, see [`Entry::reopen`]: a directory that is listed, a +/// regular file that is opened for the hash of its data, and either of +/// them where it is opened for its inode flags, its DOS attributes or the +/// identity of its file system. Nothing is opened for its attributes +/// alone, so a file that may not be opened still has them read, and +/// reading them is never an open that others see. The system calls that +/// take a descriptor refuse a handle, also those of Linux 6.13 that take a +/// descriptor and an empty path. So the attributes of any other file are +/// read through the link procfs has for its handle, see [`FdLink`], which +/// leads to the file itself, the way systemd reads them. +/// +/// It keeps what it reads into from one file to the next. +#[derive(Debug, Default)] +pub(crate) struct UserXattrs { + /// The names of the attributes of the file, each with a NUL behind it, + /// as listxattr() gives them. + names: Vec, + /// The value of one attribute. + value: Vec, +} + +impl UserXattrs { + /// `XATTR_LIST_MAX`, include/uapi/linux/limits.h: the most bytes the + /// names of the attributes of a file take. + const LIST_MAX: usize = 65536; + /// `XATTR_SIZE_MAX`, include/uapi/linux/limits.h: the most bytes the + /// value of an attribute has. + const SIZE_MAX: usize = 65536; + /// What ends a name in the list of names. + const NAME_END: u8 = b'\0'; + /// What separates the namespace of an attribute from its name. + const NAMESPACE_SEPARATOR: u8 = b'.'; + + /// A reader that has read nothing yet. + pub(crate) fn new() -> UserXattrs { + UserXattrs::default() + } + + /// The name `full`, as listxattr() lists it, without the namespace in + /// front, if it is in the user namespace. + fn in_user_namespace(full: &[u8]) -> Option<&[u8]> { + full.strip_prefix(USER_NAMESPACE.as_bytes())? + .strip_prefix(&[UserXattrs::NAMESPACE_SEPARATOR]) + } + + /// The attributes of the user namespace of the regular file or the + /// directory `file`, which is open for reading, by their names without + /// the namespace. + /// + /// A name a manifest cannot hold fails, since a manifest lists all + /// attributes of a file or none. So do attributes that take more than + /// a record of a manifest has room for, before they are all read. An + /// attribute that is gone by the time its value is read is left out. + pub(crate) fn read(&mut self, file: &Readable) -> Result>, Failure> { + self.read_from(XattrSource::File(file.as_fd())) + } + + /// The same for the file of `entry`, which is not open for reading, + /// through the link procfs has for its handle, see [`FdLink`]. A + /// symbolic link cannot have any, and is not asked. Without a procfs + /// they can't be read. A file that is gone by now can look like that, + /// and fails as one that changed. + pub(crate) fn read_unopened(&mut self, entry: &Entry<'_>) -> Result>, Failure> { + debug_assert_ne!(entry.status().file_type, FileType::Symlink); + let link = FdLink::new(entry.handle()); + match link.check() { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => { + // The link is not there without a procfs. A file system + // can also say so of a file that was removed, as a FUSE + // file system does that finds its files by their names. + // The handle itself tells the two apart. + return Err(match InodeId::of(entry.handle()) { + Err(Errno::NOENT | Errno::STALE) => Failure::Changed, + _ => Failure::Unavailable(Features::USER_XATTR, Unreadable::NoProcfs), + }); + } + Err(e) => return Err(e.into()), + } + let attributes = self.read_from(XattrSource::Link(link.path()))?; + // Where the link led elsewhere for a while, what was read can be of + // another file. + link.check()?; + Ok(attributes) + } + + /// Reads the attributes of the file `source` leads to. + fn read_from(&mut self, source: XattrSource<'_>) -> Result>, Failure> { + let unavailable = |why| Failure::Unavailable(Features::USER_XATTR, why); + let mut attributes = BTreeMap::new(); + self.names.resize(UserXattrs::LIST_MAX, 0); + let listed = match retry_on_intr(|| source.list(&mut self.names[..])) { + Ok(listed) => listed, + Err(Errno::OPNOTSUPP | Errno::NOSYS) => return Err(unavailable(Unreadable::NoXattrs)), + Err(e) => return Err(e.into()), + }; + let mut size = 0; + for full in self.names[..listed].split(|&byte| byte == UserXattrs::NAME_END) { + let Some(name) = UserXattrs::in_user_namespace(full) else { + continue; + }; + let name = str::from_utf8(name) + .ok() + .filter(|name| FileObject::is_xattr_name(name) && STRING_RULES.admits(name)) + .ok_or(unavailable(Unreadable::XattrName))?; + self.value.resize(UserXattrs::SIZE_MAX, 0); + let len = match retry_on_intr(|| source.get(full, &mut self.value[..])) { + Ok(len) => len, + // Removed since it was listed, or listed on a file that + // cannot have one. + Err(Errno::NODATA) => continue, + Err(Errno::OPNOTSUPP | Errno::NOSYS) => return Err(unavailable(Unreadable::NoXattrs)), + Err(e) => return Err(e.into()), + }; + size += name.len() + len; + if size > MAX_RECORD_SIZE { + return Err(Failure::TooLarge); + } + attributes.insert(name.to_owned(), self.value[..len].to_vec()); + } + Ok(attributes) + } +} + +/// What the extended attributes of a file are read through. +#[derive(Clone, Copy, Debug)] +enum XattrSource<'a> { + /// The file open for reading, with flistxattr() and fgetxattr(). + File(BorrowedFd<'a>), + /// The path of the link procfs has for the handle of a file that is not + /// open for reading, with listxattr() and getxattr(), which follow the + /// link. llistxattr() and lgetxattr() would read the link itself. + Link(&'a str), +} + +impl XattrSource<'_> { + /// Lists the names of the attributes into `names`. + fn list(self, names: &mut [u8]) -> rustix::io::Result { + match self { + XattrSource::File(fd) => rustix::fs::flistxattr(fd, names), + XattrSource::Link(path) => rustix::fs::listxattr(path, names), + } + } + + /// Reads the value of the attribute `name` into `value`. + fn get(self, name: &[u8], value: &mut [u8]) -> rustix::io::Result { + match self { + XattrSource::File(fd) => rustix::fs::fgetxattr(fd, name, value), + XattrSource::Link(path) => rustix::fs::getxattr(path, name, value), + } + } +} + +/// A name nobody can guess, which a file has in a directory for a while: a +/// scratch file on a file system without O_TMPFILE until it loses it right +/// away, and a new file until it gets its own. Nobody else has it, so only +/// the one who made the file removes it. +#[derive(Debug)] +pub(crate) struct TemporaryName(CString); + +impl TemporaryName { + /// How many names that something else has are tried before giving up. + const ATTEMPTS: u32 = 16; + + /// Makes a file in the directory `dir` with a name that starts with + /// `prefix` and that nothing has, opened with `flags`, which have + /// O_CREAT and O_EXCL, and with the access mode `mode`. + fn create( + dir: BorrowedFd<'_>, + prefix: &str, + flags: OFlags, + mode: rustix::fs::Mode, + ) -> io::Result<(OwnedFd, TemporaryName)> { + TemporaryName::make(dir, prefix, |name| rustix::fs::openat(dir, name, flags, mode)) + } + + /// Links the file `path` leads to into the directory `dir`, with a name + /// that starts with `prefix` and that nothing has. A symbolic link at + /// the end of `path` is followed, as the link procfs has for a + /// descriptor has to be. + fn link(dir: BorrowedFd<'_>, prefix: &str, path: &str) -> io::Result { + let flags = AtFlags::SYMLINK_FOLLOW; + let ((), name) = TemporaryName::make(dir, prefix, |name| rustix::fs::linkat(CWD, path, dir, name, flags))?; + Ok(name) + } + + /// Makes something with a name in the directory `dir` that starts with + /// `prefix` and that nothing has, with `make`, which fails with EEXIST + /// where something has the name it is given. + fn make( + dir: BorrowedFd<'_>, + prefix: &str, + mut make: impl FnMut(&CStr) -> rustix::io::Result, + ) -> io::Result<(T, TemporaryName)> { + // The keys of a hasher of std are random, and so is what it makes + // of a number. + let random = RandomState::new(); + let mut taken = 0; + for number in 0_u64.. { + let name = format!("{}{:016x}", prefix, random.hash_one(number)); + let name = TemporaryName(CString::new(name).expect("a formatted name has no NUL")); + match make(name.as_c_str()) { + Ok(made) => return Ok((made, name)), + Err(Errno::EXIST) => { + taken += 1; + if taken == TemporaryName::ATTEMPTS { + break; + } + } + // What was interrupted can have made the name before it + // failed, and the same again fails with EEXIST then. So it + // is not made again: the name, which nobody else has, is + // removed, and the next one is tried. That is no name + // something else has, and does not count as one. + Err(Errno::INTR) => name.remove(dir)?, + Err(e) => return Err(e.into()), + } + } + Err(Errno::EXIST.into()) + } + + /// The name, which need not be UTF-8 for anybody else. + fn as_c_str(&self) -> &CStr { + &self.0 + } + + /// Removes the name from the directory `dir`. A removal that was + /// interrupted can have removed it before it failed, so one that finds + /// the name gone is done. + fn remove(&self, dir: BorrowedFd<'_>) -> rustix::io::Result<()> { + match retry_on_intr(|| rustix::fs::unlinkat(dir, self.as_c_str(), AtFlags::empty())) { + Ok(()) | Err(Errno::NOENT) => Ok(()), + Err(e) => Err(e), + } + } +} + +/// The files a manifest that is being built made itself and has open, such +/// as its scratch files. A walk of a tree that they are in passes over +/// them. They are known by their inodes and not by their names: a file +/// system can keep a file that was unlinked while it is open in its +/// directory, under a name of its own. NFS does, and so does libfuse for a +/// FUSE file system on its high-level interface that does not set +/// hard_remove. +/// +/// The inode alone does not make a file one of them. A file system can +/// give two files the same device and the same inode number: a FUSE file +/// system that shows the files of two file systems with the inode numbers +/// they have there does. So each of these files is kept open with its +/// inode, and a file a walk comes to with that inode is one of them only +/// if its status is the status of the open file as well, see +/// [`OwnFiles::contains`]. A file of the tree that only has the number of +/// one of them is listed like any other. Two of these files can have one +/// inode as well. Both are kept open with it then, and a file with that +/// inode is one of them if its status is the status of either. +/// +/// A scratch file is one of them from when it is made, and it stays one and +/// stays open once whoever made it is done with it. It is closed when these +/// files are dropped, which is not before whoever walks trees for the +/// manifest is, see +/// [`Scratch::own_files`](crate::scratch::Scratch::own_files). A file that +/// was closed could not be one of them: nothing is left that a file with +/// its inode could be held against. And a file system that keeps an +/// unlinked file under a name removes that name some time after the file +/// was closed, without anybody waiting for it, as FUSE and NFS do. A walk +/// that comes to the name in between would list a file of the manifest's +/// own, or fail because the file is gone when it is opened. So a scratch +/// file that is given back is only emptied, which gives its room back. It +/// takes a descriptor and nothing else until it is handed out again, which +/// it is before a new file is made, see +/// [`Scratch::file`](crate::scratch::Scratch::file). +/// +/// The file a manifest is written to is one of them as well, while it has a +/// name of its own until it gets its name, see [`NewFile::named_file`]. It +/// is kept through the descriptor its [`NewFile`] has of it. +#[derive(Debug, Default)] +pub(crate) struct OwnFiles { + /// The files by their inodes, each of them open. An inode has every + /// file that was kept with it, in the order they were kept: one file, + /// and more where the file system gave its inode to another one of the + /// files as well. No file is ever taken out of them, so each of them is + /// open for as long as this is there. + open: HashMap>>, + /// The scratch files among them that were given back and emptied, and + /// that were not handed out since. + given_back: Vec>, +} + +impl OwnFiles { + /// Takes the file `file`, which has the inode `inode`, as one of the + /// files, and keeps it open for as long as they are there. A file that + /// was kept with that inode before stays one of them, and open, next to + /// it. + pub(crate) fn keep(&mut self, inode: InodeId, file: Arc) { + self.open.entry(inode).or_default().push(file); + } + + /// Whether the file with the status `found`, which a walk came to, is + /// one of the files: it has the inode of one of them, and its status + /// is the one that file has now, see [`Status::matches`]. Where several + /// of the files have that inode, it is held against one after the + /// other, until its status is that of one of them. That takes one + /// statx() of each open file it is held against: at most as many as + /// have that inode, and none where no file has it. Where the status of + /// one of them can't be read, this fails. + pub(crate) fn contains(&self, found: &Status) -> Result { + let own = self.open.get(&found.identity.inode_id()); + for file in own.into_iter().flatten() { + if found.matches(&Status::of(file.as_fd())?) { + return Ok(true); + } + } + Ok(false) + } + + /// Takes back the scratch file `file`, one of the files, which whoever + /// had it is done with. It is emptied, which gives its room back, and + /// it is handed out again where another one is needed. A file that + /// cannot be emptied is kept as it is, and its room with it, until it + /// is closed. It is never handed out again. + pub(crate) fn take_back(&mut self, file: ScratchFile) { + if file.set_len(0).is_ok() { + self.given_back.push(file.file); + } + } + + /// A scratch file that was given back and emptied, if there is one that + /// was not handed out since. It is one of the files as it was, with the + /// inode it had. + pub(crate) fn hand_out(&mut self) -> Option { + let file = self.given_back.pop()?; + Some(ScratchFile { file }) + } +} + +/// A file without a name, which the builder keeps in what it cannot keep +/// in memory. It is read and written at the offsets the caller gives, and +/// it is gone once it is closed, also when the process dies. It is one of +/// the files of its builder, which keep it open: one that is given back to +/// them is emptied and handed out again where another one is needed, see +/// [`OwnFiles::take_back`], and one that is dropped stays as it is. Both +/// are closed with them. +#[derive(Debug)] +pub(crate) struct ScratchFile { + /// The file, which the files of its builder have as well. + file: Arc, +} + +impl ScratchFile { + /// How a directory is opened that scratch files are made in: as a + /// handle, for a directory and nothing else. + const DIRECTORY_FLAGS: OFlags = OFlags::PATH.union(OFlags::DIRECTORY).union(OFlags::CLOEXEC); + /// How a file without a name is made: with O_TMPFILE, for reading and + /// writing, and with O_EXCL, which for such a file says that it never + /// gets a name. + const UNNAMED_FLAGS: OFlags = OFlags::TMPFILE + .union(OFlags::RDWR) + .union(OFlags::EXCL) + .union(OFlags::CLOEXEC); + /// How a file is made that loses its name right away: only if nothing + /// has that name, a symbolic link included. + const NAMED_FLAGS: OFlags = OFlags::CREATE + .union(OFlags::EXCL) + .union(OFlags::RDWR) + .union(OFlags::NOFOLLOW) + .union(OFlags::CLOEXEC); + /// Only the owner reads and writes a scratch file. + const MODE: rustix::fs::Mode = rustix::fs::Mode::RUSR.union(rustix::fs::Mode::WUSR); + /// The name a directory has in itself, which a file without a name is + /// made in. + const ITSELF: &'static CStr = c"."; + /// What the name of a file that loses its name right away starts with. + const NAME_PREFIX: &'static str = ".uapi16-"; + /// How the room of a part of a file is given back: as a hole, which + /// leaves the file as long as it is. fallocate() takes + /// FALLOC_FL_PUNCH_HOLE only together with FALLOC_FL_KEEP_SIZE. + const PUNCH_FLAGS: FallocateFlags = FallocateFlags::PUNCH_HOLE.union(FallocateFlags::KEEP_SIZE); + + /// Opens the directory `path` as one that scratch files are made in. + pub(crate) fn open_directory(path: &Path) -> io::Result { + Ok(retry_on_intr(|| { + rustix::fs::open(path, ScratchFile::DIRECTORY_FLAGS, rustix::fs::Mode::empty()) + })?) + } + + /// Makes a file without a name in the file system of the directory + /// `dir`, which is one of the files `own`. Where the file system cannot + /// make one, the file is made with a name that nothing has and loses it + /// at once, as for systemd's open_tmpfile_unlinkable(): the file system + /// says EOPNOTSUPP then, and a kernel that does not know O_TMPFILE tries + /// to open the directory for writing and says EISDIR. + pub(crate) fn create_in(dir: BorrowedFd<'_>, own: &mut OwnFiles) -> io::Result { + match ScratchFile::create_unnamed(dir, own) { + Ok(file) => Ok(file), + Err(Errno::OPNOTSUPP | Errno::ISDIR) => ScratchFile::create_and_unlink(dir, own), + Err(e) => Err(e.into()), + } + } + + /// Makes a file without a name with O_TMPFILE. + fn create_unnamed(dir: BorrowedFd<'_>, own: &mut OwnFiles) -> rustix::io::Result { + let file = retry_on_intr(|| { + rustix::fs::openat(dir, ScratchFile::ITSELF, ScratchFile::UNNAMED_FLAGS, ScratchFile::MODE) + })?; + ScratchFile::new(file, own) + } + + /// Makes a file with a name nobody can guess and removes the name. + fn create_and_unlink(dir: BorrowedFd<'_>, own: &mut OwnFiles) -> io::Result { + let (file, name) = TemporaryName::create( + dir, + ScratchFile::NAME_PREFIX, + ScratchFile::NAMED_FLAGS, + ScratchFile::MODE, + )?; + name.remove(dir)?; + Ok(ScratchFile::new(file, own)?) + } + + /// The scratch file `file`, which was just made, as one of the files + /// `own`. + fn new(file: OwnedFd, own: &mut OwnFiles) -> rustix::io::Result { + let inode = InodeId::of(file.as_fd())?; + let file = Arc::new(File::from(file)); + own.keep(inode, Arc::clone(&file)); + Ok(ScratchFile { file }) + } + + /// Makes the file `len` bytes long. What it gains reads as zeroes and + /// takes no room until it is written. + pub(crate) fn set_len(&self, len: u64) -> io::Result<()> { + Ok(retry_on_intr(|| rustix::fs::ftruncate(&self.file, len))?) + } + + /// The size of a block of the file in bytes, as statx() reports it: the + /// block size of the file system, or several blocks where the file + /// system does its I/O in more than one. + pub(crate) fn block_size(&self) -> io::Result { + let statx = retry_on_intr(|| rustix::fs::statx(&self.file, c"", Status::OF_DESCRIPTOR, StatxFlags::empty()))?; + Ok(u64::from(statx.stx_blksize)) + } + + /// Gives the room of the `len` bytes of the file at `offset` back to + /// the file system, as a hole: the bytes read as zeroes from then on, + /// and the file stays as long as it is. `len` is not 0. + /// + /// A file system gives back whole blocks. What the range has of a + /// block that is not all in it is only written over with zeroes, so a + /// caller that wants room back asks for whole blocks, see + /// [`ScratchFile::block_size`]. + /// + /// Not every file system can punch holes. One that cannot fails with + /// EOPNOTSUPP and leaves the file as it was. + pub(crate) fn punch_hole(&self, offset: u64, len: u64) -> io::Result<()> { + Ok(retry_on_intr(|| { + rustix::fs::fallocate(&self.file, ScratchFile::PUNCH_FLAGS, offset, len) + })?) + } + + /// Fills `buffer` with what the file has at `offset`. A file that ends + /// before the buffer is full fails: nothing that was written is ever + /// that short. + pub(crate) fn read_exact_at(&self, mut buffer: &mut [u8], mut offset: u64) -> io::Result<()> { + while !buffer.is_empty() { + match rustix::io::pread(&self.file, &mut *buffer, offset) { + Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()), + Ok(read) => { + let rest = buffer; + buffer = &mut rest[read..]; + offset += read as u64; + } + Err(Errno::INTR) => {} + Err(e) => return Err(e.into()), + } + } + Ok(()) + } + + /// Writes all of `data` into the file at `offset`. + pub(crate) fn write_all_at(&self, mut data: &[u8], mut offset: u64) -> io::Result<()> { + while !data.is_empty() { + match rustix::io::pwrite(&self.file, data, offset) { + Ok(0) => return Err(io::ErrorKind::WriteZero.into()), + Ok(written) => { + data = &data[written..]; + offset += written as u64; + } + Err(Errno::INTR) => {} + Err(e) => return Err(e.into()), + } + } + Ok(()) + } +} + +/// Why a new file did not get its name, with the error of what failed: +/// the errno of a call that was to give it the name, see +/// [`NewFile::give_name`], or the I/O error of the half of +/// [`NewFile::link`] that makes those calls, see +/// [`NewFile::sync_and_name`]. +#[derive(Debug, PartialEq, Eq)] +enum Unnamed { + /// The file has no name, as far as the calls that give it say, see + /// [`NewFile::link`]. + Failed(E), + /// Nobody can tell whether the file has its name: a call that was to + /// give it was interrupted and failed when it was made again, see + /// [`NewFile::give_name`]. + Unknown(E), +} + +impl From> for Unnamed { + /// What a call came to, for the half that made it. + fn from(unnamed: Unnamed) -> Unnamed { + match unnamed { + Unnamed::Failed(e) => Unnamed::Failed(e.into()), + Unnamed::Unknown(e) => Unnamed::Unknown(e.into()), + } + } +} + +impl> From for Unnamed { + /// Whatever else fails in that half fails before the file has its + /// name. + fn from(error: E) -> Unnamed { + Unnamed::Failed(error.into()) + } +} + +/// A file a manifest is written to, which gets its name in a directory once +/// the manifest is complete. Until then it has no name. Where the file +/// system cannot make a file without one, it has a name nobody can guess, +/// which it loses when it is dropped. +#[derive(Debug)] +pub(crate) struct NewFile { + /// The directory the file gets its name in, which whoever keeps other + /// files in it shares. + directory: Arc, + /// The name it gets there. + name: CString, + /// The name it was created at, as the caller gave it, which its errors + /// name. + path: PathBuf, + /// The file, which is linked in. The files of the manifest's own have + /// this descriptor as well where the file has a name until then, see + /// [`NewFile::named_file`]. + file: Arc, + /// The temporary name it has, if it has one: until it gets its own + /// name, and next to that where a link gave it its own. + temporary: Option, + /// Whether the file is synced before it gets its name, and the file + /// and its directory once it has it. + sync: bool, +} + +impl NewFile { + /// What separates the components of a path. + const SEPARATOR: u8 = b'/'; + /// The names a directory has for itself and for the one above it, which + /// no file gets. + const ITSELF_AND_PARENT: [&'static [u8]; 2] = [b".", b".."]; + /// How a directory on the way to the file is opened, and the one the + /// file is in: as a handle, for a directory and nothing else, and not + /// through a symbolic link. + const DIRECTORY_FLAGS: OFlags = OFlags::PATH + .union(OFlags::DIRECTORY) + .union(OFlags::NOFOLLOW) + .union(OFlags::CLOEXEC); + /// How a name on the way that is no directory is looked at: the name + /// itself, a symbolic link too, and without mounting anything. + const LOOK_FLAGS: AtFlags = AtFlags::SYMLINK_NOFOLLOW.union(AtFlags::NO_AUTOMOUNT); + /// How the directory is opened again to be synced: for reading, which + /// fsync() takes and a handle is not. + const SYNC_FLAGS: OFlags = OFlags::RDONLY.union(OFlags::DIRECTORY).union(OFlags::CLOEXEC); + /// How a file without a name is made that can get one later: with + /// O_TMPFILE and without O_EXCL, for reading and writing. + const UNNAMED_FLAGS: OFlags = OFlags::TMPFILE.union(OFlags::RDWR).union(OFlags::CLOEXEC); + /// How a file with a name nobody can guess is made: only if nothing has + /// that name, a symbolic link included. + const NAMED_FLAGS: OFlags = OFlags::CREATE + .union(OFlags::EXCL) + .union(OFlags::NOFOLLOW) + .union(OFlags::RDWR) + .union(OFlags::CLOEXEC); + /// The access mode of the file: read and write for everybody, less what + /// the umask takes away, as for a file that File::create() makes. + const MODE: rustix::fs::Mode = rustix::fs::Mode::RUSR + .union(rustix::fs::Mode::WUSR) + .union(rustix::fs::Mode::RGRP) + .union(rustix::fs::Mode::WGRP) + .union(rustix::fs::Mode::ROTH) + .union(rustix::fs::Mode::WOTH); + /// The name a directory has in itself, which a file without a name is + /// made in. + const ITSELF: &'static CStr = c"."; + /// What a name nobody can guess starts with. + const NAME_PREFIX: &'static str = ".#uapi16-"; + + /// Splits the name `name` of a new file below a directory into the + /// directories on the way to it, if it names any, and the name of the + /// file in the last of them. A name names no file below a directory and + /// has neither where it is empty or ends in a slash, `.` or `..`, where + /// it is absolute, and where `.` or `..` is on the way. + pub(crate) fn split(name: &Path) -> Option<(Option<&[u8]>, &[u8])> { + let path = name.as_os_str().as_bytes(); + let (parent, file_name) = match path.iter().rposition(|&byte| byte == NewFile::SEPARATOR) { + Some(at) => (Some(&path[..at]), &path[at + 1..]), + None => (None, path), + }; + let names_file = !file_name.is_empty() && !NewFile::ITSELF_AND_PARENT.contains(&file_name); + let absolute = path.first() == Some(&NewFile::SEPARATOR); + let below = parent.is_none_or(|parent| { + NewFile::components(parent).all(|component| !NewFile::ITSELF_AND_PARENT.contains(&component)) + }); + (names_file && !absolute && below).then_some((parent, file_name)) + } + + /// The components of `parent`, the directories on the way to a new + /// file. Slashes that follow each other separate as one does, as in + /// every path. + fn components(parent: &[u8]) -> impl Iterator { + parent + .split(|&byte| byte == NewFile::SEPARATOR) + .filter(|component| !component.is_empty()) + } + + /// Opens the directories `parent` on the way to a new file below the + /// directory `dir`, one component at a time, and returns the last one, + /// which the file is in. No component is opened through a symbolic + /// link, so with what [`NewFile::split`] refuses the file is below + /// `dir`, whatever the names on the way lead to by now. A mount point + /// on the way is gone through, and an automount point has its file + /// system mounted, as for any path a file is created at. + fn open_parent(dir: BorrowedFd<'_>, parent: &[u8]) -> io::Result { + let mut directory = None; + for component in NewFile::components(parent) { + let within = directory.as_ref().map_or(dir, OwnedFd::as_fd); + directory = Some(NewFile::open_component(within, component)?); + } + match directory { + Some(directory) => Ok(directory), + None => dir.try_clone_to_owned(), + } + } + + /// Opens the directory `component` of the directory `dir`, one + /// component on the way to a new file. A symbolic link fails with + /// ELOOP, and anything else that is no directory with ENOTDIR. The + /// kernel fails the open with ENOTDIR for both, so the name is looked + /// at once more then. + fn open_component(dir: BorrowedFd<'_>, component: &[u8]) -> rustix::io::Result { + let opened = + retry_on_intr(|| rustix::fs::openat(dir, component, NewFile::DIRECTORY_FLAGS, rustix::fs::Mode::empty())); + if !matches!(opened, Err(Errno::NOTDIR)) { + return opened; + } + let found = retry_on_intr(|| rustix::fs::statx(dir, component, NewFile::LOOK_FLAGS, StatxFlags::TYPE))?; + match FileType::from_raw_mode(found.stx_mode.into()) { + FileType::Symlink => Err(Errno::LOOP), + _ => Err(Errno::NOTDIR), + } + } + + /// Makes a file that gets the name `name` once it is complete, below the + /// directory `dir`. The file goes into the directory the name is in, + /// which is `dir` itself where the name has one component, and which is + /// opened one component at a time otherwise, none of them through a + /// symbolic link, see [`NewFile::open_parent`]. Something that has the + /// name already fails with EEXIST. A name that names no file below a + /// directory fails with EINVAL, see [`NewFile::split`], a symbolic link + /// on the way with ELOOP, and anything else on the way that is no + /// directory with ENOTDIR. A `dir` that is no descriptor fails with + /// EBADF, also AT_FDCWD. Where `sync` is true, the file is synced as it + /// gets its name, see [`NewFile::link`]. An error says which file it is + /// of. + pub(crate) fn create_at(dir: BorrowedFd<'_>, name: &Path, sync: bool) -> io::Result<(File, NewFile)> { + let own = || Ok(Arc::new(dir.try_clone_to_owned()?)); + NewFile::create(dir, own, name, sync).map_err(|e| NewFile::about(name, e)) + } + + /// [`NewFile::create_at`] for a caller of the C API, which lends the + /// library its directory `dir` for as long as the file is written. A + /// file whose name has one component goes into `dir` itself, and what + /// else is kept in its directory shares `dir` with it: no duplicate is + /// made of it. For a longer name the directory of the file is opened, + /// as always. + #[cfg(feature = "capi")] + pub(crate) fn create_at_lent(dir: &Arc, name: &Path, sync: bool) -> io::Result<(File, NewFile)> { + let lent = || Ok(Arc::clone(dir)); + NewFile::create(dir.as_fd(), lent, name, sync).map_err(|e| NewFile::about(name, e)) + } + + /// The I/O error `error` of the new file `name`, which says so. + fn about(name: &Path, error: io::Error) -> io::Error { + Error::io_about(format!("the manifest file '{}'", name.display()), error) + } + + /// What [`NewFile::create_at`] does, for the name `path`. `itself` gives + /// `dir` as the directory of a file that goes into it. + fn create( + dir: BorrowedFd<'_>, + itself: impl FnOnce() -> io::Result>, + path: &Path, + sync: bool, + ) -> io::Result<(File, NewFile)> { + let (parent, file_name) = NewFile::split(path).ok_or(Errno::INVAL)?; + // A negative number is no descriptor, and fails before anything is + // opened or duplicated. AT_FDCWD is such a number, which rustix has + // as a descriptor, `CWD`. It stands for the current directory only + // where a path is looked up, so openat() would take it for a name + // of more than one component. + if dir.as_raw_fd().is_negative() { + return Err(Errno::BADF.into()); + } + let directory = match parent { + Some(parent) => Arc::new(NewFile::open_parent(dir, parent)?), + None => itself()?, + }; + let name = CString::new(file_name).map_err(|_| Errno::INVAL)?; + // Something that has the name fails now and not once the manifest + // is complete. Giving the file its name checks again. + let found = retry_on_intr(|| { + rustix::fs::statx(&directory, name.as_c_str(), AtFlags::SYMLINK_NOFOLLOW, StatxFlags::TYPE) + }); + match found { + Ok(_) => return Err(Errno::EXIST.into()), + Err(Errno::NOENT) => {} + Err(e) => return Err(e.into()), + } + let unnamed = + retry_on_intr(|| rustix::fs::openat(&directory, NewFile::ITSELF, NewFile::UNNAMED_FLAGS, NewFile::MODE)); + let (file, temporary) = match unnamed { + Ok(file) => (file, None), + // A file system without O_TMPFILE, and a kernel that does not + // know it and opens the directory for writing, as for + // ScratchFile::create_in(). + Err(Errno::OPNOTSUPP | Errno::ISDIR) => { + let (file, temporary) = TemporaryName::create( + directory.as_fd(), + NewFile::NAME_PREFIX, + NewFile::NAMED_FLAGS, + NewFile::MODE, + )?; + (file, Some(temporary)) + } + Err(e) => return Err(e.into()), + }; + // The file owns its temporary name from here on, which goes when it + // is dropped, also when there is no descriptor left to write it + // through. + let new = NewFile { + directory, + name, + path: path.to_path_buf(), + file: Arc::new(File::from(file)), + temporary, + sync, + }; + let written = new.file.try_clone()?; + Ok((written, new)) + } + + /// The directory the file gets its name in, for what else is kept in + /// it while the file is written: the same descriptor, and no duplicate + /// of it. + pub(crate) fn directory(&self) -> Arc { + Arc::clone(&self.directory) + } + + /// The I/O error `error` of a write to the file, which says which file + /// it is of. + pub(crate) fn failed(&self, error: io::Error) -> io::Error { + NewFile::about(&self.path, error) + } + + /// The file with its inode, if it has a name until it gets its own, + /// which a walk of its directory has to pass over. It is the descriptor + /// this has of the file, and no duplicate of it. + pub(crate) fn named_file(&self) -> Result)>, Failure> { + if self.temporary.is_none() { + return Ok(None); + } + let inode = Status::of(self.file.as_fd())?.identity.inode_id(); + Ok(Some((inode, Arc::clone(&self.file)))) + } + + /// Gives the file its name, without replacing anything: where something + /// has the name, this fails with EEXIST, and the file gets none. + /// + /// A file that is synced is synced as systemd's link_tmpfile_at() syncs + /// one with LINK_TMPFILE_SYNC: before it gets its name, so that the name + /// never leads to data that is not on disk yet, and once more after, + /// with the directory it is in, so that the name is on disk as well. + /// That holds for every way the file gets its name. + /// + /// The file gets its name in [`NewFile::sync_and_name`]. Where that + /// fails, it got none and is emptied, see [`NewFile::give_up`]. What + /// comes once it has its name is [`NewFile::sync_named`]. Where that + /// fails, as the second sync can, the file keeps its name and what it + /// holds, and this fails all the same. So where this failed says + /// whether the file has its name, as long as the call that gives the + /// name says what it did. A look at the name would not: another + /// process can rename the file as soon as it has it, and a file + /// system can show the names of one file with inode numbers of their + /// own, as libfuse does on its high-level interface without use_ino. + /// A call that gave the name and fails all the same is taken for one + /// that gave none, and the file is emptied under its name. link(2) + /// documents that for NFS, where a server can make the link and die + /// before it can say so. Nobody can tell in one case that the calls + /// show, a call that was interrupted and failed when it was made + /// again, as [`NewFile::give_name`] has it, see [`Unnamed::Unknown`]. + /// The file stays as it is then, and this fails. An error says which + /// file it is of. + pub(crate) fn link(mut self) -> io::Result<()> { + let named = self.sync_and_name(); + self.linked(named) + } + + /// What [`NewFile::link`] does once its first half came to `named`. + /// Where that says that the file has its name, the second half + /// follows, see [`NewFile::sync_named`]. Where it says that the file + /// got none, the file is given up, and where it says that nobody can + /// tell, the file stays as it is. Both fail with the error of the + /// first half. An error says which file it is of. + fn linked(mut self, named: Result<(), Unnamed>) -> io::Result<()> { + let linked = match named { + Ok(()) => self.sync_named(), + Err(Unnamed::Failed(e)) => { + self.give_up(); + Err(e) + } + // The file can have its name, so it keeps what it holds. A + // temporary name it still has goes when this is dropped. + Err(Unnamed::Unknown(e)) => Err(e), + }; + linked.map_err(|e| NewFile::about(&self.path, e)) + } + + /// Empties the file for whoever gives it up before it has its name: + /// what was written of the manifest goes before the name the file has + /// until then does, so that nothing of it is left where a file system + /// keeps a file that was unlinked while it is open under a name until + /// it is released. Nobody gives up a file that has its name or can + /// have it, as far as the calls that give it say, see + /// [`NewFile::link`]: it stays as it is, also where a sync of it + /// failed. A truncation that fails is ignored. Dropping the file + /// empties nothing. + pub(crate) fn give_up(&self) { + let _ = retry_on_intr(|| rustix::fs::ftruncate(&self.file, 0)); + } + + /// The first half of what [`NewFile::link`] does: the sync of the file + /// before it gets its name, and the name. Where this fails, the file + /// got no name, as far as the calls that give it say, which is + /// [`Unnamed::Failed`], but for a call that was interrupted, failed + /// when it was made again and of which nobody can tell whether it gave + /// the name, which is [`Unnamed::Unknown`], see + /// [`NewFile::give_name`]. A file that got its name by a link, see + /// [`NewFile::rename`], has a temporary name next to it then, which is + /// kept for [`NewFile::sync_named`] to remove. + fn sync_and_name(&mut self) -> Result<(), Unnamed> { + if self.sync { + retry_on_intr(|| rustix::fs::fsync(&self.file))?; + } + match &self.temporary { + None => self.temporary = self.link_unnamed()?, + // A name that was not renamed is still there. It is removed + // once the file has its own, or when this is dropped. + Some(temporary) => { + if self.rename(temporary)? { + self.temporary = None; + } + } + } + Ok(()) + } + + /// The second half, for a file that has its name: the temporary name + /// it still has is removed, and the file and its directory are synced. + /// Where the temporary name can't be removed, the file has both names, + /// and this fails. Its own name is not removed again: nothing removes a + /// name only while it leads to a given file, and another file can take + /// the name in between. The temporary name is removed once more when + /// the file is dropped. + fn sync_named(&mut self) -> io::Result<()> { + if let Some(temporary) = &self.temporary { + temporary.remove(self.directory.as_fd())?; + self.temporary = None; + } + if self.sync { + retry_on_intr(|| rustix::fs::fsync(&self.file))?; + let directory = retry_on_intr(|| { + rustix::fs::openat( + &self.directory, + NewFile::ITSELF, + NewFile::SYNC_FLAGS, + rustix::fs::Mode::empty(), + ) + })?; + retry_on_intr(|| rustix::fs::fsync(&directory))?; + } + Ok(()) + } + + /// Links the file without a name in, the way systemd's link_fd() does. + /// Linux before 6.10 takes linkat() of a descriptor only from a process + /// that may look up any name, and fails with ENOENT for any other. The + /// link procfs has for the descriptor is linked then, which can leave + /// the file a temporary name next to its own. Returns that name, see + /// [`NewFile::link_through`]. + fn link_unnamed(&self) -> Result, Unnamed> { + let (directory, name) = (&self.directory, self.name.as_c_str()); + let linked = self.give_name(|| rustix::fs::linkat(&self.file, c"", directory, name, AtFlags::EMPTY_PATH)); + match linked { + Ok(()) => Ok(None), + Err(Unnamed::Failed(Errno::NOENT)) => self.link_through_procfs(), + Err(e) => Err(e.into()), + } + } + + /// Links the file in through the link procfs has for its descriptor, + /// see [`FdLink`], which is checked to lead to the file first. Returns + /// what [`NewFile::link_through`] returns. + fn link_through_procfs(&self) -> Result, Unnamed> { + let link = FdLink::new(self.file.as_fd()); + link.check()?; + self.link_through(link.path()) + } + + /// Links the file in through `path`, which was checked to lead to it. + /// A /proc that is not what it should be can lead elsewhere by then, so + /// the link goes to a name nobody can guess first, see + /// [`TemporaryName::link`], which has to lead to the file before it is + /// renamed to the name of the file, see [`NewFile::rename`]. Where it + /// leads to another file, or the rename fails, the temporary name is + /// removed, which is nobody else's whatever it leads to. The name of + /// the file only ever gets a link that was checked to lead to the file, + /// and it is never removed. Returns the temporary name where the file + /// still has it next to its own. + fn link_through(&self, path: &str) -> Result, Unnamed> { + let directory = self.directory.as_fd(); + let temporary = TemporaryName::link(directory, NewFile::NAME_PREFIX, path)?; + let renamed = match self.names_file(temporary.as_c_str()) { + Ok(true) => self.rename(&temporary), + Ok(false) => Err(FdLink::elsewhere().into()), + Err(e) => Err(e.into()), + }; + match renamed { + Ok(gone) => Ok((!gone).then_some(temporary)), + Err(e) => { + // Where it can't be removed, the file it leads to keeps it. + let _ = temporary.remove(directory); + Err(e) + } + } + } + + /// Drops the file in a process that did not make it, without removing the + /// name it has until it gets its own. The process that made it has the + /// file still, under that name. + #[cfg(feature = "capi")] + pub(crate) fn abandon(mut self) { + self.temporary = None; + } + + /// Renames the file from its name `temporary` to its own, without + /// replacing anything, and returns whether the temporary name is gone + /// by that. A file system without RENAME_NOREPLACE gets a link of the + /// new name instead, see [`NewFile::link_instead`], after which the + /// file has both names. + fn rename(&self, temporary: &TemporaryName) -> Result { + let (directory, name) = (&self.directory, self.name.as_c_str()); + let (from, flags) = (temporary.as_c_str(), RenameFlags::NOREPLACE); + match self.give_name(|| rustix::fs::renameat_with(directory, from, directory, name, flags)) { + Ok(()) => Ok(true), + Err(Unnamed::Failed(e)) if NewFile::no_such_call(e) => self.link_instead(temporary).map(|()| false), + Err(e) => Err(e.into()), + } + } + + /// Gives the file its own name from its name `temporary` where the file + /// system has no RENAME_NOREPLACE: a link of the new name, which + /// replaces nothing either, as for systemd's rename_noreplace(). The + /// temporary name is not removed here: that comes once the file has + /// its own name, see [`NewFile::sync_named`], so that what fails here + /// is the call that gives the name, and nothing after it. + fn link_instead(&self, temporary: &TemporaryName) -> Result<(), Unnamed> { + let (directory, name) = (&self.directory, self.name.as_c_str()); + let from = temporary.as_c_str(); + Ok(self.give_name(|| rustix::fs::linkat(directory, from, directory, name, AtFlags::empty()))?) + } + + /// Whether the errno `e` says that the file system has no such call: + /// EINVAL, ENOSYS and EOPNOTSUPP, which renameat2() fails with where + /// the file system has no RENAME_NOREPLACE. A call that fails with one + /// of them did nothing. + fn no_such_call(e: Errno) -> bool { + matches!(e, Errno::INVAL | Errno::NOSYS | Errno::OPNOTSUPP) + } + + /// Makes `give`, which gives the file its name without replacing + /// anything, again where it fails with EINTR. One that was interrupted + /// can have given the file the name before it failed. The same call + /// again fails then: with EEXIST for the name, with ENOENT for the + /// name that was renamed, or with anything else that goes wrong by + /// then, such as EIO or EACCES. So once a call was interrupted, the + /// name is looked at whatever the call fails with when it is made + /// again, and the file has it where it leads to the file. Where it + /// does not, or can't be looked at, nobody can tell, which is + /// [`Unnamed::Unknown`]: the call can have given the name all the + /// same, since another process can have renamed the file by then, and + /// a file system can show the names of one file with inode numbers of + /// their own. The name is not looked at where the call made again + /// says that the file system has no such call, see + /// [`NewFile::no_such_call`]: the call that was interrupted gave no + /// name either then, and [`NewFile::rename`] falls back on that. That + /// is [`Unnamed::Failed`], as is every failure of a call that was not + /// interrupted: such a call is taken to have left the file without + /// the name, see [`NewFile::link`] for one that did not. + fn give_name(&self, mut give: impl FnMut() -> rustix::io::Result<()>) -> Result<(), Unnamed> { + let mut interrupted = false; + loop { + match give() { + Ok(()) => return Ok(()), + Err(Errno::INTR) => interrupted = true, + Err(e) if interrupted && !NewFile::no_such_call(e) => { + return match self.has_name() { + Ok(true) => Ok(()), + Ok(false) => Err(Unnamed::Unknown(e)), + Err(look) => Err(Unnamed::Unknown(look)), + }; + } + Err(e) => return Err(Unnamed::Failed(e)), + } + } + } + + /// Whether the name of the file in its directory leads to the file. + fn has_name(&self) -> rustix::io::Result { + self.names_file(&self.name) + } + + /// Whether the name `name` in the directory of the file leads to the + /// file. + fn names_file(&self, name: &CStr) -> rustix::io::Result { + let found = + retry_on_intr(|| rustix::fs::statx(&self.directory, name, AtFlags::SYMLINK_NOFOLLOW, InodeId::REQUEST)); + match found { + Ok(statx) => Ok(InodeId::from_statx(&statx) == InodeId::of(self.file.as_fd())?), + Err(Errno::NOENT) => Ok(false), + Err(e) => Err(e), + } + } +} + +impl Drop for NewFile { + /// Removes the temporary name of the file, if it has one: the name it + /// has until it gets its own, or one that could not be removed then. + fn drop(&mut self) { + if let Some(temporary) = self.temporary.take() { + let _ = temporary.remove(self.directory.as_fd()); + } + } +} + +/// The hash of the data of a regular file, read a part at a time, so that +/// a large file takes several steps: the file, opened again through the +/// handle of its entry, its status when the entry was opened, the hash of +/// what was read so far, and how much that was. +#[derive(Debug)] +pub(crate) struct DataHash { + file: File, + before: Status, + context: Sha256Context, + offset: u64, +} + +impl DataHash { + /// The most bytes of data a file is hashed with: 1 TiB. Hashing takes + /// as long as the data is large, a sparse file has data of any size at + /// no cost to whoever made it, and nothing stops a hash once an add + /// began it. + pub(crate) const MAX_SIZE: u64 = 1 << 40; + + /// Fails unless the data of a file with the status `status` is hashed: + /// anything but a regular file fails with EINVAL, and a file that is + /// larger than [`DataHash::MAX_SIZE`] with EFBIG, as for systemd's + /// sha256_fd(). Both come from the status alone, before the file is + /// opened or anything is read of it. + pub(crate) fn admits(status: &Status) -> Result<(), Failure> { + if status.file_type != FileType::RegularFile { + return Err(Errno::INVAL.into()); + } + if status.size > DataHash::MAX_SIZE { + return Err(Errno::FBIG.into()); + } + Ok(()) + } + + /// Opens the regular file of `entry` again, through its handle, for the + /// hash of its data. A file whose data is not hashed fails and is not + /// opened, see [`DataHash::admits`]. + pub(crate) fn start(entry: &Entry<'_>) -> Result { + DataHash::admits(entry.status())?; + DataHash::of(entry, entry.reopen(None)?) + } + + /// The hash of the data of the regular file of `entry`, read through + /// `opened`, which is that file opened again, see [`Entry::reopen`]. So + /// a file that is open already, for its inode flags for example, is + /// not opened once more for its data. A file whose data is not hashed + /// fails, see [`DataHash::admits`]. + pub(crate) fn of(entry: &Entry<'_>, opened: Readable) -> Result { + DataHash::admits(entry.status())?; + Ok(DataHash { + file: opened.0, + before: *entry.status(), + context: Sha256Context::new(), + offset: 0, + }) + } + + /// Reads at most `budget` more bytes of the data through `buffer`, + /// which is not empty, and continues with what is left to read. Once + /// the data was read up to the size the file had when its entry was + /// opened, one byte more is read, which is not there if the data ends + /// at that size, and the status of the file is checked against the one + /// it had. Then it breaks with the hash. A file whose status shows a + /// change changed while it was read. One whose data ends early or goes + /// on after its size fails with [`Failure::WrongSize`] where its status + /// shows none. + pub(crate) fn read(mut self, buffer: &mut [u8], budget: u64) -> Result, Failure> { + debug_assert!(!buffer.is_empty()); + let mut left = budget; + let end = loop { + let rest = self.before.size - self.offset; + let want = if rest == 0 { + 1 + } else if left == 0 { + return Ok(ControlFlow::Continue(self)); + } else { + usize::try_from(rest.min(left)).map_or(buffer.len(), |most| most.min(buffer.len())) + }; + let read = match rustix::io::pread(&self.file, &mut buffer[..want], self.offset) { + Ok(read) => read, + Err(Errno::INTR) => continue, + Err(e) => break Err(DataFailure::Io(e.into())), + }; + match (read, rest) { + (0, 0) => break Ok(()), + (0, _) => break Err(DataFailure::EndedEarly), + (_, 0) => break Err(DataFailure::WentOn), + _ => {} + } + self.context.update(&buffer[..read]); + self.offset += read as u64; + left -= read as u64; + }; + let DataHash { + file, before, context, .. + } = self; + let read = end.map(|()| context.finalize()); + before + .check_read(read, Status::of(file.as_fd())) + .map(ControlFlow::Break) + } +} + +impl From for Timestamp { + fn from(time: StatxTimestamp) -> Timestamp { + Timestamp { + seconds: time.tv_sec, + nanoseconds: time.tv_nsec, + } + } +} + +impl From for Failure { + fn from(errno: Errno) -> Failure { + Failure::Io(errno.into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{OpenFile, TempDir, ST_BLOCKS_UNIT}; + use rustix::fs::{inotify, MemfdFlags, SealFlags, CWD}; + use rustix::io::FdFlags; + use std::fmt; + use std::fs::{self, OpenOptions}; + use std::io::{Read, Write}; + use std::mem::MaybeUninit; + use std::os::fd::OwnedFd; + use std::os::unix::ffi::OsStringExt; + use std::os::unix::fs::{symlink, MetadataExt, PermissionsExt}; + use std::os::unix::net::UnixListener; + use std::path::{Path, PathBuf}; + use std::process::Command; + use std::thread; + use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + + /// Opens the directory `path` as a handle, the way an entry is opened. + fn open_dir(path: &Path) -> OwnedFd { + let flags = OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC; + rustix::fs::open(path, flags, rustix::fs::Mode::empty()).unwrap() + } + + /// Makes a FIFO at `path`. + fn make_fifo(path: &Path) { + let mode = rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR; + rustix::fs::mknodat(CWD, path, FileType::Fifo, mode, 0).unwrap(); + } + + /// The errno of `result`, which failed in a system call. + fn errno(result: Result) -> i32 { + match result { + Err(Failure::Io(e)) => e.raw_os_error().unwrap(), + other => panic!("{:?}", other), + } + } + + /// The device number `dev` of std, split as statx() splits it. + fn device_number(dev: u64) -> (u32, u32) { + (rustix::fs::major(dev), rustix::fs::minor(dev)) + } + + /// The time `time`, which is after the epoch, as statx() gives it. + fn timestamp(time: SystemTime) -> (i64, u32) { + let since = time.duration_since(UNIX_EPOCH).unwrap(); + (i64::try_from(since.as_secs()).unwrap(), since.subsec_nanos()) + } + + /// The mount ID that /proc/self/fdinfo gives for the file `fd` refers + /// to, the one of /proc/self/mountinfo. + fn mountinfo_id(fd: BorrowedFd<'_>) -> u64 { + let info = fs::read_to_string(format!("/proc/self/fdinfo/{}", fd.as_raw_fd())).unwrap(); + let id = info.lines().find_map(|line| line.strip_prefix("mnt_id:")).unwrap(); + id.trim().parse().unwrap() + } + + /// The mount of the file `fd` refers to, by the mount ID of + /// /proc/self/mountinfo: what a kernel without unique mount IDs gives. + fn reusable_mount(fd: BorrowedFd<'_>) -> MountId { + let request = Status::REQUEST.difference(Status::MNT_ID_UNIQUE); + let statx = rustix::fs::statx(fd, c"", Status::OF_DESCRIPTOR, request).unwrap(); + Status::from_statx(&statx).unwrap().identity.mount + } + + /// The hash of the data of `entry`, read `budget` bytes at a time, and + /// how many steps that took. + fn hash_in_steps(entry: &Entry<'_>, buffer: &mut [u8], budget: u64) -> Result<(Sha256, u64), Failure> { + let mut hash = DataHash::start(entry)?; + let mut steps = 1; + loop { + match hash.read(buffer, budget)? { + ControlFlow::Break(found) => return Ok((found, steps)), + ControlFlow::Continue(more) => hash = more, + } + steps += 1; + } + } + + /// The hash of the data of `entry`, all of it read in one step. + fn hash(entry: &Entry<'_>, buffer: &mut [u8]) -> Result { + hash_in_steps(entry, buffer, u64::MAX).map(|(hash, _)| hash) + } + + /// How long a test waits for the clock of a file system to move: more + /// than the two seconds a time of FAT stands still. + const CLOCK_WAIT: Duration = Duration::from_secs(3); + + /// How far back the probe for the change time sets a modification + /// time: farther than any clock stands still. + const SET_BACK: Duration = Duration::from_secs(3600); + + /// Waits until a change of a file in `dir` gets a later change time + /// than `time`, for [`CLOCK_WAIT`] at most. A coarse clock gives all + /// changes in a tick the same time, and a tick of FAT is two seconds. + /// Multigrain timestamps, since Linux 6.13, give the first change + /// after a statx() a time of its own anyway. + fn wait_for_clock(dir: &Path, time: Timestamp) { + let probe = dir.join("clock"); + let then = (time.seconds, i64::from(time.nanoseconds)); + let started = Instant::now(); + loop { + // The time is taken before the clock is asked, so that the last + // look comes after the whole wait, however late it comes. + let waited = started.elapsed(); + fs::write(&probe, b"").unwrap(); + let meta = fs::symlink_metadata(&probe).unwrap(); + fs::remove_file(&probe).unwrap(); + if (meta.ctime(), meta.ctime_nsec()) > then { + return; + } + assert!(waited < CLOCK_WAIT, "the clock of {:?} does not move", dir); + thread::sleep(Duration::from_millis(1)); + } + } + + /// Whether the change time of a file in `dir` moves with its + /// modification time, as on FAT, which keeps one time for the two: a + /// modification time that is set back takes the change time back with + /// it there, and nothing tells that it was set. + fn change_time_follows(dir: &Path) -> bool { + let probe = dir.join("times"); + fs::write(&probe, b"").unwrap(); + let before = fs::symlink_metadata(&probe).unwrap(); + let back = before.modified().unwrap() - SET_BACK; + File::options() + .write(true) + .open(&probe) + .unwrap() + .set_modified(back) + .unwrap(); + let after = fs::symlink_metadata(&probe).unwrap(); + fs::remove_file(&probe).unwrap(); + (after.ctime(), after.ctime_nsec()) < (before.ctime(), before.ctime_nsec()) + } + + /// The opens of a file that inotify sees. A handle opened with O_PATH is + /// not an open for inotify. + struct Opens(OwnedFd); + + impl Opens { + /// Watches the file `path`. + fn of(path: &Path) -> Opens { + let inotify = inotify::init(inotify::CreateFlags::CLOEXEC | inotify::CreateFlags::NONBLOCK).unwrap(); + inotify::add_watch(&inotify, path, inotify::WatchFlags::OPEN).unwrap(); + Opens(inotify) + } + + /// Whether the file was opened since the last look. + fn seen(&self) -> bool { + let mut buffer = [MaybeUninit::uninit(); 4096]; + let mut events = inotify::Reader::new(&self.0, &mut buffer); + let mut opened = false; + loop { + match events.next() { + Ok(event) => opened |= event.events().contains(inotify::ReadFlags::OPEN), + Err(Errno::AGAIN) => return opened, + Err(e) => panic!("{}", e), + } + } + } + } + + /// Checks that `status` says what lstat() says of `path`, in `meta`. + fn check_status(status: &Status, meta: &fs::Metadata, path: &Path) { + let identity = &status.identity; + let device = (identity.device.major, identity.device.minor); + assert_eq!( + (device, identity.inode), + (device_number(meta.dev()), meta.ino()), + "{:?}", + path + ); + assert_eq!(status.file_type, FileType::from_raw_mode(meta.mode()), "{:?}", path); + assert_eq!(status.mode, Mode::from_st_mode(meta.mode()), "{:?}", path); + assert_eq!(u64::from(status.nlink), meta.nlink(), "{:?}", path); + assert_eq!( + (status.uid, status.gid, status.size), + (meta.uid(), meta.gid(), meta.size()), + "{:?}", + path + ); + let nanoseconds = |nsec: i64| u32::try_from(nsec).unwrap(); + let mtime = (status.mtime.seconds, status.mtime.nanoseconds); + assert_eq!(mtime, (meta.mtime(), nanoseconds(meta.mtime_nsec())), "{:?}", path); + let ctime = (status.ctime.seconds, status.ctime.nanoseconds); + assert_eq!(ctime, (meta.ctime(), nanoseconds(meta.ctime_nsec())), "{:?}", path); + assert_eq!( + (status.rdev.major, status.rdev.minor), + device_number(meta.rdev()), + "{:?}", + path + ); + // std reads the birth time with statx() where it uses statx(), + // which it does not on musl. + if let Ok(created) = meta.created() { + let btime = status.btime.map(|btime| (btime.seconds, btime.nanoseconds)); + assert_eq!(btime, Some(timestamp(created)), "{:?}", path); + } + } + + /// The status of an entry of every type a test can make, and of a + /// device node every system has, is what lstat() says of it. The + /// entries of a directory are on its mount, and two names of a file + /// are the same file. + #[test] + fn statuses_are_what_lstat_says() { + let tmp = TempDir::new("sys-status"); + let dir = &tmp.0; + fs::write(dir.join("file"), b"hello").unwrap(); + fs::hard_link(dir.join("file"), dir.join("link")).unwrap(); + fs::create_dir(dir.join("dir")).unwrap(); + symlink("target", dir.join("symlink")).unwrap(); + make_fifo(&dir.join("fifo")); + let _socket = UnixListener::bind(dir.join("socket")).unwrap(); + let tree = open_dir(dir); + let mount = Status::of(tree.as_fd()).unwrap().identity.mount; + let names = [c"file", c"link", c"dir", c"symlink", c"fifo", c"socket"]; + let entries: Vec> = names + .iter() + .map(|name| Entry::open_at(tree.as_fd(), name).unwrap()) + .collect(); + for (name, entry) in names.iter().zip(&entries) { + let path = dir.join(name.to_str().unwrap()); + check_status(entry.status(), &fs::symlink_metadata(&path).unwrap(), &path); + assert_eq!(entry.status().identity.mount, mount, "{:?}", path); + } + assert_eq!(entries[0].status().nlink, 2); + assert_eq!(entries[0].status().identity, entries[1].status().identity); + let dev = open_dir(Path::new("/dev")); + let null = Entry::open_at(dev.as_fd(), c"null").unwrap(); + let path = PathBuf::from("/dev/null"); + check_status(null.status(), &fs::symlink_metadata(&path).unwrap(), &path); + assert_eq!(null.status().file_type, FileType::CharacterDevice); + } + + /// Runs `check` with handles that open_tree() takes, and once more with + /// handles that openat() takes, as in a process that open_tree() was + /// refused in. + fn with_both_handles(check: impl Fn()) { + check(); + OPEN_TREE.store(OpenTree::REFUSED, Ordering::Relaxed); + check(); + OPEN_TREE.store(OpenTree::CALLED, Ordering::Relaxed); + } + + /// A file system that does not have an ioctl has no answer to it. It + /// says so with ENOTTY as a rule, and EOPNOTSUPP, ENOSYS and EINVAL are + /// taken for the same. Any other error of an ioctl is an error. + #[test] + fn ioctls_a_file_system_does_not_have() { + for errno in [Errno::NOTTY, Errno::OPNOTSUPP, Errno::NOSYS, Errno::INVAL] { + assert_eq!(Readable::answer(|| Err::(errno)).unwrap(), None, "{}", errno); + } + for errno in [Errno::IO, Errno::ACCESS, Errno::PERM, Errno::NOENT, Errno::BADF] { + let e = Readable::answer(|| Err::(errno)).unwrap_err(); + assert_eq!(e.raw_os_error(), Some(errno.raw_os_error())); + } + assert_eq!(Readable::answer(|| Ok(7)).unwrap(), Some(7)); + } + + /// An entry is a handle, which is not inherited across exec and opens + /// nothing behind it: a symbolic link is the link, and a FIFO is not + /// waited for. Entries below a directory are opened in its handle. A + /// file open for reading has the status of its entry. A handle that + /// openat() takes, where open_tree() was refused, is the same. + #[test] + fn entries_are_handles() { + let tmp = TempDir::new("sys-handles"); + let dir = &tmp.0; + fs::create_dir_all(dir.join("a/b")).unwrap(); + fs::write(dir.join("a/b/file"), b"deep").unwrap(); + symlink("a", dir.join("link")).unwrap(); + make_fifo(&dir.join("fifo")); + let _socket = UnixListener::bind(dir.join("socket")).unwrap(); + let tree = open_dir(dir); + with_both_handles(|| { + for name in [c"a", c"link", c"fifo", c"socket"] { + let entry = Entry::open_at(tree.as_fd(), name).unwrap(); + assert!(rustix::fs::fcntl_getfl(entry.handle()).unwrap().contains(OFlags::PATH)); + assert!(rustix::io::fcntl_getfd(entry.handle()) + .unwrap() + .contains(FdFlags::CLOEXEC)); + } + let link = Entry::open_at(tree.as_fd(), c"link").unwrap(); + assert_eq!(link.status().file_type, FileType::Symlink); + assert_eq!(errno(Entry::open_at(link.handle(), c"b")), libc::ENOTDIR); + assert_eq!(errno(Entry::open_at(tree.as_fd(), c"missing")), libc::ENOENT); + let a = Entry::open_at(tree.as_fd(), c"a").unwrap(); + let b = Entry::open_at(a.handle(), c"b").unwrap(); + let file = Entry::open_at(b.handle(), c"file").unwrap(); + assert_eq!( + (file.status().file_type, file.status().size), + (FileType::RegularFile, 4) + ); + let opened = File::open(dir.join("a/b/file")).unwrap(); + assert_eq!(Status::of(opened.as_fd()).unwrap().identity, file.status().identity); + }); + } + + /// A descriptor of a caller is the entry of its file, a handle or the + /// file open for reading. The entry borrows the descriptor: it reads + /// through that one and takes none of its own, and the descriptor is + /// open after the entry is gone. + #[test] + fn entries_of_descriptors() { + let tmp = TempDir::new("sys-descriptors"); + let dir = &tmp.0; + fs::write(dir.join("file"), b"data").unwrap(); + let tree = open_dir(dir); + let handle = Entry::open_at(tree.as_fd(), c"file").unwrap(); + for fd in [ + OwnedFd::from(File::open(dir.join("file")).unwrap()), + handle.handle().try_clone_to_owned().unwrap(), + ] { + let entry = Entry::of(fd.as_fd()).unwrap(); + assert_eq!(entry.handle().as_raw_fd(), fd.as_raw_fd()); + assert_eq!(entry.status().identity, handle.status().identity); + assert!(!entry.status().changed_since(handle.status())); + drop(entry); + assert_eq!(Status::of(fd.as_fd()).unwrap().identity, handle.status().identity); + } + } + + /// A status has the unique mount ID where the kernel gives one when + /// asked, and the one of /proc/self/mountinfo where it does not. A + /// kernel gives one of the two. Without either there is no status. + #[test] + fn mount_ids() { + let tmp = TempDir::new("sys-mount-ids"); + let tree = open_dir(&tmp.0); + let statx = rustix::fs::statx(tree.as_fd(), c"", Status::OF_DESCRIPTOR, Status::REQUEST).unwrap(); + let mask = StatxFlags::from_bits_retain(statx.stx_mask); + let unique = mask.contains(Status::MNT_ID_UNIQUE); + assert_ne!(unique, mask.contains(StatxFlags::MNT_ID)); + let expected = if unique { + MountId::Unique(statx.stx_mnt_id) + } else { + MountId::Reusable(statx.stx_mnt_id) + }; + assert_eq!(Status::from_statx(&statx).unwrap().identity.mount, expected); + assert_eq!( + reusable_mount(tree.as_fd()), + MountId::Reusable(mountinfo_id(tree.as_fd())) + ); + let mut statx = statx; + statx.stx_mask &= !(StatxFlags::MNT_ID | Status::MNT_ID_UNIQUE).bits(); + let failure = Status::from_statx(&statx).unwrap_err(); + assert!(matches!(failure, Failure::NoMountId), "{:?}", failure); + } + + /// The subvolume and the birth time are there where the mask of + /// statx() has them, and only there. + #[test] + fn what_the_mask_has() { + let tmp = TempDir::new("sys-mask"); + let tree = open_dir(&tmp.0); + let statx = rustix::fs::statx(tree.as_fd(), c"", Status::OF_DESCRIPTOR, Status::REQUEST).unwrap(); + let optional = Status::SUBVOL | StatxFlags::BTIME; + let mut with = statx; + with.stx_mask |= optional.bits(); + with.stx_subvol = 7; + let status = Status::from_statx(&with).unwrap(); + assert_eq!(status.identity.subvolume, Some(7)); + assert_eq!(status.btime, Some(Timestamp::from(with.stx_btime))); + let mut without = statx; + without.stx_mask &= !optional.bits(); + let status = Status::from_statx(&without).unwrap(); + assert_eq!((status.identity.subvolume, status.btime), (None, None)); + } + + /// The variable that tells the test binary, run again inside the + /// namespaces of [`bind_mounts_are_mounts_of_their_own`], where the + /// directory with the bind mount is. + const BIND_MOUNT_DIR: &str = "UAPI16_TEST_BIND_MOUNT_DIR"; + + /// A bind mount is a mount of its own, by the unique mount IDs and by + /// those of /proc/self/mountinfo, and a file reached through it is not + /// the file reached through its source. The bind mount needs a user and + /// a mount namespace, which unshare(1) makes, and the test binary runs + /// this test again inside them. + #[test] + fn bind_mounts_are_mounts_of_their_own() { + if let Some(dir) = std::env::var_os(BIND_MOUNT_DIR) { + return check_bind_mount(Path::new(&dir)); + } + let tmp = TempDir::new("sys-bind-mount"); + let dir = &tmp.0; + fs::create_dir_all(dir.join("source/below")).unwrap(); + fs::create_dir(dir.join("mount")).unwrap(); + fs::write(dir.join("source/below/file"), b"bound").unwrap(); + // Where unshare(1) cannot make the namespaces, there is nothing to + // run the test in. + let works = Command::new("unshare").args(["-Urm", "true"]).output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urm does not work here"); + return; + } + let script = concat!( + r#"mount --bind "$1/source" "$1/mount" && "#, + r#"exec "$2" --exact sys::tests::bind_mounts_are_mounts_of_their_own"# + ); + let output = Command::new("unshare") + .args(["-Urm", "sh", "-c", script, "sh"]) + .arg(dir) + .arg(std::env::current_exe().unwrap()) + .env(BIND_MOUNT_DIR, dir) + .output() + .unwrap(); + assert!(output.status.success(), "{:?}", output); + } + + /// The checks of [`bind_mounts_are_mounts_of_their_own`] in `dir`, in + /// which `mount` is a bind mount of `source`. + fn check_bind_mount(dir: &Path) { + let top = open_dir(dir); + let top_mount = Status::of(top.as_fd()).unwrap().identity.mount; + let source = Entry::open_at(top.as_fd(), c"source").unwrap(); + let mount = Entry::open_at(top.as_fd(), c"mount").unwrap(); + assert_eq!(source.status().identity.mount, top_mount); + assert_ne!(mount.status().identity.mount, top_mount); + let (through_source, through_mount) = (source.status().identity, mount.status().identity); + assert_eq!( + (through_source.device, through_source.inode), + (through_mount.device, through_mount.inode) + ); + // What is below the bind mount is in it. + let below = Entry::open_at(mount.handle(), c"below").unwrap(); + let file = Entry::open_at(below.handle(), c"file").unwrap(); + assert_eq!(file.status().identity.mount, mount.status().identity.mount); + let source_below = Entry::open_at(source.handle(), c"below").unwrap(); + let source_file = Entry::open_at(source_below.handle(), c"file").unwrap(); + assert_eq!(source_file.status().identity.mount, top_mount); + assert_ne!(file.status().identity, source_file.status().identity); + let mut buffer = vec![0; DATA_BUFFER_SIZE]; + assert_eq!(hash(&file, &mut buffer).unwrap(), Sha256::digest(b"bound")); + // The mount IDs of /proc/self/mountinfo tell the mounts apart too. + for fd in [top.as_fd(), mount.handle()] { + assert_eq!(reusable_mount(fd), MountId::Reusable(mountinfo_id(fd))); + } + assert_ne!(reusable_mount(top.as_fd()), reusable_mount(mount.handle())); + } + + /// The hash of a regular file is that of its data, read through a + /// buffer of any size and in steps of any budget: no data, less than + /// the buffer, and the data of several buffers and of a part of one at + /// the end. A file takes a step for every budget of its data, and the + /// last one also checks that the data ends there. A budget of nothing + /// reads nothing. + #[test] + fn hashes_the_data() { + let tmp = TempDir::new("sys-hash"); + let dir = &tmp.0; + let long: Vec = (0..2 * DATA_BUFFER_SIZE + 3).map(|i| (i % 251) as u8).collect(); + let whole = u64::try_from(DATA_BUFFER_SIZE).unwrap(); + /// A file the test hashes: its name, its data, the sizes of the + /// buffers it is read through and the budgets of its steps. + struct Sample<'a> { + name: &'a CStr, + data: &'a [u8], + buffers: [usize; 3], + budgets: [u64; 4], + } + let files = [ + Sample { + name: c"empty", + data: b"", + buffers: [1, 7, DATA_BUFFER_SIZE], + budgets: [1, 7, 4096, u64::MAX], + }, + Sample { + name: c"short", + data: b"hello", + buffers: [1, 7, DATA_BUFFER_SIZE], + budgets: [1, 2, 7, u64::MAX], + }, + Sample { + name: c"long", + data: &long, + buffers: [4096, DATA_BUFFER_SIZE - 1, DATA_BUFFER_SIZE], + budgets: [4096, whole - 1, whole, u64::MAX], + }, + ]; + for file in &files { + fs::write(dir.join(file.name.to_str().unwrap()), file.data).unwrap(); + } + let tree = open_dir(dir); + let mut buffer = vec![0; DATA_BUFFER_SIZE]; + for file in &files { + let entry = Entry::open_at(tree.as_fd(), file.name).unwrap(); + let expected = Sha256::digest(file.data); + for size in file.buffers { + let mut buffer = vec![0; size]; + assert_eq!(hash(&entry, &mut buffer).unwrap(), expected, "{:?} {}", file.name, size); + } + let len = u64::try_from(file.data.len()).unwrap(); + for budget in file.budgets { + let found = hash_in_steps(&entry, &mut buffer, budget).unwrap(); + let steps = len.div_ceil(budget).max(1); + assert_eq!(found, (expected, steps), "{:?} {}", file.name, budget); + } + match DataHash::start(&entry).unwrap().read(&mut buffer, 0).unwrap() { + ControlFlow::Continue(more) => { + assert!(len > 0, "{:?}", file.name); + let found = more.read(&mut buffer, u64::MAX).unwrap(); + assert!(matches!(found, ControlFlow::Break(found) if found == expected)); + } + ControlFlow::Break(found) => assert_eq!((len, found), (0, expected)), + } + } + } + + /// A file that grows or shrinks after it was opened, or whose data is + /// written over with the same size, changed while it was read. So did + /// one whose modification time is set back after that: its change time + /// tells. That one is skipped where the change time moves with the + /// modification time, as on FAT. + #[test] + fn changes_while_read() { + let tmp = TempDir::new("sys-changes"); + let dir = &tmp.0; + let path = dir.join("file"); + let tree = open_dir(dir); + let mut buffer = vec![0; DATA_BUFFER_SIZE]; + let long: Vec = (0..2 * DATA_BUFFER_SIZE + 3).map(|i| (i % 251) as u8).collect(); + let follows = change_time_follows(dir); + if follows { + eprintln!( + "skipping a modification time that is set back: the change time of a file in the temporary directory moves with it" + ); + } + for data in [b"hello world".to_vec(), long] { + let other: Vec = data.iter().map(|b| b ^ 1).collect(); + for what in ["grow", "shrink", "write over", "set back"] { + if what == "set back" && follows { + continue; + } + fs::write(&path, &data).unwrap(); + let entry = Entry::open_at(tree.as_fd(), c"file").unwrap(); + let before = *entry.status(); + wait_for_clock(dir, before.ctime); + let open = || File::options().write(true).open(&path).unwrap(); + match what { + "grow" => OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(b"!") + .unwrap(), + "shrink" => open().set_len(before.size / 2).unwrap(), + "write over" => open().write_all(&other).unwrap(), + _ => { + open().write_all(&other).unwrap(); + let seconds = u64::try_from(before.mtime.seconds).unwrap(); + let mtime = UNIX_EPOCH + Duration::new(seconds, before.mtime.nanoseconds); + open().set_modified(mtime).unwrap(); + // Only the change time is different. + let now = Status::of(entry.handle()).unwrap(); + assert_eq!((now.size, now.mtime), (before.size, before.mtime)); + assert_ne!(now.ctime, before.ctime); + } + } + let read = hash(&entry, &mut buffer); + assert!( + matches!(read, Err(Failure::Changed)), + "{} {}: {:?}", + what, + data.len(), + read + ); + } + // Left alone, the same file reads as it is. + fs::write(&path, &data).unwrap(); + let entry = Entry::open_at(tree.as_fd(), c"file").unwrap(); + assert_eq!(hash(&entry, &mut buffer).unwrap(), Sha256::digest(&data)); + } + } + + /// A file that changes between two steps of its hash changed while it + /// was read, also where the change is in data that was read already. + #[test] + fn changes_between_steps() { + let tmp = TempDir::new("sys-steps"); + let dir = &tmp.0; + let path = dir.join("file"); + let tree = open_dir(dir); + let mut buffer = vec![0; DATA_BUFFER_SIZE]; + let budget = 4096; + let long: Vec = (0..2 * DATA_BUFFER_SIZE + 3).map(|i| (i % 251) as u8).collect(); + for what in ["grow", "write over the start"] { + fs::write(&path, &long).unwrap(); + let entry = Entry::open_at(tree.as_fd(), c"file").unwrap(); + let Ok(ControlFlow::Continue(mut hash)) = DataHash::start(&entry).unwrap().read(&mut buffer, budget) else { + panic!("{}: the first step read all of it", what); + }; + wait_for_clock(dir, entry.status().ctime); + let mut file = File::options().write(true).open(&path).unwrap(); + match what { + "grow" => OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(b"!") + .unwrap(), + _ => file.write_all(&[!long[0]]).unwrap(), + } + let read = loop { + match hash.read(&mut buffer, budget) { + Ok(ControlFlow::Continue(more)) => hash = more, + other => break other, + } + }; + assert!(matches!(read, Err(Failure::Changed)), "{}: {:?}", what, read); + } + } + + /// A file changed while it was read if its name leads to another file: + /// one with the same data, a symbolic link, a FIFO, a directory, or + /// nothing. The data is read through the handle of the file, which lost + /// its name, and that changed the file. + #[test] + fn replaced_while_read() { + let tmp = TempDir::new("sys-replaced"); + let dir = &tmp.0; + let path = dir.join("file"); + let tree = open_dir(dir); + let mut buffer = vec![0; DATA_BUFFER_SIZE]; + type Replace = fn(&Path); + let replacements: [(&str, Replace); 5] = [ + ("twin", |path| { + let twin = path.with_file_name("twin"); + fs::write(&twin, b"hello").unwrap(); + fs::rename(twin, path).unwrap(); + }), + ("symlink", |path| { + fs::remove_file(path).unwrap(); + symlink("elsewhere", path).unwrap(); + }), + ("fifo", |path| { + fs::remove_file(path).unwrap(); + make_fifo(path); + }), + ("directory", |path| { + fs::remove_file(path).unwrap(); + fs::create_dir(path).unwrap(); + }), + ("nothing", |path| fs::remove_file(path).unwrap()), + ]; + for (what, replace) in replacements { + if path.is_dir() { + fs::remove_dir(&path).unwrap(); + } else if fs::symlink_metadata(&path).is_ok() { + fs::remove_file(&path).unwrap(); + } + fs::write(&path, b"hello").unwrap(); + let entry = Entry::open_at(tree.as_fd(), c"file").unwrap(); + wait_for_clock(dir, entry.status().ctime); + replace(&path); + let read = hash(&entry, &mut buffer); + assert!(matches!(read, Err(Failure::Changed)), "{}: {:?}", what, read); + } + } + + /// Nothing but the pinned file is opened for its data: a FIFO that takes + /// its name is never opened, whichever way the file is opened again. + /// Nor is anything that is not a regular file opened for data when its + /// entry is one, which fails with EINVAL: a FIFO, a directory, a + /// symbolic link and a device node. + #[test] + fn opens_nothing_but_the_pinned_file() { + let tmp = TempDir::new("sys-fifo"); + let dir = &tmp.0; + let path = dir.join("file"); + let tree = open_dir(dir); + let mut buffer = vec![0; DATA_BUFFER_SIZE]; + for state in [EmptyPath::UNKNOWN, EmptyPath::MISSING] { + EMPTYPATH.store(state, Ordering::Relaxed); + fs::write(&path, b"hello").unwrap(); + let entry = Entry::open_at(tree.as_fd(), c"file").unwrap(); + wait_for_clock(dir, entry.status().ctime); + make_fifo(&dir.join("fifo")); + fs::rename(dir.join("fifo"), &path).unwrap(); + let opens = Opens::of(&path); + let read = hash(&entry, &mut buffer); + assert!(matches!(read, Err(Failure::Changed)), "{:?}", read); + let fifo = Entry::open_at(tree.as_fd(), c"file").unwrap(); + assert_eq!(errno(DataHash::start(&fifo)), libc::EINVAL); + assert!(!opens.seen()); + // An open of the FIFO does show up. + let flags = OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC; + drop(rustix::fs::open(&path, flags, rustix::fs::Mode::empty()).unwrap()); + assert!(opens.seen()); + fs::remove_file(&path).unwrap(); + } + EMPTYPATH.store(EmptyPath::UNKNOWN, Ordering::Relaxed); + fs::create_dir(dir.join("dir")).unwrap(); + symlink("dir", dir.join("link")).unwrap(); + let dev = open_dir(Path::new("/dev")); + let opens = Opens::of(&dir.join("dir")); + for (parent, name) in [(tree.as_fd(), c"dir"), (tree.as_fd(), c"link"), (dev.as_fd(), c"null")] { + let entry = Entry::open_at(parent, name).unwrap(); + assert_eq!(errno(DataHash::start(&entry)), libc::EINVAL, "{:?}", name); + } + // The directory, which could be opened, was not opened either. + assert!(!opens.seen()); + let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC; + drop(rustix::fs::open(dir.join("dir"), flags, rustix::fs::Mode::empty()).unwrap()); + assert!(opens.seen()); + } + + /// A pinned file is opened again every way there is: through + /// O_EMPTYPATH where the kernel has it, and through the procfs of + /// pathrs. Each gives the pinned file, after another file took its name + /// and after it lost its last name. + #[test] + fn reopens_the_pinned_file() { + let tmp = TempDir::new("sys-reopen"); + let dir = &tmp.0; + fs::write(dir.join("file"), b"pinned").unwrap(); + let tree = open_dir(dir); + let entry = Entry::open_at(tree.as_fd(), c"file").unwrap(); + let pinned = PinnedFile::new(entry.handle()); + let read = |mut file: File| { + let mut text = String::new(); + file.read_to_string(&mut text).unwrap(); + text + }; + fs::rename(dir.join("file"), dir.join("moved")).unwrap(); + fs::write(dir.join("file"), b"impostor").unwrap(); + for unlinked in [false, true] { + if unlinked { + fs::remove_file(dir.join("moved")).unwrap(); + } + match pinned.reopen_empty_path() { + Ok(file) => assert_eq!(read(file), "pinned"), + Err(Errno::NOENT) => eprintln!("skipping O_EMPTYPATH, which the kernel does not have"), + Err(e) => panic!("{}", e), + } + assert_eq!(read(pinned.reopen_procfs().unwrap()), "pinned"); + assert_eq!(read(pinned.reopen().unwrap()), "pinned"); + } + } + + /// The link of a descriptor in procfs leads to its file, also after the + /// file lost its name, which is checked before its path is used: a link + /// that leads to another file fails. + #[test] + fn links_of_descriptors() { + let tmp = TempDir::new("sys-fd-link"); + let dir = &tmp.0; + fs::write(dir.join("a"), b"a").unwrap(); + fs::write(dir.join("b"), b"b").unwrap(); + let a = File::open(dir.join("a")).unwrap(); + let b = File::open(dir.join("b")).unwrap(); + fs::remove_file(dir.join("a")).unwrap(); + let link = FdLink::new(a.as_fd()); + link.check().unwrap(); + assert_eq!(fs::read(link.path()).unwrap(), b"a"); + let elsewhere = FdLink { + fd: a.as_fd(), + path: FdLink::new(b.as_fd()).path, + }; + let e = elsewhere.check().unwrap_err(); + assert_eq!(e.to_string(), "the link of /proc/thread-self/fd leads to another file"); + } + + /// A regular file and a directory are opened for reading as the files + /// of their entries: a regular file through its handle, also once + /// another file has its name, and a directory by its name, which is a + /// change once the name leads to another file or to none. A directory + /// that may be read but not searched is opened by its name as well, and + /// one without a name, of a descriptor a caller gave, through its + /// handle. What is opened is not a handle, and it is not inherited + /// across exec. Nothing else is opened: a symbolic link, a FIFO, a + /// socket and a device node fail with EINVAL, and nobody opened the + /// FIFO. + #[test] + fn reopens_files_and_directories() { + let tmp = TempDir::new("sys-reopen-entries"); + let dir = &tmp.0; + fs::write(dir.join("file"), b"pinned").unwrap(); + fs::create_dir(dir.join("dir")).unwrap(); + fs::write(dir.join("dir/inside"), b"").unwrap(); + fs::create_dir(dir.join("unsearchable")).unwrap(); + fs::set_permissions(dir.join("unsearchable"), fs::Permissions::from_mode(0o400)).unwrap(); + symlink("file", dir.join("link")).unwrap(); + make_fifo(&dir.join("fifo")); + let _socket = UnixListener::bind(dir.join("socket")).unwrap(); + let tree = open_dir(dir); + let at = |name| { + Some(Place { + dir: tree.as_fd(), + name, + }) + }; + let file = Entry::open_at(tree.as_fd(), c"file").unwrap(); + let directory = Entry::open_at(tree.as_fd(), c"dir").unwrap(); + let unsearchable = Entry::open_at(tree.as_fd(), c"unsearchable").unwrap(); + fs::rename(dir.join("file"), dir.join("moved")).unwrap(); + fs::write(dir.join("file"), b"impostor").unwrap(); + fs::rename(dir.join("dir"), dir.join("moved-dir")).unwrap(); + fs::create_dir(dir.join("dir")).unwrap(); + let check_flags = |opened: &Readable| { + assert!(!rustix::fs::fcntl_getfl(opened.as_fd()).unwrap().contains(OFlags::PATH)); + assert!(rustix::io::fcntl_getfd(opened.as_fd()) + .unwrap() + .contains(FdFlags::CLOEXEC)); + }; + // The entries of a directory that is open, listed through it. + let listed = |opened: &Readable| { + rustix::fs::Dir::read_from(opened.as_fd()) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_owned()) + .filter(|name| !matches!(name.to_bytes(), b"." | b"..")) + .collect::>() + }; + for state in [EmptyPath::UNKNOWN, EmptyPath::MISSING] { + EMPTYPATH.store(state, Ordering::Relaxed); + for place in [None, at(c"file")] { + let opened = file.reopen(place).unwrap(); + check_flags(&opened); + let mut data = [0; 16]; + let read = rustix::io::pread(opened.as_fd(), &mut data, 0).unwrap(); + assert_eq!(&data[..read], b"pinned"); + } + let opened = directory.reopen(None).unwrap(); + check_flags(&opened); + assert_eq!(listed(&opened), [c"inside".to_owned()]); + check_flags(&unsearchable.reopen(None).unwrap()); + } + EMPTYPATH.store(EmptyPath::UNKNOWN, Ordering::Relaxed); + let opened = directory.reopen(at(c"moved-dir")).unwrap(); + check_flags(&opened); + assert_eq!(listed(&opened), [c"inside".to_owned()]); + check_flags(&unsearchable.reopen(at(c"unsearchable")).unwrap()); + // Another directory, a regular file, a symbolic link to the + // directory, and nothing. + symlink("moved-dir", dir.join("dir-link")).unwrap(); + for name in [c"dir", c"file", c"dir-link", c"gone"] { + let reopened = directory.reopen(at(name)); + assert!(matches!(reopened, Err(Failure::Changed)), "{:?}: {:?}", name, reopened); + } + let opens = Opens::of(&dir.join("fifo")); + for name in [c"link", c"fifo", c"socket"] { + let entry = Entry::open_at(tree.as_fd(), name).unwrap(); + for place in [None, at(name)] { + assert_eq!(errno(entry.reopen(place)), libc::EINVAL, "{:?}", name); + } + } + assert!(!opens.seen()); + let dev = open_dir(Path::new("/dev")); + let null = Entry::open_at(dev.as_fd(), c"null").unwrap(); + let place = Place { + dir: dev.as_fd(), + name: c"null", + }; + assert_eq!(errno(null.reopen(Some(place))), libc::EINVAL); + } + + /// The data of a file that is open already is hashed through that + /// descriptor, with the same checks as otherwise. A directory that is + /// open has no data to hash. + #[test] + fn hashes_through_an_open_file() { + let tmp = TempDir::new("sys-hash-open"); + let dir = &tmp.0; + let data: Vec = (0..DATA_BUFFER_SIZE + 5).map(|i| (i % 249) as u8).collect(); + fs::write(dir.join("file"), &data).unwrap(); + fs::create_dir(dir.join("dir")).unwrap(); + let tree = open_dir(dir); + let entry = Entry::open_at(tree.as_fd(), c"file").unwrap(); + let mut buffer = vec![0; DATA_BUFFER_SIZE]; + let mut hash = DataHash::of(&entry, entry.reopen(None).unwrap()).unwrap(); + let found = loop { + match hash.read(&mut buffer, 4096).unwrap() { + ControlFlow::Break(found) => break found, + ControlFlow::Continue(more) => hash = more, + } + }; + assert_eq!(found, Sha256::digest(&data)); + // A file that changes after it was opened again changed while it + // was read. + let hash = DataHash::of(&entry, entry.reopen(None).unwrap()).unwrap(); + wait_for_clock(dir, entry.status().ctime); + OpenOptions::new() + .append(true) + .open(dir.join("file")) + .unwrap() + .write_all(b"!") + .unwrap(); + let read = hash.read(&mut buffer, u64::MAX); + assert!(matches!(read, Err(Failure::Changed)), "{:?}", read); + let directory = Entry::open_at(tree.as_fd(), c"dir").unwrap(); + let opened = directory + .reopen(Some(Place { + dir: tree.as_fd(), + name: c"dir", + })) + .unwrap(); + assert_eq!(errno(DataHash::of(&directory, opened)), libc::EINVAL); + } + + /// A directory lists every entry once, in the order getdents() gives + /// them, without `.` and `..`, with names that are not UTF-8 and with + /// one of the longest name, over several calls of getdents(). It is + /// listed through itself opened by its name, its entries are opened in + /// it, and its status is that of its entry. An entry that does not fit + /// into the room of a call fails it with EINVAL where it comes first, + /// and the room grows until it fits. + #[test] + fn lists_the_entries() { + let tmp = TempDir::new("sys-entries"); + let dir = &tmp.0; + fs::create_dir(dir.join("dir")).unwrap(); + let names: Vec = ["a", "b c", "\u{e9}"] + .iter() + .map(std::ffi::OsString::from) + .chain([std::ffi::OsString::from_vec(b"\xff\xfe".to_vec())]) + .chain([std::ffi::OsString::from("l".repeat(255))]) + .chain((0..1000).map(|i| std::ffi::OsString::from(format!("many-{}", i)))) + .collect(); + for name in &names { + fs::write(dir.join("dir").join(name), b"").unwrap(); + } + let tree = open_dir(dir); + let at = |name| { + Some(Place { + dir: tree.as_fd(), + name, + }) + }; + let entry = Entry::open_at(tree.as_fd(), c"dir").unwrap(); + let entries = entry.reopen(at(c"dir")).unwrap().entries(); + assert!(!rustix::fs::fcntl_getfl(entries.as_fd()).unwrap().contains(OFlags::PATH)); + assert!(!entries.status().unwrap().changed_since(entry.status())); + let listed: Vec = entries + .map(|listed| std::ffi::OsString::from_vec(listed.unwrap().name().to_bytes().to_vec())) + .collect(); + assert_eq!(listed, names_in(&dir.join("dir"))); + let mut sorted = listed.clone(); + sorted.sort(); + let mut expected = names.clone(); + expected.sort(); + assert_eq!(sorted, expected); + // What it lists is opened in it. + let mut entries = entry.reopen(at(c"dir")).unwrap().entries(); + let first = entries.next().unwrap().unwrap(); + let file = Entry::open_at(entries.as_fd(), first.name()).unwrap(); + assert_eq!(file.status().file_type, FileType::RegularFile); + // With room for 64 bytes first, an entry of 280 for the longest + // name fits once the room has grown three times. + let longest = "l".repeat(255); + fs::create_dir(dir.join("long")).unwrap(); + fs::write(dir.join("long").join(&longest), b"").unwrap(); + let entry = Entry::open_at(tree.as_fd(), c"long").unwrap(); + let mut entries = entry.reopen(at(c"long")).unwrap().entries(); + entries.size = 64; + let listed: Vec = entries.map(|listed| listed.unwrap().name().to_owned()).collect(); + assert_eq!(listed, [CString::new(longest).unwrap()]); + } + + /// The target of a symbolic link is read through its handle, as the + /// bytes it is: relative, absolute, long, and not UTF-8. + #[test] + fn reads_targets() { + let tmp = TempDir::new("sys-targets"); + let dir = &tmp.0; + // xfs takes targets of up to 1024 bytes. + let long = "x/".repeat(500); + let targets: [&[u8]; 4] = [b"file", b"/etc/passwd", long.as_bytes(), b"\xff\xfe/below"]; + for (i, target) in targets.iter().enumerate() { + symlink(std::ffi::OsStr::from_bytes(target), dir.join(format!("link-{}", i))).unwrap(); + } + let tree = open_dir(dir); + for (i, target) in targets.iter().enumerate() { + let name = CString::new(format!("link-{}", i)).unwrap(); + let entry = Entry::open_at(tree.as_fd(), &name).unwrap(); + assert_eq!(entry.target().unwrap(), *target, "{}", i); + } + } + + /// A new file has no name until it gets its own, which replaces + /// nothing. Where the file system has O_TMPFILE it has none, also not + /// one a walk would have to pass over. A link through procfs goes to a + /// temporary name first, and one that leads to another file by then + /// leaves no name behind: the name of the file never appears, as + /// inotify sees it, and the temporary name is gone again. + #[test] + fn new_files_without_names() { + let tmp = TempDir::new("sys-new-unnamed"); + let dir = &tmp.0; + let directory = File::open(dir).unwrap(); + let (mut file, new) = NewFile::create_at(directory.as_fd(), Path::new("m"), false).unwrap(); + if new.temporary.is_some() { + eprintln!("skipping: the temporary directory has no O_TMPFILE"); + return; + } + assert!(new.named_file().unwrap().is_none()); + file.write_all(b"manifest").unwrap(); + assert!(names_in(dir).is_empty()); + new.link().unwrap(); + assert_eq!(fs::read(dir.join("m")).unwrap(), b"manifest"); + // The link of procfs, for a kernel before 6.10, links the same. A + // temporary name it leaves is removed as for every file that has + // its name. + let (mut file, mut new) = NewFile::create_at(directory.as_fd(), Path::new("again"), false).unwrap(); + file.write_all(b"again").unwrap(); + new.temporary = new.link_through_procfs().unwrap(); + new.sync_named().unwrap(); + assert_eq!(fs::read(dir.join("again")).unwrap(), b"again"); + // A link that leads to another file by the time the file gets its + // name leaves no name behind, and the other file as it was. + fs::write(dir.join("decoy"), b"decoy").unwrap(); + let (_, new) = NewFile::create_at(directory.as_fd(), Path::new("decoyed"), false).unwrap(); + let decoy = dir.join("decoy"); + let inotify = inotify::init(inotify::CreateFlags::CLOEXEC | inotify::CreateFlags::NONBLOCK).unwrap(); + let named = inotify::WatchFlags::CREATE | inotify::WatchFlags::MOVED_TO; + inotify::add_watch(&inotify, dir, named).unwrap(); + let Err(Unnamed::Failed(e)) = new.link_through(decoy.to_str().unwrap()) else { + panic!("the link that leads to another file did not fail as one that gave no name"); + }; + assert_eq!(e.to_string(), "the link of /proc/thread-self/fd leads to another file"); + let mut buffer = [MaybeUninit::uninit(); 4096]; + let mut events = inotify::Reader::new(&inotify, &mut buffer); + let mut appeared = Vec::new(); + loop { + match events.next() { + Ok(event) => appeared.push(event.file_name().unwrap().to_owned()), + Err(Errno::AGAIN) => break, + Err(e) => panic!("{}", e), + } + } + assert_eq!(appeared.len(), 1, "{:?}", appeared); + assert!(appeared[0].to_bytes().starts_with(NewFile::NAME_PREFIX.as_bytes())); + let mut names = names_in(dir); + names.sort(); + assert_eq!(names, ["again", "decoy", "m"]); + assert_eq!(fs::metadata(&decoy).unwrap().nlink(), 1); + fs::remove_file(&decoy).unwrap(); + // One that is synced gets its name the same way. + let (mut file, new) = NewFile::create_at(directory.as_fd(), Path::new("synced"), true).unwrap(); + file.write_all(b"synced").unwrap(); + new.link().unwrap(); + assert_eq!(fs::read(dir.join("synced")).unwrap(), b"synced"); + // Something that has the name by then stays. + let (_, new) = NewFile::create_at(directory.as_fd(), Path::new("taken"), false).unwrap(); + fs::write(dir.join("taken"), b"mine").unwrap(); + let e = new.link().unwrap_err(); + let message = format!( + "the manifest file 'taken': {}", + io::Error::from_raw_os_error(libc::EEXIST) + ); + assert_eq!(e.to_string(), message); + assert_eq!(new_file_errno(e), Some(libc::EEXIST)); + assert_eq!(fs::read(dir.join("taken")).unwrap(), b"mine"); + } + + /// The name of a new file below a directory has the directories on the + /// way and the name of the file in the last one. A name is none of a + /// file below a directory where it is empty, absolute, ends in a slash, + /// `.` or `..`, or has `.` or `..` on the way. Slashes that follow each + /// other are one. + #[test] + fn names_of_new_files_below_a_directory() { + let split = |name: &'static str| NewFile::split(Path::new(name)); + let parts = + |parent: Option<&'static str>, file: &'static str| Some((parent.map(str::as_bytes), file.as_bytes())); + assert_eq!(split("m"), parts(None, "m")); + assert_eq!(split("a/m"), parts(Some("a"), "m")); + assert_eq!(split("a/b/m"), parts(Some("a/b"), "m")); + assert_eq!(split("a//b///m"), parts(Some("a//b//"), "m")); + assert_eq!(split("..a/b../..."), parts(Some("..a/b.."), "...")); + for name in [ + "", + "/", + "/m", + "//m", + "/a/m", + "a/", + "a//", + ".", + "..", + "a/.", + "a/..", + "./m", + "../m", + "a/./m", + "a/../m", + "a/b/../../m", + "a//../m", + ] { + assert_eq!(split(name), None, "{:?}", name); + } + let components = |parent: &'static str| NewFile::components(parent.as_bytes()).collect::>(); + assert_eq!(components("a//b//"), [b"a", b"b"]); + assert!(components("").is_empty()); + } + + /// A new file that has a name until it gets its own, as on a file + /// system without O_TMPFILE, is renamed without replacing anything, and + /// loses its name when it is dropped instead. Its inode is the one a + /// walk has to pass over. One that is synced gets its name the same + /// way. One that is dropped keeps what it holds, and one whose name is + /// taken is emptied. What the first half of the link came to decides + /// that: a file that got no name is emptied, and one of which nobody + /// can tell whether it has its name keeps what it holds. Both lose + /// their temporary name. + #[test] + fn new_files_with_names() { + let tmp = TempDir::new("sys-new-named"); + let dir = &tmp.0; + let directory = File::open(dir).unwrap(); + let new_synced = |name: &CStr, sync: bool| { + let named = TemporaryName::create( + directory.as_fd(), + NewFile::NAME_PREFIX, + NewFile::NAMED_FLAGS, + NewFile::MODE, + ); + let (file, temporary) = named.unwrap(); + let new = NewFile { + directory: Arc::new(directory.as_fd().try_clone_to_owned().unwrap()), + name: name.to_owned(), + path: PathBuf::from(name.to_str().unwrap()), + file: Arc::new(File::from(file)), + temporary: Some(temporary), + sync, + }; + (new.file.try_clone().unwrap(), new) + }; + let new = |name: &CStr| new_synced(name, false); + let (mut file, synced) = new_synced(c"synced", true); + file.write_all(b"synced").unwrap(); + synced.link().unwrap(); + assert_eq!(fs::read(dir.join("synced")).unwrap(), b"synced"); + fs::remove_file(dir.join("synced")).unwrap(); + let (mut file, made) = new(c"m"); + let inode = Status::of(file.as_fd()).unwrap().identity.inode_id(); + // What a walk passes over is the file by the descriptor the new + // file has of it: no other one is taken for it. + let (named, shared) = made.named_file().unwrap().unwrap(); + assert_eq!(named, inode); + assert!(Arc::ptr_eq(&shared, &made.file)); + drop(shared); + let listed = names_in(dir); + assert!( + listed.len() == 1 + && listed[0] + .as_encoded_bytes() + .starts_with(NewFile::NAME_PREFIX.as_bytes()) + ); + file.write_all(b"manifest").unwrap(); + made.link().unwrap(); + assert_eq!(names_in(dir), ["m"]); + assert_eq!(fs::read(dir.join("m")).unwrap(), b"manifest"); + let (mut file, dropped) = new(c"dropped"); + file.write_all(b"dropped").unwrap(); + drop(dropped); + assert_eq!(file.metadata().unwrap().len(), b"dropped".len() as u64); + assert_eq!(names_in(dir), ["m"]); + let (mut file, taken) = new(c"m"); + file.write_all(b"taken").unwrap(); + assert_eq!(new_file_errno(taken.link().unwrap_err()), Some(libc::EEXIST)); + assert_eq!(file.metadata().unwrap().len(), 0); + assert_eq!(names_in(dir), ["m"]); + assert_eq!(fs::read(dir.join("m")).unwrap(), b"manifest"); + // A file of which nobody can tell whether it has its name keeps + // what it holds, and one that got none is emptied. Both lose their + // temporary name with the drop. + for (unnamed, held) in [ + (Unnamed::Unknown(Errno::EXIST.into()), b"untold".len() as u64), + (Unnamed::Failed(Errno::EXIST.into()), 0), + ] { + let (mut file, untold) = new(c"untold"); + file.write_all(b"untold").unwrap(); + let e = untold.linked(Err(unnamed)).unwrap_err(); + assert_eq!(new_file_errno(e), Some(libc::EEXIST)); + assert_eq!(file.metadata().unwrap().len(), held); + assert_eq!(names_in(dir), ["m"]); + } + } + + /// The variable that names a directory without O_TMPFILE, in which the + /// test binary runs [`new_files_without_descriptors`] again. + const NO_TMPFILE_DIR: &str = "UAPI16_TEST_NO_TMPFILE_DIR"; + + /// A new file that has a name until it gets its own and that can't be + /// made for want of a descriptor leaves no name behind. The test binary + /// runs this test again with 64 descriptors at most, in a user, mount + /// and IPC namespace from unshare(1), on a file system of message + /// queues, which has no O_TMPFILE. It is skipped where unshare can't + /// make one. + #[test] + fn new_files_without_descriptors() { + if let Some(dir) = std::env::var_os(NO_TMPFILE_DIR) { + return check_new_files_without_descriptors(Path::new(&dir)); + } + let tmp = TempDir::new("sys-new-descriptors"); + let dir = &tmp.0; + let works = Command::new("unshare").args(["-Urmi", "true"]).output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urmi does not work here"); + return; + } + // The script exits with 77 where it can't mount the file system. + let script = concat!( + r#"mount -t mqueue mqueue "$1" || exit 77; ulimit -n 64 || exit 1; "#, + r#"exec "$2" --exact sys::tests::new_files_without_descriptors"# + ); + let output = Command::new("unshare") + .args(["-Urmi", "sh", "-c", script, "sh"]) + .arg(dir) + .arg(std::env::current_exe().unwrap()) + .env(NO_TMPFILE_DIR, dir) + .output() + .unwrap(); + if output.status.code() == Some(77) { + eprintln!("skipping: no file system of message queues here"); + return; + } + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } + + /// The checks of [`new_files_without_descriptors`] in `dir`. + fn check_new_files_without_descriptors(dir: &Path) { + let directory = File::open(dir).unwrap(); + let unnamed = rustix::fs::openat(&directory, NewFile::ITSELF, NewFile::UNNAMED_FLAGS, NewFile::MODE); + assert_eq!(unnamed.unwrap_err(), Errno::OPNOTSUPP); + // Two descriptors are left, for the directory and for the file, + // which has its name then. None is left for writing it. + let mut taken = Vec::new(); + loop { + match rustix::fs::open("/dev/null", OFlags::RDONLY | OFlags::CLOEXEC, rustix::fs::Mode::empty()) { + Ok(fd) => taken.push(fd), + Err(Errno::MFILE) => break, + Err(e) => panic!("{}", e), + } + } + taken.truncate(taken.len() - 2); + let e = NewFile::create_at(directory.as_fd(), Path::new("m"), false).unwrap_err(); + drop(taken); + assert_eq!(new_file_errno(e), Some(libc::EMFILE)); + assert!(names_in(dir).is_empty(), "{:?}", names_in(dir)); + } + + /// A call that gives a new file its name and that was interrupted can + /// have given the name before it failed. Made again it fails with + /// EEXIST for a link, with ENOENT for a rename, or with something else, + /// and the file has the name where the name leads to it. Where the + /// name leads to another file by then, is not there, or can't be + /// looked at, nobody can tell whether the call gave it, and the half + /// that made the call is told so. A call that fails because the file + /// system has no such call gave no name, and one that was not + /// interrupted says what it says. + #[test] + fn names_given_while_interrupted() { + let tmp = TempDir::new("sys-new-interrupted"); + let dir = &tmp.0; + let directory = File::open(dir).unwrap(); + let new = |name: &CStr| { + let named = TemporaryName::create( + directory.as_fd(), + NewFile::NAME_PREFIX, + NewFile::NAMED_FLAGS, + NewFile::MODE, + ); + let (file, temporary) = named.unwrap(); + NewFile { + directory: Arc::new(directory.as_fd().try_clone_to_owned().unwrap()), + name: name.to_owned(), + path: PathBuf::from(name.to_str().unwrap()), + file: Arc::new(File::from(file)), + temporary: Some(temporary), + sync: false, + } + }; + // `give`, which is interrupted the first time once it did what it + // does. + fn interrupted_once( + mut give: impl FnMut() -> rustix::io::Result<()>, + ) -> impl FnMut() -> rustix::io::Result<()> { + let mut first = true; + move || { + let given = give(); + if std::mem::take(&mut first) { + given.and(Err(Errno::INTR)) + } else { + given + } + } + } + let linked = new(c"linked"); + let from = linked.temporary.as_ref().unwrap().as_c_str(); + let link = || rustix::fs::linkat(&linked.directory, from, &linked.directory, c"linked", AtFlags::empty()); + linked.give_name(interrupted_once(link)).unwrap(); + assert!(linked.has_name().unwrap()); + // The same where the call fails for something else when it is made + // again: it gave the name before it was interrupted. + let done = new(c"done"); + let from = done.temporary.as_ref().unwrap().as_c_str(); + let link = || rustix::fs::linkat(&done.directory, from, &done.directory, c"done", AtFlags::empty()); + let mut link = interrupted_once(link); + let mut first = true; + let told = done.give_name(|| { + if std::mem::take(&mut first) { + link() + } else { + Err(Errno::IO) + } + }); + assert_eq!(told, Ok(())); + // One that did nothing before it was interrupted and fails that + // way: nobody can tell. And one that fails because the file system + // has no such call gave no name. + for (errno, told) in [ + (Errno::IO, Unnamed::Unknown(Errno::IO)), + (Errno::INVAL, Unnamed::Failed(Errno::INVAL)), + (Errno::NOSYS, Unnamed::Failed(Errno::NOSYS)), + (Errno::OPNOTSUPP, Unnamed::Failed(Errno::OPNOTSUPP)), + ] { + let mut calls = [Errno::INTR, errno].into_iter(); + assert_eq!(new(c"untold").give_name(|| Err(calls.next().unwrap())), Err(told)); + } + let renamed = new(c"renamed"); + let from = renamed.temporary.as_ref().unwrap().as_c_str(); + let flags = RenameFlags::NOREPLACE; + let rename = || rustix::fs::renameat_with(&renamed.directory, from, &renamed.directory, c"renamed", flags); + match renamed.give_name(interrupted_once(rename)) { + Ok(()) => assert!(renamed.has_name().unwrap()), + Err(Unnamed::Failed(Errno::INVAL)) => { + eprintln!("skipping the rename: the temporary directory has no RENAME_NOREPLACE") + } + Err(e) => panic!("{:?}", e), + } + // Interrupted before anything was done, and another file took the + // name in between. The call made again fails as it does after one + // that gave the name, and the name leads elsewhere, as it does once + // another process renamed its file over it: nobody can tell. + let taken = new(c"taken"); + let from = taken.temporary.as_ref().unwrap().as_c_str(); + let mut first = true; + let told = taken.give_name(|| { + if std::mem::take(&mut first) { + fs::write(dir.join("taken"), b"mine").unwrap(); + return Err(Errno::INTR); + } + rustix::fs::linkat(&taken.directory, from, &taken.directory, c"taken", AtFlags::empty()) + }); + assert_eq!(told, Err(Unnamed::Unknown(Errno::EXIST))); + // It stays that for the half that made the call. + let half: Unnamed = Unnamed::Unknown(Errno::EXIST).into(); + assert!(matches!(half, Unnamed::Unknown(_))); + assert_eq!(fs::read(dir.join("taken")).unwrap(), b"mine"); + // A name that can't be looked at tells nothing either. The + // directory may not be searched here, which is skipped where the + // tests may search any. + fs::set_permissions(dir, fs::Permissions::from_mode(0o600)).unwrap(); + let searched = fs::symlink_metadata(dir.join("taken")).is_ok(); + let mut calls = [Errno::INTR, Errno::EXIST].into_iter(); + let told = taken.give_name(|| Err(calls.next().unwrap())); + fs::set_permissions(dir, fs::Permissions::from_mode(0o700)).unwrap(); + if searched { + eprintln!("skipping the name that can't be looked at: the tests may search any directory"); + } else { + assert_eq!(told, Err(Unnamed::Unknown(Errno::ACCESS))); + } + // Not interrupted, a name that is taken is a call that failed. + let told = taken + .give_name(|| rustix::fs::linkat(&taken.directory, from, &taken.directory, c"taken", AtFlags::empty())); + assert_eq!(told, Err(Unnamed::Failed(Errno::EXIST))); + } + + /// The errno of the I/O error `e` of a new file, which says what file + /// it is of, see Error::io_about(). + fn new_file_errno(e: io::Error) -> Option { + Error::from(e).io_error().and_then(io::Error::raw_os_error) + } + + /// Without RENAME_NOREPLACE a new file gets a link of its own name, and + /// its temporary name is removed once it has that. Where that fails, + /// the file has both names and what it holds, and this fails. Its own + /// name is not removed again, since another file can have taken it in + /// between. The temporary name is removed once more when the file is + /// dropped. The temporary name here is in a directory that may be + /// searched but not written, so the link goes through and the removal + /// does not. That is skipped where the tests may remove any name. The + /// file is open for reading and writing, as a new file is, so that one + /// that is given up is seen to be empty. + #[test] + fn links_instead_of_renames() { + let tmp = TempDir::new("sys-new-link-instead"); + let dir = &tmp.0; + let directory = File::open(dir).unwrap(); + let new = |name: &CStr, temporary: &CStr| NewFile { + directory: Arc::new(directory.as_fd().try_clone_to_owned().unwrap()), + name: name.to_owned(), + path: PathBuf::from(name.to_str().unwrap()), + file: Arc::new( + OpenOptions::new() + .read(true) + .write(true) + .open(dir.join(temporary.to_str().unwrap())) + .unwrap(), + ), + temporary: Some(TemporaryName(temporary.to_owned())), + sync: false, + }; + // The link that gives the name where a rename says that there is + // no RENAME_NOREPLACE. What comes once the file has its name + // removes the temporary one. + let link = |new: &NewFile| new.link_instead(new.temporary.as_ref().unwrap()); + fs::create_dir(dir.join("open")).unwrap(); + fs::write(dir.join("open/file"), b"named").unwrap(); + let mut named = new(c"named", c"open/file"); + link(&named).unwrap(); + assert!(dir.join("open/file").exists()); + named.sync_named().unwrap(); + assert_eq!(fs::read(dir.join("named")).unwrap(), b"named"); + assert!(!dir.join("open/file").exists() && named.temporary.is_none()); + fs::create_dir(dir.join("locked")).unwrap(); + fs::write(dir.join("locked/file"), b"both").unwrap(); + fs::write(dir.join("locked/probe"), b"").unwrap(); + fs::set_permissions(dir.join("locked"), fs::Permissions::from_mode(0o500)).unwrap(); + /// Makes the directory writable again before it is removed. + struct Unlock<'a>(&'a Path); + impl Drop for Unlock<'_> { + fn drop(&mut self) { + let _ = fs::set_permissions(self.0, fs::Permissions::from_mode(0o700)); + } + } + let locked = dir.join("locked"); + let _unlock = Unlock(&locked); + if fs::remove_file(dir.join("locked/probe")).is_ok() { + eprintln!("skipping the name that can't be removed: the tests may remove any"); + return; + } + let mut both = new(c"both", c"locked/file"); + link(&both).unwrap(); + let e = both.sync_named().unwrap_err(); + assert_eq!(e.raw_os_error(), Some(libc::EACCES)); + assert_eq!(fs::read(dir.join("both")).unwrap(), b"both"); + assert_eq!(fs::read(dir.join("locked/file")).unwrap(), b"both"); + fs::set_permissions(&locked, fs::Permissions::from_mode(0o700)).unwrap(); + drop(both); + assert_eq!(fs::read(dir.join("both")).unwrap(), b"both"); + assert!(!dir.join("locked/file").exists()); + } + + /// A temporary name is made by a link as well, which follows a symbolic + /// link at the end of its path, as it has to for the link procfs has + /// for a descriptor. What was interrupted can have made the name before + /// it failed: that name is removed, and the next one is made. + #[test] + fn temporary_names_of_links() { + let tmp = TempDir::new("sys-temporary-links"); + let dir = &tmp.0; + let directory = File::open(dir).unwrap(); + fs::write(dir.join("file"), b"linked").unwrap(); + symlink("file", dir.join("link")).unwrap(); + let path = dir.join("link"); + let path = path.to_str().unwrap(); + let name = TemporaryName::link(directory.as_fd(), ".test-", path).unwrap(); + let linked = dir.join(std::ffi::OsStr::from_bytes(name.as_c_str().to_bytes())); + assert_eq!(fs::read(&linked).unwrap(), b"linked"); + assert!(!fs::symlink_metadata(&linked).unwrap().is_symlink()); + assert_eq!(fs::metadata(dir.join("file")).unwrap().nlink(), 2); + name.remove(directory.as_fd()).unwrap(); + let mut tried = Vec::new(); + let made = TemporaryName::make(directory.as_fd(), ".test-", |name| { + tried.push(name.to_owned()); + rustix::fs::linkat(CWD, path, &directory, name, AtFlags::SYMLINK_FOLLOW)?; + if tried.len() == 1 { + return Err(Errno::INTR); + } + Ok(()) + }); + let ((), name) = made.unwrap(); + assert_eq!(tried.len(), 2); + assert_eq!(name.as_c_str(), tried[1].as_c_str()); + // A call that was interrupted takes no name that something has, so + // any number of them is tried again, each with another name. + let interruptions = 3 * TemporaryName::ATTEMPTS; + let mut calls = 0; + let made = TemporaryName::make(directory.as_fd(), ".interrupted-", |_| { + calls += 1; + if calls <= interruptions { + return Err(Errno::INTR); + } + Ok(calls) + }); + assert_eq!(made.unwrap().0, interruptions + 1); + // Names that something has are tried so many times and no more, + // also with interruptions in between. + let mut calls = 0; + let taken = TemporaryName::make(directory.as_fd(), ".taken-", |_| { + calls += 1; + Err::<(), _>(if calls % 2 == 0 { Errno::EXIST } else { Errno::INTR }) + }); + assert_eq!(taken.map(drop).map_err(|e| e.raw_os_error()), Err(Some(libc::EEXIST))); + assert_eq!(calls, 2 * TemporaryName::ATTEMPTS); + let mut names = names_in(dir); + names.sort(); + let made = std::ffi::OsStr::from_bytes(name.as_c_str().to_bytes()).to_owned(); + let mut expected = vec![made, "file".into(), "link".into()]; + expected.sort(); + assert_eq!(names, expected); + assert_eq!(fs::metadata(dir.join("file")).unwrap().nlink(), 2); + } + + /// A new file that is abandoned keeps the name it has until it gets its + /// own, as the child of a fork() leaves it to its parent, which gives + /// the file its name after that. + #[cfg(feature = "capi")] + #[test] + fn abandoned_new_files_keep_their_names() { + let tmp = TempDir::new("sys-new-abandoned"); + let dir = &tmp.0; + let directory = File::open(dir).unwrap(); + let named = TemporaryName::create( + directory.as_fd(), + NewFile::NAME_PREFIX, + NewFile::NAMED_FLAGS, + NewFile::MODE, + ); + let (file, temporary) = named.unwrap(); + let made = NewFile { + directory: Arc::new(directory.as_fd().try_clone_to_owned().unwrap()), + name: c"m".to_owned(), + path: PathBuf::from("m"), + file: Arc::new(File::from(file)), + temporary: Some(temporary), + sync: false, + }; + let temporary = names_in(dir); + assert_eq!(temporary.len(), 1); + // What the child has of the file is the same descriptors and the + // same name. + let name = made.temporary.as_ref().unwrap().as_c_str().to_owned(); + let inherited = NewFile { + directory: Arc::new(made.directory.try_clone().unwrap()), + name: made.name.clone(), + path: made.path.clone(), + file: Arc::new(made.file.try_clone().unwrap()), + temporary: Some(TemporaryName(name)), + sync: false, + }; + inherited.abandon(); + assert_eq!(names_in(dir), temporary); + made.link().unwrap(); + assert_eq!(names_in(dir), ["m"]); + // One that has no such name is dropped as it is. Where the file + // system makes no file without a name it has one too, which stays. + let (_, other) = NewFile::create_at(directory.as_fd(), Path::new("other"), false).unwrap(); + let named = usize::from(other.temporary.is_some()); + other.abandon(); + let left = names_in(dir); + assert_eq!(left.len(), 1 + named); + assert!(left.contains(&"m".into())); + } + + /// The names of the entries of the directory `dir`. + fn names_in(dir: &Path) -> Vec { + fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect() + } + + /// A temporary name is one nothing has, and it is removed, also once it + /// is gone already, as after a removal that was interrupted after it + /// was done. + #[test] + fn temporary_names() { + let tmp = TempDir::new("sys-temporary-names"); + let dir = &tmp.0; + let directory = File::open(dir).unwrap(); + let names = || -> Vec> { + fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_encoded_bytes()) + .collect() + }; + let made = TemporaryName::create(directory.as_fd(), ".test-", ScratchFile::NAMED_FLAGS, ScratchFile::MODE); + let (_file, name) = made.unwrap(); + assert_eq!(names(), [name.as_c_str().to_bytes()]); + assert!(name.as_c_str().to_bytes().starts_with(b".test-")); + for _ in 0..2 { + name.remove(directory.as_fd()).unwrap(); + assert!(names().is_empty()); + } + } + + /// A scratch file has no name and can get none, only its owner reads + /// and writes it, and it is not inherited across exec. That holds for + /// one made with O_TMPFILE and for one that lost its name right away. + #[test] + fn scratch_files_have_no_name() { + let tmp = TempDir::new("sys-scratch"); + let dir = &tmp.0; + let directory = ScratchFile::open_directory(dir).unwrap(); + let mut own = OwnFiles::default(); + let mut made = vec![ + ScratchFile::create_in(directory.as_fd(), &mut own).unwrap(), + ScratchFile::create_and_unlink(directory.as_fd(), &mut own).unwrap(), + ]; + match ScratchFile::create_unnamed(directory.as_fd(), &mut own) { + Ok(file) => made.push(file), + Err(e) => { + assert!(matches!(e, Errno::OPNOTSUPP | Errno::ISDIR), "{}", e); + eprintln!("skipping O_TMPFILE, which the temporary directory does not have"); + } + } + for file in &made { + assert!(names_in(dir).is_empty()); + let meta = file.file.metadata().unwrap(); + assert_eq!((meta.nlink(), meta.len()), (0, 0)); + assert_eq!(meta.permissions().mode() & 0o7777 & !0o600, 0); + assert!(meta.is_file()); + assert!(rustix::io::fcntl_getfd(&file.file).unwrap().contains(FdFlags::CLOEXEC)); + // Not through procfs either. + let link = format!("/proc/self/fd/{}", file.file.as_raw_fd()); + let linked = rustix::fs::linkat(CWD, link.as_str(), &directory, "linked", AtFlags::SYMLINK_FOLLOW); + assert_eq!(linked, Err(Errno::NOENT)); + } + // A path that is not a directory is not one scratch files go to. + fs::write(dir.join("file"), b"").unwrap(); + let not_directory = ScratchFile::open_directory(&dir.join("file")).unwrap_err(); + assert_eq!(not_directory.raw_os_error(), Some(libc::ENOTDIR)); + let missing = ScratchFile::open_directory(&dir.join("missing")).unwrap_err(); + assert_eq!(missing.raw_os_error(), Some(libc::ENOENT)); + } + + /// A scratch file is one of the files of its builder from when it is + /// made: one made with O_TMPFILE where there is one, and one that lost + /// its name right away. It is there by the inode and the status a walk + /// finds for it, and no other file is. One that is given back is + /// emptied, and one that is dropped keeps what it has. Both stay open + /// and among the files until those are dropped, which closes them. + #[test] + fn scratch_files_are_own_files() { + let tmp = TempDir::new("sys-scratch-own"); + let dir = &tmp.0; + let directory = ScratchFile::open_directory(dir).unwrap(); + let mut own = OwnFiles::default(); + // What a walk finds of the file: its status, with its inode. + let found = |file: &File| Status::of(file.as_fd()).unwrap(); + let first = ScratchFile::create_in(directory.as_fd(), &mut own).unwrap(); + let second = ScratchFile::create_and_unlink(directory.as_fd(), &mut own).unwrap(); + let one = found(&first.file).identity.inode_id(); + let other = found(&second.file).identity.inode_id(); + assert_ne!(one, other); + assert!(own.contains(&found(&first.file)).unwrap() && own.contains(&found(&second.file)).unwrap()); + fs::write(dir.join("file"), b"").unwrap(); + assert!(!own.contains(&found(&File::open(dir.join("file")).unwrap())).unwrap()); + // The files of another builder are not these. + let mut others = OwnFiles::default(); + let third = ScratchFile::create_in(directory.as_fd(), &mut others).unwrap(); + assert!(others.contains(&found(&third.file)).unwrap() && !own.contains(&found(&third.file)).unwrap()); + assert!(!others.contains(&found(&first.file)).unwrap()); + // The files with the inodes `inodes` that this process has open + // among those made in the directory, the smallest first. + let open = |inodes: &[InodeId]| -> Vec { + let mut files = OpenFile::made_in(dir); + files.retain(|file| inodes.contains(&file.inode)); + files.sort_unstable_by_key(|file| file.size); + files + }; + let sizes = |files: &[OpenFile]| -> Vec { files.iter().map(|file| file.size).collect() }; + const DATA: &[u8] = b"data"; + const MORE: &[u8] = b"more data"; + first.write_all_at(DATA, 0).unwrap(); + second.write_all_at(MORE, 0).unwrap(); + assert_eq!(sizes(&open(&[one, other])), [DATA.len() as u64, MORE.len() as u64]); + own.take_back(first); + let files = open(&[one, other]); + assert_eq!(sizes(&files), [0, MORE.len() as u64]); + assert!(files.iter().all(|file| own.contains(&file.status).unwrap())); + own.take_back(second); + let files = open(&[one, other]); + assert_eq!(sizes(&files), [0, 0]); + assert!(files.iter().all(|file| own.contains(&file.status).unwrap())); + // A file that is dropped and not given back keeps what it has. + let kept = ScratchFile::create_in(directory.as_fd(), &mut own).unwrap(); + kept.write_all_at(MORE, 0).unwrap(); + let unused = found(&kept.file).identity.inode_id(); + drop(kept); + let files = open(&[one, other, unused]); + assert_eq!(sizes(&files), [0, 0, MORE.len() as u64]); + assert!(files.iter().all(|file| own.contains(&file.status).unwrap())); + // A file that is still used outlives the files of its builder. + let last = ScratchFile::create_in(directory.as_fd(), &mut own).unwrap(); + last.write_all_at(DATA, 0).unwrap(); + let inode = found(&last.file).identity.inode_id(); + drop(own); + assert_eq!(sizes(&open(&[one, other, unused, inode])), [DATA.len() as u64]); + let mut read = [0; DATA.len()]; + last.read_exact_at(&mut read, 0).unwrap(); + assert_eq!(read, DATA); + drop(last); + assert!(open(&[one, other, unused, inode]).is_empty()); + } + + /// A file is one of the files of a builder by its inode and by its + /// status. A file system can give two files one inode, so a file that + /// has the inode of one of the files and another status is none of + /// them. Here the inode of one file is taken as that of another one, + /// which is kept open for it, as such a file system would have it. + #[test] + fn own_files_are_known_by_their_status() { + let tmp = TempDir::new("sys-own-status"); + let dir = &tmp.0; + fs::write(dir.join("ours"), b"ours").unwrap(); + fs::write(dir.join("theirs"), b"of the tree").unwrap(); + let open = |name: &str| File::open(dir.join(name)).unwrap(); + let found = |name: &str| Status::of(open(name).as_fd()).unwrap(); + let mut own = OwnFiles::default(); + assert!(!own.contains(&found("ours")).unwrap()); + own.keep(found("theirs").identity.inode_id(), Arc::new(open("ours"))); + assert!(!own.contains(&found("theirs")).unwrap()); + assert!(!own.contains(&found("ours")).unwrap()); + // Under its own inode the file is one of them, and the other one, + // which is kept under its own inode as well now, is too. + own.keep(found("ours").identity.inode_id(), Arc::new(open("ours"))); + assert!(own.contains(&found("ours")).unwrap()); + own.keep(found("theirs").identity.inode_id(), Arc::new(open("theirs"))); + assert!(own.contains(&found("theirs")).unwrap()); + // The status is the one the file has now, and not one it had. + let before = found("ours"); + fs::write(dir.join("ours"), b"changed").unwrap(); + assert!(!own.contains(&before).unwrap()); + assert!(own.contains(&found("ours")).unwrap()); + } + + /// A file system that gives two files one inode can give it to two of + /// the files of a builder. Both are kept with that inode then, and both + /// are files of the builder's own: the one that was kept first is not + /// given up for the one that is kept after it. Both stay open until the + /// files are dropped. A file of the tree that has their inode and the + /// status of neither is none of them. Here two files are kept under + /// the inode of the first one, as such a file system would have them. + #[test] + fn own_files_with_one_inode() { + let tmp = TempDir::new("sys-own-one-inode"); + let dir = &tmp.0; + fs::write(dir.join("older"), b"the older one").unwrap(); + fs::write(dir.join("newer"), b"newer").unwrap(); + fs::write(dir.join("theirs"), b"of the tree").unwrap(); + let open = |name: &str| File::open(dir.join(name)).unwrap(); + let found = |name: &str| Status::of(open(name).as_fd()).unwrap(); + // What a walk finds of the file `name` where the file system gives + // it the inode of the older file. + let numbered = |name: &str| Status { + identity: found("older").identity, + ..found(name) + }; + let inode = found("older").identity.inode_id(); + let mut own = OwnFiles::default(); + own.keep(inode, Arc::new(open("older"))); + assert!(own.contains(&found("older")).unwrap()); + assert!(!own.contains(&numbered("newer")).unwrap()); + own.keep(inode, Arc::new(open("newer"))); + assert!(own.contains(&found("older")).unwrap()); + assert!(own.contains(&numbered("newer")).unwrap()); + assert!(!own.contains(&numbered("theirs")).unwrap()); + // The files of the builder alone have the two open, until they are + // dropped. + let mut kept: Vec = OpenFile::made_in(dir).iter().map(|file| file.size).collect(); + kept.sort_unstable(); + assert_eq!(kept, [found("newer").size, found("older").size]); + drop(own); + assert!(OpenFile::made_in(dir).is_empty()); + } + + /// A scratch file that was given back is handed out again, once: it is + /// empty, and it is the file it was, one of the files of its builder + /// with the inode it had. The files of another builder hand out none of + /// them. A file that could not be emptied when it was given back keeps + /// what it has, stays one of the files, and is not handed out again. + #[test] + fn scratch_files_given_back_are_handed_out_again() { + let tmp = TempDir::new("sys-scratch-again"); + let directory = ScratchFile::open_directory(&tmp.0).unwrap(); + let mut own = OwnFiles::default(); + let inode_of = |file: &ScratchFile| InodeId::of(file.file.as_fd()).unwrap(); + let len_of = |file: &ScratchFile| file.file.metadata().unwrap().len(); + /// More files than the test makes. A file that is handed out is + /// not handed out again, and one that was would be without end. + const MOST: usize = 8; + // Every file there is to hand out, which stays handed out. + let handed_out = + |own: &mut OwnFiles| -> Vec { std::iter::from_fn(|| own.hand_out()).take(MOST).collect() }; + assert!(handed_out(&mut own).is_empty()); + let first = ScratchFile::create_in(directory.as_fd(), &mut own).unwrap(); + let second = ScratchFile::create_in(directory.as_fd(), &mut own).unwrap(); + let (one, other) = (inode_of(&first), inode_of(&second)); + const DATA: &[u8] = b"data"; + first.write_all_at(DATA, 0).unwrap(); + second.write_all_at(DATA, 0).unwrap(); + assert!(handed_out(&mut own).is_empty()); + own.take_back(first); + let mut others = OwnFiles::default(); + assert!(handed_out(&mut others).is_empty()); + let again = handed_out(&mut own); + assert_eq!(again.len(), 1); + assert_eq!((inode_of(&again[0]), len_of(&again[0])), (one, 0)); + assert!(own.contains(&Status::of(again[0].file.as_fd()).unwrap()).unwrap()); + // It is used like a new one, and handed out again once it is + // given back again. + again[0].write_all_at(DATA, 0).unwrap(); + let mut read = [0; DATA.len()]; + again[0].read_exact_at(&mut read, 0).unwrap(); + assert_eq!(read, DATA); + again.into_iter().chain([second]).for_each(|file| own.take_back(file)); + let both = handed_out(&mut own); + assert_eq!(both.len(), 2); + assert!(both.iter().all(|file| len_of(file) == 0)); + let handed: Vec = both.iter().map(inode_of).collect(); + assert!(handed.contains(&one) && handed.contains(&other)); + // A file in memory that is sealed can't be made shorter. + let flags = MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING; + let Ok(sealed) = rustix::fs::memfd_create("uapi16-sealed", flags) else { + eprintln!("skipping the file that can't be emptied: there is no memfd_create()"); + return; + }; + let kept = ScratchFile::new(sealed, &mut own).unwrap(); + kept.write_all_at(DATA, 0).unwrap(); + rustix::fs::fcntl_add_seals(&kept.file, SealFlags::SHRINK).unwrap(); + assert_eq!(kept.set_len(0).unwrap_err().raw_os_error(), Some(libc::EPERM)); + let file = Arc::clone(&kept.file); + own.take_back(kept); + assert!(handed_out(&mut own).is_empty()); + assert_eq!(file.metadata().unwrap().len(), DATA.len() as u64); + assert!(own.contains(&Status::of(file.as_fd()).unwrap()).unwrap()); + } + + /// A file system that has no O_TMPFILE gets a file that loses its name + /// right away. The message queue file system is one, and lets anybody + /// make a file in it. + #[test] + fn scratch_files_without_o_tmpfile() { + let queues = Path::new("/dev/mqueue"); + let Ok(directory) = ScratchFile::open_directory(queues) else { + eprintln!("skipping: there is no /dev/mqueue"); + return; + }; + let mut own = OwnFiles::default(); + match ScratchFile::create_unnamed(directory.as_fd(), &mut own) { + Err(Errno::OPNOTSUPP) => {} + other => { + eprintln!("skipping: O_TMPFILE in /dev/mqueue gives {:?}", other.map(|_| ())); + return; + } + } + let before = names_in(queues).len(); + let file = match ScratchFile::create_in(directory.as_fd(), &mut own) { + Ok(file) => file, + Err(e) => { + eprintln!("skipping: no file can be made in /dev/mqueue: {}", e); + return; + } + }; + assert_eq!(file.file.metadata().unwrap().nlink(), 0); + // Other processes make and remove queues, but ours is gone. + let prefix = ScratchFile::NAME_PREFIX.as_bytes(); + let left = names_in(queues) + .iter() + .filter(|name| name.as_encoded_bytes().starts_with(prefix)) + .count(); + assert_eq!(left, 0, "{} entries before", before); + } + + /// A scratch file is read and written at any offset. What was never + /// written reads as zeroes up to the end of the file, and a read past + /// the end fails instead of coming back short. + #[test] + fn scratch_files_are_read_and_written_anywhere() { + let tmp = TempDir::new("sys-scratch-io"); + let directory = ScratchFile::open_directory(&tmp.0).unwrap(); + let file = ScratchFile::create_in(directory.as_fd(), &mut OwnFiles::default()).unwrap(); + let data: Vec = (0..3 * DATA_BUFFER_SIZE + 7).map(|i| (i % 253) as u8).collect(); + let far = 5 * 1024 * 1024 * 1024; + file.write_all_at(&data, far).unwrap(); + file.write_all_at(b"start", 0).unwrap(); + file.write_all_at(b"", 1).unwrap(); + let mut read = vec![0xff; data.len()]; + file.read_exact_at(&mut read, far).unwrap(); + assert_eq!(read, data); + let mut start = [0xff; 8]; + file.read_exact_at(&mut start, 0).unwrap(); + assert_eq!(&start, b"start\0\0\0"); + file.read_exact_at(&mut [], far + data.len() as u64 + 1).unwrap(); + // The last byte, and one more. + let end = far + data.len() as u64; + file.read_exact_at(&mut start[..1], end - 1).unwrap(); + let past = file.read_exact_at(&mut start[..2], end - 1).unwrap_err(); + assert_eq!(past.kind(), io::ErrorKind::UnexpectedEof); + // A longer file has zeroes where nothing was written, and a + // shorter one ends there. + file.set_len(end + 4096).unwrap(); + let mut tail = [0xff; 4096]; + file.read_exact_at(&mut tail, end).unwrap(); + assert_eq!(tail, [0; 4096]); + file.set_len(4).unwrap(); + let short = file.read_exact_at(&mut start[..5], 0).unwrap_err(); + assert_eq!(short.kind(), io::ErrorKind::UnexpectedEof); + // Only what is written takes room. + assert!(room_of(&file) < far); + } + + /// How many bytes of room the scratch file `file` takes. + fn room_of(file: &ScratchFile) -> u64 { + file.file.metadata().unwrap().blocks() * ST_BLOCKS_UNIT + } + + /// `blocks` blocks of `block` bytes of data without a zero. + fn blocks_of_data(blocks: u64, block: u64) -> Vec { + (0..blocks * block).map(|at| (at % 251) as u8 + 1).collect() + } + + /// A hole punched into a scratch file reads as zeroes. The file stays + /// as long as it is and keeps what is around the hole, and the room of + /// the blocks that are all in the hole is given back. Where the + /// temporary directory cannot punch holes this is skipped. + #[test] + fn holes_in_scratch_files() { + let tmp = TempDir::new("sys-scratch-holes"); + let directory = ScratchFile::open_directory(&tmp.0).unwrap(); + let file = ScratchFile::create_in(directory.as_fd(), &mut OwnFiles::default()).unwrap(); + let block = file.block_size().unwrap(); + assert!(block > 0); + let data = blocks_of_data(8, block); + file.write_all_at(&data, 0).unwrap(); + // What was written has its room now, and not only the promise of + // it. + file.file.sync_all().unwrap(); + let before = room_of(&file); + // Two blocks, and a part of the block on either side of them. + let (start, end) = (2 * block - 100, 4 * block + 100); + if let Err(e) = file.punch_hole(start, end - start) { + assert_eq!(e.raw_os_error(), Some(libc::EOPNOTSUPP), "{}", e); + eprintln!("skipping: the temporary directory cannot punch holes"); + return; + } + assert_eq!(file.file.metadata().unwrap().len(), data.len() as u64); + let mut read = vec![0xff; data.len()]; + file.read_exact_at(&mut read, 0).unwrap(); + let (start, end) = (start as usize, end as usize); + assert!(read[..start] == data[..start] && read[end..] == data[end..]); + assert!(read[start..end].iter().all(|&byte| byte == 0)); + assert!(room_of(&file) + 2 * block <= before, "{} -> {}", before, room_of(&file)); + // A hole in a hole, and one that is no block long. + file.punch_hole(2 * block, block).unwrap(); + file.punch_hole(7 * block + 1, 1).unwrap(); + file.read_exact_at(&mut read, 0).unwrap(); + assert_eq!( + read[7 * block as usize..][..3], + [data[7 * block as usize], 0, data[7 * block as usize + 2]] + ); + // No hole is nothing to ask for. + let empty = file.punch_hole(block, 0).unwrap_err(); + assert_eq!(empty.raw_os_error(), Some(libc::EINVAL)); + } + + /// The variable that names a directory of a file system that cannot + /// punch holes, in which the test binary runs + /// [`scratch_files_without_holes`] again. + const NO_HOLES_DIR: &str = "UAPI16_TEST_NO_HOLES_DIR"; + + /// A file system that cannot punch holes fails with EOPNOTSUPP, and the + /// file keeps its data and its room. The test binary runs this test + /// again with its directory on a ramfs, which is one, and it is skipped + /// where that cannot be mounted. + #[test] + fn scratch_files_without_holes() { + let Some(dir) = std::env::var_os(NO_HOLES_DIR) else { + let tmp = TempDir::new("sys-scratch-no-holes"); + tmp.rerun_on("ramfs", None, "sys::tests::scratch_files_without_holes", NO_HOLES_DIR); + return; + }; + let directory = ScratchFile::open_directory(Path::new(&dir)).unwrap(); + let file = ScratchFile::create_in(directory.as_fd(), &mut OwnFiles::default()).unwrap(); + let block = file.block_size().unwrap(); + assert!(block > 0); + let data = blocks_of_data(4, block); + file.write_all_at(&data, 0).unwrap(); + let before = room_of(&file); + let refused = file.punch_hole(block, 2 * block).unwrap_err(); + assert_eq!(refused.raw_os_error(), Some(libc::EOPNOTSUPP)); + let mut read = vec![0; data.len()]; + file.read_exact_at(&mut read, 0).unwrap(); + assert!(read == data); + assert_eq!(room_of(&file), before); + } + + /// The data of a file of procfs goes on after its size, which is 0, + /// and the status of the file shows no change. + #[test] + fn data_after_the_size() { + if rustix::fs::statfs("/proc").unwrap().f_type != rustix::fs::PROC_SUPER_MAGIC { + return; + } + let process = open_dir(Path::new("/proc/self")); + let entry = Entry::open_at(process.as_fd(), c"status").unwrap(); + assert_eq!( + (entry.status().file_type, entry.status().size), + (FileType::RegularFile, 0) + ); + let mut buffer = vec![0; DATA_BUFFER_SIZE]; + let read = hash(&entry, &mut buffer); + assert!(matches!(read, Err(Failure::WrongSize)), "{:?}", read); + } + + /// A file that cannot be opened for reading fails with the error of the + /// open. That takes a process that the permissions of a file hold for. + #[test] + fn unreadable() { + let tmp = TempDir::new("sys-unreadable"); + let dir = &tmp.0; + let path = dir.join("file"); + fs::write(&path, b"secret").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o000)).unwrap(); + if File::open(&path).is_ok() { + return; + } + let tree = open_dir(dir); + let entry = Entry::open_at(tree.as_fd(), c"file").unwrap(); + let mut buffer = vec![0; DATA_BUFFER_SIZE]; + assert_eq!(errno(hash(&entry, &mut buffer)), libc::EACCES); + } + + /// A regular file with more data than is hashed fails its hash with + /// EFBIG, by its size alone, before it is opened and before anything + /// is read of it. One with exactly as much is opened, and its data is + /// read from the beginning. Neither is read through here: that takes a + /// quarter of an hour. + #[test] + fn data_too_large_to_hash() { + let tmp = TempDir::new("sys-too-large"); + let dir = &tmp.0; + let file = File::create(dir.join("file")).unwrap(); + if let Err(e) = file.set_len(DataHash::MAX_SIZE + 1) { + eprintln!("skipping: the temporary directory takes no file of that size: {}", e); + return; + } + let tree = open_dir(dir); + let entry = Entry::open_at(tree.as_fd(), c"file").unwrap(); + assert_eq!(entry.status().size, DataHash::MAX_SIZE + 1); + assert_eq!(errno(DataHash::admits(entry.status())), libc::EFBIG); + assert_eq!(errno(DataHash::start(&entry)), libc::EFBIG); + let opened = entry.reopen(None).unwrap(); + assert_eq!(errno(DataHash::of(&entry, opened)), libc::EFBIG); + // A file that may not be opened fails for its size all the same: + // nothing opens it. + fs::set_permissions(dir.join("file"), fs::Permissions::from_mode(0o000)).unwrap(); + assert_eq!(errno(DataHash::start(&entry)), libc::EFBIG); + fs::set_permissions(dir.join("file"), fs::Permissions::from_mode(0o644)).unwrap(); + file.set_len(DataHash::MAX_SIZE).unwrap(); + let entry = Entry::open_at(tree.as_fd(), c"file").unwrap(); + DataHash::admits(entry.status()).unwrap(); + let mut buffer = vec![0; DATA_BUFFER_SIZE]; + let begun = DataHash::start(&entry).unwrap().read(&mut buffer, 1).unwrap(); + assert!(matches!(begun, ControlFlow::Continue(hash) if hash.offset == 1)); + } + + /// The variable that names an automount point for + /// [`automount_points_are_told_from_their_handles`]. + const AUTOMOUNT: &str = "UAPI16_TEST_AUTOMOUNT"; + + /// An entry says whether it is an automount point that nothing is + /// mounted on, and taking its handle mounts nothing, with open_tree() + /// and with openat(), and neither does what is read through the handle. + /// It is not opened: by its name that would mount what it stands for. + /// Only root can make one, so the test takes one that is there: + /// `UAPI16_TEST_AUTOMOUNT` names a directory that is one, such as the + /// mount point of an automount unit of systemd, or `tracing` in a + /// debugfs that was just mounted. Without the variable the test is + /// skipped. + #[test] + fn automount_points_are_told_from_their_handles() { + let Some(point) = std::env::var_os(AUTOMOUNT) else { + eprintln!("skipping: {} names no automount point", AUTOMOUNT); + return; + }; + let point = Path::new(&point); + let parent = open_dir(point.parent().unwrap()); + let name = [point.file_name().unwrap().to_str().unwrap(), "\0"].concat(); + let name = CStr::from_bytes_with_nul(name.as_bytes()).unwrap(); + // Once something is mounted on it, a handle is of the root of that, + // which is no automount point. So each handle after the first one + // says that the ones before it mounted nothing. + with_both_handles(|| { + for _ in 0..2 { + let entry = Entry::open_at(parent.as_fd(), name).unwrap(); + assert!(entry.is_automount(), "{}", point.display()); + assert_eq!(entry.status().file_type, FileType::Directory); + Status::of(entry.handle()).unwrap(); + FdLink::new(entry.handle()).check().unwrap(); + // Whether it has extended attributes is its file system's + // to say. Asking mounts nothing. + let _ = UserXattrs::new().read_unopened(&entry); + let place = Place { + dir: parent.as_fd(), + name, + }; + for place in [Some(place), None] { + assert_eq!(errno(entry.reopen(place)), libc::EINVAL); + } + } + }); + // A directory that is none says so. + let tmp = TempDir::new("sys-no-automount"); + fs::create_dir(tmp.0.join("dir")).unwrap(); + let tree = open_dir(&tmp.0); + assert!(!Entry::open_at(tree.as_fd(), c"dir").unwrap().is_automount()); + } + + /// What is kept of a file of a tree, and of the hash of its data, can + /// go to another thread and be shared between threads. + #[test] + fn send_and_sync() { + fn send_sync() {} + send_sync::(); + send_sync::>(); + send_sync::(); + send_sync::(); + send_sync::(); + send_sync::(); + send_sync::(); + send_sync::(); + send_sync::(); + send_sync::(); + } +} diff --git a/src/uapi16/tests/capi.c b/src/uapi16/tests/capi.c new file mode 100644 index 0000000..9d12b29 --- /dev/null +++ b/src/uapi16/tests/capi.c @@ -0,0 +1,11044 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +/* + * Tests the C API of uapi16 through uapi16.h, against the shared or the + * static library it is linked with. tests/capi.sh builds and runs it. + * + * It makes its trees in a directory of its own below TMPDIR, or below /tmp + * where that is not set. + * + * A test declares its descriptors before the objects it makes from them, + * so that a descriptor is closed after every object that was given it is + * freed, and does not read from or write to one while such an object is + * there. + */ + +#define _GNU_SOURCE +/* Inode numbers and sizes of 64 bits, also where long has 32. */ +#define _FILE_OFFSET_BITS 64 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define _cleanup_(f) __attribute__((cleanup(f))) +#define ELEMENTSOF(x) (sizeof(x) / sizeof((x)[0])) + +/* What a manifest starts every record with, and the records a test writes + * itself: a root that declares the code point order and one that declares + * none, a file object that has a name and nothing else, a signature object + * that has a mechanism and nothing else, and the trailer. */ +#define RECORD_SEPARATOR '\x1e' +#define RS "\x1e" +#define ROOT RS "{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n" +#define ROOT_WITHOUT_ORDER RS "{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n" +#define FILE_OBJECT(name) RS "{\"name\":\"" name "\"}\n" +#define SIGNATURE_OBJECT(mechanism) \ + RS "{\"mechanism\":\"" mechanism "\",\"mediaType\":\"application/vnd.uapi.16.signature\"}\n" +#define TRAILER RS "{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n" + +/* The longest name of a file in a directory, and of a file object. */ +#define COMPONENT_MAX 255 +#define NAME_OF_OBJECT_MAX 4095 + +/* The largest record of a manifest, and the size of a value of an extended + * attribute that is small enough for Btrfs and XFS. */ +#define RECORD_MAX (4 * 1024 * 1024) +#define XATTR_VALUE_SIZE 8192 + +/* The most data a regular file is hashed with: 1 TiB. */ +#define HASHED_MAX (UINT64_C(1) << 40) + +/* A directory on a tmpfs, which takes that many extended attributes since + * Linux 6.6, and a directory of a test in it. */ +#define MEMORY_DIR "/dev/shm" +#define MEMORY_TEMPLATE MEMORY_DIR "/uapi16-capi-XXXXXX" + +/* How many descriptors the process may have open in the test that leaves + * it none: few enough to open them all. */ +#define DESCRIPTORS_MAX 64 + +/* What a child exits with that could not do what it is for. */ +#define EXIT_SKIPPED 77 + +/* How much a pipe has room for at least: a page. A test that fills a pipe + * before anything reads from it puts in no more. */ +#define PIPE_ROOM 4096 + +/* The default features, which a manifest that lists none records: to put + * into a set. */ +#define DEFAULT_FEATURES \ + UAPI16_FEATURE_MODE, UAPI16_FEATURE_UID, UAPI16_FEATURE_GID, UAPI16_FEATURE_SIZE, \ + UAPI16_FEATURE_SHA256, UAPI16_FEATURE_SYMLINK, UAPI16_FEATURE_DEVICE, \ + UAPI16_FEATURE_HARDLINK + +/* The first and the last feature of a tree of files, the first and the last + * feature of partitions, and the first number that is no feature. */ +#define FIRST_FEATURE_OF_TREES UAPI16_FEATURE_MODE +#define LAST_FEATURE_OF_TREES UAPI16_FEATURE_FAT_SERIAL +#define FIRST_FEATURE_OF_PARTITIONS UAPI16_FEATURE_GPT_LABEL +#define LAST_FEATURE_OF_PARTITIONS UAPI16_FEATURE_GPT_FLAG_GROW_FILE_SYSTEM +#define NO_FEATURE ((uapi16_feature_t) (LAST_FEATURE_OF_PARTITIONS + 1)) + +/* More numbers than there are features: a test asks an object for each + * of them. */ +#define FEATURES_MAX 64 + +/* The Linux inode flags a manifest has, with the bits FS_IOC_GETFLAGS gives + * them: FS_APPEND_FL, FS_IMMUTABLE_FL, FS_NOATIME_FL, FS_NOCOW_FL and + * FS_NODUMP_FL of . FS_SYNC_FL is one a manifest does not have. */ +#define APPEND_FL UINT32_C(0x00000020) +#define IMMUTABLE_FL UINT32_C(0x00000010) +#define NOATIME_FL UINT32_C(0x00000080) +#define NOCOW_FL UINT32_C(0x00800000) +#define NODUMP_FL UINT32_C(0x00000040) +#define SYNC_FL UINT32_C(0x00000008) +#define INODE_FLAGS (APPEND_FL | IMMUTABLE_FL | NOATIME_FL | NOCOW_FL | NODUMP_FL) + +/* The DOS attributes a manifest has a field for, with the bits a directory + * entry of FAT has for them: hidden, system and archive. Read-only and + * directory are two it has no such field for. */ +#define DOS_HIDDEN UINT32_C(0x02) +#define DOS_SYSTEM UINT32_C(0x04) +#define DOS_ARCHIVE UINT32_C(0x20) +#define DOS_READ_ONLY UINT32_C(0x01) +#define DOS_DIRECTORY UINT32_C(0x10) +#define DOS_ATTRIBUTES (DOS_HIDDEN | DOS_SYSTEM | DOS_ARCHIVE) + +/* The SHA-256 hashes of no data, of "abc", of the 56 bytes of FIPS 180-2 + * that take two blocks, of a million times "a", and of the data of the + * files of the tests. */ +#define SHA256_OF_NOTHING "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" +#define SHA256_OF_ABC "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" +#define TWO_BLOCKS "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" +#define SHA256_OF_TWO_BLOCKS "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" +#define SHA256_OF_A_MILLION_A "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0" +#define SHA256_OF_HELLO "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" +#define SHA256_OF_TWICE "dc8ffdbf2736dbdf39508017ac594e0d069f3eee9b0f29ece256aa7d831f9ef6" + +#define check(condition) \ + do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s is false\n", __FILE__, __LINE__, #condition); \ + abort(); \ + } \ + } while (0) + +#define check_eq(got, want) \ + do { \ + long long got_ = (long long) (got), want_ = (long long) (want); \ + if (got_ != want_) { \ + fprintf(stderr, "%s:%d: %s is %lld, and %s is %lld\n", __FILE__, __LINE__, \ + #got, got_, #want, want_); \ + abort(); \ + } \ + } while (0) + +#define check_str(got, want) \ + do { \ + const char *got_ = (got), *want_ = (want); \ + if (!got_ || strcmp(got_, want_) != 0) { \ + fprintf(stderr, "%s:%d: %s is %s%s%s, and not \"%s\"\n", __FILE__, \ + __LINE__, #got, got_ ? "\"" : "", got_ ? got_ : "NULL", \ + got_ ? "\"" : "", want_); \ + abort(); \ + } \ + } while (0) + +static void closep(int *fd) { + if (*fd >= 0) + close(*fd); +} + +static void freep(void *p) { + free(*(void **) p); +} + +/* The directory the trees of the tests are in, and its path. */ +static int tmp_fd = -1; +static char tmp_path[PATH_MAX]; + +/* What takes a manifest that no test looks at: /dev/null. It is open for + * as long as the tests run, and so for longer than any writer that is given + * it. */ +static int null_fd = -1; + +static int make_dir(int dir_fd, const char *name) { + int fd; + + check_eq(mkdirat(dir_fd, name, 0755), 0); + fd = openat(dir_fd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + check(fd >= 0); + return fd; +} + +static void make_file(int dir_fd, const char *name, const char *data) { + _cleanup_(closep) int fd = openat(dir_fd, name, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644); + + check(fd >= 0); + check_eq(write(fd, data, strlen(data)), (ssize_t) strlen(data)); +} + +/* Removes the directory `name` in `dir_fd` with everything below it. */ +static void remove_tree(int dir_fd, const char *name) { + int fd = openat(dir_fd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + struct dirent *entry; + DIR *dir; + + check(fd >= 0); + dir = fdopendir(fd); + check(dir); + while ((entry = readdir(dir))) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) + continue; + if (unlinkat(fd, entry->d_name, 0) < 0) { + check(errno == EISDIR || errno == EPERM); + remove_tree(fd, entry->d_name); + } + } + closedir(dir); + check_eq(unlinkat(dir_fd, name, AT_REMOVEDIR), 0); +} + +/* How many descriptors the process has open. */ +static size_t open_descriptors(void) { + DIR *dir = opendir("/proc/self/fd"); + size_t count = 0; + + check(dir); + while (readdir(dir)) + count++; + closedir(dir); + return count; +} + +/* How many entries the directory `name` in `dir_fd` has. */ +static size_t count_entries(int dir_fd, const char *name) { + int fd = openat(dir_fd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + struct dirent *entry; + size_t count = 0; + DIR *dir; + + check(fd >= 0); + dir = fdopendir(fd); + check(dir); + while ((entry = readdir(dir))) + if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) + count++; + closedir(dir); + return count; +} + +/* How many bytes the file `fd` holds. */ +static size_t size_of(int fd) { + struct stat st; + + check_eq(fstat(fd, &st), 0); + return (size_t) st.st_size; +} + +/* Everything the file `fd` holds, and how much that is. */ +static char *read_all(int fd, size_t *ret_size) { + size_t size = size_of(fd), done = 0; + char *data = malloc(size + 1); + + check(data); + while (done < size) { + ssize_t n = pread(fd, data + done, size - done, (off_t) done); + + check(n > 0); + done += (size_t) n; + } + data[done] = 0; + *ret_size = done; + return data; +} + +static char *read_file(int dir_fd, const char *name, size_t *ret_size) { + _cleanup_(closep) int fd = openat(dir_fd, name, O_RDONLY | O_CLOEXEC); + + check(fd >= 0); + return read_all(fd, ret_size); +} + +/* A file without a name, to write a manifest to. */ +static int scratch_file(void) { + int fd = memfd_create("uapi16-capi", MFD_CLOEXEC); + + check(fd >= 0); + return fd; +} + +/* Makes the file `fd` empty, for the next manifest. */ +static void empty(int fd) { + check_eq(ftruncate(fd, 0), 0); + check_eq(lseek(fd, 0, SEEK_SET), 0); +} + +/* A file without a name that holds `text`, to read a manifest from. */ +static int manifest_file(const char *text) { + int fd = scratch_file(); + + check_eq(write(fd, text, strlen(text)), (ssize_t) strlen(text)); + check_eq(lseek(fd, 0, SEEK_SET), 0); + return fd; +} + +/* The end to read from of a pipe that holds `text` and nothing after it. */ +static int manifest_pipe(const char *text) { + int fds[2]; + + check(strlen(text) <= PIPE_ROOM); + check_eq(pipe2(fds, O_CLOEXEC), 0); + check_eq(write(fds[1], text, strlen(text)), (ssize_t) strlen(text)); + check_eq(close(fds[1]), 0); + return fds[0]; +} + +/* A page that can be neither read nor written. A call that is given it with + * a size of 0 does not look at it. */ +static const void *unreadable(void) { + static void *page; + + if (!page) { + page = mmap(NULL, (size_t) sysconf(_SC_PAGESIZE), PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, + -1, 0); + check(page != MAP_FAILED); + } + return page; +} + +/* The manifest of the tree `top_fd` as uapi16_manifest_generate() writes it. */ +static char *generate(const uapi16_manifest_options *o, int top_fd, uapi16_add_flags_t flags, size_t *ret_size) { + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(closep) int fd = scratch_file(); + + check_eq(uapi16_manifest_generate(o, fd, top_fd, flags, &report, &e), 0); + check(report && !e); + return read_all(fd, ret_size); +} + +/* Checks that the `size` bytes at `data` are the `expected_size` at + * `expected`. */ +static void check_same(const void *data, size_t size, const void *expected, size_t expected_size) { + check_eq(size, expected_size); + if (size > 0) + check_eq(memcmp(data, expected, expected_size), 0); +} + +/* Checks that `data` is a whole manifest. */ +static void check_manifest(const char *data, size_t size) { + check(size > strlen(TRAILER)); + check_eq(data[0], RECORD_SEPARATOR); + check(strstr(data, "\"mediaType\":\"application/vnd.uapi.16.manifest\"")); + check_eq(memcmp(data + size - strlen(TRAILER), TRAILER, strlen(TRAILER)), 0); +} + +/* The hash that the hex digits `hex` spell. */ +static void unhex(const char *hex, uapi16_sha256_digest_t *ret) { + check_eq(strlen(hex), 2 * UAPI16_SHA256_SIZE); + for (size_t i = 0; i < UAPI16_SHA256_SIZE; i++) { + unsigned byte; + + check_eq(sscanf(hex + 2 * i, "%2x", &byte), 1); + ret->bytes[i] = (uint8_t) byte; + } +} + +/* Checks that `hash` is what the hex digits `hex` spell. */ +static void check_hash(const uapi16_sha256_digest_t *hash, const char *hex) { + uapi16_sha256_digest_t expected; + + unhex(hex, &expected); + check_eq(memcmp(hash, &expected, sizeof(expected)), 0); +} + +/* The features that follow as a set of a test: what it expects of an + * object, or passes to one. UAPI16_FEATURE_NONE among them is no feature. */ +#define FEATURES(...) ((uapi16_features_t) UAPI16_FEATURES_SET(__VA_ARGS__)) + +/* No features as a set of a test. */ +static uapi16_features_t features_none(void) { + return (uapi16_features_t) UAPI16_FEATURES_EMPTY; +} + +/* The set `features` with the features of `more` as well. */ +static uapi16_features_t features_with(uapi16_features_t features, uapi16_features_t more) { + uapi16_features_union(&features, &more); + return features; +} + +/* The set `features` with the features that follow as well. */ +#define WITH(features, ...) features_with(features, FEATURES(__VA_ARGS__)) + +/* The set `features` without the feature `feature`. */ +static uapi16_features_t features_without(uapi16_features_t features, uapi16_feature_t feature) { + check_eq(uapi16_features_remove(&features, feature), 0); + return features; +} + +/* The features from `first` to `last`. */ +static uapi16_features_t features_from(uapi16_feature_t first, uapi16_feature_t last) { + uapi16_features_t features = UAPI16_FEATURES_EMPTY; + + check(first != UAPI16_FEATURE_NONE && first <= last); + for (uapi16_feature_t feature = first; feature <= last; feature++) + check_eq(uapi16_features_add(&features, feature), 0); + return features; +} + +/* The `n` features at `list` as a set of a test. A place that holds + * UAPI16_FEATURE_NONE is no feature of it. */ +static uapi16_features_t features_listed(const uapi16_feature_t *list, size_t n) { + uapi16_features_t features = UAPI16_FEATURES_EMPTY; + + for (size_t i = 0; i < n; i++) + if (list[i] != UAPI16_FEATURE_NONE) + check_eq(uapi16_features_add(&features, list[i]), 0); + return features; +} + +/* Every feature of a tree of files, every feature of partitions, and both. */ +#define FEATURES_OF_TREES features_from(FIRST_FEATURE_OF_TREES, LAST_FEATURE_OF_TREES) +#define FEATURES_OF_PARTITIONS features_from(FIRST_FEATURE_OF_PARTITIONS, LAST_FEATURE_OF_PARTITIONS) +#define EVERY_FEATURE features_from(FIRST_FEATURE_OF_TREES, LAST_FEATURE_OF_PARTITIONS) + +/* Checks that the sets `a` and `b` have the same features. */ +static void check_same_features(uapi16_features_t a, uapi16_features_t b) { + check(uapi16_features_equal(&a, &b)); +} + +/* Checks that the reader `r` records the features of `expected` and no + * other: asked one by one, and as the set of them. No reader has none to + * store. */ +static void check_recorded(const uapi16_reader *r, uapi16_features_t expected) { + uapi16_features_t got = FEATURES(NO_FEATURE); + + for (uapi16_feature_t feature = UAPI16_FEATURE_NONE; feature < FEATURES_MAX; feature++) + check_eq(uapi16_reader_has_feature(r, feature), uapi16_features_has(&expected, feature)); + if (!r) { + check_eq(uapi16_reader_features(r, &got), -EINVAL); + return; + } + check_eq(uapi16_reader_features(r, &got), 0); + check_same_features(got, expected); + check_eq(got.size, sizeof(got)); +} + +/* The same for the features whose fields the object `o` has. */ +static void check_stated(const uapi16_file_object *o, uapi16_features_t expected) { + uapi16_features_t got = FEATURES(NO_FEATURE); + + for (uapi16_feature_t feature = UAPI16_FEATURE_NONE; feature < FEATURES_MAX; feature++) + check_eq(uapi16_file_object_has_stated_feature(o, feature), uapi16_features_has(&expected, feature)); + if (!o) { + check_eq(uapi16_file_object_stated_features(o, &got), -EINVAL); + return; + } + check_eq(uapi16_file_object_stated_features(o, &got), 0); + check_same_features(got, expected); + check_eq(got.size, sizeof(got)); +} + +/* Checks that the objects `a` and `b` have the fields of the same + * features. */ +static void check_same_stated(const uapi16_file_object *a, const uapi16_file_object *b) { + uapi16_features_t of_a = UAPI16_FEATURES_EMPTY, of_b = UAPI16_FEATURES_EMPTY; + + check_eq(uapi16_file_object_stated_features(a, &of_a), 0); + check_eq(uapi16_file_object_stated_features(b, &of_b), 0); + check_same_features(of_a, of_b); +} + +/* uapi16_manifest_options_set_features() for a set of a test. */ +static int set_features(uapi16_manifest_options *o, uapi16_features_t features) { + return uapi16_manifest_options_set_features(o, &features); +} + +/* uapi16_file_object_retain_features() for a set of a test. */ +static int retain_features(uapi16_file_object *o, uapi16_features_t features) { + return uapi16_file_object_retain_features(o, &features); +} + +/* + * Checks that the call that returned `r` failed with the error `e` of the + * kind `kind` and the errno `error`, about `path`, and that the error says + * nothing a caller did not ask to be checked. + */ +#define CHECK_HARDLINK_PATH (1 << 0) +#define CHECK_FEATURE (1 << 1) +#define CHECK_NAME (1 << 2) +#define CHECK_FIELD (1 << 3) +#define CHECK_RECORD (1 << 4) +#define CHECK_PROBLEM (1 << 5) +static void check_error(int r, const uapi16_error *e, uapi16_error_kind_t kind, int error, const char *path, + unsigned other) { + size_t size = 1; + + check_eq(r, -error); + check(e); + check_eq(uapi16_error_kind(e), kind); + check_eq(uapi16_error_errno(e), error); + if (path) + check_str(uapi16_error_path(e), path); + else + check(!uapi16_error_path(e)); + if (!(other & CHECK_HARDLINK_PATH)) + check(!uapi16_error_hardlink_path(e)); + if (!(other & CHECK_FEATURE)) + check_eq(uapi16_error_feature(e), UAPI16_FEATURE_NONE); + if (!(other & CHECK_NAME)) { + check_eq(uapi16_error_name_problem(e), 0); + check(!uapi16_error_raw_name(e, &size)); + check_eq(size, 0); + } + if (!(other & CHECK_FIELD)) + check(!uapi16_error_field(e)); + if (!(other & CHECK_RECORD)) { + uint64_t record = 77; + + check_eq(uapi16_error_record(e, &record), -ENODATA); + check_eq(record, 77); + } + if (!(other & CHECK_PROBLEM)) + check(!uapi16_error_problem(e)); +} + +/* Checks that the error `e` is about the record `record` of a manifest, + * of which the root is record 0. */ +static void check_record(const uapi16_error *e, uint64_t record) { + uint64_t got = UINT64_MAX; + + check_eq(uapi16_error_record(e, &got), 0); + check_eq(got, record); +} + +/* What a call with something missing or unknown fails with. */ +static void check_misuse(int r, uapi16_error **e, int error) { + check_error(r, *e, UAPI16_ERROR_INVALID_ARGUMENT, error, NULL, 0); + *e = uapi16_error_free(*e); + check(!*e); +} + +/* What a call fails with on an object that takes nothing more. */ +static void check_ended(int r, uapi16_error **e) { + check_error(r, *e, UAPI16_ERROR_ENDED, ESTALE, NULL, 0); + *e = uapi16_error_free(*e); + check(!*e); +} + +/* + * What a call fails with that a manifest or a file object is refused by: an + * error of the kind UAPI16_ERROR_MANIFEST that names the rule `problem`. It + * is about the file `path`, or about no file, and about the field `field`, + * or about no field. + */ +static void check_refused(int r, uapi16_error **e, const char *problem, const char *path, + const char *field) { + check_error(r, *e, UAPI16_ERROR_MANIFEST, EBADMSG, path, CHECK_FIELD | CHECK_RECORD | CHECK_PROBLEM); + check_str(uapi16_error_problem(*e), problem); + if (field) + check_str(uapi16_error_field(*e), field); + else + check(!uapi16_error_field(*e)); + *e = uapi16_error_free(*e); + check(!*e); +} + +/* + * A tree with a directory, files, a hard link, a symbolic link and a FIFO: + * three regular files of 5 bytes each, two directories with the root, and + * two other files. + */ +static int make_tree(const char *name) { + int fd = make_dir(tmp_fd, name); + _cleanup_(closep) int a = make_dir(fd, "a"); + + make_file(a, "file", "hello"); + make_file(fd, "linked", "twice"); + check_eq(linkat(fd, "linked", a, "linked-too", 0), 0); + check_eq(symlinkat("a", fd, "link"), 0); + check_eq(mkfifoat(fd, "fifo", 0600), 0); + return fd; +} + +/* A file object for `name` that says nothing else. */ +static uapi16_file_object *make_object(const char *name) { + uapi16_file_object *o = NULL; + + check_eq(uapi16_file_object_new(name, &o, NULL), 0); + check(o); + return o; +} + +/* A file object for the regular file `name` with the data "hello": its size + * and its hash. */ +static uapi16_file_object *make_hello(const char *name) { + uapi16_file_object *o = make_object(name); + uapi16_sha256_digest_t hash; + + unhex(SHA256_OF_HELLO, &hash); + check_eq(uapi16_file_object_set_size(o, strlen("hello")), 0); + check_eq(uapi16_file_object_set_sha256(o, &hash), 0); + return o; +} + +/* A writer for the options `o`, which writes nowhere a test looks. */ +static uapi16_manifest_writer *open_writer(const uapi16_manifest_options *o) { + uapi16_manifest_writer *w = NULL; + + check_eq(uapi16_manifest_writer_open(o, null_fd, &w, NULL), 0); + check(w); + return w; +} + +/* Finishes the writer `w` and checks how many regular files, directories + * and other files it lists. */ +static void check_listed(uapi16_manifest_writer *w, uint64_t files, uint64_t directories, uint64_t others) { + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + + check_eq(uapi16_manifest_writer_finish(w, &report, NULL), 0); + check_eq(uapi16_manifest_report_files(report), files); + check_eq(uapi16_manifest_report_directories(report), directories); + check_eq(uapi16_manifest_report_others(report), others); +} + +/* A reader of the manifest the file `fd` holds, from its start. Whoever + * calls this leaves `fd` alone until the reader is freed. */ +static uapi16_reader *open_reader(int fd) { + uapi16_reader *reader = NULL; + + check_eq(lseek(fd, 0, SEEK_SET), 0); + check_eq(uapi16_reader_open(fd, &reader, NULL), 0); + check(reader); + return reader; +} + +/* The next file object of `reader`, which has the name `name`. */ +static uapi16_file_object *next_object(uapi16_reader *reader, const char *name) { + uapi16_file_object *o = NULL; + + check_eq(uapi16_reader_next(reader, &o, NULL), UAPI16_READ_FILE); + check(o); + check_str(uapi16_file_object_name(o), name); + return o; +} + +/* Checks that the manifest of `reader` ends here, without signature + * objects. */ +static void check_ends(uapi16_reader *reader) { + uapi16_file_object *o = NULL; + + check_eq(uapi16_reader_next(reader, &o, NULL), UAPI16_READ_END); +} + +/* A writer of records for the options `o` that writes to `fd`, with a root + * that says nothing. Whoever calls this leaves `fd` alone until the writer + * is freed, but for looking at its size. */ +static uapi16_writer *begin_records(const uapi16_manifest_options *o, int fd) { + uapi16_writer *w = NULL; + + check_eq(uapi16_writer_begin(o, fd, NULL, &w, NULL), 0); + check(w); + return w; +} + +/* The example of the description of the API: the manifest of a directory + * in a new file. */ +static int example(int out_dir_fd, int esp_fd, uint64_t *ret_files) { + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + int r; + + r = set_features(o, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_MTIME)); + if (r < 0) + return r; + + r = uapi16_manifest_generate_at(o, out_dir_fd, "esp.manifest", esp_fd, UAPI16_ADD_NONE, &report, &e); + if (r < 0) { + fprintf(stderr, "Failed to write the manifest, at '%s' in the tree: %s\n", + uapi16_error_path(e) ? uapi16_error_path(e) : "n/a", strerror(-r)); + return r; + } + + /* A call that succeeds leaves reterr alone. */ + check(!e); + *ret_files = uapi16_manifest_report_files(report); + return 0; +} + +static void test_example(void) { + _cleanup_(closep) int tree = make_tree("example"), out = make_dir(tmp_fd, "example-out"); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(freep) char *created = NULL, *streamed = NULL, *again = NULL; + size_t created_size, streamed_size, again_size; + uint64_t files = 0; + + check_eq(example(out, tree, &files), 0); + check_eq(files, 3); + created = read_file(out, "esp.manifest", &created_size); + check_manifest(created, created_size); + check(strstr(created, "\"name\":\"a/linked-too\"")); + check(strstr(created, "\"mTimeNSec\"")); + + /* The same manifest goes to a descriptor, and to a new file again. */ + check(o); + check_eq(set_features(o, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_MTIME)), 0); + check_eq(uapi16_manifest_options_set_order(o, UAPI16_ORDER_CODEPOINT), 0); + streamed = generate(o, tree, UAPI16_ADD_NONE, &streamed_size); + check_same(streamed, streamed_size, created, created_size); + check_eq(uapi16_manifest_generate_at(o, out, "again", tree, UAPI16_ADD_NONE, &report, NULL), 0); + check_eq(uapi16_manifest_report_files(report), 3); + again = read_file(out, "again", &again_size); + check_same(again, again_size, created, created_size); + + /* A caller that does not want the report passes no place for it. */ + { + _cleanup_(closep) int fd = scratch_file(); + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *generated = NULL, *generated_at = NULL; + size_t size; + + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, NULL, &e), 0); + generated = read_all(fd, &size); + check_same(generated, size, created, created_size); + + check_eq(uapi16_manifest_generate_at(o, out, "unreported", tree, UAPI16_ADD_NONE, NULL, NULL), 0); + generated_at = read_file(out, "unreported", &size); + check_same(generated_at, size, created, created_size); + check(!e); + } + + /* A new file that is synced holds the same manifest. Only the + * calls that make a new file sync: with the options set, a + * manifest goes to a descriptor as before. */ + { + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *generated_at = NULL, *generated = NULL; + size_t size; + + check_eq(uapi16_manifest_options_set_sync(o, true), 0); + check_eq(uapi16_manifest_generate_at(o, out, "synced", tree, UAPI16_ADD_NONE, NULL, &e), 0); + generated_at = read_file(out, "synced", &size); + check_same(generated_at, size, created, created_size); + + generated = generate(o, tree, UAPI16_ADD_NONE, &size); + check_same(generated, size, created, created_size); + check_eq(uapi16_manifest_options_set_sync(o, false), 0); + check(!e); + } + + /* The file is made with the mode of any new file: read and write + * for everybody, less what the umask takes away. */ + _cleanup_(closep) int plain_fd = openat(out, "plain", O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0666); + struct stat made, plain; + check(plain_fd >= 0); + check_eq(fstatat(out, "again", &made, 0), 0); + check_eq(fstat(plain_fd, &plain), 0); + check_eq(made.st_mode, plain.st_mode); +} + +static void test_report(void) { + _cleanup_(closep) int tree = make_tree("report"), fd = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL, *skipped = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *listed = NULL; + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_hello("d/file"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *alias = make_object("alias"); + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + struct timespec times[2] = { { .tv_sec = -1 }, { .tv_sec = -1 } }; + + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e), 0); + check_eq(uapi16_manifest_report_files(report), 3); + check_eq(uapi16_manifest_report_directories(report), 2); + check_eq(uapi16_manifest_report_others(report), 2); + check_eq(uapi16_manifest_report_bytes(report), 15); + check_eq(uapi16_manifest_report_entries_omitted(report), 0); + check_eq(uapi16_manifest_report_fields_omitted(report), 0); + + /* What is left out is counted: a name with a control character, and + * a modification time before 1970. */ + make_file(tree, "\001control", ""); + check_eq(utimensat(tree, "a/file", times, 0), 0); + check_eq(set_features(o, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_MTIME)), 0); + empty(fd); + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_GRACEFUL, &skipped, &e), 0); + check_eq(uapi16_manifest_report_files(skipped), 3); + check_eq(uapi16_manifest_report_entries_omitted(skipped), 1); + check_eq(uapi16_manifest_report_fields_omitted(skipped), 1); + + /* The report of file objects counts each of them: two names of one + * file are two files with the data of each, and the directory that + * was not added and the root are directories. */ + check_eq(set_features(o, FEATURES(DEFAULT_FEATURES)), 0); + w = open_writer(o); + check_eq(uapi16_file_object_set_inode_token(file, 1), 0); + check_eq(uapi16_manifest_writer_add_object(w, file, &e), 0); + check_eq(uapi16_file_object_set_name(file, "other", &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, file, &e), 0); + check_eq(uapi16_file_object_set_type(alias, S_IFLNK), 0); + check_eq(uapi16_file_object_set_target(alias, "d", 1), 0); + check_eq(uapi16_manifest_writer_add_object(w, alias, &e), 0); + check_eq(uapi16_manifest_writer_finish(w, &listed, &e), 0); + check_eq(uapi16_manifest_report_files(listed), 2); + check_eq(uapi16_manifest_report_directories(listed), 2); + check_eq(uapi16_manifest_report_others(listed), 1); + check_eq(uapi16_manifest_report_bytes(listed), 10); + check_eq(uapi16_manifest_report_entries_omitted(listed), 0); + check_eq(uapi16_manifest_report_fields_omitted(listed), 0); + check(!e); + + /* No report counts nothing. */ + check_eq(uapi16_manifest_report_files(NULL), 0); + check_eq(uapi16_manifest_report_directories(NULL), 0); + check_eq(uapi16_manifest_report_others(NULL), 0); + check_eq(uapi16_manifest_report_bytes(NULL), 0); + check_eq(uapi16_manifest_report_entries_omitted(NULL), 0); + check_eq(uapi16_manifest_report_fields_omitted(NULL), 0); + + /* Freeing returns NULL, and takes NULL. */ + report = uapi16_manifest_report_free(report); + check(!report); + check(!uapi16_manifest_report_free(NULL)); +} + +static void test_options(void) { + static const uapi16_feature_t for_partitions[] = { + UAPI16_FEATURE_GPT_LABEL, UAPI16_FEATURE_GPT_UUID, UAPI16_FEATURE_GPT_TYPE_UUID, + UAPI16_FEATURE_GPT_DISK_UUID, UAPI16_FEATURE_GPT_FLAGS, UAPI16_FEATURE_GPT_FLAG_NO_AUTO, + UAPI16_FEATURE_GPT_FLAG_GROW_FILE_SYSTEM, + }; + static const uint64_t no_orders[] = { 2, 3, UINT64_C(1) << 63, UINT64_MAX }; + _cleanup_(closep) int tree = make_tree("options"), out = make_dir(tmp_fd, "options-out"); + _cleanup_(closep) int fd = scratch_file(), written = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *kept = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *records = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_hello("file"); + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + uapi16_features_t all = features_none(); + struct stat st; + + check(o); + + /* Every feature is taken, and a number that is none is not. */ + check_eq(set_features(o, features_none()), 0); + check_eq(set_features(o, EVERY_FEATURE), 0); + check_eq(set_features(o, FEATURES(NO_FEATURE)), -EINVAL); + check_eq(set_features(o, FEATURES(64)), -EINVAL); + check_eq(set_features(o, FEATURES(64 * UAPI16_FEATURES_WORDS)), -EINVAL); + check_eq(set_features(NULL, FEATURES(DEFAULT_FEATURES)), -EINVAL); + + /* The code point order is the only order. No order is taken too, + * for a manifest that declares none, which test_no_order() writes. + * Any other number is no order. */ + check_eq(uapi16_manifest_options_set_order(o, UAPI16_ORDER_NONE), 0); + check_eq(uapi16_manifest_options_set_order(o, UAPI16_ORDER_CODEPOINT), 0); + for (size_t i = 0; i < ELEMENTSOF(no_orders); i++) + check_eq(uapi16_manifest_options_set_order(o, no_orders[i]), -EINVAL); + check_eq(uapi16_manifest_options_set_order(NULL, UAPI16_ORDER_CODEPOINT), -EINVAL); + check_eq(uapi16_manifest_options_set_order(NULL, UAPI16_ORDER_NONE), -EINVAL); + + /* Syncing is turned on and off. */ + check_eq(uapi16_manifest_options_set_sync(o, true), 0); + check_eq(uapi16_manifest_options_set_sync(o, false), 0); + check_eq(uapi16_manifest_options_set_sync(NULL, true), -EINVAL); + + /* The features of partitions are no features of a tree: nothing is + * made for them, and the error says which one it is. */ + for (size_t i = 0; i < ELEMENTSOF(for_partitions); i++) { + uapi16_manifest_writer *w = NULL; + uapi16_manifest_report *report = NULL; + uapi16_error *e = NULL; + int r; + + all = WITH(all, for_partitions[i]); + r = set_features(o, FEATURES(DEFAULT_FEATURES, for_partitions[i])); + check_eq(r, 0); + + r = uapi16_manifest_writer_create_at(o, out, "m", &w, &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_FEATURE); + check_eq(uapi16_error_feature(e), for_partitions[i]); + e = uapi16_error_free(e); + check(!e); + + r = uapi16_manifest_writer_open(o, fd, &w, &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_FEATURE); + check_eq(uapi16_error_feature(e), for_partitions[i]); + e = uapi16_error_free(e); + + r = uapi16_manifest_generate_at(o, out, "m", tree, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_FEATURE); + check_eq(uapi16_error_feature(e), for_partitions[i]); + e = uapi16_error_free(e); + + r = uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_FEATURE); + check_eq(uapi16_error_feature(e), for_partitions[i]); + e = uapi16_error_free(e); + + check(!w && !report); + } + check_same_features(all, FEATURES_OF_PARTITIONS); + check_eq(fstatat(out, "m", &st, 0), -1); + check_eq(size_of(fd), 0); + + /* A writer that was made with options does not need them any more, + * and neither does a writer of records: both write what the options + * said when they were made. */ + check_eq(set_features(o, FEATURES(UAPI16_FEATURE_SIZE, UAPI16_FEATURE_SHA256)), 0); + check_eq(uapi16_manifest_writer_open(o, fd, &kept, NULL), 0); + records = begin_records(o, written); + check_eq(set_features(o, FEATURES(UAPI16_FEATURE_MODE)), 0); + o = uapi16_manifest_options_free(o); + check(!o); + check_eq(uapi16_manifest_writer_add_object(kept, file, NULL), 0); + check_eq(uapi16_manifest_writer_finish(kept, NULL, NULL), 0); + check_eq(uapi16_writer_file(records, file, NULL), 0); + check_eq(uapi16_writer_finish(records, NULL), 0); + kept = uapi16_manifest_writer_free(kept); + records = uapi16_writer_free(records); + reader = open_reader(fd); + check_recorded(reader, FEATURES(UAPI16_FEATURE_SIZE, UAPI16_FEATURE_SHA256)); + reader = uapi16_reader_free(reader); + reader = open_reader(written); + check_recorded(reader, FEATURES(UAPI16_FEATURE_SIZE, UAPI16_FEATURE_SHA256)); + + /* Freeing returns NULL, and takes NULL. */ + check(!uapi16_manifest_options_free(NULL)); +} + +static void test_misuse(void) { + static const uint64_t no_flags[] = { UINT64_C(1) << 2, UINT64_C(1) << 3, UINT64_C(1) << 63, + UINT64_MAX }; + static const uapi16_add_flags_t both = UAPI16_ADD_CROSS_MOUNTS | UAPI16_ADD_GRACEFUL; + static const int no_descriptors[] = { -1, AT_FDCWD, INT_MIN }; + _cleanup_(closep) int tree = make_tree("misuse"), out = make_dir(tmp_fd, "misuse-out"); + _cleanup_(closep) int fd = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL, *none = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_hello("a/file"); + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + uint64_t record = 77; + size_t size = 1; + + check_eq(uapi16_manifest_writer_open(o, fd, &w, &e), 0); + check(w && !e); + + /* An object that is NULL, with a place for the error and without. */ + check_misuse(uapi16_manifest_writer_create_at(NULL, out, "m", &none, &e), &e, EINVAL); + check_misuse(uapi16_manifest_writer_open(NULL, fd, &none, &e), &e, EINVAL); + check_misuse(uapi16_manifest_writer_add_object(NULL, file, &e), &e, EINVAL); + check_misuse(uapi16_manifest_writer_add_object(w, NULL, &e), &e, EINVAL); + check_misuse(uapi16_manifest_writer_finish(NULL, &report, &e), &e, EINVAL); + check_misuse(uapi16_manifest_generate_at(NULL, out, "m", tree, UAPI16_ADD_NONE, &report, &e), &e, EINVAL); + check_misuse(uapi16_manifest_generate(NULL, fd, tree, UAPI16_ADD_NONE, &report, &e), &e, EINVAL); + check_eq(uapi16_manifest_writer_create_at(NULL, out, "m", &none, NULL), -EINVAL); + check_eq(uapi16_manifest_writer_open(NULL, fd, &none, NULL), -EINVAL); + check_eq(uapi16_manifest_writer_add_object(NULL, file, NULL), -EINVAL); + check_eq(uapi16_manifest_writer_add_object(w, NULL, NULL), -EINVAL); + check_eq(uapi16_manifest_writer_finish(NULL, &report, NULL), -EINVAL); + check_eq(uapi16_manifest_generate_at(NULL, out, "m", tree, UAPI16_ADD_NONE, &report, NULL), -EINVAL); + check_eq(uapi16_manifest_generate(NULL, fd, tree, UAPI16_ADD_NONE, &report, NULL), -EINVAL); + + /* No place for the writer a call makes, and no name. */ + check_misuse(uapi16_manifest_writer_create_at(o, out, "m", NULL, &e), &e, EINVAL); + check_misuse(uapi16_manifest_writer_open(o, fd, NULL, &e), &e, EINVAL); + check_misuse(uapi16_manifest_writer_create_at(o, out, NULL, &none, &e), &e, EINVAL); + check_misuse(uapi16_manifest_generate_at(o, out, NULL, tree, UAPI16_ADD_NONE, &report, &e), &e, EINVAL); + + /* Flags that are none: every bit but the two of the flags, also + * the one after them. The two can be given together. */ + for (size_t i = 0; i < ELEMENTSOF(no_flags); i++) { + uint64_t no = no_flags[i]; + + check_misuse(uapi16_manifest_generate_at(o, out, "m", tree, no, &report, &e), &e, EINVAL); + check_misuse(uapi16_manifest_generate(o, fd, tree, no, &report, &e), &e, EINVAL); + } + + /* A negative number is no descriptor, AT_FDCWD neither. */ + for (size_t i = 0; i < ELEMENTSOF(no_descriptors); i++) { + int no = no_descriptors[i]; + + check_misuse(uapi16_manifest_writer_create_at(o, no, "m", &none, &e), &e, EBADF); + check_misuse(uapi16_manifest_writer_open(o, no, &none, &e), &e, EBADF); + check_misuse(uapi16_manifest_generate_at(o, no, "m", tree, UAPI16_ADD_NONE, &report, &e), &e, EBADF); + check_misuse(uapi16_manifest_generate_at(o, out, "m", no, UAPI16_ADD_NONE, &report, &e), &e, EBADF); + check_misuse(uapi16_manifest_generate(o, no, tree, UAPI16_ADD_NONE, &report, &e), &e, EBADF); + check_misuse(uapi16_manifest_generate(o, fd, no, UAPI16_ADD_NONE, &report, &e), &e, EBADF); + } + check(!none && !report); + + /* None of that made a file or wrote anything, and none of it ended + * the writer. Once it is finished, it takes nothing more. */ + struct stat st; + check_eq(fstatat(out, "m", &st, 0), -1); + check_eq(size_of(fd), 0); + check_eq(uapi16_manifest_writer_add_object(w, file, &e), 0); + check_eq(uapi16_manifest_writer_finish(w, &report, &e), 0); + check_eq(uapi16_manifest_report_files(report), 1); + check_eq(uapi16_manifest_report_directories(report), 2); + check(size_of(fd) > 0); + report = uapi16_manifest_report_free(report); + check_ended(uapi16_manifest_writer_add_object(w, file, &e), &e); + check_ended(uapi16_manifest_writer_finish(w, &report, &e), &e); + check_eq(uapi16_manifest_writer_add_object(w, file, NULL), -ESTALE); + check_eq(uapi16_manifest_writer_finish(w, NULL, NULL), -ESTALE); + check(!report); + /* A call that is not valid fails for that still. */ + check_misuse(uapi16_manifest_writer_add_object(w, NULL, &e), &e, EINVAL); + w = uapi16_manifest_writer_free(w); + + /* The two flags together, on a manifest that goes to a descriptor + * and on one that goes to a new file. */ + empty(fd); + check_eq(uapi16_manifest_generate(o, fd, tree, both, &report, &e), 0); + report = uapi16_manifest_report_free(report); + check_eq(uapi16_manifest_generate_at(o, out, "both", tree, both, &report, &e), 0); + check(!e); + + /* No error says nothing. */ + check_eq(uapi16_error_kind(NULL), 0); + check_eq(uapi16_error_errno(NULL), 0); + check(!uapi16_error_path(NULL)); + check(!uapi16_error_hardlink_path(NULL)); + check_eq(uapi16_error_feature(NULL), UAPI16_FEATURE_NONE); + check(!uapi16_error_raw_name(NULL, &size)); + check_eq(size, 0); + check(!uapi16_error_raw_name(NULL, NULL)); + check_eq(uapi16_error_name_problem(NULL), 0); + check(!uapi16_error_field(NULL)); + check_eq(uapi16_error_record(NULL, &record), -EINVAL); + check_eq(record, 77); + check(!uapi16_error_problem(NULL)); + check(!uapi16_error_free(NULL)); + check(!uapi16_manifest_writer_free(NULL)); +} + +/* + * What the walk of the generate functions records of a tree: every file + * below its top in the order of the manifest, a symbolic link with its + * target and without what it leads to, the names of one file as such, and + * what the features ask for. + */ +static void test_walk(void) { + static const char *const names[] = { "a", "a/file", "a/linked-too", "fifo", "link", "linked" }; + static const uapi16_add_flags_t both = UAPI16_ADD_CROSS_MOUNTS | UAPI16_ADD_GRACEFUL; + static const struct timespec times[2] = { + { .tv_sec = 1234567890, .tv_nsec = 123456789 }, + { .tv_sec = 1234567890, .tv_nsec = 123456789 }, + }; + _cleanup_(closep) int tree = make_tree("walk"), fd = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *plain = NULL, *flagged = NULL; + const uapi16_file_object *root; + uapi16_features_t features; + uapi16_inode_token_t linked = UAPI16_INODE_TOKEN_NONE; + size_t plain_size, flagged_size; + struct stat st; + + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e), 0); + report = uapi16_manifest_report_free(report); + reader = open_reader(fd); + check_recorded(reader, FEATURES(DEFAULT_FEATURES)); + check_eq(uapi16_reader_order(reader), UAPI16_ORDER_CODEPOINT); + + /* The top of the tree is the root, with what stat() says of it. */ + root = uapi16_reader_root(reader); + check_eq(fstat(tree, &st), 0); + check_str(uapi16_file_object_name(root), ""); + check_eq(uapi16_file_object_type(root), S_IFDIR); + { + uint32_t mode = 0, uid = 0, gid = 0; + + check_eq(uapi16_file_object_mode(root, &mode), 0); + check_eq(mode, st.st_mode & 07777); + check_eq(uapi16_file_object_uid(root, &uid), 0); + check_eq(uid, st.st_uid); + check_eq(uapi16_file_object_gid(root, &gid), 0); + check_eq(gid, st.st_gid); + } + + /* Every file below it follows, in the order of the manifest: a + * directory right before what is in it. */ + for (size_t i = 0; i < ELEMENTSOF(names); i++) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = next_object(reader, names[i]); + uapi16_sha256_digest_t hash; + uapi16_inode_token_t token = 77; + uint64_t size = 77; + uint32_t mode = 0; + const void *target; + size_t target_size = 1; + + if (i > 0) + check_eq(uapi16_name_compare(names[i - 1], names[i]), UAPI16_NAME_BEFORE); + check_eq(fstatat(tree, names[i], &st, AT_SYMLINK_NOFOLLOW), 0); + check_eq(uapi16_file_object_type(file), st.st_mode & S_IFMT); + + switch (st.st_mode & S_IFMT) { + case S_IFREG: + /* A regular file has its size and the hash of its + * data, which is in the file of its name. */ + check_eq(uapi16_file_object_size(file, &size), 0); + check_eq(size, 5); + check_eq(uapi16_file_object_sha256(file, &hash), 0); + check_hash(&hash, st.st_nlink > 1 ? SHA256_OF_TWICE : SHA256_OF_HELLO); + check_eq(uapi16_file_object_data_location(file), UAPI16_DATA_LOCATION_EXTERNAL); + check(!uapi16_file_object_literal(file, NULL)); + break; + case S_IFLNK: + /* A symbolic link is recorded with its target, and + * is not followed: nothing is listed below it. It + * has no access mode. */ + target = uapi16_file_object_literal(file, &target_size); + check(target); + check_same(target, target_size, "a", 1); + check_eq(uapi16_file_object_data_location(file), UAPI16_DATA_LOCATION_LITERAL); + check_eq(uapi16_file_object_size(file, &size), 0); + check_eq(size, 1); + check_eq(uapi16_file_object_mode(file, &mode), -ENODATA); + break; + default: + /* A directory and a FIFO have no data. */ + check_eq(uapi16_file_object_size(file, &size), -ENODATA); + check_eq(uapi16_file_object_sha256(file, &hash), -ENODATA); + check_eq(uapi16_file_object_data_location(file), UAPI16_DATA_LOCATION_NONE); + break; + } + if (!S_ISLNK(st.st_mode)) { + check_eq(uapi16_file_object_mode(file, &mode), 0); + check_eq(mode, st.st_mode & 07777); + } + + /* The two names of one file carry one token, and no other + * file has one. */ + if (!S_ISDIR(st.st_mode) && st.st_nlink > 1) { + check_eq(uapi16_file_object_inode_token(file, &token), 0); + check(token != UAPI16_INODE_TOKEN_NONE); + check(linked == UAPI16_INODE_TOKEN_NONE || linked == token); + linked = token; + } else { + check_eq(uapi16_file_object_inode_token(file, &token), -ENODATA); + check_eq(token, 77); + } + } + check_ends(reader); + check(linked != UAPI16_INODE_TOKEN_NONE); + reader = uapi16_reader_free(reader); + + /* The two flags change nothing for a tree without mount points and + * without names a manifest can't hold. */ + plain = read_all(fd, &plain_size); + flagged = generate(o, tree, both, &flagged_size); + check_same(flagged, flagged_size, plain, plain_size); + + /* A manifest that records nothing has the names and the types of + * the files, and nothing else: no target of a symbolic link, and no + * token. */ + check_eq(set_features(o, features_none()), 0); + empty(fd); + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e), 0); + check_eq(uapi16_manifest_report_bytes(report), 15); + report = uapi16_manifest_report_free(report); + reader = open_reader(fd); + check_recorded(reader, features_none()); + check_stated(uapi16_reader_root(reader), features_none()); + for (size_t i = 0; i < ELEMENTSOF(names); i++) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = next_object(reader, names[i]); + + check_eq(fstatat(tree, names[i], &st, AT_SYMLINK_NOFOLLOW), 0); + check_eq(uapi16_file_object_type(file), st.st_mode & S_IFMT); + check_stated(file, features_none()); + check(!uapi16_file_object_literal(file, NULL)); + } + check_ends(reader); + reader = uapi16_reader_free(reader); + + /* The modification time, as stat() has it, and the name of the + * owner as the user database has it, or none where it does not have + * one, which the report counts. */ + features = FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_MTIME, UAPI16_FEATURE_USER_NAME); + check_eq(utimensat(tree, "a/file", times, 0), 0); + check_eq(fstatat(tree, "a/file", &st, 0), 0); + check_eq(st.st_mtim.tv_sec, times[1].tv_sec); + check_eq(set_features(o, features), 0); + empty(fd); + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e), 0); + reader = open_reader(fd); + check_recorded(reader, features); + { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *a = next_object(reader, "a"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = next_object(reader, "a/file"); + const struct passwd *owner = getpwuid(getuid()); + uint64_t mtime = 0; + + check_eq(uapi16_file_object_mtime_nsec(file, &mtime), 0); + check_eq(mtime, (uint64_t) st.st_mtim.tv_sec * UINT64_C(1000000000) + + (uint64_t) st.st_mtim.tv_nsec); + if (owner) { + check_str(uapi16_file_object_user_name(file), owner->pw_name); + check_eq(uapi16_manifest_report_fields_omitted(report), 0); + } else { + check(!uapi16_file_object_user_name(file)); + check(uapi16_manifest_report_fields_omitted(report) > 0); + } + check(!uapi16_file_object_group_name(file)); + } + check(!e); +} + +/* + * The extended attributes of the user namespace, which the walk records + * where the manifest has the feature: the names without "user." in front, + * in their order, and the values as the bytes they are. A file without any + * lists none. Where the file system of the temporary directory has no such + * attributes, there is nothing to test. + */ +static void test_walk_xattrs(void) { + static const char binary[] = { 'b', 0, (char) 0xff }; + _cleanup_(closep) int tree = make_dir(tmp_fd, "xattrs"), fd = scratch_file(), file = -1; + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *with = NULL, *without = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + const char *name = NULL; + const void *value = NULL; + size_t count = 77, size = 77; + int r; + + make_file(tree, "with", ""); + make_file(tree, "without", ""); + file = openat(tree, "with", O_RDONLY | O_CLOEXEC); + check(file >= 0); + if (fsetxattr(file, "user.text", "a value", 7, 0) < 0) { + fprintf(stderr, "skipping the extended attributes of a tree: %s\n", strerror(errno)); + return; + } + check_eq(fsetxattr(file, "user.binary", binary, sizeof(binary), 0), 0); + check_eq(fsetxattr(file, "user.empty", "", 0, 0), 0); + + r = set_features(o, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_USER_XATTR)); + check_eq(r, 0); + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, NULL, &e), 0); + reader = open_reader(fd); + check_eq(uapi16_file_object_user_xattrs(uapi16_reader_root(reader), &count), 0); + check_eq(count, 0); + + with = next_object(reader, "with"); + check_eq(uapi16_file_object_user_xattrs(with, &count), 0); + check_eq(count, 3); + check_eq(uapi16_file_object_user_xattr(with, 0, &name, &value, &size), 0); + check_str(name, "binary"); + check_same(value, size, binary, sizeof(binary)); + check_eq(uapi16_file_object_user_xattr(with, 1, &name, &value, &size), 0); + check_str(name, "empty"); + check_eq(size, 0); + check_eq(uapi16_file_object_user_xattr(with, 2, &name, &value, &size), 0); + check_str(name, "text"); + check_same(value, size, "a value", 7); + check(uapi16_file_object_has_stated_feature(with, UAPI16_FEATURE_USER_XATTR)); + + /* The file without any lists none, which the manifest says by its + * feature: the object has no field for it. */ + without = next_object(reader, "without"); + count = 77; + check_eq(uapi16_file_object_user_xattrs(without, &count), 0); + check_eq(count, 0); + check(!uapi16_file_object_has_stated_feature(without, UAPI16_FEATURE_USER_XATTR)); + check_ends(reader); + check(!e); +} + +/* + * A call whose `reterr` points to something is refused before it does + * anything, by every function that takes a `reterr`, and what is there + * stays there: an error that was not freed, and what is no error at all, + * which nothing reads through. + */ +static void test_error_places(void) { + static max_align_t no_error; + _cleanup_(closep) int tree = make_tree("places"), out = make_dir(tmp_fd, "places-out"); + _cleanup_(closep) int fd = scratch_file(), written = scratch_file(); + _cleanup_(closep) int manifest = + manifest_file(ROOT FILE_OBJECT("a") SIGNATURE_OBJECT("openpgp") TRAILER); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL, *none = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL, *no_reader = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *records = NULL, *no_records = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_hello("file"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *labelled = make_object("labelled"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *linked = make_object("linked"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *first = NULL, *no_object = NULL; + _cleanup_(uapi16_signature_freep) uapi16_signature *signature = NULL, *no_signature = NULL; + _cleanup_(uapi16_directory_freep) uapi16_directory *directory = NULL, *no_directory = NULL; + _cleanup_(uapi16_data_check_freep) uapi16_data_check *data = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *held = NULL; + uapi16_error *holds[2], *e; + uint64_t size = 77, offset = 7; + size_t before, begun; + int opened = -7; + + check_eq(uapi16_manifest_writer_open(o, fd, &w, NULL), 0); + reader = open_reader(manifest); + records = begin_records(o, written); + begun = size_of(written); + check_eq(uapi16_signature_new("openpgp", &signature), 0); + check_eq(uapi16_data_check_new(file, &data), 0); + check_eq(uapi16_directory_new(tree, UAPI16_DIRECTORY_NONE, &directory, NULL), 0); + + /* The error that is held: that of a file object that a writer + * refuses for the label of a file system, which only the root has. */ + check_eq(uapi16_file_object_set_fs_label(labelled, "label"), 0); + check_eq(uapi16_manifest_writer_add_object(w, labelled, &held), -EBADMSG); + check(held); + holds[0] = held; + holds[1] = (uapi16_error *) &no_error; + before = open_descriptors(); + + for (size_t i = 0; i < ELEMENTSOF(holds); i++) { + e = holds[i]; + check_eq(uapi16_manifest_generate_at(o, out, "m", tree, UAPI16_ADD_NONE, &report, &e), -EINVAL); + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e), -EINVAL); + check_eq(uapi16_manifest_writer_create_at(o, out, "m", &none, &e), -EINVAL); + check_eq(uapi16_manifest_writer_open(o, fd, &none, &e), -EINVAL); + check_eq(uapi16_manifest_writer_add_object(w, file, &e), -EINVAL); + check_eq(uapi16_manifest_writer_finish(w, &report, &e), -EINVAL); + check_eq(uapi16_reader_open(manifest, &no_reader, &e), -EINVAL); + check_eq(uapi16_reader_require_order(reader, UAPI16_ORDER_CODEPOINT, &e), -EINVAL); + check_eq(uapi16_reader_check_validity(reader, 0, &e), -EINVAL); + check_eq(uapi16_reader_next(reader, &no_object, &e), -EINVAL); + check_eq(uapi16_reader_next_signature(reader, &no_signature, &e), -EINVAL); + check_eq(uapi16_writer_begin(o, fd, NULL, &no_records, &e), -EINVAL); + check_eq(uapi16_writer_file(records, file, &e), -EINVAL); + check_eq(uapi16_writer_signature(records, signature, &e), -EINVAL); + check_eq(uapi16_writer_finish(records, &e), -EINVAL); + check_eq(uapi16_file_object_new("new", &no_object, &e), -EINVAL); + check_eq(uapi16_file_object_set_name(file, "renamed", &e), -EINVAL); + check_eq(uapi16_file_object_set_contents_file(file, "elsewhere", &e), -EINVAL); + check_eq(uapi16_file_object_check_validity(file, 0, &e), -EINVAL); + check_eq(uapi16_directory_new(tree, UAPI16_DIRECTORY_NONE, &no_directory, &e), -EINVAL); + check_eq(uapi16_directory_open_data(directory, linked, &opened, &offset, &e), -EINVAL); + check_eq(uapi16_data_check_update(data, "hello", 5, &e), -EINVAL); + check_eq(uapi16_data_check_update_zeros(data, 5, &e), -EINVAL); + check_eq(uapi16_data_check_finish(data, &size, &e), -EINVAL); + /* It is refused for that before anything else is looked + * at: a negative descriptor fails with EBADF otherwise, and + * a name that is none with the rule it breaks. */ + check_eq(uapi16_manifest_writer_open(o, -1, &none, &e), -EINVAL); + check_eq(uapi16_reader_open(-1, &no_reader, &e), -EINVAL); + check_eq(uapi16_writer_begin(o, -1, NULL, &no_records, &e), -EINVAL); + check_eq(uapi16_directory_new(-1, UAPI16_DIRECTORY_NONE, &no_directory, &e), -EINVAL); + check_eq(uapi16_file_object_new("a//b", &no_object, &e), -EINVAL); + check(e == holds[i]); + check(!none && !report && !no_reader && !no_records && !no_object && !no_signature); + check(!no_directory); + check_eq(size, 77); + check_eq(opened, -7); + check_eq(offset, 7); + } + + /* The error is the one it was. */ + check_eq(uapi16_error_kind(held), UAPI16_ERROR_MANIFEST); + check_eq(uapi16_error_errno(held), EBADMSG); + check_str(uapi16_error_path(held), "labelled"); + check_str(uapi16_error_field(held), "fsLabel"); + check_str(uapi16_error_problem(held), "fieldNotPermitted"); + + /* No call made a file, wrote anything or kept a descriptor. */ + check_eq(count_entries(tmp_fd, "places-out"), 0); + check_eq(size_of(fd), 0); + check_eq(size_of(written), begun); + check_eq(open_descriptors(), before); + + /* None changed its object: the file object has its name and its + * data where they were, and the check has seen none of the data. */ + check_str(uapi16_file_object_name(file), "file"); + check_eq(uapi16_data_check_update(data, "hello", 5, NULL), 0); + check_eq(uapi16_data_check_finish(data, &size, NULL), 0); + check_eq(size, 5); + + /* None read anything: the reader hands out its first file object, + * says that signature objects follow, and hands out the first of + * them. */ + first = next_object(reader, "a"); + check_eq(uapi16_reader_next(reader, &no_object, NULL), UAPI16_READ_SIGNATURES); + check_eq(uapi16_reader_next_signature(reader, &no_signature, NULL), UAPI16_READ_SIGNATURE); + check_str(uapi16_signature_mechanism(no_signature), "openpgp"); + + /* None added anything to the writer or finished it, and none wrote + * a record or finished the writer of records. */ + check_listed(w, 0, 1, 0); + check_eq(uapi16_writer_file(records, file, NULL), 0); + check_eq(uapi16_writer_finish(records, NULL), 0); + + /* The place is looked at before the object: one that is finished + * fails for the place as well. */ + e = held; + check_eq(uapi16_manifest_writer_add_object(w, file, NULL), -ESTALE); + check_eq(uapi16_manifest_writer_add_object(w, file, &e), -EINVAL); + check_eq(uapi16_manifest_writer_finish(w, &report, &e), -EINVAL); + check_eq(uapi16_writer_file(records, file, NULL), -ESTALE); + check_eq(uapi16_writer_file(records, file, &e), -EINVAL); + check_eq(uapi16_writer_finish(records, &e), -EINVAL); + check_eq(uapi16_data_check_update(data, "x", 1, NULL), -ESTALE); + check_eq(uapi16_data_check_update(data, "x", 1, &e), -EINVAL); + check_eq(uapi16_data_check_update_zeros(data, 1, NULL), -ESTALE); + check_eq(uapi16_data_check_update_zeros(data, 1, &e), -EINVAL); + check_eq(uapi16_data_check_finish(data, NULL, &e), -EINVAL); + check(e == held && !report); +} + +static void test_names(void) { + char too_long[NAME_OF_OBJECT_MAX + 2]; + const struct { + const char *name; + uapi16_name_problem_t problem; + } no_names[] = { + { "\xff", UAPI16_NAME_PROBLEM_NOT_UTF8 }, + { "a/\xc3", UAPI16_NAME_PROBLEM_NOT_UTF8 }, + { too_long, UAPI16_NAME_PROBLEM_TOO_LONG }, + { "Uapi16Manifest", UAPI16_NAME_PROBLEM_RESERVED }, + { "Uapi16Manifest.sig/x", UAPI16_NAME_PROBLEM_RESERVED }, + { "a\001b", UAPI16_NAME_PROBLEM_CONTROL_CHARACTER }, + { "a/b\177", UAPI16_NAME_PROBLEM_CONTROL_CHARACTER }, + { "a/\xef\xbf\xbe", UAPI16_NAME_PROBLEM_NONCHARACTER }, + { "a//b", UAPI16_NAME_PROBLEM_EMPTY_COMPONENT }, + { "/a", UAPI16_NAME_PROBLEM_EMPTY_COMPONENT }, + { "a/", UAPI16_NAME_PROBLEM_EMPTY_COMPONENT }, + { ".", UAPI16_NAME_PROBLEM_DOT_COMPONENT }, + { "a/../b", UAPI16_NAME_PROBLEM_DOT_COMPONENT }, + }; + static const char *const no_file_names[] = { + "", "x/", ".", "..", "sub/.", "sub/..", "/", "/m", "./m", + "../m", "sub/./m", "sub/../m", "//", "/./", "/../", "sub//..", "../sub/m", "sub/../../m", + }; + static const struct { + const char *name; + int error; + } not_below[] = { + { "inside/m", ELOOP }, + { "outside/m", ELOOP }, + { "sub/outside/m", ELOOP }, + { "inside/missing/m", ELOOP }, + { "file/m", ENOTDIR }, + { "sub/file/m", ENOTDIR }, + { "missing/m", ENOENT }, + { "sub/missing/m", ENOENT }, + }; + _cleanup_(closep) int tree = make_tree("names"), out = make_dir(tmp_fd, "names-out"); + _cleanup_(closep) int fd = scratch_file(), sub = make_dir(out, "sub"); + _cleanup_(closep) int elsewhere = make_dir(tmp_fd, "names-elsewhere"), probe = -1; + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL, *none = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *named = make_object("named"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *longest = NULL, *accented = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *no_object = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *written = NULL; + size_t written_size; + struct stat st; + int r; + + memset(too_long, 'a', sizeof(too_long) - 1); + too_long[sizeof(too_long) - 1] = 0; + + /* A name that is none is refused for the rule it breaks: as the + * name of a new file object, as another name for one, and as the + * name of the file its data is in. The object stays as it was. */ + for (size_t i = 0; i < ELEMENTSOF(no_names); i++) { + const char *no = no_names[i].name; + + check_eq(uapi16_file_object_new(no, &no_object, NULL), -EINVAL); + check_eq(uapi16_file_object_set_name(named, no, NULL), -EINVAL); + check_eq(uapi16_file_object_set_contents_file(named, no, NULL), -EINVAL); + + r = uapi16_file_object_new(no, &no_object, &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_NAME); + check_eq(uapi16_error_name_problem(e), no_names[i].problem); + check(!uapi16_error_raw_name(e, NULL)); + e = uapi16_error_free(e); + + r = uapi16_file_object_set_name(named, no, &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_NAME); + check_eq(uapi16_error_name_problem(e), no_names[i].problem); + e = uapi16_error_free(e); + + r = uapi16_file_object_set_contents_file(named, no, &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_NAME); + check_eq(uapi16_error_name_problem(e), no_names[i].problem); + e = uapi16_error_free(e); + + check(!no_object); + check_str(uapi16_file_object_name(named), "named"); + } + + /* The empty name is the name of the root. No file has its data in + * a file of that name, which is refused as a name that is empty. */ + r = uapi16_file_object_set_contents_file(named, "", &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_NAME); + check_eq(uapi16_error_name_problem(e), UAPI16_NAME_PROBLEM_EMPTY); + e = uapi16_error_free(e); + + /* The longest name is one, and so is one that is not ASCII. A + * manifest lists them as they are. */ + too_long[NAME_OF_OBJECT_MAX] = 0; + check_eq(uapi16_file_object_new(too_long, &longest, &e), 0); + check_str(uapi16_file_object_name(longest), too_long); + check_eq(uapi16_file_object_new("b/\xc3\xa9", &accented, &e), 0); + check_str(uapi16_file_object_name(accented), "b/\xc3\xa9"); + check_eq(uapi16_file_object_set_contents_file(accented, too_long, &e), 0); + check_eq(uapi16_manifest_writer_open(o, fd, &w, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, longest, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, accented, &e), 0); + check_eq(uapi16_manifest_writer_finish(w, &report, &e), 0); + check_eq(uapi16_manifest_report_files(report), 2); + check_eq(uapi16_manifest_report_directories(report), 2); + report = uapi16_manifest_report_free(report); + w = uapi16_manifest_writer_free(w); + written = read_all(fd, &written_size); + check_manifest(written, written_size); + check(strstr(written, "\"name\":\"b/\xc3\xa9\"")); + check(strstr(written, too_long)); + + /* The name of a new file is a path below its directory. One that + * names no file there is refused before anything is looked up: + * one that is empty or that ends in a slash, "." or "..", an + * absolute one, and one with "." or ".." on the way. */ + for (size_t i = 0; i < ELEMENTSOF(no_file_names); i++) { + const char *no = no_file_names[i]; + + check_misuse(uapi16_manifest_writer_create_at(o, out, no, &none, &e), &e, EINVAL); + check_misuse(uapi16_manifest_generate_at(o, out, no, tree, UAPI16_ADD_NONE, &report, &e), &e, EINVAL); + } + + /* The directories on the way are opened one at a time, and none + * through a symbolic link, whether it leads out of the directory + * or not: a link fails with ELOOP, a file with ENOTDIR, and a name + * that is not there with ENOENT. Nothing is made anywhere. */ + check_eq(symlinkat("sub", out, "inside"), 0); + check_eq(symlinkat("../names-elsewhere", out, "outside"), 0); + check_eq(symlinkat("../../names-elsewhere", sub, "outside"), 0); + make_file(out, "file", ""); + make_file(sub, "file", ""); + for (size_t i = 0; i < ELEMENTSOF(not_below); i++) { + r = uapi16_manifest_writer_create_at(o, out, not_below[i].name, &none, &e); + check_error(r, e, UAPI16_ERROR_IO, not_below[i].error, NULL, 0); + e = uapi16_error_free(e); + r = uapi16_manifest_generate_at(o, out, not_below[i].name, tree, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_IO, not_below[i].error, NULL, 0); + e = uapi16_error_free(e); + } + check(!none && !report); + check_eq(count_entries(tmp_fd, "names-elsewhere"), 0); + check_eq(count_entries(out, "sub"), 2); + check_eq(count_entries(tmp_fd, "names-out"), 4); + + /* A name with directories on the way names a file in the last of + * them. */ + check_eq(uapi16_manifest_generate_at(o, out, "sub/m", tree, UAPI16_ADD_NONE, &report, &e), 0); + check_eq(fstatat(sub, "m", &st, 0), 0); + check(st.st_size > 0); + report = uapi16_manifest_report_free(report); + + /* The name is taken as the bytes it is, which need not be UTF-8, + * where the file system takes such a name. */ + probe = openat(out, "\xfe", O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644); + if (probe < 0) { + fprintf(stderr, "skipping the names of new files that are not UTF-8: %s\n", strerror(errno)); + return; + } + check_eq(uapi16_manifest_writer_create_at(o, out, "\xff", &w, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, named, &e), 0); + check_eq(uapi16_manifest_writer_finish(w, NULL, &e), 0); + check_eq(fstatat(out, "\xff", &st, AT_SYMLINK_NOFOLLOW), 0); + check(S_ISREG(st.st_mode) && st.st_size > 0); + check_eq(uapi16_manifest_generate_at(o, out, "sub/caf\xe9", tree, UAPI16_ADD_NONE, &report, &e), 0); + check_eq(fstatat(sub, "caf\xe9", &st, AT_SYMLINK_NOFOLLOW), 0); + check(S_ISREG(st.st_mode) && st.st_size > 0); + check(!e); +} + +/* A file with a name that a manifest can't hold, which fails the walk of + * its tree with `error` for the rule `problem`, unless it is left out. The + * error is about the directory `in` that the file is in. */ +static void check_unwritable(int tree, const char *in, const char *raw, int error, + uapi16_name_problem_t problem) { + _cleanup_(closep) int fd = scratch_file(), out = dup(tmp_fd); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + const void *name; + size_t size = 0; + struct stat st; + int r; + + r = uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_UNWRITABLE_NAME, error, in, CHECK_NAME); + check_eq(uapi16_error_name_problem(e), problem); + name = uapi16_error_raw_name(e, &size); + check(name); + check_eq(size, strlen(raw)); + check_eq(memcmp(name, raw, size), 0); + check(uapi16_error_raw_name(e, NULL) == name); + e = uapi16_error_free(e); + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, NULL), -error); + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_CROSS_MOUNTS, &report, NULL), -error); + + /* A new file fails the same way, and is not made. */ + check(out >= 0); + r = uapi16_manifest_generate_at(o, out, "unwritable.manifest", tree, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_UNWRITABLE_NAME, error, in, CHECK_NAME); + check_eq(fstatat(out, "unwritable.manifest", &st, AT_SYMLINK_NOFOLLOW), -1); + check_eq(errno, ENOENT); + + /* Nothing was written, and no report made. */ + check(!report); + check_eq(size_of(fd), 0); + + r = uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_GRACEFUL, &report, NULL); + check_eq(r, 0); + check_eq(uapi16_manifest_report_entries_omitted(report), 1); + check(size_of(fd) > 0); +} + +static void test_unwritable_names(void) { + char component[COMPONENT_MAX + 1], deep[NAME_OF_OBJECT_MAX + 1]; + _cleanup_(closep) int control = make_dir(tmp_fd, "unwritable-control"); + _cleanup_(closep) int not_utf8 = make_dir(tmp_fd, "unwritable-utf8"); + _cleanup_(closep) int too_long = make_dir(tmp_fd, "unwritable-long"); + _cleanup_(closep) int whole = make_dir(tmp_fd, "unwritable-directory"); + _cleanup_(closep) int sub = make_dir(control, "sub"), other = make_dir(not_utf8, "sub"); + _cleanup_(closep) int below = make_dir(whole, "new\nline"); + int dir = dup(too_long); + size_t length = 0; + + make_file(sub, "tab\there", ""); + check_unwritable(control, "sub", "tab\there", EINVAL, UAPI16_NAME_PROBLEM_CONTROL_CHARACTER); + + make_file(not_utf8, "caf\xe9", ""); + make_file(other, "fine", ""); + check_unwritable(not_utf8, "", "caf\xe9", EILSEQ, UAPI16_NAME_PROBLEM_NOT_UTF8); + + /* A directory with such a name is left out with everything below + * it, as one. */ + make_file(below, "one", ""); + make_file(below, "two", ""); + check_unwritable(whole, "", "new\nline", EINVAL, UAPI16_NAME_PROBLEM_CONTROL_CHARACTER); + + /* Sixteen directories inside each other whose names are as long as + * a name gets make the longest name of a file object. A file in + * the last of them has a longer one. */ + memset(component, 'd', COMPONENT_MAX); + component[COMPONENT_MAX] = 0; + check(dir >= 0); + while (length + COMPONENT_MAX <= NAME_OF_OBJECT_MAX) { + int next = make_dir(dir, component); + + close(dir); + dir = next; + if (length > 0) + deep[length++] = '/'; + memcpy(deep + length, component, COMPONENT_MAX); + length += COMPONENT_MAX; + } + deep[length] = 0; + check_eq(length, NAME_OF_OBJECT_MAX); + make_file(dir, "x", ""); + close(dir); + check_unwritable(too_long, deep, "x", ENAMETOOLONG, UAPI16_NAME_PROBLEM_TOO_LONG); +} + +/* What says when a file is read, and changes it then, once. */ +static volatile sig_atomic_t grown; +static int grow_fd = -1; + +static void grow(int signal) { + (void) signal; + if (!grown && write(grow_fd, "!", 1) == 1) + grown = 1; +} + +/* + * UAPI16_ERROR_CHANGED: a file that changes while the walk reads it. The + * kernel says when that is: a watch of the file sends a signal for a read + * of it to the thread that reads, which gets it before its read returns. + * The handler appends to the file. Where there is no such watch, there is + * nothing to test. + */ +static void test_changes(void) { + _cleanup_(closep) int tree = make_dir(tmp_fd, "changes"), fd = scratch_file(); + _cleanup_(closep) int watch = -1; + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + struct f_owner_ex owner = { .type = F_OWNER_TID, .pid = (pid_t) syscall(SYS_gettid) }; + struct sigaction append = { .sa_handler = grow }, old; + char path[PATH_MAX]; + int r; + + make_file(tree, "before", "data"); + make_file(tree, "file", "hello"); + check((size_t) snprintf(path, sizeof(path), "%s/changes/file", tmp_path) < sizeof(path)); + watch = inotify_init1(IN_CLOEXEC | IN_NONBLOCK); + if (watch < 0 || inotify_add_watch(watch, path, IN_ACCESS) < 0) { + fprintf(stderr, "skipping a file that changes while it is read: %s\n", strerror(errno)); + return; + } + grow_fd = openat(tree, "file", O_WRONLY | O_APPEND | O_CLOEXEC); + check(grow_fd >= 0); + check_eq(sigaction(SIGIO, &append, &old), 0); + check_eq(fcntl(watch, F_SETOWN_EX, &owner), 0); + check_eq(fcntl(watch, F_SETFL, O_ASYNC | O_NONBLOCK), 0); + + r = uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e); + + check_eq(close(watch), 0); + watch = -1; + check_eq(sigaction(SIGIO, &old, NULL), 0); + check_eq(close(grow_fd), 0); + grow_fd = -1; + if (!grown) { + fprintf(stderr, "skipping a file that changes while it is read: no signal for its read\n"); + return; + } + check_error(r, e, UAPI16_ERROR_CHANGED, ESTALE, "file", 0); + check(!report); + check_eq(size_of(fd), 0); + e = uapi16_error_free(e); + + /* Once it changes no more, it is a file like any other. */ + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e), 0); + check_eq(uapi16_manifest_report_bytes(report), 10); + check(!e); +} + +static void test_errors(void) { + _cleanup_(closep) int tree = make_tree("errors"), out = make_dir(tmp_fd, "errors-out"); + _cleanup_(closep) int file = openat(tree, "a/file", O_RDONLY | O_CLOEXEC), fd = scratch_file(); + _cleanup_(closep) int path = openat(tree, "a/file", O_PATH | O_CLOEXEC); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL, *none = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *no_reader = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *no_records = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *x = make_hello("x"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *other = make_object("x"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *below = make_object("x/y"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *directory = make_object("x"); + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *taken = NULL; + size_t taken_size; + int r; + + check(file >= 0 && path >= 0); + check_eq(uapi16_file_object_set_type(directory, S_IFDIR), 0); + + /* UAPI16_ERROR_IO: a system call failed, with its errno. A manifest + * can't be read from a directory, and none can be written to a + * descriptor that is open for reading. */ + r = uapi16_reader_open(tree, &no_reader, &e); + check_error(r, e, UAPI16_ERROR_IO, EISDIR, NULL, CHECK_RECORD); + e = uapi16_error_free(e); + r = uapi16_writer_begin(o, file, NULL, &no_records, &e); + check_error(r, e, UAPI16_ERROR_IO, EBADF, NULL, CHECK_RECORD); + e = uapi16_error_free(e); + r = uapi16_manifest_generate(o, file, tree, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_IO, EBADF, NULL, 0); + e = uapi16_error_free(e); + check(!no_reader && !no_records && !report); + + /* UAPI16_ERROR_IO with EFBIG: a regular file of more than 1 TiB, + * where its data is hashed, also for the names of one file alone. + * Nothing of it is read for that. Where its data is not hashed it + * is a file like any other. A limit on the size of a file, or a + * file system that has no room for one this sparse, leaves nothing + * to test. */ + { + const uapi16_features_t unhashed = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_SIZE, + UAPI16_FEATURE_HARDLINK); + _cleanup_(closep) int top = make_dir(tmp_fd, "errors-large"), large = -1; + const off_t more = (off_t) (HASHED_MAX + 1); + struct rlimit limit; + + large = openat(top, "large", O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644); + check(large >= 0); + check_eq(getrlimit(RLIMIT_FSIZE, &limit), 0); + if (limit.rlim_cur != RLIM_INFINITY && limit.rlim_cur < (rlim_t) more) + fprintf(stderr, "skipping a file of more than 1 TiB: the limit on the size of a " + "file is %" PRIu64 " bytes\n", + (uint64_t) limit.rlim_cur); + else if (ftruncate(large, more) < 0) + fprintf(stderr, "skipping a file of more than 1 TiB: %s\n", strerror(errno)); + else { + r = uapi16_manifest_generate(o, fd, top, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_IO, EFBIG, "large", 0); + e = uapi16_error_free(e); + check_eq(size_of(fd), 0); + + check_eq(set_features(o, unhashed), 0); + check_eq(uapi16_manifest_generate(o, fd, top, UAPI16_ADD_NONE, &report, &e), 0); + check_eq(uapi16_manifest_report_files(report), 1); + check_eq(uapi16_manifest_report_bytes(report), HASHED_MAX + 1); + report = uapi16_manifest_report_free(report); + empty(fd); + + check_eq(linkat(top, "large", top, "large-too", 0), 0); + r = uapi16_manifest_generate(o, fd, top, UAPI16_ADD_NONE, &report, &e); + check_eq(r, -EFBIG); + check_eq(uapi16_error_kind(e), UAPI16_ERROR_IO); + check_eq(uapi16_error_errno(e), EFBIG); + check(strcmp(uapi16_error_path(e), "large") == 0 || + strcmp(uapi16_error_path(e), "large-too") == 0); + e = uapi16_error_free(e); + check_eq(size_of(fd), 0); + check_eq(set_features(o, FEATURES(DEFAULT_FEATURES)), 0); + } + } + + /* A directory that can't be listed fails the walk of its tree, and + * no manifest is written of a part of it. Nothing stops root from + * listing one. */ + if (geteuid() == 0) + fprintf(stderr, "skipping a directory that can't be listed: nothing stops root\n"); + else { + _cleanup_(closep) int locked = make_dir(tree, "locked"); + + check_eq(fchmodat(tree, "locked", 0, 0), 0); + r = uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_IO, EACCES, "locked", 0); + e = uapi16_error_free(e); + r = uapi16_manifest_generate_at(o, out, "locked.manifest", tree, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_IO, EACCES, "locked", 0); + e = uapi16_error_free(e); + check(!report); + check_eq(size_of(fd), 0); + check_eq(count_entries(tmp_fd, "errors-out"), 0); + check_eq(unlinkat(tree, "locked", AT_REMOVEDIR), 0); + } + + /* UAPI16_ERROR_EXISTS: the name of a new file is taken, when the + * writer is made or by the time it finishes. What has the name + * stays as it is. */ + make_file(out, "taken", "mine"); + check_eq(symlinkat("nowhere", out, "dangling"), 0); + r = uapi16_manifest_writer_create_at(o, out, "taken", &none, &e); + check_error(r, e, UAPI16_ERROR_EXISTS, EEXIST, NULL, 0); + e = uapi16_error_free(e); + r = uapi16_manifest_writer_create_at(o, out, "dangling", &none, &e); + check_error(r, e, UAPI16_ERROR_EXISTS, EEXIST, NULL, 0); + e = uapi16_error_free(e); + r = uapi16_manifest_generate_at(o, out, "taken", tree, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_EXISTS, EEXIST, NULL, 0); + e = uapi16_error_free(e); + check(!none && !report); + check_eq(uapi16_manifest_writer_create_at(o, out, "later", &w, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, x, &e), 0); + make_file(out, "later", "mine as well"); + r = uapi16_manifest_writer_finish(w, &report, &e); + check_error(r, e, UAPI16_ERROR_EXISTS, EEXIST, NULL, 0); + e = uapi16_error_free(e); + check(!report); + w = uapi16_manifest_writer_free(w); + taken = read_file(out, "later", &taken_size); + check_str(taken, "mine as well"); + + /* UAPI16_ERROR_DUPLICATE: two different file objects of one name. + * A directory and a file that is none are two as well. */ + w = open_writer(o); + check_eq(uapi16_manifest_writer_add_object(w, x, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, other, &e), 0); + r = uapi16_manifest_writer_finish(w, &report, &e); + check_error(r, e, UAPI16_ERROR_DUPLICATE, EEXIST, "x", 0); + e = uapi16_error_free(e); + w = uapi16_manifest_writer_free(w); + w = open_writer(o); + check_eq(uapi16_manifest_writer_add_object(w, directory, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, x, &e), 0); + r = uapi16_manifest_writer_finish(w, &report, &e); + check_error(r, e, UAPI16_ERROR_DUPLICATE, EEXIST, "x", 0); + e = uapi16_error_free(e); + check(!report); + w = uapi16_manifest_writer_free(w); + + /* UAPI16_ERROR_NOT_DIRECTORY: a file that is not a directory is + * where a directory is needed. The top of a tree is a directory, + * whatever its descriptor was opened for. */ + r = uapi16_manifest_generate(o, fd, file, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_NOT_DIRECTORY, ENOTDIR, "", 0); + e = uapi16_error_free(e); + r = uapi16_manifest_generate_at(o, out, "of-a-file", path, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_NOT_DIRECTORY, ENOTDIR, "", 0); + e = uapi16_error_free(e); + check_eq(size_of(fd), 0); + + /* A file object that is not a directory and that one was added + * below fails when the writer finishes, in whatever order they + * came. */ + w = open_writer(o); + check_eq(uapi16_manifest_writer_add_object(w, below, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, x, &e), 0); + r = uapi16_manifest_writer_finish(w, &report, &e); + check_error(r, e, UAPI16_ERROR_NOT_DIRECTORY, ENOTDIR, "x", 0); + e = uapi16_error_free(e); + check(!report); + w = uapi16_manifest_writer_free(w); + + /* UAPI16_ERROR_UNSUPPORTED: a feature that can't be read here, such + * as a DOS attribute of a file system that is not FAT. */ + r = set_features(o, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_FLAG_HIDDEN)); + check_eq(r, 0); + r = uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e); + if (r == 0) { + fprintf(stderr, "skipping UAPI16_ERROR_UNSUPPORTED: the temporary directory is on FAT\n"); + report = uapi16_manifest_report_free(report); + empty(fd); + } else { + check_error(r, e, UAPI16_ERROR_UNSUPPORTED, EOPNOTSUPP, "", CHECK_FEATURE); + check_eq(uapi16_error_feature(e), UAPI16_FEATURE_FLAG_HIDDEN); + check_eq(size_of(fd), 0); + } + e = uapi16_error_free(e); + + /* The UUID and the volume serial number of the file system are no + * such features: a file system need not have them. A manifest that + * records them is written of a tree whose file system has none. Its + * root says nothing of what is not there, and the report counts + * each as a field that was left out. No file system has both. */ + r = set_features(o, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_FS_UUID, UAPI16_FEATURE_FAT_SERIAL)); + check_eq(r, 0); + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e), 0); + { + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = open_reader(fd); + const uapi16_file_object *root = uapi16_reader_root(reader); + uapi16_uuid_t uuid; + uint32_t serial = 77; + int no_uuid, no_serial; + + check_recorded(reader, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_FS_UUID, + UAPI16_FEATURE_FAT_SERIAL)); + no_uuid = uapi16_file_object_fs_uuid(root, &uuid); + no_serial = uapi16_file_object_fat_serial(root, &serial); + check(no_uuid == 0 || no_uuid == -ENODATA); + check(no_serial == 0 || no_serial == -ENODATA); + check(no_uuid == -ENODATA || no_serial == -ENODATA); + check_eq(uapi16_manifest_report_fields_omitted(report), + (uint64_t) (no_uuid == -ENODATA) + (uint64_t) (no_serial == -ENODATA)); + } + report = uapi16_manifest_report_free(report); + empty(fd); + + /* Without the root the manifest is written as well, with a root + * that says nothing of them. Nothing was left out of a root that + * was not read. */ + check_eq(uapi16_manifest_writer_open(o, fd, &w, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, x, &e), 0); + check_eq(uapi16_manifest_writer_finish(w, &report, &e), 0); + check_eq(uapi16_manifest_report_files(report), 1); + check_eq(uapi16_manifest_report_fields_omitted(report), 0); + report = uapi16_manifest_report_free(report); + w = uapi16_manifest_writer_free(w); + { + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = open_reader(fd); + const uapi16_file_object *root = uapi16_reader_root(reader); + uapi16_uuid_t uuid; + uint32_t serial = 77; + + check_recorded(reader, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_FS_UUID, + UAPI16_FEATURE_FAT_SERIAL)); + check_stated(root, features_none()); + check_eq(uapi16_file_object_fs_uuid(root, &uuid), -ENODATA); + check_eq(uapi16_file_object_fat_serial(root, &serial), -ENODATA); + check_eq(serial, 77); + } + empty(fd); + + /* UAPI16_ERROR_MISSING_PARENT: a directory that was not added, where + * the features need what it would record. The root is one. */ + r = set_features(o, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_READ_ONLY)); + check_eq(r, 0); + w = open_writer(o); + check_eq(uapi16_manifest_writer_add_object(w, x, &e), 0); + r = uapi16_manifest_writer_finish(w, &report, &e); + check_error(r, e, UAPI16_ERROR_MISSING_PARENT, ENOENT, "", 0); + e = uapi16_error_free(e); + check(!report); + w = uapi16_manifest_writer_free(w); + + /* With the root added, it is the directory of a file object that + * was not added itself. */ + { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *root = make_object(""); + + w = open_writer(o); + check_eq(uapi16_manifest_writer_add_object(w, root, &e), 0); + check_eq(uapi16_file_object_set_name(below, "parent/x", &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, below, &e), 0); + r = uapi16_manifest_writer_finish(w, &report, &e); + check_error(r, e, UAPI16_ERROR_MISSING_PARENT, ENOENT, "parent", 0); + e = uapi16_error_free(e); + check(!report); + w = uapi16_manifest_writer_free(w); + } +} + +/* + * Makes the directory `name` in `dir_fd` with a file in it that has more in + * its extended attributes than a record of a manifest has room for, and + * returns the directory. Where the file system does not take that much, it + * leaves nothing behind and returns -1, with the error in errno. + */ +static int make_large(int dir_fd, const char *name) { + _cleanup_(freep) char *value = malloc(XATTR_VALUE_SIZE); + _cleanup_(closep) int file = -1; + int tree = make_dir(dir_fd, name), refused; + char attribute[32]; + + make_file(tree, "file", ""); + file = openat(tree, "file", O_RDONLY | O_CLOEXEC); + check(file >= 0 && value); + memset(value, 'x', XATTR_VALUE_SIZE); + for (size_t i = 0; i * XATTR_VALUE_SIZE <= RECORD_MAX; i++) { + snprintf(attribute, sizeof(attribute), "user.large-%03zu", i); + if (fsetxattr(file, attribute, value, XATTR_VALUE_SIZE, 0) < 0) { + refused = errno; + close(tree); + remove_tree(dir_fd, name); + errno = refused; + return -1; + } + } + return tree; +} + +/* + * UAPI16_ERROR_TOO_LARGE: a file with more in its extended attributes than + * a record of a manifest has room for. A file object of a caller has that + * much wherever it is given it, and a writer refuses it and goes on. A + * walk finds such a file where the file system of the temporary directory + * takes that much. Where it does not, as ext4 does not, the file is made + * on the tmpfs of /dev/shm. Where that does not take it either, the walk + * has nothing to test. + */ +static void test_too_large(void) { + _cleanup_(closep) int tree = -1, memory = -1, out = scratch_file(), written = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *records = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *large = make_object("large"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *literal = make_object("literal"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *small = make_object("small"); + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL, *walked = NULL; + _cleanup_(freep) char *value = malloc(RECORD_MAX); + char memory_path[] = MEMORY_TEMPLATE; + size_t before; + int r, walk; + + check(value); + memset(value, 'x', RECORD_MAX); + check_eq(uapi16_file_object_add_user_xattr(large, "large", value, RECORD_MAX), 0); + check_eq(uapi16_file_object_set_user_xattrs(small), 0); + + /* The features of a writer of records need no root. */ + r = set_features(o, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_USER_XATTR)); + check_eq(r, 0); + records = begin_records(o, written); + before = size_of(written); + r = uapi16_writer_file(records, large, &e); + check_error(r, e, UAPI16_ERROR_TOO_LARGE, E2BIG, "large", CHECK_RECORD | CHECK_PROBLEM); + check_str(uapi16_error_problem(e), "recordTooLarge"); + e = uapi16_error_free(e); + check_eq(size_of(written), before); + check_eq(uapi16_writer_file(records, small, &e), 0); + check_eq(uapi16_writer_finish(records, &e), 0); + + /* A file object with that much data in the manifest is too large + * as well. It is not added, and the writer is as it was. */ + check_eq(set_features(o, FEATURES(DEFAULT_FEATURES)), 0); + check_eq(uapi16_file_object_set_target(literal, value, RECORD_MAX), 0); + w = open_writer(o); + r = uapi16_manifest_writer_add_object(w, literal, &e); + check_error(r, e, UAPI16_ERROR_TOO_LARGE, E2BIG, "literal", CHECK_PROBLEM); + check_str(uapi16_error_problem(e), "recordTooLarge"); + e = uapi16_error_free(e); + check_listed(w, 0, 1, 0); + + tree = make_large(tmp_fd, "large"); + if (tree < 0) { + int refused = errno, again; + bool made = mkdtemp(memory_path); + + if (made) + memory = open(memory_path, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (memory >= 0) + tree = make_large(memory, "large"); + if (tree < 0) { + again = errno; + if (made) + check_eq(rmdir(memory_path), 0); + fprintf(stderr, "skipping UAPI16_ERROR_TOO_LARGE of a tree: the temporary " + "directory: %s, ", + strerror(refused)); + fprintf(stderr, "%s: %s\n", MEMORY_DIR, strerror(again)); + return; + } + } + + r = set_features(o, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_USER_XATTR)); + check_eq(r, 0); + walk = uapi16_manifest_generate(o, out, tree, UAPI16_ADD_NONE, &report, &walked); + + /* What is in memory goes before anything is checked, so that a + * check that fails leaves nothing there. */ + if (memory >= 0) { + remove_tree(memory, "large"); + check_eq(rmdir(memory_path), 0); + } + check_error(walk, walked, UAPI16_ERROR_TOO_LARGE, E2BIG, "file", CHECK_PROBLEM); + check_str(uapi16_error_problem(walked), "recordTooLarge"); + check(!report); + check_eq(size_of(out), 0); +} + +/* Writes "deny" or a map of one ID to a file of /proc/self. */ +static bool write_proc(const char *path, const char *text) { + int fd = open(path, O_WRONLY | O_CLOEXEC); + bool written; + + if (fd < 0) + return false; + written = write(fd, text, strlen(text)) == (ssize_t) strlen(text); + close(fd); + return written; +} + +/* Makes a user and a mount namespace for the process, in which it can + * mount. `uid` and `gid` are the IDs it had. Says whether it could. */ +static bool own_namespace(uid_t uid, gid_t gid) { + char map[64]; + + if (unshare(CLONE_NEWUSER | CLONE_NEWNS) < 0) + return false; + snprintf(map, sizeof(map), "0 %u 1", (unsigned) uid); + if (!write_proc("/proc/self/uid_map", map) || !write_proc("/proc/self/setgroups", "deny")) + return false; + snprintf(map, sizeof(map), "0 %u 1", (unsigned) gid); + if (!write_proc("/proc/self/gid_map", map)) + return false; + return mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) == 0; +} + +/* + * What the child of test_loop() does, which returns what it exits with: + * it makes a user and a mount namespace for itself, mounts the tree + * `source` once more at `target` inside it, and walks the tree. + */ +static int loop_in_namespace(const char *source, const char *target, uid_t uid, gid_t gid) { + _cleanup_(closep) int tree = -1, fd = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + int r; + + if (!own_namespace(uid, gid)) + return EXIT_SKIPPED; + /* The descriptors from before are of the mounts of the parent, so + * the tree is opened in this namespace. */ + check_eq(mount(source, target, NULL, MS_BIND, NULL), 0); + tree = open(source, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + check(tree >= 0); + + /* Without crossing it, the mount point is an empty directory. */ + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e), 0); + check_eq(uapi16_manifest_report_directories(report), 3); + check_eq(uapi16_manifest_report_files(report), 1); + report = uapi16_manifest_report_free(report); + empty(fd); + + /* A walk that crosses it comes to a directory that is one of the + * directories it is in, and no manifest is written. */ + r = uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_CROSS_MOUNTS, &report, &e); + check_error(r, e, UAPI16_ERROR_LOOP, ELOOP, "x/again", 0); + check(!report); + check_eq(size_of(fd), 0); + return EXIT_SUCCESS; +} + +/* + * UAPI16_ERROR_LOOP: a mount that shows a directory again inside itself, + * for a walk that crosses mount points. The mount needs a user and a mount + * namespace, which a child makes for itself. Where it can't, there is + * nothing to test. + */ +static void test_loop(void) { + _cleanup_(closep) int tree = make_dir(tmp_fd, "loop"), x = make_dir(tree, "x"); + _cleanup_(closep) int again = make_dir(x, "again"); + char source[PATH_MAX], target[PATH_MAX]; + int status; + pid_t pid; + + make_file(x, "file", ""); + check((size_t) snprintf(source, sizeof(source), "%s/loop", tmp_path) < sizeof(source)); + check((size_t) snprintf(target, sizeof(target), "%s/loop/x/again", tmp_path) < sizeof(target)); + fflush(NULL); + pid = fork(); + check(pid >= 0); + if (pid == 0) { + int code = loop_in_namespace(source, target, getuid(), getgid()); + + fflush(NULL); + _exit(code); + } + check_eq(waitpid(pid, &status, 0), pid); + check(WIFEXITED(status)); + if (WEXITSTATUS(status) == EXIT_SKIPPED) + fprintf(stderr, "skipping UAPI16_ERROR_LOOP: no user namespace that can mount here\n"); + else + check_eq(WEXITSTATUS(status), EXIT_SUCCESS); +} + +/* Checks that the descriptor `fd` is open. */ +static void check_open(int fd) { + check(fcntl(fd, F_GETFD) != -1); +} + +/* + * Descriptors are borrowed. What is made from one has it on loan until it + * is freed, and never closes it: a writer, a writer of records, a reader + * and a directory. The descriptor of the caller is open and works once the + * object finished and once it is freed, with a finish or without one, and + * the library makes no duplicate of it: the process has as many + * descriptors with the object as without. The generate functions have + * theirs for the call. A call that fails to make its object leaves the + * descriptor with the caller. + */ +/* + * What the child of test_no_uuid() does, which returns what it exits with: + * it makes a user and a mount namespace for itself, mounts a ramfs, a file + * system without a UUID, at `target` inside it, and writes the manifest of + * a tree there. + */ +static int no_uuid_in_namespace(const char *target, uid_t uid, gid_t gid) { + _cleanup_(closep) int tree = -1, fd = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + uapi16_uuid_t uuid; + + if (!own_namespace(uid, gid) || mount("none", target, "ramfs", 0, NULL) < 0) + return EXIT_SKIPPED; + tree = open(target, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + check(tree >= 0); + make_file(tree, "file", "hello"); + + check_eq(set_features(o, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_FS_UUID)), 0); + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e), 0); + check_eq(uapi16_manifest_report_files(report), 1); + check_eq(uapi16_manifest_report_fields_omitted(report), 1); + reader = open_reader(fd); + check_recorded(reader, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_FS_UUID)); + check_eq(uapi16_file_object_fs_uuid(uapi16_reader_root(reader), &uuid), -ENODATA); + return EXIT_SUCCESS; +} + +/* A manifest that records the UUID of the file system is written of a tree + * on a file system that has none. Its root says nothing of it, and the + * report counts it as a field that was left out. */ +static void test_no_uuid(void) { + _cleanup_(closep) int target = make_dir(tmp_fd, "no-uuid"); + char path[PATH_MAX]; + int status; + pid_t pid; + + check((size_t) snprintf(path, sizeof(path), "%s/no-uuid", tmp_path) < sizeof(path)); + fflush(NULL); + pid = fork(); + check(pid >= 0); + if (pid == 0) { + int code = no_uuid_in_namespace(path, getuid(), getgid()); + + fflush(NULL); + _exit(code); + } + check_eq(waitpid(pid, &status, 0), pid); + check(WIFEXITED(status)); + if (WEXITSTATUS(status) == EXIT_SKIPPED) + fprintf(stderr, "skipping a file system without a UUID: no user namespace that can mount here\n"); + else + check_eq(WEXITSTATUS(status), EXIT_SUCCESS); +} + +/* The directory on FAT that the tests of the crate use, where there is + * one. */ +#define FAT_DIR "UAPI16_TEST_FAT_DIR" + +/* A new file that is in its directory `dir` under a temporary name until + * its manifest is complete, since nothing gave it a file without a name. A + * child that frees the writer leaves that name alone: the parent finishes, + * and the file has its name. `dir` is empty before and after. */ +static void check_freed_in_a_child(int dir) { + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_object("file"); + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + int status; + pid_t pid; + + check_eq(set_features(o, FEATURES(UAPI16_FEATURE_MODE)), 0); + check_eq(uapi16_file_object_set_mode(file, S_IFREG | 0644), 0); + check_eq(uapi16_manifest_writer_create_at(o, dir, "manifest", &w, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, file, &e), 0); + check_eq(count_entries(dir, "."), 1); + check_eq(faccessat(dir, "manifest", F_OK, 0), -1); + fflush(NULL); + pid = fork(); + check(pid >= 0); + if (pid == 0) { + uapi16_manifest_writer_free(w); + /* Its copies of the two others as well, so that it leaves + * nothing behind that a check for leaks would find. */ + uapi16_file_object_free(file); + uapi16_manifest_options_free(o); + _exit(EXIT_SUCCESS); + } + check_eq(waitpid(pid, &status, 0), pid); + check(WIFEXITED(status)); + check_eq(WEXITSTATUS(status), EXIT_SUCCESS); + check_eq(count_entries(dir, "."), 1); + check_eq(uapi16_manifest_writer_finish(w, &report, &e), 0); + check_eq(uapi16_manifest_report_files(report), 1); + check_eq(count_entries(dir, "."), 1); + check_eq(faccessat(dir, "manifest", F_OK, 0), 0); + check_eq(unlinkat(dir, "manifest", 0), 0); +} + +static bool wipes_on_fork(void); + +/* A tree on FAT, which has a volume serial number and no UUID: a manifest + * that records both has the serial, and the report counts the UUID as a + * field that was left out. */ +static void test_fat(void) { + const char *fat = getenv(FAT_DIR); + _cleanup_(closep) int tree = -1, fd = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + const uapi16_features_t features = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_FS_UUID, + UAPI16_FEATURE_FAT_SERIAL); + static const char freed[] = "uapi16-capi-freed"; + _cleanup_(closep) int out = -1; + const uapi16_file_object *root; + uapi16_uuid_t uuid; + uint32_t serial; + + if (!fat || !*fat) { + fprintf(stderr, "skipping a tree on FAT: " FAT_DIR " names none\n"); + return; + } + tree = open(fat, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + check(tree >= 0); + check_eq(set_features(o, features), 0); + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e), 0); + check_eq(uapi16_manifest_report_fields_omitted(report), 1); + reader = open_reader(fd); + check_recorded(reader, features); + root = uapi16_reader_root(reader); + check_eq(uapi16_file_object_fat_serial(root, &serial), 0); + check_eq(uapi16_file_object_fs_uuid(root, &uuid), -ENODATA); + + /* FAT has no O_TMPFILE, so a new file is in its directory under a + * temporary name until its manifest is complete. A child that + * frees the writer leaves that name alone: the parent finishes, + * and the file has its name. That takes a child that is told. */ + if (!wipes_on_fork()) { + fprintf(stderr, "skipping a new file on FAT: no memory that is wiped in a child here\n"); + return; + } + /* A run that was stopped can have left the directory behind. */ + if (faccessat(tree, freed, F_OK, AT_SYMLINK_NOFOLLOW) == 0) + remove_tree(tree, freed); + out = make_dir(tree, freed); + check_freed_in_a_child(out); + check_eq(unlinkat(tree, freed, AT_REMOVEDIR), 0); +} + +static void test_descriptors(void) { + _cleanup_(closep) int tree = make_tree("descriptors"), out = make_dir(tmp_fd, "descriptors-out"); + _cleanup_(closep) int sub = make_dir(out, "sub"); + _cleanup_(closep) int kept = openat(out, "kept", O_RDWR | O_CREAT | O_CLOEXEC, 0644); + _cleanup_(closep) int records = openat(out, "records", O_RDWR | O_CREAT | O_CLOEXEC, 0644); + _cleanup_(closep) int stream = openat(out, "streamed", O_RDWR | O_CREAT | O_CLOEXEC, 0644); + _cleanup_(closep) int nothing = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *for_partitions = + uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *unordered = + uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *writer = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_directory_freep) uapi16_directory *directory = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_hello("file"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *sized = make_object(""); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *only = NULL; + _cleanup_(freep) char *expected = NULL, *generated = NULL, *streamed = NULL, *listed = NULL; + _cleanup_(freep) char *written = NULL, *recorded = NULL; + size_t before, expected_size, generated_size, streamed_size, listed_size, written_size; + size_t recorded_size, entries, begun, unfinished, held, held_below; + struct stat st; + char first = 0; + int r; + + check(kept >= 0 && records >= 0 && stream >= 0); + r = set_features(for_partitions, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_GPT_LABEL)); + check_eq(r, 0); + check_eq(uapi16_manifest_options_set_order(unordered, UAPI16_ORDER_NONE), 0); + check_eq(uapi16_file_object_set_size(sized, 1), 0); + expected = generate(o, tree, UAPI16_ADD_NONE, &expected_size); + before = open_descriptors(); + + /* The generate functions have their descriptors for the call: the + * directory of the new file, the top of the tree and what the + * manifest is written to are open when it returned, and the process + * has as many descriptors as it had. The caller goes on with them: + * the new file is found through its directory, and the manifest is + * where the descriptor was. */ + check_eq(uapi16_manifest_generate_at(o, out, "m", tree, UAPI16_ADD_NONE, &report, NULL), 0); + report = uapi16_manifest_report_free(report); + check_eq(uapi16_manifest_generate(o, stream, tree, UAPI16_ADD_NONE, &report, NULL), 0); + report = uapi16_manifest_report_free(report); + check_open(out); + check_open(tree); + check_open(stream); + check_eq(open_descriptors(), before); + generated = read_file(out, "m", &generated_size); + check_same(generated, generated_size, expected, expected_size); + check_eq(lseek(stream, 0, SEEK_CUR), (off_t) expected_size); + streamed = read_all(stream, &streamed_size); + check_same(streamed, streamed_size, expected, expected_size); + check_eq(fstatat(tree, "a/file", &st, 0), 0); + + /* One that fails leaves them as well. */ + check_eq(uapi16_manifest_generate_at(o, out, "m", tree, UAPI16_ADD_NONE, &report, NULL), -EEXIST); + check_eq(uapi16_manifest_generate(for_partitions, stream, tree, UAPI16_ADD_NONE, &report, NULL), -EINVAL); + check(!report); + check_open(out); + check_open(tree); + check_open(stream); + check_eq(open_descriptors(), before); + check_eq(size_of(stream), expected_size); + + /* A writer of a new file has the directory of the file on loan. + * Nothing has the name before the writer finishes. Once it + * finished, and once it is freed, the directory is open, and the + * file is found through it. */ + check_eq(uapi16_manifest_writer_create_at(o, out, "listed", &w, NULL), 0); + held = open_descriptors() - before; + check_eq(uapi16_manifest_writer_add_object(w, file, NULL), 0); + check_eq(fstatat(out, "listed", &st, 0), -1); + check_eq(errno, ENOENT); + check_eq(uapi16_manifest_writer_finish(w, NULL, NULL), 0); + check_open(out); + w = uapi16_manifest_writer_free(w); + check_open(out); + check_eq(open_descriptors(), before); + listed = read_file(out, "listed", &listed_size); + check_manifest(listed, listed_size); + + /* Where the name has several components, the library opens the + * directory of the file itself: such a writer holds one descriptor + * more than a writer of a file in the directory of the caller, and + * that one is the library's to close. */ + check_eq(uapi16_manifest_writer_create_at(o, out, "sub/listed", &w, NULL), 0); + held_below = open_descriptors() - before; + check_eq(held_below, held + 1); + check_eq(uapi16_manifest_writer_add_object(w, file, NULL), 0); + check_eq(uapi16_manifest_writer_finish(w, NULL, NULL), 0); + w = uapi16_manifest_writer_free(w); + check_open(out); + check_open(sub); + check_eq(open_descriptors(), before); + check_eq(fstatat(sub, "listed", &st, 0), 0); + check_eq((size_t) st.st_size, listed_size); + + /* A writer that is freed instead leaves its directory open as + * well, and nothing in it. */ + entries = count_entries(tmp_fd, "descriptors-out"); + check_eq(uapi16_manifest_writer_create_at(o, out, "abandoned", &w, NULL), 0); + check_eq(uapi16_manifest_writer_add_object(w, file, NULL), 0); + w = uapi16_manifest_writer_free(w); + check_open(out); + check_eq(open_descriptors(), before); + check_eq(fstatat(out, "abandoned", &st, 0), -1); + check_eq(errno, ENOENT); + check_eq(count_entries(tmp_fd, "descriptors-out"), entries); + + /* What a writer writes its manifest to is the descriptor of the + * caller, and no duplicate of it: the manifest goes where it + * pointed to, and the caller writes on behind it. */ + check_eq(write(kept, "before\n", 7), 7); + check_eq(uapi16_manifest_writer_open(o, kept, &w, NULL), 0); + check_eq(open_descriptors(), before); + check_eq(uapi16_manifest_writer_add_object(w, file, NULL), 0); + check_eq(uapi16_manifest_writer_finish(w, NULL, NULL), 0); + check_open(kept); + w = uapi16_manifest_writer_free(w); + check_open(kept); + check_eq(open_descriptors(), before); + check_eq(lseek(kept, 0, SEEK_CUR), (off_t) (7 + listed_size)); + check_eq(write(kept, "after\n", 6), 6); + written = read_all(kept, &written_size); + check_eq(written_size, 7 + listed_size + 6); + check_eq(memcmp(written, "before\n", 7), 0); + check_eq(memcmp(written + 7, listed, listed_size), 0); + check_eq(memcmp(written + 7 + listed_size, "after\n", 6), 0); + + /* A writer that is freed before it finished leaves its descriptor + * open too, and has written nothing to it. */ + check_eq(uapi16_manifest_writer_open(o, kept, &w, NULL), 0); + check_eq(uapi16_manifest_writer_add_object(w, file, NULL), 0); + w = uapi16_manifest_writer_free(w); + check_open(kept); + check_eq(open_descriptors(), before); + check_eq(size_of(kept), written_size); + check_eq(write(kept, "more\n", 5), 5); + check_eq(size_of(kept), written_size + 5); + + /* The same for a writer of records, which writes every record + * before its call returns. */ + check_eq(uapi16_writer_begin(o, records, NULL, &writer, NULL), 0); + check_eq(open_descriptors(), before); + begun = size_of(records); + check(begun > 0); + check_eq(uapi16_writer_file(writer, file, NULL), 0); + check(size_of(records) > begun); + check_eq(uapi16_writer_finish(writer, NULL), 0); + check_eq(size_of(records), listed_size); + check_open(records); + writer = uapi16_writer_free(writer); + check_open(records); + check_eq(open_descriptors(), before); + check_eq(lseek(records, 0, SEEK_CUR), (off_t) listed_size); + recorded = read_all(records, &recorded_size); + check_same(recorded, recorded_size, listed, listed_size); + + /* One that is freed before it finished leaves its descriptor open, + * with the records it wrote, and the caller writes on behind + * them. */ + check_eq(uapi16_writer_begin(o, nothing, NULL, &writer, NULL), 0); + check_eq(uapi16_writer_file(writer, file, NULL), 0); + unfinished = size_of(nothing); + check(unfinished > 0 && unfinished < listed_size); + writer = uapi16_writer_free(writer); + check_open(nothing); + check_eq(open_descriptors(), before); + check_eq(size_of(nothing), unfinished); + check_eq(write(nothing, "mine", 4), 4); + check_eq(size_of(nothing), unfinished + 4); + empty(nothing); + + /* What a reader reads its manifest from is the descriptor of the + * caller as well. It is open once the reader read the trailer and + * once the reader is freed, and the caller reads it again from its + * start. */ + check_eq(lseek(records, 0, SEEK_SET), 0); + check_eq(uapi16_reader_open(records, &reader, NULL), 0); + check_eq(open_descriptors(), before); + only = next_object(reader, "file"); + check_ends(reader); + check_open(records); + reader = uapi16_reader_free(reader); + check_open(records); + check_eq(open_descriptors(), before); + check_eq(lseek(records, 0, SEEK_SET), 0); + check_eq(read(records, &first, 1), 1); + check_eq(first, RECORD_SEPARATOR); + + /* So it is once a reader is freed that did not read to the end. */ + check_eq(lseek(records, 0, SEEK_SET), 0); + check_eq(uapi16_reader_open(records, &reader, NULL), 0); + reader = uapi16_reader_free(reader); + check_open(records); + check_eq(open_descriptors(), before); + first = 0; + check_eq(pread(records, &first, 1, 0), 1); + check_eq(first, RECORD_SEPARATOR); + + /* The descriptor of a directory is open once the directory is + * freed, and files are found through it. */ + check_eq(uapi16_directory_new(out, UAPI16_DIRECTORY_NONE, &directory, NULL), 0); + check(directory); + check_eq(open_descriptors(), before); + directory = uapi16_directory_free(directory); + check(!directory); + check_open(out); + check_eq(open_descriptors(), before); + check_eq(fstatat(out, "listed", &st, 0), 0); + + /* A call that fails to make its object leaves the descriptor with + * the caller: a name that is taken, options no writer is made for, + * a file that holds no manifest, a root no manifest can hold, and + * a flag that is none. Nothing is written, and no file is made. */ + entries = count_entries(tmp_fd, "descriptors-out"); + check_eq(uapi16_manifest_writer_create_at(o, out, "listed", &w, NULL), -EEXIST); + check_eq(uapi16_manifest_writer_create_at(for_partitions, out, "new", &w, NULL), -EINVAL); + check_eq(uapi16_manifest_writer_create_at(unordered, out, "new", &w, NULL), -EINVAL); + check_eq(uapi16_manifest_writer_open(for_partitions, kept, &w, NULL), -EINVAL); + check_eq(uapi16_manifest_writer_open(unordered, kept, &w, NULL), -EINVAL); + check_eq(uapi16_reader_open(nothing, &reader, NULL), -EBADMSG); + check_eq(uapi16_writer_begin(o, nothing, sized, &writer, NULL), -EBADMSG); + check_eq(uapi16_directory_new(out, UINT64_C(1) << 1, &directory, NULL), -EINVAL); + check(!w && !reader && !writer && !directory); + check_open(out); + check_open(kept); + check_open(nothing); + check_eq(open_descriptors(), before); + check_eq(size_of(nothing), 0); + check_eq(size_of(kept), written_size + 5); + check_eq(count_entries(tmp_fd, "descriptors-out"), entries); + /* Each of them works as it did. */ + check_eq(write(nothing, "mine", 4), 4); + check_eq(write(kept, "last\n", 5), 5); + check_eq(fstatat(out, "kept", &st, 0), 0); + check_eq((size_t) st.st_size, written_size + 10); + + /* The library kept none of its own. */ + check_open(tree); + check_eq(open_descriptors(), before); +} + +/* + * A process that can open no descriptor. What is made from a descriptor of + * the caller needs none of its own, so a reader, a writer of records and a + * directory are made there and work. What a call fails for anyway, it + * fails for there as well, and not for the want of a descriptor. A writer + * that takes nothing more says so, and options with a feature of + * partitions are refused, before either takes a descriptor. None of these + * calls takes a descriptor away from the caller. + */ +static void test_no_descriptors(void) { + _cleanup_(closep) int tree = make_tree("limit"), out = make_dir(tmp_fd, "limit-out"); + _cleanup_(closep) int fd = scratch_file(), manifest = manifest_file(ROOT FILE_OBJECT("a") TRAILER); + _cleanup_(closep) int written = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *for_partitions = + uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *finished = open_writer(o); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *none = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL, *no_reader = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *records = NULL, *no_records = NULL; + _cleanup_(uapi16_directory_freep) uapi16_directory *directory = NULL, *no_directory = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_hello("file"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + struct rlimit limit, few; + int taken[DESCRIPTORS_MAX], r; + size_t n = 0; + + r = set_features(for_partitions, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_GPT_LABEL)); + check_eq(r, 0); + check_eq(uapi16_manifest_writer_finish(finished, NULL, &e), 0); + + /* No descriptor is left from here on: the process may have few, + * and has them all. */ + check_eq(getrlimit(RLIMIT_NOFILE, &limit), 0); + few = limit; + if (few.rlim_cur > DESCRIPTORS_MAX) + few.rlim_cur = DESCRIPTORS_MAX; + check_eq(setrlimit(RLIMIT_NOFILE, &few), 0); + for (;;) { + int next = open("/dev/null", O_RDONLY | O_CLOEXEC); + + if (next < 0) + break; + check(n < ELEMENTSOF(taken)); + taken[n++] = next; + } + check_eq(errno, EMFILE); + + /* A reader reads its manifest from the descriptor of the caller, + * a writer of records writes to it, and a directory is made from + * it: no duplicate is made, which there is no room for. */ + check_eq(uapi16_reader_open(manifest, &reader, &e), 0); + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(got), "a"); + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_END); + reader = uapi16_reader_free(reader); + check_eq(uapi16_writer_begin(o, written, NULL, &records, &e), 0); + check_eq(uapi16_writer_file(records, file, &e), 0); + check_eq(uapi16_writer_finish(records, &e), 0); + records = uapi16_writer_free(records); + check_eq(uapi16_directory_new(tree, UAPI16_DIRECTORY_NONE, &directory, &e), 0); + directory = uapi16_directory_free(directory); + check(!e); + check(size_of(written) > 0); + + /* A call that is not valid fails for that. */ + check_misuse(uapi16_manifest_writer_open(o, -1, &none, &e), &e, EBADF); + check_misuse(uapi16_manifest_writer_open(o, fd, NULL, &e), &e, EINVAL); + check_misuse(uapi16_reader_open(-1, &no_reader, &e), &e, EBADF); + check_misuse(uapi16_reader_open(manifest, NULL, &e), &e, EINVAL); + check_misuse(uapi16_writer_begin(o, -1, NULL, &no_records, &e), &e, EBADF); + check_misuse(uapi16_writer_begin(o, fd, file, &no_records, &e), &e, EINVAL); + check_misuse(uapi16_directory_new(-1, UAPI16_DIRECTORY_NONE, &no_directory, &e), &e, EBADF); + check_misuse(uapi16_directory_new(tree, UINT64_C(1) << 1, &no_directory, &e), &e, EINVAL); + check(!none && !no_reader && !no_records && !no_directory); + + /* Options with a feature of partitions make no writer, whatever + * way it is made, and the error says which feature it is. */ + r = uapi16_manifest_writer_create_at(for_partitions, out, "m", &none, &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_FEATURE); + check_eq(uapi16_error_feature(e), UAPI16_FEATURE_GPT_LABEL); + e = uapi16_error_free(e); + r = uapi16_manifest_writer_open(for_partitions, fd, &none, &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_FEATURE); + check_eq(uapi16_error_feature(e), UAPI16_FEATURE_GPT_LABEL); + e = uapi16_error_free(e); + r = uapi16_manifest_generate_at(for_partitions, out, "m", tree, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_FEATURE); + check_eq(uapi16_error_feature(e), UAPI16_FEATURE_GPT_LABEL); + e = uapi16_error_free(e); + r = uapi16_manifest_generate(for_partitions, fd, tree, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_FEATURE); + check_eq(uapi16_error_feature(e), UAPI16_FEATURE_GPT_LABEL); + e = uapi16_error_free(e); + check(!none && !report); + + /* A writer that takes nothing more says that. */ + check_ended(uapi16_manifest_writer_add_object(finished, file, &e), &e); + check_ended(uapi16_manifest_writer_finish(finished, &report, &e), &e); + check(!report); + + /* None of that gave a descriptor back, and none closed one of the + * caller. */ + check_eq(dup(fd), -1); + check_eq(errno, EMFILE); + check_open(tree); + check_open(out); + check_open(fd); + check_open(manifest); + check_open(written); + + while (n > 0) + check_eq(close(taken[--n]), 0); + check_eq(setrlimit(RLIMIT_NOFILE, &limit), 0); +} + +/* Reads a pipe to its end, slowly, so that whoever writes to it waits. */ +struct reader { + int fd; + char *data; + size_t size; +}; + +static void *read_slowly(void *argument) { + struct reader *reader = argument; + struct timespec pause = { .tv_nsec = 20 * 1000 * 1000 }; + size_t room = 0; + sigset_t all; + + /* The signals of the test are for the thread that writes. */ + sigfillset(&all); + check_eq(pthread_sigmask(SIG_BLOCK, &all, NULL), 0); + for (;;) { + ssize_t n; + + if (reader->size == room) { + room = room ? room * 2 : 4096; + reader->data = realloc(reader->data, room); + check(reader->data); + } + nanosleep(&pause, NULL); + n = read(reader->fd, reader->data + reader->size, room - reader->size); + check(n >= 0); + if (n == 0) + return NULL; + reader->size += (size_t) n; + } +} + +/* Writes data to a pipe and closes it, slowly, so that whoever reads from + * it waits. */ +struct feeder { + int fd; + const char *data; + size_t size; +}; + +static void *feed_slowly(void *argument) { + struct feeder *feeder = argument; + struct timespec pause = { .tv_nsec = 20 * 1000 * 1000 }; + size_t done = 0; + sigset_t all; + + /* The signals of the test are for the thread that reads. */ + sigfillset(&all); + check_eq(pthread_sigmask(SIG_BLOCK, &all, NULL), 0); + while (done < feeder->size) { + size_t piece = feeder->size - done < 16384 ? feeder->size - done : 16384; + ssize_t n; + + nanosleep(&pause, NULL); + n = write(feeder->fd, feeder->data + done, piece); + check(n > 0); + done += (size_t) n; + } + check_eq(close(feeder->fd), 0); + return NULL; +} + +static volatile sig_atomic_t alarms; + +static void count_alarm(int signal) { + (void) signal; + alarms++; +} + +/* The options of a child that a signal kills, where a tool that looks for + * leaks finds them then. */ +static uapi16_manifest_options *volatile killed; + +/* What the process does with its signals: the handler of each, and which + * of them it blocks. */ +struct signals { + struct sigaction actions[NSIG]; + sigset_t mask; +}; + +static void save_signals(struct signals *signals) { + memset(signals, 0, sizeof(*signals)); + for (int i = 1; i < NSIG; i++) + check(sigaction(i, NULL, &signals->actions[i]) == 0 || errno == EINVAL); + check_eq(pthread_sigmask(SIG_SETMASK, NULL, &signals->mask), 0); +} + +/* Checks that the process does with its signals what it did at `before`. */ +static void check_signals(const struct signals *before) { + struct sigaction after; + sigset_t mask; + + for (int i = 1; i < NSIG; i++) { + if (sigaction(i, NULL, &after) < 0) + continue; + check(after.sa_handler == before->actions[i].sa_handler); + check_eq(after.sa_flags, before->actions[i].sa_flags); + } + check_eq(pthread_sigmask(SIG_SETMASK, NULL, &mask), 0); + for (int i = 1; i < NSIG; i++) + check_eq(sigismember(&mask, i), sigismember(&before->mask, i)); +} + +/* Unblocks `signal` for this thread. A process can be started with a signal + * blocked, and has it blocked in every thread and child then. Stores the + * mask of before in `ret_old`, unless that is NULL. */ +static void unblock_signal(int signal, sigset_t *ret_old) { + sigset_t set; + + check_eq(sigemptyset(&set), 0); + check_eq(sigaddset(&set, signal), 0); + check_eq(pthread_sigmask(SIG_UNBLOCK, &set, ret_old), 0); +} + +static void test_signals(void) { + _cleanup_(closep) int tree = make_dir(tmp_fd, "signals"), manifest = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *source = NULL, *piped = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *copy = NULL, *broken = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *expected = NULL; + struct sigaction old_alarm, old_pipe; + struct sigaction count = { .sa_handler = count_alarm }, ignore = { .sa_handler = SIG_IGN }; + struct sigaction by_default = { .sa_handler = SIG_DFL }; + struct itimerval often = { { 0, 1000 }, { 0, 1000 } }, never = { { 0, 0 }, { 0, 0 } }; + struct reader reader = { .fd = -1 }; + struct feeder feeder = { .fd = -1 }; + struct signals before, during; + sigset_t old_mask; + size_t expected_size, files = 0; + pthread_t thread; + int pipe_fds[2], status, r; + sig_atomic_t counted; + char name[32]; + pid_t pid; + + /* A manifest that is larger than a pipe has room for. */ + for (int i = 0; i < 2000; i++) { + snprintf(name, sizeof(name), "file-%04d", i); + make_file(tree, name, "data"); + } + + /* The library leaves the handlers and the mask of the signals as + * they are: here, and in everything below, where it is looked at + * while the test has a handler of its own. */ + save_signals(&before); + expected = generate(o, tree, UAPI16_ADD_NONE, &expected_size); + check(expected_size > 128 * 1024); + check_eq(uapi16_manifest_generate_at(o, tmp_fd, "signals.manifest", tree, UAPI16_ADD_NONE, &report, &e), 0); + report = uapi16_manifest_report_free(report); + check_signals(&before); + check_eq(write(manifest, expected, expected_size), (ssize_t) expected_size); + + /* SIGPIPE is what it is for write(2): a pipe that nobody reads + * kills a process that has the signal at its default. The default + * is what the test can check, so each child sets it first and + * unblocks the signal: the test can be started with the signal + * ignored, as a runner of CI starts it, or blocked, and a child + * has it so too then. This comes before the first thread of the + * test, so that the child has nothing of a thread that a tool + * could take for a leak. */ + check_eq(pipe2(pipe_fds, O_CLOEXEC), 0); + check_eq(close(pipe_fds[0]), 0); + fflush(NULL); + pid = fork(); + check(pid >= 0); + if (pid == 0) { + check_eq(sigaction(SIGPIPE, &by_default, NULL), 0); + unblock_signal(SIGPIPE, NULL); + killed = uapi16_manifest_options_new(); + /* The signal ends the child in the call, so nothing is made + * of what the call returns. */ + (void) uapi16_manifest_generate(killed, pipe_fds[1], tree, UAPI16_ADD_NONE, &report, NULL); + _exit(EXIT_SUCCESS); + } + check_eq(waitpid(pid, &status, 0), pid); + check(WIFSIGNALED(status)); + check_eq(WTERMSIG(status), SIGPIPE); + fflush(NULL); + pid = fork(); + check(pid >= 0); + if (pid == 0) { + check_eq(sigaction(SIGPIPE, &by_default, NULL), 0); + unblock_signal(SIGPIPE, NULL); + killed = uapi16_manifest_options_new(); + (void) uapi16_writer_begin(killed, pipe_fds[1], NULL, &broken, NULL); + _exit(EXIT_SUCCESS); + } + check_eq(waitpid(pid, &status, 0), pid); + check(WIFSIGNALED(status)); + check_eq(WTERMSIG(status), SIGPIPE); + check_eq(close(pipe_fds[1]), 0); + + /* A signal that interrupts a system call does not fail the call: + * the writes to a pipe that is full are made again. The alarms + * have to arrive for that, so SIGALRM is unblocked for as long as + * they are counted: the test can be started with it blocked. */ + unblock_signal(SIGALRM, &old_mask); + check_eq(pipe2(pipe_fds, O_CLOEXEC), 0); + reader.fd = pipe_fds[0]; + check_eq(pthread_create(&thread, NULL, read_slowly, &reader), 0); + check_eq(sigaction(SIGALRM, &count, &old_alarm), 0); + save_signals(&during); + check_eq(setitimer(ITIMER_REAL, &often, NULL), 0); + r = uapi16_manifest_generate(o, pipe_fds[1], tree, UAPI16_ADD_NONE, &report, &e); + check_eq(setitimer(ITIMER_REAL, &never, NULL), 0); + check_signals(&during); + check_eq(sigaction(SIGALRM, &old_alarm, NULL), 0); + check_eq(r, 0); + check(alarms > 0); + check_eq(close(pipe_fds[1]), 0); + check_eq(pthread_join(thread, NULL), 0); + check_eq(close(pipe_fds[0]), 0); + check_same(reader.data, reader.size, expected, expected_size); + free(reader.data); + report = uapi16_manifest_report_free(report); + + /* So are those of a writer of records, which writes the manifest a + * reader reads back to it, record by record. What comes out of the + * pipe is the manifest. */ + check_eq(pipe2(pipe_fds, O_CLOEXEC), 0); + reader = (struct reader) { .fd = pipe_fds[0] }; + source = open_reader(manifest); + counted = alarms; + check_eq(pthread_create(&thread, NULL, read_slowly, &reader), 0); + check_eq(sigaction(SIGALRM, &count, &old_alarm), 0); + save_signals(&during); + check_eq(setitimer(ITIMER_REAL, &often, NULL), 0); + r = uapi16_writer_begin(o, pipe_fds[1], uapi16_reader_root(source), ©, &e); + while (r == 0) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = NULL; + + if (uapi16_reader_next(source, &file, &e) != UAPI16_READ_FILE) + break; + r = uapi16_writer_file(copy, file, &e); + files++; + } + if (r == 0) + r = uapi16_writer_finish(copy, &e); + check_eq(setitimer(ITIMER_REAL, &never, NULL), 0); + check_signals(&during); + check_eq(sigaction(SIGALRM, &old_alarm, NULL), 0); + check_eq(r, 0); + check_eq(files, 2000); + check(!e); + check(alarms > counted); + copy = uapi16_writer_free(copy); + check_eq(close(pipe_fds[1]), 0); + check_eq(pthread_join(thread, NULL), 0); + check_eq(close(pipe_fds[0]), 0); + check_same(reader.data, reader.size, expected, expected_size); + free(reader.data); + source = uapi16_reader_free(source); + + /* And the reads of a reader from a pipe that has nothing yet. */ + check_eq(pipe2(pipe_fds, O_CLOEXEC), 0); + feeder = (struct feeder) { .fd = pipe_fds[1], .data = expected, .size = expected_size }; + counted = alarms; + files = 0; + check_eq(pthread_create(&thread, NULL, feed_slowly, &feeder), 0); + check_eq(sigaction(SIGALRM, &count, &old_alarm), 0); + save_signals(&during); + check_eq(setitimer(ITIMER_REAL, &often, NULL), 0); + r = uapi16_reader_open(pipe_fds[0], &piped, &e); + while (r >= 0) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = NULL; + + r = uapi16_reader_next(piped, &file, &e); + if (r != UAPI16_READ_FILE) + break; + files++; + } + check_eq(setitimer(ITIMER_REAL, &never, NULL), 0); + check_signals(&during); + check_eq(sigaction(SIGALRM, &old_alarm, NULL), 0); + check_eq(r, UAPI16_READ_END); + check_eq(files, 2000); + check(alarms > counted); + check_eq(pthread_join(thread, NULL), 0); + piped = uapi16_reader_free(piped); + check_eq(close(pipe_fds[0]), 0); + check(!e); + check_eq(pthread_sigmask(SIG_SETMASK, &old_mask, NULL), 0); + + /* In a process that ignores the signal, a pipe that nobody reads + * fails with EPIPE. */ + check_eq(pipe2(pipe_fds, O_CLOEXEC), 0); + check_eq(close(pipe_fds[0]), 0); + check_eq(sigaction(SIGPIPE, &ignore, &old_pipe), 0); + save_signals(&during); + r = uapi16_manifest_generate(o, pipe_fds[1], tree, UAPI16_ADD_NONE, &report, &e); + check_error(r, e, UAPI16_ERROR_IO, EPIPE, NULL, 0); + e = uapi16_error_free(e); + r = uapi16_writer_begin(o, pipe_fds[1], NULL, &broken, &e); + check_signals(&during); + check_eq(sigaction(SIGPIPE, &old_pipe, NULL), 0); + check_error(r, e, UAPI16_ERROR_IO, EPIPE, NULL, CHECK_RECORD); + check(!report && !broken); + check_eq(close(pipe_fds[1]), 0); +} + +/* How many file objects the manifest has that the reader of test_fork() + * reads: more than a reader has read of a manifest when it hands out its + * first file object. */ +#define MANY_OBJECTS 6000 + +/* What the parent of test_fork() has when it forks: an object of every + * kind, and those that take nothing more. */ +struct forked { + /* Options, options with a feature of partitions, and options + * without an order. */ + uapi16_manifest_options *o, *for_partitions, *unordered; + uapi16_manifest_writer *created, *opened, *finished; + const uapi16_manifest_report *report; + const uapi16_error *error; + /* A file object with every field, one with none but its data, and + * a root. */ + uapi16_file_object *file, *hello, *root; + /* A reader that hands out file objects, and one that hands out + * signature objects. */ + uapi16_reader *reader, *signing; + uapi16_writer *records, *finished_records; + uapi16_signature *signature; + uapi16_sha256 *sha, *finished_sha; + uapi16_data_check *data, *finished_data; + uapi16_directory *directory; + /* The descriptors the objects have on loan: the tree and the + * directory of the new file, and those of the writer that was + * opened, of the writer of records and of the two readers. */ + int tree, out, opened_fd, records_fd, manifest_fd, signing_fd; +}; + +/* What a child can do with the objects of its parent: nothing but read + * what can't fail, and free. */ +static void check_child(const struct forked *p) { + static const uapi16_uuid_t uuid = { .bytes = { 1 } }; + _cleanup_(closep) int fd = scratch_file(), written = scratch_file(); + _cleanup_(closep) int manifest = + manifest_file(ROOT FILE_OBJECT("mine") SIGNATURE_OBJECT("pkcs7") TRAILER); + _cleanup_(closep) int opened = -7; + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *mine = + uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *none = NULL, *writer = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *no_report = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *no_reader = NULL, *reader = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *no_records = NULL, *records = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *no_object = NULL, *object = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *own = NULL; + _cleanup_(uapi16_signature_freep) uapi16_signature *no_signature = NULL, *signature = NULL; + _cleanup_(uapi16_directory_freep) uapi16_directory *no_directory = NULL, *directory = NULL; + _cleanup_(uapi16_data_check_freep) uapi16_data_check *no_data = NULL, *data = NULL; + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *sha = NULL; + uapi16_sha256_digest_t hash = { .bytes = { 0 } }; + uapi16_uuid_t read_uuid = { .bytes = { 0 } }; + uapi16_features_t features = FEATURES(UAPI16_FEATURE_MTIME); + uint64_t number = 77, length = 77, offset = 7; + uapi16_inode_token_t token = 77; + uint32_t small = 77, stated = 77, set = 77; + size_t count = 77, size = 77, begun; + uapi16_file_object *theirs = p->hello; + const char *contents_file = NULL; + uapi16_signature *their_signature = p->signature; + const char *name = NULL; + const void *value = NULL; + uapi16_error *e = NULL; + int r; + + /* A call is checked for what it is given first. One that is not + * valid fails for that here as it does in the parent. */ + check_misuse(uapi16_manifest_writer_add_object(NULL, p->hello, &e), &e, EINVAL); + check_misuse(uapi16_manifest_writer_add_object(p->created, NULL, &e), &e, EINVAL); + check_misuse(uapi16_manifest_writer_create_at(p->o, p->out, "", &none, &e), &e, EINVAL); + check_misuse(uapi16_manifest_writer_create_at(p->o, p->out, "child", NULL, &e), &e, EINVAL); + check_misuse(uapi16_manifest_writer_create_at(p->o, -1, "child", &none, &e), &e, EBADF); + check_misuse(uapi16_manifest_writer_open(p->o, -1, &none, &e), &e, EBADF); + r = uapi16_manifest_generate_at(p->o, p->out, "child", -1, UAPI16_ADD_NONE, &no_report, &e); + check_misuse(r, &e, EBADF); + r = uapi16_manifest_generate(p->o, fd, p->tree, UINT64_C(1) << 40, &no_report, &e); + check_misuse(r, &e, EINVAL); + check_eq(set_features(p->o, FEATURES(64 * UAPI16_FEATURES_WORDS)), -EINVAL); + /* So is a set with a size no set has, in the calls that take one + * and in those that fill one. */ + features.size = sizeof(features) + 1; + check_eq(uapi16_manifest_options_set_features(p->o, &features), -EINVAL); + check_eq(uapi16_file_object_retain_features(p->file, &features), -EINVAL); + check_eq(uapi16_file_object_stated_features(p->file, &features), -EINVAL); + check_eq(uapi16_reader_features(p->reader, &features), -EINVAL); + features.size = UINT64_MAX; + check_eq(uapi16_manifest_options_set_features(p->o, &features), -E2BIG); + check_eq(uapi16_file_object_retain_features(p->file, &features), -E2BIG); + check_eq(uapi16_file_object_stated_features(p->file, &features), -E2BIG); + check_eq(uapi16_reader_features(p->reader, &features), -E2BIG); + features.size = sizeof(features); + check_eq(uapi16_manifest_options_set_order(p->o, 2), -EINVAL); + check_eq(uapi16_manifest_options_set_sync(NULL, true), -EINVAL); + check_misuse(uapi16_reader_open(-1, &no_reader, &e), &e, EBADF); + check_misuse(uapi16_reader_next(p->reader, NULL, &e), &e, EINVAL); + check_misuse(uapi16_reader_next_signature(p->signing, NULL, &e), &e, EINVAL); + check_misuse(uapi16_reader_require_order(p->reader, UAPI16_ORDER_NONE, &e), &e, EINVAL); + check_eq(uapi16_reader_signed_len(p->signing, NULL), -EINVAL); + check_misuse(uapi16_writer_begin(p->o, -1, NULL, &no_records, &e), &e, EBADF); + check_misuse(uapi16_writer_begin(p->o, fd, p->hello, &no_records, &e), &e, EINVAL); + check_misuse(uapi16_writer_file(p->records, NULL, &e), &e, EINVAL); + check_misuse(uapi16_writer_signature(p->records, NULL, &e), &e, EINVAL); + check_misuse(uapi16_writer_finish(NULL, &e), &e, EINVAL); + check_eq(uapi16_signature_set_key(NULL, "k", 1), -EINVAL); + check_eq(uapi16_file_object_set_type(p->file, 0), -EINVAL); + check_eq(uapi16_file_object_set_read_only(p->file, 3), -EINVAL); + check_eq(uapi16_file_object_set_sha256(p->file, NULL), -EINVAL); + check_eq(uapi16_file_object_set_user_name(p->file, NULL), -EINVAL); + check_eq(uapi16_file_object_add_user_xattr(p->file, NULL, "v", 1), -EINVAL); + check_eq(uapi16_file_object_add_user_xattr(p->file, "k", NULL, 1), -EINVAL); + check_eq(uapi16_file_object_mode(p->file, NULL), -EINVAL); + check_eq(uapi16_file_object_set_name(p->file, "a//b", NULL), -EINVAL); + check_eq(uapi16_file_object_set_contents_file(p->file, NULL, NULL), -EINVAL); + check_eq(uapi16_data_check_new(p->file, NULL), -EINVAL); + check_misuse(uapi16_data_check_update(p->data, NULL, 1, &e), &e, EINVAL); + check_eq(uapi16_sha256_update(p->sha, NULL, 1), -EINVAL); + check_eq(uapi16_sha256_finish(p->sha, NULL), -EINVAL); + check_misuse(uapi16_directory_new(-1, UAPI16_DIRECTORY_NONE, &no_directory, &e), &e, EBADF); + check_misuse(uapi16_directory_new(p->tree, UINT64_C(1) << 1, &no_directory, &e), &e, EINVAL); + check_misuse(uapi16_directory_open_data(p->directory, NULL, &opened, &offset, &e), &e, EINVAL); + check_misuse(uapi16_directory_open_data(p->directory, p->hello, NULL, &offset, &e), &e, EINVAL); + check_misuse(uapi16_directory_open_data(p->directory, p->hello, &opened, NULL, &e), &e, EINVAL); + check_eq(retain_features(p->file, FEATURES(NO_FEATURE)), -EINVAL); + check_misuse(uapi16_data_check_update_zeros(NULL, 1, &e), &e, EINVAL); + check_eq(uapi16_sha256_update_zeros(NULL, 1), -EINVAL); + check_eq(uapi16_error_record(p->error, NULL), -EINVAL); + + /* So does one whose `reterr` points to something, here to the + * error of the parent, which stays where it is. */ + e = (uapi16_error *) p->error; + check_eq(uapi16_manifest_writer_add_object(p->created, p->hello, &e), -EINVAL); + check_eq(uapi16_manifest_writer_finish(p->finished, &no_report, &e), -EINVAL); + check_eq(uapi16_manifest_writer_create_at(p->o, p->out, "child", &none, &e), -EINVAL); + check_eq(uapi16_manifest_generate(p->for_partitions, fd, p->tree, UAPI16_ADD_NONE, &no_report, &e), -EINVAL); + check_eq(uapi16_reader_next(p->reader, &no_object, &e), -EINVAL); + check_eq(uapi16_writer_file(p->records, p->hello, &e), -EINVAL); + check_eq(uapi16_file_object_set_name(p->file, "other", &e), -EINVAL); + check_eq(uapi16_data_check_update(p->data, "lo", 2, &e), -EINVAL); + check_eq(uapi16_data_check_update_zeros(p->data, 2, &e), -EINVAL); + check_eq(uapi16_directory_open_data(p->directory, p->hello, &opened, &offset, &e), -EINVAL); + check(e == p->error); + e = NULL; + + /* Then for the process: options fail for it, however they are + * used. */ + check_eq(set_features(p->o, FEATURES(DEFAULT_FEATURES)), -ECHILD); + check_eq(set_features(p->o, features_none()), -ECHILD); + check_eq(uapi16_manifest_options_set_order(p->o, UAPI16_ORDER_CODEPOINT), -ECHILD); + check_eq(uapi16_manifest_options_set_order(p->o, UAPI16_ORDER_NONE), -ECHILD); + check_eq(uapi16_manifest_options_set_sync(p->o, true), -ECHILD); + check_misuse(uapi16_manifest_writer_create_at(p->o, p->out, "child", &none, &e), &e, ECHILD); + check_misuse(uapi16_manifest_writer_open(p->o, fd, &none, &e), &e, ECHILD); + r = uapi16_manifest_generate_at(p->o, p->out, "child", p->tree, UAPI16_ADD_NONE, &no_report, &e); + check_misuse(r, &e, ECHILD); + check_misuse(uapi16_manifest_generate(p->o, fd, p->tree, UAPI16_ADD_NONE, &no_report, &e), &e, ECHILD); + check_misuse(uapi16_writer_begin(p->o, fd, NULL, &no_records, &e), &e, ECHILD); + + /* The features of the options are looked at after the process as + * well: options with a feature of partitions fail for the process + * here, and say nothing of the feature. */ + r = uapi16_manifest_writer_create_at(p->for_partitions, p->out, "child", &none, &e); + check_misuse(r, &e, ECHILD); + check_misuse(uapi16_manifest_writer_open(p->for_partitions, fd, &none, &e), &e, ECHILD); + r = uapi16_manifest_generate_at(p->for_partitions, p->out, "child", p->tree, UAPI16_ADD_NONE, &no_report, &e); + check_misuse(r, &e, ECHILD); + r = uapi16_manifest_generate(p->for_partitions, fd, p->tree, UAPI16_ADD_NONE, &no_report, &e); + check_misuse(r, &e, ECHILD); + + /* So is their order: options without one, which the functions that + * sort refuse in the parent, fail for the process here. */ + r = uapi16_manifest_writer_create_at(p->unordered, p->out, "child", &none, &e); + check_misuse(r, &e, ECHILD); + check_misuse(uapi16_manifest_writer_open(p->unordered, fd, &none, &e), &e, ECHILD); + r = uapi16_manifest_generate_at(p->unordered, p->out, "child", p->tree, UAPI16_ADD_NONE, &no_report, &e); + check_misuse(r, &e, ECHILD); + r = uapi16_manifest_generate(p->unordered, fd, p->tree, UAPI16_ADD_NONE, &no_report, &e); + check_misuse(r, &e, ECHILD); + check_misuse(uapi16_writer_begin(p->unordered, fd, NULL, &no_records, &e), &e, ECHILD); + check(!none && !no_report && !no_records); + + /* A writer fails for the process, and only then for what it is: + * one that takes nothing more fails for the process here. */ + check_misuse(uapi16_manifest_writer_add_object(p->created, p->hello, &e), &e, ECHILD); + check_misuse(uapi16_manifest_writer_finish(p->created, &no_report, &e), &e, ECHILD); + check_misuse(uapi16_manifest_writer_add_object(p->opened, p->hello, &e), &e, ECHILD); + check_misuse(uapi16_manifest_writer_finish(p->opened, &no_report, &e), &e, ECHILD); + check_misuse(uapi16_manifest_writer_add_object(p->finished, p->hello, &e), &e, ECHILD); + check_misuse(uapi16_manifest_writer_finish(p->finished, &no_report, &e), &e, ECHILD); + check_eq(uapi16_manifest_writer_add_object(p->created, p->hello, NULL), -ECHILD); + check(!no_report); + + /* A reader reads nothing here, whatever comes next in its + * manifest: a file object, a signature object, or a call that is + * too early for one. */ + check_misuse(uapi16_reader_require_order(p->reader, UAPI16_ORDER_CODEPOINT, &e), &e, ECHILD); + check_misuse(uapi16_reader_check_validity(p->reader, 0, &e), &e, ECHILD); + check_misuse(uapi16_reader_next(p->reader, &no_object, &e), &e, ECHILD); + check_misuse(uapi16_reader_next(p->signing, &no_object, &e), &e, ECHILD); + check_misuse(uapi16_reader_next_signature(p->signing, &no_signature, &e), &e, ECHILD); + check_misuse(uapi16_reader_next_signature(p->reader, &no_signature, &e), &e, ECHILD); + check_eq(uapi16_reader_signed_len(p->signing, &length), -ECHILD); + check_eq(uapi16_reader_signed_len(p->reader, &length), -ECHILD); + check_eq(length, 77); + check(!no_object && !no_signature); + + /* A writer of records writes nothing here. */ + check_misuse(uapi16_writer_file(p->records, p->hello, &e), &e, ECHILD); + check_misuse(uapi16_writer_signature(p->records, p->signature, &e), &e, ECHILD); + check_misuse(uapi16_writer_finish(p->records, &e), &e, ECHILD); + check_misuse(uapi16_writer_file(p->finished_records, p->hello, &e), &e, ECHILD); + check_misuse(uapi16_writer_signature(p->finished_records, p->signature, &e), &e, ECHILD); + check_misuse(uapi16_writer_finish(p->finished_records, &e), &e, ECHILD); + + /* A signature object is not changed here. */ + check_eq(uapi16_signature_set_key(p->signature, "other", 5), -ECHILD); + check_eq(uapi16_signature_set_key(p->signature, NULL, 0), -ECHILD); + check_eq(uapi16_signature_set_data(p->signature, "data", 4), -ECHILD); + check_eq(uapi16_signature_set_data(p->signature, NULL, 0), -ECHILD); + + /* A file object is neither changed nor read here by a function + * that can fail, and such a getter stores nothing. */ + check_misuse(uapi16_file_object_set_name(p->file, "other", &e), &e, ECHILD); + check_eq(uapi16_file_object_set_type(p->file, S_IFDIR), -ECHILD); + check_eq(uapi16_file_object_set_mode(p->file, 0600), -ECHILD); + check_eq(uapi16_file_object_mode(p->file, &small), -ECHILD); + check_eq(uapi16_file_object_set_uid(p->file, 9), -ECHILD); + check_eq(uapi16_file_object_uid(p->file, &small), -ECHILD); + check_eq(uapi16_file_object_set_gid(p->file, 9), -ECHILD); + check_eq(uapi16_file_object_gid(p->file, &small), -ECHILD); + check_eq(uapi16_file_object_set_user_name(p->file, "other"), -ECHILD); + check_eq(uapi16_file_object_set_group_name(p->file, "other"), -ECHILD); + check_eq(uapi16_file_object_set_mtime_nsec(p->file, 9), -ECHILD); + check_eq(uapi16_file_object_mtime_nsec(p->file, &number), -ECHILD); + check_eq(uapi16_file_object_set_size(p->file, 9), -ECHILD); + check_eq(uapi16_file_object_size(p->file, &number), -ECHILD); + check_eq(uapi16_file_object_set_sha256(p->file, &hash), -ECHILD); + check_eq(uapi16_file_object_sha256(p->file, &hash), -ECHILD); + check_eq(uapi16_file_object_set_major(p->file, 9), -ECHILD); + check_eq(uapi16_file_object_major(p->file, &number), -ECHILD); + check_eq(uapi16_file_object_set_minor(p->file, 9), -ECHILD); + check_eq(uapi16_file_object_minor(p->file, &number), -ECHILD); + check_eq(uapi16_file_object_set_inode_token(p->file, 9), -ECHILD); + check_eq(uapi16_file_object_inode_token(p->file, &token), -ECHILD); + check_eq(uapi16_file_object_contents_file(p->file, &contents_file, &number), -ECHILD); + check(!contents_file); + check_eq(uapi16_file_object_set_user_xattrs(p->file), -ECHILD); + check_eq(uapi16_file_object_add_user_xattr(p->file, "other", "v", 1), -ECHILD); + check_eq(uapi16_file_object_user_xattrs(p->file, &count), -ECHILD); + check_eq(uapi16_file_object_user_xattr(p->file, 0, &name, &value, &size), -ECHILD); + check_eq(uapi16_file_object_set_read_only(p->file, UAPI16_READ_ONLY_YES), -ECHILD); + check_eq(uapi16_file_object_set_inode_flags(p->file, 0, 0), -ECHILD); + check_eq(uapi16_file_object_inode_flags(p->file, &stated, &set), -ECHILD); + check_eq(uapi16_file_object_set_dos_attributes(p->file, 0, 0), -ECHILD); + check_eq(uapi16_file_object_dos_attributes(p->file, &stated, &set), -ECHILD); + check_eq(uapi16_file_object_set_target(p->file, "other", 5), -ECHILD); + check_misuse(uapi16_file_object_set_contents_file(p->file, "other", &e), &e, ECHILD); + check_eq(uapi16_file_object_set_fs_label(p->file, "other"), -ECHILD); + check_eq(uapi16_file_object_set_fs_uuid(p->file, &uuid), -ECHILD); + check_eq(uapi16_file_object_fs_uuid(p->file, &read_uuid), -ECHILD); + check_eq(uapi16_file_object_set_fat_serial(p->file, 9), -ECHILD); + check_eq(uapi16_file_object_fat_serial(p->file, &small), -ECHILD); + check_eq(uapi16_file_object_stated_features(p->file, &features), -ECHILD); + check_eq(uapi16_file_object_retain_features(p->file, &features), -ECHILD); + check_eq(uapi16_reader_features(p->reader, &features), -ECHILD); + check_same_features(features, FEATURES(UAPI16_FEATURE_MTIME)); + check_misuse(uapi16_file_object_check_validity(p->file, 0, &e), &e, ECHILD); + check_eq(retain_features(p->file, features_none()), -ECHILD); + check_eq(retain_features(p->file, FEATURES(UAPI16_FEATURE_MODE)), -ECHILD); + check_eq(small, 77); + check_eq(number, 77); + check_eq(token, 77); + check_eq(count, 77); + check_eq(size, 77); + check(stated == 77 && set == 77 && !name && !value && hash.bytes[0] == 0 && read_uuid.bytes[0] == 0); + + /* One without a field fails for the process too, and not for the + * field, and so does the root of a reader. */ + check_eq(uapi16_file_object_mode(p->hello, &small), -ECHILD); + check_eq(uapi16_file_object_inode_token(p->hello, &token), -ECHILD); + check_eq(uapi16_file_object_user_xattrs(p->hello, &count), -ECHILD); + check_eq(uapi16_file_object_mode(uapi16_reader_root(p->reader), &small), -ECHILD); + check_eq(uapi16_file_object_set_type(p->root, S_IFDIR), -ECHILD); + + /* No check is made of the data of such an object, a check takes no + * data, and a hash is not computed on. */ + check_eq(uapi16_data_check_new(p->hello, &no_data), -ECHILD); + check_misuse(uapi16_data_check_update(p->data, "lo", 2, &e), &e, ECHILD); + check_misuse(uapi16_data_check_finish(p->data, &number, &e), &e, ECHILD); + check_misuse(uapi16_data_check_update(p->finished_data, "lo", 2, &e), &e, ECHILD); + check_misuse(uapi16_data_check_finish(p->finished_data, &number, &e), &e, ECHILD); + check_eq(uapi16_sha256_update(p->sha, "lo", 2), -ECHILD); + check_eq(uapi16_sha256_finish(p->sha, &hash), -ECHILD); + check_eq(uapi16_sha256_update(p->finished_sha, "lo", 2), -ECHILD); + check_eq(uapi16_sha256_finish(p->finished_sha, &hash), -ECHILD); + check_misuse(uapi16_data_check_update_zeros(p->data, 2, &e), &e, ECHILD); + check_misuse(uapi16_data_check_update_zeros(p->finished_data, 2, &e), &e, ECHILD); + check_eq(uapi16_sha256_update_zeros(p->sha, 2), -ECHILD); + check_eq(uapi16_sha256_update_zeros(p->finished_sha, 2), -ECHILD); + check(!no_data && number == 77 && token == 77 && hash.bytes[0] == 0); + + /* What can't fail gives what the object has, as in the parent. */ + check_str(uapi16_file_object_name(p->file), "dir/file"); + check_eq(uapi16_file_object_type(p->file), S_IFREG); + check_str(uapi16_file_object_user_name(p->file), "user"); + check_str(uapi16_file_object_group_name(p->file), "group"); + check_eq(uapi16_file_object_read_only(p->file), UAPI16_READ_ONLY_NO); + check_eq(uapi16_file_object_data_location(p->file), UAPI16_DATA_LOCATION_LITERAL); + value = uapi16_file_object_literal(p->file, &size); + check_same(value, size, "target", 6); + check_str(uapi16_file_object_fs_label(p->file), "label"); + check(uapi16_file_object_has_stated_feature(p->file, UAPI16_FEATURE_MODE)); + check_str(uapi16_signature_mechanism(p->signature), "openpgp"); + value = uapi16_signature_key(p->signature, &size); + check_same(value, size, "key", 3); + check(!uapi16_signature_data(p->signature, &size)); + check_eq(size, 0); + check_str(uapi16_file_object_name(uapi16_reader_root(p->reader)), ""); + check(uapi16_reader_has_feature(p->reader, UAPI16_FEATURE_MODE)); + check(!uapi16_reader_has_feature(p->reader, UAPI16_FEATURE_MTIME)); + check_eq(uapi16_reader_order(p->reader), UAPI16_ORDER_CODEPOINT); + check_eq(uapi16_name_compare("a/x", "a-b"), UAPI16_NAME_BEFORE); + check_str(uapi16_feature_name(UAPI16_FEATURE_MODE), "mode"); + check_eq(uapi16_feature_from_name("mode"), UAPI16_FEATURE_MODE); + /* A set of features is the program's own and no object of the + * library: its calls and the two that fill one from the library + * work as in the parent. */ + check_eq(uapi16_features_default(&features), 0); + check_same_features(features, FEATURES(DEFAULT_FEATURES)); + check_eq(uapi16_features_add(&features, UAPI16_FEATURE_MTIME), 0); + check_eq(uapi16_features_remove(&features, UAPI16_FEATURE_MODE), 0); + check(uapi16_features_has(&features, UAPI16_FEATURE_MTIME)); + check_eq(uapi16_features_next(&features, UAPI16_FEATURE_NONE), UAPI16_FEATURE_UID); + check_eq(uapi16_features_known(&features), 0); + check_same_features(features, EVERY_FEATURE); + + /* Reports and errors are read as in the parent. */ + check_eq(uapi16_manifest_report_files(p->report), 3); + check_eq(uapi16_error_kind(p->error), UAPI16_ERROR_INVALID_ARGUMENT); + check_eq(uapi16_error_errno(p->error), EINVAL); + check_eq(uapi16_error_name_problem(p->error), UAPI16_NAME_PROBLEM_EMPTY_COMPONENT); + check_eq(uapi16_error_record(p->error, &number), -ENODATA); + + /* What the child makes itself is its own, and works. */ + check_eq(uapi16_manifest_generate_at(mine, p->out, "child", p->tree, UAPI16_ADD_NONE, &no_report, &e), 0); + check_eq(uapi16_manifest_report_files(no_report), 3); + check_eq(uapi16_file_object_new("mine", &object, &e), 0); + check_eq(uapi16_file_object_set_size(object, 2), 0); + check_eq(uapi16_signature_new("pkcs7", &signature), 0); + check_eq(uapi16_signature_set_key(signature, "mine", 4), 0); + check_eq(uapi16_data_check_new(object, &data), 0); + check_eq(uapi16_data_check_update(data, "ok", 2, &e), 0); + check_eq(uapi16_data_check_finish(data, &number, &e), 0); + check_eq(number, 2); + sha = uapi16_sha256_new(); + check_eq(uapi16_sha256_update(sha, "abc", 3), 0); + check_eq(uapi16_sha256_finish(sha, &hash), 0); + check_hash(&hash, SHA256_OF_ABC); + check_eq(uapi16_manifest_writer_open(mine, fd, &writer, &e), 0); + check_eq(uapi16_writer_begin(mine, written, NULL, &records, &e), 0); + check_eq(uapi16_reader_open(manifest, &reader, &e), 0); + check_eq(uapi16_directory_new(p->out, UAPI16_DIRECTORY_NONE, &directory, &e), 0); + check_eq(uapi16_file_object_new("child", &own, &e), 0); + check(!e); + + /* An object of the parent is none for a reader of the child to + * fill: the read fails before it reads anything, and leaves the + * object where it is and as it is. The reader hands out its first + * file object after that, and its first signature object. */ + check_misuse(uapi16_reader_next(reader, &theirs, &e), &e, ECHILD); + check(theirs == p->hello); + check_str(uapi16_file_object_name(p->hello), "hello"); + check_eq(uapi16_reader_next(reader, &no_object, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(no_object), "mine"); + check_eq(uapi16_reader_next(reader, &no_object, &e), UAPI16_READ_SIGNATURES); + check_misuse(uapi16_reader_next_signature(reader, &their_signature, &e), &e, ECHILD); + check(their_signature == p->signature); + check_str(uapi16_signature_mechanism(p->signature), "openpgp"); + check_eq(uapi16_reader_next_signature(reader, &no_signature, &e), UAPI16_READ_SIGNATURE); + check_str(uapi16_signature_mechanism(no_signature), "pkcs7"); + check_eq(uapi16_reader_next_signature(reader, &no_signature, &e), UAPI16_READ_END); + + /* A directory of the parent opens nothing here, and a directory of + * the child opens nothing for an object of the parent. With an + * object of the child it opens the manifest the child wrote. */ + check_misuse(uapi16_directory_open_data(p->directory, own, &opened, &offset, &e), &e, ECHILD); + check_misuse(uapi16_directory_open_data(directory, p->hello, &opened, &offset, &e), &e, ECHILD); + check_eq(opened, -7); + check_eq(offset, 7); + check_eq(uapi16_directory_open_data(directory, own, &opened, &offset, &e), 0); + check(opened >= 0); + check_eq(offset, 0); + check(!e); + + /* An object of the parent is none for a writer of the child to + * take either: a file object and a root for a writer, a file + * object and a signature object for a writer of records, and a + * root for a writer of records to begin with. Nothing is written + * for them. */ + begun = size_of(written); + check_misuse(uapi16_manifest_writer_add_object(writer, p->hello, &e), &e, ECHILD); + check_misuse(uapi16_manifest_writer_add_object(writer, p->root, &e), &e, ECHILD); + check_misuse(uapi16_writer_file(records, p->hello, &e), &e, ECHILD); + check_misuse(uapi16_writer_signature(records, p->signature, &e), &e, ECHILD); + check_misuse(uapi16_writer_begin(mine, fd, p->root, &no_records, &e), &e, ECHILD); + check_eq(uapi16_manifest_writer_add_object(writer, p->hello, NULL), -ECHILD); + check_eq(uapi16_writer_file(records, p->hello, NULL), -ECHILD); + check(!no_records); + check_eq(size_of(written), begun); + check_eq(size_of(fd), 0); + check_eq(uapi16_manifest_writer_add_object(writer, object, &e), 0); + check_eq(uapi16_writer_file(records, object, &e), 0); + check_eq(uapi16_writer_signature(records, signature, &e), 0); + check(!e); + + /* The object a call is given is looked at for its process before + * the writer is for what it is: one of the child that is finished + * fails for an object of the parent as one that is not does. With + * an object of the child it says that it takes nothing more. */ + check_eq(uapi16_manifest_writer_finish(writer, NULL, &e), 0); + check_eq(uapi16_writer_finish(records, &e), 0); + check_misuse(uapi16_manifest_writer_add_object(writer, p->hello, &e), &e, ECHILD); + check_misuse(uapi16_writer_file(records, p->hello, &e), &e, ECHILD); + check_misuse(uapi16_writer_signature(records, p->signature, &e), &e, ECHILD); + check_ended(uapi16_manifest_writer_add_object(writer, object, &e), &e); + check_ended(uapi16_writer_file(records, object, &e), &e); + check_ended(uapi16_writer_signature(records, signature, &e), &e); + + /* Freeing works, and neither writes nor links anything. */ + check(!uapi16_manifest_writer_free(p->created)); + check(!uapi16_manifest_writer_free(p->opened)); + check(!uapi16_manifest_writer_free(p->finished)); + check(!uapi16_manifest_options_free(p->o)); + check(!uapi16_manifest_options_free(p->for_partitions)); + check(!uapi16_manifest_report_free((uapi16_manifest_report *) p->report)); + check(!uapi16_error_free((uapi16_error *) p->error)); + check(!uapi16_file_object_free(p->file)); + check(!uapi16_file_object_free(p->hello)); + check(!uapi16_file_object_free(p->root)); + check(!uapi16_reader_free(p->reader)); + check(!uapi16_reader_free(p->signing)); + check(!uapi16_writer_free(p->records)); + check(!uapi16_writer_free(p->finished_records)); + check(!uapi16_signature_free(p->signature)); + check(!uapi16_sha256_free(p->sha)); + check(!uapi16_sha256_free(p->finished_sha)); + check(!uapi16_data_check_free(p->data)); + check(!uapi16_data_check_free(p->finished_data)); + check(!uapi16_directory_free(p->directory)); + + /* The descriptors those objects had on loan are open here once the + * objects are freed: nothing closed the copy the child has of + * them. */ + check_open(p->tree); + check_open(p->out); + check_open(p->opened_fd); + check_open(p->records_fd); + check_open(p->manifest_fd); + check_open(p->signing_fd); + check_open(null_fd); +} + +static void test_fork(void) { + static const uapi16_uuid_t uuid = { .bytes = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } }; + _cleanup_(closep) int tree = make_tree("fork"), out = make_dir(tmp_fd, "fork-out"); + _cleanup_(closep) int fd = openat(out, "opened", O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644); + _cleanup_(closep) int written = openat(out, "records", O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644); + _cleanup_(closep) int manifest = scratch_file(); + _cleanup_(closep) int with_signature = + manifest_file(ROOT FILE_OBJECT("a") SIGNATURE_OBJECT("openpgp") TRAILER); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *for_partitions = + uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *unordered = + uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *created = NULL, *opened = NULL; + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *finished = open_writer(o); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *none = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *first = NULL, *second = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL, *error = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_object("dir/file"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *hello = make_hello("hello"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *root = make_object(""); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = NULL, *no_object = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL, *signing = NULL, *written_back = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *records = NULL, *finished_records = NULL; + _cleanup_(uapi16_signature_freep) uapi16_signature *signature = NULL, *read_signature = NULL; + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *sha = uapi16_sha256_new(); + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *finished_sha = uapi16_sha256_new(); + _cleanup_(uapi16_data_check_freep) uapi16_data_check *data = NULL, *finished_data = NULL; + _cleanup_(uapi16_directory_freep) uapi16_directory *directory = NULL; + _cleanup_(freep) char *expected = NULL, *made = NULL, *streamed = NULL, *child = NULL; + size_t expected_size, made_size, streamed_size, child_size, begun, key_size = 0; + uapi16_sha256_digest_t hash; + const void *key; + struct forked parent; + uint64_t total = 0; + struct stat st; + char name[32]; + int status, r; + pid_t pid; + + check(fd >= 0 && written >= 0); + expected = generate(o, tree, UAPI16_ADD_NONE, &expected_size); + check_eq(uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e), 0); + empty(fd); + r = set_features(for_partitions, FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_GPT_LABEL)); + check_eq(r, 0); + check_eq(uapi16_manifest_options_set_order(unordered, UAPI16_ORDER_NONE), 0); + + /* A file object with every field. */ + unhex(SHA256_OF_HELLO, &hash); + check_eq(uapi16_file_object_set_mode(file, 0644), 0); + check_eq(uapi16_file_object_set_uid(file, 1), 0); + check_eq(uapi16_file_object_set_gid(file, 2), 0); + check_eq(uapi16_file_object_set_user_name(file, "user"), 0); + check_eq(uapi16_file_object_set_group_name(file, "group"), 0); + check_eq(uapi16_file_object_set_mtime_nsec(file, 3), 0); + check_eq(uapi16_file_object_set_size(file, 6), 0); + check_eq(uapi16_file_object_set_sha256(file, &hash), 0); + check_eq(uapi16_file_object_set_major(file, 4), 0); + check_eq(uapi16_file_object_set_minor(file, 5), 0); + check_eq(uapi16_file_object_set_inode_token(file, 6), 0); + check_eq(uapi16_file_object_add_user_xattr(file, "k", "v", 1), 0); + check_eq(uapi16_file_object_set_read_only(file, UAPI16_READ_ONLY_NO), 0); + check_eq(uapi16_file_object_set_inode_flags(file, NODUMP_FL, NODUMP_FL), 0); + check_eq(uapi16_file_object_set_dos_attributes(file, DOS_HIDDEN, 0), 0); + check_eq(uapi16_file_object_set_target(file, "target", 6), 0); + check_eq(uapi16_file_object_set_fs_label(file, "label"), 0); + check_eq(uapi16_file_object_set_fs_uuid(file, &uuid), 0); + check_eq(uapi16_file_object_set_fat_serial(file, 7), 0); + + /* Two writers with a file object each, and one that is finished. */ + check_eq(uapi16_manifest_writer_create_at(o, out, "created", &created, &e), 0); + check_eq(uapi16_manifest_writer_open(o, fd, &opened, &e), 0); + check_eq(uapi16_manifest_writer_add_object(created, hello, &e), 0); + check_eq(uapi16_manifest_writer_add_object(opened, hello, &e), 0); + check_eq(uapi16_manifest_writer_finish(finished, NULL, &e), 0); + check_eq(uapi16_file_object_new("a//b", &no_object, &error), -EINVAL); + check(error); + + /* A reader that has handed out the first of many file objects, and + * one that signature objects come from next. */ + check_eq(write(manifest, ROOT, strlen(ROOT)), (ssize_t) strlen(ROOT)); + for (int i = 0; i < MANY_OBJECTS; i++) + check(dprintf(manifest, RS "{\"name\":\"file-%06d\"}\n", i) > 0); + check_eq(write(manifest, TRAILER, strlen(TRAILER)), (ssize_t) strlen(TRAILER)); + reader = open_reader(manifest); + got = next_object(reader, "file-000000"); + got = uapi16_file_object_free(got); + signing = open_reader(with_signature); + got = next_object(signing, "a"); + got = uapi16_file_object_free(got); + check_eq(uapi16_reader_next(signing, &got, &e), UAPI16_READ_SIGNATURES); + + /* A writer of records that has written one, and one that is + * finished. */ + check_eq(uapi16_signature_new("openpgp", &signature), 0); + check_eq(uapi16_signature_set_key(signature, "key", 3), 0); + records = begin_records(o, written); + check_eq(uapi16_writer_file(records, hello, &e), 0); + begun = size_of(written); + finished_records = begin_records(o, null_fd); + check_eq(uapi16_writer_finish(finished_records, &e), 0); + + /* A hash and a check that have seen a part of their data, and two + * that are finished. */ + check_eq(uapi16_sha256_update(sha, "hel", 3), 0); + check_eq(uapi16_sha256_finish(finished_sha, &hash), 0); + check_eq(uapi16_data_check_new(hello, &data), 0); + check_eq(uapi16_data_check_update(data, "hel", 3, &e), 0); + check_eq(uapi16_data_check_new(hello, &finished_data), 0); + check_eq(uapi16_data_check_update(finished_data, "hello", 5, &e), 0); + check_eq(uapi16_data_check_finish(finished_data, NULL, &e), 0); + check_eq(uapi16_directory_new(out, UAPI16_DIRECTORY_NONE, &directory, &e), 0); + check(!e); + + parent = (struct forked) { + .o = o, + .for_partitions = for_partitions, + .unordered = unordered, + .created = created, + .opened = opened, + .finished = finished, + .report = report, + .error = error, + .file = file, + .hello = hello, + .root = root, + .reader = reader, + .signing = signing, + .records = records, + .finished_records = finished_records, + .signature = signature, + .sha = sha, + .finished_sha = finished_sha, + .data = data, + .finished_data = finished_data, + .directory = directory, + .tree = tree, + .out = out, + .opened_fd = fd, + .records_fd = written, + .manifest_fd = manifest, + .signing_fd = with_signature, + }; + fflush(NULL); + pid = fork(); + check(pid >= 0); + if (pid == 0) { + check_child(&parent); + fflush(NULL); + _exit(EXIT_SUCCESS); + } + check_eq(waitpid(pid, &status, 0), pid); + check(WIFEXITED(status)); + check_eq(WEXITSTATUS(status), EXIT_SUCCESS); + + /* The descriptors that are on loan are open in the parent, whose + * objects the child freed in its own memory alone. */ + check_open(tree); + check_open(out); + check_open(fd); + check_open(written); + check_open(manifest); + check_open(with_signature); + check_open(null_fd); + + /* The child wrote nothing and linked nothing, and what it freed is + * all there in the parent, which finishes. */ + check_eq(fstatat(out, "created", &st, 0), -1); + check_eq(errno, ENOENT); + check_eq(size_of(fd), 0); + check_eq(size_of(written), begun); + check_eq(uapi16_manifest_writer_finish(created, &first, &e), 0); + check_eq(uapi16_manifest_writer_finish(opened, &second, &e), 0); + check(!e); + check_ended(uapi16_manifest_writer_add_object(finished, hello, &e), &e); + check_eq(uapi16_manifest_report_files(first), 1); + check_eq(uapi16_manifest_report_files(second), 1); + opened = uapi16_manifest_writer_free(opened); + r = uapi16_manifest_writer_open(for_partitions, fd, &none, &e); + check_error(r, e, UAPI16_ERROR_INVALID_ARGUMENT, EINVAL, NULL, CHECK_FEATURE); + check_eq(uapi16_error_feature(e), UAPI16_FEATURE_GPT_LABEL); + e = uapi16_error_free(e); + made = read_file(out, "created", &made_size); + streamed = read_all(fd, &streamed_size); + check_manifest(made, made_size); + check_same(streamed, streamed_size, made, made_size); + child = read_file(out, "child", &child_size); + check_same(child, child_size, expected, expected_size); + + /* The reader reads on where it was: the child read nothing of its + * manifest. */ + for (int i = 1; i < MANY_OBJECTS; i++) { + snprintf(name, sizeof(name), "file-%06d", i); + got = next_object(reader, name); + got = uapi16_file_object_free(got); + } + check_ends(reader); + check_eq(uapi16_reader_next_signature(signing, &read_signature, &e), UAPI16_READ_SIGNATURE); + check_str(uapi16_signature_mechanism(read_signature), "openpgp"); + read_signature = uapi16_signature_free(read_signature); + check_eq(uapi16_reader_next_signature(signing, &read_signature, &e), UAPI16_READ_END); + + /* The writer of records writes on, and its manifest has what the + * parent wrote. */ + check_eq(uapi16_writer_signature(records, signature, &e), 0); + check_eq(uapi16_writer_finish(records, &e), 0); + check_ended(uapi16_writer_finish(finished_records, &e), &e); + records = uapi16_writer_free(records); + written_back = open_reader(written); + got = next_object(written_back, "hello"); + got = uapi16_file_object_free(got); + check_eq(uapi16_reader_next(written_back, &got, &e), UAPI16_READ_SIGNATURES); + check_eq(uapi16_reader_next_signature(written_back, &read_signature, &e), UAPI16_READ_SIGNATURE); + key = uapi16_signature_key(read_signature, &key_size); + check_same(key, key_size, "key", 3); + read_signature = uapi16_signature_free(read_signature); + check_eq(uapi16_reader_next_signature(written_back, &read_signature, &e), UAPI16_READ_END); + + /* The hash and the check go on with their data. */ + check_eq(uapi16_sha256_update(sha, "lo", 2), 0); + check_eq(uapi16_sha256_finish(sha, &hash), 0); + check_hash(&hash, SHA256_OF_HELLO); + check_eq(uapi16_sha256_update(finished_sha, "x", 1), -ESTALE); + check_eq(uapi16_data_check_update(data, "lo", 2, &e), 0); + check_eq(uapi16_data_check_finish(data, &total, &e), 0); + check_eq(total, 5); + check_ended(uapi16_data_check_finish(finished_data, NULL, &e), &e); + check(!e); +} + +/* How many files test_scratch_files() gives a writer, each with two names + * of the longest size: more file objects and more hard links than a writer + * keeps in memory. */ +#define SCRATCH_INODES 5000 + +/* How many files a writer has something in once it has that many file + * objects: one with file objects, and two with hard links, their table and + * their names. */ +#define SCRATCH_FILES_MIN 3 + +/* How many descriptors test_scratch_files() and test_failed_walks() look + * through for the files a writer keeps on disk: more than the process has + * open. */ +#define SCRATCH_DESCRIPTORS 256 + +/* Notes in `unnamed` which descriptors of the process are regular files + * without a name that hold something, as the files do that a writer keeps + * file objects and hard links in. */ +static void unnamed_files(bool unnamed[static SCRATCH_DESCRIPTORS]) { + for (int fd = 0; fd < SCRATCH_DESCRIPTORS; fd++) { + struct stat st; + + unnamed[fd] = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) && st.st_nlink == 0 && + st.st_size > 0; + } +} + +/* The name of a file of test_scratch_files(): `link` is 'a' or 'b' for the + * first or the second name of the file `inode`. */ +static void scratch_name(char name[static NAME_OF_OBJECT_MAX + 1], int inode, char link) { + char start[16]; + int n = snprintf(start, sizeof(start), "%06d%c", inode, link); + + memset(name, 'n', NAME_OF_OBJECT_MAX); + memcpy(name, start, (size_t) n); + name[NAME_OF_OBJECT_MAX] = 0; +} + +/* Whether the call that returned `r` found no room where it writes. + * test_scratch_files() needs about 100 MiB there, and is skipped with a + * line where a file system has less. */ +static bool no_room(int r) { + if (r != -ENOSPC) + return false; + fprintf(stderr, "skipping the scratch files of a writer: no room for them here, about 100 MiB\n"); + return true; +} + +/* Adds the files of test_scratch_files() to `w`, the last one first. Then + * the writer keeps file objects and hard links on disk, in files that were + * not among `before`, which this checks. Notes those files in `scratch`. */ +static bool add_scratch_files(uapi16_manifest_writer *w, const bool before[static SCRATCH_DESCRIPTORS], + bool scratch[static SCRATCH_DESCRIPTORS]) { + char name[NAME_OF_OBJECT_MAX + 1]; + size_t count = 0; + + for (int inode = SCRATCH_INODES - 1; inode >= 0; inode--) + for (char link = 'a'; link <= 'b'; link++) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = NULL; + int r; + + scratch_name(name, inode, link); + check_eq(uapi16_file_object_new(name, &o, NULL), 0); + check_eq(uapi16_file_object_set_size(o, 0), 0); + check_eq(uapi16_file_object_set_inode_token(o, (uapi16_inode_token_t) inode + 1), 0); + r = uapi16_manifest_writer_add_object(w, o, NULL); + if (no_room(r)) + return false; + check_eq(r, 0); + } + unnamed_files(scratch); + for (int fd = 0; fd < SCRATCH_DESCRIPTORS; fd++) { + scratch[fd] = scratch[fd] && !before[fd]; + count += scratch[fd]; + } + check(count >= SCRATCH_FILES_MIN); + return true; +} + +/* Checks that the manifest in the file `fd` has every file of + * test_scratch_files(), with its two names as the names of one file. */ +static void check_scratch_files(int fd) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = NULL; + uapi16_reader *reader = open_reader(fd); + char name[NAME_OF_OBJECT_MAX + 1]; + uapi16_inode_token_t last = UAPI16_INODE_TOKEN_NONE; + + for (int inode = 0; inode < SCRATCH_INODES; inode++) { + uapi16_inode_token_t first = 0, second = 0; + + scratch_name(name, inode, 'a'); + check_eq(uapi16_reader_next(reader, &o, NULL), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(o), name); + check_eq(uapi16_file_object_inode_token(o, &first), 0); + scratch_name(name, inode, 'b'); + check_eq(uapi16_reader_next(reader, &o, NULL), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(o), name); + check_eq(uapi16_file_object_inode_token(o, &second), 0); + check_eq(second, first); + check(first != last); + last = first; + } + check_eq(uapi16_reader_next(reader, &o, NULL), UAPI16_READ_END); + uapi16_reader_free(reader); +} + +/* A writer of a large manifest keeps file objects and hard links in files + * of its own, which the child of a fork() has open as well. A child that + * frees the writer leaves them as they are: the parent finishes and has + * the whole manifest, in a new file and in a file of its own. A writer + * whose files were emptied fails, with EIO for an error that no system + * call gave an errno. */ +static void test_scratch_files(void) { + _cleanup_(closep) int out = make_dir(tmp_fd, "scratch-out"); + _cleanup_(closep) int fd = openat(out, "opened", O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *emptied = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + bool before[SCRATCH_DESCRIPTORS], scratch[SCRATCH_DESCRIPTORS]; + int r; + + check(o && fd >= 0); + for (int created = 0; created < 2; created++) { + _cleanup_(closep) int created_fd = -1; + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL; + int status; + pid_t pid; + + unnamed_files(before); + if (created) + check_eq(uapi16_manifest_writer_create_at(o, out, "created", &w, &e), 0); + else + check_eq(uapi16_manifest_writer_open(o, fd, &w, &e), 0); + if (!add_scratch_files(w, before, scratch)) + return; + + fflush(NULL); + pid = fork(); + check(pid >= 0); + if (pid == 0) { + uapi16_manifest_writer_free(w); + /* Its copy of the options as well, so that it + * leaves nothing behind that a check for leaks + * would find. */ + uapi16_manifest_options_free(o); + _exit(EXIT_SUCCESS); + } + check_eq(waitpid(pid, &status, 0), pid); + check(WIFEXITED(status)); + check_eq(WEXITSTATUS(status), EXIT_SUCCESS); + + /* The parent has every file object and every hard link + * still, and a new file gets its name from it. */ + r = uapi16_manifest_writer_finish(w, &report, &e); + if (no_room(r)) + return; + check_eq(r, 0); + check(!e); + check_eq(uapi16_manifest_report_files(report), 2 * SCRATCH_INODES); + report = uapi16_manifest_report_free(report); + if (created) { + created_fd = openat(out, "created", O_RDONLY | O_CLOEXEC); + check(created_fd >= 0); + } + check_scratch_files(created ? created_fd : fd); + check_eq(count_entries(tmp_fd, "scratch-out"), (size_t) 1 + (size_t) created); + } + check_eq(unlinkat(out, "created", 0), 0); + + /* The files of a writer are emptied behind its back, as a child did + * that did not leave them alone. The writer finds that when it + * reads them, and fails. */ + empty(fd); + unnamed_files(before); + check_eq(uapi16_manifest_writer_open(o, fd, &emptied, &e), 0); + if (!add_scratch_files(emptied, before, scratch)) + return; + for (int scratch_fd = 0; scratch_fd < SCRATCH_DESCRIPTORS; scratch_fd++) + if (scratch[scratch_fd]) + check_eq(ftruncate(scratch_fd, 0), 0); + r = uapi16_manifest_writer_finish(emptied, &report, &e); + check_error(r, e, UAPI16_ERROR_IO, EIO, NULL, 0); + check(!report); + e = uapi16_error_free(e); + check_ended(uapi16_manifest_writer_finish(emptied, &report, &e), &e); +} + +/* How many directories inside each other the files of test_failed_walks() + * are in, each with a name as long as a name gets: as many as leave room + * for the name of a file in the last of them. */ +#define WALK_DEPTH 15 + +/* How many files test_failed_walks() makes there, each with two names. A + * walk keeps their hard links on disk before it has come to half of their + * names. */ +#define WALK_INODES 5000 + +/* How many descriptors of the files of a walk test_failed_walks() holds + * at most: more than a walk has of them. */ +#define WALK_FILES_MAX 16 + +/* What test_failed_walks() stops a walk with, and what it holds of the + * files the walk keeps on disk. */ +static struct { + /* The watch of the directory the walk reads. */ + int watch; + /* Which descriptors the process had before the walk. */ + bool before[SCRATCH_DESCRIPTORS]; + /* The limit that leaves the process no descriptor to open. */ + struct rlimit none; + /* Whether a signal came for the walk, and whether it was stopped. */ + volatile sig_atomic_t signaled, stopped; + /* A copy of each descriptor the walk had of a file without a name + * when it was stopped. */ + int held[WALK_FILES_MAX]; + size_t count; +} walk; + +/* Runs when the walk of test_failed_walks() has read on in its directory. + * Once the walk keeps something on disk, in files without a name that the + * process did not have before, this takes a copy of each descriptor of + * such a file, and leaves the process no descriptor to open. The walk + * fails at the next file it opens. */ +static void stop_walk(int signal) { + char events[sizeof(struct inotify_event) + NAME_MAX + 1]; + int found[WALK_FILES_MAX], saved = errno; + bool with_data = false; + size_t n = 0; + + (void) signal; + /* A watch that is not read says nothing of the next read. */ + while (read(walk.watch, events, sizeof(events)) > 0) + ; + walk.signaled = 1; + for (int fd = 0; !walk.stopped && fd < SCRATCH_DESCRIPTORS && n < WALK_FILES_MAX; fd++) { + struct stat st; + + if (walk.before[fd] || fstat(fd, &st) < 0 || !S_ISREG(st.st_mode) || st.st_nlink > 0) + continue; + found[n++] = fd; + with_data = with_data || st.st_size > 0; + } + if (with_data) { + for (size_t i = 0; i < n; i++) + walk.held[i] = fcntl(found[i], F_DUPFD_CLOEXEC, 0); + walk.count = n; + setrlimit(RLIMIT_NOFILE, &walk.none); + walk.stopped = 1; + } + errno = saved; +} + +/* + * A walk that fails leaves nothing in the files it kept on disk: each of + * them is empty when the generate function returns, as after a walk whose + * manifest was written. The files of the tree have two names each, nearly + * as long as a name gets, and there are more of them than a writer keeps + * the hard links of in memory. The kernel says when the walk reads on in + * the directory of the files: a watch of it sends a signal for each read + * to the thread that reads. The handler stops the walk once it has files + * that hold something, and keeps a descriptor of each, through which the + * test sees what is left in them. Where there is no such watch, there is + * nothing to test. + */ +static void test_failed_walks(void) { + const uapi16_features_t unhashed = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_SIZE, + UAPI16_FEATURE_HARDLINK); + _cleanup_(closep) int tree = make_dir(tmp_fd, "failed-walks"); + _cleanup_(closep) int out = make_dir(tmp_fd, "failed-walks-out"); + _cleanup_(closep) int fd = scratch_file(), dir = dup(tree), watch = -1; + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + struct f_owner_ex owner = { .type = F_OWNER_TID, .pid = (pid_t) syscall(SYS_gettid) }; + struct sigaction stop = { .sa_handler = stop_walk }, old; + char component[COMPONENT_MAX + 1], path[64]; + struct rlimit limit; + + check(o && dir >= 0); + check_eq(set_features(o, unhashed), 0); + memset(component, 'd', COMPONENT_MAX); + component[COMPONENT_MAX] = 0; + for (int depth = 0; depth < WALK_DEPTH; depth++) { + int next = make_dir(dir, component); + + close(dir); + dir = next; + } + /* The path of the directory is longer than a path can be. */ + snprintf(path, sizeof(path), "/proc/self/fd/%d", dir); + watch = inotify_init1(IN_CLOEXEC | IN_NONBLOCK); + if (watch < 0 || inotify_add_watch(watch, path, IN_ACCESS) < 0) { + fprintf(stderr, "skipping the walks that fail: %s\n", strerror(errno)); + return; + } + for (int inode = 0; inode < WALK_INODES; inode++) { + char name[16], link[16]; + + snprintf(name, sizeof(name), "%06da", inode); + snprintf(link, sizeof(link), "%06db", inode); + make_file(dir, name, ""); + check_eq(linkat(dir, name, dir, link, 0), 0); + } + check_eq(getrlimit(RLIMIT_NOFILE, &limit), 0); + walk.none = limit; + walk.none.rlim_cur = 0; + walk.watch = watch; + check_eq(sigaction(SIGIO, &stop, &old), 0); + check_eq(fcntl(watch, F_SETOWN_EX, &owner), 0); + check_eq(fcntl(watch, F_SETFL, O_ASYNC | O_NONBLOCK), 0); + + /* To a descriptor of the caller first, and to a new file then. */ + for (int created = 0; created < 2; created++) { + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + int r; + + for (int i = 0; i < SCRATCH_DESCRIPTORS; i++) + walk.before[i] = fcntl(i, F_GETFD) >= 0; + walk.signaled = walk.stopped = 0; + walk.count = 0; + if (created) + r = uapi16_manifest_generate_at(o, out, "created", tree, UAPI16_ADD_NONE, &report, &e); + else + r = uapi16_manifest_generate(o, fd, tree, UAPI16_ADD_NONE, &report, &e); + check_eq(setrlimit(RLIMIT_NOFILE, &limit), 0); + if (!walk.signaled || (!walk.stopped && r == -ENOSPC)) { + fprintf(stderr, "skipping the walks that fail: %s\n", + walk.signaled ? "no room for what a walk keeps on disk, about 10 MiB" : + "no signal for the read of a directory"); + break; + } + + /* The walk kept something on disk, and failed after that. */ + check(walk.stopped); + check_eq(r, -EMFILE); + check_eq(uapi16_error_kind(e), UAPI16_ERROR_IO); + check_eq(uapi16_error_errno(e), EMFILE); + check(!report); + for (size_t i = 0; i < walk.count; i++) { + check(walk.held[i] >= 0); + check_eq(size_of(walk.held[i]), 0); + check_eq(close(walk.held[i]), 0); + } + check_eq(size_of(fd), 0); + check_eq(count_entries(tmp_fd, "failed-walks-out"), 0); + } + + check_eq(close(watch), 0); + watch = -1; + check_eq(sigaction(SIGIO, &old, NULL), 0); +} + +/* + * A finish that fails once the new file has its name leaves the file under + * the name, with the whole manifest in it. Here the file is synced, and + * its directory can't be opened for the sync of it: it may be written and + * searched, but not read. A writer of options whose syncing was turned on + * and off again syncs nothing, and finishes in that directory. A process + * that may read any directory, as root may, has nothing to test. + */ +static void test_failed_sync(void) { + _cleanup_(closep) int out = make_dir(tmp_fd, "sync-out"), fd = -1; + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_hello("file"), *got = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + struct stat st; + int r; + + check_eq(uapi16_manifest_options_set_sync(o, true), 0); + check_eq(uapi16_manifest_writer_create_at(o, out, "m", &w, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, file, &e), 0); + + /* A directory that may be written and searched, and not read. */ + check_eq(fstat(out, &st), 0); + check_eq(fchmod(out, 0300), 0); + fd = openat(tmp_fd, "sync-out", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + r = uapi16_manifest_writer_finish(w, &report, &e); + check_eq(fchmod(out, st.st_mode & ALLPERMS), 0); + if (fd >= 0) { + fprintf(stderr, "skipping a finish whose sync fails: the process may read any directory\n"); + return; + } + check_error(r, e, UAPI16_ERROR_IO, EACCES, NULL, 0); + check(!report); + + /* The file has its name, and the manifest in it is whole. */ + check_eq(count_entries(tmp_fd, "sync-out"), 1); + fd = openat(out, "m", O_RDONLY | O_CLOEXEC); + check(fd >= 0); + reader = open_reader(fd); + got = next_object(reader, "file"); + check_ends(reader); + + /* Syncing that was turned on and off again is off: the finish has + * no directory to open, and succeeds where the one above failed. */ + { + _cleanup_(closep) int unsynced_fd = -1; + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *off = + uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *unsynced = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *written = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *listed = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *back = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *none = NULL; + + check_eq(uapi16_manifest_options_set_sync(off, true), 0); + check_eq(uapi16_manifest_options_set_sync(off, false), 0); + check_eq(uapi16_manifest_writer_create_at(off, out, "unsynced", &unsynced, &none), 0); + check_eq(uapi16_manifest_writer_add_object(unsynced, file, &none), 0); + check_eq(fchmod(out, 0300), 0); + r = uapi16_manifest_writer_finish(unsynced, &written, &none); + check_eq(fchmod(out, st.st_mode & ALLPERMS), 0); + check_eq(r, 0); + check(written && !none); + check_eq(count_entries(tmp_fd, "sync-out"), 2); + unsynced_fd = openat(out, "unsynced", O_RDONLY | O_CLOEXEC); + check(unsynced_fd >= 0); + back = open_reader(unsynced_fd); + listed = next_object(back, "file"); + check_ends(back); + } +} + +/* Runs `body` in a child of this process, and returns what the child exits + * with. */ +static int in_child(int (*body)(void *), void *argument) { + int status; + pid_t pid; + + fflush(NULL); + pid = fork(); + check(pid >= 0); + if (pid == 0) { + int code = body(argument); + + fflush(NULL); + _exit(code); + } + check_eq(waitpid(pid, &status, 0), pid); + check(WIFEXITED(status)); + return WEXITSTATUS(status); +} + +/* What madvise() notes of the pages that are wiped in a child of a fork(), + * which is how the library tells a child, and what it is asked to do with + * the next call for such a page. */ +static struct { + /* How many pages there are, and the first of them. */ + atomic_size_t count; + void *pages[16]; + /* Whether the next call for such a page says that it has come, + * and waits until it may go on. */ + atomic_bool hold; + sem_t held, released; +} wiped; + +/* + * The madvise() of this program and of the library in it. It takes the + * place of the one of the C library and does what that one does. For + * test_forks() it also notes each page that it made one that is wiped in a + * child, and it holds such a call where the test asks for that. + */ +int madvise(void *address, size_t size, int advice) { + int r; + + if (advice == MADV_WIPEONFORK && atomic_exchange(&wiped.hold, false)) { + check_eq(sem_post(&wiped.held), 0); + while (sem_wait(&wiped.released) < 0) + check_eq(errno, EINTR); + } + r = (int) syscall(SYS_madvise, address, size, advice); + if (advice == MADV_WIPEONFORK && r == 0) { + size_t n = atomic_fetch_add(&wiped.count, 1); + + if (n < ELEMENTSOF(wiped.pages)) + wiped.pages[n] = address; + } + return r; +} + +/* + * The malloc() of everything that is linked into this program, which the + * linker makes it with --wrap=malloc: the test itself and, where it is + * linked statically, the library. It is the malloc() of the C library, and + * it holds a thread that asked for that in its next call, until the thread + * is released. The shared library allocates past it, so nothing of that + * one is held. + */ +void *__real_malloc(size_t size); +void *__wrap_malloc(size_t size); +static _Thread_local bool hold_malloc; +static sem_t malloc_held, malloc_released; + +void *__wrap_malloc(size_t size) { + if (hold_malloc) { + hold_malloc = false; + check_eq(sem_post(&malloc_held), 0); + while (sem_wait(&malloc_released) < 0) + check_eq(errno, EINTR); + } + return __real_malloc(size); +} + +/* Whether the kernel has memory that is wiped in a child of a fork(), by + * which the library tells a child. Without it nothing tells a child, and + * the library checks nothing. */ +static bool wipes_on_fork(void) { + long size = sysconf(_SC_PAGESIZE); + void *page; + bool wipes; + + check(size > 0); + page = mmap(NULL, (size_t) size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + check(page != MAP_FAILED); + /* Not by the madvise() of this program, which would note the page. */ + wipes = syscall(SYS_madvise, page, (size_t) size, MADV_WIPEONFORK) == 0; + check_eq(munmap(page, (size_t) size), 0); + return wipes; +} + +/* Whether the page at `address` is wiped in a child of a fork(): its + * mapping has "wf" among its VmFlags in /proc/self/smaps. A page that is + * not mapped is none. -1 where that file can't be read. */ +static int wiped_in_a_child(const void *address) { + const uintptr_t page = (uintptr_t) address; + FILE *f = fopen("/proc/self/smaps", "re"); + bool inside = false, wiped_there = false; + char line[PATH_MAX + 128]; + + if (!f) + return -1; + while (fgets(line, sizeof(line), f)) { + unsigned long long start, end; + + if (sscanf(line, "%llx-%llx ", &start, &end) == 2) + inside = start <= page && page < end; + else if (inside && strncmp(line, "VmFlags:", strlen("VmFlags:")) == 0) + wiped_there = strstr(line, " wf") != NULL; + } + check_eq(fclose(f), 0); + return wiped_there; +} + +/* What a process of test_forks() has of the processes it comes from: a + * computation that each of them made. */ +struct lineage { + uapi16_sha256 *of_parent, *of_child; +}; + +/* A grandchild can use neither what its parent made nor what the parent of + * that made, and can use what it makes itself. */ +static int grandchild(void *argument) { + const struct lineage *lineage = argument; + uapi16_sha256 *own = uapi16_sha256_new(); + + check_eq(uapi16_sha256_update(lineage->of_parent, "x", 1), -ECHILD); + check_eq(uapi16_sha256_update(lineage->of_child, "x", 1), -ECHILD); + check_eq(uapi16_sha256_update(own, "x", 1), 0); + uapi16_sha256_free(own); + return EXIT_SUCCESS; +} + +/* A child that makes a child of its own, and is the process it was after + * that. */ +static int child_with_grandchild(void *argument) { + struct lineage *lineage = argument; + + lineage->of_child = uapi16_sha256_new(); + check_eq(uapi16_sha256_update(lineage->of_parent, "x", 1), -ECHILD); + check_eq(uapi16_sha256_update(lineage->of_child, "x", 1), 0); + check_eq(in_child(grandchild, lineage), EXIT_SUCCESS); + check_eq(uapi16_sha256_update(lineage->of_child, "y", 1), 0); + check_eq(uapi16_sha256_update(lineage->of_parent, "x", 1), -ECHILD); + uapi16_sha256_free(lineage->of_child); + return EXIT_SUCCESS; +} + +/* A child that makes a child before it has used the library itself. */ +static int idle_child_with_grandchild(void *argument) { + struct lineage *lineage = argument; + struct lineage own = { .of_parent = lineage->of_parent, .of_child = lineage->of_parent }; + + check_eq(in_child(grandchild, &own), EXIT_SUCCESS); + check_eq(uapi16_sha256_update(lineage->of_parent, "x", 1), -ECHILD); + return EXIT_SUCCESS; +} + +/* How many threads of a child use the library for the first time at once. */ +#define RACERS 8 + +struct race { + pthread_barrier_t start; + uapi16_sha256 *of_parent; + uapi16_sha256 *made[RACERS]; +}; + +struct racer { + struct race *race; + size_t number; +}; + +static void *race_in_child(void *argument) { + struct racer *racer = argument; + struct race *race = racer->race; + int r = pthread_barrier_wait(&race->start); + + check(r == 0 || r == PTHREAD_BARRIER_SERIAL_THREAD); + check_eq(uapi16_sha256_update(race->of_parent, "x", 1), -ECHILD); + race->made[racer->number] = uapi16_sha256_new(); + check_eq(uapi16_sha256_update(race->made[racer->number], "x", 1), 0); + return NULL; +} + +/* The first calls of a child come from several threads at once. They agree + * on which process this is: each is told that the object of the parent is + * not one of its process, and what one of them makes, another one uses. */ +static int child_with_threads(void *argument) { + struct race race = { .of_parent = argument }; + struct racer racers[RACERS]; + pthread_t threads[RACERS]; + + check_eq(pthread_barrier_init(&race.start, NULL, RACERS), 0); + for (size_t i = 0; i < RACERS; i++) { + racers[i] = (struct racer) { .race = &race, .number = i }; + check_eq(pthread_create(&threads[i], NULL, race_in_child, &racers[i]), 0); + } + for (size_t i = 0; i < RACERS; i++) + check_eq(pthread_join(threads[i], NULL), 0); + for (size_t i = 0; i < RACERS; i++) { + check_eq(uapi16_sha256_update(race.made[i], "y", 1), 0); + uapi16_sha256_free(race.made[i]); + } + check_eq(uapi16_sha256_update(race.of_parent, "x", 1), -ECHILD); + check_eq(pthread_barrier_destroy(&race.start), 0); + return EXIT_SUCCESS; +} + +/* The child of the first process of a PID namespace, which is the first + * process of a namespace of its own: it has the PID of its parent, and is + * told that it is a child all the same. */ +static int child_with_the_pid_of_its_parent(void *argument) { + check_eq(getpid(), 1); + check_eq(uapi16_sha256_update(argument, "x", 1), -ECHILD); + return EXIT_SUCCESS; +} + +static int first_of_a_namespace(void *argument) { + uapi16_sha256 *sha = uapi16_sha256_new(); + int code; + + (void) argument; + check_eq(getpid(), 1); + check_eq(uapi16_sha256_update(sha, "x", 1), 0); + if (unshare(CLONE_NEWPID) < 0) + return EXIT_SKIPPED; + code = in_child(child_with_the_pid_of_its_parent, sha); + check_eq(uapi16_sha256_update(sha, "y", 1), 0); + uapi16_sha256_free(sha); + return code; +} + +/* Makes a user and a PID namespace, of which its child is the first + * process. */ +static int namespace_of_its_own(void *argument) { + if (unshare(CLONE_NEWUSER | CLONE_NEWPID) < 0) + return EXIT_SKIPPED; + return in_child(first_of_a_namespace, argument); +} + +/* What the test is told to do when it runs itself once more, and the path + * it runs itself by. The last three come with a directory to do it in. */ +#define WITHOUT_WIPE_ON_FORK "--without-wipe-on-fork" +#define FORK_IN_THE_FIRST_CALL "--fork-in-the-first-call" +#define FIRST_CALLS_AT_ONCE "--first-calls-at-once" +#define FORK_IN_THE_FIRST_ASK "--fork-in-the-first-ask" +#define WITHOUT_TMPFILE "--without-tmpfile" +#define WITH_A_LINKED_NAME "--with-a-linked-name" +#define WITH_A_NAME_LEFT "--with-a-name-left" +#define WITH_A_NAME_THROUGH_PROCFS "--with-a-name-through-procfs" +static const char *self_path; + +/* Runs the test once more, as a process that has used nothing of the + * library yet and does what `what` says, with `argument` if that is not + * NULL. Returns what it exits with. */ +static int in_new_process(const char *what, const char *argument) { + int status; + pid_t pid; + + fflush(NULL); + pid = fork(); + check(pid >= 0); + if (pid == 0) { + execl(self_path, self_path, what, argument, (char *) NULL); + _exit(EXIT_FAILURE); + } + check_eq(waitpid(pid, &status, 0), pid); + check(WIFEXITED(status)); + return WEXITSTATUS(status); +} + +/* How long the first call of a child may take. One that takes longer waits + * for something that never comes, and the child is killed. */ +#define FIRST_CALL_SECONDS 30 + +/* Forks while another thread is in the first call of the process: in the + * madvise() of it. The child has this thread alone. Its own first call + * comes back all the same: it waits for nothing that the other thread of + * its parent was about to do. */ +static void *fork_in_a_first_call(void *argument) { + int status; + pid_t pid; + + (void) argument; + while (sem_wait(&wiped.held) < 0) + check_eq(errno, EINTR); + fflush(NULL); + pid = fork(); + check(pid >= 0); + if (pid == 0) { + uapi16_sha256 *own; + + alarm(FIRST_CALL_SECONDS); + own = uapi16_sha256_new(); + check_eq(uapi16_sha256_update(own, "x", 1), 0); + uapi16_sha256_free(own); + fflush(NULL); + _exit(EXIT_SUCCESS); + } + check_eq(sem_post(&wiped.released), 0); + check_eq(waitpid(pid, &status, 0), pid); + check(WIFEXITED(status)); + check_eq(WEXITSTATUS(status), EXIT_SUCCESS); + return NULL; +} + +/* What the test does when test_forks() runs it with + * FORK_IN_THE_FIRST_CALL: it makes its first call of the library while + * another thread forks, see fork_in_a_first_call(). Returns what the + * process exits with. */ +static int fork_in_the_first_call(void) { + uapi16_sha256 *sha; + pthread_t thread; + + check_eq(sem_init(&wiped.held, 0, 0), 0); + check_eq(sem_init(&wiped.released, 0, 0), 0); + check_eq(pthread_create(&thread, NULL, fork_in_a_first_call, NULL), 0); + atomic_store(&wiped.hold, true); + sha = uapi16_sha256_new(); + /* A first call that asked for no such page was not held, and the + * other thread forks after it. */ + if (atomic_exchange(&wiped.hold, false)) + check_eq(sem_post(&wiped.held), 0); + check_eq(pthread_join(thread, NULL), 0); + check_eq(uapi16_sha256_update(sha, "x", 1), 0); + uapi16_sha256_free(sha); + return EXIT_SUCCESS; +} + +static void *race_to_the_first_call(void *argument) { + struct racer *racer = argument; + struct race *race = racer->race; + int r = pthread_barrier_wait(&race->start); + + check(r == 0 || r == PTHREAD_BARRIER_SERIAL_THREAD); + race->made[racer->number] = uapi16_sha256_new(); + check_eq(uapi16_sha256_update(race->made[racer->number], "x", 1), 0); + return NULL; +} + +/* What the test does when test_forks() runs it with FIRST_CALLS_AT_ONCE: + * the first calls of the process come from several threads at once. They + * agree on which process this is: what one of them makes, another one + * uses. And they agree on one page that is wiped in a child: of the pages + * they made for that, one is left, and there is one where the kernel has + * such pages. Returns what the process exits with. */ +static int first_calls_at_once(void) { + struct race race = { .of_parent = NULL }; + struct racer racers[RACERS]; + pthread_t threads[RACERS]; + size_t made, left = 0; + + check_eq(pthread_barrier_init(&race.start, NULL, RACERS), 0); + for (size_t i = 0; i < RACERS; i++) { + racers[i] = (struct racer) { .race = &race, .number = i }; + check_eq(pthread_create(&threads[i], NULL, race_to_the_first_call, &racers[i]), 0); + } + for (size_t i = 0; i < RACERS; i++) + check_eq(pthread_join(threads[i], NULL), 0); + for (size_t i = 0; i < RACERS; i++) { + check_eq(uapi16_sha256_update(race.made[i], "y", 1), 0); + uapi16_sha256_free(race.made[i]); + } + check_eq(pthread_barrier_destroy(&race.start), 0); + + made = atomic_load(&wiped.count); + check(made <= RACERS); + for (size_t i = 0; i < made; i++) { + int r = wiped_in_a_child(wiped.pages[i]); + + if (r < 0) { + fprintf(stderr, "skipping the pages that are left of the first calls: " + "no /proc/self/smaps here\n"); + return EXIT_SUCCESS; + } + left += (size_t) r; + } + check_eq(left, wipes_on_fork() ? 1 : 0); + return EXIT_SUCCESS; +} + +/* A string that the library makes when it is first asked for, and keeps: + * the function that asks for it, the object it is a string of, and what the + * thread that asked first got. */ +struct ask { + const char *(*string)(const void *object); + const void *object; + const char *got; + /* Whether the thread went through its ask without being held, as + * with the shared library, which shows nothing. */ + bool not_held; +}; + +static const char *ask_feature_name(const void *object) { + (void) object; + return uapi16_feature_name(UAPI16_FEATURE_MODE); +} + +static const char *ask_object_name(const void *object) { + return uapi16_file_object_name(object); +} + +static const char *ask_mechanism(const void *object) { + return uapi16_signature_mechanism(object); +} + +/* Asks for a string for the first time, and is held in the malloc() that + * makes the string, where the malloc() of this program is the one of the + * library. */ +static void *first_ask(void *argument) { + struct ask *ask = argument; + + hold_malloc = true; + ask->got = ask->string(ask->object); + /* An ask that allocated past the malloc() of this program was not + * held, and whoever waits for that goes on now. */ + if (hold_malloc) { + hold_malloc = false; + ask->not_held = true; + check_eq(sem_post(&malloc_held), 0); + } + return NULL; +} + +/* A thread is in its first ask for a string, and a child is forked then. + * The child has no such thread. It asks for the same string and gets it: + * it waits for nothing that the thread of its parent was about to do. + * With `here`, this thread asks as well while the other one is held, and + * both get the one string that is kept. */ +static void fork_in_a_first_ask(struct ask *ask, bool here) { + const char *got = NULL; + pthread_t thread; + int status; + pid_t pid; + + check_eq(sem_init(&malloc_held, 0, 0), 0); + check_eq(sem_init(&malloc_released, 0, 0), 0); + check_eq(pthread_create(&thread, NULL, first_ask, ask), 0); + while (sem_wait(&malloc_held) < 0) + check_eq(errno, EINTR); + fflush(NULL); + pid = fork(); + check(pid >= 0); + if (pid == 0) { + alarm(FIRST_CALL_SECONDS); + _exit(ask->string(ask->object) ? EXIT_SUCCESS : EXIT_FAILURE); + } + check_eq(waitpid(pid, &status, 0), pid); + check(WIFEXITED(status)); + check_eq(WEXITSTATUS(status), EXIT_SUCCESS); + if (here) + got = ask->string(ask->object); + check_eq(sem_post(&malloc_released), 0); + check_eq(pthread_join(thread, NULL), 0); + check(ask->got); + if (here) + check(got == ask->got); + check_eq(sem_destroy(&malloc_held), 0); + check_eq(sem_destroy(&malloc_released), 0); +} + +/* What the test does when test_forks() runs it with FORK_IN_THE_FIRST_ASK: + * a child is forked while another thread asks for a string that the + * library makes then, see fork_in_a_first_ask(): for a name that is a + * constant of the library, for a string of a file object and for the one + * of a signature object. The name is one that nothing asked for yet in + * this process, and two threads ask for it at once. An object is used by + * one thread at a time. Returns what the process exits with. */ +static int fork_in_the_first_ask(void) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = make_object("name"); + _cleanup_(uapi16_signature_freep) uapi16_signature *signature = NULL; + struct ask name = { .string = ask_feature_name }; + struct ask of_object = { .string = ask_object_name, .object = o }; + struct ask of_signature = { .string = ask_mechanism }; + + check_eq(uapi16_signature_new("mechanism", &signature), 0); + of_signature.object = signature; + fork_in_a_first_ask(&name, true); + check_str(name.got, "mode"); + fork_in_a_first_ask(&of_object, false); + check_str(of_object.got, "name"); + fork_in_a_first_ask(&of_signature, false); + check_str(of_signature.got, "mechanism"); + /* All three were held, or none was. */ + check(name.not_held == of_object.not_held && name.not_held == of_signature.not_held); + return name.not_held ? EXIT_SKIPPED : EXIT_SUCCESS; +} + +/* What a process that nothing tells from its children shares with one of + * them: a computation and a writer. */ +struct untold { + uapi16_sha256 *sha; + uapi16_manifest_writer *writer; +}; + +/* Gives this process the seccomp filter `filter` of `size` instructions, + * next to those it has. Returns false where it can't have one. */ +static bool filter_calls(struct sock_filter *filter, size_t size) { + struct sock_fprog program = { .len = (unsigned short) size, .filter = filter }; + + return prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == 0 && + syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &program) == 0; +} + +/* Keeps this process from the system call `nr` where its argument + * `argument`, counted from 0, has one of the bits `bits`, with a seccomp + * filter that fails such a call with `error`. Returns false where the + * process can't have a filter. */ +static bool refuse_flag(long nr, size_t argument, uint32_t bits, int error) { + /* Where the low half of that argument of a system call is. */ + const size_t flags = offsetof(struct seccomp_data, args) + argument * sizeof(uint64_t) + + (BYTE_ORDER == BIG_ENDIAN ? sizeof(uint32_t) : 0); + struct sock_filter filter[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, (uint32_t) nr, 0, 3), + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, (uint32_t) flags), + BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K, bits, 0, 1), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (uint32_t) error), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + }; + + return filter_calls(filter, ELEMENTSOF(filter)); +} + +/* Keeps this process from files without a name: an openat() with O_TMPFILE + * fails with EOPNOTSUPP, as on a file system that has no such files. A new + * file is in its directory under a temporary name then, on any file + * system. Returns false where the process can't have a filter. */ +static bool refuse_tmpfile(void) { + if (!refuse_flag(SYS_openat, 2, O_TMPFILE & ~O_DIRECTORY, EOPNOTSUPP)) + return false; + check_eq(openat(AT_FDCWD, ".", O_TMPFILE | O_RDWR | O_CLOEXEC, 0600), -1); + check_eq(errno, EOPNOTSUPP); + return true; +} + +/* Keeps this process from giving a file without a name its name by its + * descriptor: a linkat() with AT_EMPTY_PATH fails with ENOENT, as Linux + * before 6.10 fails it for a process that may not look up any name. Such a + * file gets its name through the link procfs has for its descriptor then. + * Returns false where the process can't have a filter. */ +static bool refuse_link_by_descriptor(void) { + if (!refuse_flag(SYS_linkat, 4, AT_EMPTY_PATH, ENOENT)) + return false; + check_eq(syscall(SYS_linkat, -1, "", -1, "", AT_EMPTY_PATH), -1); + check_eq(errno, ENOENT); + return true; +} + +/* Keeps this process from the system call `nr`, with a seccomp filter + * that fails every call of it with `error`. Returns false where the + * process can't have a filter. */ +static bool refuse_call(long nr, int error) { + struct sock_filter filter[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, (uint32_t) nr, 0, 1), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (uint32_t) error), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + }; + + if (!filter_calls(filter, ELEMENTSOF(filter))) + return false; + check_eq(syscall(nr, -1, NULL, -1, NULL, 0), -1); + check_eq(errno, error); + return true; +} + +/* + * What the test does when test_forks() runs it with WITHOUT_TMPFILE: a + * process keeps itself from files without a name, see refuse_tmpfile(). A + * new file is in its directory under a temporary name then, and a child + * that frees its writer leaves that name alone, see + * check_freed_in_a_child(). Returns what the process exits with. + */ +static int without_tmpfile(void) { + const char *tmpdir = getenv("TMPDIR"); + _cleanup_(closep) int dir = -1; + char path[PATH_MAX]; + + if (!refuse_tmpfile()) + return EXIT_SKIPPED; + + snprintf(path, sizeof(path), "%s/uapi16-capi-XXXXXX", tmpdir && *tmpdir ? tmpdir : "/tmp"); + check(mkdtemp(path)); + dir = open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + check(dir >= 0); + check_freed_in_a_child(dir); + check_eq(rmdir(path), 0); + return EXIT_SUCCESS; +} + +/* How the new file of linked_name() comes to its name. */ +enum linked { + /* It has a temporary name, which is linked and then removed. */ + LINKED, + /* The same, but the temporary name can't be removed. */ + LINKED_AND_LEFT, + /* It has no name, and is linked through procfs to a temporary + * name, which is linked and then removed. */ + LINKED_THROUGH_PROCFS, +}; + +/* Says why a part of test_linked_names() can't run here. Returns what its + * process exits with. ci.yml matches the start of the line, so that the C + * job of CI fails where a part did not run. */ +static int skip_linked_name(const char *why) { + fprintf(stderr, "skipping a new file that gets its name by a link: %s\n", why); + return EXIT_SKIPPED; +} + +/* + * What the test does when test_linked_names() runs it for the directory + * `path`: a process keeps itself from the rename that replaces nothing, + * see refuse_call(), as a file system does that has none. A new file gets + * its name by a link of a temporary name then, and the temporary name is + * removed once the file has its own. `how` says where the temporary name + * comes from. The process keeps itself from files without a name, see + * refuse_tmpfile(), so the file has the temporary name from the start. Or + * it keeps itself from linking a file by its descriptor, see + * refuse_link_by_descriptor(), so a file without a name gets the temporary + * name through procfs. With LINKED_AND_LEFT the process keeps itself from + * removing a name as well. The finish fails then, and the file keeps both + * names. The temporary one is left since nothing can remove it, as on a + * file system that refuses to, and not since the writer forgot it. Returns + * what the process exits with. + */ +static int linked_name(const char *path, enum linked how) { + _cleanup_(closep) int dir = open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC), fd = -1; + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = NULL; + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = NULL, *got = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + const bool left = how == LINKED_AND_LEFT, unnamed = how == LINKED_THROUGH_PROCFS; + const size_t names = left ? 2 : 1; + struct stat st; + int r; + + check(dir >= 0); + if (unnamed) { + /* What that way takes besides the filters: procfs, and a + * directory that has files without a name. */ + if (faccessat(AT_FDCWD, "/proc/self/fd", F_OK, 0) < 0) + return skip_linked_name("no /proc here"); + fd = openat(dir, ".", O_TMPFILE | O_RDWR | O_CLOEXEC, 0600); + if (fd < 0) + return skip_linked_name("no file without a name here"); + check_eq(close(fd), 0); + fd = -1; + } + if (!(unnamed ? refuse_link_by_descriptor() : refuse_tmpfile()) || + !refuse_call(SYS_renameat2, EINVAL) || (left && !refuse_call(SYS_unlinkat, EPERM))) + return skip_linked_name("no seccomp filter here"); + + o = uapi16_manifest_options_new(); + file = make_hello("file"); + check_eq(uapi16_manifest_writer_create_at(o, dir, "m", &w, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, file, &e), 0); + /* The name the file has until it gets its own, if it has one. */ + check_eq(count_entries(dir, "."), unnamed ? 0 : 1); + check_eq(faccessat(dir, "m", F_OK, 0), -1); + + r = uapi16_manifest_writer_finish(w, &report, &e); + if (left) { + check_error(r, e, UAPI16_ERROR_IO, EPERM, NULL, 0); + check(!report); + } else { + check_eq(r, 0); + check(!e); + check_eq(uapi16_manifest_report_files(report), 1); + } + + /* The file has its name, and the manifest in it is whole. What is + * in the directory besides is its temporary name, where that could + * not be removed. A free of the writer changes nothing of that. */ + check_eq(count_entries(dir, "."), names); + w = uapi16_manifest_writer_free(w); + check_eq(count_entries(dir, "."), names); + fd = openat(dir, "m", O_RDONLY | O_CLOEXEC); + check(fd >= 0); + check_eq(fstat(fd, &st), 0); + check_eq(st.st_nlink, names); + reader = open_reader(fd); + got = next_object(reader, "file"); + check_ends(reader); + return EXIT_SUCCESS; +} + +/* The child of a process without memory that is wiped in a child. Nothing + * tells it from its parent: its calls on the objects of its parent go on + * as in the parent, and it frees the writer of its parent as the parent + * would. */ +static int child_without_wipe_on_fork(void *argument) { + struct untold *untold = argument; + uapi16_sha256 *own = uapi16_sha256_new(); + + check_eq(uapi16_sha256_update(untold->sha, "x", 1), 0); + check_eq(uapi16_sha256_update(own, "x", 1), 0); + uapi16_sha256_free(own); + uapi16_manifest_writer_free(untold->writer); + return EXIT_SUCCESS; +} + +/* + * What the test does when test_forks() runs it with WITHOUT_WIPE_ON_FORK: + * a process that has used nothing of the library yet keeps itself from + * memory that is wiped in a child, with a seccomp filter that refuses the + * advice MADV_WIPEONFORK of madvise() with EINVAL, as a kernel does that + * has none. The library has nothing to tell a child by then, and nothing + * to fall back to: the calls go on, in a child as in its parent, and + * nothing waits or stops. A child that frees a writer frees it as its + * parent would. That empties no file the writer keeps, so the writer of + * the parent finishes all the same. What such a free takes with it is the + * name a new file has until it is complete, on a file system that gives + * it one, see test_fat(). Returns what the process exits with. + */ +static int without_wipe_on_fork(void) { + /* Where the low half of the third argument of a system call is. */ + const uint32_t advice = offsetof(struct seccomp_data, args[2]) + + (BYTE_ORDER == BIG_ENDIAN ? sizeof(uint32_t) : 0); + struct sock_filter filter[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_madvise, 0, 3), + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, advice), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, MADV_WIPEONFORK, 0, 1), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EINVAL), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + }; + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(closep) int out = -1; + bool before[SCRATCH_DESCRIPTORS], scratch[SCRATCH_DESCRIPTORS], spilled; + long size = sysconf(_SC_PAGESIZE); + struct untold untold = { .sha = NULL }; + uapi16_sha256_digest_t hash; + void *page; + int r; + + if (!filter_calls(filter, ELEMENTSOF(filter))) + return EXIT_SKIPPED; + check(size > 0); + page = mmap(NULL, (size_t) size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + check(page != MAP_FAILED); + check_eq(madvise(page, (size_t) size, MADV_WIPEONFORK), -1); + check_eq(errno, EINVAL); + check_eq(madvise(page, (size_t) size, MADV_DONTNEED), 0); + check_eq(munmap(page, (size_t) size), 0); + + /* A computation, and a writer that keeps file objects in files of + * its own. These are the first calls of the process. */ + untold.sha = uapi16_sha256_new(); + check_eq(uapi16_sha256_update(untold.sha, "a", 1), 0); + o = uapi16_manifest_options_new(); + out = memfd_create("manifest", MFD_CLOEXEC); + check(o && out >= 0); + unnamed_files(before); + check_eq(uapi16_manifest_writer_open(o, out, &untold.writer, &e), 0); + spilled = add_scratch_files(untold.writer, before, scratch); + if (!spilled) + untold.writer = uapi16_manifest_writer_free(untold.writer); + + check_eq(in_child(child_without_wipe_on_fork, &untold), EXIT_SUCCESS); + + /* What the child did to its copy of the computation did nothing to + * the one of the parent. */ + check_eq(uapi16_sha256_update(untold.sha, "bc", 2), 0); + check_eq(uapi16_sha256_finish(untold.sha, &hash), 0); + check_hash(&hash, SHA256_OF_ABC); + uapi16_sha256_free(untold.sha); + /* The files of the writer are those of the child as well, and the + * child left them as they are when it freed its copy. */ + if (spilled) { + r = uapi16_manifest_writer_finish(untold.writer, &report, &e); + if (!no_room(r)) { + check_eq(r, 0); + check_eq(uapi16_manifest_report_files(report), 2 * SCRATCH_INODES); + } + } + uapi16_manifest_writer_free(untold.writer); + return EXIT_SUCCESS; +} + +/* A fork is told in the child, however the child came to be: the child of + * a child, one that makes a child before it uses the library, one whose + * first calls come from several threads at once, one that has the PID of + * its parent, one that is forked while another thread makes the first call + * of its parent or asks for a string the first time. The parent is the + * process it was after each of them. In a process that can't have memory + * that is wiped in a child, nothing tells a child, and its calls go on. */ +static void test_forks(void) { + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *sha = uapi16_sha256_new(); + struct lineage lineage = { .of_parent = sha }; + uapi16_sha256_digest_t hash; + int code; + + check_eq(uapi16_sha256_update(sha, "a", 1), 0); + check_eq(in_child(child_with_grandchild, &lineage), EXIT_SUCCESS); + check_eq(in_child(idle_child_with_grandchild, &lineage), EXIT_SUCCESS); + check_eq(in_child(child_with_threads, sha), EXIT_SUCCESS); + check_eq(uapi16_sha256_update(sha, "b", 1), 0); + + code = in_child(namespace_of_its_own, sha); + if (code == EXIT_SKIPPED) + fprintf(stderr, "skipping a child with the PID of its parent: no user and PID namespace here\n"); + else + check_eq(code, EXIT_SUCCESS); + + check_eq(in_new_process(FORK_IN_THE_FIRST_CALL, NULL), EXIT_SUCCESS); + check_eq(in_new_process(FIRST_CALLS_AT_ONCE, NULL), EXIT_SUCCESS); + code = in_new_process(FORK_IN_THE_FIRST_ASK, NULL); + if (code == EXIT_SKIPPED) + fprintf(stderr, "skipping a fork in a first ask for a string: the shared library allocates " + "past the malloc() of the test\n"); + else + check_eq(code, EXIT_SUCCESS); + /* ci.yml matches the starts of the next two skip lines, so that the + * C job of CI fails where a part under a seccomp filter did not + * run. */ + code = in_new_process(WITHOUT_TMPFILE, NULL); + if (code == EXIT_SKIPPED) + fprintf(stderr, "skipping a new file under a temporary name: no seccomp filter here\n"); + else + check_eq(code, EXIT_SUCCESS); + code = in_new_process(WITHOUT_WIPE_ON_FORK, NULL); + if (code == EXIT_SKIPPED) + fprintf(stderr, "skipping a fork that nothing tells: no seccomp filter here\n"); + else + check_eq(code, EXIT_SUCCESS); + + /* What the children did to their copies did nothing to this one. */ + check_eq(uapi16_sha256_update(sha, "c", 1), 0); + check_eq(uapi16_sha256_finish(sha, &hash), 0); + check_hash(&hash, SHA256_OF_ABC); +} + +/* A new file gets its name by a link where its file system has no rename + * that replaces nothing. Three processes that keep themselves from that + * rename make a manifest that way, each in a directory of its own, see + * linked_name(). One that can't run here says why. */ +static void test_linked_names(void) { + static const struct { + const char *what, *dir; + } parts[] = { + { WITH_A_LINKED_NAME, "linked-name" }, + { WITH_A_NAME_LEFT, "name-left" }, + { WITH_A_NAME_THROUGH_PROCFS, "name-through-procfs" }, + }; + char path[PATH_MAX]; + + for (size_t i = 0; i < ELEMENTSOF(parts); i++) { + int code; + + check_eq(mkdirat(tmp_fd, parts[i].dir, 0755), 0); + check((size_t) snprintf(path, sizeof(path), "%s/%s", tmp_path, parts[i].dir) < sizeof(path)); + code = in_new_process(parts[i].what, path); + check(code == EXIT_SUCCESS || code == EXIT_SKIPPED); + } +} + +/* The objects that go from thread to thread, one of every kind, and what + * the threads do with them. */ +struct step { + uapi16_manifest_writer *writer; + uapi16_manifest_report *report; + uapi16_error *error; + uapi16_file_object *file, *refused, *got; + uapi16_reader *reader; + uapi16_writer *records; + uapi16_signature *signature; + uapi16_sha256 *sha; + uapi16_data_check *data; + uapi16_directory *directory; + uapi16_sha256_digest_t hash; + uint64_t files, size; + int r; +}; + +static void *add_in_thread(void *argument) { + struct step *step = argument; + + check_eq(uapi16_manifest_writer_add_object(step->writer, step->file, NULL), 0); + check_eq(uapi16_writer_file(step->records, step->file, NULL), 0); + check_eq(uapi16_reader_next(step->reader, &step->got, NULL), UAPI16_READ_FILE); + check_eq(uapi16_signature_set_key(step->signature, "key", 3), 0); + check_eq(uapi16_sha256_update(step->sha, "hel", 3), 0); + check_eq(uapi16_data_check_update(step->data, "hel", 3, NULL), 0); + check_eq(uapi16_file_object_set_fs_label(step->refused, "label"), 0); + step->r = uapi16_manifest_writer_add_object(step->writer, step->refused, &step->error); + return NULL; +} + +static void *finish_in_thread(void *argument) { + struct step *step = argument; + uapi16_file_object *none = NULL; + + check_eq(uapi16_writer_signature(step->records, step->signature, NULL), 0); + check_eq(uapi16_writer_finish(step->records, NULL), 0); + check_eq(uapi16_reader_next(step->reader, &none, NULL), UAPI16_READ_END); + check_eq(uapi16_sha256_update(step->sha, "lo", 2), 0); + check_eq(uapi16_sha256_finish(step->sha, &step->hash), 0); + check_eq(uapi16_data_check_update(step->data, "lo", 2, NULL), 0); + check_eq(uapi16_data_check_finish(step->data, &step->size, NULL), 0); + step->r = uapi16_manifest_writer_finish(step->writer, &step->report, NULL); + return NULL; +} + +static void *read_in_thread(void *argument) { + struct step *step = argument; + + step->files = uapi16_manifest_report_files(step->report); + check_eq(uapi16_error_errno(step->error), EBADMSG); + check_str(uapi16_error_path(step->error), "refused"); + check_str(uapi16_error_field(step->error), "fsLabel"); + check_str(uapi16_file_object_name(step->got), "a"); + check_str(uapi16_file_object_name(step->file), "hello"); + check_str(uapi16_signature_mechanism(step->signature), "openpgp"); + return NULL; +} + +static void *free_in_thread(void *argument) { + struct step *step = argument; + + step->writer = uapi16_manifest_writer_free(step->writer); + step->report = uapi16_manifest_report_free(step->report); + step->error = uapi16_error_free(step->error); + step->file = uapi16_file_object_free(step->file); + step->refused = uapi16_file_object_free(step->refused); + step->got = uapi16_file_object_free(step->got); + step->reader = uapi16_reader_free(step->reader); + step->records = uapi16_writer_free(step->records); + step->signature = uapi16_signature_free(step->signature); + step->sha = uapi16_sha256_free(step->sha); + step->data = uapi16_data_check_free(step->data); + step->directory = uapi16_directory_free(step->directory); + return NULL; +} + +/* How many threads read what nothing changes at the same time, and how + * often each does. */ +#define READERS 4 +#define ROUNDS 200 + +/* A file object, a report and an error that nothing changes, and what lets + * the threads that read them start together. */ +struct shared { + pthread_barrier_t start; + const uapi16_file_object *file; + const uapi16_manifest_report *report; + const uapi16_error *error; +}; + +static void *read_shared(void *argument) { + struct shared *shared = argument; + int r = pthread_barrier_wait(&shared->start); + + check(r == 0 || r == PTHREAD_BARRIER_SERIAL_THREAD); + for (int i = 0; i < ROUNDS; i++) { + uapi16_sha256_digest_t hash; + uint32_t mode = 0, stated = 0, set = 0; + uint64_t size = 0, record = 0; + size_t count = 0, value_size = 0; + const char *name = NULL; + const void *value = NULL; + + check_str(uapi16_file_object_name(shared->file), "dir/file"); + check_str(uapi16_file_object_user_name(shared->file), "user"); + check_str(uapi16_file_object_group_name(shared->file), "group"); + check_eq(uapi16_file_object_type(shared->file), S_IFREG); + check_eq(uapi16_file_object_mode(shared->file, &mode), 0); + check_eq(mode, 0644); + check_eq(uapi16_file_object_size(shared->file, &size), 0); + check_eq(size, 5); + check_eq(uapi16_file_object_sha256(shared->file, &hash), 0); + check_hash(&hash, SHA256_OF_HELLO); + check_eq(uapi16_file_object_user_xattrs(shared->file, &count), 0); + check_eq(count, 2); + check_eq(uapi16_file_object_user_xattr(shared->file, 1, &name, &value, &value_size), 0); + check_str(name, "b"); + check_same(value, value_size, "two", 3); + check_eq(uapi16_file_object_inode_flags(shared->file, &stated, &set), 0); + check_eq(stated, NODUMP_FL); + check_eq(set, 0); + check_eq(uapi16_file_object_read_only(shared->file), UAPI16_READ_ONLY_NO); + check_eq(uapi16_file_object_data_location(shared->file), UAPI16_DATA_LOCATION_EXTERNAL); + check(uapi16_file_object_has_stated_feature(shared->file, UAPI16_FEATURE_USER_XATTR)); + check_eq(uapi16_file_object_check_validity(shared->file, 0, NULL), 0); + + check_eq(uapi16_manifest_report_files(shared->report), 1); + check_eq(uapi16_manifest_report_bytes(shared->report), 5); + check_eq(uapi16_error_kind(shared->error), UAPI16_ERROR_MANIFEST); + check_eq(uapi16_error_errno(shared->error), EBADMSG); + check_str(uapi16_error_path(shared->error), "refused"); + check_str(uapi16_error_field(shared->error), "fsLabel"); + check_str(uapi16_error_problem(shared->error), "fieldNotPermitted"); + check_eq(uapi16_error_record(shared->error, &record), -ENODATA); + } + return NULL; +} + +static void test_threads(void) { + void *(*const steps[])(void *) = { add_in_thread, finish_in_thread, read_in_thread, free_in_thread }; + _cleanup_(closep) int out = make_dir(tmp_fd, "threads-out"), written = scratch_file(); + _cleanup_(closep) int manifest = manifest_file(ROOT FILE_OBJECT("a") TRAILER); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_hello("dir/file"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *refused = make_object("refused"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *counted = make_hello("counted"); + _cleanup_(uapi16_error_freep) uapi16_error *error = NULL; + _cleanup_(freep) char *made = NULL, *records = NULL; + struct step step = { .file = make_hello("hello"), .refused = make_object("refused") }; + struct shared shared; + pthread_t readers[READERS]; + size_t made_size, records_size; + + check_eq(uapi16_manifest_writer_create_at(o, out, "m", &step.writer, NULL), 0); + step.records = begin_records(o, written); + step.reader = open_reader(manifest); + check_eq(uapi16_signature_new("openpgp", &step.signature), 0); + step.sha = uapi16_sha256_new(); + check_eq(uapi16_data_check_new(step.file, &step.data), 0); + check_eq(uapi16_directory_new(out, UAPI16_DIRECTORY_NONE, &step.directory, NULL), 0); + + /* An object is used by one thread at a time, which need not be the + * one that made it. Each step here is a thread of its own. */ + for (size_t i = 0; i < ELEMENTSOF(steps); i++) { + pthread_t thread; + + check_eq(pthread_create(&thread, NULL, steps[i], &step), 0); + check_eq(pthread_join(thread, NULL), 0); + if (steps[i] == add_in_thread) + check_eq(step.r, -EBADMSG); + if (steps[i] == finish_in_thread) + check_eq(step.r, 0); + } + check_eq(step.files, 1); + check_eq(step.size, 5); + check_hash(&step.hash, SHA256_OF_HELLO); + check(!step.writer && !step.report && !step.error && !step.file && !step.refused && !step.got); + check(!step.reader && !step.records && !step.signature && !step.sha && !step.data); + check(!step.directory); + made = read_file(out, "m", &made_size); + check_manifest(made, made_size); + check(strstr(made, "\"name\":\"hello\"")); + records = read_all(written, &records_size); + check_manifest(records, records_size); + check(strstr(records, "\"mechanism\":\"openpgp\"")); + + /* A file object that no thread changes is read from several threads + * at the same time, and so are a report and an error. The strings + * they hand out are asked for by all of the threads first. */ + check_eq(uapi16_file_object_set_mode(file, 0644), 0); + check_eq(uapi16_file_object_set_user_name(file, "user"), 0); + check_eq(uapi16_file_object_set_group_name(file, "group"), 0); + check_eq(uapi16_file_object_add_user_xattr(file, "b", "two", 3), 0); + check_eq(uapi16_file_object_add_user_xattr(file, "a", "one", 3), 0); + check_eq(uapi16_file_object_set_inode_flags(file, NODUMP_FL, 0), 0); + check_eq(uapi16_file_object_set_read_only(file, UAPI16_READ_ONLY_NO), 0); + check_eq(uapi16_file_object_set_fs_label(refused, "label"), 0); + w = open_writer(o); + check_eq(uapi16_manifest_writer_add_object(w, refused, &error), -EBADMSG); + check_eq(uapi16_manifest_writer_add_object(w, counted, NULL), 0); + check_eq(uapi16_manifest_writer_finish(w, &report, NULL), 0); + shared.file = file; + shared.report = report; + shared.error = error; + check_eq(pthread_barrier_init(&shared.start, NULL, READERS), 0); + for (size_t i = 0; i < READERS; i++) + check_eq(pthread_create(&readers[i], NULL, read_shared, &shared), 0); + for (size_t i = 0; i < READERS; i++) + check_eq(pthread_join(readers[i], NULL), 0); + check_eq(pthread_barrier_destroy(&shared.start), 0); +} + +/* + * A file object stores what it is given and gives it back: every setter + * with its getter. A getter of a number the object does not have fails + * with -ENODATA and stores nothing, and one of a string returns NULL. The + * object keeps a copy of what it is given, and says which features its + * fields are of. + */ +static void test_file_objects(void) { + static const uint32_t types[] = { S_IFREG, S_IFDIR, S_IFLNK, S_IFIFO, S_IFCHR, S_IFBLK, S_IFSOCK }; + static const uint32_t no_types[] = { 0, 0777, S_IFMT, S_IFMT | 0644 }; + static const struct { + uint32_t flag; + uapi16_feature_t feature; + } inode_flags[] = { + { APPEND_FL, UAPI16_FEATURE_FLAG_APPEND_ONLY }, + { IMMUTABLE_FL, UAPI16_FEATURE_FLAG_IMMUTABLE }, + { NOATIME_FL, UAPI16_FEATURE_FLAG_NO_ATIME }, + { NOCOW_FL, UAPI16_FEATURE_FLAG_NO_COW }, + { NODUMP_FL, UAPI16_FEATURE_FLAG_NO_DUMP }, + }, dos_attributes[] = { + { DOS_HIDDEN, UAPI16_FEATURE_FLAG_HIDDEN }, + { DOS_SYSTEM, UAPI16_FEATURE_FLAG_SYSTEM }, + { DOS_ARCHIVE, UAPI16_FEATURE_FLAG_ARCHIVE }, + }; + static const char target[] = { 't', 'o', 0, '/', (char) 0xff }; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = NULL, *none = NULL, *other = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + uapi16_sha256_digest_t hash, read_hash = { .bytes = { 0 } }; + uapi16_uuid_t uuid = { .bytes = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } }; + uapi16_uuid_t read_uuid = { .bytes = { 0 } }; + char text[] = "copied", bytes[] = { 'b', 0, 'c' }; + const char *name, *user, *group, *label, *xattr_name = NULL; + const char *contents_file = NULL, *other_file = NULL; + uapi16_features_t features = features_none(); + uint64_t number = 77, offset = 77; + uapi16_inode_token_t token = 77; + uint32_t small = 77, stated = 77, set = 77; + size_t count = 77, size = 77; + const void *value = NULL; + + /* A new object is a regular file that says nothing else. */ + check_eq(uapi16_file_object_new("dir/file", &o, &e), 0); + check(o && !e); + name = uapi16_file_object_name(o); + check_str(name, "dir/file"); + check_eq(uapi16_file_object_type(o), S_IFREG); + check_stated(o, features_none()); + check_eq(uapi16_file_object_read_only(o), UAPI16_READ_ONLY_UNSTATED); + check_eq(uapi16_file_object_check_validity(o, 0, &e), 0); + check_eq(uapi16_file_object_check_validity(o, UINT64_MAX, NULL), 0); + + /* It needs a name, and a place to go to. */ + check_misuse(uapi16_file_object_new(NULL, &none, &e), &e, EINVAL); + check_misuse(uapi16_file_object_new("x", NULL, &e), &e, EINVAL); + check_eq(uapi16_file_object_new(NULL, &none, NULL), -EINVAL); + check_eq(uapi16_file_object_new("x", NULL, NULL), -EINVAL); + check(!none); + + /* The name: the object keeps its own copy, and hands out a string + * that stays until the name is set again. */ + check_eq(uapi16_file_object_set_name(o, text, &e), 0); + text[0] = 'C'; + name = uapi16_file_object_name(o); + check_str(name, "copied"); + check_eq(uapi16_file_object_set_uid(o, 0), 0); + check_str(name, "copied"); + check_eq(uapi16_file_object_set_name(o, "dir/file", NULL), 0); + check_str(uapi16_file_object_name(o), "dir/file"); + check_misuse(uapi16_file_object_set_name(NULL, "x", &e), &e, EINVAL); + check_misuse(uapi16_file_object_set_name(o, NULL, &e), &e, EINVAL); + check_str(uapi16_file_object_name(o), "dir/file"); + check(!uapi16_file_object_name(NULL)); + features = WITH(features, UAPI16_FEATURE_UID); + + /* The type, as the bits of the file type in an st_mode. The other + * bits are not read, and bits that are no type are refused. */ + for (size_t i = 0; i < ELEMENTSOF(types); i++) { + check_eq(uapi16_file_object_set_type(o, types[i] | 0755), 0); + check_eq(uapi16_file_object_type(o), types[i]); + } + for (size_t i = 0; i < ELEMENTSOF(no_types); i++) { + check_eq(uapi16_file_object_set_type(o, no_types[i]), -EINVAL); + check_eq(uapi16_file_object_type(o), S_IFSOCK); + } + check_eq(uapi16_file_object_set_type(o, S_IFREG), 0); + check_eq(uapi16_file_object_set_type(NULL, S_IFREG), -EINVAL); + check_eq(uapi16_file_object_type(NULL), 0); + + /* The access mode: the permission bits with the set-user-ID, the + * set-group-ID and the sticky bit. The bits of the file type are + * not read, and don't change the type. */ + check_eq(uapi16_file_object_mode(o, &small), -ENODATA); + check_eq(small, 77); + check_eq(uapi16_file_object_set_mode(o, S_IFDIR | 04755), 0); + check_eq(uapi16_file_object_mode(o, &small), 0); + check_eq(small, 04755); + check_eq(uapi16_file_object_type(o), S_IFREG); + check_eq(uapi16_file_object_set_mode(o, 07777), 0); + check_eq(uapi16_file_object_mode(o, &small), 0); + check_eq(small, 07777); + check_eq(uapi16_file_object_set_mode(o, 0), 0); + check_eq(uapi16_file_object_mode(o, &small), 0); + check_eq(small, 0); + /* A bit that is neither is refused, and the mode stays. */ + check_eq(uapi16_file_object_set_mode(o, (S_IFMT | 07777) + 1), -EINVAL); + check_eq(uapi16_file_object_set_mode(o, ~(uint32_t) S_IFMT), -EINVAL); + check_eq(uapi16_file_object_mode(o, &small), 0); + check_eq(small, 0); + check_eq(uapi16_file_object_set_mode(NULL, 0644), -EINVAL); + check_eq(uapi16_file_object_mode(NULL, &small), -EINVAL); + check_eq(uapi16_file_object_mode(o, NULL), -EINVAL); + features = WITH(features, UAPI16_FEATURE_MODE); + check_stated(o, features); + + /* The owner, by its IDs. The object had its user ID from above. */ + small = 77; + check_eq(uapi16_file_object_uid(o, &small), 0); + check_eq(small, 0); + check_eq(uapi16_file_object_set_uid(o, UINT32_MAX), 0); + check_eq(uapi16_file_object_uid(o, &small), 0); + check_eq(small, UINT32_MAX); + check_eq(uapi16_file_object_set_uid(NULL, 1), -EINVAL); + check_eq(uapi16_file_object_uid(NULL, &small), -EINVAL); + check_eq(uapi16_file_object_uid(o, NULL), -EINVAL); + small = 77; + check_eq(uapi16_file_object_gid(o, &small), -ENODATA); + check_eq(small, 77); + check_eq(uapi16_file_object_set_gid(o, 1000), 0); + check_eq(uapi16_file_object_gid(o, &small), 0); + check_eq(small, 1000); + check_eq(uapi16_file_object_set_gid(NULL, 1), -EINVAL); + check_eq(uapi16_file_object_gid(NULL, &small), -EINVAL); + check_eq(uapi16_file_object_gid(o, NULL), -EINVAL); + features = WITH(features, UAPI16_FEATURE_GID); + check_stated(o, features); + + /* The owner, by its names. A string that is handed out belongs to + * the object and stays while other fields change. */ + check(!uapi16_file_object_user_name(o)); + check(!uapi16_file_object_group_name(o)); + text[0] = 'c'; + check_eq(uapi16_file_object_set_user_name(o, text), 0); + check_eq(uapi16_file_object_set_group_name(o, text), 0); + text[0] = 'C'; + user = uapi16_file_object_user_name(o); + group = uapi16_file_object_group_name(o); + check_str(user, "copied"); + check_str(group, "copied"); + check_eq(uapi16_file_object_set_group_name(o, "group"), 0); + check_str(user, "copied"); + check_str(uapi16_file_object_group_name(o), "group"); + /* A string lives until its field is set again: the one that + * uapi16_file_object_group_name() handed out before is gone now, + * and is not read here. The address sanitizer would say so. A + * string stays where it is while other fields are set, which the + * line above checks. */ + check_eq(uapi16_file_object_set_user_name(o, "user"), 0); + check_str(uapi16_file_object_user_name(o), "user"); + check_eq(uapi16_file_object_set_user_name(o, NULL), -EINVAL); + check_eq(uapi16_file_object_set_group_name(o, NULL), -EINVAL); + check_eq(uapi16_file_object_set_user_name(NULL, "user"), -EINVAL); + check_eq(uapi16_file_object_set_group_name(NULL, "group"), -EINVAL); + check_str(uapi16_file_object_user_name(o), "user"); + check_str(uapi16_file_object_group_name(o), "group"); + check(!uapi16_file_object_user_name(NULL)); + check(!uapi16_file_object_group_name(NULL)); + features = WITH(features, UAPI16_FEATURE_USER_NAME, UAPI16_FEATURE_GROUP_NAME); + check_stated(o, features); + + /* The modification time and the size, which are any number. */ + check_eq(uapi16_file_object_mtime_nsec(o, &number), -ENODATA); + check_eq(number, 77); + check_eq(uapi16_file_object_set_mtime_nsec(o, 0), 0); + check_eq(uapi16_file_object_mtime_nsec(o, &number), 0); + check_eq(number, 0); + check_eq(uapi16_file_object_set_mtime_nsec(o, UINT64_MAX), 0); + check_eq(uapi16_file_object_mtime_nsec(o, &number), 0); + check_eq(number, UINT64_MAX); + check_eq(uapi16_file_object_set_mtime_nsec(NULL, 1), -EINVAL); + check_eq(uapi16_file_object_mtime_nsec(NULL, &number), -EINVAL); + check_eq(uapi16_file_object_mtime_nsec(o, NULL), -EINVAL); + number = 77; + check_eq(uapi16_file_object_size(o, &number), -ENODATA); + check_eq(number, 77); + check_eq(uapi16_file_object_set_size(o, 0), 0); + check_eq(uapi16_file_object_size(o, &number), 0); + check_eq(number, 0); + check_eq(uapi16_file_object_set_size(o, UINT64_MAX), 0); + check_eq(uapi16_file_object_size(o, &number), 0); + check_eq(number, UINT64_MAX); + check_eq(uapi16_file_object_set_size(NULL, 1), -EINVAL); + check_eq(uapi16_file_object_size(NULL, &number), -EINVAL); + check_eq(uapi16_file_object_size(o, NULL), -EINVAL); + features = WITH(features, UAPI16_FEATURE_MTIME, UAPI16_FEATURE_SIZE); + check_stated(o, features); + + /* The hash, of which the object keeps a copy. */ + unhex(SHA256_OF_HELLO, &hash); + check_eq(uapi16_file_object_sha256(o, &read_hash), -ENODATA); + check_eq(read_hash.bytes[0], 0); + check_eq(uapi16_file_object_set_sha256(o, &hash), 0); + memset(&hash, 0, sizeof(hash)); + check_eq(uapi16_file_object_sha256(o, &read_hash), 0); + check_hash(&read_hash, SHA256_OF_HELLO); + check_eq(uapi16_file_object_set_sha256(o, NULL), -EINVAL); + check_eq(uapi16_file_object_set_sha256(NULL, &hash), -EINVAL); + check_eq(uapi16_file_object_sha256(NULL, &read_hash), -EINVAL); + check_eq(uapi16_file_object_sha256(o, NULL), -EINVAL); + memset(&read_hash, 0, sizeof(read_hash)); + check_eq(uapi16_file_object_sha256(o, &read_hash), 0); + check_hash(&read_hash, SHA256_OF_HELLO); + features = WITH(features, UAPI16_FEATURE_SHA256); + check_stated(o, features); + + /* The device numbers, each on its own. */ + number = 77; + check_eq(uapi16_file_object_major(o, &number), -ENODATA); + check_eq(uapi16_file_object_minor(o, &number), -ENODATA); + check_eq(number, 77); + check_eq(uapi16_file_object_set_major(o, 8), 0); + check_eq(uapi16_file_object_major(o, &number), 0); + check_eq(number, 8); + check_eq(uapi16_file_object_minor(o, &number), -ENODATA); + check_eq(number, 8); + features = WITH(features, UAPI16_FEATURE_DEVICE); + check_stated(o, features); + check_eq(uapi16_file_object_set_minor(o, UINT64_MAX), 0); + check_eq(uapi16_file_object_minor(o, &number), 0); + check_eq(number, UINT64_MAX); + check_eq(uapi16_file_object_set_major(NULL, 1), -EINVAL); + check_eq(uapi16_file_object_set_minor(NULL, 1), -EINVAL); + check_eq(uapi16_file_object_major(NULL, &number), -EINVAL); + check_eq(uapi16_file_object_minor(NULL, &number), -EINVAL); + check_eq(uapi16_file_object_major(o, NULL), -EINVAL); + check_eq(uapi16_file_object_minor(o, NULL), -EINVAL); + check_stated(o, features); + + /* The token of the names of one file: any number but 0, and + * UAPI16_INODE_TOKEN_NONE takes the token away. Without one there + * is nothing to get. */ + check_eq(uapi16_file_object_inode_token(o, &token), -ENODATA); + check_eq(token, 77); + check_eq(uapi16_file_object_set_inode_token(o, UINT64_MAX), 0); + check_eq(uapi16_file_object_inode_token(o, &token), 0); + check_eq(token, UINT64_MAX); + check_stated(o, WITH(features, UAPI16_FEATURE_HARDLINK)); + check_eq(uapi16_file_object_set_inode_token(o, UAPI16_INODE_TOKEN_NONE), 0); + token = 77; + check_eq(uapi16_file_object_inode_token(o, &token), -ENODATA); + check_eq(token, 77); + check_stated(o, features); + check_eq(uapi16_file_object_set_inode_token(o, 1), 0); + check_eq(uapi16_file_object_inode_token(o, &token), 0); + check_eq(token, 1); + check_eq(uapi16_file_object_set_inode_token(NULL, 1), -EINVAL); + check_eq(uapi16_file_object_inode_token(NULL, &token), -EINVAL); + check_eq(uapi16_file_object_inode_token(o, NULL), -EINVAL); + features = WITH(features, UAPI16_FEATURE_HARDLINK); + check_stated(o, features); + + /* The extended attributes: none said, then listed and none there, + * then some, which are read in the order of their names. One that + * is added again gets the new value. */ + check_eq(uapi16_file_object_user_xattrs(o, &count), -ENODATA); + check_eq(count, 77); + check_eq(uapi16_file_object_user_xattr(o, 0, &xattr_name, &value, &size), -EINVAL); + check_stated(o, features); + check_eq(uapi16_file_object_set_user_xattrs(o), 0); + check_eq(uapi16_file_object_user_xattrs(o, &count), 0); + check_eq(count, 0); + check_eq(uapi16_file_object_user_xattr(o, 0, &xattr_name, &value, &size), -EINVAL); + features = WITH(features, UAPI16_FEATURE_USER_XATTR); + check_stated(o, features); + text[0] = 'c'; + check_eq(uapi16_file_object_add_user_xattr(o, "c", "three", 5), 0); + check_eq(uapi16_file_object_add_user_xattr(o, "a", NULL, 0), 0); + check_eq(uapi16_file_object_add_user_xattr(o, text, bytes, sizeof(bytes)), 0); + check_eq(uapi16_file_object_add_user_xattr(o, "b", "two", 3), 0); + check_eq(uapi16_file_object_add_user_xattr(o, "c", unreadable(), 0), 0); + check_eq(uapi16_file_object_add_user_xattr(o, "b", bytes, sizeof(bytes)), 0); + text[0] = 'C'; + bytes[0] = 'B'; + check_eq(uapi16_file_object_user_xattrs(o, &count), 0); + check_eq(count, 4); + check_eq(uapi16_file_object_user_xattr(o, 0, &xattr_name, &value, &size), 0); + check_str(xattr_name, "a"); + check_eq(size, 0); + check_eq(uapi16_file_object_user_xattr(o, 1, &xattr_name, &value, &size), 0); + check_str(xattr_name, "b"); + check_same(value, size, "b\0c", 3); + check_eq(uapi16_file_object_user_xattr(o, 2, &xattr_name, &value, &size), 0); + check_str(xattr_name, "c"); + check_eq(size, 0); + check_eq(uapi16_file_object_user_xattr(o, 3, &xattr_name, &value, &size), 0); + check_str(xattr_name, "copied"); + check_same(value, size, "b\0c", 3); + /* Each of the three places can be NULL, and what was handed out + * stays while the object is only read. */ + check_eq(uapi16_file_object_user_xattr(o, 1, NULL, NULL, NULL), 0); + check_eq(uapi16_file_object_user_xattr(o, 1, NULL, NULL, &size), 0); + check_eq(size, 3); + check_str(xattr_name, "copied"); + check_same(value, 3, "b\0c", 3); + /* An attribute beyond the last one stores nothing. */ + xattr_name = NULL; + value = NULL; + size = 77; + check_eq(uapi16_file_object_user_xattr(o, 4, &xattr_name, &value, &size), -EINVAL); + check_eq(uapi16_file_object_user_xattr(o, SIZE_MAX, &xattr_name, &value, &size), -EINVAL); + check(!xattr_name && !value && size == 77); + check_eq(uapi16_file_object_add_user_xattr(o, NULL, "v", 1), -EINVAL); + check_eq(uapi16_file_object_add_user_xattr(o, "d", NULL, 1), -EINVAL); + check_eq(uapi16_file_object_add_user_xattr(NULL, "d", "v", 1), -EINVAL); + check_eq(uapi16_file_object_set_user_xattrs(NULL), -EINVAL); + check_eq(uapi16_file_object_user_xattrs(NULL, &count), -EINVAL); + check_eq(uapi16_file_object_user_xattrs(o, NULL), -EINVAL); + check_eq(uapi16_file_object_user_xattr(NULL, 0, &xattr_name, &value, &size), -EINVAL); + check_eq(uapi16_file_object_user_xattrs(o, &count), 0); + check_eq(count, 4); + /* Listing them again lists none, and an attribute that is added to + * an object that said nothing makes it list its attributes. */ + check_eq(uapi16_file_object_set_user_xattrs(o), 0); + check_eq(uapi16_file_object_user_xattrs(o, &count), 0); + check_eq(count, 0); + check_eq(uapi16_file_object_user_xattr(o, 0, &xattr_name, &value, &size), -EINVAL); + check(!xattr_name && !value && size == 77); + check_stated(o, features); + check_eq(uapi16_file_object_new("other", &other, &e), 0); + check_eq(uapi16_file_object_add_user_xattr(other, "only", "1", 1), 0); + check_eq(uapi16_file_object_user_xattrs(other, &count), 0); + check_eq(count, 1); + check_stated(other, FEATURES(UAPI16_FEATURE_USER_XATTR)); + check_eq(uapi16_file_object_user_xattrs(o, &count), 0); + check_eq(count, 0); + + /* Whether the file is read-only: three answers, and no other. */ + check_eq(uapi16_file_object_read_only(o), UAPI16_READ_ONLY_UNSTATED); + check_eq(uapi16_file_object_set_read_only(o, UAPI16_READ_ONLY_YES), 0); + check_eq(uapi16_file_object_read_only(o), UAPI16_READ_ONLY_YES); + check_stated(o, WITH(features, UAPI16_FEATURE_READ_ONLY)); + check_eq(uapi16_file_object_set_read_only(o, 3), -EINVAL); + check_eq(uapi16_file_object_set_read_only(o, UINT64_MAX), -EINVAL); + check_eq(uapi16_file_object_read_only(o), UAPI16_READ_ONLY_YES); + check_eq(uapi16_file_object_set_read_only(o, UAPI16_READ_ONLY_UNSTATED), 0); + check_eq(uapi16_file_object_read_only(o), UAPI16_READ_ONLY_UNSTATED); + check_stated(o, features); + check_eq(uapi16_file_object_set_read_only(o, UAPI16_READ_ONLY_NO), 0); + check_eq(uapi16_file_object_read_only(o), UAPI16_READ_ONLY_NO); + check_eq(uapi16_file_object_set_read_only(NULL, UAPI16_READ_ONLY_YES), -EINVAL); + check_eq(uapi16_file_object_read_only(NULL), UAPI16_READ_ONLY_UNSTATED); + features = WITH(features, UAPI16_FEATURE_READ_ONLY); + check_stated(o, features); + + /* The Linux inode flags, with the bits of the kernel: the flags the + * object says something about, and those of them that are set. A + * flag that is not stated is taken away, and other bits are not + * read. */ + check_eq(uapi16_file_object_inode_flags(o, &stated, &set), 0); + check_eq(stated, 0); + check_eq(set, 0); + for (size_t i = 0; i < ELEMENTSOF(inode_flags); i++) { + uint32_t flag = inode_flags[i].flag; + + check_eq(uapi16_file_object_set_inode_flags(o, flag | SYNC_FL, UINT32_MAX), 0); + check_eq(uapi16_file_object_inode_flags(o, &stated, &set), 0); + check_eq(stated, flag); + check_eq(set, flag); + check_stated(o, WITH(features, inode_flags[i].feature)); + /* A flag that is stated and not set is a field as well. */ + check_eq(uapi16_file_object_set_inode_flags(o, flag, 0), 0); + check_eq(uapi16_file_object_inode_flags(o, &stated, &set), 0); + check_eq(stated, flag); + check_eq(set, 0); + check_stated(o, WITH(features, inode_flags[i].feature)); + } + check_eq(uapi16_file_object_set_inode_flags(o, 0, UINT32_MAX), 0); + check_eq(uapi16_file_object_inode_flags(o, &stated, &set), 0); + check_eq(stated, 0); + check_eq(set, 0); + check_stated(o, features); + check_eq(uapi16_file_object_set_inode_flags(o, UINT32_MAX, APPEND_FL | NOCOW_FL | SYNC_FL), 0); + check_eq(uapi16_file_object_inode_flags(o, &stated, &set), 0); + check_eq(stated, INODE_FLAGS); + check_eq(set, APPEND_FL | NOCOW_FL); + /* Either place can be NULL. */ + stated = set = 77; + check_eq(uapi16_file_object_inode_flags(o, &stated, NULL), 0); + check_eq(uapi16_file_object_inode_flags(o, NULL, &set), 0); + check_eq(uapi16_file_object_inode_flags(o, NULL, NULL), 0); + check_eq(stated, INODE_FLAGS); + check_eq(set, APPEND_FL | NOCOW_FL); + check_eq(uapi16_file_object_set_inode_flags(NULL, 0, 0), -EINVAL); + check_eq(uapi16_file_object_inode_flags(NULL, &stated, &set), -EINVAL); + for (size_t i = 0; i < ELEMENTSOF(inode_flags); i++) + features = WITH(features, inode_flags[i].feature); + check_stated(o, features); + + /* The DOS attributes hidden, system and archive, with the bits of + * a directory entry of FAT, the same way. */ + check_eq(uapi16_file_object_dos_attributes(o, &stated, &set), 0); + check_eq(stated, 0); + check_eq(set, 0); + for (size_t i = 0; i < ELEMENTSOF(dos_attributes); i++) { + uint32_t attribute = dos_attributes[i].flag; + + check_eq(uapi16_file_object_set_dos_attributes(o, attribute | DOS_READ_ONLY, UINT32_MAX), 0); + check_eq(uapi16_file_object_dos_attributes(o, &stated, &set), 0); + check_eq(stated, attribute); + check_eq(set, attribute); + check_stated(o, WITH(features, dos_attributes[i].feature)); + check_eq(uapi16_file_object_set_dos_attributes(o, attribute, 0), 0); + check_eq(uapi16_file_object_dos_attributes(o, &stated, &set), 0); + check_eq(stated, attribute); + check_eq(set, 0); + check_stated(o, WITH(features, dos_attributes[i].feature)); + } + check_eq(uapi16_file_object_set_dos_attributes(o, 0, UINT32_MAX), 0); + check_eq(uapi16_file_object_dos_attributes(o, &stated, &set), 0); + check_eq(stated, 0); + check_eq(set, 0); + check_stated(o, features); + check_eq(uapi16_file_object_set_dos_attributes(o, UINT32_MAX, DOS_ARCHIVE | DOS_DIRECTORY), 0); + check_eq(uapi16_file_object_dos_attributes(o, &stated, &set), 0); + check_eq(stated, DOS_ATTRIBUTES); + check_eq(set, DOS_ARCHIVE); + stated = set = 77; + check_eq(uapi16_file_object_dos_attributes(o, &stated, NULL), 0); + check_eq(uapi16_file_object_dos_attributes(o, NULL, &set), 0); + check_eq(uapi16_file_object_dos_attributes(o, NULL, NULL), 0); + check_eq(stated, DOS_ATTRIBUTES); + check_eq(set, DOS_ARCHIVE); + check_eq(uapi16_file_object_set_dos_attributes(NULL, 0, 0), -EINVAL); + check_eq(uapi16_file_object_dos_attributes(NULL, &stated, &set), -EINVAL); + /* The read-only attribute of DOS is the one field for both. */ + check_eq(uapi16_file_object_read_only(o), UAPI16_READ_ONLY_NO); + for (size_t i = 0; i < ELEMENTSOF(dos_attributes); i++) + features = WITH(features, dos_attributes[i].feature); + check_stated(o, features); + + /* Where the data is. That of a regular file is in the file of its + * name next to the manifest, unless the object refers to another + * file. */ + size = 77; + check_eq(uapi16_file_object_data_location(o), UAPI16_DATA_LOCATION_EXTERNAL); + check(!uapi16_file_object_literal(o, &size)); + check_eq(size, 0); + check(!uapi16_file_object_literal(o, NULL)); + check_eq(uapi16_file_object_contents_file(o, &contents_file, &offset), -ENODATA); + check(!contents_file); + check_eq(offset, 77); + check_eq(uapi16_file_object_set_contents_file(o, "blobs/1", &e), 0); + check_eq(uapi16_file_object_data_location(o), UAPI16_DATA_LOCATION_EXTERNAL); + check(!uapi16_file_object_literal(o, &size)); + check_misuse(uapi16_file_object_set_contents_file(o, NULL, &e), &e, EINVAL); + check_misuse(uapi16_file_object_set_contents_file(NULL, "blobs/1", &e), &e, EINVAL); + check_stated(o, features); + /* The object says which file that is, and that the data starts at + * its beginning. The name is a string of the object, which stays + * until the object refers to another file. Both places are needed, + * and a call that fails stores nothing. */ + check_eq(uapi16_file_object_contents_file(o, &contents_file, &offset), 0); + check_str(contents_file, "blobs/1"); + check_eq(offset, 0); + offset = 77; + check_eq(uapi16_file_object_contents_file(o, &other_file, &offset), 0); + check(other_file == contents_file); + check_eq(uapi16_file_object_set_contents_file(o, "blobs/2", &e), 0); + check_eq(uapi16_file_object_contents_file(o, &contents_file, &offset), 0); + check_str(contents_file, "blobs/2"); + contents_file = NULL; + offset = 77; + check_eq(uapi16_file_object_contents_file(NULL, &contents_file, &offset), -EINVAL); + check_eq(uapi16_file_object_contents_file(o, NULL, &offset), -EINVAL); + check_eq(uapi16_file_object_contents_file(o, &contents_file, NULL), -EINVAL); + check_eq(uapi16_file_object_contents_file(o, NULL, NULL), -EINVAL); + check(!contents_file); + check_eq(offset, 77); + /* A file of the object's own name is no other file. */ + check_eq(uapi16_file_object_set_contents_file(o, uapi16_file_object_name(o), &e), 0); + check_eq(uapi16_file_object_contents_file(o, &contents_file, &offset), -ENODATA); + check_eq(uapi16_file_object_set_contents_file(o, "blobs/1", &e), 0); + /* The file stays with any features, as it belongs to none. */ + check_eq(retain_features(o, features), 0); + check_eq(uapi16_file_object_contents_file(o, &contents_file, &offset), 0); + check_str(contents_file, "blobs/1"); + + /* The target of a symbolic link is in the manifest: bytes, which + * need not be text and of which the object keeps a copy. They are + * a field of the feature only on a symbolic link. */ + memcpy(bytes, target, sizeof(bytes)); + check_eq(uapi16_file_object_set_target(o, bytes, sizeof(bytes)), 0); + memset(bytes, 0, sizeof(bytes)); + check_eq(uapi16_file_object_data_location(o), UAPI16_DATA_LOCATION_LITERAL); + /* Data that the manifest carries is in no other file. */ + contents_file = NULL; + offset = 77; + check_eq(uapi16_file_object_contents_file(o, &contents_file, &offset), -ENODATA); + check(!contents_file); + check_eq(offset, 77); + value = uapi16_file_object_literal(o, &size); + check_same(value, size, target, 3); + check_eq(uapi16_file_object_set_target(o, target, sizeof(target)), 0); + value = uapi16_file_object_literal(o, &size); + check_same(value, size, target, sizeof(target)); + check(uapi16_file_object_literal(o, NULL)); + check_stated(o, features); + check_eq(uapi16_file_object_set_type(o, S_IFLNK), 0); + features = WITH(features, UAPI16_FEATURE_SYMLINK); + check_stated(o, features); + check_eq(uapi16_file_object_set_target(o, NULL, 1), -EINVAL); + check_eq(uapi16_file_object_set_target(NULL, target, sizeof(target)), -EINVAL); + value = uapi16_file_object_literal(o, &size); + check_same(value, size, target, sizeof(target)); + /* A target of no bytes is one, and needs no pointer. */ + check_eq(uapi16_file_object_set_target(o, unreadable(), 0), 0); + check_eq(uapi16_file_object_data_location(o), UAPI16_DATA_LOCATION_LITERAL); + size = 77; + check(uapi16_file_object_literal(o, &size)); + check_eq(size, 0); + check_eq(uapi16_file_object_set_target(o, NULL, 0), 0); + check_eq(uapi16_file_object_data_location(o), UAPI16_DATA_LOCATION_LITERAL); + check_stated(o, features); + /* What is neither a regular file nor a symbolic link with a target + * has no data, and no object is no data. */ + check_eq(uapi16_file_object_data_location(other), UAPI16_DATA_LOCATION_EXTERNAL); + for (size_t i = 0; i < ELEMENTSOF(types); i++) { + check_eq(uapi16_file_object_set_type(other, types[i]), 0); + check_eq(uapi16_file_object_data_location(other), + types[i] == S_IFREG ? UAPI16_DATA_LOCATION_EXTERNAL : 0); + check(!uapi16_file_object_literal(other, &size)); + } + check_eq(uapi16_file_object_data_location(NULL), UAPI16_DATA_LOCATION_NONE); + size = 77; + check(!uapi16_file_object_literal(NULL, &size)); + check_eq(size, 0); + check(!uapi16_file_object_literal(NULL, NULL)); + + /* The identity of the file system, which only the root has in a + * manifest. A setter stores it on any object. */ + check(!uapi16_file_object_fs_label(o)); + text[0] = 'c'; + check_eq(uapi16_file_object_set_fs_label(o, text), 0); + text[0] = 'C'; + label = uapi16_file_object_fs_label(o); + check_str(label, "copied"); + check_eq(uapi16_file_object_set_fs_label(o, NULL), -EINVAL); + check_eq(uapi16_file_object_set_fs_label(NULL, "label"), -EINVAL); + check(!uapi16_file_object_fs_label(NULL)); + features = WITH(features, UAPI16_FEATURE_FS_LABEL); + check_stated(o, features); + check_eq(uapi16_file_object_fs_uuid(o, &read_uuid), -ENODATA); + check_eq(read_uuid.bytes[0], 0); + check_eq(uapi16_file_object_set_fs_uuid(o, &uuid), 0); + memset(&uuid, 0, sizeof(uuid)); + check_eq(uapi16_file_object_fs_uuid(o, &read_uuid), 0); + for (size_t i = 0; i < UAPI16_UUID_SIZE; i++) + check_eq(read_uuid.bytes[i], i + 1); + check_eq(uapi16_file_object_set_fs_uuid(o, NULL), -EINVAL); + check_eq(uapi16_file_object_set_fs_uuid(NULL, &uuid), -EINVAL); + check_eq(uapi16_file_object_fs_uuid(NULL, &read_uuid), -EINVAL); + check_eq(uapi16_file_object_fs_uuid(o, NULL), -EINVAL); + features = WITH(features, UAPI16_FEATURE_FS_UUID); + check_stated(o, features); + small = 77; + check_eq(uapi16_file_object_fat_serial(o, &small), -ENODATA); + check_eq(small, 77); + check_eq(uapi16_file_object_set_fat_serial(o, 0x1234abcd), 0); + check_eq(uapi16_file_object_fat_serial(o, &small), 0); + check_eq(small, 0x1234abcd); + check_eq(uapi16_file_object_set_fat_serial(o, 0), 0); + check_eq(uapi16_file_object_fat_serial(o, &small), 0); + check_eq(small, 0); + check_eq(uapi16_file_object_set_fat_serial(NULL, 1), -EINVAL); + check_eq(uapi16_file_object_fat_serial(NULL, &small), -EINVAL); + check_eq(uapi16_file_object_fat_serial(o, NULL), -EINVAL); + features = WITH(features, UAPI16_FEATURE_FAT_SERIAL); + check_stated(o, features); + + /* The object has a field of every feature of a tree now, and no + * object has none. */ + check_same_features(features, FEATURES_OF_TREES); + check_stated(NULL, features_none()); + check_str(label, "copied"); + check_str(uapi16_file_object_name(o), "dir/file"); + + /* A check of when it may be used needs an object. */ + check_misuse(uapi16_file_object_check_validity(NULL, 0, &e), &e, EINVAL); + check_eq(uapi16_file_object_check_validity(NULL, 0, NULL), -EINVAL); + check_eq(uapi16_file_object_check_validity(o, 0, &e), 0); + check(!e); + + /* Freeing returns NULL, and takes NULL. */ + o = uapi16_file_object_free(o); + check(!o); + check(!uapi16_file_object_free(NULL)); +} + +/* + * uapi16_file_object_retain_features() takes away the fields of every + * feature that is not in the set it is given, so that a caller sets all it + * knows of a file and keeps what its manifest records. The name, the type + * and what belongs to no feature stay. A string the object handed out is + * where it was as long as its field is there. + */ +static void test_retained_features(void) { + static const uapi16_feature_t no_features[] = { NO_FEATURE, 64, 65, 64 * UAPI16_FEATURES_WORDS }; + const uapi16_features_t every = EVERY_FEATURE; + const uapi16_features_t kept = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_USER_NAME, + UAPI16_FEATURE_SIZE, UAPI16_FEATURE_FLAG_NO_DUMP); + static const uapi16_uuid_t uuid = { .bytes = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } }; + _cleanup_(closep) int written = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *options = + uapi16_manifest_options_new(); + _cleanup_(uapi16_writer_freep) uapi16_writer *w = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = make_hello("file"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *link = make_object("link"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *literal = make_object("literal"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *root = make_object(""); + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *text = NULL; + uapi16_sha256_digest_t hash = { .bytes = { 0 } }; + uapi16_uuid_t read_uuid = { .bytes = { 0 } }; + uint32_t small = 77, stated = 77, set = 77; + uapi16_features_t all; + uint64_t number = 77, offset = 77; + uapi16_inode_token_t token = 77; + size_t count = 77, size = 77, text_size; + const char *name, *user, *group, *label, *xattr = NULL, *again = NULL; + const char *contents_file = NULL; + const void *value = NULL; + int r; + + /* A regular file with a field of many features, whose data is in + * another file. */ + check_eq(uapi16_file_object_set_mode(o, 0644), 0); + check_eq(uapi16_file_object_set_uid(o, 1), 0); + check_eq(uapi16_file_object_set_gid(o, 2), 0); + check_eq(uapi16_file_object_set_user_name(o, "user"), 0); + check_eq(uapi16_file_object_set_group_name(o, "group"), 0); + check_eq(uapi16_file_object_set_mtime_nsec(o, 3), 0); + check_eq(uapi16_file_object_set_inode_token(o, 4), 0); + check_eq(uapi16_file_object_add_user_xattr(o, "key", "value", 5), 0); + check_eq(uapi16_file_object_set_read_only(o, UAPI16_READ_ONLY_NO), 0); + check_eq(uapi16_file_object_set_inode_flags(o, NODUMP_FL | APPEND_FL, NODUMP_FL), 0); + check_eq(uapi16_file_object_set_dos_attributes(o, DOS_HIDDEN | DOS_ARCHIVE, DOS_HIDDEN), 0); + check_eq(uapi16_file_object_set_contents_file(o, "blobs/1", &e), 0); + all = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_UID, UAPI16_FEATURE_GID, + UAPI16_FEATURE_USER_NAME, UAPI16_FEATURE_GROUP_NAME, UAPI16_FEATURE_MTIME, + UAPI16_FEATURE_SIZE, UAPI16_FEATURE_SHA256, UAPI16_FEATURE_HARDLINK, + UAPI16_FEATURE_USER_XATTR, UAPI16_FEATURE_READ_ONLY, + UAPI16_FEATURE_FLAG_NO_DUMP, UAPI16_FEATURE_FLAG_APPEND_ONLY, + UAPI16_FEATURE_FLAG_HIDDEN, UAPI16_FEATURE_FLAG_ARCHIVE); + check_stated(o, all); + name = uapi16_file_object_name(o); + user = uapi16_file_object_user_name(o); + group = uapi16_file_object_group_name(o); + check_eq(uapi16_file_object_user_xattr(o, 0, &xattr, &value, &size), 0); + check(name && user && group && xattr && value); + + /* A manifest that records four features has no room for it as it + * is: a writer of records refuses it for a field of another one. */ + check_eq(set_features(options, kept), 0); + w = begin_records(options, written); + r = uapi16_writer_file(w, o, &e); + check_eq(r, -EBADMSG); + check_str(uapi16_error_problem(e), "unlistedFeature"); + e = uapi16_error_free(e); + + /* Every feature it has, and every feature there is: nothing + * changes, and the strings it handed out are where they were. */ + check_eq(retain_features(o, all), 0); + check_eq(retain_features(o, every), 0); + check_stated(o, all); + check(uapi16_file_object_name(o) == name); + check(uapi16_file_object_user_name(o) == user); + check(uapi16_file_object_group_name(o) == group); + check_eq(uapi16_file_object_user_xattr(o, 0, &again, NULL, NULL), 0); + check(again == xattr); + check_str(xattr, "key"); + check_eq(uapi16_file_object_uid(o, &small), 0); + check_eq(small, 1); + + /* A number that is no feature is refused, also behind one that is + * a feature, and changes nothing. So is no object. */ + for (size_t i = 0; i < ELEMENTSOF(no_features); i++) { + check_eq(retain_features(o, FEATURES(no_features[i])), -EINVAL); + check_eq(retain_features(o, FEATURES(UAPI16_FEATURE_MODE, no_features[i])), -EINVAL); + } + check_eq(retain_features(NULL, kept), -EINVAL); + check_stated(o, all); + check(uapi16_file_object_group_name(o) == group); + + /* The four features of the manifest: the fields of these stay, and + * those of the others are gone. The flag of the feature that stays + * is the one the object says something about still. */ + check_eq(retain_features(o, kept), 0); + check_stated(o, kept); + check_eq(uapi16_file_object_mode(o, &small), 0); + check_eq(small, 0644); + check_eq(uapi16_file_object_size(o, &number), 0); + check_eq(number, 5); + check_eq(uapi16_file_object_inode_flags(o, &stated, &set), 0); + check_eq(stated, NODUMP_FL); + check_eq(set, NODUMP_FL); + small = 77; + number = 77; + check_eq(uapi16_file_object_uid(o, &small), -ENODATA); + check_eq(uapi16_file_object_gid(o, &small), -ENODATA); + check_eq(uapi16_file_object_mtime_nsec(o, &number), -ENODATA); + check_eq(uapi16_file_object_sha256(o, &hash), -ENODATA); + check_eq(uapi16_file_object_inode_token(o, &token), -ENODATA); + check_eq(uapi16_file_object_user_xattrs(o, &count), -ENODATA); + check_eq(uapi16_file_object_user_xattr(o, 0, &again, NULL, NULL), -EINVAL); + check_eq(uapi16_file_object_read_only(o), UAPI16_READ_ONLY_UNSTATED); + check_eq(uapi16_file_object_dos_attributes(o, &stated, &set), 0); + check_eq(stated, 0); + check_eq(set, 0); + check(small == 77 && number == 77 && token == 77 && count == 77 && hash.bytes[0] == 0); + /* The string of the field that stays is where it was, and the one + * of the field that went is none. */ + check(uapi16_file_object_user_name(o) == user); + check_str(user, "user"); + check(!uapi16_file_object_group_name(o)); + /* The name, the type and where the data is belong to no feature. */ + check(uapi16_file_object_name(o) == name); + check_str(name, "file"); + check_eq(uapi16_file_object_type(o), S_IFREG); + check_eq(uapi16_file_object_data_location(o), UAPI16_DATA_LOCATION_EXTERNAL); + + /* The writer takes it now, with the file its data is in. */ + check_eq(uapi16_writer_file(w, o, &e), 0); + check_eq(uapi16_writer_finish(w, &e), 0); + w = uapi16_writer_free(w); + text = read_all(written, &text_size); + check_manifest(text, text_size); + check(strstr(text, "\"file\":\"blobs/1\"")); + check(strstr(text, "\"userName\":\"user\"")); + check(!strstr(text, "groupName")); + + /* No feature at all: the name and the type are left, and where + * the data is. */ + check_eq(retain_features(o, features_none()), 0); + check_stated(o, features_none()); + check(!uapi16_file_object_user_name(o)); + check_eq(uapi16_file_object_mode(o, &small), -ENODATA); + check_eq(uapi16_file_object_size(o, &number), -ENODATA); + check_eq(uapi16_file_object_inode_flags(o, &stated, &set), 0); + check_eq(stated, 0); + check(uapi16_file_object_name(o) == name); + check_eq(uapi16_file_object_type(o), S_IFREG); + check_eq(uapi16_file_object_data_location(o), UAPI16_DATA_LOCATION_EXTERNAL); + /* The file the data of a regular file is in belongs to no feature, + * and stays. */ + check_eq(uapi16_file_object_contents_file(o, &contents_file, &offset), 0); + check_str(contents_file, "blobs/1"); + check_eq(offset, 0); + + /* The target of a symbolic link is the field of a feature: it + * stays with UAPI16_FEATURE_SYMLINK, and goes without it. The link + * is one still. */ + check_eq(uapi16_file_object_set_type(link, S_IFLNK), 0); + check_eq(uapi16_file_object_set_target(link, "to", 2), 0); + check_stated(link, FEATURES(UAPI16_FEATURE_SYMLINK)); + check_eq(retain_features(link, FEATURES(UAPI16_FEATURE_SYMLINK, UAPI16_FEATURE_MODE)), 0); + value = uapi16_file_object_literal(link, &size); + check_same(value, size, "to", 2); + check_eq(uapi16_file_object_data_location(link), UAPI16_DATA_LOCATION_LITERAL); + check_eq(retain_features(link, FEATURES(UAPI16_FEATURE_MODE)), 0); + size = 77; + check(!uapi16_file_object_literal(link, &size)); + check_eq(size, 0); + check_eq(uapi16_file_object_data_location(link), UAPI16_DATA_LOCATION_NONE); + check_stated(link, features_none()); + check_eq(uapi16_file_object_type(link), S_IFLNK); + check_str(uapi16_file_object_name(link), "link"); + /* So does the file a symbolic link has its target in: the object + * names it with the feature, and names none without it. */ + check_eq(uapi16_file_object_set_contents_file(link, "blobs/target", &e), 0); + check_stated(link, FEATURES(UAPI16_FEATURE_SYMLINK)); + check_eq(retain_features(link, FEATURES(UAPI16_FEATURE_SYMLINK)), 0); + check_eq(uapi16_file_object_contents_file(link, &contents_file, &offset), 0); + check_str(contents_file, "blobs/target"); + check_eq(retain_features(link, FEATURES(UAPI16_FEATURE_MODE)), 0); + contents_file = NULL; + offset = 77; + check_eq(uapi16_file_object_contents_file(link, &contents_file, &offset), -ENODATA); + check(!contents_file); + check_eq(offset, 77); + + /* Data that the manifest carries for a regular file belongs to no + * feature, and stays. */ + check_eq(uapi16_file_object_set_target(literal, "data", 4), 0); + check_eq(retain_features(literal, features_none()), 0); + value = uapi16_file_object_literal(literal, &size); + check_same(value, size, "data", 4); + check_eq(uapi16_file_object_data_location(literal), UAPI16_DATA_LOCATION_LITERAL); + + /* What only the root has goes and stays by its features as well: + * the label, the UUID and the volume serial number of the file + * system. */ + check_eq(uapi16_file_object_set_mode(root, 0755), 0); + check_eq(uapi16_file_object_set_fs_label(root, "label"), 0); + check_eq(uapi16_file_object_set_fs_uuid(root, &uuid), 0); + check_eq(uapi16_file_object_set_fat_serial(root, 7), 0); + label = uapi16_file_object_fs_label(root); + check_str(label, "label"); + all = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_FS_LABEL, UAPI16_FEATURE_FS_UUID, + UAPI16_FEATURE_FAT_SERIAL); + check_stated(root, all); + all = FEATURES(UAPI16_FEATURE_FS_LABEL, UAPI16_FEATURE_FS_UUID); + check_eq(retain_features(root, all), 0); + check_stated(root, all); + check(uapi16_file_object_fs_label(root) == label); + check_str(label, "label"); + check_eq(uapi16_file_object_fs_uuid(root, &read_uuid), 0); + check_eq(memcmp(&read_uuid, &uuid, sizeof(uuid)), 0); + small = 77; + check_eq(uapi16_file_object_fat_serial(root, &small), -ENODATA); + check_eq(uapi16_file_object_mode(root, &small), -ENODATA); + check_eq(small, 77); + check_eq(retain_features(root, FEATURES(UAPI16_FEATURE_FS_UUID)), 0); + check(!uapi16_file_object_fs_label(root)); + check_eq(uapi16_file_object_fs_uuid(root, &read_uuid), 0); + check_stated(root, FEATURES(UAPI16_FEATURE_FS_UUID)); + /* It is the root still. */ + check_str(uapi16_file_object_name(root), ""); + check_eq(uapi16_file_object_type(root), S_IFDIR); + for (size_t i = 0; i < ELEMENTSOF(no_features); i++) + check_eq(retain_features(root, FEATURES(no_features[i])), -EINVAL); + check_stated(root, FEATURES(UAPI16_FEATURE_FS_UUID)); + /* The UUID goes like the label and the serial. */ + check_eq(retain_features(root, FEATURES(UAPI16_FEATURE_FS_LABEL)), 0); + check_eq(uapi16_file_object_fs_uuid(root, &read_uuid), -ENODATA); + check_stated(root, features_none()); + check(!e); +} + +/* + * The root is the file object with the empty name: a directory, which + * keeps its name and its type. A setter stores on it whatever it is given, + * and a writer refuses a root with what only another file object has, and + * any other file object with what only the root has. What the root has of + * its own, a writer of records writes and a reader hands out again. + */ +static void test_roots(void) { + static const uint32_t no_root_types[] = { S_IFREG, S_IFLNK, S_IFIFO, S_IFCHR, S_IFBLK, S_IFSOCK }; + static const char *const only_files_have[] = { + "size", "sha256", "contents", "contents", "inodeToken", "major", "minor", + "flagHidden", "flagSystem", "flagArchive", + }; + static const char *const only_the_root_has[] = { "fsLabel", "fsUUID", "fatSerial" }; + static const uapi16_uuid_t uuid = { .bytes = { 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 } }; + _cleanup_(closep) int written = scratch_file(), refused_to = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *listing = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *w = NULL, *none = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *root = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *other = make_object("other"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *plain = make_object("plain"); + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + uapi16_sha256_digest_t hash; + uapi16_uuid_t read_uuid; + uapi16_features_t features; + uint64_t number = 77; + uapi16_inode_token_t token = 77; + uint32_t small = 77, stated = 77, set = 77; + size_t count = 77, size = 77; + const uapi16_file_object *got; + const char *name = NULL; + const void *value = NULL; + int r; + + check_eq(set_features(o, FEATURES_OF_TREES), 0); + unhex(SHA256_OF_NOTHING, &hash); + + /* The empty name makes the root, which is a directory. */ + check_eq(uapi16_file_object_new("", &root, &e), 0); + check(root && !e); + check_str(uapi16_file_object_name(root), ""); + check_eq(uapi16_file_object_type(root), S_IFDIR); + check_stated(root, features_none()); + check_eq(uapi16_file_object_data_location(root), UAPI16_DATA_LOCATION_NONE); + + /* It takes the type of a directory and no other. */ + check_eq(uapi16_file_object_set_type(root, S_IFDIR), 0); + check_eq(uapi16_file_object_set_type(root, S_IFDIR | 0755), 0); + for (size_t i = 0; i < ELEMENTSOF(no_root_types); i++) + check_eq(uapi16_file_object_set_type(root, no_root_types[i]), -EINVAL); + check_eq(uapi16_file_object_set_type(root, 0), -EINVAL); + check_eq(uapi16_file_object_type(root), S_IFDIR); + + /* It keeps its name, and no other object takes the empty one. */ + check_misuse(uapi16_file_object_set_name(root, "name", &e), &e, EINVAL); + check_eq(uapi16_file_object_set_name(root, "name", NULL), -EINVAL); + check_str(uapi16_file_object_name(root), ""); + check_misuse(uapi16_file_object_set_name(other, "", &e), &e, EINVAL); + check_eq(uapi16_file_object_set_name(other, "", NULL), -EINVAL); + check_str(uapi16_file_object_name(other), "other"); + + /* A setter stores what only another file object has in a manifest, + * and a writer of records refuses to begin with such a root, for + * the field. Nothing is written. */ + for (size_t i = 0; i < ELEMENTSOF(only_files_have); i++) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *refused = make_object(""); + + switch (i) { + case 0: + check_eq(uapi16_file_object_set_size(refused, 1), 0); + check_eq(uapi16_file_object_size(refused, &number), 0); + check_eq(number, 1); + break; + case 1: + check_eq(uapi16_file_object_set_sha256(refused, &hash), 0); + break; + case 2: + check_eq(uapi16_file_object_set_target(refused, "target", 6), 0); + break; + case 3: + check_eq(uapi16_file_object_set_contents_file(refused, "file", NULL), 0); + break; + case 4: + check_eq(uapi16_file_object_set_inode_token(refused, 1), 0); + break; + case 5: + check_eq(uapi16_file_object_set_major(refused, 1), 0); + break; + case 6: + check_eq(uapi16_file_object_set_minor(refused, 1), 0); + break; + case 7: + check_eq(uapi16_file_object_set_dos_attributes(refused, DOS_HIDDEN, DOS_HIDDEN), 0); + break; + case 8: + check_eq(uapi16_file_object_set_dos_attributes(refused, DOS_SYSTEM, 0), 0); + break; + default: + check_eq(uapi16_file_object_set_dos_attributes(refused, DOS_ARCHIVE, 0), 0); + break; + } + r = uapi16_writer_begin(o, refused_to, refused, &none, &e); + check_refused(r, &e, "fieldNotPermitted", "", only_files_have[i]); + check_eq(uapi16_writer_begin(o, refused_to, refused, &none, NULL), -EBADMSG); + check(!none); + } + check_eq(size_of(refused_to), 0); + + /* What is no root is none for a writer of records to begin with. */ + check_misuse(uapi16_writer_begin(o, refused_to, other, &none, &e), &e, EINVAL); + check(!none); + check_eq(size_of(refused_to), 0); + + /* The other way round: a writer of records and a writer refuse any + * other file object with a part of the identity of a file system, + * for the field, and go on. */ + w = begin_records(o, refused_to); + listing = open_writer(o); + for (size_t i = 0; i < ELEMENTSOF(only_the_root_has); i++) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *refused = make_object("other"); + size_t before = size_of(refused_to); + + switch (i) { + case 0: + check_eq(uapi16_file_object_set_fs_label(refused, "label"), 0); + break; + case 1: + check_eq(uapi16_file_object_set_fs_uuid(refused, &uuid), 0); + break; + default: + check_eq(uapi16_file_object_set_fat_serial(refused, 1), 0); + break; + } + r = uapi16_writer_file(w, refused, &e); + check_refused(r, &e, "fieldNotPermitted", "other", only_the_root_has[i]); + r = uapi16_manifest_writer_add_object(listing, refused, &e); + check_refused(r, &e, "fieldNotPermitted", "other", only_the_root_has[i]); + check_eq(size_of(refused_to), before); + } + check_eq(uapi16_writer_file(w, other, &e), 0); + check_eq(uapi16_writer_file(w, plain, &e), 0); + check_eq(uapi16_writer_finish(w, &e), 0); + w = uapi16_writer_free(w); + check_eq(uapi16_manifest_writer_add_object(listing, other, &e), 0); + listing = uapi16_manifest_writer_free(listing); + + /* What the root has: the attributes of its directory, and the + * identity of its file system. */ + check_eq(uapi16_file_object_set_mode(root, 0555), 0); + check_eq(uapi16_file_object_set_uid(root, 1), 0); + check_eq(uapi16_file_object_set_gid(root, 2), 0); + check_eq(uapi16_file_object_set_user_name(root, "user"), 0); + check_eq(uapi16_file_object_set_group_name(root, "group"), 0); + check_eq(uapi16_file_object_set_mtime_nsec(root, 3), 0); + check_eq(uapi16_file_object_add_user_xattr(root, "k", "v", 1), 0); + check_eq(uapi16_file_object_set_read_only(root, UAPI16_READ_ONLY_YES), 0); + check_eq(uapi16_file_object_set_inode_flags(root, NODUMP_FL | IMMUTABLE_FL, NODUMP_FL), 0); + check_eq(uapi16_file_object_set_fs_label(root, "label"), 0); + check_eq(uapi16_file_object_set_fs_uuid(root, &uuid), 0); + check_eq(uapi16_file_object_set_fat_serial(root, 0x1234abcd), 0); + features = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_UID, UAPI16_FEATURE_GID, + UAPI16_FEATURE_USER_NAME, UAPI16_FEATURE_GROUP_NAME, + UAPI16_FEATURE_MTIME, UAPI16_FEATURE_USER_XATTR, + UAPI16_FEATURE_READ_ONLY, UAPI16_FEATURE_FLAG_NO_DUMP, + UAPI16_FEATURE_FLAG_IMMUTABLE, UAPI16_FEATURE_FS_LABEL, + UAPI16_FEATURE_FS_UUID, UAPI16_FEATURE_FAT_SERIAL); + check_stated(root, features); + + /* A writer of records begins with it, and a reader hands it out + * with every field. The flag the root said was cleared is one the + * manifest says by its features, as it says the other flags. */ + check_eq(uapi16_writer_begin(o, written, root, &w, &e), 0); + check_eq(uapi16_writer_file(w, plain, &e), 0); + check_eq(uapi16_writer_finish(w, &e), 0); + w = uapi16_writer_free(w); + reader = open_reader(written); + check_recorded(reader, FEATURES_OF_TREES); + check_eq(uapi16_reader_order(reader), UAPI16_ORDER_CODEPOINT); + got = uapi16_reader_root(reader); + check(got); + check_str(uapi16_file_object_name(got), ""); + check_eq(uapi16_file_object_type(got), S_IFDIR); + check_eq(uapi16_file_object_mode(got, &small), 0); + check_eq(small, 0555); + check_eq(uapi16_file_object_uid(got, &small), 0); + check_eq(small, 1); + check_eq(uapi16_file_object_gid(got, &small), 0); + check_eq(small, 2); + check_str(uapi16_file_object_user_name(got), "user"); + check_str(uapi16_file_object_group_name(got), "group"); + check_eq(uapi16_file_object_mtime_nsec(got, &number), 0); + check_eq(number, 3); + check_eq(uapi16_file_object_user_xattrs(got, &count), 0); + check_eq(count, 1); + check_eq(uapi16_file_object_user_xattr(got, 0, &name, &value, &size), 0); + check_str(name, "k"); + check_same(value, size, "v", 1); + check_eq(uapi16_file_object_read_only(got), UAPI16_READ_ONLY_YES); + check_eq(uapi16_file_object_inode_flags(got, &stated, &set), 0); + check_eq(stated, INODE_FLAGS); + check_eq(set, NODUMP_FL); + check_str(uapi16_file_object_fs_label(got), "label"); + check_eq(uapi16_file_object_fs_uuid(got, &read_uuid), 0); + check_eq(memcmp(&read_uuid, &uuid, sizeof(uuid)), 0); + check_eq(uapi16_file_object_fat_serial(got, &small), 0); + check_eq(small, 0x1234abcd); + features = features_without(features, UAPI16_FEATURE_FLAG_IMMUTABLE); + check_stated(got, features); + /* The root has none of what only another file object has. */ + number = 77; + check_eq(uapi16_file_object_size(got, &number), -ENODATA); + check_eq(uapi16_file_object_sha256(got, &hash), -ENODATA); + check_eq(uapi16_file_object_inode_token(got, &token), -ENODATA); + check_eq(uapi16_file_object_major(got, &number), -ENODATA); + check_eq(uapi16_file_object_minor(got, &number), -ENODATA); + check_eq(number, 77); + check_eq(token, 77); + check_eq(uapi16_file_object_dos_attributes(got, &stated, &set), 0); + check_eq(stated, 0); + check_eq(uapi16_file_object_data_location(got), UAPI16_DATA_LOCATION_NONE); + check(!uapi16_file_object_literal(got, NULL)); + /* It belongs to the reader, and is there while the reader reads + * on. */ + { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = next_object(reader, "plain"); + + check_ends(reader); + check_str(uapi16_file_object_fs_label(got), "label"); + check_str(uapi16_file_object_name(uapi16_reader_root(reader)), ""); + } + check(!uapi16_reader_root(NULL)); + check(!e); +} + +/* + * A writer takes the root as the file object with the empty name, in any + * order with the other file objects, and the record of the root has what + * that object says: the attributes of the root directory and the identity + * of its file system. A root is checked as any file object is: one with a + * field of a feature the manifest does not record is refused, and so is + * one with what only another file object has. The first root that is added + * says what the root is like. Without one, the record of the root says + * nothing. + */ +static void test_root_adds(void) { + static const char *const only_files_have[] = { + "size", "sha256", "contents", "contents", "inodeToken", "major", "minor", + "flagHidden", "flagSystem", "flagArchive", + }; + /* Roots as only a reader hands them out: with the times the + * manifest may be used between, revoked, and with the UUID of a + * disk. The last one is of a manifest that records that UUID. */ + static const struct { + const char *manifest, *field, *written; + uapi16_feature_t features[FEATURES_MAX]; + } read_roots[] = { + { RS "{\"mediaType\":\"application/vnd.uapi.16.manifest\"," + "\"validSinceUSec\":1000}\n" TRAILER, + "validSinceUSec", "\"validSinceUSec\":1000", { DEFAULT_FEATURES } }, + { RS "{\"mediaType\":\"application/vnd.uapi.16.manifest\"," + "\"validUntilUSec\":2000}\n" TRAILER, + "validUntilUSec", "\"validUntilUSec\":2000", { DEFAULT_FEATURES } }, + { RS "{\"mediaType\":\"application/vnd.uapi.16.manifest\"," + "\"validity\":\"revoked\"}\n" TRAILER, + "validity", "\"validity\":\"revoked\"", { DEFAULT_FEATURES } }, + { RS "{\"features\":[\"gpt-disk-uuid\"]," + "\"gptDiskUuid\":\"6f1d0a42-9c1e-4b7a-8d33-520c7e11a905\"," + "\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n" TRAILER, + "gptDiskUuid", "\"gptDiskUuid\":\"6f1d0a42-9c1e-4b7a-8d33-520c7e11a905\"", + { UAPI16_FEATURE_GPT_DISK_UUID } }, + }; + static const uapi16_feature_t of_the_root[] = { UAPI16_FEATURE_FS_UUID, UAPI16_FEATURE_FAT_SERIAL }; + static const uapi16_uuid_t uuid = { .bytes = { 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 } }; + _cleanup_(closep) int listed = scratch_file(), narrow_fd = scratch_file(), bare_fd = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *all = + uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *narrow = + uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *none = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *root = make_object(""); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *first = make_object(""); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *second = make_object(""); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *unlisted = make_object(""); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *nothing = make_object(""); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *plain = make_object("plain"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *below = make_object("dir/below"); + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + uapi16_sha256_digest_t hash; + uapi16_uuid_t read_uuid; + uint32_t small = 77, stated = 77, set = 77; + uapi16_features_t features; + uint64_t number = 77; + size_t count = 77, size = 77; + const uapi16_file_object *got; + const char *name = NULL; + const void *value = NULL; + int r; + + unhex(SHA256_OF_NOTHING, &hash); + check_eq(set_features(all, FEATURES_OF_TREES), 0); + features = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_FS_LABEL, UAPI16_FEATURE_FS_UUID); + check_eq(set_features(narrow, features), 0); + + /* A root with all a root has: the attributes of its directory and + * the identity of its file system. */ + check_eq(uapi16_file_object_set_mode(root, 0555), 0); + check_eq(uapi16_file_object_set_uid(root, 1), 0); + check_eq(uapi16_file_object_set_gid(root, 2), 0); + check_eq(uapi16_file_object_set_user_name(root, "user"), 0); + check_eq(uapi16_file_object_set_group_name(root, "group"), 0); + check_eq(uapi16_file_object_set_mtime_nsec(root, 3), 0); + check_eq(uapi16_file_object_add_user_xattr(root, "k", "v", 1), 0); + check_eq(uapi16_file_object_set_read_only(root, UAPI16_READ_ONLY_YES), 0); + check_eq(uapi16_file_object_set_inode_flags(root, NODUMP_FL | IMMUTABLE_FL, NODUMP_FL), 0); + check_eq(uapi16_file_object_set_fs_label(root, "label"), 0); + check_eq(uapi16_file_object_set_fs_uuid(root, &uuid), 0); + check_eq(uapi16_file_object_set_fat_serial(root, 0x1234abcd), 0); + + /* A writer whose manifest records every feature of a tree takes + * it, after a file object here. It is no file the report counts + * but as the directory it is. */ + check_eq(uapi16_manifest_writer_open(all, listed, &w, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, plain, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, root, &e), 0); + + /* A root with what only another file object has is refused for + * the field, and the writer is as it was. */ + for (size_t i = 0; i < ELEMENTSOF(only_files_have); i++) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *refused = make_object(""); + + switch (i) { + case 0: + check_eq(uapi16_file_object_set_size(refused, 1), 0); + break; + case 1: + check_eq(uapi16_file_object_set_sha256(refused, &hash), 0); + break; + case 2: + check_eq(uapi16_file_object_set_target(refused, "target", 6), 0); + break; + case 3: + check_eq(uapi16_file_object_set_contents_file(refused, "file", NULL), 0); + break; + case 4: + check_eq(uapi16_file_object_set_inode_token(refused, 1), 0); + break; + case 5: + check_eq(uapi16_file_object_set_major(refused, 1), 0); + break; + case 6: + check_eq(uapi16_file_object_set_minor(refused, 1), 0); + break; + case 7: + check_eq(uapi16_file_object_set_dos_attributes(refused, DOS_HIDDEN, DOS_HIDDEN), 0); + break; + case 8: + check_eq(uapi16_file_object_set_dos_attributes(refused, DOS_SYSTEM, 0), 0); + break; + default: + check_eq(uapi16_file_object_set_dos_attributes(refused, DOS_ARCHIVE, 0), 0); + break; + } + r = uapi16_manifest_writer_add_object(w, refused, &e); + check_refused(r, &e, "fieldNotPermitted", "", only_files_have[i]); + check_eq(uapi16_manifest_writer_add_object(w, refused, NULL), -EBADMSG); + } + check_eq(uapi16_manifest_writer_finish(w, &report, &e), 0); + check_eq(uapi16_manifest_report_files(report), 1); + check_eq(uapi16_manifest_report_directories(report), 1); + check_eq(uapi16_manifest_report_others(report), 0); + report = uapi16_manifest_report_free(report); + w = uapi16_manifest_writer_free(w); + + /* The root of the manifest has every field the object had. The + * flag the object said was cleared is one the manifest says by its + * features, as it says the other flags. */ + reader = open_reader(listed); + check_recorded(reader, FEATURES_OF_TREES); + got = uapi16_reader_root(reader); + check_str(uapi16_file_object_name(got), ""); + check_eq(uapi16_file_object_type(got), S_IFDIR); + check_eq(uapi16_file_object_mode(got, &small), 0); + check_eq(small, 0555); + check_eq(uapi16_file_object_uid(got, &small), 0); + check_eq(small, 1); + check_eq(uapi16_file_object_gid(got, &small), 0); + check_eq(small, 2); + check_str(uapi16_file_object_user_name(got), "user"); + check_str(uapi16_file_object_group_name(got), "group"); + check_eq(uapi16_file_object_mtime_nsec(got, &number), 0); + check_eq(number, 3); + check_eq(uapi16_file_object_user_xattrs(got, &count), 0); + check_eq(count, 1); + check_eq(uapi16_file_object_user_xattr(got, 0, &name, &value, &size), 0); + check_str(name, "k"); + check_same(value, size, "v", 1); + check_eq(uapi16_file_object_read_only(got), UAPI16_READ_ONLY_YES); + check_eq(uapi16_file_object_inode_flags(got, &stated, &set), 0); + check_eq(stated, INODE_FLAGS); + check_eq(set, NODUMP_FL); + check_str(uapi16_file_object_fs_label(got), "label"); + check_eq(uapi16_file_object_fs_uuid(got, &read_uuid), 0); + check_eq(memcmp(&read_uuid, &uuid, sizeof(uuid)), 0); + check_eq(uapi16_file_object_fat_serial(got, &small), 0); + check_eq(small, 0x1234abcd); + features = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_UID, UAPI16_FEATURE_GID, + UAPI16_FEATURE_USER_NAME, UAPI16_FEATURE_GROUP_NAME, + UAPI16_FEATURE_MTIME, UAPI16_FEATURE_USER_XATTR, + UAPI16_FEATURE_READ_ONLY, UAPI16_FEATURE_FLAG_NO_DUMP, + UAPI16_FEATURE_FS_LABEL, UAPI16_FEATURE_FS_UUID, + UAPI16_FEATURE_FAT_SERIAL); + check_stated(got, features); + { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = next_object(reader, "plain"); + + check_ends(reader); + } + reader = uapi16_reader_free(reader); + + /* A manifest that records the access mode, the label and the UUID + * of the file system, and no volume serial number. A root with one + * is refused for the field, and adds nothing. */ + check_eq(uapi16_file_object_set_mode(unlisted, 0700), 0); + check_eq(uapi16_file_object_set_fat_serial(unlisted, 7), 0); + check_eq(uapi16_manifest_writer_open(narrow, narrow_fd, &w, &e), 0); + r = uapi16_manifest_writer_add_object(w, unlisted, &e); + check_refused(r, &e, "unlistedFeature", "", "fatSerial"); + check_eq(uapi16_manifest_writer_add_object(w, unlisted, NULL), -EBADMSG); + + /* A writer of records does not begin with that root either, for + * the same field of the same file, and writes nothing. */ + r = uapi16_writer_begin(narrow, bare_fd, unlisted, &none, &e); + check_refused(r, &e, "unlistedFeature", "", "fatSerial"); + check_eq(uapi16_writer_begin(narrow, bare_fd, unlisted, &none, NULL), -EBADMSG); + check(!none); + check_eq(size_of(bare_fd), 0); + + /* Added twice, the first root says what the root is like, as the + * first object of any directory does. */ + check_eq(uapi16_file_object_set_mode(first, 0750), 0); + check_eq(uapi16_file_object_set_fs_label(first, "first"), 0); + check_eq(uapi16_file_object_set_fs_uuid(first, &uuid), 0); + check_eq(uapi16_file_object_set_mode(second, 0755), 0); + check_eq(uapi16_file_object_set_fs_label(second, "second"), 0); + check_eq(uapi16_manifest_writer_add_object(w, first, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, plain, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, second, &e), 0); + check_eq(uapi16_manifest_writer_finish(w, &report, &e), 0); + check_eq(uapi16_manifest_report_files(report), 1); + check_eq(uapi16_manifest_report_directories(report), 1); + report = uapi16_manifest_report_free(report); + w = uapi16_manifest_writer_free(w); + reader = open_reader(narrow_fd); + got = uapi16_reader_root(reader); + check_eq(uapi16_file_object_mode(got, &small), 0); + check_eq(small, 0750); + check_str(uapi16_file_object_fs_label(got), "first"); + check_eq(uapi16_file_object_fs_uuid(got, &read_uuid), 0); + check_eq(memcmp(&read_uuid, &uuid, sizeof(uuid)), 0); + small = 77; + check_eq(uapi16_file_object_fat_serial(got, &small), -ENODATA); + check_eq(small, 77); + reader = uapi16_reader_free(reader); + + /* Without a root, the record of the root says nothing, and so it + * does with a root that says nothing. */ + for (int with_root = 0; with_root < 2; with_root++) { + empty(bare_fd); + check_eq(uapi16_manifest_writer_open(o, bare_fd, &w, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, below, &e), 0); + if (with_root) + check_eq(uapi16_manifest_writer_add_object(w, nothing, &e), 0); + check_eq(uapi16_manifest_writer_finish(w, &report, &e), 0); + /* The root, and the directory of the file, which the + * writer made up. */ + check_eq(uapi16_manifest_report_directories(report), 2); + report = uapi16_manifest_report_free(report); + w = uapi16_manifest_writer_free(w); + reader = open_reader(bare_fd); + got = uapi16_reader_root(reader); + check_stated(got, features_none()); + small = 77; + check_eq(uapi16_file_object_mode(got, &small), -ENODATA); + check(!uapi16_file_object_fs_label(got)); + check_eq(uapi16_file_object_fs_uuid(got, &read_uuid), -ENODATA); + check_eq(uapi16_file_object_fat_serial(got, &small), -ENODATA); + check_eq(small, 77); + reader = uapi16_reader_free(reader); + } + + /* The UUID and the volume serial number of the file system are + * what the root has, where its file system has one. Without the + * root, and with a root that says nothing of it, the manifest says + * nothing of it, and with one that has it, the manifest has it. */ + for (size_t i = 0; i < ELEMENTSOF(of_the_root); i++) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *with = make_object(""); + + r = set_features(o, FEATURES(DEFAULT_FEATURES, of_the_root[i])); + check_eq(r, 0); + if (of_the_root[i] == UAPI16_FEATURE_FS_UUID) + check_eq(uapi16_file_object_set_fs_uuid(with, &uuid), 0); + else + check_eq(uapi16_file_object_set_fat_serial(with, 0xfeedf00d), 0); + for (int has_it = -1; has_it < 2; has_it++) { + empty(bare_fd); + check_eq(uapi16_manifest_writer_open(o, bare_fd, &w, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, plain, &e), 0); + /* No root at all, one without it, and one with it. + * None of them counts as a field that was left out: + * only a walk leaves one out. */ + if (has_it >= 0) + check_eq(uapi16_manifest_writer_add_object(w, has_it ? with : nothing, &e), 0); + check_eq(uapi16_manifest_writer_finish(w, &report, &e), 0); + check_eq(uapi16_manifest_report_fields_omitted(report), 0); + report = uapi16_manifest_report_free(report); + w = uapi16_manifest_writer_free(w); + reader = open_reader(bare_fd); + check_recorded(reader, FEATURES(DEFAULT_FEATURES, of_the_root[i])); + got = uapi16_reader_root(reader); + small = 77; + if (has_it <= 0) { + check_stated(got, features_none()); + check_eq(uapi16_file_object_fs_uuid(got, &read_uuid), -ENODATA); + check_eq(uapi16_file_object_fat_serial(got, &small), -ENODATA); + check_eq(small, 77); + } else if (of_the_root[i] == UAPI16_FEATURE_FS_UUID) { + check_stated(got, FEATURES(of_the_root[i])); + check_eq(uapi16_file_object_fs_uuid(got, &read_uuid), 0); + check_eq(memcmp(&read_uuid, &uuid, sizeof(uuid)), 0); + } else { + check_stated(got, FEATURES(of_the_root[i])); + check_eq(uapi16_file_object_fat_serial(got, &small), 0); + check_eq(small, 0xfeedf00d); + } + reader = uapi16_reader_free(reader); + } + } + check_eq(set_features(o, FEATURES(DEFAULT_FEATURES)), 0); + + /* A root that a reader read can say what no setter sets: when its + * manifest may be used, and the UUID of a disk. The manifest of a + * tree says neither, so a writer refuses such a root for the + * field. A writer of records takes it, and writes the field. */ + for (size_t i = 0; i < ELEMENTSOF(read_roots); i++) { + _cleanup_(closep) int from = manifest_file(read_roots[i].manifest), to = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *recording = + uapi16_manifest_options_new(); + _cleanup_(uapi16_reader_freep) uapi16_reader *source = open_reader(from); + _cleanup_(uapi16_writer_freep) uapi16_writer *records = NULL; + _cleanup_(freep) char *text = NULL; + size_t text_size; + + const uapi16_features_t recorded = + features_listed(read_roots[i].features, ELEMENTSOF(read_roots[i].features)); + + check_eq(set_features(recording, recorded), 0); + got = uapi16_reader_root(source); + check(got); + w = open_writer(o); + r = uapi16_manifest_writer_add_object(w, got, &e); + check_refused(r, &e, "fieldNotPermitted", "", read_roots[i].field); + check_listed(w, 0, 1, 0); + w = uapi16_manifest_writer_free(w); + + check_eq(uapi16_writer_begin(recording, to, got, &records, &e), 0); + check_eq(uapi16_writer_finish(records, &e), 0); + records = uapi16_writer_free(records); + text = read_all(to, &text_size); + check_manifest(text, text_size); + check(strstr(text, read_roots[i].written)); + } + check(!e); +} + +/* + * A writer takes the file objects of a caller in any order and lists them + * in the order of the manifest, with the directories that were not added. + * It keeps a copy of each. The names of one file carry one token of the + * caller, and the manifest numbers the files itself. What a reader reads + * back is what the objects said, field by field. + */ +static void test_added_objects(void) { + const uapi16_features_t features = FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_MTIME, + UAPI16_FEATURE_USER_NAME, + UAPI16_FEATURE_GROUP_NAME); + /* Those of them that a regular file has fields of: all but the + * targets of symbolic links and the numbers of device nodes. */ + const uapi16_features_t of_a_regular_file = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_UID, + UAPI16_FEATURE_GID, UAPI16_FEATURE_SIZE, + UAPI16_FEATURE_SHA256, + UAPI16_FEATURE_HARDLINK, + UAPI16_FEATURE_MTIME, + UAPI16_FEATURE_USER_NAME, + UAPI16_FEATURE_GROUP_NAME); + static const uint64_t mtime = UINT64_C(1700000000123456789); + _cleanup_(closep) int fd = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *tool = make_hello("usr/bin/tool"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *alias = make_object("usr/bin/alias"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *bin = make_object("usr/bin"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *usr = make_object("usr"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *null = make_object("dev/null"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *fifo = make_object("run/fifo"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *second = make_object("z-second"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *wrong = make_hello("wrong"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *unlisted = make_object("unlisted"); + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *listed = NULL; + size_t listed_size; + int r; + + check_eq(set_features(o, features), 0); + check_eq(uapi16_manifest_writer_open(o, fd, &w, &e), 0); + + /* A regular file with what a manifest says of one, whose data is + * in a file of another name. It is added first, and its directory + * after it. */ + check_eq(uapi16_file_object_set_mode(tool, 0755), 0); + check_eq(uapi16_file_object_set_uid(tool, 0), 0); + check_eq(uapi16_file_object_set_gid(tool, 12), 0); + check_eq(uapi16_file_object_set_user_name(tool, "root"), 0); + check_eq(uapi16_file_object_set_group_name(tool, "staff"), 0); + check_eq(uapi16_file_object_set_mtime_nsec(tool, mtime), 0); + check_eq(uapi16_file_object_set_contents_file(tool, "blobs/2cf24dba", &e), 0); + check_eq(uapi16_file_object_set_inode_token(tool, 700), 0); + check_eq(uapi16_manifest_writer_add_object(w, tool, &e), 0); + + /* A file with the token of another one that says something else + * of it is no name of that file. The error names the first name of + * the token, and the writer is as it was. */ + check_eq(uapi16_file_object_set_inode_token(wrong, 700), 0); + r = uapi16_manifest_writer_add_object(w, wrong, &e); + check_error(r, e, UAPI16_ERROR_HARDLINK_MISMATCH, ESTALE, "wrong", CHECK_HARDLINK_PATH); + check_str(uapi16_error_hardlink_path(e), "usr/bin/tool"); + e = uapi16_error_free(e); + check_eq(uapi16_manifest_writer_add_object(w, wrong, NULL), -ESTALE); + + /* Another file with two names, which come in the other order. */ + check_eq(uapi16_file_object_set_size(second, 3), 0); + check_eq(uapi16_file_object_set_inode_token(second, 9), 0); + check_eq(uapi16_manifest_writer_add_object(w, second, &e), 0); + + /* A symbolic link, a device node and a FIFO. */ + check_eq(uapi16_file_object_set_type(alias, S_IFLNK), 0); + check_eq(uapi16_file_object_set_target(alias, "tool", 4), 0); + check_eq(uapi16_file_object_set_size(alias, 4), 0); + check_eq(uapi16_manifest_writer_add_object(w, alias, &e), 0); + check_eq(uapi16_file_object_set_type(null, S_IFCHR), 0); + check_eq(uapi16_file_object_set_mode(null, 0666), 0); + check_eq(uapi16_file_object_set_major(null, 1), 0); + check_eq(uapi16_file_object_set_minor(null, 3), 0); + check_eq(uapi16_manifest_writer_add_object(w, null, &e), 0); + check_eq(uapi16_file_object_set_type(fifo, S_IFIFO), 0); + check_eq(uapi16_file_object_set_mode(fifo, 0600), 0); + check_eq(uapi16_manifest_writer_add_object(w, fifo, &e), 0); + + /* The second name of the first file is the same object under the + * next name. The writer has a copy of what it was given: the + * object changes after that, and is freed. */ + check_eq(uapi16_file_object_set_name(tool, "usr/libexec/tool", &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, tool, &e), 0); + check_eq(uapi16_file_object_set_name(tool, "changed", &e), 0); + check_eq(uapi16_file_object_set_mode(tool, 0600), 0); + check_eq(uapi16_file_object_set_size(tool, 6), 0); + tool = uapi16_file_object_free(tool); + + /* An object that is refused is not added: one with a field of a + * feature the manifest does not record. */ + check_eq(uapi16_file_object_set_read_only(unlisted, UAPI16_READ_ONLY_NO), 0); + r = uapi16_manifest_writer_add_object(w, unlisted, &e); + check_refused(r, &e, "unlistedFeature", "unlisted", "readOnly"); + check_eq(uapi16_manifest_writer_add_object(w, unlisted, NULL), -EBADMSG); + + /* Directories, after what is in them. An object that is equal to + * one that was added is no other object, and the first object of a + * directory says what the directory is like. */ + check_eq(uapi16_file_object_set_type(usr, S_IFDIR), 0); + check_eq(uapi16_file_object_set_mode(usr, 0755), 0); + check_eq(uapi16_manifest_writer_add_object(w, usr, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, usr, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, null, &e), 0); + check_eq(uapi16_file_object_set_type(bin, S_IFDIR), 0); + check_eq(uapi16_file_object_set_mode(bin, 0751), 0); + check_eq(uapi16_manifest_writer_add_object(w, bin, &e), 0); + check_eq(uapi16_file_object_set_mode(bin, 0700), 0); + check_eq(uapi16_manifest_writer_add_object(w, bin, &e), 0); + + /* The first name of the second file comes last. */ + check_eq(uapi16_file_object_set_name(second, "b-first", &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, second, &e), 0); + check(!e); + + /* Nothing is written before the writer finishes. Its report counts + * every object, the directories that were not added among them: + * the root, dev, run and usr/libexec. */ + check_eq(size_of(fd), 0); + check_eq(uapi16_manifest_writer_finish(w, &report, &e), 0); + check_eq(uapi16_manifest_report_files(report), 4); + check_eq(uapi16_manifest_report_directories(report), 6); + check_eq(uapi16_manifest_report_others(report), 3); + check_eq(uapi16_manifest_report_bytes(report), 16); + w = uapi16_manifest_writer_free(w); + listed = read_all(fd, &listed_size); + check_manifest(listed, listed_size); + check(strstr(listed, "\"file\":\"blobs/2cf24dba\"")); + check(!strstr(listed, "wrong") && !strstr(listed, "unlisted") && !strstr(listed, "changed")); + + /* A reader reads back what the objects said. The root says + * nothing, as no object was added for it. */ + reader = open_reader(fd); + check_recorded(reader, features); + check_eq(uapi16_reader_order(reader), UAPI16_ORDER_CODEPOINT); + check_eq(uapi16_reader_require_order(reader, UAPI16_ORDER_CODEPOINT, &e), 0); + check_stated(uapi16_reader_root(reader), features_none()); + { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = next_object(reader, "b-first"); + uapi16_inode_token_t token = 0; + uint64_t size = 0; + + /* The file that comes first in the manifest is its first + * file with more than one name. */ + check_eq(uapi16_file_object_type(got), S_IFREG); + check_eq(uapi16_file_object_size(got, &size), 0); + check_eq(size, 3); + check_eq(uapi16_file_object_inode_token(got, &token), 0); + check_eq(token, 1); + check_stated(got, FEATURES(UAPI16_FEATURE_SIZE, UAPI16_FEATURE_HARDLINK)); + } + { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = next_object(reader, "dev"); + uint32_t mode = 77; + + /* A directory that was not added says nothing but that it + * is one. */ + check_eq(uapi16_file_object_type(got), S_IFDIR); + check_eq(uapi16_file_object_mode(got, &mode), -ENODATA); + check_eq(mode, 77); + check_stated(got, features_none()); + } + { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = + next_object(reader, "dev/null"); + uint64_t major = 0, minor = 0, size = 77; + uint32_t mode = 0; + + check_eq(uapi16_file_object_type(got), S_IFCHR); + check_eq(uapi16_file_object_mode(got, &mode), 0); + check_eq(mode, 0666); + check_eq(uapi16_file_object_major(got, &major), 0); + check_eq(major, 1); + check_eq(uapi16_file_object_minor(got, &minor), 0); + check_eq(minor, 3); + check_eq(uapi16_file_object_size(got, &size), -ENODATA); + check_eq(uapi16_file_object_data_location(got), UAPI16_DATA_LOCATION_NONE); + check_stated(got, FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_DEVICE)); + } + { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *run = next_object(reader, "run"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = + next_object(reader, "run/fifo"); + uint32_t mode = 0; + + check_eq(uapi16_file_object_type(run), S_IFDIR); + check_eq(uapi16_file_object_type(got), S_IFIFO); + check_eq(uapi16_file_object_mode(got, &mode), 0); + check_eq(mode, 0600); + } + { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = next_object(reader, "usr"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *first = + next_object(reader, "usr/bin"); + uint32_t mode = 0; + + /* The directory that was added twice is what its first + * object said. */ + check_eq(uapi16_file_object_type(got), S_IFDIR); + check_eq(uapi16_file_object_mode(got, &mode), 0); + check_eq(mode, 0755); + check_eq(uapi16_file_object_type(first), S_IFDIR); + check_eq(uapi16_file_object_mode(first, &mode), 0); + check_eq(mode, 0751); + } + { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = + next_object(reader, "usr/bin/alias"); + uint64_t size = 0; + uint32_t mode = 77; + size_t target_size = 0; + const void *target; + + check_eq(uapi16_file_object_type(got), S_IFLNK); + target = uapi16_file_object_literal(got, &target_size); + check_same(target, target_size, "tool", 4); + check_eq(uapi16_file_object_data_location(got), UAPI16_DATA_LOCATION_LITERAL); + check_eq(uapi16_file_object_size(got, &size), 0); + check_eq(size, 4); + check_eq(uapi16_file_object_mode(got, &mode), -ENODATA); + check_stated(got, FEATURES(UAPI16_FEATURE_SIZE, UAPI16_FEATURE_SYMLINK)); + } + for (size_t i = 0; i < 2; i++) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *plain = NULL, *got = NULL; + uapi16_sha256_digest_t hash; + uapi16_inode_token_t token = 0; + uint64_t size = 0, time = 0; + uint32_t mode = 0, uid = 77, gid = 0; + + /* The two names of the first file say the same, as they + * were added: with what the object said then, and with the + * number the manifest gave the file. */ + if (i == 1) + plain = next_object(reader, "usr/libexec"); + got = next_object(reader, i == 0 ? "usr/bin/tool" : "usr/libexec/tool"); + check_eq(uapi16_file_object_type(got), S_IFREG); + check_eq(uapi16_file_object_mode(got, &mode), 0); + check_eq(mode, 0755); + check_eq(uapi16_file_object_uid(got, &uid), 0); + check_eq(uid, 0); + check_eq(uapi16_file_object_gid(got, &gid), 0); + check_eq(gid, 12); + check_str(uapi16_file_object_user_name(got), "root"); + check_str(uapi16_file_object_group_name(got), "staff"); + check_eq(uapi16_file_object_mtime_nsec(got, &time), 0); + check_eq(time, mtime); + check_eq(uapi16_file_object_size(got, &size), 0); + check_eq(size, 5); + check_eq(uapi16_file_object_sha256(got, &hash), 0); + check_hash(&hash, SHA256_OF_HELLO); + check_eq(uapi16_file_object_inode_token(got, &token), 0); + check_eq(token, 2); + check_eq(uapi16_file_object_data_location(got), UAPI16_DATA_LOCATION_EXTERNAL); + check(!uapi16_file_object_literal(got, NULL)); + check_stated(got, of_a_regular_file); + } + { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = + next_object(reader, "z-second"); + uapi16_inode_token_t token = 0; + + check_eq(uapi16_file_object_inode_token(got, &token), 0); + check_eq(token, 1); + } + check_ends(reader); + check(!e); +} + +/* + * An object that a writer refuses leaves the writer as it was: what it + * writes then is what a writer writes that was never given the object. + */ +static void test_refused_objects(void) { + const uapi16_features_t without_modes = FEATURES(UAPI16_FEATURE_SIZE, UAPI16_FEATURE_SHA256, + UAPI16_FEATURE_HARDLINK, + UAPI16_FEATURE_SYMLINK); + _cleanup_(closep) int fd = scratch_file(), clean = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL, *never = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *kept = make_hello("kept"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *linked = make_hello("linked"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *refused = make_object("refused"); + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *written = NULL, *expected = NULL; + size_t written_size, expected_size; + uint64_t record = 77; + int r; + + /* A manifest that records sizes and hashes, hard links and the + * targets of symbolic links, and no access modes. */ + check_eq(set_features(o, without_modes), 0); + check_eq(uapi16_manifest_writer_open(o, fd, &w, &e), 0); + check_eq(uapi16_manifest_writer_open(o, clean, &never, &e), 0); + check_eq(uapi16_file_object_set_inode_token(linked, 5), 0); + check_eq(uapi16_manifest_writer_add_object(w, kept, &e), 0); + check_eq(uapi16_manifest_writer_add_object(w, linked, &e), 0); + check_eq(uapi16_manifest_writer_add_object(never, kept, &e), 0); + check_eq(uapi16_manifest_writer_add_object(never, linked, &e), 0); + + /* A mode, which the manifest does not record. */ + check_eq(uapi16_file_object_set_mode(refused, 0644), 0); + r = uapi16_manifest_writer_add_object(w, refused, &e); + check_eq(uapi16_error_record(e, &record), -ENODATA); + check_refused(r, &e, "unlistedFeature", "refused", "mode"); + + /* A symbolic link without its target, which the manifest + * records. */ + refused = uapi16_file_object_free(refused); + refused = make_object("refused"); + check_eq(uapi16_file_object_set_type(refused, S_IFLNK), 0); + r = uapi16_manifest_writer_add_object(w, refused, &e); + check_refused(r, &e, "noTarget", "refused", NULL); + + /* A size on a FIFO, which has no data. */ + check_eq(uapi16_file_object_set_type(refused, S_IFIFO), 0); + check_eq(uapi16_file_object_set_size(refused, 1), 0); + r = uapi16_manifest_writer_add_object(w, refused, &e); + check_refused(r, &e, "fieldNotPermitted", "refused", "size"); + + /* A name of the file of a token that does not say what its first + * name said, and so is no name of it. */ + check_eq(uapi16_file_object_set_name(linked, "refused", &e), 0); + check_eq(uapi16_file_object_set_size(linked, 6), 0); + r = uapi16_manifest_writer_add_object(w, linked, &e); + check_error(r, e, UAPI16_ERROR_HARDLINK_MISMATCH, ESTALE, "refused", CHECK_HARDLINK_PATH); + check_str(uapi16_error_hardlink_path(e), "linked"); + e = uapi16_error_free(e); + + check_eq(uapi16_manifest_writer_finish(w, &report, &e), 0); + check_eq(uapi16_manifest_report_files(report), 2); + check_eq(uapi16_manifest_report_others(report), 0); + check_eq(uapi16_manifest_writer_finish(never, NULL, &e), 0); + w = uapi16_manifest_writer_free(w); + never = uapi16_manifest_writer_free(never); + written = read_all(fd, &written_size); + expected = read_all(clean, &expected_size); + check_manifest(written, written_size); + check_same(written, written_size, expected, expected_size); + check(!strstr(written, "refused")); + check(!e); +} + +/* + * The writer of records begins a manifest with the features and the order + * of its options, and writes every record before its call returns. It + * refuses a file object that is not where the manifest has it, and goes + * on. It takes no file object after a signature object, and nothing once + * it is finished. What it writes is byte for byte what a writer writes for + * the same objects, and a reader reads it. + */ +static void test_records(void) { + static const int no_descriptors[] = { -1, AT_FDCWD, INT_MIN }; + static const char data[] = { 's', 0, (char) 0xff, 'g' }; + _cleanup_(closep) int written = scratch_file(), listed = scratch_file(), unfinished = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_writer_freep) uapi16_writer *w = NULL, *none = NULL; + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *listing = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *a = make_object("a"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_hello("a/file"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *x = make_object("a/x"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *b = make_object("a-b"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *m = make_object("m"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *refused = make_object("zz/x"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = NULL; + _cleanup_(uapi16_signature_freep) uapi16_signature *openpgp = NULL, *pkcs7 = NULL, *signature = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *records = NULL, *expected = NULL; + size_t records_size, expected_size, before, signed_size, size = 0; + uapi16_sha256_digest_t hash; + uapi16_inode_token_t token = 0; + uint64_t number = 0; + const void *bytes; + int r; + + check_eq(uapi16_file_object_set_type(a, S_IFDIR), 0); + check_eq(uapi16_file_object_set_mode(a, 0755), 0); + check_eq(uapi16_file_object_set_mode(file, 0644), 0); + check_eq(uapi16_file_object_set_uid(file, 1), 0); + check_eq(uapi16_file_object_set_gid(file, 2), 0); + check_eq(uapi16_file_object_set_type(x, S_IFLNK), 0); + check_eq(uapi16_file_object_set_target(x, "file", 4), 0); + check_eq(uapi16_file_object_set_size(b, 0), 0); + check_eq(uapi16_signature_new("openpgp", &openpgp), 0); + check_eq(uapi16_signature_set_key(openpgp, "\x01\xab", 2), 0); + check_eq(uapi16_signature_set_data(openpgp, data, sizeof(data)), 0); + check_eq(uapi16_signature_new("pkcs7", &pkcs7), 0); + + /* A writer of records needs options, a descriptor and a place to + * go to, and no call that is not valid writes anything. */ + check_misuse(uapi16_writer_begin(NULL, written, NULL, &none, &e), &e, EINVAL); + check_misuse(uapi16_writer_begin(o, written, NULL, NULL, &e), &e, EINVAL); + check_eq(uapi16_writer_begin(NULL, written, NULL, &none, NULL), -EINVAL); + check_eq(uapi16_writer_begin(o, written, NULL, NULL, NULL), -EINVAL); + for (size_t i = 0; i < ELEMENTSOF(no_descriptors); i++) + check_misuse(uapi16_writer_begin(o, no_descriptors[i], NULL, &none, &e), &e, EBADF); + check(!none); + check_eq(size_of(written), 0); + check(!uapi16_writer_free(NULL)); + + /* It begins with the root, which says nothing here but what the + * options say: the features and the order. */ + check_eq(uapi16_writer_begin(o, written, NULL, &w, &e), 0); + check(w && !e); + before = size_of(written); + check(before > 0); + check_misuse(uapi16_writer_file(NULL, a, &e), &e, EINVAL); + check_misuse(uapi16_writer_file(w, NULL, &e), &e, EINVAL); + check_misuse(uapi16_writer_signature(NULL, openpgp, &e), &e, EINVAL); + check_misuse(uapi16_writer_signature(w, NULL, &e), &e, EINVAL); + check_misuse(uapi16_writer_finish(NULL, &e), &e, EINVAL); + check_eq(uapi16_writer_file(NULL, a, NULL), -EINVAL); + check_eq(uapi16_writer_file(w, NULL, NULL), -EINVAL); + check_eq(uapi16_writer_signature(NULL, openpgp, NULL), -EINVAL); + check_eq(uapi16_writer_signature(w, NULL, NULL), -EINVAL); + check_eq(uapi16_writer_finish(NULL, NULL), -EINVAL); + check_eq(size_of(written), before); + + /* A file object whose directory was not written is not where the + * manifest has it. It is not written, and the writer goes on. */ + r = uapi16_writer_file(w, file, &e); + check_refused(r, &e, "misplaced", "a/file", NULL); + check_eq(uapi16_writer_file(w, file, NULL), -EBADMSG); + check_eq(size_of(written), before); + + /* The file objects in the order of the manifest: a directory, what + * is in it, and what comes after it. The two names of one file + * carry the number of the file, which the caller gives it. Every + * record is written before its call returns. */ + check_eq(uapi16_writer_file(w, a, &e), 0); + check(size_of(written) > before); + before = size_of(written); + check_eq(uapi16_file_object_set_inode_token(file, 1), 0); + check_eq(uapi16_writer_file(w, file, &e), 0); + check(size_of(written) > before); + check_eq(uapi16_writer_file(w, x, &e), 0); + check_eq(uapi16_writer_file(w, b, &e), 0); + check_eq(uapi16_file_object_set_name(file, "link", &e), 0); + check_eq(uapi16_writer_file(w, file, &e), 0); + before = size_of(written); + + /* What is refused, each for its rule: a file in a directory that + * is not there, one in a directory whose files have ended, one + * that comes before the last one, and one with a field of a + * feature the manifest does not record. */ + r = uapi16_writer_file(w, refused, &e); + check_refused(r, &e, "misplaced", "zz/x", NULL); + check_eq(uapi16_file_object_set_name(refused, "a/late", &e), 0); + r = uapi16_writer_file(w, refused, &e); + check_refused(r, &e, "misplaced", "a/late", NULL); + check_eq(uapi16_file_object_set_name(refused, "b", &e), 0); + r = uapi16_writer_file(w, refused, &e); + check_refused(r, &e, "outOfOrder", "b", NULL); + check_eq(uapi16_file_object_set_name(refused, "unlisted", &e), 0); + check_eq(uapi16_file_object_set_mtime_nsec(refused, 1), 0); + r = uapi16_writer_file(w, refused, &e); + check_refused(r, &e, "unlistedFeature", "unlisted", "mTimeNSec"); + check_eq(size_of(written), before); + check_eq(uapi16_writer_file(w, m, &e), 0); + check(size_of(written) > before); + + /* A signature object signs what was written before the first of + * them. No file object can follow one, and another signature + * object can. */ + signed_size = size_of(written); + check_eq(uapi16_writer_signature(w, openpgp, &e), 0); + before = size_of(written); + check(before > signed_size); + check_eq(uapi16_file_object_set_name(m, "n", &e), 0); + r = uapi16_writer_file(w, m, &e); + check_refused(r, &e, "fileAfterSignature", "n", NULL); + check_eq(size_of(written), before); + check_eq(uapi16_writer_signature(w, pkcs7, &e), 0); + check(size_of(written) > before); + before = size_of(written); + + /* The trailer ends the manifest, and the writer takes nothing + * more. A call that is not valid fails for that still. */ + check_eq(uapi16_writer_finish(w, &e), 0); + check_eq(size_of(written), before + strlen(TRAILER)); + check_ended(uapi16_writer_file(w, m, &e), &e); + check_ended(uapi16_writer_signature(w, pkcs7, &e), &e); + check_ended(uapi16_writer_finish(w, &e), &e); + check_eq(uapi16_writer_file(w, m, NULL), -ESTALE); + check_eq(uapi16_writer_signature(w, pkcs7, NULL), -ESTALE); + check_eq(uapi16_writer_finish(w, NULL), -ESTALE); + check_misuse(uapi16_writer_file(w, NULL, &e), &e, EINVAL); + check_misuse(uapi16_writer_signature(w, NULL, &e), &e, EINVAL); + check_eq(size_of(written), before + strlen(TRAILER)); + w = uapi16_writer_free(w); + check(!w); + records = read_all(written, &records_size); + check_manifest(records, records_size); + + /* A writer that is given the same file objects in another order, + * with a number of the caller for the file with two names, writes + * the same records. */ + check_eq(uapi16_manifest_writer_open(o, listed, &listing, &e), 0); + check_eq(uapi16_file_object_set_name(m, "m", &e), 0); + check_eq(uapi16_file_object_set_inode_token(file, 42), 0); + check_eq(uapi16_manifest_writer_add_object(listing, m, &e), 0); + check_eq(uapi16_manifest_writer_add_object(listing, file, &e), 0); + check_eq(uapi16_manifest_writer_add_object(listing, b, &e), 0); + check_eq(uapi16_manifest_writer_add_object(listing, x, &e), 0); + check_eq(uapi16_file_object_set_name(file, "a/file", &e), 0); + check_eq(uapi16_manifest_writer_add_object(listing, file, &e), 0); + check_eq(uapi16_manifest_writer_add_object(listing, a, &e), 0); + check_eq(uapi16_manifest_writer_finish(listing, NULL, &e), 0); + listing = uapi16_manifest_writer_free(listing); + expected = read_all(listed, &expected_size); + check_eq(expected_size, signed_size + strlen(TRAILER)); + check_eq(memcmp(records, expected, signed_size), 0); + check_manifest(expected, expected_size); + + /* A reader reads the file objects, and then the signature objects + * with what they sign: all that was written before the first of + * them. */ + reader = open_reader(written); + check_recorded(reader, FEATURES(DEFAULT_FEATURES)); + check_eq(uapi16_reader_order(reader), UAPI16_ORDER_CODEPOINT); + got = next_object(reader, "a"); + got = uapi16_file_object_free(got); + got = next_object(reader, "a/file"); + check_eq(uapi16_file_object_inode_token(got, &token), 0); + check_eq(token, 1); + got = uapi16_file_object_free(got); + /* The size of a symbolic link follows from its target, and the + * hash of no data from the size 0. A reader fills them in, and they + * are none of the fields of the object. */ + got = next_object(reader, "a/x"); + check_eq(uapi16_file_object_size(got, &number), 0); + check_eq(number, 4); + check_stated(got, FEATURES(UAPI16_FEATURE_SYMLINK)); + got = uapi16_file_object_free(got); + got = next_object(reader, "a-b"); + check_eq(uapi16_file_object_sha256(got, &hash), 0); + check_hash(&hash, SHA256_OF_NOTHING); + check_stated(got, FEATURES(UAPI16_FEATURE_SIZE)); + got = uapi16_file_object_free(got); + got = next_object(reader, "link"); + token = 0; + check_eq(uapi16_file_object_inode_token(got, &token), 0); + check_eq(token, 1); + got = uapi16_file_object_free(got); + got = next_object(reader, "m"); + got = uapi16_file_object_free(got); + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_SIGNATURES); + check_eq(uapi16_reader_signed_len(reader, &number), 0); + check_eq(number, signed_size); + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_SIGNATURE); + check_str(uapi16_signature_mechanism(signature), "openpgp"); + bytes = uapi16_signature_key(signature, &size); + check_same(bytes, size, "\x01\xab", 2); + bytes = uapi16_signature_data(signature, &size); + check_same(bytes, size, data, sizeof(data)); + signature = uapi16_signature_free(signature); + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_SIGNATURE); + check_str(uapi16_signature_mechanism(signature), "pkcs7"); + check(!uapi16_signature_key(signature, &size)); + check(!uapi16_signature_data(signature, &size)); + signature = uapi16_signature_free(signature); + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_END); + reader = uapi16_reader_free(reader); + + /* A writer of records that is freed before it finished leaves no + * trailer, and a reader takes what it wrote as incomplete. */ + check_eq(uapi16_writer_begin(o, unfinished, NULL, &w, &e), 0); + check_eq(uapi16_writer_file(w, a, &e), 0); + w = uapi16_writer_free(w); + reader = open_reader(unfinished); + got = next_object(reader, "a"); + got = uapi16_file_object_free(got); + r = uapi16_reader_next(reader, &got, &e); + check_refused(r, &e, "noTrailer", NULL, NULL); + check(!e); +} + +/* + * The fields of the features that say something of a file by not being + * there: whether it is read-only, its extended attributes, its inode flags + * and its DOS attributes. A writer of records writes them, and what a + * reader hands out has them, also where the record left them out because + * the features of the manifest say them. + */ +static void test_record_fields(void) { + _cleanup_(closep) int written = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_writer_freep) uapi16_writer *w = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *d = make_object("d"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *f = make_hello("d/f"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *plain = make_object("plain"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + static const char binary[] = { 0, (char) 0xfe, 'x' }; + uapi16_sha256_digest_t hash; + uint32_t stated = 77, set = 77, mode = 0; + uapi16_features_t features; + uint64_t size = 0; + size_t count = 77, value_size = 77; + const char *name = NULL; + const void *value = NULL; + + check_eq(set_features(o, FEATURES_OF_TREES), 0); + + /* A directory that is not read-only, with extended attributes, an + * inode flag that is set and one that is not, and DOS attributes + * the same way. */ + check_eq(uapi16_file_object_set_type(d, S_IFDIR), 0); + check_eq(uapi16_file_object_set_mode(d, 0755), 0); + check_eq(uapi16_file_object_set_read_only(d, UAPI16_READ_ONLY_NO), 0); + check_eq(uapi16_file_object_add_user_xattr(d, "text", "a value", 7), 0); + check_eq(uapi16_file_object_add_user_xattr(d, "binary", binary, sizeof(binary)), 0); + check_eq(uapi16_file_object_add_user_xattr(d, "empty", NULL, 0), 0); + check_eq(uapi16_file_object_set_inode_flags(d, NODUMP_FL | APPEND_FL, NODUMP_FL), 0); + check_eq(uapi16_file_object_set_dos_attributes(d, DOS_HIDDEN | DOS_ARCHIVE, DOS_HIDDEN), 0); + + /* A regular file that is read-only and lists no extended + * attributes. */ + check_eq(uapi16_file_object_set_mode(f, 0444), 0); + check_eq(uapi16_file_object_set_read_only(f, UAPI16_READ_ONLY_YES), 0); + check_eq(uapi16_file_object_set_user_xattrs(f), 0); + + w = begin_records(o, written); + check_eq(uapi16_writer_file(w, d, &e), 0); + check_eq(uapi16_writer_file(w, f, &e), 0); + check_eq(uapi16_writer_file(w, plain, &e), 0); + check_eq(uapi16_writer_finish(w, &e), 0); + w = uapi16_writer_free(w); + + reader = open_reader(written); + check_recorded(reader, FEATURES_OF_TREES); + /* The root said nothing. The manifest says by its features that + * it is not read-only, has no extended attributes and none of the + * flags, which is none of its fields. */ + check_eq(uapi16_file_object_read_only(uapi16_reader_root(reader)), UAPI16_READ_ONLY_NO); + check_eq(uapi16_file_object_user_xattrs(uapi16_reader_root(reader), &count), 0); + check_eq(count, 0); + check_eq(uapi16_file_object_inode_flags(uapi16_reader_root(reader), &stated, &set), 0); + check_eq(stated, INODE_FLAGS); + check_eq(set, 0); + check_stated(uapi16_reader_root(reader), features_none()); + + got = next_object(reader, "d"); + check_eq(uapi16_file_object_read_only(got), UAPI16_READ_ONLY_NO); + check_eq(uapi16_file_object_user_xattrs(got, &count), 0); + check_eq(count, 3); + check_eq(uapi16_file_object_user_xattr(got, 0, &name, &value, &value_size), 0); + check_str(name, "binary"); + check_same(value, value_size, binary, sizeof(binary)); + check_eq(uapi16_file_object_user_xattr(got, 1, &name, &value, &value_size), 0); + check_str(name, "empty"); + check_eq(value_size, 0); + check_eq(uapi16_file_object_user_xattr(got, 2, &name, &value, &value_size), 0); + check_str(name, "text"); + check_same(value, value_size, "a value", 7); + check_eq(uapi16_file_object_inode_flags(got, &stated, &set), 0); + check_eq(stated, INODE_FLAGS); + check_eq(set, NODUMP_FL); + check_eq(uapi16_file_object_dos_attributes(got, &stated, &set), 0); + check_eq(stated, DOS_ATTRIBUTES); + check_eq(set, DOS_HIDDEN); + /* Of these it has the fields that its record has: the flags that + * are set, and the extended attributes. */ + features = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_USER_XATTR, + UAPI16_FEATURE_FLAG_NO_DUMP, UAPI16_FEATURE_FLAG_HIDDEN); + check_stated(got, features); + got = uapi16_file_object_free(got); + + got = next_object(reader, "d/f"); + check_eq(uapi16_file_object_mode(got, &mode), 0); + check_eq(mode, 0444); + check_eq(uapi16_file_object_read_only(got), UAPI16_READ_ONLY_YES); + check_eq(uapi16_file_object_user_xattrs(got, &count), 0); + check_eq(count, 0); + check_eq(uapi16_file_object_inode_flags(got, &stated, &set), 0); + check_eq(stated, INODE_FLAGS); + check_eq(set, 0); + check_eq(uapi16_file_object_dos_attributes(got, &stated, &set), 0); + check_eq(stated, DOS_ATTRIBUTES); + check_eq(set, 0); + check_eq(uapi16_file_object_size(got, &size), 0); + check_eq(size, 5); + check_eq(uapi16_file_object_sha256(got, &hash), 0); + check_hash(&hash, SHA256_OF_HELLO); + features = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_SIZE, UAPI16_FEATURE_SHA256, + UAPI16_FEATURE_READ_ONLY); + check_stated(got, features); + got = uapi16_file_object_free(got); + + /* The file that said nothing has what the features say, and no + * field of them. */ + got = next_object(reader, "plain"); + check_eq(uapi16_file_object_read_only(got), UAPI16_READ_ONLY_NO); + check_eq(uapi16_file_object_user_xattrs(got, &count), 0); + check_eq(count, 0); + check_eq(uapi16_file_object_inode_flags(got, &stated, &set), 0); + check_eq(stated, INODE_FLAGS); + check_eq(set, 0); + check_eq(uapi16_file_object_dos_attributes(got, &stated, &set), 0); + check_eq(stated, DOS_ATTRIBUTES); + check_eq(set, 0); + check_stated(got, features_none()); + check_ends(reader); + check(!e); +} + +/* + * What a reader hands out, a writer of records writes back: the root and + * every file object of the manifest of a tree, to the same bytes. What the + * reader filled in for the features of the manifest is left out again. + */ +static void test_copies(void) { + const uapi16_features_t features = FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_MTIME, + UAPI16_FEATURE_READ_ONLY, + UAPI16_FEATURE_USER_NAME, + UAPI16_FEATURE_GROUP_NAME); + _cleanup_(closep) int tree = make_tree("copies"), original = scratch_file(), copy = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_writer_freep) uapi16_writer *w = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *generated = NULL, *copied = NULL; + size_t generated_size, copied_size, files = 0; + bool read_only = false; + + /* A tree with a file that is read-only, which its record says, and + * files that are not, which the features say. */ + check_eq(fchmodat(tree, "a/file", 0444, 0), 0); + check_eq(set_features(o, features), 0); + check_eq(uapi16_manifest_generate(o, original, tree, UAPI16_ADD_NONE, NULL, &e), 0); + + reader = open_reader(original); + check_recorded(reader, features); + check_eq(uapi16_writer_begin(o, copy, uapi16_reader_root(reader), &w, &e), 0); + for (;;) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = NULL; + int r = uapi16_reader_next(reader, &file, &e); + + if (r == UAPI16_READ_END) + break; + check_eq(r, UAPI16_READ_FILE); + if (strcmp(uapi16_file_object_name(file), "a/file") == 0) { + check_eq(uapi16_file_object_read_only(file), UAPI16_READ_ONLY_YES); + check(uapi16_file_object_has_stated_feature(file, UAPI16_FEATURE_READ_ONLY)); + read_only = true; + } else { + check_eq(uapi16_file_object_read_only(file), UAPI16_READ_ONLY_NO); + check(!uapi16_file_object_has_stated_feature(file, UAPI16_FEATURE_READ_ONLY)); + } + check_eq(uapi16_writer_file(w, file, &e), 0); + files++; + } + check_eq(uapi16_writer_finish(w, &e), 0); + check_eq(files, 6); + check(read_only); + reader = uapi16_reader_free(reader); + w = uapi16_writer_free(w); + + generated = read_all(original, &generated_size); + copied = read_all(copy, &copied_size); + check_manifest(generated, generated_size); + check(strstr(generated, "\"readOnly\":true")); + check(!strstr(generated, "\"readOnly\":false")); + check_same(copied, copied_size, generated, generated_size); + check(!e); +} + +/* + * A manifest that declares no order. Options take UAPI16_ORDER_NONE for a + * writer of records, which then writes the file objects in the order of + * the caller and checks what it can without an order: that each comes + * right after the object of its directory, and that no name comes again + * right after the entries of the directory it names. A name that comes + * again later is not found. The functions that sort refuse such options. + */ +static void test_no_order(void) { + /* File objects as a caller that does not sort has them, and the + * rule a writer of records refuses each for: without an order, and + * with the code point order. */ + static const struct { + const char *name; + uint32_t type; + const char *unordered, *ordered; + } steps[] = { + { "b", S_IFDIR, NULL, NULL }, + { "b/z", S_IFREG, NULL, NULL }, + /* After b/z, which it sorts before. */ + { "b/y", S_IFREG, NULL, "outOfOrder" }, + /* A name that comes twice, with another one in between. */ + { "b/z", S_IFREG, NULL, "duplicateName" }, + /* The directory again, right after its entries. */ + { "b", S_IFDIR, "duplicateName", "duplicateName" }, + { "a", S_IFREG, NULL, "outOfOrder" }, + /* The same name again, right away. */ + { "a", S_IFREG, "duplicateName", "outOfOrder" }, + /* Not right after the object of its directory. */ + { "b/x", S_IFREG, "misplaced", "outOfOrder" }, + }; + static const char *const unordered_names[] = { "b", "b/z", "b/y", "b/z", "a" }; + static const char *const ordered_names[] = { "b", "b/z" }; + _cleanup_(closep) int tree = make_tree("no-order"), out = make_dir(tmp_fd, "no-order-out"); + _cleanup_(closep) int unsorted = scratch_file(), sorted = scratch_file(), into = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_writer_freep) uapi16_writer *w = NULL; + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *listing = NULL, *none = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *text = NULL; + size_t text_size; + struct stat st; + int r; + + /* Options take no order, and take the code point order back. */ + check_eq(uapi16_manifest_options_set_order(o, UAPI16_ORDER_NONE), 0); + + /* A writer of records for such options writes the file objects as + * they come. It lets the name through that comes twice with + * another one in between, and refuses the three it can tell + * without an order. What it refuses is not written. */ + check_eq(uapi16_writer_begin(o, unsorted, NULL, &w, &e), 0); + check(w && !e); + for (size_t i = 0; i < ELEMENTSOF(steps); i++) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_object(steps[i].name); + size_t before = size_of(unsorted); + + check_eq(uapi16_file_object_set_type(file, steps[i].type), 0); + r = uapi16_writer_file(w, file, &e); + if (steps[i].unordered) { + check_refused(r, &e, steps[i].unordered, steps[i].name, NULL); + check_eq(size_of(unsorted), before); + } else { + check_eq(r, 0); + check(size_of(unsorted) > before); + } + } + check_eq(uapi16_writer_finish(w, &e), 0); + w = uapi16_writer_free(w); + + /* The manifest declares no order: its root has none, a reader says + * so, and a caller that relies on the code point order is told + * that it can't. No order is none to require, of any manifest. The + * reader takes the file objects in the order they are in. */ + text = read_all(unsorted, &text_size); + check_manifest(text, text_size); + check(!strstr(text, "\"order\"")); + reader = open_reader(unsorted); + check_eq(uapi16_reader_order(reader), UAPI16_ORDER_NONE); + r = uapi16_reader_require_order(reader, UAPI16_ORDER_CODEPOINT, &e); + check_eq(uapi16_error_kind(e), UAPI16_ERROR_MANIFEST); + check_refused(r, &e, "noOrder", "", "order"); + check_misuse(uapi16_reader_require_order(reader, UAPI16_ORDER_NONE, &e), &e, EINVAL); + check_eq(uapi16_reader_require_order(reader, UAPI16_ORDER_NONE, NULL), -EINVAL); + for (size_t i = 0; i < ELEMENTSOF(unordered_names); i++) { + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(got), unordered_names[i]); + } + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_END); + reader = uapi16_reader_free(reader); + + /* The functions that sort take no options without an order: each + * of the four fails for them as a call that is not valid does, + * makes no file, writes nothing and stores no object. */ + check_misuse(uapi16_manifest_writer_create_at(o, out, "m", &none, &e), &e, EINVAL); + check_misuse(uapi16_manifest_writer_open(o, into, &none, &e), &e, EINVAL); + check_misuse(uapi16_manifest_generate_at(o, out, "m", tree, UAPI16_ADD_NONE, &report, &e), &e, EINVAL); + check_misuse(uapi16_manifest_generate(o, into, tree, UAPI16_ADD_NONE, &report, &e), &e, EINVAL); + check_eq(uapi16_manifest_writer_create_at(o, out, "m", &none, NULL), -EINVAL); + check_eq(uapi16_manifest_writer_open(o, into, &none, NULL), -EINVAL); + check_eq(uapi16_manifest_generate_at(o, out, "m", tree, UAPI16_ADD_NONE, NULL, NULL), -EINVAL); + check_eq(uapi16_manifest_generate(o, into, tree, UAPI16_ADD_NONE, NULL, NULL), -EINVAL); + check(!none && !report); + check_eq(size_of(into), 0); + check_eq(count_entries(tmp_fd, "no-order-out"), 0); + check_eq(fstatat(out, "m", &st, 0), -1); + check_eq(errno, ENOENT); + + /* With the code point order the names have to be in it, and every + * name that comes twice is found. */ + check_eq(uapi16_manifest_options_set_order(o, UAPI16_ORDER_CODEPOINT), 0); + check_eq(uapi16_writer_begin(o, sorted, NULL, &w, &e), 0); + for (size_t i = 0; i < ELEMENTSOF(steps); i++) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_object(steps[i].name); + size_t before = size_of(sorted); + + check_eq(uapi16_file_object_set_type(file, steps[i].type), 0); + r = uapi16_writer_file(w, file, &e); + if (steps[i].ordered) { + check_refused(r, &e, steps[i].ordered, steps[i].name, NULL); + check_eq(size_of(sorted), before); + } else { + check_eq(r, 0); + check(size_of(sorted) > before); + } + } + check_eq(uapi16_writer_finish(w, &e), 0); + w = uapi16_writer_free(w); + reader = open_reader(sorted); + check_eq(uapi16_reader_order(reader), UAPI16_ORDER_CODEPOINT); + check_eq(uapi16_reader_require_order(reader, UAPI16_ORDER_CODEPOINT, &e), 0); + check_misuse(uapi16_reader_require_order(reader, UAPI16_ORDER_NONE, &e), &e, EINVAL); + for (size_t i = 0; i < ELEMENTSOF(ordered_names); i++) { + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(got), ordered_names[i]); + } + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_END); + reader = uapi16_reader_free(reader); + + /* And the four that sort work again. */ + check_eq(uapi16_manifest_writer_create_at(o, out, "m", &listing, &e), 0); + check_eq(uapi16_manifest_writer_finish(listing, NULL, &e), 0); + listing = uapi16_manifest_writer_free(listing); + check_eq(fstatat(out, "m", &st, 0), 0); + check_eq(uapi16_manifest_writer_open(o, into, &listing, &e), 0); + check_eq(uapi16_manifest_writer_finish(listing, NULL, &e), 0); + listing = uapi16_manifest_writer_free(listing); + check(size_of(into) > 0); + empty(into); + check_eq(uapi16_manifest_generate_at(o, out, "generated", tree, UAPI16_ADD_NONE, &report, &e), 0); + report = uapi16_manifest_report_free(report); + check_eq(uapi16_manifest_generate(o, into, tree, UAPI16_ADD_NONE, &report, &e), 0); + check_eq(uapi16_manifest_report_files(report), 3); + check(size_of(into) > 0); + check(!e); +} + +/* A manifest with a file object and two signature objects, and how many + * bytes of it the signature objects sign: all before the first of them. */ +#define SIGNED_PART ROOT FILE_OBJECT("a") +#define SIGNED SIGNED_PART SIGNATURE_OBJECT("openpgp") SIGNATURE_OBJECT("pkcs7") TRAILER + +/* A manifest with a file object after a signature object, which is in + * record 3: the root is in record 0. */ +#define FILE_AFTER_SIGNATURE ROOT FILE_OBJECT("a") SIGNATURE_OBJECT("openpgp") FILE_OBJECT("b") TRAILER +#define RECORD_AFTER_SIGNATURE 3 + +/* What a reader fails with that a manifest breaks the rule `problem` for: + * an error of the kind UAPI16_ERROR_MANIFEST that names the rule. */ +static void check_broken(int r, uapi16_error **e, const char *problem) { + check_eq(r, -EBADMSG); + check(*e); + check_eq(uapi16_error_kind(*e), UAPI16_ERROR_MANIFEST); + check_eq(uapi16_error_errno(*e), EBADMSG); + check_str(uapi16_error_problem(*e), problem); + *e = uapi16_error_free(*e); +} + +/* + * The read flow: the file objects come from uapi16_reader_next(), which + * says where they end, with signature objects to follow or with the + * trailer. The signature objects come from uapi16_reader_next_signature(), + * or are passed over by uapi16_reader_next(). A reader that failed to read + * an object takes nothing more. + */ +static void test_reading(void) { + static const int no_descriptors[] = { -1, AT_FDCWD, INT_MIN }; + _cleanup_(closep) int plain = manifest_pipe(ROOT FILE_OBJECT("a") FILE_OBJECT("b") TRAILER); + _cleanup_(closep) int passed = manifest_file(SIGNED), taken = manifest_pipe(SIGNED); + _cleanup_(closep) int one = manifest_file(SIGNED); + _cleanup_(closep) int late = manifest_file(FILE_AFTER_SIGNATURE); + _cleanup_(closep) int late_passed = manifest_pipe(FILE_AFTER_SIGNATURE); + _cleanup_(closep) int cut = manifest_file(ROOT FILE_OBJECT("a")); + _cleanup_(closep) int cut_taken = manifest_file(ROOT FILE_OBJECT("a") SIGNATURE_OBJECT("openpgp")); + _cleanup_(closep) int cut_passed = manifest_pipe(ROOT FILE_OBJECT("a") SIGNATURE_OBJECT("openpgp")); + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL, *none = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = NULL; + _cleanup_(uapi16_signature_freep) uapi16_signature *signature = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + const uapi16_signature *mine; + uint64_t length = 77; + int r; + + /* A reader needs a descriptor and a place to go to. */ + check_misuse(uapi16_reader_open(plain, NULL, &e), &e, EINVAL); + check_eq(uapi16_reader_open(plain, NULL, NULL), -EINVAL); + for (size_t i = 0; i < ELEMENTSOF(no_descriptors); i++) + check_misuse(uapi16_reader_open(no_descriptors[i], &none, &e), &e, EBADF); + check(!none); + check(!uapi16_reader_free(NULL)); + + /* A manifest without signature objects, which comes through a + * pipe: its file objects, and its end. It signs nothing. A caller + * can't ask for signature objects while its file objects come, and + * a call that is not valid reads nothing. At its end it has none: a + * caller that asks is told that the manifest ended, as often as it + * asks, and keeps the object it has, as it is. */ + check_eq(uapi16_reader_open(plain, &reader, &e), 0); + check(reader && !e); + check_eq(uapi16_reader_signed_len(reader, &length), -ENODATA); + check_misuse(uapi16_reader_next_signature(reader, &signature, &e), &e, EINVAL); + check_misuse(uapi16_reader_next(NULL, &file, &e), &e, EINVAL); + check_misuse(uapi16_reader_next(reader, NULL, &e), &e, EINVAL); + check_misuse(uapi16_reader_next_signature(NULL, &signature, &e), &e, EINVAL); + check_misuse(uapi16_reader_next_signature(reader, NULL, &e), &e, EINVAL); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(file), "a"); + file = uapi16_file_object_free(file); + check_eq(uapi16_reader_next_signature(reader, &signature, NULL), -EINVAL); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(file), "b"); + file = uapi16_file_object_free(file); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_END); + check_eq(uapi16_reader_signed_len(reader, &length), -ENODATA); + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_END); + check(!signature && !e); + check_eq(uapi16_signature_new("mine", &signature), 0); + mine = signature; + for (int again = 0; again < 2; again++) { + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_END); + check(signature == mine); + check_str(uapi16_signature_mechanism(signature), "mine"); + } + signature = uapi16_signature_free(signature); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_END); + check(!file && !e); + check_eq(length, 77); + check_eq(uapi16_reader_signed_len(NULL, &length), -EINVAL); + check_eq(uapi16_reader_signed_len(reader, NULL), -EINVAL); + reader = uapi16_reader_free(reader); + check(!reader); + + /* Signature objects that are passed over: the file objects end + * where they begin, what they sign is known from there on, and the + * next call reads on to the trailer. */ + check_eq(uapi16_reader_open(passed, &reader, &e), 0); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + file = uapi16_file_object_free(file); + check_eq(uapi16_reader_signed_len(reader, &length), -ENODATA); + check_eq(length, 77); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_SIGNATURES); + check_eq(uapi16_reader_signed_len(reader, &length), 0); + check_eq(length, strlen(SIGNED_PART)); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_END); + length = 77; + check_eq(uapi16_reader_signed_len(reader, &length), 0); + check_eq(length, strlen(SIGNED_PART)); + reader = uapi16_reader_free(reader); + + /* Signature objects that are read, each once, up to the trailer. */ + check_eq(uapi16_reader_open(taken, &reader, &e), 0); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + file = uapi16_file_object_free(file); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_SIGNATURES); + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_SIGNATURE); + check_str(uapi16_signature_mechanism(signature), "openpgp"); + signature = uapi16_signature_free(signature); + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_SIGNATURE); + check_str(uapi16_signature_mechanism(signature), "pkcs7"); + signature = uapi16_signature_free(signature); + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_END); + length = 77; + check_eq(uapi16_reader_signed_len(reader, &length), 0); + check_eq(length, strlen(SIGNED_PART)); + reader = uapi16_reader_free(reader); + + /* One that is read, and the rest passed over. */ + check_eq(uapi16_reader_open(one, &reader, &e), 0); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + file = uapi16_file_object_free(file); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_SIGNATURES); + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_SIGNATURE); + check_str(uapi16_signature_mechanism(signature), "openpgp"); + signature = uapi16_signature_free(signature); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_END); + reader = uapi16_reader_free(reader); + check(!e); + + /* A file object after a signature object is one that no signature + * covers. A reader that reads the signature objects refuses it, + * and takes nothing more. */ + check_eq(uapi16_reader_open(late, &reader, &e), 0); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + file = uapi16_file_object_free(file); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_SIGNATURES); + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_SIGNATURE); + signature = uapi16_signature_free(signature); + r = uapi16_reader_next_signature(reader, &signature, &e); + check_record(e, RECORD_AFTER_SIGNATURE); + check_broken(r, &e, "fileAfterSignature"); + check_ended(uapi16_reader_next_signature(reader, &signature, &e), &e); + check_ended(uapi16_reader_next(reader, &file, &e), &e); + check_eq(uapi16_reader_next_signature(reader, &signature, NULL), -ESTALE); + check_eq(uapi16_reader_next(reader, &file, NULL), -ESTALE); + /* A call that is not valid fails for that still. */ + check_misuse(uapi16_reader_next(reader, NULL, &e), &e, EINVAL); + check_misuse(uapi16_reader_next_signature(reader, NULL, &e), &e, EINVAL); + reader = uapi16_reader_free(reader); + + /* So does one that passes over them. */ + check_eq(uapi16_reader_open(late_passed, &reader, &e), 0); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + file = uapi16_file_object_free(file); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_SIGNATURES); + r = uapi16_reader_next(reader, &file, &e); + check_record(e, RECORD_AFTER_SIGNATURE); + check_broken(r, &e, "fileAfterSignature"); + check_ended(uapi16_reader_next(reader, &file, &e), &e); + check_ended(uapi16_reader_next_signature(reader, &signature, &e), &e); + reader = uapi16_reader_free(reader); + + /* A manifest that ends without its trailer is not complete: after + * its file objects, and after its signature objects, read or + * passed over. */ + check_eq(uapi16_reader_open(cut, &reader, &e), 0); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + file = uapi16_file_object_free(file); + check_broken(uapi16_reader_next(reader, &file, &e), &e, "noTrailer"); + check_ended(uapi16_reader_next(reader, &file, &e), &e); + check_ended(uapi16_reader_next_signature(reader, &signature, &e), &e); + reader = uapi16_reader_free(reader); + check_eq(uapi16_reader_open(cut_taken, &reader, &e), 0); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + file = uapi16_file_object_free(file); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_SIGNATURES); + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_SIGNATURE); + signature = uapi16_signature_free(signature); + check_broken(uapi16_reader_next_signature(reader, &signature, &e), &e, "noTrailer"); + check_ended(uapi16_reader_next_signature(reader, &signature, &e), &e); + check_ended(uapi16_reader_next(reader, &file, &e), &e); + reader = uapi16_reader_free(reader); + check_eq(uapi16_reader_open(cut_passed, &reader, &e), 0); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + file = uapi16_file_object_free(file); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_SIGNATURES); + check_broken(uapi16_reader_next(reader, &file, &e), &e, "noTrailer"); + check_ended(uapi16_reader_next(reader, &file, &e), &e); + check(!e); +} + +/* A reader of a descriptor that does not block fails with EAGAIN while + * there is nothing to read. That does not end it: it lost nothing, and it + * reads on with the next call, also where half a record came in between. + * The object of the caller stays as it is until then. The open is another + * matter: it loses what it read where it fails with EAGAIN, so it needs the + * root and the start of the next record in the descriptor. */ +static void test_no_blocking(void) { + static const char *const too_little[] = { "\x1e{\"mediaType\":", ROOT }; + static const char enough[] = ROOT RS; + static const char begin[] = "{\"name\":\"a\"}\n" RS; + static const char half[] = "{\"name\":\"b\","; + static const char rest[] = "\"size\":7}\n" TRAILER; + _cleanup_(closep) int from = -1, into = -1; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + uint64_t size = 0; + int ends[2], r; + char byte; + + /* The open reads the root and looks at what comes after it. With + * less than that in the pipe it fails with EAGAIN, and what it read + * is lost: half of the root, and the root alone. */ + for (size_t i = 0; i < ELEMENTSOF(too_little); i++) { + int lost[2]; + + check_eq(pipe2(lost, O_CLOEXEC | O_NONBLOCK), 0); + check_eq(write(lost[1], too_little[i], strlen(too_little[i])), (ssize_t) strlen(too_little[i])); + r = uapi16_reader_open(lost[0], &reader, &e); + check_error(r, e, UAPI16_ERROR_IO, EAGAIN, NULL, CHECK_RECORD); + e = uapi16_error_free(e); + check(!reader); + check_eq(read(lost[0], &byte, 1), -1); + check_eq(errno, EAGAIN); + check_eq(close(lost[0]), 0); + check_eq(close(lost[1]), 0); + } + + /* With the root and the start of the next record it opens. */ + check_eq(pipe2(ends, O_CLOEXEC | O_NONBLOCK), 0); + from = ends[0]; + into = ends[1]; + check_eq(write(into, enough, strlen(enough)), (ssize_t) strlen(enough)); + check_eq(uapi16_reader_open(from, &reader, &e), 0); + check_eq(write(into, begin, strlen(begin)), (ssize_t) strlen(begin)); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(file), "a"); + for (int with_half = 0; with_half < 2; with_half++) { + if (with_half) + check_eq(write(into, half, strlen(half)), (ssize_t) strlen(half)); + r = uapi16_reader_next(reader, &file, &e); + check_error(r, e, UAPI16_ERROR_IO, EAGAIN, NULL, CHECK_RECORD); + e = uapi16_error_free(e); + check_eq(uapi16_reader_next(reader, &file, NULL), -EAGAIN); + check_str(uapi16_file_object_name(file), "a"); + } + check_eq(write(into, rest, strlen(rest)), (ssize_t) strlen(rest)); + check_eq(close(into), 0); + into = -1; + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(file), "b"); + check_eq(uapi16_file_object_size(file, &size), 0); + check_eq(size, 7); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_END); + check(!e); +} + +/* + * What a reader says of its manifest as a whole: its root, what it + * records, the order it declares and whether it may be used. And what it + * says of a manifest that breaks a rule: which rule, in which record, of + * which file and in which field. + */ +static void test_manifests(void) { + _cleanup_(closep) int ordered = manifest_file(ROOT FILE_OBJECT("a") FILE_OBJECT("b") TRAILER); + _cleanup_(closep) int unordered = + manifest_file(ROOT_WITHOUT_ORDER FILE_OBJECT("b") FILE_OBJECT("a") TRAILER); + _cleanup_(closep) int out_of_order = manifest_file(ROOT FILE_OBJECT("b") FILE_OBJECT("a") TRAILER); + _cleanup_(closep) int misplaced = manifest_file(ROOT FILE_OBJECT("a") FILE_OBJECT("b/c") TRAILER); + _cleanup_(closep) int featured = + manifest_file(RS "{\"features\":[\"size\",\"mtime\"]," + "\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n" + RS "{\"mTimeNSec\":7,\"name\":\"a\",\"size\":3}\n" + RS "{\"mode\":420,\"name\":\"b\"}\n" TRAILER); + _cleanup_(closep) int empty_file = scratch_file(); + _cleanup_(closep) int no_separator = + manifest_file("{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n" TRAILER); + _cleanup_(closep) int no_manifest = + manifest_file(RS "{\"mediaType\":\"application/x-other\"}\n" TRAILER); + _cleanup_(closep) int root_with_size = + manifest_file(RS "{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"size\":1}\n" + TRAILER); + _cleanup_(closep) int data = + manifest_file(ROOT RS "{\"contents\":[{\"literal\":\"aGVsbG8=\"}],\"name\":\"literal\"}\n" + RS "{\"name\":\"none\",\"size\":0}\n" + RS "{\"contents\":[{\"file\":\"blobs/1\"}],\"name\":\"other\"}\n" + RS "{\"name\":\"own\"}\n" + RS "{\"contents\":[{\"url\":\"https://example.com/x\"}],\"name\":\"remote\"}\n" + RS "{\"name\":\"without\",\"type\":\"fifo\"}\n" TRAILER); + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL, *none = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL, *again = NULL; + const char *field, *problem; + uapi16_sha256_digest_t hash; + uint64_t number = 77; + size_t size = 77; + const void *literal; + int r; + + /* A manifest that declares its order and lists no features: it + * records the default ones. Its root is the object with the empty + * name, which says nothing here. */ + reader = open_reader(ordered); + check_recorded(reader, FEATURES(DEFAULT_FEATURES)); + check_eq(uapi16_reader_order(reader), UAPI16_ORDER_CODEPOINT); + check_eq(uapi16_reader_require_order(reader, UAPI16_ORDER_CODEPOINT, &e), 0); + check_eq(uapi16_reader_require_order(reader, UAPI16_ORDER_CODEPOINT, NULL), 0); + check_str(uapi16_file_object_name(uapi16_reader_root(reader)), ""); + check_eq(uapi16_file_object_type(uapi16_reader_root(reader)), S_IFDIR); + check_stated(uapi16_reader_root(reader), features_none()); + /* An order that is none is no order to require. */ + check_misuse(uapi16_reader_require_order(reader, UAPI16_ORDER_NONE, &e), &e, EINVAL); + check_misuse(uapi16_reader_require_order(reader, 2, &e), &e, EINVAL); + check_misuse(uapi16_reader_require_order(NULL, UAPI16_ORDER_CODEPOINT, &e), &e, EINVAL); + check_eq(uapi16_reader_require_order(reader, UINT64_MAX, NULL), -EINVAL); + reader = uapi16_reader_free(reader); + + /* No reader says nothing. */ + check(!uapi16_reader_root(NULL)); + check_recorded(NULL, features_none()); + check_eq(uapi16_reader_order(NULL), UAPI16_ORDER_NONE); + + /* A manifest that declares no order has none, and a caller that + * relies on one is told: the rule, and the root with its field and + * its record. Its file objects come in the order they are in. */ + reader = open_reader(unordered); + check_eq(uapi16_reader_order(reader), UAPI16_ORDER_NONE); + r = uapi16_reader_require_order(reader, UAPI16_ORDER_CODEPOINT, &e); + check_record(e, 0); + check_refused(r, &e, "noOrder", "", "order"); + check_eq(uapi16_reader_require_order(reader, UAPI16_ORDER_CODEPOINT, NULL), -EBADMSG); + file = next_object(reader, "b"); + file = uapi16_file_object_free(file); + file = next_object(reader, "a"); + file = uapi16_file_object_free(file); + check_ends(reader); + reader = uapi16_reader_free(reader); + + /* The reader holds the file objects to the order the manifest + * declares: one that comes after one it sorts before is refused, + * with the number of its record and its name. */ + reader = open_reader(out_of_order); + file = next_object(reader, "b"); + file = uapi16_file_object_free(file); + r = uapi16_reader_next(reader, &file, &e); + check_record(e, 2); + check_refused(r, &e, "outOfOrder", "a", NULL); + check_ended(uapi16_reader_next(reader, &file, &e), &e); + reader = uapi16_reader_free(reader); + + /* So is one that does not come right after the object of its + * directory. */ + reader = open_reader(misplaced); + file = next_object(reader, "a"); + file = uapi16_file_object_free(file); + r = uapi16_reader_next(reader, &file, &e); + check_record(e, 2); + check_refused(r, &e, "misplaced", "b/c", NULL); + reader = uapi16_reader_free(reader); + + /* A manifest that lists its features records those, and a file + * object with a field of another one is refused for the field. The + * names of a field and of a rule are constants of the library: the + * same string every time, also once the error is freed. */ + reader = open_reader(featured); + check_recorded(reader, FEATURES(UAPI16_FEATURE_SIZE, UAPI16_FEATURE_MTIME)); + check_eq(uapi16_reader_order(reader), UAPI16_ORDER_NONE); + file = next_object(reader, "a"); + check_eq(uapi16_file_object_mtime_nsec(file, &number), 0); + check_eq(number, 7); + check_stated(file, FEATURES(UAPI16_FEATURE_SIZE, UAPI16_FEATURE_MTIME)); + file = uapi16_file_object_free(file); + r = uapi16_reader_next(reader, &file, &e); + check_eq(r, -EBADMSG); + check_eq(uapi16_error_kind(e), UAPI16_ERROR_MANIFEST); + check_record(e, 2); + check_str(uapi16_error_path(e), "b"); + field = uapi16_error_field(e); + problem = uapi16_error_problem(e); + check_str(field, "mode"); + check_str(problem, "unlistedFeature"); + check(uapi16_error_field(e) == field && uapi16_error_problem(e) == problem); + reader = uapi16_reader_free(reader); + reader = open_reader(featured); + file = next_object(reader, "a"); + file = uapi16_file_object_free(file); + check_eq(uapi16_reader_next(reader, &file, &again), -EBADMSG); + check(again && again != e); + check(uapi16_error_field(again) == field && uapi16_error_problem(again) == problem); + e = uapi16_error_free(e); + again = uapi16_error_free(again); + check_str(field, "mode"); + check_str(problem, "unlistedFeature"); + reader = uapi16_reader_free(reader); + + /* What is no manifest makes no reader: a file that holds nothing, + * one that does not start with a record separator, one whose first + * object is not the root of a manifest, and one whose root has what + * only another file object has. */ + check_broken(uapi16_reader_open(empty_file, &none, &e), &e, "empty"); + r = uapi16_reader_open(no_separator, &none, &e); + check_record(e, 0); + check_broken(r, &e, "recordSeparator"); + r = uapi16_reader_open(no_manifest, &none, &e); + check_record(e, 0); + check_broken(r, &e, "mediaType"); + r = uapi16_reader_open(root_with_size, &none, &e); + check_record(e, 0); + check_str(uapi16_error_field(e), "size"); + /* The error is about the root, which is the empty string, as for + * a root that uapi16_writer_begin() and + * uapi16_manifest_writer_add_object() refuse for the same rule. */ + check_str(uapi16_error_path(e), ""); + check_broken(r, &e, "fieldNotPermitted"); + check_eq(uapi16_reader_open(empty_file, &none, NULL), -EBADMSG); + check(!none); + + /* Where the data of a file object is: in the manifest, in a file + * next to it that the object names, in the file of its own name, + * or at a URL, which is not supported. A FIFO has none. The size + * of data that is in the manifest follows from it, and the hash of + * no data from the size 0: the reader fills them in, and they are + * none of the fields of the object. */ + reader = open_reader(data); + file = next_object(reader, "literal"); + check_eq(uapi16_file_object_data_location(file), UAPI16_DATA_LOCATION_LITERAL); + literal = uapi16_file_object_literal(file, &size); + check_same(literal, size, "hello", 5); + check_eq(uapi16_file_object_size(file, &number), 0); + check_eq(number, 5); + check_stated(file, features_none()); + file = uapi16_file_object_free(file); + file = next_object(reader, "none"); + check_eq(uapi16_file_object_sha256(file, &hash), 0); + check_hash(&hash, SHA256_OF_NOTHING); + check_stated(file, FEATURES(UAPI16_FEATURE_SIZE)); + file = uapi16_file_object_free(file); + file = next_object(reader, "other"); + check_eq(uapi16_file_object_data_location(file), UAPI16_DATA_LOCATION_EXTERNAL); + check(!uapi16_file_object_literal(file, &size)); + check_eq(size, 0); + file = uapi16_file_object_free(file); + file = next_object(reader, "own"); + check_eq(uapi16_file_object_data_location(file), UAPI16_DATA_LOCATION_EXTERNAL); + file = uapi16_file_object_free(file); + file = next_object(reader, "remote"); + check_eq(uapi16_file_object_data_location(file), UAPI16_DATA_LOCATION_UNSUPPORTED); + check(!uapi16_file_object_literal(file, &size)); + number = 77; + check_eq(uapi16_file_object_size(file, &number), -ENODATA); + check_eq(number, 77); + file = uapi16_file_object_free(file); + file = next_object(reader, "without"); + check_eq(uapi16_file_object_type(file), S_IFIFO); + check_eq(uapi16_file_object_data_location(file), UAPI16_DATA_LOCATION_NONE); + file = uapi16_file_object_free(file); + check_ends(reader); + check(!e); +} + +/* + * When a manifest and a file object may be used: not once they are + * revoked, not before the time they are valid from, and not from the time + * on that they are valid until. + */ +static void test_validity(void) { + _cleanup_(closep) int windows = + manifest_file(RS "{\"mediaType\":\"application/vnd.uapi.16.manifest\"," + "\"validSinceUSec\":1000,\"validUntilUSec\":2000}\n" + RS "{\"name\":\"a\",\"validity\":\"revoked\"}\n" + RS "{\"name\":\"b\",\"validSinceUSec\":10,\"validUntilUSec\":20}\n" + RS "{\"name\":\"c\"}\n" TRAILER); + _cleanup_(closep) int revoked = + manifest_file(RS "{\"mediaType\":\"application/vnd.uapi.16.manifest\"," + "\"validity\":\"revoked\"}\n" TRAILER); + _cleanup_(closep) int always = manifest_file(ROOT TRAILER); + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + const uapi16_file_object *root; + int r; + + /* The window of the root is that of the manifest: the reader and + * its root say the same of it. */ + reader = open_reader(windows); + root = uapi16_reader_root(reader); + /* An error about when a manifest may be used is about its root, + * which is the empty string. */ + r = uapi16_reader_check_validity(reader, 999, &e); + check_error(r, e, UAPI16_ERROR_NOT_YET_VALID, EKEYEXPIRED, "", 0); + e = uapi16_error_free(e); + r = uapi16_file_object_check_validity(root, 999, &e); + check_error(r, e, UAPI16_ERROR_NOT_YET_VALID, EKEYEXPIRED, "", 0); + e = uapi16_error_free(e); + check_eq(uapi16_reader_check_validity(reader, 0, NULL), -EKEYEXPIRED); + check_eq(uapi16_reader_check_validity(reader, 1000, &e), 0); + check_eq(uapi16_reader_check_validity(reader, 1999, &e), 0); + check_eq(uapi16_file_object_check_validity(root, 1000, &e), 0); + check_eq(uapi16_file_object_check_validity(root, 1999, &e), 0); + r = uapi16_reader_check_validity(reader, 2000, &e); + check_error(r, e, UAPI16_ERROR_EXPIRED, EKEYEXPIRED, "", 0); + e = uapi16_error_free(e); + r = uapi16_file_object_check_validity(root, UINT64_MAX, &e); + check_error(r, e, UAPI16_ERROR_EXPIRED, EKEYEXPIRED, "", 0); + e = uapi16_error_free(e); + + /* A file object that is revoked is that at any time, and the error + * is about it. */ + file = next_object(reader, "a"); + r = uapi16_file_object_check_validity(file, 0, &e); + check_error(r, e, UAPI16_ERROR_REVOKED, EKEYREVOKED, "a", 0); + e = uapi16_error_free(e); + r = uapi16_file_object_check_validity(file, UINT64_MAX, &e); + check_error(r, e, UAPI16_ERROR_REVOKED, EKEYREVOKED, "a", 0); + e = uapi16_error_free(e); + check_eq(uapi16_file_object_check_validity(file, 15, NULL), -EKEYREVOKED); + file = uapi16_file_object_free(file); + + /* One with a window of its own: the time it is valid from is in + * it, and the time it is valid until is not. */ + file = next_object(reader, "b"); + r = uapi16_file_object_check_validity(file, 9, &e); + check_error(r, e, UAPI16_ERROR_NOT_YET_VALID, EKEYEXPIRED, "b", 0); + e = uapi16_error_free(e); + check_eq(uapi16_file_object_check_validity(file, 10, &e), 0); + check_eq(uapi16_file_object_check_validity(file, 19, &e), 0); + r = uapi16_file_object_check_validity(file, 20, &e); + check_error(r, e, UAPI16_ERROR_EXPIRED, EKEYEXPIRED, "b", 0); + e = uapi16_error_free(e); + file = uapi16_file_object_free(file); + + /* One that says nothing may be used at any time: the check looks + * at the object alone, and not at the manifest it is in. */ + file = next_object(reader, "c"); + check_eq(uapi16_file_object_check_validity(file, 0, &e), 0); + check_eq(uapi16_file_object_check_validity(file, UINT64_MAX, &e), 0); + file = uapi16_file_object_free(file); + check_ends(reader); + reader = uapi16_reader_free(reader); + + /* A manifest that is revoked, and one that says nothing. */ + reader = open_reader(revoked); + r = uapi16_reader_check_validity(reader, 0, &e); + check_error(r, e, UAPI16_ERROR_REVOKED, EKEYREVOKED, "", 0); + e = uapi16_error_free(e); + check_eq(uapi16_reader_check_validity(reader, UINT64_MAX, NULL), -EKEYREVOKED); + check_eq(uapi16_file_object_check_validity(uapi16_reader_root(reader), 1500, NULL), -EKEYREVOKED); + reader = uapi16_reader_free(reader); + reader = open_reader(always); + check_eq(uapi16_reader_check_validity(reader, 0, &e), 0); + check_eq(uapi16_reader_check_validity(reader, UINT64_MAX, &e), 0); + check_misuse(uapi16_reader_check_validity(NULL, 0, &e), &e, EINVAL); + check_eq(uapi16_reader_check_validity(NULL, 0, NULL), -EINVAL); + check(!e); +} + +/* Checks that `a` and `b` are both no string, or the same string. */ +static void check_same_text(const char *a, const char *b) { + check(!a == !b); + if (a) + check_str(a, b); +} + +/* + * Checks that the file objects `a` and `b` say the same, through every + * getter a file object has: uapi16_file_object_name(), _type(), _mode(), + * _uid(), _gid(), _user_name(), _group_name(), _mtime_nsec(), _size(), + * _sha256(), _major(), _minor(), _inode_token(), _user_xattrs(), + * _user_xattr(), _read_only(), _inode_flags(), _dos_attributes(), + * _data_location(), _contents_file(), _literal(), _fs_label(), + * _fs_uuid(), _fat_serial(), _stated_feature() and _check_validity(). A + * getter that fails for one fails the same way for the other. + */ +static void check_same_object(const uapi16_file_object *a, const uapi16_file_object *b) { + static const uint64_t times[] = { 0, 15, 25, UINT64_MAX }; + uapi16_sha256_digest_t hash_a = { .bytes = { 0 } }, hash_b = { .bytes = { 0 } }; + uapi16_uuid_t uuid_a = { .bytes = { 0 } }, uuid_b = { .bytes = { 0 } }; + uint32_t small_a = 77, small_b = 77, set_a = 77, set_b = 77; + uint64_t number_a = 77, number_b = 77; + uapi16_inode_token_t token_a = 77, token_b = 77; + size_t count_a = 0, count_b = 0, size_a = 77, size_b = 77; + const void *bytes_a, *bytes_b; + int r; + + check(a && b && a != b); + check_same_text(uapi16_file_object_name(a), uapi16_file_object_name(b)); + check_eq(uapi16_file_object_type(a), uapi16_file_object_type(b)); + r = uapi16_file_object_mode(a, &small_a); + check_eq(uapi16_file_object_mode(b, &small_b), r); + check_eq(small_a, small_b); + r = uapi16_file_object_uid(a, &small_a); + check_eq(uapi16_file_object_uid(b, &small_b), r); + check_eq(small_a, small_b); + r = uapi16_file_object_gid(a, &small_a); + check_eq(uapi16_file_object_gid(b, &small_b), r); + check_eq(small_a, small_b); + check_same_text(uapi16_file_object_user_name(a), uapi16_file_object_user_name(b)); + check_same_text(uapi16_file_object_group_name(a), uapi16_file_object_group_name(b)); + r = uapi16_file_object_mtime_nsec(a, &number_a); + check_eq(uapi16_file_object_mtime_nsec(b, &number_b), r); + check_eq(number_a, number_b); + r = uapi16_file_object_size(a, &number_a); + check_eq(uapi16_file_object_size(b, &number_b), r); + check_eq(number_a, number_b); + r = uapi16_file_object_sha256(a, &hash_a); + check_eq(uapi16_file_object_sha256(b, &hash_b), r); + check_eq(memcmp(&hash_a, &hash_b, sizeof(hash_a)), 0); + r = uapi16_file_object_major(a, &number_a); + check_eq(uapi16_file_object_major(b, &number_b), r); + check_eq(number_a, number_b); + r = uapi16_file_object_minor(a, &number_a); + check_eq(uapi16_file_object_minor(b, &number_b), r); + check_eq(number_a, number_b); + r = uapi16_file_object_inode_token(a, &token_a); + check_eq(uapi16_file_object_inode_token(b, &token_b), r); + check_eq(token_a, token_b); + r = uapi16_file_object_user_xattrs(a, &count_a); + check_eq(uapi16_file_object_user_xattrs(b, &count_b), r); + check_eq(count_a, count_b); + /* One more than there are: both have none of that number. */ + for (size_t i = 0; i <= count_a; i++) { + const char *name_a = NULL, *name_b = NULL; + + bytes_a = bytes_b = NULL; + size_a = size_b = 77; + r = uapi16_file_object_user_xattr(a, i, &name_a, &bytes_a, &size_a); + check_eq(r, i < count_a ? 0 : -EINVAL); + check_eq(uapi16_file_object_user_xattr(b, i, &name_b, &bytes_b, &size_b), r); + check_same_text(name_a, name_b); + check_eq(size_a, size_b); + if (r == 0) + check_same(bytes_a, size_a, bytes_b, size_b); + } + check_eq(uapi16_file_object_read_only(a), uapi16_file_object_read_only(b)); + r = uapi16_file_object_inode_flags(a, &small_a, &set_a); + check_eq(uapi16_file_object_inode_flags(b, &small_b, &set_b), r); + check_eq(small_a, small_b); + check_eq(set_a, set_b); + r = uapi16_file_object_dos_attributes(a, &small_a, &set_a); + check_eq(uapi16_file_object_dos_attributes(b, &small_b, &set_b), r); + check_eq(small_a, small_b); + check_eq(set_a, set_b); + check_eq(uapi16_file_object_data_location(a), uapi16_file_object_data_location(b)); + { + const char *file_a = NULL, *file_b = NULL; + + number_a = number_b = 77; + r = uapi16_file_object_contents_file(a, &file_a, &number_a); + check_eq(uapi16_file_object_contents_file(b, &file_b, &number_b), r); + check_same_text(file_a, file_b); + check_eq(number_a, number_b); + } + size_a = size_b = 77; + bytes_a = uapi16_file_object_literal(a, &size_a); + bytes_b = uapi16_file_object_literal(b, &size_b); + check(!bytes_a == !bytes_b); + check_eq(size_a, size_b); + if (bytes_a) + check_same(bytes_a, size_a, bytes_b, size_b); + check_same_text(uapi16_file_object_fs_label(a), uapi16_file_object_fs_label(b)); + r = uapi16_file_object_fs_uuid(a, &uuid_a); + check_eq(uapi16_file_object_fs_uuid(b, &uuid_b), r); + check_eq(memcmp(&uuid_a, &uuid_b, sizeof(uuid_a)), 0); + small_a = small_b = 77; + r = uapi16_file_object_fat_serial(a, &small_a); + check_eq(uapi16_file_object_fat_serial(b, &small_b), r); + check_eq(small_a, small_b); + check_same_stated(a, b); + for (size_t i = 0; i < ELEMENTSOF(times); i++) { + r = uapi16_file_object_check_validity(a, times[i], NULL); + check_eq(uapi16_file_object_check_validity(b, times[i], NULL), r); + } +} + +/* + * Checks that the file object `o` has the name `name`, is a regular file, + * and has nothing else: every getter of a field says that there is none, + * each in its way. + */ +static void check_bare_object(const uapi16_file_object *o, const char *name) { + uapi16_sha256_digest_t hash = { .bytes = { 0 } }; + uapi16_uuid_t uuid = { .bytes = { 0 } }; + uint32_t small = 77, stated = 77, set = 77; + uint64_t number = 77; + uapi16_inode_token_t token = 77; + size_t count = 77, size = 77; + const char *xattr = NULL, *contents_file = NULL; + const void *value = NULL; + + check_str(uapi16_file_object_name(o), name); + check_eq(uapi16_file_object_type(o), S_IFREG); + check_eq(uapi16_file_object_mode(o, &small), -ENODATA); + check_eq(uapi16_file_object_uid(o, &small), -ENODATA); + check_eq(uapi16_file_object_gid(o, &small), -ENODATA); + check(!uapi16_file_object_user_name(o)); + check(!uapi16_file_object_group_name(o)); + check_eq(uapi16_file_object_mtime_nsec(o, &number), -ENODATA); + check_eq(uapi16_file_object_size(o, &number), -ENODATA); + check_eq(uapi16_file_object_sha256(o, &hash), -ENODATA); + check_eq(uapi16_file_object_major(o, &number), -ENODATA); + check_eq(uapi16_file_object_minor(o, &number), -ENODATA); + check_eq(uapi16_file_object_inode_token(o, &token), -ENODATA); + check_eq(uapi16_file_object_user_xattrs(o, &count), -ENODATA); + check_eq(uapi16_file_object_user_xattr(o, 0, &xattr, &value, &size), -EINVAL); + check_eq(uapi16_file_object_read_only(o), UAPI16_READ_ONLY_UNSTATED); + check_eq(uapi16_file_object_inode_flags(o, &stated, &set), 0); + check_eq(stated, 0); + check_eq(set, 0); + stated = set = 77; + check_eq(uapi16_file_object_dos_attributes(o, &stated, &set), 0); + check_eq(stated, 0); + check_eq(set, 0); + /* The data of a regular file that says nothing is in the file of + * its own name, so it names no other file. */ + check_eq(uapi16_file_object_data_location(o), UAPI16_DATA_LOCATION_EXTERNAL); + check_eq(uapi16_file_object_contents_file(o, &contents_file, &number), -ENODATA); + check(!uapi16_file_object_literal(o, &size)); + check_eq(size, 0); + check(!uapi16_file_object_fs_label(o)); + check_eq(uapi16_file_object_fs_uuid(o, &uuid), -ENODATA); + check_eq(uapi16_file_object_fat_serial(o, &small), -ENODATA); + check_stated(o, features_none()); + check_eq(uapi16_file_object_check_validity(o, 0, NULL), 0); + check_eq(uapi16_file_object_check_validity(o, UINT64_MAX, NULL), 0); + /* None of the getters that failed stored anything. */ + check_eq(small, 77); + check_eq(number, 77); + check_eq(token, 77); + check_eq(count, 77); + check(!xattr && !contents_file && !value && hash.bytes[0] == 0 && uuid.bytes[0] == 0); +} + +/* How many records fill_writer() writes at most, and how many it writes + * at least before a pipe or a small file system is full. */ +#define FILL_RECORDS_MAX 100000 +#define FILL_RECORDS_MIN 1 + +/* How many bytes there are in the file `fd`, or to read from it if it is + * a pipe. */ +static off_t bytes_in(int fd) { + struct stat st; + int n; + + check_eq(fstat(fd, &st), 0); + if (S_ISREG(st.st_mode)) + return st.st_size; + check_eq(ioctl(fd, FIONREAD, &n), 0); + return n; +} + +/* Writes file objects with names of `size` bytes to `w` until a write + * fails, which it does with the errno `full`: an error of the kind + * UAPI16_ERROR_IO that is about no file. The writer takes nothing more + * after that: the object that failed, another one and the end are all + * UAPI16_ERROR_ENDED, and none of them writes anything to what `look` + * shows, the file of the writer or the other end of its pipe. Stores in + * `written` how many bytes are there, and returns how many records were + * written. */ +static int fill_writer(uapi16_writer *w, size_t size, int full, int look, off_t *written) { + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *other = make_object("zz"); + _cleanup_(uapi16_signature_freep) uapi16_signature *signature = NULL; + char name[NAME_OF_OBJECT_MAX + 1]; + + check(size >= 8 && size <= NAME_OF_OBJECT_MAX); + check_eq(uapi16_signature_new("mechanism", &signature), 0); + for (int i = 0; i < FILL_RECORDS_MAX; i++) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = NULL; + uint64_t record = 0; + int r; + + memset(name, 'x', size); + name[size] = 0; + check_eq(snprintf(name, 8, "%07d", i), 7); + name[7] = 'x'; + o = make_object(name); + r = uapi16_writer_file(w, o, &e); + if (r == 0) + continue; + /* The error names the record that was not written, the + * root being record 0. */ + check_error(r, e, UAPI16_ERROR_IO, full, NULL, CHECK_RECORD); + check_eq(uapi16_error_record(e, &record), 0); + check_eq(record, (uint64_t) i + 1); + e = uapi16_error_free(e); + *written = bytes_in(look); + check_ended(uapi16_writer_file(w, o, &e), &e); + check_ended(uapi16_writer_file(w, other, &e), &e); + check_ended(uapi16_writer_signature(w, signature, &e), &e); + check_ended(uapi16_writer_finish(w, &e), &e); + check_eq(bytes_in(look), *written); + return i; + } + check(false); + return -1; +} + +/* Reads what a writer wrote to `fd` before a write of it failed. It is no + * manifest: a reader does not come to its end. */ +static void check_no_manifest(int fd) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + int r = uapi16_reader_open(fd, &reader, &e); + + while (r >= 0) { + r = uapi16_reader_next(reader, &o, &e); + check(r != UAPI16_READ_END && r != UAPI16_READ_SIGNATURES); + } + check(e); +} + +/* A writer of records on a pipe that does not block, which is full after + * a while: with records that fit the pipe, and with one that is larger + * than the pipe, of which a part is written. */ +static void failed_write_to_a_pipe(size_t size, int least) { + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_writer_freep) uapi16_writer *w = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(closep) int out = -1, in = -1; + off_t written; + int ends[2]; + + check_eq(pipe2(ends, O_CLOEXEC | O_NONBLOCK), 0); + in = ends[0]; + out = ends[1]; + check(fcntl(out, F_SETPIPE_SZ, sysconf(_SC_PAGESIZE)) > 0); + check_eq(uapi16_writer_begin(o, out, NULL, &w, &e), 0); + check(fill_writer(w, size, EAGAIN, in, &written) >= least); + w = uapi16_writer_free(w); + check_eq(bytes_in(in), written); + check_eq(close(out), 0); + out = -1; + check_eq(fcntl(in, F_SETFL, 0), 0); + check_no_manifest(in); +} + +/* What the child of test_failed_writes() does: in a user and a mount + * namespace of its own it mounts a small tmpfs at `target`, and writes + * records to a file on it until the file system is full. */ +static int failed_write_in_namespace(const char *target, uid_t uid, gid_t gid) { + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_writer_freep) uapi16_writer *w = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(closep) int dir = -1, out = -1; + off_t written; + + if (!own_namespace(uid, gid) || mount("none", target, "tmpfs", 0, "size=64k") < 0) + return EXIT_SKIPPED; + dir = open(target, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + check(dir >= 0); + out = openat(dir, "manifest", O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644); + check(out >= 0); + check_eq(uapi16_writer_begin(o, out, NULL, &w, &e), 0); + check(fill_writer(w, NAME_OF_OBJECT_MAX, ENOSPC, out, &written) >= FILL_RECORDS_MIN); + w = uapi16_writer_free(w); + check_eq(bytes_in(out), written); + check_eq(lseek(out, 0, SEEK_SET), 0); + check_no_manifest(out); + return EXIT_SUCCESS; +} + +/* A write of a writer of records that fails ends the writer: on a pipe + * that does not block and is full, and on a file system that is full. The + * call that failed says why, and every call after it fails as after + * uapi16_writer_finish(), so that nothing passes for a manifest that lacks + * a record. */ +static void test_failed_writes(void) { + _cleanup_(closep) int target = make_dir(tmp_fd, "failed-writes"); + char path[PATH_MAX]; + int status; + pid_t pid; + + failed_write_to_a_pipe(16, FILL_RECORDS_MIN); + failed_write_to_a_pipe(NAME_OF_OBJECT_MAX, 0); + + check((size_t) snprintf(path, sizeof(path), "%s/failed-writes", tmp_path) < sizeof(path)); + fflush(NULL); + pid = fork(); + check(pid >= 0); + if (pid == 0) { + int code = failed_write_in_namespace(path, getuid(), getgid()); + + fflush(NULL); + _exit(code); + } + check_eq(waitpid(pid, &status, 0), pid); + check(WIFEXITED(status)); + if (WEXITSTATUS(status) == EXIT_SKIPPED) + fprintf(stderr, "skipping a file system that is full: no user namespace that can mount here\n"); + else + check_eq(WEXITSTATUS(status), EXIT_SUCCESS); +} + +/* + * uapi16_reader_next() and uapi16_reader_next_signature() take an object + * as getline() takes its buffer: where `ret` points to an object of the + * caller, that object is cleared and filled again, and nothing of what it + * held is left. So one object serves a whole manifest, and after every + * read it says what a new object of that record says. + */ +static void test_refilled_objects(void) { + static const uapi16_uuid_t uuid = { .bytes = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6 } }; + static const char binary[] = { 0, (char) 0xfe, 'x' }; + static const char *const names[] = { "a", "b", "c", "d", "e", "f", "g", "h" }; + _cleanup_(closep) int written = scratch_file(), reused = -1, fresh = -1; + _cleanup_(closep) int bare = + manifest_file(ROOT FILE_OBJECT("bare") SIGNATURE_OBJECT("pkcs7") TRAILER); + _cleanup_(closep) int windows = + manifest_file(ROOT RS "{\"name\":\"a\",\"validSinceUSec\":10,\"validUntilUSec\":20}\n" + RS "{\"name\":\"b\",\"validity\":\"revoked\"}\n" + RS "{\"name\":\"c\"}\n" TRAILER); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_writer_freep) uapi16_writer *w = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reusing = NULL, *renewing = NULL, *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *a = make_hello("a"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *c = make_object("c"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *link = make_object("e"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *g = make_object("g"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *plain = make_object("b"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *kept = NULL, *full = make_object("full"); + _cleanup_(uapi16_signature_freep) uapi16_signature *openpgp = NULL, *pkcs7 = NULL; + _cleanup_(uapi16_signature_freep) uapi16_signature *signature = NULL, *mine = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + _cleanup_(freep) char *text = NULL; + const uapi16_file_object *first = NULL; + const uapi16_signature *first_signature = NULL; + uapi16_sha256_digest_t hash; + uint32_t stated = 77, set = 77; + uint64_t number = 77; + uapi16_inode_token_t token = 77; + size_t text_size, count = 77, size = 77; + const char *name = NULL; + const void *bytes = NULL; + int r; + + /* A manifest of file objects with fields, each of them before one + * with none: a regular file with all a regular file can have, a + * device, a symbolic link and a file whose data is elsewhere. Two + * signature objects follow, one with a key and data and one + * without. */ + check_eq(set_features(o, FEATURES_OF_TREES), 0); + check_eq(uapi16_file_object_set_mode(a, 0444), 0); + check_eq(uapi16_file_object_set_uid(a, 1), 0); + check_eq(uapi16_file_object_set_gid(a, 2), 0); + check_eq(uapi16_file_object_set_user_name(a, "user"), 0); + check_eq(uapi16_file_object_set_group_name(a, "group"), 0); + check_eq(uapi16_file_object_set_mtime_nsec(a, 3), 0); + check_eq(uapi16_file_object_set_inode_token(a, 7), 0); + check_eq(uapi16_file_object_add_user_xattr(a, "text", "a value", 7), 0); + check_eq(uapi16_file_object_add_user_xattr(a, "binary", binary, sizeof(binary)), 0); + check_eq(uapi16_file_object_set_read_only(a, UAPI16_READ_ONLY_YES), 0); + check_eq(uapi16_file_object_set_inode_flags(a, INODE_FLAGS, NODUMP_FL | IMMUTABLE_FL), 0); + check_eq(uapi16_file_object_set_dos_attributes(a, DOS_ATTRIBUTES, DOS_HIDDEN), 0); + check_eq(uapi16_file_object_set_target(a, "hello", 5), 0); + check_eq(uapi16_file_object_set_type(c, S_IFCHR), 0); + check_eq(uapi16_file_object_set_mode(c, 0600), 0); + check_eq(uapi16_file_object_set_major(c, 4), 0); + check_eq(uapi16_file_object_set_minor(c, 5), 0); + check_eq(uapi16_file_object_set_type(link, S_IFLNK), 0); + check_eq(uapi16_file_object_set_target(link, "to/somewhere", 12), 0); + check_eq(uapi16_file_object_set_size(g, 10), 0); + check_eq(uapi16_file_object_set_contents_file(g, "blobs/1", &e), 0); + check_eq(uapi16_signature_new("openpgp", &openpgp), 0); + check_eq(uapi16_signature_set_key(openpgp, "key", 3), 0); + check_eq(uapi16_signature_set_data(openpgp, binary, sizeof(binary)), 0); + check_eq(uapi16_signature_new("pkcs7", &pkcs7), 0); + + w = begin_records(o, written); + for (size_t i = 0; i < ELEMENTSOF(names); i++) { + const uapi16_file_object *with_fields[] = { a, c, link, g }; + + if (i % 2 == 0) { + check_eq(uapi16_writer_file(w, with_fields[i / 2], &e), 0); + continue; + } + check_eq(uapi16_file_object_set_name(plain, names[i], &e), 0); + check_eq(uapi16_writer_file(w, plain, &e), 0); + } + check_eq(uapi16_writer_signature(w, openpgp, &e), 0); + check_eq(uapi16_writer_signature(w, pkcs7, &e), 0); + check_eq(uapi16_writer_finish(w, &e), 0); + w = uapi16_writer_free(w); + text = read_all(written, &text_size); + check_eq(strlen(text), text_size); + reused = manifest_file(text); + fresh = manifest_file(text); + + /* One object for the whole manifest, next to a new one for every + * record: the object is the same one after every file object, and + * says what the new one says, whatever the record before it had. + * Every getter is called on it before it is filled again, so what + * it handed out, strings and bytes, is gone with what it held. */ + reusing = open_reader(reused); + renewing = open_reader(fresh); + for (size_t i = 0;; i++) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *renewed = NULL; + + r = uapi16_reader_next(reusing, &kept, &e); + check_eq(uapi16_reader_next(renewing, &renewed, &e), r); + if (r != UAPI16_READ_FILE) { + check_eq(i, ELEMENTSOF(names)); + break; + } + check(i < ELEMENTSOF(names)); + if (i == 0) + first = kept; + check(kept && kept == first); + check_str(uapi16_file_object_name(kept), names[i]); + check_same_object(kept, renewed); + if (i == 0) { + /* The first one is not what the writer was given + * for nothing: it has its fields. */ + check_str(uapi16_file_object_user_name(kept), "user"); + check_eq(uapi16_file_object_user_xattrs(kept, &count), 0); + check_eq(count, 2); + check_eq(uapi16_file_object_read_only(kept), UAPI16_READ_ONLY_YES); + bytes = uapi16_file_object_literal(kept, &size); + check_same(bytes, size, "hello", 5); + } + if (i % 2 == 0) + continue; + /* A record without a field leaves the object without it. + * This manifest records every feature of a tree, so the + * reader fills in what the features say of a file that + * says nothing: it is not read-only, it has no extended + * attributes, and none of its flags is set. */ + check_eq(uapi16_file_object_type(kept), S_IFREG); + check_eq(uapi16_file_object_mode(kept, &stated), -ENODATA); + check(!uapi16_file_object_user_name(kept)); + check(!uapi16_file_object_group_name(kept)); + check_eq(uapi16_file_object_size(kept, &number), -ENODATA); + check_eq(uapi16_file_object_sha256(kept, &hash), -ENODATA); + check_eq(uapi16_file_object_major(kept, &number), -ENODATA); + check_eq(uapi16_file_object_inode_token(kept, &token), -ENODATA); + check_eq(number, 77); + check_eq(token, 77); + check_eq(uapi16_file_object_user_xattrs(kept, &count), 0); + check_eq(count, 0); + check_eq(uapi16_file_object_user_xattr(kept, 0, &name, &bytes, &size), -EINVAL); + check_eq(uapi16_file_object_read_only(kept), UAPI16_READ_ONLY_NO); + check_eq(uapi16_file_object_inode_flags(kept, &stated, &set), 0); + check_eq(stated, INODE_FLAGS); + check_eq(set, 0); + check_eq(uapi16_file_object_dos_attributes(kept, &stated, &set), 0); + check_eq(stated, DOS_ATTRIBUTES); + check_eq(set, 0); + stated = 77; + check_eq(uapi16_file_object_data_location(kept), UAPI16_DATA_LOCATION_EXTERNAL); + check(!uapi16_file_object_literal(kept, &size)); + check_eq(size, 0); + check_stated(kept, features_none()); + } + check_eq(r, UAPI16_READ_SIGNATURES); + check(kept == first); + + /* The same for the signature objects: one object for both, which + * has the key and the data of the first, and neither once it holds + * the second. */ + check_eq(uapi16_reader_next_signature(reusing, &signature, &e), UAPI16_READ_SIGNATURE); + first_signature = signature; + check_str(uapi16_signature_mechanism(signature), "openpgp"); + bytes = uapi16_signature_key(signature, &size); + check_same(bytes, size, "key", 3); + bytes = uapi16_signature_data(signature, &size); + check_same(bytes, size, binary, sizeof(binary)); + check_eq(uapi16_reader_next_signature(reusing, &signature, &e), UAPI16_READ_SIGNATURE); + check(signature == first_signature); + check_str(uapi16_signature_mechanism(signature), "pkcs7"); + size = 77; + check(!uapi16_signature_key(signature, &size)); + check_eq(size, 0); + size = 77; + check(!uapi16_signature_data(signature, &size)); + check_eq(size, 0); + check_eq(uapi16_reader_next_signature(reusing, &signature, &e), UAPI16_READ_END); + check(signature == first_signature); + check_str(uapi16_signature_mechanism(signature), "pkcs7"); + + /* An object the caller made itself is one to fill as well. This + * one has every field a setter sets, and every string and all the + * bytes it hands out were asked for. Filled from a record that has + * a name and nothing else, in a manifest that records the default + * features, it has the name of the record and nothing else. */ + unhex(SHA256_OF_HELLO, &hash); + check_eq(uapi16_file_object_set_type(full, S_IFCHR), 0); + check_eq(uapi16_file_object_set_mode(full, 0444), 0); + check_eq(uapi16_file_object_set_uid(full, 1), 0); + check_eq(uapi16_file_object_set_gid(full, 2), 0); + check_eq(uapi16_file_object_set_user_name(full, "user"), 0); + check_eq(uapi16_file_object_set_group_name(full, "group"), 0); + check_eq(uapi16_file_object_set_mtime_nsec(full, 3), 0); + check_eq(uapi16_file_object_set_size(full, 6), 0); + check_eq(uapi16_file_object_set_sha256(full, &hash), 0); + check_eq(uapi16_file_object_set_major(full, 4), 0); + check_eq(uapi16_file_object_set_minor(full, 5), 0); + check_eq(uapi16_file_object_set_inode_token(full, 6), 0); + check_eq(uapi16_file_object_add_user_xattr(full, "text", "a value", 7), 0); + check_eq(uapi16_file_object_add_user_xattr(full, "binary", binary, sizeof(binary)), 0); + check_eq(uapi16_file_object_set_read_only(full, UAPI16_READ_ONLY_YES), 0); + check_eq(uapi16_file_object_set_inode_flags(full, INODE_FLAGS, NODUMP_FL), 0); + check_eq(uapi16_file_object_set_dos_attributes(full, DOS_ATTRIBUTES, DOS_HIDDEN), 0); + check_eq(uapi16_file_object_set_target(full, "target", 6), 0); + check_eq(uapi16_file_object_set_fs_label(full, "label"), 0); + check_eq(uapi16_file_object_set_fs_uuid(full, &uuid), 0); + check_eq(uapi16_file_object_set_fat_serial(full, 7), 0); + check_str(uapi16_file_object_name(full), "full"); + check_str(uapi16_file_object_user_name(full), "user"); + check_str(uapi16_file_object_group_name(full), "group"); + check_str(uapi16_file_object_fs_label(full), "label"); + check_eq(uapi16_file_object_user_xattrs(full, &count), 0); + check_eq(count, 2); + for (size_t i = 0; i < count; i++) { + check_eq(uapi16_file_object_user_xattr(full, i, &name, &bytes, &size), 0); + check(name && bytes && size > 0); + } + bytes = uapi16_file_object_literal(full, &size); + check_same(bytes, size, "target", 6); + check_eq(uapi16_file_object_sha256(full, &hash), 0); + check(uapi16_file_object_has_stated_feature(full, UAPI16_FEATURE_SHA256)); + first = full; + reader = open_reader(bare); + check_eq(uapi16_reader_next(reader, &full, &e), UAPI16_READ_FILE); + check(full == first); + check_bare_object(full, "bare"); + + /* A signature object of the caller with a key and data, filled + * from a record that has a mechanism alone. */ + check_eq(uapi16_signature_new("openpgp", &mine), 0); + check_eq(uapi16_signature_set_key(mine, "mine", 4), 0); + check_eq(uapi16_signature_set_data(mine, binary, sizeof(binary)), 0); + check_str(uapi16_signature_mechanism(mine), "openpgp"); + check(uapi16_signature_key(mine, &size)); + check(uapi16_signature_data(mine, &size)); + first_signature = mine; + check_eq(uapi16_reader_next(reader, &full, &e), UAPI16_READ_SIGNATURES); + check_eq(uapi16_reader_next_signature(reader, &mine, &e), UAPI16_READ_SIGNATURE); + check(mine == first_signature); + check_str(uapi16_signature_mechanism(mine), "pkcs7"); + size = 77; + check(!uapi16_signature_key(mine, &size)); + check_eq(size, 0); + size = 77; + check(!uapi16_signature_data(mine, &size)); + check_eq(size, 0); + check_eq(uapi16_reader_next_signature(reader, &mine, &e), UAPI16_READ_END); + reader = uapi16_reader_free(reader); + + /* When a file object may be used is a field no getter reads: it + * shows in the check of it. A window is gone once the object holds + * a record that is revoked, and both are once it holds one that + * says nothing. */ + reader = open_reader(windows); + check_eq(uapi16_reader_next(reader, &full, &e), UAPI16_READ_FILE); + check(full == first); + check_eq(uapi16_file_object_check_validity(full, 5, NULL), -EKEYEXPIRED); + check_eq(uapi16_file_object_check_validity(full, 15, NULL), 0); + check_eq(uapi16_file_object_check_validity(full, 25, NULL), -EKEYEXPIRED); + check_eq(uapi16_reader_next(reader, &full, &e), UAPI16_READ_FILE); + check(full == first); + check_eq(uapi16_file_object_check_validity(full, 5, NULL), -EKEYREVOKED); + check_eq(uapi16_file_object_check_validity(full, 15, NULL), -EKEYREVOKED); + check_eq(uapi16_reader_next(reader, &full, &e), UAPI16_READ_FILE); + check(full == first); + check_bare_object(full, "c"); + check_eq(uapi16_file_object_check_validity(full, 5, NULL), 0); + check_eq(uapi16_file_object_check_validity(full, 15, NULL), 0); + check_eq(uapi16_file_object_check_validity(full, 25, NULL), 0); + check_eq(uapi16_reader_next(reader, &full, &e), UAPI16_READ_END); + check(full == first); + check(!e); +} + +/* + * The object a read is given stays the caller's, whatever the read + * returns. A read that reads no object leaves `*ret` exactly as it was, the + * pointer and what the object holds: at the end of the file objects, at the + * trailer, and where it fails. A NULL there stays NULL. A caller that + * wants to keep an object sets its pointer to NULL before the next read, + * and has two objects then. + */ +static void test_kept_objects(void) { + _cleanup_(closep) int signed_fd = manifest_file( + ROOT FILE_OBJECT("a") FILE_OBJECT("b") SIGNATURE_OBJECT("openpgp") TRAILER); + _cleanup_(closep) int plain = manifest_file(ROOT FILE_OBJECT("a") TRAILER); + _cleanup_(closep) int out_of_order = manifest_file(ROOT FILE_OBJECT("b") FILE_OBJECT("a") TRAILER); + _cleanup_(closep) int late = + manifest_file(ROOT FILE_OBJECT("a") SIGNATURE_OBJECT("openpgp") FILE_OBJECT("b") TRAILER); + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = NULL, *kept = NULL, *none = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *own = make_hello("own"); + _cleanup_(uapi16_signature_freep) uapi16_signature *signature = NULL, *no_signature = NULL; + _cleanup_(uapi16_signature_freep) uapi16_signature *mine = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL, *held = NULL; + const uapi16_file_object *was; + const uapi16_signature *was_signature, *was_mine; + const void *bytes; + uint64_t number = 0; + size_t size = 0; + int r; + + check_eq(uapi16_file_object_new("a//b", &none, &held), -EINVAL); + check(held && !none); + check_eq(uapi16_signature_new("mine", &mine), 0); + check_eq(uapi16_signature_set_key(mine, "key", 3), 0); + + /* A caller keeps an object by setting its pointer to NULL before + * the next read: the read makes a new one, and both are there, + * each with its record. */ + reader = open_reader(signed_fd); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(file), "a"); + kept = file; + file = NULL; + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + check(file && file != kept); + check_str(uapi16_file_object_name(kept), "a"); + check_str(uapi16_file_object_name(file), "b"); + was = file; + + /* A read that is not valid leaves the object as it is: one whose + * `reterr` points to something, and one for a signature object + * while file objects come, which leaves the signature object of + * the caller as it is. */ + check_eq(uapi16_reader_next(reader, &file, &held), -EINVAL); + check(file == was); + check_str(uapi16_file_object_name(file), "b"); + was_signature = mine; + check_misuse(uapi16_reader_next_signature(reader, &mine, &e), &e, EINVAL); + check(mine == was_signature); + check_str(uapi16_signature_mechanism(mine), "mine"); + bytes = uapi16_signature_key(mine, &size); + check_same(bytes, size, "key", 3); + check_misuse(uapi16_reader_next_signature(reader, &no_signature, &e), &e, EINVAL); + check(!no_signature); + + /* The end of the file objects leaves it, and stores nothing where + * there is no object. */ + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_SIGNATURES); + check(file == was); + check_str(uapi16_file_object_name(file), "b"); + + /* A signature object, and the trailer, which leaves the signature + * object and the file object as they are, whichever of the two + * reads it and however often. */ + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_SIGNATURE); + check_str(uapi16_signature_mechanism(signature), "openpgp"); + was_signature = signature; + check_eq(uapi16_reader_next_signature(reader, &signature, &held), -EINVAL); + check(signature == was_signature); + check_str(uapi16_signature_mechanism(signature), "openpgp"); + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_END); + check(signature == was_signature); + check_str(uapi16_signature_mechanism(signature), "openpgp"); + check_eq(uapi16_reader_next_signature(reader, &no_signature, &e), UAPI16_READ_END); + check(!no_signature); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_END); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_END); + check(file == was); + check_str(uapi16_file_object_name(file), "b"); + check_eq(uapi16_reader_next(reader, &none, &e), UAPI16_READ_END); + check(!none); + check_str(uapi16_file_object_name(kept), "a"); + reader = uapi16_reader_free(reader); + + /* At the end of a manifest without signature objects a caller + * that asks for one is told that the manifest ended, and its + * signature object stays as it is. So does an object the caller + * made itself and that the end of the manifest is read into. */ + reader = open_reader(plain); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + check(file == was); + check_str(uapi16_file_object_name(file), "a"); + was = own; + check_eq(uapi16_reader_next(reader, &own, &e), UAPI16_READ_END); + check(own == was); + check_str(uapi16_file_object_name(own), "own"); + check_eq(uapi16_file_object_size(own, &number), 0); + check_eq(number, 5); + was_mine = mine; + check_eq(uapi16_reader_next_signature(reader, &mine, &e), UAPI16_READ_END); + check(mine == was_mine); + check_str(uapi16_signature_mechanism(mine), "mine"); + check_eq(uapi16_reader_next_signature(reader, &no_signature, &e), UAPI16_READ_END); + check(!no_signature && !e); + reader = uapi16_reader_free(reader); + + /* A read that fails for the manifest leaves the object with the + * record it had, and so does every read after it, which the reader + * takes no more of. */ + reader = open_reader(out_of_order); + was = file; + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + check(file == was); + check_str(uapi16_file_object_name(file), "b"); + r = uapi16_reader_next(reader, &file, &e); + check_refused(r, &e, "outOfOrder", "a", NULL); + check(file == was); + check_str(uapi16_file_object_name(file), "b"); + check_ended(uapi16_reader_next(reader, &file, &e), &e); + check(file == was); + check_str(uapi16_file_object_name(file), "b"); + check_eq(uapi16_reader_next(reader, &none, NULL), -ESTALE); + check(!none); + check_ended(uapi16_reader_next_signature(reader, &mine, &e), &e); + check_str(uapi16_signature_mechanism(mine), "mine"); + reader = uapi16_reader_free(reader); + + /* The same for a signature object: a file object after it fails + * the read, which leaves the one of the caller as it was. */ + reader = open_reader(late); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_SIGNATURES); + check_eq(uapi16_reader_next_signature(reader, &signature, &e), UAPI16_READ_SIGNATURE); + check(signature == was_signature); + r = uapi16_reader_next_signature(reader, &signature, &e); + check_refused(r, &e, "fileAfterSignature", NULL, NULL); + check(signature == was_signature); + check_str(uapi16_signature_mechanism(signature), "openpgp"); + check_ended(uapi16_reader_next_signature(reader, &signature, &e), &e); + check(signature == was_signature); + check_eq(uapi16_reader_next_signature(reader, &no_signature, NULL), -ESTALE); + check(!no_signature); + + /* Every object here is the caller's still, and is freed once: the + * two file objects of the first manifest, the one the caller made, + * and the signature objects. */ + check(file == was && file != kept); + file = uapi16_file_object_free(file); + kept = uapi16_file_object_free(kept); + check(!file && !kept && !e); +} + +/* + * uapi16_error_record() stores the number of the record of a manifest that + * an error is about, counting from 0, which is the record of the root. For + * a reader that is the record that failed, and for a writer of records the + * number the record it refused would have had. An error about no record + * has none, as no error of a manifest writer has, and the call fails with + * -ENODATA. It needs an error and a place, and stores nothing where it + * fails. + */ +static void test_error_records(void) { + _cleanup_(closep) int written = scratch_file(), listed = scratch_file(); + _cleanup_(closep) int no_manifest = + manifest_file(RS "{\"mediaType\":\"application/x-other\"}\n" TRAILER); + _cleanup_(closep) int unordered = manifest_file(ROOT_WITHOUT_ORDER TRAILER); + _cleanup_(closep) int out_of_order = + manifest_file(ROOT FILE_OBJECT("b") FILE_OBJECT("c") FILE_OBJECT("a") TRAILER); + _cleanup_(closep) int cut = manifest_file(ROOT FILE_OBJECT("a")); + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL, *none = NULL; + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_writer_freep) uapi16_writer *records = NULL; + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL; + _cleanup_(uapi16_manifest_report_freep) uapi16_manifest_report *report = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = NULL, *no_object = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *root = make_object(""); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *given = make_object("b"); + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + uint64_t record = 77; + int r; + + /* The root is record 0: an error about a first record that is no + * root of a manifest, and one about a root that declares no order + * where a caller relies on one. */ + check_eq(uapi16_reader_open(no_manifest, &none, &e), -EBADMSG); + check(e && !none); + check_eq(uapi16_error_record(e, &record), 0); + check_eq(record, 0); + e = uapi16_error_free(e); + reader = open_reader(unordered); + check_eq(uapi16_reader_require_order(reader, UAPI16_ORDER_CODEPOINT, &e), -EBADMSG); + record = 77; + check_eq(uapi16_error_record(e, &record), 0); + check_eq(record, 0); + e = uapi16_error_free(e); + reader = uapi16_reader_free(reader); + + /* A later record: the third file object of a manifest, which is + * out of order, is record 3. A call without a place for the number + * is not valid. */ + reader = open_reader(out_of_order); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + check_eq(uapi16_reader_next(reader, &file, &e), -EBADMSG); + check_str(uapi16_error_problem(e), "outOfOrder"); + record = 77; + check_eq(uapi16_error_record(e, &record), 0); + check_eq(record, 3); + check_eq(uapi16_error_record(e, NULL), -EINVAL); + e = uapi16_error_free(e); + reader = uapi16_reader_free(reader); + + /* An error about no record has none: one about a manifest as a + * whole, which ends without its trailer, and one about a call. The + * number of before is where it was. */ + reader = open_reader(cut); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_FILE); + check_eq(uapi16_reader_next(reader, &file, &e), -EBADMSG); + check_str(uapi16_error_problem(e), "noTrailer"); + record = 77; + check_eq(uapi16_error_record(e, &record), -ENODATA); + check_eq(record, 77); + check_eq(uapi16_error_record(e, NULL), -EINVAL); + e = uapi16_error_free(e); + check_eq(uapi16_file_object_new("a//b", &no_object, &e), -EINVAL); + check(e && !no_object); + check_eq(uapi16_error_record(e, &record), -ENODATA); + check_eq(record, 77); + e = uapi16_error_free(e); + + /* A writer of records names the record it refuses by the number + * the record would have had. For the root that is 0, whichever rule + * refuses it: a field that only another file object has, and a + * field of a feature the manifest does not record. Nothing is + * written, and no writer is made. */ + check_eq(set_features(o, FEATURES(UAPI16_FEATURE_MODE)), 0); + check_eq(uapi16_file_object_set_size(root, 1), 0); + r = uapi16_writer_begin(o, written, root, &records, &e); + check_record(e, 0); + check_refused(r, &e, "fieldNotPermitted", "", "size"); + check_eq(retain_features(root, features_none()), 0); + check_eq(uapi16_file_object_set_fs_label(root, "label"), 0); + r = uapi16_writer_begin(o, written, root, &records, &e); + check_record(e, 0); + check_refused(r, &e, "unlistedFeature", "", "fsLabel"); + check(!records); + check_eq(size_of(written), 0); + + /* A file object that is refused would have been the next record, + * whichever rule refuses it: one that is out of order, and one + * with a field that only the root has. The writer is as it was, so + * the next one that is refused has that number as well. */ + check_eq(retain_features(root, features_none()), 0); + check_eq(uapi16_writer_begin(o, written, root, &records, &e), 0); + check_eq(uapi16_writer_file(records, given, &e), 0); + check_eq(uapi16_file_object_set_name(given, "a", &e), 0); + r = uapi16_writer_file(records, given, &e); + check_record(e, 2); + check_refused(r, &e, "outOfOrder", "a", NULL); + check_eq(uapi16_file_object_set_name(given, "c", &e), 0); + check_eq(uapi16_file_object_set_fs_label(given, "label"), 0); + r = uapi16_writer_file(records, given, &e); + check_record(e, 2); + check_refused(r, &e, "fieldNotPermitted", "c", "fsLabel"); + check_eq(retain_features(given, features_none()), 0); + check_eq(uapi16_writer_file(records, given, &e), 0); + check_eq(uapi16_file_object_set_fs_label(given, "label"), 0); + r = uapi16_writer_file(records, given, &e); + check_record(e, 3); + check_refused(r, &e, "fieldNotPermitted", "c", "fsLabel"); + check_eq(uapi16_writer_finish(records, &e), 0); + + /* An error of a manifest writer is about no record: it has no + * records before it finishes, and writes them in its own order. + * That holds for an object it refuses, for a root it refuses, and + * for what it finds when it finishes. */ + check_eq(set_features(o, FEATURES(DEFAULT_FEATURES)), 0); + check_eq(uapi16_manifest_writer_open(o, listed, &w, &e), 0); + r = uapi16_manifest_writer_add_object(w, given, &e); + check_eq(uapi16_error_record(e, &record), -ENODATA); + check_refused(r, &e, "fieldNotPermitted", "c", "fsLabel"); + check_eq(retain_features(root, features_none()), 0); + check_eq(uapi16_file_object_set_size(root, 1), 0); + r = uapi16_manifest_writer_add_object(w, root, &e); + check_eq(uapi16_error_record(e, &record), -ENODATA); + check_refused(r, &e, "fieldNotPermitted", "", "size"); + check_eq(retain_features(given, features_none()), 0); + check_eq(uapi16_file_object_set_size(given, 1), 0); + check_eq(uapi16_manifest_writer_add_object(w, given, &e), 0); + check_eq(uapi16_file_object_set_size(given, 2), 0); + check_eq(uapi16_manifest_writer_add_object(w, given, &e), 0); + r = uapi16_manifest_writer_finish(w, &report, &e); + check_error(r, e, UAPI16_ERROR_DUPLICATE, EEXIST, "c", 0); + e = uapi16_error_free(e); + check_eq(record, 77); + + /* No error is none to ask. */ + check_eq(uapi16_error_record(NULL, &record), -EINVAL); + check_eq(uapi16_error_record(NULL, NULL), -EINVAL); + check_eq(record, 77); +} + +/* + * A signature object: its mechanism, what identifies its key and its + * data, each of which it has, has as no bytes at all, or does not have. A + * writer of records writes it, and a reader hands it out as it was. + */ +static void test_signatures(void) { + static const char binary[] = { 0, 'k', (char) 0xff, 0 }; + _cleanup_(closep) int written = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_writer_freep) uapi16_writer *w = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_signature_freep) uapi16_signature *s = NULL, *none = NULL, *got = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + char key[] = "a key", mechanism[] = "openpgp"; + const char *name; + const void *bytes; + size_t size = 77; + + /* A new one has its mechanism, of which it keeps a copy, and + * neither a key nor data. */ + check_eq(uapi16_signature_new(mechanism, &s), 0); + check(s); + mechanism[0] = 'O'; + name = uapi16_signature_mechanism(s); + check_str(name, "openpgp"); + check(!uapi16_signature_key(s, &size)); + check_eq(size, 0); + size = 77; + check(!uapi16_signature_data(s, &size)); + check_eq(size, 0); + check(!uapi16_signature_key(s, NULL)); + check(!uapi16_signature_data(s, NULL)); + + /* It needs a mechanism, and a place to go to. */ + check_eq(uapi16_signature_new(NULL, &none), -EINVAL); + check_eq(uapi16_signature_new("openpgp", NULL), -EINVAL); + check(!none); + + /* The key and the data are bytes, of which it keeps a copy. */ + check_eq(uapi16_signature_set_key(s, key, strlen(key)), 0); + key[0] = 'A'; + bytes = uapi16_signature_key(s, &size); + check_same(bytes, size, "a key", 5); + check(uapi16_signature_key(s, NULL)); + check(!uapi16_signature_data(s, &size)); + check_eq(uapi16_signature_set_data(s, binary, sizeof(binary)), 0); + bytes = uapi16_signature_data(s, &size); + check_same(bytes, size, binary, sizeof(binary)); + check(uapi16_signature_data(s, NULL)); + bytes = uapi16_signature_key(s, &size); + check_same(bytes, size, "a key", 5); + check_str(name, "openpgp"); + + /* Bytes of a size of 0 are a key, and data, that is there and + * empty. The pointer is not looked at. */ + check_eq(uapi16_signature_set_key(s, unreadable(), 0), 0); + size = 77; + check(uapi16_signature_key(s, &size)); + check_eq(size, 0); + check_eq(uapi16_signature_set_data(s, "", 0), 0); + size = 77; + check(uapi16_signature_data(s, &size)); + check_eq(size, 0); + + /* NULL takes them away, whatever the size. */ + check_eq(uapi16_signature_set_key(s, NULL, 0), 0); + size = 77; + check(!uapi16_signature_key(s, &size)); + check_eq(size, 0); + check_eq(uapi16_signature_set_data(s, NULL, 5), 0); + size = 77; + check(!uapi16_signature_data(s, &size)); + check_eq(size, 0); + + /* No object is none to set anything on, and has nothing. */ + check_eq(uapi16_signature_set_key(NULL, "k", 1), -EINVAL); + check_eq(uapi16_signature_set_data(NULL, "d", 1), -EINVAL); + check(!uapi16_signature_mechanism(NULL)); + size = 77; + check(!uapi16_signature_key(NULL, &size)); + check_eq(size, 0); + size = 77; + check(!uapi16_signature_data(NULL, &size)); + check_eq(size, 0); + check(!uapi16_signature_key(NULL, NULL)); + check(!uapi16_signature_data(NULL, NULL)); + + /* Written and read back: one with a key and data, one with a key + * that is empty and no data, and one with neither. */ + w = begin_records(o, written); + check_eq(uapi16_signature_set_key(s, binary, sizeof(binary)), 0); + check_eq(uapi16_signature_set_data(s, "data", 4), 0); + check_eq(uapi16_writer_signature(w, s, &e), 0); + check_eq(uapi16_signature_set_key(s, "", 0), 0); + check_eq(uapi16_signature_set_data(s, NULL, 0), 0); + check_eq(uapi16_writer_signature(w, s, &e), 0); + s = uapi16_signature_free(s); + check(!s); + check_eq(uapi16_signature_new("pkcs7", &s), 0); + check_eq(uapi16_writer_signature(w, s, &e), 0); + check_eq(uapi16_writer_finish(w, &e), 0); + w = uapi16_writer_free(w); + + reader = open_reader(written); + check_eq(uapi16_reader_next(reader, &file, &e), UAPI16_READ_SIGNATURES); + check_eq(uapi16_reader_next_signature(reader, &got, &e), UAPI16_READ_SIGNATURE); + check_str(uapi16_signature_mechanism(got), "openpgp"); + bytes = uapi16_signature_key(got, &size); + check_same(bytes, size, binary, sizeof(binary)); + bytes = uapi16_signature_data(got, &size); + check_same(bytes, size, "data", 4); + got = uapi16_signature_free(got); + check_eq(uapi16_reader_next_signature(reader, &got, &e), UAPI16_READ_SIGNATURE); + check_str(uapi16_signature_mechanism(got), "openpgp"); + size = 77; + check(uapi16_signature_key(got, &size)); + check_eq(size, 0); + check(!uapi16_signature_data(got, &size)); + got = uapi16_signature_free(got); + check_eq(uapi16_reader_next_signature(reader, &got, &e), UAPI16_READ_SIGNATURE); + check_str(uapi16_signature_mechanism(got), "pkcs7"); + check(!uapi16_signature_key(got, &size)); + check(!uapi16_signature_data(got, &size)); + /* What a reader handed out is the caller's, to change and to + * free. */ + check_eq(uapi16_signature_set_key(got, "mine", 4), 0); + bytes = uapi16_signature_key(got, &size); + check_same(bytes, size, "mine", 4); + got = uapi16_signature_free(got); + check_eq(uapi16_reader_next_signature(reader, &got, &e), UAPI16_READ_END); + check(!e); + + /* Freeing returns NULL, and takes NULL. */ + check(!uapi16_signature_free(NULL)); +} + +/* The SHA-256 hash of data that comes in pieces. */ +static void test_sha256(void) { + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *s = uapi16_sha256_new(); + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *abc = uapi16_sha256_new(); + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *blocks = uapi16_sha256_new(); + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *million = uapi16_sha256_new(); + static const char two_blocks[] = TWO_BLOCKS; + uapi16_sha256_digest_t hash, again; + char thousand[1000]; + + check(s && abc && blocks && million); + + /* The hash of no data, which takes no pointer. */ + check_eq(uapi16_sha256_update(s, NULL, 0), 0); + check_eq(uapi16_sha256_update(s, unreadable(), 0), 0); + check_eq(uapi16_sha256_finish(s, &hash), 0); + check_hash(&hash, SHA256_OF_NOTHING); + + /* A computation that is finished takes nothing more, and gives its + * hash once. Nothing is stored for a call that fails. */ + memset(&again, 0, sizeof(again)); + check_eq(uapi16_sha256_finish(s, &again), -ESTALE); + check_eq(uapi16_sha256_update(s, "abc", 3), -ESTALE); + check_eq(uapi16_sha256_update(s, NULL, 0), -ESTALE); + check_eq(again.bytes[0], 0); + /* A call that is not valid fails for that still. */ + check_eq(uapi16_sha256_update(s, NULL, 3), -EINVAL); + check_eq(uapi16_sha256_finish(s, NULL), -EINVAL); + + /* "abc" in one piece, and with data that is missing in between, + * or of a size that no data has, which is refused and not taken. */ + check_eq(uapi16_sha256_update(abc, "ab", 2), 0); + check_eq(uapi16_sha256_update(abc, NULL, 1), -EINVAL); + check_eq(uapi16_sha256_update(abc, "c", (size_t) SSIZE_MAX + 1), -EINVAL); + check_eq(uapi16_sha256_update(abc, "c", SIZE_MAX), -EINVAL); + check_eq(uapi16_sha256_finish(abc, NULL), -EINVAL); + check_eq(uapi16_sha256_update(abc, "c", 1), 0); + check_eq(uapi16_sha256_finish(abc, &hash), 0); + check_hash(&hash, SHA256_OF_ABC); + + /* Two blocks of data in pieces of every size from one byte on. */ + for (size_t done = 0, piece = 1; done < strlen(two_blocks); done += piece, piece++) { + if (piece > strlen(two_blocks) - done) + piece = strlen(two_blocks) - done; + check_eq(uapi16_sha256_update(blocks, two_blocks + done, piece), 0); + } + check_eq(uapi16_sha256_finish(blocks, &hash), 0); + check_hash(&hash, SHA256_OF_TWO_BLOCKS); + + /* A million bytes, a thousand at a time. */ + memset(thousand, 'a', sizeof(thousand)); + for (int i = 0; i < 1000; i++) + check_eq(uapi16_sha256_update(million, thousand, sizeof(thousand)), 0); + check_eq(uapi16_sha256_finish(million, &hash), 0); + check_hash(&hash, SHA256_OF_A_MILLION_A); + + /* No computation is none to give data to. */ + check_eq(uapi16_sha256_update(NULL, "abc", 3), -EINVAL); + check_eq(uapi16_sha256_finish(NULL, &hash), -EINVAL); + check_hash(&hash, SHA256_OF_A_MILLION_A); + + /* Freeing returns NULL, and takes NULL. */ + s = uapi16_sha256_free(s); + check(!s); + check(!uapi16_sha256_free(NULL)); +} + +/* + * A check holds the data of a file object against the size and the hash + * the object gives, as the data passes. It has what it needs of its + * object, which can go before the data comes. + */ +static void test_data_checks(void) { + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = make_hello("data"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *sized = make_object("sized"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *hashed = make_object("hashed"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *plain = make_object("plain"); + _cleanup_(uapi16_data_check_freep) uapi16_data_check *c = NULL, *none = NULL; + _cleanup_(uapi16_data_check_freep) uapi16_data_check *wrong = NULL, *little = NULL; + _cleanup_(uapi16_data_check_freep) uapi16_data_check *unfinished = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + uapi16_sha256_digest_t hash; + uint64_t size = 77; + int r; + + /* A check needs an object, and a place to go to. */ + check_eq(uapi16_data_check_new(NULL, &none), -EINVAL); + check_eq(uapi16_data_check_new(o, NULL), -EINVAL); + check(!none); + + /* Three checks of one object, which is changed and freed before + * any data comes. */ + check_eq(uapi16_data_check_new(o, &c), 0); + check_eq(uapi16_data_check_new(o, &wrong), 0); + check_eq(uapi16_data_check_new(o, &little), 0); + check(c && wrong && little); + check_eq(uapi16_file_object_set_size(o, 99), 0); + check_eq(uapi16_file_object_set_name(o, "changed", NULL), 0); + o = uapi16_file_object_free(o); + + /* Data that matches, in pieces, some of them empty. More data than + * the object says is refused, and none of it is taken. */ + check_eq(uapi16_data_check_update(c, "hel", 3, &e), 0); + check_eq(uapi16_data_check_update(c, NULL, 0, &e), 0); + check_eq(uapi16_data_check_update(c, unreadable(), 0, &e), 0); + r = uapi16_data_check_update(c, "lo!", 3, &e); + check_error(r, e, UAPI16_ERROR_SIZE_MISMATCH, EBADMSG, "data", 0); + e = uapi16_error_free(e); + check_eq(uapi16_data_check_update(c, "lo!", 3, NULL), -EBADMSG); + check_misuse(uapi16_data_check_update(c, NULL, 2, &e), &e, EINVAL); + check_misuse(uapi16_data_check_update(NULL, "lo", 2, &e), &e, EINVAL); + check_misuse(uapi16_data_check_finish(NULL, &size, &e), &e, EINVAL); + check_eq(uapi16_data_check_update(c, "lo", 2, &e), 0); + check_eq(uapi16_data_check_finish(c, &size, &e), 0); + check_eq(size, 5); + + /* A check that is finished takes nothing more. */ + size = 77; + check_ended(uapi16_data_check_finish(c, &size, &e), &e); + check_ended(uapi16_data_check_update(c, "x", 1, &e), &e); + check_eq(uapi16_data_check_finish(c, NULL, NULL), -ESTALE); + check_eq(uapi16_data_check_update(c, NULL, 0, NULL), -ESTALE); + check_eq(size, 77); + /* A call that is not valid fails for that still. */ + check_misuse(uapi16_data_check_update(c, NULL, 1, &e), &e, EINVAL); + + /* Data of the size the object says and of another hash, which + * shows when the check finishes. The check is finished then, as + * one that succeeded is. */ + check_eq(uapi16_data_check_update(wrong, "hallo", 5, &e), 0); + r = uapi16_data_check_finish(wrong, &size, &e); + check_error(r, e, UAPI16_ERROR_HASH_MISMATCH, EBADMSG, "data", 0); + e = uapi16_error_free(e); + check_eq(size, 77); + check_ended(uapi16_data_check_finish(wrong, &size, &e), &e); + check_ended(uapi16_data_check_update(wrong, "x", 1, &e), &e); + + /* Less data than the object says, which shows when the check + * finishes as well. */ + check_eq(uapi16_data_check_update(little, "hell", 4, &e), 0); + r = uapi16_data_check_finish(little, NULL, &e); + check_error(r, e, UAPI16_ERROR_SIZE_MISMATCH, EBADMSG, "data", 0); + e = uapi16_error_free(e); + check_eq(uapi16_data_check_finish(little, NULL, NULL), -ESTALE); + + /* An object that gives a size alone, one that gives a hash alone, + * and one that gives neither, which any data matches. No place + * for the size is fine. */ + check_eq(uapi16_file_object_set_size(sized, 3), 0); + check_eq(uapi16_data_check_new(sized, &unfinished), 0); + check_eq(uapi16_data_check_update(unfinished, "any", 3, &e), 0); + check_eq(uapi16_data_check_finish(unfinished, NULL, &e), 0); + unfinished = uapi16_data_check_free(unfinished); + check(!unfinished); + unhex(SHA256_OF_ABC, &hash); + check_eq(uapi16_file_object_set_sha256(hashed, &hash), 0); + check_eq(uapi16_data_check_new(hashed, &unfinished), 0); + check_eq(uapi16_data_check_update(unfinished, "abc", 3, &e), 0); + check_eq(uapi16_data_check_finish(unfinished, &size, &e), 0); + check_eq(size, 3); + unfinished = uapi16_data_check_free(unfinished); + check_eq(uapi16_data_check_new(hashed, &unfinished), 0); + check_eq(uapi16_data_check_update(unfinished, "abcd", 4, &e), 0); + r = uapi16_data_check_finish(unfinished, &size, &e); + check_error(r, e, UAPI16_ERROR_HASH_MISMATCH, EBADMSG, "hashed", 0); + e = uapi16_error_free(e); + unfinished = uapi16_data_check_free(unfinished); + check_eq(uapi16_data_check_new(plain, &unfinished), 0); + check_eq(uapi16_data_check_update(unfinished, "whatever", 8, &e), 0); + check_eq(uapi16_data_check_finish(unfinished, &size, &e), 0); + check_eq(size, 8); + unfinished = uapi16_data_check_free(unfinished); + + /* A check that is freed before it finished. */ + check_eq(uapi16_data_check_new(sized, &unfinished), 0); + check_eq(uapi16_data_check_update(unfinished, "an", 2, &e), 0); + check(!e); + + /* Freeing returns NULL, and takes NULL. */ + check(!uapi16_data_check_free(NULL)); +} + +/* The directory the files of a manifest are taken from: a descriptor of + * it, which may be one that only names it, and how its names are looked + * up. */ +static void test_directories(void) { + static const int no_descriptors[] = { -1, AT_FDCWD, INT_MIN }; + static const uint64_t no_flags[] = { UINT64_C(1) << 1, UINT64_C(1) << 63, UINT64_MAX }; + _cleanup_(closep) int dir = make_dir(tmp_fd, "directory"); + _cleanup_(closep) int path = openat(tmp_fd, "directory", O_PATH | O_DIRECTORY | O_CLOEXEC); + _cleanup_(uapi16_directory_freep) uapi16_directory *d = NULL, *following = NULL, *named = NULL; + _cleanup_(uapi16_directory_freep) uapi16_directory *none = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL; + + check(path >= 0); + check_eq(uapi16_directory_new(dir, UAPI16_DIRECTORY_NONE, &d, &e), 0); + check(d && !e); + check_eq(uapi16_directory_new(dir, UAPI16_DIRECTORY_FOLLOW_SYMLINKS, &following, &e), 0); + check(following); + check_eq(uapi16_directory_new(path, UAPI16_DIRECTORY_NONE, &named, NULL), 0); + check(named); + + /* It needs a descriptor, flags that are some, and a place to go + * to. */ + for (size_t i = 0; i < ELEMENTSOF(no_descriptors); i++) + check_misuse(uapi16_directory_new(no_descriptors[i], UAPI16_DIRECTORY_NONE, &none, &e), &e, EBADF); + for (size_t i = 0; i < ELEMENTSOF(no_flags); i++) + check_misuse(uapi16_directory_new(dir, no_flags[i], &none, &e), &e, EINVAL); + check_misuse(uapi16_directory_new(dir, UAPI16_DIRECTORY_NONE, NULL, &e), &e, EINVAL); + check_eq(uapi16_directory_new(-1, UAPI16_DIRECTORY_NONE, &none, NULL), -EBADF); + check_eq(uapi16_directory_new(dir, UINT64_C(1) << 1, &none, NULL), -EINVAL); + check_eq(uapi16_directory_new(dir, UAPI16_DIRECTORY_NONE, NULL, NULL), -EINVAL); + check(!none); + + /* Freeing returns NULL, and takes NULL. */ + d = uapi16_directory_free(d); + check(!d); + check(!uapi16_directory_free(NULL)); +} + +/* What qsort() compares two names with. */ +static int compare_names(const void *a, const void *b) { + return uapi16_name_compare(*(const char *const *) a, *(const char *const *) b); +} + +/* Checks that the options `o` record the features of `expected` and no + * other: a manifest that a writer of records writes for them records + * them. */ +static void check_options(const uapi16_manifest_options *o, uapi16_features_t expected) { + _cleanup_(closep) int fd = scratch_file(); + _cleanup_(uapi16_writer_freep) uapi16_writer *w = begin_records(o, fd); + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + + check_eq(uapi16_writer_finish(w, NULL), 0); + reader = open_reader(fd); + check_recorded(reader, expected); +} + +/* A set that UAPI16_FEATURES_SET() makes outside a function, and one + * without features: each is a constant of the compiler. */ +static const uapi16_features_t sizes_and_times = + UAPI16_FEATURES_SET(UAPI16_FEATURE_MTIME, UAPI16_FEATURE_SIZE, UAPI16_FEATURE_NONE, + UAPI16_FEATURE_MTIME, UAPI16_FEATURE_SIZE); +static const uapi16_features_t no_features_at_all = UAPI16_FEATURES_EMPTY; + +/* How many words the largest set has. */ +#define SET_WORDS_MAX (UAPI16_FEATURES_SIZE_MAX / sizeof(uint64_t) - 1) + +/* A set of features in pages of its own, which are laid out so that a + * call that does what it must not dies. A guarded set has a page behind + * it that can be neither read nor written, so that a call that goes past + * the set dies: its size and its words end where the page before that one + * ends. */ +struct guarded { + void *map; + size_t length; + /* The size of the set, and after it its words. */ + uint64_t *set; + size_t words; +}; + +/* A guarded set of `words` words without features, with the size a header + * with as many words gives it. */ +static struct guarded guarded_set(size_t words) { + size_t page = (size_t) sysconf(_SC_PAGESIZE); + size_t size = sizeof(uint64_t) * (1 + words); + size_t before = (size + page - 1) / page * page; + struct guarded g = { .length = before + page, .words = words }; + + g.map = mmap(NULL, g.length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + check(g.map != MAP_FAILED); + check_eq(mprotect((char *) g.map + before, page, PROT_NONE), 0); + g.set = (uint64_t *) (void *) ((char *) g.map + before - size); + g.set[0] = size; + return g; +} + +/* A set of `words` words without features whose size can't be written: + * the size ends a page that is read only from here on, and the words are + * on the page after it. So a call that writes the size of the set dies, + * also one that writes the size the set has. */ +static struct guarded set_with_fixed_size(size_t words) { + size_t page = (size_t) sysconf(_SC_PAGESIZE); + struct guarded g = { .length = 2 * page, .words = words }; + + check(sizeof(uint64_t) * words <= page); + g.map = mmap(NULL, g.length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + check(g.map != MAP_FAILED); + g.set = (uint64_t *) (void *) ((char *) g.map + page - sizeof(uint64_t)); + g.set[0] = sizeof(uint64_t) * (1 + words); + check_eq(mprotect(g.map, page, PROT_READ), 0); + return g; +} + +static void unguard(struct guarded *g) { + if (g->map) + check_eq(munmap(g->map, g->length), 0); +} + +/* The guarded set as a call takes one. */ +static uapi16_features_t *guarded_features(const struct guarded *g) { + return (uapi16_features_t *) (void *) g->set; +} + +/* Makes the first two words of the guarded set `first` and `second`, and + * every word after them `rest`. */ +static void guarded_fill(const struct guarded *g, uint64_t first, uint64_t second, uint64_t rest) { + check(g->words >= 2); + g->set[1] = first; + g->set[2] = second; + for (size_t i = 2; i < g->words; i++) + g->set[1 + i] = rest; +} + +/* Checks that the guarded set has the size it was made with, `first` and + * `second` as its first two words, and `rest` in every word after them. */ +static void check_guarded(const struct guarded *g, uint64_t first, uint64_t second, uint64_t rest) { + check(g->words >= 2); + check_eq(g->set[0], sizeof(uint64_t) * (1 + g->words)); + check_eq(g->set[1], first); + check_eq(g->set[2], second); + for (size_t i = 2; i < g->words; i++) + check_eq(g->set[1 + i], rest); +} + +/* Checks what the calls make of the set `none`, which is NULL or has a + * size no set has: those that return an int fail with `error`, the others + * take it for a set without features, and none changes anything. */ +static void check_no_set(uapi16_features_t *none, int error, uapi16_manifest_options *o, + uapi16_file_object *file) { + const uapi16_features_t some = FEATURES(UAPI16_FEATURE_MODE, 65); + uapi16_features_t set = some; + + check_eq(uapi16_features_add(none, UAPI16_FEATURE_MODE), -error); + check_eq(uapi16_features_remove(none, UAPI16_FEATURE_MODE), -error); + check(!uapi16_features_has(none, UAPI16_FEATURE_MODE)); + check_eq(uapi16_features_next(none, UAPI16_FEATURE_NONE), UAPI16_FEATURE_NONE); + check(!uapi16_features_equal(none, none)); + check(!uapi16_features_equal(none, &set)); + check(!uapi16_features_equal(&set, none)); + uapi16_features_union(&set, none); + uapi16_features_intersect(&set, none); + uapi16_features_subtract(&set, none); + check_same_features(set, some); + check_eq(set.size, sizeof(set)); + uapi16_features_union(none, &set); + uapi16_features_intersect(none, &set); + uapi16_features_subtract(none, &set); + check_eq(uapi16_features_default(none), -error); + check_eq(uapi16_features_known(none), -error); + check_eq(uapi16_manifest_options_set_features(o, none), -error); + check_eq(uapi16_file_object_retain_features(file, none), -error); + check_eq(uapi16_file_object_stated_features(file, none), -error); +} + +/* + * A set of features is a uapi16_features_t of the program: its size, and + * its words with a bit for each feature. The two macros make one. The + * calls for a set work on its bits by the size it carries, which the + * library never writes: a size above the largest one is too large, one + * below the first size or that is no multiple of 8 is none, and nothing + * of such a set is touched but its size. Two sets of different sizes are + * combined and compared word by word, and a word a set does not have + * counts as 0. A call that fills a set copies what fits and clears the + * rest of it. A call that takes one refuses a word past those of the + * library that is not 0, and a feature the library does not have, and + * changes nothing then. The sets with a page behind them show that no + * call goes past one, and the sets whose size is on a page that can't be + * written that no call writes a size. + */ +static void test_feature_sets(void) { + static const uint64_t no_sizes[] = { + 0, + 1, + sizeof(uint64_t), + UAPI16_FEATURES_SIZE_VER0 - sizeof(uint64_t), + UAPI16_FEATURES_SIZE_VER0 - 1, + UAPI16_FEATURES_SIZE_VER0 + 1, + UAPI16_FEATURES_SIZE_VER0 + sizeof(uint64_t) - 1, + UAPI16_FEATURES_SIZE_MAX - 1, + }; + static const uint64_t too_large[] = { + UAPI16_FEATURES_SIZE_MAX + 1, + UAPI16_FEATURES_SIZE_MAX + sizeof(uint64_t), + UINT64_C(1) << 32, + UINT64_MAX - 7, + UINT64_MAX, + }; + static const uapi16_feature_t numbers[] = { 1, 31, 32, 64, 65, 64 * UAPI16_FEATURES_WORDS }; + static const uapi16_feature_t unknown[] = { NO_FEATURE, 64, 65, 64 * UAPI16_FEATURES_WORDS }; + const uapi16_feature_t last = 64 * UAPI16_FEATURES_WORDS; + const uint64_t mode = UINT64_C(1) << (UAPI16_FEATURE_MODE - 1); + const uint64_t size = UINT64_C(1) << (UAPI16_FEATURE_SIZE - 1); + const uint64_t sha256 = UINT64_C(1) << (UAPI16_FEATURE_SHA256 - 1); + const uint64_t mtime = UINT64_C(1) << (UAPI16_FEATURE_MTIME - 1); + const uint64_t top = UINT64_C(1) << 63; + _cleanup_(closep) int fd = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *other = uapi16_manifest_options_new(); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_hello("file"); + _cleanup_(uapi16_writer_freep) uapi16_writer *records = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + /* A set of this header, one of a header with a word more, the + * largest set there is, and a size with nothing after it. */ + _cleanup_(unguard) struct guarded first = guarded_set(UAPI16_FEATURES_WORDS); + _cleanup_(unguard) struct guarded longer = guarded_set(UAPI16_FEATURES_WORDS + 1); + _cleanup_(unguard) struct guarded largest = guarded_set(SET_WORDS_MAX); + _cleanup_(unguard) struct guarded sized = guarded_set(0); + const struct guarded *const guards[] = { &first, &longer, &largest }; + /* A set of this header and a longer one, each with a size that + * can't be written. */ + _cleanup_(unguard) struct guarded fixed_first = set_with_fixed_size(UAPI16_FEATURES_WORDS); + _cleanup_(unguard) struct guarded fixed_longer = set_with_fixed_size(UAPI16_FEATURES_WORDS + 1); + const struct guarded *const fixed[] = { &fixed_first, &fixed_longer }; + uapi16_features_t defaults = FEATURES(NO_FEATURE), known = FEATURES(NO_FEATURE); + uapi16_features_t set, taken, kept; + uapi16_feature_t f; + size_t n; + + /* The type and the two macros. A feature that is given twice is in + * the set once, and UAPI16_FEATURE_NONE is passed over. */ + check_eq(sizeof(uapi16_features_t), UAPI16_FEATURES_SIZE_VER0); + check_eq(sizeof(uapi16_features_t), sizeof(uint64_t) * (1 + UAPI16_FEATURES_WORDS)); + check_eq(sizes_and_times.size, sizeof(uapi16_features_t)); + check_eq(sizes_and_times.words[0], size | mtime); + check_eq(sizes_and_times.words[1], 0); + check_eq(no_features_at_all.size, sizeof(uapi16_features_t)); + check_eq(no_features_at_all.words[0] | no_features_at_all.words[1], 0); + set = FEATURES(UAPI16_FEATURE_NONE); + check_same_features(set, no_features_at_all); + check_eq(set.size, sizeof(set)); + /* Feature f is bit (f - 1) % 64 of word (f - 1) / 64, also for a + * number that no feature has yet. A number this header has no word + * for is left out. */ + set = FEATURES(UAPI16_FEATURE_MODE, 64, 65, last, last + 1, UINT32_MAX); + check_eq(set.words[0], mode | top); + check_eq(set.words[1], mode | top); + + /* A set by its bits. UAPI16_FEATURE_NONE is no feature, and neither + * is a number the set has no room for. */ + set = features_none(); + check_eq(uapi16_features_add(&set, UAPI16_FEATURE_NONE), -EINVAL); + check_eq(uapi16_features_remove(&set, UAPI16_FEATURE_NONE), -EINVAL); + check_eq(uapi16_features_add(&set, last + 1), -EINVAL); + check_eq(uapi16_features_remove(&set, last + 1), -EINVAL); + check_eq(uapi16_features_add(&set, UINT32_MAX), -EINVAL); + check_eq(uapi16_features_remove(&set, UINT32_MAX), -EINVAL); + check_same_features(set, no_features_at_all); + for (size_t i = 0; i < ELEMENTSOF(numbers); i++) { + check(!uapi16_features_has(&set, numbers[i])); + check_eq(uapi16_features_add(&set, numbers[i]), 0); + check_eq(uapi16_features_add(&set, numbers[i]), 0); + check(uapi16_features_has(&set, numbers[i])); + } + check_eq(set.words[0], mode | (UINT64_C(1) << 30) | (UINT64_C(1) << 31) | top); + check_eq(set.words[1], mode | top); + check_eq(set.size, sizeof(set)); + check(!uapi16_features_has(&set, UAPI16_FEATURE_NONE)); + check(!uapi16_features_has(&set, last + 1)); + check(!uapi16_features_has(&set, UINT32_MAX)); + /* A walk gives the features in the order of their numbers, goes on + * from any number, whether the set has it or not, and ends past + * the last one. */ + n = 0; + for (f = uapi16_features_next(&set, UAPI16_FEATURE_NONE); f != UAPI16_FEATURE_NONE; + f = uapi16_features_next(&set, f)) { + check(n < ELEMENTSOF(numbers)); + check_eq(f, numbers[n++]); + } + check_eq(n, ELEMENTSOF(numbers)); + check_eq(uapi16_features_next(&set, 30), 31); + check_eq(uapi16_features_next(&set, 33), 64); + check_eq(uapi16_features_next(&set, 66), last); + check_eq(uapi16_features_next(&set, last), UAPI16_FEATURE_NONE); + check_eq(uapi16_features_next(&set, last + 1), UAPI16_FEATURE_NONE); + check_eq(uapi16_features_next(&set, UINT32_MAX), UAPI16_FEATURE_NONE); + check_eq(uapi16_features_next(&no_features_at_all, UAPI16_FEATURE_NONE), UAPI16_FEATURE_NONE); + for (size_t i = 0; i < ELEMENTSOF(numbers); i++) { + check_eq(uapi16_features_remove(&set, numbers[i]), 0); + check_eq(uapi16_features_remove(&set, numbers[i]), 0); + check(!uapi16_features_has(&set, numbers[i])); + } + check_same_features(set, no_features_at_all); + + /* What the library has: the default features and every feature, + * each of which has a name. */ + check_eq(uapi16_features_default(&defaults), 0); + check_same_features(defaults, FEATURES(DEFAULT_FEATURES)); + check_eq(uapi16_features_known(&known), 0); + check_same_features(known, EVERY_FEATURE); + check_eq(defaults.size, sizeof(defaults)); + check_eq(known.size, sizeof(known)); + check_eq(known.words[0], (UINT64_C(1) << LAST_FEATURE_OF_PARTITIONS) - 1); + check_eq(defaults.words[1] | known.words[1], 0); + n = 0; + for (f = uapi16_features_next(&known, UAPI16_FEATURE_NONE); f != UAPI16_FEATURE_NONE; + f = uapi16_features_next(&known, f)) { + check_eq(f, ++n); + check(uapi16_feature_name(f)); + check_eq(uapi16_feature_from_name(uapi16_feature_name(f)), f); + } + check_eq(n, LAST_FEATURE_OF_PARTITIONS); + + /* No set, and a size no set has: only the size is read, which is + * the last thing before a page that can't be. Nothing changes. */ + check_no_set(NULL, EINVAL, o, file); + for (size_t i = 0; i < ELEMENTSOF(no_sizes); i++) { + sized.set[0] = no_sizes[i]; + check_no_set(guarded_features(&sized), EINVAL, o, file); + check_eq(sized.set[0], no_sizes[i]); + } + for (size_t i = 0; i < ELEMENTSOF(too_large); i++) { + sized.set[0] = too_large[i]; + check_no_set(guarded_features(&sized), E2BIG, o, file); + check_eq(sized.set[0], too_large[i]); + } + check_eq(uapi16_manifest_options_set_features(NULL, &defaults), -EINVAL); + check_eq(uapi16_file_object_retain_features(NULL, &defaults), -EINVAL); + check_options(o, defaults); + check_stated(file, FEATURES(UAPI16_FEATURE_SIZE, UAPI16_FEATURE_SHA256)); + + /* Two sets of different sizes. A union drops what the first set + * has no room for, and no call writes the size of a set. */ + guarded_fill(&first, size, 0, 0); + guarded_fill(&longer, mode, mode | top, mode); + uapi16_features_union(guarded_features(&first), guarded_features(&longer)); + check_guarded(&first, mode | size, mode | top, 0); + check_guarded(&longer, mode, mode | top, mode); + check(!uapi16_features_equal(guarded_features(&first), guarded_features(&longer))); + check(!uapi16_features_equal(guarded_features(&longer), guarded_features(&first))); + /* The other way round the longer set keeps what only it has. */ + uapi16_features_union(guarded_features(&longer), guarded_features(&first)); + check_guarded(&longer, mode | size, mode | top, mode); + /* A word the shorter set does not have counts as 0: it takes + * nothing out of the longer one, and leaves nothing of it. */ + uapi16_features_subtract(guarded_features(&longer), guarded_features(&first)); + check_guarded(&longer, 0, 0, mode); + guarded_fill(&longer, mode | mtime, top, mode); + uapi16_features_intersect(guarded_features(&longer), guarded_features(&first)); + check_guarded(&longer, mode, top, 0); + uapi16_features_subtract(guarded_features(&first), guarded_features(&longer)); + check_guarded(&first, size, mode, 0); + uapi16_features_intersect(guarded_features(&first), guarded_features(&longer)); + check_guarded(&first, 0, 0, 0); + /* Two sets are equal that have the same features, whatever their + * sizes are. */ + guarded_fill(&first, mode | size, top, 0); + guarded_fill(&longer, mode | size, top, 0); + guarded_fill(&largest, mode | size, top, 0); + set = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_SIZE, last); + for (size_t i = 0; i < ELEMENTSOF(guards); i++) { + check(uapi16_features_equal(guarded_features(guards[i]), &set)); + check(uapi16_features_equal(&set, guarded_features(guards[i]))); + for (size_t j = 0; j < ELEMENTSOF(guards); j++) + check(uapi16_features_equal(guarded_features(guards[i]), guarded_features(guards[j]))); + } + largest.set[largest.words] = top; + check(!uapi16_features_equal(guarded_features(&largest), &set)); + check(!uapi16_features_equal(&set, guarded_features(&largest))); + check(!uapi16_features_equal(guarded_features(&first), guarded_features(&largest))); + /* The largest set has room for 64 features in each of its words, + * and a walk over it ends at its last word. */ + f = 64 * SET_WORDS_MAX; + check(uapi16_features_has(guarded_features(&largest), f)); + check_eq(uapi16_features_next(guarded_features(&largest), last), f); + check_eq(uapi16_features_next(guarded_features(&largest), f - 1), f); + check_eq(uapi16_features_next(guarded_features(&largest), f), UAPI16_FEATURE_NONE); + check_eq(uapi16_features_add(guarded_features(&largest), f + 1), -EINVAL); + check_eq(uapi16_features_remove(guarded_features(&largest), f), 0); + check_eq(uapi16_features_add(guarded_features(&largest), f - 63), 0); + check_eq(largest.set[largest.words], 1); + uapi16_features_union(&set, guarded_features(&largest)); + check_same_features(set, FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_SIZE, last)); + /* A set with itself. */ + uapi16_features_union(guarded_features(&first), guarded_features(&first)); + uapi16_features_intersect(guarded_features(&first), guarded_features(&first)); + check_guarded(&first, mode | size, top, 0); + check(uapi16_features_equal(guarded_features(&first), guarded_features(&first))); + uapi16_features_subtract(guarded_features(&first), guarded_features(&first)); + check_guarded(&first, 0, 0, 0); + + /* A set is filled by its own size: what fits is copied, the rest + * of the set is cleared, and its size is not written. */ + for (size_t i = 0; i < ELEMENTSOF(guards); i++) { + guarded_fill(guards[i], UINT64_MAX, UINT64_MAX, UINT64_MAX); + check_eq(uapi16_features_default(guarded_features(guards[i])), 0); + check_guarded(guards[i], defaults.words[0], 0, 0); + guarded_fill(guards[i], UINT64_MAX, UINT64_MAX, UINT64_MAX); + check_eq(uapi16_features_known(guarded_features(guards[i])), 0); + check_guarded(guards[i], known.words[0], 0, 0); + guarded_fill(guards[i], UINT64_MAX, UINT64_MAX, UINT64_MAX); + check_eq(uapi16_file_object_stated_features(file, guarded_features(guards[i])), 0); + check_guarded(guards[i], size | sha256, 0, 0); + } + + /* The options take the features of a set, and no others. */ + set = defaults; + check_eq(uapi16_features_add(&set, UAPI16_FEATURE_MTIME), 0); + check_eq(uapi16_manifest_options_set_features(o, &set), 0); + kept = FEATURES(DEFAULT_FEATURES, UAPI16_FEATURE_MTIME); + check_options(o, kept); + check_eq(uapi16_file_object_set_mtime_nsec(file, 1), 0); + check_eq(uapi16_file_object_set_mode(file, 0644), 0); + /* A feature the library does not have, in the words it has: the + * options and an object stay as they are. */ + for (size_t i = 0; i < ELEMENTSOF(unknown); i++) { + taken = set; + check_eq(uapi16_features_add(&taken, unknown[i]), 0); + check_eq(uapi16_manifest_options_set_features(o, &taken), -EINVAL); + check_eq(uapi16_file_object_retain_features(file, &taken), -EINVAL); + taken = FEATURES(unknown[i]); + check_eq(uapi16_manifest_options_set_features(o, &taken), -EINVAL); + check_eq(uapi16_file_object_retain_features(file, &taken), -EINVAL); + } + /* A longer set: words past those of the library that are 0 are + * fine. One that is not makes the set too large, also where a + * feature before it is one the library does not have. */ + for (size_t i = 1; i < ELEMENTSOF(guards); i++) { + const struct guarded *g = guards[i]; + + guarded_fill(g, size | mtime, 0, 0); + check_eq(uapi16_manifest_options_set_features(o, guarded_features(g)), 0); + check_options(o, FEATURES(UAPI16_FEATURE_SIZE, UAPI16_FEATURE_MTIME)); + check_eq(uapi16_manifest_options_set_features(o, &set), 0); + g->set[g->words] = top; + check_eq(uapi16_manifest_options_set_features(o, guarded_features(g)), -E2BIG); + check_eq(uapi16_file_object_retain_features(file, guarded_features(g)), -E2BIG); + g->set[1] |= top; + check_eq(uapi16_manifest_options_set_features(o, guarded_features(g)), -E2BIG); + check_eq(uapi16_file_object_retain_features(file, guarded_features(g)), -E2BIG); + g->set[g->words] = 0; + check_eq(uapi16_manifest_options_set_features(o, guarded_features(g)), -EINVAL); + check_eq(uapi16_file_object_retain_features(file, guarded_features(g)), -EINVAL); + g->set[1] = size | mtime; + g->set[2] = 1; + check_eq(uapi16_manifest_options_set_features(o, guarded_features(g)), -EINVAL); + check_eq(uapi16_file_object_retain_features(file, guarded_features(g)), -EINVAL); + check_guarded(g, size | mtime, 1, 0); + } + check_options(o, kept); + kept = FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_SIZE, UAPI16_FEATURE_SHA256, UAPI16_FEATURE_MTIME); + check_stated(file, kept); + /* The features of partitions are taken here, and no features at + * all are. */ + check_eq(uapi16_manifest_options_set_features(other, &known), 0); + check_eq(uapi16_manifest_options_set_features(other, &no_features_at_all), 0); + check_options(other, features_none()); + check_eq(uapi16_manifest_options_set_features(other, &sizes_and_times), 0); + check_options(other, FEATURES(UAPI16_FEATURE_SIZE, UAPI16_FEATURE_MTIME)); + check_eq(uapi16_manifest_options_set_features( + other, &(uapi16_features_t) UAPI16_FEATURES_SET(UAPI16_FEATURE_MODE, UAPI16_FEATURE_MODE)), + 0); + check_options(other, FEATURES(UAPI16_FEATURE_MODE)); + + /* The object keeps the fields of the features of a set. What it + * states goes back into it, and so does every feature there is. */ + check_eq(uapi16_file_object_stated_features(file, &taken), 0); + check_same_features(taken, kept); + check_eq(uapi16_file_object_retain_features(file, &taken), 0); + check_stated(file, kept); + check_eq(uapi16_file_object_retain_features(file, &known), 0); + check_stated(file, kept); + guarded_fill(&longer, mode | size | sha256 | (UINT64_C(1) << (UAPI16_FEATURE_UID - 1)), 0, 0); + check_eq(uapi16_file_object_retain_features(file, guarded_features(&longer)), 0); + check_stated(file, FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_SIZE, UAPI16_FEATURE_SHA256)); + check_eq(uapi16_file_object_retain_features(file, &sizes_and_times), 0); + check_stated(file, FEATURES(UAPI16_FEATURE_SIZE)); + check_eq(uapi16_file_object_retain_features(file, &no_features_at_all), 0); + check_stated(file, features_none()); + + /* The features of a manifest go into a set of any size, and from + * there into options and into an object. */ + check_eq(uapi16_manifest_options_set_features( + o, &(uapi16_features_t) UAPI16_FEATURES_SET(UAPI16_FEATURE_MTIME, UAPI16_FEATURE_MODE, + UAPI16_FEATURE_SIZE)), + 0); + records = begin_records(o, fd); + check_eq(uapi16_writer_finish(records, NULL), 0); + reader = open_reader(fd); + check_recorded(reader, FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_SIZE, UAPI16_FEATURE_MTIME)); + for (size_t i = 0; i < ELEMENTSOF(guards); i++) { + guarded_fill(guards[i], UINT64_MAX, UINT64_MAX, UINT64_MAX); + check_eq(uapi16_reader_features(reader, guarded_features(guards[i])), 0); + check_guarded(guards[i], mode | size | mtime, 0, 0); + } + check_ends(reader); + check_eq(uapi16_reader_features(reader, &taken), 0); + check_eq(uapi16_manifest_options_set_features(other, &taken), 0); + check_options(other, FEATURES(UAPI16_FEATURE_MODE, UAPI16_FEATURE_SIZE, UAPI16_FEATURE_MTIME)); + check_eq(uapi16_file_object_set_mode(file, 0644), 0); + check_eq(uapi16_file_object_set_uid(file, 1), 0); + check_eq(uapi16_file_object_retain_features(file, guarded_features(&longer)), 0); + check_stated(file, FEATURES(UAPI16_FEATURE_MODE)); + + /* The library reads the size of a set and never writes it, not + * even the size it read: every call that writes to a set leaves + * one alone that is on a page it can't write to. */ + for (size_t i = 0; i < ELEMENTSOF(fixed); i++) { + uapi16_features_t *s = guarded_features(fixed[i]); + + check_eq(uapi16_features_default(s), 0); + check_guarded(fixed[i], defaults.words[0], 0, 0); + check_eq(uapi16_features_known(s), 0); + check_guarded(fixed[i], known.words[0], 0, 0); + check_eq(uapi16_file_object_stated_features(file, s), 0); + check_guarded(fixed[i], mode, 0, 0); + check_eq(uapi16_reader_features(reader, s), 0); + check_guarded(fixed[i], mode | size | mtime, 0, 0); + check_eq(uapi16_features_add(s, UAPI16_FEATURE_SHA256), 0); + check_eq(uapi16_features_remove(s, UAPI16_FEATURE_MODE), 0); + check_guarded(fixed[i], size | sha256 | mtime, 0, 0); + uapi16_features_union(s, &defaults); + uapi16_features_intersect(s, &sizes_and_times); + uapi16_features_subtract(s, &taken); + check_guarded(fixed[i], 0, 0, 0); + } + + /* No reader and no object have no features to store, and neither + * stores them nowhere. */ + check_recorded(NULL, features_none()); + check_stated(NULL, features_none()); + check_eq(uapi16_reader_features(reader, NULL), -EINVAL); + check_eq(uapi16_file_object_stated_features(file, NULL), -EINVAL); + for (size_t i = 0; i < ELEMENTSOF(unknown); i++) + check(!uapi16_reader_has_feature(reader, unknown[i])); +} + +/* + * The order of names, which is that of a manifest, and the names of the + * features, which are those of the specification. + */ +static void test_names_and_features(void) { + /* The names of the files of a tree in the order of a manifest: a + * directory right before what is in it, which is not the order of + * their bytes. */ + static const char *const sorted[] = { + "a", "a/x", "a/x/y", "a/y", "a-b", "a-b/c", "a.b", "a0", + "b", "\xc3\xa9", "\xef\xbd\xa1", "\xf0\x9f\x98\x80", + }; + static const struct { + uapi16_feature_t feature; + const char *name; + } features[] = { + { UAPI16_FEATURE_MODE, "mode" }, + { UAPI16_FEATURE_UID, "uid" }, + { UAPI16_FEATURE_GID, "gid" }, + { UAPI16_FEATURE_USER_NAME, "user-name" }, + { UAPI16_FEATURE_GROUP_NAME, "group-name" }, + { UAPI16_FEATURE_SIZE, "size" }, + { UAPI16_FEATURE_SHA256, "sha256" }, + { UAPI16_FEATURE_SYMLINK, "symlink" }, + { UAPI16_FEATURE_DEVICE, "device" }, + { UAPI16_FEATURE_HARDLINK, "hardlink" }, + { UAPI16_FEATURE_MTIME, "mtime" }, + { UAPI16_FEATURE_USER_XATTR, "user-xattr" }, + { UAPI16_FEATURE_FLAG_HIDDEN, "flag-hidden" }, + { UAPI16_FEATURE_FLAG_SYSTEM, "flag-system" }, + { UAPI16_FEATURE_FLAG_ARCHIVE, "flag-archive" }, + { UAPI16_FEATURE_FLAG_APPEND_ONLY, "flag-append-only" }, + { UAPI16_FEATURE_FLAG_IMMUTABLE, "flag-immutable" }, + { UAPI16_FEATURE_FLAG_NO_ATIME, "flag-no-atime" }, + { UAPI16_FEATURE_FLAG_NO_COW, "flag-no-cow" }, + { UAPI16_FEATURE_FLAG_NO_DUMP, "flag-no-dump" }, + { UAPI16_FEATURE_READ_ONLY, "read-only" }, + { UAPI16_FEATURE_FS_UUID, "fs-uuid" }, + { UAPI16_FEATURE_FS_LABEL, "fs-label" }, + { UAPI16_FEATURE_FAT_SERIAL, "fat-serial" }, + { UAPI16_FEATURE_GPT_LABEL, "gpt-label" }, + { UAPI16_FEATURE_GPT_UUID, "gpt-uuid" }, + { UAPI16_FEATURE_GPT_TYPE_UUID, "gpt-type-uuid" }, + { UAPI16_FEATURE_GPT_DISK_UUID, "gpt-disk-uuid" }, + { UAPI16_FEATURE_GPT_FLAGS, "gpt-flags" }, + { UAPI16_FEATURE_GPT_FLAG_NO_AUTO, "gpt-flag-no-auto" }, + { UAPI16_FEATURE_GPT_FLAG_GROW_FILE_SYSTEM, "gpt-flag-grow-file-system" }, + }; + static const uapi16_feature_t no_features[] = { + UAPI16_FEATURE_NONE, NO_FEATURE, UINT32_C(1) << 31, UINT32_MAX, + }; + static const char *const no_feature_names[] = { "", "none", "MODE", "mode ", "user_xattr", "\xff" }; + _cleanup_(closep) int written = scratch_file(); + _cleanup_(uapi16_manifest_options_freep) uapi16_manifest_options *o = uapi16_manifest_options_new(); + _cleanup_(uapi16_manifest_writer_freep) uapi16_manifest_writer *w = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + const char *names[ELEMENTSOF(sorted)]; + + /* Two names compare as one of three numbers, those of the + * comparison function of qsort(). */ + check_eq(uapi16_name_compare("a/x", "a-b"), UAPI16_NAME_BEFORE); + check_eq(uapi16_name_compare("a-b", "a/x"), UAPI16_NAME_AFTER); + check_eq(uapi16_name_compare("a/x", "a/x"), UAPI16_NAME_SAME); + check(strcmp("a/x", "a-b") > 0); + for (size_t i = 0; i < ELEMENTSOF(sorted); i++) + for (size_t j = 0; j < ELEMENTSOF(sorted); j++) { + int order = uapi16_name_compare(sorted[i], sorted[j]); + + if (i < j) + check_eq(order, UAPI16_NAME_BEFORE); + else if (i > j) + check_eq(order, UAPI16_NAME_AFTER); + else + check_eq(order, UAPI16_NAME_SAME); + } + + /* No name is the empty name, which is that of the root and comes + * first. */ + check_eq(uapi16_name_compare(NULL, NULL), UAPI16_NAME_SAME); + check_eq(uapi16_name_compare(NULL, ""), UAPI16_NAME_SAME); + check_eq(uapi16_name_compare("", NULL), UAPI16_NAME_SAME); + check_eq(uapi16_name_compare(NULL, "a"), UAPI16_NAME_BEFORE); + check_eq(uapi16_name_compare("a", NULL), UAPI16_NAME_AFTER); + check_eq(uapi16_name_compare("", "a"), UAPI16_NAME_BEFORE); + + /* Strings that are not UTF-8 are no names. What is not UTF-8 in + * them is replaced by U+FFFD, and they are compared after that, so + * two different ones can be the same. */ + check_eq(uapi16_name_compare("\xff", "\xfe"), UAPI16_NAME_SAME); + check_eq(uapi16_name_compare("a\xff" "b", "a\xfe" "b"), UAPI16_NAME_SAME); + check_eq(uapi16_name_compare("\xff", "\xef\xbf\xbd"), UAPI16_NAME_SAME); + check_eq(uapi16_name_compare("\xff", "a"), UAPI16_NAME_AFTER); + check_eq(uapi16_name_compare("a", "\xff"), UAPI16_NAME_BEFORE); + + /* Names in any order are put into the order of a manifest with + * qsort(). */ + for (size_t i = 0; i < ELEMENTSOF(sorted); i++) + names[i] = sorted[(i * 7 + 3) % ELEMENTSOF(sorted)]; + qsort(names, ELEMENTSOF(names), sizeof(names[0]), compare_names); + for (size_t i = 0; i < ELEMENTSOF(sorted); i++) + check_str(names[i], sorted[i]); + + /* That is the order a writer lists file objects of these names + * in, whatever order they came in, and the order a reader takes + * them in. */ + check_eq(set_features(o, features_none()), 0); + check_eq(uapi16_manifest_writer_open(o, written, &w, NULL), 0); + for (size_t i = 0; i < ELEMENTSOF(sorted); i++) { + const char *name = sorted[(i * 5 + 1) % ELEMENTSOF(sorted)]; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_object(name); + bool directory = strcmp(name, "a") == 0 || strcmp(name, "a/x") == 0; + + /* What has files below it is a directory. */ + directory = directory || strcmp(name, "a-b") == 0; + check_eq(uapi16_file_object_set_type(file, directory ? S_IFDIR : S_IFREG), 0); + check_eq(uapi16_manifest_writer_add_object(w, file, NULL), 0); + } + check_eq(uapi16_manifest_writer_finish(w, NULL, NULL), 0); + w = uapi16_manifest_writer_free(w); + reader = open_reader(written); + check_eq(uapi16_reader_require_order(reader, UAPI16_ORDER_CODEPOINT, NULL), 0); + for (size_t i = 0; i < ELEMENTSOF(sorted); i++) { + uapi16_file_object *file = next_object(reader, sorted[i]); + + check(!uapi16_file_object_free(file)); + } + check_ends(reader); + + /* Every feature has the name the specification has for it, which + * leads back to the feature. The name is a constant of the + * library: the same string every time. The features are numbered + * from 1 without a gap, so these are all of them. */ + check_eq(ELEMENTSOF(features), LAST_FEATURE_OF_PARTITIONS); + for (size_t i = 0; i < ELEMENTSOF(features); i++) { + const char *name = uapi16_feature_name(features[i].feature); + + check_eq(features[i].feature, i + 1); + check_str(name, features[i].name); + check(uapi16_feature_name(features[i].feature) == name); + check_eq(uapi16_feature_from_name(name), features[i].feature); + check_eq(uapi16_feature_from_name(features[i].name), features[i].feature); + } + + /* A number that is no feature has no name, and a name that no + * feature has is no feature. */ + for (size_t i = 0; i < ELEMENTSOF(no_features); i++) + check(!uapi16_feature_name(no_features[i])); + for (size_t i = 0; i < ELEMENTSOF(no_feature_names); i++) + check_eq(uapi16_feature_from_name(no_feature_names[i]), UAPI16_FEATURE_NONE); + check_eq(uapi16_feature_from_name(NULL), UAPI16_FEATURE_NONE); +} + +/* + * The numbers of the enums never change, so every one of them is pinned + * here: a change of any fails this test. uapi16_feature_t is a plain enum, + * the other enums are 64 bits wide, and uapi16_name_order_t is the one + * that is signed. + */ +static void test_numbers(void) { + /* uapi16_feature_t: a number each from 1, in the order of the header. */ + check_eq(UAPI16_FEATURE_NONE, 0); + check_eq(UAPI16_FEATURE_MODE, 1); + check_eq(UAPI16_FEATURE_UID, 2); + check_eq(UAPI16_FEATURE_GID, 3); + check_eq(UAPI16_FEATURE_USER_NAME, 4); + check_eq(UAPI16_FEATURE_GROUP_NAME, 5); + check_eq(UAPI16_FEATURE_SIZE, 6); + check_eq(UAPI16_FEATURE_SHA256, 7); + check_eq(UAPI16_FEATURE_SYMLINK, 8); + check_eq(UAPI16_FEATURE_DEVICE, 9); + check_eq(UAPI16_FEATURE_HARDLINK, 10); + check_eq(UAPI16_FEATURE_MTIME, 11); + check_eq(UAPI16_FEATURE_USER_XATTR, 12); + check_eq(UAPI16_FEATURE_FLAG_HIDDEN, 13); + check_eq(UAPI16_FEATURE_FLAG_SYSTEM, 14); + check_eq(UAPI16_FEATURE_FLAG_ARCHIVE, 15); + check_eq(UAPI16_FEATURE_FLAG_APPEND_ONLY, 16); + check_eq(UAPI16_FEATURE_FLAG_IMMUTABLE, 17); + check_eq(UAPI16_FEATURE_FLAG_NO_ATIME, 18); + check_eq(UAPI16_FEATURE_FLAG_NO_COW, 19); + check_eq(UAPI16_FEATURE_FLAG_NO_DUMP, 20); + check_eq(UAPI16_FEATURE_READ_ONLY, 21); + check_eq(UAPI16_FEATURE_FS_UUID, 22); + check_eq(UAPI16_FEATURE_FS_LABEL, 23); + check_eq(UAPI16_FEATURE_FAT_SERIAL, 24); + check_eq(UAPI16_FEATURE_GPT_LABEL, 25); + check_eq(UAPI16_FEATURE_GPT_UUID, 26); + check_eq(UAPI16_FEATURE_GPT_TYPE_UUID, 27); + check_eq(UAPI16_FEATURE_GPT_DISK_UUID, 28); + check_eq(UAPI16_FEATURE_GPT_FLAGS, 29); + check_eq(UAPI16_FEATURE_GPT_FLAG_NO_AUTO, 30); + check_eq(UAPI16_FEATURE_GPT_FLAG_GROW_FILE_SYSTEM, 31); + + /* uapi16_order_t. */ + check_eq(UAPI16_ORDER_NONE, 0); + check_eq(UAPI16_ORDER_CODEPOINT, 1); + + /* uapi16_add_flag_t. */ + check_eq(UAPI16_ADD_NONE, 0); + check_eq(UAPI16_ADD_CROSS_MOUNTS, 1 << 0); + check_eq(UAPI16_ADD_GRACEFUL, 1 << 1); + + /* uapi16_error_kind_t: 1 to 21, without a gap. */ + check_eq(UAPI16_ERROR_IO, 1); + check_eq(UAPI16_ERROR_EXISTS, 2); + check_eq(UAPI16_ERROR_DUPLICATE, 3); + check_eq(UAPI16_ERROR_CHANGED, 4); + check_eq(UAPI16_ERROR_HARDLINK_MISMATCH, 5); + check_eq(UAPI16_ERROR_UNWRITABLE_NAME, 6); + check_eq(UAPI16_ERROR_NOT_DIRECTORY, 7); + check_eq(UAPI16_ERROR_UNSUPPORTED, 8); + check_eq(UAPI16_ERROR_INVALID_ARGUMENT, 9); + check_eq(UAPI16_ERROR_LOOP, 10); + check_eq(UAPI16_ERROR_MISSING_PARENT, 11); + check_eq(UAPI16_ERROR_TOO_LARGE, 12); + check_eq(UAPI16_ERROR_ENDED, 13); + check_eq(UAPI16_ERROR_MANIFEST, 14); + check_eq(UAPI16_ERROR_SOURCE_MISSING, 15); + check_eq(UAPI16_ERROR_SOURCE_NOT_REGULAR, 16); + check_eq(UAPI16_ERROR_SIZE_MISMATCH, 17); + check_eq(UAPI16_ERROR_HASH_MISMATCH, 18); + check_eq(UAPI16_ERROR_REVOKED, 19); + check_eq(UAPI16_ERROR_NOT_YET_VALID, 20); + check_eq(UAPI16_ERROR_EXPIRED, 21); + + /* uapi16_name_problem_t. */ + check_eq(UAPI16_NAME_PROBLEM_NOT_UTF8, 1); + check_eq(UAPI16_NAME_PROBLEM_EMPTY, 2); + check_eq(UAPI16_NAME_PROBLEM_TOO_LONG, 3); + check_eq(UAPI16_NAME_PROBLEM_RESERVED, 4); + check_eq(UAPI16_NAME_PROBLEM_CONTROL_CHARACTER, 5); + check_eq(UAPI16_NAME_PROBLEM_NONCHARACTER, 6); + check_eq(UAPI16_NAME_PROBLEM_EMPTY_COMPONENT, 7); + check_eq(UAPI16_NAME_PROBLEM_DOT_COMPONENT, 8); + + /* uapi16_read_only_t. */ + check_eq(UAPI16_READ_ONLY_UNSTATED, 0); + check_eq(UAPI16_READ_ONLY_NO, 1); + check_eq(UAPI16_READ_ONLY_YES, 2); + + /* uapi16_name_order_t: what a comparison function of qsort() + * returns. */ + check_eq(UAPI16_NAME_BEFORE, -1); + check_eq(UAPI16_NAME_SAME, 0); + check_eq(UAPI16_NAME_AFTER, 1); + + /* uapi16_read_t. */ + check_eq(UAPI16_READ_END, 0); + check_eq(UAPI16_READ_FILE, 1); + check_eq(UAPI16_READ_SIGNATURES, 2); + check_eq(UAPI16_READ_SIGNATURE, 3); + + /* uapi16_data_location_t. */ + check_eq(UAPI16_DATA_LOCATION_NONE, 0); + check_eq(UAPI16_DATA_LOCATION_LITERAL, 1); + check_eq(UAPI16_DATA_LOCATION_EXTERNAL, 2); + check_eq(UAPI16_DATA_LOCATION_UNSUPPORTED, 3); + + /* uapi16_directory_flag_t. */ + check_eq(UAPI16_DIRECTORY_NONE, 0); + check_eq(UAPI16_DIRECTORY_FOLLOW_SYMLINKS, 1 << 0); + + /* uapi16_feature_t is a plain enum, and the other enums are 64 bits + * wide. */ + check_eq(sizeof(uapi16_feature_t), sizeof(int)); + check_eq(sizeof(uapi16_order_t), 8); + check_eq(sizeof(uapi16_add_flag_t), 8); + check_eq(sizeof(uapi16_error_kind_t), 8); + check_eq(sizeof(uapi16_name_problem_t), 8); + check_eq(sizeof(uapi16_read_only_t), 8); + check_eq(sizeof(uapi16_name_order_t), 8); + check_eq(sizeof(uapi16_read_t), 8); + check_eq(sizeof(uapi16_data_location_t), 8); + check_eq(sizeof(uapi16_directory_flag_t), 8); + + /* One of them is signed, and the others are not. */ + check((uapi16_name_order_t) -1 < 0); + check((uapi16_order_t) -1 > 0 && (uapi16_add_flag_t) -1 > 0); + check((uapi16_error_kind_t) -1 > 0 && (uapi16_name_problem_t) -1 > 0); + check((uapi16_read_only_t) -1 > 0 && (uapi16_read_t) -1 > 0); + check((uapi16_data_location_t) -1 > 0 && (uapi16_directory_flag_t) -1 > 0); + + /* A set of flags is as wide as a flag, and has no sign. */ + check_eq(sizeof(uapi16_add_flags_t), sizeof(uapi16_add_flag_t)); + check_eq(sizeof(uapi16_directory_flags_t), sizeof(uapi16_directory_flag_t)); + check((uapi16_add_flags_t) -1 > 0 && (uapi16_directory_flags_t) -1 > 0); + + /* The token of a file is as wide and has no sign, and 0 is none. */ + check_eq(sizeof(uapi16_inode_token_t), 8); + check((uapi16_inode_token_t) -1 > 0); + check_eq(UAPI16_INODE_TOKEN_NONE, 0); + + /* A UUID is as large as its constant says, and aligned as the + * larger of its two members is. So is a hash. */ + check_eq(sizeof(uapi16_uuid_t), UAPI16_UUID_SIZE); + check_eq(_Alignof(uapi16_uuid_t), _Alignof(uint64_t)); + check_eq(sizeof(uapi16_sha256_digest_t), UAPI16_SHA256_SIZE); + check_eq(_Alignof(uapi16_sha256_digest_t), _Alignof(uint64_t)); +} + +/* The SHA-256 hashes of one zero byte, of a block of them and of 1 MiB of + * them, and of data with a hole in it: "head", 70000 zero bytes, "tail". */ +#define SHA256_OF_A_ZERO "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d" +#define SHA256_OF_A_BLOCK_OF_ZEROS "f5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b" +#define SHA256_OF_A_MEBIBYTE_OF_ZEROS "30e14955ebf1352266dc2ff8067e68104607e750abb9d3b36582b8af909fcb58" +#define SHA256_OF_SPARSE "dc88e94cb1c1c9c8d87cddab651038ca0bd748af7e7e8a7b714a26f842a9acd6" +#define HOLE 70000 +#define SPARSE_SIZE (4 + HOLE + 4) + +/* + * Zero bytes that a caller did not read, such as a hole of a sparse file, + * count as data: uapi16_sha256_update_zeros() hashes them as + * uapi16_sha256_update() hashes as many bytes that are zero, and + * uapi16_data_check_update_zeros() holds them against the size and the hash + * of a file object as uapi16_data_check_update() holds such bytes. + */ +static void test_zeros(void) { + /* None, one, and the sizes around the 64 bytes of a block of the + * hash and around the 56 its padding starts at. */ + static const uint64_t sizes[] = { 0, 1, 2, 55, 56, 57, 63, 64, 65, 119, 120, 127, 128, 129, + 4095, 4096, 4097, HOLE, 1024 * 1024 + 3 }; + static const char zeros[4096]; + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *s = NULL, *finished = uapi16_sha256_new(); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *sparse = make_object("sparse"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *sized = make_object("sized"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *plain = make_object("plain"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *no_object = NULL; + _cleanup_(uapi16_data_check_freep) uapi16_data_check *c = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL, *held = NULL; + uapi16_sha256_digest_t hash, expected; + uint64_t size = 77; + int r; + + /* Known hashes of zero bytes alone: one, a block, and 1 MiB in + * pieces of many sizes. No zero bytes are no data. */ + s = uapi16_sha256_new(); + check_eq(uapi16_sha256_update_zeros(s, 0), 0); + check_eq(uapi16_sha256_finish(s, &hash), 0); + check_hash(&hash, SHA256_OF_NOTHING); + s = uapi16_sha256_free(s); + s = uapi16_sha256_new(); + check_eq(uapi16_sha256_update_zeros(s, 1), 0); + check_eq(uapi16_sha256_finish(s, &hash), 0); + check_hash(&hash, SHA256_OF_A_ZERO); + s = uapi16_sha256_free(s); + s = uapi16_sha256_new(); + check_eq(uapi16_sha256_update_zeros(s, 64), 0); + check_eq(uapi16_sha256_finish(s, &hash), 0); + check_hash(&hash, SHA256_OF_A_BLOCK_OF_ZEROS); + s = uapi16_sha256_free(s); + s = uapi16_sha256_new(); + for (uint64_t done = 0, piece = 1; done < 1024 * 1024; done += piece, piece = piece * 3 + 1) { + if (piece > 1024 * 1024 - done) + piece = 1024 * 1024 - done; + check_eq(uapi16_sha256_update_zeros(s, piece), 0); + } + check_eq(uapi16_sha256_finish(s, &hash), 0); + check_hash(&hash, SHA256_OF_A_MEBIBYTE_OF_ZEROS); + s = uapi16_sha256_free(s); + + /* Zero bytes between other data, for every size: the hash is the + * one of the same bytes through uapi16_sha256_update(). */ + for (size_t i = 0; i < ELEMENTSOF(sizes); i++) { + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *skipped = uapi16_sha256_new(); + _cleanup_(uapi16_sha256_freep) uapi16_sha256 *read = uapi16_sha256_new(); + + check_eq(uapi16_sha256_update(skipped, "head", 4), 0); + check_eq(uapi16_sha256_update_zeros(skipped, sizes[i]), 0); + check_eq(uapi16_sha256_update(skipped, "tail", 4), 0); + check_eq(uapi16_sha256_finish(skipped, &hash), 0); + check_eq(uapi16_sha256_update(read, "head", 4), 0); + for (uint64_t left = sizes[i]; left > 0;) { + size_t piece = left < sizeof(zeros) ? (size_t) left : sizeof(zeros); + + check_eq(uapi16_sha256_update(read, zeros, piece), 0); + left -= piece; + } + check_eq(uapi16_sha256_update(read, "tail", 4), 0); + check_eq(uapi16_sha256_finish(read, &expected), 0); + check_eq(memcmp(&hash, &expected, sizeof(hash)), 0); + if (sizes[i] == HOLE) + check_hash(&hash, SHA256_OF_SPARSE); + } + + /* A computation that is finished takes no zero bytes, not even + * none, and no computation is none to give them to. */ + check_eq(uapi16_sha256_finish(finished, &hash), 0); + check_eq(uapi16_sha256_update_zeros(finished, 1), -ESTALE); + check_eq(uapi16_sha256_update_zeros(finished, 0), -ESTALE); + check_eq(uapi16_sha256_update_zeros(NULL, 1), -EINVAL); + check_eq(uapi16_sha256_update_zeros(NULL, 0), -EINVAL); + + /* A file with a hole: its object gives the size and the hash of + * all its bytes. The check takes the hole as the zero bytes it + * is, between the data that was read. */ + unhex(SHA256_OF_SPARSE, &hash); + check_eq(uapi16_file_object_set_size(sparse, SPARSE_SIZE), 0); + check_eq(uapi16_file_object_set_sha256(sparse, &hash), 0); + check_eq(uapi16_data_check_new(sparse, &c), 0); + check_eq(uapi16_data_check_update(c, "head", 4, &e), 0); + check_eq(uapi16_data_check_update_zeros(c, HOLE, &e), 0); + check_eq(uapi16_data_check_update_zeros(c, 0, &e), 0); + check_eq(uapi16_data_check_update(c, "tail", 4, &e), 0); + check_eq(uapi16_data_check_finish(c, &size, &e), 0); + check_eq(size, SPARSE_SIZE); + + /* A check that is finished takes no zero bytes. */ + check_ended(uapi16_data_check_update_zeros(c, 1, &e), &e); + check_ended(uapi16_data_check_update_zeros(c, 0, &e), &e); + check_eq(uapi16_data_check_update_zeros(c, 1, NULL), -ESTALE); + c = uapi16_data_check_free(c); + + /* More zero bytes than the object has room for are refused, as + * other bytes are, and none of them is taken: the check goes on + * with the hole as it is. */ + check_eq(uapi16_data_check_new(sparse, &c), 0); + check_eq(uapi16_data_check_update(c, "head", 4, &e), 0); + r = uapi16_data_check_update_zeros(c, HOLE + 5, &e); + check_error(r, e, UAPI16_ERROR_SIZE_MISMATCH, EBADMSG, "sparse", 0); + e = uapi16_error_free(e); + r = uapi16_data_check_update_zeros(c, UINT64_MAX, &e); + check_error(r, e, UAPI16_ERROR_SIZE_MISMATCH, EBADMSG, "sparse", 0); + e = uapi16_error_free(e); + check_eq(uapi16_data_check_update_zeros(c, HOLE + 5, NULL), -EBADMSG); + check_eq(uapi16_data_check_update_zeros(c, HOLE, &e), 0); + check_eq(uapi16_data_check_update(c, "tail", 4, &e), 0); + check_eq(uapi16_data_check_finish(c, &size, &e), 0); + check_eq(size, SPARSE_SIZE); + c = uapi16_data_check_free(c); + + /* Zero bytes where the data has other bytes are data of the size + * the object says and of another hash, which shows when the check + * finishes. */ + check_eq(uapi16_data_check_new(sparse, &c), 0); + check_eq(uapi16_data_check_update_zeros(c, SPARSE_SIZE, &e), 0); + size = 77; + r = uapi16_data_check_finish(c, &size, &e); + check_error(r, e, UAPI16_ERROR_HASH_MISMATCH, EBADMSG, "sparse", 0); + e = uapi16_error_free(e); + check_eq(size, 77); + c = uapi16_data_check_free(c); + + /* A call that is not valid fails for that, and takes nothing: no + * check, and a `reterr` that points to something, which is looked + * at first, also on a check that is finished. */ + check_eq(uapi16_file_object_new("a//b", &no_object, &held), -EINVAL); + check(held && !no_object); + check_misuse(uapi16_data_check_update_zeros(NULL, 1, &e), &e, EINVAL); + check_eq(uapi16_data_check_update_zeros(NULL, 1, NULL), -EINVAL); + check_eq(uapi16_file_object_set_size(sized, 3), 0); + check_eq(uapi16_data_check_new(sized, &c), 0); + { + uapi16_error *place = held; + + check_eq(uapi16_data_check_update_zeros(c, 1, &place), -EINVAL); + check_eq(uapi16_data_check_update_zeros(NULL, 1, &place), -EINVAL); + check(place == held); + /* An object that gives a size alone: zero bytes count for + * it as any bytes do. The one that was refused did not. */ + check_eq(uapi16_data_check_update_zeros(c, 2, &e), 0); + check_eq(uapi16_data_check_update(c, "x", 1, &e), 0); + check_eq(uapi16_data_check_finish(c, &size, &e), 0); + check_eq(size, 3); + check_eq(uapi16_data_check_update_zeros(c, 1, &place), -EINVAL); + check(place == held); + } + c = uapi16_data_check_free(c); + + /* One that gives neither a size nor a hash: any number of them + * passes. */ + check_eq(uapi16_data_check_new(plain, &c), 0); + check_eq(uapi16_data_check_update_zeros(c, 1024 * 1024, &e), 0); + check_eq(uapi16_data_check_update_zeros(c, 5, &e), 0); + check_eq(uapi16_data_check_finish(c, &size, &e), 0); + check_eq(size, 1024 * 1024 + 5); + check(!e); +} + +/* Everything the file `fd` holds from `offset` on, up to `room` bytes, and + * how much that is. */ +static size_t read_from(int fd, uint64_t offset, char *data, size_t room) { + size_t done = 0; + + while (done < room) { + ssize_t n = pread(fd, data + done, room - done, (off_t) (offset + done)); + + check(n >= 0); + if (n == 0) + break; + done += (size_t) n; + } + return done; +} + +/* How many threads open files from one directory at the same time, and how + * often each does. */ +#define OPENERS 4 +#define OPENINGS 100 + +/* The directory the threads open their files from, what lets them start + * together, and what each has of its own: the name and the data of its + * file. */ +struct opening { + pthread_barrier_t start; + const uapi16_directory *directory; +}; + +struct opener { + struct opening *opening; + char name[32], data[32]; +}; + +static void *open_in_thread(void *argument) { + struct opener *opener = argument; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *o = make_object(opener->name); + int r = pthread_barrier_wait(&opener->opening->start); + + check(r == 0 || r == PTHREAD_BARRIER_SERIAL_THREAD); + for (int i = 0; i < OPENINGS; i++) { + uapi16_error *e = NULL; + uint64_t offset = 77; + char data[32]; + int fd = -1; + + check_eq(uapi16_directory_open_data(opener->opening->directory, o, &fd, &offset, &e), 0); + check(fd >= 0 && !e); + check_eq(offset, 0); + check_eq(read_from(fd, offset, data, sizeof(data)), strlen(opener->data)); + check_eq(memcmp(data, opener->data, strlen(opener->data)), 0); + check_eq(close(fd), 0); + } + return NULL; +} + +/* + * A directory opens the file the data of a file object is in, below the + * descriptor it was made from, and says where the data starts in it. The + * descriptor it stores is new, read-only and the caller's. What is no + * regular file below the directory, and an object whose data is not in a + * file, is refused, each for what it is. + */ +static void test_opened_data(void) { + static const char manifest[] = + ROOT RS "{\"contents\":[{\"file\":\"blobs/1\",\"originalSize\":11}],\"name\":\"longer\"}\n" + RS "{\"contents\":[{\"file\":\"blobs/1\",\"offset\":2}],\"name\":\"part\",\"size\":3}\n" + RS "{\"contents\":[{\"file\":\"blobs/1\",\"offset\":4}],\"name\":\"rest\"}\n" + RS "{\"contents\":[{\"file\":\"blobs/1\",\"originalSize\":9}],\"name\":\"shorter\"}\n" + RS "{\"contents\":[{\"url\":\"https://example.com/x\"}],\"name\":\"url\"}\n" + RS "{\"contents\":[{\"file\":\"blobs/1\",\"originalSize\":10}],\"name\":\"whole\"}\n" + RS "{\"contents\":[{\"file\":\"blobs/2\",\"offset\":1}],\"name\":\"zz\"}\n" TRAILER; + _cleanup_(closep) int top = make_tree("opened"), blobs = make_dir(top, "blobs"); + _cleanup_(closep) int path = openat(tmp_fd, "opened", O_PATH | O_DIRECTORY | O_CLOEXEC); + _cleanup_(closep) int from = manifest_file(manifest), fd = -1, second = -1; + _cleanup_(uapi16_directory_freep) uapi16_directory *d = NULL, *following = NULL, *named = NULL; + _cleanup_(uapi16_reader_freep) uapi16_reader *reader = NULL; + _cleanup_(uapi16_file_object_freep) uapi16_file_object *file = make_object("a/file"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *blob = make_object("elsewhere"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *sparse = make_object("sparse"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *other = make_object("a/none"); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *root = make_object(""); + _cleanup_(uapi16_file_object_freep) uapi16_file_object *got = NULL; + _cleanup_(uapi16_data_check_freep) uapi16_data_check *c = NULL; + _cleanup_(uapi16_error_freep) uapi16_error *e = NULL, *held = NULL; + struct opening opening; + struct opener openers[OPENERS]; + pthread_t threads[OPENERS]; + uapi16_sha256_digest_t hash; + uint64_t offset = 77, size = 0, contents_offset = 77; + const char *contents_file = NULL; + size_t before, n; + struct stat st; + char data[64]; + int r; + + /* The files below the directory: one that other files hold data + * in, one with a hole, and symbolic links that lead to a file, at + * the end of a name and on the way, by a name of the root and by + * one that goes up. make_tree() made a/file, a FIFO and the link + * to a directory. */ + check(path >= 0); + make_file(blobs, "1", "0123456789"); + check_eq(symlinkat("a/file", top, "to-file"), 0); + check_eq(symlinkat("/a/file", top, "absolute"), 0); + check_eq(symlinkat("../../a/file", top, "up"), 0); + check_eq(symlinkat("nowhere", top, "dangling"), 0); + { + _cleanup_(closep) int holed = -1; + + holed = openat(top, "sparse", O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644); + check(holed >= 0); + check_eq(pwrite(holed, "head", 4, 0), 4); + check_eq(pwrite(holed, "tail", 4, 4 + HOLE), 4); + } + check_eq(uapi16_directory_new(top, UAPI16_DIRECTORY_NONE, &d, &e), 0); + check_eq(uapi16_directory_new(top, UAPI16_DIRECTORY_FOLLOW_SYMLINKS, &following, &e), 0); + check_eq(uapi16_directory_new(path, UAPI16_DIRECTORY_NONE, &named, &e), 0); + before = open_descriptors(); + + /* The file of the name of the object, which gives no size: the + * data is all the file holds, from its start. The descriptor is a + * new one, for reading alone, one that blocks, and closed in a + * process that executes another program. */ + check_eq(uapi16_directory_open_data(d, file, &fd, &offset, &e), 0); + check(fd >= 0 && fd != top && !e); + check_eq(offset, 0); + check_eq(open_descriptors(), before + 1); + check_eq(fcntl(fd, F_GETFL) & O_ACCMODE, O_RDONLY); + check(!(fcntl(fd, F_GETFL) & O_NONBLOCK)); + check(fcntl(fd, F_GETFD) & FD_CLOEXEC); + check_eq(write(fd, "x", 1), -1); + check_eq(errno, EBADF); + check_eq(fstat(fd, &st), 0); + check(S_ISREG(st.st_mode)); + n = read_from(fd, offset, data, sizeof(data)); + check_same(data, n, "hello", 5); + + /* Every call opens the file again: a second descriptor is another + * one, and both are the caller's to close. */ + check_eq(uapi16_directory_open_data(d, file, &second, &offset, &e), 0); + check(second >= 0 && second != fd); + check_eq(close(second), 0); + second = -1; + check_eq(close(fd), 0); + fd = -1; + check_eq(open_descriptors(), before); + + /* The size the object gives is how much of the file is its data. + * A file that holds more is fine, and one that is too short for + * it is not. Nothing is stored for a call that fails, here and + * below. */ + check_eq(uapi16_file_object_set_size(file, 5), 0); + check_eq(uapi16_directory_open_data(d, file, &fd, &offset, &e), 0); + check_eq(close(fd), 0); + check_eq(uapi16_file_object_set_size(file, 4), 0); + check_eq(uapi16_directory_open_data(d, file, &fd, &offset, &e), 0); + check_eq(close(fd), 0); + fd = -7; + offset = 7; + check_eq(uapi16_file_object_set_size(file, 6), 0); + r = uapi16_directory_open_data(d, file, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_SIZE_MISMATCH, EBADMSG, "a/file", 0); + e = uapi16_error_free(e); + check_eq(uapi16_directory_open_data(d, file, &fd, &offset, NULL), -EBADMSG); + + /* A file that is not there, and what is there and no regular file: + * a directory and a FIFO, which nothing waits for a writer of. */ + r = uapi16_directory_open_data(d, other, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_SOURCE_MISSING, ENOENT, "a/none", 0); + e = uapi16_error_free(e); + check_eq(uapi16_file_object_set_name(other, "a/file/below", &e), 0); + r = uapi16_directory_open_data(d, other, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_SOURCE_MISSING, ENOENT, "a/file/below", 0); + e = uapi16_error_free(e); + check_eq(uapi16_file_object_set_name(other, "a", &e), 0); + r = uapi16_directory_open_data(d, other, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_SOURCE_NOT_REGULAR, EINVAL, "a", 0); + e = uapi16_error_free(e); + check_eq(uapi16_file_object_set_name(other, "fifo", &e), 0); + r = uapi16_directory_open_data(d, other, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_SOURCE_NOT_REGULAR, EINVAL, "fifo", 0); + e = uapi16_error_free(e); + + /* A symbolic link is not followed, at the end of the name and on + * the way to it: the file can't be opened, and the error has the + * errno of the system call. */ + check_eq(uapi16_file_object_set_name(other, "to-file", &e), 0); + r = uapi16_directory_open_data(d, other, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_IO, ELOOP, "to-file", 0); + e = uapi16_error_free(e); + check_eq(uapi16_file_object_set_name(other, "link/file", &e), 0); + r = uapi16_directory_open_data(d, other, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_IO, ELOOP, "link/file", 0); + e = uapi16_error_free(e); + check_eq(fd, -7); + check_eq(offset, 7); + + /* A directory that follows symbolic links follows them as if it + * were the root: a name of the root and one that goes up above + * the directory stay below it. A link that leads nowhere is a + * file that is not there, and one to a directory is no regular + * file. */ + check_eq(uapi16_directory_open_data(following, other, &fd, &offset, &e), 0); + n = read_from(fd, offset, data, sizeof(data)); + check_same(data, n, "hello", 5); + check_eq(close(fd), 0); + check_eq(uapi16_file_object_set_name(other, "to-file", &e), 0); + check_eq(uapi16_directory_open_data(following, other, &fd, &offset, &e), 0); + n = read_from(fd, offset, data, sizeof(data)); + check_same(data, n, "hello", 5); + check_eq(close(fd), 0); + check_eq(uapi16_file_object_set_name(other, "absolute", &e), 0); + check_eq(uapi16_directory_open_data(following, other, &fd, &offset, &e), 0); + n = read_from(fd, offset, data, sizeof(data)); + check_same(data, n, "hello", 5); + check_eq(close(fd), 0); + check_eq(uapi16_file_object_set_name(other, "up", &e), 0); + check_eq(uapi16_directory_open_data(following, other, &fd, &offset, &e), 0); + n = read_from(fd, offset, data, sizeof(data)); + check_same(data, n, "hello", 5); + check_eq(close(fd), 0); + fd = -7; + offset = 7; + check_eq(uapi16_file_object_set_name(other, "dangling", &e), 0); + r = uapi16_directory_open_data(following, other, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_SOURCE_MISSING, ENOENT, "dangling", 0); + e = uapi16_error_free(e); + check_eq(uapi16_file_object_set_name(other, "link", &e), 0); + r = uapi16_directory_open_data(following, other, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_SOURCE_NOT_REGULAR, EINVAL, "link", 0); + e = uapi16_error_free(e); + + /* An object whose data is not in a file has none to open: a file + * that has no data, the root, data that the manifest carries, for + * a regular file and for a symbolic link, and data at a URL, which + * comes from the manifest below. */ + check_eq(uapi16_file_object_set_name(file, "fifo", &e), 0); + check_eq(uapi16_file_object_set_type(file, S_IFIFO), 0); + check_eq(uapi16_file_object_data_location(file), UAPI16_DATA_LOCATION_NONE); + r = uapi16_directory_open_data(d, file, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_UNSUPPORTED, EOPNOTSUPP, "fifo", 0); + e = uapi16_error_free(e); + check_eq(uapi16_file_object_data_location(root), UAPI16_DATA_LOCATION_NONE); + r = uapi16_directory_open_data(d, root, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_UNSUPPORTED, EOPNOTSUPP, "", 0); + e = uapi16_error_free(e); + check_eq(uapi16_directory_open_data(d, root, &fd, &offset, NULL), -EOPNOTSUPP); + check_eq(uapi16_file_object_set_name(other, "carried", &e), 0); + check_eq(uapi16_file_object_set_target(other, "data", 4), 0); + check_eq(uapi16_file_object_data_location(other), UAPI16_DATA_LOCATION_LITERAL); + for (int is_link = 0; is_link < 2; is_link++) { + check_eq(uapi16_file_object_set_type(other, is_link ? S_IFLNK : S_IFREG), 0); + r = uapi16_directory_open_data(d, other, &fd, &offset, &e); + check_eq(r, -EOPNOTSUPP); + check_eq(uapi16_error_kind(e), UAPI16_ERROR_UNSUPPORTED); + check_eq(uapi16_error_errno(e), EOPNOTSUPP); + /* The error names the object, as the one about an object + * without data does, above. */ + check_str(uapi16_error_path(e), "carried"); + e = uapi16_error_free(e); + } + + /* A call that is not valid: no directory, no object, and no place + * for the descriptor or for where the data starts. Both places are + * needed: without one of them, and without both, the call fails, + * and stores nothing in the one that is there. One whose `reterr` + * points to something fails for that first. None of them opens + * anything, also where the object has a file that could be + * opened. */ + check_eq(uapi16_file_object_set_contents_file(blob, "blobs/1", &e), 0); + check_misuse(uapi16_directory_open_data(NULL, blob, &fd, &offset, &e), &e, EINVAL); + check_misuse(uapi16_directory_open_data(d, NULL, &fd, &offset, &e), &e, EINVAL); + check_misuse(uapi16_directory_open_data(d, blob, NULL, &offset, &e), &e, EINVAL); + check_misuse(uapi16_directory_open_data(d, blob, &fd, NULL, &e), &e, EINVAL); + check_misuse(uapi16_directory_open_data(d, blob, NULL, NULL, &e), &e, EINVAL); + check_eq(uapi16_directory_open_data(d, blob, NULL, &offset, NULL), -EINVAL); + check_eq(uapi16_directory_open_data(d, blob, &fd, NULL, NULL), -EINVAL); + check_eq(uapi16_directory_open_data(d, blob, NULL, NULL, NULL), -EINVAL); + check_eq(fd, -7); + check_eq(offset, 7); + check_eq(open_descriptors(), before); + check_eq(uapi16_file_object_new("a//b", &got, &held), -EINVAL); + check(held && !got); + { + uapi16_error *place = held; + + check_eq(uapi16_directory_open_data(d, blob, &fd, &offset, &place), -EINVAL); + check_eq(uapi16_directory_open_data(NULL, blob, &fd, &offset, &place), -EINVAL); + check(place == held); + } + check_eq(fd, -7); + check_eq(offset, 7); + check_eq(open_descriptors(), before); + + /* The file the object refers to, under another name than its + * own. */ + check_eq(uapi16_directory_open_data(d, blob, &fd, &offset, &e), 0); + check_eq(offset, 0); + n = read_from(fd, offset, data, sizeof(data)); + check_same(data, n, "0123456789", 10); + check_eq(close(fd), 0); + + /* A manifest can say where in that file the data starts: such an + * object comes from a reader, and its data starts there. One + * gives a size, and its data is that many bytes. The other gives + * none, and its data reaches to the end of the file. */ + reader = open_reader(from); + /* A manifest can also say how long that file is. A file of another + * size is not the one it means: this one has 10 bytes, and the + * manifest says 11. Nothing is stored. */ + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(got), "longer"); + /* The object says which file its data is in and where it starts + * there, as the manifest has it. */ + check_eq(uapi16_file_object_contents_file(got, &contents_file, &contents_offset), 0); + check_str(contents_file, "blobs/1"); + check_eq(contents_offset, 0); + fd = -7; + offset = 7; + r = uapi16_directory_open_data(d, got, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_SIZE_MISMATCH, EBADMSG, "longer", 0); + e = uapi16_error_free(e); + check_eq(fd, -7); + check_eq(offset, 7); + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(got), "part"); + check_eq(uapi16_file_object_contents_file(got, &contents_file, &contents_offset), 0); + check_str(contents_file, "blobs/1"); + check_eq(contents_offset, 2); + check_eq(uapi16_directory_open_data(d, got, &fd, &offset, &e), 0); + check_eq(offset, 2); + check_eq(uapi16_file_object_size(got, &size), 0); + check_eq(size, 3); + n = read_from(fd, offset, data, (size_t) size); + check_same(data, n, "234", 3); + check_eq(close(fd), 0); + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(got), "rest"); + check_eq(uapi16_file_object_contents_file(got, &contents_file, &contents_offset), 0); + check_str(contents_file, "blobs/1"); + check_eq(contents_offset, 4); + check_eq(uapi16_directory_open_data(d, got, &fd, &offset, &e), 0); + check_eq(offset, 4); + n = read_from(fd, offset, data, sizeof(data)); + check_same(data, n, "456789", 6); + check_eq(close(fd), 0); + /* The manifest says 9 bytes, and the file is longer. */ + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(got), "shorter"); + fd = -7; + offset = 7; + r = uapi16_directory_open_data(d, got, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_SIZE_MISMATCH, EBADMSG, "shorter", 0); + e = uapi16_error_free(e); + check_eq(fd, -7); + check_eq(offset, 7); + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(got), "url"); + check_eq(uapi16_file_object_data_location(got), UAPI16_DATA_LOCATION_UNSUPPORTED); + /* Data that is in no file is in no other file: the object that was + * filled again names none, and nothing is stored. */ + contents_file = NULL; + contents_offset = 77; + check_eq(uapi16_file_object_contents_file(got, &contents_file, &contents_offset), -ENODATA); + check(!contents_file); + check_eq(contents_offset, 77); + fd = -7; + r = uapi16_directory_open_data(d, got, &fd, &offset, &e); + check_error(r, e, UAPI16_ERROR_UNSUPPORTED, EOPNOTSUPP, "url", 0); + e = uapi16_error_free(e); + check_eq(fd, -7); + /* A file that is as long as the manifest says is opened. */ + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(got), "whole"); + check_eq(uapi16_directory_open_data(d, got, &fd, &offset, &e), 0); + check_eq(offset, 0); + n = read_from(fd, offset, data, sizeof(data)); + check_same(data, n, "0123456789", 10); + check_eq(close(fd), 0); + check_eq(uapi16_file_object_contents_file(got, &contents_file, &contents_offset), 0); + check_str(contents_file, "blobs/1"); + /* The same object, filled again, names the file of its record. */ + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_FILE); + check_str(uapi16_file_object_name(got), "zz"); + check_eq(uapi16_file_object_contents_file(got, &contents_file, &contents_offset), 0); + check_str(contents_file, "blobs/2"); + check_eq(contents_offset, 1); + check_eq(uapi16_reader_next(reader, &got, &e), UAPI16_READ_END); + + /* What was opened is read and held against a check of the same + * object: a file with a hole, of which the caller reads the data + * at its start and at its end, and passes the hole as the zero + * bytes it is. */ + unhex(SHA256_OF_SPARSE, &hash); + check_eq(uapi16_file_object_set_size(sparse, SPARSE_SIZE), 0); + check_eq(uapi16_file_object_set_sha256(sparse, &hash), 0); + check_eq(uapi16_directory_open_data(d, sparse, &fd, &offset, &e), 0); + check_eq(offset, 0); + check_eq(uapi16_data_check_new(sparse, &c), 0); + check_eq(read_from(fd, offset, data, 4), 4); + check_eq(uapi16_data_check_update(c, data, 4, &e), 0); + check_eq(uapi16_data_check_update_zeros(c, HOLE, &e), 0); + check_eq(read_from(fd, offset + 4 + HOLE, data, sizeof(data)), 4); + check_eq(uapi16_data_check_update(c, data, 4, &e), 0); + check_eq(uapi16_data_check_finish(c, &size, &e), 0); + check_eq(size, SPARSE_SIZE); + check_eq(close(fd), 0); + + /* A directory that was made from a descriptor that only names it + * opens files as well. What it opened stays open once it is + * freed, and so does the descriptor it was made from. */ + check_eq(uapi16_directory_open_data(named, blob, &fd, &offset, &e), 0); + named = uapi16_directory_free(named); + check_open(fd); + check_open(path); + n = read_from(fd, offset, data, sizeof(data)); + check_same(data, n, "0123456789", 10); + check_eq(close(fd), 0); + fd = -1; + check_eq(fstatat(path, "blobs/1", &st, 0), 0); + + /* Several threads open files from one directory at the same time, + * each with an object of its own. */ + opening.directory = d; + check_eq(pthread_barrier_init(&opening.start, NULL, OPENERS), 0); + for (size_t i = 0; i < OPENERS; i++) { + openers[i].opening = &opening; + snprintf(openers[i].name, sizeof(openers[i].name), "thread-%zu", i); + snprintf(openers[i].data, sizeof(openers[i].data), "data of %zu", i); + make_file(top, openers[i].name, openers[i].data); + } + for (size_t i = 0; i < OPENERS; i++) + check_eq(pthread_create(&threads[i], NULL, open_in_thread, &openers[i]), 0); + for (size_t i = 0; i < OPENERS; i++) + check_eq(pthread_join(threads[i], NULL), 0); + check_eq(pthread_barrier_destroy(&opening.start), 0); + check_eq(open_descriptors(), before); + check(!e); +} + +int main(int argc, char *argv[]) { + static const struct { + const char *name; + void (*run)(void); + } tests[] = { + { "example", test_example }, + { "report", test_report }, + { "options", test_options }, + { "misuse", test_misuse }, + { "walk", test_walk }, + { "extended attributes", test_walk_xattrs }, + { "error places", test_error_places }, + { "names", test_names }, + { "unwritable names", test_unwritable_names }, + { "changes", test_changes }, + { "errors", test_errors }, + { "too large", test_too_large }, + { "loop", test_loop }, + { "no uuid", test_no_uuid }, + { "fat", test_fat }, + { "descriptors", test_descriptors }, + { "no descriptors", test_no_descriptors }, + { "signals", test_signals }, + { "fork", test_fork }, + { "scratch files", test_scratch_files }, + { "failed walks", test_failed_walks }, + { "failed sync", test_failed_sync }, + { "forks", test_forks }, + { "linked names", test_linked_names }, + { "threads", test_threads }, + { "file objects", test_file_objects }, + { "retained features", test_retained_features }, + { "feature sets", test_feature_sets }, + { "roots", test_roots }, + { "root adds", test_root_adds }, + { "added objects", test_added_objects }, + { "refused objects", test_refused_objects }, + { "records", test_records }, + { "record fields", test_record_fields }, + { "no order", test_no_order }, + { "copies", test_copies }, + { "reading", test_reading }, + { "no blocking", test_no_blocking }, + { "failed writes", test_failed_writes }, + { "refilled objects", test_refilled_objects }, + { "kept objects", test_kept_objects }, + { "manifests", test_manifests }, + { "error records", test_error_records }, + { "validity", test_validity }, + { "signatures", test_signatures }, + { "sha256", test_sha256 }, + { "data checks", test_data_checks }, + { "zeros", test_zeros }, + { "directories", test_directories }, + { "opened data", test_opened_data }, + { "names and features", test_names_and_features }, + { "numbers", test_numbers }, + }; + const char *tmpdir = getenv("TMPDIR"); + char path[PATH_MAX], *name; + _cleanup_(closep) int parent = -1; + + /* The test runs itself once more for test_forks() and + * test_linked_names(), and such a process does only what it is + * told. */ + if (argc == 2 && strcmp(argv[1], WITHOUT_WIPE_ON_FORK) == 0) + return without_wipe_on_fork(); + if (argc == 2 && strcmp(argv[1], FORK_IN_THE_FIRST_CALL) == 0) + return fork_in_the_first_call(); + if (argc == 2 && strcmp(argv[1], FIRST_CALLS_AT_ONCE) == 0) + return first_calls_at_once(); + if (argc == 2 && strcmp(argv[1], FORK_IN_THE_FIRST_ASK) == 0) + return fork_in_the_first_ask(); + if (argc == 2 && strcmp(argv[1], WITHOUT_TMPFILE) == 0) + return without_tmpfile(); + if (argc == 3 && strcmp(argv[1], WITH_A_LINKED_NAME) == 0) + return linked_name(argv[2], LINKED); + if (argc == 3 && strcmp(argv[1], WITH_A_NAME_LEFT) == 0) + return linked_name(argv[2], LINKED_AND_LEFT); + if (argc == 3 && strcmp(argv[1], WITH_A_NAME_THROUGH_PROCFS) == 0) + return linked_name(argv[2], LINKED_THROUGH_PROCFS); + check(argc == 1); + self_path = argv[0]; + + /* What ran is said at once, also to a pipe. */ + setvbuf(stdout, NULL, _IOLBF, 0); + snprintf(path, sizeof(path), "%s/uapi16-capi-XXXXXX", tmpdir && *tmpdir ? tmpdir : "/tmp"); + check(mkdtemp(path)); + tmp_fd = open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + check(tmp_fd >= 0); + check(realpath(path, tmp_path)); + name = strrchr(path, '/'); + *name++ = 0; + parent = open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + check(parent >= 0); + null_fd = open("/dev/null", O_WRONLY | O_CLOEXEC); + check(null_fd >= 0); + + /* The trees of the tests have a hard link. Where the temporary + * directory can hold none, as on FAT, nothing is tested. */ + make_file(tmp_fd, "linked", ""); + if (linkat(tmp_fd, "linked", tmp_fd, "linked-too", 0) < 0) { + check_eq(errno, EPERM); + fprintf(stderr, "skipping every test: %s can hold no hard link\n", path); + close(null_fd); + close(tmp_fd); + remove_tree(parent, name); + return EXIT_SUCCESS; + } + check_eq(unlinkat(tmp_fd, "linked-too", 0), 0); + check_eq(unlinkat(tmp_fd, "linked", 0), 0); + + for (size_t i = 0; i < ELEMENTSOF(tests); i++) { + /* These fork and count on the child being told, which + * takes memory that is wiped in a child. */ + bool forks = tests[i].run == test_fork || tests[i].run == test_scratch_files || + tests[i].run == test_forks; + + if (forks && !wipes_on_fork()) { + /* ci.yml matches the start of this line for + * "forks", which has two parts under a seccomp + * filter. */ + fprintf(stderr, "skipping %s: no memory that is wiped in a child here, so no child is told\n", + tests[i].name); + continue; + } + tests[i].run(); + printf("ok %s\n", tests[i].name); + } + + close(null_fd); + close(tmp_fd); + remove_tree(parent, name); + return EXIT_SUCCESS; +} diff --git a/src/uapi16/tests/capi.sh b/src/uapi16/tests/capi.sh new file mode 100755 index 0000000..1477d6e --- /dev/null +++ b/src/uapi16/tests/capi.sh @@ -0,0 +1,267 @@ +#!/bin/sh +# SPDX-License-Identifier: LGPL-2.1-or-later +# +# Tests the C library of uapi16 as install.sh installed it: +# +# ./build.sh +# ./install.sh --prefix=DIR +# tests/capi.sh DIR [COMMAND...] +# +# It checks what the shared library exports, builds tests/capi.c against +# the installed header, once with the shared and once with the static +# library, and runs both. Then it builds the programs of examples/ against +# the shared library, runs each on files it makes, and checks what they +# did. It takes the flags for that from uapi16.pc. +# +# The tests and the examples run under COMMAND if one is given, such as +# valgrind. CC is the compiler, and CFLAGS are its flags: unless they are +# set, the tests and the examples are built with the address and the +# undefined behavior sanitizer. LIBDIR is where the libraries are, if that +# is not DIR/lib. + +set -eu + +[ $# -ge 1 ] || { + echo "usage: $0 DIR [COMMAND...]" >&2 + exit 1 +} +prefix=$1 +shift +libdir=${LIBDIR:-$prefix/lib} +# CDPATH is where cd looks for a directory first, and it says where it went +# if it found it there. It has no say here. +here=$(CDPATH= cd -P -- "$(dirname -- "$0")" && pwd) +cc=${CC:-cc} +cflags=${CFLAGS:--std=c11 -g -fsanitize=address,undefined -fno-sanitize-recover=undefined} +warnings="-Wall -Wextra -Werror" + +fail() { + echo "$0: $*" >&2 + exit 1 +} + +export PKG_CONFIG_PATH="$libdir/pkgconfig" +includes=$(pkg-config --cflags uapi16) +shared_libs=$(pkg-config --libs uapi16) +# The same with what the static library needs, and with the static library +# named, since a linker that finds both takes the shared one. +static_libs=$(pkg-config --static --libs uapi16 | sed 's/-luapi16/-l:libuapi16.a/') +# uapi16.pc has a backslash before a space in a path, see install.sh. +includedir=$(pkg-config --variable=includedir uapi16 | sed 's/\\ / /g') + +# The shared library exports the functions uapi16.h declares, each at the +# node of the release that added it, and nothing else. So far that is +# LIBUAPI16_0.1.0 for every function. A node never changes once it is +# released, so a release that adds functions adds its node here. GNU ld +# also lists each version node as an absolute symbol of its name, which is +# no export. lld lists none. +shared=$libdir/libuapi16.so.0 +[ -e "$shared" ] || fail "$shared is missing" +declared=$(sed -n '/^static /d; s/^UAPI16_NODISCARD //; s/^[a-z][^(]*[ *]\(uapi16_[a-z0-9_]*\)(.*/\1/p' \ + "$includedir/uapi16.h" | sort) +exported=$(nm -D --defined-only --with-symbol-versions "$shared" | + sed '/ A LIBUAPI16_[0-9.]*$/d; s/^.* //' | sort) +[ -n "$declared" ] || fail "$includedir/uapi16.h declares no functions" +elsewhere=$(echo "$exported" | grep -v '@@LIBUAPI16_0\.1\.0$' || true) +[ -z "$elsewhere" ] || fail "$shared does not export at LIBUAPI16_0.1.0:" $elsewhere +[ "$(echo "$exported" | sed 's/@@.*//')" = "$declared" ] || + fail "$shared does not export what uapi16.h declares:" $exported +echo "ok symbols ($(echo "$declared" | wc -l))" + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +# The trees of the tests have a hard link. Where the temporary directory +# can hold none, as on FAT, nothing more is tested. +: > "$work/linked" +if ! ln "$work/linked" "$work/linked-too" 2> /dev/null; then + echo "skipping the tests and the examples: $work can hold no hard link" >&2 + exit 0 +fi +rm "$work/linked" "$work/linked-too" + +# $cc, $cflags and $warnings are lists of words. What pkg-config said is +# written for a shell to read, with a backslash before a space in a path, +# so the shell reads it once more here. +# +# The test holds a call of the library in its malloc(), see capi.c. With +# --wrap=malloc the linker gives everything it links into the program the +# malloc() of the test: the test itself and the static library. The shared +# library keeps the one of the C library. +wrap="-Wl,--wrap=malloc" +eval "\$cc \$cflags \$warnings -pthread $includes -o \"\$work/capi-shared\" \"\$here/capi.c\" \ + \$wrap $shared_libs -Xlinker -rpath -Xlinker \"\$libdir\"" +eval "\$cc \$cflags \$warnings -pthread $includes -o \"\$work/capi-static\" \"\$here/capi.c\" \ + \$wrap $static_libs" + +# Each test is linked with the library it is for. +needed() { + readelf -d "$1" | grep -c 'NEEDED.*libuapi16' || true +} +[ "$(needed "$work/capi-shared")" = 1 ] || fail "capi-shared is not linked with the shared library" +[ "$(needed "$work/capi-static")" = 0 ] || fail "capi-static is linked with the shared library" + +for library in shared static; do + echo "# the $library library" + "$@" "$work/capi-$library" +done + +# The programs of examples/, built as tests/capi.c is, with the shared +# library. Each runs under COMMAND on files that are made below $work, and +# what it printed and wrote is checked. assemble takes what build made, so +# build comes first. +examples="generate listing build assemble sorted signed" + +# Fails unless the file $1 has the lines $2, $3 and so on. +has_lines() { + file=$1 + shift + [ "$(cat "$file")" = "$(printf '%s\n' "$@")" ] || fail "$file has:" "$(cat "$file")" +} + +# Fails unless the manifest $1 lists the file objects $2, $3 and so on, in +# that order. Each record is a line, and that of a file object has its +# name. The root has none. +lists() { + manifest=$1 + shift + names=$(sed -n 's/^.*"name":"\([^"]*\)".*$/\1/p' "$manifest") + [ "$names" = "$(printf '%s\n' "$@")" ] || fail "$manifest lists:" $names +} + +# A line for every file below the directory $1, in the order of their +# names: its name and its type, the target of a symbolic link, and the +# number of names and the hash of the data of a regular file. +files() { + ( + CDPATH= cd -- "$1" + find . ! -name . | LC_ALL=C sort | while IFS= read -r name; do + if [ -L "$name" ]; then + echo "$name link to $(readlink "$name")" + elif [ -f "$name" ]; then + echo "$name file $(stat -c %h "$name") $(sha256sum < "$name" | cut -d ' ' -f 1)" + else + echo "$name $(stat -c %F "$name")" + fi + done + ) +} + +# A line for every regular file below the directory $1, in the order of +# their names: its name, its access mode and its modification time. +attributes() { + (CDPATH= cd -- "$1" && find . -type f -exec stat -c '%n %a %y' {} + | LC_ALL=C sort) +} + +# Makes the directory $1 with a tree in it: directories, one of them +# empty, regular files with data and without, one with holes and one with +# two names, and a symbolic link. Some of the regular files have modes and +# modification times of their own. A manifest lists a/x before a-b, which +# strcmp() does not. +make_tree() { + mkdir "$1" "$1/a" "$1/sub" "$1/sub/deeper" + echo x > "$1/a/x" + echo a-b > "$1/a-b" + : > "$1/empty" + # 1 MiB, with data at 512 KiB and holes before and after it. + truncate -s 1M "$1/hole" + echo hole | dd of="$1/hole" bs=4096 seek=128 conv=notrunc status=none + echo one > "$1/one" + ln "$1/one" "$1/sub/two" + ln -s a/x "$1/link" + chmod 0640 "$1/a/x" + chmod 0755 "$1/a-b" + touch -d 2001-02-03T04:05:06.123456789Z "$1/a/x" + touch -d 2002-03-04T05:06:07.987654321Z "$1/one" +} + +# generate writes the manifest of a tree to a new file, and says what it +# lists. It leaves out a file whose name a manifest can't hold, and it +# replaces no file. +check_generate() { + make_tree "$work/generate-tree" + mkfifo "$work/generate-tree/fifo" + : > "$work/generate-tree/$(printf 'not\377utf-8')" + "$@" "$work/generate" "$work/generate-tree" "$work" generate.manifest > "$work/generate.out" \ + 2> "$work/generate.err" || fail "generate exited with $?:" "$(cat "$work/generate.err")" + has_lines "$work/generate.out" "6 files, 4 directories, 2 others, 1048590 bytes" + has_lines "$work/generate.err" "1 files have names a manifest can't hold and were left out" + lists "$work/generate.manifest" a a/x a-b empty fifo hole link one sub sub/deeper sub/two + rc=0 + "$@" "$work/generate" "$work/generate-tree" "$work" generate.manifest 2> "$work/generate.err" || rc=$? + [ "$rc" = 1 ] || fail "generate exited with $rc for a name that is taken" + has_lines "$work/generate.err" "generate.manifest: there is a file of that name already" +} + +# listing writes the manifest of the records it has. The two names of tool +# are one file and have one token, and its data, hello, is in the store +# under the name of its hash. +check_listing() { + "$@" "$work/listing" "$work" listing.manifest > "$work/listing.out" || fail "listing exited with $?" + has_lines "$work/listing.out" "7 records" + lists "$work/listing.manifest" usr usr/bin usr/bin/alias usr/bin/tool usr/libexec usr/libexec/tool + blob=blobs/$(printf hello | sha256sum | cut -d ' ' -f 1) + for name in usr/bin/tool usr/libexec/tool; do + record=$(grep -F "\"name\":\"$name\"" "$work/listing.manifest") + case $record in + *"\"contents\":[{\"file\":\"$blob\"}]"*) ;; + *) fail "$name does not have its data in $blob:" "$record" ;; + esac + case $record in + *'"inodeToken":1,'*) ;; + *) fail "$name does not have the token 1:" "$record" ;; + esac + done +} + +# build copies a tree into a new directory, with the data, the names and +# the links of its files, and writes the manifest of what it copied. Its +# root has the identity build gives the file system. +check_build() { + "$@" "$work/build" "$work/tree" "$work/build-image" > "$work/build.manifest" || fail "build exited with $?" + [ "$(files "$work/build-image")" = "$(files "$work/tree")" ] || fail "build-image is not a copy of tree" + lists "$work/build.manifest" a a/x a-b empty hole link one sub sub/deeper sub/two + root=$(head -n 1 "$work/build.manifest") + case $root in + *'"fsLabel":"example"'*) ;; + *) fail "the root does not have the label of build:" "$root" ;; + esac + case $root in + *'"fsUUID":"6f1d0a42-9c1e-4b7a-8d33-520c7e11a905"'*) ;; + *) fail "the root does not have the UUID of build:" "$root" ;; + esac +} + +# assemble makes the tree again from the manifest of build and the files +# build copied: the data, the names and the links of its files, and the +# access modes and the modification times of its regular files. +check_assemble() { + "$@" "$work/assemble" "$work/build-image" "$work/assemble-image" < "$work/build.manifest" || + fail "assemble exited with $?" + [ "$(files "$work/assemble-image")" = "$(files "$work/tree")" ] || fail "assemble-image is not tree" + [ "$(attributes "$work/assemble-image")" = "$(attributes "$work/tree")" ] || + fail "the regular files of assemble-image do not have the modes and the times of tree" +} + +# sorted writes the records of the directories and the regular files of a +# tree as its walk comes to them, which is the order of the manifest. +check_sorted() { + "$@" "$work/sorted" "$work/tree" > "$work/sorted.manifest" || fail "sorted exited with $?" + lists "$work/sorted.manifest" a a/x a-b empty hole one sub sub/deeper sub/two +} + +# signed writes a manifest with a signature object, and reads it back with +# what the signature signs. +check_signed() { + "$@" "$work/signed" "$work/signed.manifest" > "$work/signed.out" || fail "signed exited with $?" + has_lines "$work/signed.out" hello.txt "a signature by openpgp: good" +} + +echo "# the examples" +make_tree "$work/tree" +for example in $examples; do + eval "\$cc \$cflags \$warnings $includes -o \"\$work/\$example\" \"\$here/../examples/\$example.c\" \ + $shared_libs -Xlinker -rpath -Xlinker \"\$libdir\"" + "check_$example" "$@" + echo "ok example $example" +done diff --git a/src/uapi16/tree.rs b/src/uapi16/tree.rs new file mode 100644 index 0000000..dbb75de --- /dev/null +++ b/src/uapi16/tree.rs @@ -0,0 +1,572 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The files of a tree that are added to a manifest: what statx() says of +//! one, whether that shows a change, and why one could not be read. The +//! system calls that read them are in the module sys. + +use std::ffi::CStr; +use std::fmt; +use std::io; +use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; +use std::time::Duration; + +use rustix::fs::FileType; + +use crate::error::{Error, ErrorKind, TreeProblem}; +use crate::{Features, Mode, Name, Sha256}; + +/// The mount a file was reached through, as statx() tells it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum MountId { + /// STATX_MNT_ID_UNIQUE, from Linux 6.8 on: no other mount gets this + /// ID while the system runs. + Unique(u64), + /// STATX_MNT_ID, from Linux 5.8 on: the ID of the mount in + /// /proc/self/mountinfo, which a later mount can get once this one is + /// gone. + Reusable(u64), +} + +/// A device number as statx() gives it, split into its major and its minor +/// number. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) struct DeviceNumber { + pub(crate) major: u32, + pub(crate) minor: u32, +} + +/// Which file a status is of. Two statuses of the same identity are of the +/// same file, reached through the same mount. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) struct Identity { + /// The mount the file was reached through. A bind mount is a mount of + /// its own, so a file reached through it is not the file reached + /// through its source. + pub(crate) mount: MountId, + /// The device of the file system the file is on. + pub(crate) device: DeviceNumber, + /// The inode number of the file. + pub(crate) inode: u64, + /// The subvolume the file is in, STATX_SUBVOL from Linux 6.10 on, + /// where the file system has subvolumes, such as btrfs. + pub(crate) subvolume: Option, +} + +impl Identity { + /// The inode, whatever mount it was reached through. + pub(crate) fn inode_id(&self) -> InodeId { + InodeId { + device: self.device, + inode: self.inode, + subvolume: self.subvolume, + } + } +} + +/// Which inode a file is, whatever mount it was reached through: the +/// device, the inode number and the subvolume of an [`Identity`], without +/// its mount. A mount that shows a directory again shows the same inode. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) struct InodeId { + pub(crate) device: DeviceNumber, + pub(crate) inode: u64, + pub(crate) subvolume: Option, +} + +/// A time as statx() gives it: seconds since the epoch, negative before +/// it, and nanoseconds on top. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Timestamp { + pub(crate) seconds: i64, + pub(crate) nanoseconds: u32, +} + +impl Timestamp { + /// The time as `mTimeNSec` has it, in nanoseconds since the epoch. A + /// time before the epoch has none, and neither has one that does not + /// fit into 64 bits, after the year 2554. + pub(crate) fn since_epoch_nsec(self) -> Option { + let seconds = u64::try_from(self.seconds).ok()?; + // Nanoseconds of a second or more carry into the seconds, of which + // there are less than 2^63. + let since = Duration::new(seconds, self.nanoseconds); + u64::try_from(since.as_nanos()).ok() + } +} + +/// What statx() says of a file: what a manifest records of it, and what +/// tells whether it changed. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Status { + pub(crate) identity: Identity, + /// The type of the file, from the type bits of its mode. + pub(crate) file_type: FileType, + /// The permission bits with the set-user-ID, the set-group-ID and the + /// sticky bit. + pub(crate) mode: Mode, + /// How many names the file has. + pub(crate) nlink: u32, + pub(crate) uid: u32, + pub(crate) gid: u32, + /// The size of the data of a regular file, the length of the target + /// of a symbolic link. + pub(crate) size: u64, + /// When the data changed last. + pub(crate) mtime: Timestamp, + /// When the data or the metadata changed last, the modification time + /// included. Nothing can set it. + pub(crate) ctime: Timestamp, + /// When the file was made, where the file system keeps that. + pub(crate) btime: Option, + /// The device a device node stands for. + pub(crate) rdev: DeviceNumber, +} + +impl Status { + /// Whether this status, read after `before`, shows that the file + /// changed: that it is another file now, or that its size, its + /// modification time, its change time or how many names it has are + /// different. The change time changes with everything else, also when + /// the modification time is set back. Not on FAT, though: a rename over + /// a file changes no time of the file there, only how many names it + /// has, and an unlink sets its modification time and its change time in + /// steps of two seconds, so one in the same two seconds changes none. + /// How many names it has shows both. + pub(crate) fn changed_since(&self, before: &Status) -> bool { + (self.identity, self.size, self.mtime, self.ctime, self.nlink) + != (before.identity, before.size, before.mtime, before.ctime, before.nlink) + } + + /// Whether this status, of a file that has the inode of the file `own` + /// is the status of, is of that file as well. A file system can give + /// two files one inode, see [`OwnFiles`](crate::sys::OwnFiles). They + /// are one file if the type, the mode, the owner, the group, the number + /// of names, the size, the modification time and the change time are + /// the same, and the birth time where both statuses have one. + pub(crate) fn matches(&self, own: &Status) -> bool { + let born = match (self.btime, own.btime) { + (Some(found), Some(own)) => found == own, + _ => true, + }; + let held = |s: &Status| (s.file_type, s.mode, s.uid, s.gid, s.nlink, s.size, s.mtime, s.ctime); + born && held(self) == held(own) + } + + /// What `read`, the read of the data of the file of this status, comes + /// to, with `after`, the status of the file after the read. If the + /// status shows that the file changed, the file changed while it was + /// read. Data that did not end at its size is + /// [`Failure::WrongSize`] where the status shows no change. + pub(crate) fn check_read( + &self, + read: Result, + after: Result, + ) -> Result { + // Another file in the place of this one also makes reads fail. + if after.as_ref().is_ok_and(|after| after.changed_since(self)) { + return Err(Failure::Changed); + } + let hash = match read { + Ok(hash) => hash, + Err(DataFailure::EndedEarly | DataFailure::WentOn) => return Err(Failure::WrongSize), + Err(DataFailure::Io(e)) => return Err(Failure::Io(e)), + }; + after.map(|_| hash) + } +} + +/// The handle of an [`Entry`]: the descriptor everything is read of the +/// file through. +#[derive(Debug)] +pub(crate) enum Handle<'fd> { + /// A handle the entry was opened as, which is closed with the entry. + Owned(OwnedFd), + /// A descriptor of a caller, which the entry borrows and never closes. + Borrowed(BorrowedFd<'fd>), +} + +impl AsFd for Handle<'_> { + fn as_fd(&self) -> BorrowedFd<'_> { + match self { + Handle::Owned(handle) => handle.as_fd(), + Handle::Borrowed(handle) => *handle, + } + } +} + +/// A file of a tree, open as a handle that nothing is read through, and +/// its status. A symbolic link is the link itself, and a FIFO or a device +/// node is not opened. The entry of a descriptor that a caller gave borrows +/// that descriptor for `'fd`. Any other entry owns its handle. +#[derive(Debug)] +pub(crate) struct Entry<'fd> { + handle: Handle<'fd>, + status: Status, + /// Whether it is an automount point, see [`Entry::is_automount`]. + automount: bool, +} + +impl<'fd> Entry<'fd> { + /// The entry of the handle `handle`, whose status is `status`, and + /// which is an automount point if `automount` says so. + pub(crate) fn new(handle: Handle<'fd>, status: Status, automount: bool) -> Entry<'fd> { + Entry { + handle, + status, + automount, + } + } + + /// The handle, which entries below a directory are opened in. + pub(crate) fn handle(&self) -> BorrowedFd<'_> { + self.handle.as_fd() + } + + /// The status of the file when it was opened. + pub(crate) fn status(&self) -> &Status { + &self.status + } + + /// Whether the file is an automount point: a directory that nothing is + /// mounted on yet, and that the kernel mounts something on once it is + /// opened or a name is looked up in it. Taking its handle mounts + /// nothing. It is never opened and nothing is looked up in it, so a + /// tree has it as the empty directory it is until then. + pub(crate) fn is_automount(&self) -> bool { + self.automount + } +} + +/// Where an entry of a tree is: the directory it is in and its name there, +/// which a directory is opened by, see [`Entry::reopen`]. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Place<'a> { + /// The directory, a handle or the directory open for its listing. + pub(crate) dir: BorrowedFd<'a>, + /// The name of the entry in it, one component. + pub(crate) name: &'a CStr, +} + +/// Why the data of a regular file was not read as far as its size. +#[derive(Debug)] +pub(crate) enum DataFailure { + /// A read failed. + Io(io::Error), + /// The data ended before the size. + EndedEarly, + /// The data went on after the size. + WentOn, +} + +/// Why a feature that was asked for cannot be read from a file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Unreadable { + /// The file system of the file has no inode flags. + NoInodeFlags, + /// The file system of the file has no DOS attributes. + NoDosAttributes, + /// The file system of the file has no extended attributes. + NoXattrs, + /// Extended attributes are read through procfs, which is not mounted. + NoProcfs, + /// An extended attribute of the file has a name a manifest cannot + /// hold: one that is not UTF-8, or that has a control character or a + /// noncharacter. + XattrName, + /// The file system cannot say what its label is. + NoLabel, + /// The label of the file system is not one a manifest can hold. + LabelUnwritable, + /// The file is an automount point, which is not opened, see + /// [`Entry::is_automount`], and the feature is read from the open file. + Automount, +} + +impl fmt::Display for Unreadable { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Unreadable::NoInodeFlags => f.write_str("the file system has no inode flags"), + Unreadable::NoDosAttributes => f.write_str("the file system has no DOS attributes"), + Unreadable::NoXattrs => f.write_str("the file system has no extended attributes"), + Unreadable::NoProcfs => f.write_str("extended attributes are read through /proc, which is not mounted"), + Unreadable::XattrName => f.write_str("an extended attribute has a name a manifest cannot hold"), + Unreadable::NoLabel => f.write_str("the file system cannot say what its label is"), + Unreadable::LabelUnwritable => f.write_str("the label of the file system is not one a manifest can hold"), + Unreadable::Automount => f.write_str("the file is an automount point, which is not opened"), + } + } +} + +/// Why a file of a tree could not be read as it is. +#[derive(Debug)] +pub(crate) enum Failure { + /// A system call failed. + Io(io::Error), + /// statx() gives no mount ID: the kernel is older than 5.8. + NoMountId, + /// The file changed while it was read. + Changed, + /// The data of a regular file did not end at its size, and nothing + /// else showed a change: the size of a file of procfs or sysfs says + /// nothing of its data. + WrongSize, + /// A single feature that was asked for cannot be read from the file. + Unavailable(Features, Unreadable), + /// What was read of the file is more than a record of a manifest has + /// room for. + TooLarge, +} + +impl Failure { + /// The error of a failure that is about no file of the manifest, such + /// as a failure of statx() of a descriptor a caller gave. Only a system + /// call or a kernel that is too old fail so. + pub(crate) fn into_unnamed_error(self) -> Error { + match self { + Failure::Io(e) => Error::from(e), + failure => failure.into_error(Name::ROOT), + } + } + + /// The error of the file `name`, which failed so. The error that the + /// kernel is too old is about no file. + pub(crate) fn into_error(self, name: &Name) -> Error { + let message = match self { + Failure::Io(e) => { + let message = format!("{}: {}", Subject(name), e); + return Error::new(ErrorKind::Io, message).named(name.as_str()).caused_by(e); + } + Failure::NoMountId => { + let message = "the kernel is too old: statx() reports no mount ID, uapi16 needs Linux 5.10 or newer"; + return Error::new(ErrorKind::Tree(TreeProblem::FeatureUnavailable), message.into()); + } + Failure::Changed => format!("{}: changed while it was read", Subject(name)), + Failure::WrongSize => format!("{}: its data does not end at its size", Subject(name)), + Failure::Unavailable(feature, why) => { + let message = format!( + "{}: '{}' cannot be read: {}", + Subject(name), + feature.names().next().unwrap_or_default(), + why + ); + return Error::new(ErrorKind::Tree(TreeProblem::FeatureUnavailable), message) + .named(name.as_str()) + .about(feature); + } + Failure::TooLarge => return Error::record_too_large().named(name.as_str()), + }; + Error::new(ErrorKind::Tree(TreeProblem::Changed), message).named(name.as_str()) + } +} + +impl From for Failure { + fn from(error: io::Error) -> Failure { + Failure::Io(error) + } +} + +/// A file of a tree as a message names it: by its name in the manifest, +/// and the root of the tree, which has none, as what it is. +pub(crate) struct Subject<'a>(pub(crate) &'a Name); + +impl fmt::Display for Subject<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.0.is_root() { + return f.write_str("the root of the tree"); + } + write!(f, "{}", self.0.as_str().escape_debug()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The status of a regular file that a test changes. + fn status() -> Status { + let time = Timestamp { + seconds: 1_700_000_000, + nanoseconds: 123_456_789, + }; + Status { + identity: Identity { + mount: MountId::Unique(1), + device: DeviceNumber { major: 8, minor: 1 }, + inode: 2, + subvolume: None, + }, + file_type: FileType::RegularFile, + mode: Mode::from_st_mode(0o644), + nlink: 1, + uid: 3, + gid: 4, + size: 5, + mtime: time, + ctime: time, + btime: Some(time), + rdev: DeviceNumber { major: 0, minor: 0 }, + } + } + + /// Only another file, another size, another modification time, + /// another change time or another number of names show that a file + /// changed. The rest changes with the change time. + #[test] + fn what_shows_a_change() { + let before = status(); + assert!(!before.changed_since(&before)); + type Change = fn(&mut Status); + let changes: [(&str, Change, bool); 14] = [ + ("mount", |s| s.identity.mount = MountId::Reusable(1), true), + ("device", |s| s.identity.device.minor ^= 1, true), + ("inode", |s| s.identity.inode ^= 1, true), + ("subvolume", |s| s.identity.subvolume = Some(6), true), + ("size", |s| s.size ^= 1, true), + ("mtime", |s| s.mtime.nanoseconds ^= 1, true), + ("ctime", |s| s.ctime.seconds ^= 1, true), + ("nlink", |s| s.nlink ^= 1, true), + ("type", |s| s.file_type = FileType::Fifo, false), + ("mode", |s| s.mode = Mode::from_st_mode(0o1234), false), + ("uid", |s| s.uid ^= 1, false), + ("gid", |s| s.gid ^= 1, false), + ("btime", |s| s.btime = None, false), + ("rdev", |s| s.rdev.major ^= 1, false), + ]; + for (what, change, shows) in changes { + let mut later = before; + change(&mut later); + assert_eq!(later.changed_since(&before), shows, "{}", what); + } + } + + /// Two statuses with one inode are of one file where the type, the + /// mode, the owner, the group, the number of names, the size, the + /// modification time and the change time are the same, to the + /// nanosecond, and the birth time where both have one. The mount a file + /// was reached through and the device a device node stands for say + /// nothing of that. + #[test] + fn what_tells_files_with_one_inode_apart() { + let own = status(); + assert!(own.matches(&own)); + type Change = fn(&mut Status); + let changes: [(&str, Change, bool); 14] = [ + ("type", |s| s.file_type = FileType::Fifo, false), + ("mode", |s| s.mode = Mode::from_st_mode(0o645), false), + ("uid", |s| s.uid ^= 1, false), + ("gid", |s| s.gid ^= 1, false), + ("nlink", |s| s.nlink ^= 1, false), + ("size", |s| s.size ^= 1, false), + ("mtime", |s| s.mtime.nanoseconds ^= 1, false), + ("mtime, its seconds", |s| s.mtime.seconds ^= 1, false), + ("ctime", |s| s.ctime.nanoseconds ^= 1, false), + ("ctime, its seconds", |s| s.ctime.seconds ^= 1, false), + ( + "btime", + |s| { + s.btime = Some(Timestamp { + seconds: 1, + nanoseconds: 2, + }) + }, + false, + ), + ("no btime", |s| s.btime = None, true), + ("mount", |s| s.identity.mount = MountId::Reusable(1), true), + ("rdev", |s| s.rdev.major ^= 1, true), + ]; + for (what, change, one_file) in changes { + let mut found = own; + change(&mut found); + assert_eq!(found.matches(&own), one_file, "{}", what); + assert_eq!(own.matches(&found), one_file, "{}", what); + } + let mut neither = own; + neither.btime = None; + assert!(neither.matches(&neither)); + } + + /// A read and the status after it come to the hash when both went + /// through and the file did not change. A change wins over a read that + /// failed, as another file in the place of the one opened makes reads + /// fail, and a read that failed over a statx() that failed. Data that + /// does not end at the size of a file that shows no change is a failure + /// of its own. + #[test] + fn what_a_read_comes_to() { + /// What a read comes to where it does not come to a hash. + #[derive(Debug, PartialEq)] + enum Came { + Changed, + WrongSize, + Failed(Option), + } + let before = status(); + let mut changed = before; + changed.size += 1; + let hash = Sha256::digest(b"data"); + let failed = |errno: i32| io::Error::from_raw_os_error(errno); + let comes_to = |read, after| match before.check_read(read, after) { + Ok(found) => Ok(found), + Err(Failure::Io(e)) => Err(Came::Failed(e.raw_os_error())), + Err(Failure::Changed) => Err(Came::Changed), + Err(Failure::WrongSize) => Err(Came::WrongSize), + Err(failure) => panic!("{:?}", failure), + }; + assert_eq!(comes_to(Ok(hash), Ok(before)), Ok(hash)); + assert_eq!(comes_to(Ok(hash), Ok(changed)), Err(Came::Changed)); + let read_failed = Err(DataFailure::Io(failed(libc::EISDIR))); + assert_eq!(comes_to(read_failed, Ok(changed)), Err(Came::Changed)); + for end in [DataFailure::EndedEarly, DataFailure::WentOn] { + assert_eq!(comes_to(Err(end), Ok(before)), Err(Came::WrongSize)); + } + for end in [DataFailure::EndedEarly, DataFailure::WentOn] { + assert_eq!(comes_to(Err(end), Ok(changed)), Err(Came::Changed)); + } + let statx_failed = Err(Failure::Io(failed(libc::ENOMEM))); + assert_eq!(comes_to(Err(DataFailure::WentOn), statx_failed), Err(Came::WrongSize)); + let read_failed = Err(DataFailure::Io(failed(libc::EIO))); + assert_eq!(comes_to(read_failed, Ok(before)), Err(Came::Failed(Some(libc::EIO)))); + let read_failed = Err(DataFailure::Io(failed(libc::EIO))); + let statx_failed = Err(Failure::Io(failed(libc::ENOMEM))); + assert_eq!(comes_to(read_failed, statx_failed), Err(Came::Failed(Some(libc::EIO)))); + let statx_failed = Err(Failure::Io(failed(libc::ENOMEM))); + assert_eq!(comes_to(Ok(hash), statx_failed), Err(Came::Failed(Some(libc::ENOMEM)))); + } + + /// A failure is an error about the file that failed, with its name, but + /// for the kernel that is too old. The root of the tree, which has no + /// name, is named for what it is. An I/O error says which file it is of + /// as well, and keeps the error of the system call. + #[test] + fn errors() { + let name = Name::new("a/\"b\"").unwrap(); + let e = Failure::Changed.into_error(name); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::Changed)); + assert_eq!(e.name(), Some(name.as_str())); + assert_eq!(e.to_string(), r#"a/\"b\": changed while it was read"#); + let e = Failure::Changed.into_error(Name::ROOT); + assert_eq!(e.to_string(), "the root of the tree: changed while it was read"); + let e = Failure::WrongSize.into_error(name); + assert_eq!( + (e.kind(), e.name()), + (ErrorKind::Tree(TreeProblem::Changed), Some(name.as_str())) + ); + assert_eq!(e.to_string(), r#"a/\"b\": its data does not end at its size"#); + let e = Failure::Io(io::Error::from_raw_os_error(libc::EACCES)).into_error(name); + assert_eq!(e.kind(), ErrorKind::Io); + assert_eq!(e.name(), Some(name.as_str())); + assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::EACCES)); + let denied = io::Error::from_raw_os_error(libc::EACCES); + assert_eq!(e.to_string(), format!(r#"a/\"b\": {}"#, denied)); + let failed = io::Error::from_raw_os_error(libc::EIO); + let e = Failure::Io(io::Error::from_raw_os_error(libc::EIO)).into_error(Name::ROOT); + assert_eq!(e.to_string(), format!("the root of the tree: {}", failed)); + let e = Failure::NoMountId.into_error(name); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::FeatureUnavailable)); + assert_eq!((e.name(), e.feature(), e.io_error().is_none()), (None, None, true)); + assert_eq!( + e.to_string(), + "the kernel is too old: statx() reports no mount ID, uapi16 needs Linux 5.10 or newer" + ); + } +} diff --git a/src/uapi16/uapi16.h b/src/uapi16/uapi16.h new file mode 100644 index 0000000..7d645a6 --- /dev/null +++ b/src/uapi16/uapi16.h @@ -0,0 +1,2324 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#ifndef UAPI16_H +#define UAPI16_H + +/* + * cbindgen wrote this file from capi.rs and cbindgen.toml. Change those and + * write it again: + * + * cbindgen --quiet --config cbindgen.toml --output uapi16.h capi.rs + */ + +#include +#include +#include + +/* + * The C API of uapi16: building UAPI.16 file manifests of trees of files, + * and reading and writing them record by record. + * https://uapi-group.org/specifications/specs/file_manifest/ + * + * What holds for every function: + * + * - A function that can fail returns 0, or a negative errno if it fails. + * uapi16_reader_next() and uapi16_reader_next_signature() are the one + * exception: each returns a uapi16_read_t that says what it read, or a + * negative errno. uapi16_error_errno() can't fail and returns an errno + * as a positive number. + * + * - `reterr` is NULL or points to NULL. Unless it is NULL, a call that + * fails stores a new error there, which the caller frees with + * uapi16_error_free(). A call that succeeds does not write to it. A + * call whose `reterr` points to anything but NULL fails with -EINVAL + * before it does anything, and leaves what is there as it is. + * + * - Every call that makes an object stores it in `ret` if it succeeds, + * and does not write to `ret` if it fails. uapi16_reader_next() and + * uapi16_reader_next_signature() are the one exception: `*ret` is NULL + * or an object of the caller, which is cleared and filled again, and + * which stays the caller's whatever the call returns. A caller that + * does not want a report passes NULL for its `ret`. Every other object + * needs its `ret`. + * + * - Descriptors are borrowed. An object that keeps a descriptor borrows + * the caller's until its free function returns, and never closes it: a + * reader, a writer, a writer of records and a directory. The caller + * keeps the descriptor open until then. A function that makes no object + * borrows a descriptor for the call. A call that fails to make its + * object leaves the descriptor with the caller. Where the name of + * uapi16_manifest_writer_create_at() has several components, the + * library opens the directory of the file itself. A negative number is + * no descriptor, AT_FDCWD included, and fails with -EBADF. + * + * - Strings that go in are NUL-terminated UTF-8 and are read during the + * call. The name of a new manifest file is the exception: `name` of + * uapi16_manifest_writer_create_at() and uapi16_manifest_generate_at() + * is a path, which is taken as the bytes it is. Strings and bytes that + * come out belong to the object they come from. They live until it is + * freed, or until a call sets their field again, takes it away or fills + * the object again. + * + * - uapi16_feature_t is a plain enum: a feature is a number. Later versions + * add numbers after the last one, with no gaps, and a number keeps its + * name. uapi16_feature_name() returns NULL for a number this library + * doesn't have. The other enums are 64 bits wide. + * + * - The numbers of an enum never change and new ones are only added, so a + * switch over one needs a default case. A set of flags has a type of its + * own: uapi16_add_flags_t and uapi16_directory_flags_t. + * uapi16_name_order_t is the one signed enum: it is 64 bits wide like + * the others, and its numbers are -1, 0 and 1. + * + * - An object is used by one thread at a time, and the library takes no + * locks. Reports and errors can be read from any thread. No thread of + * the library runs once a call returned, so a caller can fork() between + * calls. + * + * - After fork(), the child can't use the objects of its parent: a + * function that can fail fails with -ECHILD there. + * + * - The library installs no signal handlers and changes no signal masks. + * A system call that a signal interrupts is made again. SIGPIPE behaves + * as with write(2). + * + * - A call that is not valid fails with -EINVAL: one with an object, a set + * or a string that is NULL, with no `ret` for an object other than a + * report, with a `reterr` that points to anything but NULL, or with a + * flag or an order that is unknown. If memory runs out or the library + * panics, the process aborts. + * + * - A call is checked in this order: what it is given first, which fails + * with -EINVAL, -E2BIG or -EBADF, then the process it is made in, which + * fails with -ECHILD, and then its options or its writer. Options with a + * feature of partitions fail with -EINVAL in the calls that make a + * manifest writer, the generate functions among them, and a writer fails + * with -ESTALE once it takes nothing more. So a call that is not valid + * fails for that in a child and on such a writer as well, and a child + * gets -ECHILD for options with a feature of partitions. + * + * - Options whose order is UAPI16_ORDER_NONE are for a writer of records. + * The functions that sort refuse them with -EINVAL, where options with + * a feature of partitions fail too: uapi16_manifest_writer_create_at(), + * uapi16_manifest_writer_open(), uapi16_manifest_generate_at() and + * uapi16_manifest_generate(). + * + * - Bytes go in as a pointer and a size, and are copied during the call. + * The pointer is not read where the size is 0. Bytes that are there and + * empty come out as a pointer that is not NULL, with the size 0. + * + * - A set's size is what the program's header says. UAPI16_FEATURES_EMPTY + * or UAPI16_FEATURES_SET() writes it, and the library reads it but never + * writes it. A size above UAPI16_FEATURES_SIZE_MAX fails with -E2BIG and + * one below UAPI16_FEATURES_SIZE_VER0 with -EINVAL, as in clone3. A size + * that is not a multiple of 8 fails with -EINVAL. Calls without a result + * treat such a set as empty and change nothing: has() is false, next() + * is NONE, and equal() is false. + * + * - Set calls work on the bits, by the sizes the sets carry. A word a set + * doesn't have counts as zero. union(), intersect() and subtract() + * change the first set and keep its size. A union drops bits the first + * set has no room for. add() and remove() fail with -EINVAL for NONE, + * and for a number the set has no room for. + * + * - Calls that take a set (set_features, retain_features) follow + * copy_struct_from_user(). Non-zero words past the library's fail with + * -E2BIG, a feature the library doesn't have fails with -EINVAL, and + * nothing changes. + * + * - Getters (default, known, the reader's and the object's) follow + * copy_struct_to_user() with the set's own size. They copy what fits, + * clear the rest of the set, drop what doesn't fit, and return 0. + * + * - A getter of a field that an object does not have fails with -ENODATA + * and stores nothing, or returns NULL for a string. + * + * - A file object that no thread changes can be read from any thread, and + * several threads can open files from one uapi16_directory at the same + * time. + * + * - A reader that failed to read an object or a writer that failed to + * write a record, and a writer of records, a computation and a check + * that are finished, take nothing more: a later call fails with -ESTALE. + */ + +#if (defined(__cplusplus) && __cplusplus >= 201703L) || \ + (!defined(__cplusplus) && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) +# define UAPI16_NODISCARD [[nodiscard]] +#elif defined(__clang__) +# define UAPI16_NODISCARD __attribute__((warn_unused_result)) +#else +# define UAPI16_NODISCARD +#endif + +/** + * The size of a UUID in bytes: the length of uapi16_uuid_t's bytes. + */ +#define UAPI16_UUID_SIZE 16 + +/** + * The number of 64-bit words of a UUID: the length of uapi16_uuid_t's + * qwords. + */ +#define UAPI16_UUID_QWORDS 2 + +/** + * The size of a SHA-256 hash in bytes: the length of + * uapi16_sha256_digest_t's bytes. + */ +#define UAPI16_SHA256_SIZE 32 + +/** + * The number of 64-bit words of a SHA-256 hash: the length of + * uapi16_sha256_digest_t's qwords. + */ +#define UAPI16_SHA256_QWORDS 4 + +/** + * The number of 64-bit words of a uapi16_features_t, each with room for 64 + * features. + */ +#define UAPI16_FEATURES_WORDS 2 + +/** + * The first size of a uapi16_features_t in bytes, which every library + * takes. + */ +#define UAPI16_FEATURES_SIZE_VER0 24 + +/** + * The largest size of a uapi16_features_t in bytes. + */ +#define UAPI16_FEATURES_SIZE_MAX 4096 + +/** + * A feature of a manifest: what its file objects record. The features + * are those of the specification, which spells them in lower case with + * dashes: UAPI16_FEATURE_USER_XATTR is user-xattr. A feature is a number, + * and a set of features is a uapi16_features_t. Later versions add + * features after the last one. + * + * The features of partitions, UAPI16_FEATURE_GPT_LABEL to + * UAPI16_FEATURE_GPT_FLAG_GROW_FILE_SYSTEM, don't apply to a tree of + * files. No manifest writer is made for options that have one of them, and + * the generate functions refuse them. The writer of records takes them. + */ +typedef enum { + /** + * No feature. uapi16_feature_from_name() returns it for a name that no + * feature has. + */ + UAPI16_FEATURE_NONE = 0, + /** + * The access mode. + */ + UAPI16_FEATURE_MODE = 1, + /** + * The user ID of the owner. + */ + UAPI16_FEATURE_UID = 2, + /** + * The group ID of the owner. + */ + UAPI16_FEATURE_GID = 3, + /** + * The name of the owning user, as the user database of the host has + * it. + */ + UAPI16_FEATURE_USER_NAME = 4, + /** + * The name of the owning group, as the user database of the host has + * it. + */ + UAPI16_FEATURE_GROUP_NAME = 5, + /** + * The size of the data of a regular file. + */ + UAPI16_FEATURE_SIZE = 6, + /** + * The SHA-256 hash of the data of a regular file. + */ + UAPI16_FEATURE_SHA256 = 7, + /** + * The targets of symbolic links. + */ + UAPI16_FEATURE_SYMLINK = 8, + /** + * The major and minor numbers of device nodes. + */ + UAPI16_FEATURE_DEVICE = 9, + /** + * Which file objects are names of one file. + */ + UAPI16_FEATURE_HARDLINK = 10, + /** + * The modification time. + */ + UAPI16_FEATURE_MTIME = 11, + /** + * The extended attributes of the user namespace. + * + * The generate functions open no file for its extended attributes. + * Those of a file that is open anyway are read from the open file: a + * directory that is walked into, a regular file whose data is hashed, + * and a regular file or a directory that is opened for its inode + * flags, its DOS attributes or the identity of its file system. Those + * of any other file are read through /proc. Without a /proc they can't + * be read, and it has to be the one of the kernel: whoever can mount + * something else there can have such a file recorded with the + * attributes of another one. + */ + UAPI16_FEATURE_USER_XATTR = 12, + /** + * The DOS attribute hidden. + */ + UAPI16_FEATURE_FLAG_HIDDEN = 13, + /** + * The DOS attribute system. + */ + UAPI16_FEATURE_FLAG_SYSTEM = 14, + /** + * The DOS attribute archive. + */ + UAPI16_FEATURE_FLAG_ARCHIVE = 15, + /** + * The inode flag append only. + */ + UAPI16_FEATURE_FLAG_APPEND_ONLY = 16, + /** + * The inode flag immutable. + */ + UAPI16_FEATURE_FLAG_IMMUTABLE = 17, + /** + * The inode flag no atime updates. + */ + UAPI16_FEATURE_FLAG_NO_ATIME = 18, + /** + * The inode flag no copy on write. + */ + UAPI16_FEATURE_FLAG_NO_COW = 19, + /** + * The inode flag no dump. + */ + UAPI16_FEATURE_FLAG_NO_DUMP = 20, + /** + * Whether a file is read-only. + */ + UAPI16_FEATURE_READ_ONLY = 21, + /** + * The UUID of the file system of the root. + * + * UAPI16_FEATURE_FS_UUID and UAPI16_FEATURE_FAT_SERIAL are read from the + * root. A root whose file system has no UUID is written without one, + * and so is one whose volume serial number can't be read, which only + * FAT gives. Before Linux 6.9 no UUID can be read. Each is counted in + * uapi16_manifest_report_fields_omitted() as well. A manifest without a + * root has neither. + */ + UAPI16_FEATURE_FS_UUID = 22, + /** + * The label of the file system of the root. + */ + UAPI16_FEATURE_FS_LABEL = 23, + /** + * The volume serial number of the FAT file system of the root. + */ + UAPI16_FEATURE_FAT_SERIAL = 24, + /** + * The label of a partition. + */ + UAPI16_FEATURE_GPT_LABEL = 25, + /** + * The UUID of a partition. + */ + UAPI16_FEATURE_GPT_UUID = 26, + /** + * The type UUID of a partition. + */ + UAPI16_FEATURE_GPT_TYPE_UUID = 27, + /** + * The disk UUID of a partition table. + */ + UAPI16_FEATURE_GPT_DISK_UUID = 28, + /** + * The attribute flags of a partition. + */ + UAPI16_FEATURE_GPT_FLAGS = 29, + /** + * The partition attribute flag no auto. + */ + UAPI16_FEATURE_GPT_FLAG_NO_AUTO = 30, + /** + * The partition attribute flag grow file system. + */ + UAPI16_FEATURE_GPT_FLAG_GROW_FILE_SYSTEM = 31, +} uapi16_feature_t; + +/** + * The order a manifest lists its file objects in. + */ +enum uapi16_order_t +#if defined(__cplusplus) || __STDC_VERSION__ >= 202311L + : uint64_t +#endif // defined(__cplusplus) || __STDC_VERSION__ >= 202311L + { + /** + * No order. With options that have it, uapi16_writer_begin() writes a + * manifest that declares none, and uapi16_reader_order() returns it + * for such a manifest. The functions that sort refuse options that + * have it. + */ + UAPI16_ORDER_NONE = 0, + /** + * The order of the code points of the names, component by component: + * codepoint in the specification. + */ + UAPI16_ORDER_CODEPOINT = 1, +}; +#ifndef __cplusplus +#if __STDC_VERSION__ >= 202311L +typedef enum uapi16_order_t uapi16_order_t; +#else +typedef uint64_t uapi16_order_t; +#endif // __STDC_VERSION__ >= 202311L +#endif // __cplusplus + +/** + * A flag of the generate functions. A set of them is a + * uapi16_add_flags_t. + */ +enum uapi16_add_flag_t +#if defined(__cplusplus) || __STDC_VERSION__ >= 202311L + : uint64_t +#endif // defined(__cplusplus) || __STDC_VERSION__ >= 202311L + { + /** + * No flag. + */ + UAPI16_ADD_NONE = 0, + /** + * Walk into mount points instead of writing them as empty + * directories. + */ + UAPI16_ADD_CROSS_MOUNTS = (1 << 0), + /** + * Leave out files whose names a manifest can't hold, a directory with + * everything below it, and count them in + * uapi16_manifest_report_entries_omitted(), instead of failing. + */ + UAPI16_ADD_GRACEFUL = (1 << 1), +}; +#ifndef __cplusplus +#if __STDC_VERSION__ >= 202311L +typedef enum uapi16_add_flag_t uapi16_add_flag_t; +#else +typedef uint64_t uapi16_add_flag_t; +#endif // __STDC_VERSION__ >= 202311L +#endif // __cplusplus + +/** + * What kind of error a uapi16_error is, with the errno of each kind. + */ +enum uapi16_error_kind_t +#if defined(__cplusplus) || __STDC_VERSION__ >= 202311L + : uint64_t +#endif // defined(__cplusplus) || __STDC_VERSION__ >= 202311L + { + /** + * Reading or writing failed. The errno is that of the system call + * that failed, or EIO where none did. + */ + UAPI16_ERROR_IO = 1, + /** + * The name of the file to create is taken. EEXIST. + */ + UAPI16_ERROR_EXISTS = 2, + /** + * The same name was added for two different files that are not both + * directories. EEXIST. + */ + UAPI16_ERROR_DUPLICATE = 3, + /** + * A file changed while it was read. ESTALE. + */ + UAPI16_ERROR_CHANGED = 4, + /** + * Two names of one inode don't show the same file. ESTALE. + */ + UAPI16_ERROR_HARDLINK_MISMATCH = 5, + /** + * A file has a name that a manifest can't hold. EILSEQ for a name that + * is not UTF-8, ENAMETOOLONG for one that is too long, and EINVAL for + * any other. + */ + UAPI16_ERROR_UNWRITABLE_NAME = 6, + /** + * A file that is not a directory is where a directory is needed. + * ENOTDIR. + */ + UAPI16_ERROR_NOT_DIRECTORY = 7, + /** + * A feature that was asked for can't be read here, or the data of a + * file object is not data the library takes. EOPNOTSUPP. + */ + UAPI16_ERROR_UNSUPPORTED = 8, + /** + * The call is not a valid one. EINVAL for a NULL object, set or + * string, no `ret` for an object other than a report, an unknown flag + * or order and a name that is none. EBADF for a negative descriptor. + * ECHILD in a child of fork(). EINVAL for options with a feature of + * partitions, which a call that makes a manifest writer checks after + * the process, and for options whose order is UAPI16_ORDER_NONE in a + * function that sorts, which checks them there too. + */ + UAPI16_ERROR_INVALID_ARGUMENT = 9, + /** + * A directory is one of the directories it is in, because a mount + * shows it again. ELOOP. + */ + UAPI16_ERROR_LOOP = 10, + /** + * A directory that files were added below was not added itself, and + * the features need what it would record. ENOENT. + */ + UAPI16_ERROR_MISSING_PARENT = 11, + /** + * What a manifest records of a file is more than one of its records + * has room for, such as more than 4 MiB of extended attributes. E2BIG. + */ + UAPI16_ERROR_TOO_LARGE = 12, + /** + * The object takes nothing more: a writer, a computation or a check + * that is finished, a writer that failed to write a record, or a + * reader that failed to read an object. ESTALE. A call is checked for + * what it is given first and for its process next, so one that is + * UAPI16_ERROR_INVALID_ARGUMENT is that on such an object as well. + */ + UAPI16_ERROR_ENDED = 13, + /** + * A manifest is malformed, or a file object is not one a manifest can + * hold. uapi16_error_problem() names the rule that is broken, + * uapi16_error_field() the field and uapi16_error_record() the record. + * EBADMSG. + */ + UAPI16_ERROR_MANIFEST = 14, + /** + * The file a manifest has the data of a file object in is not there. + * ENOENT. + */ + UAPI16_ERROR_SOURCE_MISSING = 15, + /** + * The file a manifest has the data of a file object in is not a regular + * file. EINVAL. + */ + UAPI16_ERROR_SOURCE_NOT_REGULAR = 16, + /** + * The data of a file is not as many bytes as the manifest says, or its + * file is too short for it. EBADMSG. + */ + UAPI16_ERROR_SIZE_MISMATCH = 17, + /** + * The data of a file does not have the hash the manifest says. EBADMSG. + */ + UAPI16_ERROR_HASH_MISMATCH = 18, + /** + * A file object or a manifest is revoked. EKEYREVOKED. + */ + UAPI16_ERROR_REVOKED = 19, + /** + * The time is before the one a file object or a manifest may be used + * from. EKEYEXPIRED. + */ + UAPI16_ERROR_NOT_YET_VALID = 20, + /** + * The time is not before the one a file object or a manifest may be + * used until. EKEYEXPIRED. + */ + UAPI16_ERROR_EXPIRED = 21, +}; +#ifndef __cplusplus +#if __STDC_VERSION__ >= 202311L +typedef enum uapi16_error_kind_t uapi16_error_kind_t; +#else +typedef uint64_t uapi16_error_kind_t; +#endif // __STDC_VERSION__ >= 202311L +#endif // __cplusplus + +/** + * Which rule of the names of a manifest a name breaks. + */ +enum uapi16_name_problem_t +#if defined(__cplusplus) || __STDC_VERSION__ >= 202311L + : uint64_t +#endif // defined(__cplusplus) || __STDC_VERSION__ >= 202311L + { + /** + * It is not UTF-8. + */ + UAPI16_NAME_PROBLEM_NOT_UTF8 = 1, + /** + * It is empty. + */ + UAPI16_NAME_PROBLEM_EMPTY = 2, + /** + * It is longer than 4095 bytes. + */ + UAPI16_NAME_PROBLEM_TOO_LONG = 3, + /** + * Its first component is Uapi16Manifest or begins with + * Uapi16Manifest., which the specification reserves. + */ + UAPI16_NAME_PROBLEM_RESERVED = 4, + /** + * It has a control character: ASCII 0 to 31 or 127. + */ + UAPI16_NAME_PROBLEM_CONTROL_CHARACTER = 5, + /** + * It has a Unicode noncharacter. + */ + UAPI16_NAME_PROBLEM_NONCHARACTER = 6, + /** + * One of its components is empty: it begins or ends with a slash, or + * has two slashes in a row. + */ + UAPI16_NAME_PROBLEM_EMPTY_COMPONENT = 7, + /** + * One of its components is "." or "..". + */ + UAPI16_NAME_PROBLEM_DOT_COMPONENT = 8, +}; +#ifndef __cplusplus +#if __STDC_VERSION__ >= 202311L +typedef enum uapi16_name_problem_t uapi16_name_problem_t; +#else +typedef uint64_t uapi16_name_problem_t; +#endif // __STDC_VERSION__ >= 202311L +#endif // __cplusplus + +/** + * Whether a file object says that its file is read-only. + */ +enum uapi16_read_only_t +#if defined(__cplusplus) || __STDC_VERSION__ >= 202311L + : uint64_t +#endif // defined(__cplusplus) || __STDC_VERSION__ >= 202311L + { + /** + * The object does not say. + */ + UAPI16_READ_ONLY_UNSTATED = 0, + /** + * The file is not read-only. + */ + UAPI16_READ_ONLY_NO = 1, + /** + * The file is read-only. + */ + UAPI16_READ_ONLY_YES = 2, +}; +#ifndef __cplusplus +#if __STDC_VERSION__ >= 202311L +typedef enum uapi16_read_only_t uapi16_read_only_t; +#else +typedef uint64_t uapi16_read_only_t; +#endif // __STDC_VERSION__ >= 202311L +#endif // __cplusplus + +/** + * Where one name comes to another in the code point order, as + * uapi16_name_compare() returns it. This is the one signed enum: its + * numbers are those a comparison function of qsort() returns. + */ +enum uapi16_name_order_t +#if defined(__cplusplus) || __STDC_VERSION__ >= 202311L + : int64_t +#endif // defined(__cplusplus) || __STDC_VERSION__ >= 202311L + { + /** + * The first name comes before the second. + */ + UAPI16_NAME_BEFORE = -1, + /** + * The two names are the same. + */ + UAPI16_NAME_SAME = 0, + /** + * The first name comes after the second. + */ + UAPI16_NAME_AFTER = 1, +}; +#ifndef __cplusplus +#if __STDC_VERSION__ >= 202311L +typedef enum uapi16_name_order_t uapi16_name_order_t; +#else +typedef int64_t uapi16_name_order_t; +#endif // __STDC_VERSION__ >= 202311L +#endif // __cplusplus + +/** + * What uapi16_reader_next() and uapi16_reader_next_signature() read. Each + * returns one of these as an int, or a negative errno. + */ +enum uapi16_read_t +#if defined(__cplusplus) || __STDC_VERSION__ >= 202311L + : uint64_t +#endif // defined(__cplusplus) || __STDC_VERSION__ >= 202311L + { + /** + * The trailer was read and checked. The manifest is complete. + */ + UAPI16_READ_END = 0, + /** + * One file object was read, and is in `ret`. + */ + UAPI16_READ_FILE = 1, + /** + * The file objects have ended, and signature objects follow. From now + * on uapi16_reader_signed_len() has what they sign. + */ + UAPI16_READ_SIGNATURES = 2, + /** + * One signature object was read, and is in `ret`. Only + * uapi16_reader_next_signature() returns this. + */ + UAPI16_READ_SIGNATURE = 3, +}; +#ifndef __cplusplus +#if __STDC_VERSION__ >= 202311L +typedef enum uapi16_read_t uapi16_read_t; +#else +typedef uint64_t uapi16_read_t; +#endif // __STDC_VERSION__ >= 202311L +#endif // __cplusplus + +/** + * Where the data of a file object is, as uapi16_file_object_data_location() + * finds it. + */ +enum uapi16_data_location_t +#if defined(__cplusplus) || __STDC_VERSION__ >= 202311L + : uint64_t +#endif // defined(__cplusplus) || __STDC_VERSION__ >= 202311L + { + /** + * Nowhere: the object has no data. + */ + UAPI16_DATA_LOCATION_NONE = 0, + /** + * In the manifest itself. uapi16_file_object_literal() gives it. + */ + UAPI16_DATA_LOCATION_LITERAL = 1, + /** + * In a file next to the manifest. uapi16_directory_open_data() opens + * it. + */ + UAPI16_DATA_LOCATION_EXTERNAL = 2, + /** + * At a URL or in an encoding. The library neither fetches nor decodes + * data. + */ + UAPI16_DATA_LOCATION_UNSUPPORTED = 3, +}; +#ifndef __cplusplus +#if __STDC_VERSION__ >= 202311L +typedef enum uapi16_data_location_t uapi16_data_location_t; +#else +typedef uint64_t uapi16_data_location_t; +#endif // __STDC_VERSION__ >= 202311L +#endif // __cplusplus + +/** + * A flag of uapi16_directory_new(). A set of them is a + * uapi16_directory_flags_t. + */ +enum uapi16_directory_flag_t +#if defined(__cplusplus) || __STDC_VERSION__ >= 202311L + : uint64_t +#endif // defined(__cplusplus) || __STDC_VERSION__ >= 202311L + { + /** + * No flag. + */ + UAPI16_DIRECTORY_NONE = 0, + /** + * Follow symbolic links below the directory, 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. Without this flag a + * name that leads through a symbolic link fails with ELOOP. + */ + UAPI16_DIRECTORY_FOLLOW_SYMLINKS = (1 << 0), +}; +#ifndef __cplusplus +#if __STDC_VERSION__ >= 202311L +typedef enum uapi16_directory_flag_t uapi16_directory_flag_t; +#else +typedef uint64_t uapi16_directory_flag_t; +#endif // __STDC_VERSION__ >= 202311L +#endif // __cplusplus + +/** + * Holds the data of a file object against the size and the hash the + * object gives, as the data passes. Made by uapi16_data_check_new(), and + * freed by uapi16_data_check_free(). + */ +typedef struct uapi16_data_check uapi16_data_check; + +/** + * The directory the files of a manifest are taken from: the one the + * manifest is in, or one the caller chose instead. Made by + * uapi16_directory_new(), and freed by uapi16_directory_free(). + * + * The directory is never looked up again, and nothing resolves to + * anything outside it. Several threads can open files from one directory + * at the same time. + */ +typedef struct uapi16_directory uapi16_directory; + +/** + * Why a call failed. A call that fails stores one where its `reterr` + * points to, unless `reterr` is NULL, and uapi16_error_free() frees it. + * `reterr` has to point to NULL: a call that finds anything else there, + * such as an error that was not freed, fails with -EINVAL before it does + * anything, and leaves what is there as it is. + */ +typedef struct uapi16_error uapi16_error; + +/** + * A file object: what a manifest says about one file, or about the root + * directory of the tree it describes. Made by uapi16_file_object_new() and + * by uapi16_reader_next(), handed out by uapi16_reader_root(), and freed by + * uapi16_file_object_free(). + * + * The root is the object with the empty name. It is a directory. Besides + * its attributes it has the label, the UUID and the FAT serial number of + * the file system. It has no size, no hash, no target, no device numbers, + * no token and no DOS attributes. + * + * A setter stores what it is given and checks the call alone. A writer + * checks the object when it gets it. A getter of a number that the object + * does not have fails with -ENODATA and stores nothing, and a getter of a + * string returns NULL for it. What a reader filled in reads like any other + * value: a size and a hash that follow from other fields, and a flag that + * is cleared, a file that is not read-only and extended attributes there + * are none of, where the features of the manifest say so. A writer leaves + * these out again. + * + * The object keeps a copy of every string and of all bytes it is given. + */ +typedef struct uapi16_file_object uapi16_file_object; + +/** + * How to write a manifest: the features it records, the order of its + * file objects and whether a new file is synced. Made by + * uapi16_manifest_options_new(), which gives the default features and + * the code point order and does not sync, and freed by + * uapi16_manifest_options_free(). + */ +typedef struct uapi16_manifest_options uapi16_manifest_options; + +/** + * What a manifest lists, counted per file object: a file with three names + * counts three times. Made by uapi16_manifest_writer_finish() and the + * generate functions, and freed by uapi16_manifest_report_free(). + */ +typedef struct uapi16_manifest_report uapi16_manifest_report; + +/** + * Takes the files a manifest lists, and writes the manifest once it has + * them all. Made by uapi16_manifest_writer_create_at() and + * uapi16_manifest_writer_open(), and freed by + * uapi16_manifest_writer_free(). + * + * The manifest lists its file objects in the order of the options, + * whatever order the adds came in. Two equal file objects under one name + * are listed once. A directory added twice is listed with what the first + * add said of it. Two other files under one name, also a directory and a + * file that is none, are UAPI16_ERROR_DUPLICATE, from + * uapi16_manifest_writer_finish(). + * + * An add that fails leaves the writer as it was, as if the add had not + * been. + */ +typedef struct uapi16_manifest_writer uapi16_manifest_writer; + +/** + * Reads a manifest record by record, and checks it. Made by + * uapi16_reader_open(), and freed by uapi16_reader_free(). + * + * The reader checks every object against the rules of the specification, + * and where it comes: right after the object of its directory, and in the + * order the manifest declares. It keeps one record in memory, whatever the + * size of the manifest, and reads its descriptor once, so a manifest can + * come through a pipe. + * + * uapi16_reader_next() reads the file objects, and says what it read with + * a uapi16_read_t. It returns UAPI16_READ_END once it has read and checked + * the trailer: then the manifest is complete. Where signature objects + * follow the file objects, it returns UAPI16_READ_SIGNATURES first. A + * caller that wants them reads them with uapi16_reader_next_signature() + * then. A caller that does not goes on with uapi16_reader_next(), which + * passes over them. The signature objects are checked and not verified. + * + * Once one of the two failed to read an object, every later call of them + * fails with UAPI16_ERROR_ENDED. EAGAIN of a descriptor that does not + * block is the exception: the reader lost nothing, and reads on with the + * next call. + */ +typedef struct uapi16_reader uapi16_reader; + +/** + * Computes the SHA-256 hash of data that comes in pieces, such as the data + * of a file while it is copied into an image. Made by uapi16_sha256_new(), + * and freed by uapi16_sha256_free(). + */ +typedef struct uapi16_sha256 uapi16_sha256; + +/** + * A signature object: a signature over the manifest up to the first + * signature object. Made by uapi16_signature_new() and by + * uapi16_reader_next_signature(), and freed by uapi16_signature_free(). + * + * A manifest can carry several. The library reads and writes them, and + * neither makes nor verifies a signature: that takes an OpenPGP or an X.509 + * implementation. + */ +typedef struct uapi16_signature uapi16_signature; + +/** + * Writes a manifest record by record, for a caller that has its file + * objects in the order of the manifest already: every directory before + * what is in it, and the names of a directory in the order of their bytes. + * Made by uapi16_writer_begin(), and freed by uapi16_writer_free(). + * + * With options whose order is UAPI16_ORDER_NONE the manifest declares no + * order, and the file objects are written in the order of the caller. Each + * still comes right after the object of its directory. + * + * Every call writes its record before it returns, and nothing is kept on + * disk. A manifest without its trailer is one a reader takes as + * incomplete, so a writer that is freed before it finished leaves nothing + * that passes for a manifest. A write that fails ends the writer. + */ +typedef struct uapi16_writer uapi16_writer; + +/** + * A set of features that a program owns. UAPI16_FEATURES_EMPTY and + * UAPI16_FEATURES_SET() make one. + */ +typedef struct { + /** + * sizeof(uapi16_features_t), in bytes. + */ + uint64_t size; + /** + * The features: feature f is bit (f - 1) % 64 of word (f - 1) / 64. + */ + uint64_t words[UAPI16_FEATURES_WORDS]; +} uapi16_features_t; + +/** + * A set of uapi16_add_flag_t: their bitwise OR. + */ +typedef uint64_t uapi16_add_flags_t; + +/** + * A SHA-256 hash. + */ +typedef union { + uint8_t bytes[UAPI16_SHA256_SIZE]; + uint64_t qwords[UAPI16_SHA256_QWORDS]; +} uapi16_sha256_digest_t; + +/** + * The token of a file, see uapi16_file_object_set_inode_token(). + */ +typedef uint64_t uapi16_inode_token_t; + +/** + * A UUID, as the fs-uuid field carries one. + */ +typedef union { + uint8_t bytes[UAPI16_UUID_SIZE]; + uint64_t qwords[UAPI16_UUID_QWORDS]; +} uapi16_uuid_t; + +/** + * A set of uapi16_directory_flag_t: their bitwise OR. + */ +typedef uint64_t uapi16_directory_flags_t; + +/** + * The number that is no token, see uapi16_file_object_set_inode_token(). + */ +#define UAPI16_INODE_TOKEN_NONE 0 + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/** + * Makes options with the default features, the code point order and no + * syncing. The default features are those of a manifest that lists none: + * UAPI16_FEATURE_MODE, UAPI16_FEATURE_UID, UAPI16_FEATURE_GID, + * UAPI16_FEATURE_SIZE, UAPI16_FEATURE_SHA256, UAPI16_FEATURE_SYMLINK, + * UAPI16_FEATURE_DEVICE and UAPI16_FEATURE_HARDLINK. They are freed with + * uapi16_manifest_options_free(). + */ +uapi16_manifest_options *uapi16_manifest_options_new(void); + +/** + * Sets the features to record to those of the set `s`, and no others. The + * features of partitions are taken here, and refused when a manifest writer + * is made. + */ +UAPI16_NODISCARD +int uapi16_manifest_options_set_features(uapi16_manifest_options *o, + const uapi16_features_t *s); + +/** + * Sets the order of the file objects. UAPI16_ORDER_CODEPOINT is the only + * one. UAPI16_ORDER_NONE is taken too, for a manifest that declares no + * order, and any other number fails with -EINVAL. + */ +UAPI16_NODISCARD +int uapi16_manifest_options_set_order(uapi16_manifest_options *o, + uapi16_order_t order); + +/** + * Sets whether the new file of uapi16_manifest_writer_create_at() and + * uapi16_manifest_generate_at() is written to disk before + * uapi16_manifest_writer_finish() or uapi16_manifest_generate_at() + * returns, so that a crash after that does not lose it. It is off unless + * set. + * + * The file is synced before it gets its name, so that the name never + * leads to a manifest that is not all on disk, and once more after it got + * it, with the directory it is in, so that the name is on disk as well. + * Nothing else is synced: uapi16_manifest_writer_open() and + * uapi16_manifest_generate() write to a descriptor of the caller, which + * the caller syncs. + */ +UAPI16_NODISCARD int uapi16_manifest_options_set_sync(uapi16_manifest_options *o, bool sync); + +/** + * Frees options. NULL is fine. Returns NULL, so that + * `o = uapi16_manifest_options_free(o);` clears the pointer. A writer + * that was made with them does not need them any more. + */ +uapi16_manifest_options *uapi16_manifest_options_free(uapi16_manifest_options *o); + +/** + * Writes the manifest of the directory `top_fd` and everything below it + * to a new file `name` in the directory `dir_fd`, and stores a report of + * what it lists in `ret`, unless that is NULL. It is + * uapi16_manifest_writer_create_at(), a walk of `top_fd` as the root, and + * uapi16_manifest_writer_finish() in one call. `name` is what + * uapi16_manifest_writer_create_at() takes, and `flags` is a set of + * uapi16_add_flag_t. The manifest is sorted, so options whose order is + * UAPI16_ORDER_NONE fail with -EINVAL. + * + * Symbolic links are recorded and never followed. Mount points are not + * crossed unless UAPI16_ADD_CROSS_MOUNTS is given: one that is a + * directory is written as an empty directory. The walk mounts nothing: an + * automount point that nothing is mounted on yet is written as an empty + * directory with its own attributes, with any flags. There is one known + * limit. The walk looks at a directory before it opens it, and a + * directory that becomes an automount point in between has its file + * system mounted by that open. The walk fails with UAPI16_ERROR_CHANGED + * then. That takes someone who can mount in the mount namespace of the + * caller, or an automount unit that is started at that moment. + * + * A file that changes while it is read fails with UAPI16_ERROR_CHANGED, + * where its size, its times or its number of links show the change. + * + * Where the features record UAPI16_FEATURE_FLAG_HIDDEN, + * UAPI16_FEATURE_FLAG_SYSTEM or UAPI16_FEATURE_FLAG_ARCHIVE, a tree on a + * file system without DOS attributes fails before anything is read. + * + * The data of a regular file of more than 1 TiB is not hashed. Where the + * manifest records hashes, or hard links and the file has more than one + * name, the walk fails at such a file with UAPI16_ERROR_IO and EFBIG, + * before anything is read of it. + * + * A walk of the directory the new file is in passes over what the + * manifest keeps there, and over the new file under its temporary name. + * On a file system without O_TMPFILE, such as FAT, a manifest that is + * created inside the tree it describes can make the walk of a large tree + * fail with UAPI16_ERROR_CHANGED, since the room it takes changes its own + * directory while the walk reads it. + */ +UAPI16_NODISCARD +int uapi16_manifest_generate_at(const uapi16_manifest_options *o, + int dir_fd, + const char *name, + int top_fd, + uapi16_add_flags_t flags, + uapi16_manifest_report **ret, + uapi16_error **reterr); + +/** + * Writes the manifest of the directory `top_fd` and everything below it + * to the descriptor `fd`, and stores a report of what it lists in `ret`, + * unless that is NULL. It is uapi16_manifest_writer_open(), a walk of + * `top_fd` as the root, and uapi16_manifest_writer_finish() in one call. + * `flags` is a set of uapi16_add_flag_t, and the walk is the one of + * uapi16_manifest_generate_at(). The manifest is sorted, so options whose + * order is UAPI16_ORDER_NONE fail with -EINVAL. + */ +UAPI16_NODISCARD +int uapi16_manifest_generate(const uapi16_manifest_options *o, + int fd, + int top_fd, + uapi16_add_flags_t flags, + uapi16_manifest_report **ret, + uapi16_error **reterr); + +/** + * Makes a writer for a new manifest file `name` in the directory + * `dir_fd`, and stores it in `ret`. The file appears when + * uapi16_manifest_writer_finish() gives it its name, with the whole + * manifest in it. Until then nothing has the name, and a writer that is + * freed instead leaves nothing behind. The writer sorts, so options whose + * order is UAPI16_ORDER_NONE fail with -EINVAL. + * + * The writer borrows `dir_fd` until it is freed: the caller keeps it open + * until then, and closes it itself. + * + * `name` is a path, and is taken as the bytes it is, which need not be + * UTF-8. One with more than one component names a file in a directory + * below `dir_fd`. The components on the way are opened one at a time, + * each without following a symbolic link, and the file goes into the + * directory its last component is in. A symbolic link on the way fails + * with -ELOOP, and anything else on the way that is no directory with + * -ENOTDIR. A name that names no file below `dir_fd` fails with -EINVAL + * before anything is looked up: one that is empty or that ends in a + * slash, "." or "..", an absolute one, and one with "." or ".." on the + * way. For a file in a directory that is not below `dir_fd`, open that + * directory and pass it as `dir_fd`. + * + * This never replaces a file: where something has the name already, it + * fails with UAPI16_ERROR_EXISTS. The name is checked again when the file + * gets it. To write over a file, open it and use + * uapi16_manifest_writer_open(). + * + * On FAT the new file gets the mode the mount gives every file, and it + * can't be larger than 4 GiB, so a manifest there holds about 2e7 file + * objects at most: uapi16_manifest_writer_finish() fails with EFBIG for + * more. A tree with more than about 9e6 files that have several names + * fails with EFBIG already while it is added. + * + * The manifest of a large tree takes room on disk while it is built, in + * the directory the file goes to. On a file system without O_TMPFILE, such + * as FAT, the new file is in that directory under a temporary name until + * uapi16_manifest_writer_finish(). + */ +UAPI16_NODISCARD +int uapi16_manifest_writer_create_at(const uapi16_manifest_options *o, + int dir_fd, + const char *name, + uapi16_manifest_writer **ret, + uapi16_error **reterr); + +/** + * Makes a writer for a manifest that is written to the descriptor `fd`, + * and stores it in `ret`. Nothing is written before + * uapi16_manifest_writer_finish(), and the manifest is complete once that + * returns 0. The writer borrows `fd` until it is freed: the caller keeps it + * open until then, and closes it itself. The writer sorts, so options whose + * order is UAPI16_ORDER_NONE fail with -EINVAL. + * + * The manifest of a large tree takes room on disk while it is built, in + * the directory TMPDIR names, or in /var/tmp where it names none. Where it + * is on FAT, which can't hold a file of more than 4 GiB, a manifest of + * more than about 3e7 file objects fails with EFBIG, and a tree with + * more than about 9e6 files that have several names fails with EFBIG + * already while it is added. A TMPDIR that is set is used as it is. It has + * to be a directory the caller trusts, since whoever controls it can + * change the manifest. + */ +UAPI16_NODISCARD +int uapi16_manifest_writer_open(const uapi16_manifest_options *o, + int fd, + uapi16_manifest_writer **ret, + uapi16_error **reterr); + +/** + * Adds the file object `o`. It is checked as a writer of records checks a + * file object, but for where it comes, which + * uapi16_manifest_writer_finish() checks. An object that is refused is not + * added, and the writer is as it was. The writer keeps a copy: the caller + * can change the object, add it again under another name, or free it. + * + * The objects can come in any order. The object with the empty name is the + * root, and says what the root directory and its file system are like. A + * root with a validity, a validity window or a GPT disk UUID, which only a + * root that a reader read can have, is refused, since this writer writes + * none of them. uapi16_writer_begin() writes them. The first object of a + * directory says what the directory is like. Two equal objects of one name + * are listed once, and two that differ and are not both directories are + * UAPI16_ERROR_DUPLICATE, from uapi16_manifest_writer_finish(). + * + * Objects with the same token are names of one file, and say the same + * about it. One that does not fails the add with + * UAPI16_ERROR_HARDLINK_MISMATCH, and uapi16_error_hardlink_path() names the + * first of them. + */ +UAPI16_NODISCARD +int uapi16_manifest_writer_add_object(uapi16_manifest_writer *w, + const uapi16_file_object *o, + uapi16_error **reterr); + +/** + * Writes the manifest, and stores a report of what it lists in `ret`, + * unless that is NULL. With uapi16_manifest_writer_create_at() the file + * gets its name now, unless something took the name since, which is + * UAPI16_ERROR_EXISTS. Where something fails once the file has its name, + * such as the sync of its directory, the file keeps the name, and the + * call fails all the same. + * + * What the adds left open fails here: two different files under one + * name, a directory that was not added where the features need it, a file + * that is not a directory and that files were added below, and a record + * that is too large. + * + * The writer is finished after this, whether it succeeded or failed. + * Every later add and finish on it fails with UAPI16_ERROR_ENDED, and + * uapi16_manifest_writer_free() frees it. + */ +UAPI16_NODISCARD +int uapi16_manifest_writer_finish(uapi16_manifest_writer *w, + uapi16_manifest_report **ret, + uapi16_error **reterr); + +/** + * Frees a writer. One that was not finished writes nothing and leaves no + * file behind. NULL is fine. Returns NULL. The descriptor of the caller + * stays open. + */ +uapi16_manifest_writer *uapi16_manifest_writer_free(uapi16_manifest_writer *w); + +/** + * How many regular files the manifest lists. 0 for NULL, as for every + * function of a report. + */ +uint64_t uapi16_manifest_report_files(const uapi16_manifest_report *r); + +/** + * How many directories the manifest lists, the root among them. + */ +uint64_t uapi16_manifest_report_directories(const uapi16_manifest_report *r); + +/** + * How many other files the manifest lists: symbolic links, FIFOs, device + * nodes and sockets. + */ +uint64_t uapi16_manifest_report_others(const uapi16_manifest_report *r); + +/** + * The sizes of the regular files, added up. The data of a file with more + * than one name counts for each. + */ +uint64_t uapi16_manifest_report_bytes(const uapi16_manifest_report *r); + +/** + * How many files UAPI16_ADD_GRACEFUL left out, a directory with everything + * below it as one. + */ +uint64_t uapi16_manifest_report_entries_omitted(const uapi16_manifest_report *r); + +/** + * How many fields were left out of the file objects: the names of owners + * that the user database does not have, the user and group IDs 65535 and + * 4294967295, modification times before 1970 or after 2554, and the UUID + * or the volume serial number of a file system that gives none. + */ +uint64_t uapi16_manifest_report_fields_omitted(const uapi16_manifest_report *r); + +/** + * Frees a report. NULL is fine. Returns NULL. + */ +uapi16_manifest_report *uapi16_manifest_report_free(uapi16_manifest_report *r); + +/** + * Starts to read a manifest from the descriptor `fd`, reads its root, and + * stores the reader in `ret`. The reader borrows `fd` until it is freed: + * the caller keeps it open until then, and closes it itself. On a + * descriptor that does not block, EAGAIN fails the open and loses what it + * read, so the descriptor has to block, or already hold the root and the + * start of the next record. + */ +UAPI16_NODISCARD int uapi16_reader_open(int fd, uapi16_reader **ret, uapi16_error **reterr); + +/** + * The root of the manifest: an object with the empty name. It belongs to + * the reader and lives until the reader is freed. NULL for NULL. + */ +const uapi16_file_object *uapi16_reader_root(const uapi16_reader *r); + +/** + * Whether the manifest records the feature `feature`. A manifest that lists + * no features records the default features. false for a number that is no + * feature, and for NULL. + */ +bool uapi16_reader_has_feature(const uapi16_reader *r, uapi16_feature_t feature); + +/** + * Stores the features the manifest records in `ret`. + */ +UAPI16_NODISCARD int uapi16_reader_features(const uapi16_reader *r, uapi16_features_t *ret); + +/** + * The order the manifest declares, or UAPI16_ORDER_NONE where it declares + * none. + */ +uapi16_order_t uapi16_reader_order(const uapi16_reader *r); + +/** + * Requires the manifest to declare the order `order`, as a caller does + * that relies on it. A manifest that does not fails with + * UAPI16_ERROR_MANIFEST, even if its file objects are in that order. The + * reader checks the file objects against the order the manifest declares + * while it reads them. UAPI16_ORDER_NONE is no order to require, and fails + * with -EINVAL. + */ +UAPI16_NODISCARD +int uapi16_reader_require_order(const uapi16_reader *r, + uapi16_order_t order, + uapi16_error **reterr); + +/** + * Checks that the manifest may be used at the time `now_usec`, in + * microseconds since 1970: that its root is not revoked and that the time + * is inside its validity window. + */ +UAPI16_NODISCARD +int uapi16_reader_check_validity(const uapi16_reader *r, + uint64_t now_usec, + uapi16_error **reterr); + +/** + * Reads on, and returns what it read as a uapi16_read_t, or a negative + * errno: + * + * - UAPI16_READ_FILE: one file object, which is in `*ret`. + * - UAPI16_READ_SIGNATURES: the file objects have ended, and signature + * objects follow. The next call passes over them, and checks them. + * - UAPI16_READ_END: the trailer was read and checked, and the manifest is + * complete. Every later call returns this again. + * + * `ret` points to NULL or to a file object of the caller. Where it points + * to NULL, a file object that is read is stored there as a new object. + * Where it points to an object, that object is cleared and filled again, + * and nothing of what it held before is left: the strings and bytes its + * getters returned before are gone with it. So one object serves a whole + * loop, as the buffer of getline() does. A call that reads no file object + * leaves `*ret` as it is. The object stays the caller's, to free with + * uapi16_file_object_free(), also after a call that failed. + */ +UAPI16_NODISCARD +int uapi16_reader_next(uapi16_reader *r, + uapi16_file_object **ret, + uapi16_error **reterr); + +/** + * Reads the next signature object, and returns what it read as a + * uapi16_read_t, or a negative errno: + * + * - UAPI16_READ_SIGNATURE: one signature object, which is in `*ret`. + * - UAPI16_READ_END: the trailer was read and checked, and the manifest is + * complete. Every later call returns this again. + * + * The signature objects come after the file objects: a call before + * uapi16_reader_next() returned UAPI16_READ_SIGNATURES or UAPI16_READ_END + * fails with -EINVAL. `ret` points to NULL or to a signature object of the + * caller, and is used as uapi16_reader_next() uses its `ret`. The object is + * freed with uapi16_signature_free(). + */ +UAPI16_NODISCARD +int uapi16_reader_next_signature(uapi16_reader *r, + uapi16_signature **ret, + uapi16_error **reterr); + +/** + * Stores in `ret` how many bytes at the start of the manifest its signature + * objects sign: all that comes before the record of the first of them, up + * to its record separator. -ENODATA before uapi16_reader_next() returned + * UAPI16_READ_SIGNATURES, and so for a manifest without signature objects. + * + * The library does not verify signatures. With this number and the + * signature objects a caller can. + */ +UAPI16_NODISCARD int uapi16_reader_signed_len(const uapi16_reader *r, uint64_t *ret); + +/** + * Frees a reader, and its root with it. NULL is fine. Returns NULL. The + * descriptor of the caller stays open. + */ +uapi16_reader *uapi16_reader_free(uapi16_reader *r); + +/** + * Starts a manifest on the descriptor `fd` with the root `root`, and stores + * the writer in `ret`. The features and the order are those of the options + * `o`, and options with UAPI16_ORDER_NONE make a manifest that declares no + * order. `root` is an object with the empty name, or NULL for a root that + * says nothing. The writer borrows `fd` until it is freed: the caller keeps + * it open until then, and closes it itself. + */ +UAPI16_NODISCARD +int uapi16_writer_begin(const uapi16_manifest_options *o, + int fd, + const uapi16_file_object *root, + uapi16_writer **ret, + uapi16_error **reterr); + +/** + * Writes the file object `o`. The writer checks it as a reader does: it has + * no field of a feature the manifest does not record, it comes right after + * the object of its directory, and it keeps to the order. An object that is + * refused is not written, and the writer goes on as if it had not been + * given it. + * + * In a manifest that declares no order, the order of the names is not + * checked. A name that comes again right after the entries of the directory + * it names is still refused. One that comes again later is not found. + */ +UAPI16_NODISCARD +int uapi16_writer_file(uapi16_writer *w, + const uapi16_file_object *o, + uapi16_error **reterr); + +/** + * Writes the signature object `s`. No file object can follow it: it would + * be one the signature does not cover. The signature objects of a manifest + * sign the manifest up to the first of them, which is all that the writer + * wrote to its descriptor before the first call of this. + */ +UAPI16_NODISCARD +int uapi16_writer_signature(uapi16_writer *w, + const uapi16_signature *s, + uapi16_error **reterr); + +/** + * Ends the manifest with its trailer. The writer is finished after this, + * whether it succeeded or failed: every later call on it fails with + * UAPI16_ERROR_ENDED, and uapi16_writer_free() frees it. + */ +UAPI16_NODISCARD int uapi16_writer_finish(uapi16_writer *w, uapi16_error **reterr); + +/** + * Frees a writer of records. NULL is fine. Returns NULL. The descriptor of + * the caller stays open. + */ +uapi16_writer *uapi16_writer_free(uapi16_writer *w); + +/** + * Makes a signature object of the mechanism `mechanism`, without a key and + * without data, and stores it in `ret`. The specification has "openpgp" and + * "pkcs7". + */ +UAPI16_NODISCARD int uapi16_signature_new(const char *mechanism, uapi16_signature **ret); + +/** + * How the signature was made: its mechanism. NULL for NULL. The string + * belongs to the object. + */ +const char *uapi16_signature_mechanism(const uapi16_signature *s); + +/** + * Sets what identifies the key, such as its fingerprint: the `size` bytes + * at `key`. A `key` of NULL takes it away. + */ +UAPI16_NODISCARD int uapi16_signature_set_key(uapi16_signature *s, const void *key, size_t size); + +/** + * What identifies the key, and its size in `ret_size`, unless that is NULL. + * No NUL ends the bytes. NULL and 0 where the object has none. The bytes + * belong to the object. + */ +const void *uapi16_signature_key(const uapi16_signature *s, size_t *ret_size); + +/** + * Sets the signature: the `size` bytes at `data`. A `data` of NULL takes it + * away. + */ +UAPI16_NODISCARD int uapi16_signature_set_data(uapi16_signature *s, const void *data, size_t size); + +/** + * The signature, and its size in `ret_size`, unless that is NULL. No NUL + * ends the bytes. NULL and 0 where the object has none. The bytes belong to + * the object. + */ +const void *uapi16_signature_data(const uapi16_signature *s, size_t *ret_size); + +/** + * Frees a signature object. NULL is fine. Returns NULL. + */ +uapi16_signature *uapi16_signature_free(uapi16_signature *s); + +/** + * Makes a file object for the regular file `name` that says nothing else + * about it, and stores it in `ret`. `name` is the path of the file below + * the root of the tree, as a manifest has it: components separated by + * single slashes, none of them empty, "." or "..". The empty string makes + * the root. A name that a manifest can't hold fails with + * UAPI16_ERROR_INVALID_ARGUMENT, and uapi16_error_name_problem() says which + * rule it breaks. + */ +UAPI16_NODISCARD +int uapi16_file_object_new(const char *name, + uapi16_file_object **ret, + uapi16_error **reterr); + +/** + * Frees a file object. NULL is fine. Returns NULL. An object of + * uapi16_reader_root() belongs to its reader and is not freed with this. + */ +uapi16_file_object *uapi16_file_object_free(uapi16_file_object *o); + +/** + * Gives the object the name `name`, which uapi16_file_object_new() checks + * the same way. The names of one file carry the same fields: a caller adds + * the object under one name, sets the next name and adds it again. A name + * that is refused leaves the object as it was. The root keeps its name, and + * no other object takes the empty one: both fail with -EINVAL. + */ +UAPI16_NODISCARD +int uapi16_file_object_set_name(uapi16_file_object *o, + const char *name, + uapi16_error **reterr); + +/** + * The name of the file: its path below the root. The root is the empty + * string. NULL for NULL. The string belongs to the object and lives until + * the name is set again or the object is freed. + */ +const char *uapi16_file_object_name(const uapi16_file_object *o); + +/** + * Sets the type of the file from an `st_mode` as stat() gives it: S_IFREG, + * S_IFDIR, S_IFLNK, S_IFIFO, S_IFCHR, S_IFBLK or S_IFSOCK. Only the bits of + * the file type are read, and bits that are none of these fail with + * -EINVAL. The root is a directory: S_IFDIR is fine for it, and any other + * type fails with -EINVAL. + */ +UAPI16_NODISCARD int uapi16_file_object_set_type(uapi16_file_object *o, uint32_t st_mode); + +/** + * The type of the file, as the bits of the file type in an `st_mode`. An + * object that was given none is a regular file. 0 for NULL. + */ +uint32_t uapi16_file_object_type(const uapi16_file_object *o); + +/** + * Sets the access mode from an `st_mode` as stat() gives it: the permission + * bits with the set-user-ID, the set-group-ID and the sticky bit. The bits + * of the file type are not read. + */ +UAPI16_NODISCARD int uapi16_file_object_set_mode(uapi16_file_object *o, uint32_t st_mode); + +/** + * Stores the access mode in `ret`: the permission bits with the + * set-user-ID, the set-group-ID and the sticky bit, and no bits of a file + * type. + */ +UAPI16_NODISCARD int uapi16_file_object_mode(const uapi16_file_object *o, uint32_t *ret); + +/** + * Sets the user ID of the owner. + */ +UAPI16_NODISCARD int uapi16_file_object_set_uid(uapi16_file_object *o, uint32_t uid); + +/** + * Stores the user ID of the owner in `ret`. + */ +UAPI16_NODISCARD int uapi16_file_object_uid(const uapi16_file_object *o, uint32_t *ret); + +/** + * Sets the group ID of the owner. + */ +UAPI16_NODISCARD int uapi16_file_object_set_gid(uapi16_file_object *o, uint32_t gid); + +/** + * Stores the group ID of the owner in `ret`. + */ +UAPI16_NODISCARD int uapi16_file_object_gid(const uapi16_file_object *o, uint32_t *ret); + +/** + * Sets the name of the owning user. + */ +UAPI16_NODISCARD int uapi16_file_object_set_user_name(uapi16_file_object *o, const char *name); + +/** + * The name of the owning user, or NULL where the object has none. The + * string belongs to the object. + */ +const char *uapi16_file_object_user_name(const uapi16_file_object *o); + +/** + * Sets the name of the owning group. + */ +UAPI16_NODISCARD int uapi16_file_object_set_group_name(uapi16_file_object *o, const char *name); + +/** + * The name of the owning group, or NULL where the object has none. The + * string belongs to the object. + */ +const char *uapi16_file_object_group_name(const uapi16_file_object *o); + +/** + * Sets the modification time, in nanoseconds since 1970. + */ +UAPI16_NODISCARD int uapi16_file_object_set_mtime_nsec(uapi16_file_object *o, uint64_t nsec); + +/** + * Stores the modification time in `ret`, in nanoseconds since 1970. + */ +UAPI16_NODISCARD int uapi16_file_object_mtime_nsec(const uapi16_file_object *o, uint64_t *ret); + +/** + * Sets the size of the data in bytes. For a symbolic link that is the + * length of its target. + */ +UAPI16_NODISCARD int uapi16_file_object_set_size(uapi16_file_object *o, uint64_t size); + +/** + * Stores the size of the data in `ret`, in bytes. + */ +UAPI16_NODISCARD int uapi16_file_object_size(const uapi16_file_object *o, uint64_t *ret); + +/** + * Sets the SHA-256 hash of the data to the one at `sha256`. + */ +UAPI16_NODISCARD +int uapi16_file_object_set_sha256(uapi16_file_object *o, + const uapi16_sha256_digest_t *sha256); + +/** + * Stores the SHA-256 hash of the data in `ret`. + */ +UAPI16_NODISCARD +int uapi16_file_object_sha256(const uapi16_file_object *o, + uapi16_sha256_digest_t *ret); + +/** + * Sets the major number of a device node. + */ +UAPI16_NODISCARD int uapi16_file_object_set_major(uapi16_file_object *o, uint64_t major); + +/** + * Stores the major number of a device node in `ret`. + */ +UAPI16_NODISCARD int uapi16_file_object_major(const uapi16_file_object *o, uint64_t *ret); + +/** + * Sets the minor number of a device node. + */ +UAPI16_NODISCARD int uapi16_file_object_set_minor(uapi16_file_object *o, uint64_t minor); + +/** + * Stores the minor number of a device node in `ret`. + */ +UAPI16_NODISCARD int uapi16_file_object_minor(const uapi16_file_object *o, uint64_t *ret); + +/** + * Sets the token of the file. The objects that carry the same token are + * names of one file. Any number but 0 is a token, and + * UAPI16_INODE_TOKEN_NONE takes the token away. + * uapi16_manifest_writer_add_object() takes the numbers of the caller as + * they are and gives the files the numbers the specification asks for. + * uapi16_writer_file() writes the token as it is, so its caller numbers the + * files itself: from 1, in the order they first come in the manifest. + */ +UAPI16_NODISCARD +int uapi16_file_object_set_inode_token(uapi16_file_object *o, + uapi16_inode_token_t token); + +/** + * Stores the token of the file in `ret`. -ENODATA where the object has + * none: a file of no other name. + */ +UAPI16_NODISCARD +int uapi16_file_object_inode_token(const uapi16_file_object *o, + uapi16_inode_token_t *ret); + +/** + * Makes the object list its extended attributes of the user namespace, and + * lists none: the file has none, until uapi16_file_object_add_user_xattr() + * adds one. An object that does not list them says nothing about them. + */ +UAPI16_NODISCARD int uapi16_file_object_set_user_xattrs(uapi16_file_object *o); + +/** + * Adds the extended attribute `name` of the user namespace with the `size` + * bytes at `value` as its value, or gives it that value where the object + * lists it already. `name` is the name without "user." in front. The object + * lists its extended attributes after this. + */ +UAPI16_NODISCARD +int uapi16_file_object_add_user_xattr(uapi16_file_object *o, + const char *name, + const void *value, + size_t size); + +/** + * Stores in `ret_count` how many extended attributes of the user namespace + * the object lists. -ENODATA where it says nothing about them. + */ +UAPI16_NODISCARD int uapi16_file_object_user_xattrs(const uapi16_file_object *o, size_t *ret_count); + +/** + * Stores the name, the value and the size of the value of the extended + * attribute number `i`, counting from 0 in the order of the names. The name + * comes without "user." in front, and no NUL ends the value. Each of the + * three can be NULL. An `i` that is not below the count of + * uapi16_file_object_user_xattrs() fails with -EINVAL. The name and the + * value belong to the object and live until it is changed or freed. + */ +UAPI16_NODISCARD +int uapi16_file_object_user_xattr(const uapi16_file_object *o, + size_t i, + const char **ret_name, + const void **ret_value, + size_t *ret_size); + +/** + * Sets whether the file is read-only: UAPI16_READ_ONLY_YES or + * UAPI16_READ_ONLY_NO. UAPI16_READ_ONLY_UNSTATED takes the field away. Any + * other number fails with -EINVAL. The field stands for the read-only + * attribute of DOS too. + */ +UAPI16_NODISCARD +int uapi16_file_object_set_read_only(uapi16_file_object *o, + uapi16_read_only_t read_only); + +/** + * Whether the file is read-only. UAPI16_READ_ONLY_UNSTATED where the object + * does not say, and for NULL. + */ +uapi16_read_only_t uapi16_file_object_read_only(const uapi16_file_object *o); + +/** + * Sets the Linux inode flags, as the bits FS_IOC_GETFLAGS gives. `stated` + * has the flags the object says something about, and `set` those of them + * that are set. A manifest has FS_APPEND_FL, FS_IMMUTABLE_FL, FS_NOATIME_FL, + * FS_NOCOW_FL and FS_NODUMP_FL. Other bits are not read. A flag that is not + * in `stated` is taken away from the object. + */ +UAPI16_NODISCARD +int uapi16_file_object_set_inode_flags(uapi16_file_object *o, + uint32_t stated, + uint32_t set); + +/** + * Stores the Linux inode flags the object says something about in + * `ret_stated`, and those of them that are set in `ret_set`, as the bits + * FS_IOC_GETFLAGS gives. Either can be NULL. An object that says nothing + * about any flag stores 0 in both. + */ +UAPI16_NODISCARD +int uapi16_file_object_inode_flags(const uapi16_file_object *o, + uint32_t *ret_stated, + uint32_t *ret_set); + +/** + * Sets the DOS attributes hidden, system and archive, as the bits a + * directory entry of FAT has: 0x02, 0x04 and 0x20. `stated` has the + * attributes the object says something about, and `set` those of them that + * are set. Other bits are not read. An attribute that is not in `stated` is + * taken away from the object. The read-only attribute is + * uapi16_file_object_set_read_only(). + */ +UAPI16_NODISCARD +int uapi16_file_object_set_dos_attributes(uapi16_file_object *o, + uint32_t stated, + uint32_t set); + +/** + * Stores the DOS attributes the object says something about in + * `ret_stated`, and those of them that are set in `ret_set`, as the bits a + * directory entry of FAT has. Either can be NULL. An object that says + * nothing about any of them stores 0 in both. + */ +UAPI16_NODISCARD +int uapi16_file_object_dos_attributes(const uapi16_file_object *o, + uint32_t *ret_stated, + uint32_t *ret_set); + +/** + * Sets the target of a symbolic link: the `size` bytes at `target`, which + * need not be UTF-8 and which no NUL ends. The manifest carries the target + * itself. On a regular file they are the data of the file, which the + * manifest carries the same way. + */ +UAPI16_NODISCARD +int uapi16_file_object_set_target(uapi16_file_object *o, + const void *target, + size_t size); + +/** + * Says that the data of the file is in the file `file` next to the + * manifest, under another name than its own. `file` is a name as + * uapi16_file_object_new() takes one, but for the empty one. A name that is + * none fails as it does there. Without this, the data of a regular file is + * in the file of its own name next to the manifest. + */ +UAPI16_NODISCARD +int uapi16_file_object_set_contents_file(uapi16_file_object *o, + const char *file, + uapi16_error **reterr); + +/** + * The file the data of `o` is in, where that is another file than the one + * of its own name, and where the data starts in it. -ENODATA where the + * object names no such file. Both `ret_file` and `ret_offset` are needed: a + * NULL one fails with -EINVAL. + */ +UAPI16_NODISCARD +int uapi16_file_object_contents_file(const uapi16_file_object *o, + const char **ret_file, + uint64_t *ret_offset); + +/** + * Where the data of the file is: the bytes of a regular file or the target + * of a symbolic link. A literal is taken first. Otherwise the data is in + * the file next to the manifest that the object refers to, or in the file + * of its own name where it is a regular file and refers to none. + * UAPI16_DATA_LOCATION_NONE for an object without data, and for NULL. + */ +uapi16_data_location_t uapi16_file_object_data_location(const uapi16_file_object *o); + +/** + * The data of the file where the manifest carries it itself, such as the + * target of a symbolic link, and its size in `ret_size`, unless that is + * NULL. Where the object gives a size, the data is that many bytes. No NUL + * ends the bytes. NULL and 0 where the data is not in the manifest. The + * bytes belong to the object. + */ +const void *uapi16_file_object_literal(const uapi16_file_object *o, size_t *ret_size); + +/** + * Sets the label of the file system. Only the root has one. + */ +UAPI16_NODISCARD int uapi16_file_object_set_fs_label(uapi16_file_object *o, const char *label); + +/** + * The label of the file system, or NULL where the object has none. The + * string belongs to the object. + */ +const char *uapi16_file_object_fs_label(const uapi16_file_object *o); + +/** + * Sets the UUID of the file system to the one at `uuid`. Only the root has + * one. + */ +UAPI16_NODISCARD +int uapi16_file_object_set_fs_uuid(uapi16_file_object *o, + const uapi16_uuid_t *uuid); + +/** + * Stores the UUID of the file system in `ret`. + */ +UAPI16_NODISCARD int uapi16_file_object_fs_uuid(const uapi16_file_object *o, uapi16_uuid_t *ret); + +/** + * Sets the volume serial number of a FAT or exFAT file system. Only the + * root has one. + */ +UAPI16_NODISCARD int uapi16_file_object_set_fat_serial(uapi16_file_object *o, uint32_t serial); + +/** + * Stores the volume serial number of a FAT or exFAT file system in `ret`. + */ +UAPI16_NODISCARD int uapi16_file_object_fat_serial(const uapi16_file_object *o, uint32_t *ret); + +/** + * Whether the object has the fields of the feature `feature`. A manifest + * records every such feature, or the object is not one of its file objects. + * What a reader filled in does not count. false for a number that is no + * feature, and for NULL. + */ +bool uapi16_file_object_has_stated_feature(const uapi16_file_object *o, uapi16_feature_t feature); + +/** + * Stores the features whose fields the object has in `ret`, as + * uapi16_file_object_has_stated_feature() counts them. + */ +UAPI16_NODISCARD +int uapi16_file_object_stated_features(const uapi16_file_object *o, + uapi16_features_t *ret); + +/** + * Takes away the fields of every feature that is not in the set `s`. So a + * caller sets all it knows of a file and keeps what its manifest records. + * The name, the type and what belongs to no feature stay. The target of a + * symbolic link goes without UAPI16_FEATURE_SYMLINK. The data a manifest + * carries of a regular file and the file its data is in belong to no + * feature, and stay. An object whose data starts at an offset in a file + * reaches to the end of it once its size goes, and a hash that stays no + * longer fits. + */ +UAPI16_NODISCARD +int uapi16_file_object_retain_features(uapi16_file_object *o, + const uapi16_features_t *s); + +/** + * Checks that the object may be used at the time `now_usec`, in + * microseconds since 1970: that it is not revoked and that the time is + * inside its validity window. The check looks at the object alone. A caller + * that uses a file checks the objects of the directories it is in as well, + * which come before it in the manifest. + */ +UAPI16_NODISCARD +int uapi16_file_object_check_validity(const uapi16_file_object *o, + uint64_t now_usec, + uapi16_error **reterr); + +/** + * Makes a directory from the descriptor `dir_fd`, which may be opened with + * O_PATH, and stores it in `ret`. `flags` is a set of + * uapi16_directory_flag_t. The directory borrows `dir_fd` until it is + * freed: the caller keeps it open until then, and closes it itself. + */ +UAPI16_NODISCARD +int uapi16_directory_new(int dir_fd, + uapi16_directory_flags_t flags, + uapi16_directory **ret, + uapi16_error **reterr); + +/** + * Opens the file the data of `o` is in, for reading, and stores a new + * descriptor in `ret_fd`, which the caller closes. The descriptor is open + * for reading, and blocks as a regular file does. Where the data starts in + * the file is stored in `ret_offset`. Both `ret_fd` and `ret_offset` are + * needed: a NULL one fails with -EINVAL. The data is as long as the object + * says, or reaches to the end of the file where the object gives no size. + * + * The file is a regular file. One that is not there fails with + * UAPI16_ERROR_SOURCE_MISSING, one that is no regular file with + * UAPI16_ERROR_SOURCE_NOT_REGULAR, one that can't be opened with + * UAPI16_ERROR_IO and the errno of the system call, such as ELOOP for a + * symbolic link on the way, and one that is too short for the data, or of + * another size than the manifest gives for the file, with + * UAPI16_ERROR_SIZE_MISMATCH. An object whose data is not in a file, see + * uapi16_file_object_data_location(), fails with UAPI16_ERROR_UNSUPPORTED. + * + * The caller checks what it reads with a uapi16_data_check. A file can hold + * the data of several file objects. Where the manifest gives a hash for + * the whole file and none for the object, the data of the object is not + * checked against it. + */ +UAPI16_NODISCARD +int uapi16_directory_open_data(const uapi16_directory *d, + const uapi16_file_object *o, + int *ret_fd, + uint64_t *ret_offset, + uapi16_error **reterr); + +/** + * Frees a directory. NULL is fine. Returns NULL. The descriptor of the + * caller stays open, and so do those that uapi16_directory_open_data() + * stored. + */ +uapi16_directory *uapi16_directory_free(uapi16_directory *d); + +/** + * Makes a check of the data of `o`, of which nothing has passed yet, and + * stores it in `ret`. The check keeps what it needs of the object, which + * can be changed or freed after the call. + */ +UAPI16_NODISCARD int uapi16_data_check_new(const uapi16_file_object *o, uapi16_data_check **ret); + +/** + * Takes the `size` bytes at `data` as the next bytes of the data. Fails + * with UAPI16_ERROR_SIZE_MISMATCH, and takes none of them, where they + * would make the data larger than the size the object gives. + */ +UAPI16_NODISCARD +int uapi16_data_check_update(uapi16_data_check *c, + const void *data, + size_t size, + uapi16_error **reterr); + +/** + * Takes `size` zero bytes as the next bytes of the data, such as a hole of + * a sparse file that the caller did not read. Fails as + * uapi16_data_check_update() does. + */ +UAPI16_NODISCARD +int uapi16_data_check_update_zeros(uapi16_data_check *c, + uint64_t size, + uapi16_error **reterr); + +/** + * Checks the data that passed against the size and the hash the object + * gives, and stores how many bytes it is in `ret_size`, unless that is + * NULL. Data of another size fails with UAPI16_ERROR_SIZE_MISMATCH, and + * data with another hash with UAPI16_ERROR_HASH_MISMATCH. Every later call + * on the check but uapi16_data_check_free() fails with -ESTALE. + */ +UAPI16_NODISCARD +int uapi16_data_check_finish(uapi16_data_check *c, + uint64_t *ret_size, + uapi16_error **reterr); + +/** + * Frees a check. NULL is fine. Returns NULL. + */ +uapi16_data_check *uapi16_data_check_free(uapi16_data_check *c); + +/** + * Makes a computation that has taken no data yet. It is freed with + * uapi16_sha256_free(). + */ +uapi16_sha256 *uapi16_sha256_new(void); + +/** + * Takes the `size` bytes at `data` as more of the data. + */ +UAPI16_NODISCARD int uapi16_sha256_update(uapi16_sha256 *s, const void *data, size_t size); + +/** + * Takes `size` zero bytes as more of the data, such as a hole of a sparse + * file that the caller did not read. + */ +UAPI16_NODISCARD int uapi16_sha256_update_zeros(uapi16_sha256 *s, uint64_t size); + +/** + * Ends the computation and stores the hash of all the data in `ret`. Every + * later call on it but uapi16_sha256_free() fails with -ESTALE. + */ +UAPI16_NODISCARD int uapi16_sha256_finish(uapi16_sha256 *s, uapi16_sha256_digest_t *ret); + +/** + * Frees a computation. NULL is fine. Returns NULL. + */ +uapi16_sha256 *uapi16_sha256_free(uapi16_sha256 *s); + +/** + * Compares two names the way a manifest in code point order lists its file + * objects: component by component, each by its bytes, so that the name of + * a directory comes right before the names below it. Returns one of + * uapi16_name_order_t as an int: UAPI16_NAME_BEFORE where `a` comes before + * `b`, UAPI16_NAME_SAME where they are the same, and UAPI16_NAME_AFTER + * where `a` comes after `b`. A comparison function of qsort() returns that + * as it is. This is not the order of strcmp(): "a/x" comes before "a-b". + * NULL is the empty name, which comes first. Strings that are not UTF-8 are + * no names, and they compare after the replacement. + */ +UAPI16_NODISCARD int uapi16_name_compare(const char *a, const char *b); + +/** + * Adds the feature `feature` to the set `s`. + */ +UAPI16_NODISCARD int uapi16_features_add(uapi16_features_t *s, uapi16_feature_t feature); + +/** + * Takes the feature `feature` out of the set `s`. + */ +UAPI16_NODISCARD int uapi16_features_remove(uapi16_features_t *s, uapi16_feature_t feature); + +/** + * Whether the feature `feature` is in the set `s`. false for NULL. + */ +bool uapi16_features_has(const uapi16_features_t *s, uapi16_feature_t feature); + +/** + * The lowest feature of the set `s` above `after`. UAPI16_FEATURE_NONE as + * `after` gives the first one, and UAPI16_FEATURE_NONE comes back after the + * last one, and for NULL. + */ +uapi16_feature_t uapi16_features_next(const uapi16_features_t *s, uapi16_feature_t after); + +/** + * Adds the features of the set `other` to the set `s`. + */ +void uapi16_features_union(uapi16_features_t *s, const uapi16_features_t *other); + +/** + * Keeps the features of the set `s` that the set `other` has as well. + */ +void uapi16_features_intersect(uapi16_features_t *s, const uapi16_features_t *other); + +/** + * Takes the features of the set `other` out of the set `s`. + */ +void uapi16_features_subtract(uapi16_features_t *s, const uapi16_features_t *other); + +/** + * Whether the sets `a` and `b` have the same features. false for NULL. + */ +bool uapi16_features_equal(const uapi16_features_t *a, const uapi16_features_t *b); + +/** + * The name the specification has for the feature `feature`, such as + * "user-xattr" for UAPI16_FEATURE_USER_XATTR. NULL for a number that is not + * one feature of this library. The string is a constant of the library. + */ +const char *uapi16_feature_name(uapi16_feature_t feature); + +/** + * The feature with the name `name`, as the specification spells it. + * UAPI16_FEATURE_NONE for a name that no feature has, and for NULL. + */ +uapi16_feature_t uapi16_feature_from_name(const char *name); + +/** + * Stores the default features in `ret`: those of a manifest that lists + * none, and those of new options. + */ +UAPI16_NODISCARD int uapi16_features_default(uapi16_features_t *ret); + +/** + * Stores every feature this library has in `ret`. + */ +UAPI16_NODISCARD int uapi16_features_known(uapi16_features_t *ret); + +/** + * What kind of error this is. 0 for NULL. + */ +uapi16_error_kind_t uapi16_error_kind(const uapi16_error *e); + +/** + * The errno of the error, a positive number as errno has it. The call + * that failed returned it negated. 0 for NULL. + */ +UAPI16_NODISCARD int uapi16_error_errno(const uapi16_error *e); + +/** + * The name of the file the error is about, as the manifest has it, or + * NULL if the error is about no file. The root of the tree is the empty + * string. For a name a manifest can't hold, it is the name of the + * directory the file is in. The string belongs to the error. + */ +const char *uapi16_error_path(const uapi16_error *e); + +/** + * For UAPI16_ERROR_HARDLINK_MISMATCH, the other name of the inode, which + * the file of uapi16_error_path() was compared with. NULL for any other + * error. The string belongs to the error. + */ +const char *uapi16_error_hardlink_path(const uapi16_error *e); + +/** + * The feature the error is about: for UAPI16_ERROR_UNSUPPORTED the one + * that can't be read, and for a feature of partitions that feature. + * UAPI16_FEATURE_NONE if the error is about no feature. + */ +uapi16_feature_t uapi16_error_feature(const uapi16_error *e); + +/** + * For UAPI16_ERROR_UNWRITABLE_NAME, the name of the file as its directory + * has it: one component. Its bytes need not be UTF-8, and no NUL ends + * them. How many there are is stored in `ret_size`, unless that is NULL. + * For any other error this returns NULL and stores 0. The bytes belong to + * the error. + */ +const void *uapi16_error_raw_name(const uapi16_error *e, size_t *ret_size); + +/** + * Which rule of a name the name breaks: for UAPI16_ERROR_UNWRITABLE_NAME + * the name of uapi16_error_raw_name(), and for a name passed to a file + * object that is no name, that one. 0 for any other error. + */ +uapi16_name_problem_t uapi16_error_name_problem(const uapi16_error *e); + +/** + * The field the error is about, as the specification spells it, such as + * "mode" or "inodeToken". NULL if the error is about no field. The string + * is a constant of the library. + */ +const char *uapi16_error_field(const uapi16_error *e); + +/** + * Stores in `ret` the number of the record the error is about, counting + * from 0, which is the record of the root. For a reader that is the record + * that failed, and for a writer of records the number the record it refused + * would have had. -ENODATA if the error is about no record, as no error of + * a manifest writer is. + */ +UAPI16_NODISCARD int uapi16_error_record(const uapi16_error *e, uint64_t *ret); + +/** + * For UAPI16_ERROR_MANIFEST and UAPI16_ERROR_TOO_LARGE, the rule of the + * specification that a manifest or a file object breaks, by a name that + * never changes. NULL for any other error. The string is a constant of the + * library. + * + * The names are "notJson", "duplicateKey", "invalidString", "notObject", + * "notUtf8", "nulByte", "recordSeparator", "recordTooLarge", "empty", + * "noTrailer", "dataAfterTrailer", "fileAfterSignature", "mediaType", + * "firstHasName", "firstNotDirectory", "noOrder", "noName", "invalidName", + * "duplicateName", "misplaced", "outOfOrder", "unlistedFeature", + * "noTarget", "unknownType", "fieldType", "fieldRange", + * "fieldNotPermitted", "contradiction", "contents", "signature" and + * "extendedAttributes". + */ +const char *uapi16_error_problem(const uapi16_error *e); + +/** + * Frees an error. NULL is fine. Returns NULL. + */ +uapi16_error *uapi16_error_free(uapi16_error *e); + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +/* + * What UAPI16_FEATURES_SET() is made of. + */ +#ifdef __cplusplus +# define UAPI16_FEATURES_U64_(x) static_cast(x) +#else +# define UAPI16_FEATURES_U64_(x) ((uint64_t) (x)) +#endif +#define UAPI16_FEATURES_BIT_(w, f) \ + (UAPI16_FEATURES_U64_((f) != 0 && ((UAPI16_FEATURES_U64_(f) - 1) >> 6) == (w)) << ((UAPI16_FEATURES_U64_(f) - 1) & 63)) +#define UAPI16_FEATURES_OR_1(w, a) UAPI16_FEATURES_BIT_(w, a) +#define UAPI16_FEATURES_OR_2(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_1(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_3(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_2(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_4(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_3(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_5(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_4(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_6(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_5(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_7(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_6(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_8(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_7(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_9(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_8(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_10(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_9(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_11(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_10(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_12(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_11(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_13(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_12(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_14(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_13(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_15(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_14(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_16(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_15(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_17(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_16(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_18(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_17(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_19(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_18(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_20(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_19(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_21(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_20(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_22(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_21(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_23(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_22(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_24(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_23(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_25(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_24(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_26(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_25(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_27(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_26(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_28(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_27(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_29(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_28(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_30(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_29(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_31(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_30(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_32(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_31(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_33(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_32(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_34(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_33(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_35(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_34(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_36(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_35(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_37(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_36(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_38(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_37(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_39(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_38(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_40(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_39(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_41(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_40(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_42(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_41(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_43(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_42(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_44(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_43(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_45(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_44(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_46(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_45(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_47(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_46(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_48(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_47(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_49(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_48(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_50(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_49(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_51(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_50(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_52(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_51(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_53(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_52(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_54(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_53(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_55(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_54(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_56(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_55(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_57(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_56(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_58(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_57(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_59(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_58(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_60(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_59(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_61(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_60(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_62(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_61(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_63(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_62(w, __VA_ARGS__) +#define UAPI16_FEATURES_OR_64(w, a, ...) UAPI16_FEATURES_BIT_(w, a) | UAPI16_FEATURES_OR_63(w, __VA_ARGS__) +#define UAPI16_FEATURES_COUNT_N_(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, N, ...) N +#define UAPI16_FEATURES_COUNT_(...) UAPI16_FEATURES_COUNT_N_(__VA_ARGS__, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) +#define UAPI16_FEATURES_CAT2_(a, b) a##b +#define UAPI16_FEATURES_CAT_(a, b) UAPI16_FEATURES_CAT2_(a, b) +#define UAPI16_FEATURES_OR_(w, ...) \ + UAPI16_FEATURES_CAT_(UAPI16_FEATURES_OR_, UAPI16_FEATURES_COUNT_(__VA_ARGS__))(w, __VA_ARGS__) + +/** + * A set of the features given, up to 64 of them: + * `uapi16_features_t s = UAPI16_FEATURES_SET(UAPI16_FEATURE_MTIME, UAPI16_FEATURE_SIZE);`. + * UAPI16_FEATURE_NONE among them is passed over, and so is a number the set + * has no room for. + */ +#define UAPI16_FEATURES_SET(...) \ + { sizeof(uapi16_features_t), { \ + UAPI16_FEATURES_OR_(0, __VA_ARGS__), \ + UAPI16_FEATURES_OR_(1, __VA_ARGS__) \ + } } + +/** + * A set without features: `uapi16_features_t s = UAPI16_FEATURES_EMPTY;`. + */ +#define UAPI16_FEATURES_EMPTY { sizeof(uapi16_features_t), { 0 } } + +/* + * For __attribute__((cleanup(...))): each frees the object that its + * argument points to, unless that is NULL. + */ +static inline void uapi16_manifest_options_freep(uapi16_manifest_options **o) { + if (*o) + *o = uapi16_manifest_options_free(*o); +} + +static inline void uapi16_manifest_writer_freep(uapi16_manifest_writer **w) { + if (*w) + *w = uapi16_manifest_writer_free(*w); +} + +static inline void uapi16_manifest_report_freep(uapi16_manifest_report **r) { + if (*r) + *r = uapi16_manifest_report_free(*r); +} + +static inline void uapi16_error_freep(uapi16_error **e) { + if (*e) + *e = uapi16_error_free(*e); +} + +static inline void uapi16_file_object_freep(uapi16_file_object **o) { + if (*o) + *o = uapi16_file_object_free(*o); +} + +static inline void uapi16_writer_freep(uapi16_writer **w) { + if (*w) + *w = uapi16_writer_free(*w); +} + +static inline void uapi16_signature_freep(uapi16_signature **s) { + if (*s) + *s = uapi16_signature_free(*s); +} + +static inline void uapi16_sha256_freep(uapi16_sha256 **s) { + if (*s) + *s = uapi16_sha256_free(*s); +} + +static inline void uapi16_reader_freep(uapi16_reader **r) { + if (*r) + *r = uapi16_reader_free(*r); +} + +static inline void uapi16_directory_freep(uapi16_directory **d) { + if (*d) + *d = uapi16_directory_free(*d); +} + +static inline void uapi16_data_check_freep(uapi16_data_check **c) { + if (*c) + *c = uapi16_data_check_free(*c); +} + +#endif /* UAPI16_H */ diff --git a/src/uapi16/walk.rs b/src/uapi16/walk.rs new file mode 100644 index 0000000..72ec2c0 --- /dev/null +++ b/src/uapi16/walk.rs @@ -0,0 +1,2583 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The adds of a manifest that is being built. The add of a tree takes a +//! descriptor, reads the directory it refers to as the root and everything +//! below it, and hands the file objects to the [`Listing`], which sorts +//! them. The add of a file object a caller made hands that one over. +//! +//! [`Walker`] does an add in steps, as the listing and the [`Writing`] do +//! their work. [`Walker::begin`] only says what is to be added, and +//! [`Walker::step`] does a part of it at a time, as much as its budget +//! allows, and says whether the add is done. Between two entries a step +//! looks at its budget and returns once it is used up, so a walk can be +//! stopped there and picked up again later. That is the shape of walkdir's +//! IntoIter and of fts(3): the directories a walk is in are on an explicit +//! stack instead of a recursion, and the stack is where the walk is from +//! one step to the next. +//! +//! Where an add is from one step to the next is its [`Task`], which +//! whoever began the add keeps and hands to every step. The walker keeps +//! none. An add borrows the descriptor it was given for as long as it is +//! being done, and does not duplicate it. +//! +//! The walk is by descriptor throughout, the way pathrs and cap-std walk. +//! Every entry is opened as a handle in the directory it is in, see +//! [`Entry::open_at`], and everything else is read through that handle. A +//! directory the walk goes into is opened by its name for its listing, and +//! has to be the file of its handle, see [`Entry::reopen`], and its entries +//! are opened in that descriptor. So a walk keeps one descriptor for every +//! directory it is in, and a buffer of 8 KiB to 32 KiB for the names +//! getdents() gave of it that are still to come, as glibc's opendir() keeps +//! a buffer for every directory that is open. The memory of a walk grows +//! with the depth of a tree that way: to about 32 MiB at 1024 levels, and +//! to 64 MiB at the about 2048 levels a name can have. The directories are +//! read in the order readdir() gives, since the listing sorts everything +//! anyway. +//! +//! - A file on another mount than the directory the walk started at is a +//! mount point, by the mount ID of statx(). It is not walked into unless +//! the add crosses mount points. A directory that is not walked into is +//! an empty directory with the attributes of the mounted root. A file +//! that is mounted over another one is the file the mount shows, with +//! nothing to walk into: a regular file with its attributes and the hash +//! of its data, a device node with its attributes and its device numbers. +//! - Nothing is mounted for an add. An automount point that nothing is +//! mounted on yet is told from its handle, see [`Entry::is_automount`], +//! before any directory is opened. It is never opened and nothing is +//! looked up in it, since either can mount what it stands for. So it is +//! an empty directory with its own attributes, with and without crossing +//! mount points, and what is read from the open file can't be read of +//! it. A directory that becomes an automount point after its handle was +//! looked at and before it is opened by its name is a known limit: that +//! open mounts its file system, and the add fails with a tree that +//! changed, see [`Entry::reopen`]. +//! - With mount points crossed, a mount can show a directory again inside +//! itself. A directory that is one of the directories the walk is in, by +//! device, inode and subvolume, fails the add. +//! - A symbolic link is the link, with its target, and is never followed. +//! - The names the specification reserves at the top of a tree are passed +//! over. A name a manifest cannot hold fails the add, or is left out and +//! counted where the add asks for that, a directory with everything below +//! it. +//! - The files the manifest made itself and has open are passed over +//! wherever a walk comes to one, see [`OwnFiles`]: the scratch files of +//! the listing, which a file system can show in their directory although +//! they have no name, and the manifest where it has a name of its own +//! until it is complete. A file is one of them by its inode and by its +//! status. A file system can give two files one inode number, and a file +//! of the tree that only has the number of one of them is listed like +//! any other. No scratch file is closed while the walker is there, also +//! not one the listing is done with, so a walk never comes to one that +//! is none of them any more. +//! - A directory that is walked into is opened for its listing before its +//! own file object goes to the listing, and its file system is asked for +//! the DOS attributes before that where it is the root, which has none +//! of its own. +//! - An add that fails is over, and the walker keeps no note of it. A file +//! object of a caller goes to the listing with the last turn of its add, +//! so its add added nothing where it failed. The add of a tree that +//! failed added a part of the tree, which the listing can't take back: +//! whoever walks a tree gives the manifest up then. +//! - An add that is given up between two of its steps is like one that +//! failed there. Its [`Task`] is dropped or leaked for that, which tells +//! the walker nothing. +//! - A file that changes while it is read fails the add, where statx() +//! shows the change. What statx() says of a file before and after it is +//! read has to be the same. A directory is read while it is listed: +//! before each of its entries and once more at the end of its listing, +//! what statx() says of it has to be what it said when the directory was +//! opened. A rename in a directory can make readdir() return an entry +//! again under its new name, a whole directory or a file whose data was +//! read. So where statx() shows every rename, a walk reads only the +//! entries a directory had when it was opened, each once. Where it +//! doesn't, see ManifestOptions::generate_at, an entry can come twice or +//! not at all. A file that is gone between the listing of its directory +//! and its open changed as well. +//! +//! [`OwnFiles`]: crate::sys::OwnFiles + +use std::collections::HashSet; +use std::ffi::OsStr; +use std::fs::File; +use std::io; +use std::mem; +use std::ops::{BitAnd, BitOr, BitOrAssign, ControlFlow}; +use std::os::fd::BorrowedFd; +use std::os::unix::ffi::OsStrExt; +use std::sync::Arc; + +use rustix::fs::FileType; + +use crate::error::{Error, ErrorKind, TreeProblem}; +use crate::listing::{Listing, Writing}; +use crate::object::{ + ContentsObject, ContentsSource, FileObject, FileSystemIdentity, InodeAttributes, InodeType, RootObject, +}; +use crate::optional::FeatureReader; +use crate::sys::{DataHash, Entries, Listed, Readable, DATA_BUFFER_SIZE}; +use crate::tree::{Entry, Failure, InodeId, MountId, Place, Status, Subject}; +use crate::{Features, Name, NameBuf, NameProblem, Sha256}; + +/// How much a step of an add does: bytes of data hashed, and [`OPEN`] for +/// every file that is opened. It is about one read of the data of a file. +pub(crate) const STEP_BUDGET: u64 = 1024 * 1024; + +/// What a turn of a step costs at least, so that a step of any budget gets +/// further and comes to an end. +const TURN: u64 = 1; + +/// What the turn that opens an entry of a directory costs besides the +/// bytes of its name. Opening a file and reading what a manifest records +/// of it takes about as long as hashing this many bytes of data. So a +/// budget is worth about the same time over many small files as over the +/// data of a large one. +const OPEN: u64 = 4096; + +/// How [`ManifestOptions::generate_at`] and [`ManifestOptions::generate`] +/// walk: whether they cross mount points, and what they do with a file +/// whose name a manifest can't hold. +/// The flags combine with `|`. +/// +/// ``` +/// use uapi16::AddFlags; +/// +/// let flags = AddFlags::CROSS_MOUNTS | AddFlags::GRACEFUL; +/// assert!(flags.contains(AddFlags::CROSS_MOUNTS)); +/// assert!(!AddFlags::NONE.contains(AddFlags::CROSS_MOUNTS)); +/// ``` +/// +/// [`ManifestOptions::generate_at`]: crate::ManifestOptions::generate_at +/// [`ManifestOptions::generate`]: crate::ManifestOptions::generate +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct AddFlags(u8); + +impl AddFlags { + /// No flags: mount points are not crossed, and a name a manifest can't + /// hold is an error. + pub const NONE: AddFlags = AddFlags(0); + /// Walk into mount points instead of writing them as empty directories. + pub const CROSS_MOUNTS: AddFlags = AddFlags(1 << 0); + /// Leave out files whose names a manifest can't hold, a directory with + /// everything below it, and count them in + /// [`ManifestReport::entries_omitted`](crate::ManifestReport::entries_omitted), + /// instead of failing. + pub const GRACEFUL: AddFlags = AddFlags(1 << 1); + + /// Whether every flag of `flags` is among these. + pub const fn contains(self, flags: AddFlags) -> bool { + self.0 & flags.0 == flags.0 + } +} + +impl BitOr for AddFlags { + type Output = AddFlags; + + fn bitor(self, other: AddFlags) -> AddFlags { + AddFlags(self.0 | other.0) + } +} + +impl BitOrAssign for AddFlags { + fn bitor_assign(&mut self, other: AddFlags) { + self.0 |= other.0; + } +} + +impl BitAnd for AddFlags { + type Output = AddFlags; + + fn bitand(self, other: AddFlags) -> AddFlags { + AddFlags(self.0 & other.0) + } +} + +/// What is to be added. An add borrows what it is given for as long as it +/// is being done, and duplicates none of it. +#[derive(Debug)] +pub(crate) enum Add<'a> { + /// The directory a descriptor of a caller refers to, as the root, and + /// everything below it. + Tree { top: BorrowedFd<'a>, flags: AddFlags }, + /// The root as a caller describes it: its inode attributes and the + /// identity of its file system. + Root { + inode: &'a InodeAttributes, + file_system: &'a FileSystemIdentity, + }, + /// A file object a caller made. + Object(&'a FileObject), +} + +/// What the adds left out of the manifest. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Omitted { + /// The entries whose names a manifest cannot hold, which the walk + /// passed over. A directory counts once. + pub(crate) entries: u64, + /// The fields that were left out of file objects: the names of owners + /// the user database does not have, the user and group IDs 65535 and + /// 4294967295, which the specification does not permit, and + /// modification times `mTimeNSec` cannot express, before 1970 or after + /// 2554. And of the root of a walk the UUID and the volume serial + /// number of its file system, where that has none. + pub(crate) fields: u64, +} + +/// What follows once an entry is read and its file object went to the +/// listing. +#[derive(Debug)] +enum Then { + /// The add is done. + Done, + /// The walk goes into the directory that was read. + Descend, + /// The walk goes on with the next entry of the directory it is in. + List, +} + +/// A file object as an entry has it: that of the root of a tree, of which +/// the listing takes the inode attributes and the identity of its file +/// system, or that of any other file. +#[derive(Debug)] +enum Object { + Root(Box), + File(Box), +} + +/// An entry that is being read. +#[derive(Debug)] +struct Reading<'a> { + entry: Entry<'a>, + object: Object, + /// The file opened for reading, where that was needed: for its flags, + /// its DOS attributes or the identity of its file system, or to list a + /// directory that is walked into. + opened: Option, + /// The hash of the data of a regular file while it is read, and how + /// much of the data was read so far. + hash: Option, + hashed: u64, + /// The hash of the data, once it was read. + data: Option, + /// Whether the status of the file is taken again before its object goes + /// to the listing, because more than its status was read of it. + check: bool, + /// How many fields were left out of the object. + omitted: u64, + then: Then, +} + +impl Object { + /// The name of the file in the manifest. + fn name(&self) -> &Name { + match self { + Object::Root(_) => Name::ROOT, + Object::File(object) => object.name(), + } + } +} + +/// A directory a walk is in. +#[derive(Debug)] +struct Level { + entries: Entries, + /// What statx() said of the directory when it was opened, which its + /// status before each of its entries and at the end of its listing is + /// held against. + status: Status, +} + +impl Level { + /// Fails unless the directory, whose name in the manifest is `name`, is + /// what it was when it was opened, with the same entries. + fn unchanged(&self, name: &Name) -> Result<(), Error> { + let now = self.entries.status().map_err(|failure| failure.into_error(name))?; + if now.changed_since(&self.status) { + return Err(Failure::Changed.into_error(name)); + } + Ok(()) + } +} + +/// The walk of a tree below the directory it starts at. +#[derive(Debug)] +struct Walk { + /// The directories the walk is in, the one it lists last. + levels: Vec, + /// The name of the directory it lists. + directory: NameBuf, + /// The mount of the directory the walk started at. A file on another + /// one is a mount point. + mount: MountId, + /// The inodes of the directories in `levels`, where the walk crosses + /// mount points: a directory that is one of them again is a loop. + ancestors: Option>, +} + +impl Walk { + /// A walk below a directory on the mount `mount`. + fn new(mount: MountId, flags: AddFlags) -> Walk { + Walk { + levels: Vec::new(), + directory: NameBuf::default(), + mount, + ancestors: flags.contains(AddFlags::CROSS_MOUNTS).then(HashSet::new), + } + } + + /// Goes into the directory `name`, whose entries are `entries`. + fn push(&mut self, level: Level, name: NameBuf) { + if let Some(ancestors) = &mut self.ancestors { + ancestors.insert(level.status.identity.inode_id()); + } + self.levels.push(level); + self.directory = name; + } + + /// Leaves the directory it lists, and returns whether it is in one + /// still. + fn pop(&mut self) -> bool { + let Some(level) = self.levels.pop() else { + return false; + }; + if let Some(ancestors) = &mut self.ancestors { + ancestors.remove(&level.status.identity.inode_id()); + } + if self.levels.is_empty() { + return false; + } + // A directory the walk went into from another one has a name below + // that one. + self.directory = self.directory.parent().unwrap_or_default().to_owned(); + true + } +} + +/// What an add does next. +#[derive(Debug)] +enum Next<'a> { + /// Takes the status of the descriptor the add was given. + Start(BorrowedFd<'a>), + /// Reads an entry, and hands its file object to the listing. + Read(Box>), + /// Takes the next entry of the directory the walk lists. + List, + /// Hands the root as a caller describes it to the listing. + GivenRoot(&'a InodeAttributes, &'a FileSystemIdentity), + /// Hands a file object of a caller to the listing. + Given(&'a FileObject), + /// Nothing, the add is done. + Done, + /// Nothing, a step of the add failed. + Failed, +} + +impl Task<'_> { + /// Whether nothing is left to do of the add: it is done, or it failed. + fn is_over(&self) -> bool { + matches!(self.next, Next::Done | Next::Failed) + } + + /// What follows once the directory of `entry`, which the add walks, + /// was read: the walk into it, on the mount it is on. An automount + /// point is not walked into: it is the empty directory it is until + /// something is mounted on it, see [`Entry::is_automount`], and the + /// add is done with it. + fn walk_into(&mut self, entry: &Entry<'_>) -> Then { + if entry.is_automount() { + return Then::Done; + } + self.walk = Some(Walk::new(entry.status().identity.mount, self.flags)); + Then::Descend + } +} + +/// An add that is being done: what it was given, and where it is. Whoever +/// began the add keeps this and hands it to every step of it, see +/// [`Walker::begin`] and [`Walker::step`]. It borrows what the add was +/// given, and owns what the add opened on its way: a descriptor for every +/// directory the walk is in, and the file whose data is being read. So an +/// add that is given up closes those with this. +#[derive(Debug)] +pub(crate) struct Task<'a> { + flags: AddFlags, + next: Next<'a>, + /// The walk below the top directory, once the add of a tree is at it. + walk: Option, +} + +/// Does the adds of a manifest that is being built, see the documentation +/// of this module. +#[derive(Debug)] +pub(crate) struct Walker { + features: Features, + listing: Listing, + reader: FeatureReader, + /// What the data of regular files is read through, once one is hashed. + buffer: Vec, + omitted: Omitted, +} + +impl Walker { + /// A walker that hands what it reads to `listing`, which is for a + /// manifest that records `features`. + pub(crate) fn new(features: Features, listing: Listing) -> Walker { + Walker { + features, + listing, + reader: FeatureReader::new(features), + buffer: Vec::new(), + omitted: Omitted::default(), + } + } + + /// Makes walks pass over the file `file` as well, which has the inode + /// `inode` and which the manifest made itself. It is kept open with the + /// other files of the manifest's own, see [`Listing::own_files`]. + pub(crate) fn pass_over(&mut self, inode: InodeId, file: Arc) { + self.listing.own_files_mut().keep(inode, file); + } + + /// Begins the add `add`, and returns it as it is done from here on, a + /// part with every [`Walker::step`]. Nothing is read yet, and nothing + /// is duplicated: the add borrows what it was given. + pub(crate) fn begin(add: Add<'_>) -> Task<'_> { + match add { + Add::Tree { top, flags } => Task { + flags, + next: Next::Start(top), + walk: None, + }, + Add::Root { inode, file_system } => Task { + flags: AddFlags::NONE, + next: Next::GivenRoot(inode, file_system), + walk: None, + }, + Add::Object(object) => Task { + flags: AddFlags::NONE, + next: Next::Given(object), + walk: None, + }, + } + } + + /// Does a part of the add `task` and returns whether that was the end + /// of it, then it breaks. `budget` is about how many bytes it hashes, + /// lists or reads before it returns: it does one thing at a time, opens + /// an entry, reads a part of its data or hands its object to the + /// listing, and goes on while there is budget left. Without a budget it + /// does nothing. + /// + /// An add that fails is over. The add of a file object hands its object + /// to the listing with its last turn, so one that failed added nothing, + /// and the walker goes on with the next add. The add of a tree that + /// failed added a part of the tree, which the listing cannot take back: + /// whoever walks a tree gives the manifest up then. + /// + /// Of an add that is over nothing is left to do, whether it is done or + /// failed: every later step of it does nothing and breaks, whatever + /// its budget. It has nothing open any more either: the step that + /// fails closes what the add had opened on its way. + pub(crate) fn step(&mut self, task: &mut Task<'_>, budget: u64) -> Result, Error> { + let mut left = budget; + while !task.is_over() { + if left == 0 { + return Ok(ControlFlow::Continue(())); + } + if let Err(e) = self.turn(task, &mut left) { + // The directories the walk was in are closed now, and not + // when whoever has the add lets go of it. + task.walk = None; + return Err(e); + } + } + Ok(ControlFlow::Break(())) + } + + /// Ends the adds: the manifest is written from what they added, and + /// what they left out is counted. Nothing is done for that yet, see + /// [`Listing::finish`], and nothing is closed: the files of the + /// manifest's own stay open with what writes the manifest. + pub(crate) fn finish(self) -> (Writing, Omitted) { + (self.listing.finish(), self.omitted) + } + + /// The buffer the data of regular files is read through. + fn buffer(&mut self) -> &mut [u8] { + if self.buffer.is_empty() { + self.buffer = vec![0; DATA_BUFFER_SIZE]; + } + &mut self.buffer + } + + /// Does one thing of `task`, and takes what it cost from `left`. An add + /// whose turn fails is over. + fn turn(&mut self, task: &mut Task<'_>, left: &mut u64) -> Result<(), Error> { + let next = mem::replace(&mut task.next, Next::Failed); + task.next = match next { + Next::Start(fd) => { + *left -= TURN; + self.start(task, fd)? + } + Next::Read(reading) => self.read(task, reading, left)?, + Next::List => self.list(task, left)?, + Next::GivenRoot(inode, file_system) if !self.listing.make_room(*left)? => { + *left = 0; + Next::GivenRoot(inode, file_system) + } + Next::GivenRoot(inode, file_system) => { + *left -= TURN; + self.listing.add_given_root(inode, file_system)?; + Next::Done + } + Next::Given(object) if !self.listing.make_room(*left)? => { + *left = 0; + Next::Given(object) + } + Next::Given(object) => { + *left -= TURN; + self.listing.add_given(object)?; + Next::Done + } + over @ (Next::Done | Next::Failed) => over, + }; + Ok(()) + } + + /// Begins `task` with the directory of the descriptor it was given, + /// `top`, which is the root. + fn start<'a>(&mut self, task: &mut Task<'a>, top: BorrowedFd<'a>) -> Result, Error> { + let entry = Entry::of(top).map_err(|failure| failure.into_error(Name::ROOT))?; + if entry.status().file_type != FileType::Directory { + return Err(Walker::not_directory()); + } + let then = task.walk_into(&entry); + Ok(Next::Read(self.reading(entry, None, NameBuf::default(), then)?)) + } + + /// Takes the next entry of the directory the walk of `task` lists. + fn list(&mut self, task: &mut Task<'_>, left: &mut u64) -> Result, Error> { + let walk = task + .walk + .as_mut() + .expect("an add lists below a directory once it walks"); + let Some(level) = walk.levels.last_mut() else { + return Ok(Next::Done); + }; + let listed = match level.entries.next() { + Some(Ok(listed)) => listed, + Some(Err(failure)) => return Err(failure.into_error(&walk.directory)), + None => { + *left -= TURN; + // It is compared once more after its last entry was read. + level.unchanged(&walk.directory)?; + return Ok(if walk.pop() { Next::List } else { Next::Done }); + } + }; + *left = left.saturating_sub(listed.name().to_bytes().len() as u64 + OPEN); + // Before an entry is read, the directory has to be what it was when + // it was opened. A rename in it can give an entry that was read the + // next name readdir() returned, or make readdir() return the entry + // again under its new name, and none is read twice. + level.unchanged(&walk.directory)?; + Ok(self.entry(walk, &listed, task.flags)?.unwrap_or(Next::List)) + } + + /// What follows from the entry `listed` of the directory `walk` lists: + /// reading it, or nothing if it is passed over. + fn entry(&mut self, walk: &Walk, listed: &Listed, flags: AddFlags) -> Result>, Error> { + let component = listed.name().to_bytes(); + if walk.directory.is_root() && Name::is_reserved_component(component) { + return Ok(None); + } + let name = match walk.directory.join_os(OsStr::from_bytes(component)) { + Ok(name) => name, + Err(_) if flags.contains(AddFlags::GRACEFUL) => { + self.omitted.entries += 1; + return Ok(None); + } + Err(problem) => return Err(Walker::unwritable(&walk.directory, component, problem)), + }; + let level = walk.levels.last().expect("an entry is of the directory the walk lists"); + let entry = match Entry::open_at(level.entries.as_fd(), listed.name()) { + Ok(entry) => entry, + Err(Failure::Io(e)) if e.kind() == io::ErrorKind::NotFound => return Err(Walker::vanished(&name)), + Err(failure) => return Err(failure.into_error(&name)), + }; + let status = *entry.status(); + // Where the status of a file of the manifest's own can't be read, + // the entry that has its inode can't be told from it. + let own = self.listing.own_files().contains(&status); + if own.map_err(|failure| Walker::own_unread(&name, failure))? { + return Ok(None); + } + let crosses = flags.contains(AddFlags::CROSS_MOUNTS); + let mount_point = status.identity.mount != walk.mount; + let then = match status.file_type { + // An automount point is the empty directory it is until + // something is mounted on it, whatever the walk crosses. + FileType::Directory if entry.is_automount() => Then::List, + FileType::Directory if crosses || !mount_point => { + let ancestors = walk.ancestors.as_ref(); + if ancestors.is_some_and(|ancestors| ancestors.contains(&status.identity.inode_id())) { + return Err(Walker::loops(&name)); + } + Then::Descend + } + // Anything else is not walked into: a file that is not a + // directory, also one that a mount shows, and a directory that + // is a mount point the walk does not cross, which is an empty + // directory with the attributes of the mounted root. + _ => Then::List, + }; + let place = Place { + dir: level.entries.as_fd(), + name: listed.name(), + }; + Ok(Some(Next::Read(self.reading(entry, Some(place), name, then)?))) + } + + /// Whether the data of the file with the status `status` is hashed: + /// that of a regular file, where the manifest records hashes, and also + /// where it records hard links and the file has more than one name, + /// since its names are held against each other with their data. + fn hashes(&self, status: &Status) -> bool { + let linked = status.nlink > 1 && self.features.contains(Features::HARDLINK); + status.file_type == FileType::RegularFile && (self.features.contains(Features::SHA256) || linked) + } + + /// Begins to read the entry `entry`, which is at `place`, see + /// [`Entry::reopen`], and whose name in the manifest is `name`: what + /// its status says, the optional features, and the target of a + /// symbolic link. The data of a regular file is hashed in the steps + /// that follow, see [`Walker::hashes`]. + fn reading<'a>( + &mut self, + entry: Entry<'a>, + place: Option>, + name: NameBuf, + then: Then, + ) -> Result>, Error> { + let features = self.features; + let status = *entry.status(); + let hashed = self.hashes(&status); + if hashed { + DataHash::admits(&status).map_err(|failure| failure.into_error(&name))?; + } + let xattrs = features.contains(Features::USER_XATTR) && status.file_type != FileType::Symlink; + // A directory that is walked into is opened for its listing before + // anything else is read of it, and so before its object goes to the + // listing. A regular file that is hashed is opened for that before + // its extended attributes are read, which are read through the open + // file then. + let mut opened = match then { + Then::Descend => Some(entry.reopen(place).map_err(|failure| failure.into_error(&name))?), + _ if hashed && xattrs => Some(entry.reopen(place).map_err(|failure| failure.into_error(&name))?), + _ => None, + }; + let (object, omitted) = if name.is_root() { + // Every file below the root is asked for its DOS attributes, + // and the root has none. So the file system is asked before the + // root of a walk goes to the listing. + if matches!(then, Then::Descend) { + self.reader + .check_dos_attributes(&entry, &mut opened) + .map_err(|failure| failure.into_error(&name))?; + } + let (inode, omitted) = InodeAttributes::of_status(&status, features); + let mut root = RootObject { + inode, + ..RootObject::default() + }; + let left_out = self + .reader + .read_root(&entry, &mut opened, &mut root) + .map_err(|failure| failure.into_error(&name))?; + (Object::Root(Box::new(root)), omitted + left_out) + } else { + let (mut object, omitted) = FileObject::of_status(name, &status, features)?; + let names = self + .reader + .read(&entry, place, &mut opened, &mut object) + .map_err(|failure| failure.into_error(object.name()))?; + // The size of a symbolic link is the length of its target, as + // for systemd-manifest, which knows it once it read the + // target. + if status.file_type == FileType::Symlink && features.contains(Features::SYMLINK) { + let target = entry.target().map_err(|failure| failure.into_error(object.name()))?; + if features.contains(Features::SIZE) { + object.set_size(Some(target.len() as u64)); + } + object.put_contents(vec![ContentsObject::new(ContentsSource::Literal(target))]); + } + (Object::File(Box::new(object)), omitted + names) + }; + let hash = if hashed { + let hash = match opened.take() { + Some(readable) => DataHash::of(&entry, readable), + None => DataHash::start(&entry), + }; + Some(hash.map_err(|failure| failure.into_error(object.name()))?) + } else { + None + }; + // The hash checks the status after the data, and the walk checks a + // directory it goes into while it lists it. Anything else is + // checked once more than its status was read: the flags, the DOS + // attributes and the identity of the file system through the file + // opened for reading, or the extended attributes. + let check = hash.is_none() && !matches!(then, Then::Descend) && (opened.is_some() || xattrs); + Ok(Box::new(Reading { + entry, + object, + opened, + hash, + hashed: 0, + data: None, + check, + omitted, + then, + })) + } + + /// Goes on reading the entry of `reading`: hashes a part of its data, + /// checks that it did not change, and hands its object to the listing + /// once there is room. Then the add goes on as `reading` says. + fn read<'a>( + &mut self, + task: &mut Task<'a>, + mut reading: Box>, + left: &mut u64, + ) -> Result, Error> { + if let Some(hash) = reading.hash.take() { + let size = reading.entry.status().size; + let budget = *left; + let read = hash + .read(self.buffer(), budget) + .map_err(|failure| failure.into_error(reading.object.name()))?; + match read { + ControlFlow::Continue(hash) => { + reading.hashed += budget; + reading.hash = Some(hash); + *left = 0; + return Ok(Next::Read(reading)); + } + ControlFlow::Break(data) => { + *left = left.saturating_sub(size.saturating_sub(reading.hashed).max(TURN)); + reading.data = Some(data); + if let Object::File(object) = &mut reading.object { + if self.features.contains(Features::SHA256) { + object.set_sha256(Some(data)); + } + } + } + } + } + if reading.check { + let name = reading.object.name(); + let after = Status::of(reading.entry.handle()).map_err(|failure| failure.into_error(name))?; + if after.changed_since(reading.entry.status()) { + return Err(Failure::Changed.into_error(name)); + } + reading.check = false; + } + if !self.listing.make_room(*left)? { + *left = 0; + return Ok(Next::Read(reading)); + } + *left = left.saturating_sub(TURN); + let Reading { + entry, + object, + opened, + data, + omitted, + then, + .. + } = *reading; + let name = match object { + Object::Root(root) => { + self.listing.add_root(&root.inode, &root.file_system)?; + NameBuf::default() + } + Object::File(object) => { + self.listing.add_walked(&object, entry.status(), data)?; + object.into_name() + } + }; + self.omitted.fields += omitted; + let next = match then { + Then::Done => Next::Done, + Then::Descend => { + let readable = opened.expect("a directory that is walked into was opened for its listing"); + let entries = readable.entries(); + let walk = task.walk.as_mut().expect("an add walks once it goes into a directory"); + let status = *entry.status(); + walk.push(Level { entries, status }, name); + Next::List + } + Then::List => Next::List, + }; + Ok(next) + } + + /// The error for the entry `name`, which has the inode of a file of + /// the manifest's own whose status can't be read, for `failure`: the + /// entry can't be told from that file. The error is that of the + /// status and names the entry, and its message says that it is a file + /// of the manifest's own that can't be read. + fn own_unread(name: &Name, failure: Failure) -> Error { + match failure { + Failure::Io(e) => { + let message = format!( + "{}: a file of the manifest's own with its inode can't be read: {}", + Subject(name), + e + ); + Error::new(ErrorKind::Io, message).named(name.as_str()).caused_by(e) + } + failure => failure.into_error(name), + } + } + + /// The error for the file a walk is to start at, which is not a + /// directory. + fn not_directory() -> Error { + let name = Name::ROOT; + let message = format!("{}: is not a directory", Subject(name)); + Error::new(ErrorKind::Tree(TreeProblem::NotDirectory), message).named(name.as_str()) + } + + /// The error for an entry of the directory `directory` with the name + /// `component`, which a manifest cannot hold for `problem`. + fn unwritable(directory: &Name, component: &[u8], problem: NameProblem) -> Error { + let raw = OsStr::from_bytes(component); + let message = format!( + "{}: has an entry with a name a manifest cannot hold, {:?}: {}", + Subject(directory), + raw, + problem + ); + Error::new(ErrorKind::Tree(TreeProblem::UnwritableName), message) + .named(directory.as_str()) + .raw(raw) + .because(problem) + } + + /// The error for the file `name`, which its directory listed and which + /// was gone when it was opened. Files must not change while they are + /// read, and a directory is read when it is listed. + fn vanished(name: &Name) -> Error { + let message = format!("{}: was removed or renamed while its directory was read", Subject(name)); + Error::new(ErrorKind::Tree(TreeProblem::Changed), message).named(name.as_str()) + } + + /// The error for the directory `name`, which is one of the directories + /// it is in, shown again by a mount. + fn loops(name: &Name) -> Error { + let message = format!( + "{}: is one of the directories it is in, which a mount shows again", + Subject(name) + ); + Error::new(ErrorKind::Tree(TreeProblem::Loop), message).named(name.as_str()) + } +} + +impl InodeType { + /// The inode type of a file of the type `file_type`, if it is one. + fn of_file_type(file_type: FileType) -> Option { + Some(match file_type { + FileType::RegularFile => InodeType::Regular, + FileType::Directory => InodeType::Directory, + FileType::Symlink => InodeType::Symlink, + FileType::Fifo => InodeType::Fifo, + FileType::CharacterDevice => InodeType::CharDevice, + FileType::BlockDevice => InodeType::BlockDevice, + FileType::Socket => InodeType::Socket, + FileType::Unknown => return None, + }) + } +} + +impl InodeAttributes { + /// The inode attributes a manifest that records `features` takes from + /// `status`: the access mode, but of a symbolic link, the user and the + /// group ID of the owner, and the modification time. Returns them with + /// how many of them were left out: the IDs 65535 and 4294967295, which + /// the specification does not permit, and a time before 1970 or after + /// 2554, which `mTimeNSec` cannot express. + fn of_status(status: &Status, features: Features) -> (InodeAttributes, u64) { + let mut inode = InodeAttributes::default(); + let mut omitted = 0; + if features.contains(Features::MODE) && status.file_type != FileType::Symlink { + inode.set_mode(Some(status.mode)); + } + let valid = |id: u32| Some(id).filter(|&id| FileObject::is_valid_id(id)); + if features.contains(Features::UID) { + inode.set_uid(valid(status.uid)); + omitted += u64::from(inode.uid().is_none()); + } + if features.contains(Features::GID) { + inode.set_gid(valid(status.gid)); + omitted += u64::from(inode.gid().is_none()); + } + if features.contains(Features::MTIME) { + inode.set_mtime_nsec(status.mtime.since_epoch_nsec()); + omitted += u64::from(inode.mtime_nsec().is_none()); + } + (inode, omitted) + } +} + +impl FileObject { + /// The file object a manifest that records `features` gets for the file + /// `name` from its status `status`: its type, its inode attributes, see + /// [`InodeAttributes::of_status`], the size of a regular file and the + /// device numbers of a device node. Returns it with how many fields + /// were left out. A file of a type no manifest has fails. + fn of_status(name: NameBuf, status: &Status, features: Features) -> Result<(FileObject, u64), Error> { + let Some(inode_type) = InodeType::of_file_type(status.file_type) else { + let unknown = io::Error::new(io::ErrorKind::InvalidData, "the file is of no type a manifest has"); + return Err(Error::from(unknown).named(name.as_str())); + }; + let (inode, omitted) = InodeAttributes::of_status(status, features); + let mut object = FileObject::new(name); + object.set_inode_type(inode_type); + *object.inode_mut() = inode; + if features.contains(Features::SIZE) && inode_type == InodeType::Regular { + object.set_size(Some(status.size)); + } + if features.contains(Features::DEVICE) && inode_type.is_device() { + object.set_major(Some(u64::from(status.rdev.major))); + object.set_minor(Some(u64::from(status.rdev.minor))); + } + Ok((object, omitted)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::listing::Totals; + use crate::scratch::Scratch; + use crate::sys::ScratchFile; + use crate::testing::{self, read_whole, write_whole, TempDir, Whole}; + use crate::tree::{DeviceNumber, Identity, Timestamp}; + use crate::{Mode, Order}; + use rustix::fs::{inotify, OFlags, XattrFlags, CWD}; + use std::collections::HashMap; + use std::ffi::{CString, OsString}; + use std::fs::{self, File}; + use std::io::Write; + use std::os::fd::{AsFd, OwnedFd}; + use std::os::unix::ffi::OsStringExt; + use std::os::unix::fs::{symlink, MetadataExt, PermissionsExt}; + use std::os::unix::net::UnixListener; + use std::path::Path; + use std::process::{Command, Stdio}; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + /// Opens `path` as a handle, the link itself where it is a symbolic link. + fn open_path(path: &Path) -> OwnedFd { + let flags = OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC; + rustix::fs::open(path, flags, rustix::fs::Mode::empty()).unwrap() + } + + /// Makes a FIFO at `path`. + fn make_fifo(path: &Path) { + let mode = rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR; + rustix::fs::mknodat(CWD, path, FileType::Fifo, mode, 0).unwrap(); + } + + /// A manifest a test builds, with its scratch files in a directory of + /// its own. + struct Build { + walker: Walker, + _scratch: TempDir, + } + + impl Build { + /// A manifest that records `features`. + fn new(features: Features) -> Build { + // The tests run next to each other, each with directories of + // its own. + static NEXT: AtomicUsize = AtomicUsize::new(0); + let scratch = TempDir::new(&format!("walk-scratch-{}", NEXT.fetch_add(1, Ordering::Relaxed))); + let directory = Scratch::beside(ScratchFile::open_directory(&scratch.0).unwrap().into()); + let listing = Listing::new(features, Order::CodePoint, directory); + Build { + walker: Walker::new(features, listing), + _scratch: scratch, + } + } + + /// The directory `top` refers to as the root, and everything below + /// it, with the flags `flags`. + fn add_all(&mut self, top: BorrowedFd<'_>, flags: AddFlags) -> Result<(), Error> { + self.run(Add::Tree { top, flags }) + } + + /// Does the add `add` from its beginning to its end, as an add that + /// is done in one call is. + fn run(&mut self, add: Add<'_>) -> Result<(), Error> { + let mut task = Walker::begin(add); + while self.walker.step(&mut task, STEP_BUDGET)?.is_continue() {} + Ok(()) + } + + /// The manifest, read back, what it lists and what was left out. + fn finish(self) -> Result<(Whole, Totals, Omitted), Error> { + let (mut writing, omitted) = self.walker.finish(); + let mut text = String::new(); + loop { + if let ControlFlow::Break(totals) = writing.step(u64::MAX, &mut text)? { + return Ok((read_whole(text.as_bytes()).unwrap(), totals, omitted)); + } + } + } + } + + /// The manifest of the tree `dir` as a whole, as its root, for + /// `features`. + fn walked(dir: &Path, features: Features, flags: AddFlags) -> Result<(Whole, Totals, Omitted), Error> { + let mut build = Build::new(features); + build.add_all(open_path(dir).as_fd(), flags)?; + build.finish() + } + + /// The names of the file objects of `whole`. + fn names(whole: &Whole) -> Vec<&str> { + whole.objects.iter().map(|object| object.name().as_str()).collect() + } + + /// The file object `name` of `whole`. + fn object<'a>(whole: &'a Whole, name: &str) -> &'a FileObject { + whole.objects.iter().find(|object| object.name() == name).unwrap() + } + + /// What a manifest that records `features` says of the root `dir` and + /// of its files `names`, as std::fs reads them: the file objects in the + /// order of their names, the names of one inode with one token, and the + /// root with the attributes of `root`, or a made-up one without. + fn expected(dir: &Path, root: Option<&Path>, names: &[&str], features: Features) -> Whole { + let mut whole = Whole { + root: RootObject { + features: Some(features), + order: Some(Order::CodePoint), + ..RootObject::default() + }, + objects: Vec::new(), + signatures: Vec::new(), + }; + if let Some(root) = root { + let meta = fs::symlink_metadata(root).unwrap(); + let object = FileObject::from_metadata(testing::name("root"), &meta, features).unwrap(); + whole.root.inode = object.inode().clone(); + } + let mut sorted: Vec = names.iter().map(|name| testing::name(name)).collect(); + sorted.sort(); + let mut tokens = HashMap::new(); + for name in sorted { + let path = dir.join(name.as_str()); + let meta = fs::symlink_metadata(&path).unwrap(); + let mut object = FileObject::from_metadata(name, &meta, features).unwrap(); + if meta.is_file() && features.contains(Features::SHA256) { + object.set_sha256(Some(Sha256::digest(&fs::read(&path).unwrap()))); + } + if meta.is_symlink() && features.contains(Features::SYMLINK) { + let target = fs::read_link(&path).unwrap().into_os_string().into_vec(); + if features.contains(Features::SIZE) { + object.set_size(Some(target.len() as u64)); + } + object.put_contents(vec![ContentsObject::new(ContentsSource::Literal(target))]); + } + if !meta.is_dir() && meta.nlink() > 1 && features.contains(Features::HARDLINK) { + let next = tokens.len() as u64 + 1; + let token = *tokens.entry((meta.dev(), meta.ino())).or_insert(next); + object.set_inode_token(std::num::NonZeroU64::new(token)); + } + whole.objects.push(object); + } + // The way the manifest of a walk comes back, through a writer and a + // reader. + read_whole(&write_whole(&whole).unwrap()).unwrap() + } + + /// A tree with a file of every type a test can make, and the names of + /// its files: regular files, among them an empty one and one that takes + /// several reads, directories, symbolic links, a hard link, a FIFO and a + /// socket. + fn every_type(name: &str) -> (TempDir, UnixListener, Vec<&'static str>) { + let tmp = TempDir::new(name); + let dir = &tmp.0; + fs::write(dir.join("file"), b"hello").unwrap(); + fs::write(dir.join("empty"), b"").unwrap(); + let large: Vec = (0..3 * DATA_BUFFER_SIZE + 5).map(|i| (i % 251) as u8).collect(); + fs::write(dir.join("large"), large).unwrap(); + fs::create_dir(dir.join("dir")).unwrap(); + fs::set_permissions(dir.join("dir"), fs::Permissions::from_mode(0o750)).unwrap(); + fs::write(dir.join("dir/inner"), b"inner").unwrap(); + fs::create_dir(dir.join("dir/empty-dir")).unwrap(); + symlink("file", dir.join("link")).unwrap(); + symlink("nowhere/at/all", dir.join("dir/dangling")).unwrap(); + fs::write(dir.join("linked"), b"twice").unwrap(); + fs::hard_link(dir.join("linked"), dir.join("dir/linked-too")).unwrap(); + make_fifo(&dir.join("fifo")); + let socket = UnixListener::bind(dir.join("socket")).unwrap(); + let names = vec![ + "file", + "empty", + "large", + "dir", + "dir/inner", + "dir/empty-dir", + "link", + "dir/dangling", + "linked", + "dir/linked-too", + "fifo", + "socket", + ]; + (tmp, socket, names) + } + + /// A walk lists every file below the directory it starts at, of every + /// type, with what the features record of each as std::fs reads it, in + /// the order of the manifest. The names of one inode share a token, and + /// what the manifest lists is counted. + #[test] + fn walks_every_type() { + let (tmp, _socket, names) = every_type("walk-types"); + let dir = &tmp.0; + let large = 3 * DATA_BUFFER_SIZE as u64 + 5; + for features in [Features::NONE, Features::DEFAULT, Features::DEFAULT | Features::MTIME] { + let (whole, totals, omitted) = walked(dir, features, AddFlags::NONE).unwrap(); + assert_eq!(whole, expected(dir, Some(dir), &names, features), "{:?}", features); + let expected_totals = Totals { + files: 6, + directories: 3, + others: 4, + bytes: 5 + large + 5 + 5 + 5, + }; + assert_eq!(totals, expected_totals, "{:?}", features); + assert_eq!(omitted, Omitted::default()); + } + } + + /// A directory is listed through itself opened by its name, which takes + /// the permission to read it and not the one to search it. So an empty + /// one that may only be read is walked as well. + #[test] + fn walks_directories_that_may_not_be_searched() { + let tmp = TempDir::new("walk-unsearchable"); + let dir = &tmp.0; + fs::create_dir(dir.join("read-only")).unwrap(); + fs::set_permissions(dir.join("read-only"), fs::Permissions::from_mode(0o400)).unwrap(); + let (whole, totals, _) = walked(dir, Features::DEFAULT, AddFlags::NONE).unwrap(); + assert_eq!(names(&whole), ["read-only"]); + assert_eq!(object(&whole, "read-only").inode().mode().unwrap().bits(), 0o400); + assert_eq!(totals.directories, 2); + } + + /// A tree of nested directories: `a` (0700) with `b` (0750) with `c` + /// (0755) with `file`, a symbolic link `a/link` to `b`, and a regular + /// file `f`. + fn nested(name: &str) -> TempDir { + let tmp = TempDir::new(name); + let dir = &tmp.0; + fs::create_dir_all(dir.join("a/b/c")).unwrap(); + fs::write(dir.join("a/b/c/file"), b"deep").unwrap(); + for (directory, mode) in [("a/b/c", 0o755), ("a/b", 0o750), ("a", 0o700)] { + fs::set_permissions(dir.join(directory), fs::Permissions::from_mode(mode)).unwrap(); + } + symlink("b", dir.join("a/link")).unwrap(); + fs::write(dir.join("f"), b"f").unwrap(); + tmp + } + + /// The names the specification reserves for the manifest are passed + /// over at the top of a tree, whatever the file is, and uncounted. + /// Further down they are names like any other. + #[test] + fn passes_over_reserved_names() { + let tmp = TempDir::new("walk-reserved"); + let dir = &tmp.0; + fs::write(dir.join("Uapi16Manifest"), b"").unwrap(); + fs::write(dir.join("Uapi16Manifest.sig"), b"").unwrap(); + fs::create_dir(dir.join("Uapi16Manifest.d")).unwrap(); + fs::write(dir.join("Uapi16Manifest.d/x"), b"").unwrap(); + fs::create_dir(dir.join("sub")).unwrap(); + fs::write(dir.join("sub/Uapi16Manifest"), b"").unwrap(); + let (whole, _, omitted) = walked(dir, Features::DEFAULT, AddFlags::NONE).unwrap(); + assert_eq!(names(&whole), ["sub", "sub/Uapi16Manifest"]); + assert_eq!(omitted, Omitted::default()); + } + + /// A name a manifest cannot hold fails the walk, naming the directory, + /// with the name as it is and the rule it breaks. Where the walk skips + /// such names, the entry is left out, a directory with everything below + /// it, and counted once for every walk that skipped it. + #[test] + fn unwritable_names() { + let unwritable: [(&[u8], NameProblem); 4] = [ + (b"\xff", NameProblem::NotUtf8), + (b"control\x01", NameProblem::ContainsControlCharacter), + (b"delete\x7f", NameProblem::ContainsControlCharacter), + ("non\u{fffe}character".as_bytes(), NameProblem::ContainsNoncharacter), + ]; + for (i, (bad, problem)) in unwritable.iter().enumerate() { + let tmp = TempDir::new(&format!("walk-unwritable-{}", i)); + let dir = &tmp.0; + fs::create_dir(dir.join("sub")).unwrap(); + fs::write(dir.join("sub/ok"), b"").unwrap(); + let bad_path = dir.join("sub").join(OsString::from_vec(bad.to_vec())); + fs::create_dir(&bad_path).unwrap(); + fs::create_dir(bad_path.join("below")).unwrap(); + fs::write(bad_path.join("below/file"), b"").unwrap(); + let e = walked(dir, Features::DEFAULT, AddFlags::NONE).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::UnwritableName), "{}", e); + assert_eq!(e.name(), Some("sub")); + assert_eq!(e.raw_name(), Some(OsStr::from_bytes(bad))); + assert_eq!(e.name_problem(), Some(*problem)); + let graceful = AddFlags::GRACEFUL; + let (whole, _, omitted) = walked(dir, Features::DEFAULT, graceful).unwrap(); + assert_eq!(names(&whole), ["sub", "sub/ok"]); + assert_eq!(omitted.entries, 1); + } + } + + /// A name longer than a manifest holds is unwritable at the directory + /// whose entry it is, and a walk that skips such names stops there. + #[test] + fn names_too_long() { + let tmp = TempDir::new("walk-long"); + let component = "d".repeat(200); + let level = CString::new(component.as_str()).unwrap(); + let mut dir = open_path(&tmp.0); + let mut depth = 0; + // One more component than a name has room for, which takes paths + // longer than the kernel takes, so the directories are made below + // each other by descriptor. + while depth * (component.len() + 1) <= Name::MAX_LEN + component.len() { + rustix::fs::mkdirat(&dir, level.as_c_str(), rustix::fs::Mode::RWXU).unwrap(); + let flags = OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC; + dir = rustix::fs::openat(&dir, level.as_c_str(), flags, rustix::fs::Mode::empty()).unwrap(); + depth += 1; + } + // How many components a name has room for, with a separator after + // every one but the last. + let fits = (Name::MAX_LEN + 1) / (component.len() + 1); + let e = walked(&tmp.0, Features::NONE, AddFlags::NONE).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::UnwritableName)); + assert_eq!(e.name_problem(), Some(NameProblem::TooLong)); + let parent = vec![component.as_str(); fits].join("/"); + assert_eq!(e.name(), Some(parent.as_str())); + assert_eq!(e.raw_name(), Some(OsStr::new(&component))); + let (whole, _, omitted) = walked(&tmp.0, Features::NONE, AddFlags::GRACEFUL).unwrap(); + assert_eq!((whole.objects.len(), omitted.entries), (fits, 1)); + } + + /// The status of a file that a test makes up, with the owner `uid` and + /// `gid` and the modification time `mtime`. + fn made_up(uid: u32, gid: u32, mtime: Timestamp) -> Status { + Status { + identity: Identity { + mount: MountId::Unique(1), + device: DeviceNumber { major: 8, minor: 1 }, + inode: 2, + subvolume: None, + }, + file_type: FileType::RegularFile, + mode: Mode::from_st_mode(0o644), + nlink: 1, + uid, + gid, + size: 0, + mtime, + ctime: mtime, + btime: None, + rdev: DeviceNumber { major: 0, minor: 0 }, + } + } + + /// The IDs 65535 and 4294967295 and a time before 1970 or after 2554 + /// are left out and counted. Everything else is taken as it is. + #[test] + fn fields_a_manifest_cannot_hold() { + /// The nanoseconds of a second. + const SECOND: u64 = 1_000_000_000; + let features = Features::UID | Features::GID | Features::MTIME; + let time = |seconds, nanoseconds| Timestamp { seconds, nanoseconds }; + let last = u64::MAX; + let last_second = i64::try_from(last / SECOND).unwrap(); + let last_nanosecond = u32::try_from(last % SECOND).unwrap(); + let cases = [ + (made_up(0, 0, time(0, 0)), (Some(0), Some(0), Some(0)), 0), + ( + made_up(65534, 1, time(1, 5)), + (Some(65534), Some(1), Some(SECOND + 5)), + 0, + ), + (made_up(65535, 4294967295, time(1, 0)), (None, None, Some(SECOND)), 2), + (made_up(4294967295, 65535, time(-1, 0)), (None, None, None), 3), + (made_up(1, 1, time(-1, 999_999_999)), (Some(1), Some(1), None), 1), + ( + made_up(1, 1, time(last_second, last_nanosecond)), + (Some(1), Some(1), Some(last)), + 0, + ), + ( + made_up(1, 1, time(last_second, last_nanosecond + 1)), + (Some(1), Some(1), None), + 1, + ), + (made_up(1, 1, time(i64::MAX, 999_999_999)), (Some(1), Some(1), None), 1), + ]; + for (status, (uid, gid, mtime), left_out) in cases { + let (inode, omitted) = InodeAttributes::of_status(&status, features); + assert_eq!( + (inode.uid(), inode.gid(), inode.mtime_nsec()), + (uid, gid, mtime), + "{:?}", + status + ); + assert_eq!(omitted, left_out, "{:?}", status); + } + // Without the features nothing is taken, and nothing left out. + let (inode, omitted) = InodeAttributes::of_status(&made_up(65535, 65535, time(-1, 0)), Features::NONE); + assert_eq!((inode, omitted), (InodeAttributes::default(), 0)); + } + + /// A file modified before 1970 is listed without its time, which is + /// counted. + #[test] + fn times_before_1970() { + let tmp = TempDir::new("walk-old"); + let dir = &tmp.0; + let path = dir.join("old"); + fs::write(&path, b"").unwrap(); + let old = UNIX_EPOCH - Duration::from_secs(86400); + File::options() + .write(true) + .open(&path) + .unwrap() + .set_modified(old) + .unwrap(); + let features = Features::DEFAULT | Features::MTIME; + let (whole, _, omitted) = walked(dir, features, AddFlags::NONE).unwrap(); + assert_eq!(object(&whole, "old").inode().mtime(), None); + assert!(whole.root.inode().mtime().is_some()); + assert_eq!(omitted.fields, 1); + } + + /// Does steps of `budget` of the add `add` of `build` until it is done, + /// calling `between` after every step with how many there were, and + /// returns how many it took. + fn in_steps(build: &mut Build, add: Add<'_>, budget: u64, mut between: impl FnMut(u64)) -> Result { + let mut task = Walker::begin(add); + let mut steps = 0; + loop { + steps += 1; + if build.walker.step(&mut task, budget)?.is_break() { + return Ok(steps); + } + between(steps); + } + } + + /// The add of all of the directory `top` refers to as the root. + fn all_of(top: &OwnedFd, flags: AddFlags) -> Add<'_> { + Add::Tree { + top: top.as_fd(), + flags, + } + } + + /// A walk in steps of any budget comes to the manifest a walk in one go + /// comes to, and a large file is hashed over several of them. A step + /// without a budget does nothing. + #[test] + fn walks_in_steps() { + let tmp = nested("walk-steps"); + let dir = &tmp.0; + let large: Vec = (0..65536 + 3).map(|i| (i % 251) as u8).collect(); + fs::write(dir.join("a/large"), large).unwrap(); + fs::hard_link(dir.join("a/large"), dir.join("a/b/large-too")).unwrap(); + let features = Features::DEFAULT | Features::MTIME; + let (whole, _, _) = walked(dir, features, AddFlags::NONE).unwrap(); + let top = open_path(dir); + let mut counted = Vec::new(); + for budget in [1, 4096, STEP_BUDGET] { + let mut build = Build::new(features); + let steps = in_steps(&mut build, all_of(&top, AddFlags::NONE), budget, |_| {}).unwrap(); + counted.push(steps); + let (stepped, _, _) = build.finish().unwrap(); + assert_eq!(stepped, whole, "{}", budget); + } + // The large file alone takes as many steps as budgets of its data. + assert!(counted[1] > 2 * 65536 / 4096, "{:?}", counted); + assert!(counted[0] > counted[1] && counted[1] > counted[2], "{:?}", counted); + let mut build = Build::new(features); + let mut task = Walker::begin(all_of(&top, AddFlags::NONE)); + for _ in 0..3 { + assert!(build.walker.step(&mut task, 0).unwrap().is_continue()); + } + while build.walker.step(&mut task, STEP_BUDGET).unwrap().is_continue() {} + // Nothing is left of an add that is done, whatever the budget. + for budget in [0, 1, STEP_BUDGET] { + assert!(build.walker.step(&mut task, budget).unwrap().is_break()); + } + assert_eq!(build.finish().unwrap().0, whole); + } + + /// The turn that opens a file counts as [`OPEN`] bytes of data on top + /// of its name. So a step gets through as many files as its budget has + /// room for, and a walk of small files takes steps as the data of a + /// large file does. + #[test] + fn opening_a_file_counts() { + /// How many files the tree has, and how many a step has budget for. + const FILES: u64 = 200; + const EACH: u64 = 10; + let tmp = TempDir::new("walk-open-counts"); + let dir = &tmp.0; + for number in 0..FILES { + fs::write(dir.join(format!("f{:03}", number)), b"").unwrap(); + } + let top = open_path(dir); + let mut build = Build::new(Features::NONE); + let steps = in_steps(&mut build, all_of(&top, AddFlags::NONE), EACH * OPEN, |_| {}).unwrap(); + // The name of a file and the turn that hands its object over count + // as well, so a step has not quite the budget for the last of its + // files, and the walk a few steps more. + assert!((FILES / EACH..=FILES / (EACH - 1) + 2).contains(&steps), "{}", steps); + } + + /// Waits until the change time of the directory `dir` moves past that of + /// `before`, making files in it, which changes it. + fn change(dir: &Path, before: &fs::Metadata) { + for i in 0..1000 { + fs::write(dir.join(format!("new-{}", i)), b"").unwrap(); + let now = fs::symlink_metadata(dir).unwrap(); + if (now.ctime(), now.ctime_nsec()) != (before.ctime(), before.ctime_nsec()) { + return; + } + std::thread::sleep(Duration::from_millis(1)); + } + panic!("the change time of {:?} does not move", dir); + } + + /// Waits until the clock is far enough past the change time of `dir` + /// that a change gives it another one. The time of a change can come + /// from a clock that is a tick of up to 10 ms behind. + fn past_change_time(dir: &Path) { + let meta = fs::symlink_metadata(dir).unwrap(); + let ctime = UNIX_EPOCH + Duration::new(meta.ctime() as u64, meta.ctime_nsec() as u32); + while SystemTime::now() < ctime + Duration::from_millis(20) { + std::thread::sleep(Duration::from_millis(1)); + } + } + + /// A directory that gets a new entry while it is listed changed while + /// it was read, and so did one whose entries are gone before it lists + /// the next one, and one whose entry is gone between the listing and + /// its open. A file that changes while its data is read changed as + /// well. + #[test] + fn changes_while_walked() { + let tmp = TempDir::new("walk-changes"); + let dir = &tmp.0; + for i in 0..5 { + fs::write(dir.join(format!("f{}", i)), b"").unwrap(); + } + let before = fs::symlink_metadata(dir).unwrap(); + let top = open_path(dir); + // Two steps of one turn each go into the directory. + let mut build = Build::new(Features::NONE); + let e = in_steps(&mut build, all_of(&top, AddFlags::NONE), 1, |steps| { + if steps == 2 { + change(dir, &before); + } + }) + .unwrap_err(); + assert_eq!((e.kind(), e.name()), (ErrorKind::Tree(TreeProblem::Changed), Some(""))); + // The third step takes the first entry of the listing, which has + // the names of all of them. The fourth one finds the directory + // changed. + for entry in fs::read_dir(dir).unwrap() { + fs::remove_file(entry.unwrap().path()).unwrap(); + } + let names: Vec = (0..5).map(|i| format!("f{}", i)).collect(); + for name in &names { + fs::write(dir.join(name), b"").unwrap(); + } + let mut build = Build::new(Features::NONE); + let e = in_steps(&mut build, all_of(&top, AddFlags::NONE), 1, |steps| { + if steps == 3 { + past_change_time(dir); + for name in &names { + fs::remove_file(dir.join(name)).unwrap(); + } + } + }) + .unwrap_err(); + assert_eq!((e.kind(), e.name()), (ErrorKind::Tree(TreeProblem::Changed), Some(""))); + // An entry that is gone between the comparison of its directory and + // its open. + for name in &names { + fs::write(dir.join(name), b"").unwrap(); + } + let mut build = Build::new(Features::NONE); + let mut task = Walker::begin(all_of(&top, AddFlags::NONE)); + for _ in 0..2 { + assert!(build.walker.step(&mut task, 1).unwrap().is_continue()); + } + let walk = task.walk.as_mut().unwrap(); + let listed = walk.levels.last_mut().unwrap().entries.next().unwrap().unwrap(); + let name = listed.name().to_str().unwrap().to_owned(); + fs::remove_file(dir.join(&name)).unwrap(); + let e = build.walker.entry(walk, &listed, AddFlags::NONE).unwrap_err(); + assert_eq!( + (e.kind(), e.name()), + (ErrorKind::Tree(TreeProblem::Changed), Some(name.as_str())) + ); + assert!(e.to_string().contains("removed or renamed"), "{}", e); + // A file that grows while it is hashed. + fs::write(dir.join("large"), vec![1; 3 * DATA_BUFFER_SIZE]).unwrap(); + let mut build = Build::new(Features::DEFAULT); + let mut task = Walker::begin(all_of(&top, AddFlags::NONE)); + let mut grown = false; + let e = loop { + match build.walker.step(&mut task, 4096) { + Ok(flow) => assert!(flow.is_continue()), + Err(e) => break e, + } + if !grown && matches!(&task.next, Next::Read(reading) if reading.hashed > 0) { + let mut file = File::options().append(true).open(dir.join("large")).unwrap(); + file.write_all(b"!").unwrap(); + grown = true; + } + }; + assert!(grown); + assert_eq!( + (e.kind(), e.name()), + (ErrorKind::Tree(TreeProblem::Changed), Some("large")), + "{}", + e + ); + } + + /// The entries a walk in steps began to read, by name, and those whose + /// data it read. + #[derive(Debug, Default)] + struct Reads { + entries: Vec, + data: Vec, + } + + impl Reads { + /// Notes what the add `task` reads between two of its steps. + fn note(&mut self, task: &Task<'_>) { + let Next::Read(reading) = &task.next else { + return; + }; + let name = reading.object.name().as_str(); + if self.entries.last().map(String::as_str) != Some(name) { + self.entries.push(name.to_owned()); + } + let read = reading.hashed > 0 || reading.data.is_some(); + if read && self.data.last().map(String::as_str) != Some(name) { + self.data.push(name.to_owned()); + } + } + } + + /// Walks all of `dir` in steps of one turn until the walk fails, and + /// calls `rename` between two steps until it says that it renamed + /// something. Returns the error, what the walk read, and how many + /// entries and data it had read before the rename. + fn renamed_while_walked( + dir: &Path, + mut rename: impl FnMut(&Reads, &Task<'_>) -> bool, + ) -> (Error, Reads, (usize, usize)) { + let mut build = Build::new(Features::DEFAULT); + let top = open_path(dir); + let mut task = Walker::begin(all_of(&top, AddFlags::NONE)); + let mut reads = Reads::default(); + let mut before = None; + loop { + match build.walker.step(&mut task, 1) { + Ok(flow) => assert!(flow.is_continue(), "the walk ended, having read {:?}", reads), + Err(e) => return (e, reads, before.expect("a rename while the walk went on")), + } + reads.note(&task); + if before.is_none() && rename(&reads, &task) { + before = Some((reads.entries.len(), reads.data.len())); + } + } + } + + /// The names of the entries of `dir` in the order of a walk, which is + /// that of readdir() as long as the directory doesn't change. + fn listing_order(dir: &Path) -> Vec { + fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect() + } + + /// Whether `task` is between two entries of the root of its walk. + fn between_entries_of_root(task: &Task<'_>) -> bool { + matches!(task.next, Next::List) && task.walk.as_ref().is_some_and(|walk| walk.levels.len() == 1) + } + + /// A rename in a directory stops a walk before the next entry, and + /// nothing is read again under another name: a directory with what is + /// below it, a file whose data was read, a symbolic link, and a file + /// renamed over the name that is listed next. A rename while an entry + /// is read lets that entry finish, and nothing more is read. + #[test] + fn renames_while_walked() { + let tree = |case: &str| { + let tmp = TempDir::new(&format!("walk-renames-{}", case)); + let dir = &tmp.0; + for i in 0..3 { + fs::create_dir(dir.join(format!("d{}", i))).unwrap(); + fs::write(dir.join(format!("d{}/a", i)), b"below").unwrap(); + fs::write(dir.join(format!("f{}", i)), format!("data of f{}", i)).unwrap(); + symlink("target", dir.join(format!("l{}", i))).unwrap(); + } + let order = listing_order(dir); + (tmp, order) + }; + let check = |(e, reads, before): (Error, Reads, (usize, usize)), case: &str| { + assert_eq!( + (e.kind(), e.name()), + (ErrorKind::Tree(TreeProblem::Changed), Some("")), + "{}: {}", + case, + e + ); + assert_eq!((reads.entries.len(), reads.data.len()), before, "{}: {:?}", case, reads); + }; + for (case, kind) in [("directory", 'd'), ("file", 'f'), ("symlink", 'l')] { + let (tmp, order) = tree(case); + let dir = &tmp.0; + let target = order[..order.len() - 1] + .iter() + .find(|name| name.starts_with(kind)) + .unwrap() + .clone(); + let result = renamed_while_walked(dir, |reads, task| { + if !reads.entries.contains(&target) || !between_entries_of_root(task) { + return false; + } + past_change_time(dir); + fs::rename(dir.join(&target), dir.join(format!("{}-renamed", target))).unwrap(); + true + }); + check(result, case); + } + // In a tree of regular files every name but the last is followed by + // one a file can be renamed over. + let tmp = TempDir::new("walk-renames-over"); + let dir = &tmp.0; + for i in 0..5 { + fs::write(dir.join(format!("f{}", i)), format!("data of f{}", i)).unwrap(); + } + let order = listing_order(dir); + let (target, next) = (&order[0], &order[1]); + let result = renamed_while_walked(dir, |reads, task| { + if !reads.entries.contains(target) || !between_entries_of_root(task) { + return false; + } + past_change_time(dir); + fs::rename(dir.join(target), dir.join(next)).unwrap(); + true + }); + check(result, "over the next name"); + let (tmp, order) = tree("while-read"); + let dir = &tmp.0; + let result = renamed_while_walked(dir, |_, task| { + let Next::Read(reading) = &task.next else { + return false; + }; + let in_root = task.walk.as_ref().is_some_and(|walk| walk.levels.len() == 1); + if !in_root || reading.hashed == 0 || reading.data.is_some() { + return false; + } + let other = order + .iter() + .find(|name| *name != reading.object.name().as_str()) + .unwrap(); + past_change_time(dir); + fs::rename(dir.join(other), dir.join(format!("{}-renamed", other))).unwrap(); + true + }); + check(result, "while an entry is read"); + } + + /// Two names of one inode are held against each other with the hash of + /// their data where the manifest records hard links, also where it + /// records no hashes: data that is written over with the same size and + /// the modification time set back is another file. + #[test] + fn hard_links_are_held_against_their_data() { + let tmp = TempDir::new("walk-hard-links"); + let dir = &tmp.0; + fs::write(dir.join("a"), b"first").unwrap(); + fs::hard_link(dir.join("a"), dir.join("b")).unwrap(); + let features = Features::DEFAULT.without(Features::SHA256); + let top = open_path(dir); + let mut build = Build::new(features); + let mut task = Walker::begin(all_of(&top, AddFlags::NONE)); + // Steps of one turn each, until the first of the two names went to + // the listing. + let mut reads = Reads::default(); + while reads.entries.len() < 2 || !between_entries_of_root(&task) { + assert!(build.walker.step(&mut task, 1).unwrap().is_continue()); + reads.note(&task); + } + let (first, second) = match reads.entries[1].as_str() { + "a" => ("a", "b"), + _ => ("b", "a"), + }; + let mtime = fs::symlink_metadata(dir.join("a")).unwrap().modified().unwrap(); + let mut file = File::options().write(true).open(dir.join("a")).unwrap(); + file.write_all(b"other").unwrap(); + file.set_modified(mtime).unwrap(); + let e = build.walker.step(&mut task, STEP_BUDGET).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::HardlinkMismatch)); + assert_eq!((e.name(), e.hardlink_name()), (Some(second), Some(first))); + // Left alone they share a token, without a hash in the manifest. + let (whole, _, _) = walked(dir, features, AddFlags::NONE).unwrap(); + let (a, b) = (object(&whole, "a"), object(&whole, "b")); + assert_eq!(a.inode_token(), b.inode_token()); + assert!(a.inode_token().is_some() && a.sha256().is_none()); + } + + /// A device node has its device numbers where the manifest records + /// them, and none where it does not. /dev/null is there without a + /// namespace. + #[test] + fn device_numbers() { + let null = fs::metadata("/dev/null").unwrap(); + let numbers = ( + Some(u64::from(rustix::fs::major(null.rdev()))), + Some(u64::from(rustix::fs::minor(null.rdev()))), + ); + let status = Status::of(open_path(Path::new("/dev/null")).as_fd()).unwrap(); + let object = |features| { + let (object, omitted) = FileObject::of_status(testing::name("null"), &status, features).unwrap(); + assert_eq!(omitted, 0); + object + }; + let device = object(Features::DEFAULT); + assert_eq!(device.inode_type(), InodeType::CharDevice); + assert_eq!((device.major(), device.minor()), numbers); + assert_eq!((device.size(), device.sha256()), (None, None)); + let unrecorded = object(Features::DEFAULT.without(Features::DEVICE)); + assert_eq!((unrecorded.major(), unrecorded.minor()), (None, None)); + } + + /// A walk goes as deep as a tree goes, with a descriptor for every + /// directory it is in. + #[test] + fn deep_trees() { + let tmp = TempDir::new("walk-deep"); + let mut path = tmp.0.clone(); + let mut deep = Vec::new(); + let mut name = String::new(); + for _ in 0..300 { + name = if name.is_empty() { + "d".into() + } else { + format!("{}/d", name) + }; + path.push("d"); + deep.push(name.clone()); + } + fs::create_dir_all(&path).unwrap(); + fs::write(path.join("file"), b"bottom").unwrap(); + deep.push(format!("{}/file", name)); + let (whole, _, _) = walked(&tmp.0, Features::DEFAULT, AddFlags::NONE).unwrap(); + let listed: Vec<&str> = deep.iter().map(String::as_str).collect(); + assert_eq!(names(&whole), listed); + } + + /// A walk passes over the files of the manifest's own, wherever they + /// are in a tree: the file it is told to, the manifest itself, and what + /// the scratch space of its listing has among its files, as it has + /// every scratch file it made. They are known by their inodes, so one + /// that has another name by the time the walk comes to it is passed + /// over as well. A file system can give two files one inode. So a file + /// that has the inode of one of them and is another file, by its + /// status, is a file of the tree and is listed. Here the manifest is + /// kept under the inode of such a file as well, as that file system + /// would have it. + #[test] + fn passes_over_its_own_files() { + let tmp = TempDir::new("walk-own"); + let dir = &tmp.0; + fs::create_dir(dir.join("below")).unwrap(); + for name in ["manifest", "below/scratch", "other", "below/other", "same-number"] { + fs::write(dir.join(name), name).unwrap(); + } + let open = |name: &str| Arc::new(File::open(dir.join(name)).unwrap()); + let inode_of = |name: &str| { + let status = Status::of(open_path(&dir.join(name)).as_fd()).unwrap(); + status.identity.inode_id() + }; + let scratch_dir = TempDir::new("walk-own-scratch"); + let mut scratch = Scratch::beside(ScratchFile::open_directory(&scratch_dir.0).unwrap().into()); + let own = scratch.own_files_mut(); + own.keep(inode_of("below/scratch"), open("below/scratch")); + let listing = Listing::new(Features::DEFAULT, Order::CodePoint, scratch); + let mut build = Build { + walker: Walker::new(Features::DEFAULT, listing), + _scratch: scratch_dir, + }; + let manifest = open("manifest"); + build.walker.pass_over(inode_of("manifest"), Arc::clone(&manifest)); + build.walker.pass_over(inode_of("same-number"), manifest); + // As a file system renames a file that is unlinked while it is open. + fs::rename(dir.join("below/scratch"), dir.join("below/.kept")).unwrap(); + build.add_all(open_path(dir).as_fd(), AddFlags::NONE).unwrap(); + let (whole, _, _) = build.finish().unwrap(); + assert_eq!(names(&whole), ["below", "below/other", "other", "same-number"]); + } + + /// A file system that gives two files one inode can give it to two of + /// the files of the manifest's own. A walk passes over both then: a + /// file that is kept with the inode of one that was kept before does + /// not take its place, and both stay open while the walker is there. A + /// file of the tree that has their inode and the status of neither is + /// listed. Here each of the two is kept under its own inode, under that + /// of the other one and under that of such a file of the tree, as that + /// file system would have them. + #[test] + fn passes_over_own_files_with_one_inode() { + let tmp = TempDir::new("walk-own-one-inode"); + let dir = &tmp.0; + fs::create_dir(dir.join("below")).unwrap(); + let files = [ + ("older", "the older one"), + ("below/newer", "newer"), + ("same-number", "of the tree"), + ("other", "other"), + ("below/other", "other"), + ]; + for (name, data) in files { + fs::write(dir.join(name), data).unwrap(); + } + let open = |name: &str| Arc::new(File::open(dir.join(name)).unwrap()); + let inode_of = |name: &str| { + let status = Status::of(open_path(&dir.join(name)).as_fd()).unwrap(); + status.identity.inode_id() + }; + let mut build = Build::new(Features::DEFAULT); + let (older, newer) = (open("older"), open("below/newer")); + for name in ["older", "below/newer", "same-number"] { + build.walker.pass_over(inode_of(name), Arc::clone(&older)); + build.walker.pass_over(inode_of(name), Arc::clone(&newer)); + } + build.add_all(open_path(dir).as_fd(), AddFlags::NONE).unwrap(); + // What the walker has of the two, next to the test. + let held = (Arc::strong_count(&older) - 1, Arc::strong_count(&newer) - 1); + let (whole, _, _) = build.finish().unwrap(); + assert_eq!(names(&whole), ["below", "below/other", "other", "same-number"]); + assert_eq!(held, (3, 3)); + } + + /// Where the status of a file of the manifest's own can't be read, a + /// walk can't tell a file that has its inode from it. The add fails + /// with the error of that status at the first such file. The error + /// names the file, and its message says that it is a file of the + /// manifest's own that can't be read. Here that file is the directory + /// procfs has for the descriptors of a process that is gone by the time + /// the walk asks: the kernel refuses its status with ENOENT then, since + /// Linux 6.2. The test is skipped where the kernel still reads it. + #[test] + fn own_files_that_cannot_be_read() { + let tmp = TempDir::new("walk-own-unread"); + let dir = &tmp.0; + fs::create_dir(dir.join("below")).unwrap(); + fs::write(dir.join("below/file"), b"file").unwrap(); + fs::write(dir.join("other"), b"other").unwrap(); + // A process that is there until its input ends. + let mut child = Command::new("cat") + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .spawn() + .unwrap(); + let gone = File::open(format!("/proc/{}/fd", child.id())).unwrap(); + drop(child.stdin.take()); + child.wait().unwrap(); + match Status::of(gone.as_fd()) { + Err(Failure::Io(e)) => assert_eq!(e.raw_os_error(), Some(libc::ENOENT)), + read => { + eprintln!( + "skipping: the descriptors of a process that is gone have a status: {:?}", + read + ); + return; + } + } + let file = Status::of(open_path(&dir.join("below/file")).as_fd()).unwrap(); + let mut build = Build::new(Features::DEFAULT); + build.walker.pass_over(file.identity.inode_id(), Arc::new(gone)); + let e = build.add_all(open_path(dir).as_fd(), AddFlags::NONE).unwrap_err(); + assert_eq!( + (e.kind(), e.io_error().and_then(io::Error::raw_os_error), e.name()), + (ErrorKind::Io, Some(libc::ENOENT), Some("below/file")) + ); + assert_eq!( + e.to_string(), + "below/file: a file of the manifest's own with its inode can't be read: \ + No such file or directory (os error 2)" + ); + } + + /// A feature that can't be read fails the walk at the first file it + /// can't be read of, naming the file and the feature. A walk asks the + /// file system of the directory it starts at for the DOS attributes + /// with that directory, the root, which has none itself. So the walk of + /// a tree without DOS attributes fails at the root. Whether a file is + /// read-only never fails. + #[test] + fn features_that_cannot_be_read() { + let tmp = nested("walk-unreadable"); + let dir = &tmp.0; + let Err(e) = walked(dir, Features::FLAG_HIDDEN, AddFlags::NONE) else { + eprintln!("skipping: the temporary directory has DOS attributes"); + return; + }; + assert_eq!( + (e.kind(), e.name(), e.feature()), + ( + ErrorKind::Tree(TreeProblem::FeatureUnavailable), + Some(""), + Some(Features::FLAG_HIDDEN) + ), + "{}", + e + ); + walked(dir, Features::DEFAULT | Features::READ_ONLY, AddFlags::NONE).unwrap(); + } + + /// A regular file with more data than is hashed fails the walk with + /// EFBIG where its data is hashed, in the first steps of the walk, + /// before anything is read of it. Its size is recorded where its data + /// is not hashed, and a file of the most data that is hashed begins to + /// be read. + #[test] + fn files_too_large_to_hash() { + let tmp = TempDir::new("walk-too-large"); + let dir = &tmp.0; + let file = File::create(dir.join("large")).unwrap(); + if let Err(e) = file.set_len(DataHash::MAX_SIZE + 1) { + eprintln!("skipping: the temporary directory takes no file of that size: {}", e); + return; + } + let top = open_path(dir); + // Reading the file through would take a quarter of an hour. So the + // walk is done in steps of one byte, and only its first ones. + const FIRST_STEPS: usize = 8; + let mut build = Build::new(Features::DEFAULT); + let mut task = Walker::begin(all_of(&top, AddFlags::NONE)); + let failed = (0..FIRST_STEPS).find_map(|_| build.walker.step(&mut task, 1).err()); + let e = failed.expect("the walk fails before it reads"); + assert_eq!( + (e.io_error().and_then(io::Error::raw_os_error), e.name()), + (Some(libc::EFBIG), Some("large")) + ); + // The file is not opened for that, so one that may not be opened + // fails for its size, also where its extended attributes are read + // through the file that is opened for its data. That takes a root + // whose extended attributes can be read. + fs::set_permissions(dir.join("large"), fs::Permissions::from_mode(0o000)).unwrap(); + let mut closed = Build::new(Features::DEFAULT | Features::USER_XATTR); + let mut task = Walker::begin(all_of(&top, AddFlags::NONE)); + let failed = (0..FIRST_STEPS).find_map(|_| closed.walker.step(&mut task, 1).err()); + match failed.expect("the walk fails before it reads") { + e if e.kind() == ErrorKind::Tree(TreeProblem::FeatureUnavailable) => { + eprintln!("skipping extended attributes: {}", e); + } + e => assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::EFBIG)), + } + fs::set_permissions(dir.join("large"), fs::Permissions::from_mode(0o644)).unwrap(); + // Without its hash it is a file like any other. + let (whole, _, _) = walked(dir, Features::MODE | Features::SIZE, AddFlags::NONE).unwrap(); + assert_eq!(object(&whole, "large").size(), Some(DataHash::MAX_SIZE + 1)); + // One byte less, and the hash of its data begins. + file.set_len(DataHash::MAX_SIZE).unwrap(); + let mut build = Build::new(Features::DEFAULT); + let mut task = Walker::begin(all_of(&top, AddFlags::NONE)); + for _ in 0..FIRST_STEPS { + assert!(build.walker.step(&mut task, 1).unwrap().is_continue()); + } + assert!(matches!(&task.next, Next::Read(reading) if reading.hash.is_some() && reading.hashed > 0)); + } + + /// Nothing is opened for its extended attributes: where the data of a + /// file is not hashed, inotify sees no open of it, and a file that may + /// not be opened is added, with no attributes if it has none. + #[test] + fn extended_attributes_open_nothing() { + let tmp = TempDir::new("walk-xattrs-open"); + let dir = &tmp.0; + fs::write(dir.join("file"), b"data").unwrap(); + fs::write(dir.join("closed"), b"data").unwrap(); + let set = rustix::fs::setxattr(dir.join("file"), "user.of the file", b"1", XattrFlags::empty()); + if let Err(e) = set { + eprintln!("skipping: the temporary directory has no extended attributes: {}", e); + return; + } + let inotify = inotify::init(inotify::CreateFlags::CLOEXEC | inotify::CreateFlags::NONBLOCK).unwrap(); + for name in ["file", "closed"] { + inotify::add_watch(&inotify, dir.join(name), inotify::WatchFlags::OPEN).unwrap(); + } + fs::set_permissions(dir.join("closed"), fs::Permissions::from_mode(0o000)).unwrap(); + let features = Features::MODE | Features::SIZE | Features::USER_XATTR; + let (whole, _, _) = walked(dir, features, AddFlags::NONE).unwrap(); + let attributes = |name| { + let xattrs = object(&whole, name).inode().user_xattrs(); + xattrs.map(|xattrs| { + xattrs + .map(|(name, value)| (name.to_owned(), value.to_vec())) + .collect::>() + }) + }; + assert_eq!( + attributes("file"), + Some(vec![("of the file".to_owned(), b"1".to_vec())]) + ); + assert_eq!(attributes("closed"), Some(Vec::new())); + let mut buffer = [mem::MaybeUninit::uninit(); 4096]; + let mut events = inotify::Reader::new(&inotify, &mut buffer); + assert!(matches!(events.next(), Err(rustix::io::Errno::AGAIN))); + } + + /// The variable that tells the test binary, run again by + /// [`walks_without_procfs`] with nothing in /proc, where the tree is. + const NO_PROCFS_DIR: &str = "UAPI16_TEST_WALK_NO_PROCFS_DIR"; + + /// A walk takes no procfs where everything it reads extended attributes + /// of is open for reading anyway: the directories it lists, and the + /// regular files whose data it hashes, which are opened before their + /// attributes are read. A file that is not opened, such as a FIFO, + /// can't have its attributes read without one. The test binary runs + /// this test again with an empty tmpfs over /proc, in a user and a + /// mount namespace from unshare(1), and it is skipped where unshare + /// can't make them. + /// + /// Without O_EMPTYPATH a regular file and the directory of a caller are + /// opened through procfs, by pathrs, which panics where there is none. + /// So the test is skipped where the kernel does not have it. + #[test] + fn walks_without_procfs() { + if let Some(dir) = std::env::var_os(NO_PROCFS_DIR) { + return check_without_procfs(Path::new(&dir)); + } + let tmp = TempDir::new("walk-no-procfs"); + let dir = &tmp.0; + fs::create_dir_all(dir.join("tree/dir")).unwrap(); + fs::write(dir.join("tree/dir/file"), b"data").unwrap(); + for (name, value) in [("tree/dir", b"2"), ("tree/dir/file", b"1")] { + let set = rustix::fs::setxattr(dir.join(name), "user.of it", value, XattrFlags::empty()); + if let Err(e) = set { + eprintln!("skipping: the temporary directory has no extended attributes: {}", e); + return; + } + } + let works = Command::new("unshare").args(["-Urm", "true"]).output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urm does not work here"); + return; + } + if !testing::has_empty_path() { + eprintln!("skipping: the kernel has no O_EMPTYPATH"); + return; + } + let script = concat!( + r#"mount -t tmpfs tmpfs /proc && "#, + r#"exec "$1" --exact walk::tests::walks_without_procfs --nocapture"# + ); + let output = Command::new("unshare") + .args(["-Urm", "sh", "-c", script, "sh"]) + .arg(std::env::current_exe().unwrap()) + .env(NO_PROCFS_DIR, dir) + .output() + .unwrap(); + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } + + /// The checks of [`walks_without_procfs`] below `dir`, with nothing in + /// /proc. + fn check_without_procfs(dir: &Path) { + assert!(fs::read_dir("/proc").unwrap().next().is_none()); + let tree = dir.join("tree"); + let features = Features::DEFAULT | Features::USER_XATTR; + let (whole, _, _) = walked(&tree, features, AddFlags::NONE).unwrap(); + assert_eq!(names(&whole), ["dir", "dir/file"]); + assert_eq!(object(&whole, "dir").inode().user_xattr("of it"), Some(&b"2"[..])); + assert_eq!(object(&whole, "dir/file").inode().user_xattr("of it"), Some(&b"1"[..])); + // A file whose data is not hashed is not opened, and neither is a + // FIFO. + let unhashed = walked(&tree, Features::MODE | Features::USER_XATTR, AddFlags::NONE); + make_fifo(&tree.join("fifo")); + for failed in [unhashed, walked(&tree, features, AddFlags::NONE)] { + let e = failed.unwrap_err(); + assert_eq!( + (e.kind(), e.feature()), + ( + ErrorKind::Tree(TreeProblem::FeatureUnavailable), + Some(Features::USER_XATTR) + ), + "{}", + e + ); + } + } + + /// The variable that names an automount point for + /// [`automount_points`]. + const AUTOMOUNT: &str = "UAPI16_TEST_AUTOMOUNT"; + + /// An automount point is added as the empty directory it is, with what + /// statx() says of it, and nothing is mounted on it: where a walk comes + /// to it, and where it is the directory a walk starts at, whether mount + /// points are crossed or not. What is read from the open file can't be + /// read of it. + /// + /// Only root can make an automount point, so the test takes one that is + /// there: `UAPI16_TEST_AUTOMOUNT` names a directory that is one and + /// that nothing is mounted on yet, such as the mount point of an + /// automount unit of systemd, or `tracing` in a debugfs that was just + /// mounted. The directory it is in is walked, without reading the data + /// of any file. Without the variable the test is skipped. + #[test] + fn automount_points() { + let Some(point) = std::env::var_os(AUTOMOUNT) else { + eprintln!("skipping: {} names no automount point", AUTOMOUNT); + return; + }; + let point = Path::new(&point); + let name = point.file_name().unwrap().to_str().unwrap(); + let top = open_path(point.parent().unwrap()); + let in_dir = CString::new(name).unwrap(); + // A handle of it says whether something is mounted on it by now: + // it is the root of what is mounted then, and no automount point. + let entry = || Entry::open_at(top.as_fd(), &in_dir).unwrap(); + assert!( + entry().is_automount(), + "{} is no automount point, or something is mounted on it", + point.display() + ); + let mode = entry().status().mode; + let below = format!("{}/", name); + for flags in [AddFlags::NONE, AddFlags::CROSS_MOUNTS] { + // Where a walk comes to it. + let (whole, _, _) = walked(point.parent().unwrap(), Features::MODE, flags).unwrap(); + let listed = object(&whole, name); + assert_eq!( + (listed.inode_type(), listed.inode().mode()), + (InodeType::Directory, Some(mode)) + ); + assert!(!names(&whole).iter().any(|other| other.starts_with(&below))); + // As the directory a walk starts at. + let (whole, _, _) = walked(point, Features::DEFAULT, flags).unwrap(); + assert!(whole.objects.is_empty()); + assert_eq!(whole.root.inode().mode(), Some(mode)); + } + // The inode flags are read from the open file, which there is none + // of. + let e = walked(point, Features::DEFAULT | Features::FLAG_NO_DUMP, AddFlags::NONE).unwrap_err(); + assert_eq!( + (e.kind(), e.name(), e.feature()), + ( + ErrorKind::Tree(TreeProblem::FeatureUnavailable), + Some(""), + Some(Features::FLAG_NO_DUMP) + ), + "{}", + e + ); + // The UUID and the volume serial number of the file system are + // read from the open file as well, and are left out and counted as + // where a file system has none. + let identified = Features::MODE | Features::FS_UUID | Features::FAT_SERIAL; + let (whole, _, omitted) = walked(point, identified, AddFlags::NONE).unwrap(); + assert!(whole.root.file_system().is_empty()); + assert_eq!(omitted.fields, 2); + assert!(entry().is_automount(), "something was mounted on {}", point.display()); + } + + /// File objects of a caller that take more room than the 32 MiB the + /// sort keeps in memory: the listing has to make room before it takes + /// the last of them. + fn large_objects() -> Vec { + (0..36u8) + .map(|number| { + let mut object = FileObject::new(testing::name(&format!("large/{:02}", number))); + let data = vec![number; 1 << 20]; + object.set_size(Some(data.len() as u64)); + object.put_contents(vec![ContentsObject::new(ContentsSource::Literal(data))]); + object + }) + .collect() + } + + /// A file object of a caller goes into the manifest next to the files of + /// a tree. Its add waits while the listing makes room for it, a step at + /// a time, and hands it over once there is room. So does the add of + /// the root as a caller describes it, and so does the walk of a tree + /// with what it read. + #[test] + fn file_objects_of_a_caller() { + let (tmp, _socket, mut names) = every_type("walk-given"); + let dir = &tmp.0; + let mut build = Build::new(Features::DEFAULT); + build.add_all(open_path(dir).as_fd(), AddFlags::NONE).unwrap(); + let mut given = FileObject::new(testing::name("given")); + given.set_size(Some(3)); + build.run(Add::Object(&given)).unwrap(); + let (whole, _, _) = build.finish().unwrap(); + names.push("given"); + assert_eq!(object(&whole, "given").size(), Some(3)); + assert_eq!(whole.objects.len(), names.len()); + // Objects the listing has to make room for. The add of the first + // one that waits is given up for the walk of a tree, which waits + // with the root it read and is given up for the add of a root, + // which finds the listing without room as well. + let top = open_path(dir); + let objects = large_objects(); + let mut inode = InodeAttributes::default(); + inode.set_mode(Some(Mode::new(0o750).unwrap())); + let file_system = FileSystemIdentity::default(); + let mut build = Build::new(Features::DEFAULT); + let (mut waited, mut root_waited) = (0, 0); + for object in &objects { + let mut task = Walker::begin(Add::Object(object)); + if build.walker.step(&mut task, 1).unwrap().is_continue() { + assert!(matches!(task.next, Next::Given(_))); + waited += 1; + // The first step of a walk reads its root, and the second + // one waits with it. + let mut walk = Walker::begin(all_of(&top, AddFlags::NONE)); + for _ in 0..2 { + assert!(build.walker.step(&mut walk, 1).unwrap().is_continue()); + assert!(matches!(walk.next, Next::Read(_))); + } + drop(walk); + let mut root = Walker::begin(Add::Root { + inode: &inode, + file_system: &file_system, + }); + while build.walker.step(&mut root, 1).unwrap().is_continue() { + assert!(matches!(root.next, Next::GivenRoot(..))); + root_waited += 1; + } + build.run(Add::Object(object)).unwrap(); + } + } + assert!(waited > 0 && root_waited > 0); + let (whole, _, _) = build.finish().unwrap(); + assert_eq!(whole.root.inode().mode(), inode.mode()); + let listed: Vec<&str> = objects.iter().map(|object| object.name().as_str()).collect(); + assert_eq!(self::names(&whole)[1..], listed); + } + + /// The add of a file object that is refused adds nothing, and the adds + /// go on as if it had not been. A walk that fails has nothing open any + /// more, and nothing is left to do of it: every later step of it does + /// nothing and breaks, whatever its budget. That holds for the walk of + /// a file that is not a directory, for the walk of a directory that + /// can't be listed, and for a walk that fails in the middle of a tree, + /// in a directory it lists: at a file that can't be opened for its + /// hash, which the error names, and at a name a manifest can't hold. + #[test] + fn what_a_failed_add_leaves() { + let tmp = nested("walk-failed"); + let dir = &tmp.0; + let top = open_path(dir); + let all = |build: &mut Build| build.add_all(top.as_fd(), AddFlags::NONE).unwrap(); + let mut clean = Build::new(Features::DEFAULT); + all(&mut clean); + let (whole, _, _) = clean.finish().unwrap(); + // A file object with an owner that no manifest may have. + let mut build = Build::new(Features::DEFAULT); + let mut refused = FileObject::new(testing::name("refused")); + refused.inode_mut().set_uid(Some(65535)); + let e = build.run(Add::Object(&refused)).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(crate::Problem::FieldOutOfRange)); + all(&mut build); + assert_eq!(build.finish().unwrap().0, whole); + // Nothing is left to do of the add of a file object or of a root + // that was refused either: every later step of it does nothing and + // breaks, whatever its budget. + let mut build = Build::new(Features::DEFAULT); + let file_system = FileSystemIdentity::default(); + let refused_adds = [ + Add::Object(&refused), + Add::Root { + inode: refused.inode(), + file_system: &file_system, + }, + ]; + for add in refused_adds { + let mut task = Walker::begin(add); + let e = build.walker.step(&mut task, STEP_BUDGET).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(crate::Problem::FieldOutOfRange)); + assert!(matches!(task.next, Next::Failed)); + for budget in [0, 1, STEP_BUDGET] { + assert!(build.walker.step(&mut task, budget).unwrap().is_break()); + } + } + all(&mut build); + assert_eq!(build.finish().unwrap().0, whole); + // Walks what `at` refers to in steps of one turn until the walk + // fails. Returns the error, and whether the walk was in a directory + // before. + let failed = |at: &OwnedFd| { + let mut build = Build::new(Features::DEFAULT); + let mut task = Walker::begin(all_of(at, AddFlags::NONE)); + let mut open = false; + let e = loop { + open |= task.walk.as_ref().is_some_and(|walk| !walk.levels.is_empty()); + match build.walker.step(&mut task, 1) { + Ok(flow) => assert!(flow.is_continue()), + Err(e) => break e, + } + }; + assert!(task.walk.is_none() && matches!(task.next, Next::Failed)); + // Nothing is left of an add that failed, whatever the budget. + for budget in [0, 1, STEP_BUDGET] { + assert!(build.walker.step(&mut task, budget).unwrap().is_break()); + } + (e, open) + }; + // A file that is not a directory. + let (e, _) = failed(&open_path(&dir.join("f"))); + assert_eq!( + (e.kind(), e.name()), + (ErrorKind::Tree(TreeProblem::NotDirectory), Some("")) + ); + // A directory that can't be listed, as one that may be searched + // only, unless the tests may read any directory. + let locked = TempDir::new("walk-failed-locked"); + fs::create_dir(locked.0.join("dir")).unwrap(); + fs::set_permissions(locked.0.join("dir"), fs::Permissions::from_mode(0o311)).unwrap(); + if fs::read_dir(locked.0.join("dir")).is_ok() { + eprintln!("skipping the directory that can't be listed: the tests may read any"); + } else { + let (e, _) = failed(&open_path(&locked.0.join("dir"))); + assert_eq!( + (e.io_error().map(io::Error::kind), e.name()), + (Some(io::ErrorKind::PermissionDenied), Some("")), + "{}", + e + ); + } + fs::set_permissions(locked.0.join("dir"), fs::Permissions::from_mode(0o755)).unwrap(); + // A file that can't be opened for its hash, in a directory the walk + // lists, unless the tests may read any file. + fs::write(locked.0.join("dir/closed"), b"data").unwrap(); + fs::set_permissions(locked.0.join("dir/closed"), fs::Permissions::from_mode(0o000)).unwrap(); + if File::open(locked.0.join("dir/closed")).is_ok() { + eprintln!("skipping the file that can't be opened: the tests may read any"); + } else { + let (e, open) = failed(&open_path(&locked.0)); + assert_eq!( + (e.io_error().map(io::Error::kind), e.name()), + (Some(io::ErrorKind::PermissionDenied), Some("dir/closed")), + "{}", + e + ); + assert!(open); + } + // In the middle of a tree, in a directory the walk lists, which the + // step that fails closes. + fs::write(dir.join(OsString::from_vec(b"\xff".to_vec())), b"").unwrap(); + let (e, open) = failed(&top); + assert_eq!(e.kind(), ErrorKind::Tree(TreeProblem::UnwritableName)); + assert!(open); + } + + /// A walk opens nothing but regular files and directories: a FIFO, a + /// socket and a symbolic link are read through their handles, whatever + /// the features read of them, and inotify sees no open of the FIFO. + #[test] + fn opens_nothing_else() { + let (tmp, _socket, _) = every_type("walk-opens"); + let dir = &tmp.0; + let inotify = inotify::init(inotify::CreateFlags::CLOEXEC | inotify::CreateFlags::NONBLOCK).unwrap(); + inotify::add_watch(&inotify, dir.join("fifo"), inotify::WatchFlags::OPEN).unwrap(); + let features = Features::DEFAULT | Features::MTIME | Features::READ_ONLY | Features::USER_XATTR; + match walked(dir, features, AddFlags::NONE) { + Ok(_) => {} + Err(e) if e.kind() == ErrorKind::Tree(TreeProblem::FeatureUnavailable) => { + eprintln!("skipping extended attributes: {}", e); + walked(dir, Features::DEFAULT | Features::READ_ONLY, AddFlags::NONE).unwrap(); + } + Err(e) => panic!("{}", e), + } + let mut buffer = [mem::MaybeUninit::uninit(); 4096]; + let mut events = inotify::Reader::new(&inotify, &mut buffer); + assert!(matches!(events.next(), Err(rustix::io::Errno::AGAIN))); + } + + /// What a walk keeps can go to another thread. + #[test] + fn send() { + fn send() {} + send::(); + send::>(); + send::>(); + } + + /// The variable that tells the test binary, run again inside the + /// namespaces of [`mounts`], where the trees with the mounts are. + const MOUNTS_DIR: &str = "UAPI16_TEST_MOUNTS_DIR"; + + /// Mount points: what a walk makes of them without crossing them and + /// with, a mount that shows a directory again inside itself, and a + /// walk that starts at a mount point. The mounts need a user and a + /// mount namespace, which unshare(1) makes, and the test binary runs + /// this test again inside them. + #[test] + fn mounts() { + if let Some(dir) = std::env::var_os(MOUNTS_DIR) { + return check_mounts(Path::new(&dir)); + } + let tmp = TempDir::new("walk-mounts"); + let dir = &tmp.0; + fs::create_dir_all(dir.join("a/tmpfs")).unwrap(); + fs::create_dir_all(dir.join("a/bind")).unwrap(); + fs::create_dir_all(dir.join("a/bind2")).unwrap(); + fs::write(dir.join("a/file-mount"), b"covered").unwrap(); + fs::set_permissions(dir.join("a/file-mount"), fs::Permissions::from_mode(0o600)).unwrap(); + fs::write(dir.join("a/device-mount"), b"covered").unwrap(); + fs::write(dir.join("a/plain"), b"plain").unwrap(); + fs::create_dir_all(dir.join("source/below")).unwrap(); + fs::set_permissions(dir.join("source"), fs::Permissions::from_mode(0o750)).unwrap(); + fs::write(dir.join("source/below/x"), b"x").unwrap(); + fs::hard_link(dir.join("source/below/x"), dir.join("source/below/y")).unwrap(); + fs::write(dir.join("shown"), b"the file the mount shows").unwrap(); + fs::set_permissions(dir.join("shown"), fs::Permissions::from_mode(0o640)).unwrap(); + fs::create_dir_all(dir.join("b/x/loop")).unwrap(); + fs::write(dir.join("b/x/file"), b"").unwrap(); + let works = Command::new("unshare").args(["-Urm", "true"]).output(); + if !works.is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urm does not work here"); + return; + } + let script = concat!( + r#"set -e; d=$1; "#, + r#"mount -t tmpfs -o mode=0711 tmpfs "$d/a/tmpfs"; "#, + r#"echo inside > "$d/a/tmpfs/inside"; mkdir "$d/a/tmpfs/nested"; "#, + r#"mount -t tmpfs -o mode=0700 tmpfs "$d/a/tmpfs/nested"; "#, + r#"echo deeper > "$d/a/tmpfs/nested/deeper"; "#, + r#"mount --bind "$d/source" "$d/a/bind"; "#, + r#"mount --bind "$d/source" "$d/a/bind2"; "#, + r#"mount --bind "$d/shown" "$d/a/file-mount"; "#, + r#"mount --bind /dev/null "$d/a/device-mount"; "#, + r#"mount --bind "$d/b" "$d/b/x/loop"; "#, + r#"exec "$2" --exact walk::tests::mounts"# + ); + let output = Command::new("unshare") + .args(["-Urm", "sh", "-c", script, "sh"]) + .arg(dir) + .arg(std::env::current_exe().unwrap()) + .env(MOUNTS_DIR, dir) + .output() + .unwrap(); + // A test binary that runs no test succeeds as well. + let ran = String::from_utf8_lossy(&output.stdout).contains("1 passed"); + assert!(output.status.success() && ran, "{:?}", output); + } + + /// The checks of [`mounts`] below `dir`. + fn check_mounts(dir: &Path) { + let a = dir.join("a"); + let features = Features::DEFAULT; + let none = AddFlags::NONE; + let crossing = AddFlags::CROSS_MOUNTS; + let mode = |whole: &Whole, name: &str| object(whole, name).inode().mode().unwrap().bits(); + // Without crossing them, a mount point that is a directory is an + // empty one with the attributes of the mounted root, and a file that + // is mounted over another one is the file the mount shows: a regular + // file with its attributes and the hash of its data, a device node + // with its attributes and its device numbers. + let (whole, _, _) = walked(&a, features, none).unwrap(); + assert_eq!( + names(&whole), + ["bind", "bind2", "device-mount", "file-mount", "plain", "tmpfs"] + ); + assert_eq!((mode(&whole, "tmpfs"), mode(&whole, "bind")), (0o711, 0o750)); + let shown = object(&whole, "file-mount"); + let data = b"the file the mount shows"; + assert_eq!( + (shown.inode_type(), mode(&whole, "file-mount"), shown.size()), + (InodeType::Regular, 0o640, Some(data.len() as u64)) + ); + assert_eq!(shown.sha256(), Some(Sha256::digest(data))); + let null = fs::metadata("/dev/null").unwrap(); + let device = object(&whole, "device-mount"); + assert_eq!( + (device.inode_type(), device.major(), device.minor()), + (InodeType::CharDevice, Some(1), Some(3)) + ); + assert_eq!(mode(&whole, "device-mount"), null.mode() & 0o7777); + assert_eq!((device.size(), device.sha256()), (None, None)); + // Crossing them, the walk goes into them. The same directory + // mounted twice next to each other is no loop and is listed twice. + let (whole, _, _) = walked(&a, features, crossing).unwrap(); + assert_eq!( + names(&whole), + [ + "bind", + "bind/below", + "bind/below/x", + "bind/below/y", + "bind2", + "bind2/below", + "bind2/below/x", + "bind2/below/y", + "device-mount", + "file-mount", + "plain", + "tmpfs", + "tmpfs/inside", + "tmpfs/nested", + "tmpfs/nested/deeper" + ] + ); + // A mount that shows a directory again inside itself is a loop where + // the walk crosses mounts, and an empty directory where it does not. + let b = dir.join("b"); + let (whole, _, _) = walked(&b, features, none).unwrap(); + assert_eq!(names(&whole), ["x", "x/file", "x/loop"]); + let e = walked(&b, features, crossing).unwrap_err(); + assert_eq!( + (e.kind(), e.name()), + (ErrorKind::Tree(TreeProblem::Loop), Some("x/loop")) + ); + // A walk that starts at a mount point walks what is mounted there, + // with the attributes of the mounted root, and the mounts below it + // are mount points. + let (whole, _, _) = walked(&a.join("tmpfs"), features, none).unwrap(); + assert_eq!(names(&whole), ["inside", "nested"]); + assert_eq!(whole.root.inode().mode().unwrap().bits(), 0o711); + assert_eq!(mode(&whole, "nested"), 0o700); + // The names of an inode reached through a bind mount are hard links + // of each other, and not of the names reached through another + // mount of the same directory. + let (whole, _, _) = walked(&a, features, crossing).unwrap(); + let token = |name| object(&whole, name).inode_token().unwrap(); + assert_eq!(token("bind/below/x"), token("bind/below/y")); + assert_ne!(token("bind/below/x"), token("bind2/below/x")); + } +} diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs index e91d74f..5be00ec 100644 --- a/src/uapi16/writer.rs +++ b/src/uapi16/writer.rs @@ -43,11 +43,11 @@ enum Stage { /// Puts a manifest together record by record, and does no I/O. /// /// [`Encoder::begin`] appends the record of the root file object to a -/// string, [`Encoder::file`] the record of a file object, -/// [`Encoder::signature`] that of a signature object and +/// string, [`Encoder::file`] the record of a file object and /// [`Encoder::finish`] that of the trailer object. Whoever calls them sends /// the records on, each one as it comes or many at once. A [`Writer`] is -/// an encoder whose records go to a [`Write`] one at a time. +/// an encoder whose records go to a [`Write`] one at a time, and writes +/// signature objects as well. /// /// An encoder checks every object the way a [`Reader`](crate::Reader) /// does, see [`Writer`], and keeps the name of the last file object for @@ -57,31 +57,10 @@ enum Stage { /// encoder goes on as if it had not been called. Nothing can follow the /// trailer object, so after [`Encoder::finish`] every method fails. /// -/// ``` -/// use uapi16::{Encoder, FileObject, NameBuf, RootObject}; -/// -/// let mut text = String::new(); -/// let mut encoder = Encoder::begin(&RootObject::default(), &mut text)?; -/// for name in ["a", "b"] { -/// encoder.file(&FileObject::new(NameBuf::new(name)?), &mut text)?; -/// } -/// encoder.finish(&mut text)?; -/// assert_eq!( -/// text, -/// concat!( -/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n", -/// "\x1e{\"name\":\"a\"}\n", -/// "\x1e{\"name\":\"b\"}\n", -/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", -/// ) -/// ); -/// # Ok::<(), Box>(()) -/// ``` -/// /// [`Write`]: std::io::Write /// [`Writer`]: crate::Writer #[derive(Debug)] -pub struct Encoder { +pub(crate) struct Encoder { /// The number of the record that is appended next. pub(crate) next_record: u64, stage: Stage, @@ -97,36 +76,35 @@ pub struct Encoder { impl Encoder { /// Starts a manifest with the root file object `root`: appends its /// record to `text`. - pub fn begin(root: &RootObject, text: &mut String) -> Result { + pub(crate) fn begin(root: &RootObject, text: &mut String) -> Result { let mut encoder = Encoder::start(root)?; encoder.append_to(text); Ok(encoder) } /// Appends the record of the file object `file` to `text`. - pub fn file(&mut self, file: &FileObject, text: &mut String) -> Result<(), Error> { + pub(crate) fn file(&mut self, file: &FileObject, text: &mut String) -> Result<(), Error> { self.encode_file(file)?; self.append_to(text); Ok(()) } - /// 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: &SignatureObject, text: &mut String) -> Result<(), Error> { - self.encode_signature(signature)?; - self.append_to(text); - Ok(()) - } - /// Ends the manifest: appends the record of the trailer object to /// `text`. - pub fn finish(&mut self, text: &mut String) -> Result<(), Error> { + pub(crate) fn finish(&mut self, text: &mut String) -> Result<(), Error> { self.encode_trailer()?; self.append_to(text); Ok(()) } + /// Appends the record that was put together to `text`. + fn append_to(&mut self, text: &mut String) { + text.push_str(std::str::from_utf8(&self.record).expect("serde_json writes UTF-8")); + self.clear_record(); + } +} + +impl Encoder { /// An encoder that puts together the record of the root file object /// `root` first. pub(crate) fn start(root: &RootObject) -> Result { @@ -164,24 +142,26 @@ impl Encoder { // symbolic link without its target, gptFlags against the fields of // its flags, and where it comes. So the record is put together // first. Admitting the object makes it the one the next one is - // checked against, which comes last. + // checked against, which comes last. FileObject::check_alone() is + // the same but for the stage and the admission. + let subject = Subject::new(file, record_number); let encoded = self .write_record(file) - .and_then(|()| file.check_strings(record_number)) + .and_then(|()| file.check_strings(subject)) .and_then(|()| match self.stage { Stage::Signatures => Err(Error::file_after_signature(record_number)), _ => Ok(()), }) - .and_then(|()| file.check(record_number)) - .and_then(|()| self.sequence_check.check_fields(file, record_number)) + .and_then(|()| file.check(subject)) + .and_then(|()| self.sequence_check.check_fields(file, subject)) .and_then(|()| self.sequence_check.admit(file, record_number)); if let Err(e) = encoded { self.clear_record(); let e = e.in_record(record_number); - return Err(if file.name.is_root() { + return Err(if file.name().is_root() { e } else { - e.named(file.name.as_str()) + e.named(file.name().as_str()) }); } self.next_record += 1; @@ -226,23 +206,27 @@ impl Encoder { /// A record larger than [`MAX_RECORD_SIZE`], its record separator /// included, is refused. fn write_record(&mut self, object: &impl Fields) -> Result<(), Error> { - self.record.clear(); - self.record.push(RECORD_SEPARATOR); - serde_json::to_writer(&mut self.record, &Json(object)).expect("a record serializes into a Vec"); - self.record.push(RECORD_END); - if self.record.len() > MAX_RECORD_SIZE { + let written = Encoder::put_together(&mut self.record, object); + if written.is_err() { self.clear_record(); + } + written + } + + /// Puts together the record of `object` in `record`, in place of what + /// it held. A record larger than [`MAX_RECORD_SIZE`], its record + /// separator included, is refused. + fn put_together(record: &mut Vec, object: &impl Fields) -> Result<(), Error> { + record.clear(); + record.push(RECORD_SEPARATOR); + serde_json::to_writer(&mut *record, &Json(object)).expect("a record serializes into a Vec"); + record.push(RECORD_END); + if record.len() > MAX_RECORD_SIZE { return Err(Error::record_too_large()); } Ok(()) } - /// Appends the record that was put together to `text`. - fn append_to(&mut self, text: &mut String) { - text.push_str(std::str::from_utf8(&self.record).expect("serde_json writes UTF-8")); - self.clear_record(); - } - /// Forgets the record that was put together. A record larger than /// [`RECORD_CAPACITY`] gives back the room it took beyond that. pub(crate) fn clear_record(&mut self) { @@ -364,6 +348,18 @@ impl Field { // attributes. So these go out only where they say more. impl RootObject { + /// Checks the root file object as a writer does that begins a manifest + /// with it, on its own: the size of its record, its strings, its + /// fields and their features, in the order a reader finds what is + /// wrong with a record, see [`Encoder::start`]. The error names no + /// record, since the object is in none yet. + pub(crate) fn check_alone(&self) -> Result<(), Error> { + Encoder::put_together(&mut Vec::new(), self) + .and_then(|()| self.check_strings()) + .and_then(|()| self.check()) + .and_then(|()| SequenceCheck::new(self.recorded_features(), self.order).check_root_fields(self)) + } + /// Checks every string the record of the root file object has, in the /// order of the keys, for what the strings of a manifest may not hold. fn check_strings(&self) -> Result<(), Error> { @@ -384,16 +380,16 @@ impl RootObject { if let Some(label) = &self.file_system.label { FileSystemIdentity::check_label(label, subject)?; } - if let Some(gid) = inode.gid { + if let Some(gid) = inode.gid() { FileObject::check_id(Field::Gid, u64::from(gid), subject)?; } - if let Some(name) = &inode.group_name { + if let Some(name) = inode.group_name() { FileObject::check_owner_name(Field::GroupName, name, subject)?; } - if let Some(uid) = inode.uid { + if let Some(uid) = inode.uid() { FileObject::check_id(Field::Uid, u64::from(uid), subject)?; } - if let Some(name) = &inode.user_name { + if let Some(name) = inode.user_name() { FileObject::check_owner_name(Field::UserName, name, subject)?; } self.check_consistency() @@ -414,21 +410,21 @@ impl Fields for RootObject { fields.display(Field::FatSerial, identity.fat_serial)?; let listed = self.features.filter(|listed| *listed != Features::DEFAULT); fields.put(Field::Features, listed.map(FeatureNames).as_ref())?; - for field in inode.flags.set_fields() { + for field in inode.flags().set_fields() { fields.bool(field, Some(true))?; } fields.string(Field::FsLabel, identity.label.as_deref())?; fields.display(Field::FsUuid, identity.uuid)?; - fields.unsigned(Field::Gid, inode.gid.map(u64::from))?; + fields.unsigned(Field::Gid, inode.gid().map(u64::from))?; fields.display(Field::GptDiskUuid, self.gpt_disk_uuid)?; - fields.string(Field::GroupName, inode.group_name.as_deref())?; - fields.unsigned(Field::MTimeNSec, inode.mtime_nsec)?; + fields.string(Field::GroupName, inode.group_name())?; + fields.unsigned(Field::MTimeNSec, inode.mtime_nsec())?; fields.string(Field::MediaType, Some(MEDIA_TYPE))?; - fields.unsigned(Field::Mode, inode.mode.map(|mode| u64::from(mode.bits())))?; + fields.unsigned(Field::Mode, inode.mode().map(|mode| u64::from(mode.bits())))?; fields.string(Field::Order, self.order.map(Order::as_str))?; - fields.bool(Field::ReadOnly, inode.read_only.filter(|&read_only| read_only))?; - fields.unsigned(Field::Uid, inode.uid.map(u64::from))?; - fields.string(Field::UserName, inode.user_name.as_deref())?; + fields.bool(Field::ReadOnly, inode.read_only().filter(|&read_only| read_only))?; + fields.unsigned(Field::Uid, inode.uid().map(u64::from))?; + fields.string(Field::UserName, inode.user_name())?; self.validity.write_fields(fields) } } @@ -443,59 +439,74 @@ impl Serialize for FeatureNames { } impl FileObject { - /// Checks every string the record of the object, the one with the - /// number `record_number`, has, in the order of the keys, for what the - /// strings of a manifest may not hold. - fn check_strings(&self, record_number: u64) -> Result<(), Error> { - let subject = Subject::new(self, record_number); - for contents in &self.contents { + /// Checks the object as a writer of a manifest that records `features` + /// in the order `order` does, on its own: all but where it comes, which + /// depends on the objects before it. That is the size of its record, + /// its strings, its fields and their features, in the order a reader + /// finds what is wrong with a record, see [`Encoder::encode_file`]. The + /// error names the object, which is in no record yet. + pub(crate) fn check_alone(&self, features: Features, order: Order) -> Result<(), Error> { + let subject = Subject::unwritten(self); + Encoder::put_together(&mut Vec::new(), self) + .and_then(|()| self.check_strings(subject)) + .and_then(|()| self.check(subject)) + .and_then(|()| SequenceCheck::new(features, Some(order)).check_fields(self, subject)) + .map_err(|e| match self.name().is_root() { + true => e, + false => e.named(self.name().as_str()), + }) + } + + /// Checks every string the record of the object, which `subject` + /// names, has, in the order of the keys, for what the strings of a + /// manifest may not hold. + fn check_strings(&self, subject: Subject<'_>) -> Result<(), Error> { + for contents in self.contents() { contents.check_strings(subject)?; } - self.inode.check_xattr_strings(subject)?; - if let Some(label) = self.gpt.as_deref().and_then(|gpt| gpt.label.as_deref()) { + self.inode().check_xattr_strings(subject)?; + if let Some(label) = self.gpt().and_then(|gpt| gpt.label.as_deref()) { Field::GptLabel.check_string(label, subject)?; } - self.inode.check_owner_strings(subject) + self.inode().check_owner_strings(subject) } - /// Checks the object, the one of the record with the number - /// `record_number`, as a reader does: the value of every field in the - /// order of the keys, each contents object's fields against each other - /// right after its values, the name, the fields its inode type permits - /// and the fields against each other. Unlike a reader it fills nothing - /// in. - fn check(&self, record_number: u64) -> Result<(), Error> { - let subject = Subject::new(self, record_number); - if self.contents.len() > MAX_CONTENTS { + /// Checks the object, which `subject` names, as a reader does: the + /// value of every field in the order of the keys, each contents + /// object's fields against each other right after its values, the + /// name, the fields its inode type permits and the fields against each + /// other. Unlike a reader it fills nothing in. + fn check(&self, subject: Subject<'_>) -> Result<(), Error> { + if self.contents().len() > MAX_CONTENTS { return Err(Error::too_many_contents(subject)); } // What each contents object says of its data. The check of the // object below takes it from here, so that no literal is hashed // twice. - let mut contents_data = Vec::with_capacity(self.contents.len()); - for contents in &self.contents { + let mut contents_data = Vec::with_capacity(self.contents().len()); + for contents in self.contents() { contents.check(subject)?; contents_data.push(contents.check_consistency(subject)?); } - let inode = &self.inode; + let inode = self.inode(); inode.check_xattr_names(subject)?; - if let Some(gid) = inode.gid { + if let Some(gid) = inode.gid() { FileObject::check_id(Field::Gid, u64::from(gid), subject)?; } - if let Some(label) = self.gpt.as_deref().and_then(|gpt| gpt.label.as_deref()) { + if let Some(label) = self.gpt().and_then(|gpt| gpt.label.as_deref()) { GptPartition::check_label(label, subject)?; } - if let Some(name) = &inode.group_name { + if let Some(name) = inode.group_name() { FileObject::check_owner_name(Field::GroupName, name, subject)?; } - if let Some(uid) = inode.uid { + if let Some(uid) = inode.uid() { FileObject::check_id(Field::Uid, u64::from(uid), subject)?; } - if let Some(name) = &inode.user_name { + if let Some(name) = inode.user_name() { FileObject::check_owner_name(Field::UserName, name, subject)?; } - if self.name.is_root() { - return Err(Error::no_name(record_number)); + if self.name().is_root() { + return Err(Error::no_name(subject)); } self.check_permitted_fields(subject)?; // The contents objects were checked above. This is for what @@ -508,8 +519,8 @@ impl FileObject { /// and of the inode flags. In the order of their names the two kinds /// mix, so the fields of the two, each kind in that order, are merged. fn write_flags(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { - let mut dos = self.dos_flags.set_fields(); - let mut inode = self.inode.flags.set_fields(); + let mut dos = self.dos_flags().set_fields(); + let mut inode = self.inode().flags().set_fields(); let (mut next_dos, mut next_inode) = (dos.next(), inode.next()); loop { let field = match (next_dos, next_inode) { @@ -538,13 +549,13 @@ impl Fields for FileObject { } fn write_fields(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { - let inode = &self.inode; - let gpt = self.gpt.as_deref(); - let contents = (!self.contents.is_empty()).then_some(ContentsList(&self.contents)); + let inode = self.inode(); + let gpt = self.gpt(); + let contents = (!self.contents().is_empty()).then_some(ContentsList(self.contents())); fields.put(Field::Contents, contents.as_ref())?; inode.write_xattrs(fields)?; self.write_flags(fields)?; - fields.unsigned(Field::Gid, inode.gid.map(u64::from))?; + fields.unsigned(Field::Gid, inode.gid().map(u64::from))?; fields.bool( Field::GptFlagGrowFileSystem, gpt.and_then(|gpt| gpt.grow_file_system).filter(|&set| set), @@ -557,24 +568,24 @@ impl Fields for FileObject { fields.string(Field::GptLabel, gpt.and_then(|gpt| gpt.label.as_deref()))?; fields.display(Field::GptTypeUuid, gpt.and_then(|gpt| gpt.type_uuid))?; fields.display(Field::GptUuid, gpt.and_then(|gpt| gpt.uuid))?; - fields.string(Field::GroupName, inode.group_name.as_deref())?; - fields.unsigned(Field::InodeToken, self.inode_token.map(NonZeroU64::get))?; - fields.unsigned(Field::MTimeNSec, inode.mtime_nsec)?; - fields.unsigned(Field::Major, self.major)?; - fields.unsigned(Field::Minor, self.minor)?; - fields.unsigned(Field::Mode, inode.mode.map(|mode| u64::from(mode.bits())))?; - fields.string(Field::Name, (!self.name.is_root()).then_some(self.name.as_str()))?; - fields.bool(Field::ReadOnly, inode.read_only.filter(|&read_only| read_only))?; - let size = fields.written(Field::Size, self.size); - let sha256 = fields.written(Field::Sha256, self.sha256.as_ref()); + fields.string(Field::GroupName, inode.group_name())?; + fields.unsigned(Field::InodeToken, self.inode_token().map(NonZeroU64::get))?; + fields.unsigned(Field::MTimeNSec, inode.mtime_nsec())?; + fields.unsigned(Field::Major, self.major())?; + fields.unsigned(Field::Minor, self.minor())?; + fields.unsigned(Field::Mode, inode.mode().map(|mode| u64::from(mode.bits())))?; + fields.string(Field::Name, (!self.name().is_root()).then_some(self.name().as_str()))?; + fields.bool(Field::ReadOnly, inode.read_only().filter(|&read_only| read_only))?; + let size = fields.written(Field::Size, self.size()); + let sha256 = fields.written(Field::Sha256, self.sha256()); fields.display(Field::Sha256, sha256.filter(|sha256| !sha256.implied_by(size)))?; fields.unsigned(Field::Size, size)?; // The specification implies the type of a regular file. - let inode_type = Some(self.inode_type).filter(|&inode_type| inode_type != InodeType::Regular); + let inode_type = Some(self.inode_type()).filter(|&inode_type| inode_type != InodeType::Regular); fields.string(Field::Type, inode_type.map(InodeType::as_str))?; - fields.unsigned(Field::Uid, inode.uid.map(u64::from))?; - fields.string(Field::UserName, inode.user_name.as_deref())?; - self.validity.write_fields(fields) + fields.unsigned(Field::Uid, inode.uid().map(u64::from))?; + fields.string(Field::UserName, inode.user_name())?; + self.validity().write_fields(fields) } } @@ -591,7 +602,7 @@ impl InodeAttributes { /// The names of the extended attributes, in the order they are /// written. fn xattr_names(&self) -> impl Iterator { - self.user_xattrs.iter().flat_map(|attributes| attributes.keys()) + self.user_xattr_map().into_iter().flat_map(BTreeMap::keys) } /// Checks the names of the extended attributes of the object `subject` @@ -604,10 +615,10 @@ impl InodeAttributes { /// Checks `groupName` and `userName`, in that order, for what the /// strings of a manifest may not hold. fn check_owner_strings(&self, subject: Subject<'_>) -> Result<(), Error> { - if let Some(name) = &self.group_name { + if let Some(name) = self.group_name() { Field::GroupName.check_string(name, subject)?; } - if let Some(name) = &self.user_name { + if let Some(name) = self.user_name() { Field::UserName.check_string(name, subject)?; } Ok(()) @@ -621,7 +632,7 @@ impl InodeAttributes { /// Writes `extendedAttributes`, unless there are none. fn write_xattrs(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { - let attributes = self.user_xattrs.as_deref().filter(|attributes| !attributes.is_empty()); + let attributes = self.user_xattr_map().filter(|attributes| !attributes.is_empty()); fields.put(Field::ExtendedAttributes, attributes.map(XattrNamespaces).as_ref()) } } @@ -881,30 +892,32 @@ mod tests { order: Some(Order::CodePoint), ..RootObject::default() }; - 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 = Some(Mode::new(0o775).unwrap()); - root.inode.uid = Some(1000); + root.inode.set_user_xattrs(Some(BTreeMap::new())); + root.inode.set_gid(Some(1000)); + root.inode.set_mtime_nsec(Some(1_699_999_000_000_000_000)); + root.inode.set_mode(Some(Mode::new(0o775).unwrap())); + root.inode.set_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 = Some(Mode::new(0o775).unwrap()); - owned.inode.uid = Some(1000); + owned.inode_mut().set_user_xattrs(Some(BTreeMap::new())); + owned.inode_mut().set_gid(Some(1000)); + owned.inode_mut().set_mtime_nsec(Some(1_699_999_000_000_000_000)); + owned.inode_mut().set_mode(Some(Mode::new(0o775).unwrap())); + owned.inode_mut().set_uid(Some(1000)); owned }; let mut file = FileObject::new(name("EFI/BOOT/BOOTX64.EFI")); - 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 = Some(Mode::new(0o664).unwrap()); - file.sha256 = "608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b" - .parse() - .ok(); - file.size = Some(4096); - file.inode.uid = Some(1000); + file.inode_mut().set_user_xattrs(Some(BTreeMap::new())); + file.inode_mut().set_gid(Some(1000)); + file.inode_mut().set_mtime_nsec(Some(1_700_000_000_000_000_000)); + file.inode_mut().set_mode(Some(Mode::new(0o664).unwrap())); + file.set_sha256( + "608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b" + .parse() + .ok(), + ); + file.set_size(Some(4096)); + file.inode_mut().set_uid(Some(1000)); let records = written(&root, |writer| { writer.file(&owned_directory("EFI")).unwrap(); writer.file(&owned_directory("EFI/BOOT")).unwrap(); @@ -935,12 +948,12 @@ mod tests { // A symbolic link with its target, a file with an attribute, the // names of one hard-linked file. let mut link = FileObject::new(name("link")); - link.inode_type = InodeType::Symlink; - 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); - link.inode.user_name = Some("brauner".into()); + link.set_inode_type(InodeType::Symlink); + link.put_contents(vec![ContentsObject::new(ContentsSource::Literal(b"a.txt".to_vec()))]); + link.inode_mut().set_gid(Some(1000)); + link.inode_mut().set_group_name(Some("brauner".into())); + link.set_size(Some(5)); + link.inode_mut().set_user_name(Some("brauner".into())); assert_eq!( record(&link), concat!( @@ -949,7 +962,7 @@ mod tests { ) ); let mut noted = FileObject::new(name("a.txt")); - noted.inode.user_xattrs = Some(Box::new(BTreeMap::from([( + noted.inode_mut().set_user_xattrs(Some(BTreeMap::from([( "comment".to_string(), b"set by make-fixtures".to_vec(), )]))); @@ -958,11 +971,11 @@ mod tests { r#"{"extendedAttributes":{"user":{"comment":{"text":"set by make-fixtures"}}},"name":"a.txt"}"# ); let mut linked = FileObject::new(name("sub/hl_a")); - linked.inode_token = NonZeroU64::new(1); - linked.size = Some(11); + linked.set_inode_token(NonZeroU64::new(1)); + linked.set_size(Some(11)); assert_eq!(record(&linked), r#"{"inodeToken":1,"name":"sub/hl_a","size":11}"#); let mut fifo = FileObject::new(name("sub/fifo")); - fifo.inode_type = InodeType::Fifo; + fifo.set_inode_type(InodeType::Fifo); assert_eq!(record(&fifo), r#"{"name":"sub/fifo","type":"fifo"}"#); // The least a manifest and an object are. assert_eq!(record(&FileObject::new(name("x"))), r#"{"name":"x"}"#); @@ -979,11 +992,11 @@ mod tests { #[test] fn leaves_out_what_the_features_imply() { let mut object = FileObject::new(name("x")); - object.dos_flags.put(DosFlags::HIDDEN, Some(false)); - object.inode.flags.put(InodeFlags::NO_DUMP, Some(false)); - object.inode.read_only = Some(false); - object.inode.user_xattrs = Some(Box::default()); - object.gpt = Some(Box::new(GptPartition { + object.set_flag_hidden(Some(false)); + object.inode_mut().set_flag_no_dump(Some(false)); + object.inode_mut().set_read_only(Some(false)); + object.inode_mut().set_user_xattrs(Some(BTreeMap::new())); + object.set_gpt(Some(GptPartition { flags: Some(0), no_auto: Some(false), grow_file_system: Some(false), @@ -997,14 +1010,14 @@ mod tests { signatures: Vec::new(), }; let read = read_whole(&write_whole(&whole).unwrap()).unwrap().objects.remove(0); - assert_eq!(read.dos_flags.get(DosFlags::HIDDEN), Some(false)); - assert_eq!(read.inode.flags.get(InodeFlags::NO_DUMP), Some(false)); - assert_eq!(read.inode.read_only, Some(false)); - assert_eq!(read.inode.user_xattrs.as_deref(), Some(&BTreeMap::new())); + assert_eq!(read.dos_flags().get(DosFlags::HIDDEN), Some(false)); + assert_eq!(read.inode().flags().get(InodeFlags::NO_DUMP), Some(false)); + assert_eq!(read.inode().read_only(), Some(false)); + assert_eq!(read.inode().user_xattr_map(), Some(&BTreeMap::new())); // A reader leaves the fields of a partition as they are: a regular // file without any is no partition, whose flags the manifest says // are cleared. - assert_eq!(read.gpt, None); + assert_eq!(read.gpt(), None); // What a manifest does not record, an object cannot have, whatever // it says. let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); @@ -1034,9 +1047,9 @@ mod tests { fn keys_are_sorted_and_nothing_is_lost() { let object = everything(); let mut device = FileObject::new(name("dev/null")); - device.inode_type = InodeType::CharDevice; - device.major = Some(1); - device.minor = Some(3); + device.set_inode_type(InodeType::CharDevice); + device.set_major(Some(1)); + device.set_minor(Some(3)); let (mut root, _) = recording_all(); root.order = Some(Order::CodePoint); root.gpt_disk_uuid = Some(Uuid::new([0xab; Uuid::SIZE])); @@ -1045,7 +1058,7 @@ mod tests { label: Some("ESP".into()), fat_serial: Some(FatSerial(0x1234_abcd)), }; - root.inode.mtime_nsec = Some(0); + root.inode.set_mtime_nsec(Some(0)); let mut signature = SignatureObject::new("pkcs7"); signature.key = Some(vec![0xde, 0xad]); signature.data = Some(vec![1, 2, 3, 4]); @@ -1168,16 +1181,20 @@ mod tests { let mut expected: Vec = objects.to_vec(); // The reader fills in what follows from a literal: how long it is. // The header fields went out in the order of their names. - let literal = &mut expected[1].contents[2]; + let literal = &mut expected[1].contents_mut()[2]; (literal.encoded_size, literal.original_size) = (Some(5), Some(5)); literal.filled_in.insert(Field::EncodedSize); literal.filled_in.insert(Field::OriginalSize); - expected[1].contents[1].http_headers.sort(); + expected[1].contents_mut()[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; + let mut dos_flags = object.dos_flags(); + dos_flags.stated = dos_flags.set; + object.set_dos_flags(dos_flags); + let mut flags = object.inode().flags(); + flags.stated = flags.set; + object.inode_mut().set_flags(flags); object.fill_in(Features::ALL); } assert_eq!(m.objects, expected); @@ -1194,8 +1211,8 @@ mod tests { // An object has no flag its inode type does not have: the reader // says the same. let mut link = FileObject::new(name("l")); - link.inode_type = InodeType::Symlink; - link.inode.flags.put(InodeFlags::NO_DUMP, Some(false)); + link.set_inode_type(InodeType::Symlink); + link.inode_mut().set_flag_no_dump(Some(false)); let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); let e = writer.file(&link).unwrap_err(); assert_eq!( @@ -1235,7 +1252,7 @@ mod tests { writer.file(&directory("c")).unwrap(); writer.file(&FileObject::new(name("c/d"))).unwrap(); let m = read_whole(&writer.finish().unwrap()).unwrap(); - let names: Vec<&str> = m.objects.iter().map(|object| object.name.as_str()).collect(); + let names: Vec<&str> = m.objects.iter().map(|object| object.name().as_str()).collect(); assert_eq!(names, ["b", "c", "c/d"]); // What a writer leaves that did not finish is no manifest. let mut unfinished = Vec::new(); @@ -1259,7 +1276,7 @@ mod tests { (problem, e.record_number(), e.field(), e.to_string()) }; let mut root = RootObject::default(); - root.inode.uid = Some(u32::MAX); + root.inode.set_uid(Some(u32::MAX)); assert_eq!( refused(&root), ( @@ -1272,7 +1289,7 @@ mod tests { // The fields of the features the specification has had the // longest and of those it has had the shortest. let mut root = RootObject::default(); - root.inode.mtime_nsec = Some(1); + root.inode.set_mtime_nsec(Some(1)); assert_eq!(refused(&root).0, Problem::UnlistedFeature); let mut root = RootObject::default(); root.file_system.fat_serial = Some(FatSerial(0x1234_abcd)); @@ -1294,8 +1311,8 @@ mod tests { features: Some(Features::DEFAULT | Features::READ_ONLY), ..RootObject::default() }; - root.inode.read_only = Some(true); - root.inode.mode = Some(Mode::new(0o755).unwrap()); + root.inode.set_read_only(Some(true)); + root.inode.set_mode(Some(Mode::new(0o755).unwrap())); assert_eq!( refused(&root), ( @@ -1369,7 +1386,7 @@ mod tests { ); let bytes = sequence(&[root, TRAILER]); let m = read_whole(&bytes).unwrap(); - assert_eq!(m.root.inode.read_only, Some(false)); + assert_eq!(m.root.inode.read_only(), Some(false)); assert_eq!(write_whole(&m).unwrap(), bytes); } @@ -1382,9 +1399,9 @@ mod tests { let root = r#"{"features":["mode","read-only"],"mediaType":"application/vnd.uapi.16.manifest","mode":365}"#; let bytes = sequence(&[root, r#"{"mode":292,"name":"x"}"#, TRAILER]); let m = read_whole(&bytes).unwrap(); - for inode in [&m.root.inode, &m.objects[0].inode] { - assert_eq!(inode.read_only, Some(false)); - assert!(inode.filled_in.contains(Field::ReadOnly)); + for inode in [&m.root.inode, m.objects[0].inode()] { + assert_eq!(inode.read_only(), Some(false)); + assert!(inode.marks().contains(Field::ReadOnly)); } assert_eq!(write_whole(&m).unwrap(), bytes); // Given, it is refused. @@ -1398,7 +1415,8 @@ mod tests { ); assert_eq!(contradiction(read_whole(&given).unwrap_err()), expected); let mut object = m.objects[0].clone(); - object.inode.filled_in.remove(Field::ReadOnly); + let read_only = object.inode().read_only(); + object.inode_mut().set_read_only(read_only); let mut writer = Writer::begin(Vec::new(), &m.root).unwrap(); assert_eq!(contradiction(writer.file(&object).unwrap_err()), expected); // The root file object too. @@ -1417,7 +1435,8 @@ mod tests { expected ); let mut root = m.root.clone(); - root.inode.filled_in.remove(Field::ReadOnly); + let read_only = root.inode.read_only(); + root.inode.set_read_only(read_only); assert_eq!(contradiction(Writer::begin(Vec::new(), &root).unwrap_err()), expected); } @@ -1483,7 +1502,8 @@ mod tests { let empty: Sha256 = EMPTY.parse().unwrap(); // The hash of no data next to the size 0. let mut object = FileObject::new(name("x")); - (object.size, object.sha256) = (Some(0), Some(empty)); + object.set_size(Some(0)); + object.set_sha256(Some(empty)); // With an encoding, that of the encoded and of the original data. let mut encoded = ContentsObject::new(ContentsSource::File(name("x.gz"))); encoded.encoding = Some("gzip".into()); @@ -1494,7 +1514,7 @@ mod tests { 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]; + object.put_contents(vec![encoded, plain]); let written = record(&object); assert_eq!( written, @@ -1506,8 +1526,8 @@ mod tests { let (_, root) = recording_all(); let m = read_whole(&sequence(&[&root, &written, TRAILER])).unwrap(); let read = &m.objects[0]; - assert_eq!((read.size, read.sha256), (Some(0), Some(empty))); - for contents in &read.contents { + assert_eq!((read.size(), read.sha256()), (Some(0), Some(empty))); + for contents in read.contents() { let data = (contents.encoded_size, contents.encoded_sha256); assert_eq!(data, (Some(0), Some(empty))); let data = (contents.original_size, contents.original_sha256); @@ -1515,10 +1535,10 @@ mod tests { } // Where only the encoded size says it, it stays. let mut only = FileObject::new(name("y")); - only.contents = vec![ContentsObject { + only.put_contents(vec![ContentsObject { encoded_size: Some(5), ..ContentsObject::new(ContentsSource::File(name("y"))) - }]; + }]); assert_eq!( record(&only), r#"{"contents":[{"encodedSize":5,"file":"y"}],"name":"y"}"# @@ -1580,15 +1600,19 @@ mod tests { noncharacter() ), |o| { - o.contents = vec![ContentsObject::new(ContentsSource::Literal(vec![0; MAX_RECORD_SIZE / 4 * 3]))]; - o.inode.user_name = Some(format!("u{}", noncharacter()).into()); + let literal = ContentsSource::Literal(vec![0; MAX_RECORD_SIZE / 4 * 3]); + o.put_contents(vec![ContentsObject::new(literal)]); + o.inode_mut().set_user_name(Some(format!("u{}", noncharacter()))); }, Problem::RecordTooLarge, ), // A string the JSON parser refuses, before any value. ( "{\"name\":\"x\",\"uid\":65535,\"userName\":\"u\u{fdd0}\"}".into(), - |o| (o.inode.uid, o.inode.user_name) = (Some(65535), Some("u\u{fdd0}".into())), + |o| { + o.inode_mut().set_uid(Some(65535)); + o.inode_mut().set_user_name(Some("u\u{fdd0}".into())); + }, Problem::InvalidString, ), // A key the JSON parser finds twice in an object, header fields @@ -1597,11 +1621,11 @@ mod tests { r#"{"contents":[{"httpHeaders":{"A":"b","A":"c"},"url":"https://example.com/x"}],"name":"x","uid":65535}"# .into(), |o| { - o.contents = vec![ContentsObject { + o.put_contents(vec![ContentsObject { http_headers: vec![("A".into(), "b".into()), ("A".into(), "c".into())], ..ContentsObject::new(ContentsSource::Url("https://example.com/x".into())) - }]; - o.inode.uid = Some(65535); + }]); + o.inode_mut().set_uid(Some(65535)); }, Problem::DuplicateKey, ), @@ -1613,10 +1637,10 @@ mod tests { r#",{"literal":"YQ=="}"#.repeat(MAX_CONTENTS) ), |o| { - o.contents = (0..=MAX_CONTENTS) + o.put_contents((0..=MAX_CONTENTS) .map(|_| ContentsObject::new(ContentsSource::Literal(b"a".to_vec()))) - .collect(); - o.contents[0].original_size = Some(5); + .collect()); + o.contents_mut()[0].original_size = Some(5); }, Problem::InvalidContents, ), @@ -1625,11 +1649,11 @@ mod tests { ( r#"{"contents":[{"file":"a","httpHeaders":{"A":"b"}}],"name":"x","uid":65535}"#.into(), |o| { - o.contents = vec![ContentsObject { + o.put_contents(vec![ContentsObject { http_headers: vec![("A".into(), "b".into())], ..ContentsObject::new(ContentsSource::File(name("a"))) - }]; - o.inode.uid = Some(65535); + }]); + o.inode_mut().set_uid(Some(65535)); }, Problem::InvalidContents, ), @@ -1641,24 +1665,31 @@ mod tests { WORLD ), |o| { - o.contents = vec![ContentsObject { + o.put_contents(vec![ContentsObject { original_sha256: WORLD.parse().ok(), ..ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())) - }]; - o.inode.uid = Some(65535); + }]); + o.inode_mut().set_uid(Some(65535)); }, Problem::Contradiction, ), // A value, before a missing name. ( r#"{"uid":65535}"#.into(), - |o| (o.name, o.inode.uid) = (NameBuf::default(), Some(65535)), + |o| { + o.set_name(NameBuf::default()); + o.inode_mut().set_uid(Some(65535)); + }, Problem::FieldOutOfRange, ), // A value, before a field the inode type does not permit. ( r#"{"name":"x","size":1,"type":"fifo","uid":65535}"#.into(), - |o| (o.inode_type, o.size, o.inode.uid) = (InodeType::Fifo, Some(1), Some(65535)), + |o| { + o.set_inode_type(InodeType::Fifo); + o.set_size(Some(1)); + o.inode_mut().set_uid(Some(65535)); + }, Problem::FieldOutOfRange, ), // A field the inode type does not permit, before fields that @@ -1666,8 +1697,10 @@ 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) = (Some(Mode::new(0o644).unwrap()), Some(true)); + o.set_inode_type(InodeType::Fifo); + o.set_size(Some(1)); + o.inode_mut().set_mode(Some(Mode::new(0o644).unwrap())); + o.inode_mut().set_read_only(Some(true)); }, Problem::FieldNotPermitted, ), @@ -1676,8 +1709,9 @@ mod tests { ( r#"{"mTimeNSec":1,"mode":420,"name":"x","readOnly":true}"#.into(), |o| { - (o.inode.mtime_nsec, o.inode.mode) = (Some(1), Some(Mode::new(0o644).unwrap())); - o.inode.read_only = Some(true); + o.inode_mut().set_mtime_nsec(Some(1)); + o.inode_mut().set_mode(Some(Mode::new(0o644).unwrap())); + o.inode_mut().set_read_only(Some(true)); }, Problem::Contradiction, ), @@ -1685,7 +1719,10 @@ mod tests { // record. ( r#"{"mTimeNSec":1,"name":"x","uid":65535}"#.into(), - |o| (o.inode.mtime_nsec, o.inode.uid) = (Some(1), Some(65535)), + |o| { + o.inode_mut().set_mtime_nsec(Some(1)); + o.inode_mut().set_uid(Some(65535)); + }, Problem::FieldOutOfRange, ), ]; @@ -1720,7 +1757,7 @@ mod tests { let mut writer = Writer::begin(Vec::new(), &root).unwrap(); writer.signature(&SignatureObject::new("pkcs7")).unwrap(); let mut object = FileObject::new(name("x")); - object.inode.user_name = Some(format!("u{}", noncharacter()).into()); + object.inode_mut().set_user_name(Some(format!("u{}", noncharacter()))); let w = writer.file(&object).unwrap_err(); assert_eq!((w.kind(), w.record_number()), (e.kind(), e.record_number())); // A file object after a signature object, before a missing name. @@ -1729,7 +1766,7 @@ mod tests { let mut writer = Writer::begin(Vec::new(), &root).unwrap(); writer.signature(&SignatureObject::new("pkcs7")).unwrap(); let mut nameless = FileObject::new(NameBuf::default()); - nameless.inode.uid = Some(65535); + nameless.inode_mut().set_uid(Some(65535)); let w = writer.file(&nameless).unwrap_err(); assert_eq!((w.kind(), w.record_number()), (e.kind(), e.record_number())); // The root file object: the label of the file system comes before @@ -1748,7 +1785,7 @@ mod tests { ..RootObject::default() }; root.file_system.label = Some("a\tb".into()); - root.inode.uid = Some(65535); + root.inode.set_uid(Some(65535)); let w = Writer::begin(Vec::new(), &root).unwrap_err(); assert_eq!( (w.kind(), w.field(), w.record_number()), @@ -1782,33 +1819,51 @@ mod tests { } /// Gives `object` the extended attribute `name`, without a value. fn xattr(object: &mut FileObject, name: &str) { - object.inode.user_xattrs = Some(Box::new(BTreeMap::from([(name.to_string(), Vec::new())]))); + object + .inode_mut() + .set_user_xattrs(Some(BTreeMap::from([(name.to_string(), Vec::new())]))); } /// The partition label `label`. - fn gpt(label: &str) -> Option> { - Some(Box::new(GptPartition { + fn gpt(label: &str) -> Option { + Some(GptPartition { label: Some(label.into()), ..GptPartition::default() - })) + }) } let cases: [(Give, Problem, Field); 20] = [ - (|o| o.inode.uid = Some(u32::MAX), Problem::FieldOutOfRange, Field::Uid), - (|o| o.inode.gid = Some(u32::MAX), Problem::FieldOutOfRange, Field::Gid), + ( + |o| o.inode_mut().set_uid(Some(u32::MAX)), + Problem::FieldOutOfRange, + Field::Uid, + ), + ( + |o| o.inode_mut().set_gid(Some(u32::MAX)), + Problem::FieldOutOfRange, + Field::Gid, + ), // -1 as a 16-bit ID is no ID either. - (|o| o.inode.uid = Some(65535), Problem::FieldOutOfRange, Field::Uid), - (|o| o.inode.gid = Some(65535), Problem::FieldOutOfRange, Field::Gid), ( - |o| o.inode.user_name = Some("u\u{fdd0}".into()), + |o| o.inode_mut().set_uid(Some(65535)), + Problem::FieldOutOfRange, + Field::Uid, + ), + ( + |o| o.inode_mut().set_gid(Some(65535)), + Problem::FieldOutOfRange, + Field::Gid, + ), + ( + |o| o.inode_mut().set_user_name(Some("u\u{fdd0}".into())), Problem::InvalidString, Field::UserName, ), ( - |o| o.inode.user_name = Some("u\0".into()), + |o| o.inode_mut().set_user_name(Some("u\0".into())), Problem::InvalidString, Field::UserName, ), ( - |o| o.inode.group_name = Some("a:b".into()), + |o| o.inode_mut().set_group_name(Some("a:b".into())), Problem::WrongFieldType, Field::GroupName, ), @@ -1818,52 +1873,56 @@ mod tests { Problem::InvalidExtendedAttributes, Field::ExtendedAttributes, ), - (|o| o.gpt = gpt("x\0"), Problem::InvalidString, Field::GptLabel), - (|o| o.gpt = gpt("a\tb"), Problem::WrongFieldType, Field::GptLabel), + (|o| o.set_gpt(gpt("x\0")), Problem::InvalidString, Field::GptLabel), + (|o| o.set_gpt(gpt("a\tb")), Problem::WrongFieldType, Field::GptLabel), ( - |o| o.contents = vec![ContentsObject::new(ContentsSource::Url("ftp://example.com/x".into()))], + |o| { + o.put_contents(vec![ContentsObject::new(ContentsSource::Url( + "ftp://example.com/x".into(), + ))]) + }, Problem::InvalidContents, Field::Url, ), ( - |o| o.contents = vec![encoded("Identity")], + |o| o.put_contents(vec![encoded("Identity")]), Problem::InvalidContents, Field::Encoding, ), // A reader lowers the case of an encoding, a manifest has it in // lower case. ( - |o| o.contents = vec![encoded("GZIP")], + |o| o.put_contents(vec![encoded("GZIP")]), Problem::InvalidContents, Field::Encoding, ), ( - |o| o.contents = vec![encoded("gzip\u{ffff}")], + |o| o.put_contents(vec![encoded("gzip\u{ffff}")]), Problem::InvalidString, Field::Encoding, ), ( - |o| o.contents = vec![headers(&[("bad name", "b")])], + |o| o.put_contents(vec![headers(&[("bad name", "b")])]), Problem::InvalidContents, Field::HttpHeaders, ), ( - |o| o.contents = vec![headers(&[("A", "b"), ("a", "c")])], + |o| o.put_contents(vec![headers(&[("A", "b"), ("a", "c")])]), Problem::InvalidContents, Field::HttpHeaders, ), ( - |o| o.contents = vec![headers(&[("A", "b\nc")])], + |o| o.put_contents(vec![headers(&[("A", "b\nc")])]), Problem::InvalidContents, Field::HttpHeaders, ), ( - |o| o.contents = vec![ContentsObject::default(); MAX_CONTENTS + 1], + |o| o.put_contents(vec![ContentsObject::default(); MAX_CONTENTS + 1]), Problem::InvalidContents, Field::Contents, ), ( - |o| o.contents = vec![ContentsObject::new(ContentsSource::File(NameBuf::default()))], + |o| o.put_contents(vec![ContentsObject::new(ContentsSource::File(NameBuf::default()))]), Problem::InvalidContents, Field::File, ), @@ -1892,7 +1951,7 @@ mod tests { name("a").parent().unwrap().to_owned(), ] { let mut object = FileObject::new(name("x")); - object.contents = vec![ContentsObject::new(ContentsSource::File(file))]; + object.put_contents(vec![ContentsObject::new(ContentsSource::File(file))]); let mut writer = Writer::begin(Vec::new(), &root).unwrap(); let e = writer.file(&object).unwrap_err(); assert_eq!( @@ -1918,7 +1977,7 @@ mod tests { // A field of a feature the manifest does not record, also one of // those the specification added last. let mut object = FileObject::new(name("x")); - object.inode.read_only = Some(true); + object.inode_mut().set_read_only(Some(true)); let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); let e = writer.file(&object).unwrap_err(); assert_eq!( @@ -1957,15 +2016,16 @@ mod tests { ); // What the reader takes, the writer takes. let mut object = FileObject::new(name("x")); - (object.inode.uid, object.inode.gid) = (Some(65534), Some(u32::MAX - 1)); - object.inode.user_name = Some("Domain Users".into()); - object.contents = vec![headers(&[("A", "b"), ("B", "")]); MAX_CONTENTS]; + object.inode_mut().set_uid(Some(65534)); + object.inode_mut().set_gid(Some(u32::MAX - 1)); + object.inode_mut().set_user_name(Some("Domain Users".into())); + object.put_contents(vec![headers(&[("A", "b"), ("B", "")]); MAX_CONTENTS]); let mut writer = Writer::begin(Vec::new(), &root).unwrap(); writer.file(&object).unwrap(); let m = read_whole(&writer.finish().unwrap()).unwrap(); let read = &m.objects[0]; assert_eq!( - (read.inode.uid, read.inode.user_name.as_deref(), read.contents.len()), + (read.inode().uid(), read.inode().user_name(), read.contents().len()), (Some(65534), Some("Domain Users"), MAX_CONTENTS) ); } @@ -1977,11 +2037,11 @@ mod tests { /// Gives an object fields. type Give = fn(&mut FileObject); /// The fields of a partition with the attribute flags `flags`. - fn partition(flags: u64) -> Option> { - Some(Box::new(GptPartition { + fn partition(flags: u64) -> Option { + Some(GptPartition { flags: Some(flags), ..GptPartition::default() - })) + }) } /// Contents in the file "x". fn file() -> ContentsObject { @@ -1994,40 +2054,58 @@ mod tests { let cases: [(Give, Problem, Option); 22] = [ // Fields the inode type does not permit. ( - |o| (o.inode_type, o.size) = (InodeType::Fifo, Some(1)), + |o| { + o.set_inode_type(InodeType::Fifo); + o.set_size(Some(1)); + }, Problem::FieldNotPermitted, Some(Field::Size), ), ( - |o| (o.inode_type, o.contents) = (InodeType::CharDevice, vec![file()]), + |o| { + o.set_inode_type(InodeType::CharDevice); + o.put_contents(vec![file()]); + }, Problem::FieldNotPermitted, Some(Field::Contents), ), ( - |o| (o.inode_type, o.sha256) = (InodeType::Socket, EMPTY.parse().ok()), + |o| { + o.set_inode_type(InodeType::Socket); + o.set_sha256(EMPTY.parse().ok()); + }, Problem::FieldNotPermitted, Some(Field::Contents), ), - (|o| o.major = Some(1), Problem::FieldNotPermitted, Some(Field::Major)), + (|o| o.set_major(Some(1)), Problem::FieldNotPermitted, Some(Field::Major)), ( - |o| (o.inode_type, o.inode.mode) = (InodeType::Symlink, Some(Mode::new(0o777).unwrap())), + |o| { + o.set_inode_type(InodeType::Symlink); + o.inode_mut().set_mode(Some(Mode::new(0o777).unwrap())); + }, Problem::FieldNotPermitted, Some(Field::Mode), ), ( - |o| (o.inode_type, o.inode_token) = (InodeType::Directory, NonZeroU64::new(1)), + |o| { + o.set_inode_type(InodeType::Directory); + o.set_inode_token(NonZeroU64::new(1)); + }, Problem::FieldNotPermitted, Some(Field::InodeToken), ), ( - |o| (o.inode_type, o.gpt) = (InodeType::Directory, partition(0)), + |o| { + o.set_inode_type(InodeType::Directory); + o.set_gpt(partition(0)); + }, Problem::FieldNotPermitted, Some(Field::GptFlags), ), ( |o| { - o.inode_type = InodeType::Symlink; - o.dos_flags.put(DosFlags::HIDDEN, Some(true)); + o.set_inode_type(InodeType::Symlink); + o.set_flag_hidden(Some(true)); }, Problem::FieldNotPermitted, Some(Field::FlagHidden), @@ -2035,64 +2113,79 @@ 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), Some(Mode::new(0o644).unwrap())), + |o| { + o.inode_mut().set_read_only(Some(true)); + o.inode_mut().set_mode(Some(Mode::new(0o644).unwrap())); + }, Problem::Contradiction, Some(Field::ReadOnly), ), ( - |o| (o.inode.read_only, o.gpt) = (Some(true), partition(0)), + |o| { + o.inode_mut().set_read_only(Some(true)); + o.set_gpt(partition(0)); + }, Problem::Contradiction, Some(Field::GptFlags), ), ( - |o| (o.inode.read_only, o.gpt) = (Some(false), partition(GptPartition::FLAG_READ_ONLY)), + |o| { + o.inode_mut().set_read_only(Some(false)); + o.set_gpt(partition(GptPartition::FLAG_READ_ONLY)); + }, Problem::Contradiction, Some(Field::GptFlags), ), // The manifest records gptFlags, so none is 0. ( - |o| o.inode.read_only = Some(true), + |o| o.inode_mut().set_read_only(Some(true)), Problem::Contradiction, Some(Field::ReadOnly), ), ( |o| { - o.gpt = partition(GptPartition::FLAG_NO_AUTO); - o.gpt.as_mut().unwrap().no_auto = Some(false); + o.set_gpt(partition(GptPartition::FLAG_NO_AUTO)); + o.gpt_mut().unwrap().no_auto = Some(false); }, Problem::Contradiction, Some(Field::GptFlags), ), // The size 0 against the hash, and the other way around. ( - |o| (o.size, o.sha256) = (Some(0), HELLO.parse().ok()), + |o| { + o.set_size(Some(0)); + o.set_sha256(HELLO.parse().ok()); + }, Problem::Contradiction, Some(Field::Size), ), ( - |o| (o.size, o.sha256) = (Some(5), EMPTY.parse().ok()), + |o| { + o.set_size(Some(5)); + o.set_sha256(EMPTY.parse().ok()); + }, Problem::Contradiction, Some(Field::Sha256), ), // httpHeaders without a URL, and a part beyond the data. ( |o| { - o.contents = vec![ContentsObject { + o.put_contents(vec![ContentsObject { http_headers: vec![("A".into(), "b".into())], ..file() - }]; + }]); }, Problem::InvalidContents, Some(Field::HttpHeaders), ), ( |o| { - o.size = Some(5); - o.contents = vec![ContentsObject { + o.set_size(Some(5)); + o.put_contents(vec![ContentsObject { original_size: Some(6), offset: 2, ..file() - }]; + }]); }, Problem::Contradiction, Some(Field::Offset), @@ -2102,42 +2195,49 @@ mod tests { // of the data and a part of it. ( |o| { - o.contents = vec![ContentsObject { + o.put_contents(vec![ContentsObject { original_sha256: WORLD.parse().ok(), ..hello() - }]; + }]); }, Problem::Contradiction, Some(Field::Literal), ), ( |o| { - o.contents = vec![ContentsObject { + o.put_contents(vec![ContentsObject { encoded_sha256: WORLD.parse().ok(), ..hello() - }]; + }]); }, Problem::Contradiction, Some(Field::Literal), ), ( |o| { - o.contents = vec![ContentsObject { + o.put_contents(vec![ContentsObject { encoding: Some("gzip".into()), encoded_sha256: WORLD.parse().ok(), ..hello() - }]; + }]); }, Problem::Contradiction, Some(Field::Literal), ), ( - |o| (o.sha256, o.contents) = (WORLD.parse().ok(), vec![hello()]), + |o| { + o.set_sha256(WORLD.parse().ok()); + o.put_contents(vec![hello()]); + }, Problem::Contradiction, Some(Field::Literal), ), ( - |o| (o.size, o.sha256, o.contents) = (Some(2), HELLO.parse().ok(), vec![hello()]), + |o| { + o.set_size(Some(2)); + o.set_sha256(HELLO.parse().ok()); + o.put_contents(vec![hello()]); + }, Problem::Contradiction, Some(Field::Literal), ), @@ -2229,7 +2329,7 @@ mod tests { let whole = Whole { root: root.clone(), objects: vec![directory("a"), everything()], - signatures: vec![SignatureObject::new("pkcs7")], + signatures: Vec::new(), }; let mut text = String::new(); let mut encoder = Encoder::begin(&root, &mut text).unwrap(); @@ -2245,9 +2345,6 @@ mod tests { (ErrorKind::Manifest(Problem::DuplicateName), Some(3)) ); assert_eq!(text, appended); - for signature in &whole.signatures { - encoder.signature(signature, &mut text).unwrap(); - } encoder.finish(&mut text).unwrap(); assert_eq!(text.as_bytes(), write_whole(&whole).unwrap()); // Nothing follows the trailer. @@ -2257,14 +2354,11 @@ mod tests { encoder .file(&FileObject::new(NameBuf::default()), &mut text) .unwrap_err(), - encoder - .signature(&SignatureObject::new("pkcs7"), &mut text) - .unwrap_err(), encoder.finish(&mut text).unwrap_err(), ] { assert_eq!( (e.kind(), e.record_number()), - (ErrorKind::Manifest(Problem::DataAfterTrailer), Some(5)) + (ErrorKind::Manifest(Problem::DataAfterTrailer), Some(4)) ); } assert_eq!(text.len(), appended);