Skip to main content

rustls/msgs/
base.rs

1use alloc::vec::Vec;
2use core::fmt;
3use core::marker::PhantomData;
4
5use pki_types::CertificateDer;
6use zeroize::Zeroize;
7
8use crate::error::InvalidMessage;
9use crate::msgs::codec;
10use crate::msgs::codec::{Codec, Reader};
11
12/// An externally length'd payload
13#[derive(Clone, Eq, PartialEq)]
14pub enum Payload<'a> {
15    Borrowed(&'a [u8]),
16    Owned(Vec<u8>),
17}
18
19impl<'a> Codec<'a> for Payload<'a> {
20    fn encode(&self, bytes: &mut Vec<u8>) {
21        bytes.extend_from_slice(self.bytes());
22    }
23
24    fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> {
25        Ok(Self::read(r))
26    }
27}
28
29impl<'a> Payload<'a> {
30    pub fn bytes(&self) -> &[u8] {
31        match self {
32            Self::Borrowed(bytes) => bytes,
33            Self::Owned(bytes) => bytes,
34        }
35    }
36
37    pub fn into_owned(self) -> Payload<'static> {
38        Payload::Owned(self.into_vec())
39    }
40
41    pub fn into_vec(self) -> Vec<u8> {
42        match self {
43            Self::Borrowed(bytes) => bytes.to_vec(),
44            Self::Owned(bytes) => bytes,
45        }
46    }
47
48    pub fn read(r: &mut Reader<'a>) -> Self {
49        Self::Borrowed(r.rest())
50    }
51}
52
53impl Payload<'static> {
54    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
55        Self::Owned(bytes.into())
56    }
57
58    pub fn empty() -> Self {
59        Self::Borrowed(&[])
60    }
61}
62
63impl<'a> Codec<'a> for CertificateDer<'a> {
64    fn encode(&self, bytes: &mut Vec<u8>) {
65        codec::u24(self.as_ref().len() as u32).encode(bytes);
66        bytes.extend(self.as_ref());
67    }
68
69    fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> {
70        let len = codec::u24::read(r)?.0 as usize;
71        let mut sub = r.sub(len)?;
72        let body = sub.rest();
73        Ok(Self::from(body))
74    }
75}
76
77impl fmt::Debug for Payload<'_> {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        hex(f, self.bytes())
80    }
81}
82
83/// An arbitrary, unknown-content, u24-length-prefixed payload
84#[derive(Clone, Eq, PartialEq)]
85pub(crate) struct PayloadU24<'a, C: Cardinality = MaybeEmpty>(
86    pub(crate) Payload<'a>,
87    PhantomData<C>,
88);
89
90impl<C: Cardinality> PayloadU24<'_, C> {
91    pub(crate) fn into_owned(self) -> PayloadU24<'static, C> {
92        PayloadU24(self.0.into_owned(), PhantomData)
93    }
94}
95
96impl<'a, C: Cardinality> Codec<'a> for PayloadU24<'a, C> {
97    fn encode(&self, bytes: &mut Vec<u8>) {
98        let inner = self.0.bytes();
99        debug_assert!(inner.len() >= C::MIN);
100        codec::u24(inner.len() as u32).encode(bytes);
101        bytes.extend_from_slice(inner);
102    }
103
104    fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> {
105        let len = codec::u24::read(r)?.0 as usize;
106        if len < C::MIN {
107            return Err(InvalidMessage::IllegalEmptyList("PayloadU24"));
108        }
109        let mut sub = r.sub(len)?;
110        Ok(Self(Payload::read(&mut sub), PhantomData))
111    }
112}
113
114impl<'a, C: Cardinality> From<Payload<'a>> for PayloadU24<'a, C> {
115    fn from(value: Payload<'a>) -> Self {
116        debug_assert!(value.bytes().len() >= C::MIN);
117        Self(value, PhantomData)
118    }
119}
120
121impl<C: Cardinality> AsRef<[u8]> for PayloadU24<'_, C> {
122    fn as_ref(&self) -> &[u8] {
123        self.0.bytes()
124    }
125}
126
127impl<C: Cardinality> fmt::Debug for PayloadU24<'_, C> {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        self.0.fmt(f)
130    }
131}
132
133/// An arbitrary, unknown-content, u16-length-prefixed payload
134///
135/// The `C` type parameter controls whether decoded values may
136/// be empty.
137#[derive(Clone, Eq, PartialEq)]
138pub struct PayloadU16<C: Cardinality = MaybeEmpty>(pub(crate) Vec<u8>, PhantomData<C>);
139
140impl<C: Cardinality> PayloadU16<C> {
141    pub fn new(bytes: Vec<u8>) -> Self {
142        debug_assert!(bytes.len() >= C::MIN);
143        Self(bytes, PhantomData)
144    }
145}
146
147impl PayloadU16<MaybeEmpty> {
148    pub(crate) fn empty() -> Self {
149        Self::new(Vec::new())
150    }
151}
152
153impl<C: Cardinality> Codec<'_> for PayloadU16<C> {
154    fn encode(&self, bytes: &mut Vec<u8>) {
155        debug_assert!(self.0.len() >= C::MIN);
156        (self.0.len() as u16).encode(bytes);
157        bytes.extend_from_slice(&self.0);
158    }
159
160    fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> {
161        let len = u16::read(r)? as usize;
162        if len < C::MIN {
163            return Err(InvalidMessage::IllegalEmptyValue);
164        }
165        let mut sub = r.sub(len)?;
166        let body = sub.rest().to_vec();
167        Ok(Self(body, PhantomData))
168    }
169}
170
171impl<C: Cardinality> fmt::Debug for PayloadU16<C> {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        hex(f, &self.0)
174    }
175}
176
177/// An arbitrary, unknown-content, u8-length-prefixed payload
178///
179/// `C` controls the minimum length accepted when decoding.
180#[derive(Clone, Eq, PartialEq)]
181pub(crate) struct PayloadU8<C: Cardinality = MaybeEmpty>(pub(crate) Vec<u8>, PhantomData<C>);
182
183impl<C: Cardinality> PayloadU8<C> {
184    pub(crate) fn encode_slice(slice: &[u8], bytes: &mut Vec<u8>) {
185        (slice.len() as u8).encode(bytes);
186        bytes.extend_from_slice(slice);
187    }
188
189    pub(crate) fn new(bytes: Vec<u8>) -> Self {
190        debug_assert!(bytes.len() >= C::MIN);
191        Self(bytes, PhantomData)
192    }
193}
194
195impl PayloadU8<MaybeEmpty> {
196    pub(crate) fn empty() -> Self {
197        Self(Vec::new(), PhantomData)
198    }
199}
200
201impl<C: Cardinality> Codec<'_> for PayloadU8<C> {
202    fn encode(&self, bytes: &mut Vec<u8>) {
203        debug_assert!(self.0.len() >= C::MIN);
204        (self.0.len() as u8).encode(bytes);
205        bytes.extend_from_slice(&self.0);
206    }
207
208    fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> {
209        let len = u8::read(r)? as usize;
210        if len < C::MIN {
211            return Err(InvalidMessage::IllegalEmptyValue);
212        }
213        let mut sub = r.sub(len)?;
214        let body = sub.rest().to_vec();
215        Ok(Self(body, PhantomData))
216    }
217}
218
219impl<C: Cardinality> Zeroize for PayloadU8<C> {
220    fn zeroize(&mut self) {
221        self.0.zeroize();
222    }
223}
224
225impl<C: Cardinality> fmt::Debug for PayloadU8<C> {
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        hex(f, &self.0)
228    }
229}
230
231pub trait Cardinality: Clone + Eq + PartialEq {
232    const MIN: usize;
233}
234
235#[derive(Clone, Eq, PartialEq)]
236pub struct MaybeEmpty;
237
238impl Cardinality for MaybeEmpty {
239    const MIN: usize = 0;
240}
241
242#[derive(Clone, Eq, PartialEq)]
243pub struct NonEmpty;
244
245impl Cardinality for NonEmpty {
246    const MIN: usize = 1;
247}
248
249// Format an iterator of u8 into a hex string
250pub(super) fn hex<'a>(
251    f: &mut fmt::Formatter<'_>,
252    payload: impl IntoIterator<Item = &'a u8>,
253) -> fmt::Result {
254    for b in payload {
255        write!(f, "{b:02x}")?;
256    }
257    Ok(())
258}