1use base64ct::{Base64, Encoding as _};
2use bytes::{Bytes, BytesMut};
3use std::io::{Error, ErrorKind};
4use std::num::{NonZeroI64, NonZeroU64};
5
6pub(crate) fn decode_base64(base64: Bytes, oracle: &str) -> Result<Bytes, Error> {
10 let mut bytes = BytesMut::from(base64);
11 let len = Base64::decode_in_place(&mut bytes)
12 .map_err(|err| {
13 Error::new(
14 ErrorKind::InvalidData,
15 format!("{oracle} base64 decode error: {err}"),
16 )
17 })?
18 .len();
19 bytes.truncate(len);
20 Ok(bytes.freeze())
21}
22
23#[derive(Clone, Debug)]
27pub(crate) struct Reader<'t>(pub(crate) &'t [u8]);
28
29impl<'t> Reader<'t> {
30 pub(crate) fn assert_eof(self) -> Result<(), Error> {
31 if !self.0.is_empty() {
32 return Err(Error::new(
33 ErrorKind::InvalidData,
34 "unexpected trailing data",
35 ));
36 }
37 Ok(())
38 }
39 pub(crate) fn assert_remain(&self, n: usize) -> Result<(), Error> {
40 if self.0.len() != n {
41 return Err(Error::new(
42 ErrorKind::UnexpectedEof,
43 "unexpected data length",
44 ));
45 }
46 Ok(())
47 }
48 pub(crate) fn take_chunk<const N: usize>(&mut self) -> Result<[u8; N], Error> {
49 let (result, reader) = self
50 .0
51 .split_first_chunk()
52 .ok_or_else(|| Error::new(ErrorKind::UnexpectedEof, "unexpected end of data"))?;
53 self.0 = reader;
54 Ok(*result)
55 }
56 pub(crate) fn take_bool(&mut self) -> Result<bool, Error> {
57 let byte = self.take_u8()?;
58 match byte {
59 0 => Ok(false),
60 1 => Ok(true),
61 _ => Err(Error::new(ErrorKind::InvalidData, "invalid boolean value")),
62 }
63 }
64 pub(crate) fn take_u8(&mut self) -> Result<u8, Error> {
65 Ok(u8::from_le_bytes(self.take_chunk()?))
66 }
67 pub(crate) fn take_u16(&mut self) -> Result<u16, Error> {
68 Ok(u16::from_le_bytes(self.take_chunk()?))
69 }
70 pub(crate) fn take_i16(&mut self) -> Result<i16, Error> {
71 Ok(i16::from_le_bytes(self.take_chunk()?))
72 }
73 pub(crate) fn take_u32(&mut self) -> Result<u32, Error> {
74 Ok(u32::from_le_bytes(self.take_chunk()?))
75 }
76 pub(crate) fn take_u64(&mut self) -> Result<u64, Error> {
77 Ok(u64::from_le_bytes(self.take_chunk()?))
78 }
79 pub(crate) fn take_option_u64(&mut self) -> Result<Option<u64>, Error> {
82 if self.take_bool()? {
83 Ok(Some(self.take_u64()?))
84 } else {
85 Ok(None)
86 }
87 }
88 pub(crate) fn take_i64(&mut self) -> Result<i64, Error> {
89 Ok(i64::from_le_bytes(self.take_chunk()?))
90 }
91 pub(crate) fn take_nonzero_i64(&mut self) -> Result<Option<i64>, Error> {
93 Ok(NonZeroI64::new(self.take_i64()?).map(NonZeroI64::get))
94 }
95 pub(crate) fn take_nonzero_u64(&mut self) -> Result<Option<u64>, Error> {
97 Ok(NonZeroU64::new(self.take_u64()?).map(NonZeroU64::get))
98 }
99 pub(crate) fn take_vec_length(&mut self) -> Result<usize, Error> {
102 let mut total = 0u64;
103 for shift in [0, 7, 14, 21, 28] {
104 let byte = self.take_u8()?;
105 total |= u64::from(byte & 0x7f) << shift;
106 if byte & 0x80 == 0 {
107 return usize::try_from(total).map_err(|_| {
108 Error::new(ErrorKind::InvalidData, "vector length overflows usize")
109 });
110 }
111 }
112 Err(Error::new(
113 ErrorKind::InvalidData,
114 "vector length is longer than five ULEB128 bytes",
115 ))
116 }
117 pub(crate) fn take(&mut self, n: usize) -> Result<&'t [u8], Error> {
118 let (result, reader) = self
119 .0
120 .split_at_checked(n)
121 .ok_or_else(|| Error::new(ErrorKind::UnexpectedEof, "unexpected end of data"))?;
122 self.0 = reader;
123 Ok(result)
124 }
125 pub(crate) fn skip(&mut self, n: usize) -> Result<(), Error> {
126 let _ = self.take(n)?;
127 Ok(())
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use super::*;
134
135 fn vec_length(bytes: &[u8]) -> Result<(usize, usize), Error> {
136 let mut reader = Reader(bytes);
137 let length = reader.take_vec_length()?;
138 Ok((length, bytes.len() - reader.0.len()))
139 }
140
141 #[test]
142 fn take_vec_length() {
143 assert_eq!(vec_length(&[0x00]).unwrap(), (0, 1));
144 assert_eq!(vec_length(&[0x7f]).unwrap(), (127, 1));
145 assert_eq!(vec_length(&[0x80, 0x01]).unwrap(), (128, 2));
146 assert_eq!(vec_length(&[0xac, 0x02, 0xff]).unwrap(), (300, 2));
147 assert_eq!(vec_length(&[0x80, 0x80, 0x01]).unwrap(), (16_384, 3));
148 assert_eq!(
149 vec_length(&[0xff, 0xff, 0xff, 0xff, 0x0f]).unwrap(),
150 (u32::MAX as usize, 5),
151 );
152 }
153
154 #[test]
155 fn take_vec_length_accepts_non_canonical_encoding() {
156 assert_eq!(vec_length(&[0x80, 0x00]).unwrap(), (0, 2));
157 assert_eq!(vec_length(&[0x81, 0x80, 0x80, 0x80, 0x00]).unwrap(), (1, 5));
158 }
159
160 #[test]
161 fn take_vec_length_rejects_more_than_five_bytes() {
162 let err = vec_length(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x00]).unwrap_err();
163 assert_eq!(err.kind(), ErrorKind::InvalidData);
164 }
165
166 #[test]
167 fn take_vec_length_rejects_truncated_input() {
168 assert_eq!(
169 vec_length(&[]).unwrap_err().kind(),
170 ErrorKind::UnexpectedEof
171 );
172 assert_eq!(
173 vec_length(&[0x80, 0x80]).unwrap_err().kind(),
174 ErrorKind::UnexpectedEof,
175 );
176 }
177}