cocoonfs-cli 0.1.3

Cocoon TPM project - CLI utility for accessing CocoonFs images
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
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
// SPDX-License-Identifier: Apache-2.0
// Copyright 2025-2026 SUSE LLC
// Author: Nicolai Stange <nstange@suse.de>

use cocoon_tpm_crypto as crypto;
use cocoon_tpm_storage as storage;
use cocoon_tpm_tpm2_interface as tpm2_interface;
use cocoon_tpm_utils_async::{self as utils_async};
use cocoon_tpm_utils_common as utils_common;

use crypto::{
    rng,
    symcipher::{self, SymBlockCipherAlg},
};
use storage::fs::{
    NvFs, NvFsEnumerateCursor as _, NvFsFutureAsCoreFuture, NvFsReadContext, NvFsUnlinkCursor as _,
    cocoonfs::{
        AuxFsMetadata, CocoonFs, FsMetadata, ImageLayout, MkFsFuture, OpenFsFuture, ReadFsMetadataFuture,
        WriteAuxFsMetadataOfflineFuture, WriteMkFsInfoHeaderFuture,
    },
};
use tpm2_interface::TpmiAlgHash;
use utils_async::sync_types;
use utils_common::{fixed_vec::FixedVec, zeroize};

mod std_sync_types;
use std_sync_types::StdSyncTypes;
mod std_file_nvblkdev;
use std_file_nvblkdev::StdFileNvBlkDev;

use clap::{self, CommandFactory as _, Parser as _};
use pollster::FutureExt as _;
use std::{
    ffi, fmt, fs,
    io::{self, Read, Write},
    iter,
    path::PathBuf,
    pin::Pin,
};

type CocoonFsType = CocoonFs<StdSyncTypes, StdFileNvBlkDev>;

fn cocoonfs_mk_fs_instance_ref(
    fs_instance: &<CocoonFsType as NvFs>::SyncRcPtr,
) -> <CocoonFsType as NvFs>::SyncRcPtrRef<'_> {
    type CocoonFsSyncRcPtr = <CocoonFsType as NvFs>::SyncRcPtr;
    <CocoonFsSyncRcPtr as sync_types::SyncRcPtr<_>>::as_ref(fs_instance)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct CliSizeValue {
    size: u64,
}

impl From<CliSizeValue> for u64 {
    fn from(value: CliSizeValue) -> Self {
        value.size
    }
}

impl fmt::Display for CliSizeValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (shift, unit) = if self.size >> 30 << 30 == self.size {
            (30u32, 'G')
        } else if self.size >> 20 << 20 == self.size {
            (20, 'M')
        } else if self.size >> 10 << 10 == self.size {
            (10, 'K')
        } else {
            (0, 'B')
        };

        write!(f, "{}{}", self.size >> shift, unit)
    }
}

impl clap::builder::ValueParserFactory for CliSizeValue {
    type Parser = CliSizeValueParser;

    fn value_parser() -> Self::Parser {
        Self::Parser {}
    }
}

#[derive(Clone, Copy)]
struct CliSizeValueParser {}

impl clap::builder::TypedValueParser for CliSizeValueParser {
    type Value = CliSizeValue;
    fn parse_ref(
        &self,
        cmd: &clap::Command,
        arg: Option<&clap::Arg>,
        value: &ffi::OsStr,
    ) -> Result<Self::Value, clap::Error> {
        let value = value.to_str().ok_or_else(|| {
            let mut err = clap::Error::new(clap::error::ErrorKind::InvalidUtf8).with_cmd(cmd);
            if let Some(arg) = arg {
                err.insert(
                    clap::error::ContextKind::InvalidArg,
                    clap::error::ContextValue::String(arg.to_string()),
                );
            }
            err
        })?;

        let value = value.trim_start();
        let unit_pos = value.char_indices().find(|(_pos, c)| !c.is_ascii_digit());
        let (value, unit_shift) = match unit_pos {
            Some((unit_pos, _)) => {
                let unit = &value[unit_pos..].trim();
                if unit.is_empty() || *unit == "B" {
                    (&value[..unit_pos], 0u32)
                } else if *unit == "K" {
                    (&value[..unit_pos], 10)
                } else if *unit == "M" {
                    (&value[..unit_pos], 20)
                } else if *unit == "G" {
                    (&value[..unit_pos], 30)
                } else {
                    let mut err = clap::Error::new(clap::error::ErrorKind::ValueValidation).with_cmd(cmd);
                    if let Some(arg) = arg {
                        err.insert(
                            clap::error::ContextKind::InvalidArg,
                            clap::error::ContextValue::String(arg.to_string()),
                        );
                    }
                    err.insert(
                        clap::error::ContextKind::InvalidValue,
                        clap::error::ContextValue::String(value.to_string()),
                    );
                    // clap currently doesn't convey this to the user, unfortunately. Still add a
                    // meaningful message in hope it would some day.
                    err.insert(
                        clap::error::ContextKind::Custom,
                        clap::error::ContextValue::String("recognized units: [B|K|M|G], default: B".to_string()),
                    );
                    return Err(err);
                }
            }
            None => (value.trim_end(), 1),
        };

        let value = clap::value_parser!(u64).parse_ref(cmd, arg, value.as_ref())?;

        if value << unit_shift >> unit_shift != value {
            let mut err = clap::Error::new(clap::error::ErrorKind::ValueValidation).with_cmd(cmd);
            if let Some(arg) = arg {
                err.insert(
                    clap::error::ContextKind::InvalidArg,
                    clap::error::ContextValue::String(arg.to_string()),
                );
            }
            err.insert(
                clap::error::ContextKind::InvalidValue,
                clap::error::ContextValue::String(value.to_string()),
            );
            // clap currently doesn't convey this to the user, unfortunately. Still add a
            // meaningful message in hope it would some day.
            err.insert(
                clap::error::ContextKind::Custom,
                clap::error::ContextValue::String("value too large".to_string()),
            );
            return Err(err);
        }

        Ok(CliSizeValue {
            size: value << unit_shift,
        })
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct CliPowerOfTwoSizeValue<const MIN_VALUE_LOG2: u32> {
    size_log2: u32,
}

impl<const MIN_VALUE_LOG2: u32> From<CliPowerOfTwoSizeValue<MIN_VALUE_LOG2>> for u32 {
    fn from(value: CliPowerOfTwoSizeValue<MIN_VALUE_LOG2>) -> Self {
        value.size_log2
    }
}

impl<const MIN_VALUE_LOG2: u32> From<CliPowerOfTwoSizeValue<MIN_VALUE_LOG2>> for CliSizeValue {
    fn from(value: CliPowerOfTwoSizeValue<MIN_VALUE_LOG2>) -> Self {
        CliSizeValue {
            size: 1u64 << value.size_log2,
        }
    }
}

impl<const MIN_VALUE_LOG2: u32> fmt::Display for CliPowerOfTwoSizeValue<MIN_VALUE_LOG2> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        CliSizeValue::from(*self).fmt(f)
    }
}

impl<const MIN_VALUE_LOG2: u32> clap::builder::ValueParserFactory for CliPowerOfTwoSizeValue<MIN_VALUE_LOG2> {
    type Parser = CliPowerOfTwoSizeValueParser<MIN_VALUE_LOG2>;

    fn value_parser() -> Self::Parser {
        CliPowerOfTwoSizeValueParser::<MIN_VALUE_LOG2> {}
    }
}

#[derive(Clone, Copy)]
struct CliPowerOfTwoSizeValueParser<const MIN_VALUE_LOG2: u32> {}

impl<const MIN_VALUE_LOG2: u32> clap::builder::TypedValueParser for CliPowerOfTwoSizeValueParser<MIN_VALUE_LOG2> {
    type Value = CliPowerOfTwoSizeValue<MIN_VALUE_LOG2>;

    fn parse_ref(
        &self,
        cmd: &clap::Command,
        arg: Option<&clap::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, clap::Error> {
        let size = clap::value_parser!(CliSizeValue).parse_ref(cmd, arg, value)?;

        let min_size = CliSizeValue::from(CliPowerOfTwoSizeValue::<MIN_VALUE_LOG2> {
            size_log2: MIN_VALUE_LOG2,
        });
        if size < min_size {
            let mut err = clap::Error::new(clap::error::ErrorKind::ValueValidation).with_cmd(cmd);
            if let Some(arg) = arg {
                err.insert(
                    clap::error::ContextKind::InvalidArg,
                    clap::error::ContextValue::String(arg.to_string()),
                );
            }
            err.insert(
                clap::error::ContextKind::InvalidValue,
                clap::error::ContextValue::String(size.to_string()),
            );
            // clap currently doesn't convey this to the user, unfortunately. Still add a
            // meaningful message in hope it would some day.
            err.insert(
                clap::error::ContextKind::Custom,
                clap::error::ContextValue::String(format!("minimum value: {min_size}")),
            );
        } else if !size.size.is_power_of_two() {
            let mut err = clap::Error::new(clap::error::ErrorKind::ValueValidation).with_cmd(cmd);
            if let Some(arg) = arg {
                err.insert(
                    clap::error::ContextKind::InvalidArg,
                    clap::error::ContextValue::String(arg.to_string()),
                );
            }
            err.insert(
                clap::error::ContextKind::InvalidValue,
                clap::error::ContextValue::String(size.to_string()),
            );
            // clap currently doesn't convey this to the user, unfortunately. Still add a
            // meaningful message in hope it would some day.
            err.insert(
                clap::error::ContextKind::Custom,
                clap::error::ContextValue::String("value must be a power of two".to_string()),
            );
        }

        Ok(CliPowerOfTwoSizeValue {
            size_log2: size.size.ilog2(),
        })
    }
}

#[derive(Clone, Copy, Debug)]
enum ByteFromHexError {
    InvalidDigit,
}
fn nibble_from_hex(hexchar: u8) -> Result<u8, ByteFromHexError> {
    Ok(hexchar
        - match hexchar {
            b'0'..=b'9' => b'0',
            b'a'..=b'f' => b'a' - 0xa,
            b'A'..=b'F' => b'A' - 0xa,
            _ => {
                return Err(ByteFromHexError::InvalidDigit);
            }
        })
}

fn byte_from_hex(hexstr: &[u8; 2]) -> Result<u8, ByteFromHexError> {
    let mut result = 0u8;
    for hexchar in hexstr {
        let nibble = nibble_from_hex(*hexchar)?;
        result = result << 4 | nibble;
    }
    Ok(result)
}

#[derive(Clone, Copy)]
struct CliHexStringValueParser {}

impl clap::builder::TypedValueParser for CliHexStringValueParser {
    type Value = FixedVec<u8, 4>;

    fn parse_ref(
        &self,
        cmd: &clap::Command,
        arg: Option<&clap::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, clap::Error> {
        let value = value.to_str().ok_or_else(|| {
            let mut err = clap::Error::new(clap::error::ErrorKind::InvalidUtf8).with_cmd(cmd);
            if let Some(arg) = arg {
                err.insert(
                    clap::error::ContextKind::InvalidArg,
                    clap::error::ContextValue::String(arg.to_string()),
                );
            }
            err
        })?;

        let value = value.trim();
        let len = value.len().div_ceil(2);
        let mut result = FixedVec::new_with_default(len).unwrap();
        let src = value.as_bytes();
        let (src, dst) = if !value.len().is_multiple_of(2) {
            // Pad with a zero nibble at the head.
            result[0] = nibble_from_hex(src[0]).map_err(|e| {
                match e {
                    ByteFromHexError::InvalidDigit => {
                        let mut err = clap::Error::new(clap::error::ErrorKind::ValueValidation).with_cmd(cmd);
                        if let Some(arg) = arg {
                            err.insert(
                                clap::error::ContextKind::InvalidArg,
                                clap::error::ContextValue::String(arg.to_string()),
                            );
                        }
                        err.insert(
                            clap::error::ContextKind::InvalidValue,
                            clap::error::ContextValue::String(value.to_string()),
                        );
                        // clap currently doesn't convey this to the user, unfortunately. Still add a
                        // meaningful message in hope it would some day.
                        err.insert(
                            clap::error::ContextKind::Custom,
                            clap::error::ContextValue::String("invalid hexadecimal digit".to_string()),
                        );

                        err
                    }
                }
            })?;
            (&src[1..], &mut result[1..])
        } else {
            (src, &mut *result)
        };

        for (i, hexdigit_pair) in src.chunks_exact(2).enumerate() {
            let hexdigit_pair = <&[u8; 2]>::try_from(hexdigit_pair).unwrap();
            dst[i] = byte_from_hex(hexdigit_pair).map_err(|e| match e {
                ByteFromHexError::InvalidDigit => {
                    let mut err = clap::Error::new(clap::error::ErrorKind::ValueValidation).with_cmd(cmd);
                    if let Some(arg) = arg {
                        err.insert(
                            clap::error::ContextKind::InvalidArg,
                            clap::error::ContextValue::String(arg.to_string()),
                        );
                    }
                    err.insert(
                        clap::error::ContextKind::InvalidValue,
                        clap::error::ContextValue::String(value.to_string()),
                    );
                    // clap currently doesn't convey this to the user, unfortunately. Still add a
                    // meaningful message in hope it would some day.
                    err.insert(
                        clap::error::ContextKind::Custom,
                        clap::error::ContextValue::String("invalid hexadecimal digit".to_string()),
                    );

                    err
                }
            })?;
        }

        Ok(result)
    }
}

const UUID_LEN: usize = 16;
// (Binary) component lengths for the common 8-4-4-4-12 format.
const UUID_COMPONENTS_LENS: [usize; 5] = [4, 2, 2, 2, 6];

#[derive(Clone, Copy, Debug)]
struct CliUuidValue {
    uuid: [u8; UUID_LEN],
}

impl fmt::Display for CliUuidValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut i = 0;
        for component_len in UUID_COMPONENTS_LENS {
            for _ in 0..component_len {
                write!(f, "{:02x}", self.uuid[i])?;
                i += 1;
            }
            if i != UUID_LEN {
                write!(f, "-")?;
            }
        }
        Ok(())
    }
}

impl clap::builder::ValueParserFactory for CliUuidValue {
    type Parser = CliUuidValueParser;

    fn value_parser() -> Self::Parser {
        Self::Parser {}
    }
}

#[derive(Clone, Copy)]
struct CliUuidValueParser {}

impl clap::builder::TypedValueParser for CliUuidValueParser {
    type Value = CliUuidValue;

    fn parse_ref(
        &self,
        cmd: &clap::Command,
        arg: Option<&clap::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, clap::Error> {
        let value = value.to_str().ok_or_else(|| {
            let mut err = clap::Error::new(clap::error::ErrorKind::InvalidUtf8).with_cmd(cmd);
            if let Some(arg) = arg {
                err.insert(
                    clap::error::ContextKind::InvalidArg,
                    clap::error::ContextValue::String(arg.to_string()),
                );
            }
            err
        })?;

        let value = value.trim();
        let src = value.as_bytes();

        if src.iter().filter(|c| **c == b'-').count() != UUID_COMPONENTS_LENS.len() - 1 {
            let mut err = clap::Error::new(clap::error::ErrorKind::ValueValidation).with_cmd(cmd);
            if let Some(arg) = arg {
                err.insert(
                    clap::error::ContextKind::InvalidArg,
                    clap::error::ContextValue::String(arg.to_string()),
                );
            }
            err.insert(
                clap::error::ContextKind::InvalidValue,
                clap::error::ContextValue::String(value.to_string()),
            );
            // clap currently doesn't convey this to the user, unfortunately. Still add a
            // meaningful message in hope it would some day.
            err.insert(
                clap::error::ContextKind::Custom,
                clap::error::ContextValue::String(
                    "invalid number of components in UUID string (expected format is 8-4-4-4-12)".to_string(),
                ),
            );
            return Err(err);
        }

        let mut expected_component_end_pos = 0;
        for (component_index, found_component_end_pos) in src
            .iter()
            .enumerate()
            .filter_map(|(pos, c)| if *c == b'-' { Some(pos) } else { None })
            .chain(iter::once(src.len()))
            .enumerate()
        {
            expected_component_end_pos += 2 * UUID_COMPONENTS_LENS[component_index];
            if found_component_end_pos != expected_component_end_pos {
                let mut err = clap::Error::new(clap::error::ErrorKind::ValueValidation).with_cmd(cmd);
                if let Some(arg) = arg {
                    err.insert(
                        clap::error::ContextKind::InvalidArg,
                        clap::error::ContextValue::String(arg.to_string()),
                    );
                }
                err.insert(
                    clap::error::ContextKind::InvalidValue,
                    clap::error::ContextValue::String(value.to_string()),
                );
                // clap currently doesn't convey this to the user, unfortunately. Still add a
                // meaningful message in hope it would some day.
                err.insert(
                    clap::error::ContextKind::Custom,
                    clap::error::ContextValue::String(
                        "invalid component length in UUID string (expected format is 8-4-4-4-12)".to_string(),
                    ),
                );
                return Err(err);
            }
            // Account for the separator.
            expected_component_end_pos += 1;
        }

        let mut uuid = [0u8; UUID_LEN];
        let mut i = 0;
        let mut j = 0;
        for component_len in UUID_COMPONENTS_LENS.iter() {
            for _ in 0..*component_len {
                let hexdigit_pair = <&[u8; 2]>::try_from(&src[j..j + 2]).unwrap();
                j += 2;
                uuid[i] = byte_from_hex(hexdigit_pair).map_err(|e| match e {
                    ByteFromHexError::InvalidDigit => {
                        let mut err = clap::Error::new(clap::error::ErrorKind::ValueValidation).with_cmd(cmd);
                        if let Some(arg) = arg {
                            err.insert(
                                clap::error::ContextKind::InvalidArg,
                                clap::error::ContextValue::String(arg.to_string()),
                            );
                        }
                        err.insert(
                            clap::error::ContextKind::InvalidValue,
                            clap::error::ContextValue::String(value.to_string()),
                        );
                        // clap currently doesn't convey this to the user, unfortunately. Still add a
                        // meaningful message in hope it would some day.
                        err.insert(
                            clap::error::ContextKind::Custom,
                            clap::error::ContextValue::String("invalid hexadecimal digit in UUID".to_string()),
                        );

                        err
                    }
                })?;
                i += 1;
            }
            // Skip over the separator.
            j += 1;
        }

        Ok(CliUuidValue { uuid })
    }
}

#[derive(Clone)]
struct CliAuxFsMetadataExtraReserveCapacityValue {
    capacity: Option<u64>,
}

impl fmt::Display for CliAuxFsMetadataExtraReserveCapacityValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.capacity.as_ref() {
            Some(capacity) => write!(f, "{}", CliSizeValue { size: *capacity }),
            None => write!(f, "disabled"),
        }
    }
}

impl clap::builder::ValueParserFactory for CliAuxFsMetadataExtraReserveCapacityValue {
    type Parser = CliAuxFsMetadataExtraReserveCapacityValueParser;

    fn value_parser() -> Self::Parser {
        Self::Parser {}
    }
}

#[derive(Clone)]
struct CliAuxFsMetadataExtraReserveCapacityValueParser {}

impl clap::builder::TypedValueParser for CliAuxFsMetadataExtraReserveCapacityValueParser {
    type Value = CliAuxFsMetadataExtraReserveCapacityValue;

    fn parse_ref(
        &self,
        cmd: &clap::Command,
        arg: Option<&clap::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, clap::Error> {
        if value == "disabled" {
            Ok(CliAuxFsMetadataExtraReserveCapacityValue { capacity: None })
        } else {
            Ok(CliAuxFsMetadataExtraReserveCapacityValue {
                capacity: Some(clap::value_parser!(CliSizeValue).parse_ref(cmd, arg, value)?.size),
            })
        }
    }
}

#[derive(clap::Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    /// Filesystem image volume file.
    #[arg(name = "image", short, long, value_name = "FILE")]
    volume_file_path: PathBuf,

    /// Ignore the filesystem image volume file backing storage's IO block size.
    ///
    /// May be used for accessing filesystem with a maximum supported IO block
    /// size smaller than the host's. Can lead to data loss in the event of
    /// a power cut or similar.
    #[arg(name = "force-ignore-volume-storage-block-size", short = 'f', long)]
    ignore_volume_file_io_block_size: bool,

    #[command(subcommand)]
    command: CliCommand,
}

#[derive(clap::Subcommand)]
enum CliCommand {
    /// Format the filesystem.
    Mkfs(CliMkFsArgs),
    /// Write a filesystem creation info header.
    ///
    /// A filesystem creation info header can get written without access to the
    /// key and stores all configuration parameters required for actually
    /// creating the filesystem. The filesystem will get created transparently
    /// when first accessed.
    WriteMkfsInfoHeader(CliWriteMkFsInfoHeaderArgs),

    /// Show and manipulate auxiliary filesystem metadata.
    #[command(subcommand)]
    AuxFsMetadata(CliAuxFsMetadataCommand),

    /// Write to a file in the filesystem image.
    WriteFile(CliWriteFileArgs),

    /// Read from a file in the filesystem image.
    ReadFile(CliReadFileArgs),

    /// List all files in the filesystem image.
    ListFiles(CliListFilesArgs),

    /// Remove a file from the filesystem image.
    RemoveFile(CliRemoveFile),
}

#[derive(clap::Args)]
struct CliMkFsArgs {
    #[command(flatten)]
    key: CliKeySource,

    #[command(flatten)]
    mkfsinfo: CliMkfsInfo,

    /// Don't randomize unallocated storage regions.
    #[arg(name = "no-randomize-unallocated", long, short = 'n')]
    enable_trimming: bool,
}

#[derive(clap::Args)]
struct CliWriteMkFsInfoHeaderArgs {
    #[command(flatten)]
    mkfsinfo: CliMkfsInfo,

    /// Trim the filesystem volume image file to the header.
    ///
    /// The resulting file contains only the bare header and may get written to
    /// the beginning of a storage volume.
    #[arg(name = "trim-volume-file-to-header", long, short = 'T')]
    trim_volume_file_to_header: bool,
}

#[derive(clap::Subcommand)]
enum CliAuxFsMetadataCommand {
    /// List all entries.
    ListEntries,
    /// Read a selected entry's data.
    ReadEntry(CliAuxFsMetadataReadEntryArgs),
    /// Edit the auxiliary filesystem metadata.
    Edit(CliAuxFsMetadataEditArgs),
}

#[derive(clap::Args)]
struct CliAuxFsMetadataReadEntryArgs {
    /// UUID of the entry to read.
    uuid: CliUuidValue,
    /// Selection index within the sequence of all entries with matching UUIDs.
    #[arg(default_value_t = 0)]
    index: usize,
    /// Output file to write the read data to [default: standard output].
    #[arg(name = "output-file", short, long, value_name = "FILE")]
    out_file_path: Option<PathBuf>,
}

#[derive(clap::Args)]
struct CliAuxFsMetadataEditArgs {
    #[command(flatten)]
    key: CliKeySourceOpt,

    /// Don't randomize unallocated storage regions.
    #[arg(name = "no-randomize-unallocated", long, short = 'n')]
    enable_trimming: bool,

    #[command(subcommand)]
    command: CliAuxFsMetadataEditCommand,
}

#[derive(clap::Subcommand)]
enum CliAuxFsMetadataEditCommand {
    /// Change the preallocated extra reserve capacity for enabling offline
    /// updates.
    SetExtraReserveCapacity(CliAuxFsMetadataSetExtraReserveCapacityArgs),
    /// Add an entry.
    AddEntry(CliAuxFsMetadataAddEntryArgs),
    /// Remove an entry
    RemoveEntry(CliAuxFsMetadataRemoveEntryArgs),
}

#[derive(clap::Args)]
struct CliAuxFsMetadataSetExtraReserveCapacityArgs {
    /// The extra reserve capacity to preallocate.
    ///
    /// The preallocated extra reserve capacity determines whether offline
    /// auxiliary filesystem metadata updates, i.e. when the key is
    /// inaccessible, will be possible. If set to "disabled", no offline
    /// updates will be possible.  Otherwise offline updates will be enabled,
    /// with a total size increase up to the preallocated extra SIZE.
    #[arg(value_name = "disabled|SIZE")]
    extra_reserve_capacity: CliAuxFsMetadataExtraReserveCapacityValue,
}

#[derive(clap::Args)]
struct CliAuxFsMetadataAddEntryArgs {
    /// UUID of the entry to add.
    uuid: CliUuidValue,
    /// Input file providing the data to write [default: standard input].
    #[arg(name = "input-file", short, long, value_name = "FILE")]
    in_file_path: Option<PathBuf>,
}

#[derive(clap::Args)]
struct CliAuxFsMetadataRemoveEntryArgs {
    /// UUID of the entry to remove.
    uuid: CliUuidValue,
    /// Selection index within the sequence of all entries with matching UUIDs.
    #[arg(default_value_t = 0)]
    index: usize,
}

#[derive(clap::Args)]
struct CliWriteFileArgs {
    #[command(flatten)]
    key: CliKeySource,

    /// Input file providing the data to write [default: standard input].
    #[arg(name = "input-file", short, long, value_name = "FILE")]
    in_file_path: Option<PathBuf>,

    /// Don't randomize unallocated storage regions.
    #[arg(name = "no-randomize-unallocated", long, short = 'n')]
    enable_trimming: bool,

    /// Inode number of the file to write to.
    #[arg(value_name="INODE-NUMBER", value_parser = clap::value_parser!(u64).range(16..))]
    inode: u64,

    /// Flags value to set for the inode.
    #[arg(value_name="INODE-FLAGS", value_parser = clap::value_parser!(u8), default_value_t = 0)]
    inode_flags: u8,
}

#[derive(clap::Args)]
struct CliReadFileArgs {
    #[command(flatten)]
    key: CliKeySource,

    /// Output file to write the read data to [default: standard output].
    #[arg(name = "output-file", short, long, value_name = "FILE")]
    out_file_path: Option<PathBuf>,

    /// Don't randomize unallocated storage regions.
    #[arg(name = "no-randomize-unallocated", long, short = 'n')]
    enable_trimming: bool,

    /// Inode number of the file to read from.
    #[arg(value_name="INODE-NUMBER", value_parser = clap::value_parser!(u64).range(16..))]
    inode: u64,
}

#[derive(clap::Args)]
struct CliListFilesArgs {
    #[command(flatten)]
    key: CliKeySource,

    /// Don't randomize unallocated storage regions.
    #[arg(name = "no-randomize-unallocated", long, short = 'n')]
    enable_trimming: bool,
}

#[derive(clap::Args)]
struct CliRemoveFile {
    #[command(flatten)]
    key: CliKeySource,

    /// Don't randomize unallocated storage regions.
    #[arg(name = "no-randomize-unallocated", long, short = 'n')]
    enable_trimming: bool,

    /// Inode number to delete.
    #[arg(value_name="INODE-NUMBER", value_parser = clap::value_parser!(u64).range(16..))]
    inode: u64,
}

#[derive(clap::Args)]
struct CliMkfsInfo {
    /// Hash algorithm familiy to use for filesystem authentication.
    ///
    /// Hash algorithms from the given family will get selected for various
    /// purposes as suitable for the specified target security strength.
    #[arg(name = "hash-family", short = 'H', long, value_name = "HASH-FAMILY")]
    hash_familiy: CliHashFamiliy,

    /// Block cipher algorithm to use for filesystem encryption.
    ///
    /// The key size will get chosen as appropriate such that the specified
    /// target security strength is met.
    #[arg(name = "cipher", short = 'C', long, value_name = "CIPHER")]
    block_cipher: CliBlockCipher,

    /// Target security strength in bits
    #[arg(name = "target-security-strength", short, long, value_name = "BITS")]
    target_security_strength: CliSecurityStrength,

    #[command(flatten)]
    salt: CliSaltSource,

    /// Filesystem image size [default: backing file's size, if available].
    #[arg(name = "image-size", long, short = 's', value_name = "SIZE")]
    image_size: Option<CliSizeValue>,

    /// Initial allocated auxiliary filesystem metadata extra reserve capacity.
    ///
    /// The preallocated extra reserve capacity determines whether offline
    /// auxiliary filesystem metadata updates, i.e. when the key is
    /// inaccessible, will be possible. If set to "disabled", no offline
    /// updates will be possible.  Otherwise offline updates will be enabled,
    /// with a total size increase up to the preallocated extra SIZE.
    #[arg(long, value_name = "disabled|SIZE", default_value = "1K")]
    aux_fs_metadata_extra_reserve_capacity: CliAuxFsMetadataExtraReserveCapacityValue,

    /// Allocation Block size.
    ///
    /// Unit of allocation. Must be a power of two >= 128B.
    #[arg(long, value_name = "SIZE", default_value = "128B")]
    allocation_block_size: CliPowerOfTwoSizeValue<7>,

    /// IO Block size [default: max of 512B and Allocation Block size].
    ///
    /// Upper bound on the supported storage hardware's native IO size. Must be
    /// a power of two multiple <= 64 of the Allocation Block size.
    #[arg(long, value_name = "SIZE")]
    io_block_size: Option<CliPowerOfTwoSizeValue<7>>,

    /// Authentication Tree Data Block size [default: IO Block size].
    ///
    /// Unit of data authentication, controlling the fan-out at the
    /// authentication tree leaf nodes: larger values decrease the
    /// authentication tree height, but at the cost of making data
    /// authentication more coarse grained. Must be a power of two multiple <=
    /// 64 of the Allocation Block size.
    #[arg(long, value_name = "SIZE")]
    auth_tree_data_block_size: Option<CliPowerOfTwoSizeValue<7>>,

    /// Authentication Tree node size [default: max of 1024B and IO Block size].
    ///
    /// Size of an authentication tree node, controlling the tree's branching
    /// factor: larger values decrease the authentication tree height, but
    /// at the cost of having to process larger nodes. Must be a power of
    /// two >= the IO Block size.
    #[arg(long, value_name = "SIZE")]
    auth_tree_node_size: Option<CliPowerOfTwoSizeValue<7>>,

    /// Inode index B+-tree leaf node size [default: Allocation Block size].
    ///
    /// Size of a leaf node in the inode index B+-tree, controlling the number
    /// of inode entries that can be stored in a leaf node. Must be a power of
    /// two multiple <= 64 of the Allocation Block size.
    #[arg(long, value_name = "SIZE")]
    inode_index_tree_leaf_node_size: Option<CliPowerOfTwoSizeValue<7>>,

    /// Inode index B+-tree internal node size [default: Allocation Block size].
    ///
    /// Size of a internal node in the inode index B+-tree, controlling the
    /// tree's branching factor. Must be a power of two multiple <= 64 of the
    /// Allocation Block size.
    #[arg(long, value_name = "SIZE")]
    inode_index_tree_internal_node_size: Option<CliPowerOfTwoSizeValue<7>>,

    /// Allocation bitmap block size [default: max of 512B and the
    /// Authentication Tree Data Block size].
    ///
    /// Encryption granularity of the Allocation bitmap. Each unit stores an IV,
    /// so larger values reduce the overhead, but increase the update
    /// granularity. Must be a power of two >= the Allocation Block size.
    #[arg(long, value_name = "SIZE")]
    allocation_bitmap_file_block_size: Option<CliPowerOfTwoSizeValue<7>>,
}

#[derive(Clone, clap::ValueEnum)]
enum CliHashFamiliy {
    #[cfg(feature = "sha2")]
    Sha2,
    #[cfg(feature = "sha3")]
    Sha3,
    #[cfg(feature = "sm3")]
    Sm3,
}

#[derive(Clone, clap::ValueEnum)]
enum CliBlockCipher {
    #[cfg(feature = "aes")]
    Aes,
    #[cfg(feature = "camellia")]
    Camellia,
    #[cfg(feature = "sm4")]
    Sm4,
}

#[derive(Clone, clap::ValueEnum)]
enum CliSecurityStrength {
    #[value(name = "128")]
    S128,
    #[value(name = "192")]
    S192,
    #[value(name = "256")]
    S256,
}

#[derive(clap::Args)]
#[group(required = true, multiple = false)]
struct CliKeySource {
    /// File containing the filesystem key.
    #[arg(name = "key-file", short = 'k', long, value_name = "FILE")]
    key_file_path: Option<PathBuf>,
    /// Filesystem key provided as a hexadecimal string.
    #[arg(name = "key", short = 'K', long, value_name = "HEX", value_parser = CliHexStringValueParser{})]
    key: Option<FixedVec<u8, 4>>,
}

#[derive(clap::Args)]
#[group(multiple = false)]
struct CliKeySourceOpt {
    /// File containing the filesystem key.
    #[arg(name = "key-file", short = 'k', long, value_name = "FILE")]
    key_file_path: Option<PathBuf>,
    /// Filesystem key provided as a hexadecimal string.
    #[arg(name = "key", short = 'K', long, value_name = "HEX", value_parser = CliHexStringValueParser{})]
    key: Option<FixedVec<u8, 4>>,
}

struct CliKeySourceRef<'a> {
    key_file_path: Option<&'a PathBuf>,
    key: Option<&'a FixedVec<u8, 4>>,
}

impl<'a> From<&'a CliKeySource> for CliKeySourceRef<'a> {
    fn from(value: &'a CliKeySource) -> Self {
        debug_assert!(value.key_file_path.is_some() || value.key.is_some());
        Self {
            key_file_path: value.key_file_path.as_ref(),
            key: value.key.as_ref(),
        }
    }
}

impl<'a> From<&'a CliKeySourceOpt> for Option<CliKeySourceRef<'a>> {
    fn from(value: &'a CliKeySourceOpt) -> Self {
        if value.key_file_path.is_none() && value.key.is_none() {
            None
        } else {
            Some(CliKeySourceRef {
                key_file_path: value.key_file_path.as_ref(),
                key: value.key.as_ref(),
            })
        }
    }
}

#[derive(clap::Args)]
#[group(required = true, multiple = false)]
struct CliSaltSource {
    /// File containing the filesystem salt/id.
    ///
    /// The salt will be stored in the filesystem image header and may
    /// be used filesystem image identification purposes. The salt's length
    /// must not exceed 255B.
    #[arg(name = "salt-file", short = 'i', long, value_name = "FILE")]
    salt_file_path: Option<PathBuf>,
    /// Filesystem salt/id provided as a hexadecimal string.
    ///
    /// The salt will be stored in the filesystem image header and may
    /// be used filesystem image identification purposes. The salt's length
    /// must not exceed 255B.
    #[arg(name = "salt", long, short = 'I', value_name = "HEX", value_parser = CliHexStringValueParser{})]
    salt: Option<FixedVec<u8, 4>>,
}

fn cli_mkfs_to_image_layout(cli: &CliMkfsInfo) -> ImageLayout {
    let allocation_block_size_128b_log2 = cli.allocation_block_size.size_log2 - 7;

    let io_block_allocation_blocks_log2 = if let Some(io_block_size) = cli.io_block_size {
        let io_block_size_128b_log2 = io_block_size.size_log2 - 7;
        if io_block_size_128b_log2 < allocation_block_size_128b_log2
            || io_block_size_128b_log2 - allocation_block_size_128b_log2 > 6
        {
            let mut cmd = Cli::command();
            cmd.error(
                clap::error::ErrorKind::ArgumentConflict,
                "IO Block size not a multiple of the Allocation Block size between 0 and 64",
            )
            .exit()
        }
        io_block_size_128b_log2 - allocation_block_size_128b_log2
    } else {
        (9u32 - 7).saturating_sub(allocation_block_size_128b_log2)
    };

    let auth_tree_data_block_allocation_blocks_log2 =
        if let Some(auth_tree_data_block_size) = cli.auth_tree_data_block_size {
            let auth_tree_data_block_size_128b_log2 = auth_tree_data_block_size.size_log2 - 7;
            if auth_tree_data_block_size_128b_log2 < allocation_block_size_128b_log2
                || auth_tree_data_block_size_128b_log2 - allocation_block_size_128b_log2 > 6
            {
                let mut cmd = Cli::command();
                cmd.error(
                    clap::error::ErrorKind::ArgumentConflict,
                    "Authentication Tree Data Block size not a multiple of the Allocation Block size between 0 and 64",
                )
                .exit()
            }
            auth_tree_data_block_size_128b_log2 - allocation_block_size_128b_log2
        } else {
            io_block_allocation_blocks_log2
        };

    let auth_tree_node_io_blocks_log2 = if let Some(auth_tree_node_size) = cli.auth_tree_node_size {
        let auth_tree_node_size_128b_log2 = auth_tree_node_size.size_log2 - 7;
        if auth_tree_node_size_128b_log2 < io_block_allocation_blocks_log2 + allocation_block_size_128b_log2 {
            let mut cmd = Cli::command();
            cmd.error(
                clap::error::ErrorKind::ArgumentConflict,
                "authentication tree node size size not a multiple of the IO Block size",
            )
            .exit()
        }
        auth_tree_node_size_128b_log2 - io_block_allocation_blocks_log2 - allocation_block_size_128b_log2
    } else {
        (10u32 - 7).saturating_sub(io_block_allocation_blocks_log2 + allocation_block_size_128b_log2)
    };

    let inode_index_tree_leaf_node_allocation_blocks_log2 =
        if let Some(inode_index_tree_leaf_node_size) = cli.inode_index_tree_leaf_node_size {
            let inode_index_tree_leaf_node_size_128b_log2 = inode_index_tree_leaf_node_size.size_log2 - 7;
            if inode_index_tree_leaf_node_size_128b_log2 < allocation_block_size_128b_log2
                || inode_index_tree_leaf_node_size_128b_log2 - allocation_block_size_128b_log2 > 6
            {
                let mut cmd = Cli::command();
                cmd.error(
                    clap::error::ErrorKind::ArgumentConflict,
                    "inode index tree leaf node size not a multiple of the Allocation Block size between 0 and 64",
                )
                .exit()
            }
            inode_index_tree_leaf_node_size_128b_log2 - allocation_block_size_128b_log2
        } else {
            0u32
        };

    let inode_index_tree_internal_node_allocation_blocks_log2 =
        if let Some(inode_index_tree_internal_node_size) = cli.inode_index_tree_internal_node_size {
            let inode_index_tree_internal_node_size_128b_log2 = inode_index_tree_internal_node_size.size_log2 - 7;
            if inode_index_tree_internal_node_size_128b_log2 < allocation_block_size_128b_log2
                || inode_index_tree_internal_node_size_128b_log2 - allocation_block_size_128b_log2 > 6
            {
                let mut cmd = Cli::command();
                cmd.error(
                    clap::error::ErrorKind::ArgumentConflict,
                    "inode index tree internal node size not a multiple of the Allocation Block size between 0 and 64",
                )
                .exit()
            }
            inode_index_tree_internal_node_size_128b_log2 - allocation_block_size_128b_log2
        } else {
            0u32
        };

    let allocation_bitmap_file_block_allocation_blocks_log2 =
        if let Some(allocation_bitmap_file_block_size) = cli.allocation_bitmap_file_block_size {
            let allocation_bitmap_file_block_size_128b_log2 = allocation_bitmap_file_block_size.size_log2 - 7;
            if allocation_bitmap_file_block_size_128b_log2 < allocation_block_size_128b_log2 {
                let mut cmd = Cli::command();
                cmd.error(
                    clap::error::ErrorKind::ArgumentConflict,
                    "allocation bitmap block size not a multiple of the Allocation Block size",
                )
                .exit()
            }
            allocation_bitmap_file_block_size_128b_log2 - allocation_block_size_128b_log2
        } else {
            (9u32 - 7)
                .saturating_sub(allocation_block_size_128b_log2)
                .max(auth_tree_data_block_allocation_blocks_log2)
        };

    let (preimage_resistant_hash, collision_resistant_hash) = match cli.hash_familiy {
        #[cfg(feature = "sha2")]
        CliHashFamiliy::Sha2 => match cli.target_security_strength {
            CliSecurityStrength::S128 => (TpmiAlgHash::Sha256, TpmiAlgHash::Sha256),
            CliSecurityStrength::S192 => (TpmiAlgHash::Sha256, TpmiAlgHash::Sha384),
            CliSecurityStrength::S256 => (TpmiAlgHash::Sha256, TpmiAlgHash::Sha512),
        },
        #[cfg(feature = "sha3")]
        CliHashFamiliy::Sha3 => match cli.target_security_strength {
            CliSecurityStrength::S128 => (TpmiAlgHash::Sha3_256, TpmiAlgHash::Sha3_256),
            CliSecurityStrength::S192 => (TpmiAlgHash::Sha3_256, TpmiAlgHash::Sha3_384),
            CliSecurityStrength::S256 => (TpmiAlgHash::Sha3_256, TpmiAlgHash::Sha3_512),
        },
        #[cfg(feature = "sm3")]
        CliHashFamiliy::Sm3 => match cli.target_security_strength {
            CliSecurityStrength::S128 => (TpmiAlgHash::Sm3_256, TpmiAlgHash::Sm3_256),
            CliSecurityStrength::S192 | CliSecurityStrength::S256 => {
                let mut cmd = Cli::command();
                cmd.error(
                    clap::error::ErrorKind::ArgumentConflict,
                    "hash family sm3 doesn't support specified target security strength",
                )
                .exit();
            }
        },
    };

    let block_cipher_alg = match cli.block_cipher {
        #[cfg(feature = "aes")]
        CliBlockCipher::Aes => SymBlockCipherAlg::Aes(match cli.target_security_strength {
            CliSecurityStrength::S128 => symcipher::SymBlockCipherAesKeySize::Aes128,
            CliSecurityStrength::S192 => symcipher::SymBlockCipherAesKeySize::Aes192,
            CliSecurityStrength::S256 => symcipher::SymBlockCipherAesKeySize::Aes256,
        }),
        #[cfg(feature = "camellia")]
        CliBlockCipher::Camellia => SymBlockCipherAlg::Camellia(match cli.target_security_strength {
            CliSecurityStrength::S128 => symcipher::SymBlockCipherCamelliaKeySize::Camellia128,
            CliSecurityStrength::S192 => symcipher::SymBlockCipherCamelliaKeySize::Camellia192,
            CliSecurityStrength::S256 => symcipher::SymBlockCipherCamelliaKeySize::Camellia256,
        }),
        #[cfg(feature = "sm4")]
        CliBlockCipher::Sm4 => SymBlockCipherAlg::Sm4(match cli.target_security_strength {
            CliSecurityStrength::S128 => symcipher::SymBlockCipherSm4KeySize::Sm4_128,
            CliSecurityStrength::S192 | CliSecurityStrength::S256 => {
                let mut cmd = Cli::command();
                cmd.error(
                    clap::error::ErrorKind::ArgumentConflict,
                    "block cipher sm4 doesn't support specified target security strength",
                )
                .exit();
            }
        }),
    };

    match ImageLayout::new(
        allocation_block_size_128b_log2 as u8,
        io_block_allocation_blocks_log2 as u8,
        auth_tree_node_io_blocks_log2 as u8,
        auth_tree_data_block_allocation_blocks_log2 as u8,
        allocation_bitmap_file_block_allocation_blocks_log2 as u8,
        inode_index_tree_leaf_node_allocation_blocks_log2 as u8,
        inode_index_tree_internal_node_allocation_blocks_log2 as u8,
        collision_resistant_hash, // auth_tree_node_hash_alg
        collision_resistant_hash, // auth_tree_data_hmac_hash_alg
        preimage_resistant_hash,  // auth_tree_root_hmac_hash_alg
        preimage_resistant_hash,  // preauth_cca_protection_hmac_hash_alg
        preimage_resistant_hash,  // kdf_hash_alg
        block_cipher_alg,
    ) {
        Ok(image_layout) => image_layout,
        Err(e) => {
            eprintln!("error: invalid filesystem configuration parameters: {e:?}");
            std::process::exit(3);
        }
    }
}

fn load_key(key_source: CliKeySourceRef<'_>) -> FixedVec<u8, 4> {
    if let Some(src_key) = key_source.key {
        let mut key = FixedVec::new_with_default(src_key.len()).unwrap();
        key.copy_from_slice(src_key);
        key
    } else if let Some(key_file_path) = key_source.key_file_path {
        let src_key = match fs::read(key_file_path) {
            Ok(src_key) => src_key,
            Err(e) => {
                eprintln!("error: failed to read key file: error={e}");
                std::process::exit(4);
            }
        };
        let mut key = FixedVec::new_with_default(src_key.len()).unwrap();
        key.copy_from_slice(&src_key);
        key
    } else {
        // The CLI parser ensures there's either of the two.
        debug_assert!(false);
        eprintln!("error: no key source specified on command line");
        std::process::exit(2);
    }
}

fn load_salt(salt_source: &CliSaltSource) -> FixedVec<u8, 4> {
    if let Some(src_salt) = salt_source.salt.as_ref() {
        let mut salt = FixedVec::new_with_default(src_salt.len()).unwrap();
        salt.copy_from_slice(src_salt);
        salt
    } else if let Some(salt_file_path) = salt_source.salt_file_path.as_ref() {
        let src_salt = match fs::read(salt_file_path) {
            Ok(src_salt) => src_salt,
            Err(e) => {
                eprintln!("error: failed to read salt file: error={e}");
                std::process::exit(4);
            }
        };
        let mut salt = FixedVec::new_with_default(src_salt.len()).unwrap();
        salt.copy_from_slice(&src_salt);
        salt
    } else {
        // The CLI parser ensures there's either of the two.
        debug_assert!(false);
        eprintln!("error: no salt source specified on command line");
        std::process::exit(2);
    }
}

const fn rng_hash_drbg_hash() -> TpmiAlgHash {
    let candidates: &[TpmiAlgHash] = &[
        #[cfg(feature = "sha2")]
        TpmiAlgHash::Sha512,
        #[cfg(feature = "sha3")]
        TpmiAlgHash::Sha3_512,
        #[cfg(feature = "sm3")]
        TpmiAlgHash::Sm3_256,
    ];
    candidates[0]
}

fn instantiate_rng() -> Box<rng::HashDrbg> {
    let drbg_hash = rng_hash_drbg_hash();
    let seed_len = rng::HashDrbg::min_seed_entropy_len(drbg_hash);
    let mut seed = FixedVec::<u8, 5>::new_with_default(seed_len).unwrap();
    if let Err(e) = getrandom::fill(&mut seed) {
        eprintln!("failed to obtain entropy for RNG seeding: error={e}");
        std::process::exit(4);
    }
    match rng::HashDrbg::instantiate(drbg_hash, &seed, None, Some(b"cocoonfs-cli")) {
        Ok(rng) => Box::new(rng),
        Err(e) => {
            eprintln!("failed to instantiate RNG: error={e:?}");
            std::process::exit(4);
        }
    }
}

fn open_volume_file_for_mkfs(
    volume_file_path: &PathBuf,
    image_size: Option<u64>,
    max_io_block_size_128b_log2: Option<u32>,
) -> StdFileNvBlkDev {
    let mut open_flags = fs::OpenOptions::new();
    // We also want O_DIRECT, but standard Rust doesn't make it available.
    open_flags.read(true).write(true);
    if image_size.is_some() {
        // A pre-existing file isn't needed for determining the desired image size.
        open_flags.create(true);
    }
    let volume_file = match open_flags.open(volume_file_path) {
        Ok(volume_file) => volume_file,
        Err(e) => {
            if e.kind() == io::ErrorKind::NotFound && image_size.is_none() {
                eprintln!("error: filesystem image volume file doen't exist and no filesystem image size specified");
                std::process::exit(4);
            } else {
                eprintln!("error: failed to open filesystem image volume file: error={e}");
                std::process::exit(4);
            }
        }
    };

    // Truncate, ignore errors.
    match volume_file.set_len(0) {
        Ok(()) | Err(_) => (),
    };

    match StdFileNvBlkDev::new(volume_file, max_io_block_size_128b_log2) {
        Ok(blkdev) => blkdev,
        Err(_) => std::process::exit(5),
    }
}

fn open_blkdev(volume_file_path: &PathBuf, max_io_block_size_128b_log2: Option<u32>) -> StdFileNvBlkDev {
    let mut open_flags = fs::OpenOptions::new();
    // We also want O_DIRECT, but standard Rust doesn't make it available.
    open_flags.read(true).write(true);
    let volume_file = match open_flags.open(volume_file_path) {
        Ok(volume_file) => volume_file,
        Err(e) => {
            eprintln!("error: failed to open filesystem image volume file: error={e}");
            std::process::exit(4);
        }
    };

    match StdFileNvBlkDev::new(volume_file, max_io_block_size_128b_log2) {
        Ok(blkdev) => blkdev,
        Err(_) => std::process::exit(5),
    }
}

#[allow(clippy::type_complexity)]
fn open_filesystem(
    blkdev: StdFileNvBlkDev,
    key: &[u8],
    enable_trimming: bool,
) -> (
    Pin<
        <<StdSyncTypes as sync_types::SyncTypes>::SyncRcPtrFactory as sync_types::SyncRcPtrFactory>::SyncRcPtr<
            CocoonFsType,
        >,
    >,
    Box<dyn rng::RngCoreDispatchable + Send>,
) {
    let rng = instantiate_rng();
    let key = zeroize::Zeroizing::new(key.to_vec());
    let openfs_fut = match OpenFsFuture::<StdSyncTypes, StdFileNvBlkDev>::new(blkdev, None, key, enable_trimming, rng) {
        Ok(openfs_fut) => openfs_fut,
        Err((_blkdev, _key, _rng, e)) => {
            eprintln!("error: failed to initiate CocoonFs filesystem opening operation: error={e:?}");
            std::process::exit(6);
        }
    };
    match openfs_fut.block_on() {
        Ok((rng, Ok(fs_instance))) => (fs_instance, rng),
        Ok((_, Err((_, _, e)))) | Err(e) => {
            eprintln!("error: failed to open CocoonFs filesystem: error={e:?}");
            std::process::exit(6);
        }
    }
}

fn main() {
    let cli = Cli::parse();

    match cli.command {
        CliCommand::Mkfs(cli_mkfs_args) => {
            let image_layout = cli_mkfs_to_image_layout(&cli_mkfs_args.mkfsinfo);
            let key = load_key(CliKeySourceRef::from(&cli_mkfs_args.key));
            let salt = load_salt(&cli_mkfs_args.mkfsinfo.salt);
            let mut aux_fs_metadata = AuxFsMetadata::new();
            if let Err(e) = aux_fs_metadata
                .set_extra_reserve_capacity(cli_mkfs_args.mkfsinfo.aux_fs_metadata_extra_reserve_capacity.capacity)
            {
                eprintln!("error: failed to set auxiliary filesystem metadata extra reserve capacity: error={e:?}");
                std::process::exit(6);
            }

            let rng = instantiate_rng();
            let blkdev = open_volume_file_for_mkfs(
                &cli.volume_file_path,
                cli_mkfs_args.mkfsinfo.image_size.map(u64::from),
                (cli.ignore_volume_file_io_block_size).then_some(
                    image_layout.io_block_allocation_blocks_log2 as u32
                        + image_layout.allocation_block_size_128b_log2 as u32,
                ),
            );
            let mkfs_fut = match MkFsFuture::<StdSyncTypes, StdFileNvBlkDev>::new(
                blkdev,
                &image_layout,
                salt,
                aux_fs_metadata,
                cli_mkfs_args.mkfsinfo.image_size.map(u64::from),
                &key,
                cli_mkfs_args.enable_trimming,
                rng,
            ) {
                Ok(mkfs_fut) => mkfs_fut,
                Err((_blkdev, _rng, e)) => {
                    eprintln!("error: failed to initiate CocoonFs mkfs operation: error={e:?}");
                    std::process::exit(6);
                }
            };
            match mkfs_fut.block_on() {
                Ok((_rng, Ok(_fs_instance))) => (),
                Ok((_, Err((_, e)))) | Err(e) => {
                    eprintln!("error: CocoonFs mkfs operation failed: error={e:?}");
                    std::process::exit(6);
                }
            }
        }
        CliCommand::WriteMkfsInfoHeader(cli_write_mkfsinfo_header_args) => {
            let image_layout = cli_mkfs_to_image_layout(&cli_write_mkfsinfo_header_args.mkfsinfo);
            let salt = load_salt(&cli_write_mkfsinfo_header_args.mkfsinfo.salt);
            let mut aux_fs_metadata = AuxFsMetadata::new();
            if let Err(e) = aux_fs_metadata.set_extra_reserve_capacity(
                cli_write_mkfsinfo_header_args
                    .mkfsinfo
                    .aux_fs_metadata_extra_reserve_capacity
                    .capacity,
            ) {
                eprintln!("error: failed to set auxiliary filesystem metadata extra reserve capacity: error={e:?}");
                std::process::exit(6);
            }

            let blkdev = open_volume_file_for_mkfs(
                &cli.volume_file_path,
                cli_write_mkfsinfo_header_args.mkfsinfo.image_size.map(u64::from),
                (cli.ignore_volume_file_io_block_size).then_some(
                    image_layout.io_block_allocation_blocks_log2 as u32
                        + image_layout.allocation_block_size_128b_log2 as u32,
                ),
            );
            let write_mkfsinfo_header_fut = match WriteMkFsInfoHeaderFuture::new(
                blkdev,
                &image_layout,
                salt,
                aux_fs_metadata,
                cli_write_mkfsinfo_header_args.mkfsinfo.image_size.map(u64::from),
                !cli_write_mkfsinfo_header_args.trim_volume_file_to_header,
            ) {
                Ok(write_mkfsinfo_header_fut) => write_mkfsinfo_header_fut,
                Err((_blkdev, e)) => {
                    eprintln!("error: failed to initiate CocoonFs mkfsinfo header write operation: error={e:?}");
                    std::process::exit(6);
                }
            };
            match write_mkfsinfo_header_fut.block_on() {
                Ok((_blkdev, Ok(()))) => (),
                Ok((_, Err(e))) | Err(e) => {
                    eprintln!("error: CocoonFs mkfsinfo header write operation failed: error={e:?}");
                    std::process::exit(6);
                }
            }
        }
        CliCommand::AuxFsMetadata(cli_aux_fs_metdata_command) => {
            let blkdev = open_blkdev(&cli.volume_file_path, cli.ignore_volume_file_io_block_size.then_some(0));
            let read_fs_metadata_fut = match ReadFsMetadataFuture::new(blkdev) {
                Ok(read_fs_metadata_fut) => read_fs_metadata_fut,
                Err((_blkdev, e)) => {
                    eprintln!("error: failed to initiate CocoonFs metadata read operation: error={e:?}");
                    std::process::exit(6);
                }
            };
            let (blkdev, fs_metadata) = match read_fs_metadata_fut.block_on() {
                Ok((blkdev, Ok(fs_metadata))) => (blkdev, fs_metadata),
                Ok((_, Err(e))) | Err(e) => {
                    eprintln!("error: failed to read CocoonFs metadata: error={e:?}");
                    std::process::exit(6);
                }
            };

            match cli_aux_fs_metdata_command {
                CliAuxFsMetadataCommand::ListEntries => {
                    for entry in fs_metadata.get_aux().iter() {
                        println!("{}", CliUuidValue { uuid: *entry.0 });
                    }
                }
                CliAuxFsMetadataCommand::ReadEntry(cli_read_entry_args) => {
                    let mut index = cli_read_entry_args.index;
                    let mut found_entry = None;
                    for entry in fs_metadata.get_aux().iter() {
                        if *entry.0 == cli_read_entry_args.uuid.uuid {
                            if index == 0 {
                                found_entry = Some(entry);
                                break;
                            } else {
                                index -= 1;
                            }
                        }
                    }

                    let data = match found_entry {
                        Some(found_entry) => found_entry.1,
                        None => {
                            eprintln!("error: auxiliary filesystem metadata entry does not exist");
                            std::process::exit(6);
                        }
                    };

                    match cli_read_entry_args.out_file_path {
                        Some(out_file_path) => {
                            if let Err(e) = fs::write(out_file_path, data) {
                                eprintln!("error: failed to write data to output file: error={e}");
                                std::process::exit(4);
                            }
                        }
                        None => {
                            if let Err(e) = io::stdout().write_all(data) {
                                eprintln!("error: failed to write data to standard output: error={e}");
                                std::process::exit(4);
                            }
                        }
                    };
                }
                CliAuxFsMetadataCommand::Edit(cli_edit_args) => {
                    let mut updated_aux_fs_metadata = fs_metadata.get_aux().try_clone().unwrap();
                    match cli_edit_args.command {
                        CliAuxFsMetadataEditCommand::SetExtraReserveCapacity(cli_set_reserve_capacity_args) => {
                            if let Err(e) = updated_aux_fs_metadata.set_extra_reserve_capacity(
                                cli_set_reserve_capacity_args.extra_reserve_capacity.capacity,
                            ) {
                                eprintln!(
                                    "error: failed to set auxiliary filesystem metadata extra reserve capacity: error={e:?}"
                                );
                                std::process::exit(6);
                            }
                        }
                        CliAuxFsMetadataEditCommand::AddEntry(cli_add_entry_args) => {
                            let mut data = Vec::new();
                            match cli_add_entry_args.in_file_path.as_ref() {
                                Some(in_file_path) => match fs::read(in_file_path) {
                                    Ok(result) => data = result,
                                    Err(e) => {
                                        eprintln!("error: failed to read data from input file: error={e}");
                                        std::process::exit(4);
                                    }
                                },
                                None => {
                                    if let Err(e) = io::stdin().read_to_end(&mut data) {
                                        eprintln!("error: failed to read data from standard input: error={e}");
                                        std::process::exit(4);
                                    }
                                }
                            };

                            if let Err(e) = updated_aux_fs_metadata.add_entry(&cli_add_entry_args.uuid.uuid, &data) {
                                eprintln!("error: failed to add auxiliary filesystem metadata entry: error={e:?}");
                                std::process::exit(6);
                            }
                        }
                        CliAuxFsMetadataEditCommand::RemoveEntry(cli_remove_entry_args) => {
                            if !updated_aux_fs_metadata
                                .remove_entry(cli_remove_entry_args.uuid.uuid, cli_remove_entry_args.index)
                            {
                                eprintln!("error: auxiliary filesystem metadata entry does not exist");
                                std::process::exit(6);
                            }
                        }
                    }

                    // If there's a filesystem creation info header, then don't format the
                    // filesystem and do an offline update.
                    match Option::<CliKeySourceRef>::from(&cli_edit_args.key)
                        .filter(|_| matches!(&fs_metadata, FsMetadata::Formatted(_)))
                    {
                        Some(key_source) => {
                            let key = load_key(key_source);
                            // The filesystem is formatted and a key has been provided, open the
                            // filesystem and apply the update through a transaction.
                            let (fs_instance, rng) = open_filesystem(blkdev, &key, cli_edit_args.enable_trimming);
                            let (transaction, rng) = match NvFsFutureAsCoreFuture::new(
                                fs_instance.clone(),
                                <CocoonFsType as NvFs>::start_transaction(
                                    &cocoonfs_mk_fs_instance_ref(&fs_instance),
                                    None,
                                ),
                                rng,
                            )
                            .block_on()
                            {
                                Ok((rng, Ok(transaction))) => (transaction, rng),
                                Ok((_, Err(e))) | Err(e) => {
                                    eprintln!("error: failed to start CocoonFs transaction: error={e:?}");
                                    std::process::exit(6);
                                }
                            };

                            let (transaction, rng) = match NvFsFutureAsCoreFuture::new(
                                fs_instance.clone(),
                                CocoonFsType::write_aux_fs_metadata(
                                    &cocoonfs_mk_fs_instance_ref(&fs_instance),
                                    transaction,
                                    updated_aux_fs_metadata,
                                ),
                                rng,
                            )
                            .block_on()
                            {
                                Ok((rng, (_updated_aux_fs_metadata, Ok((transaction, Ok(())))))) => (transaction, rng),
                                Ok((_, (_, Ok((_, Err(e)))))) | Ok((_, (_, Err(e)))) | Err(e) => {
                                    eprintln!(
                                        "error: failed to stage auxiliary fileystem metadata update at CocoonFs transaction: error={e:?}"
                                    );
                                    std::process::exit(6);
                                }
                            };

                            match NvFsFutureAsCoreFuture::new(
                                fs_instance.clone(),
                                <CocoonFsType as NvFs>::commit_transaction(
                                    &cocoonfs_mk_fs_instance_ref(&fs_instance),
                                    transaction,
                                    None,
                                    None,
                                    true,
                                ),
                                rng,
                            )
                            .block_on()
                            {
                                Ok((_rng, Ok(()))) => (),
                                Ok((_rng, Err(e))) => {
                                    eprintln!("error: failed to commit CocoonFs transaction: error={e:?}");
                                    std::process::exit(6);
                                }
                                Err(e) => {
                                    eprintln!("error: failed to commit CocoonFs transaction: error={e:?}");
                                    std::process::exit(6);
                                }
                            }
                        }
                        None => {
                            // There's only a filesystem creation info header of the key wasn't
                            // provided, apply through an offline update.
                            match WriteAuxFsMetadataOfflineFuture::new(blkdev, fs_metadata, updated_aux_fs_metadata)
                                .block_on()
                            {
                                Ok((_blkdev, Ok(_updated_aux_fs_metadata))) => (),
                                Ok((_, Err(e))) | Err(e) => {
                                    eprintln!(
                                        "error: failed to write auxiliary fileystem metadata update: error={e:?}"
                                    );
                                    std::process::exit(6);
                                }
                            }
                        }
                    }
                }
            }
        }
        CliCommand::WriteFile(cli_write_file_args) => {
            let mut data = Vec::new();
            match cli_write_file_args.in_file_path.as_ref() {
                Some(in_file_path) => match fs::read(in_file_path) {
                    Ok(result) => data = result,
                    Err(e) => {
                        eprintln!("error: failed to read data from input file: error={e}");
                        std::process::exit(4);
                    }
                },
                None => {
                    if let Err(e) = io::stdin().read_to_end(&mut data) {
                        eprintln!("error: failed to read data from standard input: error={e}");
                        std::process::exit(4);
                    }
                }
            };

            let key = load_key(CliKeySourceRef::from(&cli_write_file_args.key));

            // If the volume file's block size is to be ignored, the it would be best to
            // resort to using the IO block size recorded in the filesystem
            // header. But that's not known as it currently stands, so use the
            // minimum possible then.
            let blkdev = open_blkdev(&cli.volume_file_path, cli.ignore_volume_file_io_block_size.then_some(0));
            let (fs_instance, rng) = open_filesystem(blkdev, &key, cli_write_file_args.enable_trimming);

            let (transaction, rng) = match NvFsFutureAsCoreFuture::new(
                fs_instance.clone(),
                <CocoonFsType as NvFs>::start_transaction(&cocoonfs_mk_fs_instance_ref(&fs_instance), None),
                rng,
            )
            .block_on()
            {
                Ok((rng, Ok(transaction))) => (transaction, rng),
                Ok((_, Err(e))) | Err(e) => {
                    eprintln!("error: failed to start CocoonFs transaction: error={e:?}");
                    std::process::exit(6);
                }
            };

            let (transaction, rng) = match NvFsFutureAsCoreFuture::new(
                fs_instance.clone(),
                <CocoonFsType as NvFs>::write_inode(
                    &cocoonfs_mk_fs_instance_ref(&fs_instance),
                    transaction,
                    cli_write_file_args.inode,
                    cli_write_file_args.inode_flags,
                    0xffu8,
                    zeroize::Zeroizing::new(data),
                ),
                rng,
            )
            .block_on()
            {
                Ok((rng, (_data, Ok((transaction, Ok(())))))) => (transaction, rng),
                Ok((_, (_, Ok((_, Err(e)))))) | Ok((_, (_, Err(e)))) | Err(e) => {
                    eprintln!("error: failed to stage file write at CocoonFs transaction: error={e:?}");
                    std::process::exit(6);
                }
            };

            match NvFsFutureAsCoreFuture::new(
                fs_instance.clone(),
                <CocoonFsType as NvFs>::commit_transaction(
                    &cocoonfs_mk_fs_instance_ref(&fs_instance),
                    transaction,
                    None,
                    None,
                    true,
                ),
                rng,
            )
            .block_on()
            {
                Ok((_rng, Ok(()))) => (),
                Ok((_rng, Err(e))) => {
                    eprintln!("error: failed to commit CocoonFs transaction: error={e:?}");
                    std::process::exit(6);
                }
                Err(e) => {
                    eprintln!("error: failed to commit CocoonFs transaction: error={e:?}");
                    std::process::exit(6);
                }
            }
        }
        CliCommand::ReadFile(cli_read_file_args) => {
            let key = load_key(CliKeySourceRef::from(&cli_read_file_args.key));

            // If the volume file's block size is to be ignored, the it would be best to
            // resort to using the IO block size recorded in the filesystem
            // header. But that's not known as it currently stands, so use the
            // minimum possible then.
            let blkdev = open_blkdev(&cli.volume_file_path, cli.ignore_volume_file_io_block_size.then_some(0));
            let (fs_instance, rng) = open_filesystem(blkdev, &key, cli_read_file_args.enable_trimming);

            let result = match NvFsFutureAsCoreFuture::new(
                fs_instance.clone(),
                <CocoonFsType as NvFs>::read_inode(
                    &cocoonfs_mk_fs_instance_ref(&fs_instance),
                    None,
                    cli_read_file_args.inode,
                ),
                rng,
            )
            .block_on()
            {
                Ok((_rng, Ok((_read_seq, Ok(result))))) => result,
                Ok((_, Ok((_, Err(e))))) | Ok((_, Err(e))) | Err(e) => {
                    eprintln!("error: failed to read CocoonFs inode data: error={e:?}");
                    std::process::exit(6);
                }
            };

            let data = match result {
                Some(result) => result.1,
                None => {
                    eprintln!("error: CocoonFs inode doesn't exist");
                    std::process::exit(6);
                }
            };

            match cli_read_file_args.out_file_path {
                Some(out_file_path) => {
                    if let Err(e) = fs::write(out_file_path, &data) {
                        eprintln!("error: failed to write data to output file: error={e}");
                        std::process::exit(4);
                    }
                }
                None => {
                    if let Err(e) = io::stdout().write_all(&data) {
                        eprintln!("error: failed to write data to standard output: error={e}");
                        std::process::exit(4);
                    }
                }
            };
        }
        CliCommand::ListFiles(cli_list_files_args) => {
            let key = load_key(CliKeySourceRef::from(&cli_list_files_args.key));

            // If the volume file's block size is to be ignored, the it would be best to
            // resort to using the IO block size recorded in the filesystem
            // header. But that's not known as it currently stands, so use the
            // minimum possible then.
            let blkdev = open_blkdev(&cli.volume_file_path, cli.ignore_volume_file_io_block_size.then_some(0));
            let (fs_instance, rng) = open_filesystem(blkdev, &key, cli_list_files_args.enable_trimming);

            let (consistent_read_sequence, mut rng) = match NvFsFutureAsCoreFuture::new(
                fs_instance.clone(),
                <CocoonFsType as NvFs>::start_read_sequence(&cocoonfs_mk_fs_instance_ref(&fs_instance)),
                rng,
            )
            .block_on()
            {
                Ok((rng, Ok(consistent_read_sequence))) => (consistent_read_sequence, rng),
                Ok((_, Err(e))) | Err(e) => {
                    eprintln!("error: failed to start consistent CocoonFs read sequence: error={e:?}");
                    std::process::exit(6);
                }
            };

            let mut enumerate_cursor = match <CocoonFsType as NvFs>::enumerate_cursor(
                &cocoonfs_mk_fs_instance_ref(&fs_instance),
                NvFsReadContext::Committed {
                    seq: consistent_read_sequence,
                },
                6..=u64::MAX,
            ) {
                Ok(Ok(enumerate_cursor)) => enumerate_cursor,
                Ok(Err((_, e))) | Err(e) => {
                    eprintln!("error: failed to instantiate CocoonFs enumeration cursor: error={e:?}");
                    std::process::exit(6);
                }
            };

            loop {
                let inode;
                (enumerate_cursor, rng, inode) =
                    match NvFsFutureAsCoreFuture::new(fs_instance.clone(), enumerate_cursor.next(), rng).block_on() {
                        Ok((rng, Ok((enumerate_cursor, Ok(inode))))) => (enumerate_cursor, rng, inode),
                        Ok((_, Ok((_, Err(e))))) | Ok((_, Err(e))) | Err(e) => {
                            eprintln!("error: failed to advance CocoonFs enumeration cursor: error={e:?}");
                            std::process::exit(6);
                        }
                    };

                match inode {
                    Some(inode) => {
                        let (inode, inode_flags) = inode;
                        println!("{inode} {inode_flags:#04x}")
                    }
                    None => break,
                };
            }
        }
        CliCommand::RemoveFile(cli_remove_file_args) => {
            let key = load_key(CliKeySourceRef::from(&cli_remove_file_args.key));

            // If the volume file's block size is to be ignored, the it would be best to
            // resort to using the IO block size recorded in the filesystem
            // header. But that's not known as it currently stands, so use the
            // minimum possible then.
            let blkdev = open_blkdev(&cli.volume_file_path, cli.ignore_volume_file_io_block_size.then_some(0));
            let (fs_instance, rng) = open_filesystem(blkdev, &key, cli_remove_file_args.enable_trimming);

            let (transaction, mut rng) = match NvFsFutureAsCoreFuture::new(
                fs_instance.clone(),
                <CocoonFsType as NvFs>::start_transaction(&cocoonfs_mk_fs_instance_ref(&fs_instance), None),
                rng,
            )
            .block_on()
            {
                Ok((rng, Ok(transaction))) => (transaction, rng),
                Ok((_, Err(e))) | Err(e) => {
                    eprintln!("error: failed to start CocoonFs transaction: error={e:?}");
                    std::process::exit(6);
                }
            };

            let mut unlink_cursor = match <CocoonFsType as NvFs>::unlink_cursor(
                &cocoonfs_mk_fs_instance_ref(&fs_instance),
                transaction,
                cli_remove_file_args.inode..=cli_remove_file_args.inode,
            ) {
                Ok(Ok(unlink_cursor)) => unlink_cursor,
                Ok(Err((_, e))) | Err(e) => {
                    eprintln!("error: failed to instantiate CocoonFs unlink cursor: error={e:?}");
                    std::process::exit(6);
                }
            };

            loop {
                let inode;
                (unlink_cursor, rng, inode) =
                    match NvFsFutureAsCoreFuture::new(fs_instance.clone(), unlink_cursor.next(), rng).block_on() {
                        Ok((rng, Ok((unlink_cursor, Ok(inode))))) => (unlink_cursor, rng, inode),
                        Ok((_, Ok((_, Err(e))))) | Ok((_, Err(e))) | Err(e) => {
                            eprintln!("error: failed to advance CocoonFs unlink cursor: error={e:?}");
                            std::process::exit(6);
                        }
                    };

                if inode.is_none() {
                    break;
                }

                (unlink_cursor, rng) =
                    match NvFsFutureAsCoreFuture::new(fs_instance.clone(), unlink_cursor.unlink_current_inode(), rng)
                        .block_on()
                    {
                        Ok((rng, Ok((unlink_cursor, Ok(()))))) => (unlink_cursor, rng),
                        Ok((_, Ok((_, Err(e))))) | Ok((_, Err(e))) | Err(e) => {
                            eprintln!("error: failed to stage inode removal at CocoonFs transaction: error={e:?}");
                            std::process::exit(6);
                        }
                    };
            }

            let transaction = match unlink_cursor.into_transaction() {
                Ok(transaction) => transaction,
                Err(e) => {
                    eprintln!("error: failed to retrieve transaction from CocoonFs unlink cursor: error={e:?}");
                    std::process::exit(6);
                }
            };

            match NvFsFutureAsCoreFuture::new(
                fs_instance.clone(),
                <CocoonFsType as NvFs>::commit_transaction(
                    &cocoonfs_mk_fs_instance_ref(&fs_instance),
                    transaction,
                    None,
                    None,
                    true,
                ),
                rng,
            )
            .block_on()
            {
                Ok((_rng, Ok(()))) => (),
                Ok((_rng, Err(e))) => {
                    eprintln!("error: failed to commit CocoonFs transaction: error={e:?}");
                    std::process::exit(6);
                }
                Err(e) => {
                    eprintln!("error: failed to commit CocoonFs transaction: error={e:?}");
                    std::process::exit(6);
                }
            }
        }
    }
}