diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 58f8f44..e121552 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,8 +2,9 @@ # # 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 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 +# the lints for twelve targets, the formatting, the documentation with the +# man page of fsmanifest, the completions of fsmanifest in their shells, +# the C library with its header and its tests, the packages cargo publish # uploads, the dependency check and the sign-offs. # # The tests and the lints run without and with the feature capi, the C @@ -376,6 +377,62 @@ jobs: RUSTDOCFLAGS: -D warnings run: cargo doc --locked --workspace --no-deps + - name: Install groff + run: | + sudo apt-get update -q + sudo apt-get install -y -q --no-install-recommends groff-base + + - name: Check the man page of fsmanifest + # groff renders it with every warning turned on. It exits with 0 + # whatever it warns about, so a warning fails the step here. + run: | + warnings=$(groff -mandoc -ww -z src/fsmanifest/fsmanifest.1 2>&1) + if [ -n "$warnings" ]; then + echo "$warnings" + echo "::error::groff warns about src/fsmanifest/fsmanifest.1" + exit 1 + fi + + completions: + name: Completions of fsmanifest + runs-on: ubuntu-26.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install zsh and fish + # bash is the runner's own. + run: | + sudo apt-get update -q + sudo apt-get install -y -q --no-install-recommends zsh fish + + - name: Install rustc + run: | + rustup toolchain install stable --profile minimal + rustup default stable + rustc --version + + - name: Build fsmanifest + # The completions take the names of the features from it. + run: cargo build --locked -p fsmanifest + + - name: Check the syntax + run: | + bash -n src/fsmanifest/completions/fsmanifest.bash + zsh -n src/fsmanifest/completions/_fsmanifest + fish -n src/fsmanifest/completions/fsmanifest.fish + + - name: Test the completion for bash + run: src/fsmanifest/tests/completions.py bash target/debug/fsmanifest + + - name: Test the completion for zsh + run: src/fsmanifest/tests/completions.py zsh target/debug/fsmanifest + + - name: Test the completion for fish + run: src/fsmanifest/tests/completions.py fish target/debug/fsmanifest + header: name: uapi16.h runs-on: ubuntu-26.04 @@ -613,6 +670,13 @@ jobs: cd target/package/uapi16-*/ CARGO_TARGET_DIR=$RUNNER_TEMP/package cargo test --locked + - name: cargo package --workspace + # Packages fsmanifest as well. On its own the tool can't be + # packaged before uapi16 is on crates.io, since its package + # depends on uapi16 without the path. With --workspace cargo + # builds the packaged tool against the packaged library. + run: cargo package --locked --workspace + deps: name: Dependencies runs-on: ubuntu-26.04 @@ -622,11 +686,12 @@ jobs: with: persist-credentials: false - - name: Check the crates uapi16 depends on + - name: Check the crates the workspace depends on # Cargo.lock lists every dependency, for all targets and features, - # the build and test dependencies included: libc, pathrs, rustix, - # serde_core, serde_json and sha2 with the crates they need, those - # for other operating systems among them. The tests turn on + # the build and test dependencies included. uapi16 has libc, + # pathrs, rustix, serde_core, serde_json and sha2 with the crates + # they need, those for other operating systems among them, and + # fsmanifest adds lexopt, which needs none. The tests turn on # preserve_order of serde_json, which adds foldhash and indexmap # with the crates it needs. serde_json and serde_core name serde # and serde_derive for cfg(any()), which no target has, so that @@ -635,7 +700,7 @@ jobs: env: EXPECTED: >- bitflags block-buffer cfg-if cpufeatures crypto-common digest either equivalent errno fastrand - foldhash getrandom hashbrown hybrid-array indexmap itertools itoa libc linux-raw-sys memchr + foldhash getrandom hashbrown hybrid-array indexmap itertools itoa lexopt libc linux-raw-sys memchr once_cell pathrs proc-macro2 quote r-efi rustix rustversion serde serde_core serde_derive serde_json sha2 static_assertions syn tempfile thiserror thiserror-impl typenum unicode-ident windows-link windows-sys zmij diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b229932..1e3e490 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,10 +1,12 @@ # SPDX-License-Identifier: LGPL-2.1-or-later # -# The C library of a release, for x86_64 and for aarch64: a tarball of -# libuapi16 for each, with a directory at its top that is laid out as -# install.sh installs and has the license texts in share/licenses/uapi16, -# built against glibc 2.34 so that it works there and with every newer -# glibc. Each tarball gets a build provenance attestation. +# The C library and fsmanifest of a release, for x86_64 and for aarch64: +# a tarball of libuapi16 and the tool for each, with a directory at its +# top that is laid out as install.sh installs, with fsmanifest in bin and +# its man page and completions in share, and with the license texts in +# share/licenses/uapi16, built against glibc 2.34 so that it works there +# and with every newer glibc. Each tarball gets a build provenance +# attestation. # # A tag v* gets a draft release with the two tarballs and SHA256SUMS, with # the message of the tag as its notes. Nothing is signed here: @@ -59,9 +61,9 @@ jobs: runner: ubuntu-26.04-arm rustup-init: 9f608c142e0e38a78957d0661ba1dfaf0b6fb37184cfaa4b9a0aa57af6184282 # AlmaLinux 9.8, whose glibc is 2.34. The linker binds every glibc - # symbol the library uses to the newest version of it in the glibc it - # links against, and a glibc without that version can't load the - # library. The runner's glibc is newer. + # symbol the library and fsmanifest use to the newest version of it in + # the glibc it links against, and a glibc without that version can't + # load them. The runner's glibc is newer. container: image: quay.io/almalinuxorg/almalinux@sha256:3b958c0ee1c6f610f39a23143117ebcf5812a17aa42b0b09ebdb6fed18da3ae5 # 9.8-20261114 env: @@ -71,9 +73,9 @@ jobs: steps: - name: Install dependencies # git for the checkout, the C compiler that links the shared - # library and builds the examples, and pkg-config, which the - # examples take their flags from. readelf, nm and objdump are in - # the image. + # library and fsmanifest and builds the examples, and pkg-config, + # which the examples take their flags from. readelf, nm and objdump + # are in the image. run: dnf install -y -q --setopt=install_weak_deps=False gcc git-core pkgconf-pkg-config - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -83,7 +85,8 @@ jobs: - name: Version # The version of the crate, which is the version of the library. A # tag has to name it: v0.1.0 for 0.1.0. install.sh reads it the - # same way. + # same way. fsmanifest goes into the tarball of that version, so it + # has to have the same one. env: EVENT: ${{ github.event_name }} REF: ${{ github.ref_name }} @@ -91,6 +94,11 @@ jobs: run: | version=$(sed -n '/^version = "\(.*\)"$/{s//\1/p;q;}' src/uapi16/Cargo.toml) [ -n "$version" ] || { echo "::error::src/uapi16/Cargo.toml has no version"; exit 1; } + tool=$(sed -n '/^version = "\(.*\)"$/{s//\1/p;q;}' src/fsmanifest/Cargo.toml) + if [ "$tool" != "$version" ]; then + echo "::error::src/fsmanifest/Cargo.toml has the version '$tool', and the library has $version" + exit 1 + fi if [ "$EVENT" = push ] && [ "$REF" != "v$version" ]; then echo "::error::the tag $REF does not name $version, the version of src/uapi16/Cargo.toml" exit 1 @@ -123,15 +131,27 @@ jobs: - name: Build the static and the shared library run: src/uapi16/build.sh -- --locked + - name: Build fsmanifest + # With the rustc and in the container the library is built with, so + # against the same glibc. + run: cargo build --locked --release -p fsmanifest + - name: Install into the directory of the tarball # What install.sh installs into a prefix of its own, which becomes - # the directory at the top of the tarball and has its name. - # uapi16.pc names that prefix, so in the tarball it names the - # directory two levels above uapi16.pc instead, wherever the tarball - # is unpacked. + # the directory at the top of the tarball and has its name, and + # fsmanifest in bin of it with its man page and its completions in + # share. uapi16.pc names that prefix, so in the tarball it names + # the directory two levels above uapi16.pc instead, wherever the + # tarball is unpacked. run: | prefix=$RUNNER_TEMP/$NAME src/uapi16/install.sh --prefix="$prefix" + install -D -m 0755 target/release/fsmanifest "$prefix/bin/fsmanifest" + install -D -m 0644 src/fsmanifest/fsmanifest.1 "$prefix/share/man/man1/fsmanifest.1" + completions=src/fsmanifest/completions + install -D -m 0644 "$completions/fsmanifest.bash" "$prefix/share/bash-completion/completions/fsmanifest" + install -D -m 0644 "$completions/_fsmanifest" "$prefix/share/zsh/site-functions/_fsmanifest" + install -D -m 0644 "$completions/fsmanifest.fish" "$prefix/share/fish/vendor_completions.d/fsmanifest.fish" pc=$prefix/lib/pkgconfig/uapi16.pc sed -i \ -e 's|^prefix=.*|prefix=${pcfiledir}/../..|' \ @@ -146,26 +166,31 @@ jobs: cat "$pc" - name: Add the license texts - # The license of libuapi16, and the licenses of what is linked into - # it: the Rust standard library, with the license texts of the - # toolchain, and every crate of Cargo.lock that is linked, with the - # license files of its source. cargo tree lists those crates, and - # leaves out procedural macros and the dependencies of builds and - # tests, which are not linked. A crate without a license file fails - # the job. + # The license of libuapi16 and fsmanifest, and the licenses of what + # is linked into them: the Rust standard library, with the license + # texts of the toolchain, and every crate of Cargo.lock that is + # linked into either, with the license files of its source. cargo + # tree lists those crates for each of the two, and leaves out + # procedural macros and the dependencies of builds and tests, which + # are not linked. A crate without a license file fails the job. run: | licenses=$RUNNER_TEMP/$NAME/share/licenses/uapi16 mkdir -p "$licenses/rust" "$licenses/crates" cp src/uapi16/LICENSE "$licenses/LICENSE" doc=$(rustc --print sysroot)/share/doc/rust cp "$doc/COPYRIGHT" "$doc/LICENSE-APACHE" "$doc/LICENSE-MIT" "$licenses/rust/" - cargo tree --locked -p uapi16 --features capi -e normal,no-proc-macro --prefix none \ - --format '{p}' | sed 's/ (\*)$//' | LC_ALL=C sort -u > "$RUNNER_TEMP/tree" + { + cargo tree --locked -p uapi16 --features capi -e normal,no-proc-macro --prefix none \ + --format '{p}' + cargo tree --locked -p fsmanifest -e normal,no-proc-macro --prefix none --format '{p}' + } | sed 's/ (\*)$//' | LC_ALL=C sort -u > "$RUNNER_TEMP/tree" registry=${CARGO_HOME:-$HOME/.cargo}/registry/src : > "$RUNNER_TEMP/crates" bad=0 while read -r name version source; do - [ "$name" != uapi16 ] || continue + case $name in + uapi16 | fsmanifest) continue ;; + esac crate=$name-${version#v} if [ -n "$source" ]; then echo "::error::$crate is not from crates.io: $source" @@ -204,8 +229,11 @@ jobs: - name: Check the layout of the tarball # Only the directory of the tarball's name at the top, and in it - # what install.sh installs, the links of the shared library and the - # license texts, with a directory of license files for every crate. + # what install.sh installs, the links of the shared library, + # fsmanifest with its man page and its completions, and the license + # texts, with a directory of license files for every crate. And + # fsmanifest runs: it says the version of the tarball, and it writes + # and checks the manifest of a small tree. run: | top=$(tar -tzf "dist/$TARBALL" | cut -d / -f 1 | LC_ALL=C sort -u) if [ "$top" != "$NAME" ]; then @@ -214,10 +242,16 @@ jobs: fi cd "$RUNNER_TEMP/unpacked/$NAME" licenses=share/licenses/uapi16 + man=share/man/man1/fsmanifest.1 + bash=share/bash-completion/completions/fsmanifest + zsh=share/zsh/site-functions/_fsmanifest + fish=share/fish/vendor_completions.d/fsmanifest.fish { - printf '%s\n' include include/uapi16.h lib lib/libuapi16.a lib/libuapi16.so \ + printf '%s\n' bin bin/fsmanifest include include/uapi16.h lib lib/libuapi16.a lib/libuapi16.so \ lib/libuapi16.so.0 "lib/libuapi16.so.$VERSION" lib/pkgconfig lib/pkgconfig/uapi16.pc \ - share share/licenses "$licenses" "$licenses/LICENSE" "$licenses/rust" \ + share share/man share/man/man1 "$man" share/bash-completion share/bash-completion/completions \ + "$bash" share/zsh share/zsh/site-functions "$zsh" share/fish share/fish/vendor_completions.d \ + "$fish" share/licenses "$licenses" "$licenses/LICENSE" "$licenses/rust" \ "$licenses/rust/COPYRIGHT" "$licenses/rust/LICENSE-APACHE" "$licenses/rust/LICENSE-MIT" \ "$licenses/crates" sed "s|^|$licenses/crates/|" "$RUNNER_TEMP/crates" @@ -230,9 +264,11 @@ jobs: LC_ALL=C comm -13 "$RUNNER_TEMP/expected" "$RUNNER_TEMP/found" | sed 's/^/not expected: /' exit 1 fi - for f in include/uapi16.h lib/libuapi16.a "lib/libuapi16.so.$VERSION" lib/pkgconfig/uapi16.pc; do + for f in bin/fsmanifest include/uapi16.h lib/libuapi16.a "lib/libuapi16.so.$VERSION" \ + lib/pkgconfig/uapi16.pc "$man" "$bash" "$zsh" "$fish"; do [ -f "$f" ] && [ ! -L "$f" ] || { echo "::error::$f is not a regular file"; exit 1; } done + [ -x bin/fsmanifest ] || { echo "::error::bin/fsmanifest is not executable"; exit 1; } for l in lib/libuapi16.so lib/libuapi16.so.0; do [ "$(readlink "$l")" = "libuapi16.so.$VERSION" ] || { echo "::error::$l does not link to libuapi16.so.$VERSION"; exit 1; } @@ -241,6 +277,18 @@ jobs: [ -n "$(ls -A "$licenses/crates/$crate")" ] || { echo "::error::$licenses/crates/$crate is empty"; exit 1; } done < "$RUNNER_TEMP/crates" + said=$(bin/fsmanifest --version) || { echo "::error::bin/fsmanifest does not run"; exit 1; } + if [ "$said" != "fsmanifest $VERSION" ]; then + echo "::error::bin/fsmanifest --version says '$said' and not 'fsmanifest $VERSION'" + exit 1 + fi + tree=$RUNNER_TEMP/fsmanifest + mkdir -p "$tree/dir" + echo data > "$tree/file" + ln "$tree/file" "$tree/dir/link" + ln -s file "$tree/symlink" + bin/fsmanifest generate "$tree" "$tree.manifest" + bin/fsmanifest check "$tree.manifest" echo "the layout is right, with the license files of $(wc -l < "$RUNNER_TEMP/crates") crates" - name: Check what the shared library exports @@ -266,19 +314,21 @@ jobs: fi echo "$count functions at LIBUAPI16_0.1.0" - - name: Check the glibc the shared library needs + - name: Check the glibc the shared library and fsmanifest need # No symbol of a glibc newer than 2.34, and none of GLIBC_PRIVATE. run: | - so=$RUNNER_TEMP/unpacked/$NAME/lib/libuapi16.so.$VERSION - versions=$(objdump -T "$so" | grep -o 'GLIBC_[A-Z0-9_.]*' | sort -u -V) - for v in $versions; do - newest=$(printf '%s\n' "$v" GLIBC_2.34 | sort -V | tail -n 1) - case $v in - GLIBC_[0-9]*) [ "$newest" = GLIBC_2.34 ] ;; - *) false ;; - esac || { echo "::error::$so needs $v, which glibc 2.34 does not have"; exit 1; } + for elf in "lib/libuapi16.so.$VERSION" bin/fsmanifest; do + file=$RUNNER_TEMP/unpacked/$NAME/$elf + versions=$(objdump -T "$file" | grep -o 'GLIBC_[A-Z0-9_.]*' | sort -u -V) + for v in $versions; do + newest=$(printf '%s\n' "$v" GLIBC_2.34 | sort -V | tail -n 1) + case $v in + GLIBC_[0-9]*) [ "$newest" = GLIBC_2.34 ] ;; + *) false ;; + esac || { echo "::error::$file needs $v, which glibc 2.34 does not have"; exit 1; } + done + echo "$elf: glibc versions:" $versions done - echo "glibc versions:" $versions - name: Build and run the examples # The six programs of examples/, built against the unpacked tarball diff --git a/Cargo.lock b/Cargo.lock index 0cf4483..2a9e7e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -85,6 +85,14 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "fsmanifest" +version = "0.1.0" +dependencies = [ + "lexopt", + "uapi16", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -136,6 +144,12 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "lexopt" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "803ec87c9cfb29b9d2633f20cba1f488db3fd53f2158b1024cbefb47ba05d413" + [[package]] name = "libc" version = "0.2.191" diff --git a/Cargo.toml b/Cargo.toml index 2a53e73..9354ec7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ # SPDX-License-Identifier: LGPL-2.1-or-later [workspace] -members = ["src/uapi16"] +members = ["src/fsmanifest", "src/uapi16"] # cargo update picks dependency versions that support rust-version. resolver = "3" @@ -12,6 +12,8 @@ rust-version = "1.85" license = "LGPL-2.1-or-later" [workspace.dependencies] +# Parses the command line of fsmanifest. +lexopt = "0.3.2" # 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 no build has two versions of libc. diff --git a/README.md b/README.md index 4be0383..11bad68 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,20 @@ # uapi16 This repository holds uapi16, a Rust crate that reads, checks and -writes [UAPI.16 file manifests][spec], and its C library, libuapi16. The -crate is in src/uapi16, and its README describes both. +writes [UAPI.16 file manifests][spec], its C library, libuapi16, and +fsmanifest, a command-line tool that generates and checks manifests. +The crate is in src/uapi16, and its README describes the crate and the +C library. The tool is in src/fsmanifest, and its README describes its +commands. + +## Command-line tool + +From the top of the repository, this builds fsmanifest as +target/release/fsmanifest: + + cargo build --release -p fsmanifest + +The tarballs of a release have it prebuilt, see below. ## C library @@ -12,21 +24,23 @@ it into /usr: src/uapi16/build.sh src/uapi16/install.sh --prefix=/usr -## Prebuilt C library +## Release tarballs -Every release has the C library prebuilt for x86_64 and aarch64 Linux -with glibc 2.34 or newer, in uapi16-VERSION-ARCH-linux-gnu.tar.gz. The -tarball holds a directory of that name with what install.sh installs, -and with the license texts in share/licenses/uapi16. These install it -into /opt/uapi16: +Every release has the C library and fsmanifest prebuilt for x86_64 and +aarch64 Linux with glibc 2.34 or newer, in +uapi16-VERSION-ARCH-linux-gnu.tar.gz. The tarball holds a directory of +that name with what install.sh installs, with bin/fsmanifest and its man +page and completions in share, and with the license texts in +share/licenses/uapi16. These install it into /opt/uapi16: mkdir -p /opt/uapi16 tar --strip-components=1 -C /opt/uapi16 \ -xf uapi16-0.1.0-x86_64-linux-gnu.tar.gz export PKG_CONFIG_PATH=/opt/uapi16/lib/pkgconfig -The directory can be moved or copied as a whole, but uapi16.pc can't be -copied or symlinked out of it. +The tool is /opt/uapi16/bin/fsmanifest then. The directory can be moved +or copied as a whole, but uapi16.pc can't be copied or symlinked out of +it. SHA256SUMS lists the hashes of the tarballs. SHA256SUMS.asc is its signature by Christian Brauner , with this key and diff --git a/TODO.md b/TODO.md index 3e91791..18437d3 100644 --- a/TODO.md +++ b/TODO.md @@ -3,6 +3,15 @@ Work that is planned for a later release, and ideas that are not decided yet. +## Reader + +- Check a manifest across its file objects. Today the reader checks a + file object by itself and against the one before it. So it takes a + name that comes twice where the manifest declares no order, objects + that share an `inodeToken` but differ in their type or in their + fields, and tokens that don't count from 1. `fsmanifest check` gets + these checks with the reader. + ## Manifest builder - A flag that leaves out every mount point a walk doesn't cross. Without @@ -98,11 +107,33 @@ yet. comes from the writer, so that it hashes only what the manifest records. +## Data + +- Download the data of a file over http and https. Today + `FileObject::data_location()` takes no data that has to be fetched + from a URL, and an object whose every contents object gives its data + that way fails with `UnsupportedData::UrlOrEncoding`. + +## Signatures + +- Verify the signatures of a manifest. Today the library reads the + signature objects, and `Reader::signed_len()` says how much of the + manifest they sign, but it verifies none of them. A caller has to do + that itself. + ## C API - Options for the install script to leave out the static or the shared library. +## fsmanifest + +- Let `check` validate a manifest against what it describes: a directory + tree, an image, such as a file system image that was built from it, + and the data next to it, which its contents objects point at. Today it + validates a manifest by itself: its form, the order it declares and + whether it may be used now. + ## pathrs - Dropping pathrs remains an option. When a call of pathrs fails, pathrs diff --git a/src/fsmanifest/Cargo.toml b/src/fsmanifest/Cargo.toml new file mode 100644 index 0000000..09dfe8f --- /dev/null +++ b/src/fsmanifest/Cargo.toml @@ -0,0 +1,24 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later + +[package] +name = "fsmanifest" +# The version of uapi16, which the tool is released with. +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "Generates and checks UAPI.16 file manifests" +repository = "https://github.com/systemd/uapi16" +keywords = ["uapi", "manifest", "filesystem", "systemd"] +categories = ["command-line-utilities", "filesystem"] + +[[bin]] +name = "fsmanifest" +path = "main.rs" + +[dependencies] +lexopt.workspace = true +uapi16 = { path = "../uapi16", version = "0.1.0" } + +[lints] +workspace = true diff --git a/src/fsmanifest/LICENSE b/src/fsmanifest/LICENSE new file mode 100644 index 0000000..86c73c7 --- /dev/null +++ b/src/fsmanifest/LICENSE @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/src/fsmanifest/README.md b/src/fsmanifest/README.md new file mode 100644 index 0000000..0054408 --- /dev/null +++ b/src/fsmanifest/README.md @@ -0,0 +1,62 @@ +# fsmanifest + +fsmanifest is a command-line tool that generates and checks +[UAPI.16 file manifests][spec]. + +`fsmanifest generate` writes the manifest of a directory and everything +below it to a new file: + + fsmanifest generate /efi esp.manifest + +The new file appears once the manifest is complete. A file that exists +already is an error. Without a file, or with `-` for it, the manifest +goes to standard output. A new file inside the directory is not listed +in the manifest. A file there that standard output is redirected to is +listed, so give the file instead of redirecting. + +A manifest of a large tree takes room on disk while it is built: next to +the new file, and for standard output in the directory `TMPDIR` names +or, without `TMPDIR`, in /var/tmp. `TMPDIR` has to be a trusted +directory, since whoever controls it can change the manifest. + +The manifest records the default features of the specification. +`--features` takes a list of the features to record instead, in which +`default` stands for the default ones and `none` for no features: + + fsmanifest generate --features=default,mtime,user-xattr /efi esp.manifest + +`--features=help` lists the names of the features and marks the default +ones. The `gpt-*` ones are for manifests of partitions, and generate +refuses them for a tree. `--cross-mounts` walks into mount points. +Without it a directory that is a mount point is recorded as an empty +directory. `--graceful` leaves out files whose names a manifest can't +hold, a directory with everything below it, instead of failing. A field +that has no value a manifest can hold is left out as well, such as a +modification time before 1970. generate says on standard error how many +files and fields it left out. + +`fsmanifest check` checks a manifest, in a file or on standard input +with `-`: + + fsmanifest check esp.manifest + +It checks each object on its own and against the one before it. So a +name that comes twice is only sure to be found where the manifest +declares an order, and file objects that share an inode token are not +compared with each other. It also checks that the manifest may be used +now: that its root file object is not revoked, and that the time is +inside its validity window. It does not look at the validity of the +other file objects, and it does not verify signatures cryptographically. + +fsmanifest exits with 0 on success and with 2 on failure. Each command +describes its options with `--help`. + +fsmanifest supports Linux 5.10 or newer, the minimum baseline of +systemd. It does not build for any other system, Android included. +fsmanifest needs Rust 1.85 or newer. + +## License + +LGPL-2.1-or-later, see LICENSE. + +[spec]: https://uapi-group.org/specifications/specs/file_manifest/ diff --git a/src/fsmanifest/check.rs b/src/fsmanifest/check.rs new file mode 100644 index 0000000..35e4410 --- /dev/null +++ b/src/fsmanifest/check.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! `fsmanifest check`: whether a manifest is valid. + +use std::ffi::OsString; +use std::fmt; +use std::fs::File; +use std::io::{self, Read}; +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; + +use lexopt::prelude::*; +use uapi16::Reader; + +use crate::command::Command; +use crate::failure::Failure; + +/// Where a manifest is read from. +#[derive(Debug)] +pub(crate) enum Input { + /// From standard input. + Stdin, + /// From a file. + File(PathBuf), +} + +impl Input { + /// What a command line has in place of a file for standard input. + const STDIN: &'static str = "-"; +} + +impl From for Input { + /// The input the argument MANIFEST of a command line names. + fn from(manifest: OsString) -> Input { + if manifest == Input::STDIN { + Input::Stdin + } else { + Input::File(manifest.into()) + } + } +} + +impl fmt::Display for Input { + /// The input as a message names it. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Input::Stdin => f.write_str("standard input"), + Input::File(path) => path.display().fmt(f), + } + } +} + +/// `check`: checks that a manifest is valid. +#[derive(Debug)] +pub(crate) struct Check { + /// Where the manifest is read from. + input: Input, +} + +impl Check { + /// The name of the command. + pub(crate) const NAME: &'static str = "check"; + + /// What `--help` prints for the command. + pub(crate) const HELP: &'static str = "\ +Usage: fsmanifest check [OPTIONS] MANIFEST + +Checks the manifest in the file MANIFEST, or the one on standard input +with - for MANIFEST. + +Each object is checked on its own and against the one before it: its +fields, where it comes in the manifest, the order of the file objects if +the manifest declares one, and the features the manifest records. So a +name that comes twice is only sure to be found where the manifest +declares an order, and file objects that share an inode token are not +compared with each other. The manifest also has to be one that may be +used now: its root file object is not revoked, and the time is inside +its validity window. + +check does not look at the validity of the other file objects, and it +does not verify signatures cryptographically. + +Options: + -h, --help Show this help. + +check prints nothing for a valid manifest. For any other it says on +standard error what is wrong. Where a record is wrong, it names the +record. + +Exit status: 0 for a valid manifest, 2 for any other, or when the +manifest can't be read. +"; + + /// The command of the arguments behind `check`, which `parser` reads. + pub(crate) fn parse(mut parser: lexopt::Parser) -> Result { + let mut manifest = None; + while let Some(arg) = parser.next()? { + match arg { + Long("help") => return Command::flag(&mut parser, "--help", Command::Help(Check::HELP)), + Short('h') => return Command::flag(&mut parser, "-h", Command::Help(Check::HELP)), + Value(path) if manifest.is_none() => manifest = Some(path), + unexpected => return Err(unexpected.unexpected()), + } + } + Ok(Command::Check(Check { + input: Input::from(manifest.ok_or("missing argument MANIFEST")?), + })) + } + + /// Checks the manifest. + pub(crate) fn run(self) -> Result<(), Failure> { + let checked = match &self.input { + Input::Stdin => Check::read(io::stdin().lock()), + Input::File(path) => Check::read(File::open(path).map_err(|error| Failure::open(path, error))?), + }; + checked.map_err(|error| Failure::Check { + input: self.input, + error, + }) + } + + /// Reads the manifest `input` holds to its end, once, which checks + /// every object of it, and then checks that it may be used now. + fn read(input: impl Read) -> Result<(), uapi16::Error> { + let mut reader = Reader::open(input)?; + for object in &mut reader { + object?; + } + reader.root().check_validity(Check::now_usec()) + } + + /// The time now in microseconds since the epoch, as the validity of a + /// manifest counts it. A clock before the epoch counts as the epoch, + /// and one past what 64 bits hold as the last time they hold. + fn now_usec() -> u64 { + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default(); + u64::try_from(now.as_micros()).unwrap_or(u64::MAX) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What `check` makes of the arguments `args` behind its name. + fn parse(args: &[&str]) -> Result { + Check::parse(lexopt::Parser::from_args(args.iter().copied())) + } + + /// The file the command the arguments `args` ask for reads its + /// manifest from, none for standard input. + fn file(args: &[&str]) -> Option { + match parse(args) { + Ok(Command::Check(Check { input: Input::Stdin })) => None, + Ok(Command::Check(Check { + input: Input::File(path), + })) => Some(path), + other => panic!("{:?}", other), + } + } + + /// What the tool says of the arguments `args`, which it refuses. + fn refusal(args: &[&str]) -> String { + parse(args).unwrap_err().to_string() + } + + #[test] + fn where_the_manifest_comes_from() { + assert_eq!(file(&["manifest"]), Some("manifest".into())); + assert_eq!(file(&["-"]), None); + assert_eq!(file(&["./-"]), Some("./-".into())); + assert_eq!(file(&["--", "--help"]), Some("--help".into())); + assert_eq!(refusal(&[]), "missing argument MANIFEST"); + assert_eq!(refusal(&["manifest", "dir"]), r#"unexpected argument "dir""#); + } + + #[test] + fn options() { + let asks_for_help = |args: &[&str]| matches!(parse(args), Ok(Command::Help(text)) if text == Check::HELP); + assert!(asks_for_help(&["--help"])); + assert!(asks_for_help(&["-h"])); + assert!(asks_for_help(&["manifest", "--help", "--frob"])); + assert!(asks_for_help(&["manifest", "-h", "--frob"])); + assert_eq!( + refusal(&["--help=yes"]), + r#"unexpected argument for option '--help': "yes""# + ); + assert_eq!(refusal(&["-h=yes"]), r#"unexpected argument for option '-h': "yes""#); + // The options of generate are none of check. + assert_eq!( + refusal(&["--cross-mounts", "manifest"]), + "invalid option '--cross-mounts'" + ); + assert_eq!(refusal(&["--features=help"]), "invalid option '--features'"); + } + + #[test] + fn inputs_as_messages_name_them() { + assert_eq!(Input::Stdin.to_string(), "standard input"); + assert_eq!(Input::File("a/manifest".into()).to_string(), "a/manifest"); + } +} diff --git a/src/fsmanifest/command.rs b/src/fsmanifest/command.rs new file mode 100644 index 0000000..b66466d --- /dev/null +++ b/src/fsmanifest/command.rs @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The command line of the tool. + +use std::io::Write; + +use lexopt::prelude::*; + +use crate::check::Check; +use crate::failure::Failure; +use crate::generate::Generate; +use crate::stdout::StandardOutput; +use crate::{NAME, VERSION}; + +/// What a command line asks the tool to do. +#[derive(Debug)] +pub(crate) enum Command { + /// `generate`: write the manifest of a directory. + Generate(Generate), + /// `check`: check a manifest. + Check(Check), + /// `--help` or `-h`, of the tool or of one of its commands: print that + /// help text. + Help(&'static str), + /// `--features=help`: print the names of the features and the note + /// below them. + Features, + /// `--version`: print the version of the tool. + Version, +} + +impl Command { + /// What `--help` prints for the tool. + const HELP: &'static str = "\ +Usage: fsmanifest generate [OPTIONS] DIR [MANIFEST] + fsmanifest check [OPTIONS] MANIFEST + fsmanifest -h | --help + fsmanifest --version + +Generates and checks UAPI.16 file manifests. + +Commands: + generate Write the manifest of a directory and everything below it + check Check a manifest + +fsmanifest generate --help and fsmanifest check --help describe them. + +Exit status: 0 on success, 2 on failure. +"; + + /// The command of the command line that `parser` reads. `--help` or + /// `-h` among the options of a command asks for the help text of that + /// command, whatever comes behind it. + pub(crate) fn parse(mut parser: lexopt::Parser) -> Result { + match parser.next()? { + None => Err("missing command (try --help)".into()), + Some(Long("help")) => Command::flag(&mut parser, "--help", Command::Help(Command::HELP)), + Some(Short('h')) => Command::flag(&mut parser, "-h", Command::Help(Command::HELP)), + Some(Long("version")) => Command::flag(&mut parser, "--version", Command::Version), + Some(Value(command)) if command == Generate::NAME => Generate::parse(parser), + Some(Value(command)) if command == Check::NAME => Check::parse(parser), + Some(Value(command)) => Err(format!("unknown command {:?}", command).into()), + Some(option) => Err(option.unexpected()), + } + } + + /// The command `command`, which the flag `option` asks for that + /// `parser` read last, unless the flag came with a value, as in + /// `--help=yes` or `-hx`. lexopt refuses the value of a flag when it is + /// asked for the next argument, and behind these flags nothing asks + /// for one. + pub(crate) fn flag(parser: &mut lexopt::Parser, option: &str, command: Command) -> Result { + match parser.optional_value() { + Some(value) => Err(lexopt::Error::UnexpectedValue { + option: option.to_string(), + value, + }), + None => Ok(command), + } + } + + /// Does what the command line asks for. + pub(crate) fn run(self) -> Result<(), Failure> { + match self { + Command::Generate(generate) => generate.run(), + Command::Check(check) => check.run(), + Command::Help(text) => Command::print(text), + Command::Features => Command::print(&Generate::features_help()), + Command::Version => Command::print(&format!("{} {}\n", NAME, VERSION)), + } + } + + /// Prints `text` on standard output. + fn print(text: &str) -> Result<(), Failure> { + let printed = StandardOutput::open().and_then(|mut out| out.write_all(text.as_bytes())); + printed.map_err(Failure::Stdout) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What the tool makes of the arguments `args`. + fn parse(args: &[&str]) -> Result { + Command::parse(lexopt::Parser::from_args(args.iter().copied())) + } + + /// What the tool says of the arguments `args`, which it refuses. + fn refusal(args: &[&str]) -> String { + parse(args).unwrap_err().to_string() + } + + /// Whether the arguments `args` ask for the help text `text`. + fn asks_for(args: &[&str], text: &str) -> bool { + matches!(parse(args), Ok(Command::Help(help)) if help == text) + } + + #[test] + fn help_and_version() { + assert!(asks_for(&["--help"], Command::HELP)); + assert!(asks_for(&["-h"], Command::HELP)); + assert!(matches!(parse(&["--version"]), Ok(Command::Version))); + // What comes behind them is not looked at. + assert!(asks_for(&["--help", "--frob"], Command::HELP)); + assert!(asks_for(&["-h", "--frob"], Command::HELP)); + assert!(matches!(parse(&["--version", "frob"]), Ok(Command::Version))); + // Neither takes a value. + assert_eq!( + refusal(&["--help=yes"]), + r#"unexpected argument for option '--help': "yes""# + ); + assert_eq!( + refusal(&["--version=1"]), + r#"unexpected argument for option '--version': "1""# + ); + // What is joined to `-h` is a value as well. + for joined in ["-h=yes", "-hyes"] { + assert_eq!( + refusal(&[joined]), + r#"unexpected argument for option '-h': "yes""#, + "{}", + joined + ); + } + } + + #[test] + fn no_command() { + assert_eq!(refusal(&[]), "missing command (try --help)"); + assert_eq!(refusal(&["frob"]), r#"unknown command "frob""#); + assert_eq!(refusal(&["--frob"]), "invalid option '--frob'"); + // `--version` has no short form, and help and version are no + // commands. + assert_eq!(refusal(&["-V"]), "invalid option '-V'"); + assert_eq!(refusal(&["help"]), r#"unknown command "help""#); + assert_eq!(refusal(&["version"]), r#"unknown command "version""#); + // An option of a command is none of the tool. + assert_eq!( + refusal(&["--graceful", "generate", "dir"]), + "invalid option '--graceful'" + ); + } + + #[test] + fn commands() { + // A command reads what comes behind its name itself. + assert!(asks_for(&["generate", "--help"], Generate::HELP)); + assert!(asks_for(&["generate", "-h"], Generate::HELP)); + assert_eq!(refusal(&["generate"]), "missing argument DIR"); + assert!(asks_for(&["check", "--help"], Check::HELP)); + assert!(asks_for(&["check", "-h"], Check::HELP)); + assert_eq!(refusal(&["check"]), "missing argument MANIFEST"); + } +} diff --git a/src/fsmanifest/completions/_fsmanifest b/src/fsmanifest/completions/_fsmanifest new file mode 100644 index 0000000..4cb8266 --- /dev/null +++ b/src/fsmanifest/completions/_fsmanifest @@ -0,0 +1,73 @@ +#compdef fsmanifest +# SPDX-License-Identifier: LGPL-2.1-or-later +# +# The completion of fsmanifest for zsh: its commands and their options, a +# directory and a file for the arguments of a command, and the names of +# the features after --features. The names come from fsmanifest generate +# --features=help. + +# The names --features takes, with commas between them: the first word of +# each line of fsmanifest generate --features=help up to the first empty +# line, which is the name of a feature, and default and none. help is the +# whole list or none of it. $fsmanifest is the fsmanifest that runs. +(( $+functions[_fsmanifest_features] )) || +_fsmanifest_features() { + local line ret=1 + local -a names + for line in "${(@f)$(_call_program features $fsmanifest generate --features=help)}"; do + [[ -n $line ]] || break + names+=(${line%%[[:space:]]*}) + done + if [[ $PREFIX != *,* ]]; then + compadd -- help && ret=0 + fi + _sequence compadd - $names default none && ret=0 + return ret +} + +_fsmanifest() { + local curcontext=$curcontext state state_descr line ret=1 + local -A opt_args + # The command as the command line has it. For the arguments of a + # command, $words starts with the name of the command. + local fsmanifest=$words[1] + + _arguments -C \ + '(- *)'{-h,--help}'[Show this help]' \ + '(- *)--version[Show the version of fsmanifest]' \ + '1:command:->command' \ + '*::argument:->argument' && ret=0 + + case $state in + command) + local -a commands=( + 'generate:Write the manifest of a directory and everything below it' + 'check:Check a manifest' + ) + _describe -t commands command commands && ret=0 + ;; + argument) + curcontext=${curcontext%:*:*}:fsmanifest-$words[1]: + case $words[1] in + generate) + _arguments -S \ + '--features=[Record the features of LIST]:LIST:_fsmanifest_features' \ + '--cross-mounts[Walk into mount points]' \ + "--graceful[Leave out files whose names a manifest can't hold]" \ + '(- *)'{-h,--help}'[Show this help]' \ + '1:DIR:_files -/' \ + '2:MANIFEST:_files' && ret=0 + ;; + check) + _arguments -S \ + '(- *)'{-h,--help}'[Show this help]' \ + '1:MANIFEST:_files' && ret=0 + ;; + esac + ;; + esac + + return ret +} + +_fsmanifest "$@" diff --git a/src/fsmanifest/completions/fsmanifest.bash b/src/fsmanifest/completions/fsmanifest.bash new file mode 100644 index 0000000..bfbb7a6 --- /dev/null +++ b/src/fsmanifest/completions/fsmanifest.bash @@ -0,0 +1,112 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +# +# The completion of fsmanifest for bash: its commands and their options, +# a directory and a file for the arguments of a command, and the names of +# the features after --features. The names come from fsmanifest generate +# --features=help. + +# Prints the names --features takes, one on each line: the first word of +# each line of fsmanifest generate --features=help up to the first empty +# line, which is the name of a feature, and default and none. $1 is the +# fsmanifest that runs. +_fsmanifest_features() { + local line + while IFS= read -r line && [[ -n $line ]]; do + printf '%s\n' "${line%%[[:space:]]*}" + done < <("$1" generate --features=help 2> /dev/null) + printf '%s\n' default none +} + +_fsmanifest() { + local cur line=$COMP_LINE at=0 space i + local -a words + # The words of the command line up to the one being completed. bash + # splits a word at the characters of COMP_WORDBREAKS as well, so the + # parts of a word that no space separates are joined again: then + # --features=LIST is one word, and so is a path with a = or : in it. + for ((i = 0; i <= COMP_CWORD; i++)); do + space=${line:at} + space=${space%%[![:space:]]*} + if ((i > 0)) && [[ -z $space ]]; then + words[${#words[@]} - 1]+=${COMP_WORDS[i]} + else + words+=("${COMP_WORDS[i]}") + fi + at=$((at + ${#space} + ${#COMP_WORDS[i]})) + done + cur=${words[${#words[@]} - 1]} + + if ((${#words[@]} == 2)); then + if [[ $cur == -* ]]; then + COMPREPLY=($(compgen -W '-h --help --version' -- "$cur")) + else + COMPREPLY=($(compgen -W 'generate check' -- "$cur")) + fi + return + fi + + local options + case ${words[1]} in + generate) options='--features= --cross-mounts --graceful -h --help' ;; + check) options='-h --help' ;; + *) return ;; + esac + + # How many arguments come before the word being completed, and whether + # a -- came, after which every word is an argument. --features takes + # the word behind it, unless its list is behind a =. + local args=0 dashes=0 list + for ((i = 2; i < ${#words[@]} - 1; i++)); do + if ((dashes)); then + ((args++)) + continue + fi + case ${words[1]}:${words[i]} in + *:--) dashes=1 ;; + generate:--features) ((i++)) ;; + *:-?*) ;; + *) ((args++)) ;; + esac + done + if ((i == ${#words[@]})); then + # The word being completed is the list behind --features. + list=$cur + elif ((!dashes)) && [[ ${words[1]} == generate && $cur == --features=* ]]; then + list=${cur#--features=} + fi + + if [[ -v list ]]; then + # The names behind the last comma, without those the list has + # already. help is the whole list or none of it. + local listed=${list%"${list##*,}"} name + local -a names + while IFS= read -r name; do + [[ ,$listed == *,"$name",* ]] || names+=("$name") + done < <(_fsmanifest_features "$1") + [[ -n $listed ]] || names+=(help) + # bash replaces only $2, the part of the word behind the last + # character of COMP_WORDBREAKS in it. So what comes in front of $2 + # goes from each list. + local front=${cur%"$list"}$listed + front=${front#"${cur%"$2"}"} + # compgen -W would expand the names, so they are matched as they + # are. + COMPREPLY=() + for name in "${names[@]}"; do + [[ $name == "${list##*,}"* ]] && COMPREPLY+=("$front$name") + done + compopt -o nospace + elif ((!dashes)) && [[ $cur == -* ]]; then + COMPREPLY=($(compgen -W "$options" -- "$cur")) + [[ ${COMPREPLY[*]} == *= ]] && compopt -o nospace + else + # DIR and MANIFEST, whose names readline completes as it does for + # a command without a completion. + case ${words[1]}:$args in + generate:0) compopt -o dirnames ;; + generate:1 | check:0) compopt -o default ;; + esac + fi +} + +complete -F _fsmanifest fsmanifest diff --git a/src/fsmanifest/completions/fsmanifest.fish b/src/fsmanifest/completions/fsmanifest.fish new file mode 100644 index 0000000..75ad825 --- /dev/null +++ b/src/fsmanifest/completions/fsmanifest.fish @@ -0,0 +1,98 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +# +# The completion of fsmanifest for fish: its commands and their options, a +# directory and a file for the arguments of a command, and the names of the +# features after --features. The names come from fsmanifest generate +# --features=help. + +# Prints the words of the command line in front of the one being +# completed. commandline has -x for them since fish 4, and -o before. +function __fsmanifest_words + commandline -xpc 2>/dev/null + or commandline -opc +end + +# Succeeds if the word being completed is the command. +function __fsmanifest_command_next + test (count (__fsmanifest_words)) -eq 1 +end + +# Succeeds if the command is $argv[1]. +function __fsmanifest_command + set -l words (__fsmanifest_words) + test "$words[2]" = "$argv[1]" +end + +# Succeeds if the word being completed is argument $argv[2] of the command +# $argv[1], counting from 1. Options don't count, and --features takes the +# word behind it unless its list is behind a =. After a -- every word is +# an argument. +function __fsmanifest_argument + set -l words (__fsmanifest_words) + test "$words[2]" = "$argv[1]"; or return + set -e words[1..2] + set -l args 0 + set -l dashes 0 + set -l list 0 + for word in $words + if test $list = 1 + set list 0 + else if test $dashes = 1 + set args (math $args + 1) + else + switch "$argv[1]:$word" + case '*:--' + set dashes 1 + case 'generate:--features' + set list 1 + case '*:-?*' + case '*' + set args (math $args + 1) + end + end + end + test $list = 0; and test (math $args + 1) = "$argv[2]" +end + +# Prints the lists --features takes that start as the one being completed +# does: a name behind its last comma, which it doesn't have already. A name +# is the first word of each line of fsmanifest generate --features=help up +# to the first empty line, which is the name of a feature, or default or +# none. help is the whole list or none of it. Each list has an empty +# description behind a tab, which takes the place of the one of +# --features. +function __fsmanifest_features + set -l list (commandline -ct | string replace -r -- '^--features=' '') + set -l listed (string replace -r -- '[^,]*$' '' "$list") + set -l have (string split -n , -- "$listed") + set -l fsmanifest (__fsmanifest_words)[1] + set -l names + # fish says itself that a command isn't there, past 2>/dev/null. + if command -q -- $fsmanifest + for line in ($fsmanifest generate --features=help 2>/dev/null) + test -n "$line"; or break + set -a names (string replace -r -- '\s.*' '' "$line") + end + end + for name in $names default none + contains -- $name $have; or printf '%s\t\n' "$listed$name" + end + test -n "$listed"; or printf '%s\t\n' help +end + +complete -c fsmanifest -f + +complete -c fsmanifest -n __fsmanifest_command_next -a generate -d 'Write the manifest of a directory and everything below it' +complete -c fsmanifest -n __fsmanifest_command_next -a check -d 'Check a manifest' +complete -c fsmanifest -n __fsmanifest_command_next -s h -l help -d 'Show this help' +complete -c fsmanifest -n __fsmanifest_command_next -l version -d 'Show the version of fsmanifest' + +complete -c fsmanifest -n '__fsmanifest_command generate' -l features -x -a '(__fsmanifest_features)' -d 'Record the features of LIST' +complete -c fsmanifest -n '__fsmanifest_command generate' -l cross-mounts -d 'Walk into mount points' +complete -c fsmanifest -n '__fsmanifest_command generate' -l graceful -d "Leave out files whose names a manifest can't hold" +complete -c fsmanifest -n '__fsmanifest_command generate' -s h -l help -d 'Show this help' +complete -c fsmanifest -n '__fsmanifest_argument generate 1' -a '(__fish_complete_directories)' +complete -c fsmanifest -n '__fsmanifest_argument generate 2' -F + +complete -c fsmanifest -n '__fsmanifest_command check' -s h -l help -d 'Show this help' +complete -c fsmanifest -n '__fsmanifest_argument check 1' -F diff --git a/src/fsmanifest/failure.rs b/src/fsmanifest/failure.rs new file mode 100644 index 0000000..353d10a --- /dev/null +++ b/src/fsmanifest/failure.rs @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! Why the tool fails, and what it exits with. + +use std::fmt; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +use uapi16::ErrorKind; + +use crate::check::Input; +use crate::NAME; + +/// What the tool exits with, as diff and cmp have it: 0 on success and 2 +/// for trouble. Their 1, for a difference, is not used. +#[derive(Clone, Copy, Debug)] +#[repr(u8)] +pub(crate) enum Status { + /// The command did what it was asked to do. + Success = 0, + /// It did not, for one of the reasons of [`Failure`]. + Trouble = 2, +} + +impl From for ExitCode { + fn from(status: Status) -> ExitCode { + ExitCode::from(status as u8) + } +} + +/// Why the tool fails. A failure prints as what the tool says about it on +/// standard error. +#[derive(Debug)] +pub(crate) enum Failure { + /// The command line is not one the tool takes. + Usage(lexopt::Error), + /// A file or a directory the command line names can't be opened. + Open { + /// Its path, as the command line has it. + path: PathBuf, + error: io::Error, + }, + /// The path of a new file does not end in the name of a file. + NotFileName(PathBuf), + /// Something has the path of a new file already. + Exists(PathBuf), + /// Standard output can't be written, which the error says itself. + Stdout(io::Error), + /// The manifest of a directory can't be written. + Generate(uapi16::Error), + /// A manifest is not valid, or can't be read. + Check { + /// Where it was read from. + input: Input, + error: uapi16::Error, + }, +} + +impl Failure { + /// What the library starts a sentence with that names a record itself, + /// in front of the number of the record: "manifest record 2 is not + /// valid JSON", "manifest object 2 (a): the name is listed twice". + const NAMED_RECORDS: [&'static str; 2] = ["manifest record", "manifest object"]; + + /// Whether `message`, a sentence of the library about the record with + /// the number `record`, names that record itself. + fn names_record(message: &str, record: u64) -> bool { + Failure::NAMED_RECORDS.iter().any(|what| { + let named = format!("{} {}", what, record); + // "object 1" is not what "object 12" names. + let ends_there = |at: usize| !message[at + named.len()..].starts_with(|next: char| next.is_ascii_digit()); + message.match_indices(&named).any(|(at, _)| ends_there(at)) + }) + } + + /// The failure to open `path` with `error`. + pub(crate) fn open(path: &Path, error: io::Error) -> Failure { + Failure::Open { + path: path.to_path_buf(), + error, + } + } + + /// Says the failure on standard error, behind the name of the tool. + /// Where that can't be written either, the exit status says it alone. + pub(crate) fn report(&self) { + let _ = writeln!(io::stderr().lock(), "{}: {}", NAME, self); + } +} + +impl fmt::Display for Failure { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Failure::Usage(error) => error.fmt(f), + Failure::Open { path, error } => write!(f, "{}: {}", path.display(), error), + Failure::NotFileName(path) => write!(f, "{}: not the name of a file", path.display()), + Failure::Exists(path) => write!(f, "{}: exists already", path.display()), + Failure::Stdout(error) => error.fmt(f), + Failure::Generate(error) => error.fmt(f), + Failure::Check { input, error } => { + let message = error.to_string(); + // The record that is wrong goes in front, unless the + // sentence of the library names it. An error of the input, + // such as the one of a directory, is about no record. + let wrong = matches!(error.kind(), ErrorKind::Manifest(_)); + match error.record_number() { + Some(record) if wrong && !Failure::names_record(&message, record) => { + write!(f, "{}: record {}: {}", input, record, message) + } + _ => write!(f, "{}: {}", input, message), + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sentences_that_name_their_record() { + assert!(Failure::names_record("manifest record 2 is not valid JSON: EOF", 2)); + assert!(Failure::names_record( + "manifest object 12 (a/b): the name is listed twice", + 12 + )); + assert!(Failure::names_record("manifest object 0", 0)); + // Another record, and one whose number only starts the same. + assert!(!Failure::names_record( + "manifest object 12 (a): the name is listed twice", + 2 + )); + assert!(!Failure::names_record( + "manifest object 12 (a): the name is listed twice", + 1 + )); + // Sentences without a number. + assert!(!Failure::names_record("manifest record exceeds 4194304 bytes", 1)); + assert!(!Failure::names_record( + "manifest contains data after the trailer object", + 3 + )); + assert!(!Failure::names_record("manifest field 'name' is not a string", 1)); + } +} diff --git a/src/fsmanifest/fsmanifest.1 b/src/fsmanifest/fsmanifest.1 new file mode 100644 index 0000000..274f746 --- /dev/null +++ b/src/fsmanifest/fsmanifest.1 @@ -0,0 +1,183 @@ +.\" SPDX-License-Identifier: LGPL-2.1-or-later +.TH FSMANIFEST 1 "" fsmanifest +.SH NAME +fsmanifest \- generate and check UAPI.16 file manifests +.SH SYNOPSIS +.B fsmanifest generate +.RI [ OPTIONS ] +.I DIR +.RI [ MANIFEST ] +.br +.B fsmanifest check +.RI [ OPTIONS ] +.I MANIFEST +.br +.B fsmanifest +.BR \-h " | " \-\-help +.br +.B fsmanifest \-\-version +.SH DESCRIPTION +.B fsmanifest +is a command-line tool that generates and checks UAPI.16 file manifests. +.SH COMMANDS +.SS generate +Writes the manifest of the directory +.I DIR +and everything below it to the new file +.IR MANIFEST . +Without +.IR MANIFEST , +or with +.B \- +for it, the manifest goes to standard output. +.PP +.I MANIFEST +appears once the manifest is complete. +A +.I MANIFEST +that exists already is an error. +A +.I MANIFEST +inside +.I DIR +is not listed in the manifest. +A file inside +.I DIR +that standard output is redirected to is listed, so give +.I MANIFEST +instead. +.PP +A manifest of a large tree takes room on disk while it is built: next to +.IR MANIFEST , +and for standard output in the directory +.B TMPDIR +names or, without +.BR TMPDIR , +in +.IR /var/tmp . +.B TMPDIR +has to be a trusted directory, since whoever controls it can change the +manifest. +.PP +Options: +.TP +.BI \-\-features= LIST +Record the features of +.IR LIST , +a list of their names with commas between them. +.B default +stands for the default features, as in +.BR \%\-\-features=default,\:mtime,\:user\-xattr , +and +.B none +for no features. +Without the option the manifest records the default features. +.B \%\-\-features=help +lists the names and marks the default ones. +The +.B gpt\-* +names are for manifests of partitions, and +.B generate +refuses them for a tree. +.TP +.B \-\-cross\-mounts +Walk into mount points. +Without the option a directory that is a mount point is recorded as an +empty directory. +.TP +.B \-\-graceful +Leave out files whose names a manifest can't hold, a directory with +everything below it, instead of failing. +.TP +.BR \-h ", " \-\-help +Show the help of +.BR generate . +.PP +A field that has no value a manifest can hold is left out, such as a +modification time before 1970. +.B generate +prints nothing on success, and says on standard error how many files +and fields it left out. +.SS check +Checks the manifest in the file +.IR MANIFEST , +or the one on standard input with +.B \- +for +.IR MANIFEST . +.PP +Each object is checked on its own and against the one before it: its +fields, where it comes in the manifest, the order of the file objects if +the manifest declares one, and the features the manifest records. +So a name that comes twice is only sure to be found where the manifest +declares an order, and file objects that share an inode token are not +compared with each other. +The manifest also has to be one that may be used now: its root file +object is not revoked, and the time is inside its validity window. +.PP +.B check +does not look at the validity of the other file objects, and it does +not verify signatures cryptographically. +.PP +Options: +.TP +.BR \-h ", " \-\-help +Show the help of +.BR check . +.PP +.B check +prints nothing for a valid manifest. +For any other it says on standard error what is wrong. +Where a record is wrong, it names the record. +.SH OPTIONS +.TP +.BR \-h ", " \-\-help +Show the help of +.BR fsmanifest . +.TP +.B \-\-version +Show the version of +.BR fsmanifest . +.SH "EXIT STATUS" +.B fsmanifest +exits with 0 on success and with 2 on failure. +.B check +exits with 0 for a valid manifest, and with 2 for any other, or when the +manifest can't be read. +.SH EXAMPLES +Write the manifest of +.I /efi +to the new file +.IR esp.manifest : +.PP +.RS +.EX +fsmanifest generate /efi esp.manifest +.EE +.RE +.PP +The same with the features +.B mtime +and +.B \%user\-xattr +next to the default ones: +.PP +.RS +.EX +fsmanifest generate \-\-features=default,mtime,user\-xattr \e + /efi esp.manifest +.EE +.RE +.PP +Check the manifest: +.PP +.RS +.EX +fsmanifest check esp.manifest +.EE +.RE +.SH "SEE ALSO" +The specification of UAPI.16 file manifests: +.br +.UR https://uapi-group.org/specifications/specs/file_manifest/ +.UE diff --git a/src/fsmanifest/generate.rs b/src/fsmanifest/generate.rs new file mode 100644 index 0000000..8cc85f7 --- /dev/null +++ b/src/fsmanifest/generate.rs @@ -0,0 +1,478 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! `fsmanifest generate`: the manifest of a directory and everything below +//! it. + +use std::ffi::OsString; +use std::fs::File; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +use lexopt::prelude::*; +use uapi16::{AddFlags, Features, ManifestOptions, ManifestReport}; + +use crate::command::Command; +use crate::failure::Failure; +use crate::stdout::StandardOutput; +use crate::NAME; + +/// What `--features` asks for. +#[derive(Debug)] +enum FeatureRequest { + /// `help`: the names of the features, and no manifest. + Names, + /// A list of names: a manifest that records these features. + Record(Features), +} + +impl FeatureRequest { + /// What asks for the names of the features. + const NAMES: &'static str = "help"; + /// What stands for the default features in a list. + const DEFAULT: &'static str = "default"; + /// What stands for no features in a list. + const NONE: &'static str = "none"; + /// What separates the names of a list. + const SEPARATOR: char = ','; +} + +impl FromStr for FeatureRequest { + type Err = lexopt::Error; + + /// The request of the value `list` of `--features`: `help`, or names + /// of features as the specification has them, with `default` for the + /// default ones and `none` for no features. A list without a name in + /// it is refused, so that no features are recorded only where `none` + /// asks for it. + fn from_str(list: &str) -> Result { + if list == FeatureRequest::NAMES { + return Ok(FeatureRequest::Names); + } + list.split(FeatureRequest::SEPARATOR) + .try_fold(Features::NONE, |features, name| { + let named = match name { + FeatureRequest::DEFAULT => Features::DEFAULT, + FeatureRequest::NONE => Features::NONE, + name => name.parse().map_err(|_| format!("unknown feature {:?}", name))?, + }; + Ok(features | named) + }) + .map(FeatureRequest::Record) + } +} + +/// Where the manifest of a directory goes. +#[derive(Debug)] +enum Output { + /// To standard output. + Stdout, + /// Into a new file, which gets its name once the manifest is complete. + File(PathBuf), +} + +impl Output { + /// What a command line has in place of a file for standard output. + const STDOUT: &'static str = "-"; + + /// The directory the new file `path` goes into and the name it gets + /// there. + fn place(path: &Path) -> Result<(&Path, &Path), Failure> { + // Path::file_name() passes over a slash and a `.` at the end of a + // path, which say that it names a directory. + let name = path + .file_name() + .filter(|name| path.as_os_str().as_encoded_bytes().ends_with(name.as_encoded_bytes())) + .ok_or_else(|| Failure::NotFileName(path.to_path_buf()))?; + // A name alone is a file in the current directory. + let dir = match path.parent() { + Some(dir) if !dir.as_os_str().is_empty() => dir, + _ => Path::new("."), + }; + Ok((dir, Path::new(name))) + } +} + +impl From> for Output { + /// The output the argument MANIFEST of a command line names. + fn from(manifest: Option) -> Output { + match manifest { + Some(path) if path != Output::STDOUT => Output::File(path.into()), + _ => Output::Stdout, + } + } +} + +/// `generate`: writes the manifest of a directory and everything below it. +#[derive(Debug)] +pub(crate) struct Generate { + /// The directory the manifest describes. + dir: PathBuf, + /// Where the manifest goes. + output: Output, + /// What the manifest records. + features: Features, + /// How the directory is walked. + flags: AddFlags, +} + +impl Generate { + /// The name of the command. + pub(crate) const NAME: &'static str = "generate"; + + /// What `--help` prints for the command. + pub(crate) const HELP: &'static str = "\ +Usage: fsmanifest generate [OPTIONS] DIR [MANIFEST] + +Writes the manifest of the directory DIR and everything below it to the +new file MANIFEST. Without MANIFEST, or with - for it, the manifest goes +to standard output. + +MANIFEST appears once the manifest is complete. A MANIFEST that exists +already is an error. A MANIFEST inside DIR is not listed in the +manifest. A file inside DIR that standard output is redirected to is +listed, so give MANIFEST instead. + +A manifest of a large tree takes room on disk while it is built: next to +MANIFEST, and for standard output in the directory TMPDIR names or, +without TMPDIR, in /var/tmp. TMPDIR has to be a trusted directory, since +whoever controls it can change the manifest. + +Options: + --features=LIST Record the features of LIST, a list of their names + with commas between them. default stands for the + default features, as in + --features=default,mtime,user-xattr, and none for no + features. Without the option the manifest records + the default features. --features=help lists the + names and marks the default ones. + --cross-mounts Walk into mount points. Without the option a + directory that is a mount point is recorded as an + empty directory. + --graceful Leave out files whose names a manifest can't hold, a + directory with everything below it, instead of + failing. + -h, --help Show this help. + +A field that has no value a manifest can hold is left out, such as a +modification time before 1970. generate prints nothing on success, and +says on standard error how many files and fields it left out. + +Exit status: 0 on success, 2 on failure. +"; + + /// What `--features=help` prints behind the name of a default feature. + const DEFAULT_MARK: &'static str = " (default)"; + + /// What `--features=help` prints below the names of the features. + const FEATURES_NOTE: &'static str = " +The gpt-* names are for manifests of partitions, and generate refuses +them for a tree. A list also takes default for the default features and +none for no features. +"; + + /// What `--features=help` prints: the name of every feature the + /// library has, each at the start of a line of its own and the default + /// ones with the mark behind them, and the note below them. + pub(crate) fn features_help() -> String { + // The library lists both in the order of the names. + let mut defaults = Features::DEFAULT.names().peekable(); + let mut help = String::new(); + for name in Features::ALL.names() { + help.push_str(name); + if defaults.next_if_eq(&name).is_some() { + help.push_str(Generate::DEFAULT_MARK); + } + help.push('\n'); + } + help.push_str(Generate::FEATURES_NOTE); + help + } + + /// The command of the arguments behind `generate`, which `parser` + /// reads. + pub(crate) fn parse(mut parser: lexopt::Parser) -> Result { + let mut features = Features::DEFAULT; + let mut flags = AddFlags::NONE; + let mut dir = None; + let mut manifest = None; + while let Some(arg) = parser.next()? { + match arg { + Long("features") => match parser.value()?.string()?.parse()? { + FeatureRequest::Names => return Ok(Command::Features), + FeatureRequest::Record(listed) => features = listed, + }, + Long("cross-mounts") => flags |= AddFlags::CROSS_MOUNTS, + Long("graceful") => flags |= AddFlags::GRACEFUL, + Long("help") => return Command::flag(&mut parser, "--help", Command::Help(Generate::HELP)), + Short('h') => return Command::flag(&mut parser, "-h", Command::Help(Generate::HELP)), + Value(path) if dir.is_none() => dir = Some(PathBuf::from(path)), + Value(path) if manifest.is_none() => manifest = Some(path), + unexpected => return Err(unexpected.unexpected()), + } + } + Ok(Command::Generate(Generate { + dir: dir.ok_or("missing argument DIR")?, + output: Output::from(manifest), + features, + flags, + })) + } + + /// Opens the directory `path`, and nothing that is no directory: a path + /// with a slash at its end is one the kernel takes for a directory + /// only, as with O_DIRECTORY. So a FIFO fails here instead of blocking, + /// and a device node is not opened. + fn open_dir(path: &Path) -> Result { + File::open(path.join("")).map_err(|error| Failure::open(path, error)) + } + + /// Writes the manifest, and says on standard error what it leaves out. + pub(crate) fn run(self) -> Result<(), Failure> { + let top = Generate::open_dir(&self.dir)?; + let mut options = ManifestOptions::new(); + options.features(self.features); + let report = match &self.output { + Output::Stdout => { + let out = StandardOutput::open().map_err(Failure::Stdout)?; + options + .generate(out, &top, self.flags) + .map(|(_, report)| report) + .map_err(Failure::Generate)? + } + Output::File(path) => { + let (dir, name) = Output::place(path)?; + let dir = Generate::open_dir(dir)?; + // The file is on disk before it gets its name. A name that + // is taken is the only thing that fails with EEXIST. + options + .sync(true) + .generate_at(&dir, name, &top, self.flags) + .map_err(|error| match error.io_error() { + Some(taken) if taken.kind() == io::ErrorKind::AlreadyExists => Failure::Exists(path.clone()), + _ => Failure::Generate(error), + })? + } + }; + Generate::report_omitted(&report); + Ok(()) + } + + /// Says on standard error what the manifest that `report` is of leaves + /// out: files whose names a manifest can't hold, and fields that have no + /// value a manifest can hold. + fn report_omitted(report: &ManifestReport) { + let mut err = io::stderr().lock(); + let _ = match report.entries_omitted() { + 0 => Ok(()), + 1 => writeln!(err, "{}: left out 1 file whose name a manifest can't hold", NAME), + files => writeln!( + err, + "{}: left out {} files whose names a manifest can't hold", + NAME, files + ), + }; + let _ = match report.fields_omitted() { + 0 => Ok(()), + 1 => writeln!(err, "{}: left out 1 field that has no value a manifest can hold", NAME), + fields => writeln!( + err, + "{}: left out {} fields that have no value a manifest can hold", + NAME, fields + ), + }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + impl Output { + /// The file the manifest goes into, none for standard output. + fn file(&self) -> Option<&Path> { + match self { + Output::Stdout => None, + Output::File(path) => Some(path), + } + } + } + + /// What `generate` makes of the arguments `args` behind its name. + fn parse(args: &[&str]) -> Result { + Generate::parse(lexopt::Parser::from_args(args.iter().copied())) + } + + /// The command the arguments `args` ask for, which writes a manifest. + fn generate(args: &[&str]) -> Generate { + match parse(args) { + Ok(Command::Generate(generate)) => generate, + other => panic!("{:?}", other), + } + } + + /// What the tool says of the arguments `args`, which it refuses. + fn refusal(args: &[&str]) -> String { + parse(args).unwrap_err().to_string() + } + + #[test] + fn where_the_manifest_goes() { + let file = |args: &[&str]| generate(args).output.file().map(Path::to_path_buf); + assert_eq!(file(&["dir"]), None); + assert_eq!(file(&["dir", "-"]), None); + assert_eq!(file(&["dir", "out"]), Some("out".into())); + assert_eq!(file(&["dir", "./-"]), Some("./-".into())); + assert_eq!(generate(&["dir", "out"]).dir, Path::new("dir")); + // After `--` an argument is no option. + let dashes = generate(&["--", "--help", "--graceful"]); + assert_eq!(dashes.dir, Path::new("--help")); + assert_eq!(dashes.output.file(), Some(Path::new("--graceful"))); + assert_eq!(dashes.flags, AddFlags::NONE); + assert_eq!(refusal(&[]), "missing argument DIR"); + assert_eq!(refusal(&["--graceful"]), "missing argument DIR"); + assert_eq!(refusal(&["dir", "out", "more"]), r#"unexpected argument "more""#); + } + + #[test] + fn options() { + let asked = |args: &[&str]| { + let generate = generate(args); + (generate.features, generate.flags) + }; + assert_eq!(asked(&["dir"]), (Features::DEFAULT, AddFlags::NONE)); + assert_eq!( + asked(&["--cross-mounts", "dir"]), + (Features::DEFAULT, AddFlags::CROSS_MOUNTS) + ); + assert_eq!(asked(&["dir", "--graceful"]), (Features::DEFAULT, AddFlags::GRACEFUL)); + let both = AddFlags::CROSS_MOUNTS | AddFlags::GRACEFUL; + assert_eq!( + asked(&["--graceful", "dir", "--cross-mounts"]), + (Features::DEFAULT, both) + ); + assert_eq!(asked(&["--features=mtime", "dir"]), (Features::MTIME, AddFlags::NONE)); + assert_eq!(asked(&["--features=none", "dir"]), (Features::NONE, AddFlags::NONE)); + assert_eq!( + asked(&["--features", "mtime", "dir"]), + (Features::MTIME, AddFlags::NONE) + ); + // The last list counts. + let lists = ["--features=mtime", "dir", "--features=size"]; + assert_eq!(asked(&lists), (Features::SIZE, AddFlags::NONE)); + assert_eq!(refusal(&["--frob", "dir"]), "invalid option '--frob'"); + assert_eq!(refusal(&["-g", "dir"]), "invalid option '-g'"); + assert_eq!(refusal(&["--replace", "dir"]), "invalid option '--replace'"); + assert_eq!( + refusal(&["dir", "--features"]), + "missing argument for option '--features'" + ); + } + + #[test] + fn flags_take_no_value() { + for (args, option) in [ + (&["--graceful=yes", "dir"][..], "--graceful"), + (&["dir", "--graceful=yes"], "--graceful"), + (&["--cross-mounts=yes", "dir"], "--cross-mounts"), + (&["dir", "--cross-mounts=yes"], "--cross-mounts"), + (&["--help=yes"], "--help"), + (&["dir", "--help=yes"], "--help"), + (&["-h=yes"], "-h"), + (&["dir", "-hyes"], "-h"), + ] { + let said = format!(r#"unexpected argument for option '{}': "yes""#, option); + assert_eq!(refusal(args), said, "{:?}", args); + } + } + + #[test] + fn help() { + let asks_for_help = |args: &[&str]| matches!(parse(args), Ok(Command::Help(text)) if text == Generate::HELP); + assert!(asks_for_help(&["--help"])); + assert!(asks_for_help(&["-h"])); + // Whatever comes behind it, and without a DIR. + assert!(asks_for_help(&["dir", "out", "--help", "--frob"])); + assert!(asks_for_help(&["dir", "out", "-h", "--frob"])); + assert!(matches!(parse(&["--features=help"]), Ok(Command::Features))); + assert!(matches!( + parse(&["--features", "help", "--frob"]), + Ok(Command::Features) + )); + // What comes before it is read first. + assert_eq!(refusal(&["--frob", "--help"]), "invalid option '--frob'"); + } + + #[test] + fn the_names_of_the_features() { + let help = Generate::features_help(); + let (names, note) = help.split_once("\n\n").unwrap(); + assert_eq!(format!("\n{}", note), Generate::FEATURES_NOTE); + // A line starts with the name of a feature, and the default ones + // have the mark behind it. + let mut listed = Features::NONE; + let mut marked = Features::NONE; + for line in names.lines() { + let (name, mark) = match line.strip_suffix(Generate::DEFAULT_MARK) { + Some(name) => (name, true), + None => (line, false), + }; + let feature: Features = name.parse().unwrap(); + assert_eq!(listed & feature, Features::NONE, "{}", line); + listed |= feature; + if mark { + marked |= feature; + } + } + assert_eq!((listed, marked), (Features::ALL, Features::DEFAULT)); + } + + #[test] + fn feature_lists() { + let record = |list: &str| match list.parse::() { + Ok(FeatureRequest::Record(features)) => Ok(features), + Ok(FeatureRequest::Names) => panic!("{} asks for the names", list), + Err(e) => Err(e.to_string()), + }; + assert!(matches!("help".parse(), Ok(FeatureRequest::Names))); + assert_eq!(record("default"), Ok(Features::DEFAULT)); + assert_eq!(record("size"), Ok(Features::SIZE)); + let listed = Features::DEFAULT | Features::MTIME | Features::USER_XATTR; + assert_eq!(record("default,mtime,user-xattr"), Ok(listed)); + assert_eq!(record("mtime,default,mtime"), Ok(Features::DEFAULT | Features::MTIME)); + // `none` stands for no features, alone and next to names. + assert_eq!(record("none"), Ok(Features::NONE)); + assert_eq!(record("none,mtime"), Ok(Features::MTIME)); + assert_eq!(record("size,none,mtime"), Ok(Features::SIZE | Features::MTIME)); + assert_eq!(record("default,none"), Ok(Features::DEFAULT)); + assert_eq!(record("none,none"), Ok(Features::NONE)); + // Every name the library has is one a list takes. + for name in Features::ALL.names() { + assert_eq!(record(name), Ok(name.parse().unwrap()), "{}", name); + } + assert_eq!(record("mtimes"), Err(r#"unknown feature "mtimes""#.into())); + assert_eq!(record("size,MTIME"), Err(r#"unknown feature "MTIME""#.into())); + // `help` is the whole value, and no name of a list. + assert_eq!(record("size,help"), Err(r#"unknown feature "help""#.into())); + // A list without a name in it is not `none`. + assert_eq!(record(""), Err(r#"unknown feature """#.into())); + assert_eq!(record(","), Err(r#"unknown feature """#.into())); + assert_eq!(record("size,"), Err(r#"unknown feature """#.into())); + assert_eq!(record("none,"), Err(r#"unknown feature """#.into())); + assert_eq!(record("None"), Err(r#"unknown feature "None""#.into())); + assert_eq!(record("size, mtime"), Err(r#"unknown feature " mtime""#.into())); + } + + #[test] + fn the_place_of_a_new_file() { + let place = |path: &'static str| Output::place(Path::new(path)).map_err(|e| e.to_string()); + assert_eq!(place("out"), Ok((Path::new("."), Path::new("out")))); + assert_eq!(place("./out"), Ok((Path::new("."), Path::new("out")))); + assert_eq!(place("a/b/out"), Ok((Path::new("a/b"), Path::new("out")))); + assert_eq!(place("/out"), Ok((Path::new("/"), Path::new("out")))); + assert_eq!(place("../out"), Ok((Path::new(".."), Path::new("out")))); + for path in ["", ".", "..", "/", "a/..", "out/", "out/.", "out//", "a/out/./"] { + let said = format!("{}: not the name of a file", path); + assert_eq!(place(path), Err(said), "{}", path); + } + } +} diff --git a/src/fsmanifest/main.rs b/src/fsmanifest/main.rs new file mode 100644 index 0000000..7790b2f --- /dev/null +++ b/src/fsmanifest/main.rs @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! fsmanifest, a command-line tool for [UAPI.16 file manifests]. +//! +//! `fsmanifest generate` writes the manifest of a directory and everything +//! below it, and `fsmanifest check` checks a manifest. Each command +//! describes itself with `--help`. +//! +//! [UAPI.16 file manifests]: https://uapi-group.org/specifications/specs/file_manifest/ + +#![forbid(unsafe_code)] + +mod check; +mod command; +mod failure; +mod generate; +mod stdout; + +use std::process::ExitCode; + +use command::Command; +use failure::{Failure, Status}; + +/// The name of the tool, which everything it says on standard error starts +/// with. +const NAME: &str = env!("CARGO_PKG_NAME"); +/// The version of the tool, which `--version` prints. +const VERSION: &str = env!("CARGO_PKG_VERSION"); + +fn main() -> ExitCode { + let done = Command::parse(lexopt::Parser::from_env()) + .map_err(Failure::Usage) + .and_then(Command::run); + match done { + Ok(()) => Status::Success.into(), + Err(failure) => { + failure.report(); + Status::Trouble.into() + } + } +} diff --git a/src/fsmanifest/stdout.rs b/src/fsmanifest/stdout.rs new file mode 100644 index 0000000..bf22a73 --- /dev/null +++ b/src/fsmanifest/stdout.rs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! Standard output, as the tool writes to it. + +use std::fs::File; +use std::io::{self, Write}; +use std::os::fd::AsFd; + +/// Standard output of the tool: what `--help` and the like print, and a +/// manifest that goes to no file. +/// +/// It is written through a descriptor of its own and not through +/// [`io::Stdout`], which takes a write that fails with EBADF for one that +/// succeeded. With a standard output that can't be written, such as one +/// that is open for reading, a manifest would be lost that way and the +/// tool would exit with 0. An error says that it is one of standard +/// output, also once the library has passed it on. +pub(crate) struct StandardOutput(File); + +impl StandardOutput { + /// What an error of standard output starts with. + const NAME: &'static str = "standard output"; + + /// Standard output of the process. + pub(crate) fn open() -> io::Result { + let descriptor = io::stdout().as_fd().try_clone_to_owned(); + let file = descriptor.map(File::from).map_err(StandardOutput::named)?; + Ok(StandardOutput(file)) + } + + /// The error `error` of standard output, which says so. It keeps its + /// kind, which is what a write that was interrupted is tried again + /// for. + fn named(error: io::Error) -> io::Error { + io::Error::new(error.kind(), format!("{}: {}", StandardOutput::NAME, error)) + } +} + +impl Write for StandardOutput { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.write(buf).map_err(StandardOutput::named) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush().map_err(StandardOutput::named) + } +} diff --git a/src/fsmanifest/tests/cli.rs b/src/fsmanifest/tests/cli.rs new file mode 100644 index 0000000..1cd30ed --- /dev/null +++ b/src/fsmanifest/tests/cli.rs @@ -0,0 +1,899 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! fsmanifest as a program: what it writes, what it says on standard error +//! and what it exits with. + +use std::ffi::OsStr; +use std::fs::{self, File}; +use std::io::Write; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::symlink; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use uapi16::{Features, FileObject, InodeType, Object, Order, Reader, RootObject, Sha256, MAX_RECORD_SIZE}; + +/// What the tool exits with on success. +const SUCCESS: Option = Some(0); +/// What it exits with when it fails. +const TROUBLE: Option = Some(2); +/// What every line the tool says on standard error starts with. +const SAYS: &str = "fsmanifest: "; + +/// The root file object that says nothing but that this is a manifest. +const ROOT: &str = r#"{"mediaType":"application/vnd.uapi.16.manifest"}"#; +/// The root file object of a manifest that declares the code point order. +const ORDERED_ROOT: &str = r#"{"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"#; +/// The trailer object. +const TRAILER: &str = r#"{"mediaType":"application/vnd.uapi.16.trailer"}"#; +/// A signature object, whose data is the signature of nothing. +const SIGNATURE: &str = r#"{"mediaType":"application/vnd.uapi.16.signature","mechanism":"pkcs7","data":"AAAA"}"#; + +/// A directory of its own below the temporary directory, removed with +/// everything in it when the test ends. +struct TempDir(PathBuf); + +impl TempDir { + fn new(test: &str) -> TempDir { + let path = std::env::temp_dir().join(format!("fsmanifest-{}-{}", test, std::process::id())); + // What a test of the same name in a process of the same number + // left behind. + let _ = fs::remove_dir_all(&path); + fs::create_dir(&path).unwrap(); + TempDir(path) + } + + /// The path of `name` in the directory, as an argument of the tool. + fn path(&self, name: &str) -> String { + self.0.join(name).into_os_string().into_string().unwrap() + } + + /// Makes a tree in the directory and returns its path: a file, a + /// directory with a file and with a second name of the first file, and + /// a symbolic link. + fn tree(&self) -> String { + let tree = self.0.join("tree"); + fs::create_dir_all(tree.join("dir")).unwrap(); + fs::write(tree.join("file"), "hello\n").unwrap(); + fs::write(tree.join("dir/inner"), "inner\n").unwrap(); + fs::hard_link(tree.join("file"), tree.join("dir/hard")).unwrap(); + symlink("file", tree.join("link")).unwrap(); + self.path("tree") + } + + /// The names of the entries of the directory, sorted. + fn entries(&self) -> Vec { + let entries = fs::read_dir(&self.0).unwrap(); + let mut names: Vec = entries + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect(); + names.sort(); + names + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// A run of the tool that ended. +#[derive(Debug)] +struct Run { + /// What it exited with, none if a signal ended it. + status: Option, + /// What it wrote to standard output. + stdout: Vec, + /// What it said on standard error. + stderr: String, +} + +impl From for Run { + fn from(output: Output) -> Run { + Run { + status: output.status.code(), + stdout: output.stdout, + stderr: String::from_utf8(output.stderr).unwrap(), + } + } +} + +impl Run { + /// The tool with the arguments `args`, not started yet. + fn tool>(args: &[S]) -> Command { + let mut tool = Command::new(env!("CARGO_BIN_EXE_fsmanifest")); + tool.args(args); + tool + } + + /// Runs `tool` to its end. + fn ended(tool: &mut Command) -> Run { + tool.output().unwrap().into() + } + + /// Runs the tool with the arguments `args` and nothing on standard + /// input. + fn of>(args: &[S]) -> Run { + Run::ended(Run::tool(args).stdin(Stdio::null())) + } + + /// Runs the tool with the arguments `args` and with `input` on + /// standard input, which is a pipe. + fn fed(args: &[&str], input: &[u8]) -> Run { + let mut tool = Run::tool(args); + tool.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + let mut tool = tool.spawn().unwrap(); + let mut stdin = tool.stdin.take().unwrap(); + std::thread::scope(|scope| { + // A tool that fails stops reading, and the write fails then. + scope.spawn(move || { + let _ = stdin.write_all(input); + }); + tool.wait_with_output().unwrap().into() + }) + } + + /// What the run wrote to standard output: it succeeded, and said + /// nothing on standard error. + #[track_caller] + fn output(self) -> Vec { + assert_eq!((self.status, self.stderr.as_str()), (SUCCESS, "")); + self.stdout + } + + /// What the run wrote to standard output: it succeeded, and said the + /// one line `said` on standard error. + #[track_caller] + fn output_with(self, said: &str) -> Vec { + let stderr = format!("{}{}\n", SAYS, said); + assert_eq!((self.status, self.stderr), (SUCCESS, stderr)); + self.stdout + } + + /// The manifest the run wrote to standard output. + #[track_caller] + fn manifest(self) -> Manifest { + Manifest::read(&self.output()) + } + + /// Asserts that the run succeeded without a word: nothing on standard + /// output, and nothing on standard error. + #[track_caller] + fn silent(self) { + assert_eq!(self.output(), b""); + } + + /// What the run said on standard error: it failed, said one line, and + /// wrote nothing to standard output. + #[track_caller] + fn failure(self) -> String { + assert_eq!( + (self.status, self.stdout.as_slice()), + (TROUBLE, &b""[..]), + "{}", + self.stderr + ); + let said = self.stderr.strip_prefix(SAYS).and_then(|said| said.strip_suffix('\n')); + match said { + Some(said) if !said.contains('\n') => said.to_string(), + _ => panic!("{:?}", self.stderr), + } + } +} + +/// A manifest read to its end. +struct Manifest { + root: RootObject, + files: Vec, +} + +impl Manifest { + /// Reads the manifest `bytes`, which has no signature objects. + #[track_caller] + fn read(bytes: &[u8]) -> Manifest { + let mut reader = Reader::open(bytes).unwrap(); + let root = reader.root().clone(); + let files = reader.by_ref().map(|object| match object.unwrap() { + Object::File(file) => *file, + other => panic!("{:?}", other), + }); + Manifest { + root, + files: files.collect(), + } + } + + /// The names of the file objects, in the order of the manifest. + fn names(&self) -> Vec<&str> { + self.files.iter().map(|file| file.name().as_str()).collect() + } + + /// The file object with the name `name`. + fn file(&self, name: &str) -> &FileObject { + let named = |file: &&FileObject| file.name().as_str() == name; + self.files.iter().find(named).unwrap() + } +} + +/// The JSON text sequence of `records`: each behind a record separator and +/// with a newline at its end. +fn sequence(records: &[&str]) -> Vec { + let mut sequence = Vec::new(); + for record in records { + sequence.push(uapi16::RECORD_SEPARATOR); + sequence.extend_from_slice(record.as_bytes()); + sequence.push(b'\n'); + } + sequence +} + +/// The root file object of a manifest with the fields `fields`. +fn root_with(fields: &str) -> String { + format!(r#"{{"mediaType":"application/vnd.uapi.16.manifest",{}}}"#, fields) +} + +/// A day. +const DAY: Duration = Duration::from_secs(24 * 60 * 60); + +/// The time `time` in microseconds since the epoch, as the validity of a +/// manifest counts it. +fn usec(time: SystemTime) -> u128 { + time.duration_since(UNIX_EPOCH).unwrap().as_micros() +} + +#[test] +fn describes_itself() { + let help = String::from_utf8(Run::of(&["--help"]).output()).unwrap(); + assert!(help.starts_with("Usage: fsmanifest generate "), "{}", help); + // `-h` is short for `--help`. + assert_eq!(Run::of(&["-h"]).output(), help.as_bytes()); + for (command, usage) in [ + ("generate", "fsmanifest generate [OPTIONS] DIR [MANIFEST]\n"), + ("check", "fsmanifest check [OPTIONS] MANIFEST\n"), + ] { + let of_command = String::from_utf8(Run::of(&[command, "--help"]).output()).unwrap(); + assert!(of_command.starts_with(&format!("Usage: {}\n", usage)), "{}", of_command); + assert_eq!(Run::of(&[command, "-h"]).output(), of_command.as_bytes()); + // The help of the tool has the usage of each command. + assert!(help.contains(usage), "{}", help); + } + let version = format!("fsmanifest {}\n", env!("CARGO_PKG_VERSION")); + assert_eq!(Run::of(&["--version"]).output(), version.as_bytes()); +} + +#[test] +fn refuses_a_command_line_it_does_not_take() { + for (args, said) in [ + (&[][..], "missing command (try --help)"), + (&["frob"], r#"unknown command "frob""#), + (&["--frob"], "invalid option '--frob'"), + (&["-V"], "invalid option '-V'"), + (&["help"], r#"unknown command "help""#), + (&["-h=yes"], r#"unexpected argument for option '-h': "yes""#), + (&["generate", "-hyes"], r#"unexpected argument for option '-h': "yes""#), + (&["generate"], "missing argument DIR"), + (&["generate", "a", "b", "c"], r#"unexpected argument "c""#), + (&["generate", "--replace", "a", "b"], "invalid option '--replace'"), + ( + &["generate", "--graceful=yes", "a"], + r#"unexpected argument for option '--graceful': "yes""#, + ), + (&["--help=yes"], r#"unexpected argument for option '--help': "yes""#), + ( + &["--version=yes"], + r#"unexpected argument for option '--version': "yes""#, + ), + ( + &["generate", "--help=yes"], + r#"unexpected argument for option '--help': "yes""#, + ), + ( + &["check", "--help=yes"], + r#"unexpected argument for option '--help': "yes""#, + ), + ( + &["generate", "a", "--features"], + "missing argument for option '--features'", + ), + ( + &["generate", "--features", "mtimes", "a"], + r#"unknown feature "mtimes""#, + ), + (&["check"], "missing argument MANIFEST"), + (&["check", "a", "b"], r#"unexpected argument "b""#), + (&["check", "--cross-mounts", "a"], "invalid option '--cross-mounts'"), + ] { + assert_eq!(Run::of(args).failure(), said, "{:?}", args); + } +} + +#[test] +fn generate_writes_to_standard_output() { + let tmp = TempDir::new("stdout"); + let tree = tmp.tree(); + let written = Run::of(&["generate", &tree]).output(); + let manifest = Manifest::read(&written); + assert_eq!(manifest.root.order(), Some(Order::CodePoint)); + // The default features, which a manifest does not list. + assert_eq!(manifest.root.features(), None); + assert_eq!(manifest.names(), ["dir", "dir/hard", "dir/inner", "file", "link"]); + assert_eq!(manifest.file("dir").inode_type(), InodeType::Directory); + let link = manifest.file("link"); + assert_eq!(link.inode_type(), InodeType::Symlink); + assert_eq!(link.contents()[0].literal(), Some(&b"file"[..])); + let file = manifest.file("file"); + assert_eq!(file.size(), Some(6)); + assert_eq!(file.sha256(), Some(Sha256::digest(b"hello\n"))); + assert!(file.inode().mode().is_some() && file.inode().mtime_nsec().is_none()); + // The two names of one file. + assert!(file.inode_token().is_some()); + assert_eq!(file.inode_token(), manifest.file("dir/hard").inode_token()); + assert_eq!(manifest.file("dir/inner").inode_token(), None); + // `-` is standard output as well. + assert_eq!(Run::of(&["generate", &tree, "-"]).output(), written); + assert_eq!(tmp.entries(), ["tree"]); +} + +#[test] +fn generate_writes_a_new_file() { + let tmp = TempDir::new("file"); + let tree = tmp.tree(); + let out = tmp.path("out.manifest"); + Run::of(&["generate", &tree, &out]).silent(); + // What it writes to standard output for the same tree. + let written = Run::of(&["generate", &tree]).output(); + assert_eq!(fs::read(&out).unwrap(), written); + assert_eq!(tmp.entries(), ["out.manifest", "tree"]); + // A name alone is a file in the current directory. + let mut here = Run::tool(&["generate", "tree", "here.manifest"]); + Run::ended(here.current_dir(&tmp.0).stdin(Stdio::null())).silent(); + assert_eq!(fs::read(tmp.path("here.manifest")).unwrap(), written); +} + +#[test] +fn generate_refuses_a_file_that_exists() { + let tmp = TempDir::new("exists"); + let tree = tmp.tree(); + let out = tmp.path("out.manifest"); + fs::write(&out, "what was there").unwrap(); + let said = Run::of(&["generate", &tree, &out]).failure(); + assert_eq!(said, format!("{}: exists already", out)); + assert_eq!(fs::read(&out).unwrap(), b"what was there"); + // A symbolic link has the name too, also one that leads nowhere. + let link = tmp.path("link.manifest"); + symlink("nowhere", &link).unwrap(); + let said = Run::of(&["generate", &tree, &link]).failure(); + assert_eq!(said, format!("{}: exists already", link)); + assert_eq!(fs::read_link(&link).unwrap(), Path::new("nowhere")); + assert_eq!(tmp.entries(), ["link.manifest", "out.manifest", "tree"]); +} + +#[test] +fn generate_fails_for_paths_it_cannot_use() { + let tmp = TempDir::new("paths"); + let tree = tmp.tree(); + let missing = tmp.path("missing"); + let not_there = format!("{}: No such file or directory (os error 2)", missing); + assert_eq!(Run::of(&["generate", &missing]).failure(), not_there); + // The directory of the new file has to be there as well. + let below = tmp.path("missing/out.manifest"); + assert_eq!(Run::of(&["generate", &tree, &below]).failure(), not_there); + // A file is no directory to describe, and none a new file goes into. + let file = tmp.path("tree/file"); + let not_a_directory = format!("{}: Not a directory (os error 20)", file); + assert_eq!(Run::of(&["generate", &file]).failure(), not_a_directory); + let below = tmp.path("tree/file/out.manifest"); + assert_eq!(Run::of(&["generate", &tree, &below]).failure(), not_a_directory); + // A path that names a directory is none of a new file. + for directory in [ + format!("{}/", tmp.path("out")), + format!("{}/.", tree), + format!("{}/..", tree), + ] { + let said = Run::of(&["generate", &tree, &directory]).failure(); + assert_eq!(said, format!("{}: not the name of a file", directory)); + } + assert_eq!(tmp.entries(), ["tree"]); +} + +#[test] +fn generate_records_the_features_asked_for() { + let tmp = TempDir::new("features"); + let tree = tmp.tree(); + let written = Run::of(&["generate", "--features=size", &tree]).output(); + let manifest = Manifest::read(&written); + assert_eq!(manifest.root.features(), Some(Features::SIZE)); + let file = manifest.file("file"); + assert_eq!((file.size(), file.sha256(), file.inode().mode()), (Some(6), None, None)); + // The list can be an argument of its own. + assert_eq!(Run::of(&["generate", "--features", "size", &tree]).output(), written); + // `default` stands for the default features. + let manifest = Run::of(&["generate", "--features=default,mtime", &tree]).manifest(); + assert_eq!(manifest.root.features(), Some(Features::DEFAULT | Features::MTIME)); + let file = manifest.file("file"); + assert!(file.sha256().is_some() && file.inode().mode().is_some()); + assert!(file.inode().mtime_nsec().is_some()); + // `none` stands for no features, which the manifest says with an + // empty list. The file objects have names and types then. + let written = Run::of(&["generate", "--features=none", &tree]).output(); + let root = written.split(|&byte| byte == b'\n').next().unwrap(); + let root = std::str::from_utf8(root).unwrap(); + assert!(root.contains(r#""features":[]"#), "{}", root); + let manifest = Manifest::read(&written); + assert_eq!(manifest.root.features(), Some(Features::NONE)); + assert_eq!(manifest.names(), ["dir", "dir/hard", "dir/inner", "file", "link"]); + let file = manifest.file("file"); + assert_eq!((file.size(), file.sha256(), file.inode().mode()), (None, None, None)); + assert_eq!(manifest.file("link").inode_type(), InodeType::Symlink); + // With names next to it the manifest records those names. + let manifest = Run::of(&["generate", "--features=none,mtime", &tree]).manifest(); + assert_eq!(manifest.root.features(), Some(Features::MTIME)); + let file = manifest.file("file"); + assert!(file.inode().mtime_nsec().is_some() && file.size().is_none()); + // A list without a name in it is not `none`. + for list in ["--features=", "--features=,", "--features=none,"] { + let said = Run::of(&["generate", list, &tree]).failure(); + assert_eq!(said, r#"unknown feature """#, "{}", list); + } + // A feature of partitions is none of a tree, which the library says. + let said = Run::of(&["generate", "--features=default,gpt-label", &tree]).failure(); + assert_eq!( + said, + "'gpt-label' is a feature of partitions and does not apply to a tree of files" + ); +} + +#[test] +fn generate_lists_the_features() { + let tmp = TempDir::new("list"); + let tree = tmp.tree(); + let listed = String::from_utf8(Run::of(&["generate", "--features=help"]).output()).unwrap(); + // A line for every name of the library, an empty line, and a note. A + // line starts with the name, and the default features have a mark + // behind it. + let (lines, note) = listed.split_once("\n\n").unwrap(); + let names: Vec<&str> = lines.lines().map(|line| line.split(' ').next().unwrap()).collect(); + assert_eq!(names, Features::ALL.names().collect::>()); + let marked = lines.lines().filter_map(|line| line.strip_suffix(" (default)")); + assert_eq!( + marked.collect::>(), + Features::DEFAULT.names().collect::>() + ); + assert!(lines.contains("\nmtime\n") && lines.contains("\nsha256 (default)\n")); + let said = "\ +The gpt-* names are for manifests of partitions, and generate refuses +them for a tree. A list also takes default for the default features and +none for no features. +"; + assert_eq!(note, said); + // The note holds: every name of the list is one generate knows, and it + // refuses those of partitions, which are the gpt-* ones. + for name in names { + let run = Run::of(&["generate", &format!("--features={}", name), &tree]); + assert!(!run.stderr.contains("unknown feature"), "{}: {}", name, run.stderr); + let refused = run.status == TROUBLE && run.stderr.contains("is a feature of partitions"); + assert_eq!(refused, name.starts_with("gpt-"), "{}: {}", name, run.stderr); + } +} + +#[test] +fn generate_leaves_out_what_a_manifest_cannot_hold() { + let tmp = TempDir::new("graceful"); + let tree = tmp.tree(); + // A name that is not UTF-8, and a directory with a newline in its name. + let not_utf8 = Path::new(&tree).join(OsStr::from_bytes(b"not-utf8-\xff")); + fs::write(¬_utf8, "data").unwrap(); + let directory = Path::new(&tree).join("new\nline"); + fs::create_dir(&directory).unwrap(); + fs::write(directory.join("below"), "data").unwrap(); + let out = tmp.path("out.manifest"); + let said = Run::of(&["generate", &tree, &out]).failure(); + assert!(said.contains("a name a manifest cannot hold"), "{}", said); + // Nothing is left of the manifest. + assert_eq!(tmp.entries(), ["tree"]); + // With --graceful they are left out, the directory with what is below + // it as one. + let written = Run::of(&["generate", "--graceful", &tree, &out]) + .output_with("left out 2 files whose names a manifest can't hold"); + assert_eq!(written, b""); + let manifest = Manifest::read(&fs::read(&out).unwrap()); + assert_eq!(manifest.names(), ["dir", "dir/hard", "dir/inner", "file", "link"]); + fs::remove_file(¬_utf8).unwrap(); + let written = + Run::of(&["generate", "--graceful", &tree]).output_with("left out 1 file whose name a manifest can't hold"); + assert_eq!(written, fs::read(&out).unwrap()); +} + +#[test] +fn generate_says_how_many_fields_it_left_out() { + let tmp = TempDir::new("fields"); + let tree = tmp.tree(); + // A modification time before 1970 is none a manifest can hold. + let file = File::options().write(true).open(Path::new(&tree).join("file")).unwrap(); + file.set_modified(UNIX_EPOCH - Duration::from_secs(1)).unwrap(); + // The file has two names, and neither of its file objects has the time. + let written = Run::of(&["generate", "--features=default,mtime", &tree]) + .output_with("left out 2 fields that have no value a manifest can hold"); + let manifest = Manifest::read(&written); + assert_eq!(manifest.file("file").inode().mtime_nsec(), None); + assert_eq!(manifest.file("dir/hard").inode().mtime_nsec(), None); + assert!(manifest.file("dir/inner").inode().mtime_nsec().is_some()); + fs::remove_file(Path::new(&tree).join("dir/hard")).unwrap(); + Run::of(&["generate", "--features=default,mtime", &tree]) + .output_with("left out 1 field that has no value a manifest can hold"); + // A manifest that does not record the time leaves nothing out. + assert_eq!(Run::of(&["generate", &tree]).manifest().names().len(), 4); +} + +#[test] +fn generate_crosses_mount_points_when_asked() { + /// What the script exits with where it can't mount. + const NOT_MOUNTED: i32 = 77; + let tmp = TempDir::new("mounts"); + let tree = tmp.tree(); + fs::create_dir(Path::new(&tree).join("mount")).unwrap(); + // The mount takes a user and a mount namespace, which unshare(1) makes. + let unshared = |script: &str, args: &[&str]| { + let mut unshare = Command::new("unshare"); + unshare.args(["-Urm", "sh", "-c", script]).args(args); + unshare.stdin(Stdio::null()).output() + }; + if !unshared("true", &[]).is_ok_and(|output| output.status.success()) { + eprintln!("skipping: unshare -Urm does not work here"); + return; + } + // The script mounts a tmpfs over the directory, makes a file in it, and + // then runs the command behind its first argument, the tree. + let script = format!( + r#"mount -t tmpfs tmpfs "$1/mount" || exit {}; echo data > "$1/mount/below" && shift && exec "$@""#, + NOT_MOUNTED + ); + let names_with = |options: &[&str]| { + let generate = [env!("CARGO_BIN_EXE_fsmanifest"), "generate"]; + let args = [&["sh", &tree], &generate[..], options, &[&tree]].concat(); + let output = unshared(&script, &args).unwrap(); + if output.status.code() == Some(NOT_MOUNTED) { + return None; + } + assert_eq!(output.status.code(), SUCCESS, "{:?}", output); + let manifest = Manifest::read(&output.stdout); + Some(manifest.names().join(" ")) + }; + let Some(not_crossed) = names_with(&[]) else { + eprintln!("skipping: no tmpfs can be mounted here"); + return; + }; + // A mount point that is not crossed is an empty directory. + assert_eq!(not_crossed, "dir dir/hard dir/inner file link mount"); + let crossed = names_with(&["--cross-mounts"]).unwrap(); + assert_eq!(crossed, "dir dir/hard dir/inner file link mount mount/below"); +} + +#[test] +fn generate_writes_a_manifest_into_the_tree_it_describes() { + let tmp = TempDir::new("inside"); + let tree = tmp.tree(); + // A manifest does not list itself while it is written. + let inside = tmp.path("tree/dir/out.manifest"); + Run::of(&["generate", &tree, &inside]).silent(); + let manifest = Manifest::read(&fs::read(&inside).unwrap()); + assert_eq!(manifest.names(), ["dir", "dir/hard", "dir/inner", "file", "link"]); + // Once it is there it is a file like any other. + let manifest = Run::of(&["generate", &tree]).manifest(); + let with_it = ["dir", "dir/hard", "dir/inner", "dir/out.manifest", "file", "link"]; + assert_eq!(manifest.names(), with_it); + fs::remove_file(&inside).unwrap(); + // The name the specification has for the manifest at the top of its + // tree is passed over, also once the manifest is there. + let at_the_top = tmp.path("tree/Uapi16Manifest"); + Run::of(&["generate", &tree, &at_the_top]).silent(); + let written = fs::read(&at_the_top).unwrap(); + assert_eq!( + Manifest::read(&written).names(), + ["dir", "dir/hard", "dir/inner", "file", "link"] + ); + assert_eq!(Run::of(&["generate", &tree]).output(), written); +} + +#[test] +fn says_when_standard_output_cannot_be_written() { + let tmp = TempDir::new("output"); + let tree = tmp.tree(); + // A device that is full, and a standard output that is open for + // reading. + let full = File::options().write(true).open("/dev/full").unwrap(); + let for_reading = File::open("/dev/null").unwrap(); + for (stdout, said) in [ + (full, "standard output: No space left on device (os error 28)"), + (for_reading, "standard output: Bad file descriptor (os error 9)"), + ] { + for args in [ + &["generate", &tree][..], + &["generate", "--features=help"], + &["--help"], + &["--version"], + ] { + let mut tool = Run::tool(args); + tool.stdin(Stdio::null()).stdout(stdout.try_clone().unwrap()); + assert_eq!(Run::ended(&mut tool).failure(), said, "{:?}", args); + } + } +} + +#[test] +fn takes_arguments_that_are_not_utf8() { + let tmp = TempDir::new("bytes"); + tmp.tree(); + // A DIR and a MANIFEST are paths, whatever their bytes are. + let dir = tmp.0.join(OsStr::from_bytes(b"tree-\xff")); + fs::rename(tmp.0.join("tree"), &dir).unwrap(); + let out = tmp.0.join(OsStr::from_bytes(b"out-\xff")); + Run::of(&[OsStr::new("generate"), dir.as_os_str(), out.as_os_str()]).silent(); + let manifest = Manifest::read(&fs::read(&out).unwrap()); + assert_eq!(manifest.names(), ["dir", "dir/hard", "dir/inner", "file", "link"]); + Run::of(&[OsStr::new("check"), out.as_os_str()]).silent(); + // What is said of such a path is said in UTF-8. + let said = Run::of(&[OsStr::new("generate"), dir.as_os_str(), out.as_os_str()]).failure(); + assert_eq!(said, format!("{}: exists already", out.display())); + let missing = tmp.0.join(OsStr::from_bytes(b"missing-\xff")); + let not_there = format!("{}: No such file or directory (os error 2)", missing.display()); + let said = Run::of(&[OsStr::new("generate"), missing.as_os_str()]).failure(); + assert_eq!(said, not_there); + let said = Run::of(&[OsStr::new("check"), missing.as_os_str()]).failure(); + assert_eq!(said, not_there); + // A list of features and a command are text. + let list = OsStr::from_bytes(b"--features=size,\xff"); + let said = Run::of(&[OsStr::new("generate"), list, dir.as_os_str()]).failure(); + assert_eq!(said, r#"argument is invalid unicode: "size,\xFF""#); + let said = Run::of(&[OsStr::from_bytes(b"gener\xffate"), dir.as_os_str()]).failure(); + assert_eq!(said, r#"unknown command "gener\xFFate""#); +} + +#[test] +fn check_takes_what_generate_writes() { + let tmp = TempDir::new("roundtrip"); + let tree = tmp.tree(); + for features in ["default", "default,mtime", "size", "mtime", "none"] { + let out = tmp.path(features); + Run::of(&["generate", "--features", features, &tree, &out]).silent(); + Run::of(&["check", &out]).silent(); + } + // From one to the other through a pipe, which is read once. + let mut generate = Run::tool(&["generate", &tree]); + let mut generate = generate.stdin(Stdio::null()).stdout(Stdio::piped()).spawn().unwrap(); + let mut check = Run::tool(&["check", "-"]); + Run::ended(check.stdin(generate.stdout.take().unwrap())).silent(); + assert!(generate.wait().unwrap().success()); +} + +#[test] +fn check_takes_a_valid_manifest() { + let tmp = TempDir::new("valid"); + let path = tmp.path("manifest"); + let file = r#"{"name":"a","size":3}"#; + let directory = r#"{"name":"b","type":"dir"}"#; + let below = r#"{"name":"b/c","type":"lnk","contents":[{"literal":"YQ=="}]}"#; + for records in [ + &[ROOT, TRAILER][..], + &[ROOT, file, directory, below, TRAILER], + &[ORDERED_ROOT, file, directory, below, TRAILER], + // A manifest that declares no order has none to keep. + &[ROOT, directory, below, file, TRAILER], + // Signature objects are read, and nothing verifies them. + &[ROOT, file, SIGNATURE, SIGNATURE, TRAILER], + ] { + let manifest = sequence(records); + Run::fed(&["check", "-"], &manifest).silent(); + fs::write(&path, &manifest).unwrap(); + Run::of(&["check", &path]).silent(); + } +} + +#[test] +fn check_refuses_a_manifest_that_may_not_be_used_now() { + let tmp = TempDir::new("validity"); + let path = tmp.path("manifest"); + let (yesterday, tomorrow) = (usec(SystemTime::now() - DAY), usec(SystemTime::now() + DAY)); + let ended = format!(r#""validUntilUSec":{}"#, yesterday); + let not_begun = format!(r#""validSinceUSec":{}"#, tomorrow); + for (fields, said) in [ + (r#""validity":"revoked""#, "the manifest is revoked"), + (r#""validUntilUSec":1"#, "the manifest has expired"), + (ended.as_str(), "the manifest has expired"), + (not_begun.as_str(), "the manifest is not valid yet"), + ] { + let manifest = sequence(&[&root_with(fields), r#"{"name":"a"}"#, TRAILER]); + let from_stdin = Run::fed(&["check", "-"], &manifest).failure(); + assert_eq!(from_stdin, format!("standard input: {}", said)); + fs::write(&path, &manifest).unwrap(); + assert_eq!(Run::of(&["check", &path]).failure(), format!("{}: {}", path, said)); + } + // The time is inside a window from yesterday to tomorrow. + let window = format!(r#""validSinceUSec":{},"validUntilUSec":{}"#, yesterday, tomorrow); + Run::fed(&["check", "-"], &sequence(&[&root_with(&window), TRAILER])).silent(); + // What is wrong with the manifest itself is found first. + let revoked = root_with(r#""validity":"revoked""#); + let said = Run::fed(&["check", "-"], &sequence(&[&revoked, r#"{"name":7}"#, TRAILER])).failure(); + assert_eq!(said, "standard input: record 1: manifest field 'name' is not a string"); +} + +#[test] +fn check_looks_at_the_validity_of_the_root_only() { + for fields in [r#""validity":"revoked""#, r#""validUntilUSec":1"#] { + let file = format!(r#"{{"name":"a",{}}}"#, fields); + Run::fed(&["check", "-"], &sequence(&[ROOT, &file, TRAILER])).silent(); + } +} + +#[test] +fn check_refuses_a_manifest_out_of_its_declared_order() { + let (a, b) = (r#"{"name":"a"}"#, r#"{"name":"b"}"#); + Run::fed(&["check", "-"], &sequence(&[ORDERED_ROOT, a, b, TRAILER])).silent(); + let said = Run::fed(&["check", "-"], &sequence(&[ORDERED_ROOT, b, a, TRAILER])).failure(); + let out_of_order = "manifest object 2 (a): comes after 'b', which it sorts before in the code point ordering"; + assert_eq!(said, format!("standard input: {}", out_of_order)); + // The same file objects in a manifest that declares no order. + Run::fed(&["check", "-"], &sequence(&[ROOT, b, a, TRAILER])).silent(); +} + +#[test] +fn check_names_the_record_that_is_wrong() { + let tmp = TempDir::new("records"); + let path = tmp.path("manifest"); + let a = r#"{"name":"a"}"#; + let unlisted = "'mTimeNSec' is a field of the feature 'mtime', which the manifest does not record"; + for (records, record, said) in [ + // Most sentences of the library name the record themselves. + ( + &[ROOT, a, r#"{"name":"#, TRAILER][..], + Some(2), + "manifest record 2 is not valid JSON: ", + ), + ( + &[ROOT, a, a, TRAILER], + Some(2), + "manifest object 2 (a): the name is listed twice\n", + ), + ( + &[ROOT, r#"{"name":"a/b"}"#, TRAILER], + Some(1), + "manifest object 1 (a/b): does not come right after the object of its directory 'a'\n", + ), + ( + &[ROOT, r#"{"name":"a","mTimeNSec":1}"#, TRAILER], + Some(1), + &format!("manifest object 1 (a): {}\n", unlisted), + ), + // The tool names it in front of those that don't. + ( + &[ROOT, r#"{"name":7}"#, TRAILER], + Some(1), + "record 1: manifest field 'name' is not a string\n", + ), + ( + &[ROOT, a, TRAILER, a], + Some(3), + "record 3: manifest contains data after the trailer object\n", + ), + ( + &[ROOT, SIGNATURE, a, TRAILER], + Some(2), + "record 2: manifest contains a file object after a signature object\n", + ), + // A manifest that ends early has no record that is wrong. + ( + &[ROOT, a], + None, + "manifest lacks the trailer object, it is incomplete\n", + ), + (&[], None, "manifest contains no objects\n"), + ] { + fs::write(&path, sequence(records)).unwrap(); + let found = Run::of(&["check", &path]).failure() + "\n"; + assert!(found.starts_with(&format!("{}: {}", path, said)), "{}", found); + // The record is named once. + if let Some(record) = record { + let named = [format!("record {}", record), format!("object {}", record)]; + let times: usize = named.iter().map(|named| found.matches(named.as_str()).count()).sum(); + assert_eq!(times, 1, "{}", found); + } + } +} + +#[test] +fn check_refuses_a_hostile_manifest() { + // Names that lead out of the tree, or to nothing below it. + for name in ["../etc/passwd", "/etc/passwd", "a/../../b", "..", ".", "a//b", "a/"] { + let file = format!(r#"{{"name":"{}"}}"#, name); + let said = Run::fed(&["check", "-"], &sequence(&[ROOT, &file, TRAILER])).failure(); + assert!(said.starts_with("standard input: manifest object 1: name "), "{}", said); + } + // A record larger than a record can be, with an end and without one. + let too_large = format!( + "standard input: record 1: manifest record exceeds {} bytes", + MAX_RECORD_SIZE + ); + let long = format!(r#"{{"name":"{}"}}"#, "a".repeat(MAX_RECORD_SIZE)); + assert_eq!( + Run::fed(&["check", "-"], &sequence(&[ROOT, &long, TRAILER])).failure(), + too_large + ); + let mut endless = sequence(&[ROOT]); + endless.push(uapi16::RECORD_SEPARATOR); + endless.resize(3 * MAX_RECORD_SIZE, b' '); + assert_eq!(Run::fed(&["check", "-"], &endless).failure(), too_large); + // Bytes that are no manifest: the program of this test, as it is and + // as the one record of a manifest. + let mut program = fs::read(std::env::current_exe().unwrap()).unwrap(); + let said = Run::fed(&["check", "-"], &program).failure(); + assert!( + said.starts_with("standard input: record 0: manifest record does not start with"), + "{}", + said + ); + program.insert(0, uapi16::RECORD_SEPARATOR); + let said = Run::fed(&["check", "-"], &program).failure(); + assert!( + said.starts_with("standard input: record 0: manifest record "), + "{}", + said + ); +} + +#[test] +fn check_fails_cleanly_for_a_manifest_changed_anywhere() { + let valid = sequence(&[ + ORDERED_ROOT, + r#"{"name":"a","size":3,"mode":420}"#, + r#"{"name":"b","type":"dir"}"#, + r#"{"name":"b/c","type":"lnk","contents":[{"literal":"YQ=="}]}"#, + SIGNATURE, + TRAILER, + ]); + Run::fed(&["check", "-"], &valid).silent(); + // Whatever a byte is changed to, the tool takes the manifest or says in + // one line why it does not. + for at in 0..valid.len() { + for byte in [0x00, b'"', b'{', b'9', uapi16::RECORD_SEPARATOR, 0xff] { + let mut changed = valid.clone(); + changed[at] = byte; + let run = Run::fed(&["check", "-"], &changed); + if run.status == SUCCESS { + run.silent(); + } else { + let said = run.failure(); + assert!( + said.starts_with("standard input: "), + "byte {} as {:#04x}: {}", + at, + byte, + said + ); + } + } + } + // A manifest that ends early is incomplete, unless all it lacks is the + // newline at its end. + for len in 0..valid.len() { + let run = Run::fed(&["check", "-"], &valid[..len]); + if len == valid.len() - 1 { + run.silent(); + } else { + let said = run.failure(); + assert!(said.starts_with("standard input: "), "{} bytes: {}", len, said); + } + } +} + +#[test] +fn check_fails_for_a_file_it_cannot_read() { + let tmp = TempDir::new("unreadable"); + let missing = tmp.path("missing"); + let said = Run::of(&["check", &missing]).failure(); + assert_eq!(said, format!("{}: No such file or directory (os error 2)", missing)); + // A directory opens, and can't be read. + let directory = tmp.path(""); + let said = Run::of(&["check", &directory]).failure(); + assert_eq!(said, format!("{}: Is a directory (os error 21)", directory)); +} diff --git a/src/fsmanifest/tests/completions.py b/src/fsmanifest/tests/completions.py new file mode 100755 index 0000000..968f4c9 --- /dev/null +++ b/src/fsmanifest/tests/completions.py @@ -0,0 +1,311 @@ +#!/usr/bin/python3 -I +# SPDX-License-Identifier: LGPL-2.1-or-later +# +# Tests the completion of fsmanifest for a shell, in that shell: +# +# completions.py SHELL FSMANIFEST +# +# SHELL is bash, zsh or fish, and FSMANIFEST the fsmanifest whose names of +# features the completion offers. bash and zsh run in a terminal of their +# own, where a key puts all the matches of the word in front of the cursor +# into the line, and another key writes the line to a file. The completion +# writes its standard error to a second terminal there. fish lists the +# matches itself, with complete -C. Each test compares the matches of a +# command line with those it expects, in a directory with directories and +# a file in it, one with a space in its name. A test fails as well if the +# completion writes to standard error or makes a file. + +import os +import pty +import select +import shlex +import shutil +import signal +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +COMPLETIONS = Path(__file__).resolve().parent.parent / "completions" +# How long a shell may take to complete a command line, or to exit. +TIMEOUT = 10 +# An fsmanifest whose --features=help lists a name with the mark of a +# default feature, and names a shell would expand: a pattern that matches +# files of the directory, and a command substitution that makes a file. +STUB = """#!/bin/sh +printf '%s\\n' 'mode (default)' 'tre*' '$(touch${IFS}EXPANDED)' '' 'no name' +""" +STUB_NAMES = {"mode", "tre*", "$(touch${IFS}EXPANDED)"} + + +def feature_names(fsmanifest): + """The names of the features as fsmanifest generate --features=help + lists them: the first word of each line up to the first empty one.""" + listed = subprocess.run( + [fsmanifest, "generate", "--features=help"], capture_output=True, text=True, check=True + ) + names = [] + for line in listed.stdout.splitlines(): + if not line: + break + names.append(line.split()[0]) + return names + + +def tests(names, stub, missing): + """The command lines that are completed, each with its matches: with + the fsmanifest that is tested, with stub, an fsmanifest that lists + STUB_NAMES, and with missing, one that isn't there.""" + files = {"tree", "other", "my dir", "tree.manifest"} + directories = {"tree", "other", "my dir"} + lists = set(names) | {"default", "none"} + keywords = {"default", "none", "help"} + return [ + ("fsmanifest ", {"generate", "check"}), + ("fsmanifest -", {"-h", "--help", "--version"}), + ("fsmanifest generate --", {"--features", "--cross-mounts", "--graceful", "--help"}), + ("fsmanifest check -", {"-h", "--help"}), + ("fsmanifest generate ", directories), + ("fsmanifest generate my", {"my dir"}), + ("fsmanifest generate tree ", files), + ("fsmanifest generate my\\ dir ", files), + ("fsmanifest generate tree tree.manifest t", set()), + ("fsmanifest generate -- -tree ", files), + ("fsmanifest generate --features mtime ", directories), + ("fsmanifest check ", files), + ("fsmanifest check tree.manifest t", set()), + ("fsmanifest generate --features=", lists | {"help"}), + ("fsmanifest generate --features=mt", {"mtime"}), + ("fsmanifest generate --features=default,user-x", {"default,user-xattr"}), + ( + "fsmanifest generate --features=default,mtime,", + {"default,mtime," + name for name in lists - {"default", "mtime"}}, + ), + ("fsmanifest generate --features mt", {"mtime"}), + (f"{stub} generate --features=", STUB_NAMES | keywords), + (f"{stub} generate --features ", STUB_NAMES | keywords), + (f"{missing} generate --features=", keywords), + ] + + +def split(line): + """The words in front of the last word of line, as a shell splits them, + and the last word, which is empty behind a space.""" + words = shlex.split(line) + if line.endswith(" "): + return words, "" + return words[:-1], words[-1] + + +def matches(line, completed): + """The matches of the last word of line among the words completed: + without the comma zsh puts behind a feature, without the slash behind a + directory, without --features= in front of a list, and without the = + behind --features.""" + _, word = split(line) + found = set() + for match in completed: + match = match.rstrip(",/") + if word.startswith("--features="): + match = match.removeprefix("--features=") + else: + match = match.removesuffix("=") + found.add(match) + return found + + +class Terminal: + """bash or zsh in a terminal of its own.""" + + # The keys the setup below binds: put all the matches into the line, + # write the line to the file $COMPLETED, and remove the line. + INSERT_ALL = b"\x18a" + WRITE_LINE = b"\x18p" + KILL_LINE = b"\x15" + + # The options of each shell, and its setup. The completion writes its + # standard error to the terminal $ERRORS. + SETUP = { + "bash": ( + ["--norc", "--noprofile", "-i"], + "PS1=\n" + "bind 'set enable-bracketed-paste off'\n" + "bind 'set bell-style none'\n" + 'source "$COMPLETIONS/fsmanifest.bash"\n' + '_fsmanifest_test() { _fsmanifest "$@" 2> "$ERRORS"; }\n' + "complete -F _fsmanifest_test fsmanifest\n" + "bind '\"\\C-xa\": insert-completions'\n" + "bind -x '\"\\C-xp\": printf \"%s\\n\" \"$READLINE_LINE\" >> \"$COMPLETED\"'\n", + ), + "zsh": ( + ["-f", "-i"], + "PS1=\n" + "unsetopt beep\n" + "bindkey -e\n" + "fpath=($COMPLETIONS $fpath)\n" + "autoload -Uz compinit && compinit -u -D\n" + '_fsmanifest_test() { _fsmanifest "$@" 2> $ERRORS }\n' + "compdef _fsmanifest_test fsmanifest\n" + "zle -C all-matches complete-word _generic\n" + "zstyle ':completion:all-matches::::' completer _all_matches _complete\n" + "zstyle ':completion:all-matches:*' insert true\n" + "bindkey '^Xa' all-matches\n" + "write-line() { print -r -- $BUFFER >> $COMPLETED }\n" + "zle -N write-line\n" + "bindkey '^Xp' write-line\n", + ), + } + + def __init__(self, shell, program, env, work): + options, setup = Terminal.SETUP[shell] + self.lines = work.parent / "lines" + self.lines.touch() + self.written = 0 + # The terminal of the standard error of the completion. Its other + # end stays open here, so that what was written to it stays there + # to be read. + self.errors, self.errors_terminal = os.openpty() + env = env | { + "COMPLETED": str(self.lines), + "COMPLETIONS": str(COMPLETIONS), + "ERRORS": os.ttyname(self.errors_terminal), + } + self.pid, self.fd = pty.fork() + if self.pid == 0: + try: + os.chdir(work) + os.execve(program, [shell, *options], env) + finally: + os._exit(127) + self.type(setup.encode()) + + def read(self, seconds): + """Reads what the shell writes to the terminal for so many seconds, + or until it exits, so that the shell never waits for the terminal. + Returns whether the shell is still there.""" + end = time.monotonic() + seconds + while (left := end - time.monotonic()) > 0: + ready, _, _ = select.select([self.fd], [], [], left) + try: + if ready and not os.read(self.fd, 65536): + return False + except OSError: + return False + return True + + def type(self, keys): + os.write(self.fd, keys) + self.read(0.1) + + def complete(self, line): + """The words the shell puts in place of the last word of line, and + what the completion wrote to its standard error.""" + self.type(line.encode() + Terminal.INSERT_ALL + Terminal.WRITE_LINE) + end = time.monotonic() + TIMEOUT + while len(written := self.lines.read_text().splitlines()) == self.written: + if time.monotonic() > end: + raise TimeoutError(f"the shell wrote no line for {line!r}") + self.read(0.05) + self.written = len(written) + self.type(Terminal.KILL_LINE) + errors = b"" + while select.select([self.errors], [], [], 0)[0]: + errors += os.read(self.errors, 65536) + # A line that is the same has no matches. + if written[-1] == line: + return [], errors.decode(errors="replace") + front, _ = split(line) + return shlex.split(written[-1])[len(front) :], errors.decode(errors="replace") + + def close(self): + os.write(self.fd, b"exit\n") + if self.read(TIMEOUT): + os.kill(self.pid, signal.SIGKILL) + os.close(self.fd) + os.waitpid(self.pid, 0) + os.close(self.errors) + os.close(self.errors_terminal) + + +class Fish: + """fish, which lists the matches of a command line with complete -C.""" + + def __init__(self, env, work): + self.env = env + self.work = work + + def complete(self, line): + """The matches of the last word of line, and what fish wrote to its + standard error.""" + script = f'source "{COMPLETIONS}/fsmanifest.fish"; complete -C "$argv[1]"' + listed = subprocess.run( + ["fish", "--no-config", "-c", script, line], + env=self.env, + cwd=self.work, + capture_output=True, + text=True, + timeout=TIMEOUT, + check=True, + ) + return [match.split("\t")[0] for match in listed.stdout.splitlines()], listed.stderr + + def close(self): + pass + + +def main(): + shell, fsmanifest = sys.argv[1:] + fsmanifest = Path(fsmanifest).resolve() + failed = 0 + with tempfile.TemporaryDirectory() as home: + home = Path(home) + work = home / "work" + for directory in ("tree", "other", "my dir"): + (work / directory).mkdir(parents=True) + (work / "tree.manifest").touch() + stub = home / "stub/fsmanifest" + stub.parent.mkdir() + stub.write_text(STUB) + stub.chmod(0o755) + missing = home / "missing/fsmanifest" + # The shells run nothing of the user's, and find the fsmanifest + # that is tested first. + env = { + "PATH": f"{fsmanifest.parent}:/usr/bin:/bin", + "HOME": str(home), + "TERM": "dumb", + "LC_ALL": "C.UTF-8", + } + program = shutil.which(shell, path=env["PATH"]) + if program is None: + sys.exit(f"{shell} is missing") + if shell == "fish": + completion = Fish(env, work) + else: + completion = Terminal(shell, program, env, work) + try: + for line, expected in tests(feature_names(fsmanifest), stub, missing): + before = set(work.iterdir()) + completed, errors = completion.complete(line) + found = matches(line, completed) + made = sorted(path.name for path in set(work.iterdir()) - before) + if found == expected and not errors and not made: + print(f"ok {shell}: {line!r}") + continue + failed += 1 + print(f"FAIL {shell}: {line!r}") + if found != expected: + print(f" missing: {sorted(expected - found)}") + print(f" not expected: {sorted(found - expected)}") + if errors: + print(f" standard error: {errors!r}") + if made: + print(f" made: {made}") + finally: + completion.close() + sys.exit(1 if failed else 0) + + +if __name__ == "__main__": + main()