summaryrefslogtreecommitdiff
path: root/src/libostree/ostree-repo.c
blob: 5b1aaae9bef4a5f020f4377e3b08c3464aff3cf9 (plain)
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
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
/*
 * Copyright (C) 2011 Colin Walters <walters@verbum.org>
 * Copyright (C) 2015 Red Hat, Inc.
 * Copyright (C) 2022 Igalia S.L.
 *
 * SPDX-License-Identifier: LGPL-2.0+
 *
 * 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; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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, see <https://www.gnu.org/licenses/>.
 *
 * Author: Colin Walters <walters@verbum.org>
 */

#include "config.h"

#include <glib-unix.h>
#include <gio/gunixinputstream.h>
#include <gio/gunixoutputstream.h>
#include <gio/gfiledescriptorbased.h>
#include "libglnx.h"
#include "ostree-core.h"
#include "otutil.h"
#include <glnx-console.h>
#include <linux/magic.h>

#include "ostree-core-private.h"
#include "ostree-sysroot-private.h"
#include "ostree-remote-private.h"
#include "ostree-repo-private.h"
#include "ostree-repo-file.h"
#include "ostree-repo-file-enumerator.h"
#include "ostree-gpg-verifier.h"
#include "ostree-repo-static-delta-private.h"
#include "ot-fs-utils.h"
#include "ostree-autocleanups.h"

#include <locale.h>
#include <glib/gstdio.h>
#include <sys/file.h>
#include <sys/statvfs.h>
#include <sys/statfs.h>

#define REPO_LOCK_DISABLED (-2)
#define REPO_LOCK_BLOCKING (-1)

/* ABI Size checks for ostree-repo.h, only for LP64 systems;
 * https://en.wikipedia.org/wiki/64-bit_computing#64-bit_data_models
 *
 * To generate this data, I used `pahole` from gdb. More concretely, `gdb --args
 * /usr/bin/ostree`, then `start`, (to ensure debuginfo was loaded), then e.g.
 * `$ pahole OstreeRepoTransactionStats`.
 */
#if __SIZEOF_POINTER__ == 8 && __SIZEOF_LONG__ == 8 && __SIZEOF_INT__ == 4
G_STATIC_ASSERT(sizeof(OstreeRepoTransactionStats) == sizeof(int) * 4 + 8 * 5);
G_STATIC_ASSERT(sizeof(OstreeRepoImportArchiveOptions) == sizeof(int) * 9 + 4 + sizeof(void*) * 8);
G_STATIC_ASSERT(sizeof(OstreeRepoExportArchiveOptions) == sizeof(int) * 9 + 4 + 8 + sizeof(void*) * 8);
G_STATIC_ASSERT(sizeof(OstreeRepoCheckoutAtOptions) ==
                sizeof(OstreeRepoCheckoutMode) + sizeof(OstreeRepoCheckoutOverwriteMode) +
                sizeof(int)*6 +
                sizeof(int)*5 +
                sizeof(int) +
                sizeof(void*)*2 +
                sizeof(int)*6 +
                sizeof(void*)*7);
G_STATIC_ASSERT(sizeof(OstreeRepoCommitTraverseIter) ==
                sizeof(int) + sizeof(int) +
                sizeof(void*) * 10 +
                130 + 6);  /* 6 byte hole */
G_STATIC_ASSERT(sizeof(OstreeRepoPruneOptions) ==
                sizeof(OstreeRepoPruneFlags) +
                4 +
                sizeof(void*) +
                sizeof(int) * 12 +
                sizeof(void*) * 7);
#endif

/**
 * SECTION:ostree-repo
 * @title: OstreeRepo: Content-addressed object store
 * @short_description: A git-like storage system for operating system binaries
 *
 * The #OstreeRepo is like git, a content-addressed object store.
 * Unlike git, it records uid, gid, and extended attributes.
 *
 * There are four possible "modes" for an #OstreeRepo; %OSTREE_REPO_MODE_BARE
 * is very simple - content files are represented exactly as they are, and
 * checkouts are just hardlinks. %OSTREE_REPO_MODE_BARE_USER is similar, except
 * the uid/gids are not set on the files, and checkouts as hardlinks work only
 * for user checkouts. %OSTREE_REPO_MODE_BARE_USER_ONLY is the same as
 * BARE_USER, but all metadata is not stored, so it can only be used for user
 * checkouts. This mode does not require xattrs. A %OSTREE_REPO_MODE_ARCHIVE
 * (also known as %OSTREE_REPO_MODE_ARCHIVE_Z2) repository in contrast stores
 * content files zlib-compressed. It is suitable for non-root-owned
 * repositories that can be served via a static HTTP server.
 *
 * Creating an #OstreeRepo does not invoke any file I/O, and thus needs
 * to be initialized, either from existing contents or as a new
 * repository. If you have an existing repo, use ostree_repo_open()
 * to load it from disk and check its validity. To initialize a new
 * repository in the given filepath, use ostree_repo_create() instead.
 *
 * To store content in the repo, first start a transaction with
 * ostree_repo_prepare_transaction().  Then create a
 * #OstreeMutableTree, and apply functions such as
 * ostree_repo_write_directory_to_mtree() to traverse a physical
 * filesystem and write content, possibly multiple times.
 *
 * Once the #OstreeMutableTree is complete, write all of its metadata
 * with ostree_repo_write_mtree(), and finally create a commit with
 * ostree_repo_write_commit().
 *
 * ## Collection IDs
 *
 * A collection ID is a globally unique identifier which, if set, is used to
 * identify refs from a repository which are mirrored elsewhere, such as in
 * mirror repositories or peer to peer networks.
 *
 * This is separate from the `collection-id` configuration key for a remote, which
 * is used to store the collection ID of the repository that remote points to.
 *
 * The collection ID should only be set on an #OstreeRepo if it is the canonical
 * collection for some refs.
 *
 * A collection ID must be a reverse DNS name, where the domain name is under the
 * control of the curator of the collection, so they can demonstrate ownership
 * of the collection. The later elements in the reverse DNS name can be used to
 * disambiguate between multiple collections from the same curator. For example,
 * `org.exampleos.Main` and `org.exampleos.Apps`. For the complete format of
 * collection IDs, see ostree_validate_collection_id().
 */
typedef struct {
  GObjectClass parent_class;

#ifndef OSTREE_DISABLE_GPGME
  void (*gpg_verify_result) (OstreeRepo *self,
                             const char *checksum,
                             OstreeGpgVerifyResult *result);
#endif
} OstreeRepoClass;

enum {
  PROP_0,

  PROP_PATH,
  PROP_REMOTES_CONFIG_DIR,
  PROP_SYSROOT_PATH
};

enum {
  GPG_VERIFY_RESULT,
  LAST_SIGNAL
};

#ifndef OSTREE_DISABLE_GPGME
static guint signals[LAST_SIGNAL] = { 0 };
#endif

G_DEFINE_TYPE (OstreeRepo, ostree_repo, G_TYPE_OBJECT)

#define SYSCONF_REMOTES SHORTENED_SYSCONFDIR "/ostree/remotes.d"

/* Repository locking
 *
 * To guard against objects being deleted (e.g., prune) while they're in
 * use by another operation that is accessing them (e.g., commit), the
 * repository must be locked by concurrent writers.
 *
 * The repository locking has several important features:
 *
 * * There are 2 states - shared and exclusive. Multiple users can hold
 *   a shared lock concurrently while only one user can hold an
 *   exclusive lock.
 *
 * * The lock can be taken recursively so long as each acquisition is paired
 *   with a matching release. The recursion is also latched to the strongest
 *   state. Once an exclusive lock has been taken, it will remain exclusive
 *   until all exclusive locks have been released.
 *
 * * It is both multiprocess- and multithread-safe. Threads that share
 *   an OstreeRepo use the lock cooperatively while processes and
 *   threads using separate OstreeRepo structures will block when
 *   acquiring incompatible lock states.
 *
 * The actual locking is implemented using either open file descriptor
 * locks or flock locks. This allows the locking to work with concurrent
 * processes or concurrent threads using a separate OstreeRepo. The lock
 * file is held on the ".lock" file within the repository.
 *
 * The intended usage is to take a shared lock when writing objects or
 * reading objects in critical sections. Exclusive locks are taken when
 * deleting objects.
 *
 * To allow fine grained locking, the lock state is maintained in shared and
 * exclusive counters. Callers then push or pop lock types to increment or
 * decrement the counters. When pushing or popping a lock type identical to
 * the existing or next state, the lock state is simply updated. Only when
 * upgrading or downgrading the lock (changing to/from unlocked, pushing
 * exclusive on shared or popping exclusive to shared) are actual locking
 * operations performed.
 */

typedef struct {
  guint len;
  int state;
  const char *name;
} OstreeRepoLockInfo;

static const char *
lock_state_name (int state)
{
  switch (state)
    {
    case LOCK_EX:
      return "exclusive";
    case LOCK_SH:
      return "shared";
    case LOCK_UN:
      return "unlocked";
    default:
      g_assert_not_reached ();
    }
}

static void
repo_lock_info (OstreeRepo *self, GMutexLocker *locker,
                OstreeRepoLockInfo *out_info)
{
  g_assert (self != NULL);
  g_assert (locker != NULL);
  g_assert (out_info != NULL);

  OstreeRepoLockInfo info;
  info.len = self->lock.shared + self->lock.exclusive;
  if (info.len == 0)
      info.state = LOCK_UN;
  else if (self->lock.exclusive > 0)
      info.state = LOCK_EX;
  else
      info.state = LOCK_SH;
  info.name = lock_state_name (info.state);

  *out_info = info;
}

/* Wrapper to handle flock vs OFD locking based on GLnxLockFile */
static gboolean
do_repo_lock (int fd,
              int flags)
{
  int res;

#ifdef F_OFD_SETLK
  struct flock fl = {
    .l_type = (flags & ~LOCK_NB) == LOCK_EX ? F_WRLCK : F_RDLCK,
    .l_whence = SEEK_SET,
    .l_start = 0,
    .l_len = 0,
  };

  res = TEMP_FAILURE_RETRY (fcntl (fd, (flags & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW, &fl));
#else
  res = -1;
  errno = EINVAL;
#endif

  /* Fallback to flock when OFD locks not available */
  if (res < 0)
    {
      if (errno == EINVAL)
        res = TEMP_FAILURE_RETRY (flock (fd, flags));
      if (res < 0)
        return FALSE;
    }

  return TRUE;
}

/* Wrapper to handle flock vs OFD unlocking based on GLnxLockFile */
static gboolean
do_repo_unlock (int fd,
                int flags)
{
  int res;

#ifdef F_OFD_SETLK
  struct flock fl = {
    .l_type = F_UNLCK,
    .l_whence = SEEK_SET,
    .l_start = 0,
    .l_len = 0,
  };

  res = TEMP_FAILURE_RETRY (fcntl (fd, (flags & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW, &fl));
#else
  res = -1;
  errno = EINVAL;
#endif

  /* Fallback to flock when OFD locks not available */
  if (res < 0)
    {
      if (errno == EINVAL)
        res = TEMP_FAILURE_RETRY (flock (fd, LOCK_UN | flags));
      if (res < 0)
        return FALSE;
    }

  return TRUE;
}

static gboolean
push_repo_lock (OstreeRepo          *self,
                OstreeRepoLockType   lock_type,
                gboolean             blocking,
                GError             **error)
{
  int flags = (lock_type == OSTREE_REPO_LOCK_EXCLUSIVE) ? LOCK_EX : LOCK_SH;
  int next_state = flags;
  if (!blocking)
    flags |= LOCK_NB;

  g_autoptr(GMutexLocker) locker = g_mutex_locker_new (&self->lock.mutex);

  if (self->lock.fd == -1)
    {
      g_debug ("Opening repo lock file");
      self->lock.fd = TEMP_FAILURE_RETRY (openat (self->repo_dir_fd, ".lock",
                                                  O_CREAT | O_RDWR | O_CLOEXEC,
                                                  DEFAULT_REGFILE_MODE));
      if (self->lock.fd < 0)
        return glnx_throw_errno_prefix (error,
                                        "Opening lock file %s/.lock failed",
                                        gs_file_get_path_cached (self->repodir));
    }

  OstreeRepoLockInfo info;
  repo_lock_info (self, locker, &info);
  g_debug ("Push lock: state=%s, depth=%u", info.name, info.len);

  guint *counter;
  if (next_state == LOCK_EX)
      counter = &(self->lock.exclusive);
  else
      counter = &(self->lock.shared);

  /* Check for overflow */
  if (*counter == G_MAXUINT)
    g_error ("Repo lock %s counter would overflow", lock_state_name (next_state));

  if (info.state == LOCK_EX || info.state == next_state)
    {
      g_debug ("Repo already locked %s, maintaining state", info.name);
    }
  else
    {
      /* We should never upgrade from exclusive to shared */
      g_assert (!(info.state == LOCK_EX && next_state == LOCK_SH));

      const char *next_state_name = lock_state_name (next_state);
      g_debug ("Locking repo %s", next_state_name);
      if (!do_repo_lock (self->lock.fd, flags))
        return glnx_throw_errno_prefix (error, "Locking repo %s failed",
                                        next_state_name);
    }

  /* Update state */
  (*counter)++;

  return TRUE;
}

static gboolean
pop_repo_lock (OstreeRepo          *self,
               OstreeRepoLockType   lock_type,
               gboolean             blocking,
               GError             **error)
{
  int flags = blocking ? 0 : LOCK_NB;

  g_autoptr(GMutexLocker) locker = g_mutex_locker_new (&self->lock.mutex);
  if (self->lock.fd == -1)
    g_error ("Cannot pop repo never locked repo lock");

  OstreeRepoLockInfo info;
  repo_lock_info (self, locker, &info);
  g_debug ("Pop lock: state=%s, depth=%u", info.name, info.len);

  if (info.len == 0 || info.state == LOCK_UN)
    g_error ("Cannot pop already unlocked repo lock");

  int state_to_drop;
  guint *counter;
  if (lock_type == OSTREE_REPO_LOCK_EXCLUSIVE)
    {
      state_to_drop = LOCK_EX;
      counter = &(self->lock.exclusive);
    }
  else
    {
      state_to_drop = LOCK_SH;
      counter = &(self->lock.shared);
    }

  /* Make sure caller specified a valid type to release */
  if (*counter == 0)
    g_error ("Repo %s lock pop requested, but none have been taken",
             lock_state_name (state_to_drop));

  int next_state;
  if (info.len == 1)
    {
      /* Lock counters will be empty, unlock */
      next_state = LOCK_UN;
    }
  else if (state_to_drop == LOCK_EX)
    next_state = (self->lock.exclusive > 1) ? LOCK_EX : LOCK_SH;
  else
    next_state = (self->lock.exclusive > 0) ? LOCK_EX : LOCK_SH;

  if (next_state == LOCK_UN)
    {
      g_debug ("Unlocking repo");
      if (!do_repo_unlock (self->lock.fd, flags))
        return glnx_throw_errno_prefix (error, "Unlocking repo failed");
    }
  else if (info.state == next_state)
    {
      g_debug ("Maintaining lock state as %s", info.name);
    }
  else
    {
      /* We should never drop from shared to exclusive */
      g_assert (next_state == LOCK_SH);
      g_debug ("Returning lock state to shared");
      if (!do_repo_lock (self->lock.fd, next_state | flags))
        return glnx_throw_errno_prefix (error,
                                        "Setting repo lock to shared failed");
    }

  /* Update state */
  (*counter)--;

  return TRUE;
}

/**
 * ostree_repo_lock_push:
 * @self: a #OstreeRepo
 * @lock_type: the type of lock to acquire
 * @cancellable: a #GCancellable
 * @error: a #GError
 *
 * Takes a lock on the repository and adds it to the lock state. If @lock_type
 * is %OSTREE_REPO_LOCK_SHARED, a shared lock is taken. If @lock_type is
 * %OSTREE_REPO_LOCK_EXCLUSIVE, an exclusive lock is taken. The actual lock
 * state is only changed when locking a previously unlocked repository or
 * upgrading the lock from shared to exclusive. If the requested lock type is
 * unchanged or would represent a downgrade (exclusive to shared), the lock
 * state is not changed.
 *
 * ostree_repo_lock_push() waits for the lock depending on the repository's
 * lock-timeout-secs configuration. When lock-timeout-secs is -1, a blocking lock is
 * attempted. Otherwise, the lock is taken non-blocking and
 * ostree_repo_lock_push() will sleep synchronously up to lock-timeout-secs seconds
 * attempting to acquire the lock. If the lock cannot be acquired within the
 * timeout, a %G_IO_ERROR_WOULD_BLOCK error is returned.
 *
 * If @self is not writable by the user, then no locking is attempted and
 * %TRUE is returned.
 *
 * Returns: %TRUE on success, otherwise %FALSE with @error set
 * Since: 2021.3
 */
gboolean
ostree_repo_lock_push (OstreeRepo          *self,
                       OstreeRepoLockType   lock_type,
                       GCancellable        *cancellable,
                       GError             **error)
{
  g_return_val_if_fail (self != NULL, FALSE);
  g_return_val_if_fail (OSTREE_IS_REPO (self), FALSE);
  g_return_val_if_fail (self->inited, FALSE);
  g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  if (!self->writable)
    return TRUE;

  g_assert (self->lock_timeout_seconds >= REPO_LOCK_DISABLED);
  if (self->lock_timeout_seconds == REPO_LOCK_DISABLED)
    return TRUE; /* No locking */
  else if (self->lock_timeout_seconds == REPO_LOCK_BLOCKING)
    {
      g_debug ("Pushing lock blocking");
      return push_repo_lock (self, lock_type, TRUE, error);
    }
  else
    {
      /* Convert to unsigned to guard against negative values */
      guint lock_timeout_seconds = self->lock_timeout_seconds;
      guint waited = 0;
      g_debug ("Pushing lock non-blocking with timeout %u",
               lock_timeout_seconds);
      for (;;)
        {
          if (g_cancellable_set_error_if_cancelled (cancellable, error))
            return FALSE;

          g_autoptr(GError) local_error = NULL;
          if (push_repo_lock (self, lock_type, FALSE, &local_error))
            return TRUE;

          if (!g_error_matches (local_error, G_IO_ERROR,
                                G_IO_ERROR_WOULD_BLOCK))
            {
              g_propagate_error (error, g_steal_pointer (&local_error));
              return FALSE;
            }

          if (waited >= lock_timeout_seconds)
            {
              g_debug ("Push lock: Could not acquire lock within %u seconds",
                       lock_timeout_seconds);
              g_propagate_error (error, g_steal_pointer (&local_error));
              return FALSE;
            }

          /* Sleep 1 second and try again */
          if (waited % 60 == 0)
            {
              guint remaining = lock_timeout_seconds - waited;
              g_debug ("Push lock: Waiting %u more second%s to acquire lock",
                       remaining, (remaining == 1) ? "" : "s");
            }
          waited++;
          sleep (1);
        }
    }
}

/**
 * ostree_repo_lock_pop:
 * @self: a #OstreeRepo
 * @lock_type: the type of lock to release
 * @cancellable: a #GCancellable
 * @error: a #GError
 *
 * Release a lock of type @lock_type from the lock state. If the lock state
 * becomes empty, the repository is unlocked. Otherwise, the lock state only
 * changes when transitioning from an exclusive lock back to a shared lock. The
 * requested @lock_type must be the same type that was requested in the call to
 * ostree_repo_lock_push(). It is a programmer error if these do not match and
 * the program may abort if the lock would reach an invalid state.
 *
 * ostree_repo_lock_pop() waits for the lock depending on the repository's
 * lock-timeout-secs configuration. When lock-timeout-secs is -1, a blocking lock is
 * attempted. Otherwise, the lock is removed non-blocking and
 * ostree_repo_lock_pop() will sleep synchronously up to lock-timeout-secs seconds
 * attempting to remove the lock. If the lock cannot be removed within the
 * timeout, a %G_IO_ERROR_WOULD_BLOCK error is returned.
 *
 * If @self is not writable by the user, then no unlocking is attempted and
 * %TRUE is returned.
 *
 * Returns: %TRUE on success, otherwise %FALSE with @error set
 * Since: 2021.3
 */
gboolean
ostree_repo_lock_pop (OstreeRepo          *self,
                      OstreeRepoLockType   lock_type,
                      GCancellable        *cancellable,
                      GError             **error)
{
  g_return_val_if_fail (self != NULL, FALSE);
  g_return_val_if_fail (OSTREE_IS_REPO (self), FALSE);
  g_return_val_if_fail (self->inited, FALSE);
  g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  if (!self->writable)
    return TRUE;

  g_assert (self->lock_timeout_seconds >= REPO_LOCK_DISABLED);
  if (self->lock_timeout_seconds == REPO_LOCK_DISABLED)
    return TRUE;
  else if (self->lock_timeout_seconds == REPO_LOCK_BLOCKING)
    {
      g_debug ("Popping lock blocking");
      return pop_repo_lock (self, lock_type, TRUE, error);
    }
  else
    {
      /* Convert to unsigned to guard against negative values */
      guint lock_timeout_seconds = self->lock_timeout_seconds;
      guint waited = 0;
      g_debug ("Popping lock non-blocking with timeout %u",
               lock_timeout_seconds);
      for (;;)
        {
          if (g_cancellable_set_error_if_cancelled (cancellable, error))
            return FALSE;

          g_autoptr(GError) local_error = NULL;
          if (pop_repo_lock (self, lock_type, FALSE, &local_error))
            return TRUE;

          if (!g_error_matches (local_error, G_IO_ERROR,
                                G_IO_ERROR_WOULD_BLOCK))
            {
              g_propagate_error (error, g_steal_pointer (&local_error));
              return FALSE;
            }

          if (waited >= lock_timeout_seconds)
            {
              g_debug ("Pop lock: Could not remove lock within %u seconds",
                       lock_timeout_seconds);
              g_propagate_error (error, g_steal_pointer (&local_error));
              return FALSE;
            }

          /* Sleep 1 second and try again */
          if (waited % 60 == 0)
            {
              guint remaining = lock_timeout_seconds - waited;
              g_debug ("Pop lock: Waiting %u more second%s to remove lock",
                       remaining, (remaining == 1) ? "" : "s");
            }
          waited++;
          sleep (1);
        }
    }
}

struct OstreeRepoAutoLock {
  OstreeRepo *repo;
  OstreeRepoLockType lock_type;
};

/**
 * ostree_repo_auto_lock_push: (skip)
 * @self: a #OstreeRepo
 * @lock_type: the type of lock to acquire
 * @cancellable: a #GCancellable
 * @error: a #GError
 *
 * Like ostree_repo_lock_push(), but for usage with #OstreeRepoAutoLock. The
 * intended usage is to declare the #OstreeRepoAutoLock with g_autoptr() so
 * that ostree_repo_auto_lock_cleanup() is called when it goes out of scope.
 * This will automatically release the lock if it was acquired successfully.
 *
 * |[<!-- language="C" -->
 * g_autoptr(OstreeRepoAutoLock) lock = NULL;
 * lock = ostree_repo_auto_lock_push (repo, lock_type, cancellable, error);
 * if (!lock)
 *   return FALSE;
 * ]|
 *
 * Returns: @self on success, otherwise %NULL with @error set
 * Since: 2021.3
 */
OstreeRepoAutoLock *
ostree_repo_auto_lock_push (OstreeRepo          *self,
                            OstreeRepoLockType   lock_type,
                            GCancellable        *cancellable,
                            GError             **error)
{
  if (!ostree_repo_lock_push (self, lock_type, cancellable, error))
    return NULL;

  OstreeRepoAutoLock *auto_lock = g_new (OstreeRepoAutoLock, 1);
  auto_lock->repo = self;
  auto_lock->lock_type = lock_type;
  return auto_lock;
}

/**
 * ostree_repo_auto_lock_cleanup: (skip)
 * @lock: a #OstreeRepoAutoLock
 *
 * A cleanup handler for use with ostree_repo_auto_lock_push(). If @lock is
 * not %NULL, ostree_repo_lock_pop() will be called on it. If
 * ostree_repo_lock_pop() fails, a critical warning will be emitted.
 *
 * Since: 2021.3
 */
void
ostree_repo_auto_lock_cleanup (OstreeRepoAutoLock *auto_lock)
{
  if (auto_lock != NULL)
    {
      g_autoptr(GError) error = NULL;
      int errsv = errno;

      if (!ostree_repo_lock_pop (auto_lock->repo, auto_lock->lock_type, NULL, &error))
        g_critical ("Cleanup repo lock failed: %s", error->message);

      errno = errsv;

      g_free (auto_lock);
    }
}

/**
 * _ostree_repo_auto_transaction_new:
 * @repo: (not nullable): an #OsreeRepo object
 * @cancellable: Cancellable
 * @error: a #GError
 *
 * Return a guard for a transaction in @repo.
 *
 * Do not call this function outside the OstreeRepo transaction implementation.
 * Use _ostree_repo_auto_transaction_start() instead.
 *
 * Returns: (transfer full): an #OstreeRepoAutoTransaction guard on success,
 * %NULL otherwise.
 */
OstreeRepoAutoTransaction *
_ostree_repo_auto_transaction_new (OstreeRepo *repo)
{
  g_assert (repo != NULL);

  OstreeRepoAutoTransaction *txn = g_malloc(sizeof(OstreeRepoAutoTransaction));
  txn->atomic_refcount = 1;
  txn->repo = g_object_ref (repo);

  return g_steal_pointer (&txn);
}

/**
 * _ostree_repo_auto_transaction_start:
 * @repo: (not nullable): an #OsreeRepo object
 * @cancellable: Cancellable
 * @error: a #GError
 *
 * Start a transaction and return a guard for it.
 *
 * Returns: (transfer full): an #OsreeRepoAutoTransaction guard on success,
 * %NULL otherwise.
 */
OstreeRepoAutoTransaction *
_ostree_repo_auto_transaction_start (OstreeRepo     *repo,
                                     GCancellable   *cancellable,
                                     GError        **error)
{
  g_assert (repo != NULL);

  if (!ostree_repo_prepare_transaction (repo, NULL, cancellable, error))
    return NULL;

  return _ostree_repo_auto_transaction_new (repo);
}

/**
 * _ostree_repo_auto_transaction_abort:
 * @txn: (not nullable): an #OsreeRepoAutoTransaction guard
 * @cancellable: Cancellable
 * @error: a #GError
 *
 * Abort a transaction, marking the related guard as completed.
 *
 * Returns: %TRUE on successful commit, %FALSE otherwise.
 */
gboolean
_ostree_repo_auto_transaction_abort (OstreeRepoAutoTransaction  *txn,
                                     GCancellable               *cancellable,
                                     GError                    **error)
{
  g_assert (txn != NULL);

  if (txn->repo == NULL) {
    return glnx_throw (error, "transaction already completed");
  }

  if (!ostree_repo_abort_transaction (txn->repo, cancellable, error))
    return FALSE;

  g_clear_object (&txn->repo);

  return TRUE;
}

/**
 * _ostree_repo_auto_transaction_commit:
 * @txn: (not nullable): an #OsreeRepoAutoTransaction guard
 * @out_stats: (out) (allow-none): transaction result statistics
 * @cancellable: Cancellable
 * @error: a #GError
 *
 * Commit a transaction, marking the related guard as completed.
 *
 * Returns: %TRUE on successful aborting, %FALSE otherwise.
 */
gboolean
_ostree_repo_auto_transaction_commit (OstreeRepoAutoTransaction  *txn,
                                      OstreeRepoTransactionStats *out_stats,
                                      GCancellable               *cancellable,
                                      GError                    **error)
{
  g_assert (txn != NULL);

  if (txn->repo == NULL) {
    return glnx_throw (error, "transaction already completed");
  }

  if (!ostree_repo_commit_transaction (txn->repo, out_stats, cancellable, error))
    return FALSE;

  g_clear_object (&txn->repo);

  return TRUE;
}

/**
 * _ostree_repo_auto_transaction_ref:
 * @txn: (not nullable): an #OsreeRepoAutoTransaction guard
 *
 * Return a new reference to the transaction guard.
 *
 * Returns: (transfer full) (not nullable): new transaction guard reference.
 */
OstreeRepoAutoTransaction *
_ostree_repo_auto_transaction_ref (OstreeRepoAutoTransaction *txn)
{
  g_assert (txn != NULL);

  gint refcount = g_atomic_int_add (&txn->atomic_refcount, 1);
  g_assert (refcount > 1);

  return txn;
}

/**
 * _ostree_repo_auto_transaction_unref:
 * @txn: (transfer full): an #OsreeRepoAutoTransaction guard
 *
 * Unreference a transaction guard. When the last reference is gone,
 * if the transaction has not yet been completed, it gets aborted.
 */
void
_ostree_repo_auto_transaction_unref (OstreeRepoAutoTransaction *txn)
{
  if (txn == NULL)
    return;

  if (!g_atomic_int_dec_and_test (&txn->atomic_refcount))
    return;

  // Auto-abort only if transaction has not already been aborted/committed.
  if (txn->repo != NULL)
    {
      g_autoptr(GError) error = NULL;
      if (!ostree_repo_abort_transaction (txn->repo, NULL, &error))
        g_warning("Failed to auto-cleanup OSTree transaction: %s", error->message);

      g_clear_object (&txn->repo);
    }

  g_free (txn);
  return;
}

G_DEFINE_BOXED_TYPE(OstreeRepoAutoTransaction, _ostree_repo_auto_transaction,
                    _ostree_repo_auto_transaction_ref,
                    _ostree_repo_auto_transaction_unref);

static GFile *
get_remotes_d_dir (OstreeRepo          *self,
                   GFile               *sysroot);

OstreeRemote *
_ostree_repo_get_remote (OstreeRepo  *self,
                         const char  *name,
                         GError     **error)
{
  OstreeRemote *remote = NULL;

  g_return_val_if_fail (name != NULL, NULL);

  g_mutex_lock (&self->remotes_lock);

  remote = g_hash_table_lookup (self->remotes, name);

  if (remote != NULL)
    ostree_remote_ref (remote);
  else
    g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
                 "Remote \"%s\" not found", name);

  g_mutex_unlock (&self->remotes_lock);

  return remote;
}

OstreeRemote *
_ostree_repo_get_remote_inherited (OstreeRepo  *self,
                                   const char  *name,
                                   GError     **error)
{
  g_autoptr(OstreeRemote) remote = NULL;
  g_autoptr(GError) temp_error = NULL;

  remote = _ostree_repo_get_remote (self, name, &temp_error);
  if (remote == NULL)
    {
      if (self->parent_repo != NULL)
        return _ostree_repo_get_remote_inherited (self->parent_repo, name, error);

      g_propagate_error (error, g_steal_pointer (&temp_error));
      return NULL;
    }

  return g_steal_pointer (&remote);
}

gboolean
_ostree_repo_add_remote (OstreeRepo   *self,
                         OstreeRemote *remote)
{
  gboolean already_existed;

  g_return_val_if_fail (self != NULL, FALSE);
  g_return_val_if_fail (remote != NULL, FALSE);
  g_return_val_if_fail (remote->name != NULL, FALSE);

  g_mutex_lock (&self->remotes_lock);

  already_existed = !g_hash_table_replace (self->remotes, remote->name, ostree_remote_ref (remote));

  g_mutex_unlock (&self->remotes_lock);

  return already_existed;
}

gboolean
_ostree_repo_remove_remote (OstreeRepo   *self,
                            OstreeRemote *remote)
{
  gboolean removed;

  g_return_val_if_fail (self != NULL, FALSE);
  g_return_val_if_fail (remote != NULL, FALSE);
  g_return_val_if_fail (remote->name != NULL, FALSE);

  g_mutex_lock (&self->remotes_lock);

  removed = g_hash_table_remove (self->remotes, remote->name);

  g_mutex_unlock (&self->remotes_lock);

  return removed;
}

gboolean
_ostree_repo_remote_name_is_file (const char *remote_name)
{
  return g_str_has_prefix (remote_name, "file://");
}

/**
 * ostree_repo_get_remote_option:
 * @self: A OstreeRepo
 * @remote_name: Name
 * @option_name: Option
 * @default_value: (allow-none): Value returned if @option_name is not present
 * @out_value: (out): Return location for value
 * @error: Error
 *
 * OSTree remotes are represented by keyfile groups, formatted like:
 * `[remote "remotename"]`. This function returns a value named @option_name
 * underneath that group, or @default_value if the remote exists but not the
 * option name.  If an error is returned, @out_value will be set to %NULL.
 *
 * Returns: %TRUE on success, otherwise %FALSE with @error set
 *
 * Since: 2016.5
 */
gboolean
ostree_repo_get_remote_option (OstreeRepo  *self,
                               const char  *remote_name,
                               const char  *option_name,
                               const char  *default_value,
                               char       **out_value,
                               GError     **error)
{
  g_autoptr(OstreeRemote) remote = NULL;
  gboolean ret = FALSE;
  g_autoptr(GError) temp_error = NULL;
  g_autofree char *value = NULL;

  if (_ostree_repo_remote_name_is_file (remote_name))
    {
      *out_value = g_strdup (default_value);
      return TRUE;
    }

  remote = _ostree_repo_get_remote (self, remote_name, &temp_error);
  if (remote != NULL)
    {
      value = g_key_file_get_string (remote->options, remote->group, option_name, &temp_error);
      if (value == NULL)
        {
          if (g_error_matches (temp_error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_KEY_NOT_FOUND))
            {
              /* Note: We ignore errors on the parent because the parent config may not
                 specify this remote, causing a "remote not found" error, but we found
                 the remote at some point, so we need to instead return the default */
              if (self->parent_repo != NULL &&
                  ostree_repo_get_remote_option (self->parent_repo,
                                                 remote_name, option_name,
                                                 default_value,
                                                 out_value,
                                                 NULL))
                return TRUE;

              value = g_strdup (default_value);
              ret = TRUE;
            }
          else
            g_propagate_error (error, g_steal_pointer (&temp_error));
        }
      else
        ret = TRUE;
    }
  else if (self->parent_repo != NULL)
    return ostree_repo_get_remote_option (self->parent_repo,
                                          remote_name, option_name,
                                          default_value,
                                          out_value,
                                          error);
  else
    g_propagate_error (error, g_steal_pointer (&temp_error));

  *out_value = g_steal_pointer (&value);
  return ret;
}

/**
 * ostree_repo_get_remote_list_option:
 * @self: A OstreeRepo
 * @remote_name: Name
 * @option_name: Option
 * @out_value: (out) (array zero-terminated=1): location to store the list
 *            of strings. The list should be freed with
 *            g_strfreev().
 * @error: Error
 *
 * OSTree remotes are represented by keyfile groups, formatted like:
 * `[remote "remotename"]`. This function returns a value named @option_name
 * underneath that group, and returns it as a zero terminated array of strings.
 * If the option is not set, or if an error is returned, @out_value will be set
 * to %NULL.
 *
 * Returns: %TRUE on success, otherwise %FALSE with @error set
 *
 * Since: 2016.5
 */
gboolean
ostree_repo_get_remote_list_option (OstreeRepo   *self,
                                    const char   *remote_name,
                                    const char   *option_name,
                                    char       ***out_value,
                                    GError      **error)
{
  g_autoptr(OstreeRemote) remote = NULL;
  gboolean ret = FALSE;
  g_autoptr(GError) temp_error = NULL;
  g_auto(GStrv) value = NULL;

  if (_ostree_repo_remote_name_is_file (remote_name))
    {
      *out_value = NULL;
      return TRUE;
    }

  remote = _ostree_repo_get_remote (self, remote_name, &temp_error);
  if (remote != NULL)
    {
      value = g_key_file_get_string_list (remote->options,
                                          remote->group,
                                          option_name,
                                          NULL, &temp_error);

      /* Default value if key not found is always NULL. */
      if (g_error_matches (temp_error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_KEY_NOT_FOUND))
        {
          /* Note: We ignore errors on the parent because the parent config may not
             specify this remote, causing a "remote not found" error, but we found
             the remote at some point, so we need to instead return the default */
          if (self->parent_repo != NULL &&
              ostree_repo_get_remote_list_option (self->parent_repo,
                                                  remote_name, option_name,
                                                  out_value,
                                                  NULL))
            return TRUE;

          ret = TRUE;
        }
      else if (temp_error)
        g_propagate_error (error, g_steal_pointer (&temp_error));
      else
        ret = TRUE;
    }
  else if (self->parent_repo != NULL)
    return ostree_repo_get_remote_list_option (self->parent_repo,
                                               remote_name, option_name,
                                               out_value,
                                               error);
  else
    g_propagate_error (error, g_steal_pointer (&temp_error));

  *out_value = g_steal_pointer (&value);
  return ret;
}

/**
 * ostree_repo_get_remote_boolean_option:
 * @self: A OstreeRepo
 * @remote_name: Name
 * @option_name: Option
 * @default_value: Value returned if @option_name is not present
 * @out_value: (out) : location to store the result.
 * @error: Error
 *
 * OSTree remotes are represented by keyfile groups, formatted like:
 * `[remote "remotename"]`. This function returns a value named @option_name
 * underneath that group, and returns it as a boolean.
 * If the option is not set, @out_value will be set to @default_value. If an
 * error is returned, @out_value will be set to %FALSE.
 *
 * Returns: %TRUE on success, otherwise %FALSE with @error set
 *
 * Since: 2016.5
 */
gboolean
ostree_repo_get_remote_boolean_option (OstreeRepo  *self,
                                       const char  *remote_name,
                                       const char  *option_name,
                                       gboolean     default_value,
                                       gboolean    *out_value,
                                       GError     **error)
{
  g_autoptr(OstreeRemote) remote = NULL;
  g_autoptr(GError) temp_error = NULL;
  gboolean ret = FALSE;
  gboolean value = FALSE;

  if (_ostree_repo_remote_name_is_file (remote_name))
    {
      *out_value = default_value;
      return TRUE;
    }

  remote = _ostree_repo_get_remote (self, remote_name, &temp_error);
  if (remote != NULL)
    {
      value = g_key_file_get_boolean (remote->options, remote->group, option_name, &temp_error);
      if (temp_error != NULL)
        {
          if (g_error_matches (temp_error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_KEY_NOT_FOUND))
            {
              /* Note: We ignore errors on the parent because the parent config may not
                 specify this remote, causing a "remote not found" error, but we found
                 the remote at some point, so we need to instead return the default */
              if (self->parent_repo != NULL &&
                  ostree_repo_get_remote_boolean_option (self->parent_repo,
                                                         remote_name, option_name,
                                                         default_value,
                                                         out_value,
                                                         NULL))
                return TRUE;

              value = default_value;
              ret = TRUE;
            }
          else
            g_propagate_error (error, g_steal_pointer (&temp_error));
        }
      else
        ret = TRUE;
    }
  else if (self->parent_repo != NULL)
    return ostree_repo_get_remote_boolean_option (self->parent_repo,
                                                  remote_name, option_name,
                                                  default_value,
                                                  out_value,
                                                  error);
  else
    g_propagate_error (error, g_steal_pointer (&temp_error));

  *out_value = value;
  return ret;
}

static void
ostree_repo_finalize (GObject *object)
{
  OstreeRepo *self = OSTREE_REPO (object);

  g_clear_object (&self->parent_repo);

  g_free (self->stagedir_prefix);
  g_clear_object (&self->repodir_fdrel);
  g_clear_object (&self->repodir);
  glnx_close_fd (&self->repo_dir_fd);
  glnx_tmpdir_unset (&self->commit_stagedir);
  glnx_release_lock_file (&self->commit_stagedir_lock);
  glnx_close_fd (&self->tmp_dir_fd);
  glnx_close_fd (&self->cache_dir_fd);
  glnx_close_fd (&self->objects_dir_fd);
  glnx_close_fd (&self->uncompressed_objects_dir_fd);
  g_clear_object (&self->sysroot_dir);
  g_weak_ref_clear (&self->sysroot);
  g_free (self->remotes_config_dir);

  if (self->loose_object_devino_hash)
    g_hash_table_destroy (self->loose_object_devino_hash);
  if (self->updated_uncompressed_dirs)
    g_hash_table_destroy (self->updated_uncompressed_dirs);
  if (self->config)
    g_key_file_free (self->config);
  g_clear_pointer (&self->txn.refs, g_hash_table_destroy);
  g_clear_pointer (&self->txn.collection_refs, g_hash_table_destroy);
  g_clear_error (&self->writable_error);
  g_clear_pointer (&self->object_sizes, g_hash_table_unref);
  g_clear_pointer (&self->dirmeta_cache, g_hash_table_unref);
  g_mutex_clear (&self->cache_lock);
  g_mutex_clear (&self->txn_lock);
  g_free (self->collection_id);
  g_strfreev (self->repo_finders);

  g_clear_pointer (&self->remotes, g_hash_table_destroy);
  g_mutex_clear (&self->remotes_lock);

  glnx_close_fd (&self->lock.fd);
  g_mutex_clear (&self->lock.mutex);

  G_OBJECT_CLASS (ostree_repo_parent_class)->finalize (object);
}

static void
ostree_repo_set_property(GObject         *object,
			   guint            prop_id,
			   const GValue    *value,
			   GParamSpec      *pspec)
{
  OstreeRepo *self = OSTREE_REPO (object);

  switch (prop_id)
    {
    case PROP_PATH:
      self->repodir = g_value_dup_object (value);
      break;
    case PROP_SYSROOT_PATH:
      self->sysroot_dir = g_value_dup_object (value);
      break;
    case PROP_REMOTES_CONFIG_DIR:
      self->remotes_config_dir = g_value_dup_string (value);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
ostree_repo_get_property(GObject         *object,
			   guint            prop_id,
			   GValue          *value,
			   GParamSpec      *pspec)
{
  OstreeRepo *self = OSTREE_REPO (object);

  switch (prop_id)
    {
    case PROP_PATH:
      g_value_set_object (value, self->repodir);
      break;
    case PROP_SYSROOT_PATH:
      g_value_set_object (value, self->sysroot_dir);
      break;
    case PROP_REMOTES_CONFIG_DIR:
      g_value_set_string (value, self->remotes_config_dir);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
ostree_repo_class_init (OstreeRepoClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->get_property = ostree_repo_get_property;
  object_class->set_property = ostree_repo_set_property;
  object_class->finalize = ostree_repo_finalize;

  /**
   * OstreeRepo:path:
   *
   * Path to repository.  Note that if this repository was created
   * via `ostree_repo_new_at()`, this value will refer to a value in
   * the Linux kernel's `/proc/self/fd` directory.  Generally, you
   * should avoid using this property at all; you can gain a reference
   * to the repository's directory fd via `ostree_repo_get_dfd()` and
   * use file-descriptor relative operations.
   */
  g_object_class_install_property (object_class,
                                   PROP_PATH,
                                   g_param_spec_object ("path", "Path", "Path",
                                                        G_TYPE_FILE,
                                                        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
  /**
   * OstreeRepo:sysroot-path:
   *
   * A system using libostree for the host has a "system" repository; this
   * property will be set for repositories referenced via
   * `ostree_sysroot_repo()` for example.
   *
   * You should avoid using this property; if your code is operating
   * on a system repository, use `OstreeSysroot` and access the repository
   * object via `ostree_sysroot_repo()`.
   */
  g_object_class_install_property (object_class,
                                   PROP_SYSROOT_PATH,
                                   g_param_spec_object ("sysroot-path",
                                                        "",
                                                        "",
                                                        G_TYPE_FILE,
                                                        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
  /**
   * OstreeRepo:remotes-config-dir:
   *
   * Path to directory containing remote definitions.  The default is `NULL`.
   * If a `sysroot-path` property is defined, this value will default to
   * `${sysroot_path}/etc/ostree/remotes.d`.
   *
   * This value will only be used for system repositories.
   */
  g_object_class_install_property (object_class,
                                   PROP_REMOTES_CONFIG_DIR,
                                   g_param_spec_string ("remotes-config-dir",
                                                        "",
                                                        "",
                                                        NULL,
                                                        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

#ifndef OSTREE_DISABLE_GPGME
  /**
   * OstreeRepo::gpg-verify-result:
   * @self: an #OstreeRepo
   * @checksum: checksum of the signed object
   * @result: an #OstreeGpgVerifyResult
   *
   * Emitted during a pull operation upon GPG verification (if enabled).
   * Applications can connect to this signal to output the verification
   * results if desired.
   *
   * The signal will be emitted from whichever #GMainContext is the
   * thread-default at the point when ostree_repo_pull_with_options()
   * is called.
   */
  signals[GPG_VERIFY_RESULT] = g_signal_new ("gpg-verify-result",
                                             OSTREE_TYPE_REPO,
                                             G_SIGNAL_RUN_LAST,
                                             G_STRUCT_OFFSET (OstreeRepoClass, gpg_verify_result),
                                             NULL, NULL, NULL,
                                             G_TYPE_NONE, 2,
                                             G_TYPE_STRING,
                                             OSTREE_TYPE_GPG_VERIFY_RESULT);
#endif /* OSTREE_DISABLE_GPGME */
}

static void
ostree_repo_init (OstreeRepo *self)
{
  const GDebugKey test_error_keys[] = {
    { "pre-commit", OSTREE_REPO_TEST_ERROR_PRE_COMMIT },
    { "invalid-cache", OSTREE_REPO_TEST_ERROR_INVALID_CACHE },
  };

#ifndef OSTREE_DISABLE_GPGME
  static gsize gpgme_initialized;

  if (g_once_init_enter (&gpgme_initialized))
    {
      gpgme_check_version (NULL);
      gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
      g_once_init_leave (&gpgme_initialized, 1);
    }
#endif

  self->test_error_flags = g_parse_debug_string (g_getenv ("OSTREE_REPO_TEST_ERROR"),
                                                 test_error_keys, G_N_ELEMENTS (test_error_keys));

  g_mutex_init (&self->lock.mutex);
  g_mutex_init (&self->cache_lock);
  g_mutex_init (&self->txn_lock);

  self->remotes = g_hash_table_new_full (g_str_hash, g_str_equal,
                                         (GDestroyNotify) NULL,
                                         (GDestroyNotify) ostree_remote_unref);
  g_mutex_init (&self->remotes_lock);

  self->repo_dir_fd = -1;
  self->cache_dir_fd = -1;
  self->tmp_dir_fd = -1;
  self->objects_dir_fd = -1;
  self->uncompressed_objects_dir_fd = -1;
  self->lock.fd = -1;
  self->sysroot_kind = OSTREE_REPO_SYSROOT_KIND_UNKNOWN;
}

/**
 * ostree_repo_new:
 * @path: Path to a repository
 *
 * Returns: (transfer full): An accessor object for an OSTree repository located at @path
 */
OstreeRepo*
ostree_repo_new (GFile *path)
{
  return g_object_new (OSTREE_TYPE_REPO, "path", path, NULL);
}

static OstreeRepo *
repo_open_at_take_fd (int *dfd,
                      GCancellable *cancellable,
                      GError **error)
{
  g_autoptr(OstreeRepo) repo = g_object_new (OSTREE_TYPE_REPO, NULL);
  repo->repo_dir_fd = glnx_steal_fd (dfd);

  if (!ostree_repo_open (repo, cancellable, error))
    return NULL;
  return g_steal_pointer (&repo);
}

/**
 * ostree_repo_open_at:
 * @dfd: Directory fd
 * @path: Path
 *
 * This combines ostree_repo_new() (but using fd-relative access) with
 * ostree_repo_open().  Use this when you know you should be operating on an
 * already extant repository.  If you want to create one, use ostree_repo_create_at().
 *
 * Returns: (transfer full): An accessor object for an OSTree repository located at @dfd + @path
 *
 * Since: 2017.10
 */
OstreeRepo*
ostree_repo_open_at (int           dfd,
                     const char   *path,
                     GCancellable *cancellable,
                     GError      **error)
{
  glnx_autofd int repo_dfd = -1;
  if (!glnx_opendirat (dfd, path, TRUE, &repo_dfd, error))
    return NULL;

  return repo_open_at_take_fd (&repo_dfd, cancellable, error);
}

static GFile *
get_default_repo_path (GFile *sysroot_path)
{
  if (sysroot_path == NULL)
    sysroot_path = _ostree_get_default_sysroot_path ();

  return g_file_resolve_relative_path (sysroot_path, "ostree/repo");
}

/**
 * ostree_repo_new_for_sysroot_path:
 * @repo_path: Path to a repository
 * @sysroot_path: Path to the system root
 *
 * Creates a new #OstreeRepo instance, taking the system root path explicitly
 * instead of assuming "/".
 *
 * Returns: (transfer full): An accessor object for the OSTree repository located at @repo_path.
 */
OstreeRepo *
ostree_repo_new_for_sysroot_path (GFile *repo_path,
                                  GFile *sysroot_path)
{
  return g_object_new (OSTREE_TYPE_REPO, "path", repo_path, "sysroot-path", sysroot_path, NULL);
}

/**
 * ostree_repo_new_default:
 *
 * If the current working directory appears to be an OSTree
 * repository, create a new #OstreeRepo object for accessing it.
 * Otherwise use the path in the OSTREE_REPO environment variable
 * (if defined) or else the default system repository located at
 * /ostree/repo.
 *
 * Returns: (transfer full): An accessor object for an OSTree repository located at /ostree/repo
 */
OstreeRepo*
ostree_repo_new_default (void)
{
  if (g_file_test ("objects", G_FILE_TEST_IS_DIR)
      && g_file_test ("config", G_FILE_TEST_IS_REGULAR))
    {
      g_autoptr(GFile) cwd = g_file_new_for_path (".");
      return ostree_repo_new (cwd);
    }
  else
    {
      const char *envvar = g_getenv ("OSTREE_REPO");
      g_autoptr(GFile) repo_path = NULL;

      if (envvar == NULL || *envvar == '\0')
        repo_path = get_default_repo_path (NULL);
      else
        repo_path = g_file_new_for_path (envvar);

      return ostree_repo_new (repo_path);
    }
}

/**
 * ostree_repo_is_system:
 * @repo: Repository
 *
 * Returns: %TRUE if this repository is the root-owned system global repository
 */
gboolean
ostree_repo_is_system (OstreeRepo   *repo)
{
  g_return_val_if_fail (OSTREE_IS_REPO (repo), FALSE);

  /* If we were created via ostree_sysroot_get_repo(), we know the answer is yes
   * without having to compare file paths.
   */
  if (repo->sysroot_kind == OSTREE_REPO_SYSROOT_KIND_VIA_SYSROOT ||
      repo->sysroot_kind == OSTREE_REPO_SYSROOT_KIND_IS_SYSROOT_OSTREE)
    return TRUE;

  /* No sysroot_dir set?  Not a system repo then. */
  if (!repo->sysroot_dir)
    return FALSE;

  /* If we created via ostree_repo_new(), we'll have a repo path.  Compare
   * it to the sysroot path in that case.
   */
  if (repo->repodir)
    {
      g_autoptr(GFile) default_repo_path = get_default_repo_path (repo->sysroot_dir);
      return g_file_equal (repo->repodir, default_repo_path);
    }
  /* Otherwise, not a system repo */
  return FALSE;
}

/**
 * ostree_repo_is_writable:
 * @self: Repo
 * @error: a #GError
 *
 * Returns whether the repository is writable by the current user.
 * If the repository is not writable, the @error indicates why.
 *
 * Returns: %TRUE if this repository is writable
 */
gboolean
ostree_repo_is_writable (OstreeRepo *self,
                         GError **error)
{
  g_assert (self != NULL);
  g_assert (self->inited);

  g_assert (self->writable == (self->writable_error == NULL));
  if (error != NULL && self->writable_error != NULL)
    *error = g_error_copy (self->writable_error);

  return self->writable;
}

/**
 * _ostree_repo_update_mtime:
 * @self: Repo
 * @error: a #GError
 *
 * Bump the mtime of the repository so that programs
 * can detect that the refs have updated.
 */
gboolean
_ostree_repo_update_mtime (OstreeRepo        *self,
                           GError           **error)
{
  if (futimens (self->repo_dir_fd, NULL) != 0)
    {
      glnx_set_prefix_error_from_errno (error, "%s", "futimens");
      return FALSE;
    }
  return TRUE;
}

/**
 * ostree_repo_get_config:
 * @self:
 *
 * Returns: (transfer none): The repository configuration; do not modify
 */
GKeyFile *
ostree_repo_get_config (OstreeRepo *self)
{
  g_assert (self != NULL);
  g_assert (self->inited);

  return self->config;
}

/**
 * ostree_repo_copy_config:
 * @self:
 *
 * Returns: (transfer full): A newly-allocated copy of the repository config
 */
GKeyFile *
ostree_repo_copy_config (OstreeRepo *self)
{
  GKeyFile *copy;
  char *data;
  gsize len;

  g_assert (self != NULL);
  g_assert (self->inited);

  copy = g_key_file_new ();
  data = g_key_file_to_data (self->config, &len, NULL);
  if (!g_key_file_load_from_data (copy, data, len, 0, NULL))
    g_assert_not_reached ();
  g_free (data);
  return copy;
}

/**
 * ostree_repo_write_config:
 * @self: Repo
 * @new_config: Overwrite the config file with this data
 * @error: a #GError
 *
 * Save @new_config in place of this repository's config file.
 */
gboolean
ostree_repo_write_config (OstreeRepo *self,
                          GKeyFile   *new_config,
                          GError    **error)
{
  g_return_val_if_fail (self->inited, FALSE);

  /* Ensure that any remotes in the new config aren't defined in a
   * separate config file.
   */
  gsize num_groups;
  g_auto(GStrv) groups = g_key_file_get_groups (new_config, &num_groups);
  for (gsize i = 0; i < num_groups; i++)
    {
      g_autoptr(OstreeRemote) new_remote = ostree_remote_new_from_keyfile (new_config, groups[i]);
      if (new_remote != NULL)
        {
          g_autoptr(GError) local_error = NULL;

          g_autoptr(OstreeRemote) cur_remote =
            _ostree_repo_get_remote (self, new_remote->name, &local_error);
          if (cur_remote == NULL)
            {
              if (!g_error_matches (local_error, G_IO_ERROR,
                                    G_IO_ERROR_NOT_FOUND))
                {
                  g_propagate_error (error, g_steal_pointer (&local_error));
                  return FALSE;
                }
            }
          else if (cur_remote->file != NULL)
            {
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_EXISTS,
                           "Remote \"%s\" already defined in %s",
                           new_remote->name,
                           gs_file_get_path_cached (cur_remote->file));
              return FALSE;
            }
        }
    }

  gsize len;
  g_autofree char *data = g_key_file_to_data (new_config, &len, error);
  if (!glnx_file_replace_contents_at (self->repo_dir_fd, "config",
                                      (guint8*)data, len, 0,
                                      NULL, error))
    return FALSE;

  g_key_file_free (self->config);
  self->config = g_key_file_new ();
  if (!g_key_file_load_from_data (self->config, data, len, 0, error))
    return FALSE;

  return TRUE;
}

/* Bind a subset of an a{sv} to options in a given GKeyfile section */
static void
keyfile_set_from_vardict (GKeyFile     *keyfile,
                          const char   *section,
                          GVariant     *vardict)
{
  GVariantIter viter;
  const char *key;
  GVariant *val;

  g_variant_iter_init (&viter, vardict);
  while (g_variant_iter_loop (&viter, "{&s@v}", &key, &val))
    {
      g_autoptr(GVariant) child = g_variant_get_variant (val);
      if (g_variant_is_of_type (child, G_VARIANT_TYPE_STRING))
        g_key_file_set_string (keyfile, section, key, g_variant_get_string (child, NULL));
      else if (g_variant_is_of_type (child, G_VARIANT_TYPE_BOOLEAN))
        g_key_file_set_boolean (keyfile, section, key, g_variant_get_boolean (child));
      else if (g_variant_is_of_type (child, G_VARIANT_TYPE_STRING_ARRAY))
        {
          gsize len;
          g_autofree const gchar **strv_child = g_variant_get_strv (child, &len);
          g_key_file_set_string_list (keyfile, section, key, strv_child, len);
        }
      else
        g_critical ("Unhandled type '%s' in %s",
                    (char*)g_variant_get_type (child), G_STRFUNC);
    }
}

static gboolean
impl_repo_remote_add (OstreeRepo     *self,
                      GFile          *sysroot,
                      gboolean        if_not_exists,
                      const char     *name,
                      const char     *url,
                      GVariant       *options,
                      GCancellable   *cancellable,
                      GError        **error)
{
  g_return_val_if_fail (name != NULL, FALSE);
  g_return_val_if_fail (options == NULL || g_variant_is_of_type (options, G_VARIANT_TYPE ("a{sv}")), FALSE);

  if (!ostree_validate_remote_name (name, error))
    return FALSE;

  g_autoptr(OstreeRemote) remote = _ostree_repo_get_remote (self, name, NULL);
  if (remote != NULL && if_not_exists)
    {
      /* Note early return */
      return TRUE;
    }
  else if (remote != NULL)
    {
      return glnx_throw (error,
                         "Remote configuration for \"%s\" already exists: %s",
                         name, remote->file ? gs_file_get_path_cached (remote->file) : "(in config)");
    }

  remote = ostree_remote_new (name);

  /* Only add repos in remotes.d if the repo option
   * add-remotes-config-dir is true. This is the default for system
   * repos.
   */
  g_autoptr(GFile) etc_ostree_remotes_d = get_remotes_d_dir (self, sysroot);
  if (etc_ostree_remotes_d && self->add_remotes_config_dir)
    {
      g_autoptr(GError) local_error = NULL;

      if (!g_file_make_directory_with_parents (etc_ostree_remotes_d,
                                               cancellable, &local_error))
        {
          if (g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS))
            {
              g_clear_error (&local_error);
            }
          else
            {
              g_propagate_error (error, g_steal_pointer (&local_error));
              return FALSE;
            }
        }

      g_autofree char *basename = g_strconcat (name, ".conf", NULL);
      remote->file = g_file_get_child (etc_ostree_remotes_d, basename);
    }

  if (url)
    {
      if (g_str_has_prefix (url, "metalink="))
        g_key_file_set_string (remote->options, remote->group, "metalink", url + strlen ("metalink="));
      else
        g_key_file_set_string (remote->options, remote->group, "url", url);
    }

  if (options)
    keyfile_set_from_vardict (remote->options, remote->group, options);

  if (remote->file != NULL)
    {
      gsize length;
      g_autofree char *data = g_key_file_to_data (remote->options, &length, NULL);

      if (!g_file_replace_contents (remote->file,
                                    data, length,
                                    NULL, FALSE, 0, NULL,
                                    cancellable, error))
        return FALSE;
    }
  else
    {
      g_autoptr(GKeyFile) config = NULL;

      config = ostree_repo_copy_config (self);
      ot_keyfile_copy_group (remote->options, config, remote->group);

      if (!ostree_repo_write_config (self, config, error))
        return FALSE;
    }

  _ostree_repo_add_remote (self, remote);

  return TRUE;
}

/**
 * ostree_repo_remote_add:
 * @self: Repo
 * @name: Name of remote
 * @url: (allow-none): URL for remote (if URL begins with metalink=, it will be used as such)
 * @options: (allow-none): GVariant of type a{sv}
 * @cancellable: Cancellable
 * @error: Error
 *
 * Create a new remote named @name pointing to @url.  If @options is
 * provided, then it will be mapped to #GKeyFile entries, where the
 * GVariant dictionary key is an option string, and the value is
 * mapped as follows:
 *   * s: g_key_file_set_string()
 *   * b: g_key_file_set_boolean()
 *   * as: g_key_file_set_string_list()
 *
 */
gboolean
ostree_repo_remote_add (OstreeRepo     *self,
                        const char     *name,
                        const char     *url,
                        GVariant       *options,
                        GCancellable   *cancellable,
                        GError        **error)
{
  return impl_repo_remote_add (self, NULL, FALSE, name, url, options,
                               cancellable, error);
}

static gboolean
impl_repo_remote_delete (OstreeRepo     *self,
                         GFile          *sysroot,
                         gboolean        if_exists,
                         const char     *name,
                         GCancellable   *cancellable,
                         GError        **error)
{
  g_return_val_if_fail (name != NULL, FALSE);

  if (!ostree_validate_remote_name (name, error))
    return FALSE;

  g_autoptr(OstreeRemote) remote = NULL;
  if (if_exists)
    {
      remote = _ostree_repo_get_remote (self, name, NULL);
      if (!remote)
        {
          /* Note early return */
          return TRUE;
        }
    }
  else
    remote = _ostree_repo_get_remote (self, name, error);

  if (remote == NULL)
    return FALSE;

  if (remote->file != NULL)
    {
      if (!glnx_unlinkat (AT_FDCWD, gs_file_get_path_cached (remote->file), 0, error))
        return FALSE;
    }
  else
    {
      g_autoptr(GKeyFile) config = ostree_repo_copy_config (self);

      /* XXX Not sure it's worth failing if the group to remove
       *     isn't found.  It's the end result we want, after all. */
      if (g_key_file_remove_group (config, remote->group, NULL))
        {
          if (!ostree_repo_write_config (self, config, error))
            return FALSE;
        }
    }

  /* Delete the remote's keyring file, if it exists. */
  if (!ot_ensure_unlinked_at (self->repo_dir_fd, remote->keyring, error))
    return FALSE;

  _ostree_repo_remove_remote (self, remote);

  return TRUE;
}

/**
 * ostree_repo_remote_delete:
 * @self: Repo
 * @name: Name of remote
 * @cancellable: Cancellable
 * @error: Error
 *
 * Delete the remote named @name.  It is an error if the provided
 * remote does not exist.
 *
 */
gboolean
ostree_repo_remote_delete (OstreeRepo     *self,
                           const char     *name,
                           GCancellable   *cancellable,
                           GError        **error)
{
  return impl_repo_remote_delete (self, NULL, FALSE, name, cancellable, error);
}


static gboolean
impl_repo_remote_replace (OstreeRepo     *self,
                          GFile          *sysroot,
                          const char     *name,
                          const char     *url,
                          GVariant       *options,
                          GCancellable   *cancellable,
                          GError        **error)
{
  g_return_val_if_fail (name != NULL, FALSE);
  g_return_val_if_fail (options == NULL || g_variant_is_of_type (options, G_VARIANT_TYPE ("a{sv}")), FALSE);

  if (!ostree_validate_remote_name (name, error))
    return FALSE;

  g_autoptr(GError) local_error = NULL;
  g_autoptr(OstreeRemote) remote = _ostree_repo_get_remote (self, name, &local_error);
  if (remote == NULL)
    {
      if (!g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
        {
          g_propagate_error (error, g_steal_pointer (&local_error));
          return FALSE;
        }
      g_clear_error (&local_error);
      if (!impl_repo_remote_add (self, sysroot, FALSE, name, url, options,
                                 cancellable, error))
        return FALSE;
    }
  else
    {
      /* Replace the entire option group */
      if (!g_key_file_remove_group (remote->options, remote->group, error))
        return FALSE;

      if (url)
        {
          if (g_str_has_prefix (url, "metalink="))
            g_key_file_set_string (remote->options, remote->group, "metalink",
                                   url + strlen ("metalink="));
          else
            g_key_file_set_string (remote->options, remote->group, "url", url);
        }

      if (options != NULL)
        keyfile_set_from_vardict (remote->options, remote->group, options);

      /* Write out updated settings */
      if (remote->file != NULL)
        {
          gsize length;
          g_autofree char *data = g_key_file_to_data (remote->options, &length,
                                                      NULL);

          if (!g_file_replace_contents (remote->file, data, length,
                                        NULL, FALSE, 0, NULL,
                                        cancellable, error))
            return FALSE;
        }
      else
        {
          g_autoptr(GKeyFile) config = ostree_repo_copy_config (self);

          /* Remove the existing group if it exists */
          if (!g_key_file_remove_group (config, remote->group, &local_error))
            {
              if (!g_error_matches (local_error, G_KEY_FILE_ERROR,
                                    G_KEY_FILE_ERROR_GROUP_NOT_FOUND))
                {
                  g_propagate_error (error, g_steal_pointer (&local_error));
                  return FALSE;
                }
            }

          ot_keyfile_copy_group (remote->options, config, remote->group);
          if (!ostree_repo_write_config (self, config, error))
            return FALSE;
        }
    }

  return TRUE;
}

/**
 * ostree_repo_remote_change:
 * @self: Repo
 * @sysroot: (allow-none): System root
 * @changeop: Operation to perform
 * @name: Name of remote
 * @url: (allow-none): URL for remote (if URL begins with metalink=, it will be used as such)
 * @options: (allow-none): GVariant of type a{sv}
 * @cancellable: Cancellable
 * @error: Error
 *
 * A combined function handling the equivalent of
 * ostree_repo_remote_add(), ostree_repo_remote_delete(), with more
 * options.
 *
 *
 */
gboolean
ostree_repo_remote_change (OstreeRepo     *self,
                           GFile          *sysroot,
                           OstreeRepoRemoteChange changeop,
                           const char     *name,
                           const char     *url,
                           GVariant       *options,
                           GCancellable   *cancellable,
                           GError        **error)
{
  switch (changeop)
    {
    case OSTREE_REPO_REMOTE_CHANGE_ADD:
      return impl_repo_remote_add (self, sysroot, FALSE, name, url, options,
                                   cancellable, error);
    case OSTREE_REPO_REMOTE_CHANGE_ADD_IF_NOT_EXISTS:
      return impl_repo_remote_add (self, sysroot, TRUE, name, url, options,
                                   cancellable, error);
    case OSTREE_REPO_REMOTE_CHANGE_DELETE:
      return impl_repo_remote_delete (self, sysroot, FALSE, name,
                                      cancellable, error);
    case OSTREE_REPO_REMOTE_CHANGE_DELETE_IF_EXISTS:
      return impl_repo_remote_delete (self, sysroot, TRUE, name,
                                      cancellable, error);
    case OSTREE_REPO_REMOTE_CHANGE_REPLACE:
      return impl_repo_remote_replace (self, sysroot, name, url, options,
                                       cancellable, error);
    }
  g_assert_not_reached ();
}

static void
_ostree_repo_remote_list (OstreeRepo *self,
                          GHashTable *out)
{
  GHashTableIter iter;
  gpointer key, value;

  g_mutex_lock (&self->remotes_lock);

  g_hash_table_iter_init (&iter, self->remotes);
  while (g_hash_table_iter_next (&iter, &key, &value))
    g_hash_table_insert (out, g_strdup (key), NULL);

  g_mutex_unlock (&self->remotes_lock);

  if (self->parent_repo)
    _ostree_repo_remote_list (self->parent_repo, out);
}

/**
 * ostree_repo_remote_list:
 * @self: Repo
 * @out_n_remotes: (out) (allow-none): Number of remotes available
 *
 * List available remote names in an #OstreeRepo.  Remote names are sorted
 * alphabetically.  If no remotes are available the function returns %NULL.
 *
 * Returns: (array length=out_n_remotes) (transfer full): a %NULL-terminated
 *          array of remote names
 **/
char **
ostree_repo_remote_list (OstreeRepo *self,
                         guint      *out_n_remotes)
{
  char **remotes = NULL;
  guint n_remotes;
  g_autoptr(GHashTable) remotes_ht = NULL;

  remotes_ht = g_hash_table_new_full (g_str_hash, g_str_equal,
                                      (GDestroyNotify) g_free,
                                      (GDestroyNotify) NULL);

  _ostree_repo_remote_list (self, remotes_ht);

  n_remotes = g_hash_table_size (remotes_ht);

  if (n_remotes > 0)
    {
      GList *list, *link;
      guint ii = 0;

      remotes = g_new (char *, n_remotes + 1);

      list = g_hash_table_get_keys (remotes_ht);
      list = g_list_sort (list, (GCompareFunc) strcmp);

      for (link = list; link != NULL; link = link->next)
        remotes[ii++] = g_strdup (link->data);

      g_list_free (list);

      remotes[ii] = NULL;
    }

  if (out_n_remotes)
    *out_n_remotes = n_remotes;

  return remotes;
}

/**
 * ostree_repo_remote_get_url:
 * @self: Repo
 * @name: Name of remote
 * @out_url: (out) (allow-none): Remote's URL
 * @error: Error
 *
 * Return the URL of the remote named @name through @out_url.  It is an
 * error if the provided remote does not exist.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean
ostree_repo_remote_get_url (OstreeRepo  *self,
                            const char  *name,
                            char       **out_url,
                            GError     **error)
{
  g_return_val_if_fail (name != NULL, FALSE);

  g_autofree char *url = NULL;
  if (_ostree_repo_remote_name_is_file (name))
    {
      url = g_strdup (name);
    }
  else
    {
      if (!ostree_repo_get_remote_option (self, name, "url", NULL, &url, error))
        return FALSE;

      if (url == NULL)
        {
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
                       "No \"url\" option in remote \"%s\"", name);
          return FALSE;
        }
    }

  if (out_url != NULL)
    *out_url = g_steal_pointer (&url);
  return TRUE;
}

/**
 * ostree_repo_remote_get_gpg_verify:
 * @self: Repo
 * @name: Name of remote
 * @out_gpg_verify: (out) (allow-none): Remote's GPG option
 * @error: Error
 *
 * Return whether GPG verification is enabled for the remote named @name
 * through @out_gpg_verify.  It is an error if the provided remote does
 * not exist.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean
ostree_repo_remote_get_gpg_verify (OstreeRepo  *self,
                                   const char  *name,
                                   gboolean    *out_gpg_verify,
                                   GError     **error)
{
  g_return_val_if_fail (OSTREE_IS_REPO (self), FALSE);
  g_return_val_if_fail (name != NULL, FALSE);

  /* For compatibility with pull-local, don't GPG verify file:// URIs. */
  if (_ostree_repo_remote_name_is_file (name))
    {
      if (out_gpg_verify != NULL)
        *out_gpg_verify = FALSE;
      return TRUE;
    }

  return ostree_repo_get_remote_boolean_option (self, name, "gpg-verify",
                                               TRUE, out_gpg_verify, error);
}

/**
 * ostree_repo_remote_get_gpg_verify_summary:
 * @self: Repo
 * @name: Name of remote
 * @out_gpg_verify_summary: (out) (allow-none): Remote's GPG option
 * @error: Error
 *
 * Return whether GPG verification of the summary is enabled for the remote
 * named @name through @out_gpg_verify_summary.  It is an error if the provided
 * remote does not exist.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean
ostree_repo_remote_get_gpg_verify_summary (OstreeRepo  *self,
                                           const char  *name,
                                           gboolean    *out_gpg_verify_summary,
                                           GError     **error)
{
  return ostree_repo_get_remote_boolean_option (self, name, "gpg-verify-summary",
                                                FALSE, out_gpg_verify_summary, error);
}

/**
 * ostree_repo_remote_gpg_import:
 * @self: Self
 * @name: name of a remote
 * @source_stream: (nullable): a #GInputStream, or %NULL
 * @key_ids: (array zero-terminated=1) (element-type utf8) (nullable): a %NULL-terminated array of GPG key IDs, or %NULL
 * @out_imported: (out) (optional): return location for the number of imported
 *                              keys, or %NULL
 * @cancellable: a #GCancellable
 * @error: a #GError
 *
 * Imports one or more GPG keys from the open @source_stream, or from the
 * user's personal keyring if @source_stream is %NULL.  The @key_ids array
 * can optionally restrict which keys are imported.  If @key_ids is %NULL,
 * then all keys are imported.
 *
 * The imported keys will be used to conduct GPG verification when pulling
 * from the remote named @name.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean
ostree_repo_remote_gpg_import (OstreeRepo         *self,
                               const char         *name,
                               GInputStream       *source_stream,
                               const char * const *key_ids,
                               guint              *out_imported,
                               GCancellable       *cancellable,
                               GError            **error)
{
#ifndef OSTREE_DISABLE_GPGME
  OstreeRemote *remote;
  g_auto(gpgme_ctx_t) source_context = NULL;
  g_auto(gpgme_ctx_t) target_context = NULL;
  g_auto(gpgme_data_t) data_buffer = NULL;
  gpgme_import_result_t import_result;
  gpgme_import_status_t import_status;
  g_autofree char *source_tmp_dir = NULL;
  g_autofree char *target_tmp_dir = NULL;
  glnx_autofd int target_temp_fd = -1;
  g_autoptr(GPtrArray) keys = NULL;
  struct stat stbuf;
  gpgme_error_t gpg_error;
  gboolean ret = FALSE;

  g_return_val_if_fail (OSTREE_IS_REPO (self), FALSE);
  g_return_val_if_fail (name != NULL, FALSE);

  /* First make sure the remote name is valid. */

  remote = _ostree_repo_get_remote_inherited (self, name, error);
  if (remote == NULL)
    goto out;

  /* Prepare the source GPGME context.  If reading GPG keys from an input
   * stream, point the OpenPGP engine at a temporary directory and import
   * the keys to a new pubring.gpg file.  If the key data format is ASCII
   * armored, this step will convert them to binary. */

  source_context = ot_gpgme_new_ctx (NULL, error);
  if (!source_context)
    goto out;

  if (source_stream != NULL)
    {
      data_buffer = ot_gpgme_data_input (source_stream);

      if (!ot_gpgme_ctx_tmp_home_dir (source_context, &source_tmp_dir,
                                      NULL, cancellable, error))
        {
          g_prefix_error (error, "Unable to configure context: ");
          goto out;
        }

      gpg_error = gpgme_op_import (source_context, data_buffer);
      if (gpg_error != GPG_ERR_NO_ERROR)
        {
          ot_gpgme_throw (gpg_error, error, "Unable to import keys");
          goto out;
        }

      g_clear_pointer (&data_buffer, gpgme_data_release);
    }

  /* Retrieve all keys or specific keys from the source GPGME context.
   * Assemble a NULL-terminated array of gpgme_key_t structs to import. */

  /* The keys array will contain a NULL terminator, but it turns out,
   * although not documented, gpgme_key_unref() gracefully handles it. */
  keys = g_ptr_array_new_with_free_func ((GDestroyNotify) gpgme_key_unref);

  if (key_ids != NULL)
    {
      guint ii;

      for (ii = 0; key_ids[ii] != NULL; ii++)
        {
          gpgme_key_t key = NULL;

          gpg_error = gpgme_get_key (source_context, key_ids[ii], &key, 0);
          if (gpg_error != GPG_ERR_NO_ERROR)
            {
              ot_gpgme_throw (gpg_error, error, "Unable to find key \"%s\"", key_ids[ii]);
              goto out;
            }

          /* Transfer ownership. */
          g_ptr_array_add (keys, key);
        }
    }
  else
    {
      gpg_error = gpgme_op_keylist_start (source_context, NULL, 0);

      while (gpg_error == GPG_ERR_NO_ERROR)
        {
          gpgme_key_t key = NULL;

          gpg_error = gpgme_op_keylist_next (source_context, &key);

          if (gpg_error != GPG_ERR_NO_ERROR)
            break;

          /* Transfer ownership. */
          g_ptr_array_add (keys, key);
        }

      if (gpgme_err_code (gpg_error) != GPG_ERR_EOF)
        {
          ot_gpgme_throw (gpg_error, error, "Unable to list keys");
          goto out;
        }
    }

  /* Add the NULL terminator. */
  g_ptr_array_add (keys, NULL);

  /* Prepare the target GPGME context to serve as the import destination.
   * Here the pubring.gpg file in a second temporary directory is a copy
   * of the remote's keyring file.  We'll let the import operation alter
   * the pubring.gpg file, then rename it back to its permanent home. */

  target_context = ot_gpgme_new_ctx (NULL, error);
  if (!target_context)
    goto out;

  /* No need for an output stream since we copy in a pubring.gpg. */
  if (!ot_gpgme_ctx_tmp_home_dir (target_context, &target_tmp_dir,
                                  NULL, cancellable, error))
    {
      g_prefix_error (error, "Unable to configure context: ");
      goto out;
    }

  if (!glnx_opendirat (AT_FDCWD, target_tmp_dir, FALSE, &target_temp_fd, error))
    {
      g_prefix_error (error, "Unable to open directory: ");
      goto out;
    }

  if (fstatat (self->repo_dir_fd, remote->keyring, &stbuf, AT_SYMLINK_NOFOLLOW) == 0)
    {
      if (!glnx_file_copy_at (self->repo_dir_fd, remote->keyring,
                              &stbuf, target_temp_fd, "pubring.gpg",
                              GLNX_FILE_COPY_NOXATTRS, cancellable, error))
        {
          g_prefix_error (error, "Unable to copy remote's keyring: ");
          goto out;
        }
    }
  else if (errno == ENOENT)
    {
      glnx_autofd int fd = -1;

      /* Create an empty pubring.gpg file prior to importing keys.  This
       * prevents gpg2 from creating a pubring.kbx file in the new keybox
       * format [1].  We want to stay with the older keyring format since
       * its performance issues are not relevant here.
       *
       * [1] https://gnupg.org/faq/whats-new-in-2.1.html#keybox
       */
      fd = openat (target_temp_fd, "pubring.gpg",
                   O_WRONLY | O_CREAT | O_CLOEXEC | O_NOCTTY, 0644);
      if (fd == -1)
        {
          glnx_set_prefix_error_from_errno (error, "%s", "Unable to create pubring.gpg");
          goto out;
        }
    }
  else
    {
      glnx_set_prefix_error_from_errno (error, "%s", "Unable to copy remote's keyring");
      goto out;
    }

  /* Export the selected keys from the source context and import them into
   * the target context. */

  gpg_error = gpgme_data_new (&data_buffer);
  if (gpg_error != GPG_ERR_NO_ERROR)
    {
      ot_gpgme_throw (gpg_error, error, "Unable to create data buffer");
      goto out;
    }

  gpg_error = gpgme_op_export_keys (source_context,
                                    (gpgme_key_t *) keys->pdata, 0,
                                    data_buffer);
  if (gpg_error != GPG_ERR_NO_ERROR)
    {
      ot_gpgme_throw (gpg_error, error, "Unable to export keys");
      goto out;
    }

  (void) gpgme_data_seek (data_buffer, 0, SEEK_SET);

  gpg_error = gpgme_op_import (target_context, data_buffer);
  if (gpg_error != GPG_ERR_NO_ERROR)
    {
      ot_gpgme_throw (gpg_error, error, "Unable to import keys");
      goto out;
    }

  import_result = gpgme_op_import_result (target_context);
  g_return_val_if_fail (import_result != NULL, FALSE);

  /* Check the status of each import and fail on the first error.
   * All imports must be successful to update the remote's keyring. */
  for (import_status = import_result->imports;
       import_status != NULL;
       import_status = import_status->next)
    {
      if (import_status->result != GPG_ERR_NO_ERROR)
        {
          ot_gpgme_throw (gpg_error, error, "Unable to import key \"%s\"",
                          import_status->fpr);
          goto out;
        }
    }

  /* Import successful; replace the remote's old keyring with the
   * updated keyring in the target context's temporary directory. */
  if (!glnx_file_copy_at (target_temp_fd, "pubring.gpg", NULL,
                          self->repo_dir_fd, remote->keyring,
                          GLNX_FILE_COPY_NOXATTRS | GLNX_FILE_COPY_OVERWRITE,
                          cancellable, error))
    goto out;

  if (out_imported != NULL)
    *out_imported = (guint) import_result->imported;

  ret = TRUE;

out:
  if (remote != NULL)
    ostree_remote_unref (remote);

  if (source_tmp_dir != NULL) {
    ot_gpgme_kill_agent (source_tmp_dir);
    (void) glnx_shutil_rm_rf_at (AT_FDCWD, source_tmp_dir, NULL, NULL);
  }

  if (target_tmp_dir != NULL) {
    ot_gpgme_kill_agent (target_tmp_dir);
    (void) glnx_shutil_rm_rf_at (AT_FDCWD, target_tmp_dir, NULL, NULL);
  }

  g_prefix_error (error, "GPG: ");

  return ret;
#else /* OSTREE_DISABLE_GPGME */
  return glnx_throw (error, "GPG feature is disabled in a build time");
#endif /* OSTREE_DISABLE_GPGME */
}

static gboolean
_ostree_repo_gpg_prepare_verifier (OstreeRepo         *self,
                                   const gchar        *remote_name,
                                   GFile              *keyringdir,
                                   GFile              *extra_keyring,
                                   gboolean            add_global_keyrings,
                                   OstreeGpgVerifier **out_verifier,
                                   GCancellable       *cancellable,
                                   GError            **error);

/**
 * ostree_repo_remote_get_gpg_keys:
 * @self: an #OstreeRepo
 * @name: (nullable): name of the remote or %NULL
 * @key_ids: (array zero-terminated=1) (element-type utf8) (nullable):
 *    a %NULL-terminated array of GPG key IDs to include, or %NULL
 * @out_keys: (out) (optional) (element-type GVariant) (transfer container):
 *    return location for a #GPtrArray of the remote's trusted GPG keys, or
 *    %NULL
 * @cancellable: (nullable): a #GCancellable, or %NULL
 * @error: return location for a #GError, or %NULL
 *
 * Enumerate the trusted GPG keys for the remote @name. If @name is
 * %NULL, the global GPG keys will be returned. The keys will be
 * returned in the @out_keys #GPtrArray. Each element in the array is a
 * #GVariant of format %OSTREE_GPG_KEY_GVARIANT_FORMAT. The @key_ids
 * array can be used to limit which keys are included. If @key_ids is
 * %NULL, then all keys are included.
 *
 * Returns: %TRUE if the GPG keys could be enumerated, %FALSE otherwise
 *
 * Since: 2021.4
 */
gboolean
ostree_repo_remote_get_gpg_keys (OstreeRepo          *self,
                                 const char          *name,
                                 const char * const  *key_ids,
                                 GPtrArray          **out_keys,
                                 GCancellable        *cancellable,
                                 GError             **error)
{
#ifndef OSTREE_DISABLE_GPGME
  g_autoptr(OstreeGpgVerifier) verifier = NULL;
  gboolean global_keyrings = (name == NULL);
  if (!_ostree_repo_gpg_prepare_verifier (self, name, NULL, NULL, global_keyrings,
                                          &verifier, cancellable, error))
    return FALSE;

  g_autoptr(GPtrArray) gpg_keys = NULL;
  if (!_ostree_gpg_verifier_list_keys (verifier, key_ids, &gpg_keys,
                                       cancellable, error))
    return FALSE;

  g_autoptr(GPtrArray) keys =
    g_ptr_array_new_with_free_func ((GDestroyNotify) g_variant_unref);
  for (guint i = 0; i < gpg_keys->len; i++)
    {
      gpgme_key_t key = gpg_keys->pdata[i];

      g_auto(GVariantBuilder) subkeys_builder = OT_VARIANT_BUILDER_INITIALIZER;
      g_variant_builder_init (&subkeys_builder, G_VARIANT_TYPE ("aa{sv}"));
      g_auto(GVariantBuilder) uids_builder = OT_VARIANT_BUILDER_INITIALIZER;
      g_variant_builder_init (&uids_builder, G_VARIANT_TYPE ("aa{sv}"));
      for (gpgme_subkey_t subkey = key->subkeys; subkey != NULL;
           subkey = subkey->next)
        {
          g_auto(GVariantDict) subkey_dict = OT_VARIANT_BUILDER_INITIALIZER;
          g_variant_dict_init (&subkey_dict, NULL);
          g_variant_dict_insert_value (&subkey_dict, "fingerprint",
                                       g_variant_new_string (subkey->fpr));
          g_variant_dict_insert_value (&subkey_dict, "created",
                                       g_variant_new_int64 (GINT64_TO_BE (subkey->timestamp)));
          g_variant_dict_insert_value (&subkey_dict, "expires",
                                       g_variant_new_int64 (GINT64_TO_BE (subkey->expires)));
          g_variant_dict_insert_value (&subkey_dict, "revoked",
                                       g_variant_new_boolean (subkey->revoked));
          g_variant_dict_insert_value (&subkey_dict, "expired",
                                       g_variant_new_boolean (subkey->expired));
          g_variant_dict_insert_value (&subkey_dict, "invalid",
                                       g_variant_new_boolean (subkey->invalid));
          g_variant_builder_add (&subkeys_builder, "@a{sv}",
                                 g_variant_dict_end (&subkey_dict));
        }

      for (gpgme_user_id_t uid = key->uids; uid != NULL; uid = uid->next)
        {
          /* Get WKD update URLs if address set */
          g_autofree char *advanced_url = NULL;
          g_autofree char *direct_url = NULL;
          if (uid->address != NULL)
            {
              if (!ot_gpg_wkd_urls (uid->address, &advanced_url, &direct_url,
                                    error))
                return FALSE;
            }

          g_auto(GVariantDict) uid_dict = OT_VARIANT_BUILDER_INITIALIZER;
          g_variant_dict_init (&uid_dict, NULL);
          g_variant_dict_insert_value (&uid_dict, "uid",
                                       g_variant_new_string (uid->uid));
          g_variant_dict_insert_value (&uid_dict, "name",
                                       g_variant_new_string (uid->name));
          g_variant_dict_insert_value (&uid_dict, "comment",
                                       g_variant_new_string (uid->comment));
          g_variant_dict_insert_value (&uid_dict, "email",
                                       g_variant_new_string (uid->email));
          g_variant_dict_insert_value (&uid_dict, "revoked",
                                       g_variant_new_boolean (uid->revoked));
          g_variant_dict_insert_value (&uid_dict, "invalid",
                                       g_variant_new_boolean (uid->invalid));
          g_variant_dict_insert_value (&uid_dict, "advanced_url",
                                       g_variant_new ("ms", advanced_url));
          g_variant_dict_insert_value (&uid_dict, "direct_url",
                                       g_variant_new ("ms", direct_url));
          g_variant_builder_add (&uids_builder, "@a{sv}",
                                 g_variant_dict_end (&uid_dict));
        }

      /* Currently empty */
      g_auto(GVariantDict) metadata_dict = OT_VARIANT_BUILDER_INITIALIZER;
      g_variant_dict_init (&metadata_dict, NULL);

      GVariant *key_variant = g_variant_new ("(@aa{sv}@aa{sv}@a{sv})",
                                             g_variant_builder_end (&subkeys_builder),
                                             g_variant_builder_end (&uids_builder),
                                             g_variant_dict_end (&metadata_dict));
      g_ptr_array_add (keys, g_variant_ref_sink (key_variant));
    }

  if (out_keys)
    *out_keys = g_steal_pointer (&keys);

  return TRUE;
#else /* OSTREE_DISABLE_GPGME */
  return glnx_throw (error, "GPG feature is disabled in a build time");
#endif /* OSTREE_DISABLE_GPGME */
}

/**
 * ostree_repo_remote_fetch_summary:
 * @self: Self
 * @name: name of a remote
 * @out_summary: (out) (optional): return location for raw summary data, or
 *               %NULL
 * @out_signatures: (out) (optional): return location for raw summary
 *                  signature data, or %NULL
 * @cancellable: a #GCancellable
 * @error: a #GError
 *
 * Tries to fetch the summary file and any GPG signatures on the summary file
 * over HTTP, and returns the binary data in @out_summary and @out_signatures
 * respectively.
 *
 * If no summary file exists on the remote server, @out_summary is set to
 * @NULL.  Likewise if the summary file is not signed, @out_signatures is
 * set to @NULL.  In either case the function still returns %TRUE.
 *
 * This method does not verify the signature of the downloaded summary file.
 * Use ostree_repo_verify_summary() for that.
 *
 * Parse the summary data into a #GVariant using g_variant_new_from_bytes()
 * with #OSTREE_SUMMARY_GVARIANT_FORMAT as the format string.
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
gboolean
ostree_repo_remote_fetch_summary (OstreeRepo    *self,
                                  const char    *name,
                                  GBytes       **out_summary,
                                  GBytes       **out_signatures,
                                  GCancellable  *cancellable,
                                  GError       **error)
{
  return ostree_repo_remote_fetch_summary_with_options (self,
                                                        name,
                                                        NULL,
                                                        out_summary,
                                                        out_signatures,
                                                        cancellable,
                                                        error);
}

static gboolean
ostree_repo_mode_to_string (OstreeRepoMode   mode,
                            const char     **out_mode,
                            GError         **error)
{
  const char *ret_mode;

  switch (mode)
    {
    case OSTREE_REPO_MODE_BARE:
      ret_mode = "bare";
      break;
    case OSTREE_REPO_MODE_BARE_USER:
      ret_mode = "bare-user";
      break;
    case OSTREE_REPO_MODE_BARE_USER_ONLY:
      ret_mode = "bare-user-only";
      break;
    case OSTREE_REPO_MODE_ARCHIVE:
      /* Legacy alias */
      ret_mode ="archive-z2";
      break;
    case OSTREE_REPO_MODE_BARE_SPLIT_XATTRS:
      ret_mode = "bare-split-xattrs";
      break;
    default:
      return glnx_throw (error, "Invalid mode '%d'", mode);
    }

  *out_mode = ret_mode;
  return TRUE;
}

/**
 * ostree_repo_mode_from_string:
 * @mode: a repo mode as a string
 * @out_mode: (out): the corresponding #OstreeRepoMode
 * @error: a #GError if the string is not a valid mode
 */
gboolean
ostree_repo_mode_from_string (const char      *mode,
                              OstreeRepoMode  *out_mode,
                              GError         **error)
{
  OstreeRepoMode ret_mode;

  if (strcmp (mode, "bare") == 0)
    ret_mode = OSTREE_REPO_MODE_BARE;
  else if (strcmp (mode, "bare-user") == 0)
    ret_mode = OSTREE_REPO_MODE_BARE_USER;
  else if (strcmp (mode, "bare-user-only") == 0)
    ret_mode = OSTREE_REPO_MODE_BARE_USER_ONLY;
  else if (strcmp (mode, "archive-z2") == 0 ||
           strcmp (mode, "archive") == 0)
    ret_mode = OSTREE_REPO_MODE_ARCHIVE;
  else if (strcmp (mode, "bare-split-xattrs") == 0)
    ret_mode = OSTREE_REPO_MODE_BARE_SPLIT_XATTRS;
  else
    return glnx_throw (error, "Invalid mode '%s' in repository configuration", mode);

  *out_mode = ret_mode;
  return TRUE;
}

#define DEFAULT_CONFIG_CONTENTS ("[core]\n" \
                                 "repo_version=1\n")

/* Just write the dirs to disk, return a dfd */
static gboolean
repo_create_at_internal (int             dfd,
                         const char     *path,
                         OstreeRepoMode  mode,
                         GVariant       *options,
                         int            *out_dfd,
                         GCancellable   *cancellable,
                         GError        **error)
{
  GLNX_AUTO_PREFIX_ERROR ("Creating repo", error);
   struct stat stbuf;
  /* We do objects/ last - if it exists we do nothing and exit successfully */
  const char *state_dirs[] = { "tmp", "extensions", "state",
                               "refs", "refs/heads", "refs/mirrors",
                               "refs/remotes", "objects" };

  /* Early return if we have an existing repo */
  { g_autofree char *objects_path = g_build_filename (path, "objects", NULL);

    if (!glnx_fstatat_allow_noent (dfd, objects_path, &stbuf, 0, error))
      return FALSE;
    if (errno == 0)
      {
        glnx_autofd int repo_dfd = -1;
        if (!glnx_opendirat (dfd, path, TRUE, &repo_dfd, error))
          return FALSE;

        /* Note early return */
        *out_dfd = glnx_steal_fd (&repo_dfd);
        return TRUE;
      }
  }

  if (mkdirat (dfd, path, DEFAULT_DIRECTORY_MODE) != 0)
    {
      if (G_UNLIKELY (errno != EEXIST))
        return glnx_throw_errno_prefix (error, "mkdirat");
    }

  glnx_autofd int repo_dfd = -1;
  if (!glnx_opendirat (dfd, path, TRUE, &repo_dfd, error))
    return FALSE;

  if (!glnx_fstatat_allow_noent (repo_dfd, "config", &stbuf, 0, error))
    return FALSE;
  if (errno == ENOENT)
    {
      const char *mode_str = NULL;
      g_autoptr(GString) config_data = g_string_new (DEFAULT_CONFIG_CONTENTS);

      if (!ostree_repo_mode_to_string (mode, &mode_str, error))
        return FALSE;
      g_assert (mode_str);

      g_string_append_printf (config_data, "mode=%s\n", mode_str);

      const char *collection_id = NULL;
      if (options)
        g_variant_lookup (options, "collection-id", "&s", &collection_id);
      if (collection_id != NULL)
        g_string_append_printf (config_data, "collection-id=%s\n", collection_id);

      if (!glnx_file_replace_contents_at (repo_dfd, "config",
                                          (guint8*)config_data->str, config_data->len,
                                          0, cancellable, error))
        return FALSE;
    }

  for (guint i = 0; i < G_N_ELEMENTS (state_dirs); i++)
    {
      const char *elt = state_dirs[i];
      if (mkdirat (repo_dfd, elt, DEFAULT_DIRECTORY_MODE) == -1)
        {
          if (G_UNLIKELY (errno != EEXIST))
            return glnx_throw_errno_prefix (error, "mkdirat");
        }
    }

  /* Test that the fs supports user xattrs now, so we get an error early rather
   * than during an object write later.
   */
  if (mode == OSTREE_REPO_MODE_BARE_USER)
    {
      g_auto(GLnxTmpfile) tmpf = { 0, };

      if (!glnx_open_tmpfile_linkable_at (repo_dfd, ".", O_RDWR|O_CLOEXEC, &tmpf, error))
        return FALSE;
      if (!_ostree_write_bareuser_metadata (tmpf.fd, 0, 0, 644, NULL, error))
        return FALSE;
  }

  *out_dfd = glnx_steal_fd (&repo_dfd);
  return TRUE;
}

/**
 * ostree_repo_create:
 * @self: An #OstreeRepo
 * @mode: The mode to store the repository in
 * @cancellable: Cancellable
 * @error: Error
 *
 * Create the underlying structure on disk for the repository, and call
 * ostree_repo_open() on the result, preparing it for use.

 * Since version 2016.8, this function will succeed on an existing
 * repository, and finish creating any necessary files in a partially
 * created repository.  However, this function cannot change the mode
 * of an existing repository, and will silently ignore an attempt to
 * do so.
 *
 * Since 2017.9, "existing repository" is defined by the existence of an
 * `objects` subdirectory.
 *
 * This function predates ostree_repo_create_at(). It is an error to call
 * this function on a repository initialized via ostree_repo_open_at().
 */
gboolean
ostree_repo_create (OstreeRepo     *self,
                    OstreeRepoMode  mode,
                    GCancellable   *cancellable,
                    GError        **error)
{
  g_return_val_if_fail (self->repodir, FALSE);
  const char *repopath = gs_file_get_path_cached (self->repodir);
  g_autoptr(GVariantBuilder) builder = g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
  if (self->collection_id)
    g_variant_builder_add (builder, "{s@v}", "collection-id",
                           g_variant_new_variant (g_variant_new_string (self->collection_id)));

  glnx_autofd int repo_dir_fd = -1;
  g_autoptr(GVariant) options = g_variant_ref_sink (g_variant_builder_end (builder));
  if (!repo_create_at_internal (AT_FDCWD, repopath, mode,
                                options,
                                &repo_dir_fd,
                                cancellable, error))
    return FALSE;
  self->repo_dir_fd = glnx_steal_fd (&repo_dir_fd);
  if (!ostree_repo_open (self, cancellable, error))
    return FALSE;
  return TRUE;
}

/**
 * ostree_repo_create_at:
 * @dfd: Directory fd
 * @path: Path
 * @mode: The mode to store the repository in
 * @options: (nullable): a{sv}: See below for accepted keys
 * @cancellable: Cancellable
 * @error: Error
 *
 * This is a file-descriptor relative version of ostree_repo_create().
 * Create the underlying structure on disk for the repository, and call
 * ostree_repo_open_at() on the result, preparing it for use.
 *
 * If a repository already exists at @dfd + @path (defined by an `objects/`
 * subdirectory existing), then this function will simply call
 * ostree_repo_open_at().  In other words, this function cannot be used to change
 * the mode or configuration (`repo/config`) of an existing repo.
 *
 * The @options dict may contain:
 *
 *   - collection-id: s: Set as collection ID in repo/config (Since 2017.9)
 *
 * Returns: (transfer full): A new OSTree repository reference
 *
 * Since: 2017.10
 */
OstreeRepo *
ostree_repo_create_at (int             dfd,
                       const char     *path,
                       OstreeRepoMode  mode,
                       GVariant       *options,
                       GCancellable   *cancellable,
                       GError        **error)
{
  glnx_autofd int repo_dfd = -1;
  if (!repo_create_at_internal (dfd, path, mode, options, &repo_dfd,
                                cancellable, error))
    return NULL;
  return repo_open_at_take_fd (&repo_dfd, cancellable, error);
}

static gboolean
enumerate_directory_allow_noent (GFile               *dirpath,
                                 const char          *queryargs,
                                 GFileQueryInfoFlags  queryflags,
                                 GFileEnumerator    **out_direnum,
                                 GCancellable        *cancellable,
                                 GError             **error)
{
  g_autoptr(GError) temp_error = NULL;
  g_autoptr(GFileEnumerator) ret_direnum = NULL;

  ret_direnum = g_file_enumerate_children (dirpath, queryargs, queryflags,
                                           cancellable, &temp_error);
  if (!ret_direnum)
    {
      if (g_error_matches (temp_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
        g_clear_error (&temp_error);
      else
        {
          g_propagate_error (error, g_steal_pointer (&temp_error));
          return FALSE;
        }
    }

  if (out_direnum)
    *out_direnum = g_steal_pointer (&ret_direnum);
  return TRUE;
}

static gboolean
add_remotes_from_keyfile (OstreeRepo *self,
                          GKeyFile   *keyfile,
                          GFile      *file,
                          GError    **error)
{
  GQueue queue = G_QUEUE_INIT;
  g_auto(GStrv) groups = NULL;
  gsize length, ii;
  gboolean ret = FALSE;

  g_mutex_lock (&self->remotes_lock);

  groups = g_key_file_get_groups (keyfile, &length);

  for (ii = 0; ii < length; ii++)
    {
      OstreeRemote *remote;

      remote = ostree_remote_new_from_keyfile (keyfile, groups[ii]);

      if (remote != NULL)
        {
          /* Make sure all the remotes in the key file are
           * acceptable before adding any to the OstreeRepo. */
          g_queue_push_tail (&queue, remote);

          if (g_hash_table_contains (self->remotes, remote->name))
            {
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "Multiple specifications found for remote \"%s\"",
                           remote->name);
              goto out;
            }

          if (file != NULL)
            remote->file = g_object_ref (file);
        }
    }

  while (!g_queue_is_empty (&queue))
    {
      OstreeRemote *remote = g_queue_pop_head (&queue);
      g_hash_table_replace (self->remotes, remote->name, remote);
    }

  ret = TRUE;

 out:
  while (!g_queue_is_empty (&queue))
    ostree_remote_unref (g_queue_pop_head (&queue));

  g_mutex_unlock (&self->remotes_lock);

  return ret;
}

static gboolean
append_one_remote_config (OstreeRepo      *self,
                          GFile           *path,
                          GCancellable    *cancellable,
                          GError         **error)
{
  g_autoptr(GKeyFile) remotedata = g_key_file_new ();
  if (!g_key_file_load_from_file (remotedata, gs_file_get_path_cached (path),
                                  0, error))
    return FALSE;

  return add_remotes_from_keyfile (self, remotedata, path, error);
}

static GFile *
get_remotes_d_dir (OstreeRepo          *self,
                   GFile               *sysroot)
{
  g_autoptr(GFile) sysroot_owned = NULL;
  /* Very complicated sysroot logic; this bit breaks the otherwise mostly clean
   * layering between OstreeRepo and OstreeSysroot. First, If a sysroot was
   * provided, use it. Otherwise, check to see whether we reference
   * /ostree/repo, or if not that, see if we have a ref to a sysroot (and it's
   * physical).
   */
  g_autoptr(OstreeSysroot) sysroot_ref = NULL;
  if (sysroot == NULL)
    {
      /* No explicit sysroot?  Let's see if we have a kind */
      switch (self->sysroot_kind)
        {
        case OSTREE_REPO_SYSROOT_KIND_UNKNOWN:
          g_assert_not_reached ();
          break;
        case OSTREE_REPO_SYSROOT_KIND_NO:
          break;
        case OSTREE_REPO_SYSROOT_KIND_IS_SYSROOT_OSTREE:
          sysroot = sysroot_owned = g_file_new_for_path ("/");
          break;
        case OSTREE_REPO_SYSROOT_KIND_VIA_SYSROOT:
          sysroot_ref = (OstreeSysroot*)g_weak_ref_get (&self->sysroot);
          /* Only write to /etc/ostree/remotes.d if we are pointed at a deployment */
          if (sysroot_ref != NULL && !sysroot_ref->is_physical)
            sysroot = ostree_sysroot_get_path (sysroot_ref);
          break;
        }
    }
  /* For backwards compat, also fall back to the sysroot-path variable, which we
   * don't set anymore internally, and I hope no one else uses.
   */
  if (sysroot == NULL && sysroot_ref == NULL)
    sysroot = self->sysroot_dir;

  /* Was the config directory specified? If so, use that with the
   * optional sysroot prepended. If not, return the path in /etc if the
   * sysroot was found and NULL otherwise to use the repo config.
   */
  if (self->remotes_config_dir != NULL)
    {
      if (sysroot == NULL)
        return g_file_new_for_path (self->remotes_config_dir);
      else
        return g_file_resolve_relative_path (sysroot, self->remotes_config_dir);
    }
  else if (sysroot == NULL)
    return NULL;
  else
    return g_file_resolve_relative_path (sysroot, SYSCONF_REMOTES);
}

static gboolean
min_free_space_calculate_reserved_bytes (OstreeRepo *self, guint64 *bytes, GError **error)
{
  guint64 reserved_bytes = 0;

  struct statvfs stvfsbuf;
  if (TEMP_FAILURE_RETRY (fstatvfs (self->repo_dir_fd, &stvfsbuf)) < 0)
    return glnx_throw_errno_prefix (error, "fstatvfs");

  if (self->min_free_space_mb > 0)
    {
      if (self->min_free_space_mb > (G_MAXUINT64 >> 20))
        return glnx_throw (error, "min-free-space value is greater than the maximum allowed value of %" G_GUINT64_FORMAT " bytes",
                           (G_MAXUINT64 >> 20));

      reserved_bytes = self->min_free_space_mb << 20;
    }
  else if (self->min_free_space_percent > 0)
    {
      if (stvfsbuf.f_frsize > (G_MAXUINT64 / stvfsbuf.f_blocks))
        return glnx_throw (error, "Filesystem's size is greater than the maximum allowed value of %" G_GUINT64_FORMAT " bytes",
                           (G_MAXUINT64 / stvfsbuf.f_blocks));

      guint64 total_bytes = (stvfsbuf.f_frsize * stvfsbuf.f_blocks);
      reserved_bytes = ((double)total_bytes) * (self->min_free_space_percent/100.0);
    }

  *bytes = reserved_bytes;
  return TRUE;
}

static gboolean
min_free_space_size_validate_and_convert (OstreeRepo    *self,
                                          const char    *min_free_space_size_str,
                                          GError       **error)
{
  static GRegex *regex;
  static gsize regex_initialized;
  if (g_once_init_enter (&regex_initialized))
    {
      regex = g_regex_new ("^([0-9]+)(G|M|T)B$", 0, 0, NULL);
      g_assert (regex);
      g_once_init_leave (&regex_initialized, 1);
    }

  g_autoptr(GMatchInfo) match = NULL;
  if (!g_regex_match (regex, min_free_space_size_str, 0, &match))
    return glnx_throw (error, "It should be of the format '123MB', '123GB' or '123TB'");

  g_autofree char *size_str = g_match_info_fetch (match, 1);
  g_autofree char *unit = g_match_info_fetch (match, 2);
  guint shifts;

  switch (*unit)
    {
      case 'M':
        shifts = 0;
        break;
      case 'G':
        shifts = 10;
        break;
      case 'T':
        shifts = 20;
        break;
      default:
        g_assert_not_reached ();
    }

  guint64 min_free_space = g_ascii_strtoull (size_str, NULL, 10);
  if (shifts > 0 && g_bit_nth_lsf (min_free_space, 63 - shifts) != -1)
    return glnx_throw (error, "Value was too high");

  self->min_free_space_mb = min_free_space << shifts;

  return TRUE;
}

static gboolean
reload_core_config (OstreeRepo          *self,
                    GCancellable        *cancellable,
                    GError             **error)
{
  g_autofree char *version = NULL;
  g_autofree char *mode = NULL;
  g_autofree char *contents = NULL;
  g_autofree char *parent_repo_path = NULL;
  gboolean is_archive;
  gsize len;

  g_clear_pointer (&self->config, g_key_file_unref);
  self->config = g_key_file_new ();

  contents = glnx_file_get_contents_utf8_at (self->repo_dir_fd, "config", &len,
                                             NULL, error);
  if (!contents)
    return FALSE;
  if (!g_key_file_load_from_data (self->config, contents, len, 0, error))
    {
      g_prefix_error (error, "Couldn't parse config file: ");
      return FALSE;
    }

  version = g_key_file_get_value (self->config, "core", "repo_version", error);
  if (!version)
    return FALSE;

  if (strcmp (version, "1") != 0)
    return glnx_throw (error, "Invalid repository version '%s'", version);

  if (!ot_keyfile_get_boolean_with_default (self->config, "core", "archive",
                                            FALSE, &is_archive, error))
    return FALSE;
  if (is_archive)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
                   "This version of OSTree no longer supports \"archive\" repositories; use archive-z2 instead");
      return FALSE;
    }

  if (!ot_keyfile_get_value_with_default (self->config, "core", "mode",
                                          "bare", &mode, error))
    return FALSE;
  if (!ostree_repo_mode_from_string (mode, &self->mode, error))
    return FALSE;

  if (self->writable)
    {
      if (!ot_keyfile_get_boolean_with_default (self->config, "core", "enable-uncompressed-cache",
                                                TRUE, &self->enable_uncompressed_cache, error))
        return FALSE;
    }
  else
    self->enable_uncompressed_cache = FALSE;

  {
    gboolean do_fsync;

    if (!ot_keyfile_get_boolean_with_default (self->config, "core", "fsync",
                                              TRUE, &do_fsync, error))
      return FALSE;

    if (!do_fsync)
      ostree_repo_set_disable_fsync (self, TRUE);
  }

  if (!ot_keyfile_get_boolean_with_default (self->config, "core", "per-object-fsync",
                                            FALSE, &self->per_object_fsync, error))
    return FALSE;

  /* See https://github.com/ostreedev/ostree/issues/758 */
  if (!ot_keyfile_get_boolean_with_default (self->config, "core", "disable-xattrs",
                                            FALSE, &self->disable_xattrs, error))
    return FALSE;

  { g_autofree char *tmp_expiry_seconds = NULL;

    /* 86400 secs = one day */
    if (!ot_keyfile_get_value_with_default (self->config, "core", "tmp-expiry-secs", "86400",
                                            &tmp_expiry_seconds, error))
      return FALSE;

    self->tmp_expiry_seconds = g_ascii_strtoull (tmp_expiry_seconds, NULL, 10);
  }

  { gboolean locking;
    /* Enabled by default in 2018.05 */
    if (!ot_keyfile_get_boolean_with_default (self->config, "core", "locking",
                                              TRUE, &locking, error))
      return FALSE;
    if (!locking)
      {
        self->lock_timeout_seconds = REPO_LOCK_DISABLED;
      }
    else
      {
        g_autofree char *lock_timeout_seconds = NULL;

        if (!ot_keyfile_get_value_with_default (self->config, "core", "lock-timeout-secs", "30",
                                                &lock_timeout_seconds, error))
          return FALSE;

        self->lock_timeout_seconds = g_ascii_strtoll (lock_timeout_seconds, NULL, 10);
      }
  }

  { g_autofree char *compression_level_str = NULL;

    /* gzip defaults to 6 */
    (void)ot_keyfile_get_value_with_default (self->config, "archive", "zlib-level", NULL,
                                             &compression_level_str, NULL);

    if (compression_level_str)
      /* Ensure level is in [1,9] */
      self->zlib_compression_level = MAX (1, MIN (9, g_ascii_strtoull (compression_level_str, NULL, 10)));
    else
      self->zlib_compression_level = OSTREE_ARCHIVE_DEFAULT_COMPRESSION_LEVEL;
  }

  {
    /* Try to parse both min-free-space-* config options first. If both are absent, fallback on 3% free space.
     * If both are present and are non-zero, use min-free-space-size unconditionally and display a warning.
     */
    if (g_key_file_has_key (self->config, "core", "min-free-space-size", NULL))
      {
        g_autofree char *min_free_space_size_str = NULL;

        if (!ot_keyfile_get_value_with_default (self->config, "core", "min-free-space-size",
                                                NULL, &min_free_space_size_str, error))
          return FALSE;

        /* Validate the string and convert the size to MBs */
        if (!min_free_space_size_validate_and_convert (self, min_free_space_size_str, error))
          return glnx_prefix_error (error, "Invalid min-free-space-size '%s'", min_free_space_size_str);
      }

    if (g_key_file_has_key (self->config, "core", "min-free-space-percent", NULL))
      {
        g_autofree char *min_free_space_percent_str = NULL;

        if (!ot_keyfile_get_value_with_default (self->config, "core", "min-free-space-percent",
                                                NULL, &min_free_space_percent_str, error))
          return FALSE;

        self->min_free_space_percent = g_ascii_strtoull (min_free_space_percent_str, NULL, 10);
        if (self->min_free_space_percent > 99)
          return glnx_throw (error, "Invalid min-free-space-percent '%s'", min_free_space_percent_str);
      }
    else if (!g_key_file_has_key (self->config, "core", "min-free-space-size", NULL))
      {
        /* Default fallback of 3% free space. If changing this, be sure to change the man page too */
        self->min_free_space_percent = 3;
        self->min_free_space_mb = 0;
      }

    if (self->min_free_space_percent != 0 && self->min_free_space_mb != 0)
      {
        self->min_free_space_percent = 0;
        g_debug ("Both min-free-space-percent and -size are mentioned in config. Enforcing min-free-space-size check only.");
      }
  }

  if (!_ostree_repo_parse_fsverity_config (self, error))
    return FALSE;
  
  {
    g_clear_pointer (&self->collection_id, g_free);
    if (!ot_keyfile_get_value_with_default (self->config, "core", "collection-id",
                                            NULL, &self->collection_id, NULL))
      return FALSE;
  }

  if (!ot_keyfile_get_value_with_default (self->config, "core", "parent",
                                          NULL, &parent_repo_path, error))
    return FALSE;

  if (parent_repo_path && parent_repo_path[0])
    {
      g_autoptr(GFile) parent_repo_f = g_file_new_for_path (parent_repo_path);

      g_clear_object (&self->parent_repo);
      self->parent_repo = ostree_repo_new (parent_repo_f);

      if (!ostree_repo_open (self->parent_repo, cancellable, error))
        {
          g_prefix_error (error, "While checking parent repository '%s': ",
                          gs_file_get_path_cached (parent_repo_f));
          return FALSE;
        }
    }

  /* By default, only add remotes in a remotes config directory for
   * system repos. This is to preserve legacy behavior for non-system
   * repos that specify a remotes config dir (flatpak).
   */
  { gboolean is_system = ostree_repo_is_system (self);

    if (!ot_keyfile_get_boolean_with_default (self->config, "core", "add-remotes-config-dir",
                                              is_system, &self->add_remotes_config_dir, error))
      return FALSE;
  }

  { g_autofree char *payload_threshold = NULL;

    if (!ot_keyfile_get_value_with_default (self->config, "core", "payload-link-threshold", "-1",
                                            &payload_threshold, error))
      return FALSE;

    self->payload_link_threshold = g_ascii_strtoull (payload_threshold, NULL, 10);
  }

  { g_auto(GStrv) configured_finders = NULL;
    g_autoptr(GError) local_error = NULL;

    configured_finders = g_key_file_get_string_list (self->config, "core", "default-repo-finders",
                                                     NULL, &local_error);
    if (g_error_matches (local_error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_KEY_NOT_FOUND))
      g_clear_error (&local_error);
    else if (local_error != NULL)
      {
        g_propagate_error (error, g_steal_pointer (&local_error));
        return FALSE;
      }

    if (configured_finders != NULL && *configured_finders == NULL)
      return glnx_throw (error, "Invalid empty default-repo-finders configuration");

    for (char **iter = configured_finders; iter && *iter; iter++)
      {
        const char *repo_finder = *iter;

        if (strcmp (repo_finder, "config") != 0 &&
            strcmp (repo_finder, "lan") != 0 &&
            strcmp (repo_finder, "mount") != 0)
          return glnx_throw (error, "Invalid configured repo-finder '%s'", repo_finder);
      }

    /* Fall back to a default set of finders */
    if (configured_finders == NULL)
      configured_finders = g_strsplit ("config;mount", ";", -1);

    g_clear_pointer (&self->repo_finders, g_strfreev);
    self->repo_finders = g_steal_pointer (&configured_finders);
  }

  return TRUE;
}

static gboolean
reload_remote_config (OstreeRepo          *self,
                      GCancellable        *cancellable,
                      GError             **error)
{

  g_mutex_lock (&self->remotes_lock);
  g_hash_table_remove_all (self->remotes);
  g_mutex_unlock (&self->remotes_lock);

  if (!add_remotes_from_keyfile (self, self->config, NULL, error))
    return FALSE;

  g_autoptr(GFile) remotes_d = get_remotes_d_dir (self, NULL);
  if (remotes_d == NULL)
    return TRUE;

  g_autoptr(GFileEnumerator) direnum = NULL;
  if (!enumerate_directory_allow_noent (remotes_d, OSTREE_GIO_FAST_QUERYINFO, 0,
                                        &direnum,
                                        cancellable, error))
    return FALSE;
  if (direnum)
    {
      while (TRUE)
        {
          GFileInfo *file_info;
          GFile *path;
          const char *name;
          guint32 type;

          if (!g_file_enumerator_iterate (direnum, &file_info, &path,
                                          NULL, error))
            return FALSE;
          if (file_info == NULL)
            break;

          name = g_file_info_get_attribute_byte_string (file_info, "standard::name");
          type = g_file_info_get_attribute_uint32 (file_info, "standard::type");

          if (type == G_FILE_TYPE_REGULAR &&
              g_str_has_suffix (name, ".conf"))
            {
              if (!append_one_remote_config (self, path, cancellable, error))
                return FALSE;
            }
        }
    }

  return TRUE;
}

static gboolean
reload_sysroot_config (OstreeRepo          *self,
                       GCancellable        *cancellable,
                       GError             **error)
{
  g_autofree char *bootloader = NULL;

  if (!ot_keyfile_get_value_with_default_group_optional (self->config, "sysroot",
                                                         "bootloader", "auto",
                                                         &bootloader, error))
    return FALSE;

  /* TODO: possibly later add support for specifying a generic bootloader
   * binary "x" in /usr/lib/ostree/bootloaders/x). See:
   * https://github.com/ostreedev/ostree/issues/1719
   * https://github.com/ostreedev/ostree/issues/1801
   */
  for (int i = 0; CFG_SYSROOT_BOOTLOADER_OPTS_STR[i]; i++)
    {
      if (g_str_equal (bootloader, CFG_SYSROOT_BOOTLOADER_OPTS_STR[i]))
        {
          self->bootloader = (OstreeCfgSysrootBootloaderOpt) i;
          return TRUE;
        }
    }

  return glnx_throw (error, "Invalid bootloader configuration: '%s'", bootloader);
}

/**
 * ostree_repo_reload_config:
 * @self: repo
 * @cancellable: cancellable
 * @error: error
 *
 * By default, an #OstreeRepo will cache the remote configuration and its
 * own repo/config data.  This API can be used to reload it.
 *
 * Since: 2017.2
 */
gboolean
ostree_repo_reload_config (OstreeRepo          *self,
                           GCancellable        *cancellable,
                           GError             **error)
{
  if (!reload_core_config (self, cancellable, error))
    return FALSE;
  if (!reload_remote_config (self, cancellable, error))
    return FALSE;
  if (!reload_sysroot_config (self, cancellable, error))
    return FALSE;
  return TRUE;
}

gboolean
ostree_repo_open (OstreeRepo    *self,
                  GCancellable  *cancellable,
                  GError       **error)
{
  GLNX_AUTO_PREFIX_ERROR ("opening repo", error);

  struct stat stbuf;

  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  if (self->inited)
    return TRUE;

  /* We use a directory of the form `staging-${BOOT_ID}-${RANDOM}`
   * where if the ${BOOT_ID} doesn't match, we know file contents
   * possibly haven't been sync'd to disk and need to be discarded.
   */
  { const char *env_bootid = getenv ("OSTREE_BOOTID");
    g_autofree char *boot_id = NULL;

    if (env_bootid != NULL)
      boot_id = g_strdup (env_bootid);
    else
      {
        if (!g_file_get_contents ("/proc/sys/kernel/random/boot_id",
                                  &boot_id,
                                  NULL,
                                  error))
          return FALSE;
        g_strdelimit (boot_id, "\n", '\0');
      }

    self->stagedir_prefix = g_strconcat (OSTREE_REPO_TMPDIR_STAGING, boot_id, "-", NULL);
  }

  if (self->repo_dir_fd == -1)
    {
      g_assert (self->repodir);
      if (!glnx_opendirat (AT_FDCWD, gs_file_get_path_cached (self->repodir), TRUE,
                           &self->repo_dir_fd, error))
        return FALSE;
    }

  if (!glnx_fstat (self->repo_dir_fd, &stbuf, error))
    return FALSE;
  self->device = stbuf.st_dev;
  self->inode = stbuf.st_ino;

  if (!glnx_opendirat (self->repo_dir_fd, "objects", TRUE,
                       &self->objects_dir_fd, error))
    return FALSE;

  self->writable = faccessat (self->objects_dir_fd, ".", W_OK, 0) == 0;
  if (!self->writable)
    {
      /* This is returned through ostree_repo_is_writable(). */
      glnx_set_error_from_errno (&self->writable_error);
      /* Note - we don't return this error yet! */
    }

  if (!glnx_fstat (self->objects_dir_fd, &stbuf, error))
    return FALSE;
  self->owner_uid = stbuf.st_uid;

  if (self->writable)
    {
      /* Always try to recreate the tmpdir to be nice to people
       * who are looking to free up space.
       *
       * https://github.com/ostreedev/ostree/issues/1018
       */
      if (mkdirat (self->repo_dir_fd, "tmp", DEFAULT_DIRECTORY_MODE) == -1)
        {
          if (G_UNLIKELY (errno != EEXIST))
            return glnx_throw_errno_prefix (error, "mkdir(tmp)");
        }
    }

  if (!glnx_opendirat (self->repo_dir_fd, "tmp", TRUE, &self->tmp_dir_fd, error))
    return FALSE;

  if (self->writable && getenv ("OSTREE_SKIP_CACHE") == NULL)
    {
      if (!glnx_shutil_mkdir_p_at (self->tmp_dir_fd, _OSTREE_CACHE_DIR, DEFAULT_DIRECTORY_MODE, cancellable, error))
        return FALSE;

      if (!glnx_opendirat (self->tmp_dir_fd, _OSTREE_CACHE_DIR, TRUE, &self->cache_dir_fd, error))
        return FALSE;
    }

  /* If we weren't created via ostree_sysroot_get_repo(), for backwards
   * compatibility we need to figure out now whether or not we refer to the
   * system repo.  See also ostree-sysroot.c.
   */
  if (self->sysroot_kind == OSTREE_REPO_SYSROOT_KIND_UNKNOWN)
    {
      struct stat system_stbuf;
      /* Ignore any errors if we can't access /ostree/repo */
      if (fstatat (AT_FDCWD, "/ostree/repo", &system_stbuf, 0) == 0)
        {
          /* Are we the same as /ostree/repo? */
          if (self->device == system_stbuf.st_dev &&
              self->inode == system_stbuf.st_ino)
            self->sysroot_kind = OSTREE_REPO_SYSROOT_KIND_IS_SYSROOT_OSTREE;
          else
            self->sysroot_kind = OSTREE_REPO_SYSROOT_KIND_NO;
        }
      else
        self->sysroot_kind = OSTREE_REPO_SYSROOT_KIND_NO;
    }

  if (!ostree_repo_reload_config (self, cancellable, error))
    return FALSE;

  self->inited = TRUE;
  return TRUE;
}

/**
 * ostree_repo_set_disable_fsync:
 * @self: An #OstreeRepo
 * @disable_fsync: If %TRUE, do not fsync
 *
 * Disable requests to fsync() to stable storage during commits.  This
 * option should only be used by build system tools which are creating
 * disposable virtual machines, or have higher level mechanisms for
 * ensuring data consistency.
 */
void
ostree_repo_set_disable_fsync (OstreeRepo    *self,
                               gboolean       disable_fsync)
{
  self->disable_fsync = disable_fsync;
}

/**
 * ostree_repo_set_cache_dir:
 * @self: An #OstreeRepo
 * @dfd: directory fd
 * @path: subpath in @dfd
 * @cancellable: a #GCancellable
 * @error: a #GError
 *
 * Set a custom location for the cache directory used for e.g.
 * per-remote summary caches. Setting this manually is useful when
 * doing operations on a system repo as a user because you don't have
 * write permissions in the repo, where the cache is normally stored.
 *
 * Since: 2016.5
 */
gboolean
ostree_repo_set_cache_dir (OstreeRepo    *self,
                           int            dfd,
                           const char    *path,
                           GCancellable  *cancellable,
                           GError        **error)
{
  glnx_autofd int fd = -1;
  if (!glnx_opendirat (dfd, path, TRUE, &fd, error))
    return FALSE;

  glnx_close_fd (&self->cache_dir_fd);
  self->cache_dir_fd = glnx_steal_fd (&fd);

  return TRUE;
}

/**
 * ostree_repo_get_disable_fsync:
 * @self: An #OstreeRepo
 *
 * For more information see ostree_repo_set_disable_fsync().
 *
 * Returns: Whether or not fsync() is enabled for this repo.
 */
gboolean
ostree_repo_get_disable_fsync (OstreeRepo    *self)
{
  return self->disable_fsync;
}

/* Replace the contents of a file, honoring the repository's fsync
 * policy.
 */
gboolean
_ostree_repo_file_replace_contents (OstreeRepo    *self,
                                    int            dfd,
                                    const char    *path,
                                    const guint8   *buf,
                                    gsize          len,
                                    GCancellable  *cancellable,
                                    GError       **error)
{
  return glnx_file_replace_contents_at (dfd, path, buf, len,
                                        self->disable_fsync ? GLNX_FILE_REPLACE_NODATASYNC : GLNX_FILE_REPLACE_DATASYNC_NEW,
                                        cancellable, error);
}

/**
 * ostree_repo_get_path:
 * @self: Repo
 *
 * Note that since the introduction of ostree_repo_open_at(), this function may
 * return a process-specific path in `/proc` if the repository was created using
 * that API. In general, you should avoid use of this API.
 *
 * Returns: (transfer none): Path to repo
 */
GFile *
ostree_repo_get_path (OstreeRepo  *self)
{
  /* Did we have an abspath?  Return it */
  if (self->repodir)
    return self->repodir;
  /* Lazily create a fd-relative path */
  if (!self->repodir_fdrel)
    self->repodir_fdrel = ot_fdrel_to_gfile (self->repo_dir_fd, ".");
  return self->repodir_fdrel;
}

/**
 * ostree_repo_get_dfd:
 * @self: Repo
 *
 * In some cases it's useful for applications to access the repository
 * directly; for example, writing content into `repo/tmp` ensures it's
 * on the same filesystem.  Another case is detecting the mtime on the
 * repository (to see whether a ref was written).
 *
 * Returns: File descriptor for repository root - owned by @self
 * Since: 2016.4
 */
int
ostree_repo_get_dfd (OstreeRepo  *self)
{
  g_return_val_if_fail (self->repo_dir_fd != -1, -1);
  return self->repo_dir_fd;
}

/**
 * ostree_repo_hash:
 * @self: an #OstreeRepo
 *
 * Calculate a hash value for the given open repository, suitable for use when
 * putting it into a hash table. It is an error to call this on an #OstreeRepo
 * which is not yet open, as a persistent hash value cannot be calculated until
 * the repository is open and the inode of its root directory has been loaded.
 *
 * This function does no I/O.
 *
 * Returns: hash value for the #OstreeRepo
 * Since: 2017.12
 */
guint
ostree_repo_hash (OstreeRepo *self)
{
  g_return_val_if_fail (OSTREE_IS_REPO (self), 0);

  /* We cannot hash non-open repositories, since their hash value would change
   * once they’re opened, resulting in false lookup misses and the inability to
   * remove them from a hash table. */
  g_assert (self->repo_dir_fd >= 0);

  /* device and inode numbers are distributed fairly uniformly, so we can’t
   * do much better than just combining them. No need to rehash to even out
   * the distribution. */
  return (self->device ^ self->inode);
}

/**
 * ostree_repo_equal:
 * @a: an #OstreeRepo
 * @b: an #OstreeRepo
 *
 * Check whether two opened repositories are the same on disk: if their root
 * directories are the same inode. If @a or @b are not open yet (due to
 * ostree_repo_open() not being called on them yet), %FALSE will be returned.
 *
 * Returns: %TRUE if @a and @b are the same repository on disk, %FALSE otherwise
 * Since: 2017.12
 */
gboolean
ostree_repo_equal (OstreeRepo *a,
                   OstreeRepo *b)
{
  g_return_val_if_fail (OSTREE_IS_REPO (a), FALSE);
  g_return_val_if_fail (OSTREE_IS_REPO (b), FALSE);

  if (a->repo_dir_fd < 0 || b->repo_dir_fd < 0)
    return FALSE;

  return (a->device == b->device && a->inode == b->inode);
}

OstreeRepoMode
ostree_repo_get_mode (OstreeRepo  *self)
{
  g_assert (self != NULL);
  g_assert (self->inited);

  return self->mode;
}

/**
 * ostree_repo_get_min_free_space_bytes:
 * @self: Repo
 * @out_reserved_bytes: (out): Location to store the result
 * @error: Return location for a #GError
 *
 * Determine the number of bytes of free disk space that are reserved according
 * to the repo config and return that number in @out_reserved_bytes. See the
 * documentation for the core.min-free-space-size and
 * core.min-free-space-percent repo config options.
 *
 * Returns: %TRUE on success, %FALSE otherwise.
 * Since: 2018.9
 */
gboolean
ostree_repo_get_min_free_space_bytes (OstreeRepo  *self, guint64 *out_reserved_bytes, GError **error)
{
  g_return_val_if_fail (OSTREE_IS_REPO (self), FALSE);
  g_return_val_if_fail (out_reserved_bytes != NULL, FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  if (!min_free_space_calculate_reserved_bytes (self, out_reserved_bytes, error))
    return glnx_prefix_error (error, "Error calculating min-free-space bytes");

  return TRUE;
}

/**
 * ostree_repo_get_parent:
 * @self: Repo
 *
 * Before this function can be used, ostree_repo_init() must have been
 * called.
 *
 * Returns: (transfer none): Parent repository, or %NULL if none
 */
OstreeRepo *
ostree_repo_get_parent (OstreeRepo  *self)
{
  return self->parent_repo;
}

static gboolean
list_loose_objects_at (OstreeRepo             *self,
                       GVariant               *dummy_value,
                       GHashTable             *inout_objects,
                       int                     dfd,
                       const char             *prefix,
                       const char             *commit_starting_with,
                       GCancellable           *cancellable,
                       GError                **error)
{
  GVariant *key;

  g_auto(GLnxDirFdIterator) dfd_iter = { 0, };
  gboolean exists;
  if (!ot_dfd_iter_init_allow_noent (dfd, prefix, &dfd_iter, &exists, error))
    return FALSE;
  /* Note early return */
  if (!exists)
    return TRUE;

  while (TRUE)
    {
      struct dirent *dent;

      if (!glnx_dirfd_iterator_next_dent (&dfd_iter, &dent, cancellable, error))
        return FALSE;
      if (dent == NULL)
        break;

      const char *name = dent->d_name;
      if (strcmp (name, ".") == 0 ||
          strcmp (name, "..") == 0)
        continue;

      const char *dot = strrchr (name, '.');
      if (!dot)
        continue;

      OstreeObjectType objtype;
      if ((self->mode == OSTREE_REPO_MODE_ARCHIVE
           && strcmp (dot, ".filez") == 0) ||
          ((_ostree_repo_mode_is_bare (self->mode))
           && strcmp (dot, ".file") == 0))
        objtype = OSTREE_OBJECT_TYPE_FILE;
      else if (strcmp (dot, ".dirtree") == 0)
        objtype = OSTREE_OBJECT_TYPE_DIR_TREE;
      else if (strcmp (dot, ".dirmeta") == 0)
        objtype = OSTREE_OBJECT_TYPE_DIR_META;
      else if (strcmp (dot, ".commit") == 0)
        objtype = OSTREE_OBJECT_TYPE_COMMIT;
      else if (strcmp (dot, ".payload-link") == 0)
        objtype = OSTREE_OBJECT_TYPE_PAYLOAD_LINK;
      else
        continue;

      if ((dot - name) != 62)
        continue;

      char buf[OSTREE_SHA256_STRING_LEN+1];

      memcpy (buf, prefix, 2);
      memcpy (buf + 2, name, 62);
      buf[sizeof(buf)-1] = '\0';

      /* if we passed in a "starting with" argument, then
         we only want to return .commit objects with a checksum
         that matches the commit_starting_with argument */
      if (commit_starting_with)
        {
          /* object is not a commit, do not add to array */
          if (objtype != OSTREE_OBJECT_TYPE_COMMIT)
              continue;

          /* commit checksum does not match "starting with", do not add to array */
          if (!g_str_has_prefix (buf, commit_starting_with))
            continue;
        }

      key = ostree_object_name_serialize (buf, objtype);

      /* transfer ownership */
      g_hash_table_replace (inout_objects, g_variant_ref_sink (key),
                            g_variant_ref (dummy_value));
    }

  return TRUE;
}

static gboolean
list_loose_objects (OstreeRepo                     *self,
                    GHashTable                     *inout_objects,
                    const char                     *commit_starting_with,
                    GCancellable                   *cancellable,
                    GError                        **error)
{
  static const gchar hexchars[] = "0123456789abcdef";
  // For unfortunate historical reasons we emit this dummy value.
  g_autoptr(GVariant) dummy_loose_object_variant =
    g_variant_ref_sink (g_variant_new ("(b@as)", TRUE, g_variant_new_strv (NULL, 0)));

  for (guint c = 0; c < 256; c++)
    {
      char buf[3];
      buf[0] = hexchars[c >> 4];
      buf[1] = hexchars[c & 0xF];
      buf[2] = '\0';
      if (!list_loose_objects_at (self, dummy_loose_object_variant,
                                  inout_objects, self->objects_dir_fd, buf,
                                  commit_starting_with,
                                  cancellable, error))
        return FALSE;
    }

  return TRUE;
}

static gboolean
load_metadata_internal (OstreeRepo       *self,
                        OstreeObjectType  objtype,
                        const char       *sha256,
                        gboolean          error_if_not_found,
                        GVariant        **out_variant,
                        GInputStream    **out_stream,
                        guint64          *out_size,
                        OstreeRepoCommitState *out_state,
                        GCancellable     *cancellable,
                        GError          **error)
{
  char loose_path_buf[_OSTREE_LOOSE_PATH_MAX];
  glnx_autofd int fd = -1;
  g_autoptr(GInputStream) ret_stream = NULL;
  g_autoptr(GVariant) ret_variant = NULL;

  g_return_val_if_fail (OSTREE_OBJECT_TYPE_IS_META (objtype), FALSE);
  g_return_val_if_fail (objtype == OSTREE_OBJECT_TYPE_COMMIT || out_state == NULL, FALSE);

  /* Ensure this is set to NULL if we didn't find the object */
  if (out_variant)
    *out_variant = NULL;

  /* Special caching for dirmeta objects, since they're commonly referenced many
   * times.
   */
  const gboolean is_dirmeta_cachable =
    (objtype == OSTREE_OBJECT_TYPE_DIR_META && out_variant && !out_stream);
  if (is_dirmeta_cachable)
    {
      GMutex *lock = &self->cache_lock;
      g_mutex_lock (lock);
      GVariant *cache_hit = NULL;
      /* Look it up, if we have a cache */
      if (self->dirmeta_cache)
        cache_hit = g_hash_table_lookup (self->dirmeta_cache, sha256);
      if (cache_hit)
        *out_variant = g_variant_ref (cache_hit);
      g_mutex_unlock (lock);
      if (cache_hit)
        return TRUE;
    }

  _ostree_loose_path (loose_path_buf, sha256, objtype, self->mode);

 if (!ot_openat_ignore_enoent (self->objects_dir_fd, loose_path_buf, &fd,
                               error))
    return FALSE;

  if (fd < 0 && self->commit_stagedir.initialized)
    {
      if (!ot_openat_ignore_enoent (self->commit_stagedir.fd, loose_path_buf, &fd,
                                    error))
        return FALSE;
    }

  if (fd != -1)
    {
      struct stat stbuf;
      if (!glnx_fstat (fd, &stbuf, error))
        return FALSE;
      if (out_variant)
        {
          if (!ot_variant_read_fd (fd, 0, ostree_metadata_variant_type (objtype), TRUE,
                                   &ret_variant, error))
            return FALSE;

          /* Now, let's put it in the cache */
          if (is_dirmeta_cachable)
            {
              GMutex *lock = &self->cache_lock;
              g_mutex_lock (lock);
              if (self->dirmeta_cache)
                g_hash_table_replace (self->dirmeta_cache, g_strdup (sha256), g_variant_ref (ret_variant));
              g_mutex_unlock (lock);
            }
        }
      else if (out_stream)
        {
          ret_stream = g_unix_input_stream_new (fd, TRUE);
          if (!ret_stream)
            return FALSE;
          fd = -1; /* Transfer ownership */
        }

      if (out_size)
        *out_size = stbuf.st_size;

      if (out_state)
        {
          g_autofree char *commitpartial_path = _ostree_get_commitpartial_path (sha256);
          *out_state = 0;

          glnx_autofd int commitpartial_fd = -1;
          if (!ot_openat_ignore_enoent (self->repo_dir_fd, commitpartial_path, &commitpartial_fd, error))
            return FALSE;
          if (commitpartial_fd != -1)
            {
              *out_state |= OSTREE_REPO_COMMIT_STATE_PARTIAL;
               char reason;
               if (read (commitpartial_fd, &reason, 1) == 1)
                 {
                   if (reason == 'f')
                     *out_state |= OSTREE_REPO_COMMIT_STATE_FSCK_PARTIAL;
                 }
            }
        }
    }
  else if (self->parent_repo)
    {
      /* Directly recurse to simplify out parameters */
      return load_metadata_internal (self->parent_repo, objtype, sha256, error_if_not_found,
                                     out_variant, out_stream, out_size, out_state,
                                     cancellable, error);
    }
  else if (error_if_not_found)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
                   "No such metadata object %s.%s",
                   sha256, ostree_object_type_to_string (objtype));
      return FALSE;
    }

  ot_transfer_out_value (out_variant, &ret_variant);
  ot_transfer_out_value (out_stream, &ret_stream);
  return TRUE;
}

static GVariant  *
filemeta_to_stat (struct stat *stbuf,
                  GVariant   *metadata)
{
  guint32 uid, gid, mode;
  GVariant *xattrs;

  g_variant_get (metadata, "(uuu@a(ayay))",
                 &uid, &gid, &mode, &xattrs);
  stbuf->st_uid = GUINT32_FROM_BE (uid);
  stbuf->st_gid = GUINT32_FROM_BE (gid);
  stbuf->st_mode = GUINT32_FROM_BE (mode);

  return xattrs;
}

static gboolean
repo_load_file_archive (OstreeRepo *self,
                        const char         *checksum,
                        GInputStream      **out_input,
                        GFileInfo         **out_file_info,
                        GVariant          **out_xattrs,
                        GCancellable       *cancellable,
                        GError            **error)
{
  struct stat stbuf;
  char loose_path_buf[_OSTREE_LOOSE_PATH_MAX];
  _ostree_loose_path (loose_path_buf, checksum, OSTREE_OBJECT_TYPE_FILE, self->mode);

  glnx_autofd int fd = -1;
  if (!ot_openat_ignore_enoent (self->objects_dir_fd, loose_path_buf, &fd,
                                error))
    return FALSE;

  if (fd < 0 && self->commit_stagedir.initialized)
    {
      if (!ot_openat_ignore_enoent (self->commit_stagedir.fd, loose_path_buf, &fd,
                                    error))
        return FALSE;
    }

  if (fd != -1)
    {
      if (!glnx_fstat (fd, &stbuf, error))
        return FALSE;

      g_autoptr(GInputStream) tmp_stream = g_unix_input_stream_new (glnx_steal_fd (&fd), TRUE);
      /* Note return here */
      return ostree_content_stream_parse (TRUE, tmp_stream, stbuf.st_size, TRUE,
                                          out_input, out_file_info, out_xattrs,
                                          cancellable, error);
    }
  else if (self->parent_repo)
    {
      return ostree_repo_load_file (self->parent_repo, checksum,
                                    out_input, out_file_info, out_xattrs,
                                    cancellable, error);
    }
  else
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
                   "Couldn't find file object '%s'", checksum);
      return FALSE;
    }
}

static GVariant *
_ostree_repo_read_xattrs_file_link (OstreeRepo   *self,
                                    const char   *checksum,
                                    GCancellable *cancellable,
                                    GError      **error)
{
  g_assert (self != NULL);
  g_assert (checksum != NULL);

  char xattr_path[_OSTREE_LOOSE_PATH_MAX];
  _ostree_loose_path (xattr_path, checksum, OSTREE_OBJECT_TYPE_FILE_XATTRS_LINK, self->mode);

  g_autoptr(GVariant) xattrs = NULL;
  glnx_autofd int fd = -1;
  if (!glnx_openat_rdonly (self->objects_dir_fd, xattr_path, FALSE, &fd, error))
    return FALSE;

  g_assert (fd >= 0);
  if (!ot_variant_read_fd (fd, 0, G_VARIANT_TYPE ("a(ayay)"), TRUE,
                           &xattrs, error))
    return glnx_prefix_error_null (error, "Deserializing xattrs content");

  g_assert (xattrs != NULL);
  return g_steal_pointer (&xattrs);
}

gboolean
_ostree_repo_load_file_bare (OstreeRepo         *self,
                             const char         *checksum,
                             int                *out_fd,
                             struct stat        *out_stbuf,
                             char              **out_symlink,
                             GVariant          **out_xattrs,
                             GCancellable       *cancellable,
                             GError            **error)
{
  /* The bottom case recursing on the parent repo */
  if (self == NULL)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
                   "Couldn't find file object '%s'", checksum);
      return FALSE;
    }

  const char *errprefix = glnx_strjoina ("Opening content object ", checksum);
  GLNX_AUTO_PREFIX_ERROR (errprefix, error);

  struct stat stbuf;
  glnx_autofd int fd = -1;
  g_autofree char *ret_symlink = NULL;
  g_autoptr(GVariant) ret_xattrs = NULL;
  char loose_path_buf[_OSTREE_LOOSE_PATH_MAX];
  _ostree_loose_path (loose_path_buf, checksum, OSTREE_OBJECT_TYPE_FILE, self->mode);

  /* Do a fstatat() and find the object directory that contains this object */
  int objdir_fd = self->objects_dir_fd;
  int res;
  if ((res = TEMP_FAILURE_RETRY (fstatat (objdir_fd, loose_path_buf, &stbuf, AT_SYMLINK_NOFOLLOW))) < 0
      && errno == ENOENT && self->commit_stagedir.initialized)
    {
      objdir_fd = self->commit_stagedir.fd;
      res = TEMP_FAILURE_RETRY (fstatat (objdir_fd, loose_path_buf, &stbuf, AT_SYMLINK_NOFOLLOW));
    }
  if (res < 0 && errno != ENOENT)
    return glnx_throw_errno_prefix (error, "fstat");
  else if (res < 0)
    {
      g_assert (errno == ENOENT);
      return _ostree_repo_load_file_bare (self->parent_repo, checksum, out_fd,
                                          out_stbuf, out_symlink, out_xattrs,
                                          cancellable, error);
    }

  const gboolean need_open = (out_fd ||
                              (out_xattrs && self->mode == OSTREE_REPO_MODE_BARE) ||
                              self->mode == OSTREE_REPO_MODE_BARE_USER);
  /* If it's a regular file and we're requested to return the fd, do it now. As
   * a special case in bare-user, we always do an open, since the stat() metadata
   * lives there.
   */
  if (need_open && S_ISREG (stbuf.st_mode))
    {
      fd = openat (objdir_fd, loose_path_buf, O_CLOEXEC | O_RDONLY);
      if (fd < 0)
        return glnx_throw_errno_prefix (error, "openat");
    }

  if (!(S_ISREG (stbuf.st_mode) || S_ISLNK (stbuf.st_mode)))
    return glnx_throw (error, "Not a regular file or symlink");

  /* In the non-bare-user case, gather symlink info if requested */
  if (self->mode != OSTREE_REPO_MODE_BARE_USER
      && S_ISLNK (stbuf.st_mode) && out_symlink)
    {
      ret_symlink = glnx_readlinkat_malloc (objdir_fd, loose_path_buf,
                                            cancellable, error);
      if (!ret_symlink)
        return FALSE;
    }

  if (self->mode == OSTREE_REPO_MODE_BARE_USER)
    {
      g_autoptr(GBytes) bytes = glnx_fgetxattr_bytes (fd, "user.ostreemeta", error);
      if (bytes == NULL)
        return FALSE;

      g_autoptr(GVariant) metadata = g_variant_ref_sink (g_variant_new_from_bytes (OSTREE_FILEMETA_GVARIANT_FORMAT,
                                                                                   bytes, FALSE));
      ret_xattrs = filemeta_to_stat (&stbuf, metadata);
      if (S_ISLNK (stbuf.st_mode))
        {
          if (out_symlink)
            {
              char targetbuf[PATH_MAX+1];
              gsize target_size;
              g_autoptr(GInputStream) target_input = g_unix_input_stream_new (fd, FALSE);
              if (!g_input_stream_read_all (target_input, targetbuf, sizeof (targetbuf),
                                            &target_size, cancellable, error))
                return FALSE;

              ret_symlink = g_strndup (targetbuf, target_size);
            }
          /* In the symlink case, we don't want to return the bare-user fd */
          glnx_close_fd (&fd);
        }
    }
  else if (self->mode == OSTREE_REPO_MODE_BARE_USER_ONLY)
    {
      /* Canonical info is: uid/gid is 0 and no xattrs, which
         might be wrong and thus not validate correctly, but
         at least we report something consistent. */
      stbuf.st_uid = stbuf.st_gid = 0;

      if (out_xattrs)
        {
          GVariantBuilder builder;
          g_variant_builder_init (&builder, G_VARIANT_TYPE ("a(ayay)"));
          ret_xattrs = g_variant_ref_sink (g_variant_builder_end (&builder));
        }
    }
  else if (self->mode == OSTREE_REPO_MODE_BARE)
    {
      if (S_ISREG (stbuf.st_mode) && out_xattrs)
        {
          if (self->disable_xattrs)
            ret_xattrs = g_variant_ref_sink (g_variant_new_array (G_VARIANT_TYPE ("(ayay)"), NULL, 0));
          else 
            {
              ret_xattrs = ostree_fs_get_all_xattrs (fd, cancellable, error);
              if (!ret_xattrs)
                return FALSE;
            }
        }
      else if (S_ISLNK (stbuf.st_mode) && out_xattrs)
        {
          if (self->disable_xattrs)
            ret_xattrs = g_variant_ref_sink (g_variant_new_array (G_VARIANT_TYPE ("(ayay)"), NULL, 0));
          else if (!glnx_dfd_name_get_all_xattrs (objdir_fd, loose_path_buf,
                                                  &ret_xattrs,
                                                  cancellable, error))
            return FALSE;
        }
    }
  else if (self->mode == OSTREE_REPO_MODE_BARE_SPLIT_XATTRS)
    {
      if (out_xattrs)
        {
          ret_xattrs = _ostree_repo_read_xattrs_file_link(self, checksum, cancellable, error);
          if (ret_xattrs == NULL)
            return FALSE;
        }
    }
  else
    {
      g_assert_not_reached ();
    }

  if (out_fd)
    *out_fd = glnx_steal_fd (&fd);
  if (out_stbuf)
    *out_stbuf = stbuf;
  ot_transfer_out_value (out_symlink, &ret_symlink);
  ot_transfer_out_value (out_xattrs, &ret_xattrs);
  return TRUE;
}

/**
 * ostree_repo_load_file:
 * @self: Repo
 * @checksum: ASCII SHA256 checksum
 * @out_input: (out) (optional) (nullable): File content
 * @out_file_info: (out) (optional) (nullable): File information
 * @out_xattrs: (out) (optional) (nullable): Extended attributes
 * @cancellable: Cancellable
 * @error: Error
 *
 * Load content object, decomposing it into three parts: the actual
 * content (for regular files), the metadata, and extended attributes.
 */
gboolean
ostree_repo_load_file (OstreeRepo         *self,
                       const char         *checksum,
                       GInputStream      **out_input,
                       GFileInfo         **out_file_info,
                       GVariant          **out_xattrs,
                       GCancellable       *cancellable,
                       GError            **error)
{
  if (self->mode == OSTREE_REPO_MODE_ARCHIVE)
    return repo_load_file_archive (self, checksum, out_input, out_file_info, out_xattrs,
                                   cancellable, error);
  else
    {
      glnx_autofd int fd = -1;
      struct stat stbuf;
      g_autofree char *symlink_target = NULL;
      g_autoptr(GVariant) ret_xattrs = NULL;
      if (!_ostree_repo_load_file_bare (self, checksum,
                                        out_input ? &fd : NULL,
                                        out_file_info ? &stbuf : NULL,
                                        out_file_info ? &symlink_target : NULL,
                                        out_xattrs ? &ret_xattrs : NULL,
                                        cancellable, error))
        return FALSE;

      /* Convert fd → GInputStream and struct stat → GFileInfo */
      if (out_input)
        {
          if (fd != -1)
            *out_input = g_unix_input_stream_new (glnx_steal_fd (&fd), TRUE);
          else
            *out_input = NULL;
        }
      if (out_file_info)
        {
          *out_file_info = _ostree_stbuf_to_gfileinfo (&stbuf);
          if (S_ISLNK (stbuf.st_mode))
            g_file_info_set_symlink_target (*out_file_info, symlink_target);
          else
            g_assert (S_ISREG (stbuf.st_mode));
        }

      ot_transfer_out_value (out_xattrs, &ret_xattrs);
      return TRUE;
    }
}

/**
 * ostree_repo_load_object_stream:
 * @self: Repo
 * @objtype: Object type
 * @checksum: ASCII SHA256 checksum
 * @out_input: (out): Stream for object
 * @out_size: (out): Length of @out_input
 * @cancellable: Cancellable
 * @error: Error
 *
 * Load object as a stream; useful when copying objects between
 * repositories.
 */
gboolean
ostree_repo_load_object_stream (OstreeRepo         *self,
                                OstreeObjectType    objtype,
                                const char         *checksum,
                                GInputStream      **out_input,
                                guint64            *out_size,
                                GCancellable       *cancellable,
                                GError            **error)
{
  guint64 size;
  g_autoptr(GInputStream) ret_input = NULL;

  if (OSTREE_OBJECT_TYPE_IS_META (objtype))
    {
      if (!load_metadata_internal (self, objtype, checksum, TRUE, NULL,
                                   &ret_input, &size, NULL,
                                   cancellable, error))
        return FALSE;
    }
  else
    {
      g_autoptr(GInputStream) input = NULL;
      g_autoptr(GFileInfo) finfo = NULL;
      g_autoptr(GVariant) xattrs = NULL;

      if (!ostree_repo_load_file (self, checksum, &input, &finfo, &xattrs,
                                  cancellable, error))
        return FALSE;

      if (!ostree_raw_file_to_content_stream (input, finfo, xattrs,
                                              &ret_input, &size,
                                              cancellable, error))
        return FALSE;
    }

  ot_transfer_out_value (out_input, &ret_input);
  *out_size = size;
  return TRUE;
}

/*
 * _ostree_repo_has_loose_object:
 * @loose_path_buf: Buffer of size _OSTREE_LOOSE_PATH_MAX
 *
 * Locate object in repository; if it exists, @out_is_stored will be
 * set to TRUE.  @loose_path_buf is always set to the loose path.
 */
gboolean
_ostree_repo_has_loose_object (OstreeRepo           *self,
                               const char           *checksum,
                               OstreeObjectType      objtype,
                               gboolean             *out_is_stored,
                               GCancellable         *cancellable,
                               GError             **error)
{
  char loose_path_buf[_OSTREE_LOOSE_PATH_MAX];
  _ostree_loose_path (loose_path_buf, checksum, objtype, self->mode);

  gboolean found = FALSE;
  /* It's easier to share code if we make this an array */
  int dfd_searches[] = { -1, self->objects_dir_fd };
  if (self->commit_stagedir.initialized)
    dfd_searches[0] = self->commit_stagedir.fd;
  for (guint i = 0; i < G_N_ELEMENTS (dfd_searches); i++)
    {
      int dfd = dfd_searches[i];
      if (dfd == -1)
        continue;
      struct stat stbuf;
      if (TEMP_FAILURE_RETRY (fstatat (dfd, loose_path_buf, &stbuf, AT_SYMLINK_NOFOLLOW)) < 0)
        {
          if (errno == ENOENT)
            ; /* Next dfd */
          else
            return glnx_throw_errno_prefix (error, "fstatat(%s)", loose_path_buf);
        }
      else
        {
          found = TRUE;
          break;
        }
    }

  *out_is_stored = found;
  return TRUE;
}

/**
 * ostree_repo_has_object:
 * @self: Repo
 * @objtype: Object type
 * @checksum: ASCII SHA256 checksum
 * @out_have_object: (out): %TRUE if repository contains object
 * @cancellable: Cancellable
 * @error: Error
 *
 * Set @out_have_object to %TRUE if @self contains the given object;
 * %FALSE otherwise.
 *
 * Returns: %FALSE if an unexpected error occurred, %TRUE otherwise
 */
gboolean
ostree_repo_has_object (OstreeRepo           *self,
                        OstreeObjectType      objtype,
                        const char           *checksum,
                        gboolean             *out_have_object,
                        GCancellable         *cancellable,
                        GError              **error)
{
  gboolean ret_have_object = FALSE;

  if (!_ostree_repo_has_loose_object (self, checksum, objtype, &ret_have_object,
                                      cancellable, error))
    return FALSE;

  /* In the future, here is where we would also look up in metadata pack files */

  if (!ret_have_object && self->parent_repo)
    {
      if (!ostree_repo_has_object (self->parent_repo, objtype, checksum,
                                   &ret_have_object, cancellable, error))
        return FALSE;
    }

  if (out_have_object)
    *out_have_object = ret_have_object;
  return TRUE;
}

/**
 * ostree_repo_delete_object:
 * @self: Repo
 * @objtype: Object type
 * @sha256: Checksum
 * @cancellable: Cancellable
 * @error: Error
 *
 * Remove the object of type @objtype with checksum @sha256
 * from the repository.  An error of type %G_IO_ERROR_NOT_FOUND
 * is thrown if the object does not exist.
 */
gboolean
ostree_repo_delete_object (OstreeRepo           *self,
                           OstreeObjectType      objtype,
                           const char           *sha256,
                           GCancellable         *cancellable,
                           GError              **error)
{
  char loose_path[_OSTREE_LOOSE_PATH_MAX];
  _ostree_loose_path (loose_path, sha256, objtype, self->mode);

  if (objtype == OSTREE_OBJECT_TYPE_COMMIT)
    {
      char meta_loose[_OSTREE_LOOSE_PATH_MAX];

      _ostree_loose_path (meta_loose, sha256, OSTREE_OBJECT_TYPE_COMMIT_META, self->mode);

      if (!ot_ensure_unlinked_at (self->objects_dir_fd, meta_loose, error))
        return FALSE;
    }

  if (!glnx_unlinkat (self->objects_dir_fd, loose_path, 0, error))
    return glnx_prefix_error (error, "Deleting object %s.%s", sha256, ostree_object_type_to_string (objtype));

  /* If the repository is configured to use tombstone commits, create one when deleting a commit.  */
  if (objtype == OSTREE_OBJECT_TYPE_COMMIT)
    {
      gboolean tombstone_commits = FALSE;
      GKeyFile *readonly_config = ostree_repo_get_config (self);
      if (!ot_keyfile_get_boolean_with_default (readonly_config, "core", "tombstone-commits", FALSE,
                                                &tombstone_commits, error))
        return FALSE;

      if (tombstone_commits)
        {
          g_auto(GVariantBuilder) builder = OT_VARIANT_BUILDER_INITIALIZER;
          g_autoptr(GVariant) variant = NULL;

          g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
          g_variant_builder_add (&builder, "{sv}", "commit", g_variant_new_bytestring (sha256));
          variant = g_variant_ref_sink (g_variant_builder_end (&builder));
          if (!ostree_repo_write_metadata_trusted (self,
                                                   OSTREE_OBJECT_TYPE_TOMBSTONE_COMMIT,
                                                   sha256,
                                                   variant,
                                                   cancellable,
                                                   error))
            return FALSE;
        }
    }

  return TRUE;
}

/* Thin wrapper for _ostree_verify_metadata_object() */
static gboolean
fsck_metadata_object (OstreeRepo           *self,
                      OstreeObjectType      objtype,
                      const char           *sha256,
                      GCancellable         *cancellable,
                      GError              **error)
{
  const char *errmsg = glnx_strjoina ("fsck ", sha256, ".", ostree_object_type_to_string (objtype));
  GLNX_AUTO_PREFIX_ERROR (errmsg, error);
  g_autoptr(GVariant) metadata = NULL;
  if (!load_metadata_internal (self, objtype, sha256, TRUE,
                               &metadata, NULL, NULL, NULL,
                               cancellable, error))
    return FALSE;

  return _ostree_verify_metadata_object (objtype, sha256, metadata, error);
}

static gboolean
fsck_content_object (OstreeRepo           *self,
                     const char           *sha256,
                     GCancellable         *cancellable,
                     GError              **error)
{
  const char *errmsg = glnx_strjoina ("fsck content object ", sha256);
  GLNX_AUTO_PREFIX_ERROR (errmsg, error);
  g_autoptr(GInputStream) input = NULL;
  g_autoptr(GFileInfo) file_info = NULL;
  g_autoptr(GVariant) xattrs = NULL;

  if (!ostree_repo_load_file (self, sha256, &input, &file_info, &xattrs,
                              cancellable, error))
    return FALSE;

  /* TODO more consistency checks here */
  const guint32 mode = g_file_info_get_attribute_uint32 (file_info, "unix::mode");
  if (!ostree_validate_structureof_file_mode (mode, error))
    return FALSE;

  g_autofree guchar *computed_csum = NULL;
  if (!ostree_checksum_file_from_input (file_info, xattrs, input,
                                        OSTREE_OBJECT_TYPE_FILE, &computed_csum,
                                        cancellable, error))
    return FALSE;

  char actual_checksum[OSTREE_SHA256_STRING_LEN+1];
  ostree_checksum_inplace_from_bytes (computed_csum, actual_checksum);
  return _ostree_compare_object_checksum (OSTREE_OBJECT_TYPE_FILE, sha256, actual_checksum, error);
}

/**
 * ostree_repo_fsck_object:
 * @self: Repo
 * @objtype: Object type
 * @sha256: Checksum
 * @cancellable: Cancellable
 * @error: Error
 *
 * Verify consistency of the object; this performs checks only relevant to the
 * immediate object itself, such as checksumming. This API call will not itself
 * traverse metadata objects for example.
 *
 * Since: 2017.15
 */
gboolean
ostree_repo_fsck_object (OstreeRepo           *self,
                         OstreeObjectType      objtype,
                         const char           *sha256,
                         GCancellable         *cancellable,
                         GError              **error)
{
  if (OSTREE_OBJECT_TYPE_IS_META (objtype))
    return fsck_metadata_object (self, objtype, sha256, cancellable, error);
  else
    return fsck_content_object (self, sha256, cancellable, error);
}

/**
 * ostree_repo_import_object_from:
 * @self: Destination repo
 * @source: Source repo
 * @objtype: Object type
 * @checksum: checksum
 * @cancellable: Cancellable
 * @error: Error
 *
 * Copy object named by @objtype and @checksum into @self from the
 * source repository @source.  If both repositories are of the same
 * type and on the same filesystem, this will simply be a fast Unix
 * hard link operation.
 *
 * Otherwise, a copy will be performed.
 */
gboolean
ostree_repo_import_object_from (OstreeRepo           *self,
                                OstreeRepo           *source,
                                OstreeObjectType      objtype,
                                const char           *checksum,
                                GCancellable         *cancellable,
                                GError              **error)
{
  return
    ostree_repo_import_object_from_with_trust (self, source, objtype,
                                               checksum, TRUE, cancellable, error);
}

/**
 * ostree_repo_import_object_from_with_trust:
 * @self: Destination repo
 * @source: Source repo
 * @objtype: Object type
 * @checksum: checksum
 * @trusted: If %TRUE, assume the source repo is valid and trusted
 * @cancellable: Cancellable
 * @error: Error
 *
 * Copy object named by @objtype and @checksum into @self from the
 * source repository @source. If @trusted is %TRUE and both
 * repositories are of the same type and on the same filesystem,
 * this will simply be a fast Unix hard link operation.
 *
 * Otherwise, a copy will be performed.
 *
 * Since: 2016.5
 */
gboolean
ostree_repo_import_object_from_with_trust (OstreeRepo           *self,
                                           OstreeRepo           *source,
                                           OstreeObjectType      objtype,
                                           const char           *checksum,
                                           gboolean              trusted,
                                           GCancellable         *cancellable,
                                           GError              **error)
{
  /* This just wraps a currently internal API, may make it public later */
  OstreeRepoImportFlags flags = trusted ? _OSTREE_REPO_IMPORT_FLAGS_TRUSTED : 0;
  return _ostree_repo_import_object (self, source, objtype, checksum,
                                     flags, cancellable, error);
}

/**
 * ostree_repo_query_object_storage_size:
 * @self: Repo
 * @objtype: Object type
 * @sha256: Checksum
 * @out_size: (out): Size in bytes object occupies physically
 * @cancellable: Cancellable
 * @error: Error
 *
 * Return the size in bytes of object with checksum @sha256, after any
 * compression has been applied.
 */
gboolean
ostree_repo_query_object_storage_size (OstreeRepo           *self,
                                       OstreeObjectType      objtype,
                                       const char           *sha256,
                                       guint64              *out_size,
                                       GCancellable         *cancellable,
                                       GError              **error)
{
  char loose_path[_OSTREE_LOOSE_PATH_MAX];
  _ostree_loose_path (loose_path, sha256, objtype, self->mode);
  int res;

  struct stat stbuf;
  res = TEMP_FAILURE_RETRY (fstatat (self->objects_dir_fd, loose_path, &stbuf, AT_SYMLINK_NOFOLLOW));
  if (res < 0 && errno == ENOENT && self->commit_stagedir.initialized)
    res = TEMP_FAILURE_RETRY (fstatat (self->commit_stagedir.fd, loose_path, &stbuf, AT_SYMLINK_NOFOLLOW));

  if (res < 0)
    return glnx_throw_errno_prefix (error, "Querying object %s.%s", sha256, ostree_object_type_to_string (objtype));

  *out_size = stbuf.st_size;
  return TRUE;
}

/**
 * ostree_repo_load_variant_if_exists:
 * @self: Repo
 * @objtype: Object type
 * @sha256: ASCII checksum
 * @out_variant: (out) (nullable) (transfer full): Metadata
 * @error: Error
 *
 * Attempt to load the metadata object @sha256 of type @objtype if it
 * exists, storing the result in @out_variant.  If it doesn't exist,
 * @out_variant will be set to %NULL and the function will still
 * return TRUE.
 */
gboolean
ostree_repo_load_variant_if_exists (OstreeRepo       *self,
                                    OstreeObjectType  objtype,
                                    const char       *sha256,
                                    GVariant        **out_variant,
                                    GError          **error)
{
  return load_metadata_internal (self, objtype, sha256, FALSE,
                                 out_variant, NULL, NULL, NULL, NULL, error);
}

/**
 * ostree_repo_load_variant:
 * @self: Repo
 * @objtype: Expected object type
 * @sha256: Checksum string
 * @out_variant: (out) (transfer full): Metadata object
 * @error: Error
 *
 * Load the metadata object @sha256 of type @objtype, storing the
 * result in @out_variant.
 */
gboolean
ostree_repo_load_variant (OstreeRepo       *self,
                          OstreeObjectType  objtype,
                          const char       *sha256,
                          GVariant        **out_variant,
                          GError          **error)
{
  return load_metadata_internal (self, objtype, sha256, TRUE,
                                 out_variant, NULL, NULL, NULL, NULL, error);
}

/**
 * ostree_repo_load_commit:
 * @self: Repo
 * @checksum: Commit checksum
 * @out_commit: (out) (allow-none): Commit
 * @out_state: (out) (allow-none): Commit state
 * @error: Error
 *
 * A version of ostree_repo_load_variant() specialized to commits,
 * capable of returning extended state information.  Currently
 * the only extended state is %OSTREE_REPO_COMMIT_STATE_PARTIAL, which
 * means that only a sub-path of the commit is available.
 */
gboolean
ostree_repo_load_commit (OstreeRepo            *self,
                         const char            *checksum,
                         GVariant             **out_variant,
                         OstreeRepoCommitState *out_state,
                         GError               **error)
{
  return load_metadata_internal (self, OSTREE_OBJECT_TYPE_COMMIT, checksum, TRUE,
                                 out_variant, NULL, NULL, out_state, NULL, error);
}

/**
 * ostree_repo_list_objects:
 * @self: Repo
 * @flags: Flags controlling enumeration
 * @out_objects: (out) (transfer container) (element-type GVariant GVariant):
 * Map of serialized object name to variant data
 * @cancellable: Cancellable
 * @error: Error
 *
 * This function synchronously enumerates all objects in the
 * repository, returning data in @out_objects.  @out_objects
 * maps from keys returned by ostree_object_name_serialize()
 * to #GVariant values of type %OSTREE_REPO_LIST_OBJECTS_VARIANT_TYPE.
 *
 * Returns: %TRUE on success, %FALSE on error, and @error will be set
 */
gboolean
ostree_repo_list_objects (OstreeRepo                  *self,
                          OstreeRepoListObjectsFlags   flags,
                          GHashTable                 **out_objects,
                          GCancellable                *cancellable,
                          GError                     **error)
{
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
  g_return_val_if_fail (self->inited, FALSE);

  g_autoptr(GHashTable) ret_objects =
    g_hash_table_new_full (ostree_hash_object_name, g_variant_equal,
                           (GDestroyNotify) g_variant_unref,
                           (GDestroyNotify) g_variant_unref);

  if (flags & OSTREE_REPO_LIST_OBJECTS_ALL)
    flags |= (OSTREE_REPO_LIST_OBJECTS_LOOSE | OSTREE_REPO_LIST_OBJECTS_PACKED);

  if (flags & OSTREE_REPO_LIST_OBJECTS_LOOSE)
    {
      if (!list_loose_objects (self, ret_objects, NULL, cancellable, error))
        return FALSE;
      if ((flags & OSTREE_REPO_LIST_OBJECTS_NO_PARENTS) == 0 && self->parent_repo)
        {
          if (!list_loose_objects (self->parent_repo, ret_objects, NULL, cancellable, error))
            return FALSE;
        }
    }

  if (flags & OSTREE_REPO_LIST_OBJECTS_PACKED)
    {
      /* Nothing for now... */
    }

  ot_transfer_out_value (out_objects, &ret_objects);
  return TRUE;
}

/**
 * ostree_repo_list_commit_objects_starting_with:
 * @self: Repo
 * @start: List commits starting with this checksum
 * @out_commits: (out) (transfer container) (element-type GVariant GVariant):
 * Map of serialized commit name to variant data
 * @cancellable: Cancellable
 * @error: Error
 *
 * This function synchronously enumerates all commit objects starting
 * with @start, returning data in @out_commits.
 *
 * Returns: %TRUE on success, %FALSE on error, and @error will be set
 */
gboolean
ostree_repo_list_commit_objects_starting_with (OstreeRepo                  *self,
                                               const char                  *start,
                                               GHashTable                 **out_commits,
                                               GCancellable                *cancellable,
                                               GError                     **error)
{
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
  g_return_val_if_fail (self->inited, FALSE);

  g_autoptr(GHashTable) ret_commits =
    g_hash_table_new_full (ostree_hash_object_name, g_variant_equal,
                           (GDestroyNotify) g_variant_unref,
                           (GDestroyNotify) g_variant_unref);

  if (!list_loose_objects (self, ret_commits, start, cancellable, error))
    return FALSE;

  if (self->parent_repo)
    {
      if (!list_loose_objects (self->parent_repo, ret_commits, start,
                               cancellable, error))
        return FALSE;
    }

  ot_transfer_out_value (out_commits, &ret_commits);
  return TRUE;
}

/**
 * ostree_repo_read_commit:
 * @self: Repo
 * @ref: Ref or ASCII checksum
 * @out_root: (out): An #OstreeRepoFile corresponding to the root
 * @out_commit: (out): The resolved commit checksum
 * @cancellable: Cancellable
 * @error: Error
 *
 * Load the content for @rev into @out_root.
 */
gboolean
ostree_repo_read_commit (OstreeRepo   *self,
                         const char   *ref,
                         GFile       **out_root,
                         char        **out_commit,
                         GCancellable *cancellable,
                         GError **error)
{
  g_autofree char *resolved_commit = NULL;
  if (!ostree_repo_resolve_rev (self, ref, FALSE, &resolved_commit, error))
    return FALSE;

  g_autoptr(GFile) ret_root = (GFile*) _ostree_repo_file_new_for_commit (self, resolved_commit, error);
  if (!ret_root)
    return FALSE;

  if (!ostree_repo_file_ensure_resolved ((OstreeRepoFile*)ret_root, error))
    return FALSE;

  ot_transfer_out_value(out_root, &ret_root);
  ot_transfer_out_value(out_commit, &resolved_commit);
  return TRUE;
}

/**
 * ostree_repo_pull:
 * @self: Repo
 * @remote_name: Name of remote
 * @refs_to_fetch: (array zero-terminated=1) (element-type utf8) (allow-none): Optional list of refs; if %NULL, fetch all configured refs
 * @flags: Options controlling fetch behavior
 * @progress: (allow-none): Progress
 * @cancellable: Cancellable
 * @error: Error
 *
 * Connect to the remote repository, fetching the specified set of
 * refs @refs_to_fetch.  For each ref that is changed, download the
 * commit, all metadata, and all content objects, storing them safely
 * on disk in @self.
 *
 * If @flags contains %OSTREE_REPO_PULL_FLAGS_MIRROR, and
 * the @refs_to_fetch is %NULL, and the remote repository contains a
 * summary file, then all refs will be fetched.
 *
 * If @flags contains %OSTREE_REPO_PULL_FLAGS_COMMIT_ONLY, then only the
 * metadata for the commits in @refs_to_fetch is pulled.
 *
 * Warning: This API will iterate the thread default main context,
 * which is a bug, but kept for compatibility reasons.  If you want to
 * avoid this, use g_main_context_push_thread_default() to push a new
 * one around this call.
 */
gboolean
ostree_repo_pull (OstreeRepo               *self,
                  const char               *remote_name,
                  char                    **refs_to_fetch,
                  OstreeRepoPullFlags       flags,
                  OstreeAsyncProgress      *progress,
                  GCancellable             *cancellable,
                  GError                  **error)
{
  return ostree_repo_pull_one_dir (self, remote_name, NULL, refs_to_fetch, flags, progress, cancellable, error);
}

/**
 * ostree_repo_pull_one_dir:
 * @self: Repo
 * @remote_name: Name of remote
 * @dir_to_pull: Subdirectory path
 * @refs_to_fetch: (array zero-terminated=1) (element-type utf8) (allow-none): Optional list of refs; if %NULL, fetch all configured refs
 * @flags: Options controlling fetch behavior
 * @progress: (allow-none): Progress
 * @cancellable: Cancellable
 * @error: Error
 *
 * This is similar to ostree_repo_pull(), but only fetches a single
 * subpath.
 */
gboolean
ostree_repo_pull_one_dir (OstreeRepo               *self,
                          const char               *remote_name,
                          const char               *dir_to_pull,
                          char                    **refs_to_fetch,
                          OstreeRepoPullFlags       flags,
                          OstreeAsyncProgress      *progress,
                          GCancellable             *cancellable,
                          GError                  **error)
{
  GVariantBuilder builder;
  g_autoptr(GVariant) options = NULL;

  g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));

  if (dir_to_pull)
    g_variant_builder_add (&builder, "{s@v}", "subdir",
                           g_variant_new_variant (g_variant_new_string (dir_to_pull)));
  g_variant_builder_add (&builder, "{s@v}", "flags",
                         g_variant_new_variant (g_variant_new_int32 (flags)));
  if (refs_to_fetch)
    g_variant_builder_add (&builder, "{s@v}", "refs",
                           g_variant_new_variant (g_variant_new_strv ((const char *const*) refs_to_fetch, -1)));

  options = g_variant_ref_sink (g_variant_builder_end (&builder));
  return ostree_repo_pull_with_options (self, remote_name, options,
                                        progress, cancellable, error);
}

/**
 * _formatted_time_remaining_from_seconds
 * @seconds_remaining: Estimated number of seconds remaining.
 *
 * Returns a strings showing the number of days, hours, minutes
 * and seconds remaining.
 **/
static char *
_formatted_time_remaining_from_seconds (guint64 seconds_remaining)
{
  guint64 minutes_remaining = seconds_remaining / 60;
  guint64 hours_remaining = minutes_remaining / 60;
  guint64 days_remaining = hours_remaining / 24;

  GString *description = g_string_new (NULL);

  if (days_remaining)
    g_string_append_printf (description, "%" G_GUINT64_FORMAT " days ", days_remaining);

  if (hours_remaining)
    g_string_append_printf (description, "%" G_GUINT64_FORMAT " hours ", hours_remaining % 24);

  if (minutes_remaining)
    g_string_append_printf (description, "%" G_GUINT64_FORMAT " minutes ", minutes_remaining % 60);

  g_string_append_printf (description, "%" G_GUINT64_FORMAT " seconds ", seconds_remaining % 60);

  return g_string_free (description, FALSE);
}

/**
 * ostree_repo_pull_default_console_progress_changed:
 * @progress: Async progress
 * @user_data: (allow-none): User data
 *
 * Convenient "changed" callback for use with
 * ostree_async_progress_new_and_connect() when pulling from a remote
 * repository.
 *
 * Depending on the state of the #OstreeAsyncProgress, either displays a
 * custom status message, or else outstanding fetch progress in bytes/sec,
 * or else outstanding content or metadata writes to the repository in
 * number of objects.
 *
 * Compatibility note: this function previously assumed that @user_data
 * was a pointer to a #GSConsole instance.  This is no longer the case,
 * and @user_data is ignored.
 **/
void
ostree_repo_pull_default_console_progress_changed (OstreeAsyncProgress *progress,
                                                   gpointer             user_data)
{
  g_autofree char *status = NULL;
  gboolean caught_error, scanning;
  guint outstanding_fetches;
  guint outstanding_metadata_fetches;
  guint outstanding_writes;
  guint n_scanned_metadata;
  guint fetched_delta_parts;
  guint total_delta_parts;
  guint fetched_delta_part_fallbacks;
  guint total_delta_part_fallbacks;

  g_autoptr(GString) buf = g_string_new ("");

  ostree_async_progress_get (progress,
                             "outstanding-fetches", "u", &outstanding_fetches,
                             "outstanding-metadata-fetches", "u", &outstanding_metadata_fetches,
                             "outstanding-writes", "u", &outstanding_writes,
                             "caught-error", "b", &caught_error,
                             "scanning", "u", &scanning,
                             "scanned-metadata", "u", &n_scanned_metadata,
                             "fetched-delta-parts", "u", &fetched_delta_parts,
                             "total-delta-parts", "u", &total_delta_parts,
                             "fetched-delta-fallbacks", "u", &fetched_delta_part_fallbacks,
                             "total-delta-fallbacks", "u", &total_delta_part_fallbacks,
                             "status", "s", &status,
                             NULL);

  if (*status != '\0')
    {
      g_string_append (buf, status);
    }
  else if (caught_error)
    {
      g_string_append_printf (buf, "Caught error, waiting for outstanding tasks");
    }
  else if (outstanding_fetches)
    {
      guint64 bytes_transferred, start_time, total_delta_part_size;
      guint fetched, metadata_fetched, requested;
      guint64 current_time = g_get_monotonic_time ();
      g_autofree char *formatted_bytes_transferred = NULL;
      g_autofree char *formatted_bytes_sec = NULL;
      guint64 bytes_sec;

      /* Note: This is not atomic wrt the above getter call. */
      ostree_async_progress_get (progress,
                                 "bytes-transferred", "t", &bytes_transferred,
                                 "fetched", "u", &fetched,
                                 "metadata-fetched", "u", &metadata_fetched,
                                 "requested", "u", &requested,
                                 "start-time", "t", &start_time,
                                 "total-delta-part-size", "t", &total_delta_part_size,
                                 NULL);

      formatted_bytes_transferred = g_format_size_full (bytes_transferred, 0);

      /* Ignore the first second, or when we haven't transferred any
       * data, since those could cause divide by zero below.
       */
      if ((current_time - start_time) < G_USEC_PER_SEC || bytes_transferred == 0)
        {
          bytes_sec = 0;
          formatted_bytes_sec = g_strdup ("-");
        }
      else
        {
          bytes_sec = bytes_transferred / ((current_time - start_time) / G_USEC_PER_SEC);
          formatted_bytes_sec = g_format_size (bytes_sec);
        }

      /* Are we doing deltas?  If so, we can be more accurate */
      if (total_delta_parts > 0)
        {
          guint64 fetched_delta_part_size = ostree_async_progress_get_uint64 (progress, "fetched-delta-part-size");
          g_autofree char *formatted_fetched = NULL;
          g_autofree char *formatted_total = NULL;

          /* Here we merge together deltaparts + fallbacks to avoid bloating the text UI */
          fetched_delta_parts += fetched_delta_part_fallbacks;
          total_delta_parts += total_delta_part_fallbacks;

          formatted_fetched = g_format_size (fetched_delta_part_size);
          formatted_total = g_format_size (total_delta_part_size);

          if (bytes_sec > 0)
            {
              guint64 est_time_remaining = 0;
              if (total_delta_part_size > fetched_delta_part_size)
                est_time_remaining = (total_delta_part_size - fetched_delta_part_size) / bytes_sec;
              g_autofree char *formatted_est_time_remaining = _formatted_time_remaining_from_seconds (est_time_remaining);
              /* No space between %s and remaining, since formatted_est_time_remaining has a trailing space */
              g_string_append_printf (buf, "Receiving delta parts: %u/%u %s/%s %s/s %sremaining",
                                      fetched_delta_parts, total_delta_parts,
                                      formatted_fetched, formatted_total,
                                      formatted_bytes_sec,
                                      formatted_est_time_remaining);
            }
          else
            {
              g_string_append_printf (buf, "Receiving delta parts: %u/%u %s/%s",
                                      fetched_delta_parts, total_delta_parts,
                                      formatted_fetched, formatted_total);
            }
        }
      else if (scanning || outstanding_metadata_fetches)
        {
          g_string_append_printf (buf, "Receiving metadata objects: %u/(estimating) %s/s %s",
                                  metadata_fetched, formatted_bytes_sec, formatted_bytes_transferred);
        }
      else
        {
          g_string_append_printf (buf, "Receiving objects: %u%% (%u/%u) %s/s %s",
                                  (guint)((((double)fetched) / requested) * 100),
                                  fetched, requested, formatted_bytes_sec, formatted_bytes_transferred);
        }
    }
  else if (outstanding_writes)
    {
      g_string_append_printf (buf, "Writing objects: %u", outstanding_writes);
    }
  else
    {
      g_string_append_printf (buf, "Scanning metadata: %u", n_scanned_metadata);
    }

  glnx_console_text (buf->str);
}

/**
 * ostree_repo_append_gpg_signature:
 * @self: Self
 * @commit_checksum: SHA256 of given commit to sign
 * @signature_bytes: Signature data
 * @cancellable: A #GCancellable
 * @error: a #GError
 *
 * Append a GPG signature to a commit.
 */
gboolean
ostree_repo_append_gpg_signature (OstreeRepo     *self,
                                  const gchar    *commit_checksum,
                                  GBytes         *signature_bytes,
                                  GCancellable   *cancellable,
                                  GError        **error)
{
  g_autoptr(GVariant) metadata = NULL;
  if (!ostree_repo_read_commit_detached_metadata (self,
                                                  commit_checksum,
                                                  &metadata,
                                                  cancellable,
                                                  error))
    return FALSE;

#ifndef OSTREE_DISABLE_GPGME
  g_autoptr(GVariant) new_metadata =
    _ostree_detached_metadata_append_gpg_sig (metadata, signature_bytes);

  if (!ostree_repo_write_commit_detached_metadata (self,
                                                   commit_checksum,
                                                   new_metadata,
                                                   cancellable,
                                                   error))
    return FALSE;

  return TRUE;
#else
  return glnx_throw (error, "GPG feature is disabled in a build time");
#endif /* OSTREE_DISABLE_GPGME */
}

#ifndef OSTREE_DISABLE_GPGME
static gboolean
sign_data (OstreeRepo     *self,
           GBytes         *input_data,
           const gchar    *key_id,
           const gchar    *homedir,
           GBytes        **out_signature,
           GCancellable   *cancellable,
           GError        **error)
{
  g_auto(GLnxTmpfile) tmpf = { 0, };
  if (!glnx_open_tmpfile_linkable_at (self->tmp_dir_fd, ".", O_RDWR | O_CLOEXEC,
                                      &tmpf, error))
    return FALSE;
  g_autoptr(GOutputStream) tmp_signature_output = g_unix_output_stream_new (tmpf.fd, FALSE);

  g_auto(gpgme_ctx_t) context = ot_gpgme_new_ctx (homedir, error);
  if (!context)
    return FALSE;

  /* Get the secret keys with the given key id */
  g_auto(gpgme_key_t) key = NULL;
  gpgme_error_t err = gpgme_get_key (context, key_id, &key, 1);
  if (gpgme_err_code (err) == GPG_ERR_EOF)
    return glnx_throw (error, "No gpg key found with ID %s (homedir: %s)", key_id,
                       homedir ? homedir : "<default>");
  else if (gpgme_err_code (err) == GPG_ERR_AMBIGUOUS_NAME) {
    return glnx_throw (error, "gpg key id %s ambiguous (homedir: %s). Try the fingerprint instead", key_id,
                       homedir ? homedir : "<default>");
   }
  else if (err != GPG_ERR_NO_ERROR)
    return ot_gpgme_throw (err, error, "Unable to lookup key ID %s", key_id);

  /* Add the key to the context as a signer */
  if ((err = gpgme_signers_add (context, key)) != GPG_ERR_NO_ERROR)
    return ot_gpgme_throw (err, error, "Error signing commit");

  /* Get a gpg buffer from the commit */
  g_auto(gpgme_data_t) commit_buffer = NULL;
  gsize len;
  const char *buf = g_bytes_get_data (input_data, &len);
  if ((err = gpgme_data_new_from_mem (&commit_buffer, buf, len, FALSE)) != GPG_ERR_NO_ERROR)
    return ot_gpgme_throw (err, error, "Failed to create buffer from commit file");

  /* Sign it */
  g_auto(gpgme_data_t) signature_buffer = ot_gpgme_data_output (tmp_signature_output);
  if ((err = gpgme_op_sign (context, commit_buffer, signature_buffer, GPGME_SIG_MODE_DETACH))
      != GPG_ERR_NO_ERROR)
    return ot_gpgme_throw (err, error, "Failure signing commit file");
  if (!g_output_stream_close (tmp_signature_output, cancellable, error))
    return FALSE;

  /* Return a mmap() reference */
  g_autoptr(GMappedFile) signature_file = g_mapped_file_new_from_fd (tmpf.fd, FALSE, error);
  if (!signature_file)
    return FALSE;

  if (out_signature)
    *out_signature = g_mapped_file_get_bytes (signature_file);
  return TRUE;
}
#endif /* OSTREE_DISABLE_GPGME */

/**
 * ostree_repo_sign_commit:
 * @self: Self
 * @commit_checksum: SHA256 of given commit to sign
 * @key_id: Use this GPG key id
 * @homedir: (allow-none): GPG home directory, or %NULL
 * @cancellable: A #GCancellable
 * @error: a #GError
 *
 * Add a GPG signature to a commit.
 */
gboolean
ostree_repo_sign_commit (OstreeRepo     *self,
                         const gchar    *commit_checksum,
                         const gchar    *key_id,
                         const gchar    *homedir,
                         GCancellable   *cancellable,
                         GError        **error)
{
#ifndef OSTREE_DISABLE_GPGME
  g_autoptr(GBytes) commit_data = NULL;
  g_autoptr(GBytes) signature = NULL;

  g_autoptr(GVariant) commit_variant = NULL;
  if (!ostree_repo_load_variant (self, OSTREE_OBJECT_TYPE_COMMIT,
                                 commit_checksum, &commit_variant, error))
    return glnx_prefix_error (error, "Failed to read commit");

  g_autoptr(GVariant) old_metadata = NULL;
  if (!ostree_repo_read_commit_detached_metadata (self,
                                                  commit_checksum,
                                                  &old_metadata,
                                                  cancellable,
                                                  error))
    return glnx_prefix_error (error, "Failed to read detached metadata");

  commit_data = g_variant_get_data_as_bytes (commit_variant);

  /* The verify operation is merely to parse any existing signatures to
   * check if the commit has already been signed with the given key ID.
   * We want to avoid storing duplicate signatures in the metadata. We
   * pass the homedir so that the signing key can be imported, allowing
   * subkey signatures to be recognised. */
  g_autoptr(GError) local_error = NULL;
  g_autoptr(GFile) verify_keydir = NULL;
  if (homedir != NULL)
    verify_keydir = g_file_new_for_path (homedir);
  g_autoptr(OstreeGpgVerifyResult) result
    =_ostree_repo_gpg_verify_with_metadata (self, commit_data, old_metadata,
                                            NULL, verify_keydir, NULL,
                                            cancellable, &local_error);
  if (!result)
    {
      /* "Not found" just means the commit is not yet signed.  That's okay. */
      if (g_error_matches (local_error, OSTREE_GPG_ERROR, OSTREE_GPG_ERROR_NO_SIGNATURE))
        {
          g_clear_error (&local_error);
        }
      else
        return g_propagate_error (error, g_steal_pointer (&local_error)), FALSE;
    }
  else if (ostree_gpg_verify_result_lookup (result, key_id, NULL))
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_EXISTS,
                   "Commit is already signed with GPG key %s", key_id);
      return FALSE;
    }

  if (!sign_data (self, commit_data, key_id, homedir,
                  &signature, cancellable, error))
    return FALSE;

  g_autoptr(GVariant) new_metadata =
    _ostree_detached_metadata_append_gpg_sig (old_metadata, signature);

  if (!ostree_repo_write_commit_detached_metadata (self,
                                                   commit_checksum,
                                                   new_metadata,
                                                   cancellable,
                                                   error))
    return FALSE;

  return TRUE;
#else
  /* FIXME: Return false until refactoring */
  return glnx_throw (error, "GPG feature is disabled in a build time");
#endif /* OSTREE_DISABLE_GPGME */
}

/**
 * ostree_repo_sign_delta:
 * @self: Self
 * @from_commit: From commit
 * @to_commit: To commit
 * @key_id: key id
 * @homedir: homedir
 * @cancellable: cancellable
 * @error: error
 *
 * This function is deprecated, sign the summary file instead.
 * Add a GPG signature to a static delta.
 */
gboolean
ostree_repo_sign_delta (OstreeRepo     *self,
                        const gchar    *from_commit,
                        const gchar    *to_commit,
                        const gchar    *key_id,
                        const gchar    *homedir,
                        GCancellable   *cancellable,
                        GError        **error)
{
  g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
               "ostree_repo_sign_delta is deprecated");
  return FALSE;
}

/**
 * ostree_repo_add_gpg_signature_summary:
 * @self: Self
 * @key_id: (array zero-terminated=1) (element-type utf8): NULL-terminated array of GPG keys.
 * @homedir: (allow-none): GPG home directory, or %NULL
 * @cancellable: A #GCancellable
 * @error: a #GError
 *
 * Add a GPG signature to a summary file.
 */
gboolean
ostree_repo_add_gpg_signature_summary (OstreeRepo     *self,
                                       const gchar    **key_id,
                                       const gchar    *homedir,
                                       GCancellable   *cancellable,
                                       GError        **error)
{
#ifndef OSTREE_DISABLE_GPGME
  glnx_autofd int fd = -1;
  if (!glnx_openat_rdonly (self->repo_dir_fd, "summary", TRUE, &fd, error))
    return FALSE;
  g_autoptr(GBytes) summary_data = ot_fd_readall_or_mmap (fd, 0, error);
  if (!summary_data)
    return FALSE;
  /* Note that fd is reused below */
  glnx_close_fd (&fd);

  g_autoptr(GVariant) metadata = NULL;
  if (!ot_openat_ignore_enoent (self->repo_dir_fd, "summary.sig", &fd, error))
    return FALSE;
  if (fd >= 0)
    {
      if (!ot_variant_read_fd (fd, 0, G_VARIANT_TYPE (OSTREE_SUMMARY_SIG_GVARIANT_STRING),
                               FALSE, &metadata, error))
        return FALSE;
    }

  for (guint i = 0; key_id[i]; i++)
    {
      g_autoptr(GBytes) signature_data = NULL;
      if (!sign_data (self, summary_data, key_id[i], homedir,
                      &signature_data,
                      cancellable, error))
        return FALSE;

      g_autoptr(GVariant) old_metadata = g_steal_pointer (&metadata);
      metadata = _ostree_detached_metadata_append_gpg_sig (old_metadata, signature_data);
    }

  g_autoptr(GVariant) normalized = g_variant_get_normal_form (metadata);

  if (!_ostree_repo_file_replace_contents (self,
                                           self->repo_dir_fd,
                                           "summary.sig",
                                           g_variant_get_data (normalized),
                                           g_variant_get_size (normalized),
                                           cancellable, error))
    return FALSE;

  return TRUE;
#else
  return glnx_throw (error, "GPG feature is disabled in a build time");
#endif /* OSTREE_DISABLE_GPGME */
}


/**
 * ostree_repo_gpg_sign_data:
 * @self: Self
 * @data: Data as a #GBytes
 * @old_signatures: Existing signatures to append to (or %NULL)
 * @key_id: (array zero-terminated=1) (element-type utf8): NULL-terminated array of GPG keys.
 * @homedir: (allow-none): GPG home directory, or %NULL
 * @out_signatures: (out): in case of success will contain signature
 * @cancellable: A #GCancellable
 * @error: a #GError
 *
 * Sign the given @data with the specified keys in @key_id. Similar to
 * ostree_repo_add_gpg_signature_summary() but can be used on any
 * data.
 *
 * You can use ostree_repo_gpg_verify_data() to verify the signatures.
 *
 * Returns: @TRUE if @data has been signed successfully,
 * @FALSE in case of error (@error will contain the reason).
 *
 * Since: 2020.8
 */
gboolean
ostree_repo_gpg_sign_data (OstreeRepo     *self,
                           GBytes         *data,
                           GBytes         *old_signatures,
                           const gchar   **key_id,
                           const gchar    *homedir,
                           GBytes        **out_signatures,
                           GCancellable   *cancellable,
                           GError        **error)
{
#ifndef OSTREE_DISABLE_GPGME
  g_autoptr(GVariant) metadata = NULL;
  g_autoptr(GVariant) res = NULL;

  if (old_signatures)
    metadata = g_variant_ref_sink (g_variant_new_from_bytes (G_VARIANT_TYPE (OSTREE_SUMMARY_SIG_GVARIANT_STRING), old_signatures, FALSE));

  for (guint i = 0; key_id[i]; i++)
    {
      g_autoptr(GBytes) signature_data = NULL;
      if (!sign_data (self, data, key_id[i], homedir,
                      &signature_data,
                      cancellable, error))
        return FALSE;

      g_autoptr(GVariant) old_metadata = g_steal_pointer (&metadata);
      metadata = _ostree_detached_metadata_append_gpg_sig (old_metadata, signature_data);
    }

  res = g_variant_get_normal_form (metadata);
  *out_signatures = g_variant_get_data_as_bytes (res);
  return TRUE;
#else
  return glnx_throw (error, "GPG feature is disabled in a build time");
#endif /* OSTREE_DISABLE_GPGME */
}


#ifndef OSTREE_DISABLE_GPGME
/* Special remote for _ostree_repo_gpg_verify_with_metadata() */
static const char *OSTREE_ALL_REMOTES = "__OSTREE_ALL_REMOTES__";

/* Look for a keyring for @remote in the repo itself, or in
 * /etc/ostree/remotes.d.
 */
static gboolean
find_keyring (OstreeRepo          *self,
              OstreeRemote        *remote,
              GBytes             **ret_bytes,
              GCancellable        *cancellable,
              GError             **error)
{
  glnx_autofd int fd = -1;
  if (!ot_openat_ignore_enoent (self->repo_dir_fd, remote->keyring, &fd, error))
    return FALSE;

  if (fd != -1)
    {
      GBytes *ret = glnx_fd_readall_bytes (fd, cancellable, error);
      if (!ret)
        return FALSE;
      *ret_bytes = ret;
      return TRUE;
    }

  g_autoptr(GFile) remotes_d = get_remotes_d_dir (self, NULL);
  if (remotes_d)
    {
      g_autoptr(GFile) child = g_file_get_child (remotes_d, remote->keyring);

      if (!ot_openat_ignore_enoent (AT_FDCWD, gs_file_get_path_cached (child), &fd, error))
        return FALSE;

      if (fd != -1)
        {
          GBytes *ret = glnx_fd_readall_bytes (fd, cancellable, error);
          if (!ret)
            return FALSE;
          *ret_bytes = ret;
          return TRUE;
        }
    }

  if (self->parent_repo)
    return find_keyring (self->parent_repo, remote, ret_bytes, cancellable, error);

  *ret_bytes = NULL;
  return TRUE;
}

static gboolean
_ostree_repo_gpg_prepare_verifier (OstreeRepo         *self,
                                   const gchar        *remote_name,
                                   GFile              *keyringdir,
                                   GFile              *extra_keyring,
                                   gboolean            add_global_keyrings,
                                   OstreeGpgVerifier **out_verifier,
                                   GCancellable       *cancellable,
                                   GError            **error)
{
  g_autoptr(OstreeGpgVerifier) verifier = _ostree_gpg_verifier_new ();

  if (remote_name == OSTREE_ALL_REMOTES)
    {
      /* Add all available remote keyring files. */

      if (!_ostree_gpg_verifier_add_keyring_dir_at (verifier, self->repo_dir_fd, ".",
                                                    cancellable, error))
        return FALSE;
    }
  else if (remote_name != NULL)
    {
      /* Add the remote's keyring file if it exists. */

      g_autoptr(OstreeRemote) remote = NULL;

      remote = _ostree_repo_get_remote_inherited (self, remote_name, error);
      if (remote == NULL)
        return FALSE;

      g_autoptr(GBytes) keyring_data = NULL;
      if (!find_keyring (self, remote, &keyring_data, cancellable, error))
        return FALSE;

      if (keyring_data != NULL)
        {
          _ostree_gpg_verifier_add_keyring_data (verifier, keyring_data, remote->keyring);
          add_global_keyrings = FALSE;
        }

      g_auto(GStrv) gpgkeypath_list = NULL;

      if (!ot_keyfile_get_string_list_with_separator_choice (remote->options,
                                                             remote->group,
                                                             "gpgkeypath",
                                                             ";,",
                                                             &gpgkeypath_list,
                                                             error))
        return FALSE;

      if (gpgkeypath_list)
        {
          for (char **iter = gpgkeypath_list; *iter != NULL; ++iter)
            if (!_ostree_gpg_verifier_add_keyfile_path (verifier, *iter,
                                                        cancellable, error))
              return FALSE;
        }
    }

  if (add_global_keyrings)
    {
      /* Use the deprecated global keyring directory. */
      if (!_ostree_gpg_verifier_add_global_keyring_dir (verifier, cancellable, error))
        return FALSE;
    }

  if (keyringdir)
    {
      if (!_ostree_gpg_verifier_add_keyring_dir (verifier, keyringdir,
                                                 cancellable, error))
        return FALSE;
    }
  if (extra_keyring != NULL)
    {
      _ostree_gpg_verifier_add_keyring_file (verifier, extra_keyring);
    }

  if (out_verifier != NULL)
    *out_verifier = g_steal_pointer (&verifier);

  return TRUE;
}

static OstreeGpgVerifyResult *
_ostree_repo_gpg_verify_data_internal (OstreeRepo    *self,
                                       const gchar   *remote_name,
                                       GBytes        *data,
                                       GBytes        *signatures,
                                       GFile         *keyringdir,
                                       GFile         *extra_keyring,
                                       GCancellable  *cancellable,
                                       GError       **error)
{
  g_autoptr(OstreeGpgVerifier) verifier = NULL;
  if (!_ostree_repo_gpg_prepare_verifier (self,
                                          remote_name,
                                          keyringdir,
                                          extra_keyring,
                                          TRUE,
                                          &verifier,
                                          cancellable,
                                          error))
    return NULL;

  return _ostree_gpg_verifier_check_signature (verifier,
                                               data,
                                               signatures,
                                               cancellable,
                                               error);
}

OstreeGpgVerifyResult *
_ostree_repo_gpg_verify_with_metadata (OstreeRepo          *self,
                                       GBytes              *signed_data,
                                       GVariant            *metadata,
                                       const char          *remote_name,
                                       GFile               *keyringdir,
                                       GFile               *extra_keyring,
                                       GCancellable        *cancellable,
                                       GError             **error)
{
  g_autoptr(GVariant) signaturedata = NULL;
  GByteArray *buffer;
  GVariantIter iter;
  GVariant *child;
  g_autoptr (GBytes) signatures = NULL;

  if (metadata)
    signaturedata = g_variant_lookup_value (metadata,
                                            _OSTREE_METADATA_GPGSIGS_NAME,
                                            _OSTREE_METADATA_GPGSIGS_TYPE);
  if (!signaturedata)
    {
      g_set_error_literal (error, OSTREE_GPG_ERROR, OSTREE_GPG_ERROR_NO_SIGNATURE,
                           "GPG verification enabled, but no signatures found (use gpg-verify=false in remote config to disable)");
      return NULL;
    }

  /* OpenPGP data is organized into binary records called packets.  RFC 4880
   * defines a packet as a chunk of data that has a tag specifying its meaning,
   * and consists of a packet header followed by a packet body.  Each packet
   * encodes its own length, and so packets can be concatenated to construct
   * OpenPGP messages, keyrings, or in this case, detached signatures.
   *
   * Each binary blob in the GVariant list is a complete signature packet, so
   * we can concatenate them together to verify all the signatures at once. */
  buffer = g_byte_array_new ();
  g_variant_iter_init (&iter, signaturedata);
  while ((child = g_variant_iter_next_value (&iter)) != NULL)
    {
      g_byte_array_append (buffer,
                           g_variant_get_data (child),
                           g_variant_get_size (child));
      g_variant_unref (child);
    }
  signatures = g_byte_array_free_to_bytes (buffer);

  return _ostree_repo_gpg_verify_data_internal (self,
                                                remote_name,
                                                signed_data,
                                                signatures,
                                                keyringdir,
                                                extra_keyring,
                                                cancellable,
                                                error);
}

/* Needed an internal version for the remote_name parameter. */
OstreeGpgVerifyResult *
_ostree_repo_verify_commit_internal (OstreeRepo    *self,
                                     const char    *commit_checksum,
                                     const char    *remote_name,
                                     GFile         *keyringdir,
                                     GFile         *extra_keyring,
                                     GCancellable  *cancellable,
                                     GError       **error)
{
  g_autoptr(GVariant) commit_variant = NULL;
  /* Load the commit */
  if (!ostree_repo_load_variant (self, OSTREE_OBJECT_TYPE_COMMIT,
                                 commit_checksum, &commit_variant,
                                 error))
    return glnx_prefix_error_null (error, "Failed to read commit");

  /* Load the metadata */
  g_autoptr(GVariant) metadata = NULL;
  if (!ostree_repo_read_commit_detached_metadata (self,
                                                  commit_checksum,
                                                  &metadata,
                                                  cancellable,
                                                  error))
    return glnx_prefix_error_null (error, "Failed to read detached metadata");

  g_autoptr(GBytes) signed_data = g_variant_get_data_as_bytes (commit_variant);

  /* XXX This is a hackish way to indicate to use ALL remote-specific
   *     keyrings in the signature verification.  We want this when
   *     verifying a signed commit that's already been pulled. */
  if (remote_name == NULL)
    remote_name = OSTREE_ALL_REMOTES;

  return _ostree_repo_gpg_verify_with_metadata (self, signed_data,
                                                metadata, remote_name,
                                                keyringdir, extra_keyring,
                                                cancellable, error);
}
#endif /* OSTREE_DISABLE_GPGME */

/**
 * ostree_repo_verify_commit:
 * @self: Repository
 * @commit_checksum: ASCII SHA256 checksum
 * @keyringdir: (allow-none): Path to directory GPG keyrings; overrides built-in default if given
 * @extra_keyring: (allow-none): Path to additional keyring file (not a directory)
 * @cancellable: Cancellable
 * @error: Error
 *
 * Check for a valid GPG signature on commit named by the ASCII
 * checksum @commit_checksum.
 *
 * Returns: %TRUE if there was a GPG signature from a trusted keyring, otherwise %FALSE
 */
gboolean
ostree_repo_verify_commit (OstreeRepo   *self,
                           const gchar  *commit_checksum,
                           GFile        *keyringdir,
                           GFile        *extra_keyring,
                           GCancellable *cancellable,
                           GError      **error)
{
#ifndef OSTREE_DISABLE_GPGME
  g_autoptr(OstreeGpgVerifyResult) result = NULL;

  result = ostree_repo_verify_commit_ext (self, commit_checksum,
                                          keyringdir, extra_keyring,
                                          cancellable, error);

  if (!ostree_gpg_verify_result_require_valid_signature (result, error))
    return glnx_prefix_error (error, "Commit %s", commit_checksum);
  return TRUE;
#else
  /* FIXME: Return false until refactoring */
  return glnx_throw (error, "GPG feature is disabled in a build time");
#endif /* OSTREE_DISABLE_GPGME */
}

/**
 * ostree_repo_verify_commit_ext:
 * @self: Repository
 * @commit_checksum: ASCII SHA256 checksum
 * @keyringdir: (allow-none): Path to directory GPG keyrings; overrides built-in default if given
 * @extra_keyring: (allow-none): Path to additional keyring file (not a directory)
 * @cancellable: Cancellable
 * @error: Error
 *
 * Read GPG signature(s) on the commit named by the ASCII checksum
 * @commit_checksum and return detailed results.
 *
 * Returns: (transfer full): an #OstreeGpgVerifyResult, or %NULL on error
 */
OstreeGpgVerifyResult *
ostree_repo_verify_commit_ext (OstreeRepo    *self,
                               const gchar   *commit_checksum,
                               GFile         *keyringdir,
                               GFile         *extra_keyring,
                               GCancellable  *cancellable,
                               GError       **error)
{
#ifndef OSTREE_DISABLE_GPGME
  return _ostree_repo_verify_commit_internal (self,
                                              commit_checksum,
                                              NULL,
                                              keyringdir,
                                              extra_keyring,
                                              cancellable,
                                              error);
#else
  glnx_throw (error, "GPG feature is disabled in a build time");
  return NULL;
#endif /* OSTREE_DISABLE_GPGME */
}

/**
 * ostree_repo_verify_commit_for_remote:
 * @self: Repository
 * @commit_checksum: ASCII SHA256 checksum
 * @remote_name: OSTree remote to use for configuration
 * @cancellable: Cancellable
 * @error: Error
 *
 * Read GPG signature(s) on the commit named by the ASCII checksum
 * @commit_checksum and return detailed results, based on the keyring
 * configured for @remote.
 *
 * Returns: (transfer full): an #OstreeGpgVerifyResult, or %NULL on error
 *
 * Since: 2016.14
 */
OstreeGpgVerifyResult *
ostree_repo_verify_commit_for_remote (OstreeRepo    *self,
                                      const gchar   *commit_checksum,
                                      const gchar   *remote_name,
                                      GCancellable  *cancellable,
                                      GError       **error)
{
#ifndef OSTREE_DISABLE_GPGME
  return _ostree_repo_verify_commit_internal (self,
                                              commit_checksum,
                                              remote_name,
                                              NULL,
                                              NULL,
                                              cancellable,
                                              error);
#else
  glnx_throw (error, "GPG feature is disabled in a build time");
  return NULL;
#endif /* OSTREE_DISABLE_GPGME */
}

/**
 * ostree_repo_gpg_verify_data:
 * @self: Repository
 * @remote_name: (nullable): Name of remote
 * @data: Data as a #GBytes
 * @signatures: Signatures as a #GBytes
 * @keyringdir: (nullable): Path to directory GPG keyrings; overrides built-in default if given
 * @extra_keyring: (nullable): Path to additional keyring file (not a directory)
 * @cancellable: Cancellable
 * @error: Error
 *
 * Verify @signatures for @data using GPG keys in the keyring for
 * @remote_name, and return an #OstreeGpgVerifyResult.
 *
 * The @remote_name parameter can be %NULL. In that case it will do
 * the verifications using GPG keys in the keyrings of all remotes.
 *
 * Returns: (transfer full): an #OstreeGpgVerifyResult, or %NULL on error
 *
 * Since: 2016.6
 */
OstreeGpgVerifyResult *
ostree_repo_gpg_verify_data (OstreeRepo    *self,
                             const gchar   *remote_name,
                             GBytes        *data,
                             GBytes        *signatures,
                             GFile         *keyringdir,
                             GFile         *extra_keyring,
                             GCancellable  *cancellable,
                             GError       **error)
{
  g_return_val_if_fail (OSTREE_IS_REPO (self), NULL);
  g_return_val_if_fail (data != NULL, NULL);
  g_return_val_if_fail (signatures != NULL, NULL);

#ifndef OSTREE_DISABLE_GPGME
  return _ostree_repo_gpg_verify_data_internal (self,
                                                (remote_name != NULL) ? remote_name : OSTREE_ALL_REMOTES,
                                                data,
                                                signatures,
                                                keyringdir,
                                                extra_keyring,
                                                cancellable,
                                                error);
#else
  glnx_throw (error, "GPG feature is disabled in a build time");
  return NULL;
#endif /* OSTREE_DISABLE_GPGME */
}

/**
 * ostree_repo_verify_summary:
 * @self: Repo
 * @remote_name: Name of remote
 * @summary: Summary data as a #GBytes
 * @signatures: Summary signatures as a #GBytes
 * @cancellable: Cancellable
 * @error: Error
 *
 * Verify @signatures for @summary data using GPG keys in the keyring for
 * @remote_name, and return an #OstreeGpgVerifyResult.
 *
 * Returns: (transfer full): an #OstreeGpgVerifyResult, or %NULL on error
 */
OstreeGpgVerifyResult *
ostree_repo_verify_summary (OstreeRepo    *self,
                            const char    *remote_name,
                            GBytes        *summary,
                            GBytes        *signatures,
                            GCancellable  *cancellable,
                            GError       **error)
{
  g_autoptr(GVariant) signatures_variant = NULL;

  g_return_val_if_fail (OSTREE_IS_REPO (self), NULL);
  g_return_val_if_fail (remote_name != NULL, NULL);
  g_return_val_if_fail (summary != NULL, NULL);
  g_return_val_if_fail (signatures != NULL, NULL);

  signatures_variant = g_variant_new_from_bytes (OSTREE_SUMMARY_SIG_GVARIANT_FORMAT,
                                                 signatures, FALSE);

#ifndef OSTREE_DISABLE_GPGME
  return _ostree_repo_gpg_verify_with_metadata (self,
                                                summary,
                                                signatures_variant,
                                                remote_name,
                                                NULL, NULL,
                                                cancellable,
                                                error);
#else
  glnx_throw (error, "GPG feature is disabled in a build time");
  return NULL;
#endif /* OSTREE_DISABLE_GPGME */
}

/* Add an entry for a @ref ↦ @checksum mapping to an `a(s(t@ay@a{sv}))`
 * @refs_builder to go into a `summary` file. This includes building the
 * standard additional metadata keys for the ref. */
static gboolean
summary_add_ref_entry (OstreeRepo       *self,
                       const char       *ref,
                       const char       *checksum,
                       GVariantBuilder  *refs_builder,
                       GError          **error)
{
  g_auto(GVariantDict) commit_metadata_builder = OT_VARIANT_BUILDER_INITIALIZER;

  g_assert (ref);  g_assert (checksum);

  g_autofree char *remotename = NULL;
  if (!ostree_parse_refspec (ref, &remotename, NULL, NULL))
    g_assert_not_reached ();

  /* Don't put remote refs in the summary */
  if (remotename != NULL)
    return TRUE;

  g_autoptr(GVariant) commit_obj = NULL;
  if (!ostree_repo_load_variant (self, OSTREE_OBJECT_TYPE_COMMIT, checksum, &commit_obj, error))
    return FALSE;
  g_autoptr(GVariant) orig_metadata = g_variant_get_child_value (commit_obj, 0);

  g_variant_dict_init (&commit_metadata_builder, NULL);

  /* Forward the commit’s timestamp and version if they're valid. */
  guint64 commit_timestamp = ostree_commit_get_timestamp (commit_obj);
  g_autoptr(GDateTime) dt = g_date_time_new_from_unix_utc (commit_timestamp);

  if (dt != NULL)
    g_variant_dict_insert_value (&commit_metadata_builder, OSTREE_COMMIT_TIMESTAMP,
                                 g_variant_new_uint64 (GUINT64_TO_BE (commit_timestamp)));

  const char *version = NULL;
  if (g_variant_lookup (orig_metadata, OSTREE_COMMIT_META_KEY_VERSION, "&s", &version))
    g_variant_dict_insert (&commit_metadata_builder, OSTREE_COMMIT_VERSION, "s", version);

  g_variant_builder_add_value (refs_builder,
                               g_variant_new ("(s(t@ay@a{sv}))", ref,
                                              (guint64) g_variant_get_size (commit_obj),
                                              ostree_checksum_to_bytes_v (checksum),
                                              g_variant_dict_end (&commit_metadata_builder)));

  return TRUE;
}

/**
 * ostree_repo_regenerate_summary:
 * @self: Repo
 * @additional_metadata: (allow-none): A GVariant of type a{sv}, or %NULL
 * @cancellable: Cancellable
 * @error: Error
 *
 * An OSTree repository can contain a high level "summary" file that
 * describes the available branches and other metadata.
 *
 * If the timetable for making commits and updating the summary file is fairly
 * regular, setting the `ostree.summary.expires` key in @additional_metadata
 * will aid clients in working out when to check for updates.
 *
 * It is regenerated automatically after any ref is
 * added, removed, or updated if `core/auto-update-summary` is set.
 *
 * If the `core/collection-id` key is set in the configuration, it will be
 * included as %OSTREE_SUMMARY_COLLECTION_ID in the summary file. Refs that
 * have associated collection IDs will be included in the generated summary
 * file, listed under the %OSTREE_SUMMARY_COLLECTION_MAP key. Collection IDs
 * and refs in %OSTREE_SUMMARY_COLLECTION_MAP are guaranteed to be in
 * lexicographic order.
 *
 * Locking: shared (Prior to 2021.7, this was exclusive)
 */
gboolean
ostree_repo_regenerate_summary (OstreeRepo     *self,
                                GVariant       *additional_metadata,
                                GCancellable   *cancellable,
                                GError        **error)
{
  g_autoptr(OstreeRepoAutoLock) lock = NULL;
  gboolean no_deltas_in_summary = FALSE;

  lock = ostree_repo_auto_lock_push (self, OSTREE_REPO_LOCK_SHARED,
                                     cancellable, error);
  if (!lock)
    return FALSE;

  g_auto(GVariantDict) additional_metadata_builder = OT_VARIANT_BUILDER_INITIALIZER;
  g_variant_dict_init (&additional_metadata_builder, additional_metadata);
  g_autoptr(GVariantBuilder) refs_builder = g_variant_builder_new (G_VARIANT_TYPE ("a(s(taya{sv}))"));

  const gchar *main_collection_id = ostree_repo_get_collection_id (self);

  {
    if (main_collection_id == NULL)
      {
        g_autoptr(GHashTable) refs = NULL;
        if (!ostree_repo_list_refs (self, NULL, &refs, cancellable, error))
          return FALSE;

        g_autoptr(GList) ordered_keys = g_hash_table_get_keys (refs);
        ordered_keys = g_list_sort (ordered_keys, (GCompareFunc)strcmp);

        for (GList *iter = ordered_keys; iter; iter = iter->next)
          {
            const char *ref = iter->data;
            const char *commit = g_hash_table_lookup (refs, ref);

            if (!summary_add_ref_entry (self, ref, commit, refs_builder, error))
              return FALSE;
          }
      }
  }

  if (!ot_keyfile_get_boolean_with_default (self->config, "core",
                                            "no-deltas-in-summary", FALSE,
                                            &no_deltas_in_summary, error))
    return FALSE;

  if (!no_deltas_in_summary)
    {
      g_autoptr(GPtrArray) delta_names = NULL;
      g_auto(GVariantDict) deltas_builder = OT_VARIANT_BUILDER_INITIALIZER;

      if (!ostree_repo_list_static_delta_names (self, &delta_names, cancellable, error))
        return FALSE;

      g_variant_dict_init (&deltas_builder, NULL);
      for (guint i = 0; i < delta_names->len; i++)
        {
          g_autofree char *from = NULL;
          g_autofree char *to = NULL;
          GVariant *digest;

          if (!_ostree_parse_delta_name (delta_names->pdata[i], &from, &to, error))
            return FALSE;

          digest = _ostree_repo_static_delta_superblock_digest (self,
                                                                (from && from[0]) ? from : NULL,
                                                                to, cancellable, error);
          if (digest == NULL)
            return FALSE;

          g_variant_dict_insert_value (&deltas_builder, delta_names->pdata[i], digest);
        }

      if (delta_names->len > 0)
        g_variant_dict_insert_value (&additional_metadata_builder, OSTREE_SUMMARY_STATIC_DELTAS, g_variant_dict_end (&deltas_builder));
    }

  {
    g_variant_dict_insert_value (&additional_metadata_builder, OSTREE_SUMMARY_LAST_MODIFIED,
                                 g_variant_new_uint64 (GUINT64_TO_BE (g_get_real_time () / G_USEC_PER_SEC)));
  }

  {
    g_autofree char *remote_mode_str = NULL;
    if (!ot_keyfile_get_value_with_default (self->config, "core", "mode", "bare",
                                            &remote_mode_str, error))
      return FALSE;
    g_variant_dict_insert_value (&additional_metadata_builder, OSTREE_SUMMARY_MODE,
                                 g_variant_new_string (remote_mode_str));
  }

  {
    gboolean tombstone_commits = FALSE;
    if (!ot_keyfile_get_boolean_with_default (self->config, "core", "tombstone-commits", FALSE,
                                              &tombstone_commits, error))
      return FALSE;
    g_variant_dict_insert_value (&additional_metadata_builder, OSTREE_SUMMARY_TOMBSTONE_COMMITS,
                                 g_variant_new_boolean (tombstone_commits));
  }

  g_variant_dict_insert_value (&additional_metadata_builder, OSTREE_SUMMARY_INDEXED_DELTAS,
                               g_variant_new_boolean (TRUE));

  /* Add refs which have a collection specified, which could be in refs/mirrors,
   * refs/heads, and/or refs/remotes. */
  {
    g_autoptr(GHashTable) collection_refs = NULL;
    if (!ostree_repo_list_collection_refs (self, NULL, &collection_refs,
                                           OSTREE_REPO_LIST_REFS_EXT_NONE, cancellable, error))
      return FALSE;

    gsize collection_map_size = 0;
    GHashTableIter iter;
    g_autoptr(GHashTable) collection_map = NULL;  /* (element-type utf8 GHashTable) */
    g_hash_table_iter_init (&iter, collection_refs);
    collection_map = g_hash_table_new_full (g_str_hash, g_str_equal, NULL,
                                            (GDestroyNotify)g_hash_table_unref);

    const OstreeCollectionRef *c_ref;
    const char *checksum;
    while (g_hash_table_iter_next (&iter, (gpointer *) &c_ref, (gpointer *) &checksum))
      {
        GHashTable *ref_map = g_hash_table_lookup (collection_map, c_ref->collection_id);

        if (ref_map == NULL)
          {
            ref_map = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, NULL);
            g_hash_table_insert (collection_map, c_ref->collection_id, ref_map);
          }

        g_hash_table_insert (ref_map, c_ref->ref_name, (gpointer) checksum);
      }

    g_autoptr(GVariantBuilder) collection_refs_builder = g_variant_builder_new (G_VARIANT_TYPE ("a{sa(s(taya{sv}))}"));

    g_autoptr(GList) ordered_collection_ids = g_hash_table_get_keys (collection_map);
    ordered_collection_ids = g_list_sort (ordered_collection_ids, (GCompareFunc) strcmp);

    for (GList *collection_iter = ordered_collection_ids; collection_iter; collection_iter = collection_iter->next)
      {
        const char *collection_id = collection_iter->data;
        GHashTable *ref_map = g_hash_table_lookup (collection_map, collection_id);

        /* We put the local repo's collection ID in the main refs map, rather
         * than the collection map, for backwards compatibility. */
        gboolean is_main_collection_id = (main_collection_id != NULL && g_str_equal (collection_id, main_collection_id));

        if (!is_main_collection_id)
          {
            g_variant_builder_open (collection_refs_builder, G_VARIANT_TYPE ("{sa(s(taya{sv}))}"));
            g_variant_builder_add (collection_refs_builder, "s", collection_id);
            g_variant_builder_open (collection_refs_builder, G_VARIANT_TYPE ("a(s(taya{sv}))"));
          }

        g_autoptr(GList) ordered_refs = g_hash_table_get_keys (ref_map);
        ordered_refs = g_list_sort (ordered_refs, (GCompareFunc) strcmp);

        for (GList *ref_iter = ordered_refs; ref_iter != NULL; ref_iter = ref_iter->next)
          {
            const char *ref = ref_iter->data;
            const char *commit = g_hash_table_lookup (ref_map, ref);
            GVariantBuilder *builder = is_main_collection_id ? refs_builder : collection_refs_builder;

            if (!summary_add_ref_entry (self, ref, commit, builder, error))
              return FALSE;

            if (!is_main_collection_id)
              collection_map_size++;
          }

        if (!is_main_collection_id)
          {
            g_variant_builder_close (collection_refs_builder);  /* array */
            g_variant_builder_close (collection_refs_builder);  /* dict entry */
          }
      }

    if (main_collection_id != NULL)
      g_variant_dict_insert_value (&additional_metadata_builder, OSTREE_SUMMARY_COLLECTION_ID,
                                   g_variant_new_string (main_collection_id));
    if (collection_map_size > 0)
      g_variant_dict_insert_value (&additional_metadata_builder, OSTREE_SUMMARY_COLLECTION_MAP,
                                   g_variant_builder_end (collection_refs_builder));
  }

  g_autoptr(GVariant) summary = NULL;
  {
    g_autoptr(GVariantBuilder) summary_builder =
      g_variant_builder_new (OSTREE_SUMMARY_GVARIANT_FORMAT);

    g_variant_builder_add_value (summary_builder, g_variant_builder_end (refs_builder));
    g_variant_builder_add_value (summary_builder, g_variant_dict_end (&additional_metadata_builder));
    summary = g_variant_builder_end (summary_builder);
    g_variant_ref_sink (summary);
  }

  if (!ostree_repo_static_delta_reindex (self, 0, NULL, cancellable, error))
    return FALSE;

  if (!_ostree_repo_file_replace_contents (self,
                                           self->repo_dir_fd,
                                           "summary",
                                           g_variant_get_data (summary),
                                           g_variant_get_size (summary),
                                           cancellable,
                                           error))
    return FALSE;

  if (!ot_ensure_unlinked_at (self->repo_dir_fd, "summary.sig", error))
    return FALSE;

  return TRUE;
}

/* Regenerate the summary if `core/auto-update-summary` is set. We default to FALSE for
 * this setting because OSTree supports multiple processes committing to the same repo (but
 * different refs) concurrently, and in fact gnome-continuous actually does this.  In that
 * context it's best to update the summary explicitly once at the end of multiple
 * transactions instead of automatically here.  `auto-update-summary` only updates
 * atomically within a transaction. */
gboolean
_ostree_repo_maybe_regenerate_summary (OstreeRepo    *self,
                                       GCancellable  *cancellable,
                                       GError       **error)
{
  gboolean auto_update_summary;
  if (!ot_keyfile_get_boolean_with_default (self->config, "core",
                                            "auto-update-summary", FALSE,
                                            &auto_update_summary, error))
    return FALSE;

  /* Deprecated alias for `auto-update-summary`. */
  gboolean commit_update_summary;
  if (!ot_keyfile_get_boolean_with_default (self->config, "core",
                                            "commit-update-summary", FALSE,
                                            &commit_update_summary, error))
    return FALSE;

  if ((auto_update_summary || commit_update_summary) &&
      !ostree_repo_regenerate_summary (self, NULL, cancellable, error))
    return FALSE;

  return TRUE;
}

gboolean
_ostree_repo_has_staging_prefix (const char *filename)
{
  return g_str_has_prefix (filename, OSTREE_REPO_TMPDIR_STAGING);
}

gboolean
_ostree_repo_try_lock_tmpdir (int            tmpdir_dfd,
                              const char    *tmpdir_name,
                              GLnxLockFile  *file_lock_out,
                              gboolean      *out_did_lock,
                              GError       **error)
{
  g_autofree char *lock_name = g_strconcat (tmpdir_name, "-lock", NULL);
  gboolean did_lock = FALSE;
  g_autoptr(GError) local_error = NULL;

  /* We put the lock outside the dir, so we can hold the lock
   * until the directory is fully removed */
  if (!glnx_make_lock_file (tmpdir_dfd, lock_name, LOCK_EX | LOCK_NB,
                            file_lock_out, &local_error))
    {
      /* we need to handle EACCES too in the case of POSIX locks; see F_SETLK in fcntl(2) */
      if (g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)
          || g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED))
        {
          did_lock = FALSE;
        }
      else
        {
          g_propagate_error (error, g_steal_pointer (&local_error));
          return FALSE;
        }
    }
  else
    {
      /* It's possible that we got a lock after seeing the directory, but
       * another process deleted the tmpdir, so verify it still exists.
       */
      struct stat stbuf;
      if (!glnx_fstatat_allow_noent (tmpdir_dfd, tmpdir_name, &stbuf, AT_SYMLINK_NOFOLLOW, error))
        return FALSE;
      if (errno == 0 && S_ISDIR (stbuf.st_mode))
        did_lock = TRUE;
      else
        glnx_release_lock_file (file_lock_out);
    }

  *out_did_lock = did_lock;
  return TRUE;
}

/* This allocates and locks a subdir of the repo tmp dir, using an existing
 * one with the same prefix if it is not in use already. */
gboolean
_ostree_repo_allocate_tmpdir (int tmpdir_dfd,
                              const char *tmpdir_prefix,
                              GLnxTmpDir *tmpdir_out,
                              GLnxLockFile *file_lock_out,
                              gboolean *reusing_dir_out,
                              GCancellable *cancellable,
                              GError **error)
{
  g_return_val_if_fail (_ostree_repo_has_staging_prefix (tmpdir_prefix), FALSE);

  /* Look for existing tmpdir (with same prefix) to reuse */
  g_auto(GLnxDirFdIterator) dfd_iter = { 0, };
  if (!glnx_dirfd_iterator_init_at (tmpdir_dfd, ".", FALSE, &dfd_iter, error))
    return FALSE;

  gboolean reusing_dir = FALSE;
  gboolean did_lock = FALSE;
  g_auto(GLnxTmpDir) ret_tmpdir = { 0, };
  while (!ret_tmpdir.initialized)
    {
      struct dirent *dent;
      g_autoptr(GError) local_error = NULL;

      if (!glnx_dirfd_iterator_next_dent (&dfd_iter, &dent, cancellable, error))
        return FALSE;

      if (dent == NULL)
        break;

      if (!g_str_has_prefix (dent->d_name, tmpdir_prefix))
        continue;

      /* Quickly skip non-dirs, if unknown we ignore ENOTDIR when opening instead */
      if (dent->d_type != DT_UNKNOWN &&
          dent->d_type != DT_DIR)
        continue;

      glnx_autofd int target_dfd = -1;
      if (!glnx_opendirat (dfd_iter.fd, dent->d_name, FALSE,
                           &target_dfd, &local_error))
        {
          if (g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_DIRECTORY) ||
              g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
            continue;
          else
            {
              g_propagate_error (error, g_steal_pointer (&local_error));
              return FALSE;
            }
        }

      /* We put the lock outside the dir, so we can hold the lock
       * until the directory is fully removed */
      if (!_ostree_repo_try_lock_tmpdir (tmpdir_dfd, dent->d_name,
                                         file_lock_out, &did_lock,
                                         error))
        return FALSE;
      if (!did_lock)
        continue;

      /* Touch the reused directory so that we don't accidentally
       * remove it due to being old when cleaning up the tmpdir.
       */
      (void)futimens (target_dfd, NULL);

      /* We found an existing tmpdir which we managed to lock */
      g_debug ("Reusing tmpdir %s", dent->d_name);
      reusing_dir = TRUE;
      ret_tmpdir.src_dfd = tmpdir_dfd;
      ret_tmpdir.fd = glnx_steal_fd (&target_dfd);
      ret_tmpdir.path = g_strdup (dent->d_name);
      ret_tmpdir.initialized = TRUE;
    }

  const char *tmpdir_name_template = glnx_strjoina (tmpdir_prefix, "XXXXXX");
  while (!ret_tmpdir.initialized)
    {
      g_auto(GLnxTmpDir) new_tmpdir = { 0, };
      /* No existing tmpdir found, create a new */
      if (!glnx_mkdtempat (tmpdir_dfd, tmpdir_name_template, DEFAULT_DIRECTORY_MODE,
                           &new_tmpdir, error))
        return FALSE;

      /* Note, at this point we can race with another process that picks up this
       * new directory. If that happens we need to retry, making a new directory. */
      if (!_ostree_repo_try_lock_tmpdir (new_tmpdir.src_dfd, new_tmpdir.path,
                                         file_lock_out, &did_lock,
                                         error))
        return FALSE;
      if (!did_lock)
        {
          /* We raced and someone else already locked the newly created
           * directory. Free the resources here and then mark it as
           * uninitialized so glnx_tmpdir_cleanup doesn't delete the directory
           * when new_tmpdir goes out of scope.
           */
          glnx_tmpdir_unset (&new_tmpdir);
          new_tmpdir.initialized = FALSE;
          continue;
        }

      g_debug ("Using new tmpdir %s", new_tmpdir.path);
      ret_tmpdir = new_tmpdir; /* Transfer ownership */
      new_tmpdir.initialized = FALSE;
    }

  *tmpdir_out = ret_tmpdir; /* Transfer ownership */
  ret_tmpdir.initialized = FALSE;
  *reusing_dir_out = reusing_dir;
  return TRUE;
}

/* See ostree-repo-private.h for more information about this */
void
_ostree_repo_memory_cache_ref_init (OstreeRepoMemoryCacheRef *state,
                                    OstreeRepo               *repo)
{
  state->repo = g_object_ref (repo);
  GMutex *lock = &repo->cache_lock;
  g_mutex_lock (lock);
  repo->dirmeta_cache_refcount++;
  if (repo->dirmeta_cache == NULL)
    repo->dirmeta_cache = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_variant_unref);
  g_mutex_unlock (lock);

}

/* See ostree-repo-private.h for more information about this */
void
_ostree_repo_memory_cache_ref_destroy (OstreeRepoMemoryCacheRef *state)
{
  OstreeRepo *repo = state->repo;
  GMutex *lock = &repo->cache_lock;
  g_mutex_lock (lock);
  repo->dirmeta_cache_refcount--;
  if (repo->dirmeta_cache_refcount == 0)
    g_clear_pointer (&repo->dirmeta_cache, g_hash_table_unref);
  g_mutex_unlock (lock);
  g_object_unref (repo);
}

/**
 * ostree_repo_get_collection_id:
 * @self: an #OstreeRepo
 *
 * Get the collection ID of this repository. See [collection IDs][collection-ids].
 *
 * Returns: (nullable): collection ID for the repository
 * Since: 2018.6
 */
const gchar *
ostree_repo_get_collection_id (OstreeRepo *self)
{
  g_return_val_if_fail (OSTREE_IS_REPO (self), NULL);

  return self->collection_id;
}

/**
 * ostree_repo_set_collection_id:
 * @self: an #OstreeRepo
 * @collection_id: (nullable): new collection ID, or %NULL to unset it
 * @error: return location for a #GError, or %NULL
 *
 * Set or clear the collection ID of this repository. See [collection IDs][collection-ids].
 * The update will be made in memory, but must be written out to the repository
 * configuration on disk using ostree_repo_write_config().
 *
 * Returns: %TRUE on success, %FALSE otherwise
 * Since: 2018.6
 */
gboolean
ostree_repo_set_collection_id (OstreeRepo   *self,
                               const gchar  *collection_id,
                               GError      **error)
{
  if (collection_id != NULL && !ostree_validate_collection_id (collection_id, error))
    return FALSE;

  g_autofree gchar *new_collection_id = g_strdup (collection_id);
  g_free (self->collection_id);
  self->collection_id = g_steal_pointer (&new_collection_id);

  if (self->config != NULL)
    {
      if (collection_id != NULL)
        g_key_file_set_string (self->config, "core", "collection-id", collection_id);
      else
        return g_key_file_remove_key (self->config, "core", "collection-id", error);
    }

  return TRUE;
}

/**
 * ostree_repo_get_default_repo_finders:
 * @self: an #OstreeRepo
 *
 * Get the set of default repo finders configured. See the documentation for
 * the "core.default-repo-finders" config key.
 *
 * Returns: (array zero-terminated=1) (element-type utf8):
 *    %NULL-terminated array of strings.
 * Since: 2018.9
 */
const gchar * const *
ostree_repo_get_default_repo_finders (OstreeRepo *self)
{
  g_return_val_if_fail (OSTREE_IS_REPO (self), NULL);

  return (const gchar * const *)self->repo_finders;
}

/**
 * ostree_repo_get_bootloader:
 * @self: an #OstreeRepo
 *
 * Get the bootloader configured. See the documentation for the
 * "sysroot.bootloader" config key.
 *
 * Returns: (transfer none): bootloader configuration for the sysroot
 * Since: 2019.2
 */
const gchar *
ostree_repo_get_bootloader (OstreeRepo   *self)
{
  g_return_val_if_fail (OSTREE_IS_REPO (self), NULL);

  return CFG_SYSROOT_BOOTLOADER_OPTS_STR[self->bootloader];
}


/**
 * _ostree_repo_verify_bindings:
 * @collection_id: (nullable): Locally specified collection ID for the remote
 *    the @commit was retrieved from, or %NULL if none is configured
 * @ref_name: (nullable): Ref name the commit was retrieved using, or %NULL if
 *    the commit was retrieved by checksum
 * @commit: Commit data to check
 * @error: Return location for a #GError, or %NULL
 *
 * Verify the ref and collection bindings.
 *
 * The ref binding is verified only if it exists. But if we have the
 * collection ID specified in the remote configuration (@collection_id is
 * non-%NULL) then the ref binding must exist, otherwise the verification will
 * fail. Parts of the verification can be skipped by passing %NULL to the
 * @ref_name parameter (in case we requested a checksum directly, without
 * looking it up from a ref).
 *
 * The collection binding is verified only when we have collection ID
 * specified in the remote configuration. If it is specified, then the
 * binding must exist and must be equal to the remote repository
 * collection ID.
 *
 * Returns: %TRUE if bindings are correct, %FALSE otherwise
 * Since: 2017.14
 */
gboolean
_ostree_repo_verify_bindings (const char  *collection_id,
                              const char  *ref_name,
                              GVariant    *commit,
                              GError     **error)
{
  g_autoptr(GVariant) metadata = g_variant_get_child_value (commit, 0);
  g_autofree const char **refs = NULL;
  if (!g_variant_lookup (metadata,
                         OSTREE_COMMIT_META_KEY_REF_BINDING,
                         "^a&s",
                         &refs))
    {
      /* Early return here - if the remote collection ID is NULL, then
       * we certainly will not verify the collection binding in the
       * commit.
       */
      if (collection_id == NULL)
        return TRUE;

      return glnx_throw (error,
                         "Expected commit metadata to have ref "
                         "binding information, found none");
    }

  if (ref_name != NULL)
    {
      if (!g_strv_contains ((const char *const *) refs, ref_name))
        {
          g_autoptr(GString) refs_dump = g_string_new (NULL);
          const char *refs_str;

          if (refs != NULL && (*refs) != NULL)
            {
              for (const char **iter = refs; *iter != NULL; ++iter)
                {
                  const char *ref = *iter;

                  if (refs_dump->len > 0)
                    g_string_append (refs_dump, ", ");
                  g_string_append_printf (refs_dump, "‘%s’", ref);
                }

              refs_str = refs_dump->str;
            }
          else
            {
              refs_str = "no refs";
            }

          return glnx_throw (error, "Commit has no requested ref ‘%s’ "
                             "in ref binding metadata (%s)",
                             ref_name, refs_str);
        }
    }

  if (collection_id != NULL)
    {
      const char *collection_id_binding;
      if (!g_variant_lookup (metadata,
                             OSTREE_COMMIT_META_KEY_COLLECTION_BINDING,
                             "&s",
                             &collection_id_binding))
        return glnx_throw (error,
                           "Expected commit metadata to have collection ID "
                           "binding information, found none");
      if (!g_str_equal (collection_id_binding, collection_id))
        return glnx_throw (error,
                           "Commit has collection ID ‘%s’ in collection binding "
                           "metadata, while the remote it came from has "
                           "collection ID ‘%s’",
                           collection_id_binding, collection_id);
    }

  return TRUE;
}