Debian Codegraph @

third_party/rust/neqo-transport/src/frame.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 // Directly relating to QUIC frames.
8
9 use std::ops::RangeInclusive;
10
11 use neqo_common::{qtrace, Decoder, Encoder, MAX_VARINT};
12 use strum::FromRepr;
13
14 use crate::{
15 cid::MAX_CONNECTION_ID_LEN,
16 ecn,
17 packet::PacketType,
18 stream_id::{StreamId, StreamType},
19 AppError, CloseReason, Error, Res, TransportError,
20 };
21
22 #[repr(u64)]
23 #[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
24 pub enum FrameType {
25 Padding = 0x0,
26 Ping = 0x1,
27 Ack = 0x2,
28 AckEcn = 0x3,
29 ResetStream = 0x4,
30 StopSending = 0x5,
31 Crypto = 0x6,
32 NewToken = 0x7,
33 Stream = 0x08, // + 0b000
34 StreamWithFin = 0x08 + 0b001,
35 StreamWithLen = 0x08 + 0b010,
36 StreamWithLenFin = 0x08 + 0b011,
37 StreamWithOff = 0x08 + 0b100,
38 StreamWithOffFin = 0x08 + 0b101,
39 StreamWithOffLen = 0x08 + 0b110,
40 StreamWithOffLenFin = 0x08 + 0b111,
41 MaxData = 0x10,
42 MaxStreamData = 0x11,
43 MaxStreamsBiDi = 0x12,
44 MaxStreamsUniDi = 0x13,
45 DataBlocked = 0x14,
46 StreamDataBlocked = 0x15,
47 StreamsBlockedBiDi = 0x16,
48 StreamsBlockedUniDi = 0x17,
49 NewConnectionId = 0x18,
50 RetireConnectionId = 0x19,
51 PathChallenge = 0x1a,
52 PathResponse = 0x1b,
53 ConnectionCloseTransport = 0x1c,
54 ConnectionCloseApplication = 0x1d,
55 HandshakeDone = 0x1e,
56 // draft-ietf-quic-ack-delay
57 AckFrequency = 0xaf,
58 // draft-ietf-quic-datagram
59 Datagram = 0x30,
60 DatagramWithLen = 0x31,
61 }
62
63 impl From<FrameType> for u64 {
64 fn from(val: FrameType) -> Self {
65 val as Self
66 }
67 }
68
69 impl From<FrameType> for u8 {
70 fn from(val: FrameType) -> Self {
71 val as Self
72 }
73 }
74
75 impl TryFrom<u64> for FrameType {
76 type Error = Error;
77
78 fn try_from(value: u64) -> Result<Self, Self::Error> {
79 Self::from_repr(value).ok_or(Error::UnknownFrameType)
80 }
81 }
82
83 impl FrameType {
84 const fn is_stream_with_length(self) -> bool {
85 matches!(
86 self,
87 Self::StreamWithLen
88 | Self::StreamWithLenFin
89 | Self::StreamWithOffLen
90 | Self::StreamWithOffLenFin
91 )
92 }
93
94 const fn is_stream_with_offset(self) -> bool {
95 matches!(
96 self,
97 Self::StreamWithOff
98 | Self::StreamWithOffFin
99 | Self::StreamWithOffLen
100 | Self::StreamWithOffLenFin
101 )
102 }
103 const fn is_stream_with_fin(self) -> bool {
104 matches!(
105 self,
106 Self::StreamWithFin
107 | Self::StreamWithLenFin
108 | Self::StreamWithOffFin
109 | Self::StreamWithOffLenFin
110 )
111 }
112 }
113
114 impl TryFrom<FrameType> for StreamType {
115 type Error = Error;
116
117 fn try_from(value: FrameType) -> Result<Self, Self::Error> {
118 match value {
119 FrameType::MaxStreamsBiDi | FrameType::StreamsBlockedBiDi => Ok(Self::BiDi),
120 FrameType::MaxStreamsUniDi | FrameType::StreamsBlockedUniDi => Ok(Self::UniDi),
121 _ => Err(Error::FrameEncodingError),
122 }
123 }
124 }
125
126 #[derive(PartialEq, Eq, Debug, PartialOrd, Ord, Clone, Copy)]
127 pub enum CloseError {
128 Transport(TransportError),
129 Application(AppError),
130 }
131
132 impl CloseError {
133 #[must_use]
134 pub const fn code(&self) -> u64 {
135 match self {
136 Self::Transport(c) | Self::Application(c) => *c,
137 }
138 }
139 }
140
141 impl From<CloseReason> for CloseError {
142 fn from(err: CloseReason) -> Self {
143 match err {
144 CloseReason::Transport(c) => Self::Transport(c.code()),
145 CloseReason::Application(c) => Self::Application(c),
146 }
147 }
148 }
149
150 impl From<std::array::TryFromSliceError> for Error {
151 fn from(_err: std::array::TryFromSliceError) -> Self {
152 Self::FrameEncodingError
153 }
154 }
155
156 #[derive(PartialEq, Eq, Debug, Default, Clone)]
157 pub struct AckRange {
158 gap: u64,
159 range: u64,
160 }
161
162 #[derive(PartialEq, Eq, Debug, Clone)]
163 pub enum Frame<'a> {
164 Padding(u16),
165 Ping,
166 Ack {
167 largest_acknowledged: u64,
168 ack_delay: u64,
169 first_ack_range: u64,
170 ack_ranges: Vec<AckRange>,
171 ecn_count: Option<ecn::Count>,
172 },
173 ResetStream {
174 stream_id: StreamId,
175 application_error_code: AppError,
176 final_size: u64,
177 },
178 StopSending {
179 stream_id: StreamId,
180 application_error_code: AppError,
181 },
182 Crypto {
183 offset: u64,
184 data: &'a [u8],
185 },
186 NewToken {
187 token: &'a [u8],
188 },
189 Stream {
190 stream_id: StreamId,
191 offset: u64,
192 data: &'a [u8],
193 fin: bool,
194 fill: bool,
195 },
196 MaxData {
197 maximum_data: u64,
198 },
199 MaxStreamData {
200 stream_id: StreamId,
201 maximum_stream_data: u64,
202 },
203 MaxStreams {
204 stream_type: StreamType,
205 maximum_streams: u64,
206 },
207 DataBlocked {
208 data_limit: u64,
209 },
210 StreamDataBlocked {
211 stream_id: StreamId,
212 stream_data_limit: u64,
213 },
214 StreamsBlocked {
215 stream_type: StreamType,
216 stream_limit: u64,
217 },
218 NewConnectionId {
219 sequence_number: u64,
220 retire_prior: u64,
221 connection_id: &'a [u8],
222 stateless_reset_token: &'a [u8; 16],
223 },
224 RetireConnectionId {
225 sequence_number: u64,
226 },
227 PathChallenge {
228 data: [u8; 8],
229 },
230 PathResponse {
231 data: [u8; 8],
232 },
233 ConnectionClose {
234 error_code: CloseError,
235 frame_type: u64,
236 // Not a reference as we use this to hold the value.
237 // This is not used in optimized builds anyway.
238 reason_phrase: String,
239 },
240 HandshakeDone,
241 AckFrequency {
242 /// The current ACK frequency sequence number.
243 seqno: u64,
244 /// The number of contiguous packets that can be received without
245 /// acknowledging immediately.
246 tolerance: u64,
247 /// The time to delay after receiving the first packet that is
248 /// not immediately acknowledged.
249 delay: u64,
250 /// Ignore reordering when deciding to immediately acknowledge.
251 ignore_order: bool,
252 },
253 Datagram {
254 data: &'a [u8],
255 fill: bool,
256 },
257 }
258
259 impl<'a> Frame<'a> {
260 #[must_use]
261 pub const fn get_type(&self) -> FrameType {
262 match self {
263 Self::Padding { .. } => FrameType::Padding,
264 Self::Ping => FrameType::Ping,
265 Self::Ack { .. } => FrameType::Ack,
266 Self::ResetStream { .. } => FrameType::ResetStream,
267 Self::StopSending { .. } => FrameType::StopSending,
268 Self::Crypto { .. } => FrameType::Crypto,
269 Self::NewToken { .. } => FrameType::NewToken,
270 Self::Stream {
271 fin, offset, fill, ..
272 } => Self::stream_type(*fin, *offset > 0, *fill),
273 Self::MaxData { .. } => FrameType::MaxData,
274 Self::MaxStreamData { .. } => FrameType::MaxStreamData,
275 Self::MaxStreams { stream_type, .. } => match stream_type {
276 StreamType::BiDi => FrameType::MaxStreamsBiDi,
277 StreamType::UniDi => FrameType::MaxStreamsUniDi,
278 },
279 Self::DataBlocked { .. } => FrameType::DataBlocked,
280 Self::StreamDataBlocked { .. } => FrameType::StreamDataBlocked,
281 Self::StreamsBlocked { stream_type, .. } => match stream_type {
282 StreamType::BiDi => FrameType::StreamsBlockedBiDi,
283 StreamType::UniDi => FrameType::StreamsBlockedUniDi,
284 },
285 Self::NewConnectionId { .. } => FrameType::NewConnectionId,
286 Self::RetireConnectionId { .. } => FrameType::RetireConnectionId,
287 Self::PathChallenge { .. } => FrameType::PathChallenge,
288 Self::PathResponse { .. } => FrameType::PathResponse,
289 Self::ConnectionClose { error_code, .. } => match error_code {
290 CloseError::Transport(_) => FrameType::ConnectionCloseTransport,
291 CloseError::Application(_) => FrameType::ConnectionCloseApplication,
292 },
293 Self::HandshakeDone => FrameType::HandshakeDone,
294 Self::AckFrequency { .. } => FrameType::AckFrequency,
295 Self::Datagram { fill, .. } => match fill {
296 false => FrameType::Datagram,
297 true => FrameType::DatagramWithLen,
298 },
299 }
300 }
301
302 #[must_use]
303 pub const fn is_stream(&self) -> bool {
304 matches!(
305 self,
306 Self::ResetStream { .. }
307 | Self::StopSending { .. }
308 | Self::Stream { .. }
309 | Self::MaxData { .. }
310 | Self::MaxStreamData { .. }
311 | Self::MaxStreams { .. }
312 | Self::DataBlocked { .. }
313 | Self::StreamDataBlocked { .. }
314 | Self::StreamsBlocked { .. }
315 )
316 }
317
318 #[must_use]
319 pub const fn stream_type(fin: bool, nonzero_offset: bool, fill: bool) -> FrameType {
320 match (nonzero_offset, fill, fin) {
321 (false, true, false) => FrameType::Stream,
322 (false, true, true) => FrameType::StreamWithFin,
323 (false, false, false) => FrameType::StreamWithLen,
324 (false, false, true) => FrameType::StreamWithLenFin,
325 (true, true, false) => FrameType::StreamWithOff,
326 (true, true, true) => FrameType::StreamWithOffFin,
327 (true, false, false) => FrameType::StreamWithOffLen,
328 (true, false, true) => FrameType::StreamWithOffLenFin,
329 }
330 }
331
332 /// If the frame causes a recipient to generate an ACK within its
333 /// advertised maximum acknowledgement delay.
334 #[must_use]
335 pub const fn ack_eliciting(&self) -> bool {
336 !matches!(
337 self,
338 Self::Ack { .. } | Self::Padding { .. } | Self::ConnectionClose { .. }
339 )
340 }
341
342 /// If the frame can be sent in a path probe
343 /// without initiating migration to that path.
344 #[must_use]
345 pub const fn path_probing(&self) -> bool {
346 matches!(
347 self,
348 Self::Padding { .. }
349 | Self::NewConnectionId { .. }
350 | Self::PathChallenge { .. }
351 | Self::PathResponse { .. }
352 )
353 }
354
355 /// Converts `AckRanges` as encoded in a ACK frame (see -transport
356 /// 19.3.1) into ranges of acked packets (end, start), inclusive of
357 /// start and end values.
358 ///
359 /// # Errors
360 ///
361 /// Returns an error if the ranges are invalid.
362 pub fn decode_ack_frame(
363 largest_acked: u64,
364 first_ack_range: u64,
365 ack_ranges: &[AckRange],
366 ) -> Res<Vec<RangeInclusive<u64>>> {
367 let mut acked_ranges = Vec::with_capacity(ack_ranges.len() + 1);
368
369 if largest_acked < first_ack_range {
370 return Err(Error::FrameEncodingError);
371 }
372 acked_ranges.push((largest_acked - first_ack_range)..=largest_acked);
373 if !ack_ranges.is_empty() && largest_acked < first_ack_range + 1 {
374 return Err(Error::FrameEncodingError);
375 }
376 let mut cur = if ack_ranges.is_empty() {
377 0
378 } else {
379 largest_acked - first_ack_range - 1
380 };
381 for r in ack_ranges {
382 if cur < r.gap + 1 {
383 return Err(Error::FrameEncodingError);
384 }
385 cur = cur - r.gap - 1;
386
387 if cur < r.range {
388 return Err(Error::FrameEncodingError);
389 }
390 acked_ranges.push((cur - r.range)..=cur);
391
392 if cur > r.range + 1 {
393 cur -= r.range + 1;
394 } else {
395 cur -= r.range;
396 }
397 }
398
399 Ok(acked_ranges)
400 }
401
402 #[must_use]
403 pub fn dump(&self) -> String {
404 match self {
405 Self::Crypto { offset, data } => {
406 format!("Crypto {{ offset: {offset}, len: {} }}", data.len())
407 }
408 Self::Stream {
409 stream_id,
410 offset,
411 fill,
412 data,
413 fin,
414 } => format!(
415 "Stream {{ stream_id: {}, offset: {offset}, len: {}{}, fin: {fin} }}",
416 stream_id.as_u64(),
417 if *fill { ">>" } else { "" },
418 data.len(),
419 ),
420 Self::Padding(length) => format!("Padding {{ len: {length} }}"),
421 Self::Datagram { data, .. } => format!("Datagram {{ len: {} }}", data.len()),
422 _ => format!("{self:?}"),
423 }
424 }
425
426 #[must_use]
427 pub fn is_allowed(&self, pt: PacketType) -> bool {
428 match self {
429 Self::Padding { .. } | Self::Ping => true,
430 Self::Crypto { .. }
431 | Self::Ack { .. }
432 | Self::ConnectionClose {
433 error_code: CloseError::Transport(_),
434 ..
435 } => pt != PacketType::ZeroRtt,
436 Self::NewToken { .. } | Self::ConnectionClose { .. } => pt == PacketType::Short,
437 _ => pt == PacketType::ZeroRtt || pt == PacketType::Short,
438 }
439 }
440
441 /// # Errors
442 ///
443 /// Returns an error if the frame cannot be decoded.
444 #[expect(
445 clippy::too_many_lines,
446 reason = "Yeah, but it's a nice match statement."
447 )]
448 pub fn decode(dec: &mut Decoder<'a>) -> Res<Self> {
449 /// Maximum ACK Range Count in ACK Frame
450 ///
451 /// Given a max UDP datagram size of 64k bytes and a minimum ACK Range size of 2
452 /// bytes (2 QUIC varints), a single datagram can at most contain 32k ACK
453 /// Ranges.
454 ///
455 /// Note that the maximum (jumbogram) Ethernet MTU of 9216 or on the
456 /// Internet the regular Ethernet MTU of 1518 are more realistically to
457 /// be the limiting factor. Though for simplicity the higher limit is chosen.
458 const MAX_ACK_RANGE_COUNT: u64 = 32 * 1024;
459
460 fn d<T>(v: Option<T>) -> Res<T> {
461 v.ok_or(Error::NoMoreData)
462 }
463 fn dv(dec: &mut Decoder) -> Res<u64> {
464 d(dec.decode_varint())
465 }
466
467 fn decode_ack<'a>(dec: &mut Decoder<'a>, ecn: bool) -> Res<Frame<'a>> {
468 let la = dv(dec)?;
469 let ad = dv(dec)?;
470 let nr = dv(dec).and_then(|nr| {
471 if nr < MAX_ACK_RANGE_COUNT {
472 Ok(nr)
473 } else {
474 Err(Error::TooMuchData)
475 }
476 })?;
477 let fa = dv(dec)?;
478 let mut arr: Vec<AckRange> = Vec::with_capacity(usize::try_from(nr)?);
479 for _ in 0..nr {
480 let ar = AckRange {
481 gap: dv(dec)?,
482 range: dv(dec)?,
483 };
484 arr.push(ar);
485 }
486
487 // Now check for the values for ACK_ECN.
488 let ecn_count = ecn
489 .then(|| -> Res<ecn::Count> {
490 Ok(ecn::Count::new(0, dv(dec)?, dv(dec)?, dv(dec)?))
491 })
492 .transpose()?;
493
494 Ok(Frame::Ack {
495 largest_acknowledged: la,
496 ack_delay: ad,
497 first_ack_range: fa,
498 ack_ranges: arr,
499 ecn_count,
500 })
501 }
502
503 // Check for minimal encoding of frame type.
504 let pos = dec.offset();
505 let t = dv(dec)?;
506 // RFC 9000, Section 12.4:
507 //
508 // The Frame Type field uses a variable-length integer encoding [...],
509 // with one exception. To ensure simple and efficient implementations of
510 // frame parsing, a frame type MUST use the shortest possible encoding.
511 if Encoder::varint_len(t) != dec.offset() - pos {
512 return Err(Error::ProtocolViolation);
513 }
514
515 let t = t.try_into()?;
516 match t {
517 FrameType::Padding => {
518 let mut length: u16 = 1;
519 while let Some(b) = dec.peek_byte() {
520 if b != u8::from(FrameType::Padding) {
521 break;
522 }
523 length += 1;
524 dec.skip(1);
525 }
526 Ok(Self::Padding(length))
527 }
528 FrameType::Ping => Ok(Self::Ping),
529 FrameType::ResetStream => Ok(Self::ResetStream {
530 stream_id: StreamId::from(dv(dec)?),
531 application_error_code: dv(dec)?,
532 final_size: match dec.decode_varint() {
533 Some(v) => v,
534 _ => return Err(Error::NoMoreData),
535 },
536 }),
537 FrameType::Ack => decode_ack(dec, false),
538 FrameType::AckEcn => decode_ack(dec, true),
539 FrameType::StopSending => Ok(Self::StopSending {
540 stream_id: StreamId::from(dv(dec)?),
541 application_error_code: dv(dec)?,
542 }),
543 FrameType::Crypto => {
544 let offset = dv(dec)?;
545 let data = d(dec.decode_vvec())?;
546 if offset + u64::try_from(data.len())? > MAX_VARINT {
547 return Err(Error::FrameEncodingError);
548 }
549 Ok(Self::Crypto { offset, data })
550 }
551 FrameType::NewToken => {
552 let token = d(dec.decode_vvec())?;
553 if token.is_empty() {
554 return Err(Error::FrameEncodingError);
555 }
556 Ok(Self::NewToken { token })
557 }
558 FrameType::Stream
559 | FrameType::StreamWithFin
560 | FrameType::StreamWithLen
561 | FrameType::StreamWithLenFin
562 | FrameType::StreamWithOff
563 | FrameType::StreamWithOffFin
564 | FrameType::StreamWithOffLen
565 | FrameType::StreamWithOffLenFin => {
566 let s = dv(dec)?;
567 let o = if t.is_stream_with_offset() {
568 dv(dec)?
569 } else {
570 0
571 };
572 let fill = !t.is_stream_with_length();
573 let data = if fill {
574 qtrace!("STREAM frame, extends to the end of the packet");
575 dec.decode_remainder()
576 } else {
577 qtrace!("STREAM frame, with length");
578 d(dec.decode_vvec())?
579 };
580 if o + u64::try_from(data.len())? > MAX_VARINT {
581 return Err(Error::FrameEncodingError);
582 }
583 Ok(Self::Stream {
584 fin: t.is_stream_with_fin(),
585 stream_id: StreamId::from(s),
586 offset: o,
587 data,
588 fill,
589 })
590 }
591 FrameType::MaxData => Ok(Self::MaxData {
592 maximum_data: dv(dec)?,
593 }),
594 FrameType::MaxStreamData => Ok(Self::MaxStreamData {
595 stream_id: StreamId::from(dv(dec)?),
596 maximum_stream_data: dv(dec)?,
597 }),
598 FrameType::MaxStreamsBiDi | FrameType::MaxStreamsUniDi => {
599 let m = dv(dec)?;
600 if m > (1 << 60) {
601 return Err(Error::StreamLimitError);
602 }
603 Ok(Self::MaxStreams {
604 stream_type: t.try_into()?,
605 maximum_streams: m,
606 })
607 }
608 FrameType::DataBlocked => Ok(Self::DataBlocked {
609 data_limit: dv(dec)?,
610 }),
611 FrameType::StreamDataBlocked => Ok(Self::StreamDataBlocked {
612 stream_id: dv(dec)?.into(),
613 stream_data_limit: dv(dec)?,
614 }),
615 FrameType::StreamsBlockedBiDi | FrameType::StreamsBlockedUniDi => {
616 Ok(Self::StreamsBlocked {
617 stream_type: t.try_into()?,
618 stream_limit: dv(dec)?,
619 })
620 }
621 FrameType::NewConnectionId => {
622 let sequence_number = dv(dec)?;
623 let retire_prior = dv(dec)?;
624 let connection_id = d(dec.decode_vec(1))?;
625 if connection_id.len() > MAX_CONNECTION_ID_LEN {
626 return Err(Error::FrameEncodingError);
627 }
628 let srt = d(dec.decode(16))?;
629 let stateless_reset_token = <&[_; 16]>::try_from(srt)?;
630
631 Ok(Self::NewConnectionId {
632 sequence_number,
633 retire_prior,
634 connection_id,
635 stateless_reset_token,
636 })
637 }
638 FrameType::RetireConnectionId => Ok(Self::RetireConnectionId {
639 sequence_number: dv(dec)?,
640 }),
641 FrameType::PathChallenge => {
642 let data = d(dec.decode(8))?;
643 let mut datav: [u8; 8] = [0; 8];
644 datav.copy_from_slice(data);
645 Ok(Self::PathChallenge { data: datav })
646 }
647 FrameType::PathResponse => {
648 let data = d(dec.decode(8))?;
649 let mut datav: [u8; 8] = [0; 8];
650 datav.copy_from_slice(data);
651 Ok(Self::PathResponse { data: datav })
652 }
653 FrameType::ConnectionCloseTransport | FrameType::ConnectionCloseApplication => {
654 let (error_code, frame_type) = if t == FrameType::ConnectionCloseTransport {
655 (CloseError::Transport(dv(dec)?), dv(dec)?)
656 } else {
657 (CloseError::Application(dv(dec)?), 0)
658 };
659 // We can tolerate this copy for now.
660 let reason_phrase = String::from_utf8_lossy(d(dec.decode_vvec())?).to_string();
661 Ok(Self::ConnectionClose {
662 error_code,
663 frame_type,
664 reason_phrase,
665 })
666 }
667 FrameType::HandshakeDone => Ok(Self::HandshakeDone),
668 FrameType::AckFrequency => {
669 let seqno = dv(dec)?;
670 let tolerance = dv(dec)?;
671 if tolerance == 0 {
672 return Err(Error::FrameEncodingError);
673 }
674 let delay = dv(dec)?;
675 let ignore_order = match d(dec.decode_uint::<u8>())? {
676 0 => false,
677 1 => true,
678 _ => return Err(Error::FrameEncodingError),
679 };
680 Ok(Self::AckFrequency {
681 seqno,
682 tolerance,
683 delay,
684 ignore_order,
685 })
686 }
687 FrameType::Datagram | FrameType::DatagramWithLen => {
688 let fill = t == FrameType::Datagram;
689 let data = if fill {
690 qtrace!("DATAGRAM frame, extends to the end of the packet");
691 dec.decode_remainder()
692 } else {
693 qtrace!("DATAGRAM frame, with length");
694 d(dec.decode_vvec())?
695 };
696 Ok(Self::Datagram { data, fill })
697 }
698 }
699 }
700 }
701
702 #[cfg(test)]
703 mod tests {
704 use neqo_common::{Decoder, Encoder};
705
706 use crate::{
707 cid::MAX_CONNECTION_ID_LEN,
708 ecn::Count,
709 frame::{AckRange, Frame, FrameType},
710 CloseError, Error, StreamId, StreamType,
711 };
712
713 fn just_dec(f: &Frame, s: &str) {
714 let encoded = Encoder::from_hex(s);
715 let decoded = Frame::decode(&mut encoded.as_decoder()).expect("Failed to decode frame");
716 assert_eq!(*f, decoded);
717 }
718
719 #[test]
720 fn padding() {
721 let f = Frame::Padding(1);
722 just_dec(&f, "00");
723 let f = Frame::Padding(2);
724 just_dec(&f, "0000");
725 }
726
727 #[test]
728 fn ping() {
729 let f = Frame::Ping;
730 just_dec(&f, "01");
731 }
732
733 #[test]
734 fn ack() {
735 let ar = vec![AckRange { gap: 1, range: 2 }, AckRange { gap: 3, range: 4 }];
736
737 let f = Frame::Ack {
738 largest_acknowledged: 0x1234,
739 ack_delay: 0x1235,
740 first_ack_range: 0x1236,
741 ack_ranges: ar.clone(),
742 ecn_count: None,
743 };
744
745 just_dec(&f, "025234523502523601020304");
746
747 // Try to parse ACK_ECN without ECN values
748 let enc = Encoder::from_hex("035234523502523601020304");
749 let mut dec = enc.as_decoder();
750 assert_eq!(Frame::decode(&mut dec).unwrap_err(), Error::NoMoreData);
751
752 // Try to parse ACK_ECN with ECN values
753 let ecn_count = Some(Count::new(0, 1, 2, 3));
754 let fe = Frame::Ack {
755 largest_acknowledged: 0x1234,
756 ack_delay: 0x1235,
757 first_ack_range: 0x1236,
758 ack_ranges: ar,
759 ecn_count,
760 };
761 let enc = Encoder::from_hex("035234523502523601020304010203");
762 let mut dec = enc.as_decoder();
763 assert_eq!(Frame::decode(&mut dec).unwrap(), fe);
764 }
765
766 #[test]
767 fn reset_stream() {
768 let f = Frame::ResetStream {
769 stream_id: StreamId::from(0x1234),
770 application_error_code: 0x77,
771 final_size: 0x3456,
772 };
773
774 just_dec(&f, "04523440777456");
775 }
776
777 #[test]
778 fn stop_sending() {
779 let f = Frame::StopSending {
780 stream_id: StreamId::from(63),
781 application_error_code: 0x77,
782 };
783
784 just_dec(&f, "053F4077");
785 }
786
787 #[test]
788 fn crypto() {
789 let f = Frame::Crypto {
790 offset: 1,
791 data: &[1, 2, 3],
792 };
793
794 just_dec(&f, "060103010203");
795 }
796
797 #[test]
798 fn new_token() {
799 let f = Frame::NewToken {
800 token: &[0x12, 0x34, 0x56],
801 };
802
803 just_dec(&f, "0703123456");
804 }
805
806 #[test]
807 fn empty_new_token() {
808 let mut dec = Decoder::from(&[0x07, 0x00][..]);
809 assert_eq!(
810 Frame::decode(&mut dec).unwrap_err(),
811 Error::FrameEncodingError
812 );
813 }
814
815 #[test]
816 fn stream() {
817 // First, just set the length bit.
818 let f = Frame::Stream {
819 fin: false,
820 stream_id: StreamId::from(5),
821 offset: 0,
822 data: &[1, 2, 3],
823 fill: false,
824 };
825
826 just_dec(&f, "0a0503010203");
827
828 // Now with offset != 0 and FIN
829 let f = Frame::Stream {
830 fin: true,
831 stream_id: StreamId::from(5),
832 offset: 1,
833 data: &[1, 2, 3],
834 fill: false,
835 };
836 just_dec(&f, "0f050103010203");
837
838 // Now to fill the packet.
839 let f = Frame::Stream {
840 fin: true,
841 stream_id: StreamId::from(5),
842 offset: 0,
843 data: &[1, 2, 3],
844 fill: true,
845 };
846 just_dec(&f, "0905010203");
847 }
848
849 #[test]
850 fn max_data() {
851 let f = Frame::MaxData {
852 maximum_data: 0x1234,
853 };
854
855 just_dec(&f, "105234");
856 }
857
858 #[test]
859 fn max_stream_data() {
860 let f = Frame::MaxStreamData {
861 stream_id: StreamId::from(5),
862 maximum_stream_data: 0x1234,
863 };
864
865 just_dec(&f, "11055234");
866 }
867
868 #[test]
869 fn max_streams() {
870 let mut f = Frame::MaxStreams {
871 stream_type: StreamType::BiDi,
872 maximum_streams: 0x1234,
873 };
874
875 just_dec(&f, "125234");
876
877 f = Frame::MaxStreams {
878 stream_type: StreamType::UniDi,
879 maximum_streams: 0x1234,
880 };
881
882 just_dec(&f, "135234");
883 }
884
885 #[test]
886 fn data_blocked() {
887 let f = Frame::DataBlocked { data_limit: 0x1234 };
888
889 just_dec(&f, "145234");
890 }
891
892 #[test]
893 fn stream_data_blocked() {
894 let f = Frame::StreamDataBlocked {
895 stream_id: StreamId::from(5),
896 stream_data_limit: 0x1234,
897 };
898
899 just_dec(&f, "15055234");
900 }
901
902 #[test]
903 fn streams_blocked() {
904 let mut f = Frame::StreamsBlocked {
905 stream_type: StreamType::BiDi,
906 stream_limit: 0x1234,
907 };
908
909 just_dec(&f, "165234");
910
911 f = Frame::StreamsBlocked {
912 stream_type: StreamType::UniDi,
913 stream_limit: 0x1234,
914 };
915
916 just_dec(&f, "175234");
917 }
918
919 #[test]
920 fn new_connection_id() {
921 let f = Frame::NewConnectionId {
922 sequence_number: 0x1234,
923 retire_prior: 0,
924 connection_id: &[0x01, 0x02],
925 stateless_reset_token: &[9; 16],
926 };
927
928 just_dec(&f, "1852340002010209090909090909090909090909090909");
929 }
930
931 #[test]
932 fn too_large_new_connection_id() {
933 let mut enc = Encoder::from_hex("18523400"); // up to the CID
934 enc.encode_vvec(&[0x0c; MAX_CONNECTION_ID_LEN + 10]);
935 enc.encode(&[0x11; 16][..]);
936 assert_eq!(
937 Frame::decode(&mut enc.as_decoder()).unwrap_err(),
938 Error::FrameEncodingError
939 );
940 }
941
942 #[test]
943 fn retire_connection_id() {
944 let f = Frame::RetireConnectionId {
945 sequence_number: 0x1234,
946 };
947
948 just_dec(&f, "195234");
949 }
950
951 #[test]
952 fn path_challenge() {
953 let f = Frame::PathChallenge { data: [9; 8] };
954
955 just_dec(&f, "1a0909090909090909");
956 }
957
958 #[test]
959 fn path_response() {
960 let f = Frame::PathResponse { data: [9; 8] };
961
962 just_dec(&f, "1b0909090909090909");
963 }
964
965 #[test]
966 fn connection_close_transport() {
967 let f = Frame::ConnectionClose {
968 error_code: CloseError::Transport(0x5678),
969 frame_type: 0x1234,
970 reason_phrase: String::from("\x01\x02\x03"),
971 };
972
973 just_dec(&f, "1c80005678523403010203");
974 }
975
976 #[test]
977 fn connection_close_application() {
978 let f = Frame::ConnectionClose {
979 error_code: CloseError::Application(0x5678),
980 frame_type: 0,
981 reason_phrase: String::from("\x01\x02\x03"),
982 };
983
984 just_dec(&f, "1d8000567803010203");
985 }
986
987 #[test]
988 fn compare() {
989 let f1 = Frame::Padding(1);
990 let f2 = Frame::Padding(1);
991 let f3 = Frame::Crypto {
992 offset: 0,
993 data: &[1, 2, 3],
994 };
995 let f4 = Frame::Crypto {
996 offset: 0,
997 data: &[1, 2, 3],
998 };
999 let f5 = Frame::Crypto {
1000 offset: 1,
1001 data: &[1, 2, 3],
1002 };
1003 let f6 = Frame::Crypto {
1004 offset: 0,
1005 data: &[1, 2, 4],
1006 };
1007
1008 assert_eq!(f1, f2);
1009 assert_ne!(f1, f3);
1010 assert_eq!(f3, f4);
1011 assert_ne!(f3, f5);
1012 assert_ne!(f3, f6);
1013 }
1014
1015 #[test]
1016 fn decode_ack_frame() {
1017 let res = Frame::decode_ack_frame(7, 2, &[AckRange { gap: 0, range: 3 }]);
1018 assert!(res.is_ok());
1019 assert_eq!(res.unwrap(), vec![5..=7, 0..=3]);
1020 }
1021
1022 #[test]
1023 fn ack_frequency() {
1024 let f = Frame::AckFrequency {
1025 seqno: 10,
1026 tolerance: 5,
1027 delay: 2000,
1028 ignore_order: true,
1029 };
1030 just_dec(&f, "40af0a0547d001");
1031 }
1032
1033 #[test]
1034 fn ack_frequency_ignore_error_error() {
1035 let enc = Encoder::from_hex("40af0a0547d003"); // ignore_order of 3
1036 assert_eq!(
1037 Frame::decode(&mut enc.as_decoder()).unwrap_err(),
1038 Error::FrameEncodingError
1039 );
1040 }
1041
1042 /// Hopefully this test is eventually redundant.
1043 #[test]
1044 fn ack_frequency_zero_packets() {
1045 let enc = Encoder::from_hex("40af0a000101"); // packets of 0
1046 assert_eq!(
1047 Frame::decode(&mut enc.as_decoder()).unwrap_err(),
1048 Error::FrameEncodingError
1049 );
1050 }
1051
1052 #[test]
1053 fn datagram() {
1054 // Without the length bit.
1055 let f = Frame::Datagram {
1056 data: &[1, 2, 3],
1057 fill: true,
1058 };
1059
1060 just_dec(&f, "30010203");
1061
1062 // With the length bit.
1063 let f = Frame::Datagram {
1064 data: &[1, 2, 3],
1065 fill: false,
1066 };
1067 just_dec(&f, "3103010203");
1068 }
1069
1070 #[test]
1071 fn frame_decode_enforces_bound_on_ack_range() {
1072 let mut e = Encoder::new();
1073
1074 e.encode_varint(FrameType::Ack);
1075 e.encode_varint(0u64); // largest acknowledged
1076 e.encode_varint(0u64); // ACK delay
1077 e.encode_varint(u32::MAX); // ACK range count = huge, but maybe available for allocation
1078
1079 assert_eq!(Err(Error::TooMuchData), Frame::decode(&mut e.as_decoder()));
1080 }
1081
1082 #[test]
1083 #[should_panic(expected = "Failed to decode frame")]
1084 fn invalid_frame_type_len() {
1085 let f = Frame::Datagram {
1086 data: &[1, 2, 3],
1087 fill: true,
1088 };
1089
1090 just_dec(&f, "4030010203");
1091 }
1092 }