logo
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
//! Functionality for dealing with mostly unparsed certificates.
//!
//! Parsing a certificate is not cheap.  When reading a keyring, most
//! certificates are discarded or never used as they are not relevant.
//! This module provides the [`RawCertParser`] and [`RawCert`] data
//! structures that can help reduce the amount of unnecessary
//! computation.
//!
//! [`RawCertParser`] splits a keyring into [`RawCert`]s by looking
//! primarily at the packet framing and the packet headers.  This is
//! much faster than parsing the packets' contents, as the
//! [`CertParser`] does.
//!
//! [`CertParser`]: crate::cert::CertParser
//!
//! [`RawCert`] exposes just enough functionality to allow the user to
//! quickly check if a certificate is not relevant.  Note: to check if
//! a certificate is really relevant, the check usually needs to be
//! repeated after canonicalizing it (by using, e.g., [`Cert::from`])
//! and validating it (by using [`Cert::with_policy`]).
//!
//! [`Cert::from`]: From<RawCert>
//!
//! # Examples
//!
//! Search for a specific certificate in a keyring:
//!
//! ```rust
//! # use std::convert::TryFrom;
//! #
//! use sequoia_openpgp as openpgp;
//!
//! # use openpgp::Result;
//! use openpgp::cert::prelude::*;
//! use openpgp::cert::raw::RawCertParser;
//! use openpgp::parse::Parse;
//! # use openpgp::serialize::Serialize;
//! #
//! # fn main() -> Result<()> {
//! # fn doit() -> Result<Cert> {
//! #      let (cert, _) = CertBuilder::new()
//! #          .generate()?;
//! #      let fpr = cert.fingerprint();
//! #
//! #      let mut bytes = Vec::new();
//! #      cert.serialize(&mut bytes);
//! for cert in RawCertParser::from_bytes(&bytes)? {
//!     /// Ignore corrupt and invalid certificates.
//!     let cert = if let Ok(cert) = cert {
//!         cert
//!     } else {
//!         continue;
//!     };
//!
//!     if cert.fingerprint() == fpr {
//!         // Found it!  Try to convert it to a Cert.
//!         if let cert = Cert::try_from(cert) {
//!             return cert;
//!         }
//!     }
//! }
//!
//! // Not found.
//! return Err(anyhow::anyhow!("Not found!").into());
//! # }
//! # doit().expect("Found the certificate");
//! # Ok(())
//! # }
//! ```
use std::borrow::Cow;
use std::convert::TryFrom;
use std::fmt;
use std::io::Read;
use std::path::Path;

use buffered_reader::{BufferedReader, Dup, EOF, File, Generic, Memory};

use crate::Error;
use crate::Fingerprint;
use crate::KeyID;
use crate::Result;
use crate::armor;
use crate::cert::Cert;
use crate::packet::Header;
use crate::packet::Key;
use crate::packet::Packet;
use crate::packet::Tag;
use crate::packet::UserID;
use crate::packet::header::BodyLength;
use crate::packet::header::CTB;
use crate::packet::key;
use crate::parse::Cookie;
use crate::parse::PacketParser;
use crate::parse::Parse;
use crate::parse::RECOVERY_THRESHOLD;

use super::TRACE;

mod iter;
pub use iter::KeyIter;

/// A mostly unparsed `Packet`.
///
/// This is returned by [`RawCert::packets`].
///
/// The data includes the OpenPGP framing (i.e., the CTB, and length
/// information).  [`RawPacket::body`] returns just the bytes
/// corresponding to the packet's body, i.e., without the OpenPGP
/// framing.
///
/// You can convert it to a [`Packet`] using `TryFrom`.
///
/// # Examples
///
/// ```rust
/// use sequoia_openpgp as openpgp;
/// # use openpgp::Result;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::cert::raw::RawCert;
/// use openpgp::packet::Packet;
/// use openpgp::packet::Tag;
/// # use openpgp::parse::Parse;
/// # use openpgp::serialize::Serialize;
/// #
/// # fn main() -> Result<()> {
/// #      let (cert, _) = CertBuilder::new()
/// #          .add_signing_subkey()
/// #          .add_certification_subkey()
/// #          .add_transport_encryption_subkey()
/// #          .add_storage_encryption_subkey()
/// #          .add_authentication_subkey()
/// #          .generate()?;
/// #
/// #      let mut bytes = Vec::new();
/// #      cert.as_tsk().serialize(&mut bytes);
/// # let mut count = 0;
/// #
/// # let rawcert = RawCert::from_bytes(&bytes)?;
/// for p in rawcert.packets() {
///     if p.tag() == Tag::SecretSubkey {
///         if let Ok(packet) = Packet::try_from(p) {
///             // Do something with the packet.
/// #           count += 1;
///         }
/// #       else { panic!("Failed to parse packet"); }
///     }
/// }
/// #     assert_eq!(count, 5);
/// #     Ok(())
/// # }
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct RawPacket<'a> {
    tag: Tag,
    header_len: usize,
    data: &'a [u8],
}
assert_send_and_sync!(RawPacket<'_>);

impl fmt::Debug for RawPacket<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RawPacket")
            .field("tag", &self.tag)
            .field("data (bytes)", &self.data.len())
            .finish()
    }
}

impl<'a> RawPacket<'a> {
    fn new(tag: Tag, header_len: usize, bytes: &'a [u8]) -> Self {
        Self {
            tag,
            header_len,
            data: bytes,
        }
    }

    /// Returns the packet's tag.
    pub fn tag(&self) -> Tag {
        self.tag
    }

    /// Returns the packet's bytes.
    pub fn as_bytes(&self) -> &[u8] {
        self.data
    }

    /// Return the packet's body without the OpenPGP framing.
    pub fn body(&self) -> &[u8] {
        &self.data[self.header_len..]
    }
}

impl<'a> TryFrom<RawPacket<'a>> for Packet {
    type Error = anyhow::Error;

    fn try_from(p: RawPacket<'a>) -> Result<Self> {
        Packet::from_bytes(p.as_bytes())
    }
}

impl<'a> crate::seal::Sealed for RawPacket<'a> {}
impl<'a> crate::serialize::Marshal for RawPacket<'a> {
    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
        o.write_all(self.as_bytes())?;
        Ok(())
    }
}

/// A mostly unparsed `Cert`.
///
/// This data structure contains the unparsed packets for a
/// certificate or key.  The packet sequence is well formed in the
/// sense that the sequence of tags conforms to the [Transferable
/// Public Key grammar] or [Transferable Secret Key grammar], and that
/// it can extract the primary key's fingerprint.  Beyond that, the
/// packets are not guaranteed to be valid.
///
/// [Transferable Public Key grammar]: https://www.rfc-editor.org/rfc/rfc4880#section-11.1
/// [Transferable Secret Key grammar]: https://www.rfc-editor.org/rfc/rfc4880#section-11.2
///
/// This data structure exists to quickly split a large keyring, and
/// only parse those certificates that appear to be relevant.
#[derive(Clone)]
pub struct RawCert<'a> {
    data: Cow<'a, [u8]>,

    fingerprint: Fingerprint,

    // The packet's tag, the length of the header, and the offset of
    // the start of the packet (including the header) into data.
    packets: Vec<(Tag, usize, usize)>,
}
assert_send_and_sync!(RawCert<'_>);

impl<'a> fmt::Debug for RawCert<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RawCert")
            .field("fingerprint", &self.fingerprint)
            .field("packets",
                   &self.packets
                   .iter()
                   .map(|p| format!("{} (offset: {})", p.0, p.1))
                   .collect::<Vec<String>>()
                   .join(", "))
            .field("data (bytes)", &self.data.as_ref().len())
            .finish()
    }
}

impl<'a> PartialEq for RawCert<'a> {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

impl<'a> Eq for RawCert<'a> {
}

impl<'a> RawCert<'a> {
    /// Returns the certificate's bytes.
    ///
    /// If you want an individual packet's bytes, use
    /// [`RawCert::packet`] or [`RawCert::packets`], and then call
    /// [`RawPacket::as_bytes`].
    pub fn as_bytes(&'a self) -> &'a [u8] {
        self.data.as_ref()
    }

    /// Returns the certificate's fingerprint.
    pub fn fingerprint(&self) -> Fingerprint {
        self.fingerprint.clone()
    }

    /// Returns the certificate's Key ID.
    pub fn keyid(&self) -> KeyID {
        KeyID::from(&self.fingerprint)
    }

    /// Returns the ith packet.
    pub fn packet(&self, i: usize) -> Option<RawPacket> {
        let data: &[u8] = self.data.as_ref();

        let &(tag, header_len, start) = self.packets.get(i)?;
        let following = self.packets
            .get(i + 1)
            .map(|&(_, _, offset)| offset)
            .unwrap_or(data.len());

        Some(RawPacket::new(tag, header_len, &data[start..following]))
    }

    /// Returns an iterator over each raw packet.
    pub fn packets(&self) -> impl Iterator<Item=RawPacket> {
        let data: &[u8] = self.data.as_ref();

        let count = self.packets.len();
        (0..count)
            .map(move |i| {
                let (tag, header_len, start) = self.packets[i];
                let following = self.packets
                    .get(i + 1)
                    .map(|&(_, _, offset)| offset)
                    .unwrap_or(data.len());

                RawPacket::new(tag, header_len, &data[start..following])
            })
    }

    /// Returns the number of packets.
    pub fn count(&self) -> usize {
        self.packets.len()
    }

    /// Returns an iterator over the certificate's keys.
    ///
    /// Note: this parses the key packets, but it does not verify any
    /// binding signatures.  As such, this can only be used as part of
    /// a precheck.  If the certificate appears to match, then the
    /// caller must convert the [`RawCert`] to a [`Cert`] or a
    /// [`ValidCert`], depending on the requirements, and perform the
    /// check again.
    ///
    /// [`ValidCert`]: crate::cert::ValidCert
    ///
    /// Use [`subkeys`] to just return the subkeys.  This function
    /// also changes the return type.  Instead of the iterator
    /// returning a [`Key`] whose role is [`key::UnspecifiedRole`],
    /// the role is [`key::SubordinateRole`].
    ///
    /// [`subkeys`]: KeyIter::subkeys
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sequoia_openpgp as openpgp;
    //
    /// # use openpgp::Result;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::cert::raw::RawCertParser;
    /// use openpgp::parse::Parse;
    /// # use openpgp::serialize::Serialize;
    /// #
    /// # fn main() -> Result<()> {
    /// #      let (cert, _) = CertBuilder::new()
    /// #          .add_signing_subkey()
    /// #          .add_certification_subkey()
    /// #          .add_transport_encryption_subkey()
    /// #          .add_storage_encryption_subkey()
    /// #          .add_authentication_subkey()
    /// #          .generate()?;
    /// #
    /// #      let mut bytes = Vec::new();
    /// #      cert.serialize(&mut bytes);
    /// # let mut certs = 0;
    /// # let mut keys = 0;
    /// for cert in RawCertParser::from_bytes(&bytes)? {
    ///     /// Ignore corrupt and invalid certificates.
    ///     let cert = if let Ok(cert) = cert {
    ///         cert
    ///     } else {
    ///         continue;
    ///     };
    ///
    ///     // Iterate over the keys.  Note: this parses the Key
    ///     // packets.
    ///     for key in cert.keys() {
    ///         println!("{}", key.fingerprint());
    /// #       keys += 1;
    ///     }
    /// #   certs += 1;
    /// }
    /// # assert_eq!(certs, 1);
    /// # assert_eq!(keys, 6);
    /// #     Ok(())
    /// # }
    /// ```
    pub fn keys(&self) -> KeyIter<key::PublicParts, key::UnspecifiedRole> {
        KeyIter::new(self)
    }

    // Returns an iterator over the certificate's keys.
    //
    // This is used by `KeyIter`, which implements a number of
    // filters.
    fn keys_internal(&self)
        -> impl Iterator<Item=Key<key::PublicParts, key::UnspecifiedRole>> + '_
    {
        self.packets()
            .filter_map(|p| {
                if matches!(p.tag(),
                            Tag::PublicKey | Tag::PublicSubkey
                            | Tag::SecretKey | Tag::SecretSubkey)
                {
                    Key::from_bytes(p.body())
                        .ok()
                        .map(|k| k.parts_into_public())
                } else {
                    None
                }
            })
    }

    /// Returns the certificate's primary key.
    ///
    /// Note: this parses the primary key packet, but it does not
    /// verify any binding signatures.  As such, this can only be used
    /// as part of a precheck.  If the certificate appears to match,
    /// then the caller must convert the [`RawCert`] to a [`Cert`] or
    /// a [`ValidCert`], depending on the requirements, and perform
    /// the check again.
    ///
    /// [`ValidCert`]: crate::cert::ValidCert
    pub fn primary_key(&self) -> Key<key::PublicParts, key::PrimaryRole> {
        self.keys().next().expect("have a primary key").role_into_primary()
    }

    /// Returns the certificate's User IDs.
    ///
    /// Note: this parses the User ID packets, but it does not verify
    /// any binding signatures.  That is, there is no guarantee that
    /// the User IDs should actually be associated with the primary
    /// key.  As such, this can only be used as part of a precheck.
    /// If a User ID appears to match, then the caller must convert
    /// the [`RawCert`] to a [`Cert`] or a [`ValidCert`], depending on
    /// the requirements, and perform the check again.
    ///
    /// [`ValidCert`]: crate::cert::ValidCert
    pub fn userids(&self) -> impl Iterator<Item=UserID> + '_
    {
        self.packets()
            .filter_map(|p| {
                if p.tag() == Tag::UserID {
                    UserID::try_from(p.body()).ok()
                } else {
                    None
                }
            })
    }
}

impl<'a> TryFrom<&RawCert<'a>> for Cert {
    type Error = anyhow::Error;

    fn try_from(c: &RawCert) -> Result<Self> {
        Cert::from_bytes(c.as_bytes())
    }
}

impl<'a> TryFrom<RawCert<'a>> for Cert {
    type Error = anyhow::Error;

    fn try_from(c: RawCert) -> Result<Self> {
        Cert::try_from(&c)
    }
}

impl<'a> Parse<'a, RawCert<'a>> for RawCert<'a> {
    /// Returns the first RawCert encountered in the reader.
    ///
    /// Returns an error if there are multiple certificates.
    fn from_reader<R: 'a + Read + Send + Sync>(reader: R) -> Result<Self> {
        let mut parser = RawCertParser::from_reader(reader)?;
        if let Some(cert_result) = parser.next() {
            if parser.next().is_some() {
                Err(Error::MalformedCert(
                    "Additional packets found, is this a keyring?".into()
                ).into())
            } else {
                cert_result
            }
        } else {
            Err(Error::MalformedCert("No data".into()).into())
        }
    }
}

impl<'a> crate::seal::Sealed for RawCert<'a> {}
impl<'a> crate::serialize::Marshal for RawCert<'a> {
    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
        o.write_all(self.as_bytes())?;
        Ok(())
    }
}

/// An iterator over a sequence of unparsed certificates, i.e., an
/// OpenPGP keyring.
///
/// A `RawCertParser` returns each certificate that it encounters.
///
/// It implements the same state machine as [`CertParser`], however, a
/// `CertParser` is stricter.  Specifically, a `CertParser` performs
/// some sanity checks on the content of the packets whereas a
/// `RawCertParser` doesn't do those checks, because it avoids parsing
/// the packets' contents; it primarily looks at the packets' framing,
/// and their headers.
///
/// [`CertParser`]: crate::cert::CertParser
///
/// `RawCertParser` checks that the packet sequence is well formed in
/// the sense that the sequence of tags conforms to the [Transferable
/// Public Key grammar] or [Transferable Secret Key grammar], and it
/// performs a few basic checks.  See the documentation for
/// [`RawCert`] for details.
///
/// [Transferable Public Key grammar]: https://www.rfc-editor.org/rfc/rfc4880#section-11.1
/// [Transferable Secret Key grammar]: https://www.rfc-editor.org/rfc/rfc4880#section-11.2
///
/// Because a `RawCertParser` doesn't parse the contents of the
/// packets, it is significantly faster than a [`CertParser`] when
/// many of the certificates in a keyring are irrelevant.
///
/// # Examples
///
/// Search for a specific certificate in a keyring:
///
/// ```rust
/// # use std::convert::TryFrom;
/// #
/// use sequoia_openpgp as openpgp;
///
/// # use openpgp::Result;
/// use openpgp::cert::prelude::*;
/// use openpgp::cert::raw::RawCertParser;
/// use openpgp::parse::Parse;
/// # use openpgp::serialize::Serialize;
/// #
/// # fn main() -> Result<()> {
/// # fn doit() -> Result<Cert> {
/// #      let (cert, _) = CertBuilder::new()
/// #          .generate()?;
/// #      let fpr = cert.fingerprint();
/// #
/// #      let mut bytes = Vec::new();
/// #      cert.serialize(&mut bytes);
/// for cert in RawCertParser::from_bytes(&bytes)? {
///     /// Ignore corrupt and invalid certificates.
///     let cert = if let Ok(cert) = cert {
///         cert
///     } else {
///         continue;
///     };
///
///     if cert.fingerprint() == fpr {
///         // Found it!  Try to convert it to a Cert.
///         if let cert = Cert::try_from(cert) {
///             return cert;
///         }
///     }
/// }
///
/// // Not found.
/// return Err(anyhow::anyhow!("Not found!").into());
/// # }
/// # doit().expect("Found the certificate");
/// # Ok(())
/// # }
/// ```
pub struct RawCertParser<'a>
{
    // If the data is being read from a slice, then the slice.  This
    // is used to avoid copying the data into the RawCert.
    slice: Option<&'a [u8]>,

    // Where `RawCertParser` reads the data.  When reading from a
    // slice, this is a `buffered_reader::Memory`.  Note: the slice
    // field will not be set, if the input needs to be transferred
    // (i.e., dearmored).
    reader: Box<dyn BufferedReader<Cookie> + 'a>,

    // Whether we are dearmoring the input.
    dearmor: bool,

    // The total number of bytes read.
    bytes_read: usize,

    // Any pending error.
    pending_error: Option<anyhow::Error>,

    // Whether there was an unrecoverable error.
    done: bool,
}
assert_send_and_sync!(RawCertParser<'_>);

impl<'a> RawCertParser<'a> {
    fn new<R>(reader: R) -> Result<Self>
    where R: 'a + BufferedReader<Cookie>
    {
        // Check that we can read the first header and that it is
        // reasonable.  Note: an empty keyring is not an error; we're
        // just checking for bad data here.  If not, try again after
        // dearmoring the input.
        let mut dearmor = false;
        let mut dup = Dup::with_cookie(reader, Default::default());
        if ! dup.eof() {
            match Header::parse(&mut dup) {
                Ok(header) => {
                    let tag = header.ctb().tag();
                    if matches!(tag, Tag::Unknown(_) | Tag::Private(_)) {
                        return Err(Error::MalformedCert(
                            format!("A certificate must start with a \
                                     public key or a secret key packet, \
                                     got a {}",
                                    tag))
                                   .into());
                    }
                }
                Err(_err) => {
                    // We failed to read a header.  Try to dearmor the
                    // input.
                    dearmor = true;
                }
            }
        }

        // Strip the Dup reader.
        let mut reader = dup.as_boxed().into_inner().expect("inner");

        if dearmor {
            reader = armor::Reader::from_buffered_reader(
                reader, armor::ReaderMode::Tolerant(None),
                Default::default()).as_boxed();

            let mut dup = Dup::with_cookie(reader, Default::default());
            match Header::parse(&mut dup) {
                Ok(header) => {
                    let tag = header.ctb().tag();
                    if matches!(tag, Tag::Unknown(_) | Tag::Private(_)) {
                        return Err(Error::MalformedCert(
                            format!("A certificate must start with a \
                                     public key or a secret key packet, \
                                     got a {}",
                                    tag))
                                   .into());
                    }
                }
                Err(err) => {
                    return Err(err);
                }
            }

            reader = dup.as_boxed().into_inner().expect("inner");
        }

        Ok(RawCertParser {
            slice: None,
            reader,
            dearmor,
            bytes_read: 0,
            pending_error: None,
            done: false,
        })
    }
}

impl<'a> Parse<'a, RawCertParser<'a>> for RawCertParser<'a>
{
    /// Initializes a `RawCertParser` from a `Read`er.
    fn from_reader<R: 'a + Read + Send + Sync>(reader: R) -> Result<Self> {
        RawCertParser::new(Generic::with_cookie(reader, None, Default::default()))
    }

    /// Initializes a `RawCertParser` from a `File`.
    fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        RawCertParser::new(File::with_cookie(path, Default::default())?)
    }

    /// Initializes a `RawCertParser` from a byte string.
    fn from_bytes<D: AsRef<[u8]> + ?Sized + Send + Sync>(data: &'a D) -> Result<Self> {
        let data = data.as_ref();
        let mut p = RawCertParser::new(Memory::with_cookie(data, Default::default()))?;

        // If we are dearmoring the input, then the slice doesn't
        // reflect the raw packets.
        if ! p.dearmor {
            p.slice = Some(data);
        }
        Ok(p)
    }
}

impl<'a> Iterator for RawCertParser<'a>
{
    type Item = Result<RawCert<'a>>;

    fn next(&mut self) -> Option<Self::Item> {
        tracer!(TRACE, "RawCertParser::next", 0);

        // Return the pending error.
        if let Some(err) = self.pending_error.take() {
            t!("Returning the queued error: {}", err);
            return Some(Err(err));
        }

        if self.done {
            return None;
        }

        if self.reader.eof() && self.dearmor {
            // We are dearmoring and hit EOF.  Maybe there is a second
            // armor block next to this one!

            // Get the reader,
            let reader = std::mem::replace(
                &mut self.reader,
                EOF::with_cookie(Default::default()).as_boxed());

            // peel off the armor reader,
            let reader = reader.into_inner().expect("the armor reader");

            // and install a new one!
            self.reader = armor::Reader::from_buffered_reader(
                reader, armor::ReaderMode::Tolerant(None),
                Default::default()).as_boxed();
        }

        if self.reader.eof() {
            return None;
        }

        let mut reader = Dup::with_cookie(
            std::mem::replace(&mut self.reader,
                              Box::new(EOF::with_cookie(Default::default()))),
                Default::default());

        // The absolute start of this certificate in the stream.
        let cert_start_absolute = self.bytes_read;

        // The number of bytes processed relative to the start of the
        // dup'ed buffered reader.  This may be less than the number
        // of bytes read, e.g., when we encounter a new certificate,
        // we read the header, but we don't necessarily want to
        // consider it consumed.
        let mut processed = 0;

        // The certificate's span relative to the start of the dup'ed
        // buffered reader.  The start will be larger than zero when
        // we skip a marker packet.
        let mut cert_start = 0;
        let mut cert_end = 0;

        // (Tag, header length, offset from start of the certificate)
        let mut packets: Vec<(Tag, usize, usize)> = Vec::new();
        let mut fingerprint = None;

        let mut pending_error = None;
        'packet_parser: loop {
            if reader.eof() {
                break;
            }

            let packet_start = reader.total_out();
            processed = packet_start;

            let mut skip = 0;
            let mut header_len = 0;
            let header = loop {
                match Header::parse(&mut reader) {
                    Err(err) => {
                        if skip == 0 {
                            t!("Reading the next packet's header: {}", err);
                        }

                        if skip >= RECOVERY_THRESHOLD {
                            pending_error = Some(err.context(
                                format!("Splitting keyring at offset {}",
                                        self.bytes_read + packet_start)));
                            processed = reader.total_out();

                            // We tried to recover and failed.  Once
                            // we return the above error, we're done.
                            self.done = true;

                            break 'packet_parser;
                        } else if reader.eof() {
                            t!("EOF while trying to recover");
                            skip += 1;
                            break Header::new(CTB::new(Tag::Reserved),
                                              BodyLength::Full(skip as u32));
                        } else {
                            skip += 1;
                            reader.rewind();
                            reader.consume(packet_start + skip);
                        }
                    }
                    Ok(header) if skip > 0 => {
                        if PacketParser::plausible_cert(&mut reader, &header)
                            .is_ok()
                        {
                            // We recovered.  First return an error.  The
                            // next time this function is called, we'll
                            // resume here.
                            t!("Found a valid header after {} bytes \
                                of junk: {:?}",
                               skip, header);

                            break Header::new(CTB::new(Tag::Reserved),
                                              BodyLength::Full(skip as u32));
                        } else {
                            skip += 1;
                            reader.rewind();
                            reader.consume(packet_start + skip);
                        }
                    }
                    Ok(header) => {
                        header_len = reader.total_out() - packet_start;
                        break header;
                    }
                }
            };

            if skip > 0 {
                // Fabricate a header.
                t!("Recovered after {} bytes of junk", skip);

                pending_error = Some(Error::MalformedPacket(
                    format!("Encountered {} bytes of junk at offset {}",
                            skip, self.bytes_read)).into());

                // Be careful: if we recovered, then we
                // reader.total_out() includes the good header.
                processed += skip;

                break;
            }

            let tag = header.ctb().tag();
            t!("Found a {:?}, length: {:?}",
               tag, header.length());

            if packet_start > cert_start
                && (tag == Tag::PublicKey || tag == Tag::SecretKey)
            {
                // Start of new cert.  Note: we don't advanced
                // processed!  That would consume the header that
                // we want to read the next time this function is
                // called.
                t!("Stopping: found the start of a new cert ({})", tag);
                break;
            }

            match header.length() {
                BodyLength::Full(l) => {
                    let l = *l as usize;

                    match reader.data_consume_hard(l) {
                        Err(err) => {
                            t!("Stopping: reading {}'s body: {}", tag, err);

                            // If we encountered an EOF while reading
                            // the packet body, then we're done.
                            if err.kind() == std::io::ErrorKind::UnexpectedEof {
                                t!("Got an unexpected EOF, done.");
                                self.done = true;
                            }

                            pending_error = Some(
                                anyhow::Error::from(err).context(format!(
                                    "While reading {}'s body", tag)));

                            break;
                        }
                        Ok(data) => {
                            if tag == Tag::PublicKey
                                || tag == Tag::SecretKey
                            {
                                let data = &data[..l];
                                match Key::from_bytes(data) {
                                    Err(err) => {
                                        t!("Stopping: parsing public key: {}",
                                           err);
                                        pending_error = Some(err);
                                        break;
                                    }
                                    Ok(key) => {
                                        fingerprint = Some(key.fingerprint());
                                    }
                                }
                            }
                        }
                    }
                }
                BodyLength::Partial(_) => {
                    t!("Stopping: Partial body length not allowed \
                        for {} packets",
                       tag);
                    pending_error = Some(
                        Error::MalformedPacket(
                            format!("Packet {} uses partial body length \
                                     encoding, which is not allowed in \
                                     certificates",
                                    tag))
                            .into());
                    self.done = true;
                    break;
                }
                BodyLength::Indeterminate => {
                    t!("Stopping: Indeterminate length not allowed \
                        for {} packets",
                       tag);
                    pending_error = Some(
                        Error::MalformedPacket(
                            format!("Packet {} uses intedeterminite length \
                                     encoding, which is not allowed in \
                                     certificates",
                                    tag))
                            .into());
                    self.done = true;
                    break;
                }
            }

            let end = reader.total_out();
            processed = end;

            let r = if packet_start == cert_start {
                if tag == Tag::Marker {
                    // Silently skip marker packets at the start of a
                    // packet sequence.
                    cert_start = end;
                    Ok(())
                } else {
                    packets.push((tag, header_len, packet_start));
                    Cert::valid_start(tag)
                }
            } else {
                packets.push((tag, header_len, packet_start));
                Cert::valid_packet(tag)
            };
            if let Err(err) = r {
                t!("Stopping: {:?} => not a certificate: {}", header, err);
                pending_error = Some(err);

                if self.bytes_read == 0 && packet_start == cert_start
                    && matches!(tag, Tag::Unknown(_) | Tag::Private(_))
                {
                    // The very first packet is not known.  Don't
                    // bother to parse anything else.
                    self.done = true;
                }

                break;
            }

            cert_end = end;
        }

        t!("{} bytes processed; RawCert @ offset {}, {} bytes",
           processed,
           self.bytes_read + cert_start, cert_end - cert_start);

        assert!(cert_start <= cert_end);
        assert!(cert_end <= processed);
        self.bytes_read += processed;

        // Strip the buffered_reader::Dup.
        self.reader = Box::new(reader).into_inner()
            .expect("just put it there");

        // Consume the data.
        let cert_data = &self.reader
            .data_consume_hard(processed)
            .expect("just read it")[cert_start..cert_end];

        if let Some(err) = pending_error.take() {
            if cert_start == cert_end {
                // We didn't read anything.
                t!("Directly returning the error");
                return Some(Err(err));
            } else {
                t!("Queuing the error");
                self.pending_error = Some(err);
            }
        }

        if cert_start == cert_end {
            t!("No data.");
            return None;
        }

        Some(Ok(RawCert {
            data: if let Some(slice) = self.slice.as_ref() {
                let data = &slice[cert_start_absolute + cert_start
                                  ..cert_start_absolute + cert_end];
                assert_eq!(data, cert_data);
                Cow::Borrowed(data)
            } else {
                Cow::Owned(cert_data.to_vec())
            },
            fingerprint: fingerprint.expect("set"),
            packets,
        }))
    }
}

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

    use crate::cert::CertParser;
    use crate::cert::CertBuilder;
    use crate::packet::Literal;
    use crate::parse::RECOVERY_THRESHOLD;
    use crate::parse::PacketParserResult;
    use crate::serialize::Serialize;
    use crate::types::DataFormat;
    use crate::packet::Unknown;
    use crate::packet::CompressedData;

    fn cert_cmp(a: Cert, b: Cert)
    {
        if a == b {
            return;
        }

        let a: Vec<Packet> = a.into();
        let b: Vec<Packet> = b.into();

        for (i, (a, b)) in a.iter().zip(b.iter()).enumerate() {
            if a != b {
                panic!("Differ at element #{}:\n  {:?}\n  {:?}",
                       i, a, b);
            }
        }
        if a.len() > b.len() {
            eprintln!("Left has more packets:");
            for p in &a[b.len()..] {
                eprintln!("  - {}", p.tag());
            }
        }
        if b.len() > a.len() {
            eprintln!("Right has more packets:");
            for p in &b[a.len()..] {
                eprintln!("  - {}", p.tag());
            }
        }
        if a.len() != b.len() {
            panic!("Different lengths (common prefix identical): {} vs. {}",
                   a.len(), b.len());
        }
    }

    // Compares the result of a RawCertParser with the results of a
    // CertParser on a particular byte stream.
    fn compare_parse(bytes: &[u8]) -> Vec<RawCert> {
        let mut result = Vec::new();

        // We do the comparison two times: once with a byte stream
        // (this exercises the Cow::Borrowed path), and one
        // with a buffered reader (this exercises the Cow::Owned
        // code path).
        for &from_bytes in [true, false].iter() {
            let cp = CertParser::from_bytes(bytes);
            let rp = if from_bytes {
                eprintln!("=== RawCertParser::from_bytes");
                RawCertParser::from_bytes(bytes)
            } else {
                eprintln!("=== RawCertParser::from_reader");
                RawCertParser::from_reader(std::io::Cursor::new(bytes))
            };

            assert_eq!(cp.is_err(), rp.is_err(),
                       "CertParser: {:?}; RawCertParser: {:?}",
                       cp.map(|_| "Parsed"),
                       rp.map(|_| "Parsed"));
            if cp.is_err() && rp.is_err() {
                return Vec::new();
            }

            let mut cp = cp.expect("valid");
            let mut rp = rp.expect("valid");

            let mut raw_certs = Vec::new();
            loop {
                eprintln!("=== NEXT CERTPARSER");
                let c = cp.next();
                eprintln!("=== END CERTPARSER");
                eprintln!("=== NEXT RAWCERTPARSER");
                let r = rp.next();
                eprintln!("=== END RAWCERTPARSER");

                let (c, r) = match (c, r) {
                    // Both return ok.
                    (Some(Ok(c)), Some(Ok(r))) => (c, r),
                    // Both return an error.
                    (Some(Err(_)), Some(Err(_))) => continue,
                    // Both return EOF.
                    (None, None) => break,
                    (c, r) => {
                        panic!("\n\
                                CertParser returned: {:?}\n\
                                RawCertParser returned: {:?}",
                               c, r);
                    }
                };

                assert_eq!(c.fingerprint(), r.fingerprint());

                eprintln!("CertParser says:");
                for (i, p) in c.clone().into_iter().enumerate() {
                    eprintln!("  - {}. {}", i, p.tag());
                }

                let rp = Cert::from_bytes(r.as_bytes()).unwrap();
                eprintln!("RawCertParser says:");
                for (i, p) in rp.clone().into_iter().enumerate() {
                    eprintln!("  - {}. {}", i, p.tag());
                }

                cert_cmp(c.clone(), rp);

                raw_certs.push(r);
            }

            result = raw_certs;
        }
        result
    }

    #[test]
    fn empty() {
        let bytes = &[];

        let certs = compare_parse(bytes);
        assert_eq!(certs.len(), 0);
    }

    #[test]
    fn a_cert() {
        let testy = crate::tests::key("testy.pgp");

        let bytes = testy;

        let certs = compare_parse(bytes);
        assert_eq!(certs.len(), 1);
        let cert = &certs[0];
        assert_eq!(cert.as_bytes(), testy);

        let tags = &[ Tag::PublicKey,
                      Tag::UserID, Tag::Signature,
                      Tag::PublicSubkey, Tag::Signature
        ];
        assert_eq!(
            &cert.packets().map(|p| p.tag()).collect::<Vec<Tag>>()[..],
            tags);

        // Check that we can parse the individual packets and that
        // they have the correct tag.
        for (p, tag) in cert.packets().zip(tags.iter()) {
            let ppr = PacketParser::from_bytes(p.as_bytes()).expect("valid");
            if let PacketParserResult::Some(pp) = ppr {
                let (p, pp) = pp.next().expect("valid");
                assert_eq!(p.tag(), *tag);
                assert!(matches!(pp, PacketParserResult::EOF(_)));
            } else {
                panic!("Unexpected EOF");
            }
        }
    }

    #[test]
    fn two_certs() {
        let testy = crate::tests::key("testy.pgp");

        let mut bytes = testy.to_vec();
        bytes.extend_from_slice(testy);

        let certs = compare_parse(&bytes[..]);
        assert_eq!(certs.len(), 2);
        for cert in certs.into_iter() {
            assert_eq!(cert.as_bytes(), testy);
            assert_eq!(
                &cert.packets().map(|p| p.tag()).collect::<Vec<Tag>>()[..],
                &[ Tag::PublicKey,
                   Tag::UserID, Tag::Signature,
                   Tag::PublicSubkey, Tag::Signature
                ]);
        }
    }

    #[test]
    fn marker_packet_ignored() {
        use crate::serialize::Serialize;

        // Only a marker packet.
        let mut marker = Vec::new();
        Packet::Marker(Default::default())
            .serialize(&mut marker).unwrap();
        compare_parse(&marker[..]);

        // Marker at the start.
        let mut testy_with_marker = Vec::new();
        Packet::Marker(Default::default())
            .serialize(&mut testy_with_marker).unwrap();
        testy_with_marker.extend_from_slice(crate::tests::key("testy.pgp"));
        compare_parse(&testy_with_marker[..]);

        // Marker at the end.
        let mut testy_with_marker = Vec::new();
        testy_with_marker.extend_from_slice(crate::tests::key("testy.pgp"));
        Packet::Marker(Default::default())
            .serialize(&mut testy_with_marker).unwrap();
        compare_parse(&testy_with_marker[..]);
    }

    #[test]
    fn invalid_packets() -> Result<()> {
        tracer!(TRACE, "invalid_packets", 0);

        let (cert, _) =
            CertBuilder::general_purpose(None, Some("alice@example.org"))
            .generate()?;
        let cert : Vec<Packet> = cert.into();

        // A userid packet.
        let userid : Packet = cert.clone()
            .into_iter()
            .filter(|p| p.tag() == Tag::UserID)
            .next()
            .unwrap();

        // An unknown packet.
        let tag = Tag::Private(61);
        let unknown : Packet
            = Unknown::new(tag, Error::UnsupportedPacketType(tag).into())
            .into();

        // A literal packet.  (This is a valid OpenPGP Message.)
        let mut lit = Literal::new(DataFormat::Text);
        lit.set_body(b"test".to_vec());
        let lit = Packet::from(lit);

        // A compressed data packet containing a literal data packet.
        // (This is a valid OpenPGP Message.)
        let cd = {
            use crate::types::CompressionAlgorithm;
            use crate::packet;
            use crate::PacketPile;
            use crate::serialize::Serialize;
            use crate::parse::Parse;

            let mut cd = CompressedData::new(
                CompressionAlgorithm::Uncompressed);
            let mut body = Vec::new();
            lit.serialize(&mut body)?;
            cd.set_body(packet::Body::Processed(body));
            let cd = Packet::from(cd);

            // Make sure we created the message correctly: serialize,
            // parse it, and then check its form.
            let mut bytes = Vec::new();
            cd.serialize(&mut bytes)?;

            let pp = PacketPile::from_bytes(&bytes[..])?;

            assert_eq!(pp.descendants().count(), 2);
            assert_eq!(pp.path_ref(&[ 0 ]).unwrap().tag(),
                       packet::Tag::CompressedData);
            assert_eq!(pp.path_ref(&[ 0, 0 ]), Some(&lit));

            cd
        };

        fn check(input: impl Iterator<Item=Packet>) {
            let mut bytes = Vec::new();
            for p in input {
                p.serialize(&mut bytes).unwrap();
            }

            compare_parse(&bytes[..]);
        }

        fn interleave(cert: &Vec<Packet>, p: &Packet) {
            t!("A certificate, a {}.", p.tag());
            check(
                cert.clone().into_iter()
                    .chain(p.clone()));

            t!("A certificate, two {}.", p.tag());
            check(
                cert.clone().into_iter()
                    .chain(p.clone())
                    .chain(p.clone()));

            t!("A {}, a certificate.", p.tag());
            check(
                p.clone().into_iter()
                    .chain(cert.clone()));

            t!("Two {}, a certificate.", p.tag());
            check(
                p.clone().into_iter()
                    .chain(p.clone())
                    .chain(cert.clone()));

            t!("Two {}, a certificate, two {}.", p.tag(), p.tag());
            check(
                p.clone().into_iter()
                    .chain(p.clone())
                    .chain(cert.clone())
                    .chain(p.clone())
                    .chain(p.clone()));

            t!("Two {}, two certificates, two {}, a certificate.");
            check(
                p.clone().into_iter()
                    .chain(p.clone())
                    .chain(cert.clone())
                    .chain(cert.clone())
                    .chain(p.clone())
                    .chain(p.clone())
                    .chain(cert.clone()));
        }

        interleave(&cert, &lit);

        // The certificate parser shouldn't recurse into containers.
        // So, the compressed data packets should show up as a single
        // error.
        interleave(&cert, &cd);


        // The certificate parser should treat unknown packets as
        // valid certificate components.
        let mut cert_plus = cert.clone();
        cert_plus.push(unknown.clone());

        t!("A certificate, an unknown.");
        check(
            cert.clone().into_iter()
                .chain(unknown.clone()));

        t!("An unknown, a certificate.");
        check(
             unknown.clone().into_iter()
                 .chain(cert.clone()));

        t!("A certificate, two unknowns.");
        check(
            cert.clone().into_iter()
                .chain(unknown.clone())
                .chain(unknown.clone()));

        t!("A certificate, an unknown, a certificate.");
        check(
            cert.clone().into_iter()
                .chain(unknown.clone())
                .chain(cert.clone()));

        t!("A Literal, two User IDs");
        check(
            lit.clone().into_iter()
                .chain(userid.clone())
                .chain(userid.clone()));

        t!("A User ID, a certificate");
        check(
            userid.clone().into_iter()
                .chain(cert.clone()));

        t!("Two User IDs, a certificate");
        check(
            userid.clone().into_iter()
                .chain(userid.clone())
                .chain(cert.clone()));

        Ok(())
    }

    fn parse_test(n: usize, literal: bool, bad: usize) -> Result<()> {
        tracer!(TRACE, "t", 0);

        // Parses keyrings with different numbers of keys and
        // different errors.

        // n: number of keys
        // literal: whether to interleave literal packets.
        // bad: whether to insert invalid data (NUL bytes where
        //      the start of a certificate is expected).
        let nulls = vec![ 0; bad ];

        t!("n: {}, literals: {}, bad data: {}",
           n, literal, bad);

        let mut data = Vec::new();

        let mut certs_orig = vec![];
        for i in 0..n {
            let (cert, _) =
                CertBuilder::general_purpose(
                    None, Some(format!("{}@example.org", i)))
                .generate()?;

            cert.as_tsk().serialize(&mut data)?;
            certs_orig.push(cert);

            if literal {
                let mut lit = Literal::new(DataFormat::Text);
                lit.set_body(b"data".to_vec());

                Packet::from(lit).serialize(&mut data)?;
            }
            // Push some NUL bytes.
            data.extend(&nulls[..bad]);
        }
        if n == 0 {
            // Push some NUL bytes even if we didn't add any packets.
            data.extend(&nulls[..bad]);
        }
        assert_eq!(certs_orig.len(), n);

        t!("Start of data: {} {}",
           if let Some(x) = data.get(0) {
               format!("{:02X}", x)
           } else {
               "XX".into()
           },
           if let Some(x) = data.get(1) {
               format!("{:02X}", x)
           } else {
               "XX".into()
           });

        compare_parse(&data);

        Ok(())
    }

    #[test]
    fn parse_keyring_simple() -> Result<()> {
        for n in [1, 100, 0].iter() {
            parse_test(*n, false, 0)?;
        }

        Ok(())
    }

    #[test]
    fn parse_keyring_interleaved_literals() -> Result<()> {
        for n in [1, 100, 0].iter() {
            parse_test(*n, true, 0)?;
        }

        Ok(())
    }

    #[test]
    fn parse_keyring_interleaved_small_junk() -> Result<()> {
        for n in [1, 100, 0].iter() {
            parse_test(*n, false, 1)?;
        }

        Ok(())
    }

    #[test]
    fn parse_keyring_interleaved_unrecoverable_junk() -> Result<()> {
        // PacketParser is pretty good at recovering from junk in the
        // middle: it will search the next RECOVERY_THRESHOLD bytes
        // for a valid packet.  If it finds it, it will turn the junk
        // into a reserved packet and resume.  Insert a lot of NULs to
        // prevent the recovery mechanism from working.
        for n in [1, 100, 0].iter() {
            parse_test(*n, false, 2 * RECOVERY_THRESHOLD)?;
        }

        Ok(())
    }

    #[test]
    fn parse_keyring_interleaved_literal_and_small_junk() -> Result<()> {
        for n in [1, 100, 0].iter() {
            parse_test(*n, true, 1)?;
        }

        Ok(())
    }

    #[test]
    fn parse_keyring_interleaved_literal_and_unrecoverable_junk() -> Result<()> {
        for n in [1, 100, 0].iter() {
            parse_test(*n, true, 2 * RECOVERY_THRESHOLD)?;
        }

        Ok(())
    }

    #[test]
    fn parse_keyring_no_public_key() -> Result<()> {
        tracer!(TRACE, "parse_keyring_no_public_key", 0);

        // The first few packets are not the valid start of a
        // certificate.  Each of those should return in an Error.
        // But, that shouldn't stop us from parsing the rest of the
        // keyring.

        let (cert_1, _) =
            CertBuilder::general_purpose(
                None, Some("a@example.org"))
            .generate()?;
        let cert_1_packets: Vec<Packet>
            = cert_1.into_packets().collect();

        let (cert_2, _) =
            CertBuilder::general_purpose(
                None, Some("b@example.org"))
            .generate()?;

        for n in 1..cert_1_packets.len() {
            t!("n: {}", n);

            let mut data = Vec::new();

            for i in n..cert_1_packets.len() {
                cert_1_packets[i].serialize(&mut data)?;
            }

            cert_2.as_tsk().serialize(&mut data)?;

            compare_parse(&data);
        }

        Ok(())
    }

    #[test]
    fn accessors() {
        let testy = crate::tests::key("testy.pgp");

        let certs = RawCertParser::from_bytes(testy)
            .expect("valid")
            .collect::<Result<Vec<RawCert>>>()
            .expect("valid");
        assert_eq!(certs.len(), 1);
        let cert = &certs[0];
        assert_eq!(cert.as_bytes(), testy);

        assert_eq!(cert.primary_key().fingerprint(),
                   "3E8877C877274692975189F5D03F6F865226FE8B"
                       .parse().expect("valid"));
        assert_eq!(cert.keys().map(|k| k.fingerprint()).collect::<Vec<_>>(),
                   vec![
                       "3E8877C877274692975189F5D03F6F865226FE8B"
                           .parse().expect("valid"),
                       "01F187575BD45644046564C149E2118166C92632"
                           .parse().expect("valid")
                   ]);
        assert_eq!(cert.keys().subkeys()
                   .map(|k| k.fingerprint()).collect::<Vec<_>>(),
                   vec![
                       "01F187575BD45644046564C149E2118166C92632"
                           .parse().expect("valid")
                   ]);
        assert_eq!(
            cert.userids()
                .map(|u| {
                    String::from_utf8_lossy(u.value()).into_owned()
                })
                .collect::<Vec<_>>(),
            vec![ "Testy McTestface <testy@example.org>" ]);
    }

    // Test the raw cert parser implementation.
    #[test]
    fn raw_cert_parser_impl() {
        // Read one certificate.
        let testy = crate::tests::key("testy.pgp");

        let raw = RawCert::from_bytes(testy).expect("valid");
        let cert = Cert::from_bytes(testy).expect("valid");

        assert_eq!(
            raw.keys().map(|k| k.fingerprint()).collect::<Vec<_>>(),
            cert.keys().map(|k| k.fingerprint()).collect::<Vec<_>>());

        assert_eq!(
            raw.userids().collect::<Vec<_>>(),
            cert.userids().map(|ua| ua.userid().clone()).collect::<Vec<_>>());

        // Parse zero certificates.
        eprintln!("Parsing 0 bytes");
        let raw = RawCert::from_bytes(b"");
        match &raw {
            Ok(_) => eprintln!("raw: Ok"),
            Err(err) => eprintln!("raw: {}", err),
        }
        let cert = Cert::from_bytes(b"");
        match &cert {
            Ok(_) => eprintln!("cert: Ok"),
            Err(err) => eprintln!("cert: {}", err),
        }

        assert!(
            matches!(cert.map_err(|e| e.downcast::<Error>()),
                     Err(Ok(Error::MalformedCert(_)))));
        assert!(
            matches!(raw.map_err(|e| e.downcast::<Error>()),
                     Err(Ok(Error::MalformedCert(_)))));

        // Parse two certificates.
        let mut bytes = Vec::new();
        bytes.extend(testy);
        bytes.extend(testy);

        let parser = CertParser::from_bytes(&bytes).expect("valid");
        assert_eq!(parser.count(), 2);

        eprintln!("Parsing two certificates");
        let raw = RawCert::from_bytes(&bytes);
        match &raw {
            Ok(_) => eprintln!("raw: Ok"),
            Err(err) => eprintln!("raw: {}", err),
        }
        let cert = Cert::from_bytes(&bytes);
        match &cert {
            Ok(_) => eprintln!("cert: Ok"),
            Err(err) => eprintln!("cert: {}", err),
        }

        assert!(
            matches!(cert.map_err(|e| e.downcast::<Error>()),
                     Err(Ok(Error::MalformedCert(_)))));
        assert!(
            matches!(raw.map_err(|e| e.downcast::<Error>()),
                     Err(Ok(Error::MalformedCert(_)))));
    }

    #[test]
    fn concatenated_armored_certs() -> Result<()> {
        let mut keyring = Vec::new();
        keyring.extend_from_slice(b"some\ntext\n");
        keyring.extend_from_slice(crate::tests::key("testy.asc"));
        keyring.extend_from_slice(crate::tests::key("testy.asc"));
        keyring.extend_from_slice(b"some\ntext\n");
        keyring.extend_from_slice(crate::tests::key("testy.asc"));
        keyring.extend_from_slice(b"some\ntext\n");
        let certs = RawCertParser::from_bytes(&keyring)?.collect::<Vec<_>>();
        assert_eq!(certs.len(), 3);
        assert!(certs.iter().all(|c| c.is_ok()));
        Ok(())
    }
}