1use super::StatusCode;
2use std::{
3 io::{Read, Write},
4 sync::atomic::{AtomicUsize, Ordering},
5};
6
7pub(crate) struct BoundedBuffer {
9 bytes: Vec<u8>,
10 limit: usize,
11 overflowed: bool,
12}
13
14impl BoundedBuffer {
15 pub(crate) fn new(limit: usize) -> Self {
16 Self {
17 bytes: Vec::new(),
18 limit,
19 overflowed: false,
20 }
21 }
22 pub(crate) fn into_vec(self) -> Vec<u8> {
23 self.bytes
24 }
25 pub(crate) fn overflowed(&self) -> bool {
26 self.overflowed
27 }
28}
29impl Write for BoundedBuffer {
30 fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
31 if data.len() > self.limit - self.bytes.len() {
32 self.overflowed = true;
33 return Err(std::io::ErrorKind::InvalidData.into());
34 }
35 let needed = self.bytes.len() + data.len();
36 if needed > self.bytes.capacity() {
37 let capacity = needed
38 .max(self.bytes.capacity().saturating_mul(2))
39 .max(64)
40 .min(self.limit);
41 self.bytes
42 .try_reserve_exact(capacity - self.bytes.len())
43 .map_err(|_| std::io::ErrorKind::OutOfMemory)?;
44 }
45 self.bytes.extend_from_slice(data);
46 Ok(data.len())
47 }
48 fn flush(&mut self) -> std::io::Result<()> {
49 Ok(())
50 }
51}
52
53#[derive(Clone, Debug)]
55pub struct DecodingOptions {
56 pub max_array_length: usize,
57 pub max_byte_string_length: usize,
58 pub max_string_length: usize,
59 pub max_depth: usize,
60 pub max_allocation_bytes: usize,
62}
63impl Default for DecodingOptions {
64 fn default() -> Self {
65 Self {
66 max_array_length: 65536,
67 max_byte_string_length: 16 << 20,
68 max_string_length: 1 << 20,
69 max_depth: 32,
70 max_allocation_bytes: 16 << 20,
71 }
72 }
73}
74
75#[derive(Default)]
77pub struct ContextOwned(pub DecodingOptions);
78impl ContextOwned {
79 pub fn context(&self) -> Context<'_> {
81 Context {
82 limits: &self.0,
83 depth: 0,
84 budget: Budget::Message(AtomicUsize::new(self.0.max_allocation_bytes)),
85 }
86 }
87}
88enum Budget<'a> {
89 Message(AtomicUsize),
90 Nested(&'a AtomicUsize),
91}
92
93pub struct Context<'a> {
95 limits: &'a DecodingOptions,
96 depth: usize,
97 budget: Budget<'a>,
98}
99impl std::ops::Deref for Context<'_> {
100 type Target = DecodingOptions;
101 fn deref(&self) -> &Self::Target {
102 self.limits
103 }
104}
105impl Context<'_> {
106 fn remaining(&self) -> &AtomicUsize {
107 match &self.budget {
108 Budget::Message(n) => n,
109 Budget::Nested(n) => n,
110 }
111 }
112
113 pub(super) fn charge<T>(&self, count: usize) -> Result<(), StatusCode> {
114 let bytes = count
115 .checked_mul(size_of::<T>())
116 .ok_or(StatusCode::BadEncodingLimitsExceeded)?;
117 let counter = self.remaining();
118 let mut remaining = counter.load(Ordering::Relaxed);
119 loop {
120 let next = remaining
121 .checked_sub(bytes)
122 .ok_or(StatusCode::BadEncodingLimitsExceeded)?;
123 match counter.compare_exchange_weak(
124 remaining,
125 next,
126 Ordering::Relaxed,
127 Ordering::Relaxed,
128 ) {
129 Ok(_) => return Ok(()),
130 Err(actual) => remaining = actual,
131 }
132 }
133 }
134
135 pub fn nested(&self) -> Result<Context<'_>, StatusCode> {
136 if self.depth >= self.max_depth {
137 return Err(StatusCode::BadEncodingLimitsExceeded);
138 }
139 Ok(Context {
140 limits: self.limits,
141 depth: self.depth + 1,
142 budget: Budget::Nested(self.remaining()),
143 })
144 }
145}
146
147pub trait BinaryEncodable {
149 fn encode<W: Write + ?Sized>(&self, out: &mut W, ctx: &Context<'_>) -> Result<(), StatusCode>;
150 fn encoded_len(&self, ctx: &Context<'_>) -> Result<usize, StatusCode> {
152 let mut counter = Counter(0);
153 self.encode(&mut counter, ctx)?;
154 Ok(counter.0)
155 }
156}
157struct Counter(usize);
158impl Write for Counter {
159 fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
160 self.0 = self
161 .0
162 .checked_add(data.len())
163 .ok_or(std::io::ErrorKind::InvalidData)?;
164 Ok(data.len())
165 }
166 fn flush(&mut self) -> std::io::Result<()> {
167 Ok(())
168 }
169}
170pub trait BinaryDecodable: Sized {
172 fn decode<R: Read + ?Sized>(input: &mut R, ctx: &Context<'_>) -> Result<Self, StatusCode>;
173}
174macro_rules! numeric {
175 ($($ty:ty),*) => {$(
176 impl BinaryEncodable for $ty {
177 fn encode<W:Write + ?Sized>(&self,w:&mut W,_:&Context<'_>)->Result<(),StatusCode>{
178 w.write_all(&self.to_le_bytes()).map_err(|_|StatusCode::BadEncodingError)
179 }
180 }
181 impl BinaryDecodable for $ty {
182 fn decode<R:Read + ?Sized>(r:&mut R,_:&Context<'_>)->Result<Self,StatusCode>{
183 let mut bytes=[0u8; size_of::<$ty>()];
184 r.read_exact(&mut bytes).map_err(|_|StatusCode::BadDecodingError)?;
185 Ok(Self::from_le_bytes(bytes))
186 }
187 }
188 )*};
189}
190numeric!(u8, i8, u16, i16, u32, i32, u64, i64, f32, f64);
191impl BinaryEncodable for bool {
192 fn encode<W: Write + ?Sized>(&self, w: &mut W, c: &Context<'_>) -> Result<(), StatusCode> {
193 u8::from(*self).encode(w, c)
194 }
195}
196impl BinaryDecodable for bool {
197 fn decode<R: Read + ?Sized>(r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
198 Ok(u8::decode(r, c)? != 0)
199 }
200}
201pub(super) fn length<R: Read + ?Sized>(
202 r: &mut R,
203 c: &Context<'_>,
204 max: usize,
205) -> Result<Option<usize>, StatusCode> {
206 match i32::decode(r, c)? {
207 -1 => Ok(None),
208 n if n < 0 => Err(StatusCode::BadDecodingError),
209 n if n as usize > max => Err(StatusCode::BadEncodingLimitsExceeded),
210 n => Ok(Some(n as usize)),
211 }
212}
213pub(super) fn read_bytes<R: Read + ?Sized>(
214 r: &mut R,
215 c: &Context<'_>,
216 max: usize,
217) -> Result<Option<Vec<u8>>, StatusCode> {
218 let Some(length) = length(r, c, max)? else {
219 return Ok(None);
220 };
221 c.charge::<u8>(length)?;
222 let mut data = Vec::new();
223 let mut scratch = [0u8; 4096];
224 while data.len() < length {
225 let take = scratch.len().min(length - data.len());
226 r.read_exact(&mut scratch[..take])
227 .map_err(|_| StatusCode::BadDecodingError)?;
228 if data.is_empty() {
229 data.try_reserve_exact(length)
230 .map_err(|_| StatusCode::BadEncodingLimitsExceeded)?;
231 }
232 data.extend_from_slice(&scratch[..take]);
233 }
234 Ok(Some(data))
235}
236pub(super) fn write_bytes<W: Write + ?Sized>(
237 bytes: Option<&[u8]>,
238 w: &mut W,
239 c: &Context<'_>,
240) -> Result<(), StatusCode> {
241 let Some(data) = bytes else {
242 return (-1i32).encode(w, c);
243 };
244 i32::try_from(data.len())
245 .map_err(|_| StatusCode::BadEncodingLimitsExceeded)?
246 .encode(w, c)?;
247 w.write_all(data).map_err(|_| StatusCode::BadEncodingError)
248}
249impl<T: BinaryEncodable> BinaryEncodable for Option<Vec<T>> {
250 fn encode<W: Write + ?Sized>(&self, w: &mut W, c: &Context<'_>) -> Result<(), StatusCode> {
251 let Some(items) = self else {
252 return (-1i32).encode(w, c);
253 };
254 i32::try_from(items.len())
255 .map_err(|_| StatusCode::BadEncodingLimitsExceeded)?
256 .encode(w, c)?;
257 for item in items {
258 item.encode(w, c)?;
259 }
260 Ok(())
261 }
262}
263impl<T: BinaryDecodable> BinaryDecodable for Option<Vec<T>> {
264 fn decode<R: Read + ?Sized>(r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
265 let Some(n) = length(r, c, c.max_array_length)? else {
266 return Ok(None);
267 };
268 Ok(Some(decode_array(n, c, || T::decode(r, c))?))
269 }
270}
271
272pub(super) fn decode_array<T>(
274 count: usize,
275 c: &Context<'_>,
276 mut decode: impl FnMut() -> Result<T, StatusCode>,
277) -> Result<Vec<T>, StatusCode> {
278 c.charge::<T>(count)?;
279 let mut values = Vec::new();
280 for _ in 0..count {
281 let item = decode()?;
282 if values.is_empty() {
283 values
284 .try_reserve_exact(count)
285 .map_err(|_| StatusCode::BadEncodingLimitsExceeded)?;
286 }
287 values.push(item);
288 }
289 Ok(values)
290}
291
292impl<T: BinaryDecodable> BinaryDecodable for Box<T> {
293 fn decode<R: Read + ?Sized>(r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
294 c.charge::<T>(1)?;
295 Ok(Box::new(T::decode(r, c)?))
296 }
297}