ssh_encoding/decoder.rs
1//! Shared decoder for SSH protocol data types.
2
3use crate::{Decode, Error, MAX_MSG_SIZE, Reader, Result};
4use core::{fmt, str};
5
6/// Maximum number of simultaneously active nested decoding scopes.
7const MAX_NESTING_DEPTH: u8 = 64;
8
9/// Decoder for SSH protocol data types over a byte [`Reader`].
10///
11/// Construct a decoder with [`Decoder::new`] or [`Reader::into_decoder`].
12///
13/// All nested decoding uses the same decoder type, with enclosing bounds stored on the call
14/// stack. A decoder permits up to 64 active nested scopes. Neither nesting nor decoding from
15/// Base64 or PEM requires a heap allocation.
16///
17/// A failed read or nested decoding operation invalidates the decoder. Subsequent reads and
18/// completion checks return [`Error::Failed`]. The underlying reader is not rewound on errors.
19///
20/// # Example
21/// ```
22/// use ssh_encoding::{Decode, Reader};
23///
24/// let mut decoder = [0, 0, 0, 42].as_slice().into_decoder()?;
25/// let value = u32::decode(&mut decoder)?;
26/// assert_eq!(decoder.finish(value)?, 42);
27/// # Ok::<(), ssh_encoding::Error>(())
28/// ```
29pub struct Decoder<R> {
30 /// Underlying byte reader.
31 reader: R,
32
33 /// Position in the decoded input.
34 position: usize,
35
36 /// End of the currently active decoding scope.
37 end: usize,
38
39 /// Number of active nested scopes.
40 depth: u8,
41
42 /// Whether a read or nested decoding operation failed.
43 failed: bool,
44}
45
46impl<R: Reader> Decoder<R> {
47 /// Create a decoder which owns the given reader.
48 ///
49 /// # Errors
50 /// Returns [`Error::Length`] if the remaining decoded input exceeds `MAX_MSG_SIZE`.
51 pub fn new(reader: R) -> Result<Self> {
52 let end = reader.remaining_len();
53 if end > MAX_MSG_SIZE {
54 return Err(Error::Length);
55 }
56
57 Ok(Self {
58 reader,
59 position: 0,
60 end,
61 depth: 0,
62 failed: false,
63 })
64 }
65
66 /// Read enough bytes to exactly fill `out`, without crossing the active scope's boundary.
67 ///
68 /// # Errors
69 /// - Returns [`Error::Failed`] if the decoder has already failed.
70 /// - Returns [`Error::Length`] if `out` exceeds the remaining length.
71 /// - Propagates errors returned from [`Reader::read`].
72 pub fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
73 if self.failed {
74 return Err(Error::Failed);
75 }
76
77 if out.len() > self.remaining_len() {
78 self.failed = true;
79 return Err(Error::Length);
80 }
81
82 // Avoid calling streaming decoders for empty reads.
83 if out.is_empty() {
84 return Ok(out);
85 }
86
87 let len = out.len();
88 match self.reader.read(out) {
89 Ok(bytes) => {
90 self.position += len;
91 Ok(bytes)
92 }
93 Err(err) => {
94 self.failed = true;
95 Err(err)
96 }
97 }
98 }
99
100 /// Get the number of decoded bytes remaining in the active scope.
101 #[must_use]
102 pub fn remaining_len(&self) -> usize {
103 self.end - self.position
104 }
105
106 /// Have all bytes in the active scope been consumed?
107 #[must_use]
108 pub fn is_finished(&self) -> bool {
109 self.remaining_len() == 0
110 }
111
112 /// Decode exactly `len` bytes within a nested scope.
113 ///
114 /// The callback receives the same decoder type with its bounds temporarily narrowed.
115 /// It must consume the entire scope before returning successfully. Enclosing bounds are
116 /// restored on success, error, or unwinding, without rewinding the underlying reader.
117 ///
118 /// # Errors
119 /// - Returns [`Error::Failed`] if the decoder has already failed.
120 /// - Returns [`Error::Length`] if `len` exceeds the remaining length.
121 /// - Returns [`Error::NestingDepth`] if the decoder already has 64 active nested scopes.
122 /// - Returns [`Error::TrailingData`] if the callback leaves unread bytes.
123 /// - Propagates errors returned from the callback.
124 pub fn read_nested<T, E, F>(&mut self, len: usize, f: F) -> core::result::Result<T, E>
125 where
126 E: From<Error>,
127 F: FnOnce(&mut Self) -> core::result::Result<T, E>,
128 {
129 let mut scope = self.enter_nested(len)?;
130 let value = f(scope.decoder)?;
131 scope.decoder.ensure_finished()?;
132 scope.completed = true;
133 Ok(value)
134 }
135
136 /// Decode a `uint32` length prefix, then decode its body in a nested scope.
137 ///
138 /// # Errors
139 /// Propagates errors decoding the prefix or returned by [`Decoder::read_nested`].
140 pub fn read_prefixed<T, E, F>(&mut self, f: F) -> core::result::Result<T, E>
141 where
142 E: From<Error>,
143 F: FnOnce(&mut Self) -> core::result::Result<T, E>,
144 {
145 let len = usize::decode(self).inspect_err(|_| self.failed = true)?;
146 self.read_nested(len, f)
147 }
148
149 /// Decode an SSH binary `string` into `out` and return the filled portion.
150 ///
151 /// The `uint32` length prefix gives the number of payload bytes to read ([RFC4251 §5]).
152 /// To decode to a `str`, use [`Decoder::read_string`].
153 ///
154 /// The [`Decode`] impl on `Vec<u8>` can be used to allocate a buffer for the result.
155 ///
156 /// [RFC4251 §5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
157 ///
158 /// # Errors
159 /// - Returns [`Error::Length`] if the payload is larger than `out`.
160 /// - Propagates errors returned from [`Decoder::read_prefixed`] or [`Decoder::read`].
161 pub fn read_string_bytes<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
162 self.read_prefixed(|reader| {
163 let slice = out.get_mut(..reader.remaining_len()).ok_or(Error::Length)?;
164 reader.read(slice)?;
165 Ok(&*slice)
166 })
167 }
168
169 /// Decode an SSH `string` into `buf` and return the filled portion as a `&str` ([RFC4251 § 5]).
170 ///
171 /// > Arbitrary length binary string. Strings are allowed to contain
172 /// > arbitrary binary data, including null characters and 8-bit
173 /// > characters. They are stored as a uint32 containing its length
174 /// > (number of bytes that follow) and zero (= empty string) or more
175 /// > bytes that are the value of the string. Terminating null
176 /// > characters are not used.
177 /// >
178 /// > Strings are also used to store text. In that case, US-ASCII is
179 /// > used for internal names, and ISO-10646 UTF-8 for text that might
180 /// > be displayed to the user. The terminating null character SHOULD
181 /// > NOT normally be stored in the string. For example: the US-ASCII
182 /// > string "testing" is represented as 00 00 00 07 t e s t i n g. The
183 /// > UTF-8 mapping does not alter the encoding of US-ASCII characters.
184 ///
185 /// Storage for the string data must be provided as mutable byte slice in order to accommodate
186 /// `no_alloc` use cases.
187 ///
188 /// The [`Decode`] impl on `String` can be used to allocate a buffer for the result.
189 ///
190 /// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
191 ///
192 /// # Errors
193 /// - Propagates errors returned from [`Decoder::read_string_bytes`].
194 /// - Returns [`Error::CharacterEncoding`] if the data is not valid UTF-8.
195 pub fn read_string<'o>(&mut self, buf: &'o mut [u8]) -> Result<&'o str> {
196 Ok(str::from_utf8(self.read_string_bytes(buf)?)?)
197 }
198
199 /// Drain the given number of bytes from the reader, discarding them.
200 ///
201 /// # Errors
202 /// Propagates errors returned from [`Decoder::read`].
203 pub fn drain(&mut self, n_bytes: usize) -> Result<()> {
204 let mut byte = [0];
205 for _ in 0..n_bytes {
206 self.read(&mut byte)?;
207 }
208 Ok(())
209 }
210
211 /// Decode a `u32` length prefix, and then drain the length of the body.
212 ///
213 /// Upon success, returns the number of bytes drained sans the length of the `u32` length prefix
214 /// (4-bytes).
215 ///
216 /// # Errors
217 /// - Propagates errors returned from [`Decoder::read_prefixed`].
218 /// - Propagates errors returned from [`Decoder::drain`].
219 pub fn drain_prefixed(&mut self) -> Result<usize> {
220 self.read_prefixed(|reader| {
221 let len = reader.remaining_len();
222 reader.drain(len)?;
223 Ok(len)
224 })
225 }
226
227 /// Ensure that decoding is finished.
228 ///
229 /// # Errors
230 /// - Returns [`Error::Failed`] if the decoder has already failed.
231 /// - Returns [`Error::TrailingData`] if there is data remaining in the decoder.
232 pub fn ensure_finished(&self) -> Result<()> {
233 if self.failed {
234 Err(Error::Failed)
235 } else if self.is_finished() {
236 Ok(())
237 } else {
238 Err(Error::TrailingData {
239 remaining: self.remaining_len(),
240 })
241 }
242 }
243
244 /// Finish decoding, returning the given value if there is no remaining data.
245 ///
246 /// # Errors
247 /// - Returns [`Error::Failed`] if the decoder has already failed.
248 /// - Returns [`Error::TrailingData`] if there is data remaining in the decoder.
249 pub fn finish<T>(self, value: T) -> Result<T> {
250 self.ensure_finished()?;
251 Ok(value)
252 }
253
254 /// Enter a nested scope, keeping setup independent of the callback type.
255 fn enter_nested(&mut self, len: usize) -> Result<NestedScope<'_, R>> {
256 if self.failed {
257 return Err(Error::Failed);
258 }
259
260 if len > self.remaining_len() {
261 self.failed = true;
262 return Err(Error::Length);
263 }
264
265 let outer_depth = self.depth;
266 if outer_depth >= MAX_NESTING_DEPTH {
267 self.failed = true;
268 return Err(Error::NestingDepth);
269 }
270
271 let outer_end = self.end;
272 self.end = self.position + len;
273 self.depth = outer_depth + 1;
274 Ok(NestedScope {
275 decoder: self,
276 outer_end,
277 outer_depth,
278 completed: false,
279 })
280 }
281}
282
283impl<R: Reader> fmt::Debug for Decoder<R> {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285 f.debug_struct("Decoder")
286 .field("position", &self.position)
287 .field("remaining_len", &self.remaining_len())
288 .field("depth", &self.depth)
289 .field("failed", &self.failed)
290 .finish_non_exhaustive()
291 }
292}
293
294/// Restores enclosing bounds on every exit path without introducing another reader type.
295struct NestedScope<'a, R> {
296 decoder: &'a mut Decoder<R>,
297 outer_end: usize,
298 outer_depth: u8,
299 completed: bool,
300}
301
302impl<R> Drop for NestedScope<'_, R> {
303 fn drop(&mut self) {
304 self.decoder.end = self.outer_end;
305 self.decoder.depth = self.outer_depth;
306 if !self.completed {
307 self.decoder.failed = true;
308 }
309 }
310}
311
312#[cfg(test)]
313mod tests {
314 use crate::{Error, MAX_MSG_SIZE, Reader};
315
316 #[test]
317 fn input_size_limit_before_reading() {
318 // Exercise the actual limit without allocating a large input buffer.
319 struct Unreadable(usize);
320
321 impl Reader for Unreadable {
322 fn read<'o>(&mut self, _: &'o mut [u8]) -> Result<&'o [u8], Error> {
323 panic!("construction must not read input");
324 }
325
326 fn remaining_len(&self) -> usize {
327 self.0
328 }
329 }
330
331 for len in [0, MAX_MSG_SIZE - 1, MAX_MSG_SIZE] {
332 let decoder = Unreadable(len).into_decoder().unwrap();
333 assert_eq!(decoder.remaining_len(), len);
334 }
335
336 for len in [MAX_MSG_SIZE + 1, usize::MAX] {
337 assert_eq!(Unreadable(len).into_decoder().err(), Some(Error::Length));
338 }
339 }
340}