Skip to main content

justssh_wire/
codec.rs

1//! RFC 4251 §5 data types: byte, boolean, uint32, string, mpint and name-list.
2
3use core::fmt;
4
5/// Why a payload could not be decoded.
6#[non_exhaustive]
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum DecodeError {
9    /// The payload ended before a field was complete.
10    Truncated,
11    /// Bytes were left over after the last field of the message.
12    TrailingBytes,
13    /// A name-list or text field was not valid UTF-8.
14    InvalidUtf8,
15    /// A boolean or fixed-value field held a value the format does not allow.
16    InvalidValue,
17    /// The payload was empty, so it had no message number.
18    Empty,
19}
20
21impl fmt::Display for DecodeError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        let s = match self {
24            DecodeError::Truncated => "payload ended before a field was complete",
25            DecodeError::TrailingBytes => "bytes left over after the last field",
26            DecodeError::InvalidUtf8 => "text field is not valid UTF-8",
27            DecodeError::InvalidValue => "field holds a value the format does not allow",
28            DecodeError::Empty => "empty payload",
29        };
30        f.write_str(s)
31    }
32}
33
34impl std::error::Error for DecodeError {}
35
36/// Reads RFC 4251 data types from a byte slice, front to back.
37#[derive(Debug, Clone)]
38pub struct Reader<'a> {
39    buf: &'a [u8],
40}
41
42impl<'a> Reader<'a> {
43    /// A reader over `buf`.
44    pub fn new(buf: &'a [u8]) -> Self {
45        Reader { buf }
46    }
47
48    /// The bytes not yet read.
49    pub fn remaining(&self) -> &'a [u8] {
50        self.buf
51    }
52
53    /// Takes the next `n` raw bytes.
54    pub fn bytes(&mut self, n: usize) -> Result<&'a [u8], DecodeError> {
55        if self.buf.len() < n {
56            return Err(DecodeError::Truncated);
57        }
58        let (head, tail) = self.buf.split_at(n);
59        self.buf = tail;
60        Ok(head)
61    }
62
63    /// `byte`.
64    pub fn u8(&mut self) -> Result<u8, DecodeError> {
65        Ok(self.bytes(1)?[0])
66    }
67
68    /// `boolean`: zero is false, any other value true (RFC 4251 §5).
69    pub fn bool(&mut self) -> Result<bool, DecodeError> {
70        Ok(self.u8()? != 0)
71    }
72
73    /// `uint32`, big-endian.
74    pub fn u32(&mut self) -> Result<u32, DecodeError> {
75        let b = self.bytes(4)?;
76        Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
77    }
78
79    /// `string`: a uint32 length and that many bytes.
80    pub fn string(&mut self) -> Result<&'a [u8], DecodeError> {
81        let len = self.u32()? as usize;
82        self.bytes(len)
83    }
84
85    /// A `string` that must be valid UTF-8.
86    pub fn utf8(&mut self) -> Result<&'a str, DecodeError> {
87        core::str::from_utf8(self.string()?).map_err(|_| DecodeError::InvalidUtf8)
88    }
89
90    /// `name-list`: a comma-separated `string` of names. The empty string is the empty list.
91    pub fn name_list(&mut self) -> Result<Vec<String>, DecodeError> {
92        let s = self.utf8()?;
93        if s.is_empty() {
94            return Ok(Vec::new());
95        }
96        Ok(s.split(',').map(str::to_owned).collect())
97    }
98
99    /// Succeeds only if every byte has been read.
100    pub fn finish(&self) -> Result<(), DecodeError> {
101        if self.buf.is_empty() {
102            Ok(())
103        } else {
104            Err(DecodeError::TrailingBytes)
105        }
106    }
107}
108
109/// Appends RFC 4251 data types to a byte vector.
110#[derive(Debug, Clone, Default)]
111pub struct Writer {
112    buf: Vec<u8>,
113}
114
115impl Writer {
116    /// An empty writer.
117    pub fn new() -> Self {
118        Writer::default()
119    }
120
121    /// A writer appending to `buf`.
122    pub(crate) fn appending(buf: Vec<u8>) -> Self {
123        Writer { buf }
124    }
125
126    /// The bytes written so far.
127    pub fn into_bytes(self) -> Vec<u8> {
128        self.buf
129    }
130
131    /// Raw bytes with no length prefix.
132    pub fn bytes(&mut self, b: &[u8]) -> &mut Self {
133        self.buf.extend_from_slice(b);
134        self
135    }
136
137    /// `byte`.
138    pub fn u8(&mut self, v: u8) -> &mut Self {
139        self.buf.push(v);
140        self
141    }
142
143    /// `boolean`, written as 0 or 1.
144    pub fn bool(&mut self, v: bool) -> &mut Self {
145        self.u8(u8::from(v))
146    }
147
148    /// `uint32`, big-endian.
149    pub fn u32(&mut self, v: u32) -> &mut Self {
150        self.bytes(&v.to_be_bytes())
151    }
152
153    /// `string`.
154    ///
155    /// # Panics
156    /// If `s` is longer than `u32::MAX` bytes.
157    pub fn string(&mut self, s: &[u8]) -> &mut Self {
158        let len = u32::try_from(s.len()).expect("SSH string longer than u32::MAX");
159        self.u32(len).bytes(s)
160    }
161
162    /// `name-list`.
163    pub fn name_list<S: AsRef<str>>(&mut self, names: &[S]) -> &mut Self {
164        let joined = names
165            .iter()
166            .map(AsRef::as_ref)
167            .collect::<Vec<_>>()
168            .join(",");
169        self.string(joined.as_bytes())
170    }
171
172    /// `mpint` holding the unsigned big-endian integer `magnitude`: leading zero bytes are
173    /// dropped, and a zero byte is prepended when the top bit is set.
174    pub fn mpint_unsigned(&mut self, magnitude: &[u8]) -> &mut Self {
175        let start = magnitude
176            .iter()
177            .position(|&b| b != 0)
178            .unwrap_or(magnitude.len());
179        let m = &magnitude[start..];
180        if m.first().is_some_and(|&b| b & 0x80 != 0) {
181            let len = u32::try_from(m.len() + 1).expect("mpint longer than u32::MAX");
182            self.u32(len).u8(0).bytes(m)
183        } else {
184            self.string(m)
185        }
186    }
187}