summaryrefslogtreecommitdiffstats
path: root/tools/gpgconf-comp.c
blob: 7a56c5b746bcfdc331474b47b3382827f58fea23 (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
/* gpgconf-comp.c - Configuration utility for GnuPG.
 * Copyright (C) 2004, 2007, 2008 Free Software Foundation, Inc.
 *
 * This file is part of GnuPG.
 *
 * GnuPG is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * GnuPG 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
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GnuPG; if not, see <http://www.gnu.org/licenses/>.
 */

#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <time.h>
#include <stdarg.h>
#include <signal.h>
#include <ctype.h>
#ifdef HAVE_W32_SYSTEM
# define WIN32_LEAN_AND_MEAN 1
# include <windows.h>
#else
# include <pwd.h>
# include <grp.h>
#endif

/* For log_logv(), asctimestamp(), gnupg_get_time ().  */
#define JNLIB_NEED_LOG_LOGV
#include "util.h"
#include "i18n.h"
#include "exechelp.h"

#include "gc-opt-flags.h"
#include "gpgconf.h"


/* There is a problem with gpg 1.4 under Windows: --gpgconf-list
   returns a plain filename without escaping.  As long as we have not
   fixed that we need to use gpg2 - it might actually be better to use
   gpg2 in any case.  */
#ifdef HAVE_W32_SYSTEM
#define GPGNAME "gpg2"
#else
#define GPGNAME "gpg"
#endif


/* TODO:
   Components: Add more components and their options.
   Robustness: Do more validation.  Call programs to do validation for us.
   Add options to change backend binary path.
   Extract binary path for some backends from gpgsm/gpg config.
*/


#if (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ))
void gc_error (int status, int errnum, const char *fmt, ...) \
  __attribute__ ((format (printf, 3, 4)));
#endif

/* Output a diagnostic message.  If ERRNUM is not 0, then the output
   is followed by a colon, a white space, and the error string for the
   error number ERRNUM.  In any case the output is finished by a
   newline.  The message is prepended by the program name, a colon,
   and a whitespace.  The output may be further formatted or
   redirected by the jnlib logging facility.  */
void
gc_error (int status, int errnum, const char *fmt, ...)
{
  va_list arg_ptr;

  va_start (arg_ptr, fmt);
  log_logv (JNLIB_LOG_ERROR, fmt, arg_ptr);
  va_end (arg_ptr);

  if (errnum)
    log_printf (": %s\n", strerror (errnum));
  else
    log_printf ("\n");

  if (status)
    {
      log_printf (NULL);
      log_printf ("fatal error (exit status %i)\n", status);
      exit (status);
    }
}


/* Forward declaration.  */
void gpg_agent_runtime_change (void);

/* Backend configuration.  Backends are used to decide how the default
   and current value of an option can be determined, and how the
   option can be changed.  To every option in every component belongs
   exactly one backend that controls and determines the option.  Some
   backends are programs from the GPG system.  Others might be
   implemented by GPGConf itself.  If you change this enum, don't
   forget to update GC_BACKEND below.  */
typedef enum
  {
    /* Any backend, used for find_option ().  */
    GC_BACKEND_ANY,

    /* The Gnu Privacy Guard.  */
    GC_BACKEND_GPG,

    /* The Gnu Privacy Guard for S/MIME.  */
    GC_BACKEND_GPGSM,

    /* The GPG Agent.  */
    GC_BACKEND_GPG_AGENT,

    /* The GnuPG SCDaemon.  */
    GC_BACKEND_SCDAEMON,

    /* The Aegypten directory manager.  */
    GC_BACKEND_DIRMNGR,

    /* The LDAP server list file for the Aegypten director manager.  */
    GC_BACKEND_DIRMNGR_LDAP_SERVER_LIST,

    /* The number of the above entries.  */
    GC_BACKEND_NR
  } gc_backend_t;


/* To be able to implement generic algorithms for the various
   backends, we collect all information about them in this struct.  */
static struct
{
  /* The name of the backend.  */
  const char *name;

  /* The name of the program that acts as the backend.  Some backends
     don't have an associated program, but are implemented directly by
     GPGConf.  In this case, PROGRAM is NULL.  */
  char *program;

  /* The module name (GNUPG_MODULE_NAME_foo) as defined by
     ../common/util.h.  This value is used to get the actual installed
     path of the program.  0 is used if no backedn program is
     available. */
  char module_name;

  /* The runtime change callback.  */
  void (*runtime_change) (void);

  /* The option name for the configuration filename of this backend.
     This must be an absolute pathname.  It can be an option from a
     different backend (but then ordering of the options might
     matter).  */
  const char *option_config_filename;

  /* If this is a file backend rather than a program backend, then
     this is the name of the option associated with the file.  */
  const char *option_name;
} gc_backend[GC_BACKEND_NR] =
  {
    { NULL },		/* GC_BACKEND_ANY dummy entry.  */
    { "GnuPG", GPGNAME, GNUPG_MODULE_NAME_GPG,
      NULL, "gpgconf-gpg.conf" },
    { "GPGSM", "gpgsm", GNUPG_MODULE_NAME_GPGSM,
      NULL, "gpgconf-gpgsm.conf" },
    { "GPG Agent", "gpg-agent", GNUPG_MODULE_NAME_AGENT, 
      gpg_agent_runtime_change, "gpgconf-gpg-agent.conf" },
    { "SCDaemon", "scdaemon", GNUPG_MODULE_NAME_SCDAEMON,
      NULL, "gpgconf-scdaemon.conf" },
    { "DirMngr", "dirmngr", GNUPG_MODULE_NAME_DIRMNGR,
      NULL, "gpgconf-dirmngr.conf" },
    { "DirMngr LDAP Server List", NULL, 0, 
      NULL, "ldapserverlist-file", "LDAP Server" },
  };


/* Option configuration.  */

/* An option might take an argument, or not.  Argument types can be
   basic or complex.  Basic types are generic and easy to validate.
   Complex types provide more specific information about the intended
   use, but can be difficult to validate.  If you add to this enum,
   don't forget to update GC_ARG_TYPE below.  YOU MUST NOT CHANGE THE
   NUMBERS OF THE EXISTING ENTRIES, AS THEY ARE PART OF THE EXTERNAL
   INTERFACE.  */
typedef enum
  {
    /* Basic argument types.  */

    /* No argument.  */
    GC_ARG_TYPE_NONE = 0,

    /* A String argument.  */
    GC_ARG_TYPE_STRING = 1,

    /* A signed integer argument.  */
    GC_ARG_TYPE_INT32 = 2,

    /* An unsigned integer argument.  */
    GC_ARG_TYPE_UINT32 = 3,

    /* ADD NEW BASIC TYPE ENTRIES HERE.  */

    /* Complex argument types.  */

    /* A complete pathname.  */
    GC_ARG_TYPE_PATHNAME = 32,

    /* An LDAP server in the format
       HOSTNAME:PORT:USERNAME:PASSWORD:BASE_DN.  */
    GC_ARG_TYPE_LDAP_SERVER = 33,

    /* A 40 character fingerprint.  */
    GC_ARG_TYPE_KEY_FPR = 34,

    /* A user ID or key ID or fingerprint for a certificate.  */
    GC_ARG_TYPE_PUB_KEY = 35,

    /* A user ID or key ID or fingerprint for a certificate with a key.  */
    GC_ARG_TYPE_SEC_KEY = 36,

    /* ADD NEW COMPLEX TYPE ENTRIES HERE.  */

    /* The number of the above entries.  */
    GC_ARG_TYPE_NR
  } gc_arg_type_t;


/* For every argument, we record some information about it in the
   following struct.  */
static struct
{
  /* For every argument type exists a basic argument type that can be
     used as a fallback for input and validation purposes.  */
  gc_arg_type_t fallback;

  /* Human-readable name of the type.  */
  const char *name;
} gc_arg_type[GC_ARG_TYPE_NR] =
  {
    /* The basic argument types have their own types as fallback.  */
    { GC_ARG_TYPE_NONE, "none" },
    { GC_ARG_TYPE_STRING, "string" },
    { GC_ARG_TYPE_INT32, "int32" },
    { GC_ARG_TYPE_UINT32, "uint32" },

    /* Reserved basic type entries for future extension.  */
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
    { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },

    /* The complex argument types have a basic type as fallback.  */
    { GC_ARG_TYPE_STRING, "pathname" },
    { GC_ARG_TYPE_STRING, "ldap server" },
    { GC_ARG_TYPE_STRING, "key fpr" },
    { GC_ARG_TYPE_STRING, "pub key" },
    { GC_ARG_TYPE_STRING, "sec key" },
  };


/* Every option has an associated expert level, than can be used to
   hide advanced and expert options from beginners.  If you add to
   this list, don't forget to update GC_LEVEL below.  YOU MUST NOT
   CHANGE THE NUMBERS OF THE EXISTING ENTRIES, AS THEY ARE PART OF THE
   EXTERNAL INTERFACE.  */
typedef enum
  {
    /* The basic options should always be displayed.  */
    GC_LEVEL_BASIC,

    /* The advanced options may be hidden from beginners.  */
    GC_LEVEL_ADVANCED,

    /* The expert options should only be displayed to experts.  */
    GC_LEVEL_EXPERT,

    /* The invisible options should normally never be displayed.  */
    GC_LEVEL_INVISIBLE,

    /* The internal options are never exported, they mark options that
       are recorded for internal use only.  */
    GC_LEVEL_INTERNAL,

    /* ADD NEW ENTRIES HERE.  */

    /* The number of the above entries.  */
    GC_LEVEL_NR
  } gc_expert_level_t;

/* A description for each expert level.  */
static struct
{
  const char *name;
} gc_level[] =
  {
    { "basic" },
    { "advanced" },
    { "expert" },
    { "invisible" },
    { "internal" }
  };


/* Option flags.  The flags which are used by the backends are defined
   by gc-opt-flags.h, included above.

   YOU MUST NOT CHANGE THE NUMBERS OF THE EXISTING FLAGS, AS THEY ARE
   PART OF THE EXTERNAL INTERFACE.  */

/* Some entries in the option list are not options, but mark the
   beginning of a new group of options.  These entries have the GROUP
   flag set.  */
#define GC_OPT_FLAG_GROUP	(1UL << 0)
/* The ARG_OPT flag for an option indicates that the argument is
   optional.  This is never set for GC_ARG_TYPE_NONE options.  */
#define GC_OPT_FLAG_ARG_OPT	(1UL << 1)
/* The LIST flag for an option indicates that the option can occur
   several times.  A comma separated list of arguments is used as the
   argument value.  */
#define GC_OPT_FLAG_LIST	(1UL << 2)
/* The NO_CHANGE flag for an option indicates that the user should not
   be allowed to change this option using the standard gpgconf method.
   Frontends using gpgconf should grey out such options, so that only
   the current value is displayed.  */
#define GC_OPT_FLAG_NO_CHANGE   (1UL <<7)


/* A human-readable description for each flag.  */
static struct
{
  const char *name;
} gc_flag[] =
  {
    { "group" },
    { "optional arg" },
    { "list" },
    { "runtime" },
    { "default" },
    { "default desc" },
    { "no arg desc" },
    { "no change" }
  };


/* To each option, or group marker, the information in the GC_OPTION
   struct is provided.  If you change this, don't forget to update the
   option list of each component.  */
struct gc_option
{
  /* If this is NULL, then this is a terminator in an array of unknown
     length.  Otherwise, if this entry is a group marker (see FLAGS),
     then this is the name of the group described by this entry.
     Otherwise it is the name of the option described by this
     entry.  The name must not contain a colon.  */
  const char *name;

  /* The option flags.  If the GROUP flag is set, then this entry is a
     group marker, not an option, and only the fields LEVEL,
     DESC_DOMAIN and DESC are valid.  In all other cases, this entry
     describes a new option and all fields are valid.  */
  unsigned long flags;

  /* The expert level.  This field is valid for options and groups.  A
     group has the expert level of the lowest-level option in the
     group.  */
  gc_expert_level_t level;

  /* A gettext domain in which the following description can be found.
     If this is NULL, then DESC is not translated.  Valid for groups
     and options.
     
     Note that we try to keep the description of groups within the
     gnupg domain. 
     
     IMPORTANT: If you add a new domain please make sure to add a code
     set switching call to the function my_dgettext further below.  */
  const char *desc_domain;

  /* A gettext description for this group or option.  If it starts
     with a '|', then the string up to the next '|' describes the
     argument, and the description follows the second '|'. 

     In general enclosing these description in N_() is not required
     because the description should be identical to the one in the
     help menu of the respective program. */
  const char *desc;

  /* The following fields are only valid for options.  */

  /* The type of the option argument.  */
  gc_arg_type_t arg_type;

  /* The backend that implements this option.  */
  gc_backend_t backend;

  /* The following fields are set to NULL at startup (because all
     option's are declared as static variables).  They are at the end
     of the list so that they can be omitted from the option
     declarations.  */

  /* This is true if the option is supported by this version of the
     backend.  */
  int active;

  /* The default value for this option.  This is NULL if the option is
     not present in the backend, the empty string if no default is
     available, and otherwise a quoted string.  */
  char *default_value;

  /* The default argument is only valid if the "optional arg" flag is
     set, and specifies the default argument (value) that is used if
     the argument is omitted.  */
  char *default_arg;

  /* The current value of this option.  */
  char *value;

  /* The new flags for this option.  The only defined flag is actually
     GC_OPT_FLAG_DEFAULT, and it means that the option should be
     deleted.  In this case, NEW_VALUE is NULL.  */
  unsigned long new_flags;

  /* The new value of this option.  */
  char *new_value;
};
typedef struct gc_option gc_option_t;

/* Use this macro to terminate an option list.  */
#define GC_OPTION_NULL { NULL }


/* The options of the GC_COMPONENT_GPG_AGENT component.  */
static gc_option_t gc_options_gpg_agent[] =
 {
   /* The configuration file to which we write the changes.  */
   { "gpgconf-gpg-agent.conf", GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
     NULL, NULL, GC_ARG_TYPE_PATHNAME, GC_BACKEND_GPG_AGENT },

   { "Monitor",
     GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
     "gnupg", N_("Options controlling the diagnostic output") },
   { "verbose", GC_OPT_FLAG_LIST|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC,
     "gnupg", "verbose",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
   { "quiet", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC,
     "gnupg", "be somewhat more quiet",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
   { "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
     NULL, NULL,
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },

   { "Configuration",
     GC_OPT_FLAG_GROUP, GC_LEVEL_EXPERT,
     "gnupg", N_("Options controlling the configuration") },
   { "options", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
     "gnupg", "|FILE|read options from FILE",
     GC_ARG_TYPE_PATHNAME, GC_BACKEND_GPG_AGENT },
   { "disable-scdaemon", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "gnupg", "do not use the SCdaemon",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },

   { "Debug",
     GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
     "gnupg", N_("Options useful for debugging") },
   { "debug-level", GC_OPT_FLAG_ARG_OPT|GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED,
     "gnupg", "|LEVEL|set the debugging level to LEVEL",
     GC_ARG_TYPE_STRING, GC_BACKEND_GPG_AGENT },
   { "log-file", GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED,
     "gnupg", N_("|FILE|write server mode logs to FILE"),
     GC_ARG_TYPE_PATHNAME, GC_BACKEND_GPG_AGENT },
   { "faked-system-time", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
     NULL, NULL,
     GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },

   { "Security",
     GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
     "gnupg", N_("Options controlling the security") },
   { "default-cache-ttl", GC_OPT_FLAG_RUNTIME,
     GC_LEVEL_BASIC, "gnupg", 
     "|N|expire cached PINs after N seconds",
     GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
   { "default-cache-ttl-ssh", GC_OPT_FLAG_RUNTIME,
     GC_LEVEL_ADVANCED, "gnupg",
     N_("|N|expire SSH keys after N seconds"),
     GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
   { "max-cache-ttl", GC_OPT_FLAG_RUNTIME,
     GC_LEVEL_EXPERT, "gnupg",
     N_("|N|set maximum PIN cache lifetime to N seconds"),
     GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
   { "max-cache-ttl-ssh", GC_OPT_FLAG_RUNTIME,
     GC_LEVEL_EXPERT, "gnupg", 
     N_("|N|set maximum SSH key lifetime to N seconds"),
     GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
   { "ignore-cache-for-signing", GC_OPT_FLAG_RUNTIME,
     GC_LEVEL_BASIC, "gnupg", "do not use the PIN cache when signing",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
   { "allow-mark-trusted", GC_OPT_FLAG_RUNTIME,
     GC_LEVEL_ADVANCED, "gnupg", "allow clients to mark keys as \"trusted\"",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
   { "no-grab", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT,
     "gnupg", "do not grab keyboard and mouse",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },

   { "Passphrase policy",
     GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
     "gnupg", N_("Options enforcing a passphrase policy") },
   { "enforce-passphrase-constraints", GC_OPT_FLAG_RUNTIME, 
     GC_LEVEL_EXPERT, "gnupg", 
     N_("do not allow to bypass the passphrase policy"),
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
   { "min-passphrase-len", GC_OPT_FLAG_RUNTIME,
     GC_LEVEL_ADVANCED, "gnupg", 
     N_("|N|set minimal required length for new passphrases to N"),
     GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
   { "min-passphrase-nonalpha", GC_OPT_FLAG_RUNTIME,
     GC_LEVEL_EXPERT, "gnupg", 
     N_("|N|require at least N non-alpha characters for a new passphrase"),
     GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
   { "check-passphrase-pattern", GC_OPT_FLAG_RUNTIME,
     GC_LEVEL_EXPERT,
     "gnupg", N_("|FILE|check new passphrases against pattern in FILE"),
     GC_ARG_TYPE_PATHNAME, GC_BACKEND_GPG_AGENT },
   { "max-passphrase-days", GC_OPT_FLAG_RUNTIME,
     GC_LEVEL_EXPERT, "gnupg", 
     N_("|N|expire the passphrase after N days"),
     GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
   { "enable-passphrase-history", GC_OPT_FLAG_RUNTIME, 
     GC_LEVEL_EXPERT, "gnupg", 
     N_("do not allow the reuse of old passphrases"),
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },

   GC_OPTION_NULL
 };


/* The options of the GC_COMPONENT_SCDAEMON component.  */
static gc_option_t gc_options_scdaemon[] =
 {
   /* The configuration file to which we write the changes.  */
   { "gpgconf-scdaemon.conf", GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
     NULL, NULL, GC_ARG_TYPE_PATHNAME, GC_BACKEND_SCDAEMON },

   { "Monitor",
     GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
     "gnupg", N_("Options controlling the diagnostic output") },
   { "verbose", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC,
     "gnupg", "verbose",
     GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },
   { "quiet", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", "be somewhat more quiet",
     GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },
   { "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
     NULL, NULL,
     GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },

   { "Configuration",
     GC_OPT_FLAG_GROUP, GC_LEVEL_EXPERT,
     "gnupg", N_("Options controlling the configuration") },
   { "options", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
     "gnupg", "|FILE|read options from FILE",
     GC_ARG_TYPE_PATHNAME, GC_BACKEND_SCDAEMON },
   { "reader-port", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", "|N|connect to reader at port N",
     GC_ARG_TYPE_STRING, GC_BACKEND_SCDAEMON },
   { "ctapi-driver", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "gnupg", "|NAME|use NAME as ct-API driver",
     GC_ARG_TYPE_STRING, GC_BACKEND_SCDAEMON },
   { "pcsc-driver", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "gnupg", "|NAME|use NAME as PC/SC driver",
     GC_ARG_TYPE_STRING, GC_BACKEND_SCDAEMON },
   { "disable-opensc", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
     "gnupg", "do not use the OpenSC layer",
     GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },
   { "disable-ccid", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
     "gnupg", "do not use the internal CCID driver",
     GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },
   { "disable-keypad", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", "do not use a reader's keypad",
     GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },

   { "Debug",
     GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
     "gnupg", N_("Options useful for debugging") },
   { "debug-level", GC_OPT_FLAG_ARG_OPT, GC_LEVEL_ADVANCED,
     "gnupg", "|LEVEL|set the debugging level to LEVEL",
     GC_ARG_TYPE_STRING, GC_BACKEND_SCDAEMON },
   { "log-file", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "gnupg", N_("|FILE|write server mode logs to FILE"),
     GC_ARG_TYPE_PATHNAME, GC_BACKEND_SCDAEMON },

   { "Security",
     GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
     "gnupg", N_("Options controlling the security") },
   { "allow-admin", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", "allow the use of admin card commands",
     GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },


   GC_OPTION_NULL
 };


/* The options of the GC_COMPONENT_GPG component.  */
static gc_option_t gc_options_gpg[] =
 {
   /* The configuration file to which we write the changes.  */
   { "gpgconf-gpg.conf", GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
     NULL, NULL, GC_ARG_TYPE_PATHNAME, GC_BACKEND_GPG },

   { "Monitor",
     GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
     "gnupg", N_("Options controlling the diagnostic output") },
   { "verbose", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC,
     "gnupg", "verbose",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG },
   { "quiet", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", "be somewhat more quiet",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG },
   { "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
     NULL, NULL,
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG },

   { "Configuration",
     GC_OPT_FLAG_GROUP, GC_LEVEL_EXPERT,
     "gnupg", N_("Options controlling the configuration") },
   { "default-key", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", N_("|NAME|use NAME as default secret key"),
     GC_ARG_TYPE_STRING, GC_BACKEND_GPG },
   { "encrypt-to", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", N_("|NAME|encrypt to user ID NAME as well"),
     GC_ARG_TYPE_STRING, GC_BACKEND_GPG },
   { "options", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
     "gnupg", "|FILE|read options from FILE",
     GC_ARG_TYPE_PATHNAME, GC_BACKEND_GPG },

   { "Debug",
     GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
     "gnupg", N_("Options useful for debugging") },
   { "debug-level", GC_OPT_FLAG_ARG_OPT, GC_LEVEL_ADVANCED,
     "gnupg", "|LEVEL|set the debugging level to LEVEL",
     GC_ARG_TYPE_STRING, GC_BACKEND_GPG },
   { "log-file", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "gnupg", N_("|FILE|write server mode logs to FILE"),
     GC_ARG_TYPE_PATHNAME, GC_BACKEND_GPG },
/*    { "faked-system-time", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE, */
/*      NULL, NULL, */
/*      GC_ARG_TYPE_UINT32, GC_BACKEND_GPG }, */

   { "Keyserver",
     GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
     "gnupg", N_("Configuration for Keyservers") },
   { "keyserver", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", N_("|URL|use keyserver at URL"),
     GC_ARG_TYPE_STRING, GC_BACKEND_GPG },
   { "allow-pka-lookup", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", N_("allow PKA lookups (DNS requests)"),
     GC_ARG_TYPE_NONE, GC_BACKEND_GPG },


   GC_OPTION_NULL
 };



/* The options of the GC_COMPONENT_GPGSM component.  */
static gc_option_t gc_options_gpgsm[] =
 {
   /* The configuration file to which we write the changes.  */
   { "gpgconf-gpgsm.conf", GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
     NULL, NULL, GC_ARG_TYPE_PATHNAME, GC_BACKEND_GPGSM },

   { "Monitor",
     GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
     "gnupg", N_("Options controlling the diagnostic output") },
   { "verbose", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC,
     "gnupg", "verbose",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
   { "quiet", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", "be somewhat more quiet",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
   { "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
     NULL, NULL,
     GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },

   { "Configuration",
     GC_OPT_FLAG_GROUP, GC_LEVEL_EXPERT,
     "gnupg", N_("Options controlling the configuration") },
   { "default-key", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", N_("|NAME|use NAME as default secret key"),
     GC_ARG_TYPE_STRING, GC_BACKEND_GPGSM },
   { "encrypt-to", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", N_("|NAME|encrypt to user ID NAME as well"),
     GC_ARG_TYPE_STRING, GC_BACKEND_GPGSM },
   { "options", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
     "gnupg", "|FILE|read options from FILE",
     GC_ARG_TYPE_PATHNAME, GC_BACKEND_GPGSM },
   { "prefer-system-dirmngr", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "gnupg", "use system's dirmngr if available",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
   { "disable-dirmngr", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
     "gnupg", N_("disable all access to the dirmngr"),
     GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
   { "p12-charset", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "gnupg", N_("|NAME|use encoding NAME for PKCS#12 passphrases"),
     GC_ARG_TYPE_STRING, GC_BACKEND_GPGSM },

   { "Debug",
     GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
     "gnupg", N_("Options useful for debugging") },
   { "debug-level", GC_OPT_FLAG_ARG_OPT, GC_LEVEL_ADVANCED,
     "gnupg", "|LEVEL|set the debugging level to LEVEL",
     GC_ARG_TYPE_STRING, GC_BACKEND_GPGSM },
   { "log-file", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "gnupg", N_("|FILE|write server mode logs to FILE"),
     GC_ARG_TYPE_PATHNAME, GC_BACKEND_GPGSM },
   { "faked-system-time", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
     NULL, NULL,
     GC_ARG_TYPE_UINT32, GC_BACKEND_GPGSM },

   { "Security",
     GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
     "gnupg", N_("Options controlling the security") },
   { "disable-crl-checks", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", "never consult a CRL",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
   { "disable-trusted-cert-crl-check", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
     "gnupg", N_("do not check CRLs for root certificates"),
     GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
   { "enable-ocsp", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "gnupg", "check validity using OCSP",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
   { "include-certs", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
     "gnupg", "|N|number of certificates to include",
     GC_ARG_TYPE_INT32, GC_BACKEND_GPGSM },
   { "disable-policy-checks", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "gnupg", "do not check certificate policies",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
   { "auto-issuer-key-retrieve", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "gnupg", "fetch missing issuer certificates",
     GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
   { "cipher-algo", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "gnupg", "|NAME|use cipher algorithm NAME",
     GC_ARG_TYPE_STRING, GC_BACKEND_GPGSM },

   GC_OPTION_NULL
 };


/* The options of the GC_COMPONENT_DIRMNGR component.  */
static gc_option_t gc_options_dirmngr[] =
 {
   /* The configuration file to which we write the changes.  */
   { "gpgconf-dirmngr.conf", GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
     NULL, NULL, GC_ARG_TYPE_PATHNAME, GC_BACKEND_DIRMNGR },

   { "Monitor",
     GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
     "gnupg", N_("Options controlling the diagnostic output") },
   { "verbose", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC,
     "dirmngr", "verbose",
     GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "quiet", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "dirmngr", "be somewhat more quiet",
     GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
     NULL, NULL,
     GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },

   { "Format",
     GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
     "gnupg", N_("Options controlling the format of the output") },
   { "sh", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "dirmngr", "sh-style command output",
     GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "csh", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "dirmngr", "csh-style command output",
     GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   
   { "Configuration",
     GC_OPT_FLAG_GROUP, GC_LEVEL_EXPERT,
     "gnupg", N_("Options controlling the configuration") },
   { "options", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
     "dirmngr", "|FILE|read options from FILE",
     GC_ARG_TYPE_PATHNAME, GC_BACKEND_DIRMNGR },

   { "Debug",
     GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
     "gnupg", N_("Options useful for debugging") },
   { "debug-level", GC_OPT_FLAG_ARG_OPT, GC_LEVEL_ADVANCED,
     "dirmngr", "|LEVEL|set the debugging level to LEVEL",
     GC_ARG_TYPE_STRING, GC_BACKEND_DIRMNGR },
   { "no-detach", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "dirmngr", "do not detach from the console",
     GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "log-file", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "dirmngr", N_("|FILE|write server mode logs to FILE"),
     GC_ARG_TYPE_PATHNAME, GC_BACKEND_DIRMNGR },
   { "debug-wait", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
     NULL, NULL,
     GC_ARG_TYPE_UINT32, GC_BACKEND_DIRMNGR },
   { "faked-system-time", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
     NULL, NULL,
     GC_ARG_TYPE_UINT32, GC_BACKEND_DIRMNGR },

   { "Enforcement",
     GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
     "gnupg", N_("Options controlling the interactivity and enforcement") },
   { "batch", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "dirmngr", "run without asking a user",
     GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "force", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "dirmngr", "force loading of outdated CRLs",
     GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },

   { "HTTP",
     GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
     "gnupg", N_("Configuration for HTTP servers") },
   { "disable-http", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "dirmngr", "inhibit the use of HTTP",
      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "ignore-http-dp", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "dirmngr", "ignore HTTP CRL distribution points",
      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "http-proxy", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "dirmngr", "|URL|redirect all HTTP requests to URL",
     GC_ARG_TYPE_STRING, GC_BACKEND_DIRMNGR },
   { "honor-http-proxy", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "gnupg", N_("use system's HTTP proxy setting"),
     GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },

   { "LDAP",
     GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
     "gnupg", N_("Configuration of LDAP servers to use") },
   { "disable-ldap", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "dirmngr", "inhibit the use of LDAP",
      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "ignore-ldap-dp", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "dirmngr", "ignore LDAP CRL distribution points",
      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "ldap-proxy", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "dirmngr", "|HOST|use HOST for LDAP queries",
     GC_ARG_TYPE_STRING, GC_BACKEND_DIRMNGR },
   { "only-ldap-proxy", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "dirmngr", "do not use fallback hosts with --ldap-proxy",
      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "add-servers", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "dirmngr", "add new servers discovered in CRL distribution points"
     " to serverlist", GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "ldaptimeout", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "dirmngr", "|N|set LDAP timeout to N seconds",
     GC_ARG_TYPE_UINT32, GC_BACKEND_DIRMNGR },
   /* The following entry must not be removed, as it is required for
      the GC_BACKEND_DIRMNGR_LDAP_SERVER_LIST.  */
   { "ldapserverlist-file",
     GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
     "dirmngr", "|FILE|read LDAP server list from FILE",
     GC_ARG_TYPE_PATHNAME, GC_BACKEND_DIRMNGR },
   /* This entry must come after at least one entry for
      GC_BACKEND_DIRMNGR in this component, so that the entry for
      "ldapserverlist-file will be initialized before this one.  */
   { "LDAP Server", GC_OPT_FLAG_ARG_OPT|GC_OPT_FLAG_LIST, GC_LEVEL_BASIC,
     "gnupg", N_("LDAP server list"),
     GC_ARG_TYPE_LDAP_SERVER, GC_BACKEND_DIRMNGR_LDAP_SERVER_LIST },
   { "max-replies", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "dirmngr", "|N|do not return more than N items in one query",
     GC_ARG_TYPE_UINT32, GC_BACKEND_DIRMNGR },

   { "OCSP",
     GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
     "gnupg", N_("Configuration for OCSP") },
   { "allow-ocsp", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
     "dirmngr", "allow sending OCSP requests",
     GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "ignore-ocsp-service-url", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "dirmngr", "ignore certificate contained OCSP service URLs",
      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
   { "ocsp-responder", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "dirmngr", "|URL|use OCSP responder at URL",
     GC_ARG_TYPE_STRING, GC_BACKEND_DIRMNGR },
   { "ocsp-signer", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
     "dirmngr", "|FPR|OCSP response signed by FPR",
     GC_ARG_TYPE_STRING, GC_BACKEND_DIRMNGR },


   GC_OPTION_NULL
 };


/* Component system.  Each component is a set of options that can be
   configured at the same time.  If you change this, don't forget to
   update GC_COMPONENT below.  */
typedef enum
  {
    /* The classic GPG for OpenPGP.  */
    GC_COMPONENT_GPG,

    /* The GPG Agent.  */
    GC_COMPONENT_GPG_AGENT,

    /* The Smardcard Daemon.  */
    GC_COMPONENT_SCDAEMON,

    /* GPG for S/MIME.  */
    GC_COMPONENT_GPGSM,

    /* The LDAP Directory Manager for CRLs.  */
    GC_COMPONENT_DIRMNGR,

    /* The number of components.  */
    GC_COMPONENT_NR
  } gc_component_t;


/* The information associated with each component.  */
static struct
{
  /* The name of this component.  Must not contain a colon (':')
     character.  */
  const char *name;

  /* The gettext domain for the description DESC.  If this is NULL,
     then the description is not translated.  */
  const char *desc_domain;

  /* The description for this domain.  */
  const char *desc;

  /* The list of options for this component, terminated by
     GC_OPTION_NULL.  */
  gc_option_t *options;
} gc_component[] =
  {
    { "gpg", NULL,   "GPG for OpenPGP", gc_options_gpg },
    { "gpg-agent", NULL, "GPG Agent", gc_options_gpg_agent },
    { "scdaemon", NULL, "Smartcard Daemon", gc_options_scdaemon },
    { "gpgsm", NULL, "GPG for S/MIME", gc_options_gpgsm },
    { "dirmngr", NULL, "Directory Manager", gc_options_dirmngr }
  };



/* Structure used to collect error output of the backend programs.  */
struct error_line_s;
typedef struct error_line_s *error_line_t;
struct error_line_s
{
  error_line_t next;   /* Link to next item.  */
  const char *fname;   /* Name of the config file (points into BUFFER).  */
  unsigned int lineno; /* Line number of the config file.  */
  const char *errtext; /* Text of the error message (points into BUFFER).  */
  char buffer[1];  /* Helper buffer.  */
};



/* Engine specific support.  */
void
gpg_agent_runtime_change (void)
{
#ifndef HAVE_W32_SYSTEM
  char *agent = getenv ("GPG_AGENT_INFO");
  char *pid_str;
  unsigned long pid_long;
  char *tail;
  pid_t pid;

  if (!agent)
    return;

  pid_str = strchr (agent, ':');
  if (!pid_str)
    return;

  pid_str++;
  errno = 0;
  pid_long = strtoul (pid_str, &tail, 0);
  if (errno || (*tail != ':' && *tail != '\0'))
    return;

  pid = (pid_t) pid_long;

  /* Check for overflow.  */
  if (pid_long != (unsigned long) pid)
    return;

  /* Ignore any errors here.  */
  kill (pid, SIGHUP);
#endif /*!HAVE_W32_SYSTEM*/
}


/* More or less Robust version of dgettext.  It has the side effect of
   switching the codeset to utf-8 because this is what we want to
   output.  In theory it is posible to keep the orginal code set and
   switch back for regular disgnostic output (redefine "_(" for that)
   but given the natur of this tool, being something invoked from
   other pograms, it does not make much sense.  */
static const char *
my_dgettext (const char *domain, const char *msgid)
{
#ifdef ENABLE_NLS
  if (domain)
    {
      static int switched_codeset;
      char *text;
      
      if (!switched_codeset)
        {
          switched_codeset = 1;
          bind_textdomain_codeset (PACKAGE_GT, "utf-8");

          bindtextdomain ("dirmngr", LOCALEDIR);
          bind_textdomain_codeset ("dirmngr", "utf-8");
   
        }

      /* Note: This is a hack to actually use the gnupg2 domain as
         long we are in a transition phase where gnupg 1.x and 1.9 may
         coexist. */
      if (!strcmp (domain, "gnupg"))
        domain = PACKAGE_GT;

      text = dgettext (domain, msgid);
      return text ? text : msgid;
    }
  else
#endif
    return msgid;
}


/* Percent-Escape special characters.  The string is valid until the
   next invocation of the function.  */
static char *
my_percent_escape (const char *src)
{
  static char *esc_str;
  static int esc_str_len;
  int new_len = 3 * strlen (src) + 1;
  char *dst;

  if (esc_str_len < new_len)
    {
      char *new_esc_str = realloc (esc_str, new_len);
      if (!new_esc_str)
	gc_error (1, errno, "can not escape string");
      esc_str = new_esc_str;
      esc_str_len = new_len;
    }

  dst = esc_str;
  while (*src)
    {
      if (*src == '%')
	{
	  *(dst++) = '%';
	  *(dst++) = '2';
	  *(dst++) = '5';
	}	  
      else if (*src == ':')
	{
	  /* The colon is used as field separator.  */
	  *(dst++) = '%';
	  *(dst++) = '3';
	  *(dst++) = 'a';
	}
      else if (*src == ',')
	{
	  /* The comma is used as list separator.  */
	  *(dst++) = '%';
	  *(dst++) = '2';
	  *(dst++) = 'c';
	}
      else
	*(dst++) = *(src);
      src++;
    }
  *dst = '\0';
  return esc_str;
}



/* Percent-Deescape special characters.  The string is valid until the
   next invocation of the function.  */
static char *
percent_deescape (const char *src)
{
  static char *str;
  static int str_len;
  int new_len = 3 * strlen (src) + 1;
  char *dst;

  if (str_len < new_len)
    {
      char *new_str = realloc (str, new_len);
      if (!new_str)
	gc_error (1, errno, "can not deescape string");
      str = new_str;
      str_len = new_len;
    }

  dst = str;
  while (*src)
    {
      if (*src == '%')
	{
	  int val = hextobyte (src + 1);

	  if (val < 0)
	    gc_error (1, 0, "malformed end of string %s", src);

	  *(dst++) = (char) val;
	  src += 3;
	}	  
      else
	*(dst++) = *(src++);
    }
  *dst = '\0';
  return str;
}


/* List all components that are available.  */
void
gc_component_list_components (FILE *out)
{
  gc_component_t component;
  gc_option_t *option;
  gc_backend_t backend;
  int backend_seen[GC_BACKEND_NR];
  const char *desc;
  const char *pgmname;

  for (component = 0; component < GC_COMPONENT_NR; component++)
    {
      option = gc_component[component].options;
      if (option)
        {
          for (backend = 0; backend < GC_BACKEND_NR; backend++)
            backend_seen[backend] = 0;

          pgmname = "";
          for (; option && option->name; option++)
            {
              if ((option->flags & GC_OPT_FLAG_GROUP))
                continue;
              backend = option->backend;
              if (backend_seen[backend])
                continue;
              backend_seen[backend] = 1;
              assert (backend != GC_BACKEND_ANY);
              if (gc_backend[backend].program
                  && !gc_backend[backend].module_name)
                continue;
              pgmname = gnupg_module_name (gc_backend[backend].module_name);
              break;
            }

          desc = gc_component[component].desc;
          desc = my_dgettext (gc_component[component].desc_domain, desc);
          fprintf (out, "%s:%s:",
                   gc_component[component].name,  my_percent_escape (desc));
          fprintf (out, "%s\n",  my_percent_escape (pgmname));
        }
    }
}



static int
all_digits_p (const char *p, size_t len)
{
  if (!len)
    return 0; /* No. */
  for (; len; len--, p++)
    if (!isascii (*p) || !isdigit (*p))
      return 0; /* No.  */
  return 1; /* Yes.  */
}


/* Collect all error lines from file descriptor FD. Only lines
   prefixed with TAG are considered.  Close that file descriptor
   then.  Returns a list of error line items (which may be empty).
   There is no error return.  */
static error_line_t
collect_error_output (int fd, const char *tag)
{
  FILE *fp;
  char buffer[1024];
  char *p, *p2, *p3;
  int c, cont_line;
  unsigned int pos;
  error_line_t eitem, errlines, *errlines_tail;
  size_t taglen = strlen (tag);

  fp = fdopen (fd, "r");
  if (!fp)
    gc_error (1, errno, "can't fdopen pipe for reading");

  errlines = NULL;
  errlines_tail = &errlines;
  pos = 0;
  cont_line = 0;
  while ((c=getc (fp)) != EOF)
    {
      buffer[pos++] = c;
      if (pos >= sizeof buffer - 5 || c == '\n')
        {
          buffer[pos - (c == '\n')] = 0;
          if (cont_line)
            ; /*Ignore continuations of previous line. */
          else if (!strncmp (buffer, tag, taglen) && buffer[taglen] == ':') 
            {
              /* "gpgsm: foo:4: bla" */
              /* Yep, we are interested in this line.  */
              p = buffer + taglen + 1;
              while (*p == ' ' || *p == '\t')
                p++;
              if (!*p)
                ; /* Empty lines are ignored.  */
              else if ( (p2 = strchr (p, ':')) && (p3 = strchr (p2+1, ':'))
                        && all_digits_p (p2+1, p3 - (p2+1)))
                {
                  /* Line in standard compiler format.  */
                  p3++;
                  while (*p3 == ' ' || *p3 == '\t')
                    p3++;
                  eitem = xmalloc (sizeof *eitem + strlen (p));
                  eitem->next = NULL;
                  strcpy (eitem->buffer, p);
                  eitem->fname = eitem->buffer;
                  eitem->buffer[p2-p] = 0;
                  eitem->errtext = eitem->buffer + (p3 - p);
                  /* (we already checked that there are only ascii
                     digits followed by a colon) */
                  eitem->lineno = 0;
                  for (p2++; isdigit (*p2); p2++)
                    eitem->lineno = eitem->lineno*10 + (*p2 - '0');
                  *errlines_tail = eitem;
                  errlines_tail = &eitem->next;
                }
              else
                {
                  /* Other error output.  */
                  eitem = xmalloc (sizeof *eitem + strlen (p));
                  eitem->next = NULL;
                  strcpy (eitem->buffer, p);
                  eitem->fname = NULL;
                  eitem->errtext = eitem->buffer;
                  eitem->lineno = 0;
                  *errlines_tail = eitem;
                  errlines_tail = &eitem->next;
                }
            }
          pos = 0;
          /* If this was not a complete line mark that we are in a
             continuation.  */
          cont_line = (c != '\n');
        }
    }
  
  /* We ignore error lines not terminated by a LF.  */

  fclose (fp);
  return errlines;
}



/* Check all components that are available.  */
void
gc_component_check_programs (FILE *out)
{
  gpg_error_t err;
  gc_component_t component;
  unsigned int result;
  int backend_seen[GC_BACKEND_NR];
  gc_backend_t backend;
  gc_option_t *option;
  const char *desc;
  const char *pgmname;
  const char *argv[2];
  pid_t pid;
  int exitcode;
  int filedes[2];
  error_line_t errlines, errptr;

  /* We use a temporary file to collect the error output.  It would be
     better to use a pipe here but as of now we have no suitable
     fucntion to create a portable pipe outside of exechelp.  Thus it
     is easier to use the tempfile approach.  */
  for (component = 0; component < GC_COMPONENT_NR; component++)
    {
      if (!gc_component[component].options)
        continue;

      for (backend = 0; backend < GC_BACKEND_NR; backend++)
        backend_seen[backend] = 0;

      option = gc_component[component].options;
      for (; option && option->name; option++)
        {
          if ((option->flags & GC_OPT_FLAG_GROUP))
            continue;
          backend = option->backend;
          if (backend_seen[backend])
            continue;
          backend_seen[backend] = 1;
          assert (backend != GC_BACKEND_ANY);
          if (!gc_backend[backend].program)
            continue;
          if (!gc_backend[backend].module_name)
            continue;

          pgmname = gnupg_module_name (gc_backend[backend].module_name);
          argv[0] = "--gpgconf-test";
          argv[1] = NULL;

          err = gnupg_create_inbound_pipe (filedes);
          if (err)
            gc_error (1, 0, _("error creating a pipe: %s\n"), 
                      gpg_strerror (err));

          result = 0;
          errlines = NULL;
          if (gnupg_spawn_process_fd (pgmname, argv, -1, -1, filedes[1], &pid))
            {
              close (filedes[0]);
              close (filedes[1]);
              result |= 1; /* Program could not be run.  */
            }
          else 
            {
              close (filedes[1]);
              errlines = collect_error_output (filedes[0], 
                                               gc_component[component].name);
              if (gnupg_wait_process (pgmname, pid, &exitcode))
                {
                  if (exitcode == -1)
                    result |= 1; /* Program could not be run or it
                                    terminated abnormally.  */
                  result |= 2; /* Program returned an error.  */
                }
            }
          
          /* If the program could not be run, we can't tell whether
             the config file is good.  */
          if ((result&1))
            result |= 2;  
          
          desc = gc_component[component].desc;
          desc = my_dgettext (gc_component[component].desc_domain, desc);
          fprintf (out, "%s:%s:",
                   gc_component[component].name, my_percent_escape (desc));
          fputs (my_percent_escape (pgmname), out);
          fprintf (out, ":%d:%d:", !(result & 1), !(result & 2));
          for (errptr = errlines; errptr; errptr = errptr->next)
            {
              if (errptr != errlines)
                fputs ("\n:::::", out); /* Continuation line.  */
              if (errptr->fname)
                fputs (my_percent_escape (errptr->fname), out);
              putc (':', out);
              if (errptr->fname)
                fprintf (out, "%u", errptr->lineno);
              putc (':', out);
              fputs (my_percent_escape (errptr->errtext), out);
              putc (':', out);
            }
          putc ('\n', out);
          
          while (errlines)
            {
              error_line_t tmp = errlines->next;
              xfree (errlines);
              errlines = tmp;
            }
          break; /* Loop over options of this component  */
        }
    } 
}



/* Find the component with the name NAME.  Returns -1 if not
   found.  */
int
gc_component_find (const char *name)
{
  gc_component_t idx;

  for (idx = 0; idx < GC_COMPONENT_NR; idx++)
    {
      if (gc_component[idx].options
          && !strcmp (name, gc_component[idx].name))
	return idx;
    }
  return -1;
}


/* List the option OPTION.  */
static void
list_one_option (const gc_option_t *option, FILE *out)
{
  const char *desc = NULL;
  char *arg_name = NULL;

  if (option->desc)
    {
      desc = my_dgettext (option->desc_domain, option->desc);

      if (*desc == '|')
	{
	  const char *arg_tail = strchr (&desc[1], '|');

	  if (arg_tail)
	    {
	      int arg_len = arg_tail - &desc[1];
	      arg_name = xmalloc (arg_len + 1);
	      memcpy (arg_name, &desc[1], arg_len);
	      arg_name[arg_len] = '\0';
	      desc = arg_tail + 1;
	    }
	}
    }


  /* YOU MUST NOT REORDER THE FIELDS IN THIS OUTPUT, AS THEIR ORDER IS
     PART OF THE EXTERNAL INTERFACE.  YOU MUST NOT REMOVE ANY
     FIELDS.  */

  /* The name field.  */
  fprintf (out, "%s", option->name);

  /* The flags field.  */
  fprintf (out, ":%lu", option->flags);
  if (opt.verbose)
    {
      putc (' ', out);
	  
      if (!option->flags)
	fprintf (out, "none");
      else
	{
	  unsigned long flags = option->flags;
	  unsigned long flag = 0;
	  unsigned long first = 1;

	  while (flags)
	    {
	      if (flags & 1)
		{
		  if (first)
		    first = 0;
		  else
		    putc (',', out);
		  fprintf (out, "%s", gc_flag[flag].name);
		}
	      flags >>= 1;
	      flag++;
	    }
	}
    }

  /* The level field.  */
  fprintf (out, ":%u", option->level);
  if (opt.verbose)
    fprintf (out, " %s", gc_level[option->level].name);

  /* The description field.  */
  fprintf (out, ":%s", desc ? my_percent_escape (desc) : "");
  
  /* The type field.  */
  fprintf (out, ":%u", option->arg_type);
  if (opt.verbose)
    fprintf (out, " %s", gc_arg_type[option->arg_type].name);

  /* The alternate type field.  */
  fprintf (out, ":%u", gc_arg_type[option->arg_type].fallback);
  if (opt.verbose)
    fprintf (out, " %s",
	     gc_arg_type[gc_arg_type[option->arg_type].fallback].name);

  /* The argument name field.  */
  fprintf (out, ":%s", arg_name ? my_percent_escape (arg_name) : "");
  if (arg_name)
    xfree (arg_name);

  /* The default value field.  */
  fprintf (out, ":%s", option->default_value ? option->default_value : "");

  /* The default argument field.  */
  fprintf (out, ":%s", option->default_arg ? option->default_arg : "");

  /* The value field.  */
  if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE
      && (option->flags & GC_OPT_FLAG_LIST)
      && option->value)
    /* The special format "1,1,1,1,...,1" is converted to a number
       here.  */
    fprintf (out, ":%u", (unsigned int)((strlen (option->value) + 1) / 2));
  else
    fprintf (out, ":%s", option->value ? option->value : "");

  /* ADD NEW FIELDS HERE.  */

  putc ('\n', out);
}


/* List all options of the component COMPONENT.  */
void
gc_component_list_options (int component, FILE *out)
{  
  const gc_option_t *option = gc_component[component].options;

  while (option && option->name)
    {
      /* Do not output unknown or internal options.  */
      if (!(option->flags & GC_OPT_FLAG_GROUP)
	  && (!option->active || option->level == GC_LEVEL_INTERNAL))
	{
	  option++;
	  continue;
	}

      if (option->flags & GC_OPT_FLAG_GROUP)
	{
	  const gc_option_t *group_option = option + 1;
	  gc_expert_level_t level = GC_LEVEL_NR;

	  /* The manual states that the group level is always the
	     minimum of the levels of all contained options.  Due to
	     different active options, and because it is hard to
	     maintain manually, we calculate it here.  The value in
	     the global static table is ignored.  */
	  
	  while (group_option->name)
	    {
	      if (group_option->flags & GC_OPT_FLAG_GROUP)
		break;
	      if (group_option->level < level)
		level = group_option->level;
	      group_option++;
	    }

	  /* Check if group is empty.  */
	  if (level != GC_LEVEL_NR)
	    {
	      gc_option_t opt_copy;

	      /* Fix up the group level.  */
	      memcpy (&opt_copy, option, sizeof (opt_copy));
	      opt_copy.level = level;
	      list_one_option (&opt_copy, out);
	    }
	}
      else
	list_one_option (option, out);

      option++;
    }
}


/* Find the option NAME in component COMPONENT, for the backend
   BACKEND.  If BACKEND is GC_BACKEND_ANY, any backend will match.  */
static gc_option_t *
find_option (gc_component_t component, const char *name,
	     gc_backend_t backend)
{
  gc_option_t *option = gc_component[component].options;
  while (option->name)
    {
      if (!(option->flags & GC_OPT_FLAG_GROUP)
	  && !strcmp (option->name, name)
	  && (backend == GC_BACKEND_ANY || option->backend == backend))
	break;
      option++;
    }
  return option->name ? option : NULL;
}


/* Determine the configuration pathname for the component COMPONENT
   and backend BACKEND.  */
static char *
get_config_pathname (gc_component_t component, gc_backend_t backend)
{
  char *pathname = NULL;
  gc_option_t *option = find_option
    (component, gc_backend[backend].option_config_filename, GC_BACKEND_ANY);
  assert (option);
  assert (option->arg_type == GC_ARG_TYPE_PATHNAME);
  assert (!(option->flags & GC_OPT_FLAG_LIST));

  if (!option->active || !option->default_value)
    gc_error (1, 0, "Option %s, needed by backend %s, was not initialized",
	      gc_backend[backend].option_config_filename,
	      gc_backend[backend].name);

  if (option->value && *option->value)
    pathname = percent_deescape (&option->value[1]);
  else if (option->default_value && *option->default_value)
    pathname = percent_deescape (&option->default_value[1]);
  else
    pathname = "";

#ifdef HAVE_DOSISH_SYSTEM
  if (!(pathname[0] 
        && pathname[1] == ':'
        && (pathname[2] == '/' || pathname[2] == '\\')))
#else
  if (pathname[0] != '/')
#endif
    gc_error (1, 0, "Option %s, needed by backend %s, is not absolute",
	      gc_backend[backend].option_config_filename,
	      gc_backend[backend].name);

  return pathname;
}


/* Retrieve the options for the component COMPONENT from backend
   BACKEND, which we already know is a program-type backend.  */
static void
retrieve_options_from_program (gc_component_t component, gc_backend_t backend)
{
  gpg_error_t err;
  int filedes[2];
  const char *pgmname;
  const char *argv[2];
  int exitcode;
  pid_t pid;
  char *line = NULL;
  size_t line_len = 0;
  ssize_t length;
  FILE *config;
  char *config_pathname;

  err = gnupg_create_inbound_pipe (filedes);
  if (err)
    gc_error (1, 0, _("error creating a pipe: %s\n"), gpg_strerror (err));

  pgmname = (gc_backend[backend].module_name 
             ? gnupg_module_name (gc_backend[backend].module_name) 
             : gc_backend[backend].program );
  argv[0] = "--gpgconf-list";
  argv[1] = NULL;

  err = gnupg_spawn_process_fd (pgmname, argv, -1, filedes[1], -1, &pid);
  if (err)
    {
      close (filedes[0]);
      close (filedes[1]);
      gc_error (1, 0, "could not gather active options from `%s': %s",
                pgmname, gpg_strerror (err));
    }
  close (filedes[1]);
  config = fdopen (filedes[0], "r");
  if (!config)
    gc_error (1, errno, "can't fdopen pipe for reading");

  while ((length = read_line (config, &line, &line_len, NULL)) > 0)
    {
      gc_option_t *option;
      char *linep;
      unsigned long flags = 0;
      char *default_value = NULL;
      
      /* Strip newline and carriage return, if present.  */
      while (length > 0
	     && (line[length - 1] == '\n' || line[length - 1] == '\r'))
	line[--length] = '\0';

      linep = strchr (line, ':');
      if (linep)
	*(linep++) = '\0';
      
      /* Extract additional flags.  Default to none.  */
      if (linep)
	{
	  char *end;
	  char *tail;

	  end = strchr (linep, ':');
	  if (end)
	    *(end++) = '\0';

	  errno = 0;
	  flags = strtoul (linep, &tail, 0);
	  if (errno)
	    gc_error (1, errno, "malformed flags in option %s from %s",
                      line, pgmname);
	  if (!(*tail == '\0' || *tail == ':' || *tail == ' '))
	    gc_error (1, 0, "garbage after flags in option %s from %s",
                      line, pgmname);

	  linep = end;
	}

      /* Extract default value, if present.  Default to empty if
	 not.  */
      if (linep)
	{
	  char *end;

	  end = strchr (linep, ':');
	  if (end)
	    *(end++) = '\0';

	  if (flags & GC_OPT_FLAG_DEFAULT)
	    default_value = linep;

	  linep = end;
	}

      /* Look up the option in the component and install the
	 configuration data.  */
      option = find_option (component, line, backend);
      if (option)
	{
	  if (option->active)
	    gc_error (1, errno, "option %s returned twice from %s",
		      line, pgmname);
	  option->active = 1;

	  option->flags |= flags;
	  if (default_value && *default_value)
	    option->default_value = xstrdup (default_value);
	}
    }
  if (length < 0 || ferror (config))
    gc_error (1, errno, "error reading from %s",pgmname);
  if (fclose (config) && ferror (config))
    gc_error (1, errno, "error closing %s", pgmname);

  err = gnupg_wait_process (pgmname, pid, &exitcode);
  if (err)
    gc_error (1, 0, "running %s failed (exitcode=%d): %s",
              pgmname, exitcode, gpg_strerror (err));


  /* At this point, we can parse the configuration file.  */
  config_pathname = get_config_pathname (component, backend);

  config = fopen (config_pathname, "r");
  if (!config)
    gc_error (0, errno, "warning: can not open config file %s",
	      config_pathname);
  else
    {
      while ((length = read_line (config, &line, &line_len, NULL)) > 0)
	{
	  char *name;
	  char *value;
	  gc_option_t *option;
	  
	  name = line;
	  while (*name == ' ' || *name == '\t')
	    name++;
	  if (!*name || *name == '#' || *name == '\r' || *name == '\n')
	    continue;

	  value = name;
	  while (*value && *value != ' ' && *value != '\t'
		 && *value != '#' && *value != '\r' && *value != '\n')
	    value++;
	  if (*value == ' ' || *value == '\t')
	    {
	      char *end;

	      *(value++) = '\0';
	      while (*value == ' ' || *value == '\t')
		value++;

	      end = value;
	      while (*end && *end != '#' && *end != '\r' && *end != '\n')
		end++;
	      while (end > value && (end[-1] == ' ' || end[-1] == '\t'))
		end--;
	      *end = '\0';
	    }
	  else
	    *value = '\0';

	  /* Look up the option in the component and install the
	     configuration data.  */
	  option = find_option (component, line, backend);
	  if (option)
	    {
	      char *opt_value;

	      if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE)
		{
		  if (*value)
		    gc_error (0, 0,
			      "warning: ignoring argument %s for option %s",
			      value, name);
		  opt_value = xstrdup ("1");
		}
	      else if (gc_arg_type[option->arg_type].fallback
		       == GC_ARG_TYPE_STRING)
		opt_value = xasprintf ("\"%s", my_percent_escape (value));
	      else
		{
		  /* FIXME: Verify that the number is sane.  */
		  opt_value = xstrdup (value);
		}

	      /* Now enter the option into the table.  */
	      if (!(option->flags & GC_OPT_FLAG_LIST))
		{
		  if (option->value)
		    free (option->value);
		  option->value = opt_value;
		}
	      else
		{
		  if (!option->value)
		    option->value = opt_value;
		  else
		    {
		      char *opt_val = opt_value;

		      option->value = xasprintf ("%s,%s", option->value,
						 opt_val);
		      xfree (opt_value);
		    }
		}
	    }
	}

      if (length < 0 || ferror (config))
	gc_error (1, errno, "error reading from %s", config_pathname);
      if (fclose (config) && ferror (config))
	gc_error (1, errno, "error closing %s", config_pathname);
    }

  xfree (line);
}


/* Retrieve the options for the component COMPONENT from backend
   BACKEND, which we already know is of type file list.  */ 
static void
retrieve_options_from_file (gc_component_t component, gc_backend_t backend)
{
  gc_option_t *list_option;
  char *list_pathname;
  FILE *list_file;
  char *line = NULL;
  size_t line_len = 0;
  ssize_t length;
  char *list = NULL;

  list_option = find_option (component,
			     gc_backend[backend].option_name, GC_BACKEND_ANY);
  assert (list_option);
  assert (!list_option->active);

  list_pathname = get_config_pathname (component, backend);
  list_file = fopen (list_pathname, "r");
  if (!list_file)
    gc_error (0, errno, "warning: can not open list file %s", list_pathname);
  else
    {

      while ((length = read_line (list_file, &line, &line_len, NULL)) > 0)
	{
	  char *start;
	  char *end;
	  char *new_list;

	  start = line;
	  while (*start == ' ' || *start == '\t')
	    start++;
	  if (!*start || *start == '#' || *start == '\r' || *start == '\n')
	    continue;

	  end = start;
	  while (*end && *end != '#' && *end != '\r' && *end != '\n')
	    end++;
	  /* Walk back to skip trailing white spaces.  Looks evil, but
	     works because of the conditions on START and END imposed
	     at this point (END is at least START + 1, and START is
	     not a whitespace character).  */
	  while (*(end - 1) == ' ' || *(end - 1) == '\t')
	    end--;
	  *end = '\0';
	  /* FIXME: Oh, no!  This is so lame!  Should use realloc and
	     really append.  */
	  if (list)
	    {
	      new_list = xasprintf ("%s,\"%s", list, my_percent_escape (start));
	      xfree (list);
	      list = new_list;
	    }
	  else
	    list = xasprintf ("\"%s", my_percent_escape (start));
	}
      if (length < 0 || ferror (list_file))
	gc_error (1, errno, "can not read list file %s", list_pathname);
    }

  list_option->active = 1;
  list_option->value = list;

  if (list_file && fclose (list_file) && ferror (list_file))
    gc_error (1, errno, "error closing %s", list_pathname);
  xfree (line);
}


/* Retrieve the currently active options and their defaults from all
   involved backends for this component.  Using -1 for component will
   retrieve all options from all components. */
void
gc_component_retrieve_options (int component)
{
  int process_all = 0;
  int backend_seen[GC_BACKEND_NR];
  gc_backend_t backend;
  gc_option_t *option;

  for (backend = 0; backend < GC_BACKEND_NR; backend++)
    backend_seen[backend] = 0;

  if (component == -1)
    {
      process_all = 1;
      component = 0;
      assert (component < GC_COMPONENT_NR);
    }
      
  do
    {
      option = gc_component[component].options;

      while (option && option->name)
        {
          if (!(option->flags & GC_OPT_FLAG_GROUP))
            {
              backend = option->backend;
              
              if (backend_seen[backend])
                {
                  option++;
                  continue;
                }
              backend_seen[backend] = 1;
              
              assert (backend != GC_BACKEND_ANY);
              
              if (gc_backend[backend].program)
                retrieve_options_from_program (component, backend);
              else
                retrieve_options_from_file (component, backend);
            }
          option++;
        }
    }
  while (process_all && ++component < GC_COMPONENT_NR);

}



/* Perform a simple validity check based on the type.  Return in
   NEW_VALUE_NR the value of the number in NEW_VALUE if OPTION is of
   type GC_ARG_TYPE_NONE.  */
static void
option_check_validity (gc_option_t *option, unsigned long flags,
		       char *new_value, unsigned long *new_value_nr)
{
  char *arg;

  if (!option->active)
    gc_error (1, 0, "option %s not supported by backend %s",
              option->name, gc_backend[option->backend].name);
      
  if (option->new_flags || option->new_value)
    gc_error (1, 0, "option %s already changed", option->name);

  if (flags & GC_OPT_FLAG_DEFAULT)
    {
      if (*new_value)
	gc_error (1, 0, "argument %s provided for deleted option %s",
		  new_value, option->name);

      return;
    }

  /* GC_ARG_TYPE_NONE options have special list treatment.  */
  if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE)
    {
      char *tail;

      errno = 0;
      *new_value_nr = strtoul (new_value, &tail, 0);

      if (errno)
	gc_error (1, errno, "invalid argument for option %s",
		  option->name);
      if (*tail)
	gc_error (1, 0, "garbage after argument for option %s",
		      option->name);

      if (!(option->flags & GC_OPT_FLAG_LIST))
	{
	  if (*new_value_nr != 1)
	    gc_error (1, 0, "argument for non-list option %s of type 0 "
		      "(none) must be 1", option->name);
	}
      else
	{
	  if (*new_value_nr == 0)
	    gc_error (1, 0, "argument for option %s of type 0 (none) "
		      "must be positive", option->name);
	}

      return;
    }

  arg = new_value;
  do
    {
      if (*arg == '\0' || *arg == ',')
	{
	  if (!(option->flags & GC_OPT_FLAG_ARG_OPT))
	    gc_error (1, 0, "argument required for option %s", option->name);

	  if (*arg == ',' && !(option->flags & GC_OPT_FLAG_LIST))
	    gc_error (1, 0, "list found for non-list option %s", option->name);
	}
      else if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_STRING)
	{
	  if (*arg != '"')
	    gc_error (1, 0, "string argument for option %s must begin "
		      "with a quote (\") character", option->name);

	  /* FIXME: We do not allow empty string arguments for now, as
	     we do not quote arguments in configuration files, and
	     thus no argument is indistinguishable from the empty
	     string.  */
	  if (arg[1] == '\0' || arg[1] == ',')
	    gc_error (1, 0, "empty string argument for option %s is "
		      "currently not allowed.  Please report this!",
		      option->name);
	}
      else if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_INT32)
	{
	  errno = 0;
	  (void) strtol (arg, &arg, 0);

	  if (errno)
	    gc_error (1, errno, "invalid argument for option %s",
		      option->name);

	  if (*arg != '\0' && *arg != ',')
	    gc_error (1, 0, "garbage after argument for option %s",
		      option->name);
	}
      else if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_INT32)
	{
	  errno = 0;
	  (void) strtoul (arg, &arg, 0);

	  if (errno)
	    gc_error (1, errno, "invalid argument for option %s",
		      option->name);

	  if (*arg != '\0' && *arg != ',')
	    gc_error (1, 0, "garbage after argument for option %s",
		      option->name);
	}
      arg = strchr (arg, ',');
      if (arg)
	arg++;
    }
  while (arg && *arg);
}

#ifdef HAVE_W32_SYSTEM
int
copy_file (const char *src_name, const char *dst_name)
{
#define BUF_LEN 4096
  char buffer[BUF_LEN];
  int len;
  FILE *src;
  FILE *dst;

  src = fopen (src_name, "r");
  if (src == NULL)
    return -1;

  dst = fopen (dst_name, "w");
  if (dst == NULL)
    {
      int saved_err = errno;
      fclose (src);
      errno = saved_err;
      return -1;
    }

  do
    {
      int written;

      len = fread (buffer, 1, BUF_LEN, src);
      if (len == 0)
	break;
      written = fwrite (buffer, 1, len, dst);
      if (written != len)
	break;
    }
  while (!feof (src) && !ferror (src) && !ferror (dst));

  if (ferror (src) || ferror (dst) || !feof (src))
    {
      int saved_errno = errno;
      fclose (src);
      fclose (dst);
      unlink (dst_name);
      errno = saved_errno;
      return -1;
    }

  if (fclose (dst) && ferror (dst))
    gc_error (1, errno, "error closing %s", dst_name);
  if (fclose (src) && ferror (src))
    gc_error (1, errno, "error closing %s", src_name);

  return 0;
}
#endif /* HAVE_W32_SYSTEM */


/* Create and verify the new configuration file for the specified
   backend and component.  Returns 0 on success and -1 on error.  */
static int
change_options_file (gc_component_t component, gc_backend_t backend,
		     char **src_filenamep, char **dest_filenamep,
		     char **orig_filenamep)
{
  static const char marker[] = "###+++--- GPGConf ---+++###";
  /* True if we are within the marker in the config file.  */
  int in_marker = 0;
  gc_option_t *option;
  char *line = NULL;
  size_t line_len;
  ssize_t length;
  int res;
  int fd;
  FILE *src_file = NULL;
  FILE *dest_file = NULL;
  char *src_filename;
  char *dest_filename;
  char *orig_filename;
  char *arg;
  char *cur_arg = NULL;

  option = find_option (component,
			gc_backend[backend].option_name, GC_BACKEND_ANY);
  assert (option);
  assert (option->active);
  assert (gc_arg_type[option->arg_type].fallback != GC_ARG_TYPE_NONE);

  /* FIXME.  Throughout the function, do better error reporting.  */
  /* Note that get_config_pathname() calls percent_deescape(), so we
     call this before processing the arguments.  */
  dest_filename = xstrdup (get_config_pathname (component, backend));
  src_filename = xasprintf ("%s.gpgconf.%i.new", dest_filename, getpid ());
  orig_filename = xasprintf ("%s.gpgconf.%i.bak", dest_filename, getpid ());

  arg = option->new_value;
  if (arg && arg[0] == '\0')
    arg = NULL;
  else if (arg)
    {
      char *end;

      arg++;
      end = strchr (arg, ',');
      if (end)
	*end = '\0';

      cur_arg = percent_deescape (arg);
      if (end)
	{
	  *end = ',';
	  arg = end + 1;
	}
      else
	arg = NULL;
    }

#ifdef HAVE_W32_SYSTEM
  res = copy_file (dest_filename, orig_filename);
#else
  res = link (dest_filename, orig_filename);
#endif
  if (res < 0 && errno != ENOENT)
    return -1;
  if (res < 0)
    {
      xfree (orig_filename);
      orig_filename = NULL;
    }

  /* We now initialize the return strings, so the caller can do the
     cleanup for us.  */
  *src_filenamep = src_filename;
  *dest_filenamep = dest_filename;
  *orig_filenamep = orig_filename;

  /* Use open() so that we can use O_EXCL.  */
  fd = open (src_filename, O_CREAT | O_EXCL | O_WRONLY, 0644);
  if (fd < 0)
    return -1;
  src_file = fdopen (fd, "w");
  res = errno;
  if (!src_file)
    {
      errno = res;
      return -1;
    }

  /* Only if ORIG_FILENAME is not NULL did the configuration file
     exist already.  In this case, we will copy its content into the
     new configuration file, changing it to our liking in the
     process.  */
  if (orig_filename)
    {
      dest_file = fopen (dest_filename, "r");
      if (!dest_file)
	goto change_file_one_err;

      while ((length = read_line (dest_file, &line, &line_len, NULL)) > 0)
	{
	  int disable = 0;
	  char *start;

	  if (!strncmp (marker, line, sizeof (marker) - 1))
	    {
	      if (!in_marker)
		in_marker = 1;
	      else
		break;
	    }

	  start = line;
	  while (*start == ' ' || *start == '\t')
	    start++;
	  if (*start && *start != '\r' && *start != '\n' && *start != '#')
	    {
	      char *end;
	      char *endp;
	      char saved_end;

	      endp = start;
	      end = endp;

	      /* Search for the end of the line.  */
	      while (*endp && *endp != '#' && *endp != '\r' && *endp != '\n')
		{
		  endp++;
		  if (*endp && *endp != ' ' && *endp != '\t'
		      && *endp != '\r' && *endp != '\n' && *endp != '#')
		    end = endp + 1;
		}
	      saved_end = *end;
	      *end = '\0';

	      if ((option->new_flags & GC_OPT_FLAG_DEFAULT)
		  || !cur_arg || strcmp (start, cur_arg))
		disable = 1;
	      else
		{
		  /* Find next argument.  */
		  if (arg)
		    {
		      char *arg_end;

		      arg++;
		      arg_end = strchr (arg, ',');
		      if (arg_end)
			*arg_end = '\0';

		      cur_arg = percent_deescape (arg);
		      if (arg_end)
			{
			  *arg_end = ',';
			  arg = arg_end + 1;
			}
		      else
			arg = NULL;
		    }
		  else
		    cur_arg = NULL;
		}

	      *end = saved_end;
	    }

	  if (disable)
	    {
	      if (!in_marker)
		{
		  fprintf (src_file,
			   "# GPGConf disabled this option here at %s\n",
			   asctimestamp (gnupg_get_time ()));
		  if (ferror (src_file))
		    goto change_file_one_err;
		  fprintf (src_file, "# %s", line);
		  if (ferror (src_file))
		    goto change_file_one_err;
		}
	    }
	  else
	    {
	      fprintf (src_file, "%s", line);
	      if (ferror (src_file))
		goto change_file_one_err;
	    }
	}
      if (length < 0 || ferror (dest_file))
	goto change_file_one_err;
    }

  if (!in_marker)
    {
      /* There was no marker.  This is the first time we edit the
	 file.  We add our own marker at the end of the file and
	 proceed.  Note that we first write a newline, this guards us
	 against files which lack the newline at the end of the last
	 line, while it doesn't hurt us in all other cases.  */
      fprintf (src_file, "\n%s\n", marker);
      if (ferror (src_file))
	goto change_file_one_err;
    }

  /* At this point, we have copied everything up to the end marker
     into the new file, except for the arguments we are going to add.
     Now, dump the new arguments and write the end marker, possibly
     followed by the rest of the original file.  */
  while (cur_arg)
    {
      fprintf (src_file, "%s\n", cur_arg);

      /* Find next argument.  */
      if (arg)
	{
	  char *end;

	  arg++;
	  end = strchr (arg, ',');
	  if (end)
	    *end = '\0';

	  cur_arg = percent_deescape (arg);
	  if (end)
	    {
	      *end = ',';
	      arg = end + 1;
	    }
	  else
	    arg = NULL;
	}
      else
	cur_arg = NULL;
    }

  fprintf (src_file, "%s %s\n", marker, asctimestamp (gnupg_get_time ()));
  if (ferror (src_file))
    goto change_file_one_err;

  if (!in_marker)
    {
      fprintf (src_file, "# GPGConf edited this configuration file.\n");
      if (ferror (src_file))
	goto change_file_one_err;
      fprintf (src_file, "# It will disable options before this marked "
	       "block, but it will\n");
      if (ferror (src_file))
	goto change_file_one_err;
      fprintf (src_file, "# never change anything below these lines.\n");
      if (ferror (src_file))
	goto change_file_one_err;
    }
  if (dest_file)
    {
      while ((length = read_line (dest_file, &line, &line_len, NULL)) > 0)
	{
	  fprintf (src_file, "%s", line);
	  if (ferror (src_file))
	    goto change_file_one_err;
	}
      if (length < 0 || ferror (dest_file))
	goto change_file_one_err;
    }
  xfree (line);
  line = NULL;

  res = fclose (src_file);
  if (res)
    {
      res = errno;
      close (fd);
      if (dest_file)
	fclose (dest_file);
      errno = res;
      return -1;
    }
  close (fd);
  if (dest_file)
    {
      res = fclose (dest_file);
      if (res)
	return -1;
    }
  return 0;

 change_file_one_err:
  xfree (line);
  res = errno;
  if (src_file)
    {
      fclose (src_file);
      close (fd);
    }
  if (dest_file)
    fclose (dest_file);
  errno = res;
  return -1;
}


/* Create and verify the new configuration file for the specified
   backend and component.  Returns 0 on success and -1 on error.  */
static int
change_options_program (gc_component_t component, gc_backend_t backend,
			char **src_filenamep, char **dest_filenamep,
			char **orig_filenamep)
{
  static const char marker[] = "###+++--- GPGConf ---+++###";
  /* True if we are within the marker in the config file.  */
  int in_marker = 0;
  gc_option_t *option;
  char *line = NULL;
  size_t line_len;
  ssize_t length;
  int res;
  int fd;
  FILE *src_file = NULL;
  FILE *dest_file = NULL;
  char *src_filename;
  char *dest_filename;
  char *orig_filename;
  /* Special hack for gpg, see below.  */
  int utf8strings_seen = 0;

  /* FIXME.  Throughout the function, do better error reporting.  */
  dest_filename = xstrdup (get_config_pathname (component, backend));
  src_filename = xasprintf ("%s.gpgconf.%i.new", dest_filename, getpid ());
  orig_filename = xasprintf ("%s.gpgconf.%i.bak", dest_filename, getpid ());

#ifdef HAVE_W32_SYSTEM
  res = copy_file (dest_filename, orig_filename);
#else
  res = link (dest_filename, orig_filename);
#endif
  if (res < 0 && errno != ENOENT)
    return -1;
  if (res < 0)
    {
      xfree (orig_filename);
      orig_filename = NULL;
    }

  /* We now initialize the return strings, so the caller can do the
     cleanup for us.  */
  *src_filenamep = src_filename;
  *dest_filenamep = dest_filename;
  *orig_filenamep = orig_filename;

  /* Use open() so that we can use O_EXCL.  */
  fd = open (src_filename, O_CREAT | O_EXCL | O_WRONLY, 0644);
  if (fd < 0)
    return -1;
  src_file = fdopen (fd, "w");
  res = errno;
  if (!src_file)
    {
      errno = res;
      return -1;
    }

  /* Only if ORIG_FILENAME is not NULL did the configuration file
     exist already.  In this case, we will copy its content into the
     new configuration file, changing it to our liking in the
     process.  */
  if (orig_filename)
    {
      dest_file = fopen (dest_filename, "r");
      if (!dest_file)
	goto change_one_err;

      while ((length = read_line (dest_file, &line, &line_len, NULL)) > 0)
	{
	  int disable = 0;
	  char *start;

	  if (!strncmp (marker, line, sizeof (marker) - 1))
	    {
	      if (!in_marker)
		in_marker = 1;
	      else
		break;
	    }
	  else if (backend == GC_BACKEND_GPG && in_marker
		   && ! strcmp ("utf8-strings\n", line))
	    {
	      /* Strip duplicated entries.  */
	      if (utf8strings_seen)
		disable = 1;
	      else
		utf8strings_seen = 1;
	    }

	  start = line;
	  while (*start == ' ' || *start == '\t')
	    start++;
	  if (*start && *start != '\r' && *start != '\n' && *start != '#')
	    {
	      char *end;
	      char saved_end;

	      end = start;
	      while (*end && *end != ' ' && *end != '\t'
		     && *end != '\r' && *end != '\n' && *end != '#')
		end++;
	      saved_end = *end;
	      *end = '\0';

	      option = find_option (component, start, backend);
	      *end = saved_end;
	      if (option && ((option->new_flags & GC_OPT_FLAG_DEFAULT)
			     || option->new_value))
		disable = 1;
	    }
	  if (disable)
	    {
	      if (!in_marker)
		{
		  fprintf (src_file,
			   "# GPGConf disabled this option here at %s\n",
			   asctimestamp (gnupg_get_time ()));
		  if (ferror (src_file))
		    goto change_one_err;
		  fprintf (src_file, "# %s", line);
		  if (ferror (src_file))
		    goto change_one_err;
		}
	    }
	  else
	    {
	      fprintf (src_file, "%s", line);
	      if (ferror (src_file))
		goto change_one_err;
	    }
	}
      if (length < 0 || ferror (dest_file))
	goto change_one_err;
    }

  if (!in_marker)
    {
      /* There was no marker.  This is the first time we edit the
	 file.  We add our own marker at the end of the file and
	 proceed.  Note that we first write a newline, this guards us
	 against files which lack the newline at the end of the last
	 line, while it doesn't hurt us in all other cases.  */
      fprintf (src_file, "\n%s\n", marker);
      if (ferror (src_file))
	goto change_one_err;
    }
  /* At this point, we have copied everything up to the end marker
     into the new file, except for the options we are going to change.
     Now, dump the changed options (except for those we are going to
     revert to their default), and write the end marker, possibly
     followed by the rest of the original file.  */

  /* We have to turn on UTF8 strings for GnuPG.  */
  if (backend == GC_BACKEND_GPG && ! utf8strings_seen)
    fprintf (src_file, "utf8-strings\n");

  option = gc_component[component].options;
  while (option->name)
    {
      if (!(option->flags & GC_OPT_FLAG_GROUP)
	  && option->backend == backend
	  && option->new_value)
	{
	  char *arg = option->new_value;

	  do
	    {
	      if (*arg == '\0' || *arg == ',')
		{
		  fprintf (src_file, "%s\n", option->name);
		  if (ferror (src_file))
		    goto change_one_err;
		}
	      else if (gc_arg_type[option->arg_type].fallback
		       == GC_ARG_TYPE_NONE)
		{
		  assert (*arg == '1');
		  fprintf (src_file, "%s\n", option->name);
		  if (ferror (src_file))
		    goto change_one_err;

		  arg++;
		}
	      else if (gc_arg_type[option->arg_type].fallback
		       == GC_ARG_TYPE_STRING)
		{
		  char *end;
		  
		  assert (*arg == '"');
		  arg++;
		  
		  end = strchr (arg, ',');
		  if (end)
		    *end = '\0';

		  fprintf (src_file, "%s %s\n", option->name,
			   percent_deescape (arg));
		  if (ferror (src_file))
		    goto change_one_err;

		  if (end)
		    *end = ',';
		  arg = end;
		}
	      else
		{
		  char *end;

		  end = strchr (arg, ',');
		  if (end)
		    *end = '\0';

		  fprintf (src_file, "%s %s\n", option->name, arg);
		  if (ferror (src_file))
		    goto change_one_err;

		  if (end)
		    *end = ',';
		  arg = end;
		}

	      assert (arg == NULL || *arg == '\0' || *arg == ',');
	      if (arg && *arg == ',')
		arg++;
	    }
	  while (arg && *arg);
	}
      option++;
    }

  fprintf (src_file, "%s %s\n", marker, asctimestamp (gnupg_get_time ()));
  if (ferror (src_file))
    goto change_one_err;

  if (!in_marker)
    {
      fprintf (src_file, "# GPGConf edited this configuration file.\n");
      if (ferror (src_file))
	goto change_one_err;
      fprintf (src_file, "# It will disable options before this marked "
	       "block, but it will\n");
      if (ferror (src_file))
	goto change_one_err;
      fprintf (src_file, "# never change anything below these lines.\n");
      if (ferror (src_file))
	goto change_one_err;
    }
  if (dest_file)
    {
      while ((length = read_line (dest_file, &line, &line_len, NULL)) > 0)
	{
	  fprintf (src_file, "%s", line);
	  if (ferror (src_file))
	    goto change_one_err;
	}
      if (length < 0 || ferror (dest_file))
	goto change_one_err;
    }
  xfree (line);
  line = NULL;

  res = fclose (src_file);
  if (res)
    {
      res = errno;
      close (fd);
      if (dest_file)
	fclose (dest_file);
      errno = res;
      return -1;
    }
  close (fd);
  if (dest_file)
    {
      res = fclose (dest_file);
      if (res)
	return -1;
    }
  return 0;

 change_one_err:
  xfree (line);
  res = errno;
  if (src_file)
    {
      fclose (src_file);
      close (fd);
    }
  if (dest_file)
    fclose (dest_file);
  errno = res;
  return -1;
}


/* Common code for gc_component_change_options and
   gc_process_gpgconf_conf.  */
static void
change_one_value (gc_option_t *option, int *runtime,
                  unsigned long flags, char *new_value)
{
  unsigned long new_value_nr = 0;

  option_check_validity (option, flags, new_value, &new_value_nr);

  if (option->flags & GC_OPT_FLAG_RUNTIME)
    runtime[option->backend] = 1;

  option->new_flags = flags;
  if (!(flags & GC_OPT_FLAG_DEFAULT))
    {
      if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE
          && (option->flags & GC_OPT_FLAG_LIST))
        {
          char *str;

          /* We convert the number to a list of 1's for convenient
             list handling.  */
          assert (new_value_nr > 0);
          option->new_value = xmalloc ((2 * (new_value_nr - 1) + 1) + 1);
          str = option->new_value;
          *(str++) = '1';
          while (--new_value_nr > 0)
            {
              *(str++) = ',';
              *(str++) = '1';
            }
          *(str++) = '\0';
        }
      else
        option->new_value = xstrdup (new_value);
    }
}


/* Read the modifications from IN and apply them.  If IN is NULL the
   modifications are expected to already have been set to the global
   table. */
void
gc_component_change_options (int component, FILE *in)
{
  int err = 0;
  int runtime[GC_BACKEND_NR];
  char *src_pathname[GC_BACKEND_NR];
  char *dest_pathname[GC_BACKEND_NR];
  char *orig_pathname[GC_BACKEND_NR];
  gc_backend_t backend;
  gc_option_t *option;
  char *line = NULL;
  size_t line_len = 0;
  ssize_t length;

  for (backend = 0; backend < GC_BACKEND_NR; backend++)
    {
      runtime[backend] = 0;
      src_pathname[backend] = NULL;
      dest_pathname[backend] = NULL;
      orig_pathname[backend] = NULL;
    }

  if (in)
    {
      /* Read options from the file IN.  */
      while ((length = read_line (in, &line, &line_len, NULL)) > 0)
        {
          char *linep;
          unsigned long flags = 0;
          char *new_value = "";
          
          /* Strip newline and carriage return, if present.  */
          while (length > 0
                 && (line[length - 1] == '\n' || line[length - 1] == '\r'))
            line[--length] = '\0';
          
          linep = strchr (line, ':');
          if (linep)
            *(linep++) = '\0';
          
          /* Extract additional flags.  Default to none.  */
          if (linep)
            {
              char *end;
              char *tail;

              end = strchr (linep, ':');
              if (end)
                *(end++) = '\0';
              
              errno = 0;
              flags = strtoul (linep, &tail, 0);
              if (errno)
                gc_error (1, errno, "malformed flags in option %s", line);
              if (!(*tail == '\0' || *tail == ':' || *tail == ' '))
                gc_error (1, 0, "garbage after flags in option %s", line);
              
              linep = end;
            }

          /* Don't allow setting of the no change flag.  */
          flags &= ~GC_OPT_FLAG_NO_CHANGE;
          
          /* Extract default value, if present.  Default to empty if not.  */
          if (linep)
            {
              char *end;
              end = strchr (linep, ':');
              if (end)
                *(end++) = '\0';
              new_value = linep;
              linep = end;
            }
          
          option = find_option (component, line, GC_BACKEND_ANY);
          if (!option)
            gc_error (1, 0, "unknown option %s", line);
          
          if ((option->flags & GC_OPT_FLAG_NO_CHANGE))
            {
              gc_error (0, 0, "ignoring new value for option %s",
                        option->name);
              continue;
            }
          
          change_one_value (option, runtime, flags, new_value);
        }
    }

  /* Now that we have collected and locally verified the changes,
     write them out to new configuration files, verify them
     externally, and then commit them.  */
  option = gc_component[component].options;
  while (option && option->name)
    {
      /* Go on if we have already seen this backend, or if there is
	 nothing to do.  */
      if (src_pathname[option->backend]
	  || !(option->new_flags || option->new_value))
	{
	  option++;
	  continue;
	}

      if (gc_backend[option->backend].program)
	err = change_options_program (component, option->backend,
				      &src_pathname[option->backend],
				      &dest_pathname[option->backend],
				      &orig_pathname[option->backend]);
      else
	err = change_options_file (component, option->backend,
				   &src_pathname[option->backend],
				   &dest_pathname[option->backend],
				   &orig_pathname[option->backend]);
	
      if (err)
	break;
	  
      option++;
    }

  if (!err)
    {
      int i;

      for (i = 0; i < GC_BACKEND_NR; i++)
	{
	  if (src_pathname[i])
	    {
	      /* FIXME: Make a verification here.  */

	      assert (dest_pathname[i]);

	      if (orig_pathname[i])
		{
#ifdef HAVE_W32_SYSTEM
		  /* There is no atomic update on W32.  */
		  err = unlink (dest_pathname[i]);
#endif /* HAVE_W32_SYSTEM */
		  if (!err)
		    err = rename (src_pathname[i], dest_pathname[i]);
		}
	      else
		{
#ifdef HAVE_W32_SYSTEM
		  /* We skip the unlink if we expect the file not to
		     be there.  */
                  err = rename (src_pathname[i], dest_pathname[i]);
#else /* HAVE_W32_SYSTEM */
		  /* This is a bit safer than rename() because we
		     expect DEST_PATHNAME not to be there.  If it
		     happens to be there, this will fail.  */
		  err = link (src_pathname[i], dest_pathname[i]);
		  if (!err)
		    err = unlink (src_pathname[i]);
#endif /* !HAVE_W32_SYSTEM */
		}
	      if (err)
		break;
	      src_pathname[i] = NULL;
	    }
	}
    }

  if (err)
    {
      int i;
      int saved_errno = errno;

      /* An error occured.  */
      for (i = 0; i < GC_BACKEND_NR; i++)
	{
	  if (src_pathname[i])
	    {
	      /* The change was not yet committed.  */
	      unlink (src_pathname[i]);
	      if (orig_pathname[i])
		unlink (orig_pathname[i]);
	    }
	  else
	    {
	      /* The changes were already committed.  FIXME: This is a
		 tad dangerous, as we don't know if we don't overwrite
		 a version of the file that is even newer than the one
		 we just installed.  */
	      if (orig_pathname[i])
		{
#ifdef HAVE_W32_SYSTEM
		  /* There is no atomic update on W32.  */
		  unlink (dest_pathname[i]);
#endif /* HAVE_W32_SYSTEM */
		  rename (orig_pathname[i], dest_pathname[i]);
		}
	      else
		unlink (dest_pathname[i]);
	    }
	}
      gc_error (1, saved_errno, "could not commit changes");
    }

  /* If it all worked, notify the daemons of the changes.  */
  if (opt.runtime)
    for (backend = 0; backend < GC_BACKEND_NR; backend++)  
      {
	if (runtime[backend] && gc_backend[backend].runtime_change)
	  (*gc_backend[backend].runtime_change) ();
      }

  /* Move the per-process backup file into its place.  */
  for (backend = 0; backend < GC_BACKEND_NR; backend++)  
    if (orig_pathname[backend])
      {
	char *backup_pathname;

	assert (dest_pathname[backend]);

	backup_pathname = xasprintf ("%s.gpgconf.bak", dest_pathname[backend]);

#ifdef HAVE_W32_SYSTEM
	/* There is no atomic update on W32.  */
	unlink (backup_pathname);
#endif /* HAVE_W32_SYSTEM */
	rename (orig_pathname[backend], backup_pathname);
      }

  xfree (line);
}


/* Check whether USER matches the current user of one of its group.
   This function may change USER.  Returns true is there is a
   match.  */
static int
key_matches_user_or_group (char *user)
{
  char *group;

  if (*user == '*' && user[1] == 0)
    return 1; /* A single asterisk matches all users.  */

  group = strchr (user, ':');
  if (group)
    *group++ = 0;

#ifdef HAVE_W32_SYSTEM
  /* Under Windows we don't support groups. */   
  if (group && *group)
    gc_error (0, 0, _("Note that group specifications are ignored\n"));
  if (*user)
    {
      static char *my_name;

      if (!my_name)
        {
          char tmp[1];
          DWORD size = 1;

          GetUserNameA (tmp, &size);
          my_name = xmalloc (size);
          if (!GetUserNameA (my_name, &size))
            gc_error (1,0, "error getting current user name: %s",
                      w32_strerror (-1));
        }

      if (!strcmp (user, my_name))
        return 1; /* Found.  */
    }
#else /*!HAVE_W32_SYSTEM*/
  /* First check whether the user matches.  */
  if (*user)
    {
      static char *my_name;

      if (!my_name)
        {
          struct passwd *pw = getpwuid ( getuid () );
          if (!pw)
            gc_error (1, errno, "getpwuid failed for current user");
          my_name = xstrdup (pw->pw_name);
        }
      if (!strcmp (user, my_name))
        return 1; /* Found.  */
    }

  /* If that failed, check whether a group matches.  */
  if (group && *group)
    {
      static char *my_group;
      static char **my_supgroups;
      int n;

      if (!my_group)
        {
          struct group *gr = getgrgid ( getgid () );
          if (!gr)
            gc_error (1, errno, "getgrgid failed for current user");
          my_group = xstrdup (gr->gr_name);
        }
      if (!strcmp (group, my_group))
        return 1; /* Found.  */

      if (!my_supgroups)
        {
          int ngids;
          gid_t *gids;

          ngids = getgroups (0, NULL);
          gids  = xcalloc (ngids+1, sizeof *gids);
          ngids = getgroups (ngids, gids);
          if (ngids < 0)
            gc_error (1, errno, "getgroups failed for current user");
          my_supgroups = xcalloc (ngids+1, sizeof *my_supgroups);
          for (n=0; n < ngids; n++)
            {
              struct group *gr = getgrgid ( gids[n] );
              if (!gr)
                gc_error (1, errno, "getgrgid failed for supplementary group");
              my_supgroups[n] = xstrdup (gr->gr_name);
            }
          xfree (gids);
        }

      for (n=0; my_supgroups[n]; n++)
        if (!strcmp (group, my_supgroups[n]))
          return 1; /* Found.  */
    }
#endif /*!HAVE_W32_SYSTEM*/
  return 0; /* No match.  */
}



/* Read and process the global configuration file for gpgconf.  This
   optional file is used to update our internal tables at runtime and
   may also be used to set new default values.  If FNAME is NULL the
   default name will be used.  With UPDATE set to true the internal
   tables are actually updated; if not set, only a syntax check is
   done.  If DEFAULTS is true the global options are written to the
   configuration files.  If LISTFP is set, no changes are done but the
   configuration file is printed to LISTFP in a colon separated format.

   Returns 0 on success or if the config file is not present; -1 is
   returned on error. */
int
gc_process_gpgconf_conf (const char *fname_arg, int update, int defaults,
                         FILE *listfp)
{
  int result = 0;
  char *line = NULL;
  size_t line_len = 0;
  ssize_t length;
  FILE *config;
  int lineno = 0;
  int in_rule = 0;
  int got_match = 0;
  int runtime[GC_BACKEND_NR];
  int used_components[GC_COMPONENT_NR];
  int backend_id, component_id;
  char *fname;

  if (fname_arg)
    fname = xstrdup (fname_arg);
  else
    fname = make_filename (gnupg_sysconfdir (), "gpgconf.conf", NULL);

  for (backend_id = 0; backend_id < GC_BACKEND_NR; backend_id++)
    runtime[backend_id] = 0;
  for (component_id = 0; component_id < GC_COMPONENT_NR; component_id++)
    used_components[component_id] = 0;

  config = fopen (fname, "r");
  if (!config)
    {
      /* Do not print an error if the file is not available, except
         when running in syntax check mode.  */
      if (errno != ENOENT || !update)
        {
          gc_error (0, errno, "can not open global config file `%s'", fname);
          result = -1;
        }
      xfree (fname);
      return result;
    }

  while ((length = read_line (config, &line, &line_len, NULL)) > 0)
    {
      char *key, *component, *option, *flags, *value;
      char *empty;
      gc_option_t *option_info = NULL;
      char *p;
      int is_continuation;
      
      lineno++;
      key = line;
      while (*key == ' ' || *key == '\t')
        key++;
      if (!*key || *key == '#' || *key == '\r' || *key == '\n')
        continue;

      is_continuation = (key != line);

      /* Parse the key field.  */
      if (!is_continuation && got_match)
        break;  /* Finish after the first match.  */
      else if (!is_continuation)
        {
          in_rule = 0;
          for (p=key+1; *p && !strchr (" \t\r\n", *p); p++)
            ;
          if (!*p)
            {
              gc_error (0, 0, "missing rule at `%s', line %d", fname, lineno);
              result = -1;
              continue;
            }
          *p++ = 0;
          component = p;
        }
      else if (!in_rule)
        {
          gc_error (0, 0, "continuation but no rule at `%s', line %d",
                    fname, lineno);
          result = -1;
          continue;
        }
      else
        {
          component = key;
          key = NULL;
        }

      in_rule = 1;

      /* Parse the component.  */
      while (*component == ' ' || *component == '\t')
        component++;
      for (p=component; *p && !strchr (" \t\r\n", *p); p++)
        ;
      if (p == component)
        {
          gc_error (0, 0, "missing component at `%s', line %d",
                    fname, lineno);
          result = -1;
          continue;
        }
      empty = p;
      *p++ = 0;
      option = p;
      component_id = gc_component_find (component);
      if (component_id < 0)
        {
          gc_error (0, 0, "unknown component at `%s', line %d",
                    fname, lineno);
          result = -1;
        }

      /* Parse the option name.  */
      while (*option == ' ' || *option == '\t')
        option++;
      for (p=option; *p && !strchr (" \t\r\n", *p); p++)
        ;
      if (p == option)
        {
          gc_error (0, 0, "missing option at `%s', line %d",
                    fname, lineno);
          result = -1;
          continue;
        }
      *p++ = 0;
      flags = p;
      if ( component_id != -1)
        {
          option_info = find_option (component_id, option, GC_BACKEND_ANY);
          if (!option_info)
            {
              gc_error (0, 0, "unknown option at `%s', line %d",
                        fname, lineno);
              result = -1;
            }
        }


      /* Parse the optional flags.  */
      while (*flags == ' ' || *flags == '\t')
        flags++;
      if (*flags == '[')
        {
          flags++;
          p = strchr (flags, ']');
          if (!p)
            {
              gc_error (0, 0, "syntax error in rule at `%s', line %d",
                        fname, lineno);
              result = -1;
              continue;
            }
          *p++ = 0;
          value = p;
        }
      else  /* No flags given.  */
        {
          value = flags;
          flags = NULL;
        }

      /* Parse the optional value.  */
      while (*value == ' ' || *value == '\t')
       value++;
      for (p=value; *p && !strchr ("\r\n", *p); p++)
        ;
      if (p == value)
        value = empty; /* No value given; let it point to an empty string.  */
      else
        {
          /* Strip trailing white space.  */
          *p = 0;
          for (p--; p > value && (*p == ' ' || *p == '\t'); p--)
            *p = 0;
        }

      /* Check flag combinations.  */
      if (!flags)
        ;
      else if (!strcmp (flags, "default"))
        {
          if (*value)
            {
              gc_error (0, 0, "flag \"default\" may not be combined "
                        "with a value at `%s', line %d",
                        fname, lineno);
              result = -1;
            }
        }
      else if (!strcmp (flags, "change"))
        ;
      else if (!strcmp (flags, "no-change"))
        ;
      else
        {
          gc_error (0, 0, "unknown flag at `%s', line %d",
                    fname, lineno);
          result = -1;
        }

      /* In list mode we print out all records.  */
      if (listfp && !result)
        {
          /* If this is a new ruleset, print a key record.  */
          if (!is_continuation)
            {
              char *group = strchr (key, ':');
              if (group)
                {
                  *group++ = 0;
                  if ((p = strchr (group, ':')))
                    *p = 0; /* We better strip any extra stuff. */
                }                    
              
              fprintf (listfp, "k:%s:", my_percent_escape (key));
              fprintf (listfp, "%s\n", group? my_percent_escape (group):"");
            }

          /* All other lines are rule records.  */
          fprintf (listfp, "r:::%s:%s:%s:",
                   gc_component[component_id].name,                     
                   option_info->name? option_info->name : "",
                   flags? flags : "");
          if (value != empty)
            fprintf (listfp, "\"%s", my_percent_escape (value));
          
          putc ('\n', listfp);
        }

      /* Check whether the key matches but do this only if we are not
         running in syntax check mode. */
      if ( update 
           && !result && !listfp
           && (got_match || (key && key_matches_user_or_group (key))) )
        {
          int newflags = 0;

          got_match = 1;

          /* Apply the flags from gpgconf.conf.  */
          if (!flags)
            ;
          else if (!strcmp (flags, "default"))
            newflags |= GC_OPT_FLAG_DEFAULT;
          else if (!strcmp (flags, "no-change"))
            option_info->flags |= GC_OPT_FLAG_NO_CHANGE;
          else if (!strcmp (flags, "change"))
            option_info->flags &= ~GC_OPT_FLAG_NO_CHANGE;

          if (defaults)
            {
              assert (component_id >= 0 && component_id < GC_COMPONENT_NR);
              used_components[component_id] = 1;

              /* Here we explicitly allow to update the value again.  */
              if (newflags)
                {
                  option_info->new_flags = 0;
                }
              if (*value)
                {
                  xfree (option_info->new_value);
                  option_info->new_value = NULL;
                }
              change_one_value (option_info, runtime, newflags, value);
            }
        }
    }

  if (length < 0 || ferror (config))
    {
      gc_error (0, errno, "error reading from `%s'", fname);
      result = -1;
    }
  if (fclose (config) && ferror (config))
    gc_error (0, errno, "error closing `%s'", fname);

  xfree (line);

  /* If it all worked, process the options. */
  if (!result && update && defaults && !listfp)
    {
      /* We need to switch off the runtime update, so that we can do
         it later all at once. */
      int save_opt_runtime = opt.runtime;
      opt.runtime = 0;

      for (component_id = 0; component_id < GC_COMPONENT_NR; component_id++)
        {
          gc_component_change_options (component_id, NULL);
        }
      opt.runtime = save_opt_runtime;

      if (opt.runtime)
        {
          for (backend_id = 0; backend_id < GC_BACKEND_NR; backend_id++)  
            if (runtime[backend_id] && gc_backend[backend_id].runtime_change)
              (*gc_backend[backend_id].runtime_change) ();
        }
    }

  xfree (fname);
  return result;
}