1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
//! Packet parsing infrastructure.
//!
//! OpenPGP defines a binary representation suitable for storing and
//! communicating OpenPGP data structures (see [Section 3 ff. of RFC
//! 4880]).  Parsing is the process of interpreting the binary
//! representation.
//!
//!   [Section 3 ff. of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-3
//!
//! An OpenPGP stream represents a sequence of packets.  Some of the
//! packets contain other packets.  These so called containers include
//! encrypted data packets (the SED and [SEIP] packets), and
//! [compressed data] packets.  This structure results in a tree,
//! which is laid out in depth-first order.
//!
//!   [SEIP]: ../packet/enum.SEIP.html
//!   [compressed data]: ../packet/struct.CompressedData.html
//!
//! OpenPGP defines objects consisting of several packets with a
//! specific structure.  These objects are [`Message`]s, [`Cert`]s and
//! sequences of [`Cert`]s ("keyrings").  Verifying the structure of
//! these objects is also an act of parsing.
//!
//!   [`Message`]: ../struct.Message.html
//!   [`Cert`]: ../cert/struct.Cert.html
//!
//! This crate provides several interfaces to parse OpenPGP data.
//! They fall in roughly three categories:
//!
//!  - First, most data structures in this crate implement the
//!    [`Parse`] trait.  It provides a uniform interface to parse data
//!    from an [`io::Read`]er, a file identified by its [`Path`], or
//!    simply a byte slice.
//!
//!  - Second, there is a convenient interface to decrypt and/or
//!    verify OpenPGP messages in a streaming fashion.  Encrypted
//!    and/or signed data is read using the [`Parse`] interface, and
//!    decrypted and/or verified data can be read using [`io::Read`].
//!
//!  - Finally, we expose the low-level [`PacketParser`], allowing
//!    fine-grained control over the parsing.
//!
//!   [`Parse`]: trait.Parse.html
//!   [`io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
//!   [`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html
//!   [`PacketParser`]: struct.PacketParser.html
//!
//! The choice of interface depends on the specific use case.  In many
//! circumstances, OpenPGP data can not be trusted until it has been
//! authenticated.  Therefore, it has to be treated as attacker
//! controlled data, and it has to be treated with great care.  See
//! the section [Security Considerations] below.
//!
//!   [Security Considerations]: #security-considerations
//!
//! # Common Operations
//!
//!  - *Decrypt a message*: Use a [streaming `Decryptor`].
//!  - *Verify a message*: Use a [streaming `Verifier`].
//!  - *Verify a detached signature*: Use a [`DetachedVerifier`].
//!  - *Parse a [`Cert`]*: Use [`Cert`]'s [`Parse`] interface.
//!  - *Parse a keyring*: Use [`CertParser`]'s [`Parse`] interface.
//!  - *Parse an unstructured sequence of small packets from a trusted
//!     source*: Use [`PacketPile`]s [`Parse`] interface (e.g.
//!     [`PacketPile::from_file`]).
//!  - *Parse an unstructured sequence of packets*: Use the
//!    [`PacketPileParser`].
//!  - *Parse an unstructured sequence of packets with full control
//!    over the parser*: Use a [`PacketParser`].
//!  - *Customize the parser behavior even more*: Use a
//!    [`PacketParserBuilder`].
//!
//!   [`CertParser`]: ../cert/struct.CertParser.html
//!   [streaming `Decryptor`]: stream/struct.Decryptor.html
//!   [streaming `Verifier`]: stream/struct.Verifier.html
//!   [`DetachedVerifier`]: stream/struct.DetachedVerifier.html
//!   [`PacketPile`]: ../struct.PacketPile.html
//!   [`PacketPile::from_file`]: ../struct.PacketPile.html#method.from_file
//!   [`PacketPileParser`]: struct.PacketPileParser.html
//!   [`PacketParserBuilder`]: struct.PacketParserBuilder.html
//!
//! # Data Structures and Interfaces
//!
//! This crate provides several interfaces for parsing OpenPGP
//! streams, ordered from the most convenient but least flexible to
//! the least convenient but most flexible:
//!
//!   - The streaming [`Verifier`], [`DetachedVerifier`], and
//!     [`Decryptor`] are the most convenient way to parse OpenPGP
//!     messages.
//!
//!   - The [`PacketPile::from_file`] (and related methods) is the
//!     most convenient, but least flexible way to parse an arbitrary
//!     sequence of OpenPGP packets.  Whereas a [`PacketPileParser`]
//!     allows the caller to determine how to handle individual
//!     packets, the [`PacketPile::from_file`] parses the whole stream
//!     at once and returns a [`PacketPile`].
//!
//!   - The [`PacketPileParser`] abstraction builds on the
//!     [`PacketParser`] abstraction and provides a similar interface.
//!     However, after each iteration, the [`PacketPileParser`] adds the
//!     packet to a [`PacketPile`], which is returned once the packets are
//!     completely processed.
//!
//!     This interface should only be used if the caller actually
//!     wants a [`PacketPile`]; if the OpenPGP stream is parsed in place,
//!     then using a [`PacketParser`] is better.
//!
//!     This interface should only be used if the caller is certain
//!     that the parsed stream will fit in memory.
//!
//!   - The [`PacketParser`] abstraction produces one packet at a
//!     time.  What is done with those packets is completely up to the
//!     caller.
//!
//! The behavior of the [`PacketParser`] can be configured using a
//! [`PacketParserBuilder`].
//!
//!   [`Decryptor`]: stream/struct.Decryptor.html
//!   [`Verifier`]: stream/struct.Verifier.html
//!
//! # ASCII armored data
//!
//! The [`PacketParser`] will by default automatically detect and
//! remove any ASCII armor encoding (see [Section 6 of RFC 4880]).
//! This automatism can be disabled and fine-tuned using
//! [`PacketParserBuilder::dearmor`].
//!
//!   [Section 6 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-6
//!   [`PacketParserBuilder::dearmor`]: struct.PacketParserBuilder.html#method.dearmor
//!
//! # Security Considerations
//!
//! In general, OpenPGP data must be considered attacker controlled
//! and thus treated with great care.  Even though we use a
//! memory-safe language, there are several aspects to be aware of:
//!
//!  - OpenPGP messages may be compressed.  Therefore, one cannot
//!    predict the uncompressed size of a message by looking at the
//!    compressed representation.  Operations that parse OpenPGP
//!    streams and buffer the packet data (like using the
//!    [`PacketPile`]'s [`Parse`] interface) are inherently unsafe and
//!    must only be used on trusted data.
//!
//!  - The authenticity of an OpenPGP message can only be checked once
//!    it has been fully processed.  Therefore, the plaintext must be
//!    buffered and not be trusted until the whole message is
//!    processed and signatures and/or ciphertext integrity are
//!    verified.  On the other hand, buffering an unbounded amount of
//!    data is problematic and can lead to out-of-memory situations
//!    resulting in denial of service.  The streaming message
//!    processing interfaces address this problem by buffering an
//!    configurable amount of data before releasing any data to the
//!    caller, and only revert to streaming unverified data if the
//!    message exceeds the buffer.  See [`DEFAULT_BUFFER_SIZE`] for
//!    more information.
//!
//!  - Not all parts of signed-then-encrypted OpenPGP messages are
//!    authenticated.  Notably, all packets outside the encryption
//!    container (any [`PKESK`] and [`SKESK`] packets, as well as the
//!    encryption container itself), the [`Literal`] packet's headers,
//!    as well as parts of the [`Signature`] are not covered by the
//!    signatures.
//!
//!  - Ciphertext integrity is provided by the [`SEIP`] packet's
//!    [`MDC`] mechanism, but the integrity can only be checked after
//!    decrypting the whole container.  Proper authenticated
//!    encryption is provided by the [`AED`] container, but as of this
//!    writing it is not standardized.
//!
//!   [`DEFAULT_BUFFER_SIZE`]: stream/constant.DEFAULT_BUFFER_SIZE.html
//!   [`PKESK`]: ../packet/enum.PKESK.html
//!   [`SKESK`]: ../packet/enum.PKESK.html
//!   [`Literal`]: ../packet/struct.Literal.html
//!   [`Signature`]: ../packet/enum.Signature.html
//!   [`SEIP`]: ../packet/enum.SEIP.html
//!   [`MDC`]: ../packet/struct.MDC.html
//!   [`AED`]: ../packet/enum.AED.html
use std;
use std::io;
use std::io::prelude::*;
use std::convert::TryFrom;
use std::cmp;
use std::str;
use std::mem;
use std::fmt;
use std::path::Path;
use std::result::Result as StdResult;

use ::buffered_reader::*;

use crate::{
    cert::CertValidator,
    cert::CertValidity,
    cert::KeyringValidator,
    cert::KeyringValidity,
    crypto::{aead, hash::Hash},
    Result,
    packet::header::{
        CTB,
        BodyLength,
        PacketLengthType,
    },
    crypto::S2K,
    Error,
    packet::{
        Container,
        Header,
    },
    packet::signature::Signature4,
    packet::prelude::*,
    Packet,
    Fingerprint,
    KeyID,
    crypto::SessionKey,
};
use crate::types::{
    AEADAlgorithm,
    CompressionAlgorithm,
    Features,
    HashAlgorithm,
    KeyFlags,
    KeyServerPreferences,
    PublicKeyAlgorithm,
    RevocationKey,
    SignatureType,
    SymmetricAlgorithm,
    Timestamp,
};
use crate::crypto::{self, mpi::{PublicKey, MPI}};
use crate::crypto::symmetric::{Decryptor, BufferedReaderDecryptor};
use crate::message;
use crate::message::MessageValidator;

mod partial_body;
use self::partial_body::BufferedReaderPartialBodyFilter;

use crate::packet::signature::subpacket::{
    NotationData,
    NotationDataFlags,
    Subpacket,
    SubpacketArea,
    SubpacketLength,
    SubpacketTag,
    SubpacketValue,
};

use crate::serialize::MarshalInto;

mod packet_pile_parser;
pub use self::packet_pile_parser::PacketPileParser;

mod hashed_reader;
pub(crate) use self::hashed_reader::{HashedReader, hash_update_text};

mod packet_parser_builder;
pub use self::packet_parser_builder::{Dearmor, PacketParserBuilder};
use packet_parser_builder::ARMOR_READER_LEVEL;

pub mod map;
mod mpis;
pub mod stream;

// Whether to trace execution by default (on stderr).
const TRACE : bool = false;

/// Parsing of packets and related structures.
///
/// This is a uniform interface to parse packets, messages, keys, and
/// related data structures.
pub trait Parse<'a, T> {
    /// Reads from the given reader.
    fn from_reader<R: 'a + Read + Send + Sync>(reader: R) -> Result<T>;

    /// Reads from the given file.
    ///
    /// The default implementation just uses [`from_reader(..)`], but
    /// implementations can provide their own specialized version.
    ///
    /// [`from_reader(..)`]: #tymethod.from_reader
    fn from_file<P: AsRef<Path>>(path: P) -> Result<T>
    {
        Self::from_reader(::std::fs::File::open(path)?)
    }

    /// Reads from the given slice.
    ///
    /// The default implementation just uses [`from_reader(..)`], but
    /// implementations can provide their own specialized version.
    ///
    /// [`from_reader(..)`]: #tymethod.from_reader
    fn from_bytes<D: AsRef<[u8]> + ?Sized + Send + Sync>(data: &'a D) -> Result<T> {
        Self::from_reader(io::Cursor::new(data))
    }
}

macro_rules! impl_parse_generic_packet {
    ($typ: ident) => {
        impl<'a> Parse<'a, $typ> for $typ {
            fn from_reader<R: 'a + Read + Send + Sync>(reader: R) -> Result<Self> {
                let bio = buffered_reader::Generic::with_cookie(
                    reader, None, Cookie::default());
                let parser = PacketHeaderParser::new_naked(bio);

                let mut pp = Self::parse(parser)?;
                pp.buffer_unread_content()?;

                match pp.next()? {
                    (Packet::$typ(o), PacketParserResult::EOF(_))
                        => Ok(o),
                    (p, PacketParserResult::EOF(_)) =>
                        Err(Error::InvalidOperation(
                            format!("Not a {} packet: {:?}", stringify!($typ),
                                    p)).into()),
                    (_, PacketParserResult::Some(_)) =>
                        Err(Error::InvalidOperation(
                            "Excess data after packet".into()).into()),
                }
            }
        }
    };
}

/// The default amount of acceptable nesting.
///
/// The default is `16`.
///
/// Typically, we expect a message to looking like:
///
/// ```text
/// [ encryption container: [ compression container: [ signature: [ literal data ]]]]
/// ```
///
/// So, this should be more than enough.
///
/// To change the maximum recursion depth, use
/// [`PacketParserBuilder::max_recursion_depth`].
///
///   [`PacketParserBuilder::max_recursion_depth`]: struct.PacketParserBuilder.html#method.max_recursion_depth
pub const DEFAULT_MAX_RECURSION_DEPTH : u8 = 16;

/// The default maximum size of non-container packets.
///
/// The default is `1 MiB`.
///
/// Packets that exceed this limit will be returned as
/// `Packet::Unknown`, with the error set to `Error::PacketTooLarge`.
///
/// This limit applies to any packet type that is *not* a container
/// packet, i.e. any packet that is not a literal data packet, a
/// compressed data packet, a symmetrically encrypted data packet, or
/// an AEAD encrypted data packet.
///
/// To change the maximum recursion depth, use
/// [`PacketParserBuilder::max_packet_size`].
///
///   [`PacketParserBuilder::max_packet_size`]: struct.PacketParserBuilder.html#method.max_packet_size
pub const DEFAULT_MAX_PACKET_SIZE: u32 = 1 << 20; // 1 MiB

// Used to parse an OpenPGP packet's header (note: in this case, the
// header means a Packet's fixed data, not the OpenPGP framing
// information, such as the CTB, and length information).
//
// This struct is not exposed to the user.  Instead, when a header has
// been successfully parsed, a `PacketParser` is returned.
pub(crate) struct PacketHeaderParser<T: BufferedReader<Cookie>> {
    // The reader stack wrapped in a buffered_reader::Dup so that if
    // there is a parse error, we can abort and still return an
    // Unknown packet.
    reader: buffered_reader::Dup<T, Cookie>,

    // The current packet's header.
    header: Header,
    header_bytes: Vec<u8>,

    // This packet's path.
    path: Vec<usize>,

    // The `PacketParser`'s state.
    state: PacketParserState,

    /// A map of this packet.
    map: Option<map::Map>,
}

/// Creates a local marco called php_try! that returns an Unknown
/// packet instead of an Error like try! on parsing-related errors.
/// (Errors like read errors are still returned as usual.)
///
/// If you want to fail like this in a non-try! context, use
/// php.fail("reason").
macro_rules! make_php_try {
    ($parser:expr) => {
        macro_rules! php_try {
            ($e:expr) => {
                match $e {
                    Ok(b) => {
                        Ok(b)
                    },
                    Err(e) => {
                        let e = match e.downcast::<io::Error>() {
                            Ok(e) =>
                                if let io::ErrorKind::UnexpectedEof = e.kind() {
                                    return $parser.error(e.into());
                                } else {
                                    e.into()
                                },
                            Err(e) => e,
                        };
                        let e = match e.downcast::<Error>() {
                            Ok(e) => return $parser.error(e.into()),
                            Err(e) => e,
                        };

                        Err(e)
                    },
                }?
            };
        }
    };
}

impl<T: BufferedReader<Cookie>> std::fmt::Debug for PacketHeaderParser<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_struct("PacketHeaderParser")
            .field("header", &self.header)
            .field("path", &self.path)
            .field("reader", &self.reader)
            .field("state", &self.state)
            .field("map", &self.map)
            .finish()
    }
}

impl<'a, T: 'a + BufferedReader<Cookie>> PacketHeaderParser<T> {
    // Returns a `PacketHeaderParser` to parse an OpenPGP packet.
    // `inner` points to the start of the OpenPGP framing information,
    // i.e., the CTB.
    fn new(inner: T,
           state: PacketParserState,
           path: Vec<usize>, header: Header,
           header_bytes: Vec<u8>) -> Self
    {
        assert!(path.len() > 0);

        let mut cookie = Cookie::default();
        cookie.level = inner.cookie_ref().level;
        let map = if state.settings.map {
            Some(map::Map::new(header_bytes.clone()))
        } else {
            None
        };
        PacketHeaderParser {
            reader: buffered_reader::Dup::with_cookie(inner, cookie),
            header: header,
            header_bytes: header_bytes,
            path: path,
            state: state,
            map: map,
        }
    }

    // Returns a `PacketHeaderParser` that parses a bare packet.  That
    // is, `inner` points to the start of the packet; the OpenPGP
    // framing has already been processed, and `inner` already
    // includes any required filters (e.g., a
    // `BufferedReaderPartialBodyFilter`, etc.).
    fn new_naked(inner: T) -> Self {
        PacketHeaderParser::new(inner,
                                PacketParserState::new(Default::default()),
                                vec![ 0 ],
                                Header::new(CTB::new(Tag::Reserved),
                                            BodyLength::Full(0)),
                                Vec::new())
    }

    // Consumes the bytes belonging to the packet's header (i.e., the
    // number of bytes read) from the reader, and returns a
    // `PacketParser` that can be returned to the user.
    //
    // Only call this function if the packet's header has been
    // completely and correctly parsed.  If a failure occurs while
    // parsing the header, use `fail()` instead.
    fn ok(mut self, packet: Packet) -> Result<PacketParser<'a>> {
        let total_out = self.reader.total_out();

        let mut reader = if self.state.settings.map {
            // Read the body for the map.  Note that
            // `total_out` does not account for the body.
            //
            // XXX avoid the extra copy.
            let body = self.reader.steal_eof()?;
            if body.len() > 0 {
                self.field("body", body.len());
            }

            // This is a buffered_reader::Dup, so this always has an
            // inner.
            let inner = Box::new(self.reader).into_inner().unwrap();

            // Combine the header with the body for the map.
            let mut data = Vec::with_capacity(total_out + body.len());
            // We know that the inner reader must have at least
            // `total_out` bytes buffered, otherwise we could never
            // have read that much from the `buffered_reader::Dup`.
            data.extend_from_slice(&inner.buffer()[..total_out]);
            data.extend(body);
            self.map.as_mut().unwrap().finalize(data);

            inner
        } else {
            // This is a buffered_reader::Dup, so this always has an
            // inner.
            Box::new(self.reader).into_inner().unwrap()
        };

        if total_out > 0 {
            // We know the data has been read, so this cannot fail.
            reader.data_consume_hard(total_out).unwrap();
        }

        Ok(PacketParser {
            header: self.header,
            packet,
            path: self.path,
            last_path: vec![],
            reader,
            content_was_read: false,
            encrypted: false,
            finished: false,
            map: self.map,
            body_hash: Some(Container::make_body_hash()),
            state: self.state,
        })
    }

    // Something went wrong while parsing the packet's header.  Aborts
    // and returns an Unknown packet instead.
    fn fail(self, reason: &'static str) -> Result<PacketParser<'a>> {
        self.error(Error::MalformedPacket(reason.into()).into())
    }

    fn error(mut self, error: anyhow::Error) -> Result<PacketParser<'a>> {
        // Rewind the dup reader, so that the caller has a chance to
        // buffer the whole body of the unknown packet.
        self.reader.rewind();
        Unknown::parse(self, error)
    }

    fn field(&mut self, name: &'static str, size: usize) {
        if let Some(ref mut map) = self.map {
            map.add(name, size)
        }
    }

    fn parse_u8(&mut self, name: &'static str) -> Result<u8> {
        self.field(name, 1);
        Ok(self.reader.data_consume_hard(1)?[0])
    }

    fn parse_be_u16(&mut self, name: &'static str) -> Result<u16> {
        self.field(name, 2);
        Ok(self.reader.read_be_u16()?)
    }

    fn parse_be_u32(&mut self, name: &'static str) -> Result<u32> {
        self.field(name, 4);
        Ok(self.reader.read_be_u32()?)
    }

    fn parse_bool(&mut self, name: &'static str) -> Result<bool> {
        self.field(name, 1);
        let v = self.reader.data_consume_hard(1)?[0];
        match v {
            0 => Ok(false),
            1 => Ok(true),
            n => Err(Error::MalformedPacket(
                format!("Invalid value for bool: {}", n)).into()),
        }
    }

    fn parse_bytes(&mut self, name: &'static str, amount: usize)
                   -> Result<Vec<u8>> {
        self.field(name, amount);
        Ok(self.reader.steal(amount)?)
    }

    fn parse_bytes_eof(&mut self, name: &'static str) -> Result<Vec<u8>> {
        let r = self.reader.steal_eof()?;
        self.field(name, r.len());
        Ok(r)
    }

    fn recursion_depth(&self) -> isize {
        self.path.len() as isize - 1
    }
}


/// What the hash in the Cookie is for.
#[derive(Copy, Clone, PartialEq, Debug)]
pub(crate) enum HashesFor {
    Nothing,
    MDC,
    Signature,
    CleartextSignature,
}

/// Controls whether or not a hashed reader hashes data.
#[derive(Copy, Clone, PartialEq, Debug)]
enum Hashing {
    /// Hashing is enabled.
    Enabled,
    /// Hashing is enabled for notarized signatures.
    Notarized,
    /// Hashing is disabled.
    Disabled,
}

/// Private state used by the `PacketParser`.
///
/// This is not intended to be used.  It is possible to explicitly
/// create `Cookie` instances using its `Default` implementation for
/// low-level interfacing with parsing code.
#[derive(Debug)]
pub struct Cookie {
    // `BufferedReader`s managed by a `PacketParser` have
    // `Some(level)`; an external `BufferedReader` (i.e., the
    // underlying `BufferedReader`) has no level.
    //
    // Before parsing a top-level packet, we may push a
    // `buffered_reader::Limitor` in front of the external
    // `BufferedReader`.  Such `BufferedReader`s are assigned a level
    // of 0.
    //
    // When a top-level packet (i.e., a packet with a recursion depth
    // of 0) reads from the `BufferedReader` stack, the top
    // `BufferedReader` will have a level of at most 0.
    //
    // If the top-level packet is a container, say, a `CompressedData`
    // packet, then it pushes a decompression filter with a level of 0
    // onto the `BufferedReader` stack, and it recursively invokes the
    // parser.
    //
    // When the parser encounters the `CompressedData`'s first child,
    // say, a `Literal` packet, it pushes a `buffered_reader::Limitor` on
    // the `BufferedReader` stack with a level of 1.  Then, a
    // `PacketParser` for the `Literal` data packet is created with a
    // recursion depth of 1.
    //
    // There are several things to note:
    //
    //   - When a `PacketParser` with a recursion depth of N reads
    //     from the `BufferedReader` stack, the top `BufferedReader`'s
    //     level is (at most) N.
    //
    //     - Because we sometimes don't need to push a limitor
    //       (specifically, when the length is indeterminate), the
    //       `BufferedReader` at the top of the stack may have a level
    //       less than the current `PacketParser`'s recursion depth.
    //
    //   - When a packet at depth N is a container that filters the
    //     data, it pushes a `BufferedReader` at level N onto the
    //     `BufferedReader` stack.
    //
    //   - When we finish parsing a packet at depth N, we pop all
    //     `BufferedReader`s from the `BufferedReader` stack that are
    //     at level N.  The intuition is: the `BufferedReaders` at
    //     level N are associated with the packet at depth N.
    //
    //   - If a OnePassSig packet occurs at the top level, then we
    //     need to push a HashedReader above the current level.  The
    //     top level is level 0, thus we push the HashedReader at
    //     level -1.
    level: Option<isize>,

    hashes_for: HashesFor,
    hashing: Hashing,

    /// Keeps track of whether the last one pass signature packet had
    /// the last flag set.
    saw_last: bool,
    sig_groups: Vec<SignatureGroup>,
    /// Keep track of the maximal size of sig_groups to compute
    /// signature levels.
    sig_groups_max_len: usize,

    /// Stashed bytes that need to be hashed.
    ///
    /// When checking nested signatures, we need to hash the framing.
    /// However, at the time we know that we want to hash it, it has
    /// already been consumed.  Deferring the consumption of headers
    /// failed due to complications with the partial body decoder
    /// eagerly consuming data.  I (Justus) decided that doing the
    /// right thing is not worth the trouble, at least for now.  Also,
    /// hash stash sounds funny.
    hash_stash: Option<Vec<u8>>,

    /// Whether this `BufferedReader` is actually an interior EOF in a
    /// container.
    ///
    /// This is used by the SEIP parser to prevent a child packet from
    /// accidentally swallowing the trailing MDC packet.  This can
    /// happen when there is a compressed data packet with an
    /// indeterminate body length encoding.  In this case, due to
    /// buffering, the decompressor consumes data beyond the end of
    /// the compressed data.
    ///
    /// When set, buffered_reader_stack_pop will return early when it
    /// encounters a fake EOF at the level it is popping to.
    fake_eof: bool,

    /// Indicates that this is the top-level armor reader that is
    /// doing a transformation of a message using the cleartext
    /// signature framework into a signed message.
    csf_transformation: bool,
}
assert_send_and_sync!(Cookie);

/// Contains hashes for consecutive one pass signature packets ending
/// in one with the last flag set.
pub(crate) struct SignatureGroup {
    /// Counts the number of one pass signature packets this group is
    /// for.  Once this drops to zero, we pop the group from the
    /// stack.
    ops_count: usize,

    /// The hash contexts.
    pub(crate) hashes: Vec<HashingMode<Box<dyn crypto::hash::Digest>>>,
}

/// Controls line-ending normalization during hashing.
///
/// OpenPGP normalizes line endings when signing or verifying text
/// signatures.
pub(crate) enum HashingMode<T> {
    /// Hash for a binary signature.
    ///
    /// The data is hashed as-is.
    Binary(T),

    /// Hash for a text signature.
    ///
    /// The data is hashed with line endings normalized to `\r\n`.
    Text(T),
}

impl<T: Clone> Clone for HashingMode<T> {
    fn clone(&self) -> Self {
        use self::HashingMode::*;
        match self {
            Binary(t) => Binary(t.clone()),
            Text(t) => Text(t.clone()),
        }
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for HashingMode<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use self::HashingMode::*;
        match self {
            Binary(t) => write!(f, "Binary({:?})", t),
            Text(t) => write!(f, "Text({:?})", t),
        }
    }
}

impl<T: PartialEq> PartialEq for HashingMode<T> {
    fn eq(&self, other: &Self) -> bool {
        use self::HashingMode::*;
        match (self, other) {
            (Binary(s), Binary(o)) => s.eq(o),
            (Text(s), Text(o)) => s.eq(o),
            _ => false,
        }
    }
}

impl<T: Eq> Eq for HashingMode<T> { }

impl<T> HashingMode<T> {
    fn map<U, F: Fn(&T) -> U>(&self, f: F) -> HashingMode<U> {
        use self::HashingMode::*;
        match self {
            Binary(t) => Binary(f(t)),
            Text(t) => Text(f(t)),
        }
    }

    pub(crate) fn as_ref(&self) -> &T {
        use self::HashingMode::*;
        match self {
            Binary(t) => t,
            Text(t) => t,
        }
    }

    pub(crate) fn as_mut(&mut self) -> &mut T {
        use self::HashingMode::*;
        match self {
            Binary(t) => t,
            Text(t) => t,
        }
    }

    fn for_signature(t: T, typ: SignatureType) -> Self {
        if typ == SignatureType::Text {
            HashingMode::Text(t)
        } else {
            HashingMode::Binary(t)
        }
    }
}

impl fmt::Debug for SignatureGroup {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let algos = self.hashes.iter().map(|mode| mode.map(|ctx| ctx.algo()))
            .collect::<Vec<_>>();

        f.debug_struct("Cookie")
            .field("ops_count", &self.ops_count)
            .field("hashes", &algos)
            .finish()
    }
}

impl Default for SignatureGroup {
    fn default() -> Self {
        SignatureGroup {
            ops_count: 0,
            hashes: Default::default(),
        }
    }
}

impl SignatureGroup {
    /// Clears the signature group.
    fn clear(&mut self) {
        self.ops_count = 0;
        self.hashes.clear();
    }
}

impl Default for Cookie {
    fn default() -> Self {
        Cookie {
            level: None,
            hashing: Hashing::Enabled,
            hashes_for: HashesFor::Nothing,
            saw_last: false,
            sig_groups: vec![Default::default()],
            sig_groups_max_len: 1,
            hash_stash: None,
            fake_eof: false,
            csf_transformation: false,
        }
    }
}

impl Cookie {
    fn new(level: isize) -> Cookie {
        Cookie {
            level: Some(level),
            hashing: Hashing::Enabled,
            hashes_for: HashesFor::Nothing,
            saw_last: false,
            sig_groups: vec![Default::default()],
            sig_groups_max_len: 1,
            hash_stash: None,
            fake_eof: false,
            csf_transformation: false,
        }
    }

    /// Returns a reference to the topmost signature group.
    pub(crate) fn sig_group(&self) -> &SignatureGroup {
        assert!(self.sig_groups.len() > 0);
        &self.sig_groups[self.sig_groups.len() - 1]
    }

    /// Returns a mutable reference to the topmost signature group.
    pub(crate) fn sig_group_mut(&mut self) -> &mut SignatureGroup {
        assert!(self.sig_groups.len() > 0);
        let len = self.sig_groups.len();
        &mut self.sig_groups[len - 1]
    }

    /// Returns the level of the currently parsed signature.
    fn signature_level(&self) -> usize {
        // The signature with the deepest "nesting" is closest to the
        // data, and hence level 0.
        self.sig_groups_max_len - self.sig_groups.len()
    }

    /// Tests whether the topmost signature group is no longer used.
    fn sig_group_unused(&self) -> bool {
        assert!(self.sig_groups.len() > 0);
        self.sig_groups[self.sig_groups.len() - 1].ops_count == 0
    }

    /// Pushes a new signature group to the stack.
    fn sig_group_push(&mut self) {
        self.sig_groups.push(Default::default());
        self.sig_groups_max_len += 1;
    }

    /// Pops a signature group from the stack.
    fn sig_group_pop(&mut self) {
        if self.sig_groups.len() == 1 {
            // Don't pop the last one, just clear it.
            self.sig_groups[0].clear();
            self.hashes_for = HashesFor::Nothing;
        } else {
            self.sig_groups.pop();
        }
    }
}

impl Cookie {
    // Enables or disables signature hashers (HashesFor::Signature) at
    // level `level`.
    //
    // Thus to disable the hashing of a level 3 literal packet's
    // meta-data, we disable hashing at level 2.
    fn hashing(reader: &mut dyn BufferedReader<Cookie>,
               how: Hashing, level: isize) {
        let mut reader : Option<&mut dyn BufferedReader<Cookie>>
            = Some(reader);
        while let Some(r) = reader {
            {
                let cookie = r.cookie_mut();
                if let Some(br_level) = cookie.level {
                    if br_level < level {
                        break;
                    }
                    if br_level == level
                        && (cookie.hashes_for == HashesFor::Signature
                            || cookie.hashes_for == HashesFor::CleartextSignature)
                    {
                        cookie.hashing = how;
                    }
                } else {
                    break;
                }
            }
            reader = r.get_mut();
        }
    }

    /// Signals that we are processing a message using the Cleartext
    /// Signature Framework.
    ///
    /// This is used by the armor reader to signal that it has
    /// encountered such a message and is transforming it into an
    /// inline signed message.
    pub(crate) fn set_processing_csf_message(&mut self) {
        tracer!(TRACE, "set_processing_csf_message", self.level.unwrap_or(0));
        t!("Enabling CSF Transformation mode");
        self.csf_transformation = true;
    }

    /// Checks if we are processing a signed message using the
    /// Cleartext Signature Framework.
    fn processing_csf_message(reader: &dyn BufferedReader<Cookie>)
                              -> bool {
        let mut reader: Option<&dyn BufferedReader<Cookie>>
            = Some(reader);
        while let Some(r) = reader {
            if r.cookie_ref().level == Some(ARMOR_READER_LEVEL) {
                return r.cookie_ref().csf_transformation;
            } else {
                reader = r.get_ref();
            }
        }
        false
    }
}

// Pops readers from a buffered reader stack at the specified level.
fn buffered_reader_stack_pop<'a>(
    mut reader: Box<dyn BufferedReader<Cookie> + 'a>, depth: isize)
    -> Result<(bool, Box<dyn BufferedReader<Cookie> + 'a>)>
{
    tracer!(TRACE, "buffered_reader_stack_pop", depth);
    t!("(reader level: {:?}, pop through: {})",
       reader.cookie_ref().level, depth);

    while let Some(level) = reader.cookie_ref().level {
        assert!(level <= depth // Peel off exactly one level.
                || depth < 0); // Except for the topmost filters.

        if level >= depth {
            let fake_eof = reader.cookie_ref().fake_eof;

            t!("top reader at level {:?} (fake eof: {}), pop through: {}",
               reader.cookie_ref().level, fake_eof, depth);

            t!("popping level {:?} reader, reader: {:?}",
               reader.cookie_ref().level,
               reader);

            if reader.eof() && ! reader.consummated() {
                return Err(Error::MalformedPacket("Truncated packet".into())
                           .into());
            }
            reader.drop_eof()?;
            reader = reader.into_inner().unwrap();

            if level == depth && fake_eof {
                t!("Popped a fake EOF reader at level {}, stopping.", depth);
                return Ok((true, reader));
            }

            t!("now at level {:?} reader: {:?}",
               reader.cookie_ref().level, reader);
        } else {
            break;
        }
    }

    Ok((false, reader))
}


// A `PacketParser`'s settings.
#[derive(Clone, Debug)]
struct PacketParserSettings {
    // The maximum allowed recursion depth.
    //
    // There is absolutely no reason that this should be more than
    // 255.  (GnuPG defaults to 32.)  Moreover, if it is too large,
    // then a read from the reader pipeline could blow the stack.
    max_recursion_depth: u8,

    // The maximum size of non-container packets.
    //
    // Packets that exceed this limit will be returned as
    // `Packet::Unknown`, with the error set to
    // `Error::PacketTooLarge`.
    //
    // This limit applies to any packet type that is *not* a
    // container packet, i.e. any packet that is not a literal data
    // packet, a compressed data packet, a symmetrically encrypted
    // data packet, or an AEAD encrypted data packet.
    max_packet_size: u32,

    // Whether a packet's contents should be buffered or dropped when
    // the next packet is retrieved.
    buffer_unread_content: bool,

    // Whether or not to create a map.
    map: bool,
}

// The default `PacketParser` settings.
impl Default for PacketParserSettings {
    fn default() -> Self {
        PacketParserSettings {
            max_recursion_depth: DEFAULT_MAX_RECURSION_DEPTH,
            max_packet_size: DEFAULT_MAX_PACKET_SIZE,
            buffer_unread_content: false,
            map: false,
        }
    }
}

impl S2K {
    /// Reads an S2K from `php`.
    fn parse<T: BufferedReader<Cookie>>(php: &mut PacketHeaderParser<T>) -> Result<Self>
    {
        let s2k = php.parse_u8("s2k_type")?;
        #[allow(deprecated)]
        let ret = match s2k {
            0 => S2K::Simple {
                hash: HashAlgorithm::from(php.parse_u8("s2k_hash_algo")?),
            },
            1 => S2K::Salted {
                hash: HashAlgorithm::from(php.parse_u8("s2k_hash_algo")?),
                salt: Self::read_salt(php)?,
            },
            3 => S2K::Iterated {
                hash: HashAlgorithm::from(php.parse_u8("s2k_hash_algo")?),
                salt: Self::read_salt(php)?,
                hash_bytes: S2K::decode_count(php.parse_u8("s2k_count")?),
            },
            100..=110 => S2K::Private {
                tag: s2k,
                parameters: None,
            },
            u => S2K::Unknown {
                tag: u,
                parameters: None,
            },
        };

        Ok(ret)
    }

    fn read_salt<'a, T: 'a + BufferedReader<Cookie>>(php: &mut PacketHeaderParser<T>) -> Result<[u8; 8]> {
        let mut b = [0u8; 8];
        b.copy_from_slice(&php.parse_bytes("s2k_salt", 8)?);

        Ok(b)
    }
}

impl<'a> Parse<'a, S2K> for S2K {
    /// Reads an S2K from `reader`.
    fn from_reader<R: 'a + Read + Send + Sync>(reader: R) -> Result<Self> {
        let bio = buffered_reader::Generic::with_cookie(
            reader, None, Cookie::default());
        let mut parser = PacketHeaderParser::new_naked(bio);
        Self::parse(&mut parser)
    }
}

impl Header {
    pub(crate) fn parse<R: BufferedReader<C>, C: fmt::Debug + Send + Sync> (bio: &mut R)
        -> Result<Header>
    {
        let ctb = CTB::try_from(bio.data_consume_hard(1)?[0])?;
        let length = match ctb {
            CTB::New(_) => BodyLength::parse_new_format(bio)?,
            CTB::Old(ref ctb) =>
                BodyLength::parse_old_format(bio, ctb.length_type())?,
        };
        return Ok(Header::new(ctb, length));
    }
}

impl<'a> Parse<'a, Header> for Header {
    /// Parses an OpenPGP packet's header as described in [Section 4.2
    /// of RFC 4880].
    ///
    ///   [Section 4.2 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-4.2
    fn from_reader<R: 'a + Read + Send + Sync>(reader: R) -> Result<Self>
    {
        let mut reader = buffered_reader::Generic::with_cookie(
            reader, None, Cookie::default());
        Header::parse(&mut reader)
    }
}

impl BodyLength {
    /// Decodes a new format body length as described in [Section
    /// 4.2.2 of RFC 4880].
    ///
    ///   [Section 4.2.2 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-4.2.2
    pub(crate) fn parse_new_format<T: BufferedReader<C>, C: fmt::Debug + Send + Sync> (bio: &mut T)
        -> io::Result<BodyLength>
    {
        let octet1 : u8 = bio.data_consume_hard(1)?[0];
        match octet1 {
            0..=191 => // One octet.
                Ok(BodyLength::Full(octet1 as u32)),
            192..=223 => { // Two octets length.
                let octet2 = bio.data_consume_hard(1)?[0];
                Ok(BodyLength::Full(((octet1 as u32 - 192) << 8)
                                    + octet2 as u32 + 192))
            },
            224..=254 => // Partial body length.
                Ok(BodyLength::Partial(1 << (octet1 & 0x1F))),
            255 => // Five octets.
                Ok(BodyLength::Full(bio.read_be_u32()?)),
        }
    }

    /// Decodes an old format body length as described in [Section
    /// 4.2.1 of RFC 4880].
    ///
    ///   [Section 4.2.1 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-4.2.1
    pub(crate) fn parse_old_format<T: BufferedReader<C>, C: fmt::Debug + Send + Sync>
        (bio: &mut T, length_type: PacketLengthType)
         -> Result<BodyLength>
    {
        match length_type {
            PacketLengthType::OneOctet =>
                Ok(BodyLength::Full(bio.data_consume_hard(1)?[0] as u32)),
            PacketLengthType::TwoOctets =>
                Ok(BodyLength::Full(bio.read_be_u16()? as u32)),
            PacketLengthType::FourOctets =>
                Ok(BodyLength::Full(bio.read_be_u32()? as u32)),
            PacketLengthType::Indeterminate =>
                Ok(BodyLength::Indeterminate),
        }
    }
}

#[test]
fn body_length_new_format() {
    fn test(input: &[u8], expected_result: BodyLength) {
        assert_eq!(
            BodyLength::parse_new_format(
                &mut buffered_reader::Memory::new(input)).unwrap(),
            expected_result);
    }

    // Examples from Section 4.2.3 of RFC4880.

    // Example #1.
    test(&[0x64][..], BodyLength::Full(100));

    // Example #2.
    test(&[0xC5, 0xFB][..], BodyLength::Full(1723));

    // Example #3.
    test(&[0xFF, 0x00, 0x01, 0x86, 0xA0][..], BodyLength::Full(100000));

    // Example #4.
    test(&[0xEF][..], BodyLength::Partial(32768));
    test(&[0xE1][..], BodyLength::Partial(2));
    test(&[0xF0][..], BodyLength::Partial(65536));
    test(&[0xC5, 0xDD][..], BodyLength::Full(1693));
}

#[test]
fn body_length_old_format() {
    fn test(input: &[u8], plt: PacketLengthType,
            expected_result: BodyLength, expected_rest: &[u8]) {
        let mut bio = buffered_reader::Memory::new(input);
        assert_eq!(BodyLength::parse_old_format(&mut bio, plt).unwrap(),
                   expected_result);
        let rest = bio.data_eof();
        assert_eq!(rest.unwrap(), expected_rest);
    }

    test(&[1], PacketLengthType::OneOctet, BodyLength::Full(1), &b""[..]);
    test(&[1, 2], PacketLengthType::TwoOctets,
         BodyLength::Full((1 << 8) + 2), &b""[..]);
    test(&[1, 2, 3, 4], PacketLengthType::FourOctets,
         BodyLength::Full((1 << 24) + (2 << 16) + (3 << 8) + 4), &b""[..]);
    test(&[1, 2, 3, 4, 5, 6], PacketLengthType::FourOctets,
         BodyLength::Full((1 << 24) + (2 << 16) + (3 << 8) + 4), &[5, 6][..]);
    test(&[1, 2, 3, 4], PacketLengthType::Indeterminate,
         BodyLength::Indeterminate, &[1, 2, 3, 4][..]);
}

impl Unknown {
    /// Parses the body of any packet and returns an Unknown.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(php: PacketHeaderParser<T>, error: anyhow::Error)
                 -> Result<PacketParser<'a>>
    {
        let tag = php.header.ctb().tag();
        php.ok(Packet::Unknown(Unknown::new(tag, error)))
            .map(|pp| pp.set_encrypted(true))
    }
}

// Read the next packet as an unknown packet.
//
// The `reader` must point to the packet's header, i.e., the CTB.
// This buffers the packet's contents.
//
// Note: we only need this function for testing purposes in a
// different module.
#[cfg(test)]
pub(crate) fn to_unknown_packet<R: Read + Send + Sync>(reader: R) -> Result<Unknown>
{
    let mut reader = buffered_reader::Generic::with_cookie(
        reader, None, Cookie::default());
    let header = Header::parse(&mut reader)?;

    let reader : Box<dyn BufferedReader<Cookie>>
        = match header.length() {
            &BodyLength::Full(len) =>
                Box::new(buffered_reader::Limitor::with_cookie(
                    reader, len as u64, Cookie::default())),
            &BodyLength::Partial(len) =>
                Box::new(BufferedReaderPartialBodyFilter::with_cookie(
                    reader, len, true, Cookie::default())),
            _ => Box::new(reader),
    };

    let parser = PacketHeaderParser::new(
        reader, PacketParserState::new(Default::default()), vec![ 0 ], header, Vec::new());
    let mut pp =
        Unknown::parse(parser,
                       anyhow::anyhow!("explicit conversion to unknown"))?;
    pp.buffer_unread_content()?;
    pp.finish()?;

    if let Packet::Unknown(packet) = pp.packet {
        Ok(packet)
    } else {
        panic!("Internal inconsistency.");
    }
}

impl Signature {
    // Parses a signature packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>)
        -> Result<PacketParser<'a>>
    {
        let indent = php.recursion_depth();
        tracer!(TRACE, "Signature::parse", indent);

        make_php_try!(php);

        let version = php_try!(php.parse_u8("version"));

        match version {
            4 => Signature4::parse(php),
            _ => {
                t!("Ignoring version {} packet.", version);
                php.fail("unknown version")
            },
        }
    }

    /// Returns whether the data appears to be a signature (no promises).
    fn plausible<T: BufferedReader<Cookie>>(
        bio: &mut buffered_reader::Dup<T, Cookie>, header: &Header)
                 -> Result<()> {
        Signature4::plausible(bio, header)
    }
}

impl Signature4 {
    // Parses a signature packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>)
        -> Result<PacketParser<'a>>
    {
        let indent = php.recursion_depth();
        tracer!(TRACE, "Signature4::parse", indent);

        make_php_try!(php);

        let typ = php_try!(php.parse_u8("type"));
        let pk_algo: PublicKeyAlgorithm = php_try!(php.parse_u8("pk_algo")).into();
        let hash_algo = php_try!(php.parse_u8("hash_algo"));
        let hashed_area_len = php_try!(php.parse_be_u16("hashed_area_len"));
        let hashed_area
            = php_try!(SubpacketArea::parse(&mut php,
                                            hashed_area_len as usize));
        let unhashed_area_len = php_try!(php.parse_be_u16("unhashed_area_len"));
        let unhashed_area
            = php_try!(SubpacketArea::parse(&mut php,
                                            unhashed_area_len as usize));
        let digest_prefix1 = php_try!(php.parse_u8("digest_prefix1"));
        let digest_prefix2 = php_try!(php.parse_u8("digest_prefix2"));
        if ! pk_algo.for_signing() {
            return php.fail("not a signature algorithm");
        }
        let mpis = php_try!(
            crypto::mpi::Signature::_parse(pk_algo, &mut php));

        let hash_algo = hash_algo.into();
        let typ = typ.into();
        let need_hash = HashingMode::for_signature(hash_algo, typ);
        let mut pp = php.ok(Packet::Signature(Signature4::new(
            typ, pk_algo.into(), hash_algo,
            hashed_area,
            unhashed_area,
            [digest_prefix1, digest_prefix2],
            mpis).into()))?;

        // Locate the corresponding HashedReader and extract the
        // computed hash.
        let mut computed_digest = None;
        {
            let recursion_depth = pp.recursion_depth();

            // We know that the top reader is not a HashedReader (it's
            // a buffered_reader::Dup).  So, start with it's child.
            let mut r = (&mut pp.reader).get_mut();
            while let Some(tmp) = r {
                {
                    let cookie = tmp.cookie_mut();

                    assert!(cookie.level.unwrap_or(-1)
                            <= recursion_depth);
                    // The HashedReader has to be at level
                    // 'recursion_depth - 1'.
                    if cookie.level.is_none()
                        || cookie.level.unwrap() < recursion_depth - 1 {
                            break
                        }

                    if cookie.hashes_for == HashesFor::Signature {
                        // When verifying cleartext signed messages,
                        // we may have more signatures than
                        // one-pass-signature packets, but are
                        // guaranteed to only have one signature
                        // group.
                        //
                        // Only decrement the count when hashing for
                        // signatures, not when hashing for cleartext
                        // signatures.
                        cookie.sig_group_mut().ops_count -= 1;
                    }

                    if cookie.hashes_for == HashesFor::Signature
                        || cookie.hashes_for == HashesFor::CleartextSignature
                    {
                        if let Some(hash) =
                            cookie.sig_group().hashes.iter().find_map(
                                |mode|
                                if mode.map(|ctx| ctx.algo()) == need_hash {
                                    Some(mode.as_ref())
                                } else {
                                    None
                                })
                        {
                            t!("found a {:?} HashedReader", need_hash);
                            computed_digest = Some((cookie.signature_level(),
                                                    hash.clone()));
                        }

                        if cookie.sig_group_unused() {
                            cookie.sig_group_pop();
                        }
                        break;
                    }
                }

                r = tmp.get_mut();
            }
        }

        if let Some((level, mut hash)) = computed_digest {
            if let Packet::Signature(ref mut sig) = pp.packet {
                sig.hash(&mut hash);

                let mut digest = vec![0u8; hash.digest_size()];
                let _ = hash.digest(&mut digest);

                sig.set_computed_digest(Some(digest));
                sig.set_level(level);
            } else {
                unreachable!()
            }
        }

        Ok(pp)
    }

    /// Returns whether the data appears to be a signature (no promises).
    fn plausible<T: BufferedReader<Cookie>>(
        bio: &mut buffered_reader::Dup<T, Cookie>, header: &Header)
                 -> Result<()> {
        // The absolute minimum size for the header is 11 bytes (this
        // doesn't include the signature MPIs).

        if let &BodyLength::Full(len) = header.length() {
            if len < 11 {
                // Much too short.
                return Err(
                    Error::MalformedPacket("Packet too short".into()).into());
            }
        } else {
            return Err(
                Error::MalformedPacket(
                    format!("Unexpected body length encoding: {:?}",
                            header.length())
                        .into()).into());
        }

        // Make sure we have a minimum header.
        let data = bio.data(11)?;
        if data.len() < 11 {
            return Err(
                Error::MalformedPacket("Short read".into()).into());
        }

        // Assume unknown == bad.
        let version = data[0];
        let typ : SignatureType = data[1].into();
        let pk_algo : PublicKeyAlgorithm = data[2].into();
        let hash_algo : HashAlgorithm = data[3].into();

        if version == 4
            && !matches!(typ, SignatureType::Unknown(_))
            && !matches!(pk_algo, PublicKeyAlgorithm::Unknown(_))
            && !matches!(hash_algo, HashAlgorithm::Unknown(_))
        {
            Ok(())
        } else {
            Err(Error::MalformedPacket("Invalid or unsupported data".into())
                .into())
        }
    }
}

impl_parse_generic_packet!(Signature);

#[test]
fn signature_parser_test () {
    use crate::serialize::MarshalInto;
    let data = crate::tests::message("sig.gpg");

    {
        let pp = PacketParser::from_bytes(data).unwrap().unwrap();
        assert_eq!(pp.header.length(), &BodyLength::Full(307));
        if let Packet::Signature(ref p) = pp.packet {
            assert_eq!(p.version(), 4);
            assert_eq!(p.typ(), SignatureType::Binary);
            assert_eq!(p.pk_algo(), PublicKeyAlgorithm::RSAEncryptSign);
            assert_eq!(p.hash_algo(), HashAlgorithm::SHA512);
            assert_eq!(p.hashed_area().iter().count(), 2);
            assert_eq!(p.unhashed_area().iter().count(), 1);
            assert_eq!(p.digest_prefix(), &[0x65u8, 0x74]);
            assert_eq!(p.mpis().serialized_len(), 258);
        } else {
            panic!("Wrong packet!");
        }
    }
}

impl SubpacketArea {
    // Parses a subpacket area.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(php: &mut PacketHeaderParser<T>, mut limit: usize)
                 -> Result<Self>
    {
        let mut packets = Vec::new();
        while limit > 0 {
            let p = Subpacket::parse(php, limit)?;
            assert!(limit >= p.length.len() + p.length.serialized_len());
            limit -= p.length.len() + p.length.serialized_len();
            packets.push(p);
        }
        assert!(limit == 0);
        Self::new(packets)
    }
}

impl Subpacket {
    // Parses a raw subpacket.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(php: &mut PacketHeaderParser<T>, limit: usize)
                 -> Result<Self> {
        let length = SubpacketLength::parse(&mut php.reader)?;
        php.field("subpacket length", length.serialized_len());
        let len = length.len() as usize;

        if limit < length.serialized_len() + len {
            return Err(Error::MalformedPacket(
                "Subpacket extends beyond the end of the subpacket area".into())
                       .into());
        }

        if len == 0 {
            return Err(Error::MalformedPacket("Zero-length subpacket".into())
                       .into());
        }

        let tag = php.parse_u8("subpacket tag")?;
        let len = len - 1;

        // Remember our position in the reader to check subpacket boundaries.
        let total_out_before = php.reader.total_out();

        // The critical bit is the high bit.  Extract it.
        let critical = tag & (1 << 7) != 0;
        // Then clear it from the type and convert it.
        let tag: SubpacketTag = (tag & !(1 << 7)).into();

        let value = match tag {
            SubpacketTag::SignatureCreationTime =>
                SubpacketValue::SignatureCreationTime(
                    php.parse_be_u32("sig creation time")?.into()),
            SubpacketTag::SignatureExpirationTime =>
                SubpacketValue::SignatureExpirationTime(
                    php.parse_be_u32("sig expiry time")?.into()),
            SubpacketTag::ExportableCertification =>
                SubpacketValue::ExportableCertification(
                    php.parse_bool("exportable")?),
            SubpacketTag::TrustSignature =>
                SubpacketValue::TrustSignature {
                    level: php.parse_u8("trust level")?,
                    trust: php.parse_u8("trust value")?,
                },
            SubpacketTag::RegularExpression => {
                let mut v = php.parse_bytes("regular expr", len)?;
                if v.len() == 0 || v[v.len() - 1] != 0 {
                    return Err(Error::MalformedPacket(
                        "Regular expression not 0-terminated".into())
                               .into());
                }
                v.pop();
                SubpacketValue::RegularExpression(v)
            },
            SubpacketTag::Revocable =>
                SubpacketValue::Revocable(php.parse_bool("revocable")?),
            SubpacketTag::KeyExpirationTime =>
                SubpacketValue::KeyExpirationTime(
                    php.parse_be_u32("key expiry time")?.into()),
            SubpacketTag::PreferredSymmetricAlgorithms =>
                SubpacketValue::PreferredSymmetricAlgorithms(
                    php.parse_bytes("pref sym algos", len)?
                        .iter().map(|o| (*o).into()).collect()),
            SubpacketTag::RevocationKey => {
                // 1 octet of class, 1 octet of pk algorithm, 20 bytes
                // for a v4 fingerprint and 32 bytes for a v5
                // fingerprint.
                if len < 22 {
                    return Err(Error::MalformedPacket(
                        "Short revocation key subpacket".into())
                               .into());
                }
                let class = php.parse_u8("class")?;
                let pk_algo = php.parse_u8("pk algo")?.into();
                let fp = Fingerprint::from_bytes(
                    &php.parse_bytes("fingerprint", len - 2)?);
                SubpacketValue::RevocationKey(
                    RevocationKey::from_bits(pk_algo, fp, class)?)
            },
            SubpacketTag::Issuer =>
                SubpacketValue::Issuer(
                    KeyID::from_bytes(&php.parse_bytes("issuer", len)?)),
            SubpacketTag::NotationData => {
                let flags = php.parse_bytes("flags", 4)?;
                let name_len = php.parse_be_u16("name len")? as usize;
                let value_len = php.parse_be_u16("value len")? as usize;

                if len != 8 + name_len + value_len {
                    return Err(Error::MalformedPacket(
                        format!("Malformed notation data subpacket: \
                                 expected {} bytes, got {}",
                                8 + name_len + value_len,
                                len)).into());
                }
                SubpacketValue::NotationData(
                    NotationData::new(
                        std::str::from_utf8(
                            &php.parse_bytes("notation name", name_len)?)
                            .map_err(|e| anyhow::Error::from(
                                Error::MalformedPacket(
                                    format!("Malformed notation name: {}", e)))
                            )?,
                        &php.parse_bytes("notation value", value_len)?,
                        Some(NotationDataFlags::new(&flags)?)))
            },
            SubpacketTag::PreferredHashAlgorithms =>
                SubpacketValue::PreferredHashAlgorithms(
                    php.parse_bytes("pref hash algos", len)?
                        .iter().map(|o| (*o).into()).collect()),
            SubpacketTag::PreferredCompressionAlgorithms =>
                SubpacketValue::PreferredCompressionAlgorithms(
                    php.parse_bytes("pref compression algos", len)?
                        .iter().map(|o| (*o).into()).collect()),
            SubpacketTag::KeyServerPreferences =>
                SubpacketValue::KeyServerPreferences(
                    KeyServerPreferences::new(
                        &php.parse_bytes("key server pref", len)?
                    )),
            SubpacketTag::PreferredKeyServer =>
                SubpacketValue::PreferredKeyServer(
                    php.parse_bytes("pref key server", len)?),
            SubpacketTag::PrimaryUserID =>
                SubpacketValue::PrimaryUserID(
                    php.parse_bool("primary user id")?),
            SubpacketTag::PolicyURI =>
                SubpacketValue::PolicyURI(php.parse_bytes("policy URI", len)?),
            SubpacketTag::KeyFlags =>
                SubpacketValue::KeyFlags(KeyFlags::new(
                    &php.parse_bytes("key flags", len)?)),
            SubpacketTag::SignersUserID =>
                SubpacketValue::SignersUserID(
                    php.parse_bytes("signers user id", len)?),
            SubpacketTag::ReasonForRevocation => {
                if len == 0 {
                    return Err(Error::MalformedPacket(
                        "Short reason for revocation subpacket".into()).into());
                }
                SubpacketValue::ReasonForRevocation {
                    code: php.parse_u8("revocation reason")?.into(),
                    reason: php.parse_bytes("human-readable", len - 1)?,
                }
            },
            SubpacketTag::Features =>
                SubpacketValue::Features(Features::new(
                    &php.parse_bytes("features", len)?)),
            SubpacketTag::SignatureTarget => {
                if len < 2 {
                    return Err(Error::MalformedPacket(
                        "Short reason for revocation subpacket".into()).into());
                }
                SubpacketValue::SignatureTarget {
                    pk_algo: php.parse_u8("pk algo")?.into(),
                    hash_algo: php.parse_u8("hash algo")?.into(),
                    digest: php.parse_bytes("digest", len - 2)?,
                }
            },
            SubpacketTag::EmbeddedSignature =>
                SubpacketValue::EmbeddedSignature(
                    Signature::from_bytes(
                        &php.parse_bytes("embedded sig", len)?)?),
            SubpacketTag::IssuerFingerprint => {
                if len == 0 {
                    return Err(Error::MalformedPacket(
                        "Short issuer fingerprint subpacket".into()).into());
                }
                let version = php.parse_u8("version")?;
                if let Some(expect_len) = match version {
                    4 => Some(1 + 20),
                    5 => Some(1 + 32),
                    _ => None,
                } {
                    if len != expect_len {
                        return Err(Error::MalformedPacket(
                            format!("Malformed issuer fingerprint subpacket: \
                                     expected {} bytes, got {}",
                                    expect_len, len)).into());
                    }
                }
                let bytes = php.parse_bytes("issuer fp", len - 1)?;
                SubpacketValue::IssuerFingerprint(
                    match version {
                        4 => Fingerprint::from_bytes(&bytes),
                        // XXX: Fix once we dig V5.
                        5 => Fingerprint::Invalid(bytes.into()),
                        _ => Fingerprint::Invalid(bytes.into()),
                    })
            },
            SubpacketTag::PreferredAEADAlgorithms =>
                SubpacketValue::PreferredAEADAlgorithms(
                    php.parse_bytes("pref aead algos", len)?
                        .iter().map(|o| (*o).into()).collect()),
            SubpacketTag::IntendedRecipient => {
                if len == 0 {
                    return Err(Error::MalformedPacket(
                        "Short intended recipient subpacket".into()).into());
                }
                let version = php.parse_u8("version")?;
                if let Some(expect_len) = match version {
                    4 => Some(1 + 20),
                    5 => Some(1 + 32),
                    _ => None,
                } {
                    if len != expect_len {
                        return Err(Error::MalformedPacket(
                            format!("Malformed intended recipient subpacket: \
                                     expected {} bytes, got {}",
                                    expect_len, len)).into());
                    }
                }
                let bytes = php.parse_bytes("intended rcpt", len - 1)?;
                SubpacketValue::IntendedRecipient(
                    match version {
                        4 => Fingerprint::from_bytes(&bytes),
                        // XXX: Fix once we dig V5.
                        5 => Fingerprint::Invalid(bytes.into()),
                        _ => Fingerprint::Invalid(bytes.into()),
                    })
            },
            SubpacketTag::Reserved(_)
                | SubpacketTag::PlaceholderForBackwardCompatibility
                | SubpacketTag::Private(_)
                | SubpacketTag::Unknown(_) =>
                SubpacketValue::Unknown {
                    tag,
                    body: php.parse_bytes("unknown subpacket", len)?,
                },
        };

        let total_out = php.reader.total_out();
        if total_out_before + len != total_out {
            return Err(Error::MalformedPacket(
                format!("Malformed subpacket: \
                         body length is {} bytes, but read {}",
                        len, total_out - total_out_before)).into());
        }

        Ok(Subpacket::with_length(
            length,
            value,
            critical,
        ))
    }
}

impl SubpacketLength {
    /// Parses a subpacket length.
    fn parse<R: BufferedReader<C>, C: fmt::Debug + Send + Sync>(bio: &mut R) -> Result<Self> {
        let octet1 = bio.data_consume_hard(1)?[0];
        if octet1 < 192 {
            // One octet.
            Ok(Self::new(
                octet1 as u32,
                // Unambiguous.
                None))
        } else if 192 <= octet1 && octet1 < 255 {
            // Two octets length.
            let octet2 = bio.data_consume_hard(1)?[0];
            let len = ((octet1 as u32 - 192) << 8) + octet2 as u32 + 192;
            Ok(Self::new(
                len,
                if Self::len_optimal_encoding(len) == 2 {
                    None
                } else {
                    Some(vec![octet1, octet2])
                }))
        } else {
            // Five octets.
            assert_eq!(octet1, 255);
            let len = bio.read_be_u32()?;
            Ok(Self::new(
                len,
                if Self::len_optimal_encoding(len) == 5 {
                    None
                } else {
                    let mut out = Vec::with_capacity(5);
                    out.push(octet1);
                    out.extend_from_slice(&len.to_be_bytes());
                    Some(out)
                }))
        }
    }
}

#[cfg(test)]
quickcheck! {
    fn length_roundtrip(l: u32) -> bool {
        use crate::serialize::Marshal;

        let length = SubpacketLength::from(l);
        let mut encoded = Vec::new();
        length.serialize(&mut encoded).unwrap();
        assert_eq!(encoded.len(), length.serialized_len());
        let mut reader = buffered_reader::Memory::new(&encoded);
        SubpacketLength::parse(&mut reader).unwrap().len() == l as usize
    }
}

impl OnePassSig {
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(php: PacketHeaderParser<T>)
        -> Result<PacketParser<'a>>
    {
        OnePassSig3::parse(php)
    }
}

impl_parse_generic_packet!(OnePassSig);

impl OnePassSig3 {
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>)
        -> Result<PacketParser<'a>>
    {
        let indent = php.recursion_depth();
        tracer!(TRACE, "OnePassSig", indent);

        make_php_try!(php);

        let version = php_try!(php.parse_u8("version"));
        if version != 3 {
            t!("Ignoring version {} packet", version);

            // Unknown version.  Return an unknown packet.
            return php.fail("unknown version");
        }

        let typ = php_try!(php.parse_u8("type"));
        let hash_algo = php_try!(php.parse_u8("hash_algo"));
        let pk_algo = php_try!(php.parse_u8("pk_algo"));
        let mut issuer = [0u8; 8];
        issuer.copy_from_slice(&php_try!(php.parse_bytes("issuer", 8)));
        let last = php_try!(php.parse_u8("last"));

        let hash_algo = hash_algo.into();
        let typ = typ.into();
        let mut sig = OnePassSig3::new(typ);
        sig.set_hash_algo(hash_algo);
        sig.set_pk_algo(pk_algo.into());
        sig.set_issuer(KeyID::from_bytes(&issuer));
        sig.set_last_raw(last);
        let need_hash = HashingMode::for_signature(hash_algo, typ);

        let recursion_depth = php.recursion_depth();

        // Check if we are processing a cleartext signed message.
        let want_hashes_for = if Cookie::processing_csf_message(&php.reader) {
            HashesFor::CleartextSignature
        } else {
            HashesFor::Signature
        };

        // Walk up the reader chain to see if there is already a
        // hashed reader on level recursion_depth - 1.
        let done = {
            let mut done = false;
            let mut reader : Option<&mut dyn BufferedReader<Cookie>>
                = Some(&mut php.reader);
            while let Some(r) = reader {
                {
                    let cookie = r.cookie_mut();
                    if let Some(br_level) = cookie.level {
                        if br_level < recursion_depth - 1 {
                            break;
                        }
                        if br_level == recursion_depth - 1
                            && cookie.hashes_for == want_hashes_for {
                                // We found a suitable hashed reader.
                                if cookie.saw_last {
                                    cookie.sig_group_push();
                                    cookie.saw_last = false;
                                    cookie.hash_stash =
                                        Some(php.header_bytes.clone());
                                }

                                // Make sure that it uses the required
                                // hash algorithm.
                                if ! cookie.sig_group().hashes.iter()
                                    .any(|mode| {
                                        mode.map(|ctx| ctx.algo()) == need_hash
                                    })
                                {
                                    if let Ok(ctx) = hash_algo.context() {
                                        cookie.sig_group_mut().hashes.push(
                                            HashingMode::for_signature(Box::new(ctx), typ)
                                        );
                                    }
                                }

                                // Account for this OPS packet.
                                cookie.sig_group_mut().ops_count += 1;

                                // Keep track of the last flag.
                                cookie.saw_last = last > 0;

                                // We're done.
                                done = true;
                                break;
                            }
                    } else {
                        break;
                    }
                }
                reader = r.get_mut();
            }
            done
        };
        // Commit here after potentially pushing a signature group.
        let mut pp = php.ok(Packet::OnePassSig(sig.into()))?;
        if done {
            return Ok(pp);
        }

        // We create an empty hashed reader even if we don't support
        // the hash algorithm so that we have something to match
        // against when we get to the Signature packet.
        let mut algos = Vec::new();
        if hash_algo.is_supported() {
            algos.push(HashingMode::for_signature(hash_algo, typ));
        }

        // We can't push the HashedReader on the BufferedReader stack:
        // when we finish processing this OnePassSig packet, it will
        // be popped.  Instead, we need to insert it at the next
        // higher level.  Unfortunately, this isn't possible.  But,
        // since we're done reading the current packet, we can pop the
        // readers associated with it, and then push the HashedReader.
        // This is a bit of a layering violation, but I (Neal) can't
        // think of a more elegant solution.

        assert!(pp.reader.cookie_ref().level <= Some(recursion_depth));
        let (fake_eof, reader)
            = buffered_reader_stack_pop(Box::new(pp.take_reader()),
                                        recursion_depth)?;
        // We only pop the buffered readers for the OPS, and we
        // (currently) never use a fake eof for OPS packets.
        assert!(! fake_eof);

        let mut reader = HashedReader::new(
            reader, want_hashes_for, algos);
        reader.cookie_mut().level = Some(recursion_depth - 1);
        // Account for this OPS packet.
        reader.cookie_mut().sig_group_mut().ops_count += 1;
        // Keep track of the last flag.
        reader.cookie_mut().saw_last = last > 0;

        t!("Pushed a hashed reader, level {:?}", reader.cookie_mut().level);

        // We add an empty limitor on top of the hashed reader,
        // because when we are done processing a packet,
        // PacketParser::finish discards any unread data from the top
        // reader.  Since the top reader is the HashedReader, this
        // discards any following packets.  To prevent this, we push a
        // Limitor on the reader stack.
        let mut reader = buffered_reader::Limitor::with_cookie(
            reader, 0, Cookie::default());
        reader.cookie_mut().level = Some(recursion_depth);

        pp.reader = Box::new(reader);

        Ok(pp)
    }
}

#[test]
fn one_pass_sig_parser_test () {
    use crate::SignatureType;
    use crate::PublicKeyAlgorithm;

    // This test assumes that the first packet is a OnePassSig packet.
    let data = crate::tests::message("signed-1.gpg");
    let mut pp = PacketParser::from_bytes(data).unwrap().unwrap();
    let p = pp.finish().unwrap();
    // eprintln!("packet: {:?}", p);

    if let &Packet::OnePassSig(ref p) = p {
        assert_eq!(p.version(), 3);
        assert_eq!(p.typ(), SignatureType::Binary);
        assert_eq!(p.hash_algo(), HashAlgorithm::SHA512);
        assert_eq!(p.pk_algo(), PublicKeyAlgorithm::RSAEncryptSign);
        assert_eq!(format!("{:X}", p.issuer()), "7223B56678E02528");
        assert_eq!(p.last_raw(), 1);
    } else {
        panic!("Wrong packet!");
    }
}

impl<'a> Parse<'a, OnePassSig3> for OnePassSig3 {
    fn from_reader<R: 'a + Read + Send + Sync>(reader: R) -> Result<Self> {
        OnePassSig::from_reader(reader).and_then(|p| match p {
            OnePassSig::V3(p) => Ok(p),
            // XXX: Once we have a second variant.
            //
            // p => Err(Error::InvalidOperation(
            //     format!("Not a OnePassSig::V3 packet: {:?}", p)).into()),
        })
    }
}

#[test]
fn one_pass_sig_test () {
    struct Test<'a> {
        filename: &'a str,
        digest_prefix: Vec<[u8; 2]>,
    };

    let tests = [
            Test {
                filename: "signed-1.gpg",
                digest_prefix: vec![ [ 0x83, 0xF5 ] ],
            },
            Test {
                filename: "signed-2-partial-body.gpg",
                digest_prefix: vec![ [ 0x2F, 0xBE ] ],
            },
            Test {
                filename: "signed-3-partial-body-multiple-sigs.gpg",
                digest_prefix: vec![ [ 0x29, 0x64 ], [ 0xff, 0x7d ] ],
            },
    ];

    for test in tests.iter() {
        eprintln!("Trying {}...", test.filename);
        let mut ppr = PacketParserBuilder::from_bytes(
            crate::tests::message(test.filename))
            .expect(&format!("Reading {}", test.filename)[..])
            .build().unwrap();

        let mut one_pass_sigs = 0;
        let mut sigs = 0;

        while let PacketParserResult::Some(pp) = ppr {
            if let Packet::OnePassSig(_) = pp.packet {
                one_pass_sigs += 1;
            } else if let Packet::Signature(ref sig) = pp.packet {
                eprintln!("  {}:\n  prefix: expected: {}, in sig: {}",
                          test.filename,
                          crate::fmt::to_hex(&test.digest_prefix[sigs][..], false),
                          crate::fmt::to_hex(sig.digest_prefix(), false));
                eprintln!("  computed hash: {}",
                          crate::fmt::to_hex(&sig.computed_digest().unwrap(),
                                             false));

                assert_eq!(&test.digest_prefix[sigs], sig.digest_prefix());
                assert_eq!(&test.digest_prefix[sigs][..],
                           &sig.computed_digest().unwrap()[..2]);

                sigs += 1;
            } else if one_pass_sigs > 0 {
                assert_eq!(one_pass_sigs, test.digest_prefix.len(),
                           "Number of OnePassSig packets does not match \
                            number of expected OnePassSig packets.");
            }

            ppr = pp.recurse().expect("Parsing message").1;
        }
        assert_eq!(one_pass_sigs, sigs,
                   "Number of OnePassSig packets does not match \
                    number of signature packets.");

        eprintln!("done.");
    }
}

// Key::parse doesn't actually use the Key type parameters.  So, we
// can just set them to anything.  This avoids the caller having to
// set them to something.
impl Key<key::UnspecifiedParts, key::UnspecifiedRole>
{
    /// Parses the body of a public key, public subkey, secret key or
    /// secret subkey packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        make_php_try!(php);
        let tag = php.header.ctb().tag();
        assert!(tag == Tag::Reserved
                || tag == Tag::PublicKey
                || tag == Tag::PublicSubkey
                || tag == Tag::SecretKey
                || tag == Tag::SecretSubkey);
        let version = php_try!(php.parse_u8("version"));

        match version {
            4 => Key4::parse(php),
            _ => php.fail("unknown version"),
        }
    }

    /// Returns whether the data appears to be a key (no promises).
    fn plausible<T: BufferedReader<Cookie>>(
        bio: &mut buffered_reader::Dup<T, Cookie>, header: &Header)
                 -> Result<()> {
        Key4::plausible(bio, header)
    }
}

// Key4::parse doesn't actually use the Key4 type parameters.  So, we
// can just set them to anything.  This avoids the caller having to
// set them to something.
impl Key4<key::UnspecifiedParts, key::UnspecifiedRole>
{
    /// Parses the body of a public key, public subkey, secret key or
    /// secret subkey packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        make_php_try!(php);
        let tag = php.header.ctb().tag();
        assert!(tag == Tag::Reserved
                || tag == Tag::PublicKey
                || tag == Tag::PublicSubkey
                || tag == Tag::SecretKey
                || tag == Tag::SecretSubkey);

        let creation_time = php_try!(php.parse_be_u32("creation_time"));
        let pk_algo: PublicKeyAlgorithm = php_try!(php.parse_u8("pk_algo")).into();
        let mpis = php_try!(PublicKey::_parse(pk_algo, &mut php));
        let secret = if let Ok(s2k_usage) = php.parse_u8("s2k_usage") {
            use crypto::mpi;
            let sec = match s2k_usage {
                // Unencrypted
                0 => {
                    let sec = php_try!(
                        mpi::SecretKeyMaterial::_parse(
                            pk_algo, &mut php,
                            Some(mpi::SecretKeyChecksum::Sum16)));
                    sec.into()
                }
                // Encrypted & MD5 for key derivation: unsupported
                1..=253 => {
                    return php.fail("unsupported secret key encryption");
                }
                // Encrypted, S2K & SHA-1 checksum
                254 | 255 => {
                    let sk: SymmetricAlgorithm = php_try!(php.parse_u8("sym_algo")).into();
                    let s2k = php_try!(S2K::parse(&mut php));
                    let s2k_supported = s2k.is_supported();
                    let cipher =
                        php_try!(php.parse_bytes_eof("encrypted_mpis"))
                        .into_boxed_slice();

                    crate::packet::key::Encrypted::new_raw(
                        s2k, sk,
                        if s2k_usage == 254 {
                            Some(mpi::SecretKeyChecksum::SHA1)
                        } else {
                            Some(mpi::SecretKeyChecksum::Sum16)
                        },
                        if s2k_supported {
                            Ok(cipher)
                        } else {
                            Err(cipher)
                        },
                    ).into()
                }
            };

            Some(sec)
        } else {
            None
        };

        let have_secret = secret.is_some();
        if have_secret {
            if tag == Tag::PublicKey || tag == Tag::PublicSubkey {
                return php.error(Error::MalformedPacket(
                    format!("Unexpected secret key found in {:?} packet", tag)
                ).into());
            }
        } else {
            if tag == Tag::SecretKey || tag == Tag::SecretSubkey {
                return php.error(Error::MalformedPacket(
                    format!("Expected secret key in {:?} packet", tag)
                ).into());
            }
        }

        fn k<R>(creation_time: u32,
                pk_algo: PublicKeyAlgorithm,
                mpis: PublicKey)
            -> Result<Key4<key::PublicParts, R>>
            where R: key::KeyRole
        {
            Key4::new(Timestamp::from(creation_time),
                      pk_algo, mpis)
        }
        fn s<R>(creation_time: u32,
                pk_algo: PublicKeyAlgorithm,
                mpis: PublicKey,
                secret: SecretKeyMaterial)
            -> Result<Key4<key::SecretParts, R>>
            where R: key::KeyRole
        {
            Key4::with_secret(Timestamp::from(creation_time),
                              pk_algo, mpis, secret)
        }

        let tag = php.header.ctb().tag();

        let p : Packet = match tag {
            // For the benefit of Key::from_bytes.
            Tag::Reserved => if have_secret {
                Packet::SecretKey(
                    php_try!(s(creation_time, pk_algo, mpis, secret.unwrap()))
                        .into())
            } else {
                Packet::PublicKey(
                    php_try!(k(creation_time, pk_algo, mpis)).into())
            },
            Tag::PublicKey => Packet::PublicKey(
                php_try!(k(creation_time, pk_algo, mpis)).into()),
            Tag::PublicSubkey => Packet::PublicSubkey(
                php_try!(k(creation_time, pk_algo, mpis)).into()),
            Tag::SecretKey => Packet::SecretKey(
                php_try!(s(creation_time, pk_algo, mpis, secret.unwrap()))
                    .into()),
            Tag::SecretSubkey => Packet::SecretSubkey(
                php_try!(s(creation_time, pk_algo, mpis, secret.unwrap()))
                    .into()),
            _ => unreachable!(),
        };

        php.ok(p)
    }

    /// Returns whether the data appears to be a key (no promises).
    fn plausible<T: BufferedReader<Cookie>>(
        bio: &mut buffered_reader::Dup<T, Cookie>, header: &Header)
                 -> Result<()> {
        // The packet's header is 6 bytes.
        if let &BodyLength::Full(len) = header.length() {
            if len < 6 {
                // Much too short.
                return Err(Error::MalformedPacket(
                    format!("Packet too short ({} bytes)", len).into()).into());
            }
        } else {
            return Err(
                Error::MalformedPacket(
                    format!("Unexpected body length encoding: {:?}",
                            header.length())
                        .into()).into());
        }

        // Make sure we have a minimum header.
        let data = bio.data(6)?;
        if data.len() < 6 {
            return Err(
                Error::MalformedPacket("Short read".into()).into());
        }

        // Assume unknown == bad.
        let version = data[0];
        let pk_algo : PublicKeyAlgorithm = data[5].into();

        if version == 4 && !matches!(pk_algo, PublicKeyAlgorithm::Unknown(_)) {
            Ok(())
        } else {
            Err(Error::MalformedPacket("Invalid or unsupported data".into())
                .into())
        }
    }
}

impl<'a> Parse<'a, key::UnspecifiedKey> for key::UnspecifiedKey {
    fn from_reader<R: 'a + Read + Send + Sync>(reader: R) -> Result<Self> {
        let bio = buffered_reader::Generic::with_cookie(
            reader, None, Cookie::default());
        let parser = PacketHeaderParser::new_naked(bio);

        let mut pp = Self::parse(parser)?;
        pp.buffer_unread_content()?;

        match pp.next()? {
            (Packet::PublicKey(o), PacketParserResult::EOF(_)) => Ok(o.into()),
            (Packet::PublicSubkey(o), PacketParserResult::EOF(_)) => Ok(o.into()),
            (Packet::SecretKey(o), PacketParserResult::EOF(_)) => Ok(o.into()),
            (Packet::SecretSubkey(o), PacketParserResult::EOF(_)) => Ok(o.into()),
            (p, PacketParserResult::EOF(_)) =>
                Err(Error::InvalidOperation(
                    format!("Not a Key packet: {:?}", p)).into()),
            (_, PacketParserResult::Some(_)) =>
                Err(Error::InvalidOperation(
                    "Excess data after packet".into()).into()),
        }
    }
}

impl Trust {
    /// Parses the body of a trust packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        make_php_try!(php);
        let value = php_try!(php.parse_bytes_eof("value"));
        php.ok(Packet::Trust(Trust::from(value)))
    }
}

impl_parse_generic_packet!(Trust);

impl UserID {
    /// Parses the body of a user id packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        make_php_try!(php);

        let value = php_try!(php.parse_bytes_eof("value"));

        php.ok(Packet::UserID(UserID::from(value)))
    }
}

impl_parse_generic_packet!(UserID);

impl UserAttribute {
    /// Parses the body of a user attribute packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        make_php_try!(php);

        let value = php_try!(php.parse_bytes_eof("value"));

        php.ok(Packet::UserAttribute(UserAttribute::from(value)))
    }
}

impl_parse_generic_packet!(UserAttribute);

impl Marker {
    /// Parses the body of a marker packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>>
    {
        make_php_try!(php);
        let marker = php_try!(php.parse_bytes("marker", Marker::BODY.len()));
        if &marker[..] == Marker::BODY {
            php.ok(Marker::default().into())
        } else {
            php.fail("invalid marker")
        }
    }

    /// Returns whether the data is a marker packet.
    fn plausible<T>(bio: &mut buffered_reader::Dup<T, Cookie>, header: &Header)
                    -> Result<()>
        where T: BufferedReader<Cookie>,
    {
        if let &BodyLength::Full(len) = header.length() {
            if len as usize != Marker::BODY.len() {
                return Err(Error::MalformedPacket(
                    format!("Unexpected packet length {}", len)).into());
            }
        } else {
            return Err(Error::MalformedPacket(
                format!("Unexpected body length encoding: {:?}",
                        header.length()).into()).into());
        }

        // Check the body.
        let data = bio.data(Marker::BODY.len())?;
        if data.len() < Marker::BODY.len() {
            return Err(Error::MalformedPacket("Short read".into()).into());
        }

        if data == Marker::BODY {
            Ok(())
        } else {
            Err(Error::MalformedPacket("Invalid or unsupported data".into())
                .into())
        }
    }
}

impl_parse_generic_packet!(Marker);

impl Literal {
    /// Parses the body of a literal packet.
    ///
    /// Condition: Hashing has been disabled by the callee.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>>
    {
        make_php_try!(php);

        // Directly hashing a literal data packet is... strange.
        // Neither the packet's header, the packet's meta-data nor the
        // length encoding information is included in the hash.

        let format = php_try!(php.parse_u8("format"));
        let filename_len = php_try!(php.parse_u8("filename_len"));

        let filename = if filename_len > 0 {
            Some(php_try!(php.parse_bytes("filename", filename_len as usize)))
        } else {
            None
        };

        let date = php_try!(php.parse_be_u32("date"));

        // The header is consumed while hashing is disabled.
        let recursion_depth = php.recursion_depth();

        let mut literal = Literal::new(format.into());
        if let Some(filename) = filename {
            literal.set_filename(&filename)
                .expect("length checked above");
        }
        literal.set_date(
            Some(std::time::SystemTime::from(Timestamp::from(date))))?;
        let mut pp = php.ok(Packet::Literal(literal))?;

        // Enable hashing of the body.
        Cookie::hashing(pp.mut_reader(), Hashing::Enabled,
                        recursion_depth - 1);

        Ok(pp)
    }
}

impl_parse_generic_packet!(Literal);

#[test]
fn literal_parser_test () {
    use crate::types::DataFormat;
    {
        let data = crate::tests::message("literal-mode-b.gpg");
        let mut pp = PacketParser::from_bytes(data).unwrap().unwrap();
        assert_eq!(pp.header.length(), &BodyLength::Full(18));
        let content = pp.steal_eof().unwrap();
        let p = pp.finish().unwrap();
        // eprintln!("{:?}", p);
        if let &Packet::Literal(ref p) = p {
            assert_eq!(p.format(), DataFormat::Binary);
            assert_eq!(p.filename().unwrap()[..], b"foobar"[..]);
            assert_eq!(p.date().unwrap(), Timestamp::from(1507458744).into());
            assert_eq!(content, b"FOOBAR");
        } else {
            panic!("Wrong packet!");
        }
    }

    {
        let data = crate::tests::message("literal-mode-t-partial-body.gpg");
        let mut pp = PacketParser::from_bytes(data).unwrap().unwrap();
        assert_eq!(pp.header.length(), &BodyLength::Partial(4096));
        let content = pp.steal_eof().unwrap();
        let p = pp.finish().unwrap();
        if let &Packet::Literal(ref p) = p {
            assert_eq!(p.format(), DataFormat::Text);
            assert_eq!(p.filename().unwrap()[..],
                       b"manifesto.txt"[..]);
            assert_eq!(p.date().unwrap(), Timestamp::from(1508000649).into());

            let expected = crate::tests::manifesto();

            assert_eq!(&content[..], &expected[..]);
        } else {
            panic!("Wrong packet!");
        }
    }
}

impl CompressedData {
    /// Parses the body of a compressed data packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        let recursion_depth = php.recursion_depth();
        tracer!(TRACE, "CompressedData::parse", recursion_depth);

        make_php_try!(php);
        let algo: CompressionAlgorithm =
            php_try!(php.parse_u8("algo")).into();

        #[allow(unreachable_patterns)]
        match algo {
            CompressionAlgorithm::Uncompressed => (),
            #[cfg(feature = "compression-deflate")]
            CompressionAlgorithm::Zip
                | CompressionAlgorithm::Zlib => (),
            #[cfg(feature = "compression-bzip2")]
            CompressionAlgorithm::BZip2 => (),
            CompressionAlgorithm::Unknown(_)
            | CompressionAlgorithm::Private(_) =>
                return php.fail("unknown compression algorithm"),
            _ =>
                return php.fail("unsupported compression algorithm"),
        }

        let recursion_depth = php.recursion_depth();
        let mut pp = php.ok(Packet::CompressedData(CompressedData::new(algo)))?;

        t!("Pushing a decompressor for {}, recursion depth = {:?}.",
           algo, recursion_depth);

        let reader = pp.take_reader();
        let reader = match algo {
            CompressionAlgorithm::Uncompressed => {
                if TRACE {
                    eprintln!("CompressedData::parse(): Actually, no need \
                               for a compression filter: this is an \
                               \"uncompressed compression packet\".");
                }
                let _ = recursion_depth;
                reader
            },
            #[cfg(feature = "compression-deflate")]
            CompressionAlgorithm::Zip =>
                Box::new(buffered_reader::Deflate::with_cookie(
                    reader, Cookie::new(recursion_depth))),
            #[cfg(feature = "compression-deflate")]
            CompressionAlgorithm::Zlib =>
                Box::new(buffered_reader::Zlib::with_cookie(
                    reader, Cookie::new(recursion_depth))),
            #[cfg(feature = "compression-bzip2")]
            CompressionAlgorithm::BZip2 =>
                Box::new(buffered_reader::Bzip::with_cookie(
                    reader, Cookie::new(recursion_depth))),
            _ => unreachable!(), // Validated above.
        };
        pp.set_reader(reader);

        Ok(pp)
    }
}

impl_parse_generic_packet!(CompressedData);

#[cfg(any(feature = "compression-deflate", feature = "compression-bzip2"))]
#[test]
fn compressed_data_parser_test () {
    use crate::types::DataFormat;

    let expected = crate::tests::manifesto();

    for i in 1..4 {
        match CompressionAlgorithm::from(i) {
            #[cfg(feature = "compression-deflate")]
            CompressionAlgorithm::Zip | CompressionAlgorithm::Zlib => (),
            #[cfg(feature = "compression-bzip2")]
            CompressionAlgorithm::BZip2 => (),
            _ => continue,
        }
        let pp = PacketParser::from_bytes(crate::tests::message(
            &format!("compressed-data-algo-{}.gpg", i))).unwrap().unwrap();

        // We expect a compressed packet containing a literal data
        // packet, and that is it.
        if let Packet::CompressedData(ref compressed) = pp.packet {
            assert_eq!(compressed.algo(), i.into());
        } else {
            panic!("Wrong packet!");
        }

        let ppr = pp.recurse().unwrap().1;

        // ppr should be the literal data packet.
        let mut pp = ppr.unwrap();

        // It is a child.
        assert_eq!(pp.recursion_depth(), 1);

        let content = pp.steal_eof().unwrap();

        let (literal, ppr) = pp.recurse().unwrap();

        if let Packet::Literal(literal) = literal {
            assert_eq!(literal.filename(), None);
            assert_eq!(literal.format(), DataFormat::Binary);
            assert_eq!(literal.date().unwrap(),
                       Timestamp::from(1509219866).into());
            assert_eq!(content, expected.to_vec());
        } else {
            panic!("Wrong packet!");
        }

        // And, we're done...
        assert!(ppr.is_eof());
    }
}

impl SKESK {
    /// Parses the body of an SK-ESK packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        make_php_try!(php);
        let version = php_try!(php.parse_u8("version"));
        let skesk = match version {
            4 => {
                let sym_algo = php_try!(php.parse_u8("sym_algo"));
                let s2k = php_try!(S2K::parse(&mut php));
                let s2k_supported = s2k.is_supported();
                let esk = php_try!(php.parse_bytes_eof("esk"));

                SKESK::V4(php_try!(SKESK4::new_raw(
                    sym_algo.into(),
                    s2k,
                    if s2k_supported || esk.is_empty() {
                        Ok(if ! esk.is_empty() {
                            Some(esk.into())
                        } else {
                            None
                        })
                    } else {
                        Err(esk.into())
                    },
                )))
            },

            5 => {
                let sym_algo: SymmetricAlgorithm =
                    php_try!(php.parse_u8("sym_algo")).into();
                let aead_algo: AEADAlgorithm =
                    php_try!(php.parse_u8("aead_algo")).into();
                let s2k = php_try!(S2K::parse(&mut php));
                let s2k_supported = s2k.is_supported();
                let iv_size = php_try!(aead_algo.iv_size());
                let digest_size = php_try!(aead_algo.digest_size());

                // The rest of the packet is (potentially) the S2K
                // parameters, the AEAD IV, the ESK, and the AEAD
                // digest.  We don't know the size of the S2K
                // parameters if the S2K method is not supported, and
                // we don't know the size of the ESK.
                let mut esk = php_try!(php.reader.steal_eof()
                                       .map_err(|e| anyhow::Error::from(e)));
                let aead_iv = if s2k_supported && esk.len() >= iv_size {
                    // We know the S2K method, so the parameters have
                    // been parsed into the S2K object.  So, `esk`
                    // starts with iv_size bytes of IV.
                    let mut iv = esk;
                    esk = iv.split_off(iv_size);
                    iv
                } else {
                    Vec::with_capacity(0) // A dummy value.
                };

                let l = esk.len();
                let aead_digest = esk.split_off(l.saturating_sub(digest_size));
                // Now fix the map.
                if s2k_supported {
                    php.field("aead_iv", iv_size);
                }
                php.field("esk", esk.len());
                php.field("aead_digest", aead_digest.len());

                SKESK::V5(php_try!(SKESK5::new_raw(
                    sym_algo,
                    aead_algo,
                    s2k,
                    if s2k_supported {
                        Ok((aead_iv.into(), esk.into()))
                    } else {
                        Err(esk.into())
                    },
                    aead_digest.into_boxed_slice(),
                )))
            },

            _ => {
                // We only support version 4 and 5 SKESK packets.
                return php.fail("unknown version");
            }
        };

        php.ok(Packet::SKESK(skesk))
    }
}

impl_parse_generic_packet!(SKESK);

#[test]
fn skesk_parser_test() {
    use crate::crypto::Password;
    struct Test<'a> {
        filename: &'a str,
        s2k: S2K,
        cipher_algo: SymmetricAlgorithm,
        password: Password,
        key_hex: &'a str,
    };

    let tests = [
        Test {
            filename: "s2k/mode-3-encrypted-key-password-bgtyhn.gpg",
            cipher_algo: SymmetricAlgorithm::AES128,
            s2k: S2K::Iterated {
                hash: HashAlgorithm::SHA1,
                salt: [0x82, 0x59, 0xa0, 0x6e, 0x98, 0xda, 0x94, 0x1c],
                hash_bytes: S2K::decode_count(238),
            },
            password: "bgtyhn".into(),
            key_hex: "474E5C373BA18AF0A499FCAFE6093F131DF636F6A3812B9A8AE707F1F0214AE9",
        },
    ];

    for test in tests.iter() {
        let pp = PacketParser::from_bytes(
            crate::tests::message(test.filename)).unwrap().unwrap();
        if let Packet::SKESK(SKESK::V4(ref skesk)) = pp.packet {
            eprintln!("{:?}", skesk);

            assert_eq!(skesk.symmetric_algo(), test.cipher_algo);
            assert_eq!(skesk.s2k(), &test.s2k);

            match skesk.decrypt(&test.password) {
                Ok((_sym_algo, key)) => {
                    let key = crate::fmt::to_hex(&key[..], false);
                    assert_eq!(&key[..], &test.key_hex[..]);
                }
                Err(e) => {
                    panic!("No session key, got: {:?}", e);
                }
            }
        } else {
            panic!("Wrong packet!");
        }
    }
}

impl SEIP {
    /// Parses the body of a SEIP packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        make_php_try!(php);
        let version = php_try!(php.parse_u8("version"));
        if version != 1 {
            return php.fail("unknown version");
        }

        php.ok(SEIP1::new().into())
            .map(|pp| pp.set_encrypted(true))
    }
}

impl_parse_generic_packet!(SEIP);

impl MDC {
    /// Parses the body of an MDC packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        make_php_try!(php);

        // Find the HashedReader pushed by the containing SEIP packet.
        // In a well-formed message, this will be the outer most
        // HashedReader on the BufferedReader stack: we pushed it
        // there when we started decrypting the SEIP packet, and an
        // MDC packet is the last packet in a SEIP container.
        // Nevertheless, we take some basic precautions to check
        // whether it is really the matching HashedReader.

        let mut computed_digest : [u8; 20] = Default::default();
        {
            let mut r : Option<&mut dyn BufferedReader<Cookie>>
                = Some(&mut php.reader);
            while let Some(bio) = r {
                {
                    let state = bio.cookie_mut();
                    if state.hashes_for == HashesFor::MDC {
                        if state.sig_group().hashes.len() > 0 {
                            let h = state.sig_group_mut().hashes
                                .iter_mut().find_map(
                                    |mode|
                                    if mode.map(|ctx| ctx.algo()) ==
                                        HashingMode::Binary(HashAlgorithm::SHA1)
                                    {
                                        Some(mode.as_mut())
                                    } else {
                                        None
                                    }).unwrap();
                            let _ = h.digest(&mut computed_digest);
                        }

                        // If the outer most HashedReader is not the
                        // matching HashedReader, then the message is
                        // malformed.
                        break;
                    }
                }

                r = bio.get_mut();
            }
        }

        let mut digest: [u8; 20] = Default::default();
        digest.copy_from_slice(&php_try!(php.parse_bytes("digest", 20)));

        php.ok(Packet::MDC(MDC::new(digest, computed_digest)))
    }
}

impl_parse_generic_packet!(MDC);

impl AED {
    /// Parses the body of a AED packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        make_php_try!(php);
        let version = php_try!(php.parse_u8("version"));

        match version {
            1 => AED1::parse(php),
            _ => php.fail("unknown version"),
        }
    }
}

impl_parse_generic_packet!(AED);

impl AED1 {
    /// Parses the body of a AED packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        make_php_try!(php);
        let cipher: SymmetricAlgorithm =
            php_try!(php.parse_u8("sym_algo")).into();
        let aead: AEADAlgorithm =
            php_try!(php.parse_u8("aead_algo")).into();
        let chunk_size = php_try!(php.parse_u8("chunk_size"));

        // DRAFT 4880bis-08, section 5.16: "An implementation MUST
        // support chunk size octets with values from 0 to 56.  Chunk
        // size octets with other values are reserved for future
        // extensions."
        if chunk_size > 56 {
            return php.fail("unsupported chunk size");
        }
        let chunk_size: u64 = 1 << (chunk_size + 6);

        let iv_size = php_try!(aead.iv_size());
        let iv = php_try!(php.parse_bytes("iv", iv_size));

        let aed = php_try!(Self::new(
            cipher, aead, chunk_size, iv.into_boxed_slice()
        ));
        php.ok(aed.into()).map(|pp| pp.set_encrypted(true))
    }
}

impl MPI {
    /// Parses an OpenPGP MPI.
    ///
    /// See [Section 3.2 of RFC 4880] for details.
    ///
    ///   [Section 3.2 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-3.2
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(
        name_len: &'static str,
        name: &'static str,
        php: &mut PacketHeaderParser<T>)
                 -> Result<Self> {
        // This function is used to parse MPIs from unknown
        // algorithms, which may use an encoding unknown to us.
        // Therefore, we need to be extra careful only to consume the
        // data once we found a well-formed MPI.
        let bits = {
            let buf = php.reader.data_hard(2)?;
            u16::from_be_bytes([buf[0], buf[1]]) as usize
        };
        if bits == 0 {
            // Now consume the data.
            php.parse_be_u16(name_len).expect("worked before");
            return Ok(vec![].into());
        }

        let bytes = (bits + 7) / 8;
        let value = {
            let buf = php.reader.data_hard(2 + bytes)?;
            Vec::from(&buf[2..2 + bytes])
        };

        let unused_bits = bytes * 8 - bits;
        assert_eq!(bytes * 8 - unused_bits, bits);

        // Make sure the unused bits are zeroed.
        if unused_bits > 0 {
            let mask = !((1 << (8 - unused_bits)) - 1);
            let unused_value = value[0] & mask;

            if unused_value != 0 {
                return Err(Error::MalformedMPI(
                        format!("{} unused bits not zeroed: ({:x})",
                        unused_bits, unused_value)).into());
            }
        }

        let first_used_bit = 8 - unused_bits;
        if value[0] & (1 << (first_used_bit - 1)) == 0 {
            return Err(Error::MalformedMPI(
                    format!("leading bit is not set: \
                             expected bit {} to be set in {:8b} ({:x})",
                             first_used_bit, value[0], value[0])).into());
        }

        // Now consume the data.
        php.parse_be_u16(name_len).expect("worked before");
        php.parse_bytes(name, bytes).expect("worked before");
        Ok(value.into())
    }
}

impl<'a> Parse<'a, MPI> for MPI {
    // Reads an MPI from `reader`.
    fn from_reader<R: io::Read + Send + Sync>(reader: R) -> Result<Self> {
        let bio = buffered_reader::Generic::with_cookie(
            reader, None, Cookie::default());
        let mut parser = PacketHeaderParser::new_naked(bio);
        Self::parse("(none_len)", "(none)", &mut parser)
    }
}

impl PKESK {
    /// Parses the body of an PK-ESK packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        make_php_try!(php);
        let version = php_try!(php.parse_u8("version"));
        match version {
            3 => PKESK3::parse(php),
            _ => php.fail("unknown version"),
        }
    }
}

impl_parse_generic_packet!(PKESK);

impl PKESK3 {
    /// Parses the body of an PK-ESK packet.
    fn parse<'a, T: 'a + BufferedReader<Cookie>>(mut php: PacketHeaderParser<T>) -> Result<PacketParser<'a>> {
        make_php_try!(php);
        let mut keyid = [0u8; 8];
        keyid.copy_from_slice(&php_try!(php.parse_bytes("keyid", 8)));
        let pk_algo: PublicKeyAlgorithm = php_try!(php.parse_u8("pk_algo")).into();
        if ! pk_algo.for_encryption() {
            return php.fail("not an encryption algorithm");
        }
        let mpis = crypto::mpi::Ciphertext::_parse(pk_algo, &mut php)?;

        let pkesk = php_try!(PKESK3::new(KeyID::from_bytes(&keyid),
                                         pk_algo, mpis));
        php.ok(pkesk.into())
    }
}

impl<'a> Parse<'a, PKESK3> for PKESK3 {
    fn from_reader<R: 'a + Read + Send + Sync>(reader: R) -> Result<Self> {
        PKESK::from_reader(reader).and_then(|p| match p {
            PKESK::V3(p) => Ok(p),
            // XXX: Once we have a second variant.
            //
            // p => Err(Error::InvalidOperation(
            //     format!("Not a PKESKv3 packet: {:?}", p)).into()),
        })
    }
}

impl<'a> Parse<'a, Packet> for Packet {
    fn from_reader<R: 'a + Read + Send + Sync>(reader: R) -> Result<Self> {
        let ppr =
            PacketParserBuilder::from_reader(reader)
            ?.buffer_unread_content().build()?;

        let (p, ppr) = match ppr {
            PacketParserResult::Some(pp) => {
                pp.next()?
            },
            PacketParserResult::EOF(_) =>
                return Err(Error::InvalidOperation(
                    "Unexpected EOF".into()).into()),
        };

        match (p, ppr) {
            (p, PacketParserResult::EOF(_)) =>
                Ok(p),
            (_, PacketParserResult::Some(_)) =>
                Err(Error::InvalidOperation(
                    "Excess data after packet".into()).into()),
        }
    }
}

// State that lives for the life of the packet parser, not the life of
// an individual packet.
#[derive(Debug)]
struct PacketParserState {
    // The `PacketParser`'s settings
    settings: PacketParserSettings,

    /// Whether the packet sequence is a valid OpenPGP Message.
    message_validator: MessageValidator,

    /// Whether the packet sequence is a valid OpenPGP keyring.
    keyring_validator: KeyringValidator,

    /// Whether the packet sequence is a valid OpenPGP Cert.
    cert_validator: CertValidator,

    // Whether this is the first packet in the packet sequence.
    first_packet: bool,
}

impl PacketParserState {
    fn new(settings: PacketParserSettings) -> Self {
        PacketParserState {
            settings: settings,
            message_validator: Default::default(),
            keyring_validator: Default::default(),
            cert_validator: Default::default(),
            first_packet: true,
        }
    }
}

/// A low-level OpenPGP message parser.
///
/// A `PacketParser` provides a low-level, iterator-like interface to
/// parse OpenPGP messages.
///
/// For each iteration, the user is presented with a [`Packet`]
/// corresponding to the last packet, a `PacketParser` for the next
/// packet, and their positions within the message.
///
/// Using the `PacketParser`, the user is able to configure how the
/// new packet will be parsed.  For instance, it is possible to stream
/// the packet's contents (a `PacketParser` implements the
/// [`std::io::Read`] and the [`BufferedReader`] traits), buffer them
/// within the [`Packet`], or drop them.  The user can also decide to
/// recurse into the packet, if it is a container, instead of getting
/// the following packet.
///
/// See the [`PacketParser::next`] and [`PacketParser::recurse`]
/// methods for more details.
///
///   [`Packet`]: ../enum.Packet.html
///   [`std::io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
///   [`BufferedReader`]: https://docs.rs/buffered-reader/*/buffered_reader/trait.BufferedReader.html
///   [`PacketParser::next`]: #method.next
///   [`PacketParser::recurse`]: #method.recurse
///
/// # Examples
///
/// These examples demonstrate how to process packet bodies by parsing
/// the simplest possible OpenPGP message containing just a single
/// literal data packet with the body "Hello world.".  There are three
/// options.  First, the body can be dropped.  Second, it can be
/// buffered.  Lastly, the body can be streamed.  In general,
/// streaming should be preferred, because it avoids buffering in
/// Sequoia.
///
/// This example demonstrates simply ignoring the packet body:
///
/// ```rust
/// # fn main() -> sequoia_openpgp::Result<()> {
/// use sequoia_openpgp as openpgp;
/// use openpgp::Packet;
/// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
///
/// // By default, the `PacketParser` will drop packet bodies.
/// let mut ppr =
///     PacketParser::from_bytes(b"\xcb\x12b\x00\x00\x00\x00\x00Hello world.")?;
/// while let PacketParserResult::Some(pp) = ppr {
///     // Get the packet out of the parser and start parsing the next
///     // packet, recursing.
///     let (packet, next_ppr) = pp.recurse()?;
///     ppr = next_ppr;
///
///     // Process the packet.
///     if let Packet::Literal(literal) = packet {
///         // The body was dropped.
///         assert_eq!(literal.body(), b"");
///     } else {
///         unreachable!("We know it is a literal packet.");
///     }
/// }
/// # Ok(()) }
/// ```
///
/// This example demonstrates how the body can be buffered by
/// configuring the `PacketParser` to buffer all packet bodies:
///
/// ```rust
/// # fn main() -> sequoia_openpgp::Result<()> {
/// use sequoia_openpgp as openpgp;
/// use openpgp::Packet;
/// use openpgp::parse::{Parse, PacketParserResult, PacketParserBuilder};
///
/// // By default, the `PacketParser` will drop packet bodies.  Use a
/// // `PacketParserBuilder` to change that.
/// let mut ppr =
///     PacketParserBuilder::from_bytes(
///         b"\xcb\x12b\x00\x00\x00\x00\x00Hello world.")?
///     .buffer_unread_content()
///     .build()?;
/// while let PacketParserResult::Some(pp) = ppr {
///     // Get the packet out of the parser and start parsing the next
///     // packet, recursing.
///     let (packet, next_ppr) = pp.recurse()?;
///     ppr = next_ppr;
///
///     // Process the packet.
///     if let Packet::Literal(literal) = packet {
///         // The body was buffered.
///         assert_eq!(literal.body(), b"Hello world.");
///     } else {
///         unreachable!("We know it is a literal packet.");
///     }
/// }
/// # Ok(()) }
/// ```
///
/// This example demonstrates how the body can be buffered by
/// buffering an individual packet:
///
/// ```rust
/// # fn main() -> sequoia_openpgp::Result<()> {
/// use sequoia_openpgp as openpgp;
/// use openpgp::Packet;
/// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
///
/// // By default, the `PacketParser` will drop packet bodies.
/// let mut ppr =
///     PacketParser::from_bytes(b"\xcb\x12b\x00\x00\x00\x00\x00Hello world.")?;
/// while let PacketParserResult::Some(mut pp) = ppr {
///     if let Packet::Literal(_) = pp.packet {
///         // Buffer this packet's body.
///         pp.buffer_unread_content()?;
///     }
///
///     // Get the packet out of the parser and start parsing the next
///     // packet, recursing.
///     let (packet, next_ppr) = pp.recurse()?;
///     ppr = next_ppr;
///
///     // Process the packet.
///     if let Packet::Literal(literal) = packet {
///         // The body was buffered.
///         assert_eq!(literal.body(), b"Hello world.");
///     } else {
///         unreachable!("We know it is a literal packet.");
///     }
/// }
/// # Ok(()) }
/// ```
///
/// This example demonstrates how to stream the packet body:
///
/// ```rust
/// # fn main() -> sequoia_openpgp::Result<()> {
/// use std::io::Read;
///
/// use sequoia_openpgp as openpgp;
/// use openpgp::Packet;
/// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
///
/// let mut ppr =
///     PacketParser::from_bytes(b"\xcb\x12b\x00\x00\x00\x00\x00Hello world.")?;
/// while let PacketParserResult::Some(mut pp) = ppr {
///     if let Packet::Literal(_) = pp.packet {
///         // Stream the body.
///         let mut buf = Vec::new();
///         pp.read_to_end(&mut buf)?;
///         assert_eq!(buf, b"Hello world.");
///     } else {
///         unreachable!("We know it is a literal packet.");
///     }
///
///     // Get the packet out of the parser and start parsing the next
///     // packet, recursing.
///     let (packet, next_ppr) = pp.recurse()?;
///     ppr = next_ppr;
///
///     // Process the packet.
///     if let Packet::Literal(literal) = packet {
///         // The body was streamed, not buffered.
///         assert_eq!(literal.body(), b"");
///     } else {
///         unreachable!("We know it is a literal packet.");
///     }
/// }
/// # Ok(()) }
/// ```
///
/// # Packet Parser Design
///
/// There are two major concerns that inform the design of the parsing
/// API.
///
/// First, when processing a container, it is possible to either
/// recurse into the container, and process its children, or treat the
/// contents of the container as an opaque byte stream, and process
/// the packet following the container.  The low-level
/// [`PacketParser`] and mid-level [`PacketPileParser`] abstractions
/// allow the caller to choose the behavior by either calling the
/// [`PacketParser::recurse`] method or the [`PacketParser::next`]
/// method, as appropriate.  OpenPGP doesn't impose any restrictions
/// on the amount of nesting.  So, to prevent a denial of service
/// attack, the parsers don't recurse more than
/// [`DEFAULT_MAX_RECURSION_DEPTH`] times, by default.
///
///   [`PacketParser`]: struct.PacketParser.html
///   [`PacketPileParser`]: struct.PacketPileParser.html
///   [`DEFAULT_MAX_RECURSION_DEPTH`]: constant.DEFAULT_MAX_RECURSION_DEPTH.html
///
/// Second, packets can contain an effectively unbounded amount of
/// data.  To avoid errors due to memory exhaustion, the
/// `PacketParser` and [`PacketPileParser`] abstractions support
/// parsing packets in a streaming manner, i.e., never buffering more
/// than O(1) bytes of data.  To do this, the parsers initially only
/// parse a packet's header (which is rarely more than a few kilobytes
/// of data), and return control to the caller.  After inspecting that
/// data, the caller can decide how to handle the packet's contents.
/// If the content is deemed interesting, it can be streamed or
/// buffered.  Otherwise, it can be dropped.  Streaming is possible
/// not only for literal data packets, but also containers (other
/// packets also support the interface, but just return EOF).  For
/// instance, encryption can be stripped by saving the decrypted
/// content of an encryption packet, which is just an OpenPGP message.
///
/// ## Iterator Design
///
/// We explicitly chose to not use a callback-based API, but something
/// that is closer to Rust's iterator API.  Unfortunately, because a
/// `PacketParser` needs mutable access to the input stream (so that
/// the content can be streamed), only a single `PacketParser` item
/// can be live at a time (without a fair amount of unsafe nastiness).
/// This is incompatible with Rust's iterator concept, which allows
/// any number of items to be live at any time.  For instance:
///
/// ```rust
/// let mut v = vec![1, 2, 3, 4];
/// let mut iter = v.iter_mut();
///
/// let x = iter.next().unwrap();
/// let y = iter.next().unwrap();
///
/// *x += 10; // This does not cause an error!
/// *y += 10;
/// ```
pub struct PacketParser<'a> {
    /// The current packet's header.
    header: Header,

    /// The packet that is being parsed.
    pub packet: Packet,

    // The path of the packet that is currently being parsed.
    path: Vec<usize>,
    // The path of the packet that was most recently returned by
    // `next()` or `recurse()`.
    last_path: Vec<usize>,

    reader: Box<dyn BufferedReader<Cookie> + 'a>,

    // Whether the caller read the packet's content.  If so, then we
    // can't recurse, because we're missing some of the packet!
    content_was_read: bool,

    // Whether PacketParser::finish has been called.
    finished: bool,

    // Whether the content is encrypted.
    encrypted: bool,

    /// A map of this packet.
    map: Option<map::Map>,

    /// We compute a hashsum over the body to implement comparison on
    /// containers that have been streamed.
    body_hash: Option<Box<dyn crate::crypto::hash::Digest>>,

    state: PacketParserState,
}
assert_send_and_sync!(PacketParser<'_>);

impl<'a> std::fmt::Display for PacketParser<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "PacketParser")
    }
}

impl<'a> std::fmt::Debug for PacketParser<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_struct("PacketParser")
            .field("header", &self.header)
            .field("packet", &self.packet)
            .field("path", &self.path)
            .field("last_path", &self.last_path)
            .field("encrypted", &self.encrypted)
            .field("content_was_read", &self.content_was_read)
            .field("settings", &self.state.settings)
            .field("map", &self.map)
            .finish()
    }
}

/// The return value of PacketParser::parse.
enum ParserResult<'a> {
    Success(PacketParser<'a>),
    EOF((Box<dyn BufferedReader<Cookie> + 'a>, PacketParserState, Vec<usize>)),
}

/// Information about the stream of packets parsed by the
/// `PacketParser`.
///
/// Once the [`PacketParser`] reaches the end of the input stream, it
/// returns a [`PacketParserResult::EOF`] with a `PacketParserEOF`.
/// This object provides information about the parsed stream, notably
/// whether or not the packet stream was a well-formed [`Message`],
/// [`Cert`] or keyring.
///
///   [`PacketParser`]: struct.PacketParser.html
///   [`PacketParserResult::EOF`]: enum.PacketParserResult.html#variant.EOF
///   [`Message`]: ../struct.Message.html
///   [`Cert`]: ../cert/struct.Cert.html
///
/// # Examples
///
/// Parse some OpenPGP stream using a [`PacketParser`] and detects the
/// kind of data:
///
/// ```rust
/// # fn main() -> sequoia_openpgp::Result<()> {
/// use sequoia_openpgp as openpgp;
/// use openpgp::Packet;
/// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
///
/// let openpgp_data: &[u8] = // ...
/// #    include_bytes!("../tests/data/keys/public-key.gpg");
/// let mut ppr = PacketParser::from_bytes(openpgp_data)?;
/// while let PacketParserResult::Some(mut pp) = ppr {
///     // Start parsing the next packet, recursing.
///     ppr = pp.recurse()?.1;
/// }
///
/// if let PacketParserResult::EOF(eof) = ppr {
///     if eof.is_message().is_ok() {
///         // ...
///     } else if eof.is_cert().is_ok() {
///         // ...
///     } else if eof.is_keyring().is_ok() {
///         // ...
///     } else {
///         // ...
///     }
/// }
/// # Ok(()) }
/// ```
#[derive(Debug)]
pub struct PacketParserEOF<'a> {
    state: PacketParserState,
    reader: Box<dyn BufferedReader<Cookie> + 'a>,
    last_path: Vec<usize>,
}
assert_send_and_sync!(PacketParserEOF<'_>);

impl<'a> PacketParserEOF<'a> {
    /// Copies the important information in `pp` into a new
    /// `PacketParserEOF` instance.
    fn new(mut state: PacketParserState,
           reader: Box<dyn BufferedReader<Cookie> + 'a>)
           -> Self {
        state.message_validator.finish();
        state.keyring_validator.finish();
        state.cert_validator.finish();

        PacketParserEOF {
            state,
            reader,
            last_path: vec![],
        }
    }

    /// Creates a placeholder instance for PacketParserResult::take.
    fn empty() -> Self {
        Self::new(
            PacketParserState::new(Default::default()),
            buffered_reader::Memory::with_cookie(b"", Default::default())
                .as_boxed())
    }

    /// Returns whether the stream is an OpenPGP Message.
    ///
    /// A [`Message`] has a very specific structure.  Returns `true`
    /// if the stream is of that form, as opposed to a [`Cert`] or
    /// just a bunch of packets.
    ///
    ///   [`Message`]: ../struct.Message.html
    ///   [`Cert`]: ../cert/struct.Cert.html
    ///
    /// # Examples
    ///
    /// Parse some OpenPGP stream using a [`PacketParser`] and detects the
    /// kind of data:
    ///
    ///   [`PacketParser`]: struct.PacketParser.html
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// let openpgp_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/keys/public-key.gpg");
    /// let mut ppr = PacketParser::from_bytes(openpgp_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    ///
    /// if let PacketParserResult::EOF(eof) = ppr {
    ///     if eof.is_message().is_ok() {
    ///         // ...
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    pub fn is_message(&self) -> Result<()> {
        use crate::message::MessageValidity;

        match self.state.message_validator.check() {
            MessageValidity::Message => Ok(()),
            MessageValidity::MessagePrefix => unreachable!(),
            MessageValidity::Error(err) => Err(err),
        }
    }

    /// Returns whether the message is an OpenPGP keyring.
    ///
    /// A keyring has a very specific structure.  Returns `true` if
    /// the stream is of that form, as opposed to a [`Message`] or
    /// just a bunch of packets.
    ///
    ///   [`Message`]: ../struct.Message.html
    ///
    /// # Examples
    ///
    /// Parse some OpenPGP stream using a [`PacketParser`] and detects the
    /// kind of data:
    ///
    ///   [`PacketParser`]: struct.PacketParser.html
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// let openpgp_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/keys/public-key.gpg");
    /// let mut ppr = PacketParser::from_bytes(openpgp_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    ///
    /// if let PacketParserResult::EOF(eof) = ppr {
    ///     if eof.is_keyring().is_ok() {
    ///         // ...
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    pub fn is_keyring(&self) -> Result<()> {
        match self.state.keyring_validator.check() {
            KeyringValidity::Keyring => Ok(()),
            KeyringValidity::KeyringPrefix => unreachable!(),
            KeyringValidity::Error(err) => Err(err),
        }
    }

    /// Returns whether the message is an OpenPGP Cert.
    ///
    /// A [`Cert`] has a very specific structure.  Returns `true` if
    /// the stream is of that form, as opposed to a [`Message`] or
    /// just a bunch of packets.
    ///
    ///   [`Message`]: ../struct.Message.html
    ///   [`Cert`]: ../cert/struct.Cert.html
    ///
    /// # Examples
    ///
    /// Parse some OpenPGP stream using a [`PacketParser`] and detects the
    /// kind of data:
    ///
    ///   [`PacketParser`]: struct.PacketParser.html
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// let openpgp_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/keys/public-key.gpg");
    /// let mut ppr = PacketParser::from_bytes(openpgp_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    ///
    /// if let PacketParserResult::EOF(eof) = ppr {
    ///     if eof.is_cert().is_ok() {
    ///         // ...
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    pub fn is_cert(&self) -> Result<()> {
        match self.state.cert_validator.check() {
            CertValidity::Cert => Ok(()),
            CertValidity::CertPrefix => unreachable!(),
            CertValidity::Error(err) => Err(err),
        }
    }

    /// Returns the path of the last packet.
    ///
    /// # Examples
    ///
    /// Parse some OpenPGP stream using a [`PacketParser`] and returns
    /// the path (see [`PacketPile::path_ref`]) of the last packet:
    ///
    ///   [`PacketPile::path_ref`]: ../struct.PacketPile.html#method.path_ref
    ///   [`PacketParser`]: struct.PacketParser.html
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// let openpgp_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/keys/public-key.gpg");
    /// let mut ppr = PacketParser::from_bytes(openpgp_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    ///
    /// if let PacketParserResult::EOF(eof) = ppr {
    ///     let _ = eof.last_path();
    /// }
    /// # Ok(()) }
    /// ```
    pub fn last_path(&self) -> &[usize] {
        &self.last_path[..]
    }

    /// The last packet's recursion depth.
    ///
    /// A top-level packet has a recursion depth of 0.  Packets in a
    /// top-level container have a recursion depth of 1, etc.
    ///
    /// # Examples
    ///
    /// Parse some OpenPGP stream using a [`PacketParser`] and returns
    /// the recursion depth of the last packet:
    ///
    ///   [`PacketParser`]: struct.PacketParser.html
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// let openpgp_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/keys/public-key.gpg");
    /// let mut ppr = PacketParser::from_bytes(openpgp_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    ///
    /// if let PacketParserResult::EOF(eof) = ppr {
    ///     let _ = eof.last_recursion_depth();
    /// }
    /// # Ok(()) }
    /// ```
    pub fn last_recursion_depth(&self) -> Option<isize> {
        if self.last_path.len() == 0 {
            None
        } else {
            Some(self.last_path.len() as isize - 1)
        }
    }

    /// Returns the exhausted reader.
    pub fn into_reader(self) -> Box<dyn BufferedReader<Cookie> + 'a> {
        self.reader
    }
}

/// The result of parsing a packet.
///
/// This type is returned by [`PacketParser::next`],
/// [`PacketParser::recurse`], [`PacketParserBuilder::build`], and the
/// implementation of [`PacketParser`]'s [`Parse` trait].  The result
/// is either `Some(PacketParser)`, indicating successful parsing of a
/// packet, or `EOF(PacketParserEOF)` if the end of the input stream
/// has been reached.
///
///   [`PacketParser::next`]: struct.PacketParser.html#method.next
///   [`PacketParser::recurse`]: struct.PacketParser.html#method.recurse
///   [`PacketParserBuilder::build`]: struct.PacketParserBuilder.html#method.build
///   [`PacketParser`]: struct.PacketParser.html
///   [`Parse` trait]: struct.PacketParser.html#impl-Parse%3C%27a%2C%20PacketParserResult%3C%27a%3E%3E
#[derive(Debug)]
pub enum PacketParserResult<'a> {
    /// A `PacketParser` for the next packet.
    Some(PacketParser<'a>),
    /// Information about a fully parsed packet sequence.
    EOF(PacketParserEOF<'a>),
}
assert_send_and_sync!(PacketParserResult<'_>);

impl<'a> PacketParserResult<'a> {
    /// Returns `true` if the result is `EOF`.
    pub fn is_eof(&self) -> bool {
        if let PacketParserResult::EOF(_) = self {
            true
        } else {
            false
        }
    }

    /// Returns `true` if the result is `Some`.
    pub fn is_some(&self) -> bool {
        ! Self::is_eof(self)
    }

    /// Unwraps a result, yielding the content of an `Some`.
    ///
    /// # Panics
    ///
    /// Panics if the value is an `EOF`, with a panic message
    /// including the passed message, and the information in the
    /// [`PacketParserEOF`] object.
    ///
    ///   [`PacketParserEOF`]: struct.PacketParserEOF.html
    pub fn expect(self, msg: &str) -> PacketParser<'a> {
        if let PacketParserResult::Some(pp) = self {
            return pp;
        } else {
            panic!("{}", msg);
        }
    }

    /// Unwraps a result, yielding the content of an `Some`.
    ///
    /// # Panics
    ///
    /// Panics if the value is an `EOF`, with a panic message
    /// including the information in the [`PacketParserEOF`] object.
    ///
    ///   [`PacketParserEOF`]: struct.PacketParserEOF.html
    pub fn unwrap(self) -> PacketParser<'a> {
        self.expect("called `PacketParserResult::unwrap()` on a \
                     `PacketParserResult::PacketParserEOF` value")
    }

    /// Converts from `PacketParserResult` to `Result<&PacketParser,
    /// &PacketParserEOF>`.
    ///
    /// Produces a new `Result`, containing references into the
    /// original `PacketParserResult`, leaving the original in place.
    pub fn as_ref(&self)
                  -> StdResult<&PacketParser<'a>, &PacketParserEOF> {
        match self {
            PacketParserResult::Some(pp) => Ok(pp),
            PacketParserResult::EOF(eof) => Err(eof),
        }
    }

    /// Converts from `PacketParserResult` to `Result<&mut
    /// PacketParser, &mut PacketParserEOF>`.
    ///
    /// Produces a new `Result`, containing mutable references into the
    /// original `PacketParserResult`, leaving the original in place.
    pub fn as_mut(&mut self)
                  -> StdResult<&mut PacketParser<'a>, &mut PacketParserEOF<'a>>
    {
        match self {
            PacketParserResult::Some(pp) => Ok(pp),
            PacketParserResult::EOF(eof) => Err(eof),
        }
    }

    /// Takes the value out of the `PacketParserResult`, leaving a
    /// `EOF` in its place.
    ///
    /// The `EOF` left in place carries a [`PacketParserEOF`] with
    /// default values.
    ///
    ///   [`PacketParserEOF`]: struct.PacketParserEOF.html
    pub fn take(&mut self) -> Self {
        mem::replace(
            self,
            PacketParserResult::EOF(PacketParserEOF::empty()))
    }

    /// Maps a `PacketParserResult` to `Result<PacketParser,
    /// PacketParserEOF>` by applying a function to a contained `Some`
    /// value, leaving an `EOF` value untouched.
    pub fn map<U, F>(self, f: F) -> StdResult<U, PacketParserEOF<'a>>
        where F: FnOnce(PacketParser<'a>) -> U
    {
        match self {
            PacketParserResult::Some(x) => Ok(f(x)),
            PacketParserResult::EOF(e) => Err(e),
        }
    }
}

impl<'a> Parse<'a, PacketParserResult<'a>> for PacketParser<'a> {
    /// Starts parsing an OpenPGP message stored in a `std::io::Read` object.
    ///
    /// This function returns a `PacketParser` for the first packet in
    /// the stream.
    fn from_reader<R: io::Read + 'a + Send + Sync>(reader: R)
            -> Result<PacketParserResult<'a>> {
        PacketParserBuilder::from_reader(reader)?.build()
    }

    /// Starts parsing an OpenPGP message stored in a file named `path`.
    ///
    /// This function returns a `PacketParser` for the first packet in
    /// the stream.
    fn from_file<P: AsRef<Path>>(path: P)
            -> Result<PacketParserResult<'a>> {
        PacketParserBuilder::from_file(path)?.build()
    }

    /// Starts parsing an OpenPGP message stored in a buffer.
    ///
    /// This function returns a `PacketParser` for the first packet in
    /// the stream.
    fn from_bytes<D: AsRef<[u8]> + ?Sized + Send + Sync>(data: &'a D)
            -> Result<PacketParserResult<'a>> {
        PacketParserBuilder::from_bytes(data)?.build()
    }
}

impl <'a> PacketParser<'a> {
    /// Starts parsing an OpenPGP message stored in a `BufferedReader`
    /// object.
    ///
    /// This function returns a `PacketParser` for the first packet in
    /// the stream.
    pub(crate) fn from_buffered_reader(bio: Box<dyn BufferedReader<Cookie> + 'a>)
            -> Result<PacketParserResult<'a>> {
        PacketParserBuilder::from_buffered_reader(bio)?.build()
    }

    /// Returns the reader stack, replacing it with a
    /// `buffered_reader::EOF` reader.
    ///
    /// This function may only be called when the `PacketParser` is in
    /// State::Body.
    fn take_reader(&mut self) -> Box<dyn BufferedReader<Cookie> + 'a> {
        self.set_reader(
            Box::new(buffered_reader::EOF::with_cookie(Default::default())))
    }

    /// Replaces the reader stack.
    ///
    /// This function may only be called when the `PacketParser` is in
    /// State::Body.
    fn set_reader(&mut self, reader: Box<dyn BufferedReader<Cookie> + 'a>)
        -> Box<dyn BufferedReader<Cookie> + 'a>
    {
        mem::replace(&mut self.reader, reader)
    }

    /// Returns a mutable reference to the reader stack.
    fn mut_reader(&mut self) -> &mut dyn BufferedReader<Cookie> {
        &mut self.reader
    }

    /// Marks the packet's contents as encrypted or not.
    fn set_encrypted(mut self, v: bool) -> Self {
        self.encrypted = v;
        self
    }

    /// Returns whether the packet's contents are encrypted.
    ///
    /// This function returns `true` while processing an encryption
    /// container before it is decrypted using
    /// [`PacketParser::decrypt`].  Once successfully decrypted, it
    /// returns `false`.
    ///
    ///   [`PacketParser::decrypt`]: struct.PacketParser.html#method.decrypt
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::fmt::hex;
    /// use openpgp::types::SymmetricAlgorithm;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse an encrypted message.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/messages/encrypted-aes256-password-123.gpg");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     if let Packet::SEIP(_) = pp.packet {
    ///         assert!(pp.encrypted());
    ///         pp.decrypt(SymmetricAlgorithm::AES256,
    ///                    &hex::decode("7EF4F08C44F780BEA866961423306166\
    ///                                  B8912C43352F3D9617F745E4E3939710")?
    ///                        .into())?;
    ///         assert!(! pp.encrypted());
    ///     }
    ///
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn encrypted(&self) -> bool {
        self.encrypted
    }

    /// Returns the path of the last packet.
    ///
    /// This function returns the path (see [`PacketPile::path_ref`]
    /// for a description of paths) of the packet last returned by a
    /// call to [`PacketParser::recurse`] or [`PacketParser::next`].
    /// If no packet has been returned (i.e. the current packet is the
    /// first packet), this returns the empty slice.
    ///
    ///   [`PacketPile::path_ref`]: ../struct.PacketPile.html#method.path_ref
    ///   [`PacketParser::recurse`]: #method.recurse
    ///   [`PacketParser::next`]: #method.next
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse a compressed message.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/messages/compressed-data-algo-0.pgp");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     match pp.packet {
    ///         Packet::CompressedData(_) => assert_eq!(pp.last_path(), &[]),
    ///         Packet::Literal(_) => assert_eq!(pp.last_path(), &[0]),
    ///         _ => (),
    ///     }
    ///
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn last_path(&self) -> &[usize] {
        &self.last_path[..]
    }

    /// Returns the path of the current packet.
    ///
    /// This function returns the path (see [`PacketPile::path_ref`]
    /// for a description of paths) of the packet currently being
    /// processed (see [`PacketParser::packet`]).
    ///
    ///   [`PacketPile::path_ref`]: ../struct.PacketPile.html#method.path_ref
    ///   [`PacketParser::packet`]: #structfield.packet
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse a compressed message.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/messages/compressed-data-algo-0.pgp");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     match pp.packet {
    ///         Packet::CompressedData(_) => assert_eq!(pp.path(), &[0]),
    ///         Packet::Literal(_) => assert_eq!(pp.path(), &[0, 0]),
    ///         _ => (),
    ///     }
    ///
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn path(&self) -> &[usize] {
        &self.path[..]
    }

    /// The current packet's recursion depth.
    ///
    /// A top-level packet has a recursion depth of 0.  Packets in a
    /// top-level container have a recursion depth of 1, etc.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse a compressed message.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/messages/compressed-data-algo-0.pgp");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     match pp.packet {
    ///         Packet::CompressedData(_) => assert_eq!(pp.recursion_depth(), 0),
    ///         Packet::Literal(_) => assert_eq!(pp.recursion_depth(), 1),
    ///         _ => (),
    ///     }
    ///
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn recursion_depth(&self) -> isize {
        self.path.len() as isize - 1
    }

    /// The last packet's recursion depth.
    ///
    /// A top-level packet has a recursion depth of 0.  Packets in a
    /// top-level container have a recursion depth of 1, etc.
    ///
    /// Note: if no packet has been returned yet, this returns None.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse a compressed message.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/messages/compressed-data-algo-0.pgp");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     match pp.packet {
    ///         Packet::CompressedData(_) => assert_eq!(pp.last_recursion_depth(), None),
    ///         Packet::Literal(_) => assert_eq!(pp.last_recursion_depth(), Some(0)),
    ///         _ => (),
    ///     }
    ///
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn last_recursion_depth(&self) -> Option<isize> {
        if self.last_path.len() == 0 {
            assert_eq!(&self.path[..], &[ 0 ]);
            None
        } else {
            Some(self.last_path.len() as isize - 1)
        }
    }

    /// Returns whether the message appears to be an OpenPGP Message.
    ///
    /// Only when the whole message has been processed is it possible
    /// to say whether the message is definitely an OpenPGP Message.
    /// Before that, it is only possible to say that the message is a
    /// valid prefix or definitely not an OpenPGP message (see
    /// [`PacketParserEOF::is_message`]).
    ///
    ///   [`PacketParserEOF::is_message`]: struct.PacketParserEOF.html#method.is_message
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse a compressed message.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/messages/compressed-data-algo-0.pgp");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     pp.possible_message()?;
    ///
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn possible_message(&self) -> Result<()> {
        use crate::message::MessageValidity;

        match self.state.message_validator.check() {
            MessageValidity::Message => unreachable!(),
            MessageValidity::MessagePrefix => Ok(()),
            MessageValidity::Error(err) => Err(err),
        }
    }

    /// Returns whether the message appears to be an OpenPGP keyring.
    ///
    /// Only when the whole message has been processed is it possible
    /// to say whether the message is definitely an OpenPGP keyring.
    /// Before that, it is only possible to say that the message is a
    /// valid prefix or definitely not an OpenPGP keyring (see
    /// [`PacketParserEOF::is_keyring`]).
    ///
    ///   [`PacketParserEOF::is_keyring`]: struct.PacketParserEOF.html#method.is_keyring
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse a certificate.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/keys/testy.pgp");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     pp.possible_keyring()?;
    ///
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn possible_keyring(&self) -> Result<()> {
        match self.state.keyring_validator.check() {
            KeyringValidity::Keyring => unreachable!(),
            KeyringValidity::KeyringPrefix => Ok(()),
            KeyringValidity::Error(err) => Err(err),
        }
    }

    /// Returns whether the message appears to be an OpenPGP Cert.
    ///
    /// Only when the whole message has been processed is it possible
    /// to say whether the message is definitely an OpenPGP Cert.
    /// Before that, it is only possible to say that the message is a
    /// valid prefix or definitely not an OpenPGP Cert (see
    /// [`PacketParserEOF::is_cert`]).
    ///
    ///   [`PacketParserEOF::is_cert`]: struct.PacketParserEOF.html#method.is_cert
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse a certificate.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/keys/testy.pgp");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     pp.possible_cert()?;
    ///
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn possible_cert(&self) -> Result<()> {
        match self.state.cert_validator.check() {
            CertValidity::Cert => unreachable!(),
            CertValidity::CertPrefix => Ok(()),
            CertValidity::Error(err) => Err(err),
        }
    }

    /// Returns Ok if the data appears to be a legal packet.
    ///
    /// This is just a heuristic.  It can be used for recovering from
    /// garbage.
    ///
    /// Successfully reading the header only means that the top bit of
    /// the ptag is 1.  Assuming a uniform distribution, there's a 50%
    /// chance that that is the case.
    ///
    /// To improve our chances of a correct recovery, we make sure the
    /// tag is known (for new format CTBs, there are 64 possible tags,
    /// but only a third of them are reasonable; for old format
    /// packets, there are only 16 and nearly all are plausible), and
    /// we make sure the packet contents are reasonable.
    ///
    /// Currently, we only try to recover the most interesting
    /// packets.
    fn plausible<T: BufferedReader<Cookie>>(
        bio: &mut buffered_reader::Dup<T, Cookie>, header: &Header)
                 -> Result<()> {
        let bad = Err(
            Error::MalformedPacket("Can't make an educated case".into()).into());

        match header.ctb().tag() {
            Tag::Reserved
            | Tag::Unknown(_) | Tag::Private(_) =>
                Err(Error::MalformedPacket("Looks like garbage".into()).into()),

            Tag::Marker => Marker::plausible(bio, &header),
            Tag::Signature => Signature::plausible(bio, &header),

            Tag::SecretKey => Key::plausible(bio, &header),
            Tag::PublicKey => Key::plausible(bio, &header),
            Tag::SecretSubkey => Key::plausible(bio, &header),
            Tag::PublicSubkey => Key::plausible(bio, &header),

            Tag::UserID => bad,
            Tag::UserAttribute => bad,

            // It is reasonable to try and ignore garbage in Certs,
            // because who knows what the keyservers return, etc.
            // But, if we have what appears to be an OpenPGP message,
            // then, ignore.
            Tag::PKESK => bad,
            Tag::SKESK => bad,
            Tag::OnePassSig => bad,
            Tag::CompressedData => bad,
            Tag::SED => bad,
            Tag::Literal => bad,
            Tag::Trust => bad,
            Tag::SEIP => bad,
            Tag::MDC => bad,
            Tag::AED => bad,
        }
    }

    /// Returns a `PacketParser` for the next OpenPGP packet in the
    /// stream.  If there are no packets left, this function returns
    /// `bio`.
    fn parse(mut bio: Box<dyn BufferedReader<Cookie> + 'a>,
             state: PacketParserState,
             path: Vec<usize>)
        -> Result<ParserResult<'a>>
    {
        assert!(path.len() > 0);

        let indent = path.len() as isize - 1;
        tracer!(TRACE, "PacketParser::parse", indent);
        t!("Parsing packet at {:?}", path);

        let recursion_depth = path.len() as isize - 1;

        // When header encounters an EOF, it returns an error.  But,
        // we want to return None.  Try a one byte read.
        if bio.data(1)?.len() == 0 {
            t!("No packet at {:?} (EOF).", path);
            return Ok(ParserResult::EOF((bio, state, path)));
        }

        // When computing a hash for a signature, most of the
        // signature packet should not be included in the hash.  That
        // is:
        //
        //    [ one pass sig ] [ ... message ... ] [ sig ]
        //                     ^^^^^^^^^^^^^^^^^^^
        //                        hash only this
        //
        // (The special logic for the Signature packet is in
        // Signature::parse.)
        //
        // To avoid this, we use a Dup reader to figure out if the
        // next packet is a sig packet without consuming the headers,
        // which would cause the headers to be hashed.  If so, we
        // extract the hash context.

        let mut bio = buffered_reader::Dup::with_cookie(bio, Cookie::default());
        let mut header;

        // Read the header.
        let mut skip = 0;
        let mut orig_error : Option<anyhow::Error> = None;
        loop {
            bio.rewind();
            bio.data_consume_hard(skip)?;

            match Header::parse(&mut bio) {
                Ok(header_) => {
                    if skip == 0 {
                        header = header_;
                        break;
                    }

                    match Self::plausible(&mut bio, &header_) {
                        Ok(()) => {
                            header = header_;
                            break;
                        }
                        Err(_err) => (),
                    }
                }
                Err(err) => {
                    if orig_error.is_none() {
                        orig_error = Some(err.into());
                    }

                    if state.first_packet || skip > 32 * 1024 {
                        // Limit the search space.  This should be
                        // enough to find a reasonable recovery point
                        // in a Cert.
                        return Err(orig_error.unwrap());
                    }
                }
            }

            skip = skip + 1;
        }

        // Prepare to actually consume the header or garbage.
        let consumed = if skip == 0 {
            bio.total_out()
        } else {
            t!("turning {} bytes of junk into an Unknown packet", skip);

            // Fabricate a header.
            header = Header::new(CTB::new(Tag::Reserved),
                                 BodyLength::Full(skip as u32));
            0
        };

        let tag = header.ctb().tag();

        // A buffered_reader::Dup always has an inner.
        let mut bio = Box::new(bio).into_inner().unwrap();

        // Disable hashing for literal packets, Literal::parse will
        // enable it for the body.  Signatures and OnePassSig packets
        // are only hashed by notarizing signatures.
        if tag == Tag::Literal {
            Cookie::hashing(
                &mut bio, Hashing::Disabled, recursion_depth - 1);
        } else if tag == Tag::OnePassSig || tag == Tag::Signature {
            if Cookie::processing_csf_message(&bio) {
                // When processing a CSF message, the hashing reader
                // is not peeled off, because the number of signature
                // packets cannot be known from the number of OPS
                // packets.  Instead, we simply disable hashing.
                //
                // XXX: It would be nice to peel off the hashing
                // reader and drop this workaround.
                Cookie::hashing(
                    &mut bio, Hashing::Disabled, recursion_depth - 1);
            } else {
                Cookie::hashing(
                    &mut bio, Hashing::Notarized, recursion_depth - 1);
            }
        }

        // Save header for the map or nested signatures.
        let header_bytes =
            Vec::from(&bio.data_consume_hard(consumed)?[..consumed]);

        let bio : Box<dyn BufferedReader<Cookie>>
            = match header.length() {
                &BodyLength::Full(len) => {
                    t!("Pushing a limitor ({} bytes), level: {}.",
                       len, recursion_depth);
                    Box::new(buffered_reader::Limitor::with_cookie(
                        bio, len as u64,
                        Cookie::new(recursion_depth)))
                },
                &BodyLength::Partial(len) => {
                    t!("Pushing a partial body chunk decoder, level: {}.",
                       recursion_depth);
                    Box::new(BufferedReaderPartialBodyFilter::with_cookie(
                        bio, len,
                        // When hashing a literal data packet, we only
                        // hash the packet's contents; we don't hash
                        // the literal data packet's meta-data or the
                        // length information, which includes the
                        // partial body headers.
                        tag != Tag::Literal,
                        Cookie::new(recursion_depth)))
                },
                BodyLength::Indeterminate => {
                    t!("Indeterminate length packet, not adding a limitor.");
                    bio
                },
        };

        // Our parser should not accept packets that fail our header
        // syntax check.  Doing so breaks roundtripping, and seems
        // like a bad idea anyway.
        let mut header_syntax_error = header.valid(true).err();

        // Check packet size.
        if header_syntax_error.is_none() {
            let max_size = state.settings.max_packet_size;
            match tag {
                // Don't check the size for container packets, those
                // can be safely streamed.
                Tag::Literal | Tag::CompressedData | Tag::SED | Tag::SEIP
                    | Tag::AED => (),
                _ => match header.length() {
                    &BodyLength::Full(l) => if l > max_size {
                        header_syntax_error = Some(
                            Error::PacketTooLarge(tag, l, max_size).into());
                    },
                    _ => unreachable!("non-data packets have full length, \
                                       syntax check above"),
                }
            }
        }

        let parser = PacketHeaderParser::new(bio, state, path,
                                             header, header_bytes);

        let mut result = match tag {
            Tag::Reserved if skip > 0 => Unknown::parse(
                parser, Error::MalformedPacket(format!(
                    "Skipped {} bytes of junk", skip)).into()),
            _ if header_syntax_error.is_some() =>
                Unknown::parse(parser, header_syntax_error.unwrap()),
            Tag::Signature =>           Signature::parse(parser),
            Tag::OnePassSig =>          OnePassSig::parse(parser),
            Tag::PublicSubkey =>        Key::parse(parser),
            Tag::PublicKey =>           Key::parse(parser),
            Tag::SecretKey =>           Key::parse(parser),
            Tag::SecretSubkey =>        Key::parse(parser),
            Tag::Trust =>               Trust::parse(parser),
            Tag::UserID =>              UserID::parse(parser),
            Tag::UserAttribute =>       UserAttribute::parse(parser),
            Tag::Marker =>              Marker::parse(parser),
            Tag::Literal =>             Literal::parse(parser),
            Tag::CompressedData =>      CompressedData::parse(parser),
            Tag::SKESK =>               SKESK::parse(parser),
            Tag::SEIP =>                SEIP::parse(parser),
            Tag::MDC =>                 MDC::parse(parser),
            Tag::PKESK =>               PKESK::parse(parser),
            Tag::AED =>                 AED::parse(parser),
            _ => Unknown::parse(parser,
                                Error::UnsupportedPacketType(tag).into()),
        }?;

        if tag == Tag::OnePassSig {
            Cookie::hashing(
                &mut result, Hashing::Enabled, recursion_depth - 1);
        }

        result.state.first_packet = false;

        t!(" -> {:?}, path: {:?}, level: {:?}.",
           result.packet.tag(), result.path, result.cookie_ref().level);

        return Ok(ParserResult::Success(result));
    }

    /// Finishes parsing the current packet and starts parsing the
    /// next one.
    ///
    /// This function finishes parsing the current packet.  By
    /// default, any unread content is dropped.  (See
    /// [`PacketParsererBuilder`] for how to configure this.)  It then
    /// creates a new packet parser for the next packet.  If the
    /// current packet is a container, this function does *not*
    /// recurse into the container, but skips any packets it contains.
    /// To recurse into the container, use the [`recurse()`] method.
    ///
    ///   [`PacketParsererBuilder`]: struct.PacketParserBuilder.html
    ///   [`recurse()`]: #method.recurse
    ///
    /// The return value is a tuple containing:
    ///
    ///   - A `Packet` holding the fully processed old packet;
    ///
    ///   - A `PacketParser` holding the new packet;
    ///
    /// To determine the two packet's position within the parse tree,
    /// you can use `last_path()` and `path()`, respectively.  To
    /// determine their depth, you can use `last_recursion_depth()`
    /// and `recursion_depth()`, respectively.
    ///
    /// Note: A recursion depth of 0 means that the packet is a
    /// top-level packet, a recursion depth of 1 means that the packet
    /// is an immediate child of a top-level-packet, etc.
    ///
    /// Since the packets are serialized in depth-first order and all
    /// interior nodes are visited, we know that if the recursion
    /// depth is the same, then the packets are siblings (they have a
    /// common parent) and not, e.g., cousins (they have a common
    /// grandparent).  This is because, if we move up the tree, the
    /// only way to move back down is to first visit a new container
    /// (e.g., an aunt).
    ///
    /// Using the two positions, we can compute the change in depth as
    /// new_depth - old_depth.  Thus, if the change in depth is 0, the
    /// two packets are siblings.  If the value is 1, the old packet
    /// is a container, and the new packet is its first child.  And,
    /// if the value is -1, the new packet is contained in the old
    /// packet's grandparent.  The idea is illustrated below:
    ///
    /// ```text
    ///             ancestor
    ///             |       \
    ///            ...      -n
    ///             |
    ///           grandparent
    ///           |          \
    ///         parent       -1
    ///         |      \
    ///      packet    0
    ///         |
    ///         1
    /// ```
    ///
    /// Note: since this function does not automatically recurse into
    /// a container, the change in depth will always be non-positive.
    /// If the current container is empty, this function DOES pop that
    /// container off the container stack, and returns the following
    /// packet in the parent container.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse a message.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/messages/compressed-data-algo-0.pgp");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     // Start parsing the next packet.
    ///     ppr = pp.next()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn next(mut self)
        -> Result<(Packet, PacketParserResult<'a>)>
    {
        let indent = self.recursion_depth();
        tracer!(TRACE, "PacketParser::next", indent);
        t!("({:?}, path: {:?}, level: {:?}).",
           self.packet.tag(), self.path, self.cookie_ref().level);

        self.finish()?;

        let (mut fake_eof, mut reader) = buffered_reader_stack_pop(
            mem::replace(&mut self.reader,
                         Box::new(buffered_reader::EOF::with_cookie(
                             Default::default()))),
            self.recursion_depth())?;

        self.last_path.clear();
        self.last_path.extend_from_slice(&self.path[..]);

        // Assume that we succeed in parsing the next packet.  If not,
        // then we'll adjust the path.
        *self.path.last_mut().expect("A path is never empty") += 1;

        // Now read the next packet.
        loop {
            // Parse the next packet.
            t!("Reading packet at {:?} from: {:?}", self.path, reader);

            let recursion_depth = self.recursion_depth();

            let ppr = PacketParser::parse(reader, self.state, self.path)?;
            match ppr {
                ParserResult::EOF((reader_, state_, path_)) => {
                    // We got EOF on the current container.  The
                    // container at recursion depth n is empty.  Pop
                    // it and any filters for it, i.e., those at level
                    // n (e.g., the limitor that caused us to hit
                    // EOF), and then try again.

                    t!("depth: {}, got EOF trying to read the next packet",
                       recursion_depth);

                    self.path = path_;

                    if ! fake_eof && recursion_depth == 0 {
                        t!("Popped top-level container, done reading message.");
                        // Pop topmost filters (e.g. the armor::Reader).
                        let (_, reader_) = buffered_reader_stack_pop(
                            reader_, ARMOR_READER_LEVEL)?;
                        let mut eof = PacketParserEOF::new(state_, reader_);
                        eof.last_path = self.last_path;
                        return Ok((self.packet,
                                   PacketParserResult::EOF(eof)));
                    } else {
                        self.state = state_;
                        self.finish()?;
                        let (fake_eof_, reader_) = buffered_reader_stack_pop(
                            reader_, recursion_depth - 1)?;
                        fake_eof = fake_eof_;
                        if ! fake_eof {
                            self.path.pop().unwrap();
                            *self.path.last_mut()
                                .expect("A path is never empty") += 1;
                        }
                        reader = reader_;
                    }
                },
                ParserResult::Success(mut pp) => {
                    let path = pp.path().to_vec();
                    pp.state.message_validator.push(pp.packet.tag(), &path);
                    pp.state.keyring_validator.push(pp.packet.tag());
                    pp.state.cert_validator.push(pp.packet.tag());

                    pp.last_path = self.last_path;

                    return Ok((self.packet, PacketParserResult::Some(pp)));
                }
            }
        }
    }

    /// Finishes parsing the current packet and starts parsing the
    /// next one, recursing if possible.
    ///
    /// This method is similar to the [`next()`] method (see that
    /// method for more details), but if the current packet is a
    /// container (and we haven't reached the maximum recursion depth,
    /// and the user hasn't started reading the packet's contents), we
    /// recurse into the container, and return a `PacketParser` for
    /// its first child.  Otherwise, we return the next packet in the
    /// packet stream.  If this function recurses, then the new
    /// packet's recursion depth will be `last_recursion_depth() + 1`;
    /// because we always visit interior nodes, we can't recurse more
    /// than one level at a time.
    ///
    ///   [`next()`]: #method.next
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse a message.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/messages/compressed-data-algo-0.pgp");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn recurse(self) -> Result<(Packet, PacketParserResult<'a>)> {
        let indent = self.recursion_depth();
        tracer!(TRACE, "PacketParser::recurse", indent);
        t!("({:?}, path: {:?}, level: {:?})",
           self.packet.tag(), self.path, self.cookie_ref().level);

        match self.packet {
            // Packets that recurse.
            Packet::CompressedData(_) | Packet::SEIP(_) | Packet::AED(_)
                if ! self.encrypted =>
            {
                if self.recursion_depth() as u8
                    >= self.state.settings.max_recursion_depth
                {
                    t!("Not recursing into the {:?} packet, maximum recursion \
                        depth ({}) reached.",
                       self.packet.tag(),
                       self.state.settings.max_recursion_depth);

                    // Drop through.
                } else if self.content_was_read {
                    t!("Not recursing into the {:?} packet, some data was \
                        already read.",
                       self.packet.tag());

                    // Drop through.
                } else {
                    let mut last_path = self.last_path;
                    last_path.clear();
                    last_path.extend_from_slice(&self.path[..]);

                    let mut path = self.path;
                    path.push(0);

                    match PacketParser::parse(self.reader, self.state,
                                              path.clone())?
                    {
                        ParserResult::Success(mut pp) => {
                            t!("Recursed into the {:?} packet, got a {:?}.",
                               self.packet.tag(), pp.packet.tag());

                            pp.state.message_validator.push(
                                pp.packet.tag(), &path);
                            pp.state.keyring_validator.push(pp.packet.tag());
                            pp.state.cert_validator.push(pp.packet.tag());

                            pp.last_path = last_path;

                            return Ok((self.packet,
                                       PacketParserResult::Some(pp)));
                        },
                        ParserResult::EOF(_) => {
                            return Err(Error::MalformedPacket(
                                "Container is truncated".into()).into());
                        },
                    }
                }
            },
            // decrypted should always be true.
            Packet::CompressedData(_) => unreachable!(),
            // Packets that don't recurse.
            Packet::Unknown(_) | Packet::Signature(_) | Packet::OnePassSig(_)
                | Packet::PublicKey(_) | Packet::PublicSubkey(_)
                | Packet::SecretKey(_) | Packet::SecretSubkey(_)
                | Packet::Marker(_) | Packet::Trust(_)
                | Packet::UserID(_) | Packet::UserAttribute(_)
                | Packet::Literal(_) | Packet::PKESK(_) | Packet::SKESK(_)
                | Packet::SEIP(_) | Packet::MDC(_) | Packet::AED(_) => {
                // Drop through.
                t!("A {:?} packet is not a container, not recursing.",
                   self.packet.tag());
            },
        }

        // No recursion.
        self.next()
    }

    /// Causes the PacketParser to buffer the packet's contents.
    ///
    /// The packet's contents can be retrieved using
    /// e.g. [`Container::body`].  In general, you should avoid
    /// buffering a packet's content and prefer streaming its content
    /// unless you are certain that the content is small.
    ///
    ///   [`Container::body`]: ../packet/struct.Container.html#method.body
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse a message.
    /// let message_data: &[u8] = // ...
    /// #   include_bytes!("../tests/data/messages/literal-mode-t-partial-body.gpg");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     // Process the packet.
    ///
    ///     if let Packet::Literal(_) = pp.packet {
    ///         assert!(pp.buffer_unread_content()?
    ///                     .starts_with(b"A Cypherpunk's Manifesto"));
    /// #       assert!(pp.buffer_unread_content()?
    /// #                   .starts_with(b"A Cypherpunk's Manifesto"));
    ///         if let Packet::Literal(l) = &pp.packet {
    ///             assert!(l.body().starts_with(b"A Cypherpunk's Manifesto"));
    ///             assert_eq!(l.body().len(), 5158);
    ///         } else {
    ///             unreachable!();
    ///         }
    ///     }
    ///
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn buffer_unread_content(&mut self) -> Result<&[u8]> {
        let rest = self.steal_eof()?;

        fn set_or_extend(rest: Vec<u8>, c: &mut Container, processed: bool)
                         -> Result<&[u8]> {
            if rest.len() > 0 {
                let current = match c.body() {
                    Body::Unprocessed(bytes) => &bytes[..],
                    Body::Processed(bytes) => &bytes[..],
                    Body::Structured(packets) if packets.is_empty() => &[][..],
                    Body::Structured(_) => return Err(Error::InvalidOperation(
                        "cannot append unread bytes to parsed packets"
                            .into()).into()),
                };
                let rest = if current.len() > 0 {
                    let mut new =
                        Vec::with_capacity(current.len() + rest.len());
                    new.extend_from_slice(current);
                    new.extend_from_slice(&rest);
                    new
                } else {
                    rest
                };

                c.set_body(if processed {
                    Body::Processed(rest)
                } else {
                    Body::Unprocessed(rest)
                });
            }

            match c.body() {
                Body::Unprocessed(bytes) => Ok(bytes),
                Body::Processed(bytes) => Ok(bytes),
                Body::Structured(packets) if packets.is_empty() => Ok(&[][..]),
                Body::Structured(_) => Err(Error::InvalidOperation(
                    "cannot append unread bytes to parsed packets"
                        .into()).into()),
            }
        }

        use std::ops::DerefMut;
        match &mut self.packet {
            Packet::Literal(p) => set_or_extend(rest, p.container_mut(), false),
            Packet::Unknown(p) => set_or_extend(rest, p.container_mut(), false),
            Packet::CompressedData(p) =>
                set_or_extend(rest, p.deref_mut(), true),
            Packet::SEIP(p) =>
                set_or_extend(rest, p.deref_mut(), ! self.encrypted),
            Packet::AED(p) =>
                set_or_extend(rest, p.deref_mut(), ! self.encrypted),
            p => {
                if rest.len() > 0 {
                    Err(Error::MalformedPacket(
                        format!("Unexpected body data for {:?}: {}",
                                p, crate::fmt::hex::encode_pretty(rest)))
                        .into())
                } else {
                    Ok(&b""[..])
                }
            },
        }
    }

    /// Finishes parsing the current packet.
    ///
    /// By default, this drops any unread content.  Use, for instance,
    /// [`PacketParserBuilder`] to customize the default behavior.
    ///
    ///   [`PacketParserBuilder`]: struct.PacketParserBuilder.html
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse a message.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/messages/compressed-data-algo-0.pgp");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     let p = pp.finish()?;
    /// #   let _ = p;
    ///
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    // Note: this function is public and may be called multiple times!
    pub fn finish<'b>(&'b mut self) -> Result<&'b Packet> {
        let indent = self.recursion_depth();
        tracer!(TRACE, "PacketParser::finish", indent);

        if self.finished {
            return Ok(&mut self.packet);
        }

        let recursion_depth = self.recursion_depth();

        let unread_content = if self.state.settings.buffer_unread_content {
            t!("({:?} at depth {}): buffering {} bytes of unread content",
               self.packet.tag(), recursion_depth,
               self.data_eof().unwrap_or(&[]).len());

            self.buffer_unread_content()?.len() > 0
        } else {
            t!("({:?} at depth {}): dropping {} bytes of unread content",
               self.packet.tag(), recursion_depth,
               self.data_eof().unwrap_or(&[]).len());

            self.drop_eof()?
        };

        if unread_content {
            match self.packet.tag() {
                Tag::SEIP | Tag::AED | Tag::SED | Tag::CompressedData => {
                    // We didn't (fully) process a container's content.  Add
                    // this as opaque content to the message validator.
                    let mut path = self.path().to_vec();
                    path.push(0);
                    self.state.message_validator.push_token(
                        message::Token::OpaqueContent, &path);
                }
                _ => {},
            }
        }

        if let Some(c) = self.packet.container_mut() {
            let h = self.body_hash.take()
                .expect("body_hash is Some");
            c.set_body_hash(h);
        }

        self.finished = true;

        Ok(&mut self.packet)
    }

    /// Hashes content that has been streamed.
    fn hash_read_content(&mut self, b: &[u8]) {
        if b.len() > 0 {
            assert!(self.body_hash.is_some());
            self.body_hash.as_mut().map(|h| h.update(b));
            self.content_was_read = true;
        }
    }

    /// Returns a reference to the current packet's header.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse a message.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/messages/compressed-data-algo-0.pgp");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     pp.header().valid(false)?;
    ///
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn header(&self) -> &Header {
        &self.header
    }

    /// Returns a reference to the map (if any is written).
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::parse::{Parse, PacketParserBuilder};
    ///
    /// let message_data = b"\xcb\x12t\x00\x00\x00\x00\x00Hello world.";
    /// let pp = PacketParserBuilder::from_bytes(message_data)?
    ///     .map(true) // Enable mapping.
    ///     .build()?
    ///     .expect("One packet, not EOF");
    /// let map = pp.map().expect("Mapping is enabled");
    ///
    /// assert_eq!(map.iter().nth(0).unwrap().name(), "CTB");
    /// assert_eq!(map.iter().nth(0).unwrap().offset(), 0);
    /// assert_eq!(map.iter().nth(0).unwrap().as_bytes(), &[0xcb]);
    /// # Ok(()) }
    /// ```
    pub fn map(&self) -> Option<&map::Map> {
        self.map.as_ref()
    }

    /// Takes the map (if any is written).
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::parse::{Parse, PacketParserBuilder};
    ///
    /// let message_data = b"\xcb\x12t\x00\x00\x00\x00\x00Hello world.";
    /// let mut pp = PacketParserBuilder::from_bytes(message_data)?
    ///     .map(true) // Enable mapping.
    ///     .build()?
    ///     .expect("One packet, not EOF");
    /// let map = pp.take_map().expect("Mapping is enabled");
    ///
    /// assert_eq!(map.iter().nth(0).unwrap().name(), "CTB");
    /// assert_eq!(map.iter().nth(0).unwrap().offset(), 0);
    /// assert_eq!(map.iter().nth(0).unwrap().as_bytes(), &[0xcb]);
    /// # Ok(()) }
    /// ```
    pub fn take_map(&mut self) -> Option<map::Map> {
        self.map.take()
    }
}

/// This interface allows a caller to read the content of a
/// `PacketParser` using the `Read` interface.  This is essential to
/// supporting streaming operation.
///
/// Note: it is safe to mix the use of the `std::io::Read` and
/// `BufferedReader` interfaces.
impl<'a> io::Read for PacketParser<'a> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        // The BufferedReader interface takes care of hashing the read
        // values.
        buffered_reader_generic_read_impl(self, buf)
    }
}

/// This interface allows a caller to read the content of a
/// `PacketParser` using the `BufferedReader` interface.  This is
/// essential to supporting streaming operation.
///
/// Note: it is safe to mix the use of the `std::io::Read` and
/// `BufferedReader` interfaces.
impl<'a> BufferedReader<Cookie> for PacketParser<'a> {
    fn buffer(&self) -> &[u8] {
        self.reader.buffer()
    }

    fn data(&mut self, amount: usize) -> io::Result<&[u8]> {
        // There is no need to set `content_was_read`, because this
        // doesn't actually consume any data.
        self.reader.data(amount)
    }

    fn data_hard(&mut self, amount: usize) -> io::Result<&[u8]> {
        // There is no need to set `content_was_read`, because this
        // doesn't actually consume any data.
        self.reader.data_hard(amount)
    }

    fn data_eof(&mut self) -> io::Result<&[u8]> {
        // There is no need to set `content_was_read`, because this
        // doesn't actually consume any data.
        self.reader.data_eof()
    }

    fn consume(&mut self, amount: usize) -> &[u8] {
        // This is awkward.  Juggle mutable references around.
        if let Some(mut body_hash) = self.body_hash.take() {
            let data = self.data_hard(amount)
                .expect("It is an error to consume more than data returns");
            body_hash.update(&data[..amount]);
            self.body_hash = Some(body_hash);
            self.content_was_read |= amount > 0;
        } else {
            panic!("body_hash is None");
        }

        self.reader.consume(amount)
    }

    fn data_consume(&mut self, mut amount: usize) -> io::Result<&[u8]> {
        // This is awkward.  Juggle mutable references around.
        if let Some(mut body_hash) = self.body_hash.take() {
            let data = self.data(amount)?;
            amount = cmp::min(data.len(), amount);
            body_hash.update(&data[..amount]);
            self.body_hash = Some(body_hash);
            self.content_was_read |= amount > 0;
        } else {
            panic!("body_hash is None");
        }

        self.reader.data_consume(amount)
    }

    fn data_consume_hard(&mut self, amount: usize) -> io::Result<&[u8]> {
        // This is awkward.  Juggle mutable references around.
        if let Some(mut body_hash) = self.body_hash.take() {
            let data = self.data_hard(amount)?;
            body_hash.update(&data[..amount]);
            self.body_hash = Some(body_hash);
            self.content_was_read |= amount > 0;
        } else {
            panic!("body_hash is None");
        }

        self.reader.data_consume_hard(amount)
    }

    fn steal(&mut self, amount: usize) -> io::Result<Vec<u8>> {
        let v = self.reader.steal(amount)?;
        self.hash_read_content(&v);
        Ok(v)
    }

    fn steal_eof(&mut self) -> io::Result<Vec<u8>> {
        let v = self.reader.steal_eof()?;
        self.hash_read_content(&v);
        Ok(v)
    }

    fn get_mut(&mut self) -> Option<&mut dyn BufferedReader<Cookie>> {
        None
    }

    fn get_ref(&self) -> Option<&dyn BufferedReader<Cookie>> {
        None
    }

    fn into_inner<'b>(self: Box<Self>)
            -> Option<Box<dyn BufferedReader<Cookie> + 'b>>
            where Self: 'b {
        None
    }

    fn cookie_set(&mut self, cookie: Cookie)
            -> Cookie {
        self.reader.cookie_set(cookie)
    }

    fn cookie_ref(&self) -> &Cookie {
        self.reader.cookie_ref()
    }

    fn cookie_mut(&mut self) -> &mut Cookie {
        self.reader.cookie_mut()
    }
}

// Check that we can use the read interface to stream the contents of
// a packet.
#[cfg(feature = "compression-deflate")]
#[test]
fn packet_parser_reader_interface() {
    // We need the Read trait.
    use std::io::Read;

    let expected = crate::tests::manifesto();

    // A message containing a compressed packet that contains a
    // literal packet.
    let pp = PacketParser::from_bytes(
        crate::tests::message("compressed-data-algo-1.gpg")).unwrap().unwrap();

    // The message has the form:
    //
    //   [ compressed data [ literal data ] ]
    //
    // packet is the compressed data packet; ppo is the literal data
    // packet.
    let packet_depth = pp.recursion_depth();
    let (packet, ppr) = pp.recurse().unwrap();
    let pp_depth = ppr.as_ref().unwrap().recursion_depth();
    if let Packet::CompressedData(_) = packet {
    } else {
        panic!("Expected a compressed data packet.");
    }

    let relative_position = pp_depth - packet_depth;
    assert_eq!(relative_position, 1);

    let mut pp = ppr.unwrap();

    if let Packet::Literal(_) = pp.packet {
    } else {
        panic!("Expected a literal data packet.");
    }

    // Check that we can read the packet's contents.  We do this one
    // byte at a time to exercise the cursor implementation.
    for i in 0..expected.len() {
        let mut buf = [0u8; 1];
        let r = pp.read(&mut buf).unwrap();
        assert_eq!(r, 1);
        assert_eq!(buf[0], expected[i]);
    }
    // And, now an EOF.
    let mut buf = [0u8; 1];
    let r = pp.read(&mut buf).unwrap();
    assert_eq!(r, 0);

    // Make sure we can still get the next packet (which in this case
    // is just EOF).
    let (packet, ppr) = pp.recurse().unwrap();
    assert!(ppr.is_eof());
    // Since we read all of the data, we expect content to be None.
    assert_eq!(packet.unprocessed_body().unwrap().len(), 0);
}

impl<'a> PacketParser<'a> {
    /// Tries to decrypt the current packet.
    ///
    /// On success, this function pushes one or more readers onto the
    /// `PacketParser`'s reader stack, and clears the packet parser's
    /// `encrypted` flag (see [`PacketParser::encrypted`]).
    ///
    ///   [`PacketParser::encrypted`]: struct.PacketParser.html#method.encrypted
    ///
    /// If this function is called on a packet that does not contain
    /// encrypted data, or some of the data was already read, then it
    /// returns [`Error::InvalidOperation`].
    ///
    ///   [`Error::InvalidOperation`]: ../enum.Error.html#variant.InvalidOperation
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> sequoia_openpgp::Result<()> {
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::Packet;
    /// use openpgp::fmt::hex;
    /// use openpgp::types::SymmetricAlgorithm;
    /// use openpgp::parse::{Parse, PacketParserResult, PacketParser};
    ///
    /// // Parse an encrypted message.
    /// let message_data: &[u8] = // ...
    /// #    include_bytes!("../tests/data/messages/encrypted-aes256-password-123.gpg");
    /// let mut ppr = PacketParser::from_bytes(message_data)?;
    /// while let PacketParserResult::Some(mut pp) = ppr {
    ///     if let Packet::SEIP(_) = pp.packet {
    ///         pp.decrypt(SymmetricAlgorithm::AES256,
    ///                    &hex::decode("7EF4F08C44F780BEA866961423306166\
    ///                                  B8912C43352F3D9617F745E4E3939710")?
    ///                        .into())?;
    ///     }
    ///
    ///     // Start parsing the next packet, recursing.
    ///     ppr = pp.recurse()?.1;
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// # Security Considerations
    ///
    /// This functions returns rich errors in case the decryption
    /// fails.  In combination with certain asymmetric algorithms
    /// (RSA), this may lead to compromise of secret key material.
    /// See [Section 14 of RFC 4880].  Do not relay these errors in
    /// situations where an attacker can request decryption of
    /// messages in an automated fashion.
    ///
    ///   [Section 14 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-14
    pub fn decrypt(&mut self, algo: SymmetricAlgorithm, key: &SessionKey)
        -> Result<()>
    {
        let indent = self.recursion_depth();
        tracer!(TRACE, "PacketParser::decrypt", indent);

        if self.content_was_read {
            return Err(Error::InvalidOperation(
                format!("Packet's content has already been read.")).into());
        }
        if ! self.encrypted {
            return Err(Error::InvalidOperation(
                format!("Packet not encrypted.")).into());
        }

        if algo.key_size()? != key.len () {
            return Err(Error::InvalidOperation(
                format!("Bad key size: {} expected: {}",
                        key.len(), algo.key_size()?)).into());
        }

        match self.packet.clone() {
            Packet::SEIP(_) => {
                // Get the first blocksize plus two bytes and check
                // whether we can decrypt them using the provided key.
                // Don't actually consume them in case we can't.
                let bl = algo.block_size()?;

                {
                    let mut dec = Decryptor::new(
                        algo, key, &self.data_hard(bl + 2)?[..bl + 2])?;
                    let mut header = vec![ 0u8; bl + 2 ];
                    dec.read_exact(&mut header)?;

                    if !(header[bl - 2] == header[bl]
                         && header[bl - 1] == header[bl + 1]) {
                        return Err(Error::InvalidSessionKey(
                            format!(
                                "Last two 16-bit quantities don't match: {}",
                                crate::fmt::to_hex(&header[..], false)))
                                   .into());
                    }
                }

                // Ok, we can decrypt the data.  Push a Decryptor and
                // a HashedReader on the `BufferedReader` stack.

                // This can't fail, because we create a decryptor
                // above with the same parameters.
                let reader = self.take_reader();
                let mut reader = BufferedReaderDecryptor::with_cookie(
                    algo, key, reader, Cookie::default()).unwrap();
                reader.cookie_mut().level = Some(self.recursion_depth());

                t!("Pushing Decryptor, level {:?}.", reader.cookie_ref().level);

                // And the hasher.
                let mut reader = HashedReader::new(
                    reader, HashesFor::MDC,
                    vec![HashingMode::Binary(HashAlgorithm::SHA1)]);
                reader.cookie_mut().level = Some(self.recursion_depth());

                t!("Pushing HashedReader, level {:?}.",
                   reader.cookie_ref().level);

                // A SEIP packet is a container that always ends with
                // an MDC packet.  But, if the packet preceding the
                // MDC packet uses an indeterminate length encoding
                // (gpg generates these for compressed data packets,
                // for instance), the parser has to detect the EOF and
                // be careful to not read any further.  Unfortunately,
                // our decompressor buffers the data.  To stop the
                // decompressor from buffering the MDC packet, we use
                // a buffered_reader::Reserve.  Note: we do this
                // unconditionally, since it doesn't otherwise
                // interfere with parsing.

                // An MDC consists of a 1-byte CTB, a 1-byte length
                // encoding, and a 20-byte hash.
                let mut reader = buffered_reader::Reserve::with_cookie(
                    reader, 1 + 1 + 20,
                    Cookie::new(self.recursion_depth()));
                reader.cookie_mut().fake_eof = true;

                t!("Pushing buffered_reader::Reserve, level: {}.",
                   self.recursion_depth());

                // Consume the header.  This shouldn't fail, because
                // it worked when reading the header.
                reader.data_consume_hard(bl + 2).unwrap();

                self.reader = Box::new(reader);
                self.encrypted = false;

                Ok(())
            },

            Packet::AED(AED::V1(aed)) => {
                let chunk_size =
                    aead::chunk_size_usize(aed.chunk_size())?;

                // Read the first chunk and check whether we can
                // decrypt it using the provided key.  Don't actually
                // consume them in case we can't.
                {
                    // We need a bit more than one chunk so that
                    // `aead::Decryptor` won't see EOF and think that
                    // it has a partial block and it needs to verify
                    // the final chunk.
                    let amount = aead::chunk_size_usize(
                        aed.chunk_digest_size()?
                        + aed.aead().digest_size()? as u64)?;

                    let data = self.data(amount)?;
                    let dec = aead::Decryptor::new(
                        1, aed.symmetric_algo(), aed.aead(), chunk_size,
                        aed.iv(), key,
                        &data[..cmp::min(data.len(), amount)])?;
                    let mut chunk = Vec::new();
                    dec.take(aed.chunk_size() as u64).read_to_end(&mut chunk)?;
                }

                // Ok, we can decrypt the data.  Push a Decryptor and
                // a HashedReader on the `BufferedReader` stack.

                // This can't fail, because we create a decryptor
                // above with the same parameters.
                let reader = self.take_reader();
                let mut reader = aead::BufferedReaderDecryptor::with_cookie(
                    1, aed.symmetric_algo(), aed.aead(), chunk_size,
                    aed.iv(), key, reader, Cookie::default()).unwrap();
                reader.cookie_mut().level = Some(self.recursion_depth());

                t!("Pushing aead::Decryptor, level {:?}.",
                   reader.cookie_ref().level);

                self.reader = Box::new(reader);
                self.encrypted = false;

                Ok(())
            },

            _ =>
                Err(Error::InvalidOperation(
                    format!("Can't decrypt {:?} packets.",
                            self.packet.tag())).into())
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    enum Data<'a> {
        File(&'a str),
        String(&'a [u8]),
    }

    impl<'a> Data<'a> {
        fn content(&self) -> Vec<u8> {
            match self {
                Data::File(filename) => crate::tests::message(filename).to_vec(),
                Data::String(data) => data.to_vec(),
            }
        }
    }

    struct DecryptTest<'a> {
        filename: &'a str,
        algo: SymmetricAlgorithm,
        key_hex: &'a str,
        plaintext: Data<'a>,
        paths: &'a[ (Tag, &'a[ usize ] ) ],
    }
    const DECRYPT_TESTS: &[DecryptTest] = &[
        // Messages with a relatively simple structure:
        //
        //   [ SKESK SEIP [ Literal MDC ] ].
        //
        // And simple length encodings (no indeterminate length
        // encodings).
        DecryptTest {
            filename: "encrypted-aes256-password-123.gpg",
            algo: SymmetricAlgorithm::AES256,
            key_hex: "7EF4F08C44F780BEA866961423306166B8912C43352F3D9617F745E4E3939710",
            plaintext: Data::File("a-cypherpunks-manifesto.txt"),
            paths: &[
                (Tag::SKESK, &[ 0 ]),
                (Tag::SEIP, &[ 1 ]),
                (Tag::Literal, &[ 1, 0 ]),
                (Tag::MDC, &[ 1, 1 ]),
            ],
        },
        DecryptTest {
            filename: "encrypted-aes192-password-123456.gpg",
            algo: SymmetricAlgorithm::AES192,
            key_hex: "B2F747F207EFF198A6C826F1D398DE037986218ED468DB61",
            plaintext: Data::File("a-cypherpunks-manifesto.txt"),
            paths: &[
                (Tag::SKESK, &[ 0 ]),
                (Tag::SEIP, &[ 1 ]),
                (Tag::Literal, &[ 1, 0 ]),
                (Tag::MDC, &[ 1, 1 ]),
            ],
        },
        DecryptTest {
            filename: "encrypted-aes128-password-123456789.gpg",
            algo: SymmetricAlgorithm::AES128,
            key_hex: "AC0553096429260B4A90B1CEC842D6A0",
            plaintext: Data::File("a-cypherpunks-manifesto.txt"),
            paths: &[
                (Tag::SKESK, &[ 0 ]),
                (Tag::SEIP, &[ 1 ]),
                (Tag::Literal, &[ 1, 0 ]),
                (Tag::MDC, &[ 1, 1 ]),
            ],
        },
        DecryptTest {
            filename: "encrypted-twofish-password-red-fish-blue-fish.gpg",
            algo: SymmetricAlgorithm::Twofish,
            key_hex: "96AFE1EDFA7C9CB7E8B23484C718015E5159CFA268594180D4DB68B2543393CB",
            plaintext: Data::File("a-cypherpunks-manifesto.txt"),
            paths: &[
                (Tag::SKESK, &[ 0 ]),
                (Tag::SEIP, &[ 1 ]),
                (Tag::Literal, &[ 1, 0 ]),
                (Tag::MDC, &[ 1, 1 ]),
            ],
        },

        // More complex messages.  In particular, some of these
        // messages include compressed data packets, and some are
        // signed.  But what makes these particularly complex is the
        // use of an indeterminate length encoding, which checks the
        // buffered_reader::Reserve hack.
        #[cfg(feature = "compression-deflate")]
        DecryptTest {
            filename: "seip/msg-compression-not-signed-password-123.pgp",
            algo: SymmetricAlgorithm::AES128,
            key_hex: "86A8C1C7961F55A3BE181A990D0ABB2A",
            plaintext: Data::String(b"compression, not signed\n"),
            paths: &[
                (Tag::SKESK, &[ 0 ]),
                (Tag::SEIP, &[ 1 ]),
                (Tag::CompressedData, &[ 1, 0 ]),
                (Tag::Literal, &[ 1, 0, 0 ]),
                (Tag::MDC, &[ 1, 1 ]),
            ],
        },
        #[cfg(feature = "compression-deflate")]
        DecryptTest {
            filename: "seip/msg-compression-signed-password-123.pgp",
            algo: SymmetricAlgorithm::AES128,
            key_hex: "1B195CD35CAD4A99D9399B4CDA4CDA4E",
            plaintext: Data::String(b"compression, signed\n"),
            paths: &[
                (Tag::SKESK, &[ 0 ]),
                (Tag::SEIP, &[ 1 ]),
                (Tag::CompressedData, &[ 1, 0 ]),
                (Tag::OnePassSig, &[ 1, 0, 0 ]),
                (Tag::Literal, &[ 1, 0, 1 ]),
                (Tag::Signature, &[ 1, 0, 2 ]),
                (Tag::MDC, &[ 1, 1 ]),
            ],
        },
        DecryptTest {
            filename: "seip/msg-no-compression-not-signed-password-123.pgp",
            algo: SymmetricAlgorithm::AES128,
            key_hex: "AFB43B83A4B9D971E4B4A4C53749076A",
            plaintext: Data::String(b"no compression, not signed\n"),
            paths: &[
                (Tag::SKESK, &[ 0 ]),
                (Tag::SEIP, &[ 1 ]),
                (Tag::Literal, &[ 1, 0 ]),
                (Tag::MDC, &[ 1, 1 ]),
            ],
        },
        DecryptTest {
            filename: "seip/msg-no-compression-signed-password-123.pgp",
            algo: SymmetricAlgorithm::AES128,
            key_hex: "9D5DB92F77F0E4A356EE53813EF2C3DC",
            plaintext: Data::String(b"no compression, signed\n"),
            paths: &[
                (Tag::SKESK, &[ 0 ]),
                (Tag::SEIP, &[ 1 ]),
                (Tag::OnePassSig, &[ 1, 0 ]),
                (Tag::Literal, &[ 1, 1 ]),
                (Tag::Signature, &[ 1, 2 ]),
                (Tag::MDC, &[ 1, 3 ]),
            ],
        },

        // AEAD encrypted messages.
        DecryptTest {
            filename: "aed/msg-aes128-eax-chunk-size-64-password-123.pgp",
            algo: SymmetricAlgorithm::AES128,
            key_hex: "E88151F2B6F6F6F0AE6B56ED247AA61B",
            plaintext: Data::File("a-cypherpunks-manifesto.txt"),
            paths: &[
                (Tag::SKESK, &[ 0 ]),
                (Tag::AED, &[ 1 ]),
                (Tag::Literal, &[ 1, 0 ]),
            ],
        },
        DecryptTest {
            filename: "aed/msg-aes128-eax-chunk-size-134217728-password-123.pgp",
            algo: SymmetricAlgorithm::AES128,
            key_hex: "D7EE3F3B049DE011687EC9E08D6DCBB0",
            plaintext: Data::File("a-cypherpunks-manifesto.txt"),
            paths: &[
                (Tag::SKESK, &[ 0 ]),
                (Tag::AED, &[ 1 ]),
                (Tag::Literal, &[ 1, 0 ]),
            ],
        },
    ];

    // Consume packets until we get to one in `keep`.
    fn consume_until<'a>(mut ppr: PacketParserResult<'a>,
                         ignore_first: bool, keep: &[Tag], skip: &[Tag])
        -> PacketParserResult<'a>
    {
        if ignore_first {
            ppr = ppr.unwrap().recurse().unwrap().1;
        }

        while let PacketParserResult::Some(pp) = ppr {
            let tag = pp.packet.tag();
            for t in keep.iter() {
                if *t == tag {
                    return PacketParserResult::Some(pp);
                }
            }

            let mut ok = false;
            for t in skip.iter() {
                if *t == tag {
                    ok = true;
                }
            }
            if !ok {
                panic!("Packet not in keep ({:?}) or skip ({:?}) set: {:?}",
                       keep, skip, pp.packet);
            }

            ppr = pp.recurse().unwrap().1;
        }
        return ppr;
    }

    #[test]
    fn decrypt_test() {
        decrypt_test_common(false);
    }

    #[test]
    fn decrypt_test_stream() {
        decrypt_test_common(true);
    }

    fn decrypt_test_common(stream: bool) {
        for test in DECRYPT_TESTS.iter() {
            if !test.algo.is_supported() {
                eprintln!("Algorithm {} unsupported, skipping", test.algo);
                continue;
            }

            eprintln!("Decrypting {}, streaming content: {}",
                      test.filename, stream);

            let ppr = PacketParserBuilder::from_bytes(
                crate::tests::message(test.filename)).unwrap()
                .buffer_unread_content()
                .build()
                .expect(&format!("Error reading {}", test.filename)[..]);

            let mut ppr = consume_until(
                ppr, false, &[ Tag::SEIP, Tag::AED ][..],
                &[ Tag::SKESK, Tag::PKESK ][..] );
            if let PacketParserResult::Some(ref mut pp) = ppr {
                let key = crate::fmt::from_hex(test.key_hex, false)
                    .unwrap().into();

                pp.decrypt(test.algo, &key).unwrap();
            } else {
                panic!("Expected a SEIP/AED packet.  Got: {:?}", ppr);
            }

            let mut ppr = consume_until(
                ppr, true, &[ Tag::Literal ][..],
                &[ Tag::OnePassSig, Tag::CompressedData ][..]);
            if let PacketParserResult::Some(ref mut pp) = ppr {
                if stream {
                    let mut body = Vec::new();
                    loop {
                        let mut b = [0];
                        if pp.read(&mut b).unwrap() == 0 {
                            break;
                        }
                        body.push(b[0]);
                    }

                    assert_eq!(&body[..],
                               &test.plaintext.content()[..],
                               "{:?}", pp.packet);
                } else {
                    pp.buffer_unread_content().unwrap();
                    if let Packet::Literal(l) = &pp.packet {
                        assert_eq!(l.body(), &test.plaintext.content()[..],
                                   "{:?}", pp.packet);
                    } else {
                        panic!("Expected literal, got: {:?}", pp.packet);
                    }
                }
            } else {
                panic!("Expected a Literal packet.  Got: {:?}", ppr);
            }

            let ppr = consume_until(
                ppr, true, &[ Tag::MDC ][..], &[ Tag::Signature ][..]);
            if let PacketParserResult::Some(
                PacketParser { packet: Packet::MDC(ref mdc), .. }) = ppr
            {
                assert_eq!(mdc.computed_digest(), mdc.digest(),
                           "MDC doesn't match");
            }

            if ppr.is_eof() {
                // AED packets don't have an MDC packet.
                continue;
            }
            let ppr = consume_until(
                ppr, true, &[][..], &[][..]);
            assert!(ppr.is_eof());
        }
    }

    #[test]
    fn message_validator() {
        for test in DECRYPT_TESTS.iter() {
            if !test.algo.is_supported() {
                eprintln!("Algorithm {} unsupported, skipping", test.algo);
                continue;
            }

            let mut ppr = PacketParserBuilder::from_bytes(
                crate::tests::message(test.filename)).unwrap()
                .build()
                .expect(&format!("Error reading {}", test.filename)[..]);

            // Make sure we actually decrypted...
            let mut saw_literal = false;
            while let PacketParserResult::Some(mut pp) = ppr {
                assert!(pp.possible_message().is_ok());

                match pp.packet {
                    Packet::SEIP(_) | Packet::AED(_) => {
                        let key = crate::fmt::from_hex(test.key_hex, false)
                            .unwrap().into();
                        pp.decrypt(test.algo, &key).unwrap();
                    },
                    Packet::Literal(_) => {
                        assert!(! saw_literal);
                        saw_literal = true;
                    },
                    _ => {},
                }

                ppr = pp.recurse().unwrap().1;
            }
            assert!(saw_literal);
            if let PacketParserResult::EOF(eof) = ppr {
                assert!(eof.is_message().is_ok());
            } else {
                unreachable!();
            }
        }
    }

    #[test]
    fn keyring_validator() {
        use std::io::Cursor;
        for test in &["testy.pgp",
                      "lutz.gpg",
                      "testy-new.pgp",
                      "neal.pgp"]
        {
            let mut ppr = PacketParserBuilder::from_reader(
                Cursor::new(crate::tests::key("testy.pgp")).chain(
                    Cursor::new(crate::tests::key(test)))).unwrap()
                .build()
                .expect(&format!("Error reading {:?}", test));

            while let PacketParserResult::Some(pp) = ppr {
                assert!(pp.possible_keyring().is_ok());
                ppr = pp.recurse().unwrap().1;
            }
            if let PacketParserResult::EOF(eof) = ppr {
                assert!(eof.is_keyring().is_ok());
                assert!(eof.is_cert().is_err());
            } else {
                unreachable!();
            }
        }
    }

    #[test]
    fn cert_validator() {
        for test in &["testy.pgp",
                      "lutz.gpg",
                      "testy-new.pgp",
                      "neal.pgp"]
        {
            let mut ppr = PacketParserBuilder::from_bytes(crate::tests::key(test))
                .unwrap()
                .build()
                .expect(&format!("Error reading {:?}", test));

            while let PacketParserResult::Some(pp) = ppr {
                assert!(pp.possible_keyring().is_ok());
                assert!(pp.possible_cert().is_ok());
                ppr = pp.recurse().unwrap().1;
            }
            if let PacketParserResult::EOF(eof) = ppr {
                assert!(eof.is_keyring().is_ok());
                assert!(eof.is_cert().is_ok());
            } else {
                unreachable!();
            }
        }
    }

    // If we don't decrypt the SEIP packet, it shows up as opaque
    // content.
    #[test]
    fn message_validator_opaque_content() {
        for test in DECRYPT_TESTS.iter() {
            let mut ppr = PacketParserBuilder::from_bytes(
                crate::tests::message(test.filename)).unwrap()
                .build()
                .expect(&format!("Error reading {}", test.filename)[..]);

            let mut saw_literal = false;
            while let PacketParserResult::Some(pp) = ppr {
                assert!(pp.possible_message().is_ok());

                match pp.packet {
                    Packet::Literal(_) => {
                        assert!(! saw_literal);
                        saw_literal = true;
                    },
                    _ => {},
                }

                ppr = pp.recurse().unwrap().1;
            }
            assert!(! saw_literal);
            if let PacketParserResult::EOF(eof) = ppr {
                eprintln!("eof: {:?}; message: {:?}", eof, eof.is_message());
                assert!(eof.is_message().is_ok());
            } else {
                unreachable!();
            }
        }
    }

    #[test]
    fn path() {
        for test in DECRYPT_TESTS.iter() {
            if !test.algo.is_supported() {
                eprintln!("Algorithm {} unsupported, skipping", test.algo);
                continue;
            }

            eprintln!("Decrypting {}", test.filename);

            let mut ppr = PacketParserBuilder::from_bytes(
                crate::tests::message(test.filename)).unwrap()
                .build()
                .expect(&format!("Error reading {}", test.filename)[..]);

            let mut last_path = vec![];

            let mut paths = test.paths.to_vec();
            // We pop from the end.
            paths.reverse();

            while let PacketParserResult::Some(mut pp) = ppr {
                let path = paths.pop().expect("Message longer than expect");
                assert_eq!(path.0, pp.packet.tag());
                assert_eq!(path.1, pp.path());

                assert_eq!(last_path, pp.last_path());
                last_path = pp.path.to_vec();

                eprintln!("  {}: {:?}", pp.packet.tag(), pp.path());

                match pp.packet {
                    Packet::SEIP(_) | Packet::AED(_) => {
                        let key = crate::fmt::from_hex(test.key_hex, false)
                            .unwrap().into();

                        pp.decrypt(test.algo, &key).unwrap();
                    }
                    _ => (),
                }

                ppr = pp.recurse().unwrap().1;
            }
            paths.reverse();
            assert_eq!(paths.len(), 0,
                       "Message shorter than expected (expecting: {:?})",
                       paths);

            if let PacketParserResult::EOF(eof) = ppr {
                assert_eq!(last_path, eof.last_path());
            } else {
                panic!("Expect an EOF");
            }
        }
    }

    #[test]
    fn corrupted_cert() {
        use crate::armor::{Reader, ReaderMode, Kind};

        // The following Cert is corrupted about a third the way
        // through.  Make sure we can recover.
        let mut ppr = PacketParser::from_reader(
            Reader::from_bytes(crate::tests::key("corrupted.pgp"),
                               ReaderMode::Tolerant(Some(Kind::PublicKey))))
            .unwrap();

        let mut sigs = 0;
        let mut subkeys = 0;
        let mut userids = 0;
        let mut uas = 0;
        let mut unknown = 0;
        while let PacketParserResult::Some(pp) = ppr {
            match pp.packet {
                Packet::Signature(_) => sigs += 1,
                Packet::PublicSubkey(_) => subkeys += 1,
                Packet::UserID(_) => userids += 1,
                Packet::UserAttribute(_) => uas += 1,
                Packet::Unknown(ref u) => {
                    unknown += 1;
                    assert_match!(Some(&Error::MalformedPacket(_))
                                  = u.error().downcast_ref());
                },
                _ => (),
            }

            ppr = pp.next().unwrap().1;
        }

        assert_eq!(sigs, 53);
        assert_eq!(subkeys, 3);
        assert_eq!(userids, 5);
        assert_eq!(uas, 0);
        assert_eq!(unknown, 2);
    }

    #[test]
    fn junk_prefix() {
        // Make sure we can read the first packet.
        let msg = crate::tests::message("sig.gpg");

        let ppr = PacketParserBuilder::from_bytes(msg).unwrap()
            .dearmor(packet_parser_builder::Dearmor::Disabled)
            .build();
        assert_match!(Ok(PacketParserResult::Some(ref _pp)) = ppr);


        // Prepend an invalid byte and make sure we fail.  Note: we
        // have a mechanism to skip corruption, however, that is only
        // activated once we've seen a good packet.  This test checks
        // that we don't try to recover.
        let mut msg2 = Vec::new();
        msg2.push(0);
        msg2.extend_from_slice(&msg[..]);

        let ppr = PacketParserBuilder::from_bytes(&msg2[..]).unwrap()
            .dearmor(packet_parser_builder::Dearmor::Disabled)
            .build();
        assert_match!(Err(_) = ppr);
    }

    /// Issue #141.
    #[test]
    fn truncated_packet() {
        for msg in &[&crate::tests::message("literal-mode-b.gpg")[..],
                     &crate::tests::message("literal-mode-t-partial-body.gpg")[..],
        ] {
            // Make sure we can read the first packet.
            let ppr = PacketParserBuilder::from_bytes(msg).unwrap()
                .dearmor(packet_parser_builder::Dearmor::Disabled)
                .build();
            assert_match!(Ok(PacketParserResult::Some(ref _pp)) = ppr);

            // Now truncate the packet.
            let msg2 = &msg[..msg.len() - 1];
            let ppr = PacketParserBuilder::from_bytes(msg2).unwrap()
                .dearmor(packet_parser_builder::Dearmor::Disabled)
                .build().unwrap();
            if let PacketParserResult::Some(pp) = ppr {
                let err = pp.next().err().unwrap();
                assert_match!(Some(&Error::MalformedPacket(_))
                              = err.downcast_ref());
            } else {
                panic!("No packet!?");
            }
        }
    }

    #[test]
    fn max_packet_size() {
        use crate::serialize::Serialize;
        let uid = Packet::UserID("foobar".into());
        let mut buf = Vec::new();
        uid.serialize(&mut buf).unwrap();

        // Make sure we can read it.
        let ppr = PacketParserBuilder::from_bytes(&buf).unwrap()
            .build().unwrap();
        if let PacketParserResult::Some(pp) = ppr {
            assert_eq!(Packet::UserID("foobar".into()), pp.packet);
        } else {
            panic!("failed to parse userid");
        }

        // But if we set the maximum packet size too low, it is parsed
        // into a unknown packet.
        let ppr = PacketParserBuilder::from_bytes(&buf).unwrap()
            .max_packet_size(5)
            .build().unwrap();
        if let PacketParserResult::Some(pp) = ppr {
            if let Packet::Unknown(ref u) = pp.packet {
                assert_eq!(u.tag(), Tag::UserID);
                assert_match!(Some(&Error::PacketTooLarge(_, _, _))
                              = u.error().downcast_ref());
            } else {
                panic!("expected an unknown packet, got {:?}", pp.packet);
            }
        } else {
            panic!("failed to parse userid");
        }

    }

    /// We erroneously assumed that when BufferedReader::next() is
    /// called, a SEIP container be opaque and hence there cannot be a
    /// buffered_reader::Reserve on the stack with Cookie::fake_eof
    /// set.  But, we could simply call BufferedReader::next() after
    /// the SEIP packet is decrypted, or buffer a SEIP packet's body,
    /// then call BufferedReader::recurse(), which falls back to
    /// BufferedReader::next() because some data has been read.
    #[test]
    fn issue_455() -> Result<()> {
        let sk: SessionKey =
            crate::fmt::hex::decode("3E99593760EE241488462BAFAE4FA268\
                                     260B14B82D310D196DCEC82FD4F67678")?.into();
        let algo = SymmetricAlgorithm::AES256;

        // Decrypt, then call BufferedReader::next().
        eprintln!("Decrypt, then next():\n");
        let mut ppr = PacketParser::from_bytes(
            crate::tests::message("encrypted-to-testy.gpg"))?;
        while let PacketParserResult::Some(mut pp) = ppr {
            match &pp.packet {
                Packet::SEIP(_) => {
                    pp.decrypt(algo, &sk)?;
                },
                _ => (),
            }
            // Used to trigger the assertion failure on the SEIP
            // packet:
            ppr = pp.next()?.1;
        }

        // Decrypt, buffer, then call BufferedReader::recurse().
        eprintln!("\nDecrypt, buffer, then recurse():\n");
        let mut ppr = PacketParser::from_bytes(
            crate::tests::message("encrypted-to-testy.gpg"))?;
        while let PacketParserResult::Some(mut pp) = ppr {
            match &pp.packet {
                Packet::SEIP(_) => {
                    pp.decrypt(algo, &sk)?;
                    pp.buffer_unread_content()?;
                },
                _ => (),
            }
            // Used to trigger the assertion failure on the SEIP
            // packet:
            ppr = pp.recurse()?.1;
        }
        Ok(())
    }

    /// Crash in the AED parser due to missing chunk size validation.
    #[test]
    fn issue_514() -> Result<()> {
        let data = &[212, 43, 1, 0, 0, 125, 212, 0, 10, 10, 10];
        let ppr = PacketParser::from_bytes(&data)?;
        let packet = &ppr.unwrap().packet;
        if let Packet::Unknown(_) = packet {
            Ok(())
        } else {
            panic!("expected unknown packet, got: {:?}", packet);
        }
    }

    /// Malformed subpackets must not cause a hard parsing error.
    #[test]
    fn malformed_embedded_signature() -> Result<()> {
        let ppr = PacketParser::from_bytes(
            crate::tests::file("edge-cases/malformed-embedded-sig.pgp"))?;
        let packet = &ppr.unwrap().packet;
        if let Packet::Unknown(_) = packet {
            Ok(())
        } else {
            panic!("expected unknown packet, got: {:?}", packet);
        }
    }

    /// Malformed notation names must not cause hard parsing errors.
    #[test]
    fn malformed_notation_name() -> Result<()> {
        let ppr = PacketParser::from_bytes(
            crate::tests::file("edge-cases/malformed-notation-name.pgp"))?;
        let packet = &ppr.unwrap().packet;
        if let Packet::Unknown(_) = packet {
            Ok(())
        } else {
            panic!("expected unknown packet, got: {:?}", packet);
        }
    }

    /// Checks that the content hash is correctly computed whether or
    /// not the content has been (fully) read.
    #[test]
    fn issue_537() -> Result<()> {
        // Buffer unread content.
        let ppr0 = PacketParserBuilder::from_bytes(
            crate::tests::message("literal-mode-b.gpg"))?
            .buffer_unread_content()
            .build()?;
        let pp0 = ppr0.unwrap();
        let (packet0, _) = pp0.recurse()?;

        // Drop unread content.
        let ppr1 = PacketParser::from_bytes(
            crate::tests::message("literal-mode-b.gpg"))?;
        let pp1 = ppr1.unwrap();
        let (packet1, _) = pp1.recurse()?;

        // Read content.
        let ppr2 = PacketParser::from_bytes(
            crate::tests::message("literal-mode-b.gpg"))?;
        let mut pp2 = ppr2.unwrap();
        io::copy(&mut pp2, &mut io::sink())?;
        let (packet2, _) = pp2.recurse()?;

        // Partially read content.
        let ppr3 = PacketParser::from_bytes(
            crate::tests::message("literal-mode-b.gpg"))?;
        let mut pp3 = ppr3.unwrap();
        let mut buf = [0];
        let nread = pp3.read(&mut buf)?;
        assert_eq!(buf.len(), nread);
        let (packet3, _) = pp3.recurse()?;

        assert_eq!(packet0, packet1);
        assert_eq!(packet1, packet2);
        assert_eq!(packet2, packet3);
        Ok(())
    }

    /// Checks that newlines are properly normalized when verifying
    /// text signatures.
    #[test]
    fn issue_530_verifying() -> Result<()> {
        use std::io::Write;
        use crate::*;
        use crate::packet::signature;
        use crate::serialize::stream::{Message, Signer};

        use crate::policy::StandardPolicy;
        use crate::{Result, Cert};
        use crate::parse::Parse;
        use crate::parse::stream::*;

        let data = b"one\r\ntwo\r\nthree";

        let p = &StandardPolicy::new();
        let cert: Cert =
            Cert::from_bytes(crate::tests::key("testy-new-private.pgp"))?;
        let signing_keypair = cert.keys().secret()
            .with_policy(p, None).alive().revoked(false).for_signing()
            .nth(0).unwrap()
            .key().clone().into_keypair()?;
        let mut signature = vec![];
        {
            let message = Message::new(&mut signature);
            let mut message = Signer::with_template(
                message, signing_keypair,
                signature::SignatureBuilder::new(SignatureType::Text)
            ).detached().build()?;
            message.write_all(data)?;
            message.finalize()?;
        }

        struct Helper {};
        impl VerificationHelper for Helper {
            fn get_certs(&mut self, _ids: &[KeyHandle]) -> Result<Vec<Cert>> {
                Ok(vec![Cert::from_bytes(crate::tests::key("testy-new.pgp"))?])
            }
            fn check(&mut self, structure: MessageStructure) -> Result<()> {
                for (i, layer) in structure.iter().enumerate() {
                    assert_eq!(i, 0);
                    if let MessageLayer::SignatureGroup { results } = layer {
                        assert_eq!(results.len(), 1);
                        results[0].as_ref().unwrap();
                        assert!(results[0].is_ok());
                        return Ok(());
                    } else {
                        unreachable!();
                    }
                }
                unreachable!()
            }
        }

        let h = Helper {};
        let mut v = DetachedVerifierBuilder::from_bytes(&signature)?
            .with_policy(p, None, h)?;

        for data in &[
            &b"one\r\ntwo\r\nthree"[..], // dos
            b"one\ntwo\nthree",          // unix
            b"one\ntwo\r\nthree",        // mixed
            b"one\r\ntwo\nthree",
            b"one\rtwo\rthree",          // classic mac
        ] {
            v.verify_bytes(data)?;
        }

        Ok(())
    }

    /// Tests for a panic in the SKESK parser.
    #[test]
    fn issue_588() -> Result<()> {
        let data = vec![0x8c, 0x34, 0x05, 0x12, 0x02, 0x00, 0xaf, 0x0d,
                        0xff, 0xff, 0x65];
        let _ = PacketParser::from_bytes(&data);
        Ok(())
    }

    /// Tests for a panic in the packet parser.
    #[test]
    fn packet_parser_on_mangled_cert() -> Result<()> {
        // The armored input cert is mangled.  Currently, Sequoia
        // doesn't grok the mangled armor, but it should not panic.
        let mut ppr = match PacketParser::from_bytes(
            crate::tests::key("bobs-cert-badly-mangled.asc")) {
            Ok(ppr) => ppr,
            Err(_) => return Ok(()),
        };
        while let PacketParserResult::Some(pp) = ppr {
            dbg!(&pp.packet);
            if let Ok((_, tmp)) = pp.recurse() {
                ppr = tmp;
            } else {
                break;
            }
        }
        Ok(())
    }
}