quiche/h3/
stream.rs

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
27use crate::range_buf::BufFactory;
28
29use super::Error;
30use super::Result;
31
32use super::frame;
33
34pub const HTTP3_CONTROL_STREAM_TYPE_ID: u64 = 0x0;
35pub const HTTP3_PUSH_STREAM_TYPE_ID: u64 = 0x1;
36pub const QPACK_ENCODER_STREAM_TYPE_ID: u64 = 0x2;
37pub const QPACK_DECODER_STREAM_TYPE_ID: u64 = 0x3;
38
39const MAX_STATE_BUF_SIZE: usize = (1 << 24) - 1;
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum Type {
43    Control,
44    Request,
45    Push,
46    QpackEncoder,
47    QpackDecoder,
48    Unknown,
49}
50
51impl Type {
52    #[cfg(feature = "qlog")]
53    pub fn to_qlog(self) -> qlog::events::h3::H3StreamType {
54        match self {
55            Type::Control => qlog::events::h3::H3StreamType::Control,
56            Type::Request => qlog::events::h3::H3StreamType::Request,
57            Type::Push => qlog::events::h3::H3StreamType::Push,
58            Type::QpackEncoder => qlog::events::h3::H3StreamType::QpackEncode,
59            Type::QpackDecoder => qlog::events::h3::H3StreamType::QpackDecode,
60            Type::Unknown => qlog::events::h3::H3StreamType::Unknown,
61        }
62    }
63}
64
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub enum State {
67    /// Reading the stream's type.
68    StreamType,
69
70    /// Reading the stream's current frame's type.
71    FrameType,
72
73    /// Reading the stream's current frame's payload length.
74    FramePayloadLen,
75
76    /// Reading the stream's current frame's payload.
77    FramePayload,
78
79    /// Reading DATA payload.
80    Data,
81
82    /// Reading the push ID.
83    PushId,
84
85    /// Reading a QPACK instruction.
86    QpackInstruction,
87
88    /// Reading and discarding data.
89    Drain,
90
91    /// All data has been read.
92    Finished,
93}
94
95impl Type {
96    pub fn deserialize(v: u64) -> Result<Type> {
97        match v {
98            HTTP3_CONTROL_STREAM_TYPE_ID => Ok(Type::Control),
99            HTTP3_PUSH_STREAM_TYPE_ID => Ok(Type::Push),
100            QPACK_ENCODER_STREAM_TYPE_ID => Ok(Type::QpackEncoder),
101            QPACK_DECODER_STREAM_TYPE_ID => Ok(Type::QpackDecoder),
102
103            _ => Ok(Type::Unknown),
104        }
105    }
106}
107
108/// An HTTP/3 stream.
109///
110/// This maintains the HTTP/3 state for streams of any type (control, request,
111/// QPACK, ...).
112///
113/// A number of bytes, depending on the current stream's state, is read from the
114/// transport stream into the HTTP/3 stream's "state buffer". This intermediate
115/// buffering is required due to the fact that data read from the transport
116/// might not be complete (e.g. a varint might be split across multiple QUIC
117/// packets).
118///
119/// When enough data to complete the current state has been buffered, it is
120/// consumed from the state buffer and the stream is transitioned to the next
121/// state (see `State` for a list of possible states).
122#[derive(Debug)]
123pub struct Stream {
124    /// The corresponding transport stream's ID.
125    id: u64,
126
127    /// The stream's type (if known).
128    ty: Option<Type>,
129
130    /// The current stream state.
131    state: State,
132
133    /// The buffer holding partial data for the current state.
134    state_buf: Vec<u8>,
135
136    /// The expected amount of bytes required to complete the state.
137    state_len: usize,
138
139    /// The write offset in the state buffer, that is, how many bytes have
140    /// already been read from the transport for the current state. When
141    /// it reaches `stream_len` the state can be completed.
142    state_off: usize,
143
144    /// The type of the frame currently being parsed.
145    frame_type: Option<u64>,
146
147    /// Whether the stream was created locally, or by the peer.
148    is_local: bool,
149
150    /// Whether the stream has been remotely initialized.
151    remote_initialized: bool,
152
153    /// Whether the stream has been locally initialized.
154    local_initialized: bool,
155
156    /// Whether a `Data` event has been triggered for this stream.
157    data_event_triggered: bool,
158
159    /// The last `PRIORITY_UPDATE` frame encoded field value, if any.
160    last_priority_update: Option<Vec<u8>>,
161
162    /// The count of HEADERS frames that have been received.
163    headers_received_count: usize,
164
165    /// Whether a DATA frame has been received.
166    data_received: bool,
167
168    /// Whether a trailing HEADER field has been sent.
169    trailers_sent: bool,
170
171    /// Whether a trailing HEADER field has been received.
172    trailers_received: bool,
173}
174
175impl Stream {
176    /// Creates a new HTTP/3 stream.
177    ///
178    /// The `is_local` parameter indicates whether the stream was created by the
179    /// local endpoint, or by the peer.
180    pub fn new(id: u64, is_local: bool) -> Stream {
181        let (ty, state) = if crate::stream::is_bidi(id) {
182            // All bidirectional streams are "request" streams, so we don't
183            // need to read the stream type.
184            (Some(Type::Request), State::FrameType)
185        } else {
186            // The stream's type is yet to be determined.
187            (None, State::StreamType)
188        };
189
190        Stream {
191            id,
192            ty,
193
194            state,
195
196            // Pre-allocate a buffer to avoid multiple tiny early allocations.
197            state_buf: vec![0; 16],
198
199            // Expect one byte for the initial state, to parse the initial
200            // varint length.
201            state_len: 1,
202            state_off: 0,
203
204            frame_type: None,
205
206            is_local,
207            remote_initialized: false,
208            local_initialized: false,
209
210            data_event_triggered: false,
211
212            last_priority_update: None,
213
214            headers_received_count: 0,
215
216            data_received: false,
217
218            trailers_sent: false,
219            trailers_received: false,
220        }
221    }
222
223    pub fn ty(&self) -> Option<Type> {
224        self.ty
225    }
226
227    pub fn state(&self) -> State {
228        self.state
229    }
230
231    /// Sets the stream's type and transitions to the next state.
232    pub fn set_ty(&mut self, ty: Type) -> Result<()> {
233        assert_eq!(self.state, State::StreamType);
234
235        self.ty = Some(ty);
236
237        let state = match ty {
238            Type::Control | Type::Request => State::FrameType,
239
240            Type::Push => State::PushId,
241
242            Type::QpackEncoder | Type::QpackDecoder => {
243                self.remote_initialized = true;
244
245                State::QpackInstruction
246            },
247
248            Type::Unknown => State::Drain,
249        };
250
251        self.state_transition(state, 1, true)?;
252
253        Ok(())
254    }
255
256    /// Sets the push ID and transitions to the next state.
257    pub fn set_push_id(&mut self, _id: u64) -> Result<()> {
258        assert_eq!(self.state, State::PushId);
259
260        // TODO: implement push ID.
261
262        self.state_transition(State::FrameType, 1, true)?;
263
264        Ok(())
265    }
266
267    /// Sets the frame type and transitions to the next state.
268    pub fn set_frame_type(&mut self, ty: u64) -> Result<()> {
269        assert_eq!(self.state, State::FrameType);
270
271        // Only expect frames on Control, Request and Push streams.
272        match self.ty {
273            Some(Type::Control) => {
274                // Control stream starts uninitialized and only SETTINGS is
275                // accepted in that state. Other frames cause an error. Once
276                // initialized, no more SETTINGS are permitted.
277                match (ty, self.remote_initialized) {
278                    // Initialize control stream.
279                    (frame::SETTINGS_FRAME_TYPE_ID, false) =>
280                        self.remote_initialized = true,
281
282                    // Non-SETTINGS frames not allowed on control stream
283                    // before initialization.
284                    (_, false) => return Err(Error::MissingSettings),
285
286                    // Additional SETTINGS frame.
287                    (frame::SETTINGS_FRAME_TYPE_ID, true) =>
288                        return Err(Error::FrameUnexpected),
289
290                    // Frames that can't be received on control stream
291                    // after initialization.
292                    (frame::DATA_FRAME_TYPE_ID, true) =>
293                        return Err(Error::FrameUnexpected),
294
295                    (frame::HEADERS_FRAME_TYPE_ID, true) =>
296                        return Err(Error::FrameUnexpected),
297
298                    (frame::PUSH_PROMISE_FRAME_TYPE_ID, true) =>
299                        return Err(Error::FrameUnexpected),
300
301                    // All other frames are ignored after initialization.
302                    (_, true) => (),
303                }
304            },
305
306            Some(Type::Request) => {
307                // Request stream starts uninitialized and only HEADERS is
308                // accepted. After initialization, DATA and HEADERS frames may
309                // be acceptable, depending on the role and HTTP message phase.
310                //
311                // Receiving some other types of known frames on the request
312                // stream is always an error.
313                if !self.is_local {
314                    match (ty, self.remote_initialized) {
315                        (frame::HEADERS_FRAME_TYPE_ID, false) => {
316                            self.remote_initialized = true;
317                        },
318
319                        (frame::DATA_FRAME_TYPE_ID, false) =>
320                            return Err(Error::FrameUnexpected),
321
322                        (frame::HEADERS_FRAME_TYPE_ID, true) => {
323                            if self.trailers_received {
324                                return Err(Error::FrameUnexpected);
325                            }
326
327                            if self.data_received {
328                                self.trailers_received = true;
329                            }
330                        },
331
332                        (frame::DATA_FRAME_TYPE_ID, true) => {
333                            if self.trailers_received {
334                                return Err(Error::FrameUnexpected);
335                            }
336
337                            self.data_received = true;
338                        },
339
340                        (frame::CANCEL_PUSH_FRAME_TYPE_ID, _) =>
341                            return Err(Error::FrameUnexpected),
342
343                        (frame::SETTINGS_FRAME_TYPE_ID, _) =>
344                            return Err(Error::FrameUnexpected),
345
346                        (frame::GOAWAY_FRAME_TYPE_ID, _) =>
347                            return Err(Error::FrameUnexpected),
348
349                        (frame::MAX_PUSH_FRAME_TYPE_ID, _) =>
350                            return Err(Error::FrameUnexpected),
351
352                        // All other frames can be ignored regardless of stream
353                        // state.
354                        _ => (),
355                    }
356                }
357            },
358
359            Some(Type::Push) => {
360                match ty {
361                    // Frames that can never be received on request streams.
362                    frame::CANCEL_PUSH_FRAME_TYPE_ID =>
363                        return Err(Error::FrameUnexpected),
364
365                    frame::SETTINGS_FRAME_TYPE_ID =>
366                        return Err(Error::FrameUnexpected),
367
368                    frame::PUSH_PROMISE_FRAME_TYPE_ID =>
369                        return Err(Error::FrameUnexpected),
370
371                    frame::GOAWAY_FRAME_TYPE_ID =>
372                        return Err(Error::FrameUnexpected),
373
374                    frame::MAX_PUSH_FRAME_TYPE_ID =>
375                        return Err(Error::FrameUnexpected),
376
377                    _ => (),
378                }
379            },
380
381            _ => return Err(Error::FrameUnexpected),
382        }
383
384        self.frame_type = Some(ty);
385
386        self.state_transition(State::FramePayloadLen, 1, true)?;
387
388        Ok(())
389    }
390
391    // Returns the stream's current frame type, if any
392    pub fn frame_type(&self) -> Option<u64> {
393        self.frame_type
394    }
395
396    /// Sets the frame's payload length and transitions to the next state.
397    pub fn set_frame_payload_len(&mut self, len: u64) -> Result<()> {
398        assert_eq!(self.state, State::FramePayloadLen);
399
400        // Only expect frames on Control, Request and Push streams.
401        if matches!(self.ty, Some(Type::Control | Type::Request | Type::Push)) {
402            let (state, resize) = match self.frame_type {
403                Some(frame::DATA_FRAME_TYPE_ID) => (State::Data, false),
404
405                // These frame types can never have 0 payload length because
406                // they always have fields that must be populated.
407                Some(
408                    frame::GOAWAY_FRAME_TYPE_ID |
409                    frame::PUSH_PROMISE_FRAME_TYPE_ID |
410                    frame::CANCEL_PUSH_FRAME_TYPE_ID |
411                    frame::MAX_PUSH_FRAME_TYPE_ID,
412                ) => {
413                    if len == 0 {
414                        return Err(Error::FrameError);
415                    }
416
417                    (State::FramePayload, true)
418                },
419
420                _ => (State::FramePayload, true),
421            };
422
423            self.state_transition(state, len as usize, resize)?;
424
425            return Ok(());
426        }
427
428        Err(Error::InternalError)
429    }
430
431    /// Tries to fill the state buffer by reading data from the corresponding
432    /// transport stream.
433    ///
434    /// When not enough data can be read to complete the state, this returns
435    /// `Error::Done`.
436    pub fn try_fill_buffer<F: BufFactory>(
437        &mut self, conn: &mut crate::Connection<F>,
438    ) -> Result<()> {
439        // If no bytes are required to be read, return early.
440        if self.state_buffer_complete() {
441            return Ok(());
442        }
443
444        let buf = &mut self.state_buf[self.state_off..self.state_len];
445
446        let read = match conn.stream_recv(self.id, buf) {
447            Ok((len, fin)) => {
448                // Check whether one of the critical stream was closed.
449                if fin &&
450                    matches!(
451                        self.ty,
452                        Some(Type::Control) |
453                            Some(Type::QpackEncoder) |
454                            Some(Type::QpackDecoder)
455                    )
456                {
457                    super::close_conn_critical_stream(conn)?;
458                }
459
460                len
461            },
462
463            Err(e @ crate::Error::StreamReset(_)) => {
464                // Check whether one of the critical stream was closed.
465                if matches!(
466                    self.ty,
467                    Some(Type::Control) |
468                        Some(Type::QpackEncoder) |
469                        Some(Type::QpackDecoder)
470                ) {
471                    super::close_conn_critical_stream(conn)?;
472                }
473
474                return Err(e.into());
475            },
476
477            Err(e) => {
478                // The stream is not readable anymore, so re-arm the Data event.
479                if e == crate::Error::Done {
480                    self.reset_data_event();
481                }
482
483                return Err(e.into());
484            },
485        };
486
487        trace!(
488            "{} read {} bytes on stream {}",
489            conn.trace_id(),
490            read,
491            self.id,
492        );
493
494        self.state_off += read;
495
496        if !self.state_buffer_complete() {
497            self.reset_data_event();
498
499            return Err(Error::Done);
500        }
501
502        Ok(())
503    }
504
505    /// Initialize the local part of the stream.
506    pub fn initialize_local(&mut self) {
507        self.local_initialized = true
508    }
509
510    /// Whether the stream has been locally initialized.
511    pub fn local_initialized(&self) -> bool {
512        self.local_initialized
513    }
514
515    pub fn increment_headers_received(&mut self) {
516        self.headers_received_count =
517            self.headers_received_count.saturating_add(1);
518    }
519
520    pub fn headers_received_count(&self) -> usize {
521        self.headers_received_count
522    }
523
524    pub fn mark_trailers_sent(&mut self) {
525        self.trailers_sent = true;
526    }
527
528    pub fn trailers_sent(&self) -> bool {
529        self.trailers_sent
530    }
531
532    /// Tries to fill the state buffer by reading data from the given cursor.
533    ///
534    /// This is intended to replace `try_fill_buffer()` in tests, in order to
535    /// avoid having to setup a transport connection.
536    #[cfg(test)]
537    fn try_fill_buffer_for_tests(
538        &mut self, stream: &mut std::io::Cursor<Vec<u8>>,
539    ) -> Result<()> {
540        // If no bytes are required to be read, return early
541        if self.state_buffer_complete() {
542            return Ok(());
543        }
544
545        let buf = &mut self.state_buf[self.state_off..self.state_len];
546
547        let read = std::io::Read::read(stream, buf).unwrap();
548
549        self.state_off += read;
550
551        if !self.state_buffer_complete() {
552            return Err(Error::Done);
553        }
554
555        Ok(())
556    }
557
558    /// Tries to parse a varint (including length) from the state buffer.
559    pub fn try_consume_varint(&mut self) -> Result<u64> {
560        if self.state_off == 1 {
561            self.state_len = octets::varint_parse_len(self.state_buf[0]);
562            self.state_buf.resize(self.state_len, 0);
563        }
564
565        // Return early if we don't have enough data in the state buffer to
566        // parse the whole varint.
567        if !self.state_buffer_complete() {
568            return Err(Error::Done);
569        }
570
571        let varint = octets::Octets::with_slice(&self.state_buf).get_varint()?;
572
573        Ok(varint)
574    }
575
576    /// Tries to parse a frame from the state buffer.
577    ///
578    /// If successful, returns the `frame::Frame` and the payload length.
579    pub fn try_consume_frame(&mut self) -> Result<(frame::Frame, u64)> {
580        // Processing a frame other than DATA, so re-arm the Data event.
581        self.reset_data_event();
582
583        let payload_len = self.state_len as u64;
584
585        // TODO: properly propagate frame parsing errors.
586        let frame = frame::Frame::from_bytes(
587            self.frame_type.unwrap(),
588            payload_len,
589            &self.state_buf,
590        )?;
591
592        self.state_transition(State::FrameType, 1, true)?;
593
594        Ok((frame, payload_len))
595    }
596
597    /// Tries to read DATA payload from the transport stream.
598    pub fn try_consume_data<F: BufFactory>(
599        &mut self, conn: &mut crate::Connection<F>, out: &mut [u8],
600    ) -> Result<(usize, bool)> {
601        let left = std::cmp::min(out.len(), self.state_len - self.state_off);
602
603        let (len, fin) = match conn.stream_recv(self.id, &mut out[..left]) {
604            Ok(v) => v,
605
606            Err(e) => {
607                // The stream is not readable anymore, so re-arm the Data event.
608                if e == crate::Error::Done {
609                    self.reset_data_event();
610                }
611
612                return Err(e.into());
613            },
614        };
615
616        self.state_off += len;
617
618        // The stream is not readable anymore, so re-arm the Data event.
619        if !conn.stream_readable(self.id) {
620            self.reset_data_event();
621        }
622
623        if self.state_buffer_complete() {
624            self.state_transition(State::FrameType, 1, true)?;
625        }
626
627        Ok((len, fin))
628    }
629
630    /// Marks the stream as finished.
631    pub fn finished(&mut self) {
632        let _ = self.state_transition(State::Finished, 0, false);
633    }
634
635    /// Tries to read DATA payload from the given cursor.
636    ///
637    /// This is intended to replace `try_consume_data()` in tests, in order to
638    /// avoid having to setup a transport connection.
639    #[cfg(test)]
640    fn try_consume_data_for_tests(
641        &mut self, stream: &mut std::io::Cursor<Vec<u8>>, out: &mut [u8],
642    ) -> Result<usize> {
643        let left = std::cmp::min(out.len(), self.state_len - self.state_off);
644
645        let len = std::io::Read::read(stream, &mut out[..left]).unwrap();
646
647        self.state_off += len;
648
649        if self.state_buffer_complete() {
650            self.state_transition(State::FrameType, 1, true)?;
651        }
652
653        Ok(len)
654    }
655
656    /// Tries to update the data triggered state for the stream.
657    ///
658    /// This returns `true` if a Data event was not already triggered before
659    /// the last reset, and updates the state. Returns `false` otherwise.
660    pub fn try_trigger_data_event(&mut self) -> bool {
661        if self.data_event_triggered {
662            return false;
663        }
664
665        self.data_event_triggered = true;
666
667        true
668    }
669
670    /// Resets the data triggered state.
671    fn reset_data_event(&mut self) {
672        self.data_event_triggered = false;
673    }
674
675    /// Set the last priority update for the stream.
676    pub fn set_last_priority_update(&mut self, priority_update: Option<Vec<u8>>) {
677        self.last_priority_update = priority_update;
678    }
679
680    /// Take the last priority update and leave `None` in its place.
681    pub fn take_last_priority_update(&mut self) -> Option<Vec<u8>> {
682        self.last_priority_update.take()
683    }
684
685    /// Returns `true` if there is a priority update.
686    pub fn has_last_priority_update(&self) -> bool {
687        self.last_priority_update.is_some()
688    }
689
690    /// Returns true if the state buffer has enough data to complete the state.
691    fn state_buffer_complete(&self) -> bool {
692        self.state_off == self.state_len
693    }
694
695    /// Transitions the stream to a new state, and optionally resets the state
696    /// buffer.
697    fn state_transition(
698        &mut self, new_state: State, expected_len: usize, resize: bool,
699    ) -> Result<()> {
700        // Some states don't need the state buffer, so don't resize it if not
701        // necessary.
702        if resize {
703            // A peer can influence the size of the state buffer (e.g. with the
704            // payload size of a GREASE frame), so we need to limit the maximum
705            // size to avoid DoS.
706            if expected_len > MAX_STATE_BUF_SIZE {
707                return Err(Error::ExcessiveLoad);
708            }
709
710            self.state_buf.resize(expected_len, 0);
711        }
712
713        self.state = new_state;
714        self.state_off = 0;
715        self.state_len = expected_len;
716
717        Ok(())
718    }
719}
720
721#[cfg(test)]
722mod tests {
723    use crate::h3::frame::*;
724
725    use super::*;
726
727    fn open_uni(b: &mut octets::OctetsMut, ty: u64) -> Result<Stream> {
728        let stream = <Stream>::new(2, false);
729        assert_eq!(stream.state, State::StreamType);
730
731        b.put_varint(ty)?;
732
733        Ok(stream)
734    }
735
736    fn parse_uni(
737        stream: &mut Stream, ty: u64, cursor: &mut std::io::Cursor<Vec<u8>>,
738    ) -> Result<()> {
739        stream.try_fill_buffer_for_tests(cursor)?;
740
741        let stream_ty = stream.try_consume_varint()?;
742        assert_eq!(stream_ty, ty);
743        stream.set_ty(Type::deserialize(stream_ty).unwrap())?;
744
745        Ok(())
746    }
747
748    fn parse_skip_frame(
749        stream: &mut Stream, cursor: &mut std::io::Cursor<Vec<u8>>,
750    ) -> Result<()> {
751        // Parse the frame type.
752        stream.try_fill_buffer_for_tests(cursor)?;
753
754        let frame_ty = stream.try_consume_varint()?;
755
756        stream.set_frame_type(frame_ty)?;
757        assert_eq!(stream.state, State::FramePayloadLen);
758
759        // Parse the frame payload length.
760        stream.try_fill_buffer_for_tests(cursor)?;
761
762        let frame_payload_len = stream.try_consume_varint()?;
763        stream.set_frame_payload_len(frame_payload_len)?;
764        assert_eq!(stream.state, State::FramePayload);
765
766        // Parse the frame payload.
767        stream.try_fill_buffer_for_tests(cursor)?;
768
769        stream.try_consume_frame()?;
770        assert_eq!(stream.state, State::FrameType);
771
772        Ok(())
773    }
774
775    #[test]
776    /// Process incoming SETTINGS frame on control stream.
777    fn control_good() {
778        let mut d = vec![42; 40];
779        let mut b = octets::OctetsMut::with_slice(&mut d);
780
781        let raw_settings = vec![
782            (SETTINGS_MAX_FIELD_SECTION_SIZE, 0),
783            (SETTINGS_QPACK_MAX_TABLE_CAPACITY, 0),
784            (SETTINGS_QPACK_BLOCKED_STREAMS, 0),
785        ];
786
787        let frame = Frame::Settings {
788            max_field_section_size: Some(0),
789            qpack_max_table_capacity: Some(0),
790            qpack_blocked_streams: Some(0),
791            connect_protocol_enabled: None,
792            h3_datagram: None,
793            grease: None,
794            additional_settings: None,
795            raw: Some(raw_settings),
796        };
797
798        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
799        frame.to_bytes(&mut b).unwrap();
800
801        let mut cursor = std::io::Cursor::new(d);
802
803        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
804            .unwrap();
805        assert_eq!(stream.state, State::FrameType);
806
807        // Parse the SETTINGS frame type.
808        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
809
810        let frame_ty = stream.try_consume_varint().unwrap();
811        assert_eq!(frame_ty, SETTINGS_FRAME_TYPE_ID);
812
813        stream.set_frame_type(frame_ty).unwrap();
814        assert_eq!(stream.state, State::FramePayloadLen);
815
816        // Parse the SETTINGS frame payload length.
817        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
818
819        let frame_payload_len = stream.try_consume_varint().unwrap();
820        assert_eq!(frame_payload_len, 6);
821        stream.set_frame_payload_len(frame_payload_len).unwrap();
822        assert_eq!(stream.state, State::FramePayload);
823
824        // Parse the SETTINGS frame payload.
825        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
826
827        assert_eq!(stream.try_consume_frame(), Ok((frame, 6)));
828        assert_eq!(stream.state, State::FrameType);
829    }
830
831    #[test]
832    /// Process incoming empty SETTINGS frame on control stream.
833    fn control_empty_settings() {
834        let mut d = vec![42; 40];
835        let mut b = octets::OctetsMut::with_slice(&mut d);
836
837        let frame = Frame::Settings {
838            max_field_section_size: None,
839            qpack_max_table_capacity: None,
840            qpack_blocked_streams: None,
841            connect_protocol_enabled: None,
842            h3_datagram: None,
843            grease: None,
844            additional_settings: None,
845            raw: Some(vec![]),
846        };
847
848        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
849        frame.to_bytes(&mut b).unwrap();
850
851        let mut cursor = std::io::Cursor::new(d);
852
853        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
854            .unwrap();
855        assert_eq!(stream.state, State::FrameType);
856
857        // Parse the SETTINGS frame type.
858        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
859
860        let frame_ty = stream.try_consume_varint().unwrap();
861        assert_eq!(frame_ty, SETTINGS_FRAME_TYPE_ID);
862
863        stream.set_frame_type(frame_ty).unwrap();
864        assert_eq!(stream.state, State::FramePayloadLen);
865
866        // Parse the SETTINGS frame payload length.
867        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
868
869        let frame_payload_len = stream.try_consume_varint().unwrap();
870        assert_eq!(frame_payload_len, 0);
871        stream.set_frame_payload_len(frame_payload_len).unwrap();
872        assert_eq!(stream.state, State::FramePayload);
873
874        // Parse the SETTINGS frame payload.
875        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
876
877        assert_eq!(stream.try_consume_frame(), Ok((frame, 0)));
878        assert_eq!(stream.state, State::FrameType);
879    }
880
881    #[test]
882    /// Process duplicate SETTINGS frame on control stream.
883    fn control_bad_multiple_settings() {
884        let mut d = vec![42; 40];
885        let mut b = octets::OctetsMut::with_slice(&mut d);
886
887        let raw_settings = vec![
888            (SETTINGS_MAX_FIELD_SECTION_SIZE, 0),
889            (SETTINGS_QPACK_MAX_TABLE_CAPACITY, 0),
890            (SETTINGS_QPACK_BLOCKED_STREAMS, 0),
891        ];
892
893        let frame = Frame::Settings {
894            max_field_section_size: Some(0),
895            qpack_max_table_capacity: Some(0),
896            qpack_blocked_streams: Some(0),
897            connect_protocol_enabled: None,
898            h3_datagram: None,
899            grease: None,
900            additional_settings: None,
901            raw: Some(raw_settings),
902        };
903
904        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
905        frame.to_bytes(&mut b).unwrap();
906        frame.to_bytes(&mut b).unwrap();
907
908        let mut cursor = std::io::Cursor::new(d);
909
910        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
911            .unwrap();
912        assert_eq!(stream.state, State::FrameType);
913
914        // Parse the SETTINGS frame type.
915        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
916
917        let frame_ty = stream.try_consume_varint().unwrap();
918        assert_eq!(frame_ty, SETTINGS_FRAME_TYPE_ID);
919
920        stream.set_frame_type(frame_ty).unwrap();
921        assert_eq!(stream.state, State::FramePayloadLen);
922
923        // Parse the SETTINGS frame payload length.
924        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
925
926        let frame_payload_len = stream.try_consume_varint().unwrap();
927        assert_eq!(frame_payload_len, 6);
928        stream.set_frame_payload_len(frame_payload_len).unwrap();
929        assert_eq!(stream.state, State::FramePayload);
930
931        // Parse the SETTINGS frame payload.
932        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
933
934        assert_eq!(stream.try_consume_frame(), Ok((frame, 6)));
935        assert_eq!(stream.state, State::FrameType);
936
937        // Parse the second SETTINGS frame type.
938        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
939
940        let frame_ty = stream.try_consume_varint().unwrap();
941        assert_eq!(stream.set_frame_type(frame_ty), Err(Error::FrameUnexpected));
942    }
943
944    #[test]
945    /// Process other frame before SETTINGS frame on control stream.
946    fn control_bad_late_settings() {
947        let mut d = vec![42; 40];
948        let mut b = octets::OctetsMut::with_slice(&mut d);
949
950        let goaway = Frame::GoAway { id: 0 };
951
952        let raw_settings = vec![
953            (SETTINGS_MAX_FIELD_SECTION_SIZE, 0),
954            (SETTINGS_QPACK_MAX_TABLE_CAPACITY, 0),
955            (SETTINGS_QPACK_BLOCKED_STREAMS, 0),
956        ];
957
958        let settings = Frame::Settings {
959            max_field_section_size: Some(0),
960            qpack_max_table_capacity: Some(0),
961            qpack_blocked_streams: Some(0),
962            connect_protocol_enabled: None,
963            h3_datagram: None,
964            grease: None,
965            additional_settings: None,
966            raw: Some(raw_settings),
967        };
968
969        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
970        goaway.to_bytes(&mut b).unwrap();
971        settings.to_bytes(&mut b).unwrap();
972
973        let mut cursor = std::io::Cursor::new(d);
974
975        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
976            .unwrap();
977        assert_eq!(stream.state, State::FrameType);
978
979        // Parse GOAWAY.
980        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
981
982        let frame_ty = stream.try_consume_varint().unwrap();
983        assert_eq!(stream.set_frame_type(frame_ty), Err(Error::MissingSettings));
984    }
985
986    #[test]
987    /// Process not-allowed frame on control stream.
988    fn control_bad_frame() {
989        let mut d = vec![42; 40];
990        let mut b = octets::OctetsMut::with_slice(&mut d);
991
992        let header_block = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
993        let hdrs = Frame::Headers { header_block };
994
995        let raw_settings = vec![
996            (SETTINGS_MAX_FIELD_SECTION_SIZE, 0),
997            (SETTINGS_QPACK_MAX_TABLE_CAPACITY, 0),
998            (SETTINGS_QPACK_BLOCKED_STREAMS, 0),
999            (33, 33),
1000        ];
1001
1002        let settings = Frame::Settings {
1003            max_field_section_size: Some(0),
1004            qpack_max_table_capacity: Some(0),
1005            qpack_blocked_streams: Some(0),
1006            connect_protocol_enabled: None,
1007            h3_datagram: None,
1008            grease: None,
1009            additional_settings: None,
1010            raw: Some(raw_settings),
1011        };
1012
1013        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
1014        settings.to_bytes(&mut b).unwrap();
1015        hdrs.to_bytes(&mut b).unwrap();
1016
1017        let mut cursor = std::io::Cursor::new(d);
1018
1019        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
1020            .unwrap();
1021        assert_eq!(stream.state, State::FrameType);
1022
1023        // Parse first SETTINGS frame.
1024        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1025
1026        let frame_ty = stream.try_consume_varint().unwrap();
1027        stream.set_frame_type(frame_ty).unwrap();
1028
1029        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1030
1031        let frame_payload_len = stream.try_consume_varint().unwrap();
1032        stream.set_frame_payload_len(frame_payload_len).unwrap();
1033
1034        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1035
1036        assert!(stream.try_consume_frame().is_ok());
1037
1038        // Parse HEADERS.
1039        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1040
1041        let frame_ty = stream.try_consume_varint().unwrap();
1042        assert_eq!(stream.set_frame_type(frame_ty), Err(Error::FrameUnexpected));
1043    }
1044
1045    #[test]
1046    fn request_no_data() {
1047        let mut stream = <Stream>::new(0, false);
1048
1049        assert_eq!(stream.ty, Some(Type::Request));
1050        assert_eq!(stream.state, State::FrameType);
1051
1052        assert_eq!(stream.try_consume_varint(), Err(Error::Done));
1053    }
1054
1055    #[test]
1056    fn request_good() {
1057        let mut stream = <Stream>::new(0, false);
1058
1059        let mut d = vec![42; 128];
1060        let mut b = octets::OctetsMut::with_slice(&mut d);
1061
1062        let header_block = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
1063        let payload = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
1064        let hdrs = Frame::Headers { header_block };
1065        let data = Frame::Data {
1066            payload: payload.clone(),
1067        };
1068
1069        hdrs.to_bytes(&mut b).unwrap();
1070        data.to_bytes(&mut b).unwrap();
1071
1072        let mut cursor = std::io::Cursor::new(d);
1073
1074        // Parse the HEADERS frame type.
1075        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1076
1077        let frame_ty = stream.try_consume_varint().unwrap();
1078        assert_eq!(frame_ty, HEADERS_FRAME_TYPE_ID);
1079
1080        stream.set_frame_type(frame_ty).unwrap();
1081        assert_eq!(stream.state, State::FramePayloadLen);
1082
1083        // Parse the HEADERS frame payload length.
1084        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1085
1086        let frame_payload_len = stream.try_consume_varint().unwrap();
1087        assert_eq!(frame_payload_len, 12);
1088
1089        stream.set_frame_payload_len(frame_payload_len).unwrap();
1090        assert_eq!(stream.state, State::FramePayload);
1091
1092        // Parse the HEADERS frame.
1093        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1094
1095        assert_eq!(stream.try_consume_frame(), Ok((hdrs, 12)));
1096        assert_eq!(stream.state, State::FrameType);
1097
1098        // Parse the DATA frame type.
1099        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1100
1101        let frame_ty = stream.try_consume_varint().unwrap();
1102        assert_eq!(frame_ty, DATA_FRAME_TYPE_ID);
1103
1104        stream.set_frame_type(frame_ty).unwrap();
1105        assert_eq!(stream.state, State::FramePayloadLen);
1106
1107        // Parse the DATA frame payload length.
1108        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1109
1110        let frame_payload_len = stream.try_consume_varint().unwrap();
1111        assert_eq!(frame_payload_len, 12);
1112
1113        stream.set_frame_payload_len(frame_payload_len).unwrap();
1114        assert_eq!(stream.state, State::Data);
1115
1116        // Parse the DATA payload.
1117        let mut recv_buf = vec![0; payload.len()];
1118        assert_eq!(
1119            stream.try_consume_data_for_tests(&mut cursor, &mut recv_buf),
1120            Ok(payload.len())
1121        );
1122        assert_eq!(payload, recv_buf);
1123
1124        assert_eq!(stream.state, State::FrameType);
1125    }
1126
1127    #[test]
1128    fn push_good() {
1129        let mut d = vec![42; 128];
1130        let mut b = octets::OctetsMut::with_slice(&mut d);
1131
1132        let header_block = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
1133        let payload = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
1134        let hdrs = Frame::Headers { header_block };
1135        let data = Frame::Data {
1136            payload: payload.clone(),
1137        };
1138
1139        let mut stream = open_uni(&mut b, HTTP3_PUSH_STREAM_TYPE_ID).unwrap();
1140        b.put_varint(1).unwrap();
1141        hdrs.to_bytes(&mut b).unwrap();
1142        data.to_bytes(&mut b).unwrap();
1143
1144        let mut cursor = std::io::Cursor::new(d);
1145
1146        parse_uni(&mut stream, HTTP3_PUSH_STREAM_TYPE_ID, &mut cursor).unwrap();
1147        assert_eq!(stream.state, State::PushId);
1148
1149        // Parse push ID.
1150        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1151
1152        let push_id = stream.try_consume_varint().unwrap();
1153        assert_eq!(push_id, 1);
1154
1155        stream.set_push_id(push_id).unwrap();
1156        assert_eq!(stream.state, State::FrameType);
1157
1158        // Parse the HEADERS frame type.
1159        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1160
1161        let frame_ty = stream.try_consume_varint().unwrap();
1162        assert_eq!(frame_ty, HEADERS_FRAME_TYPE_ID);
1163
1164        stream.set_frame_type(frame_ty).unwrap();
1165        assert_eq!(stream.state, State::FramePayloadLen);
1166
1167        // Parse the HEADERS frame payload length.
1168        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1169
1170        let frame_payload_len = stream.try_consume_varint().unwrap();
1171        assert_eq!(frame_payload_len, 12);
1172
1173        stream.set_frame_payload_len(frame_payload_len).unwrap();
1174        assert_eq!(stream.state, State::FramePayload);
1175
1176        // Parse the HEADERS frame.
1177        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1178
1179        assert_eq!(stream.try_consume_frame(), Ok((hdrs, 12)));
1180        assert_eq!(stream.state, State::FrameType);
1181
1182        // Parse the DATA frame type.
1183        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1184
1185        let frame_ty = stream.try_consume_varint().unwrap();
1186        assert_eq!(frame_ty, DATA_FRAME_TYPE_ID);
1187
1188        stream.set_frame_type(frame_ty).unwrap();
1189        assert_eq!(stream.state, State::FramePayloadLen);
1190
1191        // Parse the DATA frame payload length.
1192        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1193
1194        let frame_payload_len = stream.try_consume_varint().unwrap();
1195        assert_eq!(frame_payload_len, 12);
1196
1197        stream.set_frame_payload_len(frame_payload_len).unwrap();
1198        assert_eq!(stream.state, State::Data);
1199
1200        // Parse the DATA payload.
1201        let mut recv_buf = vec![0; payload.len()];
1202        assert_eq!(
1203            stream.try_consume_data_for_tests(&mut cursor, &mut recv_buf),
1204            Ok(payload.len())
1205        );
1206        assert_eq!(payload, recv_buf);
1207
1208        assert_eq!(stream.state, State::FrameType);
1209    }
1210
1211    #[test]
1212    fn grease() {
1213        let mut d = vec![42; 20];
1214        let mut b = octets::OctetsMut::with_slice(&mut d);
1215
1216        let mut stream = open_uni(&mut b, 33).unwrap();
1217
1218        let mut cursor = std::io::Cursor::new(d);
1219
1220        // Parse stream type.
1221        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1222
1223        let stream_ty = stream.try_consume_varint().unwrap();
1224        assert_eq!(stream_ty, 33);
1225        stream
1226            .set_ty(Type::deserialize(stream_ty).unwrap())
1227            .unwrap();
1228        assert_eq!(stream.state, State::Drain);
1229    }
1230
1231    #[test]
1232    fn data_before_headers() {
1233        let mut stream = <Stream>::new(0, false);
1234
1235        let mut d = vec![42; 128];
1236        let mut b = octets::OctetsMut::with_slice(&mut d);
1237
1238        let data = Frame::Data {
1239            payload: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
1240        };
1241
1242        data.to_bytes(&mut b).unwrap();
1243
1244        let mut cursor = std::io::Cursor::new(d);
1245
1246        // Parse the DATA frame type.
1247        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1248
1249        let frame_ty = stream.try_consume_varint().unwrap();
1250        assert_eq!(frame_ty, DATA_FRAME_TYPE_ID);
1251
1252        assert_eq!(stream.set_frame_type(frame_ty), Err(Error::FrameUnexpected));
1253    }
1254
1255    #[test]
1256    fn additional_headers() {
1257        let mut stream = Stream::new(0, false);
1258
1259        let mut d = vec![42; 128];
1260        let mut b = octets::OctetsMut::with_slice(&mut d);
1261
1262        let header_block = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
1263        let payload = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
1264        let info_hdrs = Frame::Headers {
1265            header_block: header_block.clone(),
1266        };
1267        let non_info_hdrs = Frame::Headers {
1268            header_block: header_block.clone(),
1269        };
1270        let trailers = Frame::Headers { header_block };
1271        let data = Frame::Data {
1272            payload: payload.clone(),
1273        };
1274
1275        info_hdrs.to_bytes(&mut b).unwrap();
1276        non_info_hdrs.to_bytes(&mut b).unwrap();
1277        data.to_bytes(&mut b).unwrap();
1278        trailers.to_bytes(&mut b).unwrap();
1279
1280        let mut cursor = std::io::Cursor::new(d);
1281
1282        // Parse the HEADERS frame type.
1283        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1284
1285        let frame_ty = stream.try_consume_varint().unwrap();
1286        assert_eq!(frame_ty, HEADERS_FRAME_TYPE_ID);
1287
1288        stream.set_frame_type(frame_ty).unwrap();
1289        assert_eq!(stream.state, State::FramePayloadLen);
1290
1291        // Parse the HEADERS frame payload length.
1292        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1293
1294        let frame_payload_len = stream.try_consume_varint().unwrap();
1295        assert_eq!(frame_payload_len, 12);
1296
1297        stream.set_frame_payload_len(frame_payload_len).unwrap();
1298        assert_eq!(stream.state, State::FramePayload);
1299
1300        // Parse the HEADERS frame.
1301        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1302
1303        assert_eq!(stream.try_consume_frame(), Ok((info_hdrs, 12)));
1304        assert_eq!(stream.state, State::FrameType);
1305
1306        // Parse the non-info HEADERS frame type.
1307        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1308
1309        let frame_ty = stream.try_consume_varint().unwrap();
1310        assert_eq!(frame_ty, HEADERS_FRAME_TYPE_ID);
1311
1312        stream.set_frame_type(frame_ty).unwrap();
1313        assert_eq!(stream.state, State::FramePayloadLen);
1314
1315        // Parse the HEADERS frame payload length.
1316        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1317
1318        let frame_payload_len = stream.try_consume_varint().unwrap();
1319        assert_eq!(frame_payload_len, 12);
1320
1321        stream.set_frame_payload_len(frame_payload_len).unwrap();
1322        assert_eq!(stream.state, State::FramePayload);
1323
1324        // Parse the HEADERS frame.
1325        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1326
1327        assert_eq!(stream.try_consume_frame(), Ok((non_info_hdrs, 12)));
1328        assert_eq!(stream.state, State::FrameType);
1329
1330        // Parse the DATA frame type.
1331        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1332
1333        let frame_ty = stream.try_consume_varint().unwrap();
1334        assert_eq!(frame_ty, DATA_FRAME_TYPE_ID);
1335
1336        stream.set_frame_type(frame_ty).unwrap();
1337        assert_eq!(stream.state, State::FramePayloadLen);
1338
1339        // Parse the DATA frame payload length.
1340        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1341
1342        let frame_payload_len = stream.try_consume_varint().unwrap();
1343        assert_eq!(frame_payload_len, 12);
1344
1345        stream.set_frame_payload_len(frame_payload_len).unwrap();
1346        assert_eq!(stream.state, State::Data);
1347
1348        // Parse the DATA payload.
1349        let mut recv_buf = vec![0; payload.len()];
1350        assert_eq!(
1351            stream.try_consume_data_for_tests(&mut cursor, &mut recv_buf),
1352            Ok(payload.len())
1353        );
1354        assert_eq!(payload, recv_buf);
1355
1356        assert_eq!(stream.state, State::FrameType);
1357
1358        // Parse the trailing HEADERS frame type.
1359        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1360
1361        let frame_ty = stream.try_consume_varint().unwrap();
1362        assert_eq!(frame_ty, HEADERS_FRAME_TYPE_ID);
1363
1364        stream.set_frame_type(frame_ty).unwrap();
1365        assert_eq!(stream.state, State::FramePayloadLen);
1366
1367        // Parse the HEADERS frame payload length.
1368        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1369
1370        let frame_payload_len = stream.try_consume_varint().unwrap();
1371        assert_eq!(frame_payload_len, 12);
1372
1373        stream.set_frame_payload_len(frame_payload_len).unwrap();
1374        assert_eq!(stream.state, State::FramePayload);
1375
1376        // Parse the HEADERS frame.
1377        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1378
1379        assert_eq!(stream.try_consume_frame(), Ok((trailers, 12)));
1380        assert_eq!(stream.state, State::FrameType);
1381    }
1382
1383    #[test]
1384    fn zero_length_goaway() {
1385        let mut d = vec![42; 128];
1386        let mut b = octets::OctetsMut::with_slice(&mut d);
1387
1388        let frame = Frame::Settings {
1389            max_field_section_size: None,
1390            qpack_max_table_capacity: None,
1391            qpack_blocked_streams: None,
1392            connect_protocol_enabled: None,
1393            h3_datagram: None,
1394            grease: None,
1395            additional_settings: None,
1396            raw: Some(vec![]),
1397        };
1398
1399        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
1400        frame.to_bytes(&mut b).unwrap();
1401
1402        // Write a 0-length payload frame.
1403        b.put_varint(GOAWAY_FRAME_TYPE_ID).unwrap();
1404        b.put_varint(0).unwrap();
1405
1406        let mut cursor = std::io::Cursor::new(d);
1407
1408        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
1409            .unwrap();
1410
1411        // Skip SETTINGS frame type.
1412        parse_skip_frame(&mut stream, &mut cursor).unwrap();
1413
1414        // Parse frame type.
1415        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1416        let frame_ty = stream.try_consume_varint().unwrap();
1417        assert_eq!(frame_ty, GOAWAY_FRAME_TYPE_ID);
1418
1419        stream.set_frame_type(frame_ty).unwrap();
1420        assert_eq!(stream.state, State::FramePayloadLen);
1421
1422        // Parse frame payload length.
1423        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1424        let frame_payload_len = stream.try_consume_varint().unwrap();
1425        assert_eq!(
1426            Err(Error::FrameError),
1427            stream.set_frame_payload_len(frame_payload_len)
1428        );
1429    }
1430
1431    #[test]
1432    fn zero_length_push_promise() {
1433        let mut d = vec![42; 128];
1434        let mut b = octets::OctetsMut::with_slice(&mut d);
1435
1436        let mut stream = <Stream>::new(0, false);
1437
1438        assert_eq!(stream.ty, Some(Type::Request));
1439        assert_eq!(stream.state, State::FrameType);
1440
1441        // Write a 0-length payload frame.
1442        b.put_varint(PUSH_PROMISE_FRAME_TYPE_ID).unwrap();
1443        b.put_varint(0).unwrap();
1444
1445        let mut cursor = std::io::Cursor::new(d);
1446
1447        // Parse frame type.
1448        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1449        let frame_ty = stream.try_consume_varint().unwrap();
1450        assert_eq!(frame_ty, PUSH_PROMISE_FRAME_TYPE_ID);
1451
1452        stream.set_frame_type(frame_ty).unwrap();
1453        assert_eq!(stream.state, State::FramePayloadLen);
1454
1455        // Parse frame payload length.
1456        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1457        let frame_payload_len = stream.try_consume_varint().unwrap();
1458        assert_eq!(
1459            Err(Error::FrameError),
1460            stream.set_frame_payload_len(frame_payload_len)
1461        );
1462    }
1463
1464    #[test]
1465    fn zero_length_cancel_push() {
1466        let mut d = vec![42; 128];
1467        let mut b = octets::OctetsMut::with_slice(&mut d);
1468
1469        let frame = Frame::Settings {
1470            max_field_section_size: None,
1471            qpack_max_table_capacity: None,
1472            qpack_blocked_streams: None,
1473            connect_protocol_enabled: None,
1474            h3_datagram: None,
1475            grease: None,
1476            additional_settings: None,
1477            raw: Some(vec![]),
1478        };
1479
1480        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
1481        frame.to_bytes(&mut b).unwrap();
1482
1483        // Write a 0-length payload frame.
1484        b.put_varint(CANCEL_PUSH_FRAME_TYPE_ID).unwrap();
1485        b.put_varint(0).unwrap();
1486
1487        let mut cursor = std::io::Cursor::new(d);
1488
1489        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
1490            .unwrap();
1491
1492        // Skip SETTINGS frame type.
1493        parse_skip_frame(&mut stream, &mut cursor).unwrap();
1494
1495        // Parse frame type.
1496        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1497        let frame_ty = stream.try_consume_varint().unwrap();
1498        assert_eq!(frame_ty, CANCEL_PUSH_FRAME_TYPE_ID);
1499
1500        stream.set_frame_type(frame_ty).unwrap();
1501        assert_eq!(stream.state, State::FramePayloadLen);
1502
1503        // Parse frame payload length.
1504        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1505        let frame_payload_len = stream.try_consume_varint().unwrap();
1506        assert_eq!(
1507            Err(Error::FrameError),
1508            stream.set_frame_payload_len(frame_payload_len)
1509        );
1510    }
1511
1512    #[test]
1513    fn zero_length_max_push_id() {
1514        let mut d = vec![42; 128];
1515        let mut b = octets::OctetsMut::with_slice(&mut d);
1516
1517        let frame = Frame::Settings {
1518            max_field_section_size: None,
1519            qpack_max_table_capacity: None,
1520            qpack_blocked_streams: None,
1521            connect_protocol_enabled: None,
1522            h3_datagram: None,
1523            grease: None,
1524            additional_settings: None,
1525            raw: Some(vec![]),
1526        };
1527
1528        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
1529        frame.to_bytes(&mut b).unwrap();
1530
1531        // Write a 0-length payload frame.
1532        b.put_varint(MAX_PUSH_FRAME_TYPE_ID).unwrap();
1533        b.put_varint(0).unwrap();
1534
1535        let mut cursor = std::io::Cursor::new(d);
1536
1537        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
1538            .unwrap();
1539
1540        // Skip SETTINGS frame type.
1541        parse_skip_frame(&mut stream, &mut cursor).unwrap();
1542
1543        // Parse frame type.
1544        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1545        let frame_ty = stream.try_consume_varint().unwrap();
1546        assert_eq!(frame_ty, MAX_PUSH_FRAME_TYPE_ID);
1547
1548        stream.set_frame_type(frame_ty).unwrap();
1549        assert_eq!(stream.state, State::FramePayloadLen);
1550
1551        // Parse frame payload length.
1552        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1553        let frame_payload_len = stream.try_consume_varint().unwrap();
1554        assert_eq!(
1555            Err(Error::FrameError),
1556            stream.set_frame_payload_len(frame_payload_len)
1557        );
1558    }
1559}