[][src]Struct sequoia_openpgp::cert::CertParser

pub struct CertParser<'a> { /* fields omitted */ }

An iterator over a sequence of certificates, i.e., an OpenPGP keyring.

The source of packets is a fallible iterator over Packets. In this way, it is possible to propagate parse errors.

A CertParser returns each TPK or TSK that it encounters. Its behavior can be modeled using a simple state machine.

In the first and initial state, it looks for the start of a certificate, a Public Key packet or a Secret Key packet. When it encounters such a packet it buffers it, and transitions to the second state. Any other packet or an error causes it to emit an error and stay in the same state. When the source of packets is exhausted, it enters the End state.

In the second state, it looks for packets that belong to a certificate's body. If it encounters a valid body packet, then it buffers it and stays in the same state. If it encounters the start of a certificate, then it emits the buffered certificate, buffers the packet, and stays in the same state. If it encounters an invalid packet (e.g., a Literal Data packet), it emits two items, the buffered certificate, and an error, and then it transitions back to the initial state. When the source of packets is exhausted, it emits the buffered certificate and enters the end state.

In the end state, it emits None.

                      Invalid Packet / Error
                    ,------------------------.
                    v                        |
   Not a      +---------+                +---------+
   Start  .-> | Looking | -------------> | Looking | <-. Cert
 of Cert  |   |   for   |     Start      |   for   |   | Body
  Packet  |   |  Start  |    of Cert     |  Cert   |   | Packet
 / Error  `-- | of Cert |     Packet     |  Body   | --'
              +---------+            .-> +---------+
                   |                 |      |  |
                   |                 `------'  |
                   |    Start of Cert Packet   |
                   |                           |
               EOF |         +-----+           | EOF
                    `------> | End | <---------'
                             +-----+
                              |  ^
                              `--'

The parser does not recurse into containers, thus when it encounters a container like a Compressed Data Packet, it will return an error even if the container contains a valid certificate.

The parser considers unknown packets to be valid body packets. (In a Cert, these show up as Unknown components.) The goal is to provide some future compatibility.

Example

Print information about all certificates in a keyring:

use sequoia_openpgp as openpgp;
use openpgp::parse::Parse;
use openpgp::parse::PacketParser;
use openpgp::cert::prelude::*;

let ppr = PacketParser::from_bytes(&keyring)?;
for certo in CertParser::from(ppr) {
    match certo {
        Ok(cert) => {
            println!("Key: {}", cert.fingerprint());
            for ua in cert.userids() {
                println!("  User ID: {}", ua.userid());
            }
        }
        Err(err) => {
            eprintln!("Error reading keyring: {}", err);
        }
    }
}

When an invalid packet is encountered, an error is returned and parsing continues:

use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::packet::prelude::*;
use openpgp::types::DataFormat;

let mut lit = Literal::new(DataFormat::Text);
lit.set_body(b"test".to_vec());

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

let mut packets : Vec<Packet> = Vec::new();
packets.extend(alice.clone());
packets.push(lit.clone().into());
packets.push(lit.clone().into());
packets.extend(bob.clone());

let r : Vec<Result<Cert>> = CertParser::from(packets).collect();
assert_eq!(r.len(), 4);
assert_eq!(r[0].as_ref().unwrap().fingerprint(), alice.fingerprint());
assert!(r[1].is_err());
assert!(r[2].is_err());
assert_eq!(r[3].as_ref().unwrap().fingerprint(), bob.fingerprint());

Implementations

impl<'a> CertParser<'a>[src]

pub fn from_iter<I, J>(iter: I) -> Self where
    I: 'a + IntoIterator<Item = J>,
    J: 'a + Into<Result<Packet>>, 
[src]

Creates a CertParser from a Result<Packet> iterator.

Note: because we implement From<Packet> for Result<Packet>, it is possible to pass in an iterator over Packets.

Examples

From a Vec<Packet>:

use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::packet::prelude::*;

for certo in CertParser::from_iter(packets) {
    match certo {
        Ok(cert) => {
            println!("Key: {}", cert.fingerprint());
            for ua in cert.userids() {
                println!("  User ID: {}", ua.userid());
            }
        }
        Err(err) => {
            eprintln!("Error reading keyring: {}", err);
        }
    }
}

pub fn unvalidated_cert_filter<F: 'a>(self, filter: F) -> Self where
    F: Fn(&Cert, bool) -> bool
[src]

Filters the Certs prior to validation.

By default, the CertParser only returns valdiated Certs. Checking that a certificate's self-signatures are valid, however, is computationally expensive, and not always necessary. For example, when looking for a small number of certificates in a large keyring, most certificates can be immediately discarded. That is, it is more efficient to filter, validate, and double check, than to validate and filter. (It is necessary to double check, because the check might have been on an invalid part. For example, if searching for a key with a particular Key ID, a matching key might not have any self signatures.)

If the CertParser gave out unvalidated Certs, and provided an interface to validate them, then the caller could implement this check-validate-double-check pattern. Giving out unvalidated Certs, however, is dangerous: inevitably, a Cert will be used without having been validated in a context where it should have been.

This function avoids this class of bugs while still providing a mechanism to filter Certs prior to validation: the caller provides a callback that is invoked on the unvalidated Cert. If the callback returns true, then the parser validates the Cert, and invokes the callback a second time to make sure the Cert is really wanted. If the callback returns false, then the Cert is skipped.

Note: calling this function multiple times on a single CertParser will not replace the existing filter, but install multiple filters.

Examples

use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;

for certr in CertParser::from(ppr)
    .unvalidated_cert_filter(|cert, _| {
        for component in cert.keys() {
            if component.key().keyid() == some_keyid {
                return true;
            }
        }
        false
    })
{
    match certr {
        Ok(cert) => {
            // The Cert contains the subkey.
        }
        Err(err) => {
            eprintln!("Error reading keyring: {}", err);
        }
    }
}

Trait Implementations

impl<'a> Default for CertParser<'a>[src]

impl<'a> From<PacketParserResult<'a>> for CertParser<'a>[src]

fn from(ppr: PacketParserResult<'a>) -> Self[src]

Initializes a CertParser from a PacketParser.

impl<'a> From<Vec<Packet>> for CertParser<'a>[src]

impl<'a> From<Vec<Result<Packet, Error>>> for CertParser<'a>[src]

impl<'a> Iterator for CertParser<'a>[src]

type Item = Result<Cert>

The type of the elements being iterated over.

impl<'a> Parse<'a, CertParser<'a>> for CertParser<'a>[src]

fn from_reader<R: 'a + Read>(reader: R) -> Result<Self>[src]

Initializes a CertParser from a Reader.

fn from_file<P: AsRef<Path>>(path: P) -> Result<Self>[src]

Initializes a CertParser from a File.

fn from_bytes<D: AsRef<[u8]> + ?Sized>(data: &'a D) -> Result<Self>[src]

Initializes a CertParser from a byte string.

Auto Trait Implementations

impl<'a> !RefUnwindSafe for CertParser<'a>

impl<'a> !Send for CertParser<'a>

impl<'a> !Sync for CertParser<'a>

impl<'a> Unpin for CertParser<'a>

impl<'a> !UnwindSafe for CertParser<'a>

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<I> IntoIterator for I where
    I: Iterator
[src]

type Item = <I as Iterator>::Item

The type of the elements being iterated over.

type IntoIter = I

Which kind of iterator are we turning this into?

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.