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
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
//! The filesystem view: inodes, the names they are known by, and where their bytes are.
//!
//! [`Volume`] hands back tree blocks at logical addresses and knows nothing about files. This
//! is the layer that reads the records inside them as a filesystem — an inode item as a `stat`,
//! a directory item as a name, an extent record as a run of a file's bytes — and it is what
//! [`Reader`] is.
//!
//! # Where a file lives, and how little of it is in one place
//!
//! A btrfs inode is not a structure holding pointers to its data. It is a *run of one tree*,
//! keyed by its own number: the `INODE_ITEM` first, then the names it has, then its extended
//! attributes, then its extents in file order. Everything about one file is contiguous in the
//! tree and everything about the filesystem is in the same tree as everything else, so reading
//! a file is one descent to its number and a walk forward from there.
//!
//! # A directory holds every entry twice, on purpose
//!
//! A `DIR_ITEM` is keyed by the hash of the entry's name, so [`lookup`](Reader::lookup) finds a
//! name in one descent. A `DIR_INDEX` is keyed by the entry's sequence number, so
//! [`read_dir`](Reader::read_dir) lists a directory in the order its entries were created. Both
//! records hold the same thing and this reader uses each for what it is keyed for.
//!
//! # A subvolume is a directory that is a different tree
//!
//! A directory entry whose location names a `ROOT_ITEM` rather than an inode is where a
//! subvolume is mounted, where that subvolume's backref names the entry, and stepping through
//! it means continuing in another tree entirely. Any other entry naming a subvolume, as a
//! snapshot keeps for a nested one, is an empty directory, a [`Node::stub`]. A walk crosses
//! those seams, so what it yields is every name in the filesystem rather than
//! every name in one tree — and [`Node::tree`] is what says which tree a node was found in,
//! because an inode number means nothing without it.
//!
//! This module does I/O, through the volume it owns.
use std::collections::BTreeMap;
use std::io::{Read, Seek, Write};
use crate::compress::Algorithm;
use crate::fidelity::Synthesis;
use crate::finding::{Family, Severity};
use crate::policy::MAX_PATH;
use crate::source::Metadata;
use crate::time::Timestamp;
use crate::tree::{Attributes, Bound, Child, FsTree, NodeKind, TreeEntry, TreeError, Usage};
use crate::xattr::Xattr;
use crate::{Limits, OpenOptions, ReadPolicy};
use super::decode;
use super::ondisk::{
DirEntryType, DirItem, DiskKey, ExtentKind, FileExtentItem, InodeItem, ItemType, RootFlags,
RootItem, RootRef, for_each_packed, name_hash, objectid,
};
use super::scan::{
Category, Scan, ScanReport, has_live_log, mirror_anomaly, tree_name, walk_anomaly,
};
use super::volume::{ReadError, TreeRoot, Volume};
/// One inode of one subvolume: the tree it is in, the number it has there, and what it records.
///
/// **The pair is the identity.** An inode number is unique within a subvolume and no further,
/// so two subvolumes each have an inode 256 and they are different files. Every operation here
/// takes the pair, and a node handed to one taken out of another is a node from the wrong tree
/// rather than a coincidence.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Node {
/// Which subvolume's tree the inode lives in, by that subvolume's id.
pub tree: u64,
/// The inode number within that tree.
pub inode: u64,
/// What the inode records: mode, ownership, size, and the four times.
pub item: InodeItem,
/// Whether this is the empty directory standing where an entry names a subvolume linked
/// somewhere else, which is the shape a snapshot of a subvolume holding nested ones has.
///
/// Documented in `btrfs-subvolume(8)`: a snapshot is not recursive, and a subvolume nested
/// in the one snapshotted appears in the snapshot as an empty directory. The snapshot keeps
/// the entry naming it, and that subvolume's backref names the place it was created; an
/// entry the backref does not name is this stub. It holds nothing, and its tree holds no
/// inode for it: [`inode`](Self::inode) is the id of the subvolume the entry names, and
/// [`item`](Self::item) is the directory holding the entry's, as a directory of mode 0755.
pub stub: bool,
}
impl Node {
/// The inode's ownership, permission bits and times, as the shared vocabulary carries
/// them: the twelve bits below the file type, which the node's kind supplies, and the
/// four times whole, `otime` as the birth time.
#[must_use]
pub fn metadata(&self) -> Metadata {
Metadata {
mode: (self.item.mode & 0o7777) as u16,
uid: self.item.uid,
gid: self.item.gid,
atime: self.item.atime,
ctime: self.item.ctime,
mtime: self.item.mtime,
btime: Some(self.item.otime),
}
}
/// Whether the inode is a directory.
#[must_use]
pub const fn is_dir(&self) -> bool {
self.item.mode_type() == MODE_DIR
}
/// Whether the inode is a regular file, which is the only kind that holds bytes to read.
#[must_use]
pub const fn is_file(&self) -> bool {
self.item.mode_type() == MODE_REG
}
/// Whether the inode is a symbolic link.
#[must_use]
pub const fn is_symlink(&self) -> bool {
self.item.mode_type() == MODE_LNK
}
}
/// The `S_IFMT` value of a directory.
const MODE_DIR: u32 = 0o040_000;
/// The `S_IFMT` value of a regular file.
const MODE_REG: u32 = 0o100_000;
/// The `S_IFMT` value of a symbolic link.
const MODE_LNK: u32 = 0o120_000;
/// One entry of a directory, as it is stored.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Entry {
/// The name, exactly as the bytes are stored. btrfs stores a name as a byte string and
/// interprets no encoding, and neither does this.
pub name: Vec<u8>,
/// What the entry says it names, which the inode it points at says again.
pub kind: DirEntryType,
/// The key of what it names: an `INODE_ITEM` in the same tree, or a `ROOT_ITEM` where the
/// entry is where a subvolume is mounted.
pub location: DiskKey,
/// The entry's sequence number in the directory, which is what it is ordered by.
pub index: u64,
}
impl Entry {
/// Whether stepping through this entry means continuing in another tree.
#[must_use]
pub const fn is_subvolume(&self) -> bool {
matches!(self.location.kind, ItemType::ROOT_ITEM)
}
}
/// One subvolume of the filesystem: an independent tree of files, reachable as a directory of
/// another.
///
/// The top-level tree is one of these too. It is the one with no parent, and its
/// [`id`](Self::id) is the fixed number the format gives it.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Subvolume {
/// Its id, which is its tree's objectid and what a directory entry names it by.
pub id: u64,
/// Where its tree begins.
pub root: TreeRoot,
/// The inode its root directory has within its own tree.
pub root_dir: u64,
/// Whether it is read-only, which is what a snapshot taken for sending is.
pub read_only: bool,
/// Its own identity, which survives being sent elsewhere.
pub uuid: [u8; 16],
/// The subvolume this one was snapshotted from, all zeros where it was created outright.
pub parent_uuid: [u8; 16],
/// When it was created.
pub otime: Timestamp,
/// The subvolume it appears in, or [`None`] for the top-level tree.
pub parent: Option<u64>,
/// The inode of the directory it appears in, within its parent's tree.
pub parent_dir: u64,
/// The name it appears under there, empty for the top-level tree.
pub name: Vec<u8>,
}
/// One name a walk reached, and the node at it.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct WalkEntry {
/// Absolute path from the filesystem root, `/`-joined, always beginning with `/`. Empty
/// for the root itself, which is the first entry a walk yields.
pub path: Vec<u8>,
/// The node at that path.
pub node: Node,
}
/// A btrfs filesystem opened over a seekable source, read as files rather than as trees.
///
/// ```no_run
/// use ferrosys::btrfs::Reader;
///
/// let mut reader = Reader::open(std::fs::File::open("root.img")?)?;
/// let node = reader.lookup(b"/etc/hostname")?;
/// println!("{} bytes", node.item.size);
/// print!("{}", String::from_utf8_lossy(&reader.read_data(&node)?));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// The [`Volume`] underneath stays reachable, because the two layers answer different
/// questions: which trees are there and does every block verify is the volume's, and what is at
/// this path is this.
pub struct Reader<R> {
volume: Volume<R>,
subvolumes: Vec<Subvolume>,
top: Subvolume,
default_subvolume: u64,
}
impl<R: Read + Seek> Reader<R> {
/// This reader with a tree-block cache of `capacity` blocks. See
/// [`Volume::with_cache_capacity`].
#[cfg(test)]
fn with_cache_capacity(mut self, capacity: usize) -> Self {
self.volume = self.volume.with_cache_capacity(capacity);
self
}
/// Open the filesystem at the start of `src`, strictly, with the default limits.
///
/// # Errors
///
/// See [`open_with`](Self::open_with).
pub fn open(src: R) -> Result<Self, ReadError> {
Self::open_with(src, &OpenOptions::new())
}
/// Open the filesystem `options.base` bytes into `src`.
///
/// Opening reads the volume — every superblock copy, the bootstrap, and the chunk tree —
/// and then the root tree, which is what says how many subvolumes there are and where each
/// one's tree begins. The filesystem tree of the top-level subvolume is the view a path is
/// resolved in.
///
/// # Errors
///
/// Whatever [`Volume::open_with`] refuses, and [`ReadError::MissingTree`] where the root
/// tree holds no record of the top-level filesystem tree.
pub fn open_with(src: R, options: &OpenOptions) -> Result<Self, ReadError> {
let mut volume = Volume::open_with(src, *options)?;
let subvolumes = read_subvolumes(&mut volume)?;
let top = subvolumes
.iter()
.find(|sub| sub.id == objectid::FS_TREE)
.cloned()
.ok_or(ReadError::MissingTree {
objectid: objectid::FS_TREE,
})?;
let default_subvolume = read_default_subvolume(&mut volume)?.unwrap_or(objectid::FS_TREE);
Ok(Self {
volume,
subvolumes,
top,
default_subvolume,
})
}
/// The address space and the trees underneath, for the questions this layer does not ask.
#[must_use]
pub fn volume(&self) -> &Volume<R> {
&self.volume
}
/// The same, for an operation that reads — walking a tree, fetching a block.
pub fn volume_mut(&mut self) -> &mut Volume<R> {
&mut self.volume
}
/// Give the volume back, and with it the source it was opened over.
#[must_use]
pub fn into_volume(self) -> Volume<R> {
self.volume
}
/// How strictly this filesystem is being read.
#[must_use]
pub fn policy(&self) -> ReadPolicy {
self.volume.policy()
}
/// The caps this read is held to.
#[must_use]
pub fn limits(&self) -> Limits {
self.volume.limits()
}
/// Every subvolume the filesystem has, the top-level tree first and the rest in key order.
#[must_use]
pub fn subvolumes(&self) -> &[Subvolume] {
&self.subvolumes
}
/// The subvolume a path is resolved in and a walk begins at: the top-level filesystem tree.
#[must_use]
pub fn top_level(&self) -> &Subvolume {
&self.top
}
/// The subvolume the filesystem asks to be mounted at, which is the top-level tree unless
/// something has changed it.
///
/// A fact about the filesystem rather than a choice this reader makes: what is read here is
/// always the whole tree from the top level down, subvolumes included, so nothing about a
/// read depends on this. It is what a mount would do, reported.
#[must_use]
pub fn default_subvolume(&self) -> u64 {
self.default_subvolume
}
/// The root directory of the top-level subvolume.
///
/// # Errors
///
/// [`ReadError::MissingInode`] where the tree holds no record of its own root directory.
pub fn root(&mut self) -> Result<Node, ReadError> {
let top = self.top.clone();
self.inode(top.id, top.root_dir)
}
/// One inode of one subvolume.
///
/// # Errors
///
/// [`ReadError::MissingTree`] where the filesystem has no such subvolume, and
/// [`ReadError::MissingInode`] where that subvolume's tree holds no such inode.
pub fn inode(&mut self, tree: u64, inode: u64) -> Result<Node, ReadError> {
let root = self.tree_root(tree)?;
let key = DiskKey::new(inode, ItemType::INODE_ITEM, 0);
let found = self
.volume
.tree(root)
.find_exact(key)?
.ok_or(ReadError::MissingInode { tree, inode })?;
Ok(Node {
tree,
inode,
item: InodeItem::read_from(&found.data)?,
stub: false,
})
}
/// Every entry of a directory, in the order the directory stores them.
///
/// The order is the `DIR_INDEX` one, which is the order the entries were created and what a
/// readdir of the mounted filesystem yields. btrfs stores no `.` or `..` entry, so what
/// comes back is the directory's own contents and nothing else.
///
/// # Errors
///
/// [`ReadError::NotADirectory`] where the node is not one, whatever a walk of the tree
/// refuses, and [`ReadError::BadDirEntry`] where an entry does not describe a name.
pub fn read_dir(&mut self, node: &Node) -> Result<Vec<Entry>, ReadError> {
if !node.is_dir() {
return Err(ReadError::NotADirectory { path: Vec::new() });
}
if node.stub {
return Ok(Vec::new());
}
let root = self.tree_root(node.tree)?;
let from = DiskKey::first_of(node.inode, ItemType::DIR_INDEX);
let mut entries = Vec::new();
let mut failure = None;
self.volume
.tree(root)
.for_each_item_from(from, |key, data| {
if key.objectid != node.inode || key.kind != ItemType::DIR_INDEX {
return false;
}
// A `DIR_INDEX` key is one entry, so an item holding more than one record is
// a filesystem saying two entries have one sequence number. Framed the same
// way regardless, and every record kept: dropping the second would hide a
// name rather than report it.
let framed = for_each_packed::<DirItem, _>(data, |head, tail| {
let (name, _) = head.split(tail);
entries.push(Entry {
name: name.to_vec(),
kind: head.kind,
location: head.location,
index: key.offset,
});
true
});
match framed {
Ok(()) => true,
Err(e) => {
failure = Some(e.into());
false
}
}
})?;
match failure {
Some(e) => Err(e),
None => Ok(entries),
}
}
/// The node at `path`, resolved from the root of the top-level subvolume, expanding every
/// symbolic link along the way including one in the last component.
///
/// Each component is found through the `DIR_ITEM` keyed by the hash of its name, so a
/// resolution costs one descent per component rather than a listing per directory. A
/// component naming a subvolume continues in that subvolume's tree where the subvolume's
/// backref names that entry, which is what makes a path across a subvolume boundary one
/// path. Any other entry naming one is an empty directory, a [`Node::stub`].
///
/// A `..` component ascends to the directory the resolution descended from, staying at the
/// root where there is nothing to ascend to — so it crosses back out of a subvolume the
/// way it came in, and nothing outside the filesystem can be named.
///
/// Resolution follows at most [`MAX_SYMLINK_HOPS`](crate::MAX_SYMLINK_HOPS) links, so
/// a cycle terminates. A link whose target begins with `/` restarts at the top-level
/// subvolume's root; one that does not continues from the directory holding the link.
///
/// # Errors
///
/// [`ReadError::NotFound`] where no such name exists, [`ReadError::NotADirectory`] where a
/// component names something a name cannot be looked up in, and
/// [`ReadError::SymlinkLoop`] where the resolution follows too many links.
pub fn lookup(&mut self, path: &[u8]) -> Result<Node, ReadError> {
self.resolve(path, true)
}
/// The node at `path`, expanding symbolic links in every component *except* the last — so a
/// path naming a link yields the link and not what it points at. Otherwise as
/// [`lookup`](Self::lookup).
///
/// # Errors
///
/// As [`lookup`](Self::lookup).
pub fn lookup_no_follow(&mut self, path: &[u8]) -> Result<Node, ReadError> {
self.resolve(path, false)
}
/// Walk `path` component by component from the root, expanding symbolic links.
///
/// `follow_final` decides whether a link in the last component is expanded; the ones before
/// it always are, because a path cannot continue through a link without going where it
/// points. A distribution's root filesystem is the case that makes this obligatory rather
/// than a nicety: `/bin`, `/lib`, and `/sbin` are links to directories under `/usr` on every
/// current one, so a resolver that stopped at a link would find nothing under any of them.
fn resolve(&mut self, path: &[u8], follow_final: bool) -> Result<Node, ReadError> {
crate::resolve::drive(self, path, follow_final)
}
/// The entry of `dir` named `name`, or [`None`] where the directory holds no such name.
///
/// # Errors
///
/// Whatever a descent refuses, and [`ReadError::BadDirEntry`] where an item under the
/// name's own hash does not frame as entries.
pub fn find_entry(&mut self, dir: &Node, name: &[u8]) -> Result<Option<Entry>, ReadError> {
if dir.stub {
return Ok(None);
}
let root = self.tree_root(dir.tree)?;
let key = DiskKey::new(dir.inode, ItemType::DIR_ITEM, name_hash(name));
let Some(found) = self.volume.tree(root).find_exact(key)? else {
return Ok(None);
};
let mut entry = None;
for_each_packed::<DirItem, _>(&found.data, |head, tail| {
let (stored, _) = head.split(tail);
if stored == name {
entry = Some(Entry {
name: stored.to_vec(),
kind: head.kind,
location: head.location,
// The hashed copy of an entry does not carry its sequence number; the
// indexed copy is keyed by it. A caller that needs the order asks
// `read_dir`, which reads the copy that has it.
index: 0,
});
return false;
}
true
})?;
Ok(entry)
}
/// The node an entry of `dir` names, crossing into another subvolume where it names one.
///
/// # Errors
///
/// [`ReadError::MissingTree`] where an entry names a subvolume the root tree has no record
/// of, [`ReadError::MissingInode`] where it names an inode its tree does not hold, and
/// [`ReadError::BadDirEntry`] where it names neither.
pub fn step(&mut self, dir: &Node, entry: &Entry) -> Result<Node, ReadError> {
self.at_location(dir, &entry.name, entry.location)
}
/// Every extended attribute of a node, in the order the tree holds them.
///
/// The values are the boundary form — what `getxattr` would have returned — which is what
/// btrfs stores, so nothing is decoded on the way out. POSIX ACLs are `system.posix_acl_*`
/// attributes holding the bytes [`Acl::encode`](crate::Acl::encode) produces, like every
/// other value here.
///
/// # Errors
///
/// Whatever a walk of the tree refuses, and [`ReadError::BadXattr`] where a record does not
/// frame as a name and a value.
pub fn xattrs(&mut self, node: &Node) -> Result<Vec<Xattr>, ReadError> {
if node.stub {
return Ok(Vec::new());
}
let root = self.tree_root(node.tree)?;
let from = DiskKey::first_of(node.inode, ItemType::XATTR_ITEM);
let mut out = Vec::new();
let mut failure = None;
self.volume
.tree(root)
.for_each_item_from(from, |key, data| {
if key.objectid != node.inode || key.kind != ItemType::XATTR_ITEM {
return false;
}
let framed = for_each_packed::<DirItem, _>(data, |head, tail| {
let (name, value) = head.split(tail);
out.push(Xattr {
name: name.to_vec(),
value: value.to_vec(),
});
true
});
match framed {
Ok(()) => true,
Err(_) => {
failure = Some(ReadError::BadXattr {
tree: node.tree,
inode: node.inode,
});
false
}
}
})?;
match failure {
Some(e) => Err(e),
None => Ok(out),
}
}
/// Fill `buf` from `offset` in a regular file, returning how many bytes were placed.
///
/// A short fill means the file ends there. A run the file never had written — a hole, or a
/// preallocated extent nothing has been put in — reads back as zeros, which is what it is.
///
/// A node that is not a regular file holds no bytes and yields none: a directory's storage
/// is its entries and a device node's is a pair of numbers, and handing either back as
/// contents would be a record read as data.
///
/// # Errors
///
/// [`ReadError::BadExtent`] where an extent record does not describe a run of the file,
/// [`ReadError::UnsupportedCompression`] where its bytes are stored in a form this build
/// does not decode, and whatever reading the tree or the data refuses.
pub fn read_into(
&mut self,
node: &Node,
offset: u64,
buf: &mut [u8],
) -> Result<usize, ReadError> {
if !node.is_file() && !node.is_symlink() {
return Ok(0);
}
let size = node.item.size;
if offset >= size || buf.is_empty() {
return Ok(0);
}
let want = buf
.len()
.min(usize::try_from(size - offset).unwrap_or(usize::MAX));
let out = &mut buf[..want];
// Everything the extents do not cover is a hole, so the answer starts as zeros and
// what is read overwrites them. A record that covers nothing therefore leaves the
// right bytes rather than whatever the caller's buffer held.
out.fill(0);
let end = offset + want as u64;
for (at, item, raw) in self.extent_records(node, offset, end)? {
self.place_extent(node, at, &item, &raw, offset, out)?;
}
Ok(want)
}
/// Every byte of a regular file, gathered into memory.
///
/// Held to [`Limits::max_file_bytes`](crate::Limits::max_file_bytes), which defaults to no
/// cap: a file's declared length is a number an image supplies, and a hole reads back as
/// zeros, so an inode claiming a terabyte and mapping nothing costs a terabyte of them.
/// Behind the caller's cap sits the machine's — a buffer no allocation can represent is
/// refused with the same error, never attempted.
///
/// # Errors
///
/// [`ReadError::FileTooLarge`] where the file is longer than that cap, and whatever
/// [`read_into`](Self::read_into) refuses.
pub fn read_data(&mut self, node: &Node) -> Result<Vec<u8>, ReadError> {
let size = node.item.size;
// The declared size is a number the image supplies. The caller's cap defaults to
// trusting it, but a buffer is addressed in `isize`, so a size past that bound has no
// allocation to trust it into — asking would abort rather than fail, and every other
// value an image oversupplies is a refusal.
let cap = self.limits().max_file_bytes.min(isize::MAX as u64);
if size > cap {
return Err(ReadError::FileTooLarge {
tree: node.tree,
inode: node.inode,
size,
cap,
});
}
let mut out = vec![0u8; size as usize];
let mut at = 0usize;
while at < out.len() {
let placed = self.read_into(node, at as u64, &mut out[at..])?;
if placed == 0 {
break;
}
at += placed;
}
out.truncate(at);
Ok(out)
}
/// Stream a regular file's bytes to `out`, returning how many were written.
///
/// Bounded by a fixed buffer rather than by the file, so a file far larger than memory
/// streams through. The same [`Limits::max_file_bytes`](crate::Limits::max_file_bytes)
/// cap applies as to [`read_data`](Self::read_data), checked before a byte is written:
/// what the cap expresses is distrust of the declared length, and a stream writes every
/// byte that length claims — a hole reads back as zeros — as surely as a buffer holds them.
///
/// # Errors
///
/// [`ReadError::FileTooLarge`] where the file is longer than that cap, whatever
/// [`read_into`](Self::read_into) refuses, and [`ReadError::Io`] where the destination
/// could not be written.
pub fn read_data_to(&mut self, node: &Node, mut out: impl Write) -> Result<u64, ReadError> {
let size = node.item.size;
let cap = self.limits().max_file_bytes;
if size > cap {
return Err(ReadError::FileTooLarge {
tree: node.tree,
inode: node.inode,
size,
cap,
});
}
let mut buf = vec![0u8; STREAM_BUFFER];
let mut at = 0u64;
loop {
let placed = self.read_into(node, at, &mut buf)?;
if placed == 0 {
return Ok(at);
}
out.write_all(&buf[..placed])?;
at += placed as u64;
}
}
/// A symbolic link's target, exactly as the filesystem records it.
///
/// A link's target is its contents, and btrfs stores it as an inline extent — so this is a
/// whole-file read with the length the inode declares, and nothing here resolves what comes
/// back.
///
/// # Errors
///
/// [`ReadError::NotASymlink`] where the node is not one, and whatever reading its bytes
/// refuses.
pub fn link_target(&mut self, node: &Node) -> Result<Vec<u8>, ReadError> {
if !node.is_symlink() {
return Err(ReadError::NotASymlink {
tree: node.tree,
inode: node.inode,
});
}
self.read_data(node)
}
/// Every name in the filesystem, gathered.
///
/// The root comes first under the empty path, then depth-first with a parent before its
/// children and siblings in the order their directory stores them.
///
/// # Errors
///
/// As [`walk_with`](Self::walk_with).
pub fn walk(&mut self) -> Result<Vec<WalkEntry>, ReadError> {
let mut out = Vec::new();
self.walk_with::<ReadError, _>(|_, entry| {
out.push(entry);
Ok(())
})?;
Ok(out)
}
/// Walk every name in the filesystem, calling `visit` for each.
///
/// The visitor is handed the reader back, so it can stat, read, and resolve while the walk
/// is in progress and nothing has to be gathered up front.
///
/// **Subvolume boundaries are crossed**, so what is walked is the filesystem rather than
/// one tree. Every bound a walk of an untrusted tree needs — the cycle a crafted image can
/// describe, the frontier, the depth — is the crate's shared walk rather than this
/// family's, and what this family supplies is the three things it genuinely decides: what
/// sits on the frontier, what identifies a directory, and how a directory's names are read.
///
/// # Errors
///
/// Whatever the visitor returns, and a [`ReadError`] converted into it where the filesystem
/// cannot be walked — including [`ReadError::RepeatedDirectory`] under
/// [`ReadPolicy::Strict`] where an entry names a directory the tree already reaches, and
/// [`ReadError::WalkTooLarge`] where the walk reaches the caller's cap.
pub fn walk_with<E, F>(&mut self, mut visit: F) -> Result<(), E>
where
E: From<ReadError>,
F: FnMut(&mut Self, WalkEntry) -> Result<(), E>,
{
// The root has no name, so the walk seeds from its children rather than from it.
// Yielding it first under the empty path is what lets a sink apply the root's own
// metadata without a second way of asking for it.
let root = self.root().map_err(E::from)?;
visit(
self,
WalkEntry {
path: Vec::new(),
node: root,
},
)?;
crate::walk::drive(self, |reader, entry| visit(reader, entry))
}
/// Walk the whole filesystem and report every deviation, rather than stopping at the first.
///
/// A read stops where it cannot go on. This does not: every tree the filesystem has is
/// walked block by block — which verifies the checksum of every one of them — and what
/// cannot be read becomes a finding rather than an error. An empty report is a filesystem
/// nothing here objects to.
///
/// Three of what it reports are this family's own: **a live log tree**, which means the
/// committed trees are stale with respect to writes this reader does not replay, reported
/// in the sentence every family uses for a filesystem left mounted; **a tree block read
/// through a later copy** because its first failed its checks; and **item types this
/// reader has no opinion about**, which are skipped, counted, and named.
///
/// What it does *not* do is verify file data. That is
/// [`verify_data`](Self::verify_data), per file, because it reads every byte of the volume
/// rather than every byte of its metadata — a different order of cost, and a caller asking
/// whether an image is sound should not pay it without asking.
#[must_use]
pub fn scan(&mut self) -> ScanReport {
let mut scan = Scan::new(self.limits().max_findings);
let live = self.volume.superblock().generation;
for (index, &state) in self.volume.mirrors().iter().enumerate() {
if let Some((severity, detail)) = mirror_anomaly(state, live) {
scan.at(
Category::Superblock,
severity,
None,
None,
format!("copy {index} of the superblock: {detail}"),
);
}
}
// A device longer than its source: the bytes past the source's end are bytes the
// filesystem counts on and does not have. `btrfs check` 7.1 reports it as an error
// (observed), and nothing else here does where no copy of the superblock and no tree
// block falls in the missing part.
let device = self.volume.superblock().dev_item.total_bytes;
let held = self.volume.source_bytes();
if device > held {
scan.at(
Category::Superblock,
Severity::Structural,
None,
None,
format!(
"the device records {device} bytes and the source holds {held} from where \
the filesystem begins"
),
);
}
if has_live_log(&self.volume) {
// The one instance of this rule across the families where "cosmetic" is
// arguable. The message
// says what is missing rather than which field held an unexpected value: the
// filesystem genuinely holds writes the committed trees do not, and every byte
// this reader hands back is nonetheless the last committed transaction's.
scan.at(
Category::Superblock,
Severity::Cosmetic,
None,
Some(self.volume.superblock().log_root),
format!(
"{}; what is read here is the last committed transaction, without the \
writes its log tree holds",
crate::finding::NOT_CLEANLY_UNMOUNTED
),
);
}
let roots = match self.volume.tree_roots() {
Ok(roots) => roots,
Err(e) => {
let (category, severity) = walk_anomaly(&e);
scan.at(
category,
severity,
Some(objectid::ROOT_TREE),
None,
format!("the root tree, which names every other: {e}"),
);
return scan.finish();
}
};
for &root in &roots {
if scan.found.is_full() {
break;
}
// Every item of every tree, so the checksum of every block is verified on the way
// and every item type met is counted. What the walk *means* is not asked here:
// this pass is about whether the filesystem describes itself consistently.
let walked = self.volume.tree(root).for_each_item(|key, _| {
scan.met_unknown(key.kind);
!scan.found.is_full()
});
if let Err(e) = walked {
let (category, severity) = walk_anomaly(&e);
scan.at(
category,
severity,
Some(root.objectid),
Some(root.bytenr),
format!("{}: {e}", tree_name(root.objectid)),
);
}
}
self.scan_uuid_mapping(&roots, &mut scan);
for &logical in self.volume.bootstrap_conflicts() {
scan.at(
Category::ChunkMap,
Severity::Integrity,
Some(objectid::CHUNK_TREE),
Some(logical),
"the chunk tree maps this chunk differently from the superblock's bootstrap \
array; the bootstrap's mapping, which read the chunk tree, is the one used"
.to_string(),
);
}
for (&logical, through) in self.volume.read_through() {
scan.at(
Category::Tree,
Severity::Integrity,
None,
Some(logical),
format!(
"the first copy of this tree block failed its checks ({}), and it was read \
through copy {}",
through.fault, through.copy
),
);
}
scan.finish()
}
/// Hold the UUID tree and the subvolume root items to each other.
///
/// Each names the other: a subvolume's root item records its identifier, and the UUID tree
/// maps that identifier back to the subvolume. The pair can disagree while every block and
/// every item of both trees verifies — a lookup by identifier then misses, and the format's
/// own tooling rewrites the tree on the next writable mount — so the agreement is a check
/// of its own rather than a property a walk implies. An all-zero identifier records that
/// none was set, and has no entry to be held to.
fn scan_uuid_mapping(&mut self, roots: &[TreeRoot], scan: &mut Scan) {
let Some(&uuid_root) = roots
.iter()
.find(|root| root.objectid == objectid::UUID_TREE)
else {
return;
};
// What the root items record, keyed by subvolume id. Gathered when the filesystem was
// opened, so this reads it rather than walking the root tree again.
let recorded: std::collections::HashMap<u64, [u8; 16]> = self
.subvolumes
.iter()
.map(|sub| (sub.id, sub.uuid))
.collect();
let mut satisfied: std::collections::HashSet<u64> = std::collections::HashSet::new();
let walked = self.volume.tree(uuid_root).for_each_item(|key, data| {
if key.kind != ItemType::UUID_SUBVOL {
return true;
}
// The key is the identifier split in half; the data is the subvolume ids it maps
// to, 8 bytes each.
let mut uuid = [0u8; 16];
uuid[..8].copy_from_slice(&key.objectid.to_le_bytes());
uuid[8..].copy_from_slice(&key.offset.to_le_bytes());
if data.is_empty() || data.len() % 8 != 0 {
scan.at(
Category::Item,
Severity::Structural,
Some(objectid::UUID_TREE),
None,
format!(
"the UUID tree's entry for {} holds {} bytes, which is not a list of \
8-byte subvolume ids",
crate::escape::hex(&uuid),
data.len()
),
);
return !scan.found.is_full();
}
for id in data.as_chunks::<8>().0 {
let id = u64::from_le_bytes(*id);
match recorded.get(&id) {
Some(held) if *held == uuid => {
satisfied.insert(id);
}
Some(_) => scan.at(
Category::Item,
Severity::Structural,
Some(objectid::UUID_TREE),
None,
format!(
"the UUID tree maps identifier {} to subvolume {id}, whose root \
item records a different identifier",
crate::escape::hex(&uuid)
),
),
None => scan.at(
Category::Item,
Severity::Structural,
Some(objectid::UUID_TREE),
None,
format!(
"the UUID tree maps identifier {} to subvolume {id}, which does \
not exist",
crate::escape::hex(&uuid)
),
),
}
}
!scan.found.is_full()
});
if walked.is_err() {
// The walk of this tree failed in the pass above and was reported there; the
// mapping cannot be judged on a tree that does not walk.
return;
}
for sub in &self.subvolumes {
if scan.found.is_full() {
break;
}
if sub.uuid != [0; 16] && !satisfied.contains(&sub.id) {
scan.at(
Category::Item,
Severity::Structural,
Some(objectid::UUID_TREE),
None,
format!(
"subvolume {} records identifier {} and the UUID tree has no entry \
mapping it back",
sub.id,
crate::escape::hex(&sub.uuid)
),
);
}
}
}
/// Hold every byte of a regular file against the checksums the filesystem recorded for it.
///
/// **The check no other family in this crate can make.** ext4 checksums its metadata and
/// not its data; neither FAT nor exFAT checksums anything. btrfs keeps a checksum per
/// sector of every data extent in a tree of its own, in the algorithm its superblock names, so an extent that has decayed on the medium,
/// or a file whose bytes were replaced under a correct-looking tree, is detectable — and a
/// reader that verified only what it walked through would not detect either.
///
/// What is verified is the bytes **on the volume**, which is what the checksums cover. A
/// compressed extent is therefore verifiable without being decompressed, and this verifies
/// one.
///
/// Three kinds of run are skipped, and each for a reason the format states: a hole and a
/// preallocated extent hold nothing to check, and a file whose inode carries
/// [`NODATASUM`](super::ondisk::InodeFlags::NODATASUM) has no checksums recorded at all.
///
/// # Errors
///
/// [`ReadError::DataChecksum`] naming the address whose bytes do not match,
/// [`ReadError::MissingDataChecksum`] where a file that should have one has none, and
/// whatever reading the trees or the data refuses.
pub fn verify_data(&mut self, node: &Node) -> Result<(), ReadError> {
if !node.is_file() && !node.is_symlink() {
return Ok(());
}
if node
.item
.flags
.contains(super::ondisk::InodeFlags::NODATASUM)
{
return Ok(());
}
let sector = u64::from(self.volume.superblock().sectorsize);
let csum_type = self.volume.superblock().csum_type;
let records = self.extent_records(node, 0, u64::MAX)?;
for (at, item, _) in records {
if item.kind.is_inline() || item.is_hole() || item.kind == ExtentKind::Prealloc {
continue;
}
// The sectors this record's bytes are read from. A compressed extent is one stream,
// so every byte a record reads depends on the whole of it, and the whole extent is
// checked. An uncompressed record reads its own share, from its offset for its
// length, and that share is what holds checksums: a write into part of a
// preallocated extent leaves a regular record over the written sectors, which
// carry checksums, and preallocated records over the rest, which do not.
let bad = || ReadError::BadExtent {
tree: node.tree,
inode: node.inode,
at,
fault: "the extent's address runs past the end of the address space",
};
let (from, len) = if item.compression == super::ondisk::Compression::None {
let first = item.offset - item.offset % sector;
let last = item
.offset
.checked_add(item.num_bytes)
.ok_or_else(bad)?
.next_multiple_of(sector)
.min(item.disk_num_bytes.max(first));
(first, last - first)
} else {
(0, item.disk_num_bytes)
};
let mut logical = item.disk_bytenr.checked_add(from).ok_or_else(bad)?;
let end = logical.checked_add(len).ok_or_else(bad)?;
let mut buf = vec![0u8; sector as usize];
while logical < end {
let take = (end - logical).min(sector) as usize;
self.volume.read_at(logical, &mut buf[..take])?;
let recorded = self
.data_checksum(logical)?
.ok_or(ReadError::MissingDataChecksum { logical })?;
if csum_type.field(&buf[..take]) != Some(recorded) {
return Err(ReadError::DataChecksum { logical });
}
logical += take as u64;
}
}
Ok(())
}
/// The checksum the checksum tree records for the sector at `logical`, or [`None`] where it
/// records none.
///
/// An `EXTENT_CSUM` item is keyed by the logical address its first checksum covers and
/// holds one digest per sector from there, so finding the one covering an address is the
/// last item keyed at or before it — and whether it reaches that far is arithmetic on its
/// own length.
///
/// The digest comes back in the checksum field's form — its bytes at the front and zeros
/// behind — which is the form [`ChecksumType::field`](super::ondisk::ChecksumType::field)
/// computes one in.
fn data_checksum(
&mut self,
logical: u64,
) -> Result<Option<[u8; super::ondisk::CSUM_FIELD_LEN]>, ReadError> {
let sector = u64::from(self.volume.superblock().sectorsize);
let Some(digest) = self.volume.superblock().csum_type.digest_len() else {
return Ok(None);
};
let root = self.tree_root_of(objectid::CSUM_TREE)?;
let wanted = DiskKey::new(objectid::EXTENT_CSUM, ItemType::EXTENT_CSUM, logical);
let Some(found) = self.volume.tree(root).find_at_or_before(wanted)? else {
return Ok(None);
};
if found.key.objectid != objectid::EXTENT_CSUM || found.key.kind != ItemType::EXTENT_CSUM {
return Ok(None);
}
let covered = (found.data.len() / digest) as u64 * sector;
// Checked, because the offset is a key the image supplies: an item keyed near the
// top of the address space would wrap the sum, and a wrapped bound answers "covered"
// for addresses the record never reached.
let end = found.key.offset.checked_add(covered);
if end.is_none_or(|end| logical >= end) {
return Ok(None);
}
let index = ((logical - found.key.offset) / sector) as usize * digest;
// An item holds the digests packed at the algorithm's own length, one per sector.
Ok(found.data.get(index..index + digest).map(|stored| {
let mut field = [0u8; super::ondisk::CSUM_FIELD_LEN];
field[..digest].copy_from_slice(stored);
field
}))
}
/// Where one of the filesystem's own trees begins, found through the root tree.
///
/// Separate from [`tree_root`](Self::tree_root), which answers for a subvolume: a subvolume
/// is gathered at open because a walk crosses into one, and the filesystem's own trees are
/// reached rarely and looked up when they are.
fn tree_root_of(&mut self, objectid: u64) -> Result<TreeRoot, ReadError> {
let root_tree = self.volume.root_tree();
let key = DiskKey::new(objectid, ItemType::ROOT_ITEM, 0);
let found = self
.volume
.tree(root_tree)
.find_first(key)?
.filter(|found| found.key.objectid == objectid && found.key.kind == ItemType::ROOT_ITEM)
.ok_or(ReadError::MissingTree { objectid })?;
let item = RootItem::read_from(&found.data)
.map_err(|source| ReadError::BadRootItem { objectid, source })?;
Ok(TreeRoot {
objectid,
bytenr: item.bytenr,
level: item.level,
generation: item.generation,
})
}
/// The names below `dir`, as frontier elements under `path`, in reverse order so a stack
/// pops them in the order the directory stores them.
///
/// A name no directory can hold stops the walk here rather than becoming a path: a name
/// carrying a separator would traverse out of its own directory in every path built from
/// it, which is what an extraction would then write.
fn pending_children(
&mut self,
dir: &Node,
path: &[u8],
) -> Result<Vec<(Vec<u8>, Node, DiskKey)>, ReadError> {
let entries = self
.read_dir(dir)?
.into_iter()
.map(|e| (e.name, e.location));
let pending = crate::walk::frontier(
path,
entries,
|name| ReadError::HostileName { name },
|path| ReadError::PathTooLong { path },
)?;
Ok(pending
.into_iter()
.map(|(child, location)| (child, *dir, location))
.collect())
}
/// The node the entry `name` of directory `dir` names by `location`.
///
/// An entry naming a subvolume crosses into it where the subvolume's backref names this
/// directory of this tree under this name, which is the one place the subvolume is linked.
/// Any other entry naming it is a [stub](Node::stub), an empty directory, and is not
/// crossed: a snapshot of a subvolume holding nested ones keeps their entries, and
/// following them would read the nested subvolumes as the snapshot's content.
fn at_location(
&mut self,
dir: &Node,
name: &[u8],
location: DiskKey,
) -> Result<Node, ReadError> {
let tree = dir.tree;
match location.kind {
ItemType::INODE_ITEM => self.inode(tree, location.objectid),
ItemType::ROOT_ITEM => {
let id = location.objectid;
let sub = self
.subvolumes
.iter()
.find(|sub| sub.id == id)
.ok_or(ReadError::MissingTree { objectid: id })?;
if sub.parent == Some(tree) && sub.parent_dir == dir.inode && sub.name == name {
let root_dir = sub.root_dir;
return self.inode(id, root_dir);
}
let mut item = dir.item;
item.mode = MODE_DIR | 0o755;
item.size = 0;
item.nbytes = 0;
item.nlink = 1;
Ok(Node {
tree,
inode: id,
item,
stub: true,
})
}
other => Err(ReadError::BadDirEntry {
tree,
inode: location.objectid,
fault: "the entry names neither an inode nor a subvolume",
kind: other.value(),
}),
}
}
/// Where the tree of one subvolume begins.
fn tree_root(&self, id: u64) -> Result<TreeRoot, ReadError> {
self.subvolumes
.iter()
.find(|sub| sub.id == id)
.map(|sub| sub.root)
.ok_or(ReadError::MissingTree { objectid: id })
}
/// Every extent record of `node` that overlaps `[offset, end)`, in file order.
///
/// Two descents rather than one per record: the first finds the record covering `offset`,
/// which is the last one keyed at or before it, and the walk forward from there stops at
/// the first record beyond the range. Reading from the middle of a file is what makes the
/// first descent necessary — the record covering a position is keyed by where it *begins*,
/// which is below the position asked for.
fn extent_records(
&mut self,
node: &Node,
offset: u64,
end: u64,
) -> Result<Vec<(u64, FileExtentItem, Vec<u8>)>, ReadError> {
let root = self.tree_root(node.tree)?;
let wanted = DiskKey::new(node.inode, ItemType::EXTENT_DATA, offset);
let covering = self.volume.tree(root).find_at_or_before(wanted)?;
let from = match covering {
Some(found)
if found.key.objectid == node.inode && found.key.kind == ItemType::EXTENT_DATA =>
{
found.key
}
// Nothing at or before it belongs to this file, so the range begins at whatever
// the file's first record is — and a file with none reads back as all zeros.
_ => DiskKey::first_of(node.inode, ItemType::EXTENT_DATA),
};
let mut out = Vec::new();
let mut failure = None;
self.volume
.tree(root)
.for_each_item_from(from, |key, data| {
if key.objectid != node.inode
|| key.kind != ItemType::EXTENT_DATA
|| key.offset >= end
{
return false;
}
match FileExtentItem::read_from(data) {
Ok(item) => {
out.push((key.offset, item, data.to_vec()));
true
}
Err(e) => {
failure = Some(e.into());
false
}
}
})?;
match failure {
Some(e) => Err(e),
None => Ok(out),
}
}
/// Copy whatever one extent record contributes to `out`, which covers `[offset, ..)` of the
/// file.
fn place_extent(
&mut self,
node: &Node,
at: u64,
item: &FileExtentItem,
raw: &[u8],
offset: u64,
out: &mut [u8],
) -> Result<(), ReadError> {
let bad = |fault: &'static str| ReadError::BadExtent {
tree: node.tree,
inode: node.inode,
at,
fault,
};
// Which encoding the bytes on the volume are in, and whether this build can undo it.
// An algorithm the format has not defined and one this build carries no decoder for
// are the same answer to a caller — the file cannot be read here — and the message
// names which it was.
let encoding = match decode::algorithm(item.compression) {
None => None,
Some(Some(algorithm)) if algorithm.available() => Some(algorithm),
Some(_) => {
return Err(ReadError::UnsupportedCompression {
tree: node.tree,
inode: node.inode,
compression: item.compression.to_u8(),
});
}
};
if item.encryption != 0 || item.other_encoding != 0 {
return Err(ReadError::UnsupportedEncoding {
tree: node.tree,
inode: node.inode,
encryption: item.encryption,
other: item.other_encoding,
});
}
// How much of the file this record claims, and where in `out` that lands. Both are
// computed against the record's own declared length, which is a number the image
// supplied — so every step of it is checked rather than assumed to fit.
let covers = if item.kind.is_inline() {
item.ram_bytes
} else {
item.num_bytes
};
let record_end = at
.checked_add(covers)
.ok_or_else(|| bad("the record's length runs past the end of the address space"))?;
let start = at.max(offset);
let stop = record_end.min(offset + out.len() as u64);
if stop <= start {
return Ok(());
}
let into = (start - offset) as usize;
let len = (stop - start) as usize;
let within = start - at;
if item.kind.is_inline() {
let stored = item.inline_data(raw)?;
if let Some(algorithm) = encoding {
// The record's own bytes are the stream, and what it expands to is the whole
// of what the record covers — so the window is taken from the expansion at
// the same position it would have been taken from the item.
let whole = self.expand(node, at, item, algorithm, stored)?;
let from = within as usize;
out[into..into + len].copy_from_slice(&whole[from..from + len]);
return Ok(());
}
// The item's own length is what says how many bytes are there, and a record
// claiming more than the item holds is refused rather than padded: padding it
// would hand back zeros the file does not have.
if (stored.len() as u64) < covers {
return Err(bad("the record claims more bytes than the item holds"));
}
let from = within as usize;
out[into..into + len].copy_from_slice(&stored[from..from + len]);
return Ok(());
}
// A hole and a preallocated extent both read back as zeros, which `out` already holds.
if item.is_hole() || item.kind == ExtentKind::Prealloc {
return Ok(());
}
if item.kind != ExtentKind::Regular {
return Err(bad("the record is of a shape this reader does not define"));
}
if let Some(algorithm) = encoding {
// A compressed extent is undone whole: the bytes on the volume are one framed run
// that expands to `ram_bytes`, and nothing inside it says where a position in the
// file lands. So the extent is read, expanded, and the window taken from what it
// expanded to — which is also why `offset` is measured against that length here
// and against the stored length below.
if item.disk_num_bytes > decode::MAX_COMPRESSED {
return Err(bad(
"the extent stores more than this format compresses into",
));
}
let mut stored = vec![0u8; item.disk_num_bytes as usize];
self.volume.read_at(item.disk_bytenr, &mut stored)?;
let whole = self.expand(node, at, item, algorithm, &stored)?;
let skip = item
.offset
.checked_add(within)
.ok_or_else(|| bad("the record begins past the end of the extent it names"))?;
let last = skip
.checked_add(len as u64)
.ok_or_else(|| bad("the record's run leaves the extent it names"))?;
if last > whole.len() as u64 {
return Err(bad("the record's run leaves the extent it names"));
}
let from = skip as usize;
out[into..into + len].copy_from_slice(&whole[from..from + len]);
return Ok(());
}
// Where in the extent this record's bytes begin, plus how far into the record the
// wanted run starts. Both are the image's numbers, and the sum must stay inside the
// extent the record names — otherwise the read is of whatever follows it on the
// volume, under this file's name.
let skip = item
.offset
.checked_add(within)
.ok_or_else(|| bad("the record begins past the end of the extent it names"))?;
let last = skip
.checked_add(len as u64)
.ok_or_else(|| bad("the record's run leaves the extent it names"))?;
if last > item.disk_num_bytes {
return Err(bad("the record's run leaves the extent it names"));
}
let logical = item
.disk_bytenr
.checked_add(skip)
.ok_or_else(|| bad("the record's address runs past the end of the address space"))?;
self.volume.read_at(logical, &mut out[into..into + len])
}
/// The bytes one compressed extent expands to, whole.
///
/// The buffer is the size the record declares, and that declaration is a number the image
/// supplied — so it is held to what this format compresses in before a byte is allocated
/// for it. A record claiming a gibibyte costs a refusal rather than a gibibyte.
///
/// **An inline record's stream may expand to a whole sector.** The file is its first
/// `ram_bytes`, and what follows is the rest of the sector it was compressed from. Observed:
/// every inline extent a Linux 7.1 driver compressed with zlib, LZO or zstd, a file of 1 to
/// 4095 bytes in a 4096-byte sector, expands to the whole sector, where `mkfs.btrfs`
/// compresses the file's bytes alone. So an inline record is undone into a sector's room
/// and holds to its own length within it.
///
/// **A regular extent's stream may stop at the file's end.** Its record declares a whole
/// number of sectors, and the stream may hold only the bytes the file has. Observed: the
/// pinned `mkfs.btrfs --compress zlib -r` writes a 4451-byte file's last extent as 8192
/// declared, its stream expanding to 4451, and `btrfs check --check-data-csum` and `btrfs
/// restore` both accept it. So a regular extent's stream holds to every byte the file reads
/// from it — from the record's offset into the extent up to the file's size — and what lies
/// past that and past the stream is zeros the file never reads.
///
/// A stream that stops inside what the file reads is refused rather than zero-filled, which
/// is the same rule the uncompressed inline path follows: the tail would be zeros the file
/// does not have.
fn expand(
&mut self,
node: &Node,
at: u64,
item: &FileExtentItem,
algorithm: Algorithm,
stored: &[u8],
) -> Result<Vec<u8>, ReadError> {
if item.ram_bytes > decode::MAX_UNCOMPRESSED {
return Err(ReadError::BadExtent {
tree: node.tree,
inode: node.inode,
at,
fault: "the record expands to more than this format compresses in",
});
}
let sector_size = self.volume.superblock().sectorsize;
let declared = item.ram_bytes as usize;
let room = if item.kind.is_inline() {
declared.max(sector_size as usize)
} else {
declared
};
let mut whole = vec![0u8; room];
let produced = decode::decode(algorithm, stored, &mut whole, sector_size).map_err(|e| {
ReadError::BadCompressedExtent {
tree: node.tree,
inode: node.inode,
at,
fault: e.to_string(),
}
})?;
let holds = if item.kind.is_inline() {
produced >= declared
} else {
// The bytes of the extent the file reads: from the record's offset into it, for
// the record's length or up to the file's end, whichever comes first.
let read = item
.num_bytes
.min(node.item.size.saturating_sub(at))
.saturating_add(item.offset);
produced == declared || (produced < declared && produced as u64 >= read)
};
if !holds {
return Err(ReadError::BadCompressedExtent {
tree: node.tree,
inode: node.inode,
at,
fault: format!("it expands to {produced} bytes and the record declares {declared}"),
});
}
whole.truncate(declared);
Ok(whole)
}
}
/// How much of a file is held in memory at once while it is streamed. A megabyte, which is
/// large enough that the per-call descent is amortized and small enough to be nothing.
const STREAM_BUFFER: usize = 1 << 20;
/// Every subvolume the root tree records, the top-level tree first.
///
/// Three item types in one pass over the root tree, because they are three views of the same
/// thing: a `ROOT_ITEM` says where a tree is, a `ROOT_BACKREF` says which subvolume it appears
/// in and under what name, and everything else in the tree is one of the filesystem's own trees
/// rather than a subvolume.
fn read_subvolumes<R: Read + Seek>(volume: &mut Volume<R>) -> Result<Vec<Subvolume>, ReadError> {
let root_tree = volume.root_tree();
let mut items: BTreeMap<u64, (RootItem, TreeRoot)> = BTreeMap::new();
let mut links: BTreeMap<u64, (u64, u64, Vec<u8>)> = BTreeMap::new();
let mut failure = None;
volume.tree(root_tree).for_each_item(|key, data| {
if !is_subvolume_id(key.objectid) {
return true;
}
match key.kind {
ItemType::ROOT_ITEM => match RootItem::read_from(data) {
// A subvolume being deleted: no reference holds it, or a drop of its tree has
// begun and records how far it got. Documented: a deleted subvolume's tree is
// freed in the background, so after an unclean unmount part of it may already
// be gone. It is no subvolume of the filesystem, and its blocks are not read.
Ok(item) if item.refs == 0 || item.drop_progress.objectid != 0 => true,
Ok(item) => {
let root = TreeRoot {
objectid: key.objectid,
bytenr: item.bytenr,
level: item.level,
generation: item.generation,
};
items.insert(key.objectid, (item, root));
true
}
Err(e) => {
failure = Some(ReadError::BadRootItem {
objectid: key.objectid,
source: e,
});
false
}
},
// The child's own copy of the link, so the parent is the key's offset and one
// pass over the tree finds every subvolume's parent without a second descent.
ItemType::ROOT_BACKREF => {
let mut link = None;
let framed = for_each_packed::<RootRef, _>(data, |head, name| {
link = Some((key.offset, head.dirid, name.to_vec()));
false
});
match framed {
Ok(()) => {
if let Some(link) = link {
links.insert(key.objectid, link);
}
true
}
Err(e) => {
failure = Some(e.into());
false
}
}
}
_ => true,
}
})?;
if let Some(e) = failure {
return Err(e);
}
let mut out: Vec<Subvolume> = items
.into_iter()
.map(|(id, (item, root))| {
let (parent, parent_dir, name) = links
.remove(&id)
.map_or((None, 0, Vec::new()), |(parent, dir, name)| {
(Some(parent), dir, name)
});
Subvolume {
id,
root,
root_dir: item.root_dirid,
read_only: item.flags.contains(RootFlags::SUBVOL_RDONLY),
uuid: item.uuid,
parent_uuid: item.parent_uuid,
otime: item.otime,
parent,
parent_dir,
name,
}
})
.collect();
out.sort_by_key(|sub| (sub.id != objectid::FS_TREE, sub.id));
Ok(out)
}
/// The subvolume the filesystem asks to be mounted at, or [`None`] where nothing has said.
///
/// It is a directory entry rather than a field: the root tree has a directory of its own, and
/// the entry named `default` in it is what a mount follows.
fn read_default_subvolume<R: Read + Seek>(
volume: &mut Volume<R>,
) -> Result<Option<u64>, ReadError> {
let root_tree = volume.root_tree();
let key = DiskKey::new(
objectid::ROOT_TREE_DIR,
ItemType::DIR_ITEM,
name_hash(b"default"),
);
let Some(found) = volume.tree(root_tree).find_exact(key)? else {
return Ok(None);
};
let mut id = None;
for_each_packed::<DirItem, _>(&found.data, |head, tail| {
let (name, _) = head.split(tail);
if name == b"default" && head.location.kind == ItemType::ROOT_ITEM {
id = Some(head.location.objectid);
return false;
}
true
})?;
Ok(id)
}
/// What this family supplies to the crate's shared path resolution: a hashed lookup to find a
/// name in a directory, and the pair that names an inode to come back to.
///
/// The ascent a `..` component makes is the shared resolution's, and this family is the reason
/// it holds directories rather than inode numbers: an inode number means one thing in one
/// subvolume's tree and something else in another, so a path that descends into a subvolume and
/// ascends back out of it needs the tree it came from as much as the number.
impl<R: Read + Seek> crate::resolve::Resolve for Reader<R> {
/// A subvolume and an inode number, which is what [`Reader::inode`] takes and what a node
/// is identified by anywhere in this family.
type Ancestor = (u64, u64);
type Node = Node;
type Error = ReadError;
fn root_node(&mut self) -> Result<Node, ReadError> {
self.root()
}
fn ancestor_of(&self, node: &Node) -> (u64, u64) {
(node.tree, node.inode)
}
fn node_at(&mut self, (tree, inode): (u64, u64)) -> Result<Node, ReadError> {
self.inode(tree, inode)
}
fn is_directory(&self, node: &Node) -> bool {
node.is_dir()
}
fn find_name(&mut self, dir: &Node, name: &[u8]) -> Result<Option<Node>, ReadError> {
// One descent per component rather than a listing per directory: a name is found
// through the `DIR_ITEM` keyed by its own hash. A component naming a subvolume steps
// into that subvolume's tree, which is what makes a path across the boundary one path.
let Some(entry) = self.find_entry(dir, name)? else {
return Ok(None);
};
Ok(Some(self.step(dir, &entry)?))
}
fn read_link(&mut self, node: &Node, path: &[u8]) -> Result<Option<Vec<u8>>, ReadError> {
if !node.is_symlink() {
return Ok(None);
}
// A target longer than a path can be is refused before it is read, so a crafted size
// cannot make one link allocate more than a path's worth.
if node.item.size > MAX_PATH as u64 {
return Err(self.not_found(path));
}
Ok(Some(self.link_target(node)?))
}
fn not_found(&self, path: &[u8]) -> ReadError {
ReadError::NotFound {
path: path.to_vec(),
}
}
fn not_a_directory(&self, _node: &Node, path: &[u8]) -> ReadError {
ReadError::NotADirectory {
path: path.to_vec(),
}
}
fn too_many_links(&self, path: &[u8]) -> ReadError {
ReadError::SymlinkLoop {
path: path.to_vec(),
}
}
}
/// What this family supplies to the crate's shared depth-first walk: what sits on the frontier,
/// what identifies a directory, and how a directory's names are read.
///
/// The three bounds a walk of an untrusted tree needs — the cycle, the frontier, the depth —
/// are the shared walk's and not restated here. What is this family's alone is that a frontier
/// element carries **the subvolume its parent was in**: a location naming an inode is an inode
/// of that same tree, and one naming a root is where another tree begins.
impl<R: Read + Seek> crate::walk::Walk for Reader<R> {
/// A name reached and not yet visited: its path, the directory holding it, and the key of
/// what it names.
///
/// The node itself is not kept. The frontier holds every name reached and not yet visited,
/// and re-reading an inode is one descent — so what rides here is the least that can find
/// it again: the holding directory's node is a copy of a few words, and it is what says
/// whether an entry naming a subvolume is the one the subvolume is linked by.
type Pending = (Vec<u8>, Node, DiskKey);
type Entry = WalkEntry;
type Key = (u64, u64);
type Error = ReadError;
fn cap(&mut self) -> usize {
self.limits().max_walk_entries
}
fn seed(&mut self) -> Result<crate::walk::Seed<Self>, ReadError> {
let root = self.root()?;
let children = self.pending_children(&root, b"")?;
Ok((children, vec![(root.tree, root.inode)]))
}
fn resolve(&mut self, pending: Self::Pending) -> Result<WalkEntry, ReadError> {
let (path, dir, location) = pending;
let name = crate::path::canonical_parts(&path)
.last()
.copied()
.unwrap_or_default();
let node = self.at_location(&dir, name, location)?;
Ok(WalkEntry { path, node })
}
fn repeated(&mut self, entry: &WalkEntry) -> Result<(), ReadError> {
// Every record parses, and the records disagree about the tree they make: integrity
// damage, which a strict read refuses and a lenient one passes over.
if self.policy().is_fatal(Severity::Integrity) {
return Err(ReadError::RepeatedDirectory {
tree: entry.node.tree,
inode: entry.node.inode,
});
}
Ok(())
}
fn descend_key(&self, entry: &WalkEntry) -> Option<(u64, u64)> {
// A stub holds nothing to descend into, and its pair names a subvolume rather than an
// inode of its tree.
(entry.node.is_dir() && !entry.node.stub).then_some((entry.node.tree, entry.node.inode))
}
fn children(&mut self, entry: &WalkEntry) -> Result<Vec<Self::Pending>, ReadError> {
self.pending_children(&entry.node, &entry.path)
}
fn too_large(limit: usize) -> ReadError {
ReadError::WalkTooLarge { limit }
}
}
/// Everything a walk through the shared surface can fail on, kept apart until it ends.
type WalkFail<E> = crate::tree::WalkFail<ReadError, E>;
impl<E> From<ReadError> for WalkFail<E> {
fn from(err: ReadError) -> Self {
WalkFail::Read(err)
}
}
impl From<ReadError> for TreeError {
fn from(err: ReadError) -> Self {
match err {
ReadError::Io { kind, message } => TreeError::Io { kind, message },
ReadError::FileTooLarge { .. } => {
TreeError::limit(Family::Btrfs, Bound::FileBytes, &err)
}
ReadError::TooManyEntries { .. } | ReadError::WalkTooLarge { .. } => {
TreeError::limit(Family::Btrfs, Bound::Entries, &err)
}
ReadError::PathTooLong { .. } => {
TreeError::limit(Family::Btrfs, Bound::PathBytes, &err)
}
// A filesystem that is entirely well-formed and beyond this build. Every one of
// these names what it would take to read it, which is what the shared frame calls
// unsupported rather than malformed.
ReadError::UnsupportedFeatures { .. }
| ReadError::UnsupportedChecksum { .. }
| ReadError::UnsupportedProfile { .. }
| ReadError::UnsupportedCompression { .. }
| ReadError::UnsupportedEncoding { .. }
| ReadError::MultiDevice { .. } => TreeError::Unsupported {
family: Family::Btrfs,
detail: err.to_string(),
},
other => TreeError::Malformed {
family: Family::Btrfs,
detail: other.to_string(),
},
}
}
}
impl<R: Read + Seek> FsTree for Reader<R> {
type Node = Node;
fn family(&self) -> Family {
Family::Btrfs
}
fn max_file_bytes(&self) -> u64 {
self.limits().max_file_bytes
}
fn walk_tree<E, F>(&mut self, mut visit: F) -> Result<(), E>
where
E: From<TreeError>,
F: FnMut(&mut Self, TreeEntry<Node>) -> Result<(), E>,
{
// Which nodes two names are both for, assigned as the walk meets them. The pair
// `(subvolume, inode)` is what identifies a node here and a shared identity is one
// number, so the mapping cannot be arithmetic: inode 257 exists in every subvolume,
// and a scheme that mixed the two into one integer would claim two unrelated files
// were hard links to each other.
let mut shared: BTreeMap<(u64, u64), u64> = BTreeMap::new();
let outcome = self.walk_with::<WalkFail<E>, _>(|reader, entry| {
let node = entry.node;
let kind = node_kind(&node).map_err(WalkFail::Tree)?;
let mut out = TreeEntry::new(entry.path, kind, node);
// A directory has one name by construction, so its link count says nothing and it
// is never a second name for anything. Only a node the image says has more than
// one name carries an identity, which keeps a sink's table down to the tree's
// actual links rather than a path per file in it.
if !matches!(kind, NodeKind::Directory) && node.item.nlink > 1 {
let next = shared.len() as u64;
out = out.shared(*shared.entry((node.tree, node.inode)).or_insert(next));
}
visit(reader, out).map_err(WalkFail::Visitor)
});
match outcome {
Ok(()) => Ok(()),
Err(WalkFail::Read(e)) => Err(E::from(TreeError::from(e))),
Err(WalkFail::Tree(e)) => Err(E::from(e)),
Err(WalkFail::Visitor(e)) => Err(e),
}
}
fn stat(&mut self, node: &Node, _synthesis: &Synthesis) -> Result<Attributes, TreeError> {
// Nothing is synthesized. btrfs records an owner, a group, a mode, and four times of
// full nanosecond resolution, so every property the shared frame carries is one this
// filesystem holds — and the caller's fallbacks are ignored rather than mixed in.
// The mode's file-type bits are the node's kind, which the walk reports; the
// metadata carries the twelve below them.
Ok(Attributes::read(node.metadata(), self.xattrs(node)?))
}
fn read_bytes(&mut self, node: &Node, offset: u64, buf: &mut [u8]) -> Result<usize, TreeError> {
Ok(Reader::read_into(self, node, offset, buf)?)
}
fn link_target(&mut self, node: &Node) -> Result<Vec<u8>, TreeError> {
Ok(Reader::link_target(self, node)?)
}
fn find(&mut self, path: &[u8]) -> Result<Child<Node>, TreeError> {
let node = self.lookup(path).map_err(|e| match e {
ReadError::NotFound { .. }
| ReadError::NotADirectory { .. }
| ReadError::SymlinkLoop { .. } => TreeError::NotFound {
family: Family::Btrfs,
path: path.to_vec(),
},
other => TreeError::from(other),
})?;
let kind = node_kind(&node)?;
Ok(Child::new(crate::tree::last_name(path), kind, node))
}
fn list(&mut self, dir: &Node) -> Result<Vec<Child<Node>>, TreeError> {
if !dir.is_dir() {
return Err(crate::tree::not_a_directory(Family::Btrfs));
}
let entries = self.read_dir(dir)?.into_iter().map(|e| (e.name.clone(), e));
let mut out = Vec::new();
for (name, entry) in crate::tree::listed(Family::Btrfs, entries)? {
// Through the entry's own key, which is a subvolume's root where the entry names
// one: a listing crosses into a subvolume as a walk does.
let node = self.step(dir, &entry)?;
let kind = node_kind(&node)?;
out.push(Child::new(name, kind, node));
}
Ok(out)
}
/// In sectors: the device's size, and the superblock's account of what is free, which is
/// logical. The superblock counts the bytes its extents use once each, so the free count
/// is the device's size less those: a tree block a DUP profile stores twice is counted
/// once, and the device holds that many fewer sectors unused than this says.
fn usage(&mut self) -> Result<Usage, TreeError> {
let sb = self.volume.superblock();
let unit = u64::from(sb.sectorsize);
Ok(Usage::new(
unit,
sb.total_bytes / unit,
sb.total_bytes.saturating_sub(sb.bytes_used) / unit,
))
}
}
/// What a node is, in the shared frame's words: the one projection a walk, a lookup and a
/// listing all go through.
fn node_kind(node: &Node) -> Result<NodeKind, TreeError> {
Ok(match node.item.mode_type() {
MODE_DIR => NodeKind::Directory,
MODE_REG => NodeKind::File {
size: node.item.size,
},
MODE_LNK => NodeKind::Symlink,
MODE_CHR => {
let (major, minor) = node.item.device();
NodeKind::CharDevice { major, minor }
}
MODE_BLK => {
let (major, minor) = node.item.device();
NodeKind::BlockDevice { major, minor }
}
MODE_FIFO => NodeKind::Fifo,
MODE_SOCK => NodeKind::Socket,
other => {
return Err(TreeError::Malformed {
family: Family::Btrfs,
detail: format!(
"inode {} of subvolume {} records file type {other:#o}, which names no \
file type",
node.inode, node.tree
),
});
}
})
}
/// The `S_IFMT` value of a character-special device node.
const MODE_CHR: u32 = 0o020_000;
/// The `S_IFMT` value of a block-special device node.
const MODE_BLK: u32 = 0o060_000;
/// The `S_IFMT` value of a named pipe.
const MODE_FIFO: u32 = 0o010_000;
/// The `S_IFMT` value of a Unix-domain socket node.
const MODE_SOCK: u32 = 0o140_000;
/// Whether an id in the root tree names a subvolume rather than one of the filesystem's own
/// trees.
///
/// The top-level tree has a fixed id below the free range, and every other subvolume is inside
/// it. The relocation trees sit at the top of the range and are neither.
const fn is_subvolume_id(objectid: u64) -> bool {
objectid == objectid::FS_TREE
|| (objectid >= objectid::FIRST_FREE && objectid <= objectid::LAST_FREE)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::btrfs::forge::{
DATA_AT, DATA_BYTE, FS_TREE_AT, Forge, NODE_SIZE, ROOT_DIR, TIME, addressed_extent,
compressed_extent, csum_item, entry, fs_tree, inline_extent, inode_item, leaf, root_item,
};
use crate::btrfs::ondisk::{Compression, InodeFlags};
use crate::btrfs::scan::Anomaly;
/// Where a second subvolume's tree sits in the forged image.
const SUB_TREE_AT: u64 = FS_TREE_AT + NODE_SIZE as u64;
/// The id a nested subvolume takes.
const SUB_ID: u64 = 257;
/// A filesystem whose root directory holds `items`, and nothing else.
///
/// What each gate below builds for itself: the filesystem that is wrong in the way that
/// gate is about. The one that is right is `Forge::populated`.
fn a_filesystem_holding(items: Vec<(DiskKey, Vec<u8>)>) -> Forge {
let mut all = vec![(
DiskKey::new(ROOT_DIR, ItemType::INODE_ITEM, 0),
inode_item(MODE_DIR | 0o755, 0, 1),
)];
all.extend(items);
let mut forge = Forge::new();
forge.block(FS_TREE_AT, &fs_tree(FS_TREE_AT, objectid::FS_TREE, all));
forge.data(DATA_AT, &[DATA_BYTE; 4096]);
forge.root_leaf(&[(
DiskKey::new(objectid::FS_TREE, ItemType::ROOT_ITEM, 0),
root_item(FS_TREE_AT, 0, ROOT_DIR),
)]);
forge
}
/// One file at `/name`, of `mode`, `size` bytes long, whose bytes `record` describes.
fn a_file(name: &[u8], mode: u32, size: u64, record: Vec<u8>) -> Vec<(DiskKey, Vec<u8>)> {
let mut items = vec![
(
DiskKey::new(257, ItemType::INODE_ITEM, 0),
inode_item(mode, size, 1),
),
(DiskKey::new(257, ItemType::EXTENT_DATA, 0), record),
];
items.extend(entry(
ROOT_DIR,
2,
name,
DiskKey::new(257, ItemType::INODE_ITEM, 0),
DirEntryType::RegFile,
));
items
}
/// The same, with a subvolume mounted at `/nested` and a file inside it.
fn a_filesystem_with_a_subvolume() -> Forge {
a_filesystem_with_a_subvolume_and(Vec::new())
}
/// The same, with `extra` among the top-level tree's items.
fn a_filesystem_with_a_subvolume_and(extra: Vec<(DiskKey, Vec<u8>)>) -> Forge {
let mut top = vec![
(
DiskKey::new(ROOT_DIR, ItemType::INODE_ITEM, 0),
inode_item(MODE_DIR | 0o755, 0, 1),
),
(
DiskKey::new(257, ItemType::INODE_ITEM, 0),
inode_item(MODE_REG | 0o644, 3, 1),
),
(
DiskKey::new(257, ItemType::EXTENT_DATA, 0),
inline_extent(b"up\n"),
),
];
top.extend(entry(
ROOT_DIR,
2,
b"above",
DiskKey::new(257, ItemType::INODE_ITEM, 0),
DirEntryType::RegFile,
));
// The entry a subvolume is mounted at names a `ROOT_ITEM`, not an inode.
top.extend(entry(
ROOT_DIR,
3,
b"nested",
DiskKey::new(SUB_ID, ItemType::ROOT_ITEM, u64::MAX),
DirEntryType::Dir,
));
top.extend(extra);
let mut sub = vec![
(
DiskKey::new(ROOT_DIR, ItemType::INODE_ITEM, 0),
inode_item(MODE_DIR | 0o755, 0, 1),
),
(
DiskKey::new(257, ItemType::INODE_ITEM, 0),
inode_item(MODE_REG | 0o644, 6, 1),
),
(
DiskKey::new(257, ItemType::EXTENT_DATA, 0),
inline_extent(b"inside"),
),
];
sub.extend(entry(
ROOT_DIR,
2,
b"within",
DiskKey::new(257, ItemType::INODE_ITEM, 0),
DirEntryType::RegFile,
));
let mut forge = Forge::new();
forge.block(FS_TREE_AT, &fs_tree(FS_TREE_AT, objectid::FS_TREE, top));
forge.block(SUB_TREE_AT, &fs_tree(SUB_TREE_AT, SUB_ID, sub));
let mut backref = vec![0u8; 18];
RootRef {
dirid: ROOT_DIR,
sequence: 3,
name_len: 6,
}
.write_to(&mut backref);
backref.extend_from_slice(b"nested");
forge.root_leaf(&[
(
DiskKey::new(objectid::FS_TREE, ItemType::ROOT_ITEM, 0),
root_item(FS_TREE_AT, 0, ROOT_DIR),
),
(
DiskKey::new(SUB_ID, ItemType::ROOT_ITEM, 0),
root_item(SUB_TREE_AT, 0, ROOT_DIR),
),
(
DiskKey::new(SUB_ID, ItemType::ROOT_BACKREF, objectid::FS_TREE),
backref,
),
]);
forge
}
fn open(forge: &Forge) -> Reader<crate::btrfs::forge::Sparse> {
Reader::open(forge.source()).expect("a forged filesystem opens")
}
#[test]
fn a_filesystem_opens_at_the_root_of_its_top_level_subvolume() {
let forge = Forge::populated();
let mut reader = open(&forge);
assert_eq!(reader.subvolumes().len(), 1);
assert_eq!(reader.top_level().id, objectid::FS_TREE);
assert_eq!(reader.default_subvolume(), objectid::FS_TREE);
let root = reader.root().expect("the root directory");
assert_eq!(root.inode, ROOT_DIR);
assert!(root.is_dir());
assert_eq!(root.item.mode & 0o7777, 0o755);
// The four times a btrfs inode carries, all of them read rather than derived.
assert_eq!(root.item.mtime, TIME);
assert_eq!(root.item.otime, TIME);
// What the shared surface reports is the permission bits alone: the kind is the
// walk's to say, and a writer handed the metadata refuses a mode carrying both.
let meta = FsTree::stat(&mut reader, &root, &Synthesis::default())
.expect("stats")
.meta;
assert_eq!(meta.mode, 0o755);
assert_eq!(meta, root.metadata(), "the one projection");
assert_eq!(meta.btime, Some(TIME), "otime is the birth time");
}
#[test]
fn a_mode_wider_than_a_hosts_narrows_to_its_permission_bits() {
// The field is thirty-two bits and a host's is sixteen, so what crosses is the low
// twelve. A cast without the mask would carry the file-type bits into a permission
// value and give a directory the set-user-id bit. And the high half is not permission
// bits either: every filesystem in circulation carries zero there, and a reader that
// trusted that rather than masking would hand a sink a mode out of an image that had
// not.
let forge = Forge::populated();
let mut node = open(&forge).root().expect("the root directory");
for (mode, bits) in [
(0o040_755, 0o755),
(0o100_644, 0o644),
(0o120_777, 0o777),
(0xFFFF_0000 | 0o644, 0o644),
] {
node.item.mode = mode;
assert_eq!(node.metadata().mode, bits, "{mode:#o}");
}
}
#[test]
fn a_directory_lists_its_entries_in_the_order_it_stores_them() {
// The order is the indexed copy's, which is creation order — not the hashed copy's,
// which is an order nothing about the filesystem chose.
let forge = Forge::populated();
let mut reader = open(&forge);
let root = reader.root().expect("the root");
let names: Vec<Vec<u8>> = reader
.read_dir(&root)
.expect("the root lists")
.into_iter()
.map(|entry| entry.name)
.collect();
assert_eq!(
names,
vec![
b"hello.txt".to_vec(),
b"big".to_vec(),
b"link".to_vec(),
b"sub".to_vec()
]
);
// And a directory holds no `.` or `..` entry, so what comes back is its contents.
assert!(!names.iter().any(|name| name == b"." || name == b".."));
}
#[test]
fn a_name_is_found_through_the_hash_it_is_keyed_by() {
let forge = Forge::populated();
let mut reader = open(&forge);
let node = reader.lookup(b"/hello.txt").expect("the file");
assert!(node.is_file());
assert_eq!(node.item.size, 6);
// A path more than one component deep crosses a directory at each step.
let inner = reader.lookup(b"/sub/inner").expect("the nested file");
assert_eq!(reader.read_data(&inner).expect("its bytes"), b"in\n");
// A name that is not there is not an error about the tree.
assert!(matches!(
reader.lookup(b"/missing"),
Err(ReadError::NotFound { .. })
));
// And a name looked up inside something that is not a directory says so.
assert!(matches!(
reader.lookup(b"/hello.txt/deeper"),
Err(ReadError::NotADirectory { .. })
));
}
#[test]
fn a_small_file_is_read_out_of_the_record_that_holds_it() {
let forge = Forge::populated();
let mut reader = open(&forge);
let node = reader.lookup(b"/hello.txt").expect("the file");
assert_eq!(reader.read_data(&node).expect("its bytes"), b"hello\n");
// And read from the middle, which is what the covering-record search is for: the
// record is keyed at zero and the position asked for is not.
let mut buf = [0u8; 3];
assert_eq!(
reader
.read_into(&node, 2, &mut buf)
.expect("a partial read"),
3
);
assert_eq!(&buf, b"llo");
// Past the end is no bytes rather than a failure.
assert_eq!(
reader.read_into(&node, 6, &mut buf).expect("past the end"),
0
);
}
#[test]
fn a_large_file_is_read_through_the_extent_that_addresses_it() {
let forge = Forge::populated();
let mut reader = open(&forge);
let node = reader.lookup(b"/big").expect("the file");
let bytes = reader.read_data(&node).expect("its bytes");
assert_eq!(bytes.len(), 4096);
assert!(bytes.iter().all(|&b| b == 0xab));
// Streamed to a destination it is the same bytes, which is what says the two paths
// through the extents agree.
let mut streamed = Vec::new();
assert_eq!(
reader
.read_data_to(&node, &mut streamed)
.expect("streaming it"),
4096
);
assert_eq!(streamed, bytes);
}
#[test]
fn a_symbolic_link_hands_back_the_target_it_records() {
let forge = Forge::populated();
let mut reader = open(&forge);
let link = reader.lookup_no_follow(b"/link").expect("the link");
assert!(link.is_symlink());
assert_eq!(reader.link_target(&link).expect("its target"), b"hello.txt");
// The target is reproduced as it stands: reading one is not resolving one.
let file = reader.lookup_no_follow(b"/hello.txt").expect("the file");
assert_ne!(link.inode, file.inode);
// And a node that is not a link has no target rather than an empty one.
assert!(matches!(
reader.link_target(&file),
Err(ReadError::NotASymlink { .. })
));
}
/// A symbolic link numbered `inode`, entered in `dir` at `index` under `name`, pointing at
/// `target`.
fn a_link(
dir: u64,
inode: u64,
index: u64,
name: &[u8],
target: &[u8],
) -> Vec<(DiskKey, Vec<u8>)> {
let mut items = vec![
(
DiskKey::new(inode, ItemType::INODE_ITEM, 0),
inode_item(MODE_LNK | 0o777, target.len() as u64, 1),
),
(
DiskKey::new(inode, ItemType::EXTENT_DATA, 0),
inline_extent(target),
),
];
items.extend(entry(
dir,
index,
name,
DiskKey::new(inode, ItemType::INODE_ITEM, 0),
DirEntryType::Symlink,
));
items
}
#[test]
fn a_path_continues_through_a_link_naming_a_directory() {
// The shape every current distribution's root filesystem has: `/bin`, `/lib`, and
// `/sbin` are links to directories under `/usr`, so a resolver that stopped at a link
// would find nothing under any of them and report the tree as missing most of itself.
let mut items = vec![
(
DiskKey::new(260, ItemType::INODE_ITEM, 0),
inode_item(MODE_DIR | 0o755, 0, 1),
),
(
DiskKey::new(261, ItemType::INODE_ITEM, 0),
inode_item(MODE_REG | 0o644, 3, 1),
),
(
DiskKey::new(261, ItemType::EXTENT_DATA, 0),
inline_extent(b"in\n"),
),
];
items.extend(entry(
ROOT_DIR,
2,
b"sub",
DiskKey::new(260, ItemType::INODE_ITEM, 0),
DirEntryType::Dir,
));
items.extend(entry(
260,
2,
b"inner",
DiskKey::new(261, ItemType::INODE_ITEM, 0),
DirEntryType::RegFile,
));
items.extend(a_link(ROOT_DIR, 259, 3, b"to-sub", b"sub"));
let forge = a_filesystem_holding(items);
let mut reader = open(&forge);
let through = reader
.lookup(b"/to-sub/inner")
.expect("a path continuing through a link to a directory");
let direct = reader
.lookup(b"/sub/inner")
.expect("the same file directly");
assert_eq!((through.tree, through.inode), (direct.tree, direct.inode));
assert_eq!(reader.read_data(&through).expect("its bytes"), b"in\n");
// And a link in a component that is not the last is expanded whichever lookup asks,
// because a path cannot continue through a link without going where it points.
let stopped = reader
.lookup_no_follow(b"/to-sub/inner")
.expect("the same, not following the last component");
assert_eq!((stopped.tree, stopped.inode), (direct.tree, direct.inode));
}
#[test]
fn a_target_beginning_at_the_root_restarts_there() {
let mut items = vec![
(
DiskKey::new(260, ItemType::INODE_ITEM, 0),
inode_item(MODE_DIR | 0o755, 0, 1),
),
(
DiskKey::new(261, ItemType::INODE_ITEM, 0),
inode_item(MODE_REG | 0o644, 3, 1),
),
(
DiskKey::new(261, ItemType::EXTENT_DATA, 0),
inline_extent(b"at\n"),
),
];
items.extend(entry(
ROOT_DIR,
2,
b"sub",
DiskKey::new(260, ItemType::INODE_ITEM, 0),
DirEntryType::Dir,
));
items.extend(entry(
ROOT_DIR,
3,
b"top.txt",
DiskKey::new(261, ItemType::INODE_ITEM, 0),
DirEntryType::RegFile,
));
// A link two directories down whose target begins at the root. Resolved against the
// directory holding it, it would name nothing; resolved against the root, it names the
// file. The two readings differ on every absolute link in a real tree.
items.extend(a_link(260, 259, 2, b"up", b"/top.txt"));
// And the relative form of the same reach, which is the shape a distribution's
// `/usr/lib64` has: the target ascends out of the directory holding the link and comes
// back down. It names the same file by a route that never mentions the root.
items.extend(a_link(260, 262, 3, b"over", b"../top.txt"));
let forge = a_filesystem_holding(items);
let mut reader = open(&forge);
let found = reader
.lookup(b"/sub/up")
.expect("resolving the absolute target");
assert_eq!(reader.read_data(&found).expect("its bytes"), b"at\n");
let ascended = reader
.lookup(b"/sub/over")
.expect("resolving the ascending relative target");
assert_eq!((ascended.tree, ascended.inode), (found.tree, found.inode));
}
#[test]
fn a_chain_of_links_that_does_not_end_is_refused() {
// Two links naming each other. A resolver with no budget follows this until something
// else stops it, which on an image this crate did not write is the caller's patience.
let mut items = a_link(ROOT_DIR, 259, 2, b"a", b"b");
items.extend(a_link(ROOT_DIR, 260, 3, b"b", b"a"));
let forge = a_filesystem_holding(items);
let mut reader = open(&forge);
assert!(matches!(
reader.lookup(b"/a"),
Err(ReadError::SymlinkLoop { .. })
));
// Not following the last component reaches the link itself, which is not a loop: the
// budget is spent by expanding links, and this expands none.
let stopped = reader.lookup_no_follow(b"/a").expect("the link itself");
assert!(stopped.is_symlink());
}
#[test]
fn a_lookup_follows_a_link_and_a_no_follow_lookup_stops_at_it() {
let forge = Forge::populated();
let mut reader = open(&forge);
// The same path, resolved the two ways, reaches two different inodes — which is the
// whole of the difference between the pair and the reason both exist. A caller
// extracting a tree wants the link; a caller reading a file wants what it points at.
let followed = reader.lookup(b"/link").expect("resolving through the link");
let stopped = reader.lookup_no_follow(b"/link").expect("stopping at it");
let target = reader.lookup(b"/hello.txt").expect("the file it names");
assert_eq!((followed.tree, followed.inode), (target.tree, target.inode));
assert!(stopped.is_symlink());
assert_ne!(stopped.inode, followed.inode);
}
#[test]
fn a_nodes_extended_attributes_come_back_in_the_boundary_form() {
let forge = Forge::populated();
let mut reader = open(&forge);
let node = reader.lookup(b"/hello.txt").expect("the file");
assert_eq!(
reader.xattrs(&node).expect("its attributes"),
vec![Xattr {
name: b"user.note".to_vec(),
value: b"a value".to_vec(),
}]
);
// A node with none has none, rather than the previous node's.
let root = reader.root().expect("the root");
assert!(reader.xattrs(&root).expect("no attributes").is_empty());
}
#[test]
fn a_walk_yields_the_root_first_and_then_every_name_below_it() {
let forge = Forge::populated();
let mut reader = open(&forge);
let paths: Vec<Vec<u8>> = reader
.walk()
.expect("a walk")
.into_iter()
.map(|entry| entry.path)
.collect();
assert_eq!(
paths,
vec![
Vec::new(),
b"/hello.txt".to_vec(),
b"/big".to_vec(),
b"/link".to_vec(),
b"/sub".to_vec(),
b"/sub/inner".to_vec(),
],
"a parent comes before its children, in the order its directory stores them"
);
}
#[test]
fn a_subvolume_is_crossed_into_as_though_it_were_a_directory() {
// The seam that makes this family different from the other three: an entry names a
// tree rather than an inode, and a path across it is one path.
let forge = a_filesystem_with_a_subvolume();
let mut reader = open(&forge);
assert_eq!(reader.subvolumes().len(), 2);
let nested = &reader.subvolumes()[1];
assert_eq!(nested.id, SUB_ID);
assert_eq!(nested.name, b"nested");
assert_eq!(nested.parent, Some(objectid::FS_TREE));
assert_eq!(nested.parent_dir, ROOT_DIR);
let node = reader.lookup(b"/nested/within").expect("the nested file");
assert_eq!(node.tree, SUB_ID, "the node is in the subvolume's own tree");
assert_eq!(reader.read_data(&node).expect("its bytes"), b"inside");
let paths: Vec<Vec<u8>> = reader
.walk()
.expect("a walk")
.into_iter()
.map(|entry| entry.path)
.collect();
assert_eq!(
paths,
vec![
Vec::new(),
b"/above".to_vec(),
b"/nested".to_vec(),
b"/nested/within".to_vec(),
]
);
}
#[test]
fn a_subvolume_being_deleted_is_no_subvolume_of_the_filesystem() {
// No reference holds its root, or a drop of its tree has begun: either way its tree is
// being freed, and after an unclean unmount part of it may be gone. It is left out of
// what the filesystem holds rather than walked as a live tree.
for (what, at, value) in [("no reference", 216usize, 0u8), ("a drop begun", 220, 1)] {
let mut forge = Forge::new();
forge.block(
FS_TREE_AT,
&fs_tree(
FS_TREE_AT,
objectid::FS_TREE,
vec![(
DiskKey::new(ROOT_DIR, ItemType::INODE_ITEM, 0),
inode_item(MODE_DIR | 0o755, 0, 1),
)],
),
);
forge.block(
SUB_TREE_AT,
&fs_tree(
SUB_TREE_AT,
SUB_ID,
vec![(
DiskKey::new(ROOT_DIR, ItemType::INODE_ITEM, 0),
inode_item(MODE_DIR | 0o755, 0, 1),
)],
),
);
let mut dying = root_item(SUB_TREE_AT, 0, ROOT_DIR);
dying[at..at + 4].fill(0);
dying[at] = value;
forge.root_leaf(&[
(
DiskKey::new(objectid::FS_TREE, ItemType::ROOT_ITEM, 0),
root_item(FS_TREE_AT, 0, ROOT_DIR),
),
(DiskKey::new(SUB_ID, ItemType::ROOT_ITEM, 0), dying),
]);
let reader = open(&forge);
assert_eq!(reader.subvolumes().len(), 1, "{what}");
}
}
#[test]
fn an_entry_naming_a_subvolume_linked_elsewhere_is_an_empty_directory() {
// A snapshot of a subvolume holding a nested one keeps the entry naming it, and the
// nested subvolume's backref names where it was created. Here `/stub` is the kept
// entry and `/nested` the link: `/stub` reads as an empty directory, a walk reaches
// the nested subvolume once, under `/nested`, and a strict walk finds nothing twice.
let forge = a_filesystem_with_a_subvolume_and(entry(
ROOT_DIR,
4,
b"stub",
DiskKey::new(SUB_ID, ItemType::ROOT_ITEM, u64::MAX),
DirEntryType::Dir,
));
let mut reader = open(&forge);
let stub = reader.lookup(b"/stub").expect("the stub");
assert!(stub.stub && stub.is_dir());
assert_eq!(
stub.tree,
objectid::FS_TREE,
"a stub is in the tree holding it"
);
assert_eq!(reader.read_dir(&stub).expect("its entries"), Vec::new());
assert!(
reader.lookup(b"/stub/within").is_err(),
"nothing is under it"
);
let nested = reader.lookup(b"/nested/within").expect("the nested file");
assert_eq!(reader.read_data(&nested).expect("its bytes"), b"inside");
let paths: Vec<Vec<u8>> = reader
.walk()
.expect("a strict walk")
.into_iter()
.map(|entry| entry.path)
.collect();
assert_eq!(
paths,
vec![
Vec::new(),
b"/above".to_vec(),
b"/nested".to_vec(),
b"/nested/within".to_vec(),
b"/stub".to_vec(),
]
);
}
#[test]
fn a_parent_component_ascends_back_out_of_the_subvolume_it_descended_into() {
// The ascent holds the directories a resolution went through, not the inode numbers
// they have — and this family is why. Inode 257 exists in every subvolume, so a
// number popped off a stack would name a file in whichever tree happened to be
// current. What comes back must be the directory that was left, tree and all.
let forge = a_filesystem_with_a_subvolume();
let mut reader = open(&forge);
let above = reader.lookup(b"/above").expect("the file above the seam");
let within = reader.lookup(b"/nested/within").expect("the nested file");
assert_eq!(within.tree, SUB_ID);
// Down into the subvolume and back out of it, which is a path that changes tree
// twice.
let ascended = reader
.lookup(b"/nested/../above")
.expect("out of the subvolume and back down");
assert_eq!((ascended.tree, ascended.inode), (above.tree, above.inode));
assert_eq!(ascended.tree, objectid::FS_TREE);
// And back down into it again, so the ascent left the resolution where it started
// rather than one step to the side.
let returned = reader
.lookup(b"/nested/../nested/within")
.expect("back into the subvolume");
assert_eq!((returned.tree, returned.inode), (within.tree, within.inode));
// The subvolume's own root ascends to the directory it is mounted in, which is in
// the tree above it.
let seam = reader
.lookup(b"/nested/..")
.expect("the mount point's parent");
assert_eq!(seam.tree, objectid::FS_TREE);
assert_eq!(seam.inode, ROOT_DIR);
// At the root there is nothing to ascend to, so nothing outside the filesystem can
// be named however many of them a caller writes.
let root = reader.root().expect("the root");
for path in [&b"/.."[..], b"/../..", b"/nested/../../.."] {
let stayed = reader
.lookup(path)
.unwrap_or_else(|e| panic!("{}: {e}", String::from_utf8_lossy(path)));
assert_eq!((stayed.tree, stayed.inode), (root.tree, root.inode));
}
}
#[test]
fn an_inode_number_is_only_an_identity_within_its_own_subvolume() {
// Two subvolumes each hold an inode 257 and they are different files. A reader that
// keyed a node by its number alone would hand back one of them for the other, and
// both are perfectly ordinary filesystems.
let forge = a_filesystem_with_a_subvolume();
let mut reader = open(&forge);
let above = reader.lookup(b"/above").expect("the top-level file");
let within = reader.lookup(b"/nested/within").expect("the nested file");
assert_eq!(above.inode, within.inode);
assert_ne!(above.tree, within.tree);
assert_eq!(reader.read_data(&above).expect("bytes"), b"up\n");
assert_eq!(reader.read_data(&within).expect("bytes"), b"inside");
}
#[test]
fn a_run_of_a_file_that_was_never_written_reads_back_as_zeros() {
// Both spellings of a gap. With `no-holes` there is no record at all and the reader
// has to notice the absence; without it there is a record whose extent address is
// zero. Neither may read back as whatever was on the volume.
let mut items = vec![
(
DiskKey::new(257, ItemType::INODE_ITEM, 0),
inode_item(MODE_REG | 0o644, 12288, 1),
),
// Nothing at all for the first 4 KiB, a written extent, then a recorded hole.
(
DiskKey::new(257, ItemType::EXTENT_DATA, 4096),
addressed_extent(ExtentKind::Regular, DATA_AT, 4096, 0, 4096),
),
(
DiskKey::new(257, ItemType::EXTENT_DATA, 8192),
addressed_extent(ExtentKind::Regular, 0, 0, 0, 4096),
),
];
items.extend(entry(
ROOT_DIR,
2,
b"sparse",
DiskKey::new(257, ItemType::INODE_ITEM, 0),
DirEntryType::RegFile,
));
let forge = a_filesystem_holding(items);
let mut reader = open(&forge);
let node = reader.lookup(b"/sparse").expect("the file");
let bytes = reader.read_data(&node).expect("its bytes");
assert_eq!(bytes.len(), 12288);
assert!(bytes[..4096].iter().all(|&b| b == 0), "the unrecorded gap");
assert!(
bytes[4096..8192].iter().all(|&b| b == DATA_BYTE),
"the extent"
);
assert!(bytes[8192..].iter().all(|&b| b == 0), "the recorded hole");
// And a read that begins inside the written run finds the record covering it rather
// than the one keyed at or after the position.
let mut buf = [0u8; 8];
reader
.read_into(&node, 5000, &mut buf)
.expect("a read from the middle of an extent");
assert!(buf.iter().all(|&b| b == DATA_BYTE));
}
#[test]
fn a_preallocated_extent_reads_back_as_zeros_rather_than_as_what_is_on_the_volume() {
// An extent that has been allocated and not written holds whatever the volume held
// before it. Handing that back would be handing back another file's deleted bytes.
let forge = a_filesystem_holding(a_file(
b"reserved",
MODE_REG | 0o644,
4096,
addressed_extent(ExtentKind::Prealloc, DATA_AT, 4096, 0, 4096),
));
let mut reader = open(&forge);
let node = reader.lookup(b"/reserved").expect("the file");
assert!(
reader
.read_data(&node)
.expect("its bytes")
.iter()
.all(|&b| b == 0)
);
}
#[test]
fn an_extent_whose_run_leaves_the_extent_it_names_is_refused() {
// The bound that matters most in this module: the record's own numbers decide which
// bytes of the volume are handed back under this file's name, so a run reaching past
// the extent would return whatever follows it — another file's contents, or metadata.
let forge = a_filesystem_holding(a_file(
b"overreaching",
MODE_REG | 0o644,
4096,
// The extent is 512 bytes long and the record claims 4096 of it.
addressed_extent(ExtentKind::Regular, DATA_AT, 512, 0, 4096),
));
let mut reader = open(&forge);
let node = reader.lookup(b"/overreaching").expect("the file");
assert!(matches!(
reader.read_data(&node),
Err(ReadError::BadExtent { .. })
));
}
#[test]
fn an_extent_encoded_in_a_way_the_format_has_not_defined_is_refused_by_its_byte() {
// A filesystem that may be entirely well-formed and is beyond every build of this
// crate, because the byte names nothing any release of the format defines. What the
// refusal must not be is a read of the encoded bytes as though they were the file's.
let record = compressed_extent(Compression::Unknown(9), b"encoded somehow", 4096);
let forge = a_filesystem_holding(a_file(b"squeezed", MODE_REG | 0o644, 4096, record));
let mut reader = open(&forge);
let node = reader.lookup(b"/squeezed").expect("the file");
let err = reader.read_data(&node).expect_err("an encoded extent");
assert!(matches!(
err,
ReadError::UnsupportedCompression { compression: 9, .. }
));
assert!(
format!("{err}").contains("an algorithm the format has not defined"),
"{err}"
);
}
/// One payload and the zlib stream it compresses to.
///
/// Recorded rather than produced: this crate writes no compressed extent, so the fixture
/// has to come from something that does — here `python3 -c "import zlib;
/// zlib.compress(b'ferrosys' * 8, 9)"`. The payload repeats, which is what makes the
/// stream shorter than what it stands for and therefore a compressed extent at all.
#[cfg(feature = "zlib")]
const ZLIB_STREAM: &[u8] = &[
0x78, 0xda, 0x4b, 0x4b, 0x2d, 0x2a, 0xca, 0x2f, 0xae, 0x2c, 0x4e, 0x23, 0x93, 0x06, 0x00,
0x88, 0x65, 0x1b, 0xe9,
];
#[cfg(feature = "zlib")]
fn zlib_payload() -> Vec<u8> {
b"ferrosys".repeat(8)
}
#[cfg(feature = "zlib")]
#[test]
fn a_compressed_extent_reads_back_as_the_bytes_it_stands_for() {
// Both shapes a compressed extent takes, because the two reach the stream by
// different routes: an inline record carries it inside the item, and an addressed one
// names a run of logical space holding it.
let want = zlib_payload();
let record = compressed_extent(Compression::Zlib, ZLIB_STREAM, want.len() as u64);
let forge = a_filesystem_holding(a_file(
b"inline",
MODE_REG | 0o644,
want.len() as u64,
record,
));
let mut reader = open(&forge);
let node = reader.lookup(b"/inline").expect("the file");
assert_eq!(reader.read_data(&node).expect("it decodes"), want);
let mut record = addressed_extent(
ExtentKind::Regular,
DATA_AT,
ZLIB_STREAM.len() as u64,
0,
64,
);
record[16] = Compression::Zlib.to_u8();
// `ram_bytes` is what the *extent* expands to, which for a record covering all of it
// is also what the record covers.
record[8..16].copy_from_slice(&(want.len() as u64).to_le_bytes());
let mut forge = a_filesystem_holding(a_file(
b"addressed",
MODE_REG | 0o644,
want.len() as u64,
record,
));
forge.data(DATA_AT, ZLIB_STREAM);
let mut reader = open(&forge);
let node = reader.lookup(b"/addressed").expect("the file");
assert_eq!(reader.read_data(&node).expect("it decodes"), want);
// And a read from the middle of it, which is the case the expansion exists for: the
// stream says nothing about where a position in the file lands, so the whole extent
// is undone and the window taken from what it became.
let mut middle = [0u8; 8];
assert_eq!(
reader
.read_into(&node, 20, &mut middle)
.expect("it decodes"),
8
);
assert_eq!(&middle, &want[20..28]);
}
#[cfg(feature = "zlib")]
#[test]
fn a_compressed_extent_that_does_not_decode_is_a_fault_in_the_filesystem() {
// Apart from an algorithm this build has no decoder for, which is a filesystem that
// is sound and beyond it. Here the build *does* decode the algorithm and the bytes
// are not a stream of it, which is damage and says so.
let record = compressed_extent(Compression::Zlib, b"not a stream", 64);
let forge = a_filesystem_holding(a_file(b"damaged", MODE_REG | 0o644, 64, record));
let mut reader = open(&forge);
let node = reader.lookup(b"/damaged").expect("the file");
assert!(matches!(
reader.read_data(&node),
Err(ReadError::BadCompressedExtent { .. })
));
}
#[cfg(feature = "zlib")]
#[test]
fn a_record_expanding_to_more_than_the_format_compresses_in_is_refused_before_it_costs_it() {
// The bound that keeps a crafted record from being an allocation. The expanded length
// is a number the image supplied and it is the size of a buffer, so a record naming a
// gibibyte must cost a refusal rather than a gibibyte.
let mut record = compressed_extent(Compression::Zlib, ZLIB_STREAM, 64);
record[8..16].copy_from_slice(&(1u64 << 30).to_le_bytes());
let forge = a_filesystem_holding(a_file(b"greedy", MODE_REG | 0o644, 1 << 30, record));
let mut reader = open(&forge);
let node = reader.lookup(b"/greedy").expect("the file");
let mut out = [0u8; 64];
assert!(matches!(
reader.read_into(&node, 0, &mut out),
Err(ReadError::BadExtent { .. })
));
}
#[test]
fn a_directory_reachable_from_itself_is_refused_strictly_and_descended_once_leniently() {
// No formatter writes this and a crafted image is exactly where it appears. Nothing
// about a bound on one entry sees it: every record is well-formed, and a walk that
// followed the entries would not terminate. A btrfs directory has one name, so a
// strict walk refuses the filesystem for the repeat.
let mut items = vec![(
DiskKey::new(257, ItemType::INODE_ITEM, 0),
inode_item(MODE_DIR | 0o755, 0, 1),
)];
items.extend(entry(
ROOT_DIR,
2,
b"down",
DiskKey::new(257, ItemType::INODE_ITEM, 0),
DirEntryType::Dir,
));
items.extend(entry(
257,
2,
b"up",
DiskKey::new(ROOT_DIR, ItemType::INODE_ITEM, 0),
DirEntryType::Dir,
));
let forge = a_filesystem_holding(items);
assert!(matches!(
open(&forge).walk(),
Err(ReadError::RepeatedDirectory {
inode: ROOT_DIR,
..
})
));
let mut reader = Reader::open_with(
forge.source(),
&OpenOptions::new().policy(ReadPolicy::Lenient),
)
.expect("a forged filesystem");
let paths: Vec<Vec<u8>> = reader
.walk()
.expect("a lenient walk terminates")
.into_iter()
.map(|walked| walked.path)
.collect();
// The second name for the root is yielded, because it is a name the filesystem holds.
// What does not happen is descending into it, which is what would not terminate.
assert_eq!(
paths,
vec![Vec::new(), b"/down".to_vec(), b"/down/up".to_vec()]
);
}
#[test]
fn a_name_no_directory_can_hold_stops_a_walk_rather_than_becoming_a_path() {
// A name carrying a separator would traverse out of its own directory in every path
// built from it, which is what an extraction would then write.
let forge = a_filesystem_holding(a_file(
b"../escape",
MODE_REG | 0o644,
0,
inline_extent(b""),
));
let mut reader = open(&forge);
assert!(matches!(reader.walk(), Err(ReadError::HostileName { .. })));
// And it is unreachable as a path, which is the other half of the same claim: written
// out, the name is an ascent and then a component, so what a resolution looks for is
// an entry called `escape` in the root — a name this filesystem does not hold. The
// entry it does hold cannot be named at all, which is what refusing it where it is
// read is for.
assert!(matches!(
reader.lookup(b"/../escape"),
Err(ReadError::NotFound { .. })
));
}
/// A filesystem holding one addressed file and a checksum tree covering `covering` — which
/// is the bytes the extent is *said* to hold, and need not be the bytes on the volume.
fn a_filesystem_with_checksums(on_the_volume: &[u8], covering: &[u8]) -> Forge {
let items = a_file(
b"data",
MODE_REG | 0o644,
4096,
addressed_extent(ExtentKind::Regular, DATA_AT, 4096, 0, 4096),
);
a_checksummed_filesystem_holding(items, on_the_volume, covering)
}
/// A filesystem whose root holds `items`, with `on_the_volume` at the data address and the
/// checksum tree recording one checksum per sector of `covering` from there.
fn a_checksummed_filesystem_holding(
items: Vec<(DiskKey, Vec<u8>)>,
on_the_volume: &[u8],
covering: &[u8],
) -> Forge {
let mut forge = Forge::new();
let mut all = vec![(
DiskKey::new(ROOT_DIR, ItemType::INODE_ITEM, 0),
inode_item(MODE_DIR | 0o755, 0, 1),
)];
all.extend(items);
forge.block(FS_TREE_AT, &fs_tree(FS_TREE_AT, objectid::FS_TREE, all));
forge.data(DATA_AT, on_the_volume);
forge.block(
SUB_TREE_AT,
&fs_tree(
SUB_TREE_AT,
objectid::CSUM_TREE,
vec![(
DiskKey::new(objectid::EXTENT_CSUM, ItemType::EXTENT_CSUM, DATA_AT),
csum_item(covering, NODE_SIZE),
)],
),
);
// In key order, which the format requires of every tree and a walk checks: the
// filesystem tree is 5 and the checksum tree is 7.
forge.root_leaf(&[
(
DiskKey::new(objectid::FS_TREE, ItemType::ROOT_ITEM, 0),
root_item(FS_TREE_AT, 0, ROOT_DIR),
),
(
DiskKey::new(objectid::CSUM_TREE, ItemType::ROOT_ITEM, 0),
root_item(SUB_TREE_AT, 0, 0),
),
]);
forge
}
#[test]
fn a_files_bytes_are_held_against_the_checksums_the_filesystem_recorded_for_them() {
// The check no other family here can make: every tree is well-formed, every metadata
// block verifies, and the bytes of the file are still not the bytes that were written.
let bytes = [DATA_BYTE; 4096];
let forge = a_filesystem_with_checksums(&bytes, &bytes);
let mut reader = open(&forge);
let node = reader.lookup(b"/data").expect("the file");
reader.verify_data(&node).expect("the bytes are the bytes");
// One byte of the volume changed, with nothing else touched — which is exactly the
// damage a medium does and the one an ordinary read hands straight back.
let mut decayed = bytes;
decayed[100] ^= 0xff;
let forge = a_filesystem_with_checksums(&decayed, &bytes);
let mut reader = open(&forge);
let node = reader.lookup(b"/data").expect("the file");
assert_eq!(
reader.read_data(&node).expect("a read still succeeds")[100],
DATA_BYTE ^ 0xff,
"an ordinary read hands back what is there"
);
assert!(matches!(
reader.verify_data(&node),
Err(ReadError::DataChecksum { logical }) if logical == DATA_AT
));
}
#[test]
fn a_record_over_part_of_an_extent_is_held_to_its_own_sectors() {
// A write into part of a preallocated extent leaves a regular record over the written
// sector, which carries a checksum, and a preallocated one over the rest, which does
// not. What the file reads through the regular record is what has a checksum.
let mut items = vec![
(
DiskKey::new(257, ItemType::INODE_ITEM, 0),
inode_item(MODE_REG | 0o644, 8192, 1),
),
(
DiskKey::new(257, ItemType::EXTENT_DATA, 0),
addressed_extent(ExtentKind::Regular, DATA_AT, 8192, 0, 4096),
),
(
DiskKey::new(257, ItemType::EXTENT_DATA, 4096),
addressed_extent(ExtentKind::Prealloc, DATA_AT, 8192, 4096, 4096),
),
];
items.extend(entry(
ROOT_DIR,
2,
b"part",
DiskKey::new(257, ItemType::INODE_ITEM, 0),
DirEntryType::RegFile,
));
let mut on_the_volume = vec![0u8; 8192];
on_the_volume[..4096].fill(DATA_BYTE);
let forge = a_checksummed_filesystem_holding(items, &on_the_volume, &on_the_volume[..4096]);
let mut reader = open(&forge);
let node = reader.lookup(b"/part").expect("the file");
reader
.verify_data(&node)
.expect("the written sector verifies, and the rest holds nothing to check");
}
#[test]
fn a_file_with_no_checksum_recorded_for_it_is_reported_rather_than_passed() {
// A run with no record is not a run that verified. Treating a missing checksum as a
// pass would make the whole check vacuous on an image whose checksum tree was lost.
let forge = a_filesystem_with_checksums(&[DATA_BYTE; 4096], &[]);
let mut reader = open(&forge);
let node = reader.lookup(b"/data").expect("the file");
assert!(matches!(
reader.verify_data(&node),
Err(ReadError::MissingDataChecksum { .. })
));
}
#[test]
fn a_file_the_filesystem_does_not_checksum_is_not_held_to_one() {
// `NODATASUM` says there is nothing recorded, so asking for a checksum would report a
// healthy file as one whose checksums are missing.
let mut record = inode_item(MODE_REG | 0o644, 4096, 1);
// The flags word sits at offset 64 of an inode item.
record[64] = InodeFlags::NODATASUM.bits() as u8;
let mut items = vec![
(DiskKey::new(257, ItemType::INODE_ITEM, 0), record),
(
DiskKey::new(257, ItemType::EXTENT_DATA, 0),
addressed_extent(ExtentKind::Regular, DATA_AT, 4096, 0, 4096),
),
];
items.extend(entry(
ROOT_DIR,
2,
b"raw",
DiskKey::new(257, ItemType::INODE_ITEM, 0),
DirEntryType::RegFile,
));
let forge = a_filesystem_holding(items);
let mut reader = open(&forge);
let node = reader.lookup(b"/raw").expect("the file");
assert!(node.item.flags.contains(InodeFlags::NODATASUM));
reader
.verify_data(&node)
.expect("nothing is recorded, so nothing is held against");
// And a hole or a preallocated extent has nothing to check either, on a filesystem
// that does checksum — so a file of them verifies without a checksum tree being
// consulted at all.
let forge = a_filesystem_holding(a_file(
b"reserved",
MODE_REG | 0o644,
4096,
addressed_extent(ExtentKind::Prealloc, DATA_AT, 4096, 0, 4096),
));
let mut reader = open(&forge);
let node = reader.lookup(b"/reserved").expect("the file");
reader.verify_data(&node).expect("nothing has been written");
}
#[test]
fn a_device_longer_than_its_region_is_found_short_and_one_inside_it_is_not() {
// The forged device a mebibyte into a disk, and a neighbour's bytes after it. The
// device's only copy of the superblock and its one chunk lie in its first 384 KiB,
// so a region of 512 KiB opens strictly, and nothing the scan reads is missing.
const BASE: u64 = 1 << 20;
let mut device = Vec::new();
std::io::Read::read_to_end(&mut Forge::populated().source(), &mut device)
.expect("the forged device");
let len = device.len() as u64;
let mut disk = vec![0u8; BASE as usize];
disk.extend_from_slice(&device);
disk.extend(vec![0xee; 1 << 20]);
let scan = |len: Option<u64>| {
let mut options = OpenOptions::new().base(BASE);
options.len = len;
Reader::open_with(std::io::Cursor::new(disk.as_slice()), &options)
.expect("open")
.scan()
};
let report = scan(Some(512 << 10));
assert_eq!(report.anomalies().len(), 1, "{:?}", report.anomalies());
let short = &report.anomalies()[0];
assert_eq!(
(short.category, short.severity),
(Category::Superblock, Severity::Structural)
);
assert!(
short.detail.contains(&format!(
"records {len} bytes and the source holds {}",
512 << 10
)),
"{}",
short.detail
);
for len in [Some(len), None] {
let report = scan(len);
assert!(report.is_clean(), "{len:?}: {:?}", report.anomalies());
}
}
#[test]
fn a_filesystem_nothing_is_wrong_with_scans_clean() {
let forge = Forge::populated();
let mut reader = open(&forge);
let report = reader.scan();
assert!(report.is_clean(), "{:?}", report.anomalies());
assert!(!report.is_truncated());
}
#[test]
fn a_filesystem_that_was_not_cleanly_unmounted_says_what_is_missing() {
// The instance where "cosmetic" is arguable: the image is
// conformant and every byte read is trustworthy, and the filesystem genuinely holds
// writes the committed trees do not. So the message says what is missing rather than
// which field held an unexpected value.
let mut forge = Forge::populated();
forge.amend_superblock(0, |sb| sb.log_root = FS_TREE_AT);
let mut reader = open(&forge);
let report = reader.scan();
let logged: Vec<&Anomaly> = report
.anomalies()
.iter()
.filter(|a| a.category == Category::Superblock)
.collect();
assert_eq!(logged.len(), 1);
assert_eq!(logged[0].severity, Severity::Cosmetic);
// The sentence every family says of a filesystem left mounted, and then what this
// family's record adds to it.
assert!(
logged[0]
.detail
.starts_with(crate::finding::NOT_CLEANLY_UNMOUNTED),
"{}",
logged[0].detail
);
assert!(logged[0].detail.contains("last committed transaction"));
// A scan reports rather than refuses, so the filesystem still reads.
let node = reader.lookup(b"/hello.txt").expect("the file");
assert_eq!(reader.read_data(&node).expect("its bytes"), b"hello\n");
}
#[test]
fn a_scan_reports_a_block_that_does_not_verify_rather_than_stopping_at_it() {
// The difference between a scan and a read: a read stops where it cannot go on, and a
// scan is what a caller asking "is anything wrong with this image" runs.
let mut forge = Forge::populated();
forge.break_checksum(FS_TREE_AT);
let mut reader = Reader::open_with(
forge.source(),
&OpenOptions::new().policy(ReadPolicy::Lenient),
)
.expect("the superblock and the root tree are intact");
let report = reader.scan();
assert!(!report.is_clean());
let damaged: Vec<&Anomaly> = report
.anomalies()
.iter()
.filter(|a| a.severity == Severity::Integrity)
.collect();
assert_eq!(damaged.len(), 1, "{:?}", report.anomalies());
assert_eq!(damaged[0].category, Category::Tree);
assert_eq!(damaged[0].tree, Some(objectid::FS_TREE));
// And a read of the same filesystem fails at that block, which is the other half of
// the contract: what a scan reports, a read refuses.
assert!(matches!(
reader.lookup(b"/hello.txt"),
Err(ReadError::BadChecksum { .. })
));
}
#[test]
fn a_scan_reports_a_uuid_tree_that_disagrees_with_the_root_items() {
// A subvolume's root item records its identifier and the UUID tree maps the identifier
// back to the subvolume, and the pair can disagree while every block of both trees
// verifies: no checksum covers the agreement, and a walk of either tree alone meets
// nothing wrong. A lookup by identifier then misses, and the format's own tooling
// rewrites the tree on the next writable mount — so the scan is where the disagreement
// has to surface.
const UUID_TREE_AT: u64 = FS_TREE_AT + 3 * NODE_SIZE as u64;
let held = [0x44u8; 16];
let mut item = root_item(FS_TREE_AT, 0, ROOT_DIR);
let mut with_uuid = RootItem::read_from(&item).expect("the forge's root item reads back");
with_uuid.uuid = held;
with_uuid.write_to(&mut item);
let mut forge = Forge::new();
forge.block(
FS_TREE_AT,
&fs_tree(
FS_TREE_AT,
objectid::FS_TREE,
vec![(
DiskKey::new(ROOT_DIR, ItemType::INODE_ITEM, 0),
inode_item(MODE_DIR | 0o755, 0, 1),
)],
),
);
// The tree's one entry maps the null identifier to the subvolume, while the root item
// records 0x44…44 — the two halves of one fact, filled from different sources.
forge.block(
UUID_TREE_AT,
&leaf(
UUID_TREE_AT,
objectid::UUID_TREE,
&[(
DiskKey::new(0, ItemType::UUID_SUBVOL, 0),
objectid::FS_TREE.to_le_bytes().to_vec(),
)],
),
);
forge.root_leaf(&[
(
DiskKey::new(objectid::FS_TREE, ItemType::ROOT_ITEM, 0),
item,
),
(
DiskKey::new(objectid::UUID_TREE, ItemType::ROOT_ITEM, 0),
root_item(UUID_TREE_AT, 0, 0),
),
]);
let mut reader = open(&forge);
let report = reader.scan();
let details: Vec<&str> = report
.anomalies()
.iter()
.filter(|a| a.tree == Some(objectid::UUID_TREE))
.map(|a| a.detail.as_str())
.collect();
assert_eq!(details.len(), 2, "{:?}", report.anomalies());
assert!(
details[0].contains("records a different identifier"),
"{details:?}"
);
assert!(
details[1].contains("no entry mapping it back"),
"{details:?}"
);
// Both directions hold severity below refusal: the filesystem still reads.
reader.root().expect("the root directory");
}
#[test]
fn a_filesystem_with_no_top_level_tree_is_refused_at_open() {
// The root tree names every tree there is, so one with no record of the filesystem
// tree is an image with nowhere for a path to start.
let mut forge = Forge::new();
forge.root_leaf(&[]);
assert!(matches!(
Reader::open(forge.source()),
Err(ReadError::MissingTree { objectid: 5 })
));
}
#[test]
fn a_whole_file_read_is_held_to_the_cap_the_caller_set() {
// A file's declared length is a number the image supplies and a hole reads back as
// zeros, so a whole-file read of an inode claiming more than the image holds costs
// exactly what the inode claims.
let forge = Forge::populated();
let mut reader = Reader::open_with(
forge.source(),
&OpenOptions::new().limits(Limits::new().max_file_bytes(4)),
)
.expect("a forged filesystem");
let node = reader.lookup(b"/hello.txt").expect("the file");
assert!(matches!(
reader.read_data(&node),
Err(ReadError::FileTooLarge {
size: 6,
cap: 4,
..
})
));
// Streaming is held to it as well: what the cap expresses is distrust of the declared
// length, and a stream writes every byte that length claims as surely as a buffer
// holds them. Nothing is written before the refusal.
let mut out = Vec::new();
assert!(matches!(
reader.read_data_to(&node, &mut out),
Err(ReadError::FileTooLarge {
size: 6,
cap: 4,
..
})
));
assert!(out.is_empty());
// Under the cap the stream is the file.
let mut reader = Reader::open_with(
forge.source(),
&OpenOptions::new().limits(Limits::new().max_file_bytes(6)),
)
.expect("a forged filesystem");
let node = reader.lookup(b"/hello.txt").expect("the file");
assert_eq!(reader.read_data_to(&node, &mut out).expect("streaming"), 6);
}
// -- what a read costs ------------------------------------------------------------------
//
// These pin the shape of the reads a walk issues, not their count on one build: the count
// moves with the tree, and the shape is the property.
use crate::io::Counting;
/// A filesystem whose trees have levels above their leaves: six thousand files in twenty
/// directories, each small enough to be stored in the metadata.
fn read_cost_image() -> Vec<u8> {
use crate::source::{Metadata, TreeBuilder};
let time = crate::Timestamp::from_secs(1_700_000_000);
let mut tree = TreeBuilder::new();
for d in 0..20u32 {
tree = tree.directory(format!("/d{d}").into_bytes(), Metadata::new(0o755, time));
for f in 0..300u32 {
let len = ((d * 61 + f * 389) % 3000) as usize;
tree = tree.file(
format!("/d{d}/f{f}").into_bytes(),
vec![(d + f) as u8; len],
Metadata::new(0o644, time),
);
}
}
crate::btrfs::format(
tree,
1 << 30,
crate::btrfs::FormatOptions::new([0x11; 16], time),
)
.expect("a formattable tree")
.into_bytes()
}
#[test]
fn a_walk_reads_each_tree_block_once() {
// A walk looks every entry up again under its inode, and each search passes through
// the top of the tree it searches. With those held, every block the walk needs is
// fetched once: each read is one block, and no block is asked for twice.
let (source, reads) = Counting::new(read_cost_image());
let mut reader = Reader::open(source).expect("this crate reads what it wrote");
reads.borrow_mut().clear();
let entries = reader.walk().expect("a walk");
assert!(entries.len() > 6000, "the walk reached {}", entries.len());
let mut blocks: Vec<u64> = reads
.borrow()
.iter()
.map(|&(at, len)| {
assert_eq!(len, 16384, "a read of {len} bytes at {at}");
at
})
.collect();
let read = blocks.len();
blocks.sort_unstable();
blocks.dedup();
assert_eq!(blocks.len(), read, "a tree block was read twice");
}
#[test]
fn a_search_reads_the_top_of_a_tree_once_rather_than_once_per_search() {
// Every lookup descends from the root of the tree it searches, so without the cache
// the upper levels are read and checksummed once per lookup. Measured over a walk and
// a lookup of every seventh path, with no cache and with the default one. That a
// larger cache never misses where a smaller one hits is the cache's own property, and
// is held there.
let bytes = read_cost_image();
let reads_with = |capacity: Option<usize>| {
let (source, reads) = Counting::new(bytes.clone());
let mut reader = Reader::open(source).expect("this crate reads what it wrote");
if let Some(capacity) = capacity {
reader = reader.with_cache_capacity(capacity);
}
reads.borrow_mut().clear();
let entries = reader.walk().expect("a walk");
for entry in entries.iter().step_by(7) {
reader
.lookup(&entry.path)
.expect("every path walked resolves");
}
reads.borrow().len()
};
let (none, held) = (reads_with(Some(0)), reads_with(None));
assert!(
held * 10 < none,
"holding tree blocks cut {none} reads only to {held}"
);
}
/// The filesystem tree's root in `image`, where each of its copies sits on the device, and
/// the node size — what a gate damaging one copy of a mirrored block needs.
fn mirrored_fs_root(image: &[u8]) -> (TreeRoot, Vec<u64>, usize) {
use crate::btrfs::Volume;
let mut volume = Volume::open(std::io::Cursor::new(image)).expect("healthy");
let root = volume
.tree_roots()
.expect("the root tree")
.into_iter()
.find(|root| root.objectid == objectid::FS_TREE)
.expect("a filesystem tree");
let chunk = volume.chunk_map().chunk_at(root.bytenr).expect("mapped");
let copies: Vec<u64> = chunk
.copies
.iter()
.map(|©| copy + (root.bytenr - chunk.logical))
.collect();
assert_eq!(copies.len(), 2, "the block is mirrored");
(root, copies, volume.node_size() as usize)
}
#[test]
fn a_tree_block_whose_first_copy_is_from_another_transaction_is_read_through_the_second() {
use crate::btrfs::ondisk::{Header, checksum};
use crate::{OpenOptions, ReadPolicy};
// A copy left from an earlier transaction verifies in every respect but the
// generation, so that is what tells the stale copy from the live one — and a lenient
// read that recovers through a mirror has to judge it by that too.
let healthy = read_cost_image();
let (root, copies, node) = mirrored_fs_root(&healthy);
let (logical, generation) = (root.bytenr, root.generation);
let stale = |bytes: &mut Vec<u8>, copy: u64| {
let block = &mut bytes[copy as usize..copy as usize + node];
let mut header = Header::read_from(block).expect("a header");
header.generation = generation + 1;
header.write_to(block);
let digest = checksum(block);
block[..4].copy_from_slice(&digest.to_le_bytes());
};
let lenient = OpenOptions::new().policy(ReadPolicy::Lenient);
let expected = Reader::open(std::io::Cursor::new(healthy.clone()))
.expect("healthy")
.walk()
.expect("a walk");
let mut first = healthy.clone();
stale(&mut first, copies[0]);
let mut strict = Reader::open(std::io::Cursor::new(first.clone())).expect("it opens");
assert!(matches!(
strict.walk(),
Err(ReadError::WrongGeneration { logical: at, .. }) if at == logical
));
let mut reader =
Reader::open_with(std::io::Cursor::new(first), &lenient).expect("it opens");
assert_eq!(
reader.walk().expect("read through the second copy"),
expected
);
let report = reader.scan();
assert!(
report
.anomalies()
.iter()
.any(|anomaly| anomaly.logical == Some(logical)
&& anomaly.detail.contains("read through copy 1")),
"{:?}",
report.anomalies()
);
let mut both = healthy;
stale(&mut both, copies[0]);
stale(&mut both, copies[1]);
let mut reader = Reader::open_with(std::io::Cursor::new(both), &lenient).expect("it opens");
assert!(matches!(
reader.walk(),
Err(ReadError::WrongGeneration { logical: at, .. }) if at == logical
));
}
#[test]
fn a_tree_block_with_a_damaged_first_copy_is_read_through_the_second_leniently() {
use crate::{OpenOptions, ReadPolicy};
// The filesystem tree's root, in a block group whose metadata is mirrored by default.
let healthy = read_cost_image();
let (root, copies, _) = mirrored_fs_root(&healthy);
let logical = root.bytenr;
let damage = |bytes: &mut Vec<u8>, copy: u64| bytes[copy as usize + 200] ^= 0xff;
let lenient = OpenOptions::new().policy(ReadPolicy::Lenient);
let expected = Reader::open(std::io::Cursor::new(healthy.clone()))
.expect("healthy")
.walk()
.expect("a walk");
let mut first = healthy.clone();
damage(&mut first, copies[0]);
// A strict read takes the first copy and refuses the block.
let mut strict = Reader::open(std::io::Cursor::new(first.clone())).expect("it opens");
assert!(matches!(
strict.walk(),
Err(ReadError::BadChecksum { at, .. }) if at == logical
));
// A lenient one reads it through the second, and the scan names it.
let mut reader =
Reader::open_with(std::io::Cursor::new(first), &lenient).expect("it opens");
assert_eq!(
reader.walk().expect("read through the second copy"),
expected
);
let report = reader.scan();
let named: Vec<_> = report
.anomalies()
.iter()
.filter(|anomaly| anomaly.logical == Some(logical))
.collect();
assert_eq!(named.len(), 1, "{:?}", report.anomalies());
assert_eq!(named[0].category, Category::Tree);
assert!(
named[0].detail.contains("read through copy 1"),
"{:?}",
named[0]
);
// With both copies damaged there is nothing to read it through.
let mut both = healthy;
damage(&mut both, copies[0]);
damage(&mut both, copies[1]);
let mut reader = Reader::open_with(std::io::Cursor::new(both), &lenient).expect("it opens");
assert!(matches!(
reader.walk(),
Err(ReadError::BadChecksum { at, .. }) if at == logical
));
}
}