1 // Copyright (C) 2019, Cloudflare, Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright notice,
9 //       this list of conditions and the following disclaimer.
10 //
11 //     * Redistributions in binary form must reproduce the above copyright
12 //       notice, this list of conditions and the following disclaimer in the
13 //       documentation and/or other materials provided with the distribution.
14 //
15 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16 // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 
27 use crate::octets;
28 
29 use super::Error;
30 use super::Result;
31 
32 use crate::h3::Header;
33 
34 use super::INDEXED;
35 use super::INDEXED_WITH_POST_BASE;
36 use super::LITERAL;
37 use super::LITERAL_WITH_NAME_REF;
38 
39 #[derive(Clone, Copy, Debug, PartialEq)]
40 enum Representation {
41     Indexed,
42     IndexedWithPostBase,
43     Literal,
44     LiteralWithNameRef,
45     LiteralWithPostBase,
46 }
47 
48 impl Representation {
from_byte(b: u8) -> Representation49     pub fn from_byte(b: u8) -> Representation {
50         if b & INDEXED == INDEXED {
51             return Representation::Indexed;
52         }
53 
54         if b & LITERAL_WITH_NAME_REF == LITERAL_WITH_NAME_REF {
55             return Representation::LiteralWithNameRef;
56         }
57 
58         if b & LITERAL == LITERAL {
59             return Representation::Literal;
60         }
61 
62         if b & INDEXED_WITH_POST_BASE == INDEXED_WITH_POST_BASE {
63             return Representation::IndexedWithPostBase;
64         }
65 
66         Representation::LiteralWithPostBase
67     }
68 }
69 
70 /// A QPACK decoder.
71 pub struct Decoder {}
72 
73 impl Default for Decoder {
default() -> Decoder74     fn default() -> Decoder {
75         Decoder {}
76     }
77 }
78 
79 impl Decoder {
80     /// Creates a new QPACK decoder.
new() -> Decoder81     pub fn new() -> Decoder {
82         Decoder::default()
83     }
84 
85     /// Processes control instructions from the encoder.
control(&mut self, _buf: &mut [u8]) -> Result<()>86     pub fn control(&mut self, _buf: &mut [u8]) -> Result<()> {
87         // TODO: process control instructions
88         Ok(())
89     }
90 
91     /// Decodes a QPACK header block into a list of headers.
decode(&mut self, buf: &[u8], max_size: u64) -> Result<Vec<Header>>92     pub fn decode(&mut self, buf: &[u8], max_size: u64) -> Result<Vec<Header>> {
93         let mut b = octets::Octets::with_slice(buf);
94 
95         let mut out = Vec::new();
96 
97         let mut left = max_size;
98 
99         let req_insert_count = decode_int(&mut b, 8)?;
100         let base = decode_int(&mut b, 7)?;
101 
102         trace!("Header count={} base={}", req_insert_count, base);
103 
104         while b.cap() > 0 {
105             let first = b.peek_u8()?;
106 
107             match Representation::from_byte(first) {
108                 Representation::Indexed => {
109                     const STATIC: u8 = 0x40;
110 
111                     let s = first & STATIC == STATIC;
112                     let index = decode_int(&mut b, 6)?;
113 
114                     trace!("Indexed index={} static={}", index, s);
115 
116                     if !s {
117                         // TODO: implement dynamic table
118                         return Err(Error::InvalidHeaderValue);
119                     }
120 
121                     let (name, value) = lookup_static(index)?;
122 
123                     left = left
124                         .checked_sub((name.len() + value.len()) as u64)
125                         .ok_or(Error::HeaderListTooLarge)?;
126 
127                     let hdr = Header::new(name, value);
128                     out.push(hdr);
129                 },
130 
131                 Representation::IndexedWithPostBase => {
132                     let index = decode_int(&mut b, 4)?;
133 
134                     trace!("Indexed With Post Base index={}", index);
135 
136                     // TODO: implement dynamic table
137                     return Err(Error::InvalidHeaderValue);
138                 },
139 
140                 Representation::Literal => {
141                     let name_huff = b.as_ref()[0] & 0x08 == 0x08;
142                     let name_len = decode_int(&mut b, 3)? as usize;
143 
144                     let mut name = b.get_bytes(name_len)?;
145 
146                     let name = if name_huff {
147                         super::huffman::decode(&mut name)?
148                     } else {
149                         name.to_vec()
150                     };
151 
152                     let name = name.to_vec();
153                     let value = decode_str(&mut b)?;
154 
155                     trace!(
156                         "Literal Without Name Reference name={:?} value={:?}",
157                         name,
158                         value,
159                     );
160 
161                     left = left
162                         .checked_sub((name.len() + value.len()) as u64)
163                         .ok_or(Error::HeaderListTooLarge)?;
164 
165                     // Instead of calling Header::new(), create Header directly
166                     // from `name` and `value`, which are already String.
167                     let hdr = Header(name, value);
168                     out.push(hdr);
169                 },
170 
171                 Representation::LiteralWithNameRef => {
172                     const STATIC: u8 = 0x10;
173 
174                     let s = first & STATIC == STATIC;
175                     let name_idx = decode_int(&mut b, 4)?;
176                     let value = decode_str(&mut b)?;
177 
178                     trace!(
179                         "Literal name_idx={} static={} value={:?}",
180                         name_idx,
181                         s,
182                         value
183                     );
184 
185                     if !s {
186                         // TODO: implement dynamic table
187                         return Err(Error::InvalidHeaderValue);
188                     }
189 
190                     let (name, _) = lookup_static(name_idx)?;
191 
192                     left = left
193                         .checked_sub((name.len() + value.len()) as u64)
194                         .ok_or(Error::HeaderListTooLarge)?;
195 
196                     // Instead of calling Header::new(), create Header directly
197                     // from `value`, which is already String, but clone `name`
198                     // as it is just a reference.
199                     let hdr = Header(name.to_vec(), value);
200                     out.push(hdr);
201                 },
202 
203                 Representation::LiteralWithPostBase => {
204                     trace!("Literal With Post Base");
205 
206                     // TODO: implement dynamic table
207                     return Err(Error::InvalidHeaderValue);
208                 },
209             }
210         }
211 
212         Ok(out)
213     }
214 }
215 
lookup_static(idx: u64) -> Result<(&'static [u8], &'static [u8])>216 fn lookup_static(idx: u64) -> Result<(&'static [u8], &'static [u8])> {
217     if idx >= super::static_table::STATIC_TABLE.len() as u64 {
218         return Err(Error::InvalidStaticTableIndex);
219     }
220 
221     Ok(super::static_table::STATIC_TABLE[idx as usize])
222 }
223 
decode_int(b: &mut octets::Octets, prefix: usize) -> Result<u64>224 fn decode_int(b: &mut octets::Octets, prefix: usize) -> Result<u64> {
225     let mask = 2u64.pow(prefix as u32) - 1;
226 
227     let mut val = u64::from(b.get_u8()?);
228     val &= mask;
229 
230     if val < mask {
231         return Ok(val);
232     }
233 
234     let mut shift = 0;
235 
236     while b.cap() > 0 {
237         let byte = b.get_u8()?;
238 
239         let inc = u64::from(byte & 0x7f)
240             .checked_shl(shift)
241             .ok_or(Error::BufferTooShort)?;
242 
243         val = val.checked_add(inc).ok_or(Error::BufferTooShort)?;
244 
245         shift += 7;
246 
247         if byte & 0x80 == 0 {
248             return Ok(val);
249         }
250     }
251 
252     Err(Error::BufferTooShort)
253 }
254 
decode_str(b: &mut octets::Octets) -> Result<Vec<u8>>255 fn decode_str(b: &mut octets::Octets) -> Result<Vec<u8>> {
256     let first = b.peek_u8()?;
257 
258     let huff = first & 0x80 == 0x80;
259 
260     let len = decode_int(b, 7)? as usize;
261 
262     let mut val = b.get_bytes(len)?;
263 
264     let val = if huff {
265         super::huffman::decode(&mut val)?
266     } else {
267         val.to_vec()
268     };
269 
270     Ok(val)
271 }
272 
273 #[cfg(test)]
274 mod tests {
275     use super::*;
276 
277     use crate::octets;
278 
279     #[test]
decode_int1()280     fn decode_int1() {
281         let mut encoded = [0b01010, 0x02];
282         let mut b = octets::Octets::with_slice(&mut encoded);
283 
284         assert_eq!(decode_int(&mut b, 5), Ok(10));
285     }
286 
287     #[test]
decode_int2()288     fn decode_int2() {
289         let mut encoded = [0b11111, 0b10011010, 0b00001010];
290         let mut b = octets::Octets::with_slice(&mut encoded);
291 
292         assert_eq!(decode_int(&mut b, 5), Ok(1337));
293     }
294 
295     #[test]
decode_int3()296     fn decode_int3() {
297         let mut encoded = [0b101010];
298         let mut b = octets::Octets::with_slice(&mut encoded);
299 
300         assert_eq!(decode_int(&mut b, 8), Ok(42));
301     }
302 }
303