File: rockridge.py

package info (click to toggle)
python-pycdlib 1.12.0%2Bds1-4%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,044 kB
  • sloc: python: 35,639; makefile: 63
file content (3767 lines) | stat: -rw-r--r-- 131,485 bytes parent folder | download | duplicates (2)
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
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
# Copyright (C) 2015-2020  Chris Lalancette <clalancette@gmail.com>

# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation;
# version 2.1 of the License.

# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

'''
Classes and utilities to support Rock Ridge extensions.
'''

from __future__ import absolute_import

import bisect
import struct

from pycdlib import dates
from pycdlib import pycdlibexception
from pycdlib import utils

# For mypy annotations
if False:  # pylint: disable=using-constant-test
    from typing import Dict, List, Optional  # NOQA pylint: disable=unused-import
    # NOTE: this has to be here to avoid circular deps
    from pycdlib import dr  # NOQA pylint: disable=unused-import

SU_ENTRY_VERSION = 1
ALLOWED_DR_SIZE = 254
TF_FLAGS = 0x0e
EXT_ID_109 = b'RRIP_1991A'
EXT_DES_109 = b'THE ROCK RIDGE INTERCHANGE PROTOCOL PROVIDES SUPPORT FOR POSIX FILE SYSTEM SEMANTICS'
EXT_SRC_109 = b'PLEASE CONTACT DISC PUBLISHER FOR SPECIFICATION SOURCE.  SEE PUBLISHER IDENTIFIER IN PRIMARY VOLUME DESCRIPTOR FOR CONTACT INFORMATION.'
EXT_ID_112 = b'IEEE_P1282'
EXT_DES_112 = b'THE IEEE P1282 PROTOCOL PROVIDES SUPPORT FOR POSIX FILE SYSTEM SEMANTICS'
EXT_SRC_112 = b'PLEASE CONTACT THE IEEE STANDARDS DEPARTMENT, PISCATAWAY, NJ, USA FOR THE P1282 SPECIFICATION'


class RRSPRecord(object):
    '''
    A class that represents a Rock Ridge Sharing Protocol record.  This record
    indicates that the sharing protocol is in use, and how many bytes to skip
    prior to parsing a Rock Ridge entry out of a directory record.
    '''
    __slots__ = ('_initialized', 'bytes_to_skip')

    FMT = '=BBBBB'

    def __init__(self):
        # type: () -> None
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Sharing Protocol record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SP record already initialized')

        (su_len, su_entry_version_unused, check_byte1, check_byte2,
         self.bytes_to_skip) = struct.unpack_from(self.FMT, rrstr[:7], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        if su_len != RRSPRecord.length():
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on rock ridge extension')
        if check_byte1 != 0xbe or check_byte2 != 0xef:
            raise pycdlibexception.PyCdlibInvalidISO('Invalid check bytes on rock ridge extension')

        self._initialized = True

    def new(self, bytes_to_skip):
        # type: (int) -> None
        '''
        Create a new Rock Ridge Sharing Protocol record.

        Parameters:
        bytes_to_skip - The number of bytes to skip.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SP record already initialized')

        self.bytes_to_skip = bytes_to_skip
        self._initialized = True

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Sharing Protocol record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SP record not initialized')

        return b'SP' + struct.pack(self.FMT, RRSPRecord.length(),
                                   SU_ENTRY_VERSION, 0xbe, 0xef,
                                   self.bytes_to_skip)

    @staticmethod
    def length():
        # type: () -> int
        '''
        Static method to return the length of the Rock Ridge Sharing Protocol
        record.

        Parameters:
         None.
        Returns:
         The length of this record in bytes.
        '''
        return 7


class RRRRRecord(object):
    '''
    A class that represents a Rock Ridge Rock Ridge record.  This optional
    record indicates which other Rock Ridge fields are present.
    '''
    __slots__ = ('_initialized', 'rr_flags')

    FMT = '=BBB'

    def __init__(self):
        # type: () -> None
        self.rr_flags = 0
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Rock Ridge record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('RR record already initialized')

        (su_len, su_entry_version_unused,
         self.rr_flags) = struct.unpack_from(self.FMT, rrstr[:5], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        if su_len != RRRRRecord.length():
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on rock ridge extension')

        self._initialized = True

    def new(self):
        # type: () -> None
        '''
        Create a new Rock Ridge Rock Ridge record.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('RR record already initialized')

        self.rr_flags = 0
        self._initialized = True

    def append_field(self, fieldname):
        # type: (str) -> None
        '''
        Mark a field as present in the Rock Ridge records.

        Parameters:
         fieldname - The name of the field to mark as present; should be one
                     of 'PX', 'PN', 'SL', 'NM', 'CL', 'PL', 'RE', or 'TF'.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('RR record not initialized')

        field_to_bit = {
            'PX': 0,
            'PN': 1,
            'SL': 2,
            'NM': 3,
            'CL': 4,
            'PL': 5,
            'RE': 6,
            'TF': 7
        }

        try:
            self.rr_flags |= (1 << field_to_bit[fieldname])
        except KeyError:
            raise pycdlibexception.PyCdlibInternalError('Unknown RR field name %s' % (fieldname))

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Rock Ridge record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('RR record not initialized')

        return b'RR' + struct.pack(self.FMT, RRRRRecord.length(),
                                   SU_ENTRY_VERSION, self.rr_flags)

    @staticmethod
    def length():
        # type: () -> int
        '''
        Static method to return the length of the Rock Ridge Rock Ridge
        record.

        Parameters:
         None.
        Returns:
         The length of this record in bytes.
        '''
        return 5


class RRCERecord(object):
    '''
    A class that represents a Rock Ridge Continuation Entry record.  This
    record represents additional information that did not fit in the standard
    directory record.
    '''
    __slots__ = ('_initialized', 'bl_cont_area', 'offset_cont_area',
                 'len_cont_area')

    FMT = '<BBLLLLLL'

    def __init__(self):
        # type: () -> None
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Continuation Entry record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('CE record already initialized')

        (su_len, su_entry_version_unused, bl_cont_area_le, bl_cont_area_be,
         offset_cont_area_le, offset_cont_area_be,
         len_cont_area_le, len_cont_area_be) = struct.unpack_from(self.FMT, rrstr[:28], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        if su_len != RRCERecord.length():
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on rock ridge extension')

        if bl_cont_area_le != utils.swab_32bit(bl_cont_area_be):
            raise pycdlibexception.PyCdlibInvalidISO('CE record big and little endian continuation area do not agree')

        if offset_cont_area_le != utils.swab_32bit(offset_cont_area_be):
            raise pycdlibexception.PyCdlibInvalidISO('CE record big and little endian continuation area offset do not agree')

        if len_cont_area_le != utils.swab_32bit(len_cont_area_be):
            raise pycdlibexception.PyCdlibInvalidISO('CE record big and little endian continuation area length do not agree')

        self.bl_cont_area = bl_cont_area_le
        self.offset_cont_area = offset_cont_area_le
        self.len_cont_area = len_cont_area_le

        self._initialized = True

    def new(self):
        # type: () -> None
        '''
        Create a new Rock Ridge Continuation Entry record.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('CE record already initialized')

        self.bl_cont_area = 0  # This will get set during reshuffle_extents
        self.offset_cont_area = 0  # This will get set during reshuffle_extents
        self.len_cont_area = 0  # This will be calculated based on fields put in

        self._initialized = True

    def update_extent(self, extent):
        # type: (int) -> None
        '''
        Update the extent for this CE record.

        Parameters:
         extent - The new extent for this CE record.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('CE record not initialized')

        self.bl_cont_area = extent

    def update_offset(self, offset):
        # type: (int) -> None
        '''
        Update the offset for this CE record.

        Parameters:
         extent - The new offset for this CE record.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('CE record not initialized')

        self.offset_cont_area = offset

    def add_record(self, length):
        # type: (int) -> None
        '''
        Add some more length to this CE record.  Used when a new record is going
        to get recorded into the CE (rather than the DR).

        Parameters:
         length - The length to add to this CE record.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('CE record not initialized')

        self.len_cont_area += length

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Continuation Entry record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('CE record not initialized')

        return b'CE' + struct.pack(self.FMT,
                                   RRCERecord.length(),
                                   SU_ENTRY_VERSION,
                                   self.bl_cont_area,
                                   utils.swab_32bit(self.bl_cont_area),
                                   self.offset_cont_area,
                                   utils.swab_32bit(self.offset_cont_area),
                                   self.len_cont_area,
                                   utils.swab_32bit(self.len_cont_area))

    @staticmethod
    def length():
        # type: () -> int
        '''
        Static method to return the length of the Rock Ridge Continuation Entry
        record.

        Parameters:
         None.
        Returns:
         The length of this record in bytes.
        '''
        return 28


class RRPXRecord(object):
    '''
    A class that represents a Rock Ridge POSIX File Attributes record.  This
    record contains information about the POSIX file mode, file links,
    user ID, group ID, and serial number of a directory record.
    '''
    __slots__ = ('_initialized', 'posix_file_mode', 'posix_file_links',
                 'posix_user_id', 'posix_group_id', 'posix_serial_number')

    FMT = '<BBLLLLLLLL'

    def __init__(self):
        # type: () -> None
        self.posix_file_mode = 0
        self.posix_file_links = 1
        self.posix_user_id = 0
        self.posix_group_id = 0
        self.posix_serial_number = 0

        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> int
        '''
        Parse a Rock Ridge POSIX File Attributes record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         The length of the record in bytes.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PX record already initialized')

        (su_len, su_entry_version_unused, posix_file_mode_le, posix_file_mode_be,
         posix_file_links_le, posix_file_links_be, posix_file_user_id_le,
         posix_file_user_id_be, posix_file_group_id_le,
         posix_file_group_id_be) = struct.unpack_from(self.FMT, rrstr[:38], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        if posix_file_mode_le != utils.swab_32bit(posix_file_mode_be):
            raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file mode do not agree')

        if posix_file_links_le != utils.swab_32bit(posix_file_links_be):
            raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file links do not agree')

        if posix_file_user_id_le != utils.swab_32bit(posix_file_user_id_be):
            raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file user ID do not agree')

        if posix_file_group_id_le != utils.swab_32bit(posix_file_group_id_be):
            raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file group ID do not agree')

        # In Rock Ridge 1.09 and 1.10, there is no serial number so the su_len
        # is 36, while in Rock Ridge 1.12, there is an 8-byte serial number so
        # su_len is 44.
        if su_len == 36:
            posix_file_serial_number_le = 0
        elif su_len == 44:
            (posix_file_serial_number_le,
             posix_file_serial_number_be) = struct.unpack_from('<LL',
                                                               rrstr[:44], 36)
            if posix_file_serial_number_le != utils.swab_32bit(posix_file_serial_number_be):
                raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file serial number do not agree')
        else:
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on Rock Ridge PX record')

        self.posix_file_mode = posix_file_mode_le
        self.posix_file_links = posix_file_links_le
        self.posix_user_id = posix_file_user_id_le
        self.posix_group_id = posix_file_group_id_le
        self.posix_serial_number = posix_file_serial_number_le

        self._initialized = True

        return su_len

    def new(self, mode):
        # type: (int) -> None
        '''
        Create a new Rock Ridge POSIX File Attributes record.

        Parameters:
         mode - The Unix file mode for this record.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PX record already initialized')

        self.posix_file_mode = mode
        self.posix_file_links = 1
        self.posix_user_id = 0
        self.posix_group_id = 0
        self.posix_serial_number = 0

        self._initialized = True

    def record(self, rr_version):
        # type: (str) -> bytes
        '''
        Generate a string representing the Rock Ridge POSIX File Attributes
        record.

        Parameters:
         rr_version - The Rock Ridge version to use.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PX record not initialized')

        outlist = [b'PX', struct.pack(self.FMT, RRPXRecord.length(rr_version),
                                      SU_ENTRY_VERSION, self.posix_file_mode,
                                      utils.swab_32bit(self.posix_file_mode),
                                      self.posix_file_links,
                                      utils.swab_32bit(self.posix_file_links),
                                      self.posix_user_id,
                                      utils.swab_32bit(self.posix_user_id),
                                      self.posix_group_id,
                                      utils.swab_32bit(self.posix_group_id))]
        if rr_version == '1.12':
            outlist.append(struct.pack('<LL', self.posix_serial_number,
                                       utils.swab_32bit(self.posix_serial_number)))
        # The rr_version can never be "wrong" at this point; if it was, it would
        # have thrown an exception earlier when calling length().  So just skip
        # any potential checks here.

        return b''.join(outlist)

    @staticmethod
    def length(rr_version):
        # type: (str) -> int
        '''
        Static method to return the length of the Rock Ridge POSIX File
        Attributes record.

        Parameters:
         rr_version - The version of Rock Ridge in use; must be '1.09', '1.10',
                      or '1.12'.
        Returns:
         The length of this record in bytes.
        '''
        if rr_version in ('1.09', '1.10'):
            return 36
        if rr_version == '1.12':
            return 44

        # This should never happen
        raise pycdlibexception.PyCdlibInternalError('Invalid rr_version')


class RRERRecord(object):
    '''
    A class that represents a Rock Ridge Extensions Reference record.
    '''
    __slots__ = ('_initialized', 'ext_id', 'ext_des', 'ext_src', 'ext_ver')

    FMT = '=BBBBBB'

    def __init__(self):
        # type: () -> None
        self.ext_id = b''
        self.ext_des = b''
        self.ext_src = b''
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Extensions Reference record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('ER record already initialized')

        (su_len, su_entry_version_unused, len_id, len_des, len_src,
         self.ext_ver) = struct.unpack_from(self.FMT, rrstr[:8], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        # Ensure that the length isn't crazy
        if su_len > len(rrstr):
            raise pycdlibexception.PyCdlibInvalidISO('Length of ER record much too long')

        # Also ensure that the combination of len_id, len_des, and len_src
        # doesn't overrun su_len; because of the check above, this means it
        # can't overrun len(rrstr) either
        total_length = len_id + len_des + len_src
        if total_length > su_len:
            raise pycdlibexception.PyCdlibInvalidISO('Combined length of ER ID, des, and src longer than record')

        fmtstr = '=%ds%ds%ds' % (len_id, len_des, len_src)
        (self.ext_id, self.ext_des,
         self.ext_src) = struct.unpack_from(fmtstr, rrstr, 8)

        self._initialized = True

    def new(self, ext_id, ext_des, ext_src):
        # type: (bytes, bytes, bytes) -> None
        '''
        Create a new Rock Ridge Extensions Reference record.

        Parameters:
         ext_id - The extension identifier to use.
         ext_des - The extension descriptor to use.
         ext_src - The extension specification source to use.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('ER record already initialized')

        self.ext_id = ext_id
        self.ext_des = ext_des
        self.ext_src = ext_src
        self.ext_ver = 1

        self._initialized = True

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Extensions Reference
        record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('ER record not initialized')

        return b'ER' + struct.pack(self.FMT,
                                   RRERRecord.length(self.ext_id, self.ext_des, self.ext_src),
                                   SU_ENTRY_VERSION,
                                   len(self.ext_id),
                                   len(self.ext_des),
                                   len(self.ext_src),
                                   self.ext_ver) + self.ext_id + self.ext_des + self.ext_src

    @staticmethod
    def length(ext_id, ext_des, ext_src):
        # type: (bytes, bytes, bytes) -> int
        '''
        Static method to return the length of the Rock Ridge Extensions Reference
        record.

        Parameters:
         ext_id - The extension identifier to use.
         ext_des - The extension descriptor to use.
         ext_src - The extension specification source to use.
        Returns:
         The length of this record in bytes.
        '''
        return 8 + len(ext_id) + len(ext_des) + len(ext_src)


class RRESRecord(object):
    '''
    A class that represents a Rock Ridge Extension Selector record.
    '''
    __slots__ = ('_initialized', 'extension_sequence')

    FMT = '=BBB'

    def __init__(self):
        # type: () -> None
        self.extension_sequence = 0
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Extension Selector record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('ES record already initialized')

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        (su_len, su_entry_version_unused,
         self.extension_sequence) = struct.unpack_from(self.FMT, rrstr[:5], 2)
        if su_len != RRESRecord.length():
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on rock ridge extension')

        self._initialized = True

    def new(self, extension_sequence):
        # type: (int) -> None
        '''
        Create a new Rock Ridge Extension Selector record.

        Parameters:
         extension_sequence - The sequence number of this extension.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('ES record already initialized')

        self.extension_sequence = extension_sequence
        self._initialized = True

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Extension Selector record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('ES record not initialized')

        return b'ES' + struct.pack(self.FMT,
                                   RRESRecord.length(),
                                   SU_ENTRY_VERSION,
                                   self.extension_sequence)

    @staticmethod
    def length():
        # type: () -> int
        '''
        Static method to return the length of the Rock Ridge Extensions Selector
        record.

        Parameters:
         None.
        Returns:
         The length of this record in bytes.
        '''
        return 5


class RRPNRecord(object):
    '''
    A class that represents a Rock Ridge POSIX Device Number record.  This
    record represents a device major and minor special file.
    '''
    __slots__ = ('_initialized', 'dev_t_high', 'dev_t_low')

    FMT = '<BBLLLL'

    def __init__(self):
        # type: () -> None
        self.dev_t_high = 0
        self.dev_t_low = 0
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge POSIX Device Number record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PN record already initialized')

        (su_len, su_entry_version_unused, dev_t_high_le, dev_t_high_be,
         dev_t_low_le, dev_t_low_be) = struct.unpack_from(self.FMT, rrstr[:20], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        if su_len != RRPNRecord.length():
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on rock ridge extension')

        if dev_t_high_le != utils.swab_32bit(dev_t_high_be):
            raise pycdlibexception.PyCdlibInvalidISO('Dev_t high little-endian does not match big-endian')

        if dev_t_low_le != utils.swab_32bit(dev_t_low_be):
            raise pycdlibexception.PyCdlibInvalidISO('Dev_t low little-endian does not match big-endian')

        self.dev_t_high = dev_t_high_le
        self.dev_t_low = dev_t_low_le

        self._initialized = True

    def new(self, dev_t_high, dev_t_low):
        # type: (int, int) -> None
        '''
        Create a new Rock Ridge POSIX device number record.

        Parameters:
         dev_t_high - The high-order 32-bits of the device number.
         dev_t_low - The low-order 32-bits of the device number.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PN record already initialized')

        self.dev_t_high = dev_t_high
        self.dev_t_low = dev_t_low

        self._initialized = True

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge POSIX Device Number
        record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PN record not initialized')

        return b'PN' + struct.pack(self.FMT,
                                   RRPNRecord.length(),
                                   SU_ENTRY_VERSION,
                                   self.dev_t_high,
                                   utils.swab_32bit(self.dev_t_high),
                                   self.dev_t_low,
                                   utils.swab_32bit(self.dev_t_low))

    @staticmethod
    def length():
        # type: () -> int
        '''
        Static method to return the length of the Rock Ridge POSIX Device Number
        record.

        Parameters:
         None.
        Returns:
         The length of this record in bytes.
        '''
        return 20


class RRSLRecord(object):
    '''
    A class that represents a Rock Ridge Symbolic Link record.  This record
    represents some or all of a symbolic link.  For a symbolic link, Rock Ridge
    specifies that each component (part of path separated by /) be in a separate
    component entry, and individual components may be split across multiple
    Symbolic Link records.  This class takes care of all of those details.
    '''
    __slots__ = ('_initialized', 'symlink_components', 'flags')

    class Component(object):
        '''
        A class that represents one component of a Symbolic Link Record.
        '''
        __slots__ = ('flags', 'curr_length', 'data')

        def __init__(self, flags, length, data):
            # type: (int, int, bytes) -> None
            if flags not in (0, 1, 2, 4, 8):
                raise pycdlibexception.PyCdlibInternalError('Invalid Rock Ridge symlink flags 0x%x' % (flags))

            if (flags & (1 << 1) or flags & (1 << 2) or flags & (1 << 3)) and length != 0:
                raise pycdlibexception.PyCdlibInternalError('Rock Ridge symlinks to dot, dotdot, or root should have zero length')

            # A Component can't both be a continuation and one of dot, dotdot,
            # or root, but this case is caught by the initial flags check so we
            # don't check for it again here.

            self.flags = flags
            self.curr_length = length
            self.data = data

        def name(self):
            # type: () -> bytes
            '''
            Retrieve the human-readable name of this component.

            Parameters:
             None.
            Returns:
             Human readable name of this component.
            '''
            if self.flags & (1 << 1):
                return b'.'
            if self.flags & (1 << 2):
                return b'..'
            if self.flags & (1 << 3):
                return b'/'

            return self.data

        def is_continued(self):
            # type: () -> bool
            '''
            Determine whether this component is continued in the next component.

            Parameters:
             None.
            Returns:
             True if this component is continued in the next component, False otherwise.
            '''
            return self.flags & (1 << 0) != 0

        def record(self):
            # type: () -> bytes
            '''
            Return the representation of this component that is suitable for
            writing to disk.

            Parameters:
             None.
            Returns:
             Representation of this compnent suitable for writing to disk.
            '''
            if self.flags & (1 << 1):
                return struct.pack('=BB', (1 << 1), 0)
            if self.flags & (1 << 2):
                return struct.pack('=BB', (1 << 2), 0)
            if self.flags & (1 << 3):
                return struct.pack('=BB', (1 << 3), 0)

            return struct.pack('=BB', self.flags, self.curr_length) + self.data

        def set_continued(self):
            # type: () -> None
            '''
            Set the continued flag on this component.

            Parameters:
             None.
            Returns:
             Nothing.
            '''
            self.flags |= (1 << 0)

        def __eq__(self, other):
            # type: (object) -> bool
            if not isinstance(other, RRSLRecord.Component):
                return NotImplemented
            return self.flags == other.flags and self.curr_length == other.curr_length and self.data == other.data

        def __ne__(self, other):
            # type: (object) -> bool
            return not self.__eq__(other)

        @staticmethod
        def length(symlink_component):
            # type: (bytes) -> int
            '''
            Static method to compute the length of one symlink component.

            Parameters:
             symlink_component - String representing one symlink component.
            Returns:
             Length of symlink component plus overhead.
            '''
            length = 2
            if symlink_component not in (b'.', b'..', b'/'):
                length += len(symlink_component)

            return length

        @staticmethod
        def factory(name):
            # type: (bytes) -> RRSLRecord.Component
            '''
            A static method to create a new, valid Component given a human
            readable name.

            Parameters:
             name - The name to create the Component from.
            Returns:
             A new Component object representing this name.
            '''
            if name == b'.':
                flags = (1 << 1)
                length = 0
            elif name == b'..':
                flags = (1 << 2)
                length = 0
            elif name == b'/':
                flags = (1 << 3)
                length = 0
            else:
                flags = 0
                length = len(name)

            # Theoretically, this factory method could be passed a name
            # that wouldn't fit into either this SL record or into a single
            # component.  However, the only caller of this factory method
            # (add_component(), below) already checks to make sure this
            # name would fit into the SL record, and the job of making sure
            # everything fits into an SL record really belongs there.
            # Further, we recognize that an SL record and a component
            # record both use an 8-bit quantity for the length, so there is
            # never a time when something would fit into the SL record but
            # would not fit into a component.  Thus, we elide any length
            # checks here.
            return RRSLRecord.Component(flags, length, name)

    def __init__(self):
        # type: () -> None
        self.symlink_components = []  # type: List[RRSLRecord.Component]
        self.flags = 0
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Symbolic Link record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SL record already initialized')

        (su_len, su_entry_version_unused,
         self.flags) = struct.unpack_from('=BBB', rrstr[:5], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        cr_offset = 5
        data_len = su_len - 5
        while data_len > 0:
            (cr_flags, len_cp) = struct.unpack_from('=BB',
                                                    rrstr[:cr_offset + 2],
                                                    cr_offset)

            data_len -= 2
            cr_offset += 2

            self.symlink_components.append(self.Component(cr_flags, len_cp,
                                                          rrstr[cr_offset:cr_offset + len_cp]))

            # FIXME: if this is the last component in this SL record,
            # but the component continues on in the next SL record, we will
            # fail to record this bit.  We should fix that.

            cr_offset += len_cp
            data_len -= len_cp

        self._initialized = True

    def new(self):
        # type: () -> None
        '''
        Create a new Rock Ridge Symbolic Link record.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SL record already initialized')

        self._initialized = True

    def add_component(self, symlink_comp):
        # type: (bytes) -> None
        '''
        Add a new component to this symlink record.

        Parameters:
         symlink_comp - The string to add to this symlink record.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SL record not initialized')

        if (self.current_length() + RRSLRecord.Component.length(symlink_comp)) > 255:
            raise pycdlibexception.PyCdlibInvalidInput('Symlink would be longer than 255')

        self.symlink_components.append(self.Component.factory(symlink_comp))

    def current_length(self):
        # type: () -> int
        '''
        Calculate the current length of this symlink record.

        Parameters:
         None.
        Returns:
         Length of this symlink record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SL record not initialized')

        strlist = []
        for comp in self.symlink_components:
            strlist.append(comp.name())

        return RRSLRecord.length(strlist)

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Symbolic Link record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SL record not initialized')

        outlist = [b'SL', struct.pack('=BBB',
                                      self.current_length(),
                                      SU_ENTRY_VERSION,
                                      self.flags)]
        for comp in self.symlink_components:
            outlist.append(comp.record())

        return b''.join(outlist)

    def name(self):
        # type: () -> bytes
        '''
        Generate a string that contains all components of the symlink.

        Parameters:
         None
        Returns:
         String containing all components of the symlink.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SL record not initialized')

        outlist = []  # type: List[bytes]
        continued = False
        for comp in self.symlink_components:
            name = comp.name()
            if name == b'/':
                outlist = []
                continued = False
                name = b''

            if not continued:
                outlist.append(name)
            else:
                outlist[-1] += name

            continued = comp.is_continued()

        return b'/'.join(outlist)

    def set_continued(self):
        # type: () -> None
        '''
        Set this SL record as continued in the next System Use Entry.

        Parameters:
         None
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SL record not initialized')

        self.flags |= (1 << 0)

    def set_last_component_continued(self):
        # type: () -> None
        '''
        Set the previous component of this SL record to continued.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SL record not initialized')

        if not self.symlink_components:
            raise pycdlibexception.PyCdlibInternalError('Trying to set continued on a non-existent component!')

        self.symlink_components[-1].set_continued()

    def last_component_continued(self):
        # type: () -> bool
        '''
        Determines whether the previous component of this SL record is a
        continued one or not.

        Parameters:
         None.
        Returns:
         True if the previous component of this SL record is continued, False
         otherwise.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SL record not initialized')

        if not self.symlink_components:
            raise pycdlibexception.PyCdlibInternalError('Trying to get continued on a non-existent component!')

        return self.symlink_components[-1].is_continued()

    @staticmethod
    def header_length():
        # type: () -> int
        '''
        Static method to return the length of a Rock Ridge Symbolic Link
        header.

        Parameters:
         None
        Returns:
         The length of the RRSLRecord header.
        '''
        return 5

    @staticmethod
    def maximum_component_area_length():
        # type: () -> int
        '''
        Static method to return the absolute maximum length a Rock Ridge
        Symbolic Link component area can be.

        Parameters:
         None
        Returns:
         The maximum length a Symbolic Link component area can be.
        '''
        return 255 - RRSLRecord.header_length()

    @staticmethod
    def length(symlink_components):
        # type: (List[bytes]) -> int
        '''
        Static method to return the length of the Rock Ridge Symbolic Link
        record.

        Parameters:
         symlink_components - A list containing a string for each of the
                              symbolic link components.
        Returns:
         The length of this record in bytes.
        '''
        length = RRSLRecord.header_length()
        for comp in symlink_components:
            length += RRSLRecord.Component.length(comp)
        return length


class RRALRecord(object):
    '''
    A class that represents an Arbitrary Attribute Interchange Protocol record.
    This is an unoffical extension by libisofs: https://dev.lovelyhq.com/libburnia/libisofs/src/commit/d297ce3aed5935e469bb108a36b7d6e31763a075/doc/susp_aaip_2_0.txt
    The goal of this record is to allow arbitrary attributes with arbitrary
    name/value pairs in the SUSP record.  It is split up much like an SL record,
    so a lot of the code is copied from that class.
    '''
    __slots__ = ('_initialized', 'flags', 'components')

    class Component(object):
        '''
        A class that represents one component of an Arbitrary Attribute.
        '''
        __slots__ = ('flags', 'curr_length', 'data')

        def __init__(self, flags, length, data):
            # type: (int, int, bytes) -> None
            if flags not in (0, 1):
                raise pycdlibexception.PyCdlibInternalError('Invalid Arbitrary Attribute flags 0x%x' % (flags))

            self.flags = flags
            self.curr_length = length
            self.data = data

        def record(self):
            # type: () -> bytes
            '''
            Return the representation of this component that is suitable for
            writing to disk.

            Parameters:
             None.
            Returns:
             Representation of this compnent suitable for writing to disk.
            '''
            return struct.pack('=BB', self.flags, self.curr_length) + self.data

        def set_continued(self):
            # type: () -> None
            '''
            Set the continued flag on this component.

            Parameters:
             None.
            Returns:
             Nothing.
            '''
            self.flags |= (1 << 0)

        @staticmethod
        def length(attr):
            # type: (bytes) -> int
            '''
            Method to compute the length of a component.

            Parameters:
             None.
            Returns:
             Length of this component plus overhead.
            '''
            return 2 + len(attr)

        @staticmethod
        def factory(component):
            # type: (bytes) -> RRALRecord.Component
            '''
            A static method to create a new, valid Component given an attribute.

            Parameters:
             component - The string to create the Component from.
            Returns:
             A new Component object representing this string.
            '''
            # Theoretically, this factory method could be passed a name
            # that wouldn't fit into either this AL record or into a single
            # component.  However, the only caller of this factory method
            # (add_component(), below) already checks to make sure this
            # name would fit into the AL record, and the job of making sure
            # everything fits into an AL record really belongs there.
            # Further, we recognize that an AL record and a component
            # record both use an 8-bit quantity for the length, so there is
            # never a time when something would fit into the AL record but
            # would not fit into a component.  Thus, we elide any length
            # checks here.
            return RRALRecord.Component(0, len(component), component)

    def __init__(self):
        # type: () -> None
        self.flags = 0
        self.components = []  # type: List[RRALRecord.Component]
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse an Arbitrary Attribute record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('AL record already initialized')

        (su_len, su_entry_version_unused,
         self.flags) = struct.unpack_from('=BBB', rrstr[:5], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        cr_offset = 5
        data_len = su_len - 5
        while data_len > 0:
            (cr_flags, len_cp) = struct.unpack_from('=BB',
                                                    rrstr[:cr_offset + 2],
                                                    cr_offset)

            data_len -= 2
            cr_offset += 2

            self.components.append(self.Component(cr_flags, len_cp,
                                                  rrstr[cr_offset:cr_offset + len_cp]))

            # FIXME: if this is the last component in this AL record,
            # but the component continues on in the next AL record, we will
            # fail to record this bit.  We should fix that.

            cr_offset += len_cp
            data_len -= len_cp

        self._initialized = True

    def current_length(self):
        # type: () -> int
        '''
        Calculate the current length of this Arbitrary Attribute record.

        Parameters:
         None.
        Returns:
         Length of this Arbitrary Attribute record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('AL record not initialized')

        strlist = []
        for comp in self.components:
            strlist.append(comp.data)

        return RRALRecord.length(strlist)

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Arbitrary Attribute record.

        Parameters:
         None.
        Returns:
         String containing the Arbitrary Attribute record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('AL record not initialized')

        outlist = [b'AL', struct.pack('=BBB',
                                      self.current_length(),
                                      SU_ENTRY_VERSION,
                                      self.flags)]
        for comp in self.components:
            outlist.append(comp.record())

        return b''.join(outlist)

    def new(self):
        # type: () -> None
        '''
        Create a new Arbitrary Attribute record.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('AL record already initialized')

        self._initialized = True

    def set_continued(self):
        # type: () -> None
        '''
        Set this AL record as continued in the next System Use Entry.

        Parameters:
         None
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('AL record not initialized')

        self.flags |= (1 << 0)

    def set_last_component_continued(self):
        # type: () -> None
        '''
        Set the previous component of this AL record to continued.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('AL record not initialized')

        if not self.components:
            raise pycdlibexception.PyCdlibInternalError('Trying to set continued on a non-existent component!')

        self.components[-1].set_continued()

    def add_component(self, comp):
        # type: (bytes) -> None
        '''
        Add a new component to this Arbitrary Attribute record.

        Parameters:
         comp - The string to add to this Arbitrary Attribute record.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('AL record not initialized')

        if (self.current_length() + RRALRecord.Component.length(comp)) > 255:
            raise pycdlibexception.PyCdlibInvalidInput('Attribute would be longer than 255')

        self.components.append(self.Component.factory(comp))

    @staticmethod
    def header_length():
        # type: () -> int
        '''
        Static method to return the length of an Arbitrary Attribute header.

        Parameters:
         None
        Returns:
         The length of the RRALRecord header.
        '''
        return 5

    @staticmethod
    def maximum_component_area_length():
        # type: () -> int
        '''
        Static method to return the absolute maximum length an Arbitrary
        Attribute component area can be.

        Parameters:
         None
        Returns:
         The maximum length an Arbitrary Attribute component area can be.
        '''
        return 255 - RRALRecord.header_length()

    @staticmethod
    def length(attrs):
        # type: (List[bytes]) -> int
        '''
        Static method to return the length of a list of attributes.

        Parameters:
         attrs - A list of attributes.
        Returns:
         The length of the entire record in bytes.
        '''
        length = RRALRecord.header_length()
        for attr in attrs:
            length += RRALRecord.Component.length(attr)
        return length


class RRNMRecord(object):
    '''
    A class that represents a Rock Ridge Alternate Name record.
    '''
    __slots__ = ('_initialized', 'posix_name_flags', 'posix_name')

    FMT = '=BBB'

    def __init__(self):
        # type: () -> None
        self._initialized = False
        self.posix_name_flags = 0
        self.posix_name = b''

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Alternate Name record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('NM record already initialized')

        (su_len, su_entry_version_unused,
         self.posix_name_flags) = struct.unpack_from(self.FMT, rrstr[:5], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        name_len = su_len - 5
        if (self.posix_name_flags & 0x7) not in (0, 1, 2, 4):
            raise pycdlibexception.PyCdlibInvalidISO('Invalid Rock Ridge NM flags')

        if name_len != 0:
            if (self.posix_name_flags & (1 << 1)) or (self.posix_name_flags & (1 << 2)) or (self.posix_name_flags & (1 << 5)):
                raise pycdlibexception.PyCdlibInvalidISO('Invalid name in Rock Ridge NM entry (0x%x %d)' % (self.posix_name_flags, name_len))
            self.posix_name += rrstr[5:5 + name_len]

        self._initialized = True

    def new(self, rr_name):
        # type: (bytes) -> None
        '''
        Create a new Rock Ridge Alternate Name record.

        Parameters:
         rr_name - The name for the new record.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('NM record already initialized')

        self.posix_name = rr_name
        self.posix_name_flags = 0

        self._initialized = True

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Alternate Name record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('NM record not initialized')

        return b'NM' + struct.pack(self.FMT,
                                   RRNMRecord.length(self.posix_name),
                                   SU_ENTRY_VERSION,
                                   self.posix_name_flags) + self.posix_name

    def set_continued(self):
        # type: () -> None
        '''
        Mark this alternate name record as continued.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('NM record not initialized')

        self.posix_name_flags |= (1 << 0)

    @staticmethod
    def length(rr_name):
        # type: (bytes) -> int
        '''
        Static method to return the length of the Rock Ridge Alternate Name
        record.

        Parameters:
         rr_name - The name to use.
        Returns:
         The length of this record in bytes.
        '''
        return 5 + len(rr_name)


class RRCLRecord(object):
    '''
    A class that represents a Rock Ridge Child Link record.  This record
    represents the logical block where a deeply nested directory was relocated
    to.
    '''
    __slots__ = ('_initialized', 'child_log_block_num')

    FMT = '<BBLL'

    def __init__(self):
        # type: () -> None
        self.child_log_block_num = 0
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Child Link record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('CL record already initialized')

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        (su_len, su_entry_version_unused,
         child_log_block_num_le, child_log_block_num_be) = struct.unpack_from(self.FMT, rrstr[:12], 2)
        if su_len != RRCLRecord.length():
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on rock ridge extension')

        if child_log_block_num_le != utils.swab_32bit(child_log_block_num_be):
            raise pycdlibexception.PyCdlibInvalidISO('Little endian block num does not equal big endian; corrupt ISO')
        self.child_log_block_num = child_log_block_num_le

        self._initialized = True

    def new(self):
        # type: () -> None
        '''
        Create a new Rock Ridge Child Link record.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('CL record already initialized')

        self.child_log_block_num = 0  # This gets set later

        self._initialized = True

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Child Link record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('CL record not initialized')

        return b'CL' + struct.pack(self.FMT,
                                   RRCLRecord.length(),
                                   SU_ENTRY_VERSION,
                                   self.child_log_block_num,
                                   utils.swab_32bit(self.child_log_block_num))

    def set_log_block_num(self, bl):
        # type: (int) -> None
        '''
        Set the logical block number for the child.

        Parameters:
         bl - Logical block number of the child.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('CL record not initialized')

        self.child_log_block_num = bl

    @staticmethod
    def length():
        # type: () -> int
        '''
        Static method to return the length of the Rock Ridge Child Link
        record.

        Parameters:
         None.
        Returns:
         The length of this record in bytes.
        '''
        return 12


class RRPLRecord(object):
    '''
    A class that represents a Rock Ridge Parent Link record.  This record
    represents the logical block where a deeply nested directory was located
    from.
    '''
    __slots__ = ('_initialized', 'parent_log_block_num')

    FMT = '<BBLL'

    def __init__(self):
        # type: () -> None
        self.parent_log_block_num = 0
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Parent Link record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PL record already initialized')

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        (su_len, su_entry_version_unused,
         parent_log_block_num_le, parent_log_block_num_be) = struct.unpack_from(self.FMT, rrstr[:12], 2)
        if su_len != RRPLRecord.length():
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on rock ridge extension')
        if parent_log_block_num_le != utils.swab_32bit(parent_log_block_num_be):
            raise pycdlibexception.PyCdlibInvalidISO('Little endian block num does not equal big endian; corrupt ISO')
        self.parent_log_block_num = parent_log_block_num_le

        self._initialized = True

    def new(self):
        # type: () -> None
        '''
        Generate a string representing the Rock Ridge Parent Link record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PL record already initialized')

        self.parent_log_block_num = 0  # This will get set later

        self._initialized = True

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Child Link record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PL record not initialized')

        return b'PL' + struct.pack(self.FMT,
                                   RRPLRecord.length(),
                                   SU_ENTRY_VERSION,
                                   self.parent_log_block_num,
                                   utils.swab_32bit(self.parent_log_block_num))

    def set_log_block_num(self, bl):
        # type: (int) -> None
        '''
        Set the logical block number for the parent.

        Parameters:
         bl - Logical block number of the parent.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PL record not initialized')

        self.parent_log_block_num = bl

    @staticmethod
    def length():
        # type: () -> int
        '''
        Static method to return the length of the Rock Ridge Parent Link
        record.

        Parameters:
         None.
        Returns:
         The length of this record in bytes.
        '''
        return 12


class RRTFRecord(object):
    '''
    A class that represents a Rock Ridge Time Stamp record.  This record
    represents the creation timestamp, the access time timestamp, the
    modification time timestamp, the attribute change time timestamp, the
    backup time timestamp, the expiration time timestamp, and the effective time
    timestamp.  Each of the timestamps can be selectively enabled or disabled.
    Additionally, the timestamps can be configured to be Directory Record
    style timestamps (7 bytes) or Volume Descriptor style timestamps (17 bytes).
    '''
    __slots__ = ('_initialized', 'creation_time', 'access_time',
                 'modification_time', 'attribute_change_time', 'backup_time',
                 'expiration_time', 'effective_time', 'time_flags')

    FIELDNAMES = ('creation_time', 'access_time', 'modification_time',
                  'attribute_change_time', 'backup_time', 'expiration_time',
                  'effective_time')

    def __init__(self):
        # type: () -> None
        for fieldname in self.FIELDNAMES:
            setattr(self, fieldname, None)

        self.time_flags = 0
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Time Stamp record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('TF record already initialized')

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        (su_len, su_entry_version_unused,
         self.time_flags) = struct.unpack_from('=BBB', rrstr[:5], 2)
        if su_len < 5:
            raise pycdlibexception.PyCdlibInvalidISO('Not enough bytes in the TF record')

        tflen = 7
        if self.time_flags & (1 << 7):
            tflen = 17

        offset = 5
        for index, fieldname in enumerate(self.FIELDNAMES):
            if self.time_flags & (1 << index):
                if tflen == 7:
                    setattr(self, fieldname, dates.DirectoryRecordDate())
                elif tflen == 17:
                    setattr(self, fieldname, dates.VolumeDescriptorDate())
                getattr(self, fieldname).parse(rrstr[offset:offset + tflen])
                offset += tflen

        self._initialized = True

    def new(self, time_flags):
        # type: (int) -> None
        '''
        Create a new Rock Ridge Time Stamp record.

        Parameters:
         time_flags - The flags to use for this time stamp record.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('TF record already initialized')

        self.time_flags = time_flags

        tflen = 7
        if self.time_flags & (1 << 7):
            tflen = 17

        for index, fieldname in enumerate(self.FIELDNAMES):
            if self.time_flags & (1 << index):
                if tflen == 7:
                    setattr(self, fieldname, dates.DirectoryRecordDate())
                elif tflen == 17:
                    setattr(self, fieldname, dates.VolumeDescriptorDate())
                getattr(self, fieldname).new()

        self._initialized = True

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Time Stamp record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('TF record not initialized')

        outlist = [b'TF', struct.pack('=BBB',
                                      RRTFRecord.length(self.time_flags),
                                      SU_ENTRY_VERSION,
                                      self.time_flags)]
        for fieldname in self.FIELDNAMES:
            field = getattr(self, fieldname)
            if field is not None:
                outlist.append(field.record())

        return b''.join(outlist)

    @staticmethod
    def length(time_flags):
        # type: (int) -> int
        '''
        Static method to return the length of the Rock Ridge Time Stamp
        record.

        Parameters:
         time_flags - Integer representing the flags to use.
        Returns:
         The length of this record in bytes.
        '''
        tf_each_size = 7
        if time_flags & (1 << 7):
            tf_each_size = 17
        time_flags &= 0x7f
        tf_num = 0
        while time_flags:
            time_flags &= time_flags - 1
            tf_num += 1

        return 5 + tf_each_size * tf_num


class RRSFRecord(object):
    '''
    A class that represents a Rock Ridge Sparse File record.  This record
    represents the full file size of a sparsely-populated file.
    '''
    __slots__ = ('_initialized', 'virtual_file_size_high',
                 'virtual_file_size_low', 'table_depth')

    def __init__(self):
        # type: () -> None
        self.table_depth = None  # type: Optional[int]
        self.virtual_file_size_low = 0
        self.virtual_file_size_high = None  # type: Optional[int]
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Sparse File record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SF record already initialized')

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        (su_len,
         su_entry_version_unused) = struct.unpack_from('=BB', rrstr[:4], 2)

        if su_len == 12:
            # This is a Rock Ridge version 1.10 SF Record, which is 12 bytes.
            (virtual_file_size_le, virtual_file_size_be) = struct.unpack_from('<LL', rrstr[:12], 4)
            if virtual_file_size_le != utils.swab_32bit(virtual_file_size_be):
                raise pycdlibexception.PyCdlibInvalidISO('Virtual file size little-endian does not match big-endian')
            self.virtual_file_size_low = virtual_file_size_le
        elif su_len == 21:
            # This is a Rock Ridge version 1.12 SF Record, which is 21 bytes.
            (virtual_file_size_high_le, virtual_file_size_high_be, virtual_file_size_low_le,
             virtual_file_size_low_be, self.table_depth) = struct.unpack_from('<LLLLB', rrstr[:21], 4)
            if virtual_file_size_high_le != utils.swab_32bit(virtual_file_size_high_be):
                raise pycdlibexception.PyCdlibInvalidISO('Virtual file size high little-endian does not match big-endian')

            if virtual_file_size_low_le != utils.swab_32bit(virtual_file_size_low_be):
                raise pycdlibexception.PyCdlibInvalidISO('Virtual file size low little-endian does not match big-endian')
            self.virtual_file_size_low = virtual_file_size_low_le
            self.virtual_file_size_high = virtual_file_size_high_le
        else:
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on Rock Ridge SF record (expected 12 or 21)')

        self._initialized = True

    def new(self, file_size_high, file_size_low, table_depth):
        # type: (Optional[int], int, Optional[int]) -> None
        '''
        Create a new Rock Ridge Sparse File record.

        Parameters:
         file_size_high - The high-order 32-bits of the file size.
         file_size_low - The low-order 32-bits of the file size.
         table_depth - The maximum virtual file size.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SF record already initialized')

        self.virtual_file_size_high = file_size_high
        self.virtual_file_size_low = file_size_low
        self.table_depth = table_depth

        self._initialized = True

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Sparse File record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SF record not initialized')

        length = 12
        if self.virtual_file_size_high is not None:
            length = 21
        ret = b'SF' + struct.pack('=BB', length, SU_ENTRY_VERSION)
        if self.virtual_file_size_high is not None and self.table_depth is not None:
            ret += struct.pack('<LLLLB',
                               self.virtual_file_size_high,
                               utils.swab_32bit(self.virtual_file_size_high),
                               self.virtual_file_size_low,
                               utils.swab_32bit(self.virtual_file_size_low),
                               self.table_depth)
        else:
            ret += struct.pack('<LL',
                               self.virtual_file_size_low,
                               utils.swab_32bit(self.virtual_file_size_low))

        return ret

    @staticmethod
    def length(rr_version):
        # type: (str) -> int
        '''
        Static method to return the length of the Rock Ridge Sparse File
        record.

        Parameters:
         rr_version - The version of Rock Ridge in use; must be '1.10' or '1.12'.
        Returns:
         The length of this record in bytes.
        '''
        if rr_version == '1.10':
            return 12
        if rr_version == '1.12':
            return 21

        # This should never happen
        raise pycdlibexception.PyCdlibInternalError('Invalid rr_version')


class RRRERecord(object):
    '''
    A class that represents a Rock Ridge Relocated Directory record.  This
    record is used to mark an entry as having been relocated because it was
    deeply nested.
    '''
    __slots__ = ('_initialized',)

    FMT = '=BB'

    def __init__(self):
        # type: () -> None
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Relocated Directory record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('RE record already initialized')

        (su_len,
         su_entry_version_unused) = struct.unpack_from(self.FMT, rrstr[:4], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        if su_len != 4:
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on rock ridge extension')

        self._initialized = True

    def new(self):
        # type: () -> None
        '''
        Create a new Rock Ridge Relocated Directory record.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('RE record already initialized')

        self._initialized = True

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Relocated Directory
        record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('RE record not initialized')

        return b'RE' + struct.pack(self.FMT,
                                   RRRERecord.length(),
                                   SU_ENTRY_VERSION)

    @staticmethod
    def length():
        # type: () -> int
        '''
        Static method to return the length of the Rock Ridge Relocated Directory
        record.

        Parameters:
         None.
        Returns:
         The length of this record in bytes.
        '''
        return 4


class RRSTRecord(object):
    '''
    A class that represents a Rock Ridge System Terminator record.  This
    record is used to terminate the SUSP/Rock Ridge records in a Directory
    Entry.
    '''
    __slots__ = ('_initialized',)

    FMT = '=BB'

    def __init__(self):
        # type: () -> None
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge System Terminator record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('ST record already initialized')

        (su_len,
         su_entry_version_unused) = struct.unpack_from(self.FMT, rrstr[:4], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        if su_len != 4:
            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on rock ridge extension')

        self._initialized = True

    def new(self):
        # type: () -> None
        '''
        Create a new Rock Ridge System Terminator record.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('ST record already initialized')

        self._initialized = True

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge System Terminator
        record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('ST record not initialized')

        return b'ST' + struct.pack(self.FMT,
                                   RRSTRecord.length(),
                                   SU_ENTRY_VERSION)

    @staticmethod
    def length():
        # type: () -> int
        '''
        Static method to return the length of the Rock Ridge System Terminator
        record.

        Parameters:
         None.
        Returns:
         The length of this record in bytes.
        '''
        return 4


class RRPDRecord(object):
    '''
    A class that represents a Rock Ridge Platform Dependent record.  This
    record is used to add platform-specific information to a Directory
    Entry, and may also be used as a terminator for Rock Ridge entries.
    '''
    __slots__ = ('_initialized', 'padding')

    FMT = '=BB'

    def __init__(self):
        # type: () -> None
        self._initialized = False

    def parse(self, rrstr):
        # type: (bytes) -> None
        '''
        Parse a Rock Ridge Platform Dependent record out of a string.

        Parameters:
         rrstr - The string to parse the record out of.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PD record already initialized')

        (su_len_unused,
         su_entry_version_unused) = struct.unpack_from(self.FMT, rrstr[:4], 2)

        self.padding = rrstr[4:]

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        self._initialized = True

    def new(self):
        # type: () -> None
        '''
        Create a new Rock Ridge Platform Dependent record.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PD record already initialized')

        self._initialized = True
        self.padding = b''

    def record(self):
        # type: () -> bytes
        '''
        Generate a string representing the Rock Ridge Platform Dependent
        record.

        Parameters:
         None.
        Returns:
         String containing the Rock Ridge record.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('PD record not initialized')

        return b'PD' + struct.pack(self.FMT, RRPDRecord.length(self.padding),
                                   SU_ENTRY_VERSION) + self.padding

    @staticmethod
    def length(padding):
        # type: (bytes) -> int
        '''
        Static method to return the length of the Rock Ridge Platform Dependent
        record.

        Parameters:
         padding - The padding bytes that this record will use.
        Returns:
         The length of this record in bytes.
        '''
        return 4 + len(padding)


class RockRidgeEntries(object):
    '''
    A simple class container to hold a long list of possible Rock Ridge
    records.
    '''
    __slots__ = ('sp_record', 'rr_record', 'ce_record', 'px_record',
                 'er_record', 'es_records', 'pn_record', 'sl_records',
                 'nm_records', 'cl_record', 'pl_record', 'tf_record',
                 'sf_record', 're_record', 'st_record', 'pd_records',
                 'al_records')

    def __init__(self):
        # type: () -> None
        self.sp_record = None  # type: Optional[RRSPRecord]
        self.rr_record = None  # type: Optional[RRRRRecord]
        self.ce_record = None  # type: Optional[RRCERecord]
        self.px_record = None  # type: Optional[RRPXRecord]
        self.er_record = None  # type: Optional[RRERRecord]
        self.es_records = []  # type: List[RRESRecord]
        self.pn_record = None  # type: Optional[RRPNRecord]
        self.sl_records = []  # type: List[RRSLRecord]
        self.nm_records = []  # type: List[RRNMRecord]
        self.cl_record = None  # type: Optional[RRCLRecord]
        self.pl_record = None  # type: Optional[RRPLRecord]
        self.tf_record = None  # type: Optional[RRTFRecord]
        self.sf_record = None  # type: Optional[RRSFRecord]
        self.re_record = None  # type: Optional[RRRERecord]
        self.st_record = None  # type: Optional[RRSTRecord]
        self.pd_records = []  # type: List[RRPDRecord]
        self.al_records = []  # type: List[RRALRecord]


# This is the class that implements the Rock Ridge extensions for PyCdlib.  The
# Rock Ridge extensions are a set of extensions for embedding POSIX semantics
# on an ISO9660 filesystem.  Rock Ridge works by utilizing the 'System Use'
# area of the directory record to store additional metadata about files.  This
# includes things like POSIX users, groups, ctime, mtime, atime, etc., as well
# as the ability to have directory structures deeper than 8 and filenames longer
# than 8.3.  Rock Ridge depends on the System Use and Sharing Protocol (SUSP),
# which defines some standards on how to use the System Area.

class RockRidge(object):
    '''
    A class representing Rock Ridge entries.
    '''
    __slots__ = ('_initialized', 'dr_entries', 'ce_entries', 'cl_to_moved_dr',
                 'moved_to_cl_dr', 'parent_link', 'rr_version', 'ce_block',
                 'bytes_to_skip', '_full_name')

    def __init__(self):
        # type: () -> None
        self.dr_entries = RockRidgeEntries()
        self.ce_entries = RockRidgeEntries()
        self.cl_to_moved_dr = None  # type: Optional[dr.DirectoryRecord]
        self.moved_to_cl_dr = None  # type: Optional[dr.DirectoryRecord]
        self.parent_link = None  # type: Optional[dr.DirectoryRecord]
        self.rr_version = ''
        self.ce_block = None  # type: Optional[RockRidgeContinuationBlock]
        self._initialized = False

    def has_entry(self, name):
        # type: (str) -> bool
        '''
        An internal method to tell if we have already parsed an entry of the
        named type.

        Parameters:
         name - The name of the entry to check.
        Returns:
         True if we have already parsed an entry of the named type, False
         otherwise.
        '''
        return getattr(self.dr_entries, name) or getattr(self.ce_entries, name)

    def parse(self, record, is_first_dir_record_of_root, bytes_to_skip,
              continuation):
        # type: (bytes, bool, int, bool) -> None
        '''
        Method to parse a rock ridge record.

        Parameters:
         record - The record to parse.
         is_first_dir_record_of_root - Whether this is the first directory
                                       record of the root directory record;
                                       certain Rock Ridge entries are only
                                       valid there.
         bytes_to_skip - The number of bytes to skip at the beginning of the
                         record.
         continuation - Whether the new entries should go in the continuation
                        list or in the DR list.
        Returns:
         Nothing.
        '''
        # Note that we very explicitly do not check if self._initialized is True
        # here; this can be called multiple times in the case where there is
        # a continuation entry.

        if continuation:
            entry_list = self.ce_entries
        else:
            entry_list = self.dr_entries

        self.bytes_to_skip = bytes_to_skip
        offset = bytes_to_skip
        left = len(record)
        px_record_length = None
        has_es_record = False
        sf_record_length = None
        er_id = None
        while True:
            if left == 0:
                break
            if left == 1:
                # There may be a padding byte on the end.
                if bytes(bytearray([record[offset]])) != b'\x00':
                    raise pycdlibexception.PyCdlibInvalidISO('Invalid pad byte')
                break
            if left < 4:
                raise pycdlibexception.PyCdlibInvalidISO('Not enough bytes left in the System Use field')

            (rtype, su_len, su_entry_version) = struct.unpack_from('=2sBB', record[:offset + 4], offset)
            if su_entry_version != SU_ENTRY_VERSION:
                raise pycdlibexception.PyCdlibInvalidISO('Invalid RR version %d!' % su_entry_version)
            if su_len == 0:
                raise pycdlibexception.PyCdlibInvalidISO('Zero size for Rock Ridge entry length')

            recslice = record[offset:]

            if rtype in (b'SP', b'RR', b'CE', b'PX', b'ST', b'ER',
                         b'PN', b'CL', b'PL', b'RE', b'TF', b'SF'):
                recname = rtype.decode('utf-8').lower() + '_record'
                if self.has_entry(recname):
                    raise pycdlibexception.PyCdlibInvalidISO('Only single %s record supported' % (rtype.decode('utf-8')))

            if rtype == b'SP':
                if left < 7 or not is_first_dir_record_of_root:
                    raise pycdlibexception.PyCdlibInvalidISO('Invalid SUSP SP record')

                # OK, this is the first Directory Record of the root
                # directory, which means we should check it for the SUSP/RR
                # extension, which is exactly 7 bytes and starts with 'SP'.

                entry_list.sp_record = RRSPRecord()
                entry_list.sp_record.parse(recslice)
            elif rtype == b'RR':
                entry_list.rr_record = RRRRRecord()
                entry_list.rr_record.parse(recslice)
            elif rtype == b'CE':
                entry_list.ce_record = RRCERecord()
                entry_list.ce_record.parse(recslice)
            elif rtype == b'PX':
                entry_list.px_record = RRPXRecord()
                px_record_length = entry_list.px_record.parse(recslice)
            elif rtype == b'PD':
                pd = RRPDRecord()
                pd.parse(recslice)
                entry_list.pd_records.append(pd)
            elif rtype == b'ST':
                entry_list.st_record = RRSTRecord()
                entry_list.st_record.parse(recslice)
            elif rtype == b'ER':
                entry_list.er_record = RRERRecord()
                entry_list.er_record.parse(recslice)
                er_id = entry_list.er_record.ext_id
            elif rtype == b'ES':
                es = RRESRecord()
                es.parse(recslice)
                entry_list.es_records.append(es)
                has_es_record = True
            elif rtype == b'PN':
                entry_list.pn_record = RRPNRecord()
                entry_list.pn_record.parse(recslice)
            elif rtype == b'SL':
                new_sl_record = RRSLRecord()
                new_sl_record.parse(recslice)
                entry_list.sl_records.append(new_sl_record)
            elif rtype == b'NM':
                new_nm_record = RRNMRecord()
                new_nm_record.parse(recslice)
                entry_list.nm_records.append(new_nm_record)
            elif rtype == b'CL':
                entry_list.cl_record = RRCLRecord()
                entry_list.cl_record.parse(recslice)
            elif rtype == b'PL':
                entry_list.pl_record = RRPLRecord()
                entry_list.pl_record.parse(recslice)
            elif rtype == b'RE':
                entry_list.re_record = RRRERecord()
                entry_list.re_record.parse(recslice)
            elif rtype == b'TF':
                entry_list.tf_record = RRTFRecord()
                entry_list.tf_record.parse(recslice)
            elif rtype == b'SF':
                entry_list.sf_record = RRSFRecord()
                entry_list.sf_record.parse(recslice)
                sf_record_length = len(recslice)
            elif rtype == b'AL':
                new_al_record = RRALRecord()
                new_al_record.parse(recslice)
                entry_list.al_records.append(new_al_record)
            else:
                raise pycdlibexception.PyCdlibInvalidISO('Unknown SUSP record')
            offset += su_len
            left -= su_len

        # Now let's determine the version of Rock Ridge that we have (1.09,
        # 1.10, or 1.12).  Unfortunately, there is no direct information from
        # Rock Ridge, so we infer it from what is present.  In an ideal world,
        # the following table would tell us:
        #
        # | Feature/Rock Ridge version |      1.09     |      1.10     |      1.12     |
        # +----------------------------+---------------+---------------+---------------+
        # |    Has RR Record?          | True or False |     False     |     False     |
        # |    Has ES Record?          |     False     |     False     | True or False |
        # |    Has SF Record?          |     False     | True or False | True or False |
        # |    PX Record length        |      36       |      36       |      44       |
        # |    SF Record length        |     N/A       |      12       |      21       |
        # |    ER Desc string          |  RRIP_1991A   |  RRIP_1991A   |  IEEE_P1282   |
        # +----------------------------+---------------+---------------+---------------+
        #
        # While that is a good start, we don't live in an ideal world.  In
        # particular, we've seen ISOs in the wild (OpenSolaris 2008) that put an
        # RR record into an otherwise 1.12 Rock Ridge entry.  So we'll use the
        # above as a hint, and allow for some wiggle room.

        if px_record_length == 44 or sf_record_length == 21 or has_es_record or er_id == EXT_ID_112:
            self.rr_version = '1.12'
        else:
            # Not 1.12, so either 1.09 or 1.10.
            if sf_record_length == 12:
                self.rr_version = '1.10'
            else:
                self.rr_version = '1.09'

        namelist = [nm.posix_name for nm in self.dr_entries.nm_records]
        namelist.extend([nm.posix_name for nm in self.ce_entries.nm_records])
        self._full_name = b''.join(namelist)

        self._initialized = True

    def _record(self, entries):
        # type: (RockRidgeEntries) -> bytes
        '''
        Return a string representing the Rock Ridge entry.

        Parameters:
         entries - The dr_entries or ce_entries to generate a record for.
        Returns:
         A string representing the Rock Ridge entry.
        '''

        outlist = []
        if entries.sp_record is not None:
            outlist.append(entries.sp_record.record())

        if entries.rr_record is not None:
            outlist.append(entries.rr_record.record())

        for nm_record in entries.nm_records:
            outlist.append(nm_record.record())

        if entries.px_record is not None:
            outlist.append(entries.px_record.record(self.rr_version))

        for sl_record in entries.sl_records:
            outlist.append(sl_record.record())

        if entries.tf_record is not None:
            outlist.append(entries.tf_record.record())

        if entries.cl_record is not None:
            outlist.append(entries.cl_record.record())

        if entries.pl_record is not None:
            outlist.append(entries.pl_record.record())

        if entries.re_record is not None:
            outlist.append(entries.re_record.record())

        for es_record in entries.es_records:
            outlist.append(es_record.record())

        if entries.er_record is not None:
            outlist.append(entries.er_record.record())

        for al_record in entries.al_records:
            outlist.append(al_record.record())

        if entries.ce_record is not None:
            outlist.append(entries.ce_record.record())

        for pd_record in entries.pd_records:
            outlist.append(pd_record.record())

        if entries.st_record is not None:
            outlist.append(entries.st_record.record())

        if entries.sf_record is not None:
            outlist.append(entries.sf_record.record())

        return b''.join(outlist)

    def record_dr_entries(self):
        # type: () -> bytes
        '''
        Return a string representing the Rock Ridge entries in the Directory
        Record.

        Parameters:
         None.
        Returns:
         A string representing the Rock Ridge entry.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        return self._record(self.dr_entries)

    def record_ce_entries(self):
        # type: () -> bytes
        '''
        Return a string representing the Rock Ridge entries in the Continuation
        Entry.

        Parameters:
         None.
        Returns:
         A string representing the Rock Ridge entry.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        return self._record(self.ce_entries)

    def _new_symlink(self, symlink_path, curr_dr_len):
        # type: (bytes, int) -> int
        '''
        An internal method to add the appropriate symlink record(s) to the ISO.

        Parameters:
         symlink_path - The absolute symlink path to add to the ISO.
         curr_dr_len - The current directory record length.
        Returns:
         The new directory record length.
        '''
        # This is more complicated than I realized.  There are up to 3 layers
        # of maximum length:
        # 1.  If we are still using the directory record, then we are
        #     subject to the maximum length left in the directory record.
        # 2.  The SL entry length is an 8-bit number, so we may need multiple
        #     SL entries in order to encode all of the components.
        # 3.  The Component header is also an 8-bit number, so we may need
        #     multiple SL records to record this component.
        #
        # Note that the component header length can never be longer than the SL
        # entry length.  Thus, we are reduced to 2 lengths to worry about.

        if curr_dr_len + RRSLRecord.length(symlink_path.split(b'/')) > ALLOWED_DR_SIZE:
            if self.dr_entries.ce_record is None:
                return -1

        curr_sl = RRSLRecord()
        curr_sl.new()

        sl_rec_header_len = RRSLRecord.header_length()

        thislen = RRSLRecord.length([b'a'])
        if curr_dr_len + thislen < ALLOWED_DR_SIZE:
            # There is enough room in the directory record for at least
            # part of the symlink
            curr_comp_area_length = ALLOWED_DR_SIZE - curr_dr_len - sl_rec_header_len
            self.dr_entries.sl_records.append(curr_sl)
            curr_dr_len += sl_rec_header_len
            sl_in_dr = True
        else:
            # Not enough room in the directory record, so proceed to
            # the continuation entry directly.
            curr_comp_area_length = RRSLRecord.maximum_component_area_length()
            self.ce_entries.sl_records.append(curr_sl)
            if self.dr_entries.ce_record is not None:
                self.dr_entries.ce_record.add_record(sl_rec_header_len)
            sl_in_dr = False

        for index, comp in enumerate(symlink_path.split(b'/')):
            special = False
            if index == 0 and comp == b'':
                comp = b'/'
                special = True
                mincomp = comp
            elif comp == b'.':
                special = True
                mincomp = comp
            elif comp == b'..':
                special = True
                mincomp = comp
            else:
                mincomp = b'a'

            offset = 0
            done = False
            while not done:
                minimum = RRSLRecord.Component.length(mincomp)
                if minimum > curr_comp_area_length:
                    # There wasn't enough room in the last SL record
                    # for more data.  Set the 'continued' flag on the old
                    # SL record, and then create a new one.
                    curr_sl.set_continued()
                    if offset != 0:
                        # If we need to continue this particular
                        # *component* in the next SL record, then we
                        # also need to mark the curr_sl's last component
                        # header as continued.
                        curr_sl.set_last_component_continued()

                    curr_sl = RRSLRecord()
                    curr_sl.new()
                    self.ce_entries.sl_records.append(curr_sl)
                    curr_comp_area_length = RRSLRecord.maximum_component_area_length()
                    if self.dr_entries.ce_record is not None:
                        self.dr_entries.ce_record.add_record(sl_rec_header_len)
                    sl_in_dr = False

                if special:
                    complen = minimum
                    length = 0
                    compslice = comp
                else:
                    complen = RRSLRecord.Component.length(comp[offset:])
                    if complen > curr_comp_area_length:
                        length = curr_comp_area_length - 2
                    else:
                        length = complen
                    compslice = comp[offset:offset + length]

                curr_sl.add_component(compslice)

                if sl_in_dr:
                    curr_dr_len += RRSLRecord.Component.length(compslice)
                else:
                    if self.dr_entries.ce_record is not None:
                        self.dr_entries.ce_record.add_record(RRSLRecord.Component.length(compslice))

                offset += length

                curr_comp_area_length = curr_comp_area_length - length - 2

                if special:
                    done = True
                else:
                    if offset >= len(comp):
                        done = True

        return curr_dr_len

    def _new_attributes(self, attributes, curr_dr_len):
        # type: (Dict[bytes, bytes], int) -> int
        '''
        An internal method to add arbitrary attributes to the ISO.

        Parameters:
         attributes - A dictionary of attributes to add to the ISO.
         curr_dr_len - The current directory record length.
        Returns:
         The new directory record length.
        '''
        attr_list = list(attributes.keys()) + list(attributes.values())
        if curr_dr_len + RRALRecord.length(attr_list) > ALLOWED_DR_SIZE:
            if self.dr_entries.ce_record is None:
                return -1

        curr_al = RRALRecord()
        curr_al.new()

        al_rec_header_len = RRALRecord.header_length()

        thislen = RRALRecord.length([b'a'])
        if curr_dr_len + thislen < ALLOWED_DR_SIZE:
            # There is enough room in the directory record for at least
            # part of one of the attributes.
            curr_comp_area_length = ALLOWED_DR_SIZE - curr_dr_len - al_rec_header_len
            self.dr_entries.al_records.append(curr_al)
            curr_dr_len += al_rec_header_len
            al_in_dr = True
        else:
            # Not enough room in the directory record, so proceed to
            # the continuation entry directly.
            curr_comp_area_length = RRALRecord.maximum_component_area_length()
            if self.dr_entries.ce_record is not None:
                self.dr_entries.ce_record.add_record(al_rec_header_len)
            self.ce_entries.al_records.append(curr_al)
            al_in_dr = False

        for attr in attr_list:
            offset = 0
            done = False
            while not done:
                minimum = RRALRecord.Component.length(b'a')
                if minimum > curr_comp_area_length:
                    # There wasn't enough room in the last AL record
                    # for more data.  Set the 'continued' flag on the old
                    # AL record, and then create a new one.
                    curr_al.set_continued()
                    if offset != 0:
                        # If we need to continue this particular
                        # *component* in the next AL record, then we
                        # also need to mark the curr_al's last component
                        # header as continued.
                        curr_al.set_last_component_continued()

                    curr_al = RRALRecord()
                    curr_al.new()
                    self.ce_entries.al_records.append(curr_al)
                    curr_comp_area_length = RRALRecord.maximum_component_area_length()
                    if self.dr_entries.ce_record is not None:
                        self.dr_entries.ce_record.add_record(al_rec_header_len)
                    al_in_dr = False

                complen = RRALRecord.Component.length(attr[offset:])
                if complen > curr_comp_area_length:
                    length = curr_comp_area_length - 2
                else:
                    length = complen
                compslice = attr[offset:offset + length]

                curr_al.add_component(compslice)

                if al_in_dr:
                    curr_dr_len += RRALRecord.Component.length(compslice)
                else:
                    if self.dr_entries.ce_record is not None:
                        self.dr_entries.ce_record.add_record(RRALRecord.Component.length(compslice))

                offset += length

                curr_comp_area_length = curr_comp_area_length - length - 2

                if offset >= len(attr):
                    done = True

        return curr_dr_len

    def _add_name(self, rr_name, curr_dr_len):
        # type: (bytes, int) -> int
        '''
        An internal method to add the appropriate name records to the ISO.

        Parameters:
         rr_name - The Rock Ridge name to add to the ISO.
         curr_dr_len - The current directory record length.
        Returns:
         The new directory record length.
        '''
        # The length we are putting in this object (as opposed to the
        # continuation entry) is the maximum, minus how much is already in the
        # DR, minus 5 for the NM metadata.  We know that at least part of the
        # NM record will always fit in this DR.  That's because the DR is a
        # maximum size of 255, and the ISO9660 fields uses a maximum of 34 bytes
        # for metadata and 8+1+3+1+5 (8 for name, 1 for dot, 3 for extension,
        # 1 for semicolon, and 5 for version number, allowed up to 32767), which
        # leaves the System Use entry with 255 - 34 - 18 = 203 bytes.  Before
        # this record, the only records we ever put in place could be the SP or
        # the RR record, and the combination of them is never > 203, so we will
        # always put some NM data in here.

        len_here = ALLOWED_DR_SIZE - curr_dr_len - 5
        if len_here < len(rr_name):
            # If there isn't room in the DR entry for the entire name, we know
            # we need a CE record to fit it.
            if self.dr_entries.ce_record is None:
                return -1

            if len_here < 0:
                len_here = 0

        curr_nm = None
        if len_here > 0:
            curr_nm = RRNMRecord()
            curr_nm.new(rr_name[:len_here])
            self.dr_entries.nm_records.append(curr_nm)
            curr_dr_len += RRNMRecord.length(rr_name[:len_here])

        offset = len_here
        while offset < len(rr_name):
            if self.dr_entries.ce_record is None:
                return -1

            if curr_nm is not None:
                curr_nm.set_continued()

            # We clip the length for this NM entry to 250, as that is
            # the maximum possible size for an NM entry.
            length = min(len(rr_name[offset:]), 250)

            curr_nm = RRNMRecord()
            curr_nm.new(rr_name[offset:offset + length])
            self.ce_entries.nm_records.append(curr_nm)
            self.dr_entries.ce_record.add_record(RRNMRecord.length(rr_name[offset:offset + length]))

            offset += length

        return curr_dr_len

    def _assign_entries(self, is_first_dir_record_of_root, rr_name, file_mode,
                        symlink_path, rr_relocated_child, rr_relocated,
                        rr_relocated_parent, bytes_to_skip, curr_dr_len,
                        attributes):
        # type: (bool, bytes, int, bytes, bool, bool, bool, int, int, Dict[bytes, bytes]) -> int
        '''
        Assign Rock Ridge entries to the appropriate DR or CE record.

        Parameters:
         is_first_dir_record_of_root - Whether this is the first directory
                                       record of the root directory record;
                                       certain Rock Ridge entries are only
                                       valid there.
         rr_name - The alternate name for this Rock Ridge entry.
         file_mode - The Unix file mode for this Rock Ridge entry.
         symlink_path - The path to the target of the symlink, or None if this
                        is not a symlink.
         rr_relocated_child - Whether this is a relocated child entry.
         rr_relocated - Whether this is a relocated entry.
         rr_relocated_parent - Whether this is a relocated parent entry.
         bytes_to_skip - The number of bytes to skip for the record.
         curr_dr_len - The current length of the directory record; this is used
                       when figuring out whether a continuation entry is needed.
         attributes - Arbitrary attributes to add to the Rock Ridge entry.
        Returns:
         The length of the directory record after the Rock Ridge extension has
         been added, or -1 if the entry will not fit.
        '''
        # For SP Record
        if is_first_dir_record_of_root:
            new_sp = RRSPRecord()
            new_sp.new(bytes_to_skip)
            thislen = RRSPRecord.length()
            if curr_dr_len + thislen > ALLOWED_DR_SIZE:
                if self.dr_entries.ce_record is None:
                    # In reality, this can never happen.  If the SP record pushes
                    # us over the DR limit, then there is no room for a CE record
                    # either, and we are going to fail.  We leave this in place
                    # both for consistency with other records and to keep mypy
                    # happy.
                    return -1
                self.dr_entries.ce_record.add_record(thislen)
                self.ce_entries.sp_record = new_sp
            else:
                curr_dr_len += thislen
                self.dr_entries.sp_record = new_sp

        # For RR Record
        rr_record = None
        if self.rr_version == '1.09':
            rr_record = RRRRRecord()
            rr_record.new()
            thislen = RRRRRecord.length()
            if curr_dr_len + thislen > ALLOWED_DR_SIZE:
                if self.dr_entries.ce_record is None:
                    # In reality, this can never happen.  If the RR record pushes
                    # us over the DR limit, then there is no room for a CE record
                    # either, and we are going to fail.  We leave this in place
                    # both for consistency with other records and to keep mypy
                    # happy.
                    return -1
                self.dr_entries.ce_record.add_record(thislen)
                self.ce_entries.rr_record = rr_record
            else:
                curr_dr_len += thislen
                self.dr_entries.rr_record = rr_record

        # For NM record
        if rr_name:
            curr_dr_len = self._add_name(rr_name, curr_dr_len)
            if curr_dr_len < 0:
                return -1

            if rr_record is not None:
                rr_record.append_field('NM')

        # For PX record
        new_px = RRPXRecord()
        new_px.new(file_mode)
        thislen = RRPXRecord.length(self.rr_version)
        if curr_dr_len + thislen > ALLOWED_DR_SIZE:
            if self.dr_entries.ce_record is None:
                return -1
            self.dr_entries.ce_record.add_record(thislen)
            self.ce_entries.px_record = new_px
        else:
            curr_dr_len += thislen
            self.dr_entries.px_record = new_px

        if rr_record is not None:
            rr_record.append_field('PX')

        # For SL record
        if symlink_path:
            curr_dr_len = self._new_symlink(symlink_path, curr_dr_len)
            if curr_dr_len < 0:
                return -1

            if rr_record is not None:
                rr_record.append_field('SL')

        # For TF record
        new_tf = RRTFRecord()
        new_tf.new(TF_FLAGS)
        thislen = RRTFRecord.length(TF_FLAGS)
        if curr_dr_len + thislen > ALLOWED_DR_SIZE:
            if self.dr_entries.ce_record is None:
                return -1
            self.dr_entries.ce_record.add_record(thislen)
            self.ce_entries.tf_record = new_tf
        else:
            curr_dr_len += thislen
            self.dr_entries.tf_record = new_tf

        if rr_record is not None:
            rr_record.append_field('TF')

        # For CL record
        if rr_relocated_child:
            new_cl = RRCLRecord()
            new_cl.new()
            thislen = RRCLRecord.length()
            if curr_dr_len + thislen > ALLOWED_DR_SIZE:
                if self.dr_entries.ce_record is None:
                    return -1
                self.dr_entries.ce_record.add_record(thislen)
                self.ce_entries.cl_record = new_cl
            else:
                curr_dr_len += thislen
                self.dr_entries.cl_record = new_cl

            if rr_record is not None:
                rr_record.append_field('CL')

        # For RE record
        if rr_relocated:
            new_re = RRRERecord()
            new_re.new()
            thislen = RRRERecord.length()
            if curr_dr_len + thislen > ALLOWED_DR_SIZE:
                if self.dr_entries.ce_record is None:
                    return -1
                self.dr_entries.ce_record.add_record(thislen)
                self.ce_entries.re_record = new_re
            else:
                curr_dr_len += thislen
                self.dr_entries.re_record = new_re

            if rr_record is not None:
                rr_record.append_field('RE')

        # For PL record
        if rr_relocated_parent:
            new_pl = RRPLRecord()
            new_pl.new()
            thislen = RRPLRecord.length()
            if curr_dr_len + thislen > ALLOWED_DR_SIZE:
                if self.dr_entries.ce_record is None:
                    return -1
                self.dr_entries.ce_record.add_record(thislen)
                self.ce_entries.pl_record = new_pl
            else:
                curr_dr_len += thislen
                self.dr_entries.pl_record = new_pl

            if rr_record is not None:
                rr_record.append_field('PL')

        # For ER record
        if is_first_dir_record_of_root:
            new_er = RRERRecord()
            if self.rr_version in ('1.09', '1.10'):
                new_er.new(EXT_ID_109, EXT_DES_109, EXT_SRC_109)
                thislen = RRERRecord.length(EXT_ID_109, EXT_DES_109, EXT_SRC_109)
            else:
                # Assume 1.12
                new_er.new(EXT_ID_112, EXT_DES_112, EXT_SRC_112)
                thislen = RRERRecord.length(EXT_ID_112, EXT_DES_112, EXT_SRC_112)

            if curr_dr_len + thislen > ALLOWED_DR_SIZE:
                if self.dr_entries.ce_record is None:
                    return -1
                self.dr_entries.ce_record.add_record(thislen)
                self.ce_entries.er_record = new_er
            else:
                curr_dr_len += thislen
                self.dr_entries.er_record = new_er

        # For AL record
        if attributes:
            curr_dr_len = self._new_attributes(attributes, curr_dr_len)
            if curr_dr_len < 0:
                return -1

        return curr_dr_len

    def new(self, is_first_dir_record_of_root, rr_name, file_mode,
            symlink_path, rr_version, rr_relocated_child, rr_relocated,
            rr_relocated_parent, bytes_to_skip, curr_dr_len, attributes):
        # type: (bool, bytes, int, bytes, str, bool, bool, bool, int, int, Dict[bytes, bytes]) -> int
        '''
        Create a new Rock Ridge record.

        Parameters:
         is_first_dir_record_of_root - Whether this is the first directory
                                       record of the root directory record;
                                       certain Rock Ridge entries are only
                                       valid there.
         rr_name - The alternate name for this Rock Ridge entry.
         file_mode - The Unix file mode for this Rock Ridge entry.
         symlink_path - The path to the target of the symlink, or None if this
                        is not a symlink.
         rr_version - The version of Rock Ridge to use; must be '1.09', '1.10',
                      or '1.12'.
         rr_relocated_child - Whether this is a relocated child entry.
         rr_relocated - Whether this is a relocated entry.
         rr_relocated_parent - Whether this is a relocated parent entry.
         bytes_to_skip - The number of bytes to skip for the record.
         curr_dr_len - The current length of the directory record; this is used
                       when figuring out whether a continuation entry is needed.
         attributes - Arbitrary attributes to add to the record.  This is a
                      non-standard extension, so use with care.
        Returns:
         The length of the directory record after the Rock Ridge extension has
         been added.
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension already initialized')

        if rr_version not in ('1.09', '1.10', '1.12'):
            raise pycdlibexception.PyCdlibInvalidInput('Only Rock Ridge versions 1.09, 1.10, and 1.12 are implemented')

        self.rr_version = rr_version

        new_dr_len = self._assign_entries(is_first_dir_record_of_root, rr_name,
                                          file_mode, symlink_path,
                                          rr_relocated_child, rr_relocated,
                                          rr_relocated_parent, bytes_to_skip,
                                          curr_dr_len, attributes)

        if new_dr_len < 0:
            self.dr_entries = RockRidgeEntries()
            self.ce_entries = RockRidgeEntries()

            self.dr_entries.ce_record = RRCERecord()
            self.dr_entries.ce_record.new()
            curr_dr_len += RRCERecord.length()

            new_dr_len = self._assign_entries(is_first_dir_record_of_root,
                                              rr_name, file_mode, symlink_path,
                                              rr_relocated_child, rr_relocated,
                                              rr_relocated_parent, bytes_to_skip,
                                              curr_dr_len, attributes)
            if new_dr_len < 0:
                raise pycdlibexception.PyCdlibInternalError('Could not assign Rock Ridge entries')

        if new_dr_len > ALLOWED_DR_SIZE:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge entry increased DR length too far')

        new_dr_len += (new_dr_len % 2)

        namelist = [nm.posix_name for nm in self.dr_entries.nm_records]
        namelist.extend([nm.posix_name for nm in self.ce_entries.nm_records])
        self._full_name = b''.join(namelist)

        self._initialized = True

        return new_dr_len

    def add_to_file_links(self):
        # type: () -> None
        '''
        Increment the number of POSIX file links on this entry by one.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        if self.dr_entries.px_record is None:
            if self.ce_entries.px_record is None:
                raise pycdlibexception.PyCdlibInvalidInput('No Rock Ridge file links')
            self.ce_entries.px_record.posix_file_links += 1
        else:
            self.dr_entries.px_record.posix_file_links += 1

    def remove_from_file_links(self):
        # type: () -> None
        '''
        Decrement the number of POSIX file links on this entry by one.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        if self.dr_entries.px_record is None:
            if self.ce_entries.px_record is None:
                raise pycdlibexception.PyCdlibInvalidInput('No Rock Ridge file links')
            self.ce_entries.px_record.posix_file_links -= 1
        else:
            self.dr_entries.px_record.posix_file_links -= 1

    def copy_file_links(self, src):
        # type: (RockRidge) -> None
        '''
        Copy the number of file links from the source Rock Ridge entry into
        this Rock Ridge entry.

        Parameters:
         src - The source Rock Ridge entry to copy from.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        # First, get the src data
        if src.dr_entries.px_record is None:
            if src.ce_entries.px_record is None:
                raise pycdlibexception.PyCdlibInvalidInput('No Rock Ridge file links')
            num_links = src.ce_entries.px_record.posix_file_links
        else:
            num_links = src.dr_entries.px_record.posix_file_links

        # Now apply it to this record.
        if self.dr_entries.px_record is None:
            if self.ce_entries.px_record is None:
                raise pycdlibexception.PyCdlibInvalidInput('No Rock Ridge file links')
            self.ce_entries.px_record.posix_file_links = num_links
        else:
            self.dr_entries.px_record.posix_file_links = num_links

    def get_file_mode(self):
        # type: () -> int
        '''
        Get the POSIX file mode bits for this Rock Ridge entry.

        Parameters:
         None.
        Returns:
         The POSIX file mode bits for this Rock Ridge entry.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        if self.dr_entries.px_record is None:
            if self.ce_entries.px_record is None:
                raise pycdlibexception.PyCdlibInvalidInput('No Rock Ridge file mode')
            return self.ce_entries.px_record.posix_file_mode

        return self.dr_entries.px_record.posix_file_mode

    def name(self):
        # type: () -> bytes
        '''
        Get the alternate name from this Rock Ridge entry.

        Parameters:
         None.
        Returns:
         The alternate name from this Rock Ridge entry.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        return self._full_name

    def _is_symlink(self):
        # type: () -> bool
        '''
        Internal method to determine whether this Rock Ridge entry is a symlink.
        '''
        return len(self.dr_entries.sl_records) > 0 or len(self.ce_entries.sl_records) > 0

    def is_symlink(self):
        # type: () -> bool
        '''
        Determine whether this Rock Ridge entry describes a symlink.

        Parameters:
         None.
        Returns:
         True if this Rock Ridge entry describes a symlink, False otherwise.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        return self._is_symlink()

    def symlink_path(self):
        # type: () -> bytes
        '''
        Get the path as a string of the symlink target of this Rock Ridge entry
        (if this is a symlink).

        Parameters:
         None.
        Returns:
         Symlink path as a string.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        if not self._is_symlink():
            raise pycdlibexception.PyCdlibInvalidInput('Entry is not a symlink!')

        outlist = []
        saved = b''
        for rec in self.dr_entries.sl_records + self.ce_entries.sl_records:
            if rec.last_component_continued():
                saved += rec.name()
            else:
                saved += rec.name()
                outlist.append(saved)
                saved = b''

        if saved != b'':
            raise pycdlibexception.PyCdlibInvalidISO('Saw a continued symlink record with no end; ISO is probably malformed')

        return b'/'.join(outlist)

    def child_link_record_exists(self):
        # type: () -> bool
        '''
        Determine whether this Rock Ridge entry has a child link record (used
        for relocating deep directory records).

        Parameters:
         None.
        Returns:
         True if this Rock Ridge entry has a child link record, False otherwise.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        return self.dr_entries.cl_record is not None or self.ce_entries.cl_record is not None

    def child_link_update_from_dirrecord(self):
        # type: () -> None
        '''
        Update the logical extent number stored in the child link record (if
        there is one), from the directory record entry that was stored in
        the child_link member.  This is used at the end of reshuffling extents
        to properly update the child link records.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        if self.cl_to_moved_dr is None:
            raise pycdlibexception.PyCdlibInvalidInput('No child link found!')

        if self.dr_entries.cl_record is not None:
            self.dr_entries.cl_record.set_log_block_num(self.cl_to_moved_dr.extent_location())
        elif self.ce_entries.cl_record is not None:
            self.ce_entries.cl_record.set_log_block_num(self.cl_to_moved_dr.extent_location())
        else:
            raise pycdlibexception.PyCdlibInvalidInput('Could not find child link record!')

    def child_link_extent(self):
        # type: () -> int
        '''
        Get the extent of the child of this entry if it has one.

        Parameters:
         None.
        Returns:
         The logical block number of the child if it exists.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        if self.dr_entries.cl_record is not None:
            return self.dr_entries.cl_record.child_log_block_num
        if self.ce_entries.cl_record is not None:
            return self.ce_entries.cl_record.child_log_block_num

        raise pycdlibexception.PyCdlibInternalError('Asked for child extent for non-existent child record')

    def parent_link_record_exists(self):
        # type: () -> bool
        '''
        Determine whether this Rock Ridge entry has a parent link record (used
        for relocating deep directory records).

        Parameters:
         None:
        Returns:
         True if this Rock Ridge entry has a parent link record, False otherwise.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        return self.dr_entries.pl_record is not None or self.ce_entries.pl_record is not None

    def parent_link_update_from_dirrecord(self):
        # type: () -> None
        '''
        Update the logical extent number stored in the parent link record (if
        there is one), from the directory record entry that was stored in
        the parent_link member.  This is used at the end of reshuffling extents
        to properly update the parent link records.

        Parameters:
         None.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        if self.parent_link is None:
            raise pycdlibexception.PyCdlibInvalidInput('No parent link found!')

        if self.dr_entries.pl_record is not None:
            self.dr_entries.pl_record.set_log_block_num(self.parent_link.extent_location())
        elif self.ce_entries.pl_record is not None:
            self.ce_entries.pl_record.set_log_block_num(self.parent_link.extent_location())
        else:
            raise pycdlibexception.PyCdlibInvalidInput('Could not find parent link record!')

    def parent_link_extent(self):
        # type: () -> int
        '''
        Get the extent of the parent of this entry if it has one.

        Parameters:
         None.
        Returns:
         The logical block number of the parent if it exists.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        if self.dr_entries.pl_record is not None:
            return self.dr_entries.pl_record.parent_log_block_num
        if self.ce_entries.pl_record is not None:
            return self.ce_entries.pl_record.parent_log_block_num

        raise pycdlibexception.PyCdlibInternalError('Asked for parent extent for non-existent parent record')

    def relocated_record(self):
        # type: () -> bool
        '''
        Determine whether this Rock Ridge entry has a relocated record (used for
        relocating deep directory records).

        Parameters:
         None.
        Returns:
         True if this Rock Ridge entry has a relocated record, False otherwise.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        return self.dr_entries.re_record is not None or self.ce_entries.re_record is not None

    def update_ce_block(self, block):
        # type: (RockRidgeContinuationBlock) -> None
        '''
        Update the Continuation Entry block object used by this Rock Ridge Record.

        Parameters:
         block - The new block object.
        Returns:
         Nothing.
        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not initialized')

        self.ce_block = block


class RockRidgeContinuationEntry(object):
    '''
    A class representing one 'abstract' Rock Ridge Continuation Entry.
    These entries are strictly for keeping tabs of the offset and size
    of each entry in a continuation block; they have no smarts beyond that.
    '''
    __slots__ = ('_offset', '_length')

    def __init__(self, offset, length):
        # type: (int, int) -> None
        self._offset = offset
        self._length = length

    @property
    def offset(self):
        # type: () -> int
        '''
        Property method to return the offset of this entry.

        Parameters:
         None.
        Returns:
         The offset of this entry.
        '''
        return self._offset

    @property
    def length(self):
        # type: () -> int
        '''
        Property method to return the length of this entry.

        Parameters:
         None.
        Returns:
         The length of this entry.
        '''
        return self._length

    def __lt__(self, other):
        return self._offset < other.offset


class RockRidgeContinuationBlock(object):
    '''
    A class representing one 'abstract' Rock Ridge Continuation Block.
    A Continuation Block is one extent holding many Rock Ridge Continuation
    Entries.  However, this is just used for tracking how many entries will
    fit in one block; all tracking of the actual data must be done elsewhere.
    '''
    __slots__ = ('_extent', '_max_block_size', '_entries')

    def __init__(self, extent, max_block_size):
        # type: (int, int) -> None
        self._extent = extent
        self._max_block_size = max_block_size
        self._entries = []  # type: List[RockRidgeContinuationEntry]

    def extent_location(self):
        # type: () -> int
        '''
        Get the extent location that this block resides at.

        Parameters:
         None.
        Returns:
         The extent location that this block resides at.
        '''
        return self._extent

    def set_extent_location(self, loc):
        # type: (int) -> None
        '''
        Set the extent location that this block resides at.

        Parameters:
         loc - The new extent location.
        Returns:
         Nothing.
        '''
        self._extent = loc

    def track_entry(self, offset, length):
        # type: (int, int) -> None
        '''
        Track an already allocated entry in this Rock Ridge Continuation Block.

        Parameters:
         offset - The offset at which to place the entry.
         length - The length of the entry to track.
        Returns:
         Nothing.
        '''
        newlen = offset + length - 1
        for entry in self._entries:
            thislen = entry.offset + entry.length - 1
            overlap = range(max(entry.offset, offset), min(thislen, newlen) + 1)
            if overlap:
                raise pycdlibexception.PyCdlibInvalidISO('Overlapping CE regions on the ISO')

        # OK, there were no overlaps with existing entries.  Let's see if
        # the new entry fits at the end.
        if offset + length > self._max_block_size:
            raise pycdlibexception.PyCdlibInvalidISO('No room in continuation block to track entry')

        # We passed all of the checks; add the new entry to track in.
        bisect.insort_left(self._entries, RockRidgeContinuationEntry(offset, length))

    def add_entry(self, length):
        # type: (int) -> int
        '''
        Add a new entry to this Rock Ridge Continuation Block.  This method
        attempts to find a gap that fits the new length anywhere within this
        Continuation Block.  If successful, it returns the offset at which
        it placed this entry.  If unsuccessful, it returns None.

        Parameters:
         length - The length of the entry to find a gap for.
        Returns:
         The offset the entry was placed at, or None if no gap was found.
        '''
        offset = -1
        # Need to find a gap
        for index, entry in enumerate(self._entries):
            if index == 0:
                if entry.offset != 0 and length <= entry.offset:
                    # We can put it at the beginning!
                    offset = 0
                    break
            else:
                lastentry = self._entries[index - 1]
                lastend = lastentry.offset + lastentry.length - 1
                gapsize = entry.offset - lastend - 1
                if gapsize >= length:
                    # We found a spot for it!
                    offset = lastend + 1
                    break
        else:
            # We reached the end without finding a gap for it.  Look at the last
            # entry and see if there is room at the end.
            if self._entries:
                lastentry = self._entries[-1]
                lastend = lastentry.offset + lastentry.length - 1
                left = self._max_block_size - lastend - 1
                if left >= length:
                    offset = lastend + 1
            else:
                if self._max_block_size >= length:
                    offset = 0

        if offset >= 0:
            bisect.insort_left(self._entries,
                               RockRidgeContinuationEntry(offset, length))

        return offset

    def remove_entry(self, offset, length):
        # type: (int, int) -> None
        '''
        Given an offset and length, find and remove the entry in this block
        that corresponds.

        Parameters:
         offset - The offset of the entry to look for.
         length - The length of the entry to look for.
        Returns:
         Nothing.
        '''
        for index, entry in enumerate(self._entries):
            if entry.offset == offset and entry.length == length:
                del self._entries[index]
                break
        else:
            raise pycdlibexception.PyCdlibInternalError('Could not find an entry for the RR CE entry in the CE block!')