Debian Codegraph @

third_party/rust/neqo-qpack/src/table.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 use std::{
8 collections::VecDeque,
9 fmt::{self, Display, Formatter},
10 };
11
12 use neqo_common::qtrace;
13
14 use crate::{
15 static_table::{StaticTableEntry, HEADER_STATIC_TABLE},
16 Error, Res,
17 };
18
19 pub const ADDITIONAL_TABLE_ENTRY_SIZE: usize = 32;
20
21 pub struct LookupResult {
22 pub index: u64,
23 pub static_table: bool,
24 pub value_matches: bool,
25 }
26
27 #[derive(Debug)]
28 pub struct DynamicTableEntry {
29 base: u64,
30 name: Vec<u8>,
31 value: Vec<u8>,
32 /// Number of header blocks that refer this entry.
33 /// This is only used by the encoder.
34 refs: u64,
35 }
36
37 impl DynamicTableEntry {
38 pub const fn can_reduce(&self, first_not_acked: u64) -> bool {
39 self.refs == 0 && self.base < first_not_acked
40 }
41
42 pub fn size(&self) -> usize {
43 self.name.len() + self.value.len() + ADDITIONAL_TABLE_ENTRY_SIZE
44 }
45
46 pub fn add_ref(&mut self) {
47 self.refs += 1;
48 }
49
50 pub fn remove_ref(&mut self) {
51 assert!(self.refs > 0);
52 self.refs -= 1;
53 }
54
55 pub fn name(&self) -> &[u8] {
56 &self.name
57 }
58
59 pub fn value(&self) -> &[u8] {
60 &self.value
61 }
62
63 pub const fn index(&self) -> u64 {
64 self.base
65 }
66 }
67
68 #[derive(Debug)]
69 pub struct HeaderTable {
70 dynamic: VecDeque<DynamicTableEntry>,
71 /// The total capacity (in QPACK bytes) of the table. This is set by
72 /// configuration.
73 capacity: u64,
74 /// The amount of used capacity.
75 used: u64,
76 /// The total number of inserts thus far.
77 base: u64,
78 /// This is number of inserts that are acked. this correspond to index of the first not acked.
79 /// This is only used by the encoder.
80 acked_inserts_cnt: u64,
81 }
82
83 impl Display for HeaderTable {
84 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
85 write!(
86 f,
87 "HeaderTable for (base={} acked_inserts_cnt={} capacity={})",
88 self.base, self.acked_inserts_cnt, self.capacity
89 )
90 }
91 }
92
93 impl HeaderTable {
94 pub const fn new(encoder: bool) -> Self {
95 Self {
96 dynamic: VecDeque::new(),
97 capacity: 0,
98 used: 0,
99 base: 0,
100 acked_inserts_cnt: if encoder { 0 } else { u64::MAX },
101 }
102 }
103
104 /// Returns number of inserts.
105 pub const fn base(&self) -> u64 {
106 self.base
107 }
108
109 /// Returns capacity of the dynamic table
110 pub const fn capacity(&self) -> u64 {
111 self.capacity
112 }
113
114 /// Change the dynamic table capacity.
115 ///
116 /// # Errors
117 ///
118 /// [`Error::ChangeCapacity`] if table capacity cannot be reduced.
119 /// The table cannot be reduced if there are entries that are referred to at
120 /// the moment, or whose inserts are unacked.
121 pub fn set_capacity(&mut self, cap: u64) -> Res<()> {
122 qtrace!("[{self}] set capacity to {cap}");
123 if !self.evict_to(cap) {
124 return Err(Error::ChangeCapacity);
125 }
126 self.capacity = cap;
127 Ok(())
128 }
129
130 /// Get a static entry with `index`.
131 ///
132 /// # Errors
133 ///
134 /// `HeaderLookup` if the index does not exist in the static table.
135 pub fn get_static(index: u64) -> Res<&'static StaticTableEntry> {
136 let inx = usize::try_from(index).or(Err(Error::HeaderLookup))?;
137 if inx > HEADER_STATIC_TABLE.len() {
138 return Err(Error::HeaderLookup);
139 }
140 Ok(&HEADER_STATIC_TABLE[inx])
141 }
142
143 fn get_dynamic_with_abs_index(&mut self, index: u64) -> Res<&mut DynamicTableEntry> {
144 if self.base <= index {
145 debug_assert!(false, "This is an internal error");
146 return Err(Error::HeaderLookup);
147 }
148 let inx = self.base - index - 1;
149 let inx = usize::try_from(inx).or(Err(Error::HeaderLookup))?;
150 if inx >= self.dynamic.len() {
151 return Err(Error::HeaderLookup);
152 }
153 Ok(&mut self.dynamic[inx])
154 }
155
156 fn get_dynamic_with_relative_index(&self, index: u64) -> Res<&DynamicTableEntry> {
157 let inx = usize::try_from(index).or(Err(Error::HeaderLookup))?;
158 if inx >= self.dynamic.len() {
159 return Err(Error::HeaderLookup);
160 }
161 Ok(&self.dynamic[inx])
162 }
163
164 /// Get a entry in the dynamic table.
165 ///
166 /// # Errors
167 ///
168 /// `HeaderLookup` if entry does not exist.
169 pub fn get_dynamic(&self, index: u64, base: u64, post: bool) -> Res<&DynamicTableEntry> {
170 let inx = if post {
171 if self.base < (base + index + 1) {
172 return Err(Error::HeaderLookup);
173 }
174 self.base - (base + index + 1)
175 } else {
176 if (self.base + index) < base {
177 return Err(Error::HeaderLookup);
178 }
179 (self.base + index) - base
180 };
181
182 self.get_dynamic_with_relative_index(inx)
183 }
184
185 /// Remove a reference to a dynamic table entry.
186 pub fn remove_ref(&mut self, index: u64) {
187 qtrace!("[{self}] remove reference to entry {index}");
188 self.get_dynamic_with_abs_index(index)
189 .expect("we should have the entry")
190 .remove_ref();
191 }
192
193 /// Add a reference to a dynamic table entry.
194 pub fn add_ref(&mut self, index: u64) {
195 qtrace!("[{self}] add reference to entry {index}");
196 self.get_dynamic_with_abs_index(index)
197 .expect("we should have the entry")
198 .add_ref();
199 }
200
201 /// Look for a header pair.
202 /// The function returns `LookupResult`: `index`, `static_table` (if it is a static table entry)
203 /// and `value_matches` (if the header value matches as well not only header name)
204 pub fn lookup(&mut self, name: &[u8], value: &[u8], can_block: bool) -> Option<LookupResult> {
205 qtrace!("[{self}] lookup name:{name:?} value {value:?} can_block={can_block}",);
206 let mut name_match = None;
207 for iter in HEADER_STATIC_TABLE {
208 if iter.name() == name {
209 if iter.value() == value {
210 return Some(LookupResult {
211 index: iter.index(),
212 static_table: true,
213 value_matches: true,
214 });
215 }
216
217 if name_match.is_none() {
218 name_match = Some(LookupResult {
219 index: iter.index(),
220 static_table: true,
221 value_matches: false,
222 });
223 }
224 }
225 }
226
227 for iter in &mut self.dynamic {
228 if !can_block && iter.index() >= self.acked_inserts_cnt {
229 continue;
230 }
231 if iter.name == name {
232 if iter.value == value {
233 return Some(LookupResult {
234 index: iter.index(),
235 static_table: false,
236 value_matches: true,
237 });
238 }
239
240 if name_match.is_none() {
241 name_match = Some(LookupResult {
242 index: iter.index(),
243 static_table: false,
244 value_matches: false,
245 });
246 }
247 }
248 }
249 name_match
250 }
251
252 fn evict_to(&mut self, reduce: u64) -> bool {
253 qtrace!(
254 "[{self}] reduce table to {reduce}, currently used:{}",
255 self.used,
256 );
257 while (!self.dynamic.is_empty()) && self.used > reduce {
258 if let Some(e) = self.dynamic.back() {
259 if !e.can_reduce(self.acked_inserts_cnt) {
260 return false;
261 }
262 self.used -= u64::try_from(e.size()).expect("usize fits in u64");
263 self.dynamic.pop_back();
264 }
265 }
266 true
267 }
268
269 pub fn can_evict_to(&self, reduce: u64) -> bool {
270 let evictable_size: usize = self
271 .dynamic
272 .iter()
273 .rev()
274 .take_while(|e| e.can_reduce(self.acked_inserts_cnt))
275 .map(DynamicTableEntry::size)
276 .sum();
277
278 self.used - u64::try_from(evictable_size).expect("usize fits in u64") <= reduce
279 }
280
281 pub fn insert_possible(&self, size: usize) -> bool {
282 let size = u64::try_from(size).expect("usize fits in u64");
283 size <= self.capacity && self.can_evict_to(self.capacity - size)
284 }
285
286 /// Insert a new entry.
287 ///
288 /// # Errors
289 ///
290 /// `DynamicTableFull` if an entry cannot be added to the table because there is not enough
291 /// space and/or other entry cannot be evicted.
292 pub fn insert(&mut self, name: &[u8], value: &[u8]) -> Res<u64> {
293 qtrace!("[{self}] insert name={name:?} value={value:?}");
294 let entry = DynamicTableEntry {
295 name: name.to_vec(),
296 value: value.to_vec(),
297 base: self.base,
298 refs: 0,
299 };
300 if u64::try_from(entry.size()).map_err(|_| Error::Internal)? > self.capacity
301 || !self
302 .evict_to(self.capacity - u64::try_from(entry.size()).map_err(|_| Error::Internal)?)
303 {
304 return Err(Error::DynamicTableFull);
305 }
306 self.base += 1;
307 self.used += u64::try_from(entry.size()).map_err(|_| Error::Internal)?;
308 let index = entry.index();
309 self.dynamic.push_front(entry);
310 Ok(index)
311 }
312
313 /// Insert a new entry with the name refer to by a index to static or dynamic table.
314 ///
315 /// # Errors
316 ///
317 /// `DynamicTableFull` if an entry cannot be added to the table because there is not enough
318 /// space and/or other entry cannot be evicted.
319 /// `HeaderLookup` if the index dos not exits in the static/dynamic table.
320 pub fn insert_with_name_ref(
321 &mut self,
322 name_static_table: bool,
323 name_index: u64,
324 value: &[u8],
325 ) -> Res<u64> {
326 qtrace!(
327 "[{self}] insert with ref to index={name_index} in {} value={value:?}",
328 if name_static_table {
329 "static"
330 } else {
331 "dynamic"
332 },
333 );
334 let name = if name_static_table {
335 Self::get_static(name_index)?.name().to_vec()
336 } else {
337 self.get_dynamic(name_index, self.base, false)?
338 .name()
339 .to_vec()
340 };
341 self.insert(&name, value)
342 }
343
344 /// Duplicate an entry.
345 ///
346 /// # Errors
347 ///
348 /// `DynamicTableFull` if an entry cannot be added to the table because there is not enough
349 /// space and/or other entry cannot be evicted.
350 /// `HeaderLookup` if the index dos not exits in the static/dynamic table.
351 pub fn duplicate(&mut self, index: u64) -> Res<u64> {
352 qtrace!("[{self}] duplicate entry={index}");
353 // need to remember name and value because insert may delete the entry.
354 let name: Vec<u8>;
355 let value: Vec<u8>;
356 {
357 let entry = self.get_dynamic(index, self.base, false)?;
358 name = entry.name().to_vec();
359 value = entry.value().to_vec();
360 qtrace!("[{self}] duplicate name={name:?} value={value:?}");
361 }
362 self.insert(&name, &value)
363 }
364
365 /// Increment number of acknowledge entries.
366 ///
367 /// # Errors
368 ///
369 /// `IncrementAck` if ack is greater than actual number of inserts.
370 pub fn increment_acked(&mut self, increment: u64) -> Res<()> {
371 qtrace!("[{self}] increment acked by {increment}");
372 self.acked_inserts_cnt += increment;
373 if self.base < self.acked_inserts_cnt {
374 return Err(Error::IncrementAck);
375 }
376 Ok(())
377 }
378
379 /// Return number of acknowledge inserts.
380 pub const fn get_acked_inserts_cnt(&self) -> u64 {
381 self.acked_inserts_cnt
382 }
383 }
384
385 #[cfg(test)]
386 mod tests {
387 use super::*;
388
389 /// Due to a bug in [`HeaderTable::can_evict_to`], the function would
390 /// continuously subtract the size of the last entry instead of the size of
391 /// each entry starting from the back.
392 ///
393 /// See <https://github.com/mozilla/neqo/issues/2306> for details.
394 mod issue_2306 {
395 use super::*;
396
397 const VALUE: &[u8; 2] = b"42";
398
399 /// Given two entries where the first is smaller than the second,
400 /// subtracting the size of the second from the overall size twice leads
401 /// to an underflow.
402 #[test]
403 fn can_evict_to_no_underflow() {
404 let mut table = HeaderTable::new(true);
405 table.set_capacity(10000).unwrap();
406
407 table.insert(b"header1", VALUE).unwrap();
408 table.insert(b"larger-header1", VALUE).unwrap();
409
410 table.increment_acked(2).unwrap();
411
412 assert!(table.can_evict_to(0));
413 }
414
415 /// Given two entries where only the first is acked, continuously
416 /// subtracting the size of the last entry would give a false-positive
417 /// on whether both entries can be evicted.
418 #[test]
419 fn can_evict_to_false() {
420 let mut table = HeaderTable::new(true);
421 table.set_capacity(10000).unwrap();
422
423 table.insert(b"header1", VALUE).unwrap();
424 table.insert(b"header2", VALUE).unwrap();
425
426 table.increment_acked(1).unwrap();
427
428 let first_entry_size = table.get_dynamic_with_abs_index(0).unwrap().size() as u64;
429
430 assert!(table.can_evict_to(first_entry_size));
431 assert!(!table.can_evict_to(0));
432 }
433 }
434 }