summaryrefslogtreecommitdiffstats
path: root/openpgp/src/cert/component_iter.rs
blob: 8df64778966fef8112193fdc97756fe4725be00e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
use std::fmt;
use std::time::SystemTime;

use crate::{
    RevocationStatus,
    cert::{
        Cert,
        components::{
            ComponentBinding,
            ComponentBindingIter,
        },
        amalgamation::ComponentAmalgamation,
    },
};

/// Returns a fresh iterator for the component bindings.
pub(crate) type IterFactory<C> =
    fn(&Cert) -> std::slice::Iter<ComponentBinding<C>>;

/// An iterator over all components in a certificate.
///
/// `ComponentIter` follows the builder pattern.  There is no need to
/// explicitly finalize it, however: it already implements the
/// `Iterator` trait.
///
/// By default, `ComponentIter` returns all components without context.
pub struct ComponentIter<'a, C> {
    cert: &'a Cert,
    make_iter: IterFactory<C>,
    iter: ComponentBindingIter<'a, C>,
}

impl<'a, C> fmt::Debug for ComponentIter<'a, C> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ComponentIter")
            .finish()
    }
}

impl<'a, C> Iterator for ComponentIter<'a, C> {
    type Item = &'a C;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|c| c.component())
    }
}

impl<'a, C> ComponentIter<'a, C>
    where C: Ord
{
    /// Returns a new `ComponentIter` instance.
    pub(crate) fn new(cert: &'a Cert, make_iter: IterFactory<C>) -> Self
        where Self: 'a
    {
        let iter = ComponentBindingIter { iter: Some(make_iter(cert)) };
        ComponentIter {
            cert, make_iter, iter,
        }
    }

    /// Changes the iterator to only return components that are valid at
    /// time `time`.
    ///
    /// If `time` is None, then the current time is used.
    ///
    /// See `ValidComponentIter` for the definition of a valid component.
    pub fn policy<T>(self, time: T) -> ValidComponentIter<'a, C>
        where T: Into<Option<SystemTime>>
    {
        ValidComponentIter {
            cert: self.cert,
            iter: self.iter,
            time: time.into().unwrap_or_else(SystemTime::now),
            revoked: None,
        }
    }

    /// Returns the amalgamated primary component at time `time`
    ///
    /// If `time` is None, then the current time is used.
    /// `ValidComponentIter` for the definition of a valid component.
    ///
    /// The primary component is determined by taking the components that
    /// are alive at time `t`, and sorting them as follows:
    ///
    ///   - non-revoked first
    ///   - primary first
    ///   - signature creation first
    ///
    /// If there is more than one, than one is selected in a
    /// deterministic, but undefined manner.
    pub fn primary<T>(self, time: T) -> Option<ComponentAmalgamation<'a, C>>
        where T: Into<Option<SystemTime>>
    {
        use std::cmp::Ordering;
        use std::time::{Duration, SystemTime};

        let t = time.into()
            .unwrap_or_else(SystemTime::now);
        (self.make_iter)(self.cert)
            // Filter out components that are not alive at time `t`.
            //
            // While we have the binding signature, extract a few
            // properties to avoid recomputing the same thing multiple
            // times.
            .filter_map(|c| {
                // No binding signature at time `t` => not alive.
                let sig = c.binding_signature(t)?;

                if !sig.signature_alive(t, Duration::new(0, 0)).is_ok() {
                    return None;
                }

                let revoked = c._revoked(false, Some(sig), t);
                let primary = sig.primary_userid().unwrap_or(false);
                let signature_creation_time = sig.signature_creation_time()?;

                Some(((c, sig, revoked), primary, signature_creation_time))
            })
            .max_by(|(a, a_primary, a_signature_creation_time),
                    (b, b_primary, b_signature_creation_time)| {
                match (destructures_to!(RevocationStatus::Revoked(_) = &a.2),
                       destructures_to!(RevocationStatus::Revoked(_) = &b.2)) {
                    (true, false) => return Ordering::Less,
                    (false, true) => return Ordering::Greater,
                    _ => (),
                }
                match (a_primary, b_primary) {
                    (true, false) => return Ordering::Greater,
                    (false, true) => return Ordering::Less,
                    _ => (),
                }
                match a_signature_creation_time.cmp(&b_signature_creation_time)
                {
                    Ordering::Less => return Ordering::Less,
                    Ordering::Greater => return Ordering::Greater,
                    Ordering::Equal => (),
                }

                // Fallback to a lexographical comparison.  Prefer
                // the "smaller" one.
                match a.0.component().cmp(&b.0.component()) {
                    Ordering::Less => return Ordering::Greater,
                    Ordering::Greater => return Ordering::Less,
                    Ordering::Equal =>
                        panic!("non-canonicalized Cert (duplicate components)"),
                }
            })
            .map(|c| ComponentAmalgamation::new(self.cert, (c.0).0, t))
    }

    /// Changes the iterator to return components.
    ///
    /// A component is similar to a component amalgamation, but is not
    /// bound to a specific time.  It contains the component and all
    /// relevant signatures.
    pub fn components(self) -> ComponentBindingIter<'a, C> {
        self.iter
    }
}

/// An iterator over all valid `Component`s in a certificate.
///
/// A component is valid at time `t` if it was not created after `t`
/// and it has a live self-signature at time `t`.
///
/// `ValidComponentIter` follows the builder pattern.  There is no
/// need to explicitly finalize it, however: it already implements the
/// `Iterator` trait.
pub struct ValidComponentIter<'a, C> {
    // This is an option to make it easier to create an empty ValidComponentIter.
    cert: &'a Cert,
    iter: ComponentBindingIter<'a, C>,
    // The time.
    time: SystemTime,
    // If not None, filters by whether the component is revoked or not
    // at time `t`.
    revoked: Option<bool>,
}

impl<'a, C> fmt::Debug for ValidComponentIter<'a, C> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ValidComponentIter")
            .field("time", &self.time)
            .field("revoked", &self.revoked)
            .finish()
    }
}

impl<'a, C> Iterator for ValidComponentIter<'a, C>
    where C: std::fmt::Debug
{
    type Item = ComponentAmalgamation<'a, C>;

    fn next(&mut