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
use std::fmt;

#[cfg(test)]
use quickcheck::{Arbitrary, Gen};

use crate::types::Bitfield;

/// Describes the features supported by an OpenPGP implementation.
///
/// The feature flags are defined in [Section 5.2.3.24 of RFC 4880],
/// and [Section 5.2.3.25 of RFC 4880bis].
///
/// [Section 5.2.3.24 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.24
/// [Section 5.2.3.25 of RFC 4880bis]: https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-09#section-5.2.3.25
///
/// The feature flags are set by the user's OpenPGP implementation to
/// signal to any senders what features the implementation supports.
///
/// # A note on equality
///
/// `PartialEq` compares the serialized form of the two feature sets.
/// If you prefer to compare two feature sets for semantic equality,
/// you should use [`Features::normalized_eq`].  The difference
/// between semantic equality and serialized equality is that semantic
/// equality ignores differences in the amount of padding.
///
///   [`Features::normalized_eq`]: #method.normalized_eq
///
/// # Examples
///
/// ```
/// use sequoia_openpgp as openpgp;
/// # use openpgp::Result;
/// use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
///
/// # fn main() -> Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) =
/// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
/// #     .generate()?;
/// match cert.with_policy(p, None)?.primary_userid()?.features() {
///     Some(features) => {
///         println!("Certificate holder's supported features:");
///         assert!(features.supports_mdc());
///         assert!(!features.supports_aead());
///     }
///     None => {
///         println!("Certificate Holder did not specify any features.");
/// #       unreachable!();
///     }
/// }
/// # Ok(()) }
/// ```
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Features(Bitfield);

impl fmt::Debug for Features {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Print known features first.
        let mut need_comma = false;
        if self.supports_mdc() {
            f.write_str("MDC")?;
            need_comma = true;
        }
        if self.supports_aead() {
            if need_comma { f.write_str(", ")?; }
            f.write_str("AEAD")?;
            need_comma = true;
        }

        // Now print any unknown features.
        for i in self.0.iter() {
            match i {
                FEATURE_FLAG_MDC => (),
                FEATURE_FLAG_AEAD => (),
                i => {
                    if need_comma { f.write_str(", ")?; }
                    write!(f, "#{}", i)?;
                    need_comma = true;
                }
            }
        }

        // Mention any padding, as equality is sensitive to this.
        let padding = self.0.padding_len();
        if padding > 0 {
            if need_comma { f.write_str(", ")?; }
            write!(f, "+padding({} bytes)", padding)?;
        }

        Ok(())
    }
}

impl Features {
    /// Creates a new instance from `bytes`.
    ///
    /// This does not remove any trailing padding from `bytes`.
    pub fn new<B>(bytes: B) -> Self
        where B: AsRef<[u8]>
    {
        Features(bytes.as_ref().to_vec().into())
    }

    /// Returns an empty feature set.
    pub fn empty() -> Self {
        Self::new(&[][..])
    }

    /// Returns a feature set describing Sequoia's capabilities.
    pub fn sequoia() -> Self {
        let v : [u8; 1] = [ 0 ];

        Self::new(&v[..]).set_mdc()
    }

    /// Compares two feature sets for semantic equality.
    ///
    /// `Features`' implementation of `PartialEq` compares two feature
    /// sets for serialized equality.  That is, the `PartialEq`
    /// implementation considers two feature sets to *not* be equal if
    /// they have different amounts of padding.  This comparison
    /// function ignores padding.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::types::Features;
    ///
    /// # fn main() -> Result<()> {
    /// let a = Features::new(&[0x1]);
    /// let b = Features::new(&[0x1, 0x0]);
    ///
    /// assert!(a != b);
    /// assert!(a.normalized_eq(&b));
    /// # Ok(()) }
    /// ```
    pub fn normalized_eq(&self, other: &Self) -> bool {
        self.0.normalized_eq(&other.0)
    }

    /// Returns a slice containing the raw values.
    pub(crate) fn as_slice(&self) -> &[u8] {
        self.0.as_slice()
    }

    /// Returns whether the specified feature flag is set.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::types::Features;
    ///
    /// # fn main() -> Result<()> {
    /// // Feature flags 0 and 2.
    /// let f = Features::new(&[0x5]);
    ///
    /// assert!(f.get(0));
    /// assert!(! f.get(1));
    /// assert!(f.get(2));
    /// assert!(! f.get(3));
    /// assert!(! f.get(8));
    /// assert!(! f.get(80));
    /// # assert!(f.supports_mdc());
    /// # assert!(! f.supports_aead());
    /// # Ok(()) }
    /// ```
    pub fn get(&self, bit: usize) -> bool {
        self.0.get(bit)
    }

    /// Sets the specified feature flag.
    ///
    /// This also clears any padding (trailing NUL bytes).
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::types::Features;
    ///
    /// # fn main() -> Result<()> {
    /// let f = Features::empty().set(0).set(2);
    ///
    /// assert!(f.get(0));
    /// assert!(! f.get(1));
    /// assert!(f.get(2));
    /// assert!(! f.get(3));
    /// # assert!(f.supports_mdc());
    /// # assert!(! f.supports_aead());
    /// # Ok(()) }
    /// ```
    pub fn set(self, bit: usize) -> Self {
        Self(self.0.set(bit))
    }

    /// Clears the specified feature flag.
    ///
    /// This also clears any padding (trailing NUL bytes).
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::types::Features;
    ///
    /// # fn main() -> Result<()> {
    /// let f = Features::empty().set(0).set(2).clear(2);
    ///
    /// assert!(f.get(0));
    /// assert!(! f.get(1));
    /// assert!(! f.get(2));
    /// assert!(! f.get(3));
    /// # assert!(f.supports_mdc());
    /// # assert!(! f.supports_aead());
    /// # Ok(()) }
    /// ```
    pub fn clear(self, bit: usize) -> Self {
        Self(self.0.clear(bit))
    }

    /// Returns whether the MDC feature flag is set.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::types::Features;
    ///
    /// # fn main() -> Result<()> {
    /// let f = Features::empty();
    ///
    /// assert!(! f.supports_mdc());
    /// # Ok(()) }
    /// ```
    pub fn supports_mdc(&self) -> bool {
        self.get(FEATURE_FLAG_MDC)
    }

    /// Sets the MDC feature flag.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::types::Features;
    ///
    /// # fn main() -> Result<()> {
    /// let f = Features::empty().set_mdc();
    ///
    /// assert!(f.supports_mdc());
    /// # assert!(f.get(0));
    /// # Ok(()) }
    /// ```
    pub fn set_mdc(self) -> Self {
        self.set(FEATURE_FLAG_MDC)
    }

    /// Clears the MDC feature flag.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::types::Features;
    ///
    /// # fn main() -> Result<()> {
    /// let f = Features::new(&[0x1]);
    /// assert!(f.supports_mdc());
    ///
    /// let f = f.clear_mdc();
    /// assert!(! f.supports_mdc());
    /// # Ok(()) }
    /// ```
    pub fn clear_mdc(self) -> Self {
        self.clear(FEATURE_FLAG_MDC)
    }

    /// Returns whether the AEAD feature flag is set.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::types::Features;
    ///
    /// # fn main() -> Result<()> {
    /// let f = Features::empty();
    ///
    /// assert!(! f.supports_aead());
    /// # Ok(()) }
    /// ```
    pub fn supports_aead(&self) -> bool {
        self.get(FEATURE_FLAG_AEAD)
    }

    /// Sets the AEAD feature flag.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::types::Features;
    ///
    /// # fn main() -> Result<()> {
    /// let f = Features::empty().set_aead();
    ///
    /// assert!(f.supports_aead());
    /// # assert!(f.get(1));
    /// # Ok(()) }
    /// ```
    pub fn set_aead(self) -> Self {
        self.set(FEATURE_FLAG_AEAD)
    }

    /// Clears the AEAD feature flag.
    ///
    /// # Examples
    ///
    /// ```
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::types::Features;
    ///
    /// # fn main() -> Result<()> {
    /// let f = Features::new(&[0x2]);
    /// assert!(f.supports_aead());
    ///
    /// let f = f.clear_aead();
    /// assert!(! f.supports_aead());
    /// # Ok(()) }
    /// ```
    pub fn clear_aead(self) -> Self {
        self.clear(FEATURE_FLAG_AEAD)
    }
}

/// Modification Detection (packets 18 and 19).
const FEATURE_FLAG_MDC: usize = 0;

/// AEAD Encrypted Data Packet (packet 20) and version 5 Symmetric-Key
/// Encrypted Session Key Packets (packet 3).
const FEATURE_FLAG_AEAD: usize = 1;

#[cfg(test)]
impl Arbitrary for Features {
    fn arbitrary<G: Gen>(g: &mut G) -> Self {
        Self::new(Vec::arbitrary(g))
    }
}

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

    quickcheck! {
        fn roundtrip(val: Features) -> bool {
            let mut q = Features::new(val.as_slice());
            assert_eq!(val, q);
            assert!(val.normalized_eq(&q));

            // Add some padding to q.  Make sure they are still equal.
            q.0.raw.push(0);
            assert!(val != q);
            assert!(val.normalized_eq(&q));

            q.0.raw.push(0);
            assert!(val != q);
            assert!(val.normalized_eq(&q));

            true
        }
    }

    #[test]
    fn set_clear() {
        let a = Features::new(&[ 0x5, 0x1, 0x0, 0xff ]);
        let b = Features::new(&[])
            .set(0).set(2)
            .set(8)
            .set(24).set(25).set(26).set(27).set(28).set(29).set(30).set(31);
        assert_eq!(a, b);

        // Clear a bit and make sure they are not equal.
        let b = b.clear(0);
        assert!(a != b);
        assert!(! a.normalized_eq(&b));
        let b = b.set(0);
        assert_eq!(a, b);
        assert!(a.normalized_eq(&b));

        let b = b.clear(8);
        assert!(a != b);
        assert!(! a.normalized_eq(&b));
        let b = b.set(8);
        assert_eq!(a, b);
        assert!(a.normalized_eq(&b));

        let b = b.clear(31);
        assert!(a != b);
        assert!(! a.normalized_eq(&b));
        let b = b.set(31);
        assert_eq!(a, b);
        assert!(a.normalized_eq(&b));

        // Add a bit.
        let a = a.set(10);
        assert!(a != b);
        assert!(! a.normalized_eq(&b));
        let b = b.set(10);
        assert_eq!(a, b);
        assert!(a.normalized_eq(&b));

        let a = a.set(32);
        assert!(a != b);
        assert!(! a.normalized_eq(&b));
        let b = b.set(32);
        assert_eq!(a, b);
        assert!(a.normalized_eq(&b));

        let a = a.set(1000);
        assert!(a != b);
        assert!(! a.normalized_eq(&b));
        let b = b.set(1000);
        assert_eq!(a, b);
        assert!(a.normalized_eq(&b));
    }

    #[test]
    fn known() {
        let a = Features::empty().set_mdc();
        let b = Features::new(&[ 0x1 ]);
        assert_eq!(a, b);
        assert!(a.normalized_eq(&b));

        let a = Features::empty().set_aead();
        let b = Features::new(&[ 0x2 ]);
        assert_eq!(a, b);
        assert!(a.normalized_eq(&b));

        let a = Features::empty().set_mdc().set_aead();
        let b = Features::new(&[ 0x1 | 0x2 ]);
        assert_eq!(a, b);
        assert!(a.normalized_eq(&b));
    }
}