ostrya 0.17.0

Pure-Rust async reimplementation of the ostree repository library
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
//! The read primitives: the open of a regular file, of a root file, and of a
//! loose object, the capped reads, the symlink targets, the status of an
//! entry, the extended attributes, and the fs-verity digest.
//!
//! Each open of a path below a [`RepoDir`] is one `openat2` with
//! `RESOLVE_BENEATH|RESOLVE_NO_SYMLINKS`, as in the directory primitives,
//! with two exceptions. The open of a keyring file by
//! [`open_root_file`](RepoDir::open_root_file) is a plain `openat` that
//! follows a symlink. [`link_xattrs`](RepoDir::link_xattrs) opens the parent
//! directory with `openat2`, and then reaches the leaf through
//! `/proc/self/fd`. The path rules of the directory primitives apply.
//! [`link_xattrs_at`] reads an entry of a tree outside the repository below a
//! plain descriptor, with no path rule. A regular file opens with
//! `O_NONBLOCK`, so the open of a FIFO does not wait for a writer. One `statx`
//! on the open descriptor then refuses each entry that is not a regular file.
//!
//! Each read has a cap. A read of file content has the cap of the caller, and
//! a symlink target has the cap of the caller or a fixed cap. For
//! [`xattrs`], [`link_xattrs`](RepoDir::link_xattrs), and [`link_xattrs_at`],
//! the cap applies to the list of names and to each value, and not to their
//! sum. It is the limit of the kernel for each of them, 64 KiB.

use std::ffi::CStr;
use std::fs::File;
use std::io::{self, Read, Seek, SeekFrom};
use std::mem::MaybeUninit;
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::path::{Path, PathBuf};

use ostrya_core::Xattrs;
use rustix::fs::{AtFlags, FileType, Mode, OFlags, StatxFlags};
use rustix::io::Errno;

use super::dir::{BENEATH, DIR_OPEN, io_error, is_component, require};
use super::{
    FsError, ObjectEntry, Opened, Reason, RepoDir, RepoLayout, RootFile, STAT_FIELDS, Stat,
    stat_fd, stat_from_statx,
};

/// The flags of the open of a regular file. `O_NOFOLLOW` refuses a symlink at
/// the leaf, and `O_NONBLOCK` keeps the open of a FIFO from waiting for a
/// writer. The flag changes no read of a regular file.
const FILE_OPEN: OFlags = OFlags::RDONLY
    .union(OFlags::NOFOLLOW)
    .union(OFlags::NONBLOCK)
    .union(OFlags::NOCTTY)
    .union(OFlags::CLOEXEC);

/// The flags of the open of a keyring file at the root. They are the flags of
/// [`FILE_OPEN`] with no `O_NOFOLLOW`, because a keyring file can be a
/// symlink.
pub(super) const KEYRING_OPEN: OFlags = OFlags::RDONLY
    .union(OFlags::NONBLOCK)
    .union(OFlags::NOCTTY)
    .union(OFlags::CLOEXEC);

/// The flags of the open of an entry itself. With `O_PATH|O_NOFOLLOW`, a
/// symlink at the leaf opens as the symlink, also with
/// `RESOLVE_NO_SYMLINKS`.
const LINK_OPEN: OFlags = OFlags::PATH.union(OFlags::NOFOLLOW).union(OFlags::CLOEXEC);

/// The size of the first buffer of an xattr list or value.
const XATTR_BUF_START: usize = 256;

/// The maximum size of an xattr list or value. It is the limit of the kernel.
const XATTR_MAX: usize = 64 * 1024;

/// The cap of the target of a symlink object, in bytes. It is `PATH_MAX`
/// with no terminating NUL.
const OBJECT_LINK_CAP: u64 = 4095;

/// The size of the stack buffer of a symlink read. It is `PATH_MAX`, one byte
/// more than the longest symlink target on Linux.
const LINK_STACK_LEN: usize = 4096;

/// The maximum number of passes of [`read_grown`].
const GROW_PASSES: usize = 4;

impl RepoDir {
    /// Opens the regular file at `path` below this handle for read, and gives
    /// the file and its status.
    ///
    /// The open is one `openat2`, and its descriptor keeps `O_NONBLOCK`. The
    /// errors of the open are those of
    /// [`open_dir`](RepoDir::open_dir): a symlink at a component, also at the
    /// leaf, gives [`Reason::Symlink`], and a `..`, `.`, or empty component or
    /// an absolute path gives [`Reason::Escape`]. An absent entry gives
    /// [`FsError::Absent`].
    ///
    /// An entry that is not a regular file gives [`Reason::NotRegular`] with
    /// its type. A FIFO and a directory open, and the `statx` on the
    /// descriptor refuses them. A socket and a device with no driver do not
    /// open, so the function reads their type with
    /// [`lstat`](RepoDir::lstat).
    pub(crate) fn open_regular(&self, path: &str) -> Result<Opened, FsError> {
        self.check_path(path)?;
        match rustix::fs::openat2(self, path, FILE_OPEN, Mode::empty(), BENEATH) {
            Ok(fd) => self.finish(fd, path),
            Err(e) => Err(self.open_error(e, path)),
        }
    }

    /// Opens the root file `file` for read, and gives the file and its
    /// status. The call is on the root handle.
    ///
    /// Each root file other than a keyring opens as
    /// [`open_regular`](RepoDir::open_regular) opens it, so a symlink at it
    /// gives [`Reason::Symlink`].
    ///
    /// A keyring file can be a symlink, also to a path outside the
    /// repository. Its open is one `openat` that follows each symlink. A name
    /// that is not one path component gives [`Reason::Escape`]. An absent
    /// file gives [`FsError::Absent`]. An entry that is not a regular file
    /// gives [`Reason::NotRegular`] with its type: for a socket and a device
    /// with no driver, one `statx` that follows the symlink reads the type.
    /// Each other errno, also `ELOOP` and `ENOTDIR`, gives [`FsError::Io`].
    ///
    /// A call on a handle other than the root is a defect of the caller: it
    /// fails a debug assertion, and gives an `InvalidInput` error in a release
    /// build.
    #[cfg_attr(not(feature = "verify-gpg"), allow(dead_code))]
    pub(crate) fn open_root_file(&self, file: RootFile) -> Result<Opened, FsError> {
        require(
            (self.kind == RepoLayout::Root).then_some(()),
            "open_root_file needs the root handle",
        )?;
        let RootFile::Keyring(name) = &file else {
            return self.open_regular(file.name());
        };
        if !is_component(name.as_bytes()) {
            return Err(FsError::Invalid {
                path: self.err_path(name),
                reason: Reason::Escape,
            });
        }
        match rustix::fs::openat(self, name.as_str(), KEYRING_OPEN, Mode::empty()) {
            Ok(fd) => self.finish(fd, name),
            Err(Errno::NOENT) => Err(FsError::Absent {
                path: self.err_path(name),
            }),
            Err(e @ (Errno::NXIO | Errno::NODEV)) => {
                Err(followed_type_error(self.as_fd(), name.as_str(), e, || {
                    self.err_path(name)
                }))
            }
            Err(e) => Err(io_error(e)),
        }
    }

    /// Opens the loose object at `path` below this handle, and gives a
    /// regular file with its status, or the target of a symlink object. The
    /// call is on a handle of kind [`RepoLayout::Objects`] or
    /// [`RepoLayout::Staging`].
    ///
    /// The function first opens the path as
    /// [`open_regular`](RepoDir::open_regular) does. When the open gives
    /// `ELOOP`, a second `openat2` with `O_PATH|O_NOFOLLOW` opens a symlink at
    /// the leaf as the symlink, and the function reads its target with a cap
    /// of 4095 bytes. A longer target gives [`Reason::TooLarge`]. A symlink at
    /// a component before the leaf fails the second open too, and gives
    /// [`Reason::Symlink`]. An entry that is no longer a symlink at the read
    /// of the target gives [`FsError::Io`] with `EINVAL`.
    ///
    /// The other errors are those of [`open_regular`](RepoDir::open_regular).
    /// A call on a handle of another kind is a defect of the caller.
    pub(crate) fn open_object(&self, path: &str) -> Result<ObjectEntry, FsError> {
        require(
            matches!(self.kind, RepoLayout::Objects | RepoLayout::Staging).then_some(()),
            "open_object needs an objects handle or a staging handle",
        )?;
        self.check_path(path)?;
        match rustix::fs::openat2(self, path, FILE_OPEN, Mode::empty(), BENEATH) {
            Ok(fd) => self.finish(fd, path).map(ObjectEntry::Regular),
            Err(Errno::LOOP) => {
                let fd = self.open_link(path)?;
                self.read_link_fd(fd.as_fd(), path, OBJECT_LINK_CAP)
                    .map(ObjectEntry::Symlink)
            }
            Err(e) => Err(self.open_error(e, path)),
        }
    }

    /// Reads the whole regular file at `path` below this handle. The file has
    /// `cap` bytes at most.
    ///
    /// The open and its errors are those of
    /// [`open_regular`](RepoDir::open_regular). A file with a size over `cap`
    /// gives [`Reason::TooLarge`] before the read. The read stops after
    /// `cap + 1` bytes, so a file that grows after the `statx` also gives
    /// [`Reason::TooLarge`]. A buffer of the size of the file that cannot be
    /// allocated gives an `OutOfMemory` error. An error of the read gives
    /// [`FsError::Io`].
    pub(crate) fn read_capped(&self, path: &str, cap: u64) -> Result<Vec<u8>, FsError> {
        let Opened { file, stat } = self.open_regular(path)?;
        let too_large = || FsError::Invalid {
            path: self.err_path(path),
            reason: Reason::TooLarge { cap },
        };
        if stat.size > cap {
            return Err(too_large());
        }
        let mut buf = Vec::new();
        buf.try_reserve_exact(usize::try_from(stat.size).unwrap_or(usize::MAX))
            .map_err(|_| FsError::Io(io::ErrorKind::OutOfMemory.into()))?;
        (&file)
            .take(cap.saturating_add(1))
            .read_to_end(&mut buf)
            .map_err(FsError::Io)?;
        if buf.len() as u64 > cap {
            return Err(too_large());
        }
        Ok(buf)
    }

    /// Opens the regular file at `path` below this handle for read, at the
    /// position `offset`, and gives the file and its status.
    ///
    /// The open and its errors are those of
    /// [`open_regular`](RepoDir::open_regular). A positive `offset` costs one
    /// seek, and an error of the seek gives [`FsError::Io`].
    pub(crate) fn open_regular_at(&self, path: &str, offset: u64) -> Result<Opened, FsError> {
        let mut opened = self.open_regular(path)?;
        if offset > 0 {
            opened
                .file
                .seek(SeekFrom::Start(offset))
                .map_err(FsError::Io)?;
        }
        Ok(opened)
    }

    /// Reads the target of the symlink at `path` below this handle. The
    /// target has `cap` bytes at most.
    ///
    /// A `path` of one component costs one `readlinkat` relative to this
    /// handle. The path has no directory component to resolve, and the
    /// `readlinkat` does not follow the leaf. An absent entry gives
    /// [`FsError::Absent`], and each other errno maps by [`FsError::at`] with
    /// `path`.
    ///
    /// For a longer `path`, one `openat2` with `O_PATH|O_NOFOLLOW` opens the
    /// symlink itself, and a `readlinkat` on its descriptor reads the target.
    /// The path rules and the errors of the open are those of
    /// [`open_dir`](RepoDir::open_dir). A symlink at a component before the
    /// leaf gives [`Reason::Symlink`].
    ///
    /// The `readlinkat` reads the target into a stack buffer of `cap + 1`
    /// bytes, or of 4096 bytes for a larger cap. A symlink target on Linux
    /// has 4095 bytes at most, so the cap in effect is the smaller of `cap`
    /// and 4095. A target over that cap gives [`Reason::TooLarge`]. An entry
    /// that is not a symlink gives [`FsError::Io`] with `EINVAL`.
    pub(crate) fn read_link(&self, path: &str, cap: u64) -> Result<Vec<u8>, FsError> {
        self.check_path(path)?;
        if !path.contains('/') {
            return self.read_link_at(self.as_fd(), path, path, cap, |e| {
                FsError::at(e, self.err_path(path))
            });
        }
        let fd = self.open_link(path)?;
        self.read_link_fd(fd.as_fd(), path, cap)
    }

    /// Returns the status of the entry at `path` below this handle. A
    /// symlink at the leaf gives the status of the symlink itself.
    ///
    /// A `path` of one component costs one `statx` with
    /// `AT_SYMLINK_NOFOLLOW` relative to this handle. The path has no
    /// directory component to resolve, and the `statx` does not follow the
    /// leaf. Its errno maps by [`FsError::at`] with `path`.
    ///
    /// A longer `path` costs one `openat2` with `O_PATH|O_NOFOLLOW`, one
    /// `statx` on the descriptor, and one `close`. The path rules and the
    /// errors of the open are those of [`open_dir`](RepoDir::open_dir). A
    /// symlink at a component before the leaf gives [`Reason::Symlink`]. An
    /// error of the `statx` gives [`FsError::Io`].
    pub(crate) fn lstat(&self, path: &str) -> Result<Stat, FsError> {
        self.check_path(path)?;
        if !path.contains('/') {
            return rustix::fs::statx(self, path, AtFlags::SYMLINK_NOFOLLOW, STAT_FIELDS)
                .map(|stx| stat_from_statx(&stx))
                .map_err(|e| FsError::at(e, self.err_path(path)));
        }
        let fd = self.open_link(path)?;
        stat_fd(fd.as_fd())
    }

    /// Returns `true` if an entry exists at `path` below this handle. A
    /// symlink at the leaf exists, also when its target does not.
    ///
    /// A `path` of one component costs one `statx` with
    /// `AT_SYMLINK_NOFOLLOW`, as in [`lstat`](RepoDir::lstat). A longer
    /// `path` costs one `openat2` with `O_PATH|O_NOFOLLOW` and one `close`.
    /// An absent entry gives `false`. Each other error stays an error, as in
    /// [`lstat`](RepoDir::lstat): a symlink at a component before the leaf
    /// gives [`Reason::Symlink`], and a file there gives
    /// [`Reason::NotDirectory`].
    pub(crate) fn exists(&self, path: &str) -> Result<bool, FsError> {
        self.check_path(path)?;
        let found = if path.contains('/') {
            rustix::fs::openat2(self, path, LINK_OPEN, Mode::empty(), BENEATH).map(drop)
        } else {
            rustix::fs::statx(self, path, AtFlags::SYMLINK_NOFOLLOW, StatxFlags::TYPE).map(drop)
        };
        match found {
            Ok(()) => Ok(true),
            Err(Errno::NOENT) => Ok(false),
            Err(e) => Err(FsError::at(e, self.err_path(path))),
        }
    }

    /// Returns the extended attributes of the entry at `path` below this
    /// handle. A symlink at the leaf gives the attributes of the symlink
    /// itself.
    ///
    /// One `openat2` opens the parent directory of the leaf, with the path
    /// rules and the errors of [`open_dir`](RepoDir::open_dir). The leaf is
    /// read through `/proc/self/fd` with `llistxattr` and `lgetxattr`, which
    /// do not follow a symlink. An `ENOENT` from them also comes when `/proc`
    /// is not mounted or is of another PID namespace, so one `statx` of the
    /// leaf with `AT_SYMLINK_NOFOLLOW` then makes sure that the leaf is
    /// absent. An absent leaf gives [`FsError::Absent`]. A leaf that the
    /// `statx` finds gives [`FsError::Io`] with a message that names
    /// `/proc/self/fd`. A
    /// file system with no xattr support gives an empty set. An attribute
    /// that is removed between the list and the read of its value is left
    /// out. Each other error gives [`FsError::Io`]. The rules of
    /// [`xattrs`] for the size and the names apply.
    pub(crate) fn link_xattrs(&self, path: &str) -> Result<Xattrs, FsError> {
        self.check_path(path)?;
        let (parent, leaf) = match path.rsplit_once('/') {
            Some((parent, leaf)) => {
                let fd = rustix::fs::openat2(self, parent, DIR_OPEN, Mode::empty(), BENEATH)
                    .map_err(|e| FsError::at(e, self.err_path(parent)))?;
                (Some(fd), leaf)
            }
            None => (None, path),
        };
        let dir = parent.as_ref().map_or(self.as_fd(), AsFd::as_fd);
        let link = format!("/proc/self/fd/{}/{leaf}", dir.as_raw_fd());
        proc_xattrs(Path::new(&link), |e| self.link_error(e, dir, leaf, path))
    }

    /// Returns the error of `errno` from an xattr call on the leaf `leaf` of
    /// the directory open at `dir`, through `/proc/self/fd`. `path` is the
    /// path of the leaf below this handle.
    ///
    /// For `ENOENT`, one `statx` of the leaf with `AT_SYMLINK_NOFOLLOW` makes
    /// sure that the leaf is absent, and then gives [`FsError::Absent`]. A
    /// leaf that the `statx` finds gives [`FsError::Io`] with a message that
    /// names `/proc/self/fd`. An error of the `statx` and each other errno
    /// give [`FsError::Io`].
    fn link_error(&self, errno: Errno, dir: BorrowedFd<'_>, leaf: &str, path: &str) -> FsError {
        if errno != Errno::NOENT {
            return io_error(errno);
        }
        match rustix::fs::statx(dir, leaf, AtFlags::SYMLINK_NOFOLLOW, StatxFlags::TYPE) {
            Err(Errno::NOENT) => FsError::Absent {
                path: self.err_path(path),
            },
            Err(e) => io_error(e),
            Ok(_) => proc_hidden(self.err_path(path)),
        }
    }

    /// Opens the entry at `path` below this handle itself, with
    /// `O_PATH|O_NOFOLLOW`. The caller checks `path`.
    fn open_link(&self, path: &str) -> Result<OwnedFd, FsError> {
        rustix::fs::openat2(self, path, LINK_OPEN, Mode::empty(), BENEATH)
            .map_err(|e| FsError::at(e, self.err_path(path)))
    }

    /// Reads the target of the symlink open at `fd` with `O_PATH|O_NOFOLLOW`.
    /// The target has `cap` bytes at most. `path` is the path of the symlink
    /// below this handle, for an error.
    ///
    /// `ENOENT` from the `readlinkat` means that the entry is not a symlink,
    /// and gives `EINVAL`. The read is that of
    /// [`read_link_at`](RepoDir::read_link_at).
    fn read_link_fd(&self, fd: BorrowedFd<'_>, path: &str, cap: u64) -> Result<Vec<u8>, FsError> {
        self.read_link_at(fd, c"", path, cap, |e| {
            io_error(if e == Errno::NOENT { Errno::INVAL } else { e })
        })
    }

    /// Reads the target of the symlink `name` relative to `dir` with one
    /// `readlinkat`. The target has `cap` bytes at most. `path` is the path of
    /// the symlink below this handle, for an error, and `map` converts the
    /// errno of the `readlinkat`.
    ///
    /// The read goes into a stack buffer of `cap + 1` bytes, or of 4096 bytes
    /// for a larger cap, and the target then costs one allocation of its own
    /// size. A target that fills the buffer is over `cap`, or has 4096 bytes
    /// or more, and gives [`Reason::TooLarge`].
    fn read_link_at<P: rustix::path::Arg>(
        &self,
        dir: BorrowedFd<'_>,
        name: P,
        path: &str,
        cap: u64,
        map: impl FnOnce(Errno) -> FsError,
    ) -> Result<Vec<u8>, FsError> {
        let mut stack = [MaybeUninit::<u8>::uninit(); LINK_STACK_LEN];
        let len = usize::try_from(cap)
            .ok()
            .filter(|&c| c < LINK_STACK_LEN)
            .map_or(LINK_STACK_LEN, |c| c + 1);
        let (target, _) = rustix::fs::readlinkat_raw(dir, name, &mut stack[..len]).map_err(map)?;
        if target.len() == len {
            return Err(FsError::Invalid {
                path: self.err_path(path),
                reason: Reason::TooLarge { cap },
            });
        }
        Ok(target.to_vec())
    }

    /// Gives the file open at `fd` and its status, or [`Reason::NotRegular`]
    /// if the file is not a regular file. `path` is the path of the file
    /// below this handle, for an error.
    pub(super) fn finish(&self, fd: OwnedFd, path: &str) -> Result<Opened, FsError> {
        let stat = stat_fd(fd.as_fd())?;
        if stat.file_type != FileType::RegularFile {
            return Err(FsError::Invalid {
                path: self.err_path(path),
                reason: Reason::NotRegular(stat.file_type),
            });
        }
        Ok(Opened {
            file: File::from(fd),
            stat,
        })
    }

    /// Returns the error of `errno` from the open of the regular file at
    /// `path` below this handle.
    ///
    /// `ENXIO` and `ENODEV` come from a socket and a device with no driver.
    /// For them, [`lstat`](RepoDir::lstat) reads the type: an entry that is
    /// not a regular file gives [`Reason::NotRegular`], a regular file gives
    /// [`FsError::Io`] with `errno`, and an error of the `lstat` stays as it
    /// is. Each other errno gives the result of [`FsError::at`].
    pub(super) fn open_error(&self, errno: Errno, path: &str) -> FsError {
        if !matches!(errno, Errno::NXIO | Errno::NODEV) {
            return FsError::at(errno, self.err_path(path));
        }
        match self.lstat(path) {
            Ok(stat) if stat.file_type != FileType::RegularFile => FsError::Invalid {
                path: self.err_path(path),
                reason: Reason::NotRegular(stat.file_type),
            },
            Ok(_) => io_error(errno),
            Err(e) => e,
        }
    }
}

/// Returns the error of `errno`, `ENXIO` or `ENODEV`, from an open of `path`
/// relative to `base` that follows each symlink.
///
/// A socket and a device with no driver give these errnos. One `statx` that
/// follows each symlink reads the type: an entry that is not a regular file
/// gives [`Reason::NotRegular`] with the path from `err_path`, and a regular
/// file gives [`FsError::Io`] with `errno`. An error of the `statx` gives
/// [`FsError::Io`].
pub(super) fn followed_type_error<P: rustix::path::Arg>(
    base: BorrowedFd<'_>,
    path: P,
    errno: Errno,
    err_path: impl FnOnce() -> String,
) -> FsError {
    match rustix::fs::statx(base, path, AtFlags::empty(), StatxFlags::TYPE) {
        Ok(stx) => match FileType::from_raw_mode(u32::from(stx.stx_mode)) {
            FileType::RegularFile => io_error(errno),
            other => FsError::Invalid {
                path: err_path(),
                reason: Reason::NotRegular(other),
            },
        },
        Err(e) => io_error(e),
    }
}

/// Returns the extended attributes of the file open at `fd`.
///
/// The set is canonical, and each name keeps its terminating NUL, as in the
/// storage form of [`Xattrs`]. A name need not be UTF-8. The function reads
/// the list of names with `flistxattr` and each value with `fgetxattr`. Each
/// buffer starts at 256 bytes and grows to the size that the kernel gives,
/// to 64 KiB at most: a larger list or value gives [`FsError::Io`] with
/// `E2BIG`. One buffer serves the read of all values. A file system with no
/// xattr support gives an empty set. An attribute that is removed between
/// the list and the read of its value is left out. Each error gives
/// [`FsError::Io`]. A set that [`Xattrs::new`] refuses gives an
/// `InvalidData` error.
pub(crate) fn xattrs(fd: BorrowedFd<'_>) -> Result<Xattrs, FsError> {
    let mut list = Vec::new();
    let len = match read_grown(&mut list, |buf| rustix::fs::flistxattr(fd, buf)) {
        Ok(len) => len,
        Err(Errno::NOTSUP) => return Ok(Xattrs::empty()),
        Err(e) => return Err(io_error(e)),
    };
    collect_xattrs(
        &list[..len],
        |name, buf| read_grown(buf, |b| rustix::fs::fgetxattr(fd, name, b)),
        io_error,
    )
}

/// Returns the value of the extended attribute `name` of the file open at
/// `fd`, or `None` if the file has no such attribute.
///
/// A file system with no xattr support gives `None`. The buffer starts at 256
/// bytes and grows to the size that the kernel gives, to 64 KiB at most: a
/// larger value gives [`FsError::Io`] with `E2BIG`. Each other error gives
/// [`FsError::Io`].
pub(crate) fn xattr(fd: BorrowedFd<'_>, name: &str) -> Result<Option<Vec<u8>>, FsError> {
    let mut value = Vec::new();
    match read_grown(&mut value, |buf| rustix::fs::fgetxattr(fd, name, buf)) {
        Ok(len) => {
            value.truncate(len);
            Ok(Some(value))
        }
        Err(Errno::NODATA | Errno::NOTSUP) => Ok(None),
        Err(e) => Err(io_error(e)),
    }
}

/// Returns the extended attributes of the entry `name` below the directory
/// open at `dir`, in a tree outside the repository, for example the source
/// tree of a commit. A symlink at the leaf gives the attributes of the
/// symlink itself.
///
/// The reads are those of [`link_xattrs`](RepoDir::link_xattrs), through
/// `/proc/self/fd/<dir>/<name>`, with no path rule. `name` can have more than
/// one component, and the kernel follows a symlink at a component before the
/// leaf. For an `ENOENT` of the reads, one `statx` of the leaf with
/// `AT_SYMLINK_NOFOLLOW` checks the leaf. A leaf that exists gives
/// [`FsError::Io`] with a message that names `/proc/self/fd`. Each other
/// error, also an absent leaf, gives [`FsError::Io`] with the errno of the
/// xattr call. The rules of [`xattrs`] for the size and the names apply.
pub(crate) fn link_xattrs_at(dir: BorrowedFd<'_>, name: &Path) -> Result<Xattrs, FsError> {
    let mut link = PathBuf::from(format!("/proc/self/fd/{}", dir.as_raw_fd()));
    link.push(name);
    let found = || rustix::fs::statx(dir, name, AtFlags::SYMLINK_NOFOLLOW, StatxFlags::TYPE);
    proc_xattrs(&link, |e| match e {
        Errno::NOENT if found().is_ok() => proc_hidden(name.display()),
        e => io_error(e),
    })
}

/// Returns the extended attributes of the entry at `link`, a path through
/// `/proc/self/fd`, with `llistxattr` and `lgetxattr`. A file system with no
/// xattr support gives an empty set. `map` gives the error of each other
/// errno of the two calls.
fn proc_xattrs(link: &Path, map: impl Fn(Errno) -> FsError) -> Result<Xattrs, FsError> {
    let mut list = Vec::new();
    let len = match read_grown(&mut list, |buf| rustix::fs::llistxattr(link, buf)) {
        Ok(len) => len,
        Err(Errno::NOTSUP) => return Ok(Xattrs::empty()),
        Err(e) => return Err(map(e)),
    };
    collect_xattrs(
        &list[..len],
        |name, buf| read_grown(buf, |b| rustix::fs::lgetxattr(link, name, b)),
        map,
    )
}

/// Returns the error of an xattr read of `path` through `/proc/self/fd` that
/// gives `ENOENT` for an entry that exists.
fn proc_hidden(path: impl std::fmt::Display) -> FsError {
    FsError::Io(io::Error::new(
        io::ErrorKind::NotFound,
        format!(
            "the xattr read of {path} through /proc/self/fd gives ENOENT, but \
             the entry exists: /proc is not mounted or is of another PID \
             namespace"
        ),
    ))
}

/// Returns the fs-verity digest that the kernel holds for the file open at
/// `fd`, or `None`.
///
/// The file must be sealed with SHA-256, 4096-byte blocks, no salt, and a
/// data size of `size`. Each other file, each error, and each mismatch gives
/// `None`. The function issues two ioctls, so a caller calls it only for a
/// file that the `statx` reports as sealed ([`Stat::verity`]).
pub(crate) fn verity_digest(fd: BorrowedFd<'_>, size: u64) -> Option<[u8; 32]> {
    let desc = ostrya_sys::read_verity_descriptor(fd).ok()?;
    if desc.hash_algorithm != 1
        || desc.log_blocksize != 12
        || desc.salt_size != 0
        || desc.data_size != size
    {
        return None;
    }
    ostrya_sys::measure_verity(fd).ok()
}

/// Calls `call` with `buf` until the buffer holds the whole result, and gives
/// the length of the result. The result is `buf[..len]`.
///
/// An empty `buf` starts at 256 bytes. When `call` gives `ERANGE`, a call with
/// an empty buffer gives the size of the result, and `buf` grows to that
/// size exactly. A size over 64 KiB gives `E2BIG`. A result that grows
/// between the two calls causes one more pass. The function makes 4 passes
/// at most: `ERANGE` in the fourth pass gives `ERANGE`. `buf` keeps its
/// length, so a caller can use it again with no new allocation.
fn read_grown(
    buf: &mut Vec<u8>,
    mut call: impl FnMut(&mut [u8]) -> Result<usize, Errno>,
) -> Result<usize, Errno> {
    if buf.is_empty() {
        buf.resize(XATTR_BUF_START, 0);
    }
    let mut pass = 1;
    loop {
        match call(buf) {
            Err(Errno::RANGE) if pass < GROW_PASSES => {}
            other => return other,
        }
        let size = call(&mut [])?;
        if size > XATTR_MAX {
            return Err(Errno::TOOBIG);
        }
        if size > buf.len() {
            buf.reserve_exact(size - buf.len());
            buf.resize(size, 0);
        }
        pass += 1;
    }
}

/// Builds the set of the attributes in `list`, a list of names that each end
/// with a NUL.
///
/// `get` reads the value of a name into the buffer that it gets, and gives
/// the length of the value. `ENODATA` leaves the name out, and `map` gives
/// the error of each other errno. One buffer serves all values.
fn collect_xattrs(
    list: &[u8],
    mut get: impl FnMut(&CStr, &mut Vec<u8>) -> Result<usize, Errno>,
    map: impl Fn(Errno) -> FsError,
) -> Result<Xattrs, FsError> {
    let mut pairs = Vec::with_capacity(list.iter().filter(|&&b| b == 0).count());
    let mut value = Vec::new();
    for name in list.split_inclusive(|&b| b == 0) {
        let Ok(c_name) = CStr::from_bytes_with_nul(name) else {
            return Err(FsError::Io(io::Error::new(
                io::ErrorKind::InvalidData,
                "an xattr name of the list does not end with a NUL",
            )));
        };
        match get(c_name, &mut value) {
            Ok(len) => pairs.push((name.to_vec(), value[..len].to_vec())),
            Err(Errno::NODATA) => {}
            Err(e) => return Err(map(e)),
        }
    }
    Xattrs::new(pairs).map_err(|e| FsError::Io(io::Error::new(io::ErrorKind::InvalidData, e)))
}

#[cfg(test)]
mod tests {
    use std::fmt::Debug;
    use std::os::unix::fs::symlink;
    use std::os::unix::net::UnixListener;

    use ostrya_composefs::FsVerityHasher;
    use rustix::fs::XattrFlags;

    use super::super::{TestDir, invalid, io_err, mkfifo, root, without_block};
    use super::*;

    /// Makes `objects/ab` in `dir`, and returns a handle of `objects/`.
    fn objects(dir: &TestDir) -> RepoDir {
        std::fs::create_dir_all(dir.path().join("objects/ab")).unwrap();
        root(dir).open_layout(RepoLayout::Objects).unwrap()
    }

    /// Returns the path and the file type of a `NotRegular` error.
    fn not_regular<T: Debug>(result: Result<T, FsError>) -> (String, FileType) {
        match invalid(result) {
            (path, Reason::NotRegular(file_type)) => (path, file_type),
            other => panic!("{other:?}"),
        }
    }

    /// Returns the path of an `Absent` error.
    fn absent<T: Debug>(result: Result<T, FsError>) -> String {
        match result {
            Err(FsError::Absent { path }) => path,
            other => panic!("{other:?}"),
        }
    }

    /// Returns the content of `file` from its position.
    fn content(mut file: &File) -> Vec<u8> {
        let mut buf = Vec::new();
        file.read_to_end(&mut buf).unwrap();
        buf
    }

    /// Sets the xattr `name` of the file open at `fd`. It gives `false` if the
    /// file system has no support for user xattrs.
    fn set_xattr(fd: BorrowedFd<'_>, name: &str, value: &[u8]) -> bool {
        match rustix::fs::fsetxattr(fd, name, value, XattrFlags::empty()) {
            Ok(()) => true,
            Err(Errno::NOTSUP) => false,
            Err(e) => panic!("fsetxattr {name}: {e}"),
        }
    }

    #[test]
    fn a_fifo_gives_not_regular_and_does_not_block() {
        let dir = TestDir::new("read-fifo");
        let objects = objects(&dir);
        let fifo = dir.path().join("objects/ab/cd.file");
        mkfifo(&fifo);
        let handle = objects.clone();
        let results = without_block(&fifo, move || {
            [
                handle.open_regular("ab/cd.file").map(drop),
                handle.read_capped("ab/cd.file", 16).map(drop),
                handle.open_regular_at("ab/cd.file", 4).map(drop),
                handle.open_object("ab/cd.file").map(drop),
            ]
        });
        for result in results {
            let (path, file_type) = not_regular(result);
            assert_eq!(path, "objects/ab/cd.file");
            assert_eq!(file_type, FileType::Fifo);
        }
    }

    #[test]
    fn a_socket_a_device_or_a_directory_gives_not_regular() {
        let dir = TestDir::new("read-special");
        let objects = objects(&dir);
        let ab = dir.path().join("objects/ab");
        let _listener = UnixListener::bind(ab.join("sock.file")).unwrap();
        std::fs::create_dir(ab.join("dir.file")).unwrap();
        let mut cases = vec![
            ("sock.file", FileType::Socket),
            ("dir.file", FileType::Directory),
        ];
        // A whiteout is a character device 0:0. Its create needs no
        // privilege, and its open gives `ENXIO`. A `nodev` mount, and a file
        // system that a user namespace mounts, refuse the open with `EACCES`
        // before the type check.
        let dev = ab.join("dev.file");
        match rustix::fs::mknodat(
            rustix::fs::CWD,
            &dev,
            FileType::CharacterDevice,
            Mode::from_raw_mode(0o600),
            rustix::fs::makedev(0, 0),
        ) {
            Ok(()) => match rustix::fs::open(
                &dev,
                OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
                Mode::empty(),
            ) {
                Err(Errno::ACCESS) => {
                    eprintln!("skipping the device case: the open of a device gives EACCES");
                }
                _ => cases.push(("dev.file", FileType::CharacterDevice)),
            },
            Err(e) => eprintln!("skipping the device case: mknod gives {e}"),
        }
        for (name, expected) in cases {
            let path = format!("ab/{name}");
            let results = [
                objects.open_regular(&path).map(drop),
                objects.read_capped(&path, 16).map(drop),
                objects.open_regular_at(&path, 1).map(drop),
                objects.open_object(&path).map(drop),
            ];
            for result in results {
                let (err_path, file_type) = not_regular(result);
                assert_eq!(err_path, format!("objects/{path}"));
                assert_eq!(file_type, expected, "{name}");
            }
        }
    }

    #[test]
    fn open_regular_refuses_a_symlink_and_gives_absent_for_a_missing_file() {
        let dir = TestDir::new("read-regular");
        let objects = objects(&dir);
        let ab = dir.path().join("objects/ab");
        std::fs::write(ab.join("file"), b"content").unwrap();
        symlink("file", ab.join("link")).unwrap();

        let opened = objects.open_regular("ab/file").unwrap();
        assert_eq!(opened.stat.file_type, FileType::RegularFile);
        assert_eq!(opened.stat.size, 7);
        assert_eq!(content(&opened.file), b"content");

        let (path, reason) = invalid(objects.open_regular("ab/link"));
        assert_eq!(path, "objects/ab/link");
        assert!(matches!(reason, Reason::Symlink), "{reason:?}");
        assert_eq!(absent(objects.open_regular("ab/none")), "objects/ab/none");
        let (path, reason) = invalid(objects.open_regular("ab/file/x"));
        assert_eq!(path, "objects/ab/file/x");
        assert!(matches!(reason, Reason::NotDirectory), "{reason:?}");
    }

    #[test]
    fn read_capped_reads_a_file_of_cap_bytes_and_refuses_one_more() {
        let dir = TestDir::new("read-capped");
        let objects = objects(&dir);
        let ab = dir.path().join("objects/ab");
        std::fs::write(ab.join("ten"), b"0123456789").unwrap();
        std::fs::write(ab.join("empty"), b"").unwrap();

        assert_eq!(objects.read_capped("ab/ten", 10).unwrap(), b"0123456789");
        assert_eq!(
            objects.read_capped("ab/ten", u64::MAX).unwrap(),
            b"0123456789"
        );
        let (path, reason) = invalid(objects.read_capped("ab/ten", 9));
        assert_eq!(path, "objects/ab/ten");
        assert!(matches!(reason, Reason::TooLarge { cap: 9 }), "{reason:?}");
        assert!(objects.read_capped("ab/empty", 0).unwrap().is_empty());
        assert_eq!(
            absent(objects.read_capped("ab/none", 10)),
            "objects/ab/none"
        );
    }

    #[test]
    fn open_regular_at_starts_at_the_offset() {
        let dir = TestDir::new("read-at");
        let objects = objects(&dir);
        std::fs::write(dir.path().join("objects/ab/ten"), b"0123456789").unwrap();

        let opened = objects.open_regular_at("ab/ten", 0).unwrap();
        assert_eq!(opened.stat.size, 10);
        assert_eq!(content(&opened.file), b"0123456789");
        let opened = objects.open_regular_at("ab/ten", 4).unwrap();
        assert_eq!(opened.stat.size, 10);
        assert_eq!(content(&opened.file), b"456789");
        let opened = objects.open_regular_at("ab/ten", 20).unwrap();
        assert!(content(&opened.file).is_empty());
    }

    #[test]
    fn open_object_gives_a_regular_file_or_the_target_of_a_symlink() {
        let dir = TestDir::new("read-object");
        let objects = objects(&dir);
        let tmp = root(&dir).tmp_dir(false).unwrap();
        let (name, staging, ()) = tmp.make_temp_dir("staging-", |_| Some(())).unwrap();
        let cases = [
            (dir.path().join("objects"), objects, "objects".to_owned()),
            (
                dir.path().join("tmp").join(&name),
                staging,
                format!("tmp/{name}"),
            ),
        ];
        for (base, handle, prefix) in cases {
            let ab = base.join("ab");
            std::fs::create_dir_all(&ab).unwrap();
            std::fs::write(ab.join("cd.file"), b"content").unwrap();
            symlink("target", ab.join("ef.file")).unwrap();

            match handle.open_object("ab/cd.file").unwrap() {
                ObjectEntry::Regular(opened) => {
                    assert_eq!(opened.stat.file_type, FileType::RegularFile);
                    assert_eq!(opened.stat.size, 7);
                    assert_eq!(content(&opened.file), b"content");
                }
                other => panic!("{other:?}"),
            }
            match handle.open_object("ab/ef.file").unwrap() {
                ObjectEntry::Symlink(target) => assert_eq!(target, b"target"),
                other => panic!("{other:?}"),
            }
            assert_eq!(
                absent(handle.open_object("ab/none.file")),
                format!("{prefix}/ab/none.file")
            );
        }
    }

    #[test]
    fn open_object_refuses_a_symlinked_fan_out() {
        let dir = TestDir::new("read-object-fan-out");
        let real = dir.path().join("objects/real");
        std::fs::create_dir_all(&real).unwrap();
        std::fs::write(real.join("cd.file"), b"content").unwrap();
        symlink("target", real.join("ef.file")).unwrap();
        symlink("real", dir.path().join("objects/ab")).unwrap();
        let objects = root(&dir).open_layout(RepoLayout::Objects).unwrap();
        for leaf in ["cd.file", "ef.file", "none.file"] {
            let (path, reason) = invalid(objects.open_object(&format!("ab/{leaf}")));
            assert_eq!(path, format!("objects/ab/{leaf}"));
            assert!(matches!(reason, Reason::Symlink), "{leaf}: {reason:?}");
        }
    }

    #[test]
    fn read_link_reads_a_target_to_its_cap_and_refuses_a_longer_one() {
        let dir = TestDir::new("read-link");
        let objects = objects(&dir);
        let ab = dir.path().join("objects/ab");
        let target = "t".repeat(3000);
        symlink(&target, ab.join("link")).unwrap();

        for cap in [3000, 3001, 4095, 4096, 10_000, u64::MAX] {
            assert_eq!(
                objects.read_link("ab/link", cap).unwrap(),
                target.as_bytes(),
                "cap {cap}"
            );
        }
        let (path, reason) = invalid(objects.read_link("ab/link", 2999));
        assert_eq!(path, "objects/ab/link");
        assert!(
            matches!(reason, Reason::TooLarge { cap: 2999 }),
            "{reason:?}"
        );
        let (_, reason) = invalid(objects.read_link("ab/link", 0));
        assert!(matches!(reason, Reason::TooLarge { cap: 0 }), "{reason:?}");

        // A target of 4095 bytes fills the stack buffer to one byte below its
        // size. A file system can refuse a target that long.
        let longest = "u".repeat(4095);
        match symlink(&longest, ab.join("longest")) {
            Ok(()) => {
                for cap in [4095, 4096, 10_000] {
                    assert_eq!(
                        objects.read_link("ab/longest", cap).unwrap(),
                        longest.as_bytes(),
                        "cap {cap}"
                    );
                }
                let (_, reason) = invalid(objects.read_link("ab/longest", 4094));
                assert!(
                    matches!(reason, Reason::TooLarge { cap: 4094 }),
                    "{reason:?}"
                );
            }
            Err(e) => eprintln!("skipping the 4095-byte target: {e}"),
        }
    }

    #[test]
    fn read_link_of_an_entry_that_is_not_a_symlink_gives_einval() {
        let dir = TestDir::new("read-link-errors");
        let objects = objects(&dir);
        let ab = dir.path().join("objects/ab");
        std::fs::write(ab.join("file"), b"x").unwrap();
        std::fs::create_dir(ab.join("dir")).unwrap();
        for path in ["ab/file", "ab/dir"] {
            let err = io_err(objects.read_link(path, 64));
            assert_eq!(
                err.raw_os_error(),
                Some(Errno::INVAL.raw_os_error()),
                "{path}"
            );
        }
        assert_eq!(absent(objects.read_link("ab/none", 64)), "objects/ab/none");

        symlink("ab", dir.path().join("objects/cd")).unwrap();
        symlink("target", ab.join("link")).unwrap();
        let (path, reason) = invalid(objects.read_link("cd/link", 64));
        assert_eq!(path, "objects/cd/link");
        assert!(matches!(reason, Reason::Symlink), "{reason:?}");
    }

    #[test]
    fn read_link_of_one_component_reads_relative_to_the_handle() {
        let dir = TestDir::new("read-link-one");
        let objects = objects(&dir);
        let base = dir.path().join("objects");
        symlink("ab", base.join("link")).unwrap();
        std::fs::write(base.join("file"), b"x").unwrap();
        assert_eq!(objects.read_link("link", 64).unwrap(), b"ab");
        let (path, reason) = invalid(objects.read_link("link", 1));
        assert_eq!(path, "objects/link");
        assert!(matches!(reason, Reason::TooLarge { cap: 1 }), "{reason:?}");
        for path in ["file", "ab"] {
            let err = io_err(objects.read_link(path, 64));
            assert_eq!(
                err.raw_os_error(),
                Some(Errno::INVAL.raw_os_error()),
                "{path}"
            );
        }
        assert_eq!(absent(objects.read_link("none", 64)), "objects/none");
    }

    #[test]
    fn lstat_does_not_follow_a_symlink_at_the_leaf() {
        let dir = TestDir::new("read-lstat");
        let objects = objects(&dir);
        let ab = dir.path().join("objects/ab");
        std::fs::write(ab.join("file"), b"0123456789abcdef").unwrap();
        symlink("file", ab.join("link")).unwrap();
        symlink("nowhere-at-all", ab.join("dangling")).unwrap();

        let stat = objects.lstat("ab/link").unwrap();
        assert_eq!(stat.file_type, FileType::Symlink);
        assert_eq!(stat.size, 4);
        let stat = objects.lstat("ab/dangling").unwrap();
        assert_eq!(stat.file_type, FileType::Symlink);
        assert_eq!(stat.size, 14);
        let stat = objects.lstat("ab/file").unwrap();
        assert_eq!(stat.file_type, FileType::RegularFile);
        assert_eq!(stat.size, 16);
        assert_eq!(objects.lstat("ab").unwrap().file_type, FileType::Directory);
        assert_eq!(absent(objects.lstat("ab/none")), "objects/ab/none");
    }

    /// Returns each field of `stat`.
    fn stat_fields(stat: &Stat) -> (FileType, u32, u32, u32, u64, u64, u64, i64, u32, bool) {
        (
            stat.file_type,
            stat.mode,
            stat.uid,
            stat.gid,
            stat.size,
            stat.dev,
            stat.ino,
            stat.mtime_sec,
            stat.mtime_nsec,
            stat.verity,
        )
    }

    #[test]
    fn lstat_and_exists_of_one_component_match_a_longer_path() {
        let dir = TestDir::new("read-lstat-one");
        let objects = objects(&dir);
        let ab_dir = objects.open_dir("ab").unwrap();
        let ab = dir.path().join("objects/ab");
        std::fs::write(ab.join("file"), b"0123456789abcdef").unwrap();
        std::fs::create_dir(ab.join("sub")).unwrap();
        symlink("file", ab.join("link")).unwrap();
        symlink("nowhere-at-all", ab.join("dangling")).unwrap();

        for (name, file_type) in [
            ("file", FileType::RegularFile),
            ("sub", FileType::Directory),
            ("link", FileType::Symlink),
            ("dangling", FileType::Symlink),
        ] {
            let one = ab_dir.lstat(name).unwrap();
            let long = objects.lstat(&format!("ab/{name}")).unwrap();
            assert_eq!(one.file_type, file_type, "{name}");
            assert_eq!(stat_fields(&one), stat_fields(&long), "{name}");
            assert!(ab_dir.exists(name).unwrap(), "{name}");
        }
        assert_eq!(ab_dir.lstat("link").unwrap().size, 4);
        assert_eq!(absent(ab_dir.lstat("none")), "objects/ab/none");
        assert!(!ab_dir.exists("none").unwrap());
        assert_eq!(
            stat_fields(&objects.lstat("ab").unwrap()),
            stat_fields(&stat_fd(ab_dir.as_fd()).unwrap())
        );
    }

    #[test]
    fn exists_gives_false_for_an_absent_entry_alone() {
        let dir = TestDir::new("read-exists");
        let objects = objects(&dir);
        let ab = dir.path().join("objects/ab");
        std::fs::write(ab.join("file"), b"x").unwrap();
        std::fs::create_dir(ab.join("real")).unwrap();
        std::fs::write(ab.join("real/x"), b"x").unwrap();
        symlink("real", ab.join("link")).unwrap();
        symlink("nowhere", ab.join("dangling")).unwrap();

        assert!(!objects.exists("ab/none").unwrap());
        assert!(!objects.exists("cd/none").unwrap());
        for path in ["ab", "ab/file", "ab/real/x", "ab/link", "ab/dangling"] {
            assert!(objects.exists(path).unwrap(), "{path}");
        }
        let (path, reason) = invalid(objects.exists("ab/file/x"));
        assert_eq!(path, "objects/ab/file/x");
        assert!(matches!(reason, Reason::NotDirectory), "{reason:?}");
        let (path, reason) = invalid(objects.exists("ab/link/x"));
        assert_eq!(path, "objects/ab/link/x");
        assert!(matches!(reason, Reason::Symlink), "{reason:?}");
    }

    #[test]
    fn open_root_file_follows_a_symlink_at_a_keyring_alone() {
        let dir = TestDir::new("read-root-file");
        let other = TestDir::new("read-root-file-other");
        std::fs::write(other.path().join("keys.gpg"), b"keys").unwrap();
        symlink(
            other.path().join("keys.gpg"),
            dir.path().join("origin.trustedkeys.gpg"),
        )
        .unwrap();
        std::fs::write(dir.path().join("gpgkeys.gpg"), b"plain").unwrap();
        std::fs::write(dir.path().join("config"), b"[core]\n").unwrap();
        symlink(other.path().join("keys.gpg"), dir.path().join("summary")).unwrap();
        let repo = root(&dir);

        let opened = repo
            .open_root_file(RootFile::Keyring("origin.trustedkeys.gpg".into()))
            .unwrap();
        assert_eq!(content(&opened.file), b"keys");
        assert_eq!(opened.stat.size, 4);
        let opened = repo
            .open_root_file(RootFile::Keyring("gpgkeys.gpg".into()))
            .unwrap();
        assert_eq!(content(&opened.file), b"plain");
        let opened = repo.open_root_file(RootFile::Config).unwrap();
        assert_eq!(content(&opened.file), b"[core]\n");

        let (path, reason) = invalid(repo.open_root_file(RootFile::Summary));
        assert_eq!(path, "summary");
        assert!(matches!(reason, Reason::Symlink), "{reason:?}");
        assert_eq!(
            absent(repo.open_root_file(RootFile::SummarySig)),
            "summary.sig"
        );
    }

    #[test]
    fn open_root_file_maps_the_errors_of_a_keyring() {
        let dir = TestDir::new("read-keyring");
        let other = TestDir::new("read-keyring-other");
        let at = |name: &str| dir.path().join(name);
        std::fs::write(at("file"), b"x").unwrap();
        symlink("nowhere", at("dangling.gpg")).unwrap();
        symlink("loop.gpg", at("loop.gpg")).unwrap();
        symlink("file/x", at("notdir.gpg")).unwrap();
        symlink("/dev/null", at("null.gpg")).unwrap();
        let _listener = UnixListener::bind(other.path().join("sock")).unwrap();
        symlink(other.path().join("sock"), at("sock.gpg")).unwrap();
        symlink(other.path(), at("dir.gpg")).unwrap();
        let repo = root(&dir);
        let keyring = |name: &str| repo.open_root_file(RootFile::Keyring(name.to_owned()));

        assert_eq!(absent(keyring("absent.gpg")), "absent.gpg");
        assert_eq!(absent(keyring("dangling.gpg")), "dangling.gpg");
        for (name, errno) in [("loop.gpg", Errno::LOOP), ("notdir.gpg", Errno::NOTDIR)] {
            let err = io_err(keyring(name));
            assert_eq!(err.raw_os_error(), Some(errno.raw_os_error()), "{name}");
        }
        for (name, expected) in [
            ("null.gpg", FileType::CharacterDevice),
            ("sock.gpg", FileType::Socket),
            ("dir.gpg", FileType::Directory),
        ] {
            let (path, file_type) = not_regular(keyring(name));
            assert_eq!(path, name);
            assert_eq!(file_type, expected, "{name}");
        }
        for name in ["", ".", "..", "a/b", "/etc/passwd"] {
            let (path, reason) = invalid(keyring(name));
            assert_eq!(path, repo.err_path(name), "{name:?}");
            assert!(matches!(reason, Reason::Escape), "{name:?}: {reason:?}");
        }
    }

    #[test]
    fn open_root_file_refuses_a_keyring_fifo_and_does_not_block() {
        let dir = TestDir::new("read-keyring-fifo");
        let other = TestDir::new("read-keyring-fifo-other");
        let fifo = other.path().join("fifo");
        mkfifo(&fifo);
        symlink(&fifo, dir.path().join("fifo.gpg")).unwrap();
        let repo = root(&dir);
        let result = without_block(&fifo, move || {
            repo.open_root_file(RootFile::Keyring("fifo.gpg".into()))
                .map(drop)
        });
        let (path, file_type) = not_regular(result);
        assert_eq!(path, "fifo.gpg");
        assert_eq!(file_type, FileType::Fifo);
    }

    #[test]
    fn each_read_primitive_refuses_an_escape() {
        let dir = TestDir::new("read-escape");
        let objects = objects(&dir);
        std::fs::write(dir.path().join("x"), b"outside").unwrap();
        let cases = [
            "..",
            "../x",
            "ab/../cd",
            "ab/..",
            "/etc/passwd",
            "/",
            "",
            "ab//cd",
            "./ab",
            "ab/.",
            "ab/",
        ];
        for path in cases {
            let results = [
                objects.open_regular(path).map(drop),
                objects.read_capped(path, 64).map(drop),
                objects.open_regular_at(path, 0).map(drop),
                objects.open_object(path).map(drop),
                objects.read_link(path, 64).map(drop),
                objects.lstat(path).map(drop),
                objects.exists(path).map(drop),
                objects.link_xattrs(path).map(drop),
            ];
            for (at, result) in results.into_iter().enumerate() {
                let (err_path, reason) = invalid(result);
                assert_eq!(err_path, objects.err_path(path), "{path:?} #{at}");
                assert!(
                    matches!(reason, Reason::Escape),
                    "{path:?} #{at}: {reason:?}"
                );
            }
        }
    }

    #[test]
    fn read_grown_grows_to_the_size_that_the_kernel_gives() {
        let value: Vec<u8> = (0..1000u32).map(|i| (i % 251) as u8).collect();
        let mut calls = Vec::new();
        let mut buf = Vec::new();
        let len = read_grown(&mut buf, |b| {
            calls.push(b.len());
            if b.is_empty() {
                Ok(value.len())
            } else if b.len() < value.len() {
                Err(Errno::RANGE)
            } else {
                b[..value.len()].copy_from_slice(&value);
                Ok(value.len())
            }
        })
        .unwrap();
        assert_eq!(&buf[..len], value.as_slice());
        assert_eq!(calls, [XATTR_BUF_START, 0, 1000]);
        assert_eq!(buf.len(), 1000);

        // A buffer that is large enough serves the next read with no growth.
        let len = read_grown(&mut buf, |b| {
            b[..3].copy_from_slice(b"abc");
            Ok(3)
        })
        .unwrap();
        assert_eq!(&buf[..len], b"abc");
        assert_eq!(buf.len(), 1000);
    }

    #[test]
    fn read_grown_refuses_a_size_over_64_kib() {
        let mut buf = Vec::new();
        let result = read_grown(&mut buf, |b| {
            if b.is_empty() {
                Ok(XATTR_MAX + 1)
            } else {
                Err(Errno::RANGE)
            }
        });
        assert_eq!(result, Err(Errno::TOOBIG));
        assert_eq!(buf.len(), XATTR_BUF_START);
    }

    #[test]
    fn read_grown_stops_after_four_passes() {
        let mut calls = Vec::new();
        let mut buf = Vec::new();
        let result = read_grown(&mut buf, |b| {
            calls.push(b.len());
            if b.is_empty() {
                Ok(100)
            } else {
                Err(Errno::RANGE)
            }
        });
        assert_eq!(result, Err(Errno::RANGE));
        let s = XATTR_BUF_START;
        assert_eq!(calls, [s, 0, s, 0, s, 0, s]);
    }

    #[test]
    fn link_error_gives_absent_only_for_an_absent_leaf() {
        let dir = TestDir::new("read-link-error");
        let objects = objects(&dir);
        let ab = dir.path().join("objects/ab");
        std::fs::write(ab.join("file"), b"x").unwrap();
        symlink("nowhere", ab.join("dangling")).unwrap();
        let ab_dir = objects.open_dir("ab").unwrap();
        let fd = ab_dir.as_fd();

        let error = |leaf: &str| objects.link_error(Errno::NOENT, fd, leaf, &format!("ab/{leaf}"));
        assert_eq!(absent::<()>(Err(error("none"))), "objects/ab/none");
        for leaf in ["file", "dangling"] {
            let err = io_err::<()>(Err(error(leaf)));
            assert_eq!(err.kind(), io::ErrorKind::NotFound, "{leaf}");
            let message = err.to_string();
            assert!(message.contains("/proc/self/fd"), "{message}");
            assert!(message.contains(&format!("objects/ab/{leaf}")), "{message}");
        }
        let err = io_err::<()>(Err(objects.link_error(
            Errno::ACCESS,
            fd,
            "none",
            "ab/none",
        )));
        assert_eq!(err.raw_os_error(), Some(Errno::ACCESS.raw_os_error()));
    }

    #[test]
    fn the_xattr_reads_grow_their_buffers_for_a_large_value_and_a_long_list() {
        let dir = TestDir::new("read-xattr");
        let path = dir.path().join("file");
        std::fs::write(&path, b"x").unwrap();
        let file = File::open(&path).unwrap();
        let fd = file.as_fd();
        let big: Vec<u8> = (0..1024u32).map(|i| (i % 251) as u8).collect();
        if !set_xattr(fd, "user.big", &big) {
            eprintln!("skipping: the file system has no user xattrs");
            return;
        }
        let mut expected = vec![(b"user.big\0".to_vec(), big.clone())];
        for i in 0..30 {
            let name = format!("user.a-name-with-a-long-part-{i:02}");
            let value = format!("value {i}");
            assert!(set_xattr(fd, &name, value.as_bytes()));
            expected.push((format!("{name}\0").into_bytes(), value.into_bytes()));
        }
        expected.sort();

        assert_eq!(xattr(fd, "user.big").unwrap(), Some(big));
        assert_eq!(xattr(fd, "user.missing").unwrap(), None);
        assert_eq!(
            xattr(fd, "user.a-name-with-a-long-part-07").unwrap(),
            Some(b"value 7".to_vec())
        );
        let set = xattrs(fd).unwrap();
        let got: Vec<(Vec<u8>, Vec<u8>)> = set
            .iter()
            .filter(|(name, _)| name.starts_with(b"user."))
            .map(|(name, value)| (name.to_vec(), value.to_vec()))
            .collect();
        assert_eq!(got, expected);
    }

    #[test]
    fn link_xattrs_does_not_follow_the_leaf() {
        let dir = TestDir::new("read-link-xattrs");
        let objects = objects(&dir);
        let ab = dir.path().join("objects/ab");
        std::fs::write(ab.join("file"), b"x").unwrap();
        let file = File::open(ab.join("file")).unwrap();
        if !set_xattr(file.as_fd(), "user.demo", b"value") {
            eprintln!("skipping: the file system has no user xattrs");
            return;
        }
        symlink("file", ab.join("link")).unwrap();
        let has_demo = |set: &Xattrs| {
            set.iter()
                .any(|(name, value)| name == b"user.demo\0" && value == b"value")
        };

        assert!(has_demo(&objects.link_xattrs("ab/file").unwrap()));
        assert!(!has_demo(&objects.link_xattrs("ab/link").unwrap()));
        let ab_dir = objects.open_dir("ab").unwrap();
        assert!(has_demo(&ab_dir.link_xattrs("file").unwrap()));
        assert!(!has_demo(&ab_dir.link_xattrs("link").unwrap()));
        assert!(has_demo(&xattrs(file.as_fd()).unwrap()));

        assert_eq!(absent(objects.link_xattrs("ab/none")), "objects/ab/none");
        assert_eq!(absent(ab_dir.link_xattrs("none")), "objects/ab/none");
        symlink("ab", dir.path().join("objects/cd")).unwrap();
        let (path, reason) = invalid(objects.link_xattrs("cd/file"));
        assert_eq!(path, "objects/cd");
        assert!(matches!(reason, Reason::Symlink), "{reason:?}");

        let at = |name: &str| link_xattrs_at(objects.as_fd(), Path::new(name));
        assert!(has_demo(&at("ab/file").unwrap()));
        assert!(!has_demo(&at("ab/link").unwrap()));
        assert!(has_demo(&at("cd/file").unwrap()));
        let err = io_err(at("ab/none"));
        assert_eq!(err.raw_os_error(), Some(Errno::NOENT.raw_os_error()));
    }

    #[test]
    fn verity_digest_gives_the_digest_of_a_sealed_file_alone() {
        let dir = TestDir::new("read-verity");
        let path = dir.path().join("file");
        let data = vec![7u8; 10_000];
        std::fs::write(&path, &data).unwrap();
        let file = File::open(&path).unwrap();
        let size = data.len() as u64;
        assert_eq!(verity_digest(file.as_fd(), size), None);
        if let Err(e) = ostrya_sys::enable_verity(file.as_fd()) {
            eprintln!("skipping: the file system has no fs-verity: {e}");
            return;
        }
        assert!(stat_fd(file.as_fd()).unwrap().verity);
        assert_eq!(
            verity_digest(file.as_fd(), size),
            Some(FsVerityHasher::hash(&data))
        );
        assert_eq!(verity_digest(file.as_fd(), size + 1), None);
    }

    #[cfg(debug_assertions)]
    #[test]
    #[should_panic(expected = "open_object needs an objects handle or a staging handle")]
    fn open_object_on_another_kind_fails_a_debug_assertion() {
        let dir = TestDir::new("misuse-object");
        std::fs::create_dir_all(dir.path().join("refs/ab")).unwrap();
        let refs = root(&dir).open_layout(RepoLayout::Refs).unwrap();
        let _ = refs.open_object("ab/cd.file");
    }

    #[cfg(debug_assertions)]
    #[test]
    #[should_panic(expected = "open_root_file needs the root handle")]
    fn open_root_file_on_another_handle_fails_a_debug_assertion() {
        let dir = TestDir::new("misuse-root-file");
        let objects = objects(&dir);
        let _ = objects.open_root_file(RootFile::Config);
    }
}