sequoia_openpgp/
serialize.rs

1//! Packet serialization infrastructure.
2//!
3//! OpenPGP defines a binary representation suitable for storing and
4//! communicating OpenPGP data structures (see [Section 3 ff. of RFC
5//! 9580]).  Serialization is the process of creating the binary
6//! representation.
7//!
8//!   [Section 3 ff. of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-3
9//!
10//! There are two interfaces to serialize OpenPGP data.  Which one is
11//! applicable depends on whether or not the packet structure is
12//! already assembled in memory, with all information already in place
13//! (e.g. because it was previously parsed).
14//!
15//! If it is, you can use the [`Serialize`] or [`SerializeInto`]
16//! trait.  Otherwise, please use our [streaming serialization
17//! interface].
18//!
19//!   [streaming serialization interface]: stream
20//!
21//! # Streaming serialization
22//!
23//! The [streaming serialization interface] is the preferred way to
24//! create OpenPGP messages (see [Section 10.3 of RFC 9580]).  It is
25//! ergonomic, yet flexible enough to accommodate most use cases.  It
26//! requires little buffering, minimizing the memory footprint of the
27//! operation.
28//!
29//! This example demonstrates how to create the simplest possible
30//! OpenPGP message (see [Section 10.3 of RFC 9580]) containing just a
31//! literal data packet (see [Section 5.9 of RFC 9580]):
32//!
33//!   [Section 10.3 of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-10.3
34//!   [Section 5.9 of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.9
35//!
36//! ```
37//! # fn main() -> sequoia_openpgp::Result<()> {
38//! use std::io::Write;
39//! use sequoia_openpgp as openpgp;
40//! use openpgp::serialize::stream::{Message, LiteralWriter};
41//!
42//! let mut o = vec![];
43//! {
44//!     let message = Message::new(&mut o);
45//!     let mut w = LiteralWriter::new(message).build()?;
46//!     w.write_all(b"Hello world.")?;
47//!     w.finalize()?;
48//! }
49//! assert_eq!(b"\xcb\x12b\x00\x00\x00\x00\x00Hello world.", o.as_slice());
50//! # Ok(()) }
51//! ```
52//!
53//! For a more complete example, see the [streaming examples].
54//!
55//!   [streaming examples]: stream#examples
56//!
57//! # Serializing objects
58//!
59//! The traits [`Serialize`] and [`SerializeInto`] provide a mechanism
60//! to serialize OpenPGP data structures.  [`Serialize`] writes to
61//! [`io::Write`]rs, while [`SerializeInto`] writes into pre-allocated
62//! buffers, computes the size of the serialized representation, and
63//! provides a convenient method to create byte vectors with the
64//! serialized form.
65//!
66//!   [`io::Write`]: std::io::Write
67//!
68//! To prevent accidentally serializing data structures that are not
69//! commonly exchanged between OpenPGP implementations, [`Serialize`]
70//! and [`SerializeInto`] is only implemented for types like
71//! [`Packet`], [`Cert`], and [`Message`], but not for packet bodies
72//! like [`Signature`].
73//!
74//!   [`Packet`]: super::Packet
75//!   [`Cert`]: super::Cert
76//!   [`Message`]: super::Message
77//!   [`Signature`]: crate::packet::Signature
78//!
79//! This example demonstrates how to serialize a literal data packet
80//! (see [Section 5.9 of RFC 9580]):
81//!
82//! ```
83//! # fn main() -> sequoia_openpgp::Result<()> {
84//! use sequoia_openpgp as openpgp;
85//! use openpgp::packet::{Literal, Packet};
86//! use openpgp::serialize::{Serialize, SerializeInto};
87//!
88//! let mut l = Literal::default();
89//! l.set_body(b"Hello world.".to_vec());
90//!
91//! // Add packet framing.
92//! let p = Packet::from(l);
93//!
94//! // Using Serialize.
95//! let mut b = vec![];
96//! p.serialize(&mut b)?;
97//! assert_eq!(b"\xcb\x12b\x00\x00\x00\x00\x00Hello world.", b.as_slice());
98//!
99//! // Using SerializeInto.
100//! let b = p.to_vec()?;
101//! assert_eq!(b"\xcb\x12b\x00\x00\x00\x00\x00Hello world.", b.as_slice());
102//! # Ok(()) }
103//! ```
104//!
105//! # Marshalling objects
106//!
107//! The traits [`Marshal`] and [`MarshalInto`] provide a mechanism to
108//! serialize all OpenPGP data structures in this crate, even those
109//! not commonly interchanged between OpenPGP implementations.  For
110//! example, it allows the serialization of unframed packet bodies:
111//!
112//!
113//! ```
114//! # fn main() -> sequoia_openpgp::Result<()> {
115//! use sequoia_openpgp as openpgp;
116//! use openpgp::packet::Literal;
117//! use openpgp::serialize::{Marshal, MarshalInto};
118//!
119//! let mut l = Literal::default();
120//! l.set_body(b"Hello world.".to_vec());
121//!
122//! // Using Marshal.
123//! let mut b = vec![];
124//! l.serialize(&mut b)?;
125//! assert_eq!(b"b\x00\x00\x00\x00\x00Hello world.", b.as_slice());
126//!
127//! // Using MarshalInto.
128//! let b = l.to_vec()?;
129//! assert_eq!(b"b\x00\x00\x00\x00\x00Hello world.", b.as_slice());
130//! # Ok(()) }
131//! ```
132
133use std::io::{self, Write};
134use std::cmp;
135use std::convert::{TryFrom, TryInto};
136
137use super::*;
138
139mod cert;
140pub use self::cert::TSK;
141mod cert_armored;
142pub mod stream;
143use crate::crypto::S2K;
144use crate::packet::header::{
145    BodyLength,
146    CTB,
147    CTBNew,
148    CTBOld,
149};
150use crate::packet::signature::subpacket::{
151    SubpacketArea, Subpacket, SubpacketValue, SubpacketLength
152};
153use crate::packet::prelude::*;
154use crate::packet::signature::Signature3;
155use crate::seal;
156use crate::types::{
157    RevocationKey,
158    Timestamp,
159};
160
161// Whether to trace the modules execution (on stderr).
162const TRACE : bool = false;
163
164/// Serializes OpenPGP data structures.
165///
166/// This trait provides the same interface as the [`Marshal`] trait (in
167/// fact, it is just a wrapper around that trait), but only data
168/// structures that it makes sense to export implement it.
169///
170///
171/// Having a separate trait for data structures that it makes sense to
172/// export avoids an easy-to-make and hard-to-debug bug: inadvertently
173/// exporting an OpenPGP data structure without any framing
174/// information.
175///
176/// This bug is easy to make, because Rust infers types, which means
177/// that it is often not clear from the immediate context exactly what
178/// is being serialized.  This bug is hard to debug, because errors
179/// parsing data that has been incorrectly exported, are removed from
180/// the serialization code.
181///
182/// The following example shows how to correctly export a revocation
183/// certificate.  It should make clear how easy it is to forget to
184/// convert a bare signature into an OpenPGP packet before serializing
185/// it:
186///
187/// ```
188/// # use sequoia_openpgp as openpgp;
189/// # use openpgp::Result;
190/// use openpgp::cert::prelude::*;
191/// use openpgp::Packet;
192/// use openpgp::serialize::Serialize;
193///
194/// # fn main() -> Result<()> {
195/// let (_cert, rev) =
196///     CertBuilder::general_purpose(Some("alice@example.org"))
197///     .generate()?;
198/// let rev : Packet = rev.into();
199/// # let output = &mut Vec::new();
200/// rev.serialize(output)?;
201/// # Ok(())
202/// # }
203/// ```
204///
205/// Note: if you `use` both `Serialize` and [`Marshal`], then, because
206/// they both have the same methods, and all data structures that
207/// implement `Serialize` also implement [`Marshal`], you will have to
208/// use the Universal Function Call Syntax (UFCS) to call the methods
209/// on those objects, for example:
210///
211/// ```
212/// # use sequoia_openpgp as openpgp;
213/// # use openpgp::Result;
214/// # use openpgp::cert::prelude::*;
215/// # use openpgp::Packet;
216/// # use openpgp::serialize::Serialize;
217/// #
218/// # fn main() -> Result<()> {
219/// # let (_cert, rev) =
220/// #     CertBuilder::general_purpose(Some("alice@example.org"))
221/// #     .generate()?;
222/// # let rev : Packet = rev.into();
223/// # let output = &mut Vec::new();
224/// Serialize::serialize(&rev, output)?;
225/// # Ok(())
226/// # }
227/// ```
228///
229/// If you really needed [`Marshal`], we strongly recommend importing it
230/// in as small a scope as possible to avoid this, and to avoid
231/// accidentally exporting data without the required framing.
232pub trait Serialize : Marshal {
233    /// Writes a serialized version of the object to `o`.
234    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
235        Marshal::serialize(self, o)
236    }
237
238    /// Exports a serialized version of the object to `o`.
239    ///
240    /// This is similar to [`serialize(..)`], with these exceptions:
241    ///
242    ///   - It is an error to export a [`Signature`] if it is marked
243    ///     as non-exportable.
244    ///   - When exporting a [`Cert`], non-exportable signatures are
245    ///     not exported, and any component bound merely by
246    ///     non-exportable signatures is not exported.
247    ///
248    ///   [`serialize(..)`]: Serialize::serialize
249    ///   [`Signature`]: crate::packet::Signature
250    ///   [`Cert`]: super::Cert
251    fn export(&self, o: &mut dyn std::io::Write) -> Result<()> {
252        Marshal::export(self, o)
253    }
254}
255
256/// Serializes OpenPGP data structures.
257///
258/// This trait provides the same interface as [`Serialize`], but is
259/// implemented for all data structures that can be serialized.
260///
261///
262/// In general, you should prefer the [`Serialize`] trait, as it is only
263/// implemented for data structures that are normally exported.  See
264/// the documentation for [`Serialize`] for more details.
265///
266/// # Sealed trait
267///
268/// This trait is [sealed] and cannot be implemented for types outside this crate.
269/// Therefore it can be extended in a non-breaking way.
270/// If you want to implement the trait inside the crate
271/// you also need to implement the `seal::Sealed` marker trait.
272///
273/// [sealed]: https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed
274pub trait Marshal: seal::Sealed {
275    /// Writes a serialized version of the object to `o`.
276    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()>;
277
278    /// Exports a serialized version of the object to `o`.
279    ///
280    /// This is similar to [`serialize(..)`], with these exceptions:
281    ///
282    ///   - It is an error to export a [`Signature`] if it is marked
283    ///     as non-exportable.
284    ///   - When exporting a [`Cert`], non-exportable signatures are
285    ///     not exported, and any component bound merely by
286    ///     non-exportable signatures is not exported.
287    ///
288    ///   [`serialize(..)`]: Marshal::serialize
289    ///   [`Signature`]: crate::packet::Signature
290    ///   [`Cert`]: super::Cert
291    fn export(&self, o: &mut dyn std::io::Write) -> Result<()> {
292        self.serialize(o)
293    }
294}
295
296/// Serializes OpenPGP data structures into pre-allocated buffers.
297///
298/// This trait provides the same interface as [`MarshalInto`], but is
299/// only implemented for data structures that can be serialized.
300///
301///
302/// In general, you should prefer this trait to [`MarshalInto`], as it
303/// is only implemented for data structures that are normally
304/// exported.  See the documentation for [`Serialize`] for more details.
305///
306pub trait SerializeInto : MarshalInto {
307    /// Computes the maximal length of the serialized representation.
308    ///
309    /// # Errors
310    ///
311    /// If serialization would fail, this function underestimates the
312    /// length.
313    fn serialized_len(&self) -> usize {
314        MarshalInto::serialized_len(self)
315    }
316
317    /// Serializes into the given buffer.
318    ///
319    /// Returns the length of the serialized representation.
320    ///
321    /// # Errors
322    ///
323    /// If the length of the given slice is smaller than the maximal
324    /// length computed by `serialized_len()`, this function returns
325    /// [`Error::InvalidArgument`].
326    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
327        MarshalInto::serialize_into(self, buf)
328    }
329
330    /// Serializes the packet to a vector.
331    fn to_vec(&self) -> Result<Vec<u8>> {
332        MarshalInto::to_vec(self)
333    }
334
335    /// Exports into the given buffer.
336    ///
337    /// This is similar to [`serialize_into(..)`], with these
338    /// exceptions:
339    ///
340    ///   - It is an error to export a [`Signature`] if it is marked
341    ///     as non-exportable.
342    ///   - When exporting a [`Cert`], non-exportable signatures are
343    ///     not exported, and any component bound merely by
344    ///     non-exportable signatures is not exported.
345    ///
346    ///   [`serialize_into(..)`]: SerializeInto::serialize_into
347    ///   [`Signature`]: crate::packet::Signature
348    ///   [`Cert`]: super::Cert
349    ///
350    /// Returns the length of the serialized representation.
351    ///
352    /// # Errors
353    ///
354    /// If the length of the given slice is smaller than the maximal
355    /// length computed by `serialized_len()`, this function returns
356    /// [`Error::InvalidArgument`].
357    fn export_into(&self, buf: &mut [u8]) -> Result<usize> {
358        MarshalInto::export_into(self, buf)
359    }
360
361    /// Exports to a vector.
362    ///
363    /// This is similar to [`to_vec()`], with these exceptions:
364    ///
365    ///   - It is an error to export a [`Signature`] if it is marked
366    ///     as non-exportable.
367    ///   - When exporting a [`Cert`], non-exportable signatures are
368    ///     not exported, and any component bound merely by
369    ///     non-exportable signatures is not exported.
370    ///
371    ///   [`to_vec()`]: SerializeInto::to_vec()
372    ///   [`Signature`]: crate::packet::Signature
373    ///   [`Cert`]: super::Cert
374    fn export_to_vec(&self) -> Result<Vec<u8>> {
375        MarshalInto::export_to_vec(self)
376    }
377}
378
379/// Serializes OpenPGP data structures into pre-allocated buffers.
380///
381/// This trait provides the same interface as [`SerializeInto`], but is
382/// implemented for all data structures that can be serialized.
383///
384///
385/// In general, you should prefer the [`SerializeInto`] trait, as it is
386/// only implemented for data structures that are normally exported.
387/// See the documentation for [`Serialize`] for more details.
388///
389///
390/// # Sealed trait
391///
392/// This trait is [sealed] and cannot be implemented for types outside this crate.
393/// Therefore it can be extended in a non-breaking way.
394/// If you want to implement the trait inside the crate
395/// you also need to implement the `seal::Sealed` marker trait.
396///
397/// [sealed]: https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed
398pub trait MarshalInto : seal::Sealed {
399    /// Computes the maximal length of the serialized representation.
400    ///
401    /// # Errors
402    ///
403    /// If serialization would fail, this function underestimates the
404    /// length.
405    fn serialized_len(&self) -> usize;
406
407    /// Serializes into the given buffer.
408    ///
409    /// Returns the length of the serialized representation.
410    ///
411    /// # Errors
412    ///
413    /// If the length of the given slice is smaller than the maximal
414    /// length computed by `serialized_len()`, this function returns
415    /// [`Error::InvalidArgument`].
416    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize>;
417
418    /// Serializes the packet to a vector.
419    fn to_vec(&self) -> Result<Vec<u8>> {
420        let mut o = vec![0; self.serialized_len()];
421        let len = self.serialize_into(&mut o[..])?;
422        vec_truncate(&mut o, len);
423        o.shrink_to_fit();
424        Ok(o)
425    }
426
427    /// Exports into the given buffer.
428    ///
429    /// This is similar to [`serialize_into(..)`], with these
430    /// exceptions:
431    ///
432    ///   - It is an error to export a [`Signature`] if it is marked
433    ///     as non-exportable.
434    ///   - When exporting a [`Cert`], non-exportable signatures are
435    ///     not exported, and any component bound merely by
436    ///     non-exportable signatures is not exported.
437    ///
438    ///   [`serialize_into(..)`]: MarshalInto::serialize_into
439    ///   [`Signature`]: crate::packet::Signature
440    ///   [`Cert`]: super::Cert
441    ///
442    /// Returns the length of the serialized representation.
443    ///
444    /// # Errors
445    ///
446    /// If the length of the given slice is smaller than the maximal
447    /// length computed by `serialized_len()`, this function returns
448    /// [`Error::InvalidArgument`].
449    fn export_into(&self, buf: &mut [u8]) -> Result<usize> {
450        self.serialize_into(buf)
451    }
452
453    /// Exports to a vector.
454    ///
455    /// This is similar to [`to_vec()`], with these exceptions:
456    ///
457    ///   - It is an error to export a [`Signature`] if it is marked
458    ///     as non-exportable.
459    ///   - When exporting a [`Cert`], non-exportable signatures are
460    ///     not exported, and any component bound merely by
461    ///     non-exportable signatures is not exported.
462    ///
463    ///   [`to_vec()`]: MarshalInto::to_vec()
464    ///   [`Signature`]: crate::packet::Signature
465    ///   [`Cert`]: super::Cert
466    fn export_to_vec(&self) -> Result<Vec<u8>> {
467        let mut o = vec![0; self.serialized_len()];
468        let len = self.export_into(&mut o[..])?;
469        vec_truncate(&mut o, len);
470        o.shrink_to_fit();
471        Ok(o)
472    }
473}
474
475trait NetLength {
476    /// Computes the maximal length of the serialized representation
477    /// without framing.
478    ///
479    /// # Errors
480    ///
481    /// If serialization would fail, this function underestimates the
482    /// length.
483    fn net_len(&self) -> usize;
484
485    /// Computes the maximal length of the serialized representation
486    /// with framing.
487    ///
488    /// # Errors
489    ///
490    /// If serialization would fail, this function underestimates the
491    /// length.
492    fn gross_len(&self) -> usize {
493        let net = self.net_len();
494
495        1 // CTB
496            + BodyLength::Full(net as u32).serialized_len()
497            + net
498    }
499}
500
501/// Provides a generic implementation for SerializeInto::serialize_into.
502///
503/// For now, we express SerializeInto using Serialize.  In the future,
504/// we may provide implementations not relying on Serialize for a
505/// no_std configuration of this crate.
506fn generic_serialize_into(o: &dyn Marshal, serialized_len: usize,
507                          buf: &mut [u8])
508                          -> Result<usize> {
509    let buf_len = buf.len();
510    let mut cursor = ::std::io::Cursor::new(buf);
511    match o.serialize(&mut cursor) {
512        Ok(_) => (),
513        Err(e) => {
514            let short_write =
515                if let Some(ioe) = e.downcast_ref::<io::Error>() {
516                    ioe.kind() == io::ErrorKind::WriteZero
517                } else {
518                    false
519                };
520            return if short_write {
521                if buf_len >= serialized_len {
522                    let mut b = Vec::new();
523                    let need_len = o.serialize(&mut b).map(|_| b.len());
524                    panic!("o.serialized_len() = {} underestimated required \
525                            space, need {:?}", serialized_len, need_len);
526                }
527                Err(Error::InvalidArgument(
528                    format!("Invalid buffer size, expected {}, got {}",
529                            serialized_len, buf_len)).into())
530            } else {
531                Err(e)
532            }
533        }
534    };
535    Ok(cursor.position() as usize)
536}
537
538
539/// Provides a generic implementation for SerializeInto::export_into.
540///
541/// For now, we express SerializeInto using Serialize.  In the future,
542/// we may provide implementations not relying on Serialize for a
543/// no_std configuration of this crate.
544fn generic_export_into(o: &dyn Marshal, serialized_len: usize,
545                       buf: &mut [u8])
546                       -> Result<usize> {
547    let buf_len = buf.len();
548    let mut cursor = ::std::io::Cursor::new(buf);
549    match o.export(&mut cursor) {
550        Ok(_) => (),
551        Err(e) => {
552            let short_write =
553                if let Some(ioe) = e.downcast_ref::<io::Error>() {
554                    ioe.kind() == io::ErrorKind::WriteZero
555                } else {
556                    false
557                };
558            return if short_write {
559                if buf_len >= serialized_len {
560                    let mut b = Vec::new();
561                    let need_len = o.serialize(&mut b).map(|_| b.len());
562                    panic!("o.serialized_len() = {} underestimated required \
563                            space, need {:?}", serialized_len, need_len);
564                }
565                Err(Error::InvalidArgument(
566                    format!("Invalid buffer size, expected {}, got {}",
567                            serialized_len, buf_len)).into())
568            } else {
569                Err(e)
570            }
571        }
572    };
573    Ok(cursor.position() as usize)
574}
575
576#[test]
577fn test_generic_serialize_into() {
578    let u = UserID::from("Mr. Pink");
579    let mut b = vec![0; u.serialized_len()];
580    u.serialize_into(&mut b[..]).unwrap();
581
582    // Short buffer.
583    let mut b = vec![0; u.serialized_len() - 1];
584    let e = u.serialize_into(&mut b[..]).unwrap_err();
585    assert_match!(Some(Error::InvalidArgument(_)) = e.downcast_ref());
586}
587
588#[test]
589fn test_generic_export_into() {
590    let u = UserID::from("Mr. Pink");
591    let mut b = vec![0; u.serialized_len()];
592    u.export_into(&mut b[..]).unwrap();
593
594    // Short buffer.
595    let mut b = vec![0; u.serialized_len() - 1];
596    let e = u.export_into(&mut b[..]).unwrap_err();
597    assert_match!(Some(Error::InvalidArgument(_)) = e.downcast_ref());
598}
599
600fn write_byte(o: &mut dyn std::io::Write, b: u8) -> io::Result<()> {
601    o.write_all(&[b])
602}
603
604fn write_be_u16(o: &mut dyn std::io::Write, n: u16) -> io::Result<()> {
605    o.write_all(&n.to_be_bytes())
606}
607
608fn write_be_u32(o: &mut dyn std::io::Write, n: u32) -> io::Result<()> {
609    o.write_all(&n.to_be_bytes())
610}
611
612// Compute the log2 of an integer.  (This is simply the most
613// significant bit.)  Note: log2(0) = -Inf, but this function returns
614// log2(0) as 0 (which is the closest number that we can represent).
615fn log2(x: u32) -> usize {
616    if x == 0 {
617        0
618    } else {
619        31 - x.leading_zeros() as usize
620    }
621}
622
623#[test]
624fn log2_test() {
625    for i in 0..32 {
626        // eprintln!("log2(1 << {} = {}) = {}", i, 1u32 << i, log2(1u32 << i));
627        assert_eq!(log2(1u32 << i), i);
628        if i > 0 {
629            assert_eq!(log2((1u32 << i) - 1), i - 1);
630            assert_eq!(log2((1u32 << i) + 1), i);
631        }
632    }
633}
634
635impl seal::Sealed for BodyLength {}
636impl Marshal for BodyLength {
637    /// Emits the length encoded for use with new-style CTBs.
638    ///
639    /// Note: the CTB itself is not emitted.
640    ///
641    /// # Errors
642    ///
643    /// Returns [`Error::InvalidArgument`] if invoked on
644    /// [`BodyLength::Indeterminate`].  If you want to serialize an
645    /// old-style length, use [`serialize_old(..)`].
646    ///
647    /// [`Error::InvalidArgument`]: Error::InvalidArgument
648    /// [`serialize_old(..)`]: BodyLength::serialize_old()
649    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
650        match self {
651            BodyLength::Full(l) => {
652                let l = *l;
653                if l <= 191 {
654                    write_byte(o, l as u8)?;
655                } else if l <= 8383 {
656                    let v = l - 192;
657                    let v = v + (192 << 8);
658                    write_be_u16(o, v as u16)?;
659                } else {
660                    write_byte(o, 0xff)?;
661                    write_be_u32(o, l)?;
662                }
663            },
664            BodyLength::Partial(l) => {
665                let l = *l;
666                if l > 1 << 30 {
667                    return Err(Error::InvalidArgument(
668                        format!("Partial length too large: {}", l)).into());
669                }
670
671                let chunk_size_log2 = log2(l);
672                let chunk_size = 1 << chunk_size_log2;
673
674                if l != chunk_size {
675                    return Err(Error::InvalidArgument(
676                        format!("Not a power of two: {}", l)).into());
677                }
678
679                let size_byte = 224 + chunk_size_log2;
680                assert!(size_byte < 255);
681                write_byte(o, size_byte as u8)?;
682            },
683            BodyLength::Indeterminate =>
684                return Err(Error::InvalidArgument(
685                    "Indeterminate lengths are not support for new format packets".
686                        into()).into()),
687        }
688
689        Ok(())
690    }
691}
692
693impl MarshalInto for BodyLength {
694    fn serialized_len(&self) -> usize {
695        match self {
696            BodyLength::Full(l) => {
697                let l = *l;
698                if l <= 191 {
699                    1
700                } else if l <= 8383 {
701                    2
702                } else {
703                    5
704                }
705            },
706            BodyLength::Partial(_) => 1,
707            BodyLength::Indeterminate => 0,
708        }
709    }
710
711    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
712        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
713    }
714}
715
716impl BodyLength {
717    /// Emits the length encoded for use with old-style CTBs.
718    ///
719    /// Note: the CTB itself is not emitted.
720    ///
721    /// # Errors
722    ///
723    /// Returns [`Error::InvalidArgument`] if invoked on
724    /// [`BodyLength::Partial`].  If you want to serialize a
725    /// new-style length, use [`serialize(..)`].
726    ///
727    /// [`Error::InvalidArgument`]: Error::InvalidArgument
728    /// [`serialize(..)`]: Serialize
729    pub fn serialize_old<W: io::Write + ?Sized>(&self, o: &mut W) -> Result<()> {
730        // Assume an optimal encoding is desired.
731        let mut buffer = Vec::with_capacity(4);
732        match self {
733            BodyLength::Full(l) => {
734                let l = *l;
735                match l {
736                    // One octet length.
737                    // write_byte can't fail for a Vec.
738                    0 ..= 0xFF =>
739                        write_byte(&mut buffer, l as u8).unwrap(),
740                    // Two octet length.
741                    0x1_00 ..= 0xFF_FF =>
742                        write_be_u16(&mut buffer, l as u16).unwrap(),
743                    // Four octet length,
744                    _ =>
745                        write_be_u32(&mut buffer, l as u32).unwrap(),
746                }
747            },
748            BodyLength::Indeterminate => {},
749            BodyLength::Partial(_) =>
750                return Err(Error::InvalidArgument(
751                    "Partial body lengths are not support for old format packets".
752                        into()).into()),
753        }
754
755        o.write_all(&buffer)?;
756        Ok(())
757    }
758
759    /// Computes the length of the length encoded for use with
760    /// old-style CTBs.
761    fn old_serialized_len(&self) -> usize {
762        // Assume an optimal encoding is desired.
763        match self {
764            BodyLength::Full(l) => {
765                match *l {
766                    0 ..= 0xFF => 1,
767                    0x1_00 ..= 0xFF_FF => 2,
768                    _ => 4,
769                }
770            },
771            BodyLength::Indeterminate => 0,
772            BodyLength::Partial(_) => 0,
773        }
774    }
775}
776
777impl seal::Sealed for CTBNew {}
778impl Marshal for CTBNew {
779    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
780        let tag: u8 = self.tag().into();
781        o.write_all(&[0b1100_0000u8 | tag])?;
782        Ok(())
783    }
784}
785
786impl MarshalInto for CTBNew {
787    fn serialized_len(&self) -> usize { 1 }
788
789    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
790        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
791    }
792}
793
794impl seal::Sealed for CTBOld {}
795impl Marshal for CTBOld {
796    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
797        let tag: u8 = self.tag().into();
798        let length_type: u8 = self.length_type().into();
799        o.write_all(&[0b1000_0000u8 | (tag << 2) | length_type])?;
800        Ok(())
801    }
802}
803
804impl MarshalInto for CTBOld {
805    fn serialized_len(&self) -> usize { 1 }
806
807    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
808        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
809    }
810}
811
812impl seal::Sealed for CTB {}
813impl Marshal for CTB {
814    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
815        match self {
816            CTB::New(ref c) => c.serialize(o),
817            CTB::Old(ref c) => c.serialize(o),
818        }?;
819        Ok(())
820    }
821}
822
823impl MarshalInto for CTB {
824    fn serialized_len(&self) -> usize { 1 }
825
826    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
827        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
828    }
829}
830
831impl seal::Sealed for Header {}
832impl Marshal for Header {
833    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
834        self.ctb().serialize(o)?;
835        match self.ctb() {
836            CTB::New(_) => self.length().serialize(o)?,
837            CTB::Old(_) => self.length().serialize_old(o)?,
838        }
839        Ok(())
840    }
841}
842
843impl MarshalInto for Header {
844    fn serialized_len(&self) -> usize {
845        self.ctb().serialized_len()
846            + match self.ctb() {
847                CTB::New(_) => self.length().serialized_len(),
848                CTB::Old(_) => self.length().old_serialized_len(),
849            }
850    }
851
852    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
853        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
854    }
855}
856
857#[test]
858fn legacy_header() -> Result<()> {
859    use crate::serialize::MarshalInto;
860    let len = BodyLength::Indeterminate;
861    let ctb = CTB::Old(CTBOld::new(Tag::Literal, len)?);
862    assert_eq!(&ctb.to_vec()?[..], &[0b1_0_1011_11]);
863    // Bit encoding: OpenPGP_Legacy_Literal_Indeterminate
864    Ok(())
865}
866
867impl Serialize for KeyID {}
868impl seal::Sealed for KeyID {}
869impl Marshal for KeyID {
870    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
871        let raw = match self {
872            KeyID::Long(ref fp) => &fp[..],
873            KeyID::Invalid(ref fp) => &fp[..],
874        };
875        o.write_all(raw)?;
876        Ok(())
877    }
878}
879
880impl SerializeInto for KeyID {}
881impl MarshalInto for KeyID {
882    fn serialized_len(&self) -> usize {
883        match self {
884            KeyID::Long(_) => 8,
885            KeyID::Invalid(ref fp) => fp.len(),
886        }
887    }
888
889    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
890        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
891    }
892}
893
894impl Serialize for Fingerprint {}
895impl seal::Sealed for Fingerprint {}
896impl Marshal for Fingerprint {
897    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
898        o.write_all(self.as_bytes())?;
899        Ok(())
900    }
901}
902
903impl SerializeInto for Fingerprint {}
904impl MarshalInto for Fingerprint {
905    fn serialized_len(&self) -> usize {
906        self.as_bytes().len()
907    }
908
909    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
910        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
911    }
912}
913
914impl seal::Sealed for crypto::mpi::MPI {}
915impl Marshal for crypto::mpi::MPI {
916    fn serialize(&self, w: &mut dyn std::io::Write) -> Result<()> {
917        write_be_u16(w, self.bits() as u16)?;
918        w.write_all(self.value())?;
919        Ok(())
920    }
921}
922
923impl MarshalInto for crypto::mpi::MPI {
924    fn serialized_len(&self) -> usize {
925        2 + self.value().len()
926    }
927
928    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
929        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
930    }
931}
932
933impl seal::Sealed for crypto::mpi::ProtectedMPI {}
934impl Marshal for crypto::mpi::ProtectedMPI {
935    fn serialize(&self, w: &mut dyn std::io::Write) -> Result<()> {
936        write_be_u16(w, self.bits() as u16)?;
937        w.write_all(self.value())?;
938        Ok(())
939    }
940}
941
942impl MarshalInto for crypto::mpi::ProtectedMPI {
943    fn serialized_len(&self) -> usize {
944        2 + self.value().len()
945    }
946
947    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
948        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
949    }
950}
951
952/// Writes `buf` into `w` prefixed by the length as u8, bailing out if
953/// the length exceeds 256 bytes.
954fn write_field_with_u8_size(w: &mut dyn Write, name: &str, buf: &[u8])
955                            -> Result<()> {
956    w.write_all(&[buf.len().try_into()
957                  .map_err(|_| anyhow::Error::from(
958                      Error::InvalidArgument(
959                          format!("{} exceeds 255 bytes: {:?}",
960                                  name, buf))))?])?;
961    w.write_all(buf)?;
962    Ok(())
963}
964
965impl seal::Sealed for crypto::mpi::PublicKey {}
966impl Marshal for crypto::mpi::PublicKey {
967    fn serialize(&self, w: &mut dyn std::io::Write) -> Result<()> {
968        use crate::crypto::mpi::PublicKey::*;
969
970        match self {
971            RSA { ref e, ref n } => {
972                n.serialize(w)?;
973                e.serialize(w)?;
974            }
975
976            DSA { ref p, ref q, ref g, ref y } => {
977                p.serialize(w)?;
978                q.serialize(w)?;
979                g.serialize(w)?;
980                y.serialize(w)?;
981            }
982
983            ElGamal { ref p, ref g, ref y } => {
984                p.serialize(w)?;
985                g.serialize(w)?;
986                y.serialize(w)?;
987            }
988
989            EdDSA { ref curve, ref q } => {
990                write_field_with_u8_size(w, "Curve's OID", curve.oid())?;
991                q.serialize(w)?;
992            }
993
994            ECDSA { ref curve, ref q } => {
995                write_field_with_u8_size(w, "Curve's OID", curve.oid())?;
996                q.serialize(w)?;
997            }
998
999            ECDH { ref curve, ref q, hash, sym } => {
1000                write_field_with_u8_size(w, "Curve's OID", curve.oid())?;
1001                q.serialize(w)?;
1002                w.write_all(&[3u8, 1u8, u8::from(*hash), u8::from(*sym)])?;
1003            }
1004
1005            X25519 { u } => w.write_all(&u[..])?,
1006            X448 { u } => w.write_all(&u[..])?,
1007            Ed25519 { a } => w.write_all(&a[..])?,
1008            Ed448 { a } => w.write_all(&a[..])?,
1009
1010            Unknown { ref mpis, ref rest } => {
1011                for mpi in mpis.iter() {
1012                    mpi.serialize(w)?;
1013                }
1014                w.write_all(rest)?;
1015            }
1016        }
1017
1018        Ok(())
1019    }
1020}
1021
1022impl MarshalInto for crypto::mpi::PublicKey {
1023    fn serialized_len(&self) -> usize {
1024        use crate::crypto::mpi::PublicKey::*;
1025        match self {
1026            RSA { ref e, ref n } => {
1027                n.serialized_len() + e.serialized_len()
1028            }
1029
1030            DSA { ref p, ref q, ref g, ref y } => {
1031                p.serialized_len() + q.serialized_len() + g.serialized_len()
1032                    + y.serialized_len()
1033            }
1034
1035            ElGamal { ref p, ref g, ref y } => {
1036                p.serialized_len() + g.serialized_len() + y.serialized_len()
1037            }
1038
1039            EdDSA { ref curve, ref q } => {
1040                1 + curve.oid().len() + q.serialized_len()
1041            }
1042
1043            ECDSA { ref curve, ref q } => {
1044                1 + curve.oid().len() + q.serialized_len()
1045            }
1046
1047            ECDH { ref curve, ref q, hash: _, sym: _ } => {
1048                1 + curve.oid().len() + q.serialized_len() + 4
1049            }
1050
1051            X25519 { .. } => 32,
1052            X448 { .. } => 56,
1053            Ed25519 { .. } => 32,
1054            Ed448 { .. } => 57,
1055
1056            Unknown { ref mpis, ref rest } => {
1057                mpis.iter().map(|mpi| mpi.serialized_len()).sum::<usize>()
1058                    + rest.len()
1059            }
1060        }
1061    }
1062
1063    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1064        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
1065    }
1066}
1067
1068impl seal::Sealed for crypto::mpi::SecretKeyMaterial {}
1069impl Marshal for crypto::mpi::SecretKeyMaterial {
1070    fn serialize(&self, w: &mut dyn std::io::Write) -> Result<()> {
1071        use crate::crypto::mpi::SecretKeyMaterial::*;
1072
1073        match self {
1074            RSA{ ref d, ref p, ref q, ref u } => {
1075                d.serialize(w)?;
1076                p.serialize(w)?;
1077                q.serialize(w)?;
1078                u.serialize(w)?;
1079            }
1080
1081            DSA{ ref x } => {
1082                x.serialize(w)?;
1083            }
1084
1085            ElGamal{ ref x } => {
1086                x.serialize(w)?;
1087            }
1088
1089            EdDSA{ ref scalar } => {
1090                scalar.serialize(w)?;
1091            }
1092
1093            ECDSA{ ref scalar } => {
1094                scalar.serialize(w)?;
1095            }
1096
1097            ECDH{ ref scalar } => {
1098                scalar.serialize(w)?;
1099            }
1100
1101            X25519 { x } => w.write_all(x)?,
1102            X448 { x } => w.write_all(x)?,
1103            Ed25519 { x } => w.write_all(x)?,
1104            Ed448 { x } => w.write_all(x)?,
1105
1106            Unknown { ref mpis, ref rest } => {
1107                for mpi in mpis.iter() {
1108                    mpi.serialize(w)?;
1109                }
1110                w.write_all(rest)?;
1111            }
1112        }
1113
1114        Ok(())
1115    }
1116}
1117
1118impl MarshalInto for crypto::mpi::SecretKeyMaterial {
1119    fn serialized_len(&self) -> usize {
1120        use crate::crypto::mpi::SecretKeyMaterial::*;
1121        match self {
1122            RSA{ ref d, ref p, ref q, ref u } => {
1123                d.serialized_len() + p.serialized_len() + q.serialized_len()
1124                    + u.serialized_len()
1125            }
1126
1127            DSA{ ref x } => {
1128                x.serialized_len()
1129            }
1130
1131            ElGamal{ ref x } => {
1132                x.serialized_len()
1133            }
1134
1135            EdDSA{ ref scalar } => {
1136                scalar.serialized_len()
1137            }
1138
1139            ECDSA{ ref scalar } => {
1140                scalar.serialized_len()
1141            }
1142
1143            ECDH{ ref scalar } => {
1144                scalar.serialized_len()
1145            }
1146
1147            X25519 { .. } => 32,
1148            X448 { .. } => 56,
1149            Ed25519 { .. } => 32,
1150            Ed448 { .. } => 57,
1151
1152            Unknown { ref mpis, ref rest } => {
1153                mpis.iter().map(|mpi| mpi.serialized_len()).sum::<usize>()
1154                    + rest.len()
1155            }
1156        }
1157    }
1158
1159    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1160        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
1161    }
1162}
1163
1164impl crypto::mpi::SecretKeyMaterial {
1165    /// Writes this secret key with a checksum to `w`.
1166    pub fn serialize_with_checksum(
1167        &self, w: &mut dyn io::Write,
1168        checksum: crypto::mpi::SecretKeyChecksum)
1169        -> Result<()>
1170    {
1171        // First, the MPIs.
1172        self.serialize(w)?;
1173
1174        match checksum {
1175            crypto::mpi::SecretKeyChecksum::SHA1 => {
1176                // The checksum is SHA1 over the serialized MPIs.
1177                let mut hash =
1178                    HashAlgorithm::SHA1.context().unwrap().for_digest();
1179                self.serialize(&mut hash)?;
1180                let mut digest = [0u8; 20];
1181                let _ = hash.digest(&mut digest);
1182                w.write_all(&digest)?;
1183            },
1184            crypto::mpi::SecretKeyChecksum::Sum16 => {
1185                w.write_all(&self.to_vec()?.iter()
1186                            .fold(0u16, |acc, v| acc.wrapping_add(*v as u16))
1187                            .to_be_bytes())?;
1188            },
1189        }
1190
1191        Ok(())
1192    }
1193}
1194
1195impl seal::Sealed for crypto::mpi::Ciphertext {}
1196impl Marshal for crypto::mpi::Ciphertext {
1197    fn serialize(&self, w: &mut dyn std::io::Write) -> Result<()> {
1198        use crate::crypto::mpi::Ciphertext::*;
1199
1200        match self {
1201            RSA{ ref c } => {
1202                c.serialize(w)?;
1203            }
1204
1205            ElGamal{ ref e, ref c } => {
1206                e.serialize(w)?;
1207                c.serialize(w)?;
1208            }
1209
1210            ECDH{ ref e, ref key } => {
1211                e.serialize(w)?;
1212                write_field_with_u8_size(w, "Key", key)?;
1213            }
1214
1215            X25519 {  e, key } => {
1216                w.write_all(&e[..])?;
1217                write_field_with_u8_size(w, "Key", key)?;
1218            }
1219
1220            X448 {  e, key } => {
1221                w.write_all(&e[..])?;
1222                write_field_with_u8_size(w, "Key", key)?;
1223            }
1224
1225            Unknown { ref mpis, ref rest } => {
1226                for mpi in mpis.iter() {
1227                    mpi.serialize(w)?;
1228                }
1229                w.write_all(rest)?;
1230            }
1231        }
1232
1233        Ok(())
1234    }
1235}
1236
1237impl MarshalInto for crypto::mpi::Ciphertext {
1238    fn serialized_len(&self) -> usize {
1239        use crate::crypto::mpi::Ciphertext::*;
1240        match self {
1241            RSA{ ref c } => {
1242                c.serialized_len()
1243            }
1244
1245            ElGamal{ ref e, ref c } => {
1246                e.serialized_len() + c.serialized_len()
1247            }
1248
1249            ECDH{ ref e, ref key } => {
1250                e.serialized_len() + 1 + key.len()
1251            }
1252
1253            X25519 { key, .. } => {
1254                32 + 1 + key.len()
1255            }
1256
1257            X448 { key, .. } => {
1258                56 + 1 + key.len()
1259            }
1260
1261            Unknown { ref mpis, ref rest } => {
1262                mpis.iter().map(|mpi| mpi.serialized_len()).sum::<usize>()
1263                    + rest.len()
1264            }
1265        }
1266    }
1267
1268    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1269        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
1270    }
1271}
1272
1273impl seal::Sealed for crypto::mpi::Signature {}
1274impl Marshal for crypto::mpi::Signature {
1275    fn serialize(&self, w: &mut dyn std::io::Write) -> Result<()> {
1276        use crate::crypto::mpi::Signature::*;
1277
1278        match self {
1279            RSA { ref s } => {
1280                s.serialize(w)?;
1281            }
1282            DSA { ref r, ref s } => {
1283                r.serialize(w)?;
1284                s.serialize(w)?;
1285            }
1286            ElGamal { ref r, ref s } => {
1287                r.serialize(w)?;
1288                s.serialize(w)?;
1289            }
1290            EdDSA { ref r, ref s } => {
1291                r.serialize(w)?;
1292                s.serialize(w)?;
1293            }
1294            ECDSA { ref r, ref s } => {
1295                r.serialize(w)?;
1296                s.serialize(w)?;
1297            }
1298
1299            Ed25519 { s } => w.write_all(&s[..])?,
1300            Ed448 { s } => w.write_all(&s[..])?,
1301
1302            Unknown { ref mpis, ref rest } => {
1303                for mpi in mpis.iter() {
1304                    mpi.serialize(w)?;
1305                }
1306                w.write_all(rest)?;
1307            }
1308        }
1309
1310        Ok(())
1311    }
1312}
1313
1314impl MarshalInto for crypto::mpi::Signature {
1315    fn serialized_len(&self) -> usize {
1316        use crate::crypto::mpi::Signature::*;
1317        match self {
1318            RSA { ref s } => {
1319                s.serialized_len()
1320            }
1321            DSA { ref r, ref s } => {
1322                r.serialized_len() + s.serialized_len()
1323            }
1324            ElGamal { ref r, ref s } => {
1325                r.serialized_len() + s.serialized_len()
1326            }
1327            EdDSA { ref r, ref s } => {
1328                r.serialized_len() + s.serialized_len()
1329            }
1330            ECDSA { ref r, ref s } => {
1331                r.serialized_len() + s.serialized_len()
1332            }
1333
1334            Ed25519 { .. } => 64,
1335            Ed448 { .. } => 114,
1336
1337            Unknown { ref mpis, ref rest } => {
1338                mpis.iter().map(|mpi| mpi.serialized_len()).sum::<usize>()
1339                    + rest.len()
1340            }
1341        }
1342    }
1343
1344    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1345        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
1346    }
1347}
1348
1349impl seal::Sealed for S2K {}
1350impl Marshal for S2K {
1351    fn serialize(&self, w: &mut dyn std::io::Write) -> Result<()> {
1352        #[allow(deprecated)]
1353        match self {
1354            &S2K::Simple{ hash } => {
1355                w.write_all(&[0, hash.into()])?;
1356            }
1357            &S2K::Salted{ hash, salt } => {
1358                w.write_all(&[1, hash.into()])?;
1359                w.write_all(&salt[..])?;
1360            }
1361            &S2K::Iterated{ hash, salt, hash_bytes } => {
1362                w.write_all(&[3, hash.into()])?;
1363                w.write_all(&salt[..])?;
1364                w.write_all(&[S2K::encode_count(hash_bytes)?])?;
1365            }
1366            S2K::Implicit => (),
1367            S2K::Argon2 { salt, t, p, m, } => {
1368                w.write_all(&[4])?;
1369                w.write_all(salt)?;
1370                w.write_all(&[*t, *p, *m])?;
1371            },
1372            S2K::Private { tag, parameters }
1373            | S2K::Unknown { tag, parameters} => {
1374                w.write_all(&[*tag])?;
1375                if let Some(p) = parameters.as_ref() {
1376                    w.write_all(p)?;
1377                }
1378            }
1379        }
1380
1381        Ok(())
1382    }
1383}
1384
1385impl MarshalInto for S2K {
1386    fn serialized_len(&self) -> usize {
1387        #[allow(deprecated)]
1388        match self {
1389            &S2K::Simple{ .. } => 2,
1390            &S2K::Salted{ .. } => 2 + 8,
1391            &S2K::Iterated{ .. } => 2 + 8 + 1,
1392            S2K::Implicit => 0,
1393            S2K::Argon2 { .. } => 20,
1394            S2K::Private { parameters, .. }
1395            | S2K::Unknown { parameters, .. } =>
1396                1 + parameters.as_ref().map(|p| p.len()).unwrap_or(0),
1397        }
1398    }
1399
1400    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1401        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
1402    }
1403}
1404
1405impl seal::Sealed for Unknown {}
1406impl Marshal for Unknown {
1407    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
1408        o.write_all(self.body())?;
1409        Ok(())
1410    }
1411}
1412
1413impl NetLength for Unknown {
1414    fn net_len(&self) -> usize {
1415        self.body().len()
1416    }
1417}
1418
1419impl MarshalInto for Unknown {
1420    fn serialized_len(&self) -> usize {
1421        self.net_len()
1422    }
1423
1424    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1425        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
1426    }
1427}
1428
1429impl seal::Sealed for SubpacketArea {}
1430impl Marshal for SubpacketArea {
1431    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
1432        for sb in self.iter() {
1433            sb.serialize(o)?;
1434        }
1435        Ok(())
1436    }
1437}
1438
1439impl MarshalInto for SubpacketArea {
1440    fn serialized_len(&self) -> usize {
1441        self.iter().map(|sb| sb.serialized_len()).sum()
1442    }
1443
1444    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1445        let mut written = 0;
1446        for sb in self.iter() {
1447            let n = sb.serialize_into(&mut buf[written..])?;
1448            written += cmp::min(buf.len() - written, n);
1449        }
1450        Ok(written)
1451    }
1452}
1453
1454impl seal::Sealed for Subpacket {}
1455impl Marshal for Subpacket {
1456    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
1457        let tag = u8::from(self.tag())
1458            | if self.critical() { 1 << 7 } else { 0 };
1459
1460        self.length.serialize(o)?;
1461        o.write_all(&[tag])?;
1462        self.value().serialize(o)
1463    }
1464}
1465
1466impl MarshalInto for Subpacket {
1467    fn serialized_len(&self) -> usize {
1468        self.length.serialized_len() + 1 + self.value().serialized_len()
1469    }
1470
1471    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1472        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
1473    }
1474}
1475
1476impl seal::Sealed for SubpacketValue {}
1477impl Marshal for SubpacketValue {
1478    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
1479        use self::SubpacketValue::*;
1480        #[allow(deprecated)]
1481        match self {
1482            SignatureCreationTime(t) =>
1483                write_be_u32(o, (*t).into())?,
1484            SignatureExpirationTime(t) =>
1485                write_be_u32(o, (*t).into())?,
1486            ExportableCertification(e) =>
1487                o.write_all(&[if *e { 1 } else { 0 }])?,
1488            TrustSignature { ref level, ref trust } =>
1489                o.write_all(&[*level, *trust])?,
1490            RegularExpression(ref re) => {
1491                o.write_all(re)?;
1492                o.write_all(&[0])?;
1493            },
1494            Revocable(r) =>
1495                o.write_all(&[if *r { 1 } else { 0 }])?,
1496            KeyExpirationTime(t) =>
1497                write_be_u32(o, (*t).into())?,
1498            PreferredSymmetricAlgorithms(ref p) =>
1499                for a in p {
1500                    o.write_all(&[(*a).into()])?;
1501                },
1502            RevocationKey(rk) => rk.serialize(o)?,
1503            Issuer(ref id) =>
1504                o.write_all(id.as_bytes())?,
1505            NotationData(nd) => {
1506                o.write_all(nd.flags().as_bitfield().as_bytes())?;
1507                write_be_u16(o, nd.name().len() as u16)?;
1508                write_be_u16(o, nd.value().len() as u16)?;
1509                o.write_all(nd.name().as_bytes())?;
1510                o.write_all(nd.value())?;
1511            },
1512            PreferredHashAlgorithms(ref p) =>
1513                for a in p {
1514                    o.write_all(&[(*a).into()])?;
1515                },
1516            PreferredCompressionAlgorithms(ref p) =>
1517                for a in p {
1518                    o.write_all(&[(*a).into()])?;
1519                },
1520            KeyServerPreferences(ref p) =>
1521                o.write_all(p.as_bitfield().as_bytes())?,
1522            PreferredKeyServer(ref p) =>
1523                o.write_all(p)?,
1524            PrimaryUserID(p) =>
1525                o.write_all(&[if *p { 1 } else { 0 }])?,
1526            PolicyURI(ref p) =>
1527                o.write_all(p)?,
1528            KeyFlags(ref f) =>
1529                o.write_all(f.as_bitfield().as_bytes())?,
1530            SignersUserID(ref uid) =>
1531                o.write_all(uid)?,
1532            ReasonForRevocation { ref code, ref reason } => {
1533                o.write_all(&[(*code).into()])?;
1534                o.write_all(reason)?;
1535            },
1536            Features(ref f) =>
1537                o.write_all(f.as_bitfield().as_bytes())?,
1538            SignatureTarget { pk_algo, hash_algo, ref digest } => {
1539                o.write_all(&[(*pk_algo).into(), (*hash_algo).into()])?;
1540                o.write_all(digest)?;
1541            },
1542            EmbeddedSignature(sig) => sig.serialize(o)?,
1543            IssuerFingerprint(ref fp) => match fp {
1544                Fingerprint::V4(_) => {
1545                    o.write_all(&[4])?;
1546                    o.write_all(fp.as_bytes())?;
1547                },
1548                Fingerprint::V6(_) => {
1549                    o.write_all(&[6])?;
1550                    o.write_all(fp.as_bytes())?;
1551                },
1552                _ => return Err(Error::InvalidArgument(
1553                    "Unknown kind of fingerprint".into()).into()),
1554            }
1555            IntendedRecipient(ref fp) => match fp {
1556                Fingerprint::V4(_) => {
1557                    o.write_all(&[4])?;
1558                    o.write_all(fp.as_bytes())?;
1559                },
1560                Fingerprint::V6(_) => {
1561                    o.write_all(&[6])?;
1562                    o.write_all(fp.as_bytes())?;
1563                },
1564                _ => return Err(Error::InvalidArgument(
1565                    "Unknown kind of fingerprint".into()).into()),
1566            }
1567            ApprovedCertifications(digests) => {
1568                for digest in digests {
1569                    o.write_all(digest)?;
1570                }
1571            },
1572
1573            PreferredAEADCiphersuites(p) =>
1574                for (symm, aead) in p {
1575                    o.write_all(&[(*symm).into(), (*aead).into()])?;
1576                },
1577
1578            Unknown { body, .. } =>
1579                o.write_all(body)?,
1580        }
1581        Ok(())
1582    }
1583}
1584
1585impl MarshalInto for SubpacketValue {
1586    fn serialized_len(&self) -> usize {
1587        use self::SubpacketValue::*;
1588        #[allow(deprecated)]
1589        match self {
1590            SignatureCreationTime(_) => 4,
1591            SignatureExpirationTime(_) => 4,
1592            ExportableCertification(_) => 1,
1593            TrustSignature { .. } => 2,
1594            RegularExpression(ref re) => re.len() + 1,
1595            Revocable(_) => 1,
1596            KeyExpirationTime(_) => 4,
1597            PreferredSymmetricAlgorithms(ref p) => p.len(),
1598            RevocationKey(rk) => rk.serialized_len(),
1599            Issuer(ref id) => (id as &dyn MarshalInto).serialized_len(),
1600            NotationData(nd) => 4 + 2 + 2 + nd.name().len() + nd.value().len(),
1601            PreferredHashAlgorithms(ref p) => p.len(),
1602            PreferredCompressionAlgorithms(ref p) => p.len(),
1603            KeyServerPreferences(p) => p.as_bitfield().as_bytes().len(),
1604            PreferredKeyServer(ref p) => p.len(),
1605            PrimaryUserID(_) => 1,
1606            PolicyURI(ref p) => p.len(),
1607            KeyFlags(f) => f.as_bitfield().as_bytes().len(),
1608            SignersUserID(ref uid) => uid.len(),
1609            ReasonForRevocation { ref reason, .. } => 1 + reason.len(),
1610            Features(f) => f.as_bitfield().as_bytes().len(),
1611            SignatureTarget { ref digest, .. } => 2 + digest.len(),
1612            EmbeddedSignature(sig) => sig.serialized_len(),
1613            IssuerFingerprint(ref fp) =>
1614                1 + (fp as &dyn MarshalInto).serialized_len(),
1615            IntendedRecipient(ref fp) =>
1616                1 + (fp as &dyn MarshalInto).serialized_len(),
1617            ApprovedCertifications(digests) =>
1618                digests.iter().map(|d| d.len()).sum(),
1619            PreferredAEADCiphersuites(c) => c.len() * 2,
1620            Unknown { body, .. } => body.len(),
1621        }
1622    }
1623
1624    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1625        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
1626    }
1627}
1628
1629impl seal::Sealed for SubpacketLength {}
1630impl Marshal for SubpacketLength {
1631    /// Writes the subpacket length to `sink`.
1632    fn serialize(&self, sink: &mut dyn std::io::Write)
1633                            -> Result<()> {
1634        match self.raw {
1635            Some(ref raw) => sink.write_all(raw)?,
1636            None => {
1637                BodyLength::serialize(&BodyLength::Full(self.len() as u32), sink)?
1638            }
1639        };
1640
1641        Ok(())
1642    }
1643}
1644
1645impl MarshalInto for SubpacketLength {
1646    /// Returns the length of the serialized subpacket length.
1647    fn serialized_len(&self) -> usize {
1648        if let Some(ref raw) = self.raw {
1649            raw.len()
1650        } else {
1651            Self::len_optimal_encoding(self.len() as u32)
1652        }
1653    }
1654
1655    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1656        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
1657    }
1658}
1659
1660
1661impl seal::Sealed for RevocationKey {}
1662impl Marshal for RevocationKey {
1663    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
1664        let (pk_algo, fp) = self.revoker();
1665        o.write_all(&[self.class(), pk_algo.into()])?;
1666        o.write_all(fp.as_bytes())?;
1667        Ok(())
1668    }
1669}
1670
1671impl MarshalInto for RevocationKey {
1672    fn serialized_len(&self) -> usize {
1673        1 + 1 + self.revoker().1.as_bytes().len()
1674    }
1675
1676    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1677        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
1678    }
1679}
1680
1681impl seal::Sealed for Signature {}
1682impl Marshal for Signature {
1683    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
1684        match self {
1685            Signature::V3(ref s) => s.serialize(o),
1686            Signature::V4(ref s) => s.serialize(o),
1687            Signature::V6(ref s) => s.serialize(o),
1688        }
1689    }
1690
1691    fn export(&self, o: &mut dyn std::io::Write) -> Result<()> {
1692        match self {
1693            Signature::V3(ref s) => s.export(o),
1694            Signature::V4(ref s) => s.export(o),
1695            Signature::V6(ref s) => s.export(o),
1696        }
1697    }
1698}
1699
1700impl MarshalInto for Signature {
1701    fn serialized_len(&self) -> usize {
1702        match self {
1703            Signature::V3(ref s) => s.serialized_len(),
1704            Signature::V4(ref s) => s.serialized_len(),
1705            Signature::V6(ref s) => s.serialized_len(),
1706        }
1707    }
1708
1709    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1710        match self {
1711            Signature::V3(ref s) => s.serialize_into(buf),
1712            Signature::V4(ref s) => s.serialize_into(buf),
1713            Signature::V6(ref s) => s.serialize_into(buf),
1714        }
1715    }
1716
1717    fn export_into(&self, buf: &mut [u8]) -> Result<usize> {
1718        match self {
1719            Signature::V3(ref s) => s.export_into(buf),
1720            Signature::V4(ref s) => s.export_into(buf),
1721            Signature::V6(ref s) => s.export_into(buf),
1722        }
1723    }
1724
1725    fn export_to_vec(&self) -> Result<Vec<u8>> {
1726        match self {
1727            Signature::V3(ref s) => s.export_to_vec(),
1728            Signature::V4(ref s) => s.export_to_vec(),
1729            Signature::V6(ref s) => s.export_to_vec(),
1730        }
1731    }
1732}
1733
1734impl NetLength for Signature {
1735    fn net_len(&self) -> usize {
1736        match self {
1737            Signature::V3(sig) => sig.net_len(),
1738            Signature::V4(sig) => sig.net_len(),
1739            Signature::V6(sig) => sig.net_len(),
1740        }
1741    }
1742}
1743
1744impl seal::Sealed for Signature3 {}
1745impl Marshal for Signature3 {
1746    /// Writes a serialized version of the specified `Signature`
1747    /// packet to `o`.
1748    ///
1749    /// # Errors
1750    ///
1751    /// Returns [`Error::InvalidArgument`] if `self` does not contain
1752    /// a valid v3 signature.  Because v3 signature support was added
1753    /// late in the 1.x release cycle, `Signature3` is just a thin
1754    /// wrapper around a `Signature4`.  As such, it is possible to add
1755    /// v4 specific data to a `Signature3`.  In general, this isn't a
1756    /// significnat problem as generating v3 is deprecated.
1757    ///
1758    /// [`Error::InvalidArgument`]: Error::InvalidArgument
1759    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
1760        use crate::packet::signature::subpacket::SubpacketTag;
1761
1762        assert_eq!(self.version(), 3);
1763        write_byte(o, self.version())?;
1764        // hashed length.
1765        write_byte(o, 5)?;
1766        write_byte(o, self.typ().into())?;
1767        if let Some(SubpacketValue::SignatureCreationTime(ct))
1768            = self.hashed_area().subpacket(
1769                SubpacketTag::SignatureCreationTime)
1770            .map(|sp| sp.value())
1771        {
1772            write_be_u32(o, u32::from(*ct))?;
1773        } else {
1774            return Err(Error::InvalidArgument(
1775                "Invalid v3 signature, missing creation time.".into()).into());
1776        }
1777
1778        // Only one signature creation time subpacket is allowed in
1779        // the hashed area.
1780        let mut iter = self.hashed_area().iter();
1781        let _ = iter.next();
1782        if iter.next().is_some() {
1783            return Err(Error::InvalidArgument(
1784                format!("Invalid v3 signature: \
1785                         subpackets are not allowed: {}",
1786                        self.hashed_area().iter().map(|sp| {
1787                            format!("{}: {:?}", sp.tag(), sp.value())
1788                        }).collect::<Vec<String>>().join(", "))).into());
1789        }
1790
1791        if let Some(SubpacketValue::Issuer(keyid))
1792            = self.unhashed_area().subpacket(SubpacketTag::Issuer)
1793            .map(|sp| sp.value())
1794        {
1795            match keyid {
1796                KeyID::Long(bytes) => {
1797                    assert_eq!(bytes.len(), 8);
1798                    o.write_all(&bytes[..])?;
1799                }
1800                KeyID::Invalid(_) => {
1801                    return Err(Error::InvalidArgument(
1802                        "Invalid v3 signature, invalid issuer.".into()).into());
1803                }
1804            }
1805        } else {
1806            return Err(Error::InvalidArgument(
1807                "Invalid v3 signature, missing issuer.".into()).into());
1808        }
1809
1810        // Only one issuer subpacket is allowed in the unhashed area.
1811        let mut iter = self.unhashed_area().iter();
1812        let _ = iter.next();
1813        if iter.next().is_some() {
1814            return Err(Error::InvalidArgument(
1815                format!("Invalid v3 signature: \
1816                         subpackets are not allowed: {}",
1817                        self.unhashed_area().iter().map(|sp| {
1818                            format!("{}: {:?}", sp.tag(), sp.value())
1819                        }).collect::<Vec<String>>().join(", "))).into());
1820        }
1821
1822        write_byte(o, self.pk_algo().into())?;
1823        write_byte(o, self.hash_algo().into())?;
1824
1825        write_byte(o, self.digest_prefix()[0])?;
1826        write_byte(o, self.digest_prefix()[1])?;
1827
1828        self.mpis().serialize(o)?;
1829
1830        Ok(())
1831    }
1832
1833    fn export(&self, o: &mut dyn std::io::Write) -> Result<()> {
1834        self.exportable()?;
1835        self.serialize(o)
1836    }
1837}
1838
1839impl NetLength for Signature3 {
1840    fn net_len(&self) -> usize {
1841        assert_eq!(self.version(), 3);
1842
1843        1 // Version.
1844            + 1 // Hashed length.
1845            + 1 // Signature type.
1846            + 4 // Creation time.
1847            + 8 // Issuer.
1848            + 1 // PK algorithm.
1849            + 1 // Hash algorithm.
1850            + 2 // Hash prefix.
1851            + self.mpis().serialized_len()
1852    }
1853}
1854
1855impl MarshalInto for Signature3 {
1856    fn serialized_len(&self) -> usize {
1857        self.net_len()
1858    }
1859
1860    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1861        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
1862    }
1863
1864    fn export_into(&self, buf: &mut [u8]) -> Result<usize> {
1865        self.exportable()?;
1866        self.serialize_into(buf)
1867    }
1868
1869    fn export_to_vec(&self) -> Result<Vec<u8>> {
1870        self.exportable()?;
1871        self.to_vec()
1872    }
1873}
1874
1875impl seal::Sealed for Signature4 {}
1876impl Marshal for Signature4 {
1877    /// Writes a serialized version of the specified `Signature`
1878    /// packet to `o`.
1879    ///
1880    /// # Errors
1881    ///
1882    /// Returns [`Error::InvalidArgument`] if either the hashed-area
1883    /// or the unhashed-area exceeds the size limit of 2^16.
1884    ///
1885    /// [`Error::InvalidArgument`]: Error::InvalidArgument
1886    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
1887        assert_eq!(self.version(), 4);
1888        write_byte(o, self.version())?;
1889        write_byte(o, self.typ().into())?;
1890        write_byte(o, self.pk_algo().into())?;
1891        write_byte(o, self.hash_algo().into())?;
1892
1893        let l = self.hashed_area().serialized_len();
1894        if l > std::u16::MAX as usize {
1895            return Err(Error::InvalidArgument(
1896                "Hashed area too large".into()).into());
1897        }
1898        write_be_u16(o, l as u16)?;
1899        self.hashed_area().serialize(o)?;
1900
1901        let l = self.unhashed_area().serialized_len();
1902        if l > std::u16::MAX as usize {
1903            return Err(Error::InvalidArgument(
1904                "Unhashed area too large".into()).into());
1905        }
1906        write_be_u16(o, l as u16)?;
1907        self.unhashed_area().serialize(o)?;
1908
1909        write_byte(o, self.digest_prefix()[0])?;
1910        write_byte(o, self.digest_prefix()[1])?;
1911
1912        self.mpis().serialize(o)?;
1913
1914        Ok(())
1915    }
1916
1917    fn export(&self, o: &mut dyn std::io::Write) -> Result<()> {
1918        self.exportable()?;
1919        self.serialize(o)
1920    }
1921}
1922
1923impl NetLength for Signature4 {
1924    fn net_len(&self) -> usize {
1925        assert_eq!(self.version(), 4);
1926
1927        1 // Version.
1928            + 1 // Signature type.
1929            + 1 // PK algorithm.
1930            + 1 // Hash algorithm.
1931            + 2 // Hashed area size.
1932            + self.hashed_area().serialized_len()
1933            + 2 // Unhashed area size.
1934            + self.unhashed_area().serialized_len()
1935            + 2 // Hash prefix.
1936            + self.mpis().serialized_len()
1937    }
1938}
1939
1940impl MarshalInto for Signature4 {
1941    fn serialized_len(&self) -> usize {
1942        self.net_len()
1943    }
1944
1945    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1946        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
1947    }
1948
1949    fn export_into(&self, buf: &mut [u8]) -> Result<usize> {
1950        self.exportable()?;
1951        self.serialize_into(buf)
1952    }
1953
1954    fn export_to_vec(&self) -> Result<Vec<u8>> {
1955        self.exportable()?;
1956        self.to_vec()
1957    }
1958}
1959
1960impl seal::Sealed for Signature6 {}
1961impl Marshal for Signature6 {
1962    /// Writes a serialized version of the specified `Signature`
1963    /// packet to `o`.
1964    ///
1965    /// # Errors
1966    ///
1967    /// Returns [`Error::InvalidArgument`] if either the hashed-area
1968    /// or the unhashed-area exceeds the size limit of 2^16.
1969    ///
1970    /// [`Error::InvalidArgument`]: Error::InvalidArgument
1971    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
1972        assert_eq!(self.version(), 6);
1973        write_byte(o, self.version())?;
1974        write_byte(o, self.typ().into())?;
1975        write_byte(o, self.pk_algo().into())?;
1976        write_byte(o, self.hash_algo().into())?;
1977
1978        let l = self.hashed_area().serialized_len();
1979        if l > u32::MAX as usize {
1980            return Err(Error::InvalidArgument(
1981                "Hashed area too large".into()).into());
1982        }
1983        write_be_u32(o, l as u32)?;
1984        self.hashed_area().serialize(o)?;
1985
1986        let l = self.unhashed_area().serialized_len();
1987        if l > u32::MAX as usize {
1988            return Err(Error::InvalidArgument(
1989                "Unhashed area too large".into()).into());
1990        }
1991        write_be_u32(o, l as u32)?;
1992        self.unhashed_area().serialize(o)?;
1993
1994        write_byte(o, self.digest_prefix()[0])?;
1995        write_byte(o, self.digest_prefix()[1])?;
1996        write_byte(o, self.salt().len() as u8)?;
1997        o.write_all(self.salt())?;
1998
1999        self.mpis().serialize(o)?;
2000
2001        Ok(())
2002    }
2003
2004    fn export(&self, o: &mut dyn std::io::Write) -> Result<()> {
2005        self.exportable()?;
2006        self.serialize(o)
2007    }
2008}
2009
2010impl NetLength for Signature6 {
2011    fn net_len(&self) -> usize {
2012        assert_eq!(self.version(), 6);
2013
2014        1 // Version.
2015            + 1 // Signature type.
2016            + 1 // PK algorithm.
2017            + 1 // Hash algorithm.
2018            + 4 // Hashed area size.
2019            + self.hashed_area().serialized_len()
2020            + 4 // Unhashed area size.
2021            + self.unhashed_area().serialized_len()
2022            + 2 // Hash prefix.
2023            + 1 // Salt length.
2024            + self.salt().len()
2025            + self.mpis().serialized_len()
2026    }
2027}
2028
2029impl MarshalInto for Signature6 {
2030    fn serialized_len(&self) -> usize {
2031        self.net_len()
2032    }
2033
2034    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2035        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2036    }
2037
2038    fn export_into(&self, buf: &mut [u8]) -> Result<usize> {
2039        self.exportable()?;
2040        self.serialize_into(buf)
2041    }
2042
2043    fn export_to_vec(&self) -> Result<Vec<u8>> {
2044        self.exportable()?;
2045        self.to_vec()
2046    }
2047}
2048
2049impl seal::Sealed for OnePassSig {}
2050impl Marshal for OnePassSig {
2051    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2052        match self {
2053            OnePassSig::V3(ref s) => s.serialize(o),
2054            OnePassSig::V6(ref s) => s.serialize(o),
2055        }
2056    }
2057}
2058
2059impl MarshalInto for OnePassSig {
2060    fn serialized_len(&self) -> usize {
2061        match self {
2062            OnePassSig::V3(ref s) => s.serialized_len(),
2063            OnePassSig::V6(ref s) => s.serialized_len(),
2064        }
2065    }
2066
2067    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2068        match self {
2069            OnePassSig::V3(ref s) => s.serialize_into(buf),
2070            OnePassSig::V6(ref s) => s.serialize_into(buf),
2071        }
2072    }
2073}
2074
2075impl NetLength for OnePassSig {
2076    fn net_len(&self) -> usize {
2077        match self {
2078            OnePassSig::V3(ref s) => s.net_len(),
2079            OnePassSig::V6(ref s) => s.net_len(),
2080        }
2081    }
2082}
2083
2084impl seal::Sealed for OnePassSig3 {}
2085impl Marshal for OnePassSig3 {
2086    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2087        write_byte(o, 3)?; // Version.
2088        write_byte(o, self.typ().into())?;
2089        write_byte(o, self.hash_algo().into())?;
2090        write_byte(o, self.pk_algo().into())?;
2091        o.write_all(self.issuer().as_bytes())?;
2092        write_byte(o, self.last_raw())?;
2093
2094        Ok(())
2095    }
2096}
2097
2098impl NetLength for OnePassSig3 {
2099    fn net_len(&self) -> usize {
2100        1 // Version.
2101            + 1 // Signature type.
2102            + 1 // Hash algorithm
2103            + 1 // PK algorithm.
2104            + 8 // Issuer.
2105            + 1 // Last.
2106    }
2107}
2108
2109impl MarshalInto for OnePassSig3 {
2110    fn serialized_len(&self) -> usize {
2111        self.net_len()
2112    }
2113
2114    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2115        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2116    }
2117}
2118
2119impl seal::Sealed for OnePassSig6 {}
2120impl Marshal for OnePassSig6 {
2121    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2122        write_byte(o, 6)?; // Version.
2123        write_byte(o, self.typ().into())?;
2124        write_byte(o, self.hash_algo().into())?;
2125        write_byte(o, self.pk_algo().into())?;
2126        write_byte(o, self.salt().len().try_into().map_err(
2127            |_| Error::InvalidArgument("Salt too large".into()))?)?;
2128        o.write_all(self.salt())?;
2129        if let Fingerprint::V6(bytes) = self.issuer() {
2130            o.write_all(bytes)?;
2131        } else {
2132            return Err(Error::InvalidArgument(
2133                "Need a v6 fingerprint as issuer".into()).into());
2134        }
2135        write_byte(o, self.last_raw())?;
2136
2137        Ok(())
2138    }
2139}
2140
2141impl NetLength for OnePassSig6 {
2142    fn net_len(&self) -> usize {
2143        1 // Version.
2144            + 1 // Signature type.
2145            + 1 // Hash algorithm
2146            + 1 // PK algorithm.
2147            + 1 // The salt length.
2148            + self.salt().len() // The salt.
2149            + 32 // Issuer fingerprint.
2150            + 1 // Last.
2151    }
2152}
2153
2154impl MarshalInto for OnePassSig6 {
2155    fn serialized_len(&self) -> usize {
2156        self.net_len()
2157    }
2158
2159    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2160        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2161    }
2162}
2163
2164impl<P: key::KeyParts, R: key::KeyRole> seal::Sealed for Key<P, R> {}
2165impl<P: key::KeyParts, R: key::KeyRole> Marshal for Key<P, R> {
2166    fn serialize(&self, o: &mut dyn io::Write) -> Result<()> {
2167        match self {
2168            Key::V4(ref p) => p.serialize(o),
2169            Key::V6(ref p) => p.serialize(o),
2170        }
2171    }
2172}
2173
2174impl<P: key::KeyParts, R: key::KeyRole> MarshalInto for Key<P, R> {
2175    fn serialized_len(&self) -> usize {
2176        match self {
2177            Key::V4(ref p) => p.serialized_len(),
2178            Key::V6(ref p) => p.serialized_len(),
2179        }
2180    }
2181
2182    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2183        match self {
2184            Key::V4(ref p) => p.serialize_into(buf),
2185            Key::V6(ref p) => p.serialize_into(buf),
2186        }
2187    }
2188}
2189
2190impl<P: key::KeyParts, R: key::KeyRole> NetLength for Key<P, R> {
2191    fn net_len(&self) -> usize {
2192        match self {
2193            Key::V4(ref p) => p.net_len(),
2194            Key::V6(ref p) => p.net_len(),
2195        }
2196    }
2197}
2198impl<P, R> seal::Sealed for Key4<P, R>
2199    where P: key::KeyParts,
2200          R: key::KeyRole,
2201{}
2202impl<P, R> Marshal for Key4<P, R>
2203    where P: key::KeyParts,
2204          R: key::KeyRole,
2205{
2206    fn serialize(&self, o: &mut dyn io::Write) -> Result<()> {
2207        let have_secret_key = P::significant_secrets() && self.has_secret();
2208
2209        write_byte(o, 4)?; // Version.
2210        write_be_u32(o, self.creation_time_raw().into())?;
2211        write_byte(o, self.pk_algo().into())?;
2212        self.mpis().serialize(o)?;
2213
2214        if have_secret_key {
2215            use crypto::mpi::SecretKeyChecksum;
2216            match self.optional_secret().unwrap() {
2217                SecretKeyMaterial::Unencrypted(ref u) => u.map(|mpis| -> Result<()> {
2218                    write_byte(o, 0)?; // S2K usage.
2219                    mpis.serialize_with_checksum(o, SecretKeyChecksum::Sum16)
2220                })?,
2221                SecretKeyMaterial::Encrypted(ref e) => {
2222                    if let (Some(aead_algo), Some(aead_iv)) =
2223                        (e.aead_algo(), e.aead_iv())
2224                    {
2225                        o.write_all(&[
2226                            253, // S2K usage.
2227                            // No Parameter length for v4 packets.
2228                            e.algo().into(),
2229                            aead_algo.into(),
2230                        ])?;
2231                        e.s2k().serialize(o)?;
2232                        o.write_all(aead_iv)?;
2233                        o.write_all(e.raw_ciphertext())?;
2234                    } else {
2235                        // S2K usage
2236                        #[allow(deprecated)]
2237                        if let S2K::Implicit = e.s2k() {
2238                            // When the legacy implicit S2K mechanism is
2239                            // in use, the symmetric algorithm octet below
2240                            // takes the place of the S2K usage octet.
2241                        } else {
2242                            write_byte(o, match e.checksum() {
2243                                Some(SecretKeyChecksum::SHA1) => 254,
2244                                Some(SecretKeyChecksum::Sum16) => 255,
2245                                None => return Err(Error::InvalidOperation(
2246                                    "In Key4 packets, CFB encrypted secret keys must be \
2247                                     checksummed".into()).into()),
2248                            })?;
2249                        }
2250                        write_byte(o, e.algo().into())?;
2251                        e.s2k().serialize(o)?;
2252                        o.write_all(e.raw_ciphertext())?;
2253                    }
2254                },
2255            }
2256        }
2257
2258        Ok(())
2259    }
2260}
2261
2262impl<P, R> NetLength for Key4<P, R>
2263    where P: key::KeyParts,
2264          R: key::KeyRole,
2265{
2266    #[allow(deprecated)]
2267    fn net_len(&self) -> usize {
2268        let have_secret_key = P::significant_secrets() && self.has_secret();
2269
2270        1 // Version.
2271            + 4 // Creation time.
2272            + 1 // PK algo.
2273            + self.mpis().serialized_len()
2274            + if have_secret_key {
2275                1 + match self.optional_secret().unwrap() {
2276                    SecretKeyMaterial::Unencrypted(ref u) =>
2277                        u.map(|mpis| mpis.serialized_len())
2278                        + 2, // Two octet checksum.
2279                    SecretKeyMaterial::Encrypted(ref e) =>
2280                        matches!(e.s2k(), S2K::Implicit)
2281                        .then_some(0).unwrap_or(1)
2282                        + if e.aead_algo().is_some() { 1 } else { 0 }
2283                        + e.s2k().serialized_len()
2284                        + e.aead_iv().map(|iv| iv.len()).unwrap_or(0)
2285                        + e.raw_ciphertext().len(),
2286                }
2287            } else {
2288                0
2289            }
2290    }
2291}
2292
2293impl<P, R> MarshalInto for Key4<P, R>
2294    where P: key::KeyParts,
2295          R: key::KeyRole,
2296{
2297    fn serialized_len(&self) -> usize {
2298        self.net_len()
2299    }
2300
2301    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2302        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2303    }
2304}
2305
2306impl<P, R> seal::Sealed for Key6<P, R>
2307    where P: key::KeyParts,
2308          R: key::KeyRole,
2309{}
2310
2311impl<P, R> Marshal for Key6<P, R>
2312    where P: key::KeyParts,
2313          R: key::KeyRole,
2314{
2315    fn serialize(&self, o: &mut dyn io::Write) -> Result<()> {
2316        let have_secret_key = P::significant_secrets() && self.has_secret();
2317
2318        write_byte(o, 6)?; // Version.
2319        write_be_u32(o, self.creation_time_raw().into())?;
2320        write_byte(o, self.pk_algo().into())?;
2321        write_be_u32(o, self.mpis().serialized_len() as u32)?;
2322        self.mpis().serialize(o)?;
2323
2324        if have_secret_key {
2325            use crypto::mpi::SecretKeyChecksum;
2326            match self.optional_secret().unwrap() {
2327                SecretKeyMaterial::Unencrypted(u) => u.map(|mpis| {
2328                    write_byte(o, 0)?; // S2K usage.
2329                    mpis.serialize(o)
2330                })?,
2331                SecretKeyMaterial::Encrypted(e) => {
2332                    if let (Some(aead_algo), Some(aead_iv)) =
2333                        (e.aead_algo(), e.aead_iv())
2334                    {
2335                        o.write_all(&[
2336                            253, // S2K usage.
2337                            (1 + 1 + 1 + e.s2k().serialized_len() + aead_iv.len())
2338                                .try_into().unwrap_or(0),
2339                            e.algo().into(),
2340                            aead_algo.into(),
2341                            e.s2k().serialized_len().try_into().unwrap_or(0),
2342                        ])?;
2343                        e.s2k().serialize(o)?;
2344                        o.write_all(aead_iv)?;
2345                        o.write_all(e.raw_ciphertext())?;
2346                    } else {
2347                        o.write_all(&[
2348                            // S2K usage.
2349                            match e.checksum() {
2350                                Some(SecretKeyChecksum::SHA1) => 254,
2351                                Some(SecretKeyChecksum::Sum16) => 255,
2352                                None => return Err(Error::InvalidOperation(
2353                                    "In Key6 packets, CFB encrypted secret keys \
2354                                     must be checksummed".into()).into()),
2355                            },
2356                            // Parameter length octet.
2357                            (1 + 1 + e.s2k().serialized_len()
2358                             + e.cfb_iv_len())
2359                                .try_into().unwrap_or(0),
2360                            // Cipher octet.
2361                            e.algo().into(),
2362                            // S2k length octet.
2363                            e.s2k().serialized_len().try_into().unwrap_or(0),
2364                        ])?;
2365                        e.s2k().serialize(o)?;
2366                        o.write_all(e.raw_ciphertext())?;
2367                    }
2368                },
2369            }
2370        }
2371
2372        Ok(())
2373    }
2374}
2375
2376impl<P, R> NetLength for Key6<P, R>
2377    where P: key::KeyParts,
2378          R: key::KeyRole,
2379{
2380    fn net_len(&self) -> usize {
2381        let have_secret_key = P::significant_secrets() && self.has_secret();
2382
2383        1 // Version.
2384            + 4 // Creation time.
2385            + 1 // PK algo.
2386            + 4 // Size of the public key material.
2387            + self.mpis().serialized_len()
2388            + if have_secret_key {
2389                1 // S2K method octet.
2390                    + match self.optional_secret().unwrap() {
2391                        SecretKeyMaterial::Unencrypted(u) =>
2392                            u.map(|mpis| mpis.serialized_len()),
2393                        SecretKeyMaterial::Encrypted(e) =>
2394                            1 // Parameter length octet.
2395                            + 1 // Cipher octet
2396                            + if e.aead_algo().is_some() { 1 } else { 0 }
2397                            + 1 // S2K length octet
2398                            + e.s2k().serialized_len()
2399                            + e.aead_iv().map(|iv| iv.len()).unwrap_or(0)
2400                            + e.raw_ciphertext().len(),
2401                }
2402            } else {
2403                0
2404            }
2405    }
2406}
2407
2408impl<P, R> MarshalInto for Key6<P, R>
2409    where P: key::KeyParts,
2410          R: key::KeyRole,
2411{
2412    fn serialized_len(&self) -> usize {
2413        self.net_len()
2414    }
2415
2416    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2417        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2418    }
2419}
2420
2421impl seal::Sealed for Marker {}
2422impl Marshal for Marker {
2423    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2424        o.write_all(Marker::BODY)?;
2425        Ok(())
2426    }
2427}
2428
2429impl NetLength for Marker {
2430    fn net_len(&self) -> usize {
2431        Marker::BODY.len()
2432    }
2433}
2434
2435impl MarshalInto for Marker {
2436    fn serialized_len(&self) -> usize {
2437        self.net_len()
2438    }
2439
2440    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2441        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2442    }
2443}
2444
2445impl seal::Sealed for Trust {}
2446impl Marshal for Trust {
2447    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2448        o.write_all(self.value())?;
2449        Ok(())
2450    }
2451}
2452
2453impl NetLength for Trust {
2454    fn net_len(&self) -> usize {
2455        self.value().len()
2456    }
2457}
2458
2459impl MarshalInto for Trust {
2460    fn serialized_len(&self) -> usize {
2461        self.net_len()
2462    }
2463
2464    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2465        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2466    }
2467}
2468
2469impl seal::Sealed for UserID {}
2470impl Marshal for UserID {
2471    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2472        o.write_all(self.value())?;
2473        Ok(())
2474    }
2475}
2476
2477impl NetLength for UserID {
2478    fn net_len(&self) -> usize {
2479        self.value().len()
2480    }
2481}
2482
2483impl MarshalInto for UserID {
2484    fn serialized_len(&self) -> usize {
2485        self.net_len()
2486    }
2487
2488    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2489        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2490    }
2491}
2492
2493impl seal::Sealed for UserAttribute {}
2494impl Marshal for UserAttribute {
2495    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2496        o.write_all(self.value())?;
2497        Ok(())
2498    }
2499}
2500
2501impl NetLength for UserAttribute {
2502    fn net_len(&self) -> usize {
2503        self.value().len()
2504    }
2505}
2506
2507impl MarshalInto for UserAttribute {
2508    fn serialized_len(&self) -> usize {
2509        self.net_len()
2510    }
2511
2512    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2513        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2514    }
2515}
2516
2517impl seal::Sealed for user_attribute::Subpacket {}
2518impl Marshal for user_attribute::Subpacket {
2519    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2520        let body_len = match self {
2521            user_attribute::Subpacket::Image(image) =>
2522                image.serialized_len(),
2523            user_attribute::Subpacket::Unknown(_tag, data) =>
2524                data.len(),
2525        };
2526        BodyLength::Full(1 + body_len as u32).serialize(o)?;
2527        match self {
2528            user_attribute::Subpacket::Image(image) => {
2529                write_byte(o, 1)?;
2530                image.serialize(o)?;
2531            },
2532            user_attribute::Subpacket::Unknown(tag, data) => {
2533                write_byte(o, *tag)?;
2534                o.write_all(&data[..])?;
2535            }
2536        }
2537
2538        Ok(())
2539    }
2540}
2541
2542impl MarshalInto for user_attribute::Subpacket {
2543    fn serialized_len(&self) -> usize {
2544        let body_len = match self {
2545            user_attribute::Subpacket::Image(image) =>
2546                image.serialized_len(),
2547            user_attribute::Subpacket::Unknown(_tag, data) =>
2548                data.len(),
2549        };
2550        let header_len =
2551            BodyLength::Full(1 + body_len as u32).serialized_len();
2552        header_len + 1 + body_len
2553    }
2554
2555    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2556        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2557    }
2558}
2559
2560impl seal::Sealed for user_attribute::Image {}
2561impl Marshal for user_attribute::Image {
2562    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2563        const V1HEADER_TOP: [u8; 3] = [0x10, 0x00, 0x01];
2564        const V1HEADER_PAD: [u8; 12] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
2565        match self {
2566            user_attribute::Image::JPEG(data) => {
2567                o.write_all(&V1HEADER_TOP[..])?;
2568                write_byte(o, 1)?;
2569                o.write_all(&V1HEADER_PAD[..])?;
2570                o.write_all(&data[..])?;
2571            }
2572            user_attribute::Image::Unknown(tag, data)
2573            | user_attribute::Image::Private(tag, data) => {
2574                o.write_all(&V1HEADER_TOP[..])?;
2575                write_byte(o, *tag)?;
2576                o.write_all(&V1HEADER_PAD[..])?;
2577                o.write_all(&data[..])?;
2578            }
2579        }
2580
2581        Ok(())
2582    }
2583}
2584
2585impl MarshalInto for user_attribute::Image {
2586    fn serialized_len(&self) -> usize {
2587        const V1HEADER_LEN: usize =
2588            2     /* Length */
2589            + 1   /* Version */
2590            + 1   /* Tag */
2591            + 12; /* Reserved padding */
2592        match self {
2593            user_attribute::Image::JPEG(data)
2594            | user_attribute::Image::Unknown(_, data)
2595            | user_attribute::Image::Private(_, data) =>
2596                V1HEADER_LEN + data.len(),
2597        }
2598    }
2599
2600    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2601        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2602    }
2603}
2604
2605impl Literal {
2606    /// Writes the headers of the `Literal` data packet to `o`.
2607    pub(crate) fn serialize_headers(&self, o: &mut dyn std::io::Write,
2608                                    write_tag: bool) -> Result<()>
2609    {
2610        let filename = if let Some(filename) = self.filename() {
2611            let len = cmp::min(filename.len(), 255) as u8;
2612            &filename[..len as usize]
2613        } else {
2614            &b""[..]
2615        };
2616
2617        let date = if let Some(d) = self.date() {
2618            Timestamp::try_from(d)?.into()
2619        } else {
2620            0
2621        };
2622
2623        if write_tag {
2624            let len = 1 + (1 + filename.len()) + 4
2625                + self.body().len();
2626            CTB::new(Tag::Literal).serialize(o)?;
2627            BodyLength::Full(len as u32).serialize(o)?;
2628        }
2629        write_byte(o, self.format().into())?;
2630        write_byte(o, filename.len() as u8)?;
2631        o.write_all(filename)?;
2632        write_be_u32(o, date)?;
2633        Ok(())
2634    }
2635}
2636
2637impl seal::Sealed for Literal {}
2638impl Marshal for Literal {
2639    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2640        let body = self.body();
2641        if TRACE {
2642            let prefix = &body[..cmp::min(body.len(), 20)];
2643            eprintln!("Literal::serialize({}{}, {} bytes)",
2644                      String::from_utf8_lossy(prefix),
2645                      if body.len() > 20 { "..." } else { "" },
2646                      body.len());
2647        }
2648
2649        self.serialize_headers(o, false)?;
2650        o.write_all(body)?;
2651
2652        Ok(())
2653    }
2654}
2655
2656impl NetLength for Literal {
2657    fn net_len(&self) -> usize {
2658        1 + (1 + self.filename().map(|f| f.len()).unwrap_or(0)) + 4
2659            + self.body().len()
2660    }
2661}
2662
2663impl MarshalInto for Literal {
2664    fn serialized_len(&self) -> usize {
2665        self.net_len()
2666    }
2667
2668    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2669        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2670    }
2671}
2672
2673impl seal::Sealed for CompressedData {}
2674impl Marshal for CompressedData {
2675    /// Writes a serialized version of the specified `CompressedData`
2676    /// packet to `o`.
2677    ///
2678    /// This function works recursively: if the `CompressedData` packet
2679    /// contains any packets, they are also serialized.
2680    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2681        // The streaming serialization framework requires the sink to
2682        // be Send + Sync, but `o` is not.  Knowing that we create the
2683        // message here and don't keep the message object around, we
2684        // can cheat by creating a shim that is Send + Sync.
2685        struct Shim<'a>(&'a mut dyn std::io::Write);
2686        impl std::io::Write for Shim<'_> {
2687            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
2688                self.0.write(buf)
2689            }
2690            fn flush(&mut self) -> std::io::Result<()> {
2691                self.0.flush()
2692            }
2693        }
2694        unsafe impl Send for Shim<'_> {}
2695        unsafe impl Sync for Shim<'_> {}
2696
2697        match self.body() {
2698            Body::Unprocessed(bytes) => {
2699                if TRACE {
2700                    eprintln!("CompressedData::serialize(\
2701                               algo: {}, {} bytes of unprocessed body)",
2702                              self.algo(), bytes.len());
2703                }
2704
2705                o.write_all(&[self.algo().into()])?;
2706                o.write_all(bytes)?;
2707            },
2708
2709            Body::Processed(bytes) => {
2710                if TRACE {
2711                    eprintln!("CompressedData::serialize(\
2712                               algo: {}, {} bytes of processed body)",
2713                              self.algo(), bytes.len());
2714                }
2715
2716                let o = stream::Message::new(Shim(o));
2717                let mut o = stream::Compressor::new_naked(
2718                    o, self.algo(), Default::default(), 0)?;
2719                o.write_all(bytes)?;
2720                o.finalize()?;
2721            },
2722
2723            Body::Structured(children) => {
2724                if TRACE {
2725                    eprintln!("CompressedData::serialize(\
2726                               algo: {}, {:?} children)",
2727                              self.algo(), children.len());
2728                }
2729
2730                let o = stream::Message::new(Shim(o));
2731                let mut o = stream::Compressor::new_naked(
2732                    o, self.algo(), Default::default(), 0)?;
2733
2734                // Serialize the packets.
2735                for p in children {
2736                    (p as &dyn Marshal).serialize(&mut o)?;
2737                }
2738
2739                o.finalize()?;
2740            },
2741        }
2742        Ok(())
2743    }
2744}
2745
2746impl NetLength for CompressedData {
2747    fn net_len(&self) -> usize {
2748        // Worst case, the data gets larger.  Account for that.
2749        // Experiments suggest that the overhead of compressing random
2750        // data is worse for BZIP2, but it converges to 20% starting
2751        // at ~2k of random data.
2752        let compressed = |l| l + cmp::max(l / 5, 4096);
2753
2754        match self.body() {
2755            Body::Unprocessed(bytes) => 1 /* Algo */ + bytes.len(),
2756            Body::Processed(bytes) => 1 /* Algo */ + compressed(bytes.len()),
2757            Body::Structured(packets) =>
2758                1 // Algo
2759                + compressed(packets.iter().map(|p| {
2760                    (p as &dyn MarshalInto).serialized_len()
2761                }).sum::<usize>()),
2762        }
2763    }
2764}
2765
2766impl MarshalInto for CompressedData {
2767    /// Computes the maximal length of the serialized representation.
2768    ///
2769    /// The size of the serialized compressed data packet is tricky to
2770    /// predict.  First, it depends on the data being compressed.
2771    /// Second, we emit partial body encoded data.
2772    ///
2773    /// This function tries overestimates the length.  However, it may
2774    /// happen that `serialize_into()` fails.
2775    ///
2776    /// # Errors
2777    ///
2778    /// If serialization would fail, this function returns 0.
2779    fn serialized_len(&self) -> usize {
2780        self.net_len()
2781    }
2782
2783    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2784        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2785    }
2786}
2787
2788impl seal::Sealed for PKESK {}
2789impl Marshal for PKESK {
2790    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2791        match self {
2792            PKESK::V3(ref p) => p.serialize(o),
2793            PKESK::V6(p) => p.serialize(o),
2794        }
2795    }
2796}
2797
2798impl NetLength for PKESK {
2799    fn net_len(&self) -> usize {
2800        match self {
2801            PKESK::V3(p) => p.net_len(),
2802            PKESK::V6(p) => p.net_len(),
2803        }
2804    }
2805}
2806
2807impl MarshalInto for PKESK {
2808    fn serialized_len(&self) -> usize {
2809        match self {
2810            PKESK::V3(ref p) => p.serialized_len(),
2811            PKESK::V6(p) => p.serialized_len(),
2812        }
2813    }
2814
2815    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2816        match self {
2817            PKESK::V3(p) =>
2818                generic_serialize_into(p, MarshalInto::serialized_len(p), buf),
2819            PKESK::V6(p) =>
2820                generic_serialize_into(p, MarshalInto::serialized_len(p), buf),
2821        }
2822    }
2823}
2824
2825impl seal::Sealed for PKESK3 {}
2826impl Marshal for PKESK3 {
2827    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2828        write_byte(o, 3)?; // Version.
2829        let wildcard = KeyID::wildcard();
2830        (self.recipient().unwrap_or(&wildcard) as &dyn Marshal).serialize(o)?;
2831        write_byte(o, self.pk_algo().into())?;
2832        self.esk().serialize(o)?;
2833
2834        Ok(())
2835    }
2836}
2837
2838impl NetLength for PKESK3 {
2839    fn net_len(&self) -> usize {
2840        1 // Version.
2841            + 8 // Recipient's key id.
2842            + 1 // Algo.
2843            + self.esk().serialized_len()
2844    }
2845}
2846
2847impl MarshalInto for PKESK3 {
2848    fn serialized_len(&self) -> usize {
2849        self.net_len()
2850    }
2851
2852    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2853        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2854    }
2855}
2856
2857impl seal::Sealed for PKESK6 {}
2858impl Marshal for PKESK6 {
2859    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2860        write_byte(o, 6)?; // Version.
2861        if let Some(recipient) = self.recipient() {
2862             // Recipient length.
2863            write_byte(o, ((recipient as &dyn MarshalInto).serialized_len() + 1) as u8)?;
2864            match recipient {
2865                Fingerprint::V4(_) => write_byte(o, 4)?,
2866                Fingerprint::V6(_) => write_byte(o, 6)?,
2867                Fingerprint::Unknown { version, .. } =>
2868                    write_byte(o, version.unwrap_or(0xff))?,
2869            }
2870            (recipient as &dyn Marshal).serialize(o)?;
2871        } else {
2872            // No recipient.
2873            write_byte(o, 0)?;
2874        }
2875
2876        write_byte(o, self.pk_algo().into())?;
2877        self.esk().serialize(o)?;
2878
2879        Ok(())
2880    }
2881}
2882
2883impl NetLength for PKESK6 {
2884    fn net_len(&self) -> usize {
2885        1 // Version.
2886            + 1 // Recipient length.
2887            // Recipient's versioned fingerprint, if any:
2888            + self.recipient().map(|r| r.as_bytes().len() + 1).unwrap_or(0)
2889            + 1 // Algo.
2890            + self.esk().serialized_len()
2891    }
2892}
2893
2894impl MarshalInto for PKESK6 {
2895    fn serialized_len(&self) -> usize {
2896        self.net_len()
2897    }
2898
2899    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2900        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2901    }
2902}
2903
2904impl seal::Sealed for SKESK {}
2905impl Marshal for SKESK {
2906    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2907        match self {
2908            SKESK::V4(ref s) => s.serialize(o),
2909            SKESK::V6(ref s) => s.serialize(o),
2910        }
2911    }
2912}
2913
2914impl NetLength for SKESK {
2915    fn net_len(&self) -> usize {
2916        match self {
2917            SKESK::V4(ref s) => s.net_len(),
2918            SKESK::V6(ref s) => s.net_len(),
2919        }
2920    }
2921}
2922
2923impl MarshalInto for SKESK {
2924    fn serialized_len(&self) -> usize {
2925        match self {
2926            SKESK::V4(ref s) => s.serialized_len(),
2927            SKESK::V6(ref s) => s.serialized_len(),
2928        }
2929    }
2930
2931    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2932        match self {
2933            SKESK::V4(s) =>
2934                generic_serialize_into(s, MarshalInto::serialized_len(s), buf),
2935            SKESK::V6(s) =>
2936                generic_serialize_into(s, MarshalInto::serialized_len(s), buf),
2937        }
2938    }
2939}
2940
2941impl seal::Sealed for SKESK4 {}
2942impl Marshal for SKESK4 {
2943    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2944        write_byte(o, 4)?; // Version.
2945        write_byte(o, self.symmetric_algo().into())?;
2946        self.s2k().serialize(o)?;
2947        o.write_all(self.raw_esk())?;
2948        Ok(())
2949    }
2950}
2951
2952impl NetLength for SKESK4 {
2953    fn net_len(&self) -> usize {
2954        1 // Version.
2955            + 1 // Algo.
2956            + self.s2k().serialized_len()
2957            + self.raw_esk().len()
2958    }
2959}
2960
2961impl MarshalInto for SKESK4 {
2962    fn serialized_len(&self) -> usize {
2963        self.net_len()
2964    }
2965
2966    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
2967        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
2968    }
2969}
2970
2971impl seal::Sealed for SKESK6 {}
2972impl Marshal for SKESK6 {
2973    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
2974        let s2k_len = self.s2k().serialized_len();
2975
2976        write_byte(o, 6)?; // Version.
2977        // Parameter octet count.
2978        write_byte(o, (1   // Symmetric algorithm.
2979                       + 1 // AEAD mode.
2980                       + 1 // S2K octet count.
2981                       + s2k_len
2982                       + self.aead_iv().len()) as u8)?;
2983        write_byte(o, self.symmetric_algo().into())?;
2984        write_byte(o, self.aead_algo().into())?;
2985        // S2K octet count.
2986        write_byte(o, s2k_len as u8)?;
2987        self.s2k().serialize(o)?;
2988        o.write_all(self.aead_iv())?;
2989        o.write_all(self.esk())?;
2990
2991        Ok(())
2992    }
2993}
2994
2995impl NetLength for SKESK6 {
2996    fn net_len(&self) -> usize {
2997        1 // Version.
2998            + 1 // Parameter octet count.
2999            + 1 // Cipher algo.
3000            + 1 // AEAD algo.
3001            + 1 // S2K octet count.
3002            + self.s2k().serialized_len()
3003            + self.aead_iv().len()
3004            + self.esk().len()
3005    }
3006}
3007
3008impl MarshalInto for SKESK6 {
3009    fn serialized_len(&self) -> usize {
3010        self.net_len()
3011    }
3012
3013    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
3014        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
3015    }
3016}
3017
3018impl seal::Sealed for SEIP {}
3019impl Marshal for SEIP {
3020    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
3021        match self {
3022            SEIP::V1(p) => p.serialize(o),
3023            SEIP::V2(p) => p.serialize(o),
3024        }
3025    }
3026}
3027
3028impl NetLength for SEIP {
3029    fn net_len(&self) -> usize {
3030        match self {
3031            SEIP::V1(p) => p.net_len(),
3032            SEIP::V2(p) => p.net_len(),
3033        }
3034    }
3035}
3036
3037impl MarshalInto for SEIP {
3038    fn serialized_len(&self) -> usize {
3039        self.net_len()
3040    }
3041
3042    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
3043        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
3044    }
3045}
3046
3047impl seal::Sealed for SEIP1 {}
3048impl Marshal for SEIP1 {
3049    /// Writes a serialized version of the specified `SEIP1`
3050    /// packet to `o`.
3051    ///
3052    /// # Errors
3053    ///
3054    /// Returns `Error::InvalidOperation` if this packet has children.
3055    /// To construct an encrypted message, use
3056    /// `serialize::stream::Encryptor`.
3057    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
3058        match self.body() {
3059            Body::Unprocessed(bytes) => {
3060                o.write_all(&[1])?;
3061                o.write_all(bytes)?;
3062                Ok(())
3063            },
3064            _ => Err(Error::InvalidOperation(
3065                "Cannot encrypt, use serialize::stream::Encryptor".into())
3066                     .into()),
3067        }
3068    }
3069}
3070
3071impl NetLength for SEIP1 {
3072    fn net_len(&self) -> usize {
3073        match self.body() {
3074            Body::Unprocessed(bytes) => 1 /* Version */ + bytes.len(),
3075            _ => 0,
3076        }
3077    }
3078}
3079
3080impl MarshalInto for SEIP1 {
3081    fn serialized_len(&self) -> usize {
3082        self.net_len()
3083    }
3084
3085    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
3086        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
3087    }
3088}
3089
3090impl SEIP2 {
3091    /// Writes the headers of the `SEIP2` data packet to `o`.
3092    fn serialize_headers(&self, o: &mut dyn std::io::Write) -> Result<()> {
3093        o.write_all(&[2, // Version.
3094                      self.symmetric_algo().into(),
3095                      self.aead().into(),
3096                      self.chunk_size().trailing_zeros() as u8 - 6])?;
3097        o.write_all(self.salt())?;
3098        Ok(())
3099    }
3100}
3101
3102impl seal::Sealed for SEIP2 {}
3103impl Marshal for SEIP2 {
3104    /// Writes a serialized version of the specified `SEIPv2`
3105    /// packet to `o`.
3106    ///
3107    /// # Errors
3108    ///
3109    /// Returns `Error::InvalidOperation` if this packet has children.
3110    /// To construct an encrypted message, use
3111    /// `serialize::stream::Encryptor`.
3112    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
3113        match self.body() {
3114            Body::Unprocessed(bytes) => {
3115                self.serialize_headers(o)?;
3116                o.write_all(bytes)?;
3117                Ok(())
3118            },
3119            _ => Err(Error::InvalidOperation(
3120                "Cannot encrypt, use serialize::stream::Encryptor".into())
3121                     .into()),
3122        }
3123    }
3124}
3125
3126impl NetLength for SEIP2 {
3127    fn net_len(&self) -> usize {
3128        match self.body() {
3129            Body::Unprocessed(bytes) =>
3130                4 // Headers.
3131                + self.salt().len()
3132                + bytes.len(),
3133            _ => 0,
3134        }
3135    }
3136}
3137
3138impl MarshalInto for SEIP2 {
3139    fn serialized_len(&self) -> usize {
3140        self.net_len()
3141    }
3142
3143    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
3144        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
3145    }
3146}
3147
3148impl seal::Sealed for MDC {}
3149impl Marshal for MDC {
3150    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
3151        o.write_all(self.digest())?;
3152        Ok(())
3153    }
3154}
3155
3156impl NetLength for MDC {
3157    fn net_len(&self) -> usize {
3158        20
3159    }
3160}
3161
3162impl MarshalInto for MDC {
3163    fn serialized_len(&self) -> usize {
3164        self.net_len()
3165    }
3166
3167    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
3168        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
3169    }
3170}
3171
3172impl seal::Sealed for Padding {}
3173impl Marshal for Padding {
3174    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
3175        o.write_all(self.value())?;
3176        Ok(())
3177    }
3178}
3179
3180impl NetLength for Padding {
3181    fn net_len(&self) -> usize {
3182        self.value().len()
3183    }
3184}
3185
3186impl MarshalInto for Padding {
3187    fn serialized_len(&self) -> usize {
3188        self.net_len()
3189    }
3190
3191    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
3192        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
3193    }
3194}
3195
3196impl Serialize for Packet {}
3197impl seal::Sealed for Packet {}
3198impl Marshal for Packet {
3199    /// Writes a serialized version of the specified `Packet` to `o`.
3200    ///
3201    /// This function works recursively: if the packet contains any
3202    /// packets, they are also serialized.
3203    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
3204        CTB::new(self.tag()).serialize(o)?;
3205
3206        // Special-case the compressed data packet, because we need
3207        // the accurate length, and CompressedData::net_len()
3208        // overestimates the size.
3209        if let Packet::CompressedData(ref p) = self {
3210            let mut body = Vec::new();
3211            p.serialize(&mut body)?;
3212            BodyLength::Full(body.len() as u32).serialize(o)?;
3213            o.write_all(&body)?;
3214            return Ok(());
3215        }
3216
3217        BodyLength::Full(self.net_len() as u32).serialize(o)?;
3218        match self {
3219            Packet::Unknown(ref p) => p.serialize(o),
3220            Packet::Signature(ref p) => p.serialize(o),
3221            Packet::OnePassSig(ref p) => p.serialize(o),
3222            Packet::PublicKey(ref p) => p.serialize(o),
3223            Packet::PublicSubkey(ref p) => p.serialize(o),
3224            Packet::SecretKey(ref p) => p.serialize(o),
3225            Packet::SecretSubkey(ref p) => p.serialize(o),
3226            Packet::Marker(ref p) => p.serialize(o),
3227            Packet::Trust(ref p) => p.serialize(o),
3228            Packet::UserID(ref p) => p.serialize(o),
3229            Packet::UserAttribute(ref p) => p.serialize(o),
3230            Packet::Literal(ref p) => p.serialize(o),
3231            Packet::CompressedData(_) => unreachable!("handled above"),
3232            Packet::PKESK(ref p) => p.serialize(o),
3233            Packet::SKESK(ref p) => p.serialize(o),
3234            Packet::SEIP(ref p) => p.serialize(o),
3235            #[allow(deprecated)]
3236            Packet::MDC(ref p) => p.serialize(o),
3237            Packet::Padding(p) => p.serialize(o),
3238        }
3239    }
3240
3241    /// Exports a serialized version of the specified `Packet` to `o`.
3242    ///
3243    /// This function works recursively: if the packet contains any
3244    /// packets, they are also serialized.
3245    fn export(&self, o: &mut dyn std::io::Write) -> Result<()> {
3246        CTB::new(self.tag()).serialize(o)?;
3247
3248        // Special-case the compressed data packet, because we need
3249        // the accurate length, and CompressedData::net_len()
3250        // overestimates the size.
3251        if let Packet::CompressedData(ref p) = self {
3252            let mut body = Vec::new();
3253            p.export(&mut body)?;
3254            BodyLength::Full(body.len() as u32).export(o)?;
3255            o.write_all(&body)?;
3256            return Ok(());
3257        }
3258
3259        BodyLength::Full(self.net_len() as u32).export(o)?;
3260        match self {
3261            Packet::Unknown(ref p) => p.export(o),
3262            Packet::Signature(ref p) => p.export(o),
3263            Packet::OnePassSig(ref p) => p.export(o),
3264            Packet::PublicKey(ref p) => p.export(o),
3265            Packet::PublicSubkey(ref p) => p.export(o),
3266            Packet::SecretKey(ref p) => p.export(o),
3267            Packet::SecretSubkey(ref p) => p.export(o),
3268            Packet::Marker(ref p) => p.export(o),
3269            Packet::Trust(ref p) => p.export(o),
3270            Packet::UserID(ref p) => p.export(o),
3271            Packet::UserAttribute(ref p) => p.export(o),
3272            Packet::Literal(ref p) => p.export(o),
3273            Packet::CompressedData(_) => unreachable!("handled above"),
3274            Packet::PKESK(ref p) => p.export(o),
3275            Packet::SKESK(ref p) => p.export(o),
3276            Packet::SEIP(ref p) => p.export(o),
3277            #[allow(deprecated)]
3278            Packet::MDC(ref p) => p.export(o),
3279            Packet::Padding(p) => p.export(o),
3280        }
3281    }
3282}
3283
3284impl NetLength for Packet {
3285    fn net_len(&self) -> usize {
3286        match self {
3287            Packet::Unknown(ref p) => p.net_len(),
3288            Packet::Signature(ref p) => p.net_len(),
3289            Packet::OnePassSig(ref p) => p.net_len(),
3290            Packet::PublicKey(ref p) => p.net_len(),
3291            Packet::PublicSubkey(ref p) => p.net_len(),
3292            Packet::SecretKey(ref p) => p.net_len(),
3293            Packet::SecretSubkey(ref p) => p.net_len(),
3294            Packet::Marker(ref p) => p.net_len(),
3295            Packet::Trust(ref p) => p.net_len(),
3296            Packet::UserID(ref p) => p.net_len(),
3297            Packet::UserAttribute(ref p) => p.net_len(),
3298            Packet::Literal(ref p) => p.net_len(),
3299            Packet::CompressedData(ref p) => p.net_len(),
3300            Packet::PKESK(ref p) => p.net_len(),
3301            Packet::SKESK(ref p) => p.net_len(),
3302            Packet::SEIP(ref p) => p.net_len(),
3303            #[allow(deprecated)]
3304            Packet::MDC(ref p) => p.net_len(),
3305            Packet::Padding(p) => p.net_len(),
3306        }
3307    }
3308}
3309
3310impl SerializeInto for Packet {}
3311impl MarshalInto for Packet {
3312    fn serialized_len(&self) -> usize {
3313        self.gross_len()
3314    }
3315
3316    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
3317        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
3318    }
3319
3320    fn export_into(&self, buf: &mut [u8]) -> Result<usize> {
3321        generic_export_into(self, MarshalInto::serialized_len(self), buf)
3322    }
3323}
3324
3325/// References packet bodies.
3326///
3327/// Like [`openpgp::Packet`], but instead of owning the packet's bodies,
3328/// they are referenced.  `PacketRef` is only used to serialize packet
3329/// bodies (like [`packet::Signature`]) encapsulating them in OpenPGP
3330/// frames.
3331///
3332/// [`openpgp::Packet`]: super::Packet
3333/// [`packet::Signature`]: crate::packet::Signature
3334#[allow(dead_code)]
3335enum PacketRef<'a> {
3336    /// Unknown packet.
3337    Unknown(&'a packet::Unknown),
3338    /// Signature packet.
3339    Signature(&'a packet::Signature),
3340    /// One pass signature packet.
3341    OnePassSig(&'a packet::OnePassSig),
3342    /// Public key packet.
3343    PublicKey(&'a packet::key::PublicKey),
3344    /// Public subkey packet.
3345    PublicSubkey(&'a packet::key::PublicSubkey),
3346    /// Public/Secret key pair.
3347    SecretKey(&'a packet::key::SecretKey),
3348    /// Public/Secret subkey pair.
3349    SecretSubkey(&'a packet::key::SecretSubkey),
3350    /// Marker packet.
3351    Marker(&'a packet::Marker),
3352    /// Trust packet.
3353    Trust(&'a packet::Trust),
3354    /// User ID packet.
3355    UserID(&'a packet::UserID),
3356    /// User attribute packet.
3357    UserAttribute(&'a packet::UserAttribute),
3358    /// Literal data packet.
3359    Literal(&'a packet::Literal),
3360    /// Compressed literal data packet.
3361    CompressedData(&'a packet::CompressedData),
3362    /// Public key encrypted data packet.
3363    PKESK(&'a packet::PKESK),
3364    /// Symmetric key encrypted data packet.
3365    SKESK(&'a packet::SKESK),
3366    /// Symmetric key encrypted, integrity protected data packet.
3367    SEIP(&'a packet::SEIP),
3368    /// Modification detection code packet.
3369    MDC(&'a packet::MDC),
3370    /// Padding packet.
3371    Padding(&'a packet::Padding),
3372}
3373
3374impl<'a> PacketRef<'a> {
3375    /// Returns the `PacketRef's` corresponding OpenPGP tag.
3376    ///
3377    /// Tags are explained in [Section 5 of RFC 9580].
3378    ///
3379    ///   [Section 5 of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-5
3380    fn tag(&self) -> packet::Tag {
3381        match self {
3382            PacketRef::Unknown(packet) => packet.tag(),
3383            PacketRef::Signature(_) => Tag::Signature,
3384            PacketRef::OnePassSig(_) => Tag::OnePassSig,
3385            PacketRef::PublicKey(_) => Tag::PublicKey,
3386            PacketRef::PublicSubkey(_) => Tag::PublicSubkey,
3387            PacketRef::SecretKey(_) => Tag::SecretKey,
3388            PacketRef::SecretSubkey(_) => Tag::SecretSubkey,
3389            PacketRef::Marker(_) => Tag::Marker,
3390            PacketRef::Trust(_) => Tag::Trust,
3391            PacketRef::UserID(_) => Tag::UserID,
3392            PacketRef::UserAttribute(_) => Tag::UserAttribute,
3393            PacketRef::Literal(_) => Tag::Literal,
3394            PacketRef::CompressedData(_) => Tag::CompressedData,
3395            PacketRef::PKESK(_) => Tag::PKESK,
3396            PacketRef::SKESK(_) => Tag::SKESK,
3397            PacketRef::SEIP(_) => Tag::SEIP,
3398            PacketRef::MDC(_) => Tag::MDC,
3399            PacketRef::Padding(_) => Tag::Padding,
3400        }
3401    }
3402}
3403
3404impl<'a> Serialize for PacketRef<'a> {}
3405impl<'a> seal::Sealed for PacketRef<'a> {}
3406impl<'a> Marshal for PacketRef<'a> {
3407    /// Writes a serialized version of the specified `Packet` to `o`.
3408    ///
3409    /// This function works recursively: if the packet contains any
3410    /// packets, they are also serialized.
3411    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
3412        CTB::new(self.tag()).serialize(o)?;
3413
3414        // Special-case the compressed data packet, because we need
3415        // the accurate length, and CompressedData::net_len()
3416        // overestimates the size.
3417        if let PacketRef::CompressedData(p) = self {
3418            let mut body = Vec::new();
3419            p.serialize(&mut body)?;
3420            BodyLength::Full(body.len() as u32).serialize(o)?;
3421            o.write_all(&body)?;
3422            return Ok(());
3423        }
3424
3425        BodyLength::Full(self.net_len() as u32).serialize(o)?;
3426        match self {
3427            PacketRef::Unknown(p) => p.serialize(o),
3428            PacketRef::Signature(p) => p.serialize(o),
3429            PacketRef::OnePassSig(p) => p.serialize(o),
3430            PacketRef::PublicKey(p) => p.serialize(o),
3431            PacketRef::PublicSubkey(p) => p.serialize(o),
3432            PacketRef::SecretKey(p) => p.serialize(o),
3433            PacketRef::SecretSubkey(p) => p.serialize(o),
3434            PacketRef::Marker(p) => p.serialize(o),
3435            PacketRef::Trust(p) => p.serialize(o),
3436            PacketRef::UserID(p) => p.serialize(o),
3437            PacketRef::UserAttribute(p) => p.serialize(o),
3438            PacketRef::Literal(p) => p.serialize(o),
3439            PacketRef::CompressedData(_) => unreachable!("handled above"),
3440            PacketRef::PKESK(p) => p.serialize(o),
3441            PacketRef::SKESK(p) => p.serialize(o),
3442            PacketRef::SEIP(p) => p.serialize(o),
3443            PacketRef::MDC(p) => p.serialize(o),
3444            PacketRef::Padding(p) => p.serialize(o),
3445        }
3446    }
3447
3448    /// Exports a serialized version of the specified `Packet` to `o`.
3449    ///
3450    /// This function works recursively: if the packet contains any
3451    /// packets, they are also serialized.
3452    fn export(&self, o: &mut dyn std::io::Write) -> Result<()> {
3453        CTB::new(self.tag()).serialize(o)?;
3454
3455        // Special-case the compressed data packet, because we need
3456        // the accurate length, and CompressedData::net_len()
3457        // overestimates the size.
3458        if let PacketRef::CompressedData(p) = self {
3459            let mut body = Vec::new();
3460            p.export(&mut body)?;
3461            BodyLength::Full(body.len() as u32).export(o)?;
3462            o.write_all(&body)?;
3463            return Ok(());
3464        }
3465
3466        BodyLength::Full(self.net_len() as u32).export(o)?;
3467        match self {
3468            PacketRef::Unknown(p) => p.export(o),
3469            PacketRef::Signature(p) => p.export(o),
3470            PacketRef::OnePassSig(p) => p.export(o),
3471            PacketRef::PublicKey(p) => p.export(o),
3472            PacketRef::PublicSubkey(p) => p.export(o),
3473            PacketRef::SecretKey(p) => p.export(o),
3474            PacketRef::SecretSubkey(p) => p.export(o),
3475            PacketRef::Marker(p) => p.export(o),
3476            PacketRef::Trust(p) => p.export(o),
3477            PacketRef::UserID(p) => p.export(o),
3478            PacketRef::UserAttribute(p) => p.export(o),
3479            PacketRef::Literal(p) => p.export(o),
3480            PacketRef::CompressedData(_) => unreachable!("handled above"),
3481            PacketRef::PKESK(p) => p.export(o),
3482            PacketRef::SKESK(p) => p.export(o),
3483            PacketRef::SEIP(p) => p.export(o),
3484            PacketRef::MDC(p) => p.export(o),
3485            PacketRef::Padding(p) => p.export(o),
3486        }
3487    }
3488}
3489
3490impl<'a> NetLength for PacketRef<'a> {
3491    fn net_len(&self) -> usize {
3492        match self {
3493            PacketRef::Unknown(p) => p.net_len(),
3494            PacketRef::Signature(p) => p.net_len(),
3495            PacketRef::OnePassSig(p) => p.net_len(),
3496            PacketRef::PublicKey(p) => p.net_len(),
3497            PacketRef::PublicSubkey(p) => p.net_len(),
3498            PacketRef::SecretKey(p) => p.net_len(),
3499            PacketRef::SecretSubkey(p) => p.net_len(),
3500            PacketRef::Marker(p) => p.net_len(),
3501            PacketRef::Trust(p) => p.net_len(),
3502            PacketRef::UserID(p) => p.net_len(),
3503            PacketRef::UserAttribute(p) => p.net_len(),
3504            PacketRef::Literal(p) => p.net_len(),
3505            PacketRef::CompressedData(p) => p.net_len(),
3506            PacketRef::PKESK(p) => p.net_len(),
3507            PacketRef::SKESK(p) => p.net_len(),
3508            PacketRef::SEIP(p) => p.net_len(),
3509            PacketRef::MDC(p) => p.net_len(),
3510            PacketRef::Padding(p) => p.net_len(),
3511        }
3512    }
3513}
3514
3515impl<'a> SerializeInto for PacketRef<'a> {}
3516impl<'a> MarshalInto for PacketRef<'a> {
3517    fn serialized_len(&self) -> usize {
3518        self.gross_len()
3519    }
3520
3521    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
3522        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
3523    }
3524
3525    fn export_into(&self, buf: &mut [u8]) -> Result<usize> {
3526        generic_export_into(self, MarshalInto::serialized_len(self), buf)
3527    }
3528}
3529
3530impl Serialize for PacketPile {}
3531impl seal::Sealed for PacketPile {}
3532impl Marshal for PacketPile {
3533    /// Writes a serialized version of the specified `PacketPile` to `o`.
3534    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
3535        for p in self.children() {
3536            (p as &dyn Marshal).serialize(o)?;
3537        }
3538
3539        Ok(())
3540    }
3541
3542    /// Exports a serialized version of the specified `PacketPile` to `o`.
3543    fn export(&self, o: &mut dyn std::io::Write) -> Result<()> {
3544        for p in self.children() {
3545            (p as &dyn Marshal).export(o)?;
3546        }
3547
3548        Ok(())
3549    }
3550}
3551
3552impl SerializeInto for PacketPile {}
3553impl MarshalInto for PacketPile {
3554    fn serialized_len(&self) -> usize {
3555        self.children().map(|p| {
3556            (p as &dyn MarshalInto).serialized_len()
3557        }).sum()
3558    }
3559
3560    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
3561        generic_serialize_into(self, MarshalInto::serialized_len(self), buf)
3562    }
3563
3564    fn export_into(&self, buf: &mut [u8]) -> Result<usize> {
3565        generic_export_into(self, MarshalInto::serialized_len(self), buf)
3566    }
3567}
3568
3569impl Serialize for Message {}
3570impl seal::Sealed for Message {}
3571impl Marshal for Message {
3572    /// Writes a serialized version of the specified `Message` to `o`.
3573    fn serialize(&self, o: &mut dyn std::io::Write) -> Result<()> {
3574        Marshal::serialize(self.packets(), o)
3575    }
3576}
3577
3578impl SerializeInto for Message {}
3579impl MarshalInto for Message {
3580    fn serialized_len(&self) -> usize {
3581        MarshalInto::serialized_len(self.packets())
3582    }
3583
3584    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
3585        MarshalInto::serialize_into(self.packets(), buf)
3586    }
3587
3588    fn export_into(&self, buf: &mut [u8]) -> Result<usize> {
3589        MarshalInto::export_into(self.packets(), buf)
3590    }
3591}
3592
3593#[cfg(test)]
3594mod test {
3595    use super::*;
3596    use crate::types::CompressionAlgorithm;
3597    use crate::parse::to_unknown_packet;
3598    use crate::parse::PacketParserBuilder;
3599    use crate::parse::Parse;
3600
3601    // A convenient function to dump binary data to stdout.
3602    fn binary_pp(data: &[u8]) -> String {
3603        let mut output = Vec::new();
3604        crate::fmt::hex::Dumper::new(&mut output, "")
3605            .write_ascii(data).unwrap();
3606        // We know the content is valid UTF-8.
3607        String::from_utf8(output).unwrap()
3608    }
3609
3610    // Does a bit-wise comparison of two packets ignoring the CTB
3611    // format, the body length encoding, and whether partial body
3612    // length encoding was used.
3613    fn packets_bitwise_compare(filename: &str, packet: &Packet,
3614                               expected: &[u8], got: &[u8]) {
3615        let expected = to_unknown_packet(expected).unwrap();
3616        let got = to_unknown_packet(got).unwrap();
3617
3618        let expected_body = expected.body();
3619        let got_body = got.body();
3620
3621        let mut fail = false;
3622        if expected.tag() != got.tag() {
3623            eprintln!("Expected a {:?}, got a {:?}", expected.tag(), got.tag());
3624            fail = true;
3625        }
3626        if expected_body != got_body {
3627            eprintln!("Packet contents don't match (for {}):",
3628                      filename);
3629            eprintln!("Expected ({} bytes):\n{}",
3630                      expected_body.len(), binary_pp(expected_body));
3631            eprintln!("Got ({} bytes):\n{}",
3632                      got_body.len(), binary_pp(got_body));
3633            eprintln!("Packet: {:#?}", packet);
3634            fail = true;
3635        }
3636        if fail {
3637            panic!("Packets don't match (for {}).", filename);
3638        }
3639    }
3640
3641    #[test]
3642    fn serialize_test_1() {
3643        // Given a packet in serialized form:
3644        //
3645        // - Parse and reserialize it;
3646        //
3647        // - Do a bitwise comparison (modulo the body length encoding)
3648        //   of the original and reserialized data.
3649        //
3650        // Note: This test only works on messages with a single packet.
3651        //
3652        // Note: This test does not work with non-deterministic
3653        // packets, like compressed data packets, since the serialized
3654        // forms may be different.
3655
3656        let filenames = [
3657            "literal-mode-b.pgp",
3658            "literal-mode-t-partial-body.pgp",
3659
3660            "sig.pgp",
3661
3662            "public-key-bare.pgp",
3663            "public-subkey-bare.pgp",
3664            "userid-bare.pgp",
3665
3666            "s2k/mode-0-password-1234.pgp",
3667            "s2k/mode-0-password-1234.pgp",
3668            "s2k/mode-1-password-123456-1.pgp",
3669            "s2k/mode-1-password-foobar-2.pgp",
3670            "s2k/mode-3-aes128-password-13-times-0123456789.pgp",
3671            "s2k/mode-3-aes192-password-123.pgp",
3672            "s2k/mode-3-encrypted-key-password-bgtyhn.pgp",
3673            "s2k/mode-3-password-9876-2.pgp",
3674            "s2k/mode-3-password-qwerty-1.pgp",
3675            "s2k/mode-3-twofish-password-13-times-0123456789.pgp",
3676        ];
3677
3678        for filename in filenames.iter() {
3679            // 1. Read the message byte stream into a local buffer.
3680            let data = crate::tests::message(filename);
3681
3682            // 2. Parse the message.
3683            let pile = PacketPile::from_bytes(data).unwrap();
3684
3685            // The following test only works if the message has a
3686            // single top-level packet.
3687            assert_eq!(pile.children().len(), 1);
3688
3689            // 3. Serialize the packet it into a local buffer.
3690            let p = pile.descendants().next().unwrap();
3691            let mut buffer = Vec::new();
3692            match p {
3693                Packet::Literal(_) | Packet::Signature(_)
3694                    | Packet::PublicKey(_) | Packet::PublicSubkey(_)
3695                    | Packet::UserID(_) | Packet::SKESK(_) => (),
3696                p => {
3697                    panic!("Didn't expect a {:?} packet.", p.tag());
3698                },
3699            }
3700            (p as &dyn Marshal).serialize(&mut buffer).unwrap();
3701
3702            // 4. Modulo the body length encoding, check that the
3703            // reserialized content is identical to the original data.
3704            packets_bitwise_compare(filename, p, data, &buffer[..]);
3705        }
3706    }
3707
3708    #[test]
3709    fn serialize_test_1_unknown() {
3710        // This is an variant of serialize_test_1 that tests the
3711        // unknown packet serializer.
3712        let filenames = [
3713            "compressed-data-algo-1.pgp",
3714            "compressed-data-algo-2.pgp",
3715            "compressed-data-algo-3.pgp",
3716            "recursive-2.pgp",
3717            "recursive-3.pgp",
3718        ];
3719
3720        for filename in filenames.iter() {
3721            // 1. Read the message byte stream into a local buffer.
3722            let data = crate::tests::message(filename);
3723
3724            // 2. Parse the message.
3725            let u = Packet::Unknown(to_unknown_packet(data).unwrap());
3726
3727            // 3. Serialize the packet it into a local buffer.
3728            let data2 = (&u as &dyn MarshalInto).to_vec().unwrap();
3729
3730            // 4. Modulo the body length encoding, check that the
3731            // reserialized content is identical to the original data.
3732            packets_bitwise_compare(filename, &u, data, &data2[..]);
3733        }
3734
3735    }
3736
3737    #[test]
3738    fn serialize_test_2() {
3739        // Given a packet in serialized form:
3740        //
3741        // - Parse, reserialize, and reparse it;
3742        //
3743        // - Compare the messages.
3744        //
3745        // Note: This test only works on messages with a single packet
3746        // top-level packet.
3747        //
3748        // Note: serialize_test_1 is a better test, because it
3749        // compares the serialized data, but serialize_test_1 doesn't
3750        // work if the content is non-deterministic.
3751        let filenames = [
3752            "compressed-data-algo-1.pgp",
3753            "compressed-data-algo-2.pgp",
3754            "compressed-data-algo-3.pgp",
3755            "recursive-2.pgp",
3756            "recursive-3.pgp",
3757        ];
3758
3759        for filename in filenames.iter() {
3760            eprintln!("{}...", filename);
3761
3762            // 1. Read the message into a local buffer.
3763            let data = crate::tests::message(filename);
3764
3765            // 2. Do a shallow parse of the message.  In other words,
3766            // never recurse so that the resulting message only
3767            // contains the top-level packets.  Any containers will
3768            // have their raw content stored in packet.content.
3769            let pile = PacketParserBuilder::from_bytes(data).unwrap()
3770                .max_recursion_depth(0)
3771                .buffer_unread_content()
3772                //.trace()
3773                .into_packet_pile().unwrap();
3774
3775            // 3. Get the first packet.
3776            let po = pile.descendants().next();
3777            if let Some(&Packet::CompressedData(ref cd)) = po {
3778                if ! cd.algo().is_supported() {
3779                    eprintln!("Skipping {} because {} is not supported.",
3780                              filename, cd.algo());
3781                    continue;
3782                }
3783
3784                // 4. Serialize the container.
3785                let buffer =
3786                    (&Packet::CompressedData(cd.clone()) as &dyn MarshalInto)
3787                        .to_vec().unwrap();
3788
3789                // 5. Reparse it.
3790                let pile2 = PacketParserBuilder::from_bytes(&buffer[..]).unwrap()
3791                    .max_recursion_depth(0)
3792                    .buffer_unread_content()
3793                    //.trace()
3794                    .into_packet_pile().unwrap();
3795
3796                // 6. Make sure the original message matches the
3797                // serialized and reparsed message.
3798                if pile != pile2 {
3799                    eprintln!("Orig:");
3800                    let p = pile.children().next().unwrap();
3801                    eprintln!("{:?}", p);
3802                    let body = p.processed_body().unwrap();
3803                    eprintln!("Body: {}", body.len());
3804                    eprintln!("{}", binary_pp(body));
3805
3806                    eprintln!("Reparsed:");
3807                    let p = pile2.children().next().unwrap();
3808                    eprintln!("{:?}", p);
3809                    let body = p.processed_body().unwrap();
3810                    eprintln!("Body: {}", body.len());
3811                    eprintln!("{}", binary_pp(body));
3812
3813                    assert_eq!(pile, pile2);
3814                }
3815            } else {
3816                panic!("Expected a compressed data data packet.");
3817            }
3818        }
3819    }
3820
3821    // Create some crazy nesting structures, serialize the messages,
3822    // reparse them, and make sure we get the same result.
3823    #[test]
3824    fn serialize_test_3() {
3825        use crate::types::DataFormat::Unicode as T;
3826
3827        // serialize_test_1 and serialize_test_2 parse a byte stream.
3828        // This tests creates the message, and then serializes and
3829        // reparses it.
3830
3831        let mut messages = Vec::new();
3832
3833        // 1: CompressedData(CompressedData { algo: 0 })
3834        //  1: Literal(Literal { body: "one (3 bytes)" })
3835        //  2: Literal(Literal { body: "two (3 bytes)" })
3836        // 2: Literal(Literal { body: "three (5 bytes)" })
3837        let mut one = Literal::new(T);
3838        one.set_body(b"one".to_vec());
3839        let mut two = Literal::new(T);
3840        two.set_body(b"two".to_vec());
3841        let mut three = Literal::new(T);
3842        three.set_body(b"three".to_vec());
3843        let mut four = Literal::new(T);
3844        four.set_body(b"four".to_vec());
3845        let mut five = Literal::new(T);
3846        five.set_body(b"five".to_vec());
3847        let mut six = Literal::new(T);
3848        six.set_body(b"six".to_vec());
3849
3850        let mut top_level = Vec::new();
3851        top_level.push(
3852            CompressedData::new(CompressionAlgorithm::Uncompressed)
3853                .push(one.clone().into())
3854                .push(two.clone().into())
3855                .into());
3856        top_level.push(three.clone().into());
3857        messages.push(top_level);
3858
3859        // 1: CompressedData(CompressedData { algo: 0 })
3860        //  1: CompressedData(CompressedData { algo: 0 })
3861        //   1: Literal(Literal { body: "one (3 bytes)" })
3862        //   2: Literal(Literal { body: "two (3 bytes)" })
3863        //  2: CompressedData(CompressedData { algo: 0 })
3864        //   1: Literal(Literal { body: "three (5 bytes)" })
3865        //   2: Literal(Literal { body: "four (4 bytes)" })
3866        let mut top_level = Vec::new();
3867        top_level.push(
3868            CompressedData::new(CompressionAlgorithm::Uncompressed)
3869                .push(CompressedData::new(CompressionAlgorithm::Uncompressed)
3870                      .push(one.clone().into())
3871                      .push(two.clone().into())
3872                      .into())
3873                .push(CompressedData::new(CompressionAlgorithm::Uncompressed)
3874                      .push(three.clone().into())
3875                      .push(four.clone().into())
3876                      .into())
3877                .into());
3878        messages.push(top_level);
3879
3880        // 1: CompressedData(CompressedData { algo: 0 })
3881        //  1: CompressedData(CompressedData { algo: 0 })
3882        //   1: CompressedData(CompressedData { algo: 0 })
3883        //    1: CompressedData(CompressedData { algo: 0 })
3884        //     1: Literal(Literal { body: "one (3 bytes)" })
3885        //     2: Literal(Literal { body: "two (3 bytes)" })
3886        //  2: CompressedData(CompressedData { algo: 0 })
3887        //   1: CompressedData(CompressedData { algo: 0 })
3888        //    1: Literal(Literal { body: "three (5 bytes)" })
3889        //   2: Literal(Literal { body: "four (4 bytes)" })
3890        let mut top_level = Vec::new();
3891        top_level.push(
3892            CompressedData::new(CompressionAlgorithm::Uncompressed)
3893                .push(CompressedData::new(CompressionAlgorithm::Uncompressed)
3894                    .push(CompressedData::new(CompressionAlgorithm::Uncompressed)
3895                        .push(CompressedData::new(CompressionAlgorithm::Uncompressed)
3896                            .push(one.clone().into())
3897                            .push(two.clone().into())
3898                            .into())
3899                        .into())
3900                    .into())
3901                .push(CompressedData::new(CompressionAlgorithm::Uncompressed)
3902                    .push(CompressedData::new(CompressionAlgorithm::Uncompressed)
3903                        .push(three.clone().into())
3904                        .into())
3905                    .push(four.clone().into())
3906                    .into())
3907                .into());
3908        messages.push(top_level);
3909
3910        // 1: CompressedData(CompressedData { algo: 0 })
3911        //  1: Literal(Literal { body: "one (3 bytes)" })
3912        //  2: Literal(Literal { body: "two (3 bytes)" })
3913        // 2: Literal(Literal { body: "three (5 bytes)" })
3914        // 3: Literal(Literal { body: "four (4 bytes)" })
3915        // 4: CompressedData(CompressedData { algo: 0 })
3916        //  1: Literal(Literal { body: "five (4 bytes)" })
3917        //  2: Literal(Literal { body: "six (3 bytes)" })
3918        let mut top_level = Vec::new();
3919        top_level.push(
3920            CompressedData::new(CompressionAlgorithm::Uncompressed)
3921                .push(one.clone().into())
3922                .push(two.clone().into())
3923                .into());
3924        top_level.push(
3925            three.clone().into());
3926        top_level.push(
3927            four.clone().into());
3928        top_level.push(
3929            CompressedData::new(CompressionAlgorithm::Uncompressed)
3930                .push(five.into())
3931                .push(six.into())
3932                .into());
3933        messages.push(top_level);
3934
3935        // 1: UserID(UserID { value: "Foo" })
3936        let mut top_level = Vec::new();
3937        let uid = UserID::from("Foo");
3938        top_level.push(uid.into());
3939        messages.push(top_level);
3940
3941        for m in messages.into_iter() {
3942            // 1. The message.
3943            let pile = PacketPile::from(m);
3944
3945            pile.pretty_print();
3946
3947            // 2. Serialize the message into a buffer.
3948            let mut buffer = Vec::new();
3949            (&pile as &dyn Marshal).serialize(&mut buffer).unwrap();
3950
3951            // 3. Reparse it.
3952            let pile2 = PacketParserBuilder::from_bytes(&buffer[..]).unwrap()
3953                //.trace()
3954                .buffer_unread_content()
3955                .into_packet_pile().unwrap();
3956
3957            // 4. Compare the messages.
3958            if pile != pile2 {
3959                eprintln!("ORIG...");
3960                pile.pretty_print();
3961                eprintln!("REPARSED...");
3962                pile2.pretty_print();
3963                panic!("Reparsed packet does not match original packet!");
3964            }
3965        }
3966    }
3967
3968    #[test]
3969    fn body_length_edge_cases() {
3970        {
3971            let mut buf = vec![];
3972            BodyLength::Full(0).serialize(&mut buf).unwrap();
3973            assert_eq!(&buf[..], &b"\x00"[..]);
3974        }
3975
3976        {
3977            let mut buf = vec![];
3978            BodyLength::Full(1).serialize(&mut buf).unwrap();
3979            assert_eq!(&buf[..], &b"\x01"[..]);
3980        }
3981        {
3982            let mut buf = vec![];
3983            BodyLength::Full(191).serialize(&mut buf).unwrap();
3984            assert_eq!(&buf[..], &b"\xbf"[..]);
3985        }
3986        {
3987            let mut buf = vec![];
3988            BodyLength::Full(192).serialize(&mut buf).unwrap();
3989            assert_eq!(&buf[..], &b"\xc0\x00"[..]);
3990        }
3991        {
3992            let mut buf = vec![];
3993            BodyLength::Full(193).serialize(&mut buf).unwrap();
3994            assert_eq!(&buf[..], &b"\xc0\x01"[..]);
3995        }
3996        {
3997            let mut buf = vec![];
3998            BodyLength::Full(8383).serialize(&mut buf).unwrap();
3999            assert_eq!(&buf[..], &b"\xdf\xff"[..]);
4000        }
4001        {
4002            let mut buf = vec![];
4003            BodyLength::Full(8384).serialize(&mut buf).unwrap();
4004            assert_eq!(&buf[..], &b"\xff\x00\x00\x20\xc0"[..]);
4005        }
4006        {
4007            let mut buf = vec![];
4008            BodyLength::Full(0xffffffff).serialize(&mut buf).unwrap();
4009            assert_eq!(&buf[..], &b"\xff\xff\xff\xff\xff"[..]);
4010        }
4011    }
4012
4013    #[test]
4014    fn export_signature() {
4015        use crate::cert::prelude::*;
4016
4017        let (cert, _) = CertBuilder::new().generate().unwrap();
4018        let mut keypair = cert.primary_key().key().clone().parts_into_secret()
4019            .unwrap().into_keypair().unwrap();
4020        let uid = UserID::from("foo");
4021
4022        // Make a signature w/o an exportable certification subpacket.
4023        let sig = uid.bind(
4024            &mut keypair, &cert,
4025            signature::SignatureBuilder::new(SignatureType::GenericCertification))
4026            .unwrap();
4027
4028        // The signature is exportable.  Try to export it in
4029        // various ways.
4030        sig.export(&mut Vec::new()).unwrap();
4031        sig.export_into(&mut vec![0; sig.serialized_len()]).unwrap();
4032        sig.export_to_vec().unwrap();
4033        (&PacketRef::Signature(&sig) as &dyn Marshal)
4034            .export(&mut Vec::new()).unwrap();
4035        (&PacketRef::Signature(&sig) as &dyn MarshalInto).export_into(
4036            &mut vec![0; (&PacketRef::Signature(&sig) as &dyn MarshalInto)
4037                             .serialized_len()]).unwrap();
4038        (&PacketRef::Signature(&sig) as &dyn MarshalInto)
4039            .export_to_vec().unwrap();
4040        let p = Packet::Signature(sig);
4041        (&p as &dyn Marshal).export(&mut Vec::new()).unwrap();
4042        (&p as &dyn MarshalInto)
4043            .export_into(
4044                &mut vec![0; (&p as &dyn MarshalInto).serialized_len()])
4045            .unwrap();
4046        (&p as &dyn MarshalInto).export_to_vec().unwrap();
4047        let pp = PacketPile::from(vec![p]);
4048        (&pp as &dyn Marshal).export(&mut Vec::new()).unwrap();
4049        (&pp as &dyn MarshalInto)
4050            .export_into(
4051                &mut vec![0; (&pp as &dyn MarshalInto).serialized_len()])
4052            .unwrap();
4053        (&pp as &dyn MarshalInto).export_to_vec().unwrap();
4054
4055        // Make a signature that is explicitly marked as exportable.
4056        let sig = uid.bind(
4057            &mut keypair, &cert,
4058            signature::SignatureBuilder::new(SignatureType::GenericCertification)
4059                .set_exportable_certification(true).unwrap()).unwrap();
4060
4061        // The signature is exportable.  Try to export it in
4062        // various ways.
4063        sig.export(&mut Vec::new()).unwrap();
4064        sig.export_into(&mut vec![0; sig.serialized_len()]).unwrap();
4065        sig.export_to_vec().unwrap();
4066        (&PacketRef::Signature(&sig) as &dyn Marshal)
4067            .export(&mut Vec::new()).unwrap();
4068        (&PacketRef::Signature(&sig) as &dyn MarshalInto)
4069            .export_into(
4070                &mut vec![0; (&PacketRef::Signature(&sig)
4071                              as &dyn MarshalInto).serialized_len()])
4072            .unwrap();
4073        (&PacketRef::Signature(&sig) as &dyn MarshalInto)
4074            .export_to_vec().unwrap();
4075        let p = Packet::Signature(sig);
4076        (&p as &dyn Marshal).export(&mut Vec::new()).unwrap();
4077        (&p as &dyn MarshalInto)
4078            .export_into(
4079                &mut vec![0; (&p as &dyn MarshalInto).serialized_len()])
4080            .unwrap();
4081        (&p as &dyn MarshalInto).export_to_vec().unwrap();
4082        let pp = PacketPile::from(vec![p]);
4083        (&pp as &dyn Marshal).export(&mut Vec::new()).unwrap();
4084        (&pp as &dyn MarshalInto)
4085            .export_into(
4086                &mut vec![0; (&pp as &dyn MarshalInto).serialized_len()])
4087            .unwrap();
4088        (&pp as &dyn MarshalInto).export_to_vec().unwrap();
4089
4090        // Make a non-exportable signature.
4091        let sig = uid.bind(
4092            &mut keypair, &cert,
4093            signature::SignatureBuilder::new(SignatureType::GenericCertification)
4094                .set_exportable_certification(false).unwrap()).unwrap();
4095
4096        // The signature is not exportable.  Try to export it in
4097        // various ways.
4098        sig.export(&mut Vec::new()).unwrap_err();
4099        sig.export_into(&mut vec![0; sig.serialized_len()]).unwrap_err();
4100        sig.export_to_vec().unwrap_err();
4101        (&PacketRef::Signature(&sig) as &dyn Marshal)
4102            .export(&mut Vec::new()).unwrap_err();
4103        (&PacketRef::Signature(&sig) as &dyn MarshalInto)
4104            .export_into(
4105                &mut vec![0; (&PacketRef::Signature(&sig)
4106                              as &dyn MarshalInto).serialized_len()])
4107            .unwrap_err();
4108        (&PacketRef::Signature(&sig) as &dyn MarshalInto)
4109            .export_to_vec().unwrap_err();
4110        let p = Packet::Signature(sig);
4111        (&p as &dyn Marshal).export(&mut Vec::new()).unwrap_err();
4112        (&p as &dyn MarshalInto)
4113            .export_into(&mut vec![0; (&p as &dyn MarshalInto).serialized_len()])
4114            .unwrap_err();
4115        (&p as &dyn MarshalInto).export_to_vec().unwrap_err();
4116        let pp = PacketPile::from(vec![p]);
4117        (&pp as &dyn Marshal).export(&mut Vec::new()).unwrap_err();
4118        (&pp as &dyn MarshalInto)
4119            .export_into(
4120                &mut vec![0; (&pp as &dyn MarshalInto).serialized_len()])
4121            .unwrap_err();
4122        (&pp as &dyn MarshalInto).export_to_vec().unwrap_err();
4123    }
4124
4125    quickcheck! {
4126        /// Checks that SerializeInto::serialized_len computes the
4127        /// exact size (except for CompressedData packets where we may
4128        /// overestimate the size).
4129        fn packet_serialized_len(p: Packet) -> bool {
4130            let p_as_vec = SerializeInto::to_vec(&p).unwrap();
4131            if let Packet::CompressedData(_) = p {
4132                // serialized length may be an over-estimate
4133                assert!(SerializeInto::serialized_len(&p) >= p_as_vec.len());
4134            } else {
4135                // serialized length should be exact
4136                assert_eq!(SerializeInto::serialized_len(&p), p_as_vec.len());
4137            }
4138            true
4139        }
4140    }
4141}