ferrosys 0.8.0

Pure-Rust filesystem formatter and reader: ext4, ext3, ext2, FAT32, FAT16, FAT12, exFAT, btrfs, and APFS — rootless, in userspace, byte-reproducible
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
//! Writing a filesystem's contents out as a tar archive: the [`ArchiveSink`].
//!
//! This is [`ArchiveSource`](crate::archive::ArchiveSource) in the other direction, and the
//! two are deliberately a pair — what this writes, that reads, and the round trip
//! reproduces the filesystem it came from.
//!
//! # What the archive carries
//!
//! Everything the filesystem holds that tar can express, and nothing is dropped in silence.
//! Ownership, mode bits, symlinks, hard links, device and FIFO nodes come out in the header;
//! the times (to the nanosecond, and negative where the file predates the epoch), the paths,
//! the ids, the extended attributes, and the POSIX ACLs come out in PAX records, because the
//! header cannot hold them. A socket has no tar entry type at all, so a filesystem holding
//! one is a typed error rather than an archive quietly missing a file. A device number is
//! written into the header exactly — eight octal digits filling the field where seven do not
//! hold it — and one past what eight digits hold is a typed error too.
//!
//! The PAX record is authoritative for every field it carries, and it is always written. The
//! header's own path and link-target fields hold the same value when it fits in them, and
//! are left empty when it does not — so they are either right or absent, never subtly wrong.
//!
//! A record is written in the length-prefixed form the format defines, so its value is
//! delimited by the count and not by the newline that ends the record. A filesystem holding a
//! name with a newline in it therefore round-trips: the length says where the value stops.
//!
//! # Any family, and what that costs a value
//!
//! The source is any [`FsTree`], so the same sink drains whatever `open` hands back. A
//! filesystem that does not record ownership or permission bits has them filled from the
//! [`Synthesis`] the caller named, and every value invented that way is named in the
//! [`FidelityReport`] the write returns — so an archive built from such an image says what
//! in it was the image's and what was policy.
//!
//! # What comes out is what goes back in
//!
//! The archive opens with a `./` member describing the root directory, which is how the
//! root's own metadata survives a round trip. It omits an ext filesystem's `/lost+found`,
//! which every ext filesystem makes for itself and which the ext formatter refuses to be told
//! to make; on every other family a directory of that name is the volume's own and is written
//! like any other.
//!
//! # Memory
//!
//! A file's bytes are streamed from the filesystem into the archive, so an archive of a tree
//! far larger than memory costs the working set of one read rather than the size of its
//! largest file. The tree is walked entry by entry for the same reason: nothing accumulates
//! but the hard-link table, which holds one path per node that has more than one name.

use std::collections::HashMap;
use std::io::{Read, Write};

use tar::{Builder, EntryType, Header};

use crate::archive::ArchiveError;
use crate::fidelity::{Direction, FidelityReport, Property, Synthesis};
use crate::time::Timestamp;
use crate::tree::{
    Attributes, BODY_WINDOW, FsTree, NodeKind, TreeEntry, TreeError, flags_not_carried,
    made_by_the_format,
};

/// Writes a filesystem's contents out as a tar archive with PAX extensions.
///
/// The counterpart to [`ArchiveSource`](crate::archive::ArchiveSource): one reads a tree
/// into a filesystem, this writes a filesystem back out as a tree, and an archive that makes
/// the round trip describes the same filesystem at both ends.
///
/// ```no_run
/// # use ferrosys::ArchiveSink;
/// # use ferrosys::ext::Reader;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut reader = Reader::open(std::fs::File::open("rootfs.img")?)?;
/// let out = std::io::BufWriter::new(std::fs::File::create("rootfs.tar")?);
/// let fidelity = ArchiveSink::new(out).write_tree(&mut reader)?;
/// assert!(fidelity.is_faithful());
/// # Ok(())
/// # }
/// ```
pub struct ArchiveSink<W: Write> {
    builder: Builder<W>,
    synthesis: Synthesis,
}

impl<W: Write> ArchiveSink<W> {
    /// A sink that writes its archive to `out`.
    ///
    /// Nothing is buffered here beyond what tar's own framing needs, so a destination that
    /// benefits from buffering should be wrapped in a [`BufWriter`](std::io::BufWriter)
    /// before it is handed over.
    #[must_use]
    pub fn new(out: W) -> Self {
        Self {
            builder: Builder::new(out),
            synthesis: Synthesis::new(),
        }
    }

    /// Name what to record for a property the source filesystem has no field for.
    ///
    /// Defaults to [`Synthesis::new`] — owned by root, `0644` for a file and `0755` for a
    /// directory. Ignored entirely by a filesystem that records the property itself.
    #[must_use]
    pub fn synthesis(mut self, synthesis: Synthesis) -> Self {
        self.synthesis = synthesis;
        self
    }

    /// Write the filesystem's whole tree, then finish the archive.
    ///
    /// The archive's first member is `./`, the root directory, so the root's own metadata
    /// and attributes survive; an ext filesystem's `/lost+found` and everything under it is
    /// omitted, since the format makes it for itself. Every other
    /// name the filesystem holds appears exactly once, with the second and later names for
    /// one node written as hard links to the first.
    ///
    /// The returned [`FidelityReport`] names every property the source filesystem had no
    /// field for and the archive therefore carries an invented value of, and as dropped every
    /// entry's BSD flags, which a Darwin filesystem records and a tar header has no field for.
    /// It is faithful for a family that records everything a tar member holds.
    ///
    /// # Errors
    ///
    /// [`ArchiveError::Read`] if the filesystem cannot be read; [`ArchiveError::Io`] if the
    /// destination cannot be written; [`ArchiveError::Unrepresentable`] if the filesystem
    /// holds a socket, [`ArchiveError::DeviceUnrepresentable`] if it holds a device node whose
    /// numbers a tar header cannot hold, and [`ArchiveError::XattrNameUnrepresentable`] if an
    /// attribute's name cannot be written to a PAX record.
    pub fn write_tree<T: FsTree>(mut self, tree: &mut T) -> Result<FidelityReport, ArchiveError> {
        // The first name to reach a node is the file; every later name for the same node is
        // another name for it — a hard link — and the archive says so rather than storing
        // the bytes a second time.
        let mut named: HashMap<u64, Vec<u8>> = HashMap::new();
        let mut fidelity = FidelityReport::new();
        let synthesis = self.synthesis;

        // Walked entry by entry rather than gathered, so the memory an archive costs does
        // not grow with the number of names in the tree. The walk reports in this module's
        // own error vocabulary, so a member that cannot be written and a directory that
        // cannot be read both stop it as themselves. The root arrives first, under the empty
        // path, which is what becomes the `./` member.
        tree.walk_tree(|tree, entry| {
            if made_by_the_format(&entry.path, tree.family()) {
                return Ok(());
            }
            let member = Member::of(tree, entry, &mut named, &synthesis, &mut fidelity)?;
            self.append(tree, &member)
        })?;

        self.builder.finish().map_err(ArchiveError::Io)?;
        Ok(fidelity)
    }

    /// Append one member: its PAX records, then its header and contents.
    ///
    /// The records go first because that is where they apply — an `x` header describes the
    /// entry that follows it.
    fn append<T: FsTree>(&mut self, tree: &mut T, m: &Member<T::Node>) -> Result<(), ArchiveError> {
        let name = member_name(&m.path, matches!(m.kind, NodeKind::Directory));

        let entry_type = if m.hardlink.is_some() {
            EntryType::Link
        } else {
            match m.kind {
                NodeKind::Directory => EntryType::Directory,
                NodeKind::File { .. } => EntryType::Regular,
                NodeKind::Symlink => EntryType::Symlink,
                NodeKind::CharDevice { .. } => EntryType::Char,
                NodeKind::BlockDevice { .. } => EntryType::Block,
                NodeKind::Fifo => EntryType::Fifo,
                // A socket has no tar entry type at all, and is refused before a member is
                // ever built for it. Matched by name rather than by wildcard so a
                // `NodeKind` a later family adds is a compile error here, which forces a
                // decision about how tar carries it.
                NodeKind::Socket => {
                    return Err(ArchiveError::Unrepresentable {
                        path: m.path.clone(),
                    });
                }
            }
        };
        let target = m.hardlink.as_ref().or(m.symlink.as_ref());
        let meta = &m.attrs.meta;

        // Every field the header cannot hold exactly goes into a PAX record, and the ones it
        // can go into both: the record is authoritative, and every reader that honours it —
        // GNU tar, bsdtar, and this crate's own archive source among them — reads the exact
        // value whatever the header says.
        let mut records: Vec<(String, Vec<u8>)> = vec![
            ("path".to_string(), name.clone()),
            ("atime".to_string(), pax_time(meta.atime).into()),
            ("ctime".to_string(), pax_time(meta.ctime).into()),
            ("mtime".to_string(), pax_time(meta.mtime).into()),
            ("uid".to_string(), meta.uid.to_string().into()),
            ("gid".to_string(), meta.gid.to_string().into()),
        ];
        if let Some(target) = target {
            records.push(("linkpath".to_string(), target.clone()));
        }
        for xattr in &m.attrs.xattrs {
            records.push((pax_xattr_key(&m.path, &xattr.name)?, xattr.value.clone()));
        }
        let borrowed: Vec<(&str, &[u8])> = records
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_slice()))
            .collect();
        self.builder
            .append_pax_extensions(borrowed)
            .map_err(ArchiveError::Io)?;

        let mut header = Header::new_ustar();
        header.set_entry_type(entry_type);
        header.set_mode(u32::from(meta.mode & 0o7777));
        header.set_uid(u64::from(meta.uid));
        header.set_gid(u64::from(meta.gid));
        // The header's time is unsigned whole seconds, so a file older than the epoch or one
        // carrying a sub-second time cannot be written there. The PAX record above holds the
        // real value; this is the approximation a reader that ignores it would see.
        header.set_mtime(u64::try_from(meta.mtime.secs).unwrap_or(0));
        if let NodeKind::CharDevice { major, minor } | NodeKind::BlockDevice { major, minor } =
            m.kind
            && let Some(ustar) = header.as_ustar_mut()
        {
            // Both fit: `Member::of` refused a node whose numbers do not.
            device_field(&mut ustar.dev_major, major);
            device_field(&mut ustar.dev_minor, minor);
        }
        // A path or a target that is text and short enough goes into the header as well,
        // where a reader that ignores PAX records finds it. One that is neither — not text,
        // or too long for the field — is left out rather than truncated into a name that is
        // not the file's, or transliterated into a differently-named file. The PAX record
        // above holds it exactly either way, so an empty field here is honestly absent,
        // never subtly wrong.
        if let Ok(text) = std::str::from_utf8(&name) {
            let _ = header.set_path(text);
        }
        if let Some(target) = target
            && let Ok(text) = std::str::from_utf8(target)
        {
            let _ = header.set_link_name(text);
        }

        // A regular file's bytes are streamed out of the filesystem rather than held: the
        // reader fills the archive from the blocks as it goes. Everything else has no body
        // at all — a hard link's contents belong to the node the first name wrote.
        //
        // The size declared is the length the body will actually run to, which is what the
        // walk reported rather than what any size field claims. A header promising more than
        // the body carries is an archive a reader that trusts it mis-frames.
        let size = match m.kind {
            NodeKind::File { size } if m.hardlink.is_none() => size,
            _ => 0,
        };
        // What an archive *writes* is driven entirely by a length the filesystem declares,
        // and a hole reads back as zeros — so an inode claiming terabytes and mapping
        // nothing costs terabytes of members, from an image of a few kilobytes. The cap a
        // caller set on what a read will return governs that too, checked before a byte is
        // written and against the same declared length a whole-file read would have refused.
        tree.check_file_size(&m.path, size)?;
        header.set_size(size);
        header.set_cksum();
        if size == 0 {
            return self
                .builder
                .append(&header, std::io::empty())
                .map_err(ArchiveError::Io);
        }
        // `tar` copies a body a few kilobytes at a time. Buffered to the window, each read of
        // the filesystem moves up to a mebibyte, which is what lets a reader fetch the
        // blocks of a contiguous file in one request rather than two at a time.
        let window = usize::try_from(size).unwrap_or(usize::MAX).min(BODY_WINDOW);
        let mut body =
            std::io::BufReader::with_capacity(window, NodeData::new(tree, &m.node, size));
        match self.builder.append(&header, &mut body) {
            Ok(()) => Ok(()),
            // The filesystem's own verdict, kept beside the I/O error it had to travel as,
            // so a file the image cannot yield is the image's failure and not the
            // destination's.
            Err(e) => {
                let body = body.into_inner();
                Err(match (body.failed, body.short) {
                    (Some(source), _) => ArchiveError::Read(source),
                    (None, true) => ArchiveError::ShortRead {
                        path: m.path.clone(),
                        size,
                        got: body.offset,
                    },
                    (None, false) => ArchiveError::from_body_io(e, &m.path),
                })
            }
        }
    }
}

/// A regular file's bytes as a [`Read`], filled from the filesystem a window at a time.
///
/// This is what keeps an archive's memory bounded: `tar` copies a body out of a reader, so
/// handing it one that reads through the filesystem means neither side ever holds the file.
struct NodeData<'a, T: FsTree> {
    tree: &'a mut T,
    node: &'a T::Node,
    offset: u64,
    /// The length the header declared, which the body is held to exactly: a filesystem
    /// yielding more than was promised would push the archive's framing out of step with it.
    size: u64,
    /// The filesystem's failure, when a read of it is what stopped the body. A `Read` can
    /// only speak `io::Error`, so this is where the typed verdict waits to be handed back.
    failed: Option<TreeError>,
    /// Whether the filesystem yielded nothing with bytes of the declared length still owed.
    /// `tar` reads a zero as the end of the body and pads to the bytes it copied, so a short
    /// body is an error here and not an end.
    short: bool,
}

impl<'a, T: FsTree> NodeData<'a, T> {
    fn new(tree: &'a mut T, node: &'a T::Node, size: u64) -> Self {
        Self {
            tree,
            node,
            offset: 0,
            size,
            failed: None,
            short: false,
        }
    }
}

impl<T: FsTree> Read for NodeData<'_, T> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let left = self.size.saturating_sub(self.offset);
        if left == 0 || buf.is_empty() {
            return Ok(0);
        }
        let want = usize::try_from(left).unwrap_or(usize::MAX).min(buf.len());
        // A read failure of the *filesystem* has to leave through `io::Error`, because that
        // is the only failure a `Read` has. The typed error is kept here as well, and the
        // sink hands that back rather than the I/O error it travelled as.
        let filled = match self
            .tree
            .read_bytes(self.node, self.offset, &mut buf[..want])
        {
            Ok(filled) => filled,
            Err(e) => {
                let carried = match &e {
                    TreeError::Io { kind, message } => std::io::Error::new(*kind, message.clone()),
                    other => std::io::Error::other(other.to_string()),
                };
                self.failed = Some(e);
                return Err(carried);
            }
        };
        if filled == 0 {
            self.short = true;
            return Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "the filesystem yielded fewer bytes than the file's length",
            ));
        }
        self.offset += filled as u64;
        Ok(filled)
    }
}

/// One archive member: what the header and its records say, and the node a body comes from.
struct Member<N> {
    /// The path in the filesystem. Empty for the root, which has no name of its own.
    path: Vec<u8>,
    /// What is at the path.
    kind: NodeKind,
    /// The mode, ownership, times, and attributes to record.
    attrs: Attributes,
    /// The member this name is a second name for, when it is a hard link.
    hardlink: Option<Vec<u8>>,
    /// Where a symbolic link points.
    symlink: Option<Vec<u8>>,
    /// The family's handle to the node, for streaming a regular file's bytes.
    node: N,
}

impl<N> Member<N> {
    /// Everything one walk entry contributes to the archive.
    fn of<T: FsTree<Node = N>>(
        tree: &mut T,
        entry: TreeEntry<N>,
        named: &mut HashMap<u64, Vec<u8>>,
        synthesis: &Synthesis,
        fidelity: &mut FidelityReport,
    ) -> Result<Self, ArchiveError> {
        let TreeEntry {
            path,
            kind,
            shared,
            node,
            ..
        } = entry;
        if matches!(kind, NodeKind::Socket) {
            return Err(ArchiveError::Unrepresentable { path });
        }
        if let NodeKind::CharDevice { major, minor } | NodeKind::BlockDevice { major, minor } = kind
            && (major > DEVICE_MAX || minor > DEVICE_MAX)
        {
            return Err(ArchiveError::DeviceUnrepresentable { path, major, minor });
        }

        // A node the walk says is reachable by more than one name is the file the first time
        // it is seen and a hard link every time after. Only such a node carries an identity,
        // so the table holds the tree's hard links rather than a path per file in it.
        let hardlink = match shared {
            // A hard link's target is a member of this same archive, so it is named the way
            // that member is named.
            Some(id) => match named.get(&id) {
                Some(first) => Some(member_name(first, false)),
                None => {
                    named.insert(id, path.clone());
                    None
                }
            },
            None => None,
        };

        let mut attrs = tree.stat(&node, synthesis)?;
        for property in &attrs.synthesized {
            fidelity.record(Direction::Synthesized, &path, *property);
        }
        // A tar header has no field a BSD flag goes in, so the archive does not carry one.
        if hardlink.is_none() && flags_not_carried(tree, &node)? != 0 {
            fidelity.record(Direction::Dropped, &path, Property::BsdFlags);
        }
        // A hard link carries nothing of its own: the contents and the attributes belong to
        // the node, which the name that came first already wrote.
        if hardlink.is_some() {
            attrs.xattrs.clear();
        }

        let symlink = if matches!(kind, NodeKind::Symlink) && hardlink.is_none() {
            Some(tree.link_target(&node)?)
        } else {
            None
        };

        Ok(Self {
            path,
            kind,
            attrs,
            hardlink,
            symlink,
            node,
        })
    }
}

/// The largest device number a tar header holds: eight octal digits filling its field.
const DEVICE_MAX: u32 = 0o7777_7777;

/// Write a device number into a header's eight-byte field: seven octal digits and a
/// terminator where they hold it, as every tar writer spells it, and eight digits filling the
/// field where they do not — the form bsdtar writes for a number past seven digits and GNU tar
/// reads back (both observed). Reports whether the number fit; one past [`DEVICE_MAX`] fits
/// neither form, and the field is left as it was.
fn device_field(field: &mut [u8; 8], value: u32) -> bool {
    let digits = if value <= 0o777_7777 {
        format!("{value:07o}\0")
    } else if value <= DEVICE_MAX {
        format!("{value:08o}")
    } else {
        return false;
    };
    field.copy_from_slice(digits.as_bytes());
    true
}

/// The name a path takes inside an archive: `/etc/hostname` becomes `./etc/hostname`, and
/// the root becomes `./`.
///
/// A relative name is what a tar archive carries and what an extractor unpacks without
/// argument; the archive source maps it back to an absolute path on the way in. A
/// directory's name ends in a slash, as every tar writer marks one.
fn member_name(path: &[u8], directory: bool) -> Vec<u8> {
    let mut name = Vec::with_capacity(path.len() + 2);
    name.push(b'.');
    name.extend_from_slice(path);
    if directory {
        name.push(b'/');
    }
    name
}

/// A timestamp as a PAX record's value: decimal seconds, with a fractional part when the
/// time carries one.
///
/// A negative time floors its seconds and carries the fraction up towards the next
/// second — the same convention the archive source reads back — so
/// `Timestamp { secs: -6, nanos: 750_000_000 }` is written `-5.250000000`, which is the
/// instant it names.
///
/// A filesystem's stored fraction need not divide a second — ext4's is a thirty-bit field —
/// so an image this crate did not write can name more nanoseconds than there are in one.
/// Such a fraction is carried into the seconds before anything is written, so the record
/// names the instant the two fields describe and always holds a nine-digit fraction, rather
/// than a ten-digit one a reader would scale wrongly.
#[must_use]
fn pax_time(t: Timestamp) -> String {
    // Normalize first: every case below assumes a fraction smaller than a second.
    let t = Timestamp {
        secs: t
            .secs
            .saturating_add(i64::from(t.nanos / Timestamp::NANOS_PER_SEC)),
        nanos: t.nanos % Timestamp::NANOS_PER_SEC,
    };
    if t.nanos == 0 {
        return t.secs.to_string();
    }
    if t.secs < 0 {
        let whole = t.secs + 1;
        let frac = Timestamp::NANOS_PER_SEC - t.nanos;
        // A time inside the last second before the epoch has no negative whole part to
        // carry the sign, so the sign is written onto the zero.
        if whole == 0 {
            return format!("-0.{frac:09}");
        }
        return format!("{whole}.{frac:09}");
    }
    format!("{}.{:09}", t.secs, t.nanos)
}

/// The PAX keyword for an extended attribute, `SCHILY.xattr.<name>`.
///
/// A PAX record's keyword is text and cannot hold an `=` (its key/value delimiter) or a
/// newline (its record terminator), and a reader taking it as a C string ends it at a NUL, so
/// a name carrying any of the three, an empty name, or one that is not valid UTF-8 has no
/// faithful spelling. It is refused rather than flattened through U+FFFD or split at a
/// delimiter into a differently-named attribute, which would corrupt the round trip silently.
/// Standard attribute names are ASCII without these bytes.
fn pax_xattr_key(path: &[u8], name: &[u8]) -> Result<String, ArchiveError> {
    match std::str::from_utf8(name) {
        Ok(text) if !text.is_empty() && !text.contains(['=', '\n', '\0']) => {
            Ok(format!("SCHILY.xattr.{text}"))
        }
        _ => Err(ArchiveError::XattrNameUnrepresentable {
            path: path.to_vec(),
            name: name.to_vec(),
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_member_is_named_relative_to_the_archive_root() {
        assert_eq!(member_name(b"/etc/hostname", false), b"./etc/hostname");
        assert_eq!(member_name(b"/etc", true), b"./etc/");
        // The root has no name of its own, so it is the bare `./` — which is exactly what
        // the archive source reads back as the filesystem root.
        assert_eq!(member_name(b"", true), b"./");
    }

    #[test]
    fn a_device_number_fills_the_header_field_as_far_as_it_reads_back() {
        // Seven digits and a terminator up to 2097151, eight filling the field up to
        // 16777215 — Darwin's twenty-four-bit minor numbers among them — and each reads back
        // through the header as the number written.
        for value in [0u32, 3, 0o777_7777, 0o1000_0000, 16_777_215] {
            let mut header = Header::new_ustar();
            let ustar = header.as_ustar_mut().expect("a ustar header");
            assert!(device_field(&mut ustar.dev_minor, value), "{value}");
            assert_eq!(header.device_minor().expect("a number"), Some(value));
        }
        // The seven-digit form is the one every tar writer spells, so an archive of ordinary
        // devices is the bytes it is without this.
        let mut ours = Header::new_ustar();
        device_field(&mut ours.as_ustar_mut().expect("ustar").dev_minor, 3);
        let mut theirs = Header::new_ustar();
        theirs.set_device_minor(3).expect("a ustar header");
        assert_eq!(ours.as_bytes(), theirs.as_bytes());
        // Past eight digits there is no spelling, and nothing is written.
        let mut header = Header::new_ustar();
        let ustar = header.as_ustar_mut().expect("a ustar header");
        assert!(!device_field(&mut ustar.dev_minor, DEVICE_MAX + 1));
    }

    #[test]
    fn a_pax_xattr_key_is_built_for_a_plain_name_and_refused_otherwise() {
        // A standard ASCII name becomes the SCHILY.xattr keyword.
        assert_eq!(
            pax_xattr_key(b"/f", b"user.comment").unwrap(),
            "SCHILY.xattr.user.comment"
        );

        // A name a PAX keyword cannot carry faithfully is a typed error, not a silently
        // corrupted record: an embedded '=' or newline (the record's own delimiters), a NUL a
        // C-string reader ends the keyword at, no name at all, or a byte that is not valid UTF-8.
        for bad in [
            &b"user.a=b"[..],
            b"user.a\nb",
            b"user.a\0b",
            b"",
            b"user.\xff",
        ] {
            assert!(
                matches!(
                    pax_xattr_key(b"/f", bad),
                    Err(ArchiveError::XattrNameUnrepresentable { .. })
                ),
                "name {bad:?} must be refused"
            );
        }
    }

    #[test]
    fn a_pax_time_is_the_instant_it_names() {
        assert_eq!(pax_time(Timestamp::from_secs(1_700_000_000)), "1700000000");
        assert_eq!(
            pax_time(Timestamp {
                secs: 1_700_000_000,
                nanos: 123_456_789
            }),
            "1700000000.123456789"
        );
        // A negative time stores the floored second and the fraction up to the next one;
        // the decimal form is the instant itself.
        assert_eq!(
            pax_time(Timestamp {
                secs: -6,
                nanos: 750_000_000
            }),
            "-5.250000000"
        );
        // Inside the last second before the epoch there is no negative whole part, so the
        // sign is written onto the zero.
        assert_eq!(
            pax_time(Timestamp {
                secs: -1,
                nanos: 500_000_000
            }),
            "-0.500000000"
        );
        assert_eq!(pax_time(Timestamp::from_secs(-1)), "-1");
    }

    #[test]
    fn a_pax_time_carries_an_over_long_fraction_into_the_seconds() {
        // A filesystem's stored fraction need not divide a second, so an image this crate
        // did not write can name more nanoseconds than a second holds. The record still
        // names the instant the two fields describe, with a nine-digit fraction: writing the
        // raw value would make a ten-digit one, which a reader scales as a tenth of what was
        // meant.
        assert_eq!(
            pax_time(Timestamp {
                secs: 100,
                nanos: 1_073_741_823 // the largest ext4's field holds
            }),
            "101.073741823"
        );
        // The same on the negative side, where the fraction is written as the distance to
        // the next second — the subtraction that an over-long fraction would otherwise
        // take below zero.
        assert_eq!(
            pax_time(Timestamp {
                secs: -6,
                nanos: 1_073_741_823
            }),
            "-4.926258177"
        );
        // A whole number of extra seconds leaves no fraction at all.
        assert_eq!(
            pax_time(Timestamp {
                secs: 10,
                nanos: 2_000_000_000
            }),
            "12"
        );
    }
}