Skip to content

Add a uapi16 crate and stream manifests through it - #19

Merged
brauner merged 19 commits into
ebusyfixfrom
manifest
Nov 21, 2026
Merged

brauner merged 19 commits into
ebusyfixfrom
manifest

Conversation

@brauner

@brauner brauner commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

This moves the UAPI.16 manifest handling into a crate of its own and
makes ufat read manifests as a stream.

My main requirement is that a manifest can be gigabytes long and come
through a pipe. Think of a manifest that describes the dataset for a
large model. Currently we read the whole manifest into memory, up to
256 MiB, and build a Manifest that holds every object and a map of every
folded name before anything is written. That doesn't scale, and a pipe
can only be read once anyway.

So nothing holds a whole manifest anymore. The reader keeps the current
record, at most 4 MiB like systemd's reader, and the name of the object
before it. ufat writes what a record describes as soon as it comes. The
planner keeps the directories that are still open instead of every name,
so its memory grows with the depth of the tree and not with the number
of objects. A plan of a million files from a manifest peaks at 3.0 to
3.5 MiB, and so does a plan of a quarter of them.

json gets a pull parser and writers for objects and arrays, so that a
record is read and written without building a Value tree. parse() sits
on top of the pull parser now. A key that comes twice is refused right
behind the key, before anybody reads its value. A caller can also have
the parser refuse noncharacters and NUL in strings, which UAPI.16
forbids.

The uapi16 crate knows nothing about FAT. It compares names exactly and
has no limits but the ones of the specification, so xfs, ext4 and others
can use it too, and I'd like to publish it on its own at some point. It
implements the merged specification (cf. 1): the string rules, names,
tree order, code point order, features, the root fields that name a
file system, the DOS attributes and inode flags and httpHeaders. Where
systemd's reader and the specification disagree, the crate follows the
specification.

  • The reader and the writer do no I/O of their own. A Decoder is fed the
    bytes of a manifest and hands out its objects, and an Encoder appends
    the records of a manifest to a string. Reader and Writer are small
    drivers over them for io::Read and io::Write. So an async front end
    can use the same code later.
  • The reader checks every object while it reads it: its fields against
    the features the manifest lists, its place in the tree, and the order
    the manifest declares. It fills in what the features imply.
    src/uapi16/refused.jsonl has 358 manifests it has to refuse.
  • The writer runs the reader's checks on what it writes, and leaves out
    defaults and what a reader filled in, as the specification asks. So
    what a reader returns can be written back with the root file object
    it read. A record close to 4 MiB can grow past the limit on the way,
    since a UUID goes out with its hyphens and the value of an extended
    attribute as text where it can, and is refused then.
  • The content sources get at the data of a file, in the files next to
    the manifest or in one stream with the contents of all files back to
    back, and check its size and hash while it is copied. A file that
    holds the data of many file objects is read whole once at most, not
    once for every part.

ufat moves over to the crate. assemble, populate and the plan take its
reader and its content sources, and the manifests ufat writes go through
its writer. They list their features and declare "order": "codepoint"
now. ufat manifest prints its manifest while it walks the tree instead
of holding all of it first.

The manifest of a volume is written from a walk by cluster now. The
walk marks every cluster of every directory it lists and of every file
it hashes, and fails with Corrupt when it reaches a cluster it marked
before. So a damaged or crafted image can't make it list a directory or
hash a file twice, and the walk takes time in proportion to the size of
the volume. Currently we only remember the first cluster of every
directory, and that misses chains that run together further down and
files that share a chain.

Streaming made a few policy changes necessary or obvious:

  • ufat takes one SOURCE tree, like the mkfs tools. Merging trees is up
    to the caller.
  • Every manifest we read has to declare "order": "codepoint" (cf. 2)
    and is checked to be in that order while it is read. That catches
    every repeated name and every object that comes before its directory.
    systemd-manifest make sorts its output that way and declares it since
    systemd commit 330fab5e90 (cf. 3). systemd-manifest isn't in a
    systemd release yet, so this only refuses manifests from a build of
    systemd main before that commit.
  • Sizing to fit is opt-in now, --minimize, like repart's Minimize=.
    Without it a file system takes the size given or the whole image, like
    mkfs.fat, so an empty image needs --size. Content that doesn't fit
    fails while it is written. --minimize with a SOURCE reads the manifest
    twice, to plan the file system and to fill it, so it wants the
    manifest in a regular file. Everything else reads it once and takes it
    through a pipe on standard input. --fit and --manifest without a
    SOURCE take the size given as well, and what they describe has to fit
    it.
  • assemble and populate refuse existing files and names FAT doesn't tell
    apart, such as README and readme, unless --replace is given. A
    directory that is there already takes the entries either way. A plan
    doesn't compare names, so such names pass it and only the write
    refuses them.
  • assemble --create makes the image with O_TMPFILE and gives it its name
    only once everything succeeded, its hash included. So a failed
    assemble --create leaves nothing of it, and a file that took the name
    in the meantime stays as it is. On a file system that can't make a
    file without a name the image has a temporary name until then, which
    a kill or a crash leaves behind. The files of --write-manifest and
    --write-hash get their names after the image. There are exceptions.
    On a file system that can neither rename a file without replacing
    another one nor make hard links, such as vboxsf, the image gets its
    name right away. A failure removes it again, but a kill leaves it. An
    image another process locked first is left to that process, under its
    temporary name, or on vboxsf under its name. And an image that has its
    name keeps it when a file next to it can't get its own or its
    directory can't be synced.
  • A populate that fails partway leaves the file system marked as not
    cleanly unmounted, as an assemble into an existing image does. A
    populate that fails before it writes anything leaves the file system
    as it was.

ufat also applies more of what a manifest records:

  • The read-only, hidden, system and archive attributes, to directories
    as well. The manifest of a volume always records read-only, and the
    other three when a ManifestSink asks for them. --write-manifest can't
    ask yet.
  • The serial number in fatSerial, or the one fsUUID gives, and the label
    in fsLabel. Without a serial number from the manifest or from
    --identifier, the serial number is the first eight hex digits
    sha256sum prints for the manifest. So it doesn't matter whether the
    manifest came from a file or through a pipe. --identifier and
    --label have to agree with the manifest, and populate checks that the
    volume is the one the manifest names. The label is the one blkid
    shows, the name of the label entry in the root directory, and ufat no
    longer falls back to the copy in the boot sector. A manifest whose
    label ends with a space, is blank or is NO NAME is refused, since FAT
    would report another label. --label still takes those, as
    mkfs.fat -n does. The manifest of a volume names it in turn, with
    fatSerial and fsLabel.

Note that this changes org.uapi-group.FileSystem incompatibly. That's
only fine because the interface isn't released yet. What changes for a
client:

  • ManifestSink takes UAPI.16's features in features instead of
    systemd-manifest's field names in fields.
  • A manifest has to declare "order": "codepoint". The manifest and the
    content stream are read in lockstep, so a client that passes both as
    pipes has to write to both at the same time.
  • SourceMismatch loses reason size and its sizes. A file that is too
    short is found while it is copied, as ContentMismatch.
  • Assemble's reply loses exact, SizeToFit's values are renamed to guess
    and best, and without minimize an omitted size no longer means sized
    to fit.
  • replace is false by default.
  • An integer parameter of -0 is refused now. The service reads its
    messages with the json parser, which takes -0 for a float.
  • Enums gain values, such as the new problems of InvalidManifest,
    sourceChanged in ContentProblem and reserved in LabelProblem, and
    there's a new error, FileSystemMismatch.

bench/compare.sh with CI's defaults, nine alternating pairs on trees of
10000 files and an ESP with four UKIs of 2M, gives this change of the
series against main, so a minus is less work or less time than on main:

                    instructions  system calls     time   on main
plan/wide-manifest        -65.1%        -13.2%   9.6 ms   25.3 ms
assemble/wide             -19.5%        -18.6%   100 ms    124 ms
manifest/wide              -9.8%         +0.3%  41.6 ms   45.9 ms
assemble/esp               -8.8%        -15.7%   4.0 ms    4.1 ms

manifest/wide makes a statx more and a read less per file, and 193
writes instead of one since it streams now. assemble/esp-stream makes 11
more system calls, 1.7%, among them the linkat, the extra fsync and the
flock of creating the image with O_TMPFILE. Everything else stays within
2%, every workload reads and writes the same bytes, and compare.py flags
nothing in three runs. The times are the medians of this series and of
main in the first run, and the third gives the same within 0.6 ms.

Not in here:

  • Verifying signatures.
  • Contents behind a URL or in an encoding.

After this:

  • The rework of the directory index and cache, as a series of its own
    on top of this one.
  • serde_json in place of our json crate, everywhere, with our own checks
    for duplicate keys and the string rules on top. That comes before
    uapi16 is published, and it has to pass the refused manifests and the
    round trips of this series.
  • A restructuring of the command line and the Varlink service. Both
    implement every operation on their own today. They'll share one
    request type per operation instead.

@brauner
brauner changed the base branch from main to layout November 13, 2026 19:45
@brauner
brauner added this pull request to stack #24 November 13, 2026 19:45
Base automatically changed from layout to main November 13, 2026 20:21
Comment thread src/json/lib.rs Resolved
Comment thread src/json/lib.rs Resolved
Comment thread src/json/lib.rs Resolved
Comment thread src/uapi16/object.rs Resolved
Comment thread src/uapi16/lib.rs Resolved
@brauner brauner changed the title Move the UAPI.16 manifest handling into a crate of its own Add a uapi16 crate and stream manifests through it Nov 18, 2026
Comment thread src/fat/manifest/tests.rs Resolved
Comment thread docs/org.uapi-group.FileSystem.varlink Resolved
@brauner
brauner force-pushed the manifest branch 2 times, most recently from 259ea14 to 844ffe0 Compare November 18, 2026 22:47
Comment thread src/json/lib.rs Resolved
Comment thread src/json/lib.rs Resolved
Comment thread src/json/lib.rs Resolved
Comment thread src/json/lib.rs Resolved
Comment thread src/json/lib.rs Resolved
Comment thread src/json/lib.rs Resolved
Comment thread src/uapi16/name.rs Resolved
Comment thread src/uapi16/name.rs Resolved
Comment thread src/uapi16/digest.rs Resolved
Comment thread src/uapi16/hex.rs Resolved
Comment thread src/uapi16/features.rs Resolved
Comment thread src/uapi16/object.rs Resolved

@brauner brauner left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Naming in the reader: types and methods should say what they are and read like idiomatic Rust.

Comment thread src/uapi16/reader.rs Resolved
Comment thread src/uapi16/reader.rs Resolved
Comment thread src/uapi16/reader.rs Resolved
Comment thread src/uapi16/reader.rs Resolved
Comment thread src/uapi16/decode.rs Resolved
Comment thread src/uapi16/decode.rs Resolved
Comment thread src/uapi16/sequence.rs Resolved
Comment thread src/uapi16/base64.rs Resolved
Comment thread src/uapi16/decode.rs Resolved
Comment thread src/uapi16/error.rs Resolved
Comment thread src/uapi16/decode.rs Resolved

@brauner brauner left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The writer.

Comment thread src/uapi16/features.rs Resolved
Comment thread src/uapi16/decode.rs Resolved
Comment thread src/uapi16/writer.rs Resolved
Comment thread src/uapi16/writer.rs Resolved
Comment thread src/uapi16/writer.rs Resolved
Comment thread src/uapi16/writer.rs Resolved
Comment thread src/uapi16/writer.rs Resolved
Comment thread src/uapi16/writer.rs Resolved
Comment thread src/uapi16/writer.rs Resolved
Comment thread src/uapi16/lib.rs Resolved

@brauner brauner left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The sources of file contents.

Comment thread src/uapi16/content.rs Resolved
Comment thread src/uapi16/content.rs Resolved
Comment thread src/uapi16/content.rs Resolved
Comment thread src/uapi16/content.rs Resolved
Comment thread src/uapi16/content.rs Resolved
Comment thread src/uapi16/content.rs Resolved
Comment thread src/uapi16/content.rs Resolved
Comment thread src/uapi16/content.rs Resolved
Comment thread src/uapi16/error.rs Resolved
Comment thread src/uapi16/content.rs Resolved

@brauner brauner left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sans-I/O reader and writer, so that async front ends can come later without duplicating them.

Comment thread src/uapi16/reader.rs Resolved
Comment thread src/uapi16/reader.rs Resolved
Comment thread src/uapi16/writer.rs Resolved
Comment thread src/uapi16/content.rs Resolved

@brauner brauner left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One SOURCE tree.

Comment thread src/bin/ufat/cli.rs Resolved
Comment thread src/bin/ufat/cli.rs Resolved
Comment thread src/bin/ufat/cli.rs Resolved
Comment thread src/bin/ufat/cli.rs Resolved

@brauner brauner left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recording and applying the DOS attributes. The commit message says "readOnly sets the read-only attribute as before", which only holds for files: directories get it, and the derivation from mode, for the first time here.

Comment thread src/fat/manifest/assemble.rs Resolved
Comment thread src/fat/manifest/assemble.rs Resolved
Comment thread src/fat/manifest/mod.rs Resolved
Comment thread src/fat/manifest/mod.rs Resolved
Comment thread README.md Resolved
Comment thread src/bin/ufat/cli.rs Resolved

@brauner brauner left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Giving the volume the identity its manifest names.

Comment thread src/bin/ufat/cli.rs Resolved
Comment thread src/fat/manifest/identity.rs Resolved
Comment thread src/fat/manifest/volume.rs Resolved
Comment thread src/fat/manifest/identity.rs Resolved
Comment thread src/fat/error.rs Resolved
Comment thread src/bin/ufat/util.rs Resolved
Comment thread src/fat/manifest/identity.rs Resolved
Currently parse() is the only way to read JSON. It turns the whole text
into a Value tree: every string is copied and every array and object is
allocated before the caller gets to look at any of it. That's fine for
the Varlink messages we exchange. But a UAPI.16 manifest can be
gigabytes of records and a reader only wants a handful of fields out of
each of them. Building a tree for every record just to throw it away
again is a waste.

Add Parser which reads a text value by value. peek() says what kind of
value comes next and the method named after that kind reads it. An
array is entered with array() and walked with element(). An object is
entered with object() and walked with key(), which returns the key of
the next member. skip() reads over a value of any kind, value() reads
one into a Value, and end() checks that nothing but whitespace is left.
A string without an escape is handed out as a slice of the text, so
nothing is copied for it.

The parser refuses what parse() refuses: bad syntax, nesting deeper
than 128 levels and objects that have a key twice. Every object the
parser is inside of gets a set of its keys. Keys without an escape are
borrowed from the text for that, and checking a key is one lookup no
matter how large the object is. When the parser leaves an object it
empties the set and takes it again for the next object that is inside
of as many objects. So a text needs as many sets as the most objects the
parser is inside of at once, and not one for every object. The set of
the outermost object is kept apart, so a text whose objects aren't
nested needs nothing more.

skip() is the exception. A reader of a manifest has to pass over a
field it doesn't know whatever its value is, so skip() checks the
grammar and nothing else: numbers aren't converted and arrays and
objects can be nested to any depth. It doesn't recurse, and it keeps
the keys of all objects of the value in one set, each with where its
object starts, so a key twice is still refused at any depth. The parser
keeps that set from one skip() to the next and empties it in between.

A key twice is refused right behind the key, by key() and skip() alike,
before its value is read. Currently parse() only notices it behind the
value. A caller that streams would have read, and maybe acted on, the
value of the duplicate by then. The error also has a kind of its own
now, ParseErrorKind::DuplicateKey, so callers can tell it apart from a
syntax error.

Note that emptying a set that has keys takes time in proportion to its
capacity, and an emptied set keeps its capacity. So a set that grew past
the capacity it starts with is shrunk back when it is emptied. Otherwise
every object that takes the set after a large one would pay for the
capacity of the large one. One object with 200000 keys followed by
200000 small ones in the same array takes one to two seconds without
that and 0.04 seconds with it.

A string is searched for its end eight bytes at a time. std has nothing
that looks for any of several bytes, and going byte by byte takes about
four times as long on long strings. Everything else uses std. Numbers
go through str::parse() once the JSON grammar has been checked by hand,
since std's parsers would also take a plus sign, leading zeros, "inf"
and "NaN". \u escapes go through char::to_digit() and
char::decode_utf16().

-0 is read as a float. Currently parse() reads it as the integer 0
since an integer has no negative zero. But then a caller that only takes
unsigned integers, like the reader of a manifest, can't tell it from 0.
The Varlink service reads its messages with parse() as well, so it now
refuses -0 for an integer parameter too.

is_whitespace() is public. JSON's whitespace is space, tab, newline and
carriage return, and that is also what systemd skips. Code that wants
the same shouldn't use u8::is_ascii_whitespace() which takes form feed
as well.

Rebuild parse() on top of the parser so we only have one of them. On
two million texts made by mutating a handful of seeds the old and the
new parse() agree: both return the same value, or both fail with the
same message at the same offset. Only -0 is read as a float now, and a
key twice is reported earlier, right behind the key.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
Currently the only way to write JSON is to build a Value and print it.
That's what the manifest writers in the fat crate do for every record:
put each field into an Object with a String for its key, sort the
Object and format it into a fresh String. That's a lot of allocations
for a single line of text.

Add ObjectWriter and ArrayWriter. They append an object or an array to
a String member by member and close it when they are dropped.
ObjectWriter::key() and ArrayWriter::element() hand out a ValueWriter
which writes the value: null, a boolean, an unsigned integer, a string,
anything that implements Display, or another object or array. The
caller keeps the keys of an object unique and writes them in the order
it wants.

key() and element() don't write anything themselves. The ValueWriter
they hand out carries the key and a reference to the flag of the object
or array that says whether a comma is needed. Every value method writes
the comma, the key and the colon together with the value. So a member
exists exactly when its value was written, the text is always valid
JSON, and this is a correct way to write an optional member:

    let v = object.key("k");
    if let Some(s) = maybe {
        v.string(s);
    }

If key() wrote the key right away, a ValueWriter that is dropped without
a value would leave {"k":} or [1,] behind. #[must_use] doesn't catch
that once the ValueWriter is bound to a variable and only used on one
branch, like above.

Note that the key has to live as long as the ValueWriter. So a
ValueWriter kept in a variable can't take a temporary as its key.

While at it, let the printer of a Value and the writers share the code
that escapes strings. escape() looks for the bytes that need an escape
eight bytes at a time, the same way the parser looks for the end of a
string, and copies everything in between in one go. Value and Object
print themselves in their Display implementations now instead of going
through write_value() and write_object().

Note that floats are printed with Debug now. It writes the shortest
text that reads back as the same float, and always one that reads back
as a float. Currently a whole number is printed with Display and ".0"
appended, and anything else with Display alone. That writes 1e21 as 22
digits and ".0", and 5e-324 as 326 bytes. Debug writes "1e21" and
"5e-324". Both forms read back with the same bits, and nothing outside
of this crate prints floats.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
JSON lets a string hold any Unicode scalar value. Formats built on JSON
often allow less, and UAPI.16 manifests are one of them. The
specification says that strings must not contain noncharacters or NUL,
that this applies to a string after its escapes have been decoded, and
that a consumer has to refuse a manifest with such a string instead of
repairing it.

Add StringRules with NO_NONCHARACTERS and NO_NUL. A parser made with
Parser::with_rules() refuses every string that breaks one of them, keys
included, whether the character is written as it is or as an escape.
The error is reported right behind the string and is of the new kind
ParseErrorKind::StringRule. StringRules::admits() checks a string the
same way, for code that writes JSON and has to know whether a string
can go out as it is.

This has to happen in the parser. A reader passes over the fields it
doesn't know but the rules apply to their strings too, and the parser is
the only place that sees every string.

Most strings are plain ASCII, so let's keep the check cheap for them. A
string without an escape can't hold a NUL since JSON wants every
control character in a string escaped. And every noncharacter starts
with the byte 0xef or a higher one in UTF-8, while no continuation byte
is that high. So only a string with such a byte is walked character by
character. Whether it has one is found with is_ascii() and a fold the
compiler turns into vector instructions.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
A UAPI.16 file manifest describes a tree of files as a sequence of JSON
records: the root of the tree first, then a file object for every file,
then optional signature objects and a trailer. Currently ufat handles
manifests in src/fat/manifest, which is tied to ufat and to FAT and
applies the limits of Linux in places, such as 255 bytes for a
component of a name.

Manifests aren't a FAT thing though. Other file systems want to build
images from them too, and we might want to publish the code as a crate
of its own at some point. So let's add a uapi16 crate that does
manifests and nothing else. It compares names exactly, knows no limits
but the ones of the specification, and reads a manifest record by
record instead of holding all of it. ufat moves over to it later in
this series.

This starts the crate with what everything else builds on, the names of
file objects. A Name is what the specification allows as a name: a
normalized relative path whose components are separated by single
slashes, none of them empty, "." or "..". It has no control characters
and, like every string of a manifest, no noncharacters. It is at most
4095 bytes long and its components aren't limited on their own.
"Uapi16Manifest" and names that start with "Uapi16Manifest." are
reserved for the manifest and what belongs to it. Name::ROOT, the empty
name, stands in for the root file object, which has none.

If a string isn't a name InvalidName says why: it is empty, too long or
reserved, it has a control character or a noncharacter, or one of its
components is empty, "." or "..". So code that reads a manifest can
tell people what is actually wrong with a name.

Names are ordered the way the specification orders the file objects of
a manifest in code point order: component by component, each compared
by its bytes. That's the same as comparing the whole names with "/"
lower than any other byte. So a/x comes before a-b, although "-" is
lower than "/". Ord for Name finds the first byte the two names differ
in and decides there, so a comparison is a single pass over the bytes
they share.

Name::join() adds a component to the name of a directory and only
checks that component, so building the names of a tree on the way down
costs time in proportion to their length.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
A manifest gives the SHA-256 hash of the contents of a file in sha256,
and the hashes of the data a contents object refers to in encodedSha256
and originalSha256.

Add Sha256 for such a hash. It prints as 64 lower case hex digits and
parses from 64 hex digits of either case and nothing else. Note that
systemd passes over whitespace between the digits while we refuse it.
The specification wants 64 hexadecimal digits, and the clarification in
[1] makes refusing anything else explicit.

Sha256Context computes the hash of data that comes in pieces. It
implements io::Write so the contents of a file can be hashed with
io::copy() while they are read, and Finalize::finalize() consumes it
and returns the hash. The hashing itself is done by the sha2 crate,
which the workspace already uses.

The specification leaves room for other hash algorithms, each with
fields of its own next to the SHA-256 ones. The Digest trait is what
such an algorithm would implement: the hash of no data and a context
that computes the hash. The context implements Finalize so that code
written against Digest can get the hash out of it.

[1]: uapi-group/specifications#260

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
Add the types for what a manifest is made of. RootObject is the root
file object, FileObject a file object, Contents a contents object and
Signature a signature object.

The root file object and the file objects don't carry the same fields.
Only the root has fsUUID, fsLabel, fatSerial, gptDiskUuid, order and
features. And the root has no name and is a directory, so it has no
inodeToken and no device numbers, and the specification gives it
neither the gpt fields of a partition nor the DOS attributes.

It has no size, sha256 or contents either. That's our reading of the
specification rather than something it says outright, and systemd's
reader takes them on the root. But where a directory has a sub-manifest
of its own, the fields that refer to the sub-manifest itself, such as
size, contents and sha256, go on the dir object of the outer manifest,
and the root file object of the sub-manifest may repeat the inode
attributes of the directory. So on a root these fields have nothing to
refer to.

A single type with every field would let the root carry everything a
file object can and a file object everything the root can, and the
reader would have to catch both at runtime. So let's give each of them
a type of its own.

What they share is split out. In that same paragraph about sub-manifests
the specification calls mode, uid, gid, userName, groupName, mTimeNSec
and extendedAttributes the inode attributes of the directory.
InodeAttributes holds those, plus readOnly and the Linux inode flags,
which the root may have as well.
validSinceUSec, validUntilUSec and validity aren't inode attributes but
both objects have them too, and on the root they cover the whole
manifest. They go into ValidityWindow. RootObject and FileObject embed
both.

Note that there's no embedding in Rust that would let object.mode work
for a field of the embedded struct. Deref to the inner struct is the
known anti-pattern: it doesn't allow split borrows of object.name and
object.mode, struct literals or patterns with those fields don't work,
and there can only be one target. So access is spelled out as
object.inode.mode and root.inode.mtime_nsec.

The fields get types that only hold what the specification allows:

- InodeType for type.
- Mode for mode, which takes the permission bits, setuid, setgid and
  the sticky bit and nothing else.
- Uuid for fsUUID and the gpt UUIDs. It prints the text form of
  RFC 9562, and parses that form in either case as well as 32 hex
  digits without the hyphens, both optionally with "urn:uuid:" in
  front. The groups of the text form are named after the fields of a
  version 1 UUID instead of being bare numbers.
- DosFlags for the DOS attributes hidden, system and archive, which
  only a file object has, and InodeFlags for the Linux inode flags.
  FlagStates says for every flag of one kind whether an object has it
  set, cleared, or doesn't say.
- GptPartition for the gpt fields that describe a regular file as a
  partition. GptPartition::FLAG_READ_ONLY is the bit of gptFlags that
  readOnly stands for.
- FatSerial for fatSerial, written as 1234-ABCD.
  FileSystemIdentity::volume_serial() takes fatSerial or else derives
  the serial number from the first four bytes of fsUUID, as the
  specification asks.
- Validity for validity, and Validity::as_str() for its value in a
  manifest.

Features is the set of features a manifest records, which the features
field of the root file object lists by the names of the specification.
That includes the features upstream added for readOnly, fsUUID,
fsLabel, fatSerial and each of the gpt fields (cf. [1]). Without the
field a manifest records what the specification says: device, gid,
hardlink, mode, sha256, size, symlink and uid. Only the names of the
specification parse. "hash", which systemd-manifest make takes for
sha256 on its command line, isn't one of them.
RootObject::stated_features() and FileObject::stated_features() say
which features the fields of an object belong to, which is what has to
be checked against the features of its manifest. Order is the value of
the order field, and "codepoint" is the only one the specification
defines.

InodeAttributes::is_read_only() says whether a file gets the read-only
attribute in a file system with DOS attributes, such as FAT: readOnly,
or else derived from mode. The specification allows deriving it from
mode for the DOS attribute only, and only where the manifest doesn't
list the read-only feature. Where it does, an object without readOnly
isn't read-only, and a reader fills that in. The read-only flag of a
GPT partition is readOnly alone.

check_validity() checks validity, validSinceUSec and validUntilUSec
against a point in time: those of a file object, or on the root file
object those of the whole manifest.

FileObject::filled_in and Contents::filled_in mark the sizes and hashes
a reader filled in because they follow from other fields, so that a
writer can leave them out again. Whoever sets such a field takes it
out of filled_in. FileSystemIdentity::is_valid_label() says which
labels a manifest can carry in fsLabel.

Error is the error of the crate. Its kind says what went wrong, and the
error names the number of the record, the file object and the field it
is about wherever that's known. All of it lives behind a single
allocation so a Result stays small. Field names every field of every
object as the manifest spells it, in Field::as_str() and nowhere else.

[1]: uapi-group/specifications@1eb019d

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
Add Decoder and Reader, which read a manifest record by record.

Decoder does the reading but no I/O. It is fed the bytes of the
manifest with feed() as they come and told with end() that the input
ended, and step() says what comes next: Step::Input when it needs more
of the manifest, Step::Root with the root file object, Step::Object with
a file object or a signature object, and Step::End after the trailer.
Reader is a small driver that feeds a Decoder from anything that
implements io::Read with BufReader::fill_buf(), Decoder::feed() and
consume(). Reader::open() reads the root file object and the reader is
then an iterator over the objects that follow, up to the trailer. So an
async front end can drive the same decoder later without a second copy
of the reader.

A manifest can be gigabytes long and come through a pipe, so it is read
exactly once and the decoder keeps nothing but the current record and
the name of the file object before it. Nothing grows with the manifest
and reading takes time in proportion to its size.

The decoder splits the records as it is fed. feed() takes bytes up to
the next record separator, with the same memchr search that
BufRead::skip_until() does. A record may be 4 MiB large, from its
record separator up to the next one, which is how the specification
counts it. So feed() never takes more than what a record of 4 MiB has
behind its separator, plus the separator after it. A record whose
separator doesn't come within that is refused as too large, however the
manifest is fed. The separator isn't kept and the buffer grows the way
a Vec does but never beyond what a record has behind its separator, so
the decoder holds less than 4 MiB of one record, like systemd does. A
record that has a NUL byte or isn't UTF-8 is refused. Records of nothing
but whitespace are skipped, as RFC 7464 suggests, but nothing may follow
the trailer, whitespace included, as the specification asks.

A record ends where the next one starts. So an object comes out once
the separator of the record behind it was fed, and the trailer gives
Step::End only after end(). A step reads one record at most.

An error of the input ends the reader, with one exception: a WouldBlock
from a non-blocking input loses nothing. The record being read is kept
and the next call to next() reads on. Reader::open() fails on it like on
any other error. Reader::get_mut() hands out the input the way
BufReader's does. Decoder::input_error() turns an error of the input
into one about the record being read.

The first record makes a RootObject and every other one a FileObject.
The root can't have a name or a type other than dir, or any of the
fields only the other file objects have: size, sha256, contents,
inodeToken, major, minor, the gpt fields of a partition and the DOS
attributes. Note that systemd's reader takes size, sha256 and contents
on the root and we don't. These fields refer to a sub-manifest, and the
specification puts them on the dir object of the outer manifest, not on
the root file object of the sub-manifest. On a root they have nothing to
refer to.

Each record is read once with the pull parser, which refuses strings
with noncharacters or NUL as the specification asks, and every field
goes straight to where it belongs. Whether a record holds a file object
is only known once its mediaType has been read, and that can be its
last member. So the first error in a field is remembered and only
reported once the record turned out to be valid JSON and a file object.

The rules are those of the specification, and where it leaves something
open those of systemd's reader in src/shared/uapi16-manifest.c: the type
of every field, which fields an inode type permits, how the sizes and
hashes of an object and of its contents objects have to agree, and what
contents objects, extended attributes and signature objects may look
like. A null value counts as no value, also for mediaType and for
extended attributes and HTTP headers. A size the contents objects give
has to agree with every one of them, whichever comes first. A field the
reader doesn't know is passed over whatever its value is, as the
specification asks, at any depth and with numbers of any size.

Where systemd is laxer than the specification we follow the
specification:

- Integers are JSON numbers written as decimal digits without sign,
  fraction or exponent, up to 64 bits, and the access mode follows the
  same rule. systemd also takes integers as decimal strings and an
  access mode as a string of octal digits (cf. [3]). We refuse those
  like any other string. -0 is refused too, the json parser reads it
  as a float.
- Base64 and the hex digits of a signature key take no whitespace
  anywhere, while systemd passes over it in both. The specification
  wants hex digits and the Base64 of RFC 4648, which has nothing but the
  digits and the padding, and the clarification in [1] makes refusing
  whitespace explicit. Base64 takes both alphabets in any mix, as
  systemd's unbase64mem() does.

A uid or gid of 65535 is refused like one of 4294967295. The
specification forbids both again since upstream 7ad6521 (cf. [2]), and
systemd refuses both as well.

The reader also checks where every file object comes. The specification
wants them in tree order: every directory comes before the objects
below it and these follow it immediately. Since every directory is
listed, the directories that can still get entries are the root, the
directories the last object is in, and the last object itself if it is
a directory. So the name of the last object is all we need to keep. The
first byte in which the next name differs from it settles whether the
next object may come, and also catches a name that comes twice in a row
or again right after the entries of the directory it names. A name that
comes again further down could only be found by remembering every name,
and we don't. A manifest that declares "order": "codepoint" is checked
to have every name sort after the one before it though, which finds
every repeated name. A consumer that relies on the order calls
RootObject::require_order() and refuses a manifest that doesn't declare
it, even if its objects happen to be sorted.

The fields of every object are checked against the features the manifest
lists, the ones upstream added for readOnly, fsUUID, fsLabel, fatSerial
and the gpt fields included, and a symbolic link has to carry its target
if the manifest records them. The reader also fills in what the features
say about the fields an object doesn't have: a flag the manifest records
is cleared, an object without readOnly isn't read-only where the
manifest lists read-only, and a file without extended attributes has
none if the manifest records them. The sizes and hashes it fills in from
other fields and a readOnly it fills in are marked in filled_in, and the
checks of an object treat a filled-in readOnly as one that isn't there.
So an object read from a manifest passes the same checks again.

The gpt fields aren't filled in, as every regular file of a manifest
that lists gpt-flags would get a GptPartition otherwise. Instead,
gptFlags is checked against gptFlagNoAuto, gptFlagGrowFileSystem and
readOnly, which give one of its flags each, and a missing field counts
as cleared, gptFlags as 0, where the manifest lists its feature. Only a
regular file has gptFlags. Note that systemd doesn't compare readOnly
with gptFlags at all.

The checks of a single object are kept apart from the filling in so
that a writer can run the same ones on what it writes.
FileObject::check_permitted_fields() checks the fields against the
inode type, and check_consistency() on FileObject, RootObject and
Contents checks the fields that have to agree with each other, such as
readOnly and mode, a size of 0 and the hash, or httpHeaders and url.
The reader fills in what follows from them once they passed.

An error about a name says why the name is invalid, such as "name has
an empty component". The strings of a manifest that error messages
quote go through escape_debug(), so a manifest can't put control
characters on a terminal.

Signature objects are read but not verified. That takes an OpenPGP or
an X.509 implementation. Reader::signed_len() says how much of the
manifest they sign so that a caller can verify them.

Error grows Problem, what is wrong with a manifest. A record the parser
refuses is NotJson, DuplicateKey or InvalidString, after the kind of
error the parser reports. Problem::as_str() gives every problem a stable
name, the one ufat's Varlink interface uses for it, so a caller can pass
it on, and Problem::ALL lists them all, so a caller can check that it
knows every name. Problem and ErrorKind are non_exhaustive so that both
can grow.

src/uapi16/refused.jsonl holds 358 manifests the reader has to refuse,
each with one problem or with two of them to show which one is reported.
They cover the decoder cases of ufat's own manifest tests in
src/fat/manifest/tests.rs as well. For each of them the test checks the
problem, the record, the name and the field the error is about, and its
message.

[1]: uapi-group/specifications#260
[2]: uapi-group/specifications@7ad6521
[3]: systemd/systemd#44897

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
Add a writer for manifests. Writer::begin() writes the root file
object, file() a file object, signature() a signature object and
finish() the trailer object. A writer that is dropped before finish()
leaves a manifest without a trailer, which a reader refuses as
incomplete.

The writer is split up the same way the reader is. An Encoder puts the
manifest together record by record and does no I/O: its begin(),
file(), signature() and finish() append the record of their object to
a string, and whoever calls them sends the records on, one at a time or
many at once. Writer<W: Write> drives an Encoder and writes every
record out in a single write. So a front end for an async runtime can
drive the same encoder later, the way it can drive the reader's
Decoder, without a copy of the checks of its own.

Every object is one record: the record separator, the object with its
keys sorted and without whitespace, and a newline, which is what
systemd-manifest writes. The record is put together with the writers
of the json crate in a buffer that the writer keeps from one record to
the next. Once a record larger than 64 KiB went out, the buffer gives
back what it took beyond that. The specification limits a record to
4 MiB, its record separator included, and a reader takes no more than
256 contents objects for a file object, so the encoder refuses both. A
record that turns out to be too large is taken back before anything of
it is written.

The writer checks every object against the root file object the same
way the reader does, with the same code: an object has no field of a
feature the manifest doesn't list, readOnly and fatSerial among them,
it comes right after the object of its directory, and it keeps to the
order the manifest declares. The value of every field has to be one
the reader takes. Strings keep to the rules the reader applies, and
names, labels, URLs, encodings, HTTP headers, user and group IDs and
the names of extended attributes are checked by the same functions.

The writer also runs the checks the reader does on an object as a
whole, which the reader keeps apart from what it fills in: the fields
an inode type permits, readOnly against mode and against bit 60 of
gptFlags, gptFlags against the gptFlag* fields, a size of 0 against the
hash, httpHeaders only next to a url, and a part that has to fit into
the data it is taken from. Otherwise a bug in a caller produces a
manifest that no reader takes, and only the consumer finds out.

An object with more than one fault is refused for the one a reader
reports, so the writer checks in the reader's order: a record that is
too large, a string the JSON parser refuses or a key it sees twice in
an object, such as two header fields of the same name, a file object
after a signature object, the values of the fields in the order of
their keys, a missing name, a field the inode type doesn't permit,
fields that contradict each other, a field of a feature the manifest
doesn't list, a symbolic link without its target, gptFlags against the
fields of its flags, and where the object comes. That is why the record
is put together before the object is checked.

The specification wants the encoding in lower case. A reader lowers the
case of what it reads first, as systemd does, but the writer writes what
it is given. So the check the two share refuses any other encoding.
That's the one fault the writer refuses where a reader of the same
record finds none.

An object the writer refuses is not written, and the writer goes on as
if it hadn't been given it. Every error carries the number of the
record it is about, record 0 for those of begin(). begin() takes a
RootObject, so the root file object can't have a name or be anything
but a directory. Writer::get_ref() hands out what the manifest is
written to, so that a caller can hash what was written before the first
signature object for its data.

The specification asks generators not to write fields that are set to
their default, so that file objects describing the same file compare as
equivalent. So the writer leaves out the type of regular files, a
validSinceUSec of 0, a validity of good and an offset of 0. The
specification also recommends leaving out the hash of no data next to a
size of 0, and the writer does that too. So an empty file goes out with
a size of 0 and no hash, and a reader fills the hash in again. For data
without an encoding the specification says that the encoded size and
hash shouldn't be there at all. The writer leaves them out next to the
original ones, which say the same, and writes one that is the only
statement of the size or the hash. Written as the original size or hash
it would come back as another field, and left out it would be lost.

The writer also leaves out what the features of the manifest imply
without the field: a flag that is cleared, a readOnly of false, a
gptFlags of 0 and extended attributes when there are none. An object
only has these fields where the manifest records their features. The
features field itself is only written if it isn't the default. A field
that FilledIn marks as filled in by a reader isn't written at all,
whichever field it is.

So what a reader returns can be written back with the root file object
it read. The value of an extended attribute goes out as text if it is a
string a manifest can hold and as Base64 otherwise, as the specification
asks. Note that a record close to 4 MiB can grow past the limit on the
way back. The writer writes some values in another form than a manifest
may carry them in, a UUID with its hyphens and the value of an extended
attribute as text where it can, and refuses such a record.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
A manifest says where the contents of a file are: in the manifest
itself as a literal, in a file next to the manifest, or at a URL,
possibly in an encoding such as gzip. Add what it takes to get at them
when a manifest is applied.

FileObject::data() finds the data of a regular file, the target of a
symbolic link or the manifest of its own that a directory refers to. A
literal is taken first, as the specification suggests, since the
manifest carries the data already. Otherwise it's the file the first
contents object without an encoding names. The specification implies a
contents object only for a regular file. So a regular file without
contents objects has its data in the file of its own name, and any
other object without them has no data at all. Data that would have to
be decoded or fetched from a URL isn't taken. An object that has its
data only that way fails with UnsupportedContent::UrlOrEncoding, and
one without data with UnsupportedContent::Absent.

A ContentSource hands out the data that isn't in the manifest:

- DirectorySource takes it from the files next to the manifest. A
  manifest can't be trusted to stay inside of that directory and a
  symbolic link can lead out of it, so resolving a name below the
  directory and nowhere else is up to the caller, through the Directory
  trait.
- StreamSource takes it from one stream that has the data of all files
  back to back, in the order of the manifest. Its end() is called after
  the last file object, also when none of them had data on the stream,
  and fails if the stream goes on. The stream holds the data of a file
  object and nothing else of its file. So the object needs a size, and
  a missing one is UnsupportedContent::NoSize. The size is optional in
  the specification, so that's a limit of the stream and not a
  malformed manifest.

A consumer hands every file object whose data it doesn't take to
ContentSource::skip(). StreamSource reads past the data there with the
checks of a copy, and DirectorySource does nothing. So only the source
knows what the stream carries, and a consumer that leaves an object out
doesn't have to know whether its data is on the stream.

FileObject::copy_contents() copies the data of a file to a sink and
checks its size and its hash on the way with a ContentCheck. A
ContentCheck counts and hashes what it is given in update(), refuses
anything beyond the size of the object, and holds the data against the
size and the hash in finish(). It checks what the file object says of
its data, which the specification asks of every file. What the contents
objects say of the files the data is in is for the sources to check. A
ContentCheck isn't tied to Write. So a caller that copies the data some
other way, in an async runtime for example, can check it with the same
code. The copies themselves stay blocking.

The data of a file object is the part of its file that starts at the
offset and is as long as the object says, whatever else the file holds.
That's how the specification has it. A file that is too short for the
data fails, and so does one of another size than the originalSize the
manifest gives.

A file can hold the data of several file objects, each of them a part
of it, and the manifest can give the size and the hash of the whole
file with every one of them. Currently src/fat/manifest/assemble.rs
reads such a file from its very beginning for each of its parts, and
all of it whenever the hash of the whole file is given. With many parts
that's quadratic. Instead, seek to the part.

A part whose file object has a sha256 of its own is checked against
that while it is copied, and the specification lets a consumer that
only takes a part of a file skip the checks of the whole file. So
originalSha256 is checked for a part only when its object has no
sha256, and for all of a file only when it isn't the object's own
sha256. No byte is hashed twice for an object whose sha256 is the hash
of its whole file. In a stream a part without a sha256 is taken
unchecked, which the specification allows as well: the stream doesn't
have the rest of the file.

For a part without a sha256 a DirectorySource reads the file once and
keeps the hash of every piece of it. Every piece a later part is copied
from is then checked against the hash kept for it. A piece is 1 MiB,
and larger in a file of more than about 32 GiB, so that the hashes of a
file of any size fit into the 1 MiB that the hashes a source keeps take
at most. So in the common case, one large file that holds the data of
many file objects, every part is checked and the file is read once. A
file of about 32 GiB or more takes all of the 1 MiB, and the hashes of
a split file are kept while they fit into what is left of it. The
parts of a file whose hashes don't fit aren't checked against its
originalSha256, which step 8 of acquiring a file in the specification
allows. Parts with a sha256 of their own are always checked against
that, as step 16 asks. The source doesn't drop the hashes of one file
for those of another. If it did, parts of two such files that take
turns would each read their file whole again, which is the parts times
size this is meant to get rid of. So while copies succeed, a file of
more than one piece is read whole once at most for its parts, and the
memory a source takes doesn't grow with the manifest. For 1024 parts of
64 KiB of a 33 GiB file, none of them with a sha256, a source reads
34.1 GiB. Reading all of the file for every part came to 33 TiB. Of a
66 GiB file it reads 68.2 GiB.

A file is read up to the size it had when it was opened. One that ends
before that while it is read, or that is read whole for its hash and
has a byte more, changed in the meantime, and that's
ContentProblem::SourceChanged. That also keeps a file that is cut short
and written again while it is read from adding pieces beyond those the
source made room for.

Error grows the kinds for all of this: SourceProblem for a file that
isn't there the way the manifest says or a file or a stream that can't
be read, ContentProblem for data that doesn't match the manifest, and
UnsupportedContent for what this crate can't take. A size mismatch and
a stream that ended early also carry the size that was found, where
it's known, and the one that was expected. A read that fails names the
object and the file or the stream, and an error of the sink comes back
as it was. Data, SourceProblem, ContentProblem and UnsupportedContent
are non_exhaustive as they gain variants once URLs or encodings are
supported.

DirectorySource and StreamSource print the size of their buffers in
Debug, the way BufReader does, but not the buffers.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
assemble, populate and assemble --plan take any number of SOURCE trees
and merge them, and --fit can be given more than once. No mkfs tool
does that. mke2fs -d, mkfs.xfs -p and mkfs.btrfs --rootdir take one
directory. mksquashfs takes several sources, but each of them becomes
an entry of the root instead of being merged into it. systemd-repart
takes several CopyFiles= and merges them itself, and the Varlink
interface takes one sourceFileDescriptor.

So let's take one tree as well. A second SOURCE or a second --fit fails
with EINVAL, and merging trees is up to the caller. That is checked
before anything is opened. So are the values of --times and
--unsupported, right after the command line is parsed. A bad --times
used to fail only when the content was written, after assemble had
formatted the image or populate had made the directory --path names.
Bad values are now refused whatever the command does, so also with
--plan, --fit or --manifest without a SOURCE, which didn't look at them
before.

While at it, let's make the resolved SOURCE a proper type. Sources held
a list of trees and an optional manifest, and each function that used
it went through both. Now Source is nothing, a tree, or a manifest with
the place its file contents come from. Source::open() resolves it, and
checking, planning and filling it are its methods check(), add_to() and
fill(). Data becomes ContentOrigin, since uapi16::Data is something
else.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
Currently we write manifests by hand. The generator of a host tree and
the writer of a volume both build a json::Object per entry, sort its
keys and frame it with write_record(). Let's port both of them to the
uapi16 crate. They fill in a FileObject per entry and hand it to a
uapi16::Writer, which frames the records and runs the checks of the
reader on every object it writes.

While at it, turn the free functions into methods. generate() becomes
HostTree::write_manifest() and volume::write() becomes
Volume::write_manifest(). Both take any Write, and both return a
WriteReport. What a caller asks a manifest to record are the features
of UAPI.16 now, uapi16::Features, instead of our own Fields.

The merged specification gives the root object of a manifest two more
fields (cf. [1]). features lists what the manifest records whenever
that isn't the default set, and order declares the order its file
objects are in. Both writers sort their objects in code point order
already, so they say so with "order": "codepoint". The generator
records size, sha256 and mtime and lists them. The manifest of a volume
records what FAT has of what it is asked for: sizes, hashes and times.
Where FAT has none of what a feature describes, as for symbolic links,
device nodes, hard links and extended attributes, the manifest lists
the feature and so says that there is none.

The read-only attribute is different. Every entry of a volume has it
set or cleared, and the specification has a read-only feature now
(cf. [2]): where a manifest lists it, an object without readOnly isn't
read-only. So the manifest of a volume always records the attribute,
whatever the caller asks for. It lists read-only and writes readOnly
where the attribute is set. The writer refuses readOnly without the
feature anyway.

The writer leaves out what the specification recommends leaving out.
So an empty file goes out with a size of 0 and without the hash of no
data, and a reader fills the hash in again.

The Varlink ManifestSink follows. It took systemd-manifest's field names
in fields. Now it takes the names of the features of UAPI.16 in
features, with "_" in place of "-", the way systemd writes the values of
enumerations. So hash is sha256 and userXattr is user_xattr.

Names are uapi16::Name now, which follows the spec: a component can be
longer than 255 bytes, and a name can't hold a noncharacter. An entry
of a volume whose name a manifest can't carry is left out and counted
in omitted as before. Note that the generator used to list a directory
whose name no manifest can carry, which no reader takes, ours included.
It leaves such a directory out now, with everything below it, as
systemd-manifest does.

The generator also left out a file whose name no manifest can carry
without a word, and a name that isn't UTF-8 or a path longer than a
volume takes failed the walk. Now it leaves all of them out and counts
the regular files and directories among them the way the writer of a
volume does, a directory with everything below it as one, and ufat
manifest says how many entries aren't in the manifest, as
--write-manifest does. walk_tree() leaves out and counts what it can't
name when the generator asks it to. The populator and the planner still
fail on it, since they couldn't store it.

The long names of a volume are decoded with String::from_utf16_lossy(),
so a long name with an unpaired surrogate reads with U+FFFD in its
place, and two names that differ only there read as one. Reading a
directory now decodes a long name with String::from_utf16(), which
refuses exactly such a name, and says how the name came out in a new
NameDecoding, Exact or Lossy, which Metadata carries as well. The writer
of a volume leaves the lossy names out and counts them before it
compares names. The NameDecoding of an entry goes next to the count of
its long name slots, which becomes a byte since a set has at most 20
slots, so that the entries the directory cache keeps don't grow.

Currently ufat manifest keeps the whole manifest in memory before it
prints anything, 150 to 250 bytes per file. The point was to print
nothing of a tree that can't be listed to its end. But the trailer
covers that already: a manifest without one is incomplete and readers
refuse it, and ufat exits with an error. So let's stream the manifest
to standard output while the tree is walked.

The generator records the size of what it hashed instead of the size
that stat() reported before. So the two agree for a file that changes
while it is read, and the writer never sees an empty file with the
hash of some data, which it would refuse. It reads a file no further
than the size the walk found, so a file that keeps growing doesn't keep
it busy. Afterwards it compares the size, the modification time and the
change time with what the walk found, the way tar does. A file that
changed while it was read is counted in a new field of WriteReport,
changed, and ufat manifest says how many there were. The exit status
stays 0, since 1 says that the manifest has no trailer.

Currently, the writer of a volume walks the directory tree by path. It
lists a directory with read_dir(path) and reads a file with
begin_read(path), and both look up every component of the path again.
On a damaged volume that lookup can find another entry than the one the
walk is at. Lookups fold names, so of "AAAA" and "aaaa" in one directory
it finds the same one twice, and the manifest lists what "aaaa" holds
under "AAAA" as well. So let's walk the tree by cluster instead. A
directory is listed from the first cluster its entry names, with a
crate-private read_dir_at() that does what read_dir() does once it has
found the cluster. A file is read from the first cluster and the size of
its entry with begin_read_at(). Note that begin_read() walks the chain
of a file once before reading to see that it's long enough.
begin_read_at() doesn't, and the read that runs past the end of a short
chain fails with Corrupt instead. The read of the last cluster of a file
looks at the FAT entry of that cluster, which has to end the chain or go
on. So a chain that runs into a free, bad or invalid entry right after
the file fails as it did before, and the rest of a longer chain isn't
read.

The writer also keeps the first cluster of every directory it listed in
a HashSet, to refuse a directory tree that is cross-linked or that
loops. That set grows with the number of directories on the volume.
Comparing with the first clusters of the directories that are open
would catch a loop only. A cross-link that doesn't loop does end, but a
chain of directories that each hold two entries pointing at the next one
is listed 2^k times for k levels, and 40 levels take 40 clusters of a
small image. And first clusters aren't enough either, since chains can
run together further down. 200 empty directories whose chains run on
into the chain of a directory of 1000 files list those files 201 times,
and 1000 entries of files of 4 MiB that share one chain make us hash
4 GiB.

So keep one bit for every cluster of the volume instead, set for every
cluster of every directory the walk lists, which Directory::chain()
has, and for every cluster of every file it reads for the hash, one per
read. Where the walk reaches a cluster whose bit is set already it
fails with EUCLEAN and Corrupt. IOW, the walk lists no directory and
reads no file twice, and takes time in proportion to the size of the
volume. The bits take 16 KiB for a typical ESP and 32 MiB at the most
clusters FAT32 has. A directory whose entry points at cluster 0 or past
the last cluster of the volume fails with Corrupt as well, and so does a
file that isn't empty when it is read for the hash, which is when the
manifest records sha256. load_directory() refused a directory whose own
chain loops or is longer than a directory can be with a bare EUCLEAN,
which a Varlink client sees as io.systemd.System. It names the directory
and its first cluster now, so Describe answers Corrupt there too.

A damaged directory can also hold two entries of the same name. The
writer of the crate would refuse the second one as an InvalidManifest
with reason duplicateName, which blames a manifest the caller never
sent. The entries of a directory are sorted right there, so compare
each name with the one before and fail with EUCLEAN and Corrupt, before
the record of the directory goes out. Names that FAT takes for one, like
"AAAA" and "aaaa", are two names to a manifest. Since the walk follows
the cluster of every entry, it lists each of them with what it holds.
Linux writes such directories with some mount options. With
iocharset=utf8, for instance, it compares names byte for byte. fsck
reports them, which is its job, and the manifest describes what is on
the volume.

The systemd-manifest the fixtures were made with doesn't write features
and order. systemd-manifest writes both since 118717cfe2 and
330fab5e90, which aren't in a release yet. So make-fixtures.sh adds
both to the fixtures after systemd-manifest wrote them, and
tests/fixtures.rs keeps comparing our writers with them byte for byte.
The manifest of a volume lists read-only on top of the features
systemd-manifest records, so the comparison adds read-only to the
features of systemd's manifest. Adding features and order changes the
bytes the signature of signed.Uapi16Manifest covers and the signature
doesn't match anymore, which the README of the fixtures says.

tests/fixtures.rs also gets a test that reads every fixture with the
uapi16 crate and writes it back. It lives there and not in the crate,
so that the crate needs no files from outside of it for its tests. Note
that the systemd-manifest the fixtures were made with writes the hash
of no data next to a size of 0. The writer leaves it out, and so does
systemd-manifest since e83f7bce0c, which isn't in a release yet
either. A reader that fills it in again marks it as filled in, so the
empty file of the special case wouldn't read back as the same object.
So make-fixtures.sh also takes that hash out of the file objects of
size 0, as the specification recommends. The empty file of the special
case is the only one, and the byte comparisons don't use that case.

The errors of the crate's writer are turned into ours in
src/fat/manifest/error.rs, with the errno and the detail a Varlink
client sees. Instead of mirroring uapi16::Problem with a list of its
own, ManifestProblem carries the problem itself, and Problem::as_str()
gives the name a client sees. So the names on the wire stay what they
are. noSize isn't a problem of the crate and stays ours. The interface
description gains the problems the crate knows about, and
tests/varlink.rs checks that its ManifestProblem has the names of
Problem::ALL and noSize. verify/lib.rs builds error.rs for Kani without
uapi16, so it stands in for uapi16 with a Problem that has no value.

The reader is still the old one. It reports its problems with the
variants of uapi16::Problem now, under the names it used before.

[1]: uapi-group/specifications#253
[2]: uapi-group/specifications@1eb019d

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
Currently we read a manifest into memory in one go, up to 256 MiB, and
parse it into a fat::manifest::Manifest that holds every object and a
map of every name folded the way FAT folds names. That is checked as a
whole and only then is the volume assembled from it. This doesn't work
for a manifest of a few gigabytes, and a manifest that describes the
dataset of a large model gets there easily. It can also come through a
pipe, which can be read only once.

So let's never hold a whole manifest. The tools open a uapi16::Reader
on the file or the pipe and read the root object up front, so a file
that isn't a manifest is refused before an image is touched.
Volume::assemble() then takes the records from the reader one by one
and writes what each of them describes right away. So populating a file
system from a manifest takes the same memory whatever the size of the
manifest.

fat::manifest::Manifest, fields.rs and read_all() are gone. The content
sources are the ones of the uapi16 crate, and PinnedDirectory tells its
DirectorySource how to open a file below the source directory, pinned
with chase() as before. The crate takes contents only as they are, in
the manifest or in a file next to it. Contents that are only at a URL or
in an encoding fail with ContentNotSupported and what transport now,
with the ways the manifest offers in value, instead of url or encoding.
Nothing produces UnsupportedKind::Url and Encoding anymore, so they go.
The interface keeps url and encoding for implementations that can tell
them apart. What an object is to FAT is EntryKind::try_from(), which now
also refuses a file FAT32 can't hold with EFBIG when its record comes.
What the decoder refuses is tested by uapi16's refused.jsonl and its
reader tests, and fat's tests keep what is about the assembly. A file
object with "mediaType": null is taken now, since the uapi16 reader
takes a field that is null for one that isn't there.

A manifest that is read while it is written has to come in the order
the volume is written in. UAPI.16 asks a manifest that a file system is
made from to declare "order": "codepoint" (cf. [1]), and the reader
checks the file objects against the order that is declared. So we
require the declaration and refuse a manifest without it with
InvalidManifest and reason noOrder, also when its objects are sorted.
With the order checked a name that comes twice is refused, and so is
an object that comes before its directory. We used to create missing
directories on demand. systemd-manifest make sorts its output that way
and declares it since 330fab5e90, which isn't in a release yet. The
manifests of an older systemd-manifest are refused. GetCapabilities
announces the order in manifest.order.

Names that FAT doesn't tell apart, such as README and readme, aren't
the reader's business. The uapi16 crate compares exact names and knows
nothing about FAT, and finding them would take a map of every name of
the manifest. Instead, the volume finds the second one when it is
created. Replacing is the default, so it is taken as the same name: a
file replaces the first one under its own spelling, and a directory
takes the entries of the first one.

There is no check of the source directory before the format anymore.
Each file is looked up when its record comes. Its data is the part of
the file that starts at the offset the manifest gives and is as long as
the manifest says, whatever else the file holds, as UAPI.16 has it. So
a file that grew since the manifest was written is copied as far as the
manifest says. One that is too short for the data, or not of the
originalSize the manifest gives, fails with ContentMismatch and reason
size while it is copied. So SourceProblem::Size and the sizes of
SourceMismatch go. A file that changes while it is read fails with
ContentMismatch and the new reason sourceChanged, without sizes.
Nothing names the source directory up front anymore, so the command
line puts it in front of the errors about the files below it:

    ufat: /srv/esp: EFI/x.efi: failed to open EFI/x.efi: ...

The service names a file the way the manifest does. Its caller passed
the directory and knows which one it is. --unsupported fail fails on an
object of a manifest when its record comes as well, and so does the
plan of it, before anything is written.

When the contents come in a stream, the manifest and the stream are
read in lockstep: a record, then the contents of the file it describes.
We used to read the whole manifest first, so a client could write all
of it to one pipe and the contents to the other after it. Now such a
client deadlocks with the service once the manifest is larger than the
pipe and what the reader reads ahead. varlink.md and the interface say
that both pipes have to be written at the same time, and a test passes a
large manifest that way. ManifestInput::open() takes the passed stream,
so a manifest pipe that is made non-blocking during the call fails with
BadFileDescriptor and reason flags like the other passed pipes. The
error names the parameter of the pipe it came from, and so do the errors
of the vetting of the passed streams. So the service takes the name from
the error and names only the image and a manifest refused for a plan
itself. A stream also has the contents of every object that is left
out, and ContentSource::skip() reads past them, a sub-manifest's
included. With --unsupported fail a directory that refers to a
sub-manifest is refused at its object, before the stream is asked for
anything. Left out without a size it fails with InvalidManifest and
reason noSize, like a file without a size, since the stream can't be
read past it. A stream has the contents of each file and nothing else
of it. So an object whose contents start at an offset fails with
ContentNotSupported and what offset when its record comes, whatever
--unsupported says.

A populate that fails while it writes a tree or a manifest leaves the
file system marked as not cleanly unmounted, as a failed assemble does.
Dropping the volume would mark it clean with half of the content in it.
But a manifest can also be refused at its first object, before anything
was written, and then the file system stays as it was.
Volume::is_writing() tells the two apart. For that the volume has to
begin a write only when something is written. Volume::create_dir(),
create_dir_all() and begin_file() marked the volume first and checked
the name after, and set_times() wrote a time an entry had already.
make_directory() even allocated and wrote the cluster of the new
directory before it looked at the parent. Now placing an entry does
everything that only reads first. It checks that the directory isn't
damaged and that the name is free, makes the short name, and finds free
slots or makes sure that the directory can grow and that the clusters
for that are free, the one of a new directory included. Only then does
it begin the write. The cluster of a new directory and the FAT still go
out before its entry, so a crash in between leaks a cluster as before.
The crash harness now makes directories with and without their parent
growing for them. create_dir_all() walks the path to the first directory
that is missing and checks the names of the directories it creates
before it creates the first one, and set_times() writes only what
changes, after it checked the directories it changes. So a name FAT
can't store or that is too long, a name that is taken, a file named like
a directory, a damaged or full directory, too few free clusters for the
entry and directories that are there with their times write nothing.

Populate over Varlink ran create_dir_all("/") for a manifest with
parents, which marked the volume as well. Like the command line it makes
sure that the destination is a directory only for a tree now. And the
assembly creates a file in the volume when its first data comes. So
nothing is written either when the source refuses the object, such as a
stream that needs a size the object doesn't give, or a file that is
missing below the source directory. A file that runs out of space is
named in the error, the way a tree names it. Only the errors of the
volume are named that way, since the ones about the files of the
manifest name them already.

The rest follows from reading a manifest once:

- The stream is checked to end after the trailer, also when no file
  had its contents on it.
- skipped is a count, and an AssembleObserver hears about every object
  that is left out, so Volume::assemble_with_progress() is
  assemble_with_observer() now. A directory that is left out takes
  everything below it along. ObjectTriage::decide() says what happens to
  each object, for the assembly and the plan alike. An object that isn't
  valid fails the assembly whether it would be left out or not, as
  before.
- The switches of an assembly become AssembleFlags instead of two
  booleans that don't say what they mean at the call site. The default
  stays REPLACE. The plan takes them too.
- fat uses json in its tests only from here on.
- The fuzzers write their large manifests in code point order, and
  bench/run.sh builds the inputs an older ufat wrote again.

While at it, fat::sha256 goes. fat::manifest re-exports the Sha256 of
the uapi16 crate now, and the image hash uses its Sha256Context, so
there is one SHA-256 context and one Sha256. fat::sha512's Sha512 is
Sha512Context to match. And the interface says that its sizes and times
are 64-bit integers, which can be larger than 2^53 and so more than a
JSON parser that keeps numbers as doubles holds exactly.

The planner takes the records the same way, with add_records() in place
of add_manifest(). Note that it still keeps every name it is given, so
the memory a plan takes still grows with the manifest. The next commit
takes care of that. Sizing to fit is still the default, so the plan
reads the manifest from its start and the assembly reads it once more.
A regular file is read twice with positional reads, but a pipe can be
read only once. So assemble with a SOURCE refuses a manifest that comes
through a pipe, BadFileDescriptor with reason wrongType over Varlink. It
does that before it reads anything from it, so all of it is still in the
pipe. populate takes one. assemble --plan and assemble without a SOURCE
write nothing of the content after the plan, so they plan with the
reader that read the root object. They read the manifest only once and
take one through a pipe as well. So does Assemble in mode plan.

[1]: uapi-group/specifications#255

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
Currently the planner keeps every name of every directory it is given,
in a BTreeMap per directory keyed by the folded name. Now that a
manifest is read record by record that's the last thing that grows with
the manifest, about 160 bytes per object. assemble --plan of a manifest
of a million files peaks at 153 MiB, and at 41 MiB for a quarter of
them.

But a tree walk and a manifest in code point order both hand us the
entries in tree order: every directory before what is in it, and what
is in it right after it. So the planner only has to keep the
directories more entries can still go into, the root and the ones on
the way to the last entry, with the slots their entries take so far.
When the entries of a directory are done we add up the clusters it
takes for every cluster size and forget about it. A file only adds its
clusters. IOW, the memory a plan takes grows with the depth of the tree
and not with the number of its entries.

The price is that names aren't compared anymore. Two names FAT doesn't
tell apart, such as README.TXT and readme.txt, are two entries to the
plan. Where the assembly replaces, which it does by default, the file
under the second name replaces the first one. The replaced file stays
allocated until its replacement is complete, so the plan has to count
both for the peak. The old planner kept one count per folded name, and
that was too small: a volume of the size it planned ran out of clusters
while a large file that came late replaced an earlier one. Counting
both fixes that, and the finished file system keeps the clusters of
every replaced file free. That's fine, we're after a size that fits and
not the absolute minimum. Both entries also count against the 65536
entry slots of their directory, so the plan of a directory close to the
limit can fail although the write would fit. We accept that too. A
file and a directory under two such names don't fail the plan anymore
either. The write fails on the second one, replacing or not.

A directory under two such names is another matter. Its entries come
in two runs then, one under each name, and the plan holds each run to
the 65536 entry slots of a directory on its own while both together
might not fit. So the plan can pass what the write refuses with ENOSPC,
"directory is full". Remembering every directory the plan is done with,
by its parent and its folded name, would catch the second run. But that
grows with every directory, about 180 bytes each and 349 MiB for two
million of them, and it still misses a directory that comes back under
its 8.3 alias, such as FOOBAR~1 after FOO BAR. The numeric tails depend
on the siblings, so catching that needs every name of every directory,
which is exactly what we're getting rid of here. So the plan doesn't
compare names, and the README and the Varlink documentation say so. The
entries of a directory under two such names are held to the slot limit
as a whole only when they are written, and a file and a directory under
such names, or names that --no-replace refuses, pass a plan as well.

The slot limit is checked when a directory takes an entry. So a plan
fails at the entry that doesn't fit, and the error names the directory,
NoSpaceLeft with reason directoryEntries and its path over Varlink.
add_file() and add_dir() count right only in tree order, so they are
private now. Nothing outside the planner used them. Plan::add_tree()
takes the CopyOptions of the copy it plans for instead of a bare bool
for following symbolic links, and the command line and the service
build them in one place for the copy and its plan.

The planner allocates nothing per record. The open directories share one
path buffer, LongName::slots_for() counts the slots of a name from the
string with the checks of LongName::new(), Alias::of() puts the parts of
the alias in place instead of collecting them in two vectors first, and
path::names() hands out the names of a path without collecting them. The
path of an object goes into one more buffer, written by the helper that
gives the assembly its path, so the plan holds it to the 4095 bytes of a
path the way the write does. Most records go into the deepest open
directory. So the directory a record is in is compared with the path of
the open directories first, and the path of a record is split into names
only when it leaves the deepest one.

A plan of the same million files now peaks at 3.0 to 3.5 MiB, and so
does a plan of a quarter of them, of a million files in sixteen
directories, of a million files down a chain of 500 directories, and of
a tree of a million files on disk. It runs about half the instructions
and takes about half the time, and down the chain it takes 1.5 seconds
instead of 45. assemble of a million files from a manifest takes the
101 MiB populate takes, down from 154 MiB, and populate runs 3% fewer
instructions. So the README, the Varlink documentation and the manifest
module say that memory use doesn't grow with the manifest, for assemble
and its plan as well.

The tests pin what the old planner said for a synthetic tree of 885
entries with every shape of name the slots depend on, for 512 and 4096
byte sectors and every cluster size. The new one agrees, fed from a
walk and from a manifest. That tree fills a volume of the planned size
to the last cluster, copied from a walk and assembled from a manifest.
A tree with names FAT doesn't tell apart fits with the clusters of the
replaced file and of the second directory free, a file and a directory
under such names pass the plan and fail the write, names of 4094 and
4095 bytes are planned the way they are assembled, and the command line
passes a plan of a directory under two names and fails to write it.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
The manifests bench/compare.sh hands to the binaries are the ones of
the ESP, a few dozen records each. A slower reader or planner wouldn't
show up in what bench/compare.py reports.

So let's add plan/wide-manifest: assemble --plan on the manifest of the
wide tree, ten thousand records, with nothing else to do. The head
binary writes that manifest once with the other inputs, and an input
directory that doesn't have it yet is built again.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
Currently assemble sizes a file system to fit its content unless --size
is given, and even with --size it plans the content first to see that
it fits. Now that a manifest is read while its content is written, a
plan means reading the manifest twice. A regular file can be read twice
but a pipe can't, so assemble with a SOURCE refuses a manifest that
comes through a pipe altogether.

Let's make sizing to fit opt-in instead, like repart's Minimize=. With
--minimize, minimize in the FormatOptions of Assemble, the file system
is as small as its content allows, and a size given is the most it may
take. Without it the file system takes the size given, or else all of
the image behind the offset, the way mkfs.fat does. An empty image
without a size fails with SizeRequired. --fit and --manifest without a
SOURCE take the size given as well, which the --fit directory or what
the manifest describes has to fit, and without one they make the file
system as small as that allows.

A file system that takes the size given gets the cluster size the
formatter picks for that size, also when --fit or --manifest plans its
content first. So the plan uses that cluster size, and only a file
system sized to fit is formatted with the cluster size of its plan.
Taking the plan's cluster size for a size given would turn
--size 1G --fit DIR into 512 byte clusters where --size 1G alone gets
4 KiB ones, and above about 128 GiB 512 byte clusters are more than
FAT32 can count.

Whether the content fits that file system has to be counted in
clusters. The formatter's layout doesn't grow with the size in every
step: one sector more can take one more sector for each FAT and leave
one cluster less. With 512 byte clusters 66590 sectors hold 65534
clusters, and 66591 sectors only 65533. So --fit and --manifest compare
the clusters the plan counts with the clusters of the file system of the
size given, and say so in clusters when the content doesn't fit. A file
system sized to fit is made at the size of its plan, which holds what
the plan counts, so with --minimize comparing sizes is fine.

assemble --plan --size has to follow, since it answers for assemble with
the same options. Until now both planned with the cluster size of the
smallest file system. Now assemble --size gets the cluster size the
formatter picks for that size, so --plan --size plans with that one and
counts clusters as well. With --minimize it compares the smallest size
with --size as before.

Without --minimize a SOURCE isn't planned. Its content is written right
away, and content that doesn't fit fails with ENOSPC while it is
written and leaves the file system marked as not cleanly unmounted. So
a manifest can come through a pipe again. Only --minimize with a SOURCE
plans before it writes, so only it needs the manifest in a regular
file. It refuses a pipe before it reads anything from it, and over
Varlink so does minimize.

What can be found before the image is touched still is. A size no file
system of the options fits in, such as --size 1M, is refused before the
image grows, so a file that --create made is removed again. So is a
size of 0, whether it is given or what an --offset at the end of the
image leaves. SizeRequired is only for an empty image and no size at
all. The service checks the block size against the sector size before
it sizes anything, also for a size given. Both front ends walk a tree
under unsupported fail before they touch the image, in the plan with
minimize and on its own without it. An --offset beyond the end of the
image without a size says so.

--hash hashes the file system that was written, also where --size is
only the most --minimize may take. Whether a manifest is planned before
its content is written and how the file system is sized are one
decision now, util::SizeMode, so the two can't disagree.

Over Varlink Assemble only has a planning phase with minimize. Its
reply said in exact whether the size was planned, which the caller
knows from its own call, so exact goes. Capabilities.sizeToFit says in
the words of repart's Minimize= what a plan finds: best, the smallest
size, for vfat, or guess, a size with room to spare. That changes
org.uapi-group.FileSystem incompatibly: exact goes, SizeToFit's values
are renamed and without minimize an omitted size no longer means sized
to fit, which is only fine because the interface isn't released yet.
The README, the Varlink documentation and interface, the help and the
benchmark scripts follow.

The fuzzers pass --minimize where they relied on the plan, and they get
cases that plan nothing: a --size, a manifest through a pipe, and an
Assemble over Varlink with image.size. So a manifest that breaks while
the volume is written is fuzzed as well.

bench/compare.sh gives the file systems it assembles a size, so that a
binary that sizes to fit on its own and one that doesn't make the same
ones.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
Currently assemble and populate replace a file that is there already
unless --no-replace is given, and replace in the Content of the Varlink
interface is true by default. Two names FAT doesn't tell apart, such as
README.TXT and readme.txt, are taken as one name: the second file
replaces the first one and the second directory takes the entries of
the first one.

The reader refuses a manifest that names a file twice, as UAPI.16 asks.
To FAT two names it doesn't tell apart are one name, so they should be
refused just the same. assemble makes a new file system, so a name that
is there already comes from its content: a name FAT doesn't tell apart
from an earlier one. And populate usually fills an empty file system,
or one that doesn't hold the files it is given.

So let's refuse existing files by default. assemble and populate take
--replace now and --no-replace goes. replace in the Varlink Content is
false by default for Assemble and Populate. Without it a file that is
there fails with EEXIST, FileExists over Varlink. A name FAT doesn't
tell apart from one that is there fails with EEXIST as well, and with
InvalidName and reason caseCollision over Varlink, for files and
directories, from a manifest or a tree. A directory that is there under
the same name takes the entries either way.

The error of a case collision is Error::case_collision(). It names the
entry that is there by its path as the volume spells it. So with /EFI/x
in the volume, populate with --path /efi/X says that '/efi/X' and
'/EFI/x' are names FAT cannot tell apart. begin_file() raises it for
files and the new Volume::find_or_create_dir() for the directories of
the populator and the assembly, before anything else about the entry.
So a file under a name FAT doesn't tell apart from a directory's is a
case collision as well. The assembly creates a file once the source has
its first data. So an error the source finds before the data, such as a
file that is missing below the source directory, still comes first, and
EEXIST comes before one in the data, such as a hash that doesn't match.

begin_file(), create_file() and write_file() took a bare bool for
replacing, and CopyOptions kept one in replace. They take a
NameCollision now, Fail or Replace, and so does find_or_create_dir().
CopyOptions keeps it in name_collision. find_or_create_dir() returns a
DirectoryOrigin: Created, or Existing with the attributes of the
directory that is there. The populator and the assembly looked a
directory up from the root to see whether it is there, and walked from
the root once more to create it. find_or_create_dir() does both in one
walk.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
Currently, assemble --create creates the image right away and removes it
again only when it fails before the format, because the content doesn't
fit the size given or a source can't be read. When filling the file
system fails the image stays, marked as not cleanly unmounted. Without
--minimize the content is written right away and a size that is too
small is only found while it is written. So a failed assemble --create
--size leaves a half-written image behind.

We could remove the image by its name after any failure. But no unlink
is conditional on the inode, so whatever has the name by then would go.
Instead, let's not give the image a name before everything succeeded.
Device::create() makes the image with O_TMPFILE in the parent directory
it looked up, and it has no name while it is formatted and filled. Once
the manifest of --write-manifest and the hash are written the image gets
its name with linkat(fd, "", dir, name, AT_EMPTY_PATH). Since
42bd2af59504 ("vfs: relax linkat() AT_EMPTY_PATH - aka flink() -
requirements") the opener can do that without CAP_DAC_READ_SEARCH. Where
it fails with ENOENT we link through /proc/self/fd/<fd> with
AT_SYMLINK_FOLLOW, as systemd's link_fd() does. A failure, a kill, or
SIGPIPE while the manifest goes to standard output leave no name behind.
A name that something else took meanwhile stays as it is since the link
fails with EEXIST. The cost is that --create only claims the name at the
end. A file system that makes files without a name but can't link them,
say a FUSE server with FUSE_TMPFILE but without FUSE_LINK, fails only
then, and we say so.

Where O_TMPFILE is refused (EOPNOTSUPP from a file system without it,
EISDIR from a kernel that doesn't know it) the image is made under a
temporary name in the same directory: ".#", the name and 16 random hex
digits, as systemd's tempfn_random() does it. At the end it is renamed
with RENAME_NOREPLACE. NFS, CephFS and 9p refuse that flag with EINVAL,
and a kernel without renameat2() says ENOSYS. There we link the image by
its descriptor and remove the temporary name afterwards. We call
renameat2() through syscall(), since the musl that Rust links its musl
targets with has no wrapper for it. A kill leaves the temporary name
behind, as a crash would. A rename moves whatever has the temporary name
by then. So right before each rename we check by device and inode number
that the temporary name still refers to our file, and after it that the
name does, and fail otherwise. A file that takes the temporary name
between that check and the rename still ends up under the image's name,
and we leave it there. When the check after the link fails for another
reason, say EMFILE, the image keeps its name and we say that it has its
name but couldn't be checked.

Which of the two works is found out right when the image is made, before
anything is written to it, by renaming the temporary file to another
temporary name with RENAME_NOREPLACE, or else by linking it to one. A
file system without hard links refuses the link with EPERM (vfs_link()).
Where both are refused, as on vboxsf and orangefs, the image is created
under its name with O_CREAT|O_EXCL as main does it, and removed by that
name after any failure, where main removes it only when sizing it fails
before the format. Note that this last resort can't avoid the window
between checking that the name still refers to the image and removing
it. A rename onto the name in between gets the other file removed. That
crosses no privilege boundary though, whoever can rename onto the name
could unlink it anyway. The new file takes the exclusive lock the device
takes as soon as it exists. A file another process locked first keeps
its name and we fail with EBUSY. Where the lock can't be had at all, say
ENOLCK from NFS without lockd, we remove the fresh name after the same
check and fail with that error. Otherwise a name is only ever removed
while we hold the lock.

fat::host::NewFile is a file that waits for its name. Dropping it gives
it up, and giving it up removes a temporary name, or the name of the
last resort, after checking by device and inode number that it still
refers to the file. NewFile::discard() says what became of the name and
NewFile::give_up() says what of the file stays, if anything. The tool
collects that in Leftovers, and prints it after the error: what failed,
then what that left behind. The device gets a descriptor of its own that
shares the open file description with the new file, so the lock is held
until the new file is gone. The hash has to be taken before the link, so
we take it through the volume's device after syncing it instead of
opening the image by path again. A failure there goes through
NewVolume::abandon() like any other one, and the hash is printed only
once the image has its name. abandon() drops the volume with
Volume::abandon(), which writes nothing. So a half-filled file system
that somebody linked meanwhile isn't marked clean. NewVolume is a guard
as well. A NewVolume that is dropped before link() or abandon(), say by
an early return added later, gives up an image made for it and closes an
image that was there as not cleanly unmounted, or writes nothing at all
while a panic unwinds.

The files of --write-manifest and --write-hash are made the same way and
get their names after the image, in place of what has them. So a failed
run doesn't leave a manifest of an image that doesn't exist. Since such
a file is replaced and not written over, other hard links to it keep
what it held. A pipe, a device or a symbolic link at their path is
written to as we go, as standard output is, and that can't be taken
back. An image that has its name keeps it when one of these files can't
get its own.

Since the names are made last now, a power cut right after a reported
success could lose them although the data was synced. So, as systemd's
LINK_TMPFILE_SYNC does, each file is synced before it gets its name, the
image by closing the volume, and each directory is synced once after the
last link, also when something fails after the image got its name, so
that a crash can't take the name of a complete image we said we kept.
vboxsf, orangefs, AFS and 9p without 9P2000.L have no fsync for
directories and vfs_fsync_range() gives EINVAL there, so we skip the
sync. We skip it as well for a directory we may write to but not read,
mode 0300 say, since it can't be opened for the fsync. That's also why
the directory is only opened once the names are given and not before.
Any other failure of the sync fails the command, but the names stay and
we say so.

Note that an image that was there before keeps what was written, marked
as not cleanly unmounted, the way a crash would leave it.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
UAPI.16 has flags for the hidden, system and archive attributes of DOS,
flagHidden, flagSystem and flagArchive, recorded by the features
flag-hidden, flag-system and flag-archive. FAT has exactly these
attributes. It has none of the Linux inode flags the spec has flags
for: flagAppendOnly, flagImmutable, flagNoAtime, flagNoCow and
flagNoDump.

The manifest of a volume records the hidden, system and archive
attributes now when it is asked for their features. A flag is written
where an entry has the attribute and is cleared where it isn't
written. Asked for the inode flags, the manifest lists them and so says
that they are cleared everywhere, the way it says that FAT has no
symbolic links.

An assembly applies the flags. A flag that is set sets the attribute,
and a flag the manifest lists in features but an object leaves out
clears it, also the archive attribute a new file gets otherwise.
Without the feature the attribute stays as it is. A directory gets its
attributes too, also one that is there already. The inode flags are
ignored.

A file gets the read-only attribute as before: from readOnly, or from a
mode that gives nobody write permission where the manifest doesn't list
read-only. A directory gets it the same way now, a new one and one that
is there. Otherwise an object isn't read-only, which is the default the
spec gives readOnly when an object is placed. So a directory that is
there loses the attribute when its object doesn't say that it's
read-only.

DosAttributes translates between the attribute byte of an entry and
what a file object says about it. with_object() is the one place that
applies readOnly and the flags of an object to an entry, for files and
directories alike. record_in() is its counterpart and puts readOnly and
the flags of an entry into the object the manifest of a volume writes
for it. A FileWriter tells which attributes the file it writes gets.
Nothing calls set_read_only() of FileWriter and OpenFile anymore, so it
goes. find_or_create_dir() takes the attributes of a directory it makes.
So a new directory is written once, with its attributes, and nothing
copies what make_directory() puts into the entry.

An assembly calls set_attributes() for a directory that is there. So
set_attributes() now looks at the entry and its directory before it
begins writing, as set_times() does, and a call that is refused leaves
the volume unmarked.

The manifest of --write-manifest has the default features, so it has
none of the flags. The README says so. Letting the command line ask for
them is for later.

While at it, say in the README and in the Varlink documentation that
the files a manifest lists as hard links of one file become copies.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
The root object of a manifest can name the file system it is for.
fatSerial is the serial number of a FAT volume, fsUUID the UUID of a
file system and fsLabel its label. The spec has a file system made from
the manifest take them, and a file system the file objects are put into
have them. We ignored all three so far.

Now a volume assemble makes from a manifest takes the serial number in
fatSerial, or else the one the first eight hex digits of fsUUID give,
and the label in fsLabel. A manifest that lists fs-label and has no
fsLabel names a volume without a label, and so does an empty fsLabel. An
--identifier or a --label that differs from what the manifest names
fails with EINVAL and the new FileSystemMismatch, and so do identifier
and label over Varlink. The error's FileSystemField names the field of
the manifest the value comes from. Volume::assemble() checks that the
volume has the serial number and the label the manifest names before it
writes anything. So populate, and a caller of the library, can't put a
manifest into another volume either.

The spec defines the label as what the file system reports, and on FAT
that's what blkid shows: the name of the root directory's label entry,
where Windows, EDK2 and GRUB read it too. Volume::label() fell back to
the copy in the boot sector where there is no such entry, which blkid
stopped doing in util-linux 2.33. Now it reads the root directory's
entry only.

FAT pads a label with spaces, which blkid trims, and stores the blank
label and NO NAME for no label. So a label with a space at its end, a
blank one and NO NAME can't be represented, and we refuse them in a
manifest as the spec asks, with InvalidLabel in assemble and in populate
alike: a trailing space with reason invalidCharacter, the blank label
and NO NAME with the new reason reserved. Taking "TEST " would make a
volume labeled TEST, and the manifest ufat writes of that volume would
say TEST, so the label wouldn't survive the round trip. --label still
takes such a label, as mkfs.fat -n does.

A manifest that names no serial number gives the volume one derived from
its bytes, as the spec recommends, instead of one drawn at random or
derived from the time stamp: the first four bytes of the SHA-256 hash of
the manifest, read big-endian. So its eight hex digits are the first
ones sha256sum prints for the manifest. Whoever opens a manifest says
what it does with it, and only where that may derive a serial number is
the manifest hashed while it is read. populate never derives one, and
neither does assemble with --identifier, so neither pays for the hash.
assemble stops hashing once the manifest turns out to name a serial
number. For a manifest of 1M files, 112 MB, the hash costs assemble 1.2%
more instructions, populate none. The hash is there once the reader read
the end of the manifest, and not before. So assemble knows the serial
number once the content is written, whether the manifest came in a
regular file or through a pipe. Volume::set_volume_id() sets it then,
first in the backup boot sector and then in the boot sector, while the
volume is marked as being written. The crash harness sets a serial
number at the start and at the end of its scenario. A plan reads the
whole manifest up front and keeps its hash, so with --minimize the
manifest is hashed once, and the reply of a plan has the serial number
right away.

reproducible doesn't need an identifier anymore when the content is a
manifest, which names the serial number or has it derived.

The manifests ufat writes name the volume as well. The root object
always has fatSerial, and fsLabel when the volume has a label, and the
manifest lists fat-serial and fs-label, since an object can't carry a
field whose feature the manifest doesn't list. So a manifest without
fsLabel says that the volume has no label. A volume made from the
manifest gets the same serial number and label, and its content goes
into that volume and no other. A label that a volume made from the
manifest wouldn't get, one with a control character or a Latin-1
character that only other tools write, is left out, and the manifest
doesn't list fs-label then. WriteReport names it in omitted_label, apart
from the entries in omitted, so the command line says which label it
left out instead of counting it as an entry. Varlink's omitted counts
it with the entries, since it is metadata the manifest couldn't record.

Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
@brauner
brauner removed this pull request from stack #24 November 20, 2026 22:21
@brauner
brauner changed the base branch from main to ebusyfix November 20, 2026 22:22
@brauner
brauner added this pull request to stack #29 November 20, 2026 22:22
@brauner
brauner merged commit 186671f into main Nov 21, 2026
24 of 52 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant