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
use std::collections::BTreeMap;
use std::io::{Cursor, Read, Seek};
use crate::armor::{self, BlockType};
use crate::errors::{Error, Result};
use crate::packet::{Packet, PacketParser};
pub trait Deserializable: Sized {
fn from_bytes(bytes: impl Read) -> Result<Self> {
let mut el = Self::from_bytes_many(bytes);
el.nth(0).ok_or_else(|| Error::NoMatchingPacket)?
}
fn from_string(input: &str) -> Result<(Self, BTreeMap<String, String>)> {
let (mut el, headers) = Self::from_string_many(input)?;
Ok((el.nth(0).ok_or_else(|| Error::NoMatchingPacket)??, headers))
}
#[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
fn from_string_many<'a>(
input: &'a str,
) -> Result<(
Box<dyn Iterator<Item = Result<Self>> + 'a>,
BTreeMap<String, String>,
)> {
Self::from_armor_many(Cursor::new(input))
}
fn from_armor_single<R: Read + Seek>(input: R) -> Result<(Self, BTreeMap<String, String>)> {
let (mut el, headers) = Self::from_armor_many(input)?;
Ok((el.nth(0).ok_or_else(|| Error::NoMatchingPacket)??, headers))
}
#[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
fn from_armor_many<'a, R: Read + Seek + 'a>(
input: R,
) -> Result<(
Box<dyn Iterator<Item = Result<Self>> + 'a>,
BTreeMap<String, String>,
)> {
let mut dearmor = armor::Dearmor::new(input);
dearmor.read_header()?;
let typ = dearmor
.typ
.ok_or_else(|| format_err!("dearmor failed to retrieve armor type"))?;
match typ {
BlockType::PublicKey
| BlockType::PrivateKey
| BlockType::Message
| BlockType::MultiPartMessage(_, _)
| BlockType::Signature
| BlockType::File => {
let headers = dearmor.headers.clone();
Ok((Self::from_bytes_many(dearmor), headers))
}
BlockType::PublicKeyPKCS1(_)
| BlockType::PublicKeyPKCS8
| BlockType::PublicKeyOpenssh
| BlockType::PrivateKeyPKCS1(_)
| BlockType::PrivateKeyPKCS8
| BlockType::PrivateKeyOpenssh => {
unimplemented_err!("key format {:?}", typ);
}
}
}
fn from_bytes_many<'a>(bytes: impl Read + 'a) -> Box<dyn Iterator<Item = Result<Self>> + 'a> {
let packets = PacketParser::new(bytes).filter_map(|p| {
if p.is_ok() {
p.ok()
} else {
warn!("skipping packet: {:?}", p);
None
}
});
Self::from_packets(packets)
}
fn from_packets<'a>(
packets: impl Iterator<Item = Packet> + 'a,
) -> Box<dyn Iterator<Item = Result<Self>> + 'a>;
}