summaryrefslogtreecommitdiffstats
path: root/g10/mainproc.c
blob: 8e4d848bb6c7b747d1c5f165ee1ecfbfa5fc286f (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
/* mainproc.c - handle packets
 * Copyright (C) 1998-2009 Free Software Foundation, Inc.
 * Copyright (C) 2013-2014 Werner Koch
 * Copyright (C) 2020 g10 Code GmbH
 *
 * 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 this program; if not, see <https://www.gnu.org/licenses/>.
 */

#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "gpg.h"
#include "../common/util.h"
#include "packet.h"
#include "../common/iobuf.h"
#include "options.h"
#include "keydb.h"
#include "filter.h"
#include "main.h"
#include "../common/status.h"
#include "../common/i18n.h"
#include "trustdb.h"
#include "keyserver-internal.h"
#include "photoid.h"
#include "../common/mbox-util.h"
#include "call-dirmngr.h"
#include "../common/compliance.h"

/* Put an upper limit on nested packets.  The 32 is an arbitrary
   value, a much lower should actually be sufficient.  */
#define MAX_NESTING_DEPTH 32


/* An object to build a list of keyid related info.  */
struct kidlist_item
{
  struct kidlist_item *next;
  u32 kid[2];
  int pubkey_algo;
  int reason;
};

/* An object to build a list of symkey packet info.  */
struct symlist_item
{
  struct symlist_item *next;
  int cipher_algo;
  int cfb_mode;
  int other_error;
};


/*
 * Object to hold the processing context.
 */
typedef struct mainproc_context *CTX;
struct mainproc_context
{
  ctrl_t ctrl;
  struct mainproc_context *anchor;  /* May be useful in the future. */
  PKT_public_key *last_pubkey;
  PKT_user_id     *last_user_id;
  md_filter_context_t mfx;
  int sigs_only;    /* Process only signatures and reject all other stuff. */
  int encrypt_only; /* Process only encryption messages. */

  /* Name of the file with the complete signature or the file with the
     detached signature.  This is currently only used to deduce the
     file name of the data file if that has not been given. */
  const char *sigfilename;

  /* A structure to describe the signed data in case of a detached
     signature. */
  struct
  {
    /* A file descriptor of the signed data.  Only used if not -1. */
    int data_fd;
    /* A list of filenames with the data files or NULL. This is only
       used if DATA_FD is -1. */
    strlist_t data_names;
    /* Flag to indicated that either one of the next previous fields
       is used.  This is only needed for better readability. */
    int used;
  } signed_data;

  DEK *dek;
  int last_was_session_key;
  kbnode_t list;    /* The current list of packets. */
  iobuf_t iobuf;    /* Used to get the filename etc. */
  int trustletter;  /* Temporary usage in list_node. */
  ulong symkeys;    /* Number of symmetrically encrypted session keys.  */
  struct kidlist_item *pkenc_list; /* List of encryption packets. */
  struct symlist_item *symenc_list; /* List of sym. encryption packets. */
  int seen_pkt_encrypted_aead; /* PKT_ENCRYPTED_AEAD packet seen. */
  int seen_pkt_encrypted_mdc;  /* PKT_ENCRYPTED_MDC packet seen. */
  struct {
    unsigned int sig_seen:1;      /* Set to true if a signature packet
                                     has been seen. */
    unsigned int data:1;          /* Any data packet seen */
    unsigned int uncompress_failed:1;
  } any;
};


/* Counter with the number of literal data packets seen.  Note that
 * this is also bumped at the end of an encryption.  This counter is
 * used for a basic consistency check of a received PGP message.  */
static int literals_seen;


/*** Local prototypes.  ***/
static int do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a);
static void list_node (CTX c, kbnode_t node);
static void proc_tree (CTX c, kbnode_t node);


/*** Functions.  ***/

/* Reset the literal data counter.  This is required to setup a new
 * decryption or verification context.  */
void
reset_literals_seen(void)
{
  literals_seen = 0;
}


static void
release_list( CTX c )
{
  proc_tree (c, c->list);
  release_kbnode (c->list);
  while (c->pkenc_list)
    {
      struct kidlist_item *tmp = c->pkenc_list->next;
      xfree (c->pkenc_list);
      c->pkenc_list = tmp;
    }
  c->pkenc_list = NULL;
  while (c->symenc_list)
    {
      struct symlist_item *tmp = c->symenc_list->next;
      xfree (c->symenc_list);
      c->symenc_list = tmp;
    }
  c->symenc_list = NULL;
  c->list = NULL;
  c->any.data = 0;
  c->any.uncompress_failed = 0;
  c->last_was_session_key = 0;
  c->seen_pkt_encrypted_aead = 0;
  c->seen_pkt_encrypted_mdc = 0;
  xfree (c->dek);
  c->dek = NULL;
}


static int
add_onepass_sig (CTX c, PACKET *pkt)
{
  kbnode_t node;

  if (c->list) /* Add another packet. */
    add_kbnode (c->list, new_kbnode (pkt));
  else /* Insert the first one.  */
    c->list = node = new_kbnode (pkt);

  return 1;
}


static int
add_gpg_control (CTX c, PACKET *pkt)
{
  if ( pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START )
    {
      /* New clear text signature.
       * Process the last one and reset everything */
      release_list(c);
    }

  if (c->list)  /* Add another packet.  */
    add_kbnode (c->list, new_kbnode (pkt));
  else /* Insert the first one. */
    c->list = new_kbnode (pkt);

  return 1;
}


static int
add_user_id (CTX c, PACKET *pkt)
{
  if (!c->list)
    {
      log_error ("orphaned user ID\n");
      return 0;
    }
  add_kbnode (c->list, new_kbnode (pkt));
  return 1;
}


static int
add_subkey (CTX c, PACKET *pkt)
{
  if (!c->list)
    {
      log_error ("subkey w/o mainkey\n");
      return 0;
    }
  add_kbnode (c->list, new_kbnode (pkt));
  return 1;
}


static int
add_ring_trust (CTX c, PACKET *pkt)
{
  if (!c->list)
    {
      log_error ("ring trust w/o key\n");
      return 0;
    }
  add_kbnode (c->list, new_kbnode (pkt));
  return 1;
}


static int
add_signature (CTX c, PACKET *pkt)
{
  kbnode_t node;

  c->any.sig_seen = 1;
  if (pkt->pkttype == PKT_SIGNATURE && !c->list)
    {
      /* This is the first signature for the following datafile.
       * GPG does not write such packets; instead it always uses
       * onepass-sig packets.  The drawback of PGP's method
       * of prepending the signature to the data is
       * that it is not possible to make a signature from data read
       * from stdin.	(GPG is able to read PGP stuff anyway.) */
      node = new_kbnode (pkt);
      c->list = node;
      return 1;
    }
  else if (!c->list)
    return 0; /* oops (invalid packet sequence)*/
  else if (!c->list->pkt)
    BUG();    /* so nicht */

  /* Add a new signature node item at the end. */
  node = new_kbnode (pkt);
  add_kbnode (c->list, node);

  return 1;
}


static gpg_error_t
symkey_decrypt_seskey (DEK *dek, byte *seskey, size_t slen)
{
  gpg_error_t err;
  gcry_cipher_hd_t hd;
  enum gcry_cipher_modes ciphermode;
  unsigned int noncelen, keylen;

  if (dek->use_aead)
    {
      err = openpgp_aead_algo_info (dek->use_aead, &ciphermode, &noncelen);
      if (err)
        return err;
    }
  else
    {
      ciphermode = GCRY_CIPHER_MODE_CFB;
      noncelen = 0;
    }

  /* Check that the session key has a size of 16 to 32 bytes.  */
  if ((dek->use_aead && (slen < (noncelen + 16 + 16)
                         || slen > (noncelen + 32 + 16)))
      || (!dek->use_aead && (slen < 17 || slen > 33)))
    {
      log_error ( _("weird size for an encrypted session key (%d)\n"),
		  (int)slen);
      return gpg_error (GPG_ERR_BAD_KEY);
    }

  err = openpgp_cipher_open (&hd, dek->algo, ciphermode, 1);
  if (!err)
    err = gcry_cipher_setkey (hd, dek->key, dek->keylen);
  if (!err)
    err = gcry_cipher_setiv (hd, noncelen? seskey : NULL, noncelen);
  if (err)
    goto leave;

  if (dek->use_aead)
    {
      byte ad[4];

      ad[0] = (0xc0 | PKT_SYMKEY_ENC);
      ad[1] = 5;
      ad[2] = dek->algo;
      ad[3] = dek->use_aead;
      err = gcry_cipher_authenticate (hd, ad, 4);
      if (err)
        goto leave;
      gcry_cipher_final (hd);
      keylen = slen - noncelen - 16;
      err = gcry_cipher_decrypt (hd, seskey+noncelen, keylen, NULL, 0);
      if (err)
        goto leave;
      err = gcry_cipher_checktag (hd, seskey+noncelen+keylen, 16);
      if (err)
        goto leave;
      /* Now we replace the dek components with the real session key to
       * decrypt the contents of the sequencing packet. */
      if (keylen > DIM(dek->key))
        {
          err = gpg_error (GPG_ERR_TOO_LARGE);
          goto leave;
        }
      dek->keylen = keylen;
      memcpy (dek->key, seskey + noncelen, dek->keylen);
    }
  else
    {
      gcry_cipher_decrypt (hd, seskey, slen, NULL, 0);

      /* Here we can only test whether the algo given in decrypted
       * session key is a valid OpenPGP algo.  With 11 defined
       * symmetric algorithms we will miss 4.3% of wrong passphrases
       * here.  The actual checking is done later during bulk
       * decryption; we can't bring this check forward easily.  We
       * need to use the GPG_ERR_CHECKSUM so that we won't run into
       * the gnupg < 2.2 bug compatible case which would terminate the
       * process on GPG_ERR_CIPHER_ALGO.  Note that with AEAD (above)
       * we will have a reliable test here.  */
      if (openpgp_cipher_test_algo (seskey[0])
          || openpgp_cipher_get_algo_keylen (seskey[0]) != slen - 1)
        {
          err = gpg_error (GPG_ERR_CHECKSUM);
          goto leave;
        }

      /* Now we replace the dek components with the real session key to
       * decrypt the contents of the sequencing packet. */
      keylen = slen-1;
      if (keylen > DIM(dek->key))
        {
          err = gpg_error (GPG_ERR_TOO_LARGE);
          goto leave;
        }
      dek->algo = seskey[0];
      dek->keylen = slen-1;
      memcpy (dek->key, seskey + 1, dek->keylen);
    }

  /*log_hexdump( "thekey", dek->key, dek->keylen );*/

 leave:
  gcry_cipher_close (hd);
  return 0;
}


static void
proc_symkey_enc (CTX c, PACKET *pkt)
{
  gpg_error_t err;
  PKT_symkey_enc *enc;

  enc = pkt->pkt.symkey_enc;
  if (!enc)
    log_error ("invalid symkey encrypted packet\n");
  else if(!c->dek)
    {
      int algo = enc->cipher_algo;
      const char *s = openpgp_cipher_algo_name (algo);
      const char *a = (enc->aead_algo ? openpgp_aead_algo_name (enc->aead_algo)
                       /**/           : "CFB");

      if (!openpgp_cipher_test_algo (algo))
        {
          if (!opt.quiet)
            {
              /* Note: TMPSTR is only used to avoid i18n changes.  */
              char *tmpstr = xstrconcat (s, ".", a, NULL);
              if (enc->seskeylen)
                log_info (_("%s encrypted session key\n"), tmpstr);
              else
                log_info (_("%s encrypted data\n"), tmpstr);
              xfree (tmpstr);
            }
        }
      else
        {
          log_error (_("encrypted with unknown algorithm %d\n"), algo);
          s = NULL; /* Force a goto leave.  */
        }

      if (openpgp_md_test_algo (enc->s2k.hash_algo))
        {
          log_error(_("passphrase generated with unknown digest"
                      " algorithm %d\n"),enc->s2k.hash_algo);
          s = NULL;
        }

      c->last_was_session_key = 2;
      if (!s || opt.list_only)
        goto leave;

      if (opt.override_session_key)
        {
          c->dek = xmalloc_clear (sizeof *c->dek);
          if (get_override_session_key (c->dek, opt.override_session_key))
            {
              xfree (c->dek);
              c->dek = NULL;
            }
        }
      else
        {
          c->dek = passphrase_to_dek (algo, &enc->s2k, 0, 0, NULL,
                                      GETPASSWORD_FLAG_SYMDECRYPT, NULL);
          if (c->dek)
            {
              c->dek->symmetric = 1;
              c->dek->use_aead = enc->aead_algo;

              /* FIXME: This doesn't work perfectly if a symmetric key
                 comes before a public key in the message - if the
                 user doesn't know the passphrase, then there is a
                 chance that the "decrypted" algorithm will happen to
                 be a valid one, which will make the returned dek
                 appear valid, so we won't try any public keys that
                 come later. */
              if (enc->seskeylen)
                {
                  err = symkey_decrypt_seskey (c->dek,
                                               enc->seskey, enc->seskeylen);
                  if (err)
                    {
                      log_info ("decryption of the symmetrically encrypted"
                                 " session key failed: %s\n",
                                 gpg_strerror (err));
                      if (gpg_err_code (err) != GPG_ERR_BAD_KEY
                          && gpg_err_code (err) != GPG_ERR_CHECKSUM)
                        log_fatal ("process terminated to be bug compatible\n");
                      else
                        write_status_text (STATUS_ERROR,
                                           "symkey_decrypt.maybe_error"
                                           " 11_BAD_PASSPHRASE");

                      if (c->dek->s2k_cacheid[0])
                        {
                          if (opt.debug)
                            log_debug ("cleared passphrase cached with ID:"
                                       " %s\n", c->dek->s2k_cacheid);
                          passphrase_clear_cache (c->dek->s2k_cacheid);
                        }
                      xfree (c->dek);
                      c->dek = NULL;
                    }
                }
              else
                c->dek->algo_info_printed = 1;
            }
        }
    }

 leave:
  /* Record infos from the packet.  */
  {
    struct symlist_item  *symitem;
    symitem = xcalloc (1, sizeof *symitem);
    if (enc)
      {
        symitem->cipher_algo = enc->cipher_algo;
        symitem->cfb_mode = !enc->aead_algo;
      }
    else
      symitem->other_error = 1;
    symitem->next = c->symenc_list;
    c->symenc_list = symitem;
  }
  c->symkeys++;
  free_packet (pkt, NULL);
}


static void
proc_pubkey_enc (ctrl_t ctrl, CTX c, PACKET *pkt)
{
  PKT_pubkey_enc *enc;
  int result = 0;

  /* Check whether the secret key is available and store in this case.  */
  c->last_was_session_key = 1;
  enc = pkt->pkt.pubkey_enc;
  /*printf("enc: encrypted by a pubkey with keyid %08lX\n", enc->keyid[1] );*/
  /* Hmmm: why do I have this algo check here - anyway there is
   * function to check it. */
  if (opt.verbose)
    log_info (_("public key is %s\n"), keystr (enc->keyid));

  if (is_status_enabled())
    {
      char buf[50];
      /* FIXME: For ECC support we need to map the OpenPGP algo number
         to the Libgcrypt defined one.  This is due a chicken-egg
         problem: We need to have code in Libgcrypt for a new
         algorithm so to implement a proposed new algorithm before the
         IANA will finally assign an OpenPGP identifier.  */
      snprintf (buf, sizeof buf, "%08lX%08lX %d 0",
		(ulong)enc->keyid[0], (ulong)enc->keyid[1], enc->pubkey_algo);
      write_status_text (STATUS_ENC_TO, buf);
    }

  if (!opt.list_only && opt.override_session_key)
    {
      /* It does not make much sense to store the session key in
       * secure memory because it has already been passed on the
       * command line and the GCHQ knows about it.  */
      c->dek = xmalloc_clear (sizeof *c->dek);
      result = get_override_session_key (c->dek, opt.override_session_key);
      if (result)
        {
          xfree (c->dek);
          c->dek = NULL;
	}
    }
  else if (enc->pubkey_algo == PUBKEY_ALGO_ELGAMAL_E
           || enc->pubkey_algo == PUBKEY_ALGO_ECDH
           || enc->pubkey_algo == PUBKEY_ALGO_RSA
           || enc->pubkey_algo == PUBKEY_ALGO_RSA_E
           || enc->pubkey_algo == PUBKEY_ALGO_ELGAMAL)
    {
      /* Note that we also allow type 20 Elgamal keys for decryption.
         There are still a couple of those keys in active use as a
         subkey.  */

      /* FIXME: Store this all in a list and process it later so that
         we can prioritize what key to use.  This gives a better user
         experience if wildcard keyids are used.  */
      if  (!c->dek && ((!enc->keyid[0] && !enc->keyid[1])
                       || opt.try_all_secrets
                       || have_secret_key_with_kid (enc->keyid)))
        {
          if(opt.list_only)
            result = GPG_ERR_MISSING_ACTION; /* fixme: Use better error code. */
          else
            {
              c->dek = xmalloc_secure_clear (sizeof *c->dek);
              if ((result = get_session_key (ctrl, enc, c->dek)))
                {
                  /* Error: Delete the DEK. */
                  xfree (c->dek);
                  c->dek = NULL;
		}
	    }
	}
      else
        result = GPG_ERR_NO_SECKEY;
    }
  else
    result = GPG_ERR_PUBKEY_ALGO;

  if (1)
    {
      /* Store it for later display.  */
      struct kidlist_item *x = xmalloc (sizeof *x);
      x->kid[0] = enc->keyid[0];
      x->kid[1] = enc->keyid[1];
      x->pubkey_algo = enc->pubkey_algo;
      x->reason = result;
      x->next = c->pkenc_list;
      c->pkenc_list = x;

      if (!result && opt.verbose > 1)
        log_info (_("public key encrypted data: good DEK\n"));
    }

  free_packet(pkt, NULL);
}


/*
 * Print the list of public key encrypted packets which we could
 * not decrypt.
 */
static void
print_pkenc_list (ctrl_t ctrl, struct kidlist_item *list, int failed)
{
  for (; list; list = list->next)
    {
      PKT_public_key *pk;
      const char *algstr;

      if (failed && !list->reason)
        continue;
      if (!failed && list->reason)
        continue;

      algstr = openpgp_pk_algo_name (list->pubkey_algo);
      pk = xmalloc_clear (sizeof *pk);

      if (!algstr)
        algstr = "[?]";
      pk->pubkey_algo = list->pubkey_algo;
      if (!get_pubkey (ctrl, pk, list->kid))
        {
          char *p;
          log_info (_("encrypted with %u-bit %s key, ID %s, created %s\n"),
                    nbits_from_pk (pk), algstr, keystr_from_pk(pk),
                    strtimestamp (pk->timestamp));
          p = get_user_id_native (ctrl, list->kid);
          log_printf (_("      \"%s\"\n"), p);
          xfree (p);
        }
      else
        log_info (_("encrypted with %s key, ID %s\n"),
                  algstr, keystr(list->kid));

      free_public_key (pk);

      if (gpg_err_code (list->reason) == GPG_ERR_NO_SECKEY)
        {
          if (is_status_enabled())
            {
              char buf[20];
              snprintf (buf, sizeof buf, "%08lX%08lX",
                        (ulong)list->kid[0], (ulong)list->kid[1]);
              write_status_text (STATUS_NO_SECKEY, buf);
	    }
	}
      else if (gpg_err_code (list->reason) == GPG_ERR_MISSING_ACTION)
        {
          /* Not tested for secret key due to --list-only mode.  */
        }
      else if (list->reason)
        {
          log_info (_("public key decryption failed: %s\n"),
                    gpg_strerror (list->reason));
          if (gpg_err_source (list->reason) == GPG_ERR_SOURCE_SCD
              && gpg_err_code (list->reason) == GPG_ERR_INV_ID)
            print_further_info ("a reason might be a card with replaced keys");
          write_status_error ("pkdecrypt_failed", list->reason);
        }
    }
}


static void
proc_encrypted (CTX c, PACKET *pkt)
{
  int result = 0;
  int early_plaintext = literals_seen;
  unsigned int compliance_de_vs = 0;

  if (pkt->pkttype == PKT_ENCRYPTED_AEAD)
    c->seen_pkt_encrypted_aead = 1;
  if (pkt->pkttype == PKT_ENCRYPTED_MDC)
    c->seen_pkt_encrypted_mdc = 1;

  if (early_plaintext)
    {
      log_info (_("WARNING: multiple plaintexts seen\n"));
      write_status_errcode ("decryption.early_plaintext", GPG_ERR_BAD_DATA);
      /* We fail only later so that we can print some more info first.  */
    }

  if (!opt.quiet)
    {
      if (c->symkeys>1)
        log_info (_("encrypted with %lu passphrases\n"), c->symkeys);
      else if (c->symkeys == 1)
        log_info (_("encrypted with 1 passphrase\n"));
      print_pkenc_list (c->ctrl, c->pkenc_list, 1 );
      print_pkenc_list (c->ctrl, c->pkenc_list, 0 );
    }

  /* FIXME: Figure out the session key by looking at all pkenc packets. */

  write_status (STATUS_BEGIN_DECRYPTION);

  /*log_debug("dat: %sencrypted data\n", c->dek?"":"conventional ");*/
  if (opt.list_only)
    result = -1;
  else if (!c->dek && !c->last_was_session_key)
    {
      int algo;
      STRING2KEY s2kbuf;
      STRING2KEY *s2k = NULL;
      int canceled;

      if (opt.override_session_key)
        {
          c->dek = xmalloc_clear (sizeof *c->dek);
          result = get_override_session_key (c->dek, opt.override_session_key);
          if (result)
            {
              xfree (c->dek);
              c->dek = NULL;
            }
        }
      else
        {
          /* Assume this is old style conventional encrypted data. */
          algo = opt.def_cipher_algo;
          if (algo)
            log_info (_("assuming %s encrypted data\n"),
                      openpgp_cipher_algo_name (algo));
          else if (openpgp_cipher_test_algo (CIPHER_ALGO_IDEA))
            {
              algo = opt.def_cipher_algo;
              if (!algo)
                algo = opt.s2k_cipher_algo;
              log_info (_("IDEA cipher unavailable, "
                          "optimistically attempting to use %s instead\n"),
                        openpgp_cipher_algo_name (algo));
            }
          else
            {
              algo = CIPHER_ALGO_IDEA;
              if (!opt.s2k_digest_algo)
                {
                  /* If no digest is given we assume SHA-1. */
                  s2kbuf.mode = 0;
                  s2kbuf.hash_algo = DIGEST_ALGO_SHA1;
                  s2k = &s2kbuf;
                }
              log_info (_("assuming %s encrypted data\n"), "IDEA");
            }

          c->dek = passphrase_to_dek (algo, s2k, 0, 0, NULL,
                                      GETPASSWORD_FLAG_SYMDECRYPT, &canceled);
          if (c->dek)
            c->dek->algo_info_printed = 1;
          else if (canceled)
            result = gpg_error (GPG_ERR_CANCELED);
          else
            result = gpg_error (GPG_ERR_INV_PASSPHRASE);
        }
    }
  else if (!c->dek)
    result = GPG_ERR_NO_SECKEY;

  /* Compute compliance with CO_DE_VS.  */
  if (!result && is_status_enabled ()
      /* Overriding session key voids compliance.  */
      && !opt.override_session_key
      /* Check symmetric cipher.  */
      && gnupg_gcrypt_is_compliant (CO_DE_VS)
      && gnupg_cipher_is_compliant (CO_DE_VS, c->dek->algo,
                                    GCRY_CIPHER_MODE_CFB))
    {
      struct kidlist_item *i;
      struct symlist_item *si;
      int compliant = 1;
      PKT_public_key *pk = xmalloc (sizeof *pk);

      if ( !(c->pkenc_list || c->symkeys) )
        log_debug ("%s: where else did the session key come from?\n", __func__);

      /* Check that all seen symmetric key packets use compliant
       * algos.  This is so that no non-compliant encrypted session
       * key can be sneaked in.  */
      for (si = c->symenc_list; si && compliant; si = si->next)
        {
          if (!si->cfb_mode
              || !gnupg_cipher_is_compliant (CO_DE_VS, si->cipher_algo,
                                             GCRY_CIPHER_MODE_CFB))
            compliant = 0;
        }

      /* Check that every known public key used to encrypt the session key
       * is compliant.  */
      for (i = c->pkenc_list; i && compliant; i = i->next)
        {
          memset (pk, 0, sizeof *pk);
          pk->pubkey_algo = i->pubkey_algo;
          if (!get_pubkey (c->ctrl, pk, i->kid)
              && !gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0,
                                         pk->pkey, nbits_from_pk (pk), NULL))
            compliant = 0;
          release_public_key_parts (pk);
        }

      xfree (pk);

      if (compliant)
        compliance_de_vs |= 1;
    }


  if (!result)
    {
      int compl_error;
      result = decrypt_data (c->ctrl, c, pkt->pkt.encrypted, c->dek,
                             &compl_error);
      if (!result && !compl_error)
        compliance_de_vs |= 2;
    }

  /* Trigger the deferred error.  */
  if (!result && early_plaintext)
    result = gpg_error (GPG_ERR_BAD_DATA);

  if (result == -1)
    ;
  else if (!result
           && !opt.ignore_mdc_error
           && !pkt->pkt.encrypted->mdc_method
           && !pkt->pkt.encrypted->aead_algo)
    {
      /* The message has been decrypted but does not carry an MDC.
       * The option --ignore-mdc-error has also not been used.  To
       * avoid attacks changing an MDC message to a non-MDC message,
       * we fail here.  */
      log_error (_("WARNING: message was not integrity protected\n"));
      if (!pkt->pkt.encrypted->mdc_method
          && (openpgp_cipher_get_algo_blklen (c->dek->algo) == 8
              || c->dek->algo == CIPHER_ALGO_TWOFISH))
        {
          /* Before 2.2.8 we did not fail hard for a missing MDC if
           * one of the old ciphers where used.  Although these cases
           * are rare in practice we print a hint on how to decrypt
           * such messages.  */
          log_string
            (GPGRT_LOG_INFO,
             _("Hint: If this message was created before the year 2003 it is\n"
               "likely that this message is legitimate.  This is because back\n"
               "then integrity protection was not widely used.\n"));
          log_info (_("Use the option '%s' to decrypt anyway.\n"),
                     "--ignore-mdc-error");
          write_status_errcode ("nomdc_with_legacy_cipher",
                                GPG_ERR_DECRYPT_FAILED);
        }
      log_info (_("decryption forced to fail!\n"));
      write_status (STATUS_DECRYPTION_FAILED);
    }
  else if (!result || (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE
                       && !pkt->pkt.encrypted->aead_algo
                       && opt.ignore_mdc_error))
    {
      /* All is fine or for an MDC message the MDC failed but the
       * --ignore-mdc-error option is active.  For compatibility
       * reasons we issue GOODMDC also for AEAD messages.  */
      write_status (STATUS_DECRYPTION_OKAY);
      if (opt.verbose > 1)
        log_info(_("decryption okay\n"));

      if (pkt->pkt.encrypted->aead_algo)
        {
          write_status (STATUS_GOODMDC);
          compliance_de_vs |= 4;
        }
      else if (pkt->pkt.encrypted->mdc_method && !result)
        {
          write_status (STATUS_GOODMDC);
          compliance_de_vs |= 4;
        }
      else
        log_info (_("WARNING: message was not integrity protected\n"));
    }
  else if (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE
           || gpg_err_code (result) == GPG_ERR_TRUNCATED)
    {
      glo_ctrl.lasterr = result;
      log_error (_("WARNING: encrypted message has been manipulated!\n"));
      write_status (STATUS_BADMDC);
      write_status (STATUS_DECRYPTION_FAILED);
    }
  else
    {
      if (gpg_err_code (result) == GPG_ERR_BAD_KEY
          || gpg_err_code (result) == GPG_ERR_CHECKSUM
          || gpg_err_code (result) == GPG_ERR_CIPHER_ALGO)
        {
          if (c->symkeys)
            write_status_text (STATUS_ERROR,
                               "symkey_decrypt.maybe_error"
                               " 11_BAD_PASSPHRASE");

          if (*c->dek->s2k_cacheid != '\0')
            {
              if (opt.debug)
                log_debug ("cleared passphrase cached with ID: %s\n",
                           c->dek->s2k_cacheid);
              passphrase_clear_cache (c->dek->s2k_cacheid);
            }
        }
      glo_ctrl.lasterr = result;
      write_status (STATUS_DECRYPTION_FAILED);
      log_error (_("decryption failed: %s\n"), gpg_strerror (result));
      /* Hmmm: does this work when we have encrypted using multiple
       * ways to specify the session key (symmmetric and PK). */
    }


  /* If we concluded that the decryption was compliant, issue a
   * compliance status before the end of the decryption status.  */
  if (compliance_de_vs == (4|2|1))
    {
      write_status_strings (STATUS_DECRYPTION_COMPLIANCE_MODE,
                            gnupg_status_compliance_flag (CO_DE_VS),
                            NULL);
    }

  xfree (c->dek);
  c->dek = NULL;
  free_packet (pkt, NULL);
  c->last_was_session_key = 0;
  write_status (STATUS_END_DECRYPTION);

  /* Bump the counter even if we have not seen a literal data packet
   * inside an encryption container.  This acts as a sentinel in case
   * a misplace extra literal data packets follows after this
   * encrypted packet.  */
  literals_seen++;

  /* The --require-compliance option allows to simplify decryption in
   * de-vs compliance mode by just looking at the exit status.  */
  if (opt.flags.require_compliance
      && opt.compliance == CO_DE_VS
      && compliance_de_vs != (4|2|1))
    {
      compliance_failure ();
    }
}


static int
have_seen_pkt_encrypted_aead_or_mdc( CTX c )
{
  CTX cc;

  for (cc = c; cc; cc = cc->anchor)
    {
      if (cc->seen_pkt_encrypted_aead)
	return 1;
      if (cc->seen_pkt_encrypted_mdc)
	return 1;
    }

  return 0;
}


static void
proc_plaintext( CTX c, PACKET *pkt )
{
  PKT_plaintext *pt = pkt->pkt.plaintext;
  int any, clearsig, rc;
  kbnode_t n;

  /* This is a literal data packet.  Bumb a counter for later checks.  */
  literals_seen++;

  if (pt->namelen == 8 && !memcmp( pt->name, "_CONSOLE", 8))
    log_info (_("Note: sender requested \"for-your-eyes-only\"\n"));
  else if (opt.verbose)
    {
      /* We don't use print_utf8_buffer because that would require a
       * string change which we don't want in 2.2.  It is also not
       * clear whether the filename is always utf-8 encoded.  */
      char *tmp = make_printable_string (pt->name, pt->namelen, 0);
      log_info (_("original file name='%.*s'\n"), (int)strlen (tmp), tmp);
      xfree (tmp);
    }

  free_md_filter_context (&c->mfx);
  if (gcry_md_open (&c->mfx.md, 0, 0))
    BUG ();
  /* fixme: we may need to push the textfilter if we have sigclass 1
   * and no armoring - Not yet tested
   * Hmmm, why don't we need it at all if we have sigclass 1
   * Should we assume that plaintext in mode 't' has always sigclass 1??
   * See: Russ Allbery's mail 1999-02-09
   */
  any = clearsig = 0;
  for (n=c->list; n; n = n->next )
    {
      if (n->pkt->pkttype == PKT_ONEPASS_SIG)
        {
          /* The onepass signature case. */
          if (n->pkt->pkt.onepass_sig->digest_algo)
            {
              if (!opt.skip_verify)
                gcry_md_enable (c->mfx.md,
                                n->pkt->pkt.onepass_sig->digest_algo);

              any = 1;
            }
        }
      else if (n->pkt->pkttype == PKT_GPG_CONTROL
               && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START)
        {
          /* The clearsigned message case. */
          size_t datalen = n->pkt->pkt.gpg_control->datalen;
          const byte *data = n->pkt->pkt.gpg_control->data;

          /* Check that we have at least the sigclass and one hash.  */
          if  (datalen < 2)
            log_fatal ("invalid control packet CTRLPKT_CLEARSIGN_START\n");
          /* Note that we don't set the clearsig flag for not-dash-escaped
           * documents.  */
          clearsig = (*data == 0x01);
          for (data++, datalen--; datalen; datalen--, data++)
            if (!opt.skip_verify)
              gcry_md_enable (c->mfx.md, *data);
          any = 1;
          break;  /* Stop here as one-pass signature packets are not
                     expected.  */
        }
      else if (n->pkt->pkttype == PKT_SIGNATURE)
        {
          /* The SIG+LITERAL case that PGP used to use.  */
          if (!opt.skip_verify)
            gcry_md_enable (c->mfx.md, n->pkt->pkt.signature->digest_algo);
          any = 1;
        }
    }

  if (!any && !opt.skip_verify && !have_seen_pkt_encrypted_aead_or_mdc(c))
    {
      /* This is for the old GPG LITERAL+SIG case.  It's not legal
         according to 2440, so hopefully it won't come up that often.
         There is no good way to specify what algorithms to use in
         that case, so these there are the historical answer. */
	gcry_md_enable (c->mfx.md, DIGEST_ALGO_RMD160);
	gcry_md_enable (c->mfx.md, DIGEST_ALGO_SHA1);
    }
  if (DBG_HASHING)
    {
      gcry_md_debug (c->mfx.md, "verify");
      if (c->mfx.md2)
        gcry_md_debug (c->mfx.md2, "verify2");
    }

  rc=0;

  if (literals_seen > 1)
    {
      log_info (_("WARNING: multiple plaintexts seen\n"));

      if (!opt.flags.allow_multiple_messages)
        {
          write_status_text (STATUS_ERROR, "proc_pkt.plaintext 89_BAD_DATA");
          log_inc_errorcount ();
          rc = gpg_error (GPG_ERR_UNEXPECTED);
        }
    }

  if (!rc)
    {
      /* It we are in --verify mode, we do not want to output the
       * signed text.  However, if --output is also used we do what
       * has been requested and write out the signed data.  */
      rc = handle_plaintext (pt, &c->mfx,
                             (opt.outfp || opt.outfile)? 0 :  c->sigs_only,
                             clearsig);
      if (gpg_err_code (rc) == GPG_ERR_EACCES && !c->sigs_only)
        {
          /* Can't write output but we hash it anyway to check the
             signature. */
          rc = handle_plaintext( pt, &c->mfx, 1, clearsig );
        }
    }

  if (rc)
    log_error ("handle plaintext failed: %s\n", gpg_strerror (rc));

  free_packet (pkt, NULL);
  c->last_was_session_key = 0;

  /* We add a marker control packet instead of the plaintext packet.
   * This is so that we can later detect invalid packet sequences.  */
  n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK, NULL, 0));
  if (c->list)
    add_kbnode (c->list, n);
  else
    c->list = n;
}


static int
proc_compressed_cb (iobuf_t a, void *info)
{
  if ( ((CTX)info)->signed_data.used
       && ((CTX)info)->signed_data.data_fd != -1)
    return proc_signature_packets_by_fd (((CTX)info)->ctrl, info, a,
                                         ((CTX)info)->signed_data.data_fd);
  else
    return proc_signature_packets (((CTX)info)->ctrl, info, a,
                                   ((CTX)info)->signed_data.data_names,
                                   ((CTX)info)->sigfilename );
}


static int
proc_encrypt_cb (iobuf_t a, void *info )
{
  CTX c = info;
  return proc_encryption_packets (c->ctrl, info, a );
}


static int
proc_compressed (CTX c, PACKET *pkt)
{
  PKT_compressed *zd = pkt->pkt.compressed;
  int rc;

  /*printf("zip: compressed data packet\n");*/
  if (c->sigs_only)
    rc = handle_compressed (c->ctrl, c, zd, proc_compressed_cb, c);
  else if( c->encrypt_only )
    rc = handle_compressed (c->ctrl, c, zd, proc_encrypt_cb, c);
  else
    rc = handle_compressed (c->ctrl, c, zd, NULL, NULL);

  if (gpg_err_code (rc) == GPG_ERR_BAD_DATA)
    {
      if  (!c->any.uncompress_failed)
        {
          CTX cc;

          for (cc=c; cc; cc = cc->anchor)
            cc->any.uncompress_failed = 1;
          log_error ("uncompressing failed: %s\n", gpg_strerror (rc));
        }
    }
  else if (rc)
    log_error ("uncompressing failed: %s\n", gpg_strerror (rc));

  free_packet (pkt, NULL);
  c->last_was_session_key = 0;
  return rc;
}


/*
 * Check the signature.  If R_PK is not NULL a copy of the public key
 * used to verify the signature will be stored there, or NULL if not
 * found.  If FORCED_PK is not NULL, this public key is used to verify
 * _data signatures_ and no key lookup is done.  Returns: 0 = valid
 * signature or an error code
 */
static int
do_check_sig (CTX c, kbnode_t node,
              PKT_public_key *forced_pk, int *is_selfsig,
	      int *is_expkey, int *is_revkey, PKT_public_key **r_pk)
{
  PKT_signature *sig;
  gcry_md_hd_t md = NULL;
  gcry_md_hd_t md2 = NULL;
  gcry_md_hd_t md_good = NULL;
  int algo, rc;

  if (r_pk)
    *r_pk = NULL;

  log_assert (node->pkt->pkttype == PKT_SIGNATURE);
  if (is_selfsig)
    *is_selfsig = 0;
  sig = node->pkt->pkt.signature;

  algo = sig->digest_algo;
  rc = openpgp_md_test_algo (algo);
  if (rc)
    return rc;

  if (sig->sig_class == 0x00)
    {
      if (c->mfx.md)
        {
          if (gcry_md_copy (&md, c->mfx.md ))
            BUG ();
        }
      else /* detached signature */
        {
          /* check_signature() will enable the md. */
          if (gcry_md_open (&md, 0, 0 ))
            BUG ();
        }
    }
  else if (sig->sig_class == 0x01)
    {
      /* How do we know that we have to hash the (already hashed) text
         in canonical mode ??? (calculating both modes???) */
      if (c->mfx.md)
        {
          if (gcry_md_copy (&md, c->mfx.md ))
            BUG ();
          if (c->mfx.md2 && gcry_md_copy (&md2, c->mfx.md2))
            BUG ();
	}
      else /* detached signature */
        {
          log_debug ("Do we really need this here?");
          /* check_signature() will enable the md*/
          if (gcry_md_open (&md, 0, 0 ))
            BUG ();
          if (gcry_md_open (&md2, 0, 0 ))
            BUG ();
	}
    }
  else if ((sig->sig_class&~3) == 0x10
           ||   sig->sig_class == 0x18
           ||   sig->sig_class == 0x1f
	   ||   sig->sig_class == 0x20
	   ||   sig->sig_class == 0x28
           ||   sig->sig_class == 0x30)
    {
      if (c->list->pkt->pkttype == PKT_PUBLIC_KEY
          || c->list->pkt->pkttype == PKT_PUBLIC_SUBKEY)
        {
          return check_key_signature (c->ctrl, c->list, node, is_selfsig);
	}
      else if (sig->sig_class == 0x20)
        {
          log_error (_("standalone revocation - "
                       "use \"gpg --import\" to apply\n"));
          return GPG_ERR_NOT_PROCESSED;
	}
      else
        {
          log_error ("invalid root packet for sigclass %02x\n", sig->sig_class);
          return GPG_ERR_SIG_CLASS;
	}
    }
  else
    return GPG_ERR_SIG_CLASS;

  /* We only get here if we are checking the signature of a binary
     (0x00) or text document (0x01).  */
  rc = check_signature2 (c->ctrl, sig, md,
                         forced_pk,
                         NULL, is_expkey, is_revkey, r_pk);
  if (! rc)
    md_good = md;
  else if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE && md2)
    {
      PKT_public_key *pk2;

      rc = check_signature2 (c->ctrl, sig, md2,
                             forced_pk,
                             NULL, is_expkey, is_revkey,
                             r_pk? &pk2 : NULL);
      if (!rc)
        {
          md_good = md2;
          if (r_pk)
            {
              free_public_key (*r_pk);
              *r_pk = pk2;
            }
        }
    }

  if (md_good)
    {
      unsigned char *buffer = gcry_md_read (md_good, sig->digest_algo);
      sig->digest_len = gcry_md_get_algo_dlen (map_md_openpgp_to_gcry (algo));
      memcpy (sig->digest, buffer, sig->digest_len);
    }

  gcry_md_close (md);
  gcry_md_close (md2);

  return rc;
}


static void
print_userid (PACKET *pkt)
{
  if (!pkt)
    BUG();

  if (pkt->pkttype != PKT_USER_ID)
    {
      es_printf ("ERROR: unexpected packet type %d", pkt->pkttype );
      return;
    }
  if (opt.with_colons)
    {
      if (pkt->pkt.user_id->attrib_data)
        es_printf("%u %lu",
                  pkt->pkt.user_id->numattribs,
                  pkt->pkt.user_id->attrib_len);
      else
        es_write_sanitized (es_stdout, pkt->pkt.user_id->name,
                            pkt->pkt.user_id->len, ":", NULL);
    }
  else
    print_utf8_buffer (es_stdout, pkt->pkt.user_id->name,
                       pkt->pkt.user_id->len );
}


/*
 * List the keyblock in a user friendly way
 */
static void
list_node (CTX c, kbnode_t node)
{
  if (!node)
    ;
  else if (node->pkt->pkttype == PKT_PUBLIC_KEY
           || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
    {
      PKT_public_key *pk = node->pkt->pkt.public_key;

      if (opt.with_colons)
        {
          u32 keyid[2];

          keyid_from_pk( pk, keyid );
          if (pk->flags.primary)
            c->trustletter = (opt.fast_list_mode
                              ? 0
                              : get_validity_info
                                  (c->ctrl,
                                   node->pkt->pkttype == PKT_PUBLIC_KEY
                                   ? node : NULL,
                                   pk, NULL));
          es_printf ("%s:", pk->flags.primary? "pub":"sub" );
          if (c->trustletter)
            es_putc (c->trustletter, es_stdout);
          es_printf (":%u:%d:%08lX%08lX:%s:%s::",
                     nbits_from_pk( pk ),
                     pk->pubkey_algo,
                     (ulong)keyid[0],(ulong)keyid[1],
                     colon_datestr_from_pk( pk ),
                     colon_strtime (pk->expiredate) );
          if (pk->flags.primary && !opt.fast_list_mode)
            es_putc (get_ownertrust_info (c->ctrl, pk, 1), es_stdout);
          es_putc (':', es_stdout);
          es_putc ('\n', es_stdout);
        }
      else
        {
          print_key_line (c->ctrl, es_stdout, pk, 0);
        }

      if (opt.keyid_format == KF_NONE && !opt.with_colons)
        ; /* Already printed.  */
      else if ((pk->flags.primary && opt.fingerprint) || opt.fingerprint > 1)
        print_fingerprint (c->ctrl, NULL, pk, 0);

      if (pk->flags.primary)
        {
          int kl = opt.keyid_format == KF_NONE? 0 : keystrlen ();

          /* Now list all userids with their signatures. */
          for (node = node->next; node; node = node->next)
            {
              if (node->pkt->pkttype == PKT_SIGNATURE)
                {
                  list_node (c,  node );
                }
              else if (node->pkt->pkttype == PKT_USER_ID)
                {
                  if (opt.with_colons)
                    es_printf ("%s:::::::::",
                               node->pkt->pkt.user_id->attrib_data?"uat":"uid");
                  else
                    es_printf ("uid%*s",
                               kl + (opt.legacy_list_mode? 9:11),
                               "" );
                  print_userid (node->pkt);
                  if (opt.with_colons)
                    es_putc (':', es_stdout);
                  es_putc ('\n', es_stdout);
		}
              else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
                {
                  list_node(c,  node );
                }
            }
        }
    }
  else if (node->pkt->pkttype == PKT_SECRET_KEY
           || node->pkt->pkttype == PKT_SECRET_SUBKEY)
    {

      log_debug ("FIXME: No way to print secret key packets here\n");
      /* fixme: We may use a function to turn a secret key packet into
         a public key one and use that here.  */
    }
  else if (node->pkt->pkttype == PKT_SIGNATURE)
    {
      PKT_signature *sig = node->pkt->pkt.signature;
      int is_selfsig = 0;
      int rc2 = 0;
      size_t n;
      char *p;
      int sigrc = ' ';

      if (!opt.verbose)
        return;

      if (sig->sig_class == 0x20 || sig->sig_class == 0x30)
        es_fputs ("rev", es_stdout);
      else
        es_fputs ("sig", es_stdout);
      if (opt.check_sigs)
        {
          fflush (stdout);
          rc2 = do_check_sig (c, node, NULL, &is_selfsig, NULL, NULL, NULL);
          switch (gpg_err_code (rc2))
            {
            case 0:		          sigrc = '!'; break;
            case GPG_ERR_BAD_SIGNATURE:   sigrc = '-'; break;
            case GPG_ERR_NO_PUBKEY:
            case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break;
            default:		          sigrc = '%'; break;
	    }
	}
      else /* Check whether this is a self signature.  */
        {
          u32 keyid[2];

          if (c->list->pkt->pkttype == PKT_PUBLIC_KEY
              || c->list->pkt->pkttype == PKT_SECRET_KEY )
            {
              keyid_from_pk (c->list->pkt->pkt.public_key, keyid);

              if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1])
                is_selfsig = 1;
            }
	}

      if (opt.with_colons)
        {
          es_putc (':', es_stdout);
          if (sigrc != ' ')
            es_putc (sigrc, es_stdout);
          es_printf ("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo,
                     (ulong)sig->keyid[0], (ulong)sig->keyid[1],
                     colon_datestr_from_sig (sig),
                     colon_expirestr_from_sig (sig));

          if (sig->trust_depth || sig->trust_value)
            es_printf ("%d %d",sig->trust_depth,sig->trust_value);
          es_putc (':', es_stdout);

          if (sig->trust_regexp)
            es_write_sanitized (es_stdout, sig->trust_regexp,
                                strlen (sig->trust_regexp), ":", NULL);
          es_putc (':', es_stdout);
	}
      else
        es_printf ("%c       %s %s   ",
                   sigrc, keystr (sig->keyid), datestr_from_sig(sig));
      if (sigrc == '%')
        es_printf ("[%s] ", gpg_strerror (rc2) );
      else if (sigrc == '?')
        ;
      else if (is_selfsig)
        {
          if (opt.with_colons)
            es_putc (':', es_stdout);
          es_fputs (sig->sig_class == 0x18? "[keybind]":"[selfsig]", es_stdout);
          if (opt.with_colons)
            es_putc (':', es_stdout);
	}
      else if (!opt.fast_list_mode)
        {
          p = get_user_id (c->ctrl, sig->keyid, &n, NULL);
          es_write_sanitized (es_stdout, p, n,
                              opt.with_colons?":":NULL, NULL );
          xfree (p);
	}
      if (opt.with_colons)
        es_printf (":%02x%c:", sig->sig_class, sig->flags.exportable?'x':'l');
      es_putc ('\n', es_stdout);
    }
  else
    log_error ("invalid node with packet of type %d\n", node->pkt->pkttype);
}


int
proc_packets (ctrl_t ctrl, void *anchor, iobuf_t a )
{
  int rc;
  CTX c = xmalloc_clear (sizeof *c);

  c->ctrl = ctrl;
  c->anchor = anchor;
  rc = do_proc_packets (ctrl, c, a);
  xfree (c);

  return rc;
}


int
proc_signature_packets (ctrl_t ctrl, void *anchor, iobuf_t a,
			strlist_t signedfiles, const char *sigfilename )
{
  CTX c = xmalloc_clear (sizeof *c);
  int rc;

  c->ctrl = ctrl;
  c->anchor = anchor;
  c->sigs_only = 1;

  c->signed_data.data_fd = -1;
  c->signed_data.data_names = signedfiles;
  c->signed_data.used = !!signedfiles;

  c->sigfilename = sigfilename;
  rc = do_proc_packets (ctrl, c, a);

  /* If we have not encountered any signature we print an error
     messages, send a NODATA status back and return an error code.
     Using log_error is required because verify_files does not check
     error codes for each file but we want to terminate the process
     with an error. */
  if (!rc && !c->any.sig_seen)
    {
      write_status_text (STATUS_NODATA, "4");
      log_error (_("no signature found\n"));
      rc = GPG_ERR_NO_DATA;
    }

  /* Propagate the signature seen flag upward. Do this only on success
     so that we won't issue the nodata status several times.  */
  if (!rc && c->anchor && c->any.sig_seen)
    c->anchor->any.sig_seen = 1;

  xfree (c);
  return rc;
}


int
proc_signature_packets_by_fd (ctrl_t ctrl,
                              void *anchor, iobuf_t a, int signed_data_fd )
{
  int rc;
  CTX c;

  c = xtrycalloc (1, sizeof *c);
  if (!c)
    return gpg_error_from_syserror ();

  c->ctrl = ctrl;
  c->anchor = anchor;
  c->sigs_only = 1;

  c->signed_data.data_fd = signed_data_fd;
  c->signed_data.data_names = NULL;
  c->signed_data.used = (signed_data_fd != -1);

  rc = do_proc_packets (ctrl, c, a);

  /* If we have not encountered any signature we print an error
     messages, send a NODATA status back and return an error code.
     Using log_error is required because verify_files does not check
     error codes for each file but we want to terminate the process
     with an error. */
  if (!rc && !c->any.sig_seen)
    {
      write_status_text (STATUS_NODATA, "4");
      log_error (_("no signature found\n"));
      rc = gpg_error (GPG_ERR_NO_DATA);
    }

  /* Propagate the signature seen flag upward. Do this only on success
     so that we won't issue the nodata status several times. */
  if (!rc && c->anchor && c->any.sig_seen)
    c->anchor->any.sig_seen = 1;

  xfree ( c );
  return rc;
}


int
proc_encryption_packets (ctrl_t ctrl, void *anchor, iobuf_t a )
{
  CTX c = xmalloc_clear (sizeof *c);
  int rc;

  c->ctrl = ctrl;
  c->anchor = anchor;
  c->encrypt_only = 1;
  rc = do_proc_packets (ctrl, c, a);
  xfree (c);
  return rc;
}


static int
check_nesting (CTX c)
{
  int level;

  for (level=0; c; c = c->anchor)
    level++;

  if (level > MAX_NESTING_DEPTH)
    {
      log_error ("input data with too deeply nested packets\n");
      write_status_text (STATUS_UNEXPECTED, "1");
      return GPG_ERR_BAD_DATA;
    }

  return 0;
}


static int
do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a)
{
  PACKET *pkt;
  struct parse_packet_ctx_s parsectx;
  int rc = 0;
  int any_data = 0;
  int newpkt;

  rc = check_nesting (c);
  if (rc)
    return rc;

  pkt = xmalloc( sizeof *pkt );
  c->iobuf = a;
  init_packet(pkt);
  init_parse_packet (&parsectx, a);
  while ((rc=parse_packet (&parsectx, pkt)) != -1)
    {
      any_data = 1;
      if (rc)
        {
          free_packet (pkt, &parsectx);
          /* Stop processing when an invalid packet has been encountered
           * but don't do so when we are doing a --list-packets.  */
          if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
              && opt.list_packets == 0)
            break;
          continue;
	}
      newpkt = -1;
      if (opt.list_packets)
        {
          switch (pkt->pkttype)
            {
            case PKT_PUBKEY_ENC:    proc_pubkey_enc (ctrl, c, pkt); break;
            case PKT_SYMKEY_ENC:    proc_symkey_enc (c, pkt); break;
            case PKT_ENCRYPTED:
            case PKT_ENCRYPTED_MDC:
            case PKT_ENCRYPTED_AEAD:proc_encrypted (c, pkt); break;
            case PKT_COMPRESSED:    rc = proc_compressed (c, pkt); break;
            default: newpkt = 0; break;
	    }
	}
      else if (c->sigs_only)
        {
          switch (pkt->pkttype)
            {
            case PKT_PUBLIC_KEY:
            case PKT_SECRET_KEY:
            case PKT_USER_ID:
            case PKT_SYMKEY_ENC:
            case PKT_PUBKEY_ENC:
            case PKT_ENCRYPTED:
            case PKT_ENCRYPTED_MDC:
            case PKT_ENCRYPTED_AEAD:
              write_status_text( STATUS_UNEXPECTED, "0" );
              rc = GPG_ERR_UNEXPECTED;
              goto leave;

            case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
            case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
            case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
            case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
            case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break;
            default: newpkt = 0; break;
	    }
	}
      else if (c->encrypt_only)
        {
          switch (pkt->pkttype)
            {
            case PKT_PUBLIC_KEY:
            case PKT_SECRET_KEY:
            case PKT_USER_ID:
              write_status_text (STATUS_UNEXPECTED, "0");
              rc = GPG_ERR_UNEXPECTED;
              goto leave;

            case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
            case PKT_SYMKEY_ENC:  proc_symkey_enc (c, pkt); break;
            case PKT_PUBKEY_ENC:  proc_pubkey_enc (ctrl, c, pkt); break;
            case PKT_ENCRYPTED:
            case PKT_ENCRYPTED_MDC:
            case PKT_ENCRYPTED_AEAD: proc_encrypted (c, pkt); break;
            case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
            case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
            case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
            case PKT_GPG_CONTROL: newpkt = add_gpg_control (c, pkt); break;
            default: newpkt = 0; break;
	    }
	}
      else
        {
          switch (pkt->pkttype)
            {
            case PKT_PUBLIC_KEY:
            case PKT_SECRET_KEY:
              release_list (c);
              c->list = new_kbnode (pkt);
              newpkt = 1;
              break;
            case PKT_PUBLIC_SUBKEY:
            case PKT_SECRET_SUBKEY:
              newpkt = add_subkey (c, pkt);
              break;
            case PKT_USER_ID:     newpkt = add_user_id (c, pkt); break;
            case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
            case PKT_PUBKEY_ENC:  proc_pubkey_enc (ctrl, c, pkt); break;
            case PKT_SYMKEY_ENC:  proc_symkey_enc (c, pkt); break;
            case PKT_ENCRYPTED:
            case PKT_ENCRYPTED_MDC:
            case PKT_ENCRYPTED_AEAD: proc_encrypted (c, pkt); break;
            case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
            case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
            case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
            case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
            case PKT_RING_TRUST:  newpkt = add_ring_trust (c, pkt); break;
            default: newpkt = 0; break;
	    }
	}

      if (rc)
        goto leave;

      /* This is a very ugly construct and frankly, I don't remember why
       * I used it.  Adding the MDC check here is a hack.
       * The right solution is to initiate another context for encrypted
       * packet and not to reuse the current one ...  It works right
       * when there is a compression packet between which adds just
       * an extra layer.
       * Hmmm: Rewrite this whole module here??
       */
      if (pkt->pkttype != PKT_SIGNATURE && pkt->pkttype != PKT_MDC)
        c->any.data = (pkt->pkttype == PKT_PLAINTEXT);

      if (newpkt == -1)
        ;
      else if (newpkt)
        {
          pkt = xmalloc (sizeof *pkt);
          init_packet (pkt);
	}
      else
        free_packet (pkt, &parsectx);
    }

  if (rc == GPG_ERR_INV_PACKET)
    write_status_text (STATUS_NODATA, "3");

  if (any_data)
    rc = 0;
  else if (rc == -1)
    write_status_text (STATUS_NODATA, "2");


 leave:
  release_list (c);
  xfree(c->dek);
  free_packet (pkt, &parsectx);
  deinit_parse_packet (&parsectx);
  xfree (pkt);
  free_md_filter_context (&c->mfx);
  return rc;
}


/* Helper for pka_uri_from_sig to parse the to-be-verified address out
   of the notation data. */
static pka_info_t *
get_pka_address (PKT_signature *sig)
{
  pka_info_t *pka = NULL;
  struct notation *nd,*notation;

  notation=sig_to_notation(sig);

  for(nd=notation;nd;nd=nd->next)
    {
      if(strcmp(nd->name,"pka-address@gnupg.org")!=0)
        continue; /* Not the notation we want. */

      /* For now we only use the first valid PKA notation. In future
	 we might want to keep additional PKA notations in a linked
	 list. */
      if (is_valid_mailbox (nd->value))
	{
	  pka = xmalloc (sizeof *pka + strlen(nd->value));
	  pka->valid = 0;
	  pka->checked = 0;
	  pka->uri = NULL;
	  strcpy (pka->email, nd->value);
	  break;
	}
    }

  free_notation(notation);

  return pka;
}


/* Return the URI from a DNS PKA record.  If this record has already
   be retrieved for the signature we merely return it; if not we go
   out and try to get that DNS record. */
static const char *
pka_uri_from_sig (CTX c, PKT_signature *sig)
{
  if (!sig->flags.pka_tried)
    {
      log_assert (!sig->pka_info);
      sig->flags.pka_tried = 1;
      sig->pka_info = get_pka_address (sig);
      if (sig->pka_info)
        {
          char *url;
          unsigned char *fpr;
          size_t fprlen;

          if (!gpg_dirmngr_get_pka (c->ctrl, sig->pka_info->email,
                                    &fpr, &fprlen, &url))
            {
              if (fpr && fprlen == sizeof sig->pka_info->fpr)
                {
                  memcpy (sig->pka_info->fpr, fpr, fprlen);
                  if (url)
                    {
                      sig->pka_info->valid = 1;
                      if (!*url)
                        xfree (url);
                      else
                        sig->pka_info->uri = url;
                      url = NULL;
                    }
                }
              xfree (fpr);
              xfree (url);
            }
        }
    }
  return sig->pka_info? sig->pka_info->uri : NULL;
}


/* Return true if the AKL has the WKD method specified.  */
static int
akl_has_wkd_method (void)
{
  struct akl *akl;

  for (akl = opt.auto_key_locate; akl; akl = akl->next)
    if (akl->type == AKL_WKD)
      return 1;
  return 0;
}


/* Return the ISSUER fingerprint buffer and its lenbgth at R_LEN.
 * Returns NULL if not available.  The returned buffer is valid as
 * long as SIG is not modified.  */
const byte *
issuer_fpr_raw (PKT_signature *sig, size_t *r_len)
{
  const byte *p;
  size_t n;

  p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_ISSUER_FPR, &n);
  if (p && n == 21 && p[0] == 4)
    {
      *r_len = n - 1;
      return p+1;
    }
  *r_len = 0;
  return NULL;
}


/* Return the ISSUER fingerprint string in human readable format if
 * available.  Caller must release the string.  */
/* FIXME: Move to another file.  */
char *
issuer_fpr_string (PKT_signature *sig)
{
  const byte *p;
  size_t n;

  p = issuer_fpr_raw (sig, &n);
  return p? bin2hex (p, n, NULL) : NULL;
}


static void
print_good_bad_signature (int statno, const char *keyid_str, kbnode_t un,
                          PKT_signature *sig, int rc)
{
  char *p;

  write_status_text_and_buffer (statno, keyid_str,
                                un? un->pkt->pkt.user_id->name:"[?]",
                                un? un->pkt->pkt.user_id->len:3,
                                -1);

  if (un)
    p = utf8_to_native (un->pkt->pkt.user_id->name,
                        un->pkt->pkt.user_id->len, 0);
  else
    p = xstrdup ("[?]");

  if (rc)
    log_info (_("BAD signature from \"%s\""), p);
  else if (sig->flags.expired)
    log_info (_("Expired signature from \"%s\""), p);
  else
    log_info (_("Good signature from \"%s\""), p);

  xfree (p);
}


static int
check_sig_and_print (CTX c, kbnode_t node)
{
  PKT_signature *sig = node->pkt->pkt.signature;
  const char *astr;
  int rc;
  int is_expkey = 0;
  int is_revkey = 0;
  char *issuer_fpr = NULL;
  PKT_public_key *pk = NULL;  /* The public key for the signature or NULL. */
  kbnode_t included_keyblock = NULL;

  if (opt.skip_verify)
    {
      log_info(_("signature verification suppressed\n"));
      return 0;
    }

  /* Check that the message composition is valid.
   *
   * Per RFC-2440bis (-15) allowed:
   *
   * S{1,n}           -- detached signature.
   * S{1,n} P         -- old style PGP2 signature
   * O{1,n} P S{1,n}  -- standard OpenPGP signature.
   * C P S{1,n}       -- cleartext signature.
   *
   *
   *      O = One-Pass Signature packet.
   *      S = Signature packet.
   *      P = OpenPGP Message packet (Encrypted | Compressed | Literal)
   *             (Note that the current rfc2440bis draft also allows
   *              for a signed message but that does not work as it
   *              introduces ambiguities.)
   *          We keep track of these packages using the marker packet
   *          CTRLPKT_PLAINTEXT_MARK.
   *      C = Marker packet for cleartext signatures.
   *
   * We reject all other messages.
   *
   * Actually we are calling this too often, i.e. for verification of
   * each message but better have some duplicate work than to silently
   * introduce a bug here.
   */
  {
    kbnode_t n;
    int n_onepass, n_sig;

/*     log_debug ("checking signature packet composition\n"); */
/*     dump_kbnode (c->list); */

    n = c->list;
    log_assert (n);
    if ( n->pkt->pkttype == PKT_SIGNATURE )
      {
        /* This is either "S{1,n}" case (detached signature) or
           "S{1,n} P" (old style PGP2 signature). */
        for (n = n->next; n; n = n->next)
          if (n->pkt->pkttype != PKT_SIGNATURE)
            break;
        if (!n)
          ; /* Okay, this is a detached signature.  */
        else if (n->pkt->pkttype == PKT_GPG_CONTROL
                 && (n->pkt->pkt.gpg_control->control
                     == CTRLPKT_PLAINTEXT_MARK) )
          {
            if (n->next)
              goto ambiguous;  /* We only allow one P packet. */
          }
        else
          goto ambiguous;
      }
    else if (n->pkt->pkttype == PKT_ONEPASS_SIG)
      {
        /* This is the "O{1,n} P S{1,n}" case (standard signature). */
        for (n_onepass=1, n = n->next;
             n && n->pkt->pkttype == PKT_ONEPASS_SIG; n = n->next)
          n_onepass++;
        if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
                    && (n->pkt->pkt.gpg_control->control
                        == CTRLPKT_PLAINTEXT_MARK)))
          goto ambiguous;
        for (n_sig=0, n = n->next;
             n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
          n_sig++;
        if (!n_sig)
          goto ambiguous;

	/* If we wanted to disallow multiple sig verification, we'd do
	   something like this:

	   if (n && !opt.allow_multisig_verification)
             goto ambiguous;

	   However, now that we have --allow-multiple-messages, this
	   can stay allowable as we can't get here unless multiple
	   messages (i.e. multiple literals) are allowed. */

        if (n_onepass != n_sig)
          {
            log_info ("number of one-pass packets does not match "
                      "number of signature packets\n");
            goto ambiguous;
          }
      }
    else if (n->pkt->pkttype == PKT_GPG_CONTROL
             && n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START )
      {
        /* This is the "C P S{1,n}" case (clear text signature). */
        n = n->next;
        if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
                    && (n->pkt->pkt.gpg_control->control
                        == CTRLPKT_PLAINTEXT_MARK)))
          goto ambiguous;
        for (n_sig=0, n = n->next;
             n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
          n_sig++;
        if (n || !n_sig)
          goto ambiguous;
      }
    else
      {
      ambiguous:
        log_error(_("can't handle this ambiguous signature data\n"));
        return 0;
      }
  }

  if (sig->signers_uid)
    write_status_buffer (STATUS_NEWSIG,
                         sig->signers_uid, strlen (sig->signers_uid), 0);
  else
    write_status_text (STATUS_NEWSIG, NULL);

  astr = openpgp_pk_algo_name ( sig->pubkey_algo );
  issuer_fpr = issuer_fpr_string (sig);

  if (issuer_fpr)
    {
      log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
      log_info (_("               using %s key %s\n"),
                astr? astr: "?", issuer_fpr);

    }
  else if (!keystrlen () || keystrlen () > 8)
    {
      log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
      log_info (_("               using %s key %s\n"),
                astr? astr: "?", keystr(sig->keyid));
    }
  else /* Legacy format.  */
    log_info (_("Signature made %s using %s key ID %s\n"),
              asctimestamp(sig->timestamp), astr? astr: "?",
              keystr(sig->keyid));

  /* In verbose mode print the signers UID.  */
  if (sig->signers_uid)
    log_info (_("               issuer \"%s\"\n"), sig->signers_uid);

  rc = do_check_sig (c, node, NULL, NULL, &is_expkey, &is_revkey, &pk);

  /* If the key is not found but the signature includes a key block we
   * use that key block for verification and on success import it.  */
  if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
      && sig->flags.key_block
      && opt.flags.auto_key_import)
    {
      PKT_public_key *included_pk;
      const byte *kblock;
      size_t kblock_len;

      included_pk = xcalloc (1, sizeof *included_pk);
      kblock = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_BLOCK, &kblock_len);
      if (kblock && kblock_len > 1
          && !get_pubkey_from_buffer (c->ctrl, included_pk,
                                      kblock+1, kblock_len-1,
                                      sig->keyid, &included_keyblock))
        {
          rc = do_check_sig (c, node, included_pk,
                             NULL, &is_expkey, &is_revkey, &pk);
          if (!rc)
            {
              /* The keyblock has been verified, we now import it.  */
              rc = import_included_key_block (c->ctrl, included_keyblock);
            }

        }
      free_public_key (included_pk);
    }

  /* If the key isn't found, check for a preferred keyserver.  Note
   * that this is only done if honor-keyserver-url has been set.  We
   * test for this in the loop so that we can show info about the
   * preferred keyservers.  */
  if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
      && sig->flags.pref_ks)
    {
      const byte *p;
      int seq = 0;
      size_t n;
      int any_pref_ks = 0;

      while ((p=enum_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS,&n,&seq,NULL)))
        {
          /* According to my favorite copy editor, in English grammar,
             you say "at" if the key is located on a web page, but
             "from" if it is located on a keyserver.  I'm not going to
             even try to make two strings here :) */
          log_info(_("Key available at: ") );
          print_utf8_buffer (log_get_stream(), p, n);
          log_printf ("\n");
          any_pref_ks = 1;

          if ((opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
              && (opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL))
            {
              struct keyserver_spec *spec;

              spec = parse_preferred_keyserver (sig);
              if (spec)
                {
                  int res;

                  if (DBG_LOOKUP)
                    log_debug ("trying auto-key-retrieve method %s\n",
                               "Pref-KS");

                  free_public_key (pk);
                  pk = NULL;
                  glo_ctrl.in_auto_key_retrieve++;
                  res = keyserver_import_keyid (c->ctrl, sig->keyid,spec,
                                                KEYSERVER_IMPORT_FLAG_QUICK);
                  glo_ctrl.in_auto_key_retrieve--;
                  if (!res)
                    rc = do_check_sig (c, node, NULL,
                                       NULL, &is_expkey, &is_revkey, &pk);
                  else if (DBG_LOOKUP)
                    log_debug ("lookup via %s failed: %s\n", "Pref-KS",
                               gpg_strerror (res));
                  free_keyserver_spec (spec);

                  if (!rc)
                    break;
                }
            }
        }

      if (any_pref_ks
          && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
          && !(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL))
        log_info (_("Note: Use '%s' to make use of this info\n"),
                  "--keyserver-option honor-keyserver-url");
    }

  /* If the above methods didn't work, our next try is to retrieve the
   * key from the WKD.  This requires that WKD is in the AKL and the
   * Signer's UID is in the signature.  */
  if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
      && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)
      && !opt.flags.disable_signer_uid
      && akl_has_wkd_method ()
      && sig->signers_uid)
    {
      int res;

      if (DBG_LOOKUP)
        log_debug ("trying auto-key-retrieve method %s\n", "WKD");
      free_public_key (pk);
      pk = NULL;
      glo_ctrl.in_auto_key_retrieve++;
      res = keyserver_import_wkd (c->ctrl, sig->signers_uid,
                                  KEYSERVER_IMPORT_FLAG_QUICK, NULL, NULL);
      glo_ctrl.in_auto_key_retrieve--;
      /* Fixme: If the fingerprint is embedded in the signature,
       * compare it to the fingerprint of the returned key.  */
      if (!res)
        rc = do_check_sig (c, node, NULL, NULL, &is_expkey, &is_revkey, &pk);
      else if (DBG_LOOKUP)
        log_debug ("lookup via %s failed: %s\n", "WKD", gpg_strerror (res));
    }

  /* If the avove methods didn't work, our next try is to use the URI
   * from a DNS PKA record.  This is a legacy method which will
   * eventually be removed.  */
  if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
      && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)
      && (opt.keyserver_options.options & KEYSERVER_HONOR_PKA_RECORD))
    {
      const char *uri = pka_uri_from_sig (c, sig);

      if (uri)
        {
          /* FIXME: We might want to locate the key using the
             fingerprint instead of the keyid. */
          int res;
          struct keyserver_spec *spec;

          spec = parse_keyserver_uri (uri, 1);
          if (spec)
            {
              if (DBG_LOOKUP)
                log_debug ("trying auto-key-retrieve method %s\n", "PKA");

              free_public_key (pk);
              pk = NULL;
              glo_ctrl.in_auto_key_retrieve++;
              res = keyserver_import_keyid (c->ctrl, sig->keyid, spec, 1);
              glo_ctrl.in_auto_key_retrieve--;
              free_keyserver_spec (spec);
              if (!res)
                rc = do_check_sig (c, node, NULL,
                                   NULL, &is_expkey, &is_revkey, &pk);
              else if (DBG_LOOKUP)
                log_debug ("lookup via %s failed: %s\n", "PKA",
                           gpg_strerror (res));
            }
        }
    }

  /* If the above methods didn't work, our next try is to locate
   * the key via its fingerprint from a keyserver.  This requires
   * that the signers fingerprint is encoded in the signature.  */
  if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
      && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
      && keyserver_any_configured (c->ctrl))
    {
      int res;
      const byte *p;
      size_t n;

      p = issuer_fpr_raw (sig, &n);
      if (p)
        {
          /* v4 packet with a SHA-1 fingerprint.  */
          if (DBG_LOOKUP)
            log_debug ("trying auto-key-retrieve method %s\n", "KS");

          free_public_key (pk);
          pk = NULL;
          glo_ctrl.in_auto_key_retrieve++;
          res = keyserver_import_fprint (c->ctrl, p, n, opt.keyserver,
                                         KEYSERVER_IMPORT_FLAG_QUICK);
          glo_ctrl.in_auto_key_retrieve--;
          if (!res)
            rc = do_check_sig (c, node, NULL,
                               NULL, &is_expkey, &is_revkey, &pk);
          else if (DBG_LOOKUP)
            log_debug ("lookup via %s failed: %s\n", "KS", gpg_strerror (res));
        }
    }

  if (!rc || gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE)
    {
      kbnode_t un, keyblock;
      int count = 0;
      int statno;
      char keyid_str[50];
      PKT_public_key *mainpk = NULL;

      if (rc)
        statno = STATUS_BADSIG;
      else if (sig->flags.expired)
        statno = STATUS_EXPSIG;
      else if (is_expkey)
        statno = STATUS_EXPKEYSIG;
      else if(is_revkey)
        statno = STATUS_REVKEYSIG;
      else
        statno = STATUS_GOODSIG;

      /* FIXME: We should have the public key in PK and thus the
       * keyblock has already been fetched.  Thus we could use the
       * fingerprint or PK itself to lookup the entire keyblock.  That
       * would best be done with a cache.  */
      if (included_keyblock)
        {
          keyblock = included_keyblock;
          included_keyblock = NULL;
        }
      else
        keyblock = get_pubkeyblock_for_sig (c->ctrl, sig);

      snprintf (keyid_str, sizeof keyid_str, "%08lX%08lX [uncertain] ",
                (ulong)sig->keyid[0], (ulong)sig->keyid[1]);

      /* Find and print the primary user ID along with the
         "Good|Expired|Bad signature" line.  */
      for (un=keyblock; un; un = un->next)
        {
          int valid;

          if (un->pkt->pkttype==PKT_PUBLIC_KEY)
            {
              mainpk = un->pkt->pkt.public_key;
              continue;
            }
          if (un->pkt->pkttype != PKT_USER_ID)
            continue;
          if (!un->pkt->pkt.user_id->created)
            continue;
          if (un->pkt->pkt.user_id->flags.revoked)
            continue;
          if (un->pkt->pkt.user_id->flags.expired)
            continue;
          if (!un->pkt->pkt.user_id->flags.primary)
            continue;
          /* We want the textual primary user ID here */
          if (un->pkt->pkt.user_id->attrib_data)
            continue;

          log_assert (mainpk);

	  /* Since this is just informational, don't actually ask the
	     user to update any trust information.  (Note: we register
	     the signature later.)  Because print_good_bad_signature
	     does not print a LF we need to compute the validity
	     before calling that function.  */
          if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
            valid = get_validity (c->ctrl, keyblock, mainpk,
                                  un->pkt->pkt.user_id, NULL, 0);
          else
            valid = 0; /* Not used.  */

          keyid_str[17] = 0; /* cut off the "[uncertain]" part */

          print_good_bad_signature (statno, keyid_str, un, sig, rc);

          if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
            log_printf (" [%s]\n",trust_value_to_string(valid));
          else
            log_printf ("\n");

          count++;
	}

      log_assert (mainpk);

      /* In case we did not found a valid textual userid above
         we print the first user id packet or a "[?]" instead along
         with the "Good|Expired|Bad signature" line.  */
      if (!count)
        {
          /* Try for an invalid textual userid */
          for (un=keyblock; un; un = un->next)
            {
              if (un->pkt->pkttype == PKT_USER_ID
                  && !un->pkt->pkt.user_id->attrib_data)
                break;
            }

          /* Try for any userid at all */
          if (!un)
            {
              for (un=keyblock; un; un = un->next)
                {
                  if (un->pkt->pkttype == PKT_USER_ID)
                    break;
		}
	    }

          if (opt.trust_model==TM_ALWAYS || !un)
            keyid_str[17] = 0; /* cut off the "[uncertain]" part */

          print_good_bad_signature (statno, keyid_str, un, sig, rc);

          if (opt.trust_model != TM_ALWAYS && un)
            log_printf (" %s",_("[uncertain]") );
          log_printf ("\n");
	}

      /* If we have a good signature and already printed
       * the primary user ID, print all the other user IDs */
      if (count
          && !rc
          && !(opt.verify_options & VERIFY_SHOW_PRIMARY_UID_ONLY))
        {
          char *p;
          for( un=keyblock; un; un = un->next)
            {
              if (un->pkt->pkttype != PKT_USER_ID)
                continue;
              if ((un->pkt->pkt.user_id->flags.revoked
                   || un->pkt->pkt.user_id->flags.expired)
                  && !(opt.verify_options & VERIFY_SHOW_UNUSABLE_UIDS))
                continue;
              /* Skip textual primary user ids which we printed above. */
              if (un->pkt->pkt.user_id->flags.primary
                  && !un->pkt->pkt.user_id->attrib_data )
                continue;

              /* If this user id has attribute data, print that.  */
              if (un->pkt->pkt.user_id->attrib_data)
                {
                  dump_attribs (un->pkt->pkt.user_id, mainpk);

                  if (opt.verify_options&VERIFY_SHOW_PHOTOS)
                    show_photos (c->ctrl,
                                 un->pkt->pkt.user_id->attribs,
                                 un->pkt->pkt.user_id->numattribs,
                                 mainpk ,un->pkt->pkt.user_id);
                }

              p = utf8_to_native (un->pkt->pkt.user_id->name,
				  un->pkt->pkt.user_id->len, 0);
              log_info (_("                aka \"%s\""), p);
              xfree (p);

              if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
                {
                  const char *valid;

                  if (un->pkt->pkt.user_id->flags.revoked)
                    valid = _("revoked");
                  else if (un->pkt->pkt.user_id->flags.expired)
                    valid = _("expired");
                  else
		    /* Since this is just informational, don't
		       actually ask the user to update any trust
		       information.  */
                    valid = (trust_value_to_string
                             (get_validity (c->ctrl, keyblock, mainpk,
                                            un->pkt->pkt.user_id, NULL, 0)));
                  log_printf (" [%s]\n",valid);
                }
              else
                log_printf ("\n");
            }
	}

      /* For good signatures print notation data.  */
      if (!rc)
        {
          if ((opt.verify_options & VERIFY_SHOW_POLICY_URLS))
            show_policy_url (sig, 0, 1);
          else
            show_policy_url (sig, 0, 2);

          if ((opt.verify_options & VERIFY_SHOW_KEYSERVER_URLS))
            show_keyserver_url (sig, 0, 1);
          else
            show_keyserver_url (sig, 0, 2);

          if ((opt.verify_options & VERIFY_SHOW_NOTATIONS))
            show_notation
              (sig, 0, 1,
               (((opt.verify_options&VERIFY_SHOW_STD_NOTATIONS)?1:0)
                + ((opt.verify_options&VERIFY_SHOW_USER_NOTATIONS)?2:0)));
          else
            show_notation (sig, 0, 2, 0);
        }

      /* For good signatures print the VALIDSIG status line.  */
      if (!rc && is_status_enabled () && pk)
        {
          char pkhex[MAX_FINGERPRINT_LEN*2+1];
          char mainpkhex[MAX_FINGERPRINT_LEN*2+1];

          hexfingerprint (pk, pkhex, sizeof pkhex);
          hexfingerprint (mainpk, mainpkhex, sizeof mainpkhex);

          /* TODO: Replace the reserved '0' in the field below with
             bits for status flags (policy url, notation, etc.).  */
          write_status_printf (STATUS_VALIDSIG,
                               "%s %s %lu %lu %d 0 %d %d %02X %s",
                               pkhex,
                               strtimestamp (sig->timestamp),
                               (ulong)sig->timestamp,
                               (ulong)sig->expiredate,
                               sig->version, sig->pubkey_algo,
                               sig->digest_algo,
                               sig->sig_class,
                               mainpkhex);
	}

      /* Print compliance warning for Good signatures.  */
      if (!rc && pk && !opt.quiet
          && !gnupg_pk_is_compliant (opt.compliance, pk->pubkey_algo, 0,
                                     pk->pkey, nbits_from_pk (pk), NULL))
        {
          log_info (_("WARNING: This key is not suitable for signing"
                      " in %s mode\n"),
                    gnupg_compliance_option_string (opt.compliance));
        }

      /* For good signatures compute and print the trust information.
         Note that in the Tofu trust model this may ask the user on
         how to resolve a conflict.  */
      if (!rc)
        {
          if ((opt.verify_options & VERIFY_PKA_LOOKUPS))
            pka_uri_from_sig (c, sig); /* Make sure PKA info is available. */
          rc = check_signatures_trust (c->ctrl, sig);
        }

      /* Print extra information about the signature.  */
      if (sig->flags.expired)
        {
          log_info (_("Signature expired %s\n"), asctimestamp(sig->expiredate));
          rc = GPG_ERR_GENERAL; /* Need a better error here?  */
        }
      else if (sig->expiredate)
        log_info (_("Signature expires %s\n"), asctimestamp(sig->expiredate));

      if (opt.verbose)
        {
          char pkstrbuf[PUBKEY_STRING_SIZE];

          if (pk)
            pubkey_string (pk, pkstrbuf, sizeof pkstrbuf);
          else
            *pkstrbuf = 0;

          log_info (_("%s signature, digest algorithm %s%s%s\n"),
                    sig->sig_class==0x00?_("binary"):
                    sig->sig_class==0x01?_("textmode"):_("unknown"),
                    gcry_md_algo_name (sig->digest_algo),
                    *pkstrbuf?_(", key algorithm "):"", pkstrbuf);
        }

      /* Print final warnings.  */
      if (!rc && !c->signed_data.used)
        {
          /* Signature is basically good but we test whether the
             deprecated command
               gpg --verify FILE.sig
             was used instead of
               gpg --verify FILE.sig FILE
             to verify a detached signature.  If we figure out that a
             data file with a matching name exists, we print a warning.

             The problem is that the first form would also verify a
             standard signature.  This behavior could be used to
             create a made up .sig file for a tarball by creating a
             standard signature from a valid detached signature packet
             (for example from a signed git tag).  Then replace the
             sig file on the FTP server along with a changed tarball.
             Using the first form the verify command would correctly
             verify the signature but don't even consider the tarball.  */
          kbnode_t n;
          char *dfile;

          dfile = get_matching_datafile (c->sigfilename);
          if (dfile)
            {
              for (n = c->list; n; n = n->next)
                if (n->pkt->pkttype != PKT_SIGNATURE)
                  break;
              if (n)
                {
                  /* Not only signature packets in the tree thus this
                     is not a detached signature.  */
                  log_info (_("WARNING: not a detached signature; "
                              "file '%s' was NOT verified!\n"), dfile);
                }
              xfree (dfile);
            }
        }

      /* Compute compliance with CO_DE_VS.  */
      if (pk && is_status_enabled ()
          && gnupg_gcrypt_is_compliant (CO_DE_VS)
          && gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0, pk->pkey,
                                    nbits_from_pk (pk), NULL)
          && gnupg_digest_is_compliant (CO_DE_VS, sig->digest_algo))
        write_status_strings (STATUS_VERIFICATION_COMPLIANCE_MODE,
                              gnupg_status_compliance_flag (CO_DE_VS),
                              NULL);
      else if (opt.flags.require_compliance
               && opt.compliance == CO_DE_VS)
        {
          compliance_failure ();
          if (!rc)
            rc = gpg_error (GPG_ERR_FORBIDDEN);
        }


      free_public_key (pk);
      pk = NULL;
      release_kbnode( keyblock );
      if (rc)
        g10_errors_seen = 1;
      if (opt.batch && rc)
        g10_exit (1);
    }
  else
    {
      write_status_printf (STATUS_ERRSIG, "%08lX%08lX %d %d %02x %lu %d %s",
                           (ulong)sig->keyid[0], (ulong)sig->keyid[1],
                           sig->pubkey_algo, sig->digest_algo,
                           sig->sig_class, (ulong)sig->timestamp,
                           gpg_err_code (rc),
                           issuer_fpr? issuer_fpr:"-");
      if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
        {
          write_status_printf (STATUS_NO_PUBKEY, "%08lX%08lX",
                               (ulong)sig->keyid[0], (ulong)sig->keyid[1]);
	}
      if (gpg_err_code (rc) != GPG_ERR_NOT_PROCESSED)
        log_error (_("Can't check signature: %s\n"), gpg_strerror (rc));
    }

  free_public_key (pk);
  release_kbnode (included_keyblock);
  xfree (issuer_fpr);
  return rc;
}


/*
 * Process the tree which starts at node
 */
static void
proc_tree (CTX c, kbnode_t node)
{
  kbnode_t n1;
  int rc;

  if (opt.list_packets || opt.list_only)
    return;

  /* We must skip our special plaintext marker packets here because
     they may be the root packet.  These packets are only used in
     additional checks and skipping them here doesn't matter.  */
  while (node
         && node->pkt->pkttype == PKT_GPG_CONTROL
          && node->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK)
    {
      node = node->next;
    }
  if (!node)
    return;

  c->trustletter = ' ';
  if (node->pkt->pkttype == PKT_PUBLIC_KEY
      || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
    {
      merge_keys_and_selfsig (c->ctrl, node);
      list_node (c, node);
    }
  else if (node->pkt->pkttype == PKT_SECRET_KEY)
    {
      merge_keys_and_selfsig (c->ctrl, node);
      list_node (c, node);
    }
  else if (node->pkt->pkttype == PKT_ONEPASS_SIG)
    {
      /* Check all signatures.  */
      if (!c->any.data)
        {
          int use_textmode = 0;

          free_md_filter_context (&c->mfx);
          /* Prepare to create all requested message digests.  */
          rc = gcry_md_open (&c->mfx.md, 0, 0);
          if (rc)
            goto hash_err;

          /* Fixme: why looking for the signature packet and not the
             one-pass packet?  */
          for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
            gcry_md_enable (c->mfx.md, n1->pkt->pkt.signature->digest_algo);

          if (n1 && n1->pkt->pkt.onepass_sig->sig_class == 0x01)
            use_textmode = 1;

          /* Ask for file and hash it. */
          if (c->sigs_only)
            {
              if (c->signed_data.used && c->signed_data.data_fd != -1)
                rc = hash_datafile_by_fd (c->mfx.md, NULL,
                                          c->signed_data.data_fd,
                                          use_textmode);
              else
                rc = hash_datafiles (c->mfx.md, NULL,
                                     c->signed_data.data_names,
                                     c->sigfilename,
                                     use_textmode);
	    }
          else
            {
              rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
                                              iobuf_get_real_fname (c->iobuf),
                                              use_textmode);
	    }

        hash_err:
          if (rc)
            {
              log_error ("can't hash datafile: %s\n", gpg_strerror (rc));
              return;
	    }
	}
      else if (c->signed_data.used)
        {
          log_error (_("not a detached signature\n"));
          return;
        }

      for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
        check_sig_and_print (c, n1);

    }
  else if (node->pkt->pkttype == PKT_GPG_CONTROL
           && node->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START)
    {
      /* Clear text signed message.  */
      if (!c->any.data)
        {
          log_error ("cleartext signature without data\n");
          return;
        }
      else if (c->signed_data.used)
        {
          log_error (_("not a detached signature\n"));
          return;
        }

      for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE));)
        check_sig_and_print (c, n1);

    }
  else if (node->pkt->pkttype == PKT_SIGNATURE)
    {
      PKT_signature *sig = node->pkt->pkt.signature;
      int multiple_ok = 1;

      n1 = find_next_kbnode (node, PKT_SIGNATURE);
      if (n1)
        {
          byte class = sig->sig_class;
          byte hash  = sig->digest_algo;

          for (; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
            {
              /* We can't currently handle multiple signatures of
               * different classes (we'd pretty much have to run a
               * different hash context for each), but if they are all
               * the same and it is detached signature, we make an
               * exception.  Note that the old code also disallowed
               * multiple signatures if the digest algorithms are
               * different.  We softened this restriction only for
               * detached signatures, to be on the safe side. */
              if (n1->pkt->pkt.signature->sig_class != class
                  || (c->any.data
                      && n1->pkt->pkt.signature->digest_algo != hash))
                {
                  multiple_ok = 0;
                  log_info (_("WARNING: multiple signatures detected.  "
                              "Only the first will be checked.\n"));
                  break;
                }
            }
        }

      if (sig->sig_class != 0x00 && sig->sig_class != 0x01)
        {
          log_info(_("standalone signature of class 0x%02x\n"), sig->sig_class);
        }
      else if (!c->any.data)
        {
          /* Detached signature */
          free_md_filter_context (&c->mfx);
          rc = gcry_md_open (&c->mfx.md, sig->digest_algo, 0);
          if (rc)
            goto detached_hash_err;

          if (multiple_ok)
            {
              /* If we have and want to handle multiple signatures we
               * need to enable all hash algorithms for the context.  */
              for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE)); )
                if (!openpgp_md_test_algo (n1->pkt->pkt.signature->digest_algo))
                  gcry_md_enable (c->mfx.md,
                                  map_md_openpgp_to_gcry
                                  (n1->pkt->pkt.signature->digest_algo));
            }

          if (RFC2440 || RFC4880)
            ; /* Strict RFC mode.  */
          else if (sig->digest_algo == DIGEST_ALGO_SHA1
                   && sig->pubkey_algo == PUBKEY_ALGO_DSA
                   && sig->sig_class == 0x01)
            {
              /* Enable a workaround for a pgp5 bug when the detached
               * signature has been created in textmode.  Note that we
               * do not implement this for multiple signatures with
               * different hash algorithms. */
              rc = gcry_md_open (&c->mfx.md2, sig->digest_algo, 0);
              if (rc)
                goto detached_hash_err;
	    }

          /* Here we used to have another hack to work around a pgp
           * 2 bug: It worked by not using the textmode for detached
           * signatures; this would let the first signature check
           * (on md) fail but the second one (on md2), which adds an
           * extra CR would then have produced the "correct" hash.
           * This is very, very ugly hack but it may haved help in
           * some cases (and break others).
           *	 c->mfx.md2? 0 :(sig->sig_class == 0x01)
           */

          if (DBG_HASHING)
            {
              gcry_md_debug (c->mfx.md, "verify");
              if (c->mfx.md2)
                gcry_md_debug (c->mfx.md2, "verify2");
            }

          if (c->sigs_only)
            {
              if (c->signed_data.used && c->signed_data.data_fd != -1)
                rc = hash_datafile_by_fd (c->mfx.md, c->mfx.md2,
                                          c->signed_data.data_fd,
                                          (sig->sig_class == 0x01));
              else
                rc = hash_datafiles (c->mfx.md, c->mfx.md2,
                                     c->signed_data.data_names,
                                     c->sigfilename,
                                     (sig->sig_class == 0x01));
	    }
          else
            {
              rc = ask_for_detached_datafile (c->mfx.md, c->mfx.md2,
                                              iobuf_get_real_fname(c->iobuf),
                                              (sig->sig_class == 0x01));
	    }

        detached_hash_err:
          if (rc)
            {
              log_error ("can't hash datafile: %s\n", gpg_strerror (rc));
              return;
	    }
	}
      else if (c->signed_data.used)
        {
          log_error (_("not a detached signature\n"));
          return;
        }
      else if (!opt.quiet)
        log_info (_("old style (PGP 2.x) signature\n"));

      if (multiple_ok)
        {
          for (n1 = node; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
	    check_sig_and_print (c, n1);
        }
      else
        check_sig_and_print (c, node);

    }
  else
    {
      dump_kbnode (c->list);
      log_error ("invalid root packet detected in proc_tree()\n");
      dump_kbnode (node);
    }
}