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