Skip to main content

ssh_encoding/
encode.rs

1//! Encoder-side implementation of the SSH protocol's data type representations
2//! as described in [RFC4251 § 5].
3//!
4//! [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
5
6use crate::{Error, checked::CheckedSum, writer::Writer};
7use core::str;
8
9#[cfg(feature = "alloc")]
10use alloc::{string::String, vec::Vec};
11
12#[cfg(feature = "bytes")]
13use bytes::{Bytes, BytesMut};
14
15/// Encoding trait.
16///
17/// This trait describes how to encode a given type.
18pub trait Encode {
19    /// Get the length of this type encoded in bytes, prior to Base64 encoding.
20    ///
21    /// # Errors
22    /// Returns errors specific to the concrete implementation of this trait.
23    fn encoded_len(&self) -> Result<usize, Error>;
24
25    /// Encode this value using the provided [`Writer`].
26    ///
27    /// # Errors
28    /// Returns errors specific to the concrete implementation of this trait.
29    fn encode(&self, writer: &mut impl Writer) -> Result<(), Error>;
30
31    /// Return the length of this type after encoding when prepended with a `uint32` length prefix.
32    ///
33    /// # Errors
34    /// Returns errors specific to the concrete implementation of this trait.
35    fn encoded_len_prefixed(&self) -> Result<usize, Error> {
36        [4, self.encoded_len()?].checked_sum()
37    }
38
39    /// Encode this value, first prepending a `uint32` length prefix set to [`Encode::encoded_len`].
40    ///
41    /// # Errors
42    /// Returns errors specific to the concrete implementation of this trait.
43    fn encode_prefixed(&self, writer: &mut impl Writer) -> Result<(), Error> {
44        self.encoded_len()?.encode(writer)?;
45        self.encode(writer)
46    }
47
48    /// Encode this value, returning a `Vec<u8>` containing the encoded message.
49    ///
50    /// # Errors
51    /// Returns [`Error::Alloc`] if reserving capacity fails.
52    /// Returns errors specific to the concrete implementation of this trait.
53    #[cfg(feature = "alloc")]
54    fn encode_vec(&self) -> Result<Vec<u8>, Error> {
55        let mut ret = crate::vec_with_reserve(self.encoded_len()?)?;
56        self.encode(&mut ret)?;
57        Ok(ret)
58    }
59
60    /// Encode this value, returning a [`BytesMut`] containing the encoded message.
61    ///
62    /// # Errors
63    /// Returns errors specific to the concrete implementation of this trait.
64    #[cfg(feature = "bytes")]
65    fn encode_bytes(&self) -> Result<BytesMut, Error> {
66        let mut ret = BytesMut::with_capacity(self.encoded_len()?);
67        self.encode(&mut ret)?;
68        Ok(ret)
69    }
70}
71
72/// Encode a single `byte` to the writer.
73impl Encode for u8 {
74    fn encoded_len(&self) -> Result<usize, Error> {
75        Ok(1)
76    }
77
78    fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
79        writer.write(&[*self])
80    }
81}
82
83/// Encode a `boolean` as described in [RFC4251 § 5]:
84///
85/// > A boolean value is stored as a single byte.  The value 0
86/// > represents FALSE, and the value 1 represents TRUE.  All non-zero
87/// > values MUST be interpreted as TRUE; however, applications MUST NOT
88/// > store values other than 0 and 1.
89///
90/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
91impl Encode for bool {
92    fn encoded_len(&self) -> Result<usize, Error> {
93        Ok(1)
94    }
95
96    fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
97        if *self {
98            1u8.encode(writer)
99        } else {
100            0u8.encode(writer)
101        }
102    }
103}
104
105/// Encode a `uint32` as described in [RFC4251 § 5]:
106///
107/// > Represents a 32-bit unsigned integer.  Stored as four bytes in the
108/// > order of decreasing significance (network byte order).
109/// > For example: the value 699921578 (0x29b7f4aa) is stored as 29 b7 f4 aa.
110///
111/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
112impl Encode for u32 {
113    fn encoded_len(&self) -> Result<usize, Error> {
114        Ok(4)
115    }
116
117    fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
118        writer.write(&self.to_be_bytes())
119    }
120}
121
122/// Encode a `uint64` as described in [RFC4251 § 5]:
123///
124/// > Represents a 64-bit unsigned integer.  Stored as eight bytes in
125/// > the order of decreasing significance (network byte order).
126///
127/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
128impl Encode for u64 {
129    fn encoded_len(&self) -> Result<usize, Error> {
130        Ok(8)
131    }
132
133    fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
134        writer.write(&self.to_be_bytes())
135    }
136}
137
138/// Encode a `usize` as a `uint32` as described in [RFC4251 § 5].
139///
140/// Uses [`Encode`] impl on `u32` after converting from a `usize`, handling
141/// potential overflow if `usize` is bigger than `u32`.
142///
143/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
144impl Encode for usize {
145    fn encoded_len(&self) -> Result<usize, Error> {
146        Ok(4)
147    }
148
149    fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
150        u32::try_from(*self)?.encode(writer)
151    }
152}
153
154/// Encodes `[u8]` into `string` as described in [RFC4251 § 5]:
155///
156/// > Arbitrary length binary string.  Strings are allowed to contain
157/// > arbitrary binary data, including null characters and 8-bit
158/// > characters.  They are stored as a uint32 containing its length
159/// > (number of bytes that follow) and zero (= empty string) or more
160/// > bytes that are the value of the string.  Terminating null
161/// > characters are not used.
162///
163/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
164impl Encode for [u8] {
165    fn encoded_len(&self) -> Result<usize, Error> {
166        [4, self.len()].checked_sum()
167    }
168
169    fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
170        self.len().encode(writer)?;
171        writer.write(self)
172    }
173}
174
175/// Encodes byte array using `byte[n]` encoding as described in [RFC4251 § 5]:
176///
177/// > A byte represents an arbitrary 8-bit value (octet).  Fixed length
178/// > data is sometimes represented as an array of bytes, written
179/// > `byte[n]`, where n is the number of bytes in the array.
180///
181/// Note that unlike `string`, this type is encoded without a length prefix,
182/// but instead implicitly obtains its length as `N`.
183///
184/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
185impl<const N: usize> Encode for [u8; N] {
186    fn encoded_len(&self) -> Result<usize, Error> {
187        Ok(N)
188    }
189
190    fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
191        writer.write(self)
192    }
193}
194
195/// A macro to implement `Encode` for a type by delegating to some transformed version of `self`.
196macro_rules! impl_by_delegation {
197    (
198        $(
199            $(#[$attr:meta])*
200            impl $( ($($generics:tt)+) )? Encode for $type:ty where $self:ident -> $delegate:expr;
201        )+
202    ) => {
203        $(
204            $(#[$attr])*
205            impl $(< $($generics)* >)? Encode for $type  {
206                fn encoded_len(&$self) -> Result<usize, Error> {
207                    $delegate.encoded_len()
208                }
209
210                fn encode(&$self, writer: &mut impl Writer) -> Result<(), Error> {
211                    $delegate.encode(writer)
212                }
213            }
214        )+
215    };
216}
217
218impl_by_delegation!(
219    /// Encode a `string` as described in [RFC4251 § 5]:
220    ///
221    /// > Arbitrary length binary string.  Strings are allowed to contain
222    /// > arbitrary binary data, including null characters and 8-bit
223    /// > characters.  They are stored as a uint32 containing its length
224    /// > (number of bytes that follow) and zero (= empty string) or more
225    /// > bytes that are the value of the string.  Terminating null
226    /// > characters are not used.
227    /// >
228    /// > Strings are also used to store text.  In that case, US-ASCII is
229    /// > used for internal names, and ISO-10646 UTF-8 for text that might
230    /// > be displayed to the user.  The terminating null character SHOULD
231    /// > NOT normally be stored in the string.  For example: the US-ASCII
232    /// > string "testing" is represented as 00 00 00 07 t e s t i n g.  The
233    /// > UTF-8 mapping does not alter the encoding of US-ASCII characters.
234    ///
235    /// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
236    impl Encode for str where self -> self.as_bytes();
237
238    #[cfg(feature = "alloc")]
239    impl Encode for Vec<u8> where self -> self.as_slice();
240    #[cfg(feature = "alloc")]
241    impl Encode for String where self -> self.as_bytes();
242    #[cfg(feature = "bytes")]
243    impl Encode for Bytes where self -> self.as_ref();
244
245    // While deref coercion ensures that `&E` can use the `Encode` trait methods, it will not be
246    // allowed in trait bounds, as `&E` does not implement `Encode` itself just because `E: Encode`.
247    // A blanket impl for `&E` would be the most generic, but that collides with the `Label` trait's
248    // blanket impl. Instead, we can do it explicitly for the immediately relevant base types.
249    impl Encode for &str where self -> **self;
250    impl Encode for &[u8] where self -> **self;
251    #[cfg(feature = "alloc")]
252    impl Encode for &Vec<u8> where self -> **self;
253    #[cfg(feature = "alloc")]
254    impl Encode for &String where self -> **self;
255    #[cfg(feature = "bytes")]
256    impl Encode for &Bytes where self -> **self;
257
258);
259
260/// A trait indicating that the type is encoded like an RFC4251 string.
261///
262/// Implementing this trait allows encoding sequences of the type as a  string of strings.
263///
264/// A `string` is described in [RFC4251 § 5]:
265///
266/// > Arbitrary length binary string.  Strings are allowed to contain
267/// > arbitrary binary data, including null characters and 8-bit
268/// > characters.  They are stored as a uint32 containing its length
269/// > (number of bytes that follow) and zero (= empty string) or more
270/// > bytes that are the value of the string.  Terminating null
271/// > characters are not used.
272/// >
273/// > Strings are also used to store text.  In that case, US-ASCII is
274/// > used for internal names, and ISO-10646 UTF-8 for text that might
275/// > be displayed to the user.  The terminating null character SHOULD
276/// > NOT normally be stored in the string.  For example: the US-ASCII
277/// > string "testing" is represented as 00 00 00 07 t e s t i n g.  The
278/// > UTF-8 mapping does not alter the encoding of US-ASCII characters.
279///
280/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
281pub trait Rfc4251String: Encode {}
282
283impl Rfc4251String for str {}
284impl Rfc4251String for [u8] {}
285#[cfg(feature = "alloc")]
286impl Rfc4251String for String {}
287#[cfg(feature = "alloc")]
288impl Rfc4251String for Vec<u8> {}
289#[cfg(feature = "bytes")]
290impl Rfc4251String for Bytes {}
291
292/// Any reference to [`Rfc4251String`] is itself [`Rfc4251String`] if `&T: Encode`.
293impl<'a, T> Rfc4251String for &'a T
294where
295    T: Rfc4251String + ?Sized,
296    &'a T: Encode,
297{
298}
299
300/// Encode a slice of string-like types as a string wrapping all the entries.
301impl<T: Rfc4251String> Encode for [T] {
302    fn encoded_len(&self) -> Result<usize, Error> {
303        self.iter().try_fold(4usize, |acc, string| {
304            acc.checked_add(string.encoded_len()?).ok_or(Error::Length)
305        })
306    }
307
308    fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
309        self.encoded_len()?
310            .checked_sub(4)
311            .ok_or(Error::Length)?
312            .encode(writer)?;
313        self.iter().try_fold((), |(), entry| entry.encode(writer))
314    }
315}
316
317impl_by_delegation!(
318    #[cfg(feature = "alloc")]
319    impl (T: Rfc4251String) Encode for Vec<T> where self -> self.as_slice();
320);