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                        (frame::PRIORITY_UPDATE_FRAME_REQUEST_TYPE_ID, _) =>
353                            return Err(Error::FrameUnexpected),
354
355                        (frame::PRIORITY_UPDATE_FRAME_PUSH_TYPE_ID, _) =>
356                            return Err(Error::FrameUnexpected),
357
358                        // All other frames can be ignored regardless of stream
359                        // state.
360                        _ => (),
361                    }
362                }
363            },
364
365            Some(Type::Push) => {
366                match ty {
367                    // Frames that can never be received on request streams.
368                    frame::CANCEL_PUSH_FRAME_TYPE_ID =>
369                        return Err(Error::FrameUnexpected),
370
371                    frame::SETTINGS_FRAME_TYPE_ID =>
372                        return Err(Error::FrameUnexpected),
373
374                    frame::PUSH_PROMISE_FRAME_TYPE_ID =>
375                        return Err(Error::FrameUnexpected),
376
377                    frame::GOAWAY_FRAME_TYPE_ID =>
378                        return Err(Error::FrameUnexpected),
379
380                    frame::MAX_PUSH_FRAME_TYPE_ID =>
381                        return Err(Error::FrameUnexpected),
382
383                    _ => (),
384                }
385            },
386
387            _ => return Err(Error::FrameUnexpected),
388        }
389
390        self.frame_type = Some(ty);
391
392        self.state_transition(State::FramePayloadLen, 1, true)?;
393
394        Ok(())
395    }
396
397    // Returns the stream's current frame type, if any
398    pub fn frame_type(&self) -> Option<u64> {
399        self.frame_type
400    }
401
402    /// Sets the frame's payload length and transitions to the next state.
403    pub fn set_frame_payload_len(&mut self, len: u64) -> Result<()> {
404        assert_eq!(self.state, State::FramePayloadLen);
405
406        // Only expect frames on Control, Request and Push streams.
407        if matches!(self.ty, Some(Type::Control | Type::Request | Type::Push)) {
408            let (state, resize) = match self.frame_type {
409                Some(frame::DATA_FRAME_TYPE_ID) => (State::Data, false),
410
411                // These frame types can never have 0 payload length because
412                // they always have fields that must be populated.
413                Some(
414                    frame::GOAWAY_FRAME_TYPE_ID |
415                    frame::PUSH_PROMISE_FRAME_TYPE_ID |
416                    frame::CANCEL_PUSH_FRAME_TYPE_ID |
417                    frame::MAX_PUSH_FRAME_TYPE_ID,
418                ) => {
419                    if len == 0 {
420                        return Err(Error::FrameError);
421                    }
422
423                    (State::FramePayload, true)
424                },
425
426                _ => (State::FramePayload, true),
427            };
428
429            self.state_transition(state, len as usize, resize)?;
430
431            return Ok(());
432        }
433
434        Err(Error::InternalError)
435    }
436
437    /// Tries to fill the state buffer by reading data from the corresponding
438    /// transport stream.
439    ///
440    /// When not enough data can be read to complete the state, this returns
441    /// `Error::Done`.
442    pub fn try_fill_buffer<F: BufFactory>(
443        &mut self, conn: &mut crate::Connection<F>,
444    ) -> Result<()> {
445        // If no bytes are required to be read, return early.
446        if self.state_buffer_complete() {
447            return Ok(());
448        }
449
450        let buf = &mut self.state_buf[self.state_off..self.state_len];
451
452        let read = match conn.stream_recv(self.id, buf) {
453            Ok((len, fin)) => {
454                // Check whether one of the critical stream was closed.
455                if fin &&
456                    matches!(
457                        self.ty,
458                        Some(Type::Control) |
459                            Some(Type::QpackEncoder) |
460                            Some(Type::QpackDecoder)
461                    )
462                {
463                    super::close_conn_critical_stream(conn)?;
464                }
465
466                len
467            },
468
469            Err(e @ crate::Error::StreamReset(_)) => {
470                // Check whether one of the critical stream was closed.
471                if matches!(
472                    self.ty,
473                    Some(Type::Control) |
474                        Some(Type::QpackEncoder) |
475                        Some(Type::QpackDecoder)
476                ) {
477                    super::close_conn_critical_stream(conn)?;
478                }
479
480                return Err(e.into());
481            },
482
483            Err(e) => {
484                // The stream is not readable anymore, so re-arm the Data event.
485                if e == crate::Error::Done {
486                    self.reset_data_event();
487                }
488
489                return Err(e.into());
490            },
491        };
492
493        trace!(
494            "{} read {} bytes on stream {}",
495            conn.trace_id(),
496            read,
497            self.id,
498        );
499
500        self.state_off += read;
501
502        if !self.state_buffer_complete() {
503            self.reset_data_event();
504
505            return Err(Error::Done);
506        }
507
508        Ok(())
509    }
510
511    /// Initialize the local part of the stream.
512    pub fn initialize_local(&mut self) {
513        self.local_initialized = true
514    }
515
516    /// Whether the stream has been locally initialized.
517    pub fn local_initialized(&self) -> bool {
518        self.local_initialized
519    }
520
521    pub fn increment_headers_received(&mut self) {
522        self.headers_received_count =
523            self.headers_received_count.saturating_add(1);
524    }
525
526    pub fn headers_received_count(&self) -> usize {
527        self.headers_received_count
528    }
529
530    pub fn mark_trailers_sent(&mut self) {
531        self.trailers_sent = true;
532    }
533
534    pub fn trailers_sent(&self) -> bool {
535        self.trailers_sent
536    }
537
538    /// Tries to fill the state buffer by reading data from the given cursor.
539    ///
540    /// This is intended to replace `try_fill_buffer()` in tests, in order to
541    /// avoid having to setup a transport connection.
542    #[cfg(test)]
543    fn try_fill_buffer_for_tests(
544        &mut self, stream: &mut std::io::Cursor<Vec<u8>>,
545    ) -> Result<()> {
546        // If no bytes are required to be read, return early
547        if self.state_buffer_complete() {
548            return Ok(());
549        }
550
551        let buf = &mut self.state_buf[self.state_off..self.state_len];
552
553        let read = std::io::Read::read(stream, buf).unwrap();
554
555        self.state_off += read;
556
557        if !self.state_buffer_complete() {
558            return Err(Error::Done);
559        }
560
561        Ok(())
562    }
563
564    /// Tries to parse a varint (including length) from the state buffer.
565    pub fn try_consume_varint(&mut self) -> Result<u64> {
566        if self.state_off == 1 {
567            self.state_len = octets::varint_parse_len(self.state_buf[0]);
568            self.state_buf.resize(self.state_len, 0);
569        }
570
571        // Return early if we don't have enough data in the state buffer to
572        // parse the whole varint.
573        if !self.state_buffer_complete() {
574            return Err(Error::Done);
575        }
576
577        let varint = octets::Octets::with_slice(&self.state_buf).get_varint()?;
578
579        Ok(varint)
580    }
581
582    /// Tries to parse a frame from the state buffer.
583    ///
584    /// If successful, returns the `frame::Frame` and the payload length.
585    pub fn try_consume_frame(&mut self) -> Result<(frame::Frame, u64)> {
586        // Processing a frame other than DATA, so re-arm the Data event.
587        self.reset_data_event();
588
589        let payload_len = self.state_len as u64;
590
591        // TODO: properly propagate frame parsing errors.
592        let frame = frame::Frame::from_bytes(
593            self.frame_type.unwrap(),
594            payload_len,
595            &self.state_buf,
596        )?;
597
598        self.state_transition(State::FrameType, 1, true)?;
599
600        Ok((frame, payload_len))
601    }
602
603    /// Tries to read DATA payload from the transport stream.
604    pub fn try_consume_data<F: BufFactory>(
605        &mut self, conn: &mut crate::Connection<F>, out: &mut [u8],
606    ) -> Result<(usize, bool)> {
607        let left = std::cmp::min(out.len(), self.state_len - self.state_off);
608
609        let (len, fin) = match conn.stream_recv(self.id, &mut out[..left]) {
610            Ok(v) => v,
611
612            Err(e) => {
613                // The stream is not readable anymore, so re-arm the Data event.
614                if e == crate::Error::Done {
615                    self.reset_data_event();
616                }
617
618                return Err(e.into());
619            },
620        };
621
622        self.state_off += len;
623
624        // The stream is not readable anymore, so re-arm the Data event.
625        if !conn.stream_readable(self.id) {
626            self.reset_data_event();
627        }
628
629        if self.state_buffer_complete() {
630            self.state_transition(State::FrameType, 1, true)?;
631        }
632
633        Ok((len, fin))
634    }
635
636    /// Marks the stream as finished.
637    pub fn finished(&mut self) {
638        let _ = self.state_transition(State::Finished, 0, false);
639    }
640
641    /// Tries to read DATA payload from the given cursor.
642    ///
643    /// This is intended to replace `try_consume_data()` in tests, in order to
644    /// avoid having to setup a transport connection.
645    #[cfg(test)]
646    fn try_consume_data_for_tests(
647        &mut self, stream: &mut std::io::Cursor<Vec<u8>>, out: &mut [u8],
648    ) -> Result<usize> {
649        let left = std::cmp::min(out.len(), self.state_len - self.state_off);
650
651        let len = std::io::Read::read(stream, &mut out[..left]).unwrap();
652
653        self.state_off += len;
654
655        if self.state_buffer_complete() {
656            self.state_transition(State::FrameType, 1, true)?;
657        }
658
659        Ok(len)
660    }
661
662    /// Tries to update the data triggered state for the stream.
663    ///
664    /// This returns `true` if a Data event was not already triggered before
665    /// the last reset, and updates the state. Returns `false` otherwise.
666    pub fn try_trigger_data_event(&mut self) -> bool {
667        if self.data_event_triggered {
668            return false;
669        }
670
671        self.data_event_triggered = true;
672
673        true
674    }
675
676    /// Resets the data triggered state.
677    fn reset_data_event(&mut self) {
678        self.data_event_triggered = false;
679    }
680
681    /// Set the last priority update for the stream.
682    pub fn set_last_priority_update(&mut self, priority_update: Option<Vec<u8>>) {
683        self.last_priority_update = priority_update;
684    }
685
686    /// Take the last priority update and leave `None` in its place.
687    pub fn take_last_priority_update(&mut self) -> Option<Vec<u8>> {
688        self.last_priority_update.take()
689    }
690
691    /// Returns `true` if there is a priority update.
692    pub fn has_last_priority_update(&self) -> bool {
693        self.last_priority_update.is_some()
694    }
695
696    /// Returns true if the state buffer has enough data to complete the state.
697    fn state_buffer_complete(&self) -> bool {
698        self.state_off == self.state_len
699    }
700
701    /// Transitions the stream to a new state, and optionally resets the state
702    /// buffer.
703    fn state_transition(
704        &mut self, new_state: State, expected_len: usize, resize: bool,
705    ) -> Result<()> {
706        // Some states don't need the state buffer, so don't resize it if not
707        // necessary.
708        if resize {
709            // A peer can influence the size of the state buffer (e.g. with the
710            // payload size of a GREASE frame), so we need to limit the maximum
711            // size to avoid DoS.
712            if expected_len > MAX_STATE_BUF_SIZE {
713                return Err(Error::ExcessiveLoad);
714            }
715
716            self.state_buf.resize(expected_len, 0);
717        }
718
719        self.state = new_state;
720        self.state_off = 0;
721        self.state_len = expected_len;
722
723        Ok(())
724    }
725}
726
727#[cfg(test)]
728mod tests {
729    use crate::h3::frame::*;
730
731    use super::*;
732
733    fn open_uni(b: &mut octets::OctetsMut, ty: u64) -> Result<Stream> {
734        let stream = <Stream>::new(2, false);
735        assert_eq!(stream.state, State::StreamType);
736
737        b.put_varint(ty)?;
738
739        Ok(stream)
740    }
741
742    fn parse_uni(
743        stream: &mut Stream, ty: u64, cursor: &mut std::io::Cursor<Vec<u8>>,
744    ) -> Result<()> {
745        stream.try_fill_buffer_for_tests(cursor)?;
746
747        let stream_ty = stream.try_consume_varint()?;
748        assert_eq!(stream_ty, ty);
749        stream.set_ty(Type::deserialize(stream_ty).unwrap())?;
750
751        Ok(())
752    }
753
754    fn parse_skip_frame(
755        stream: &mut Stream, cursor: &mut std::io::Cursor<Vec<u8>>,
756    ) -> Result<()> {
757        // Parse the frame type.
758        stream.try_fill_buffer_for_tests(cursor)?;
759
760        let frame_ty = stream.try_consume_varint()?;
761
762        stream.set_frame_type(frame_ty)?;
763        assert_eq!(stream.state, State::FramePayloadLen);
764
765        // Parse the frame payload length.
766        stream.try_fill_buffer_for_tests(cursor)?;
767
768        let frame_payload_len = stream.try_consume_varint()?;
769        stream.set_frame_payload_len(frame_payload_len)?;
770        assert_eq!(stream.state, State::FramePayload);
771
772        // Parse the frame payload.
773        stream.try_fill_buffer_for_tests(cursor)?;
774
775        stream.try_consume_frame()?;
776        assert_eq!(stream.state, State::FrameType);
777
778        Ok(())
779    }
780
781    #[test]
782    /// Process incoming SETTINGS frame on control stream.
783    fn control_good() {
784        let mut d = vec![42; 40];
785        let mut b = octets::OctetsMut::with_slice(&mut d);
786
787        let raw_settings = vec![
788            (SETTINGS_MAX_FIELD_SECTION_SIZE, 0),
789            (SETTINGS_QPACK_MAX_TABLE_CAPACITY, 0),
790            (SETTINGS_QPACK_BLOCKED_STREAMS, 0),
791        ];
792
793        let frame = Frame::Settings {
794            max_field_section_size: Some(0),
795            qpack_max_table_capacity: Some(0),
796            qpack_blocked_streams: Some(0),
797            connect_protocol_enabled: None,
798            h3_datagram: None,
799            grease: None,
800            additional_settings: None,
801            raw: Some(raw_settings),
802        };
803
804        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
805        frame.to_bytes(&mut b).unwrap();
806
807        let mut cursor = std::io::Cursor::new(d);
808
809        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
810            .unwrap();
811        assert_eq!(stream.state, State::FrameType);
812
813        // Parse the SETTINGS frame type.
814        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
815
816        let frame_ty = stream.try_consume_varint().unwrap();
817        assert_eq!(frame_ty, SETTINGS_FRAME_TYPE_ID);
818
819        stream.set_frame_type(frame_ty).unwrap();
820        assert_eq!(stream.state, State::FramePayloadLen);
821
822        // Parse the SETTINGS frame payload length.
823        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
824
825        let frame_payload_len = stream.try_consume_varint().unwrap();
826        assert_eq!(frame_payload_len, 6);
827        stream.set_frame_payload_len(frame_payload_len).unwrap();
828        assert_eq!(stream.state, State::FramePayload);
829
830        // Parse the SETTINGS frame payload.
831        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
832
833        assert_eq!(stream.try_consume_frame(), Ok((frame, 6)));
834        assert_eq!(stream.state, State::FrameType);
835    }
836
837    #[test]
838    /// Process incoming empty SETTINGS frame on control stream.
839    fn control_empty_settings() {
840        let mut d = vec![42; 40];
841        let mut b = octets::OctetsMut::with_slice(&mut d);
842
843        let frame = Frame::Settings {
844            max_field_section_size: None,
845            qpack_max_table_capacity: None,
846            qpack_blocked_streams: None,
847            connect_protocol_enabled: None,
848            h3_datagram: None,
849            grease: None,
850            additional_settings: None,
851            raw: Some(vec![]),
852        };
853
854        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
855        frame.to_bytes(&mut b).unwrap();
856
857        let mut cursor = std::io::Cursor::new(d);
858
859        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
860            .unwrap();
861        assert_eq!(stream.state, State::FrameType);
862
863        // Parse the SETTINGS frame type.
864        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
865
866        let frame_ty = stream.try_consume_varint().unwrap();
867        assert_eq!(frame_ty, SETTINGS_FRAME_TYPE_ID);
868
869        stream.set_frame_type(frame_ty).unwrap();
870        assert_eq!(stream.state, State::FramePayloadLen);
871
872        // Parse the SETTINGS frame payload length.
873        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
874
875        let frame_payload_len = stream.try_consume_varint().unwrap();
876        assert_eq!(frame_payload_len, 0);
877        stream.set_frame_payload_len(frame_payload_len).unwrap();
878        assert_eq!(stream.state, State::FramePayload);
879
880        // Parse the SETTINGS frame payload.
881        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
882
883        assert_eq!(stream.try_consume_frame(), Ok((frame, 0)));
884        assert_eq!(stream.state, State::FrameType);
885    }
886
887    #[test]
888    /// Process duplicate SETTINGS frame on control stream.
889    fn control_bad_multiple_settings() {
890        let mut d = vec![42; 40];
891        let mut b = octets::OctetsMut::with_slice(&mut d);
892
893        let raw_settings = vec![
894            (SETTINGS_MAX_FIELD_SECTION_SIZE, 0),
895            (SETTINGS_QPACK_MAX_TABLE_CAPACITY, 0),
896            (SETTINGS_QPACK_BLOCKED_STREAMS, 0),
897        ];
898
899        let frame = Frame::Settings {
900            max_field_section_size: Some(0),
901            qpack_max_table_capacity: Some(0),
902            qpack_blocked_streams: Some(0),
903            connect_protocol_enabled: None,
904            h3_datagram: None,
905            grease: None,
906            additional_settings: None,
907            raw: Some(raw_settings),
908        };
909
910        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
911        frame.to_bytes(&mut b).unwrap();
912        frame.to_bytes(&mut b).unwrap();
913
914        let mut cursor = std::io::Cursor::new(d);
915
916        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
917            .unwrap();
918        assert_eq!(stream.state, State::FrameType);
919
920        // Parse the SETTINGS frame type.
921        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
922
923        let frame_ty = stream.try_consume_varint().unwrap();
924        assert_eq!(frame_ty, SETTINGS_FRAME_TYPE_ID);
925
926        stream.set_frame_type(frame_ty).unwrap();
927        assert_eq!(stream.state, State::FramePayloadLen);
928
929        // Parse the SETTINGS frame payload length.
930        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
931
932        let frame_payload_len = stream.try_consume_varint().unwrap();
933        assert_eq!(frame_payload_len, 6);
934        stream.set_frame_payload_len(frame_payload_len).unwrap();
935        assert_eq!(stream.state, State::FramePayload);
936
937        // Parse the SETTINGS frame payload.
938        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
939
940        assert_eq!(stream.try_consume_frame(), Ok((frame, 6)));
941        assert_eq!(stream.state, State::FrameType);
942
943        // Parse the second SETTINGS frame type.
944        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
945
946        let frame_ty = stream.try_consume_varint().unwrap();
947        assert_eq!(stream.set_frame_type(frame_ty), Err(Error::FrameUnexpected));
948    }
949
950    #[test]
951    /// Process other frame before SETTINGS frame on control stream.
952    fn control_bad_late_settings() {
953        let mut d = vec![42; 40];
954        let mut b = octets::OctetsMut::with_slice(&mut d);
955
956        let goaway = Frame::GoAway { id: 0 };
957
958        let raw_settings = vec![
959            (SETTINGS_MAX_FIELD_SECTION_SIZE, 0),
960            (SETTINGS_QPACK_MAX_TABLE_CAPACITY, 0),
961            (SETTINGS_QPACK_BLOCKED_STREAMS, 0),
962        ];
963
964        let settings = Frame::Settings {
965            max_field_section_size: Some(0),
966            qpack_max_table_capacity: Some(0),
967            qpack_blocked_streams: Some(0),
968            connect_protocol_enabled: None,
969            h3_datagram: None,
970            grease: None,
971            additional_settings: None,
972            raw: Some(raw_settings),
973        };
974
975        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
976        goaway.to_bytes(&mut b).unwrap();
977        settings.to_bytes(&mut b).unwrap();
978
979        let mut cursor = std::io::Cursor::new(d);
980
981        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
982            .unwrap();
983        assert_eq!(stream.state, State::FrameType);
984
985        // Parse GOAWAY.
986        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
987
988        let frame_ty = stream.try_consume_varint().unwrap();
989        assert_eq!(stream.set_frame_type(frame_ty), Err(Error::MissingSettings));
990    }
991
992    #[test]
993    /// Process not-allowed frame on control stream.
994    fn control_bad_frame() {
995        let mut d = vec![42; 40];
996        let mut b = octets::OctetsMut::with_slice(&mut d);
997
998        let header_block = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
999        let hdrs = Frame::Headers { header_block };
1000
1001        let raw_settings = vec![
1002            (SETTINGS_MAX_FIELD_SECTION_SIZE, 0),
1003            (SETTINGS_QPACK_MAX_TABLE_CAPACITY, 0),
1004            (SETTINGS_QPACK_BLOCKED_STREAMS, 0),
1005            (33, 33),
1006        ];
1007
1008        let settings = Frame::Settings {
1009            max_field_section_size: Some(0),
1010            qpack_max_table_capacity: Some(0),
1011            qpack_blocked_streams: Some(0),
1012            connect_protocol_enabled: None,
1013            h3_datagram: None,
1014            grease: None,
1015            additional_settings: None,
1016            raw: Some(raw_settings),
1017        };
1018
1019        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
1020        settings.to_bytes(&mut b).unwrap();
1021        hdrs.to_bytes(&mut b).unwrap();
1022
1023        let mut cursor = std::io::Cursor::new(d);
1024
1025        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
1026            .unwrap();
1027        assert_eq!(stream.state, State::FrameType);
1028
1029        // Parse first SETTINGS frame.
1030        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1031
1032        let frame_ty = stream.try_consume_varint().unwrap();
1033        stream.set_frame_type(frame_ty).unwrap();
1034
1035        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1036
1037        let frame_payload_len = stream.try_consume_varint().unwrap();
1038        stream.set_frame_payload_len(frame_payload_len).unwrap();
1039
1040        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1041
1042        assert!(stream.try_consume_frame().is_ok());
1043
1044        // Parse HEADERS.
1045        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1046
1047        let frame_ty = stream.try_consume_varint().unwrap();
1048        assert_eq!(stream.set_frame_type(frame_ty), Err(Error::FrameUnexpected));
1049    }
1050
1051    #[test]
1052    fn request_no_data() {
1053        let mut stream = <Stream>::new(0, false);
1054
1055        assert_eq!(stream.ty, Some(Type::Request));
1056        assert_eq!(stream.state, State::FrameType);
1057
1058        assert_eq!(stream.try_consume_varint(), Err(Error::Done));
1059    }
1060
1061    #[test]
1062    fn request_good() {
1063        let mut stream = <Stream>::new(0, false);
1064
1065        let mut d = vec![42; 128];
1066        let mut b = octets::OctetsMut::with_slice(&mut d);
1067
1068        let header_block = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
1069        let payload = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
1070        let hdrs = Frame::Headers { header_block };
1071        let data = Frame::Data {
1072            payload: payload.clone(),
1073        };
1074
1075        hdrs.to_bytes(&mut b).unwrap();
1076        data.to_bytes(&mut b).unwrap();
1077
1078        let mut cursor = std::io::Cursor::new(d);
1079
1080        // Parse the HEADERS frame type.
1081        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1082
1083        let frame_ty = stream.try_consume_varint().unwrap();
1084        assert_eq!(frame_ty, HEADERS_FRAME_TYPE_ID);
1085
1086        stream.set_frame_type(frame_ty).unwrap();
1087        assert_eq!(stream.state, State::FramePayloadLen);
1088
1089        // Parse the HEADERS frame payload length.
1090        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1091
1092        let frame_payload_len = stream.try_consume_varint().unwrap();
1093        assert_eq!(frame_payload_len, 12);
1094
1095        stream.set_frame_payload_len(frame_payload_len).unwrap();
1096        assert_eq!(stream.state, State::FramePayload);
1097
1098        // Parse the HEADERS frame.
1099        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1100
1101        assert_eq!(stream.try_consume_frame(), Ok((hdrs, 12)));
1102        assert_eq!(stream.state, State::FrameType);
1103
1104        // Parse the DATA frame type.
1105        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1106
1107        let frame_ty = stream.try_consume_varint().unwrap();
1108        assert_eq!(frame_ty, DATA_FRAME_TYPE_ID);
1109
1110        stream.set_frame_type(frame_ty).unwrap();
1111        assert_eq!(stream.state, State::FramePayloadLen);
1112
1113        // Parse the DATA frame payload length.
1114        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1115
1116        let frame_payload_len = stream.try_consume_varint().unwrap();
1117        assert_eq!(frame_payload_len, 12);
1118
1119        stream.set_frame_payload_len(frame_payload_len).unwrap();
1120        assert_eq!(stream.state, State::Data);
1121
1122        // Parse the DATA payload.
1123        let mut recv_buf = vec![0; payload.len()];
1124        assert_eq!(
1125            stream.try_consume_data_for_tests(&mut cursor, &mut recv_buf),
1126            Ok(payload.len())
1127        );
1128        assert_eq!(payload, recv_buf);
1129
1130        assert_eq!(stream.state, State::FrameType);
1131    }
1132
1133    #[test]
1134    fn push_good() {
1135        let mut d = vec![42; 128];
1136        let mut b = octets::OctetsMut::with_slice(&mut d);
1137
1138        let header_block = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
1139        let payload = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
1140        let hdrs = Frame::Headers { header_block };
1141        let data = Frame::Data {
1142            payload: payload.clone(),
1143        };
1144
1145        let mut stream = open_uni(&mut b, HTTP3_PUSH_STREAM_TYPE_ID).unwrap();
1146        b.put_varint(1).unwrap();
1147        hdrs.to_bytes(&mut b).unwrap();
1148        data.to_bytes(&mut b).unwrap();
1149
1150        let mut cursor = std::io::Cursor::new(d);
1151
1152        parse_uni(&mut stream, HTTP3_PUSH_STREAM_TYPE_ID, &mut cursor).unwrap();
1153        assert_eq!(stream.state, State::PushId);
1154
1155        // Parse push ID.
1156        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1157
1158        let push_id = stream.try_consume_varint().unwrap();
1159        assert_eq!(push_id, 1);
1160
1161        stream.set_push_id(push_id).unwrap();
1162        assert_eq!(stream.state, State::FrameType);
1163
1164        // Parse the HEADERS frame type.
1165        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1166
1167        let frame_ty = stream.try_consume_varint().unwrap();
1168        assert_eq!(frame_ty, HEADERS_FRAME_TYPE_ID);
1169
1170        stream.set_frame_type(frame_ty).unwrap();
1171        assert_eq!(stream.state, State::FramePayloadLen);
1172
1173        // Parse the HEADERS frame payload length.
1174        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1175
1176        let frame_payload_len = stream.try_consume_varint().unwrap();
1177        assert_eq!(frame_payload_len, 12);
1178
1179        stream.set_frame_payload_len(frame_payload_len).unwrap();
1180        assert_eq!(stream.state, State::FramePayload);
1181
1182        // Parse the HEADERS frame.
1183        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1184
1185        assert_eq!(stream.try_consume_frame(), Ok((hdrs, 12)));
1186        assert_eq!(stream.state, State::FrameType);
1187
1188        // Parse the DATA frame type.
1189        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1190
1191        let frame_ty = stream.try_consume_varint().unwrap();
1192        assert_eq!(frame_ty, DATA_FRAME_TYPE_ID);
1193
1194        stream.set_frame_type(frame_ty).unwrap();
1195        assert_eq!(stream.state, State::FramePayloadLen);
1196
1197        // Parse the DATA frame payload length.
1198        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1199
1200        let frame_payload_len = stream.try_consume_varint().unwrap();
1201        assert_eq!(frame_payload_len, 12);
1202
1203        stream.set_frame_payload_len(frame_payload_len).unwrap();
1204        assert_eq!(stream.state, State::Data);
1205
1206        // Parse the DATA payload.
1207        let mut recv_buf = vec![0; payload.len()];
1208        assert_eq!(
1209            stream.try_consume_data_for_tests(&mut cursor, &mut recv_buf),
1210            Ok(payload.len())
1211        );
1212        assert_eq!(payload, recv_buf);
1213
1214        assert_eq!(stream.state, State::FrameType);
1215    }
1216
1217    #[test]
1218    fn grease() {
1219        let mut d = vec![42; 20];
1220        let mut b = octets::OctetsMut::with_slice(&mut d);
1221
1222        let mut stream = open_uni(&mut b, 33).unwrap();
1223
1224        let mut cursor = std::io::Cursor::new(d);
1225
1226        // Parse stream type.
1227        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1228
1229        let stream_ty = stream.try_consume_varint().unwrap();
1230        assert_eq!(stream_ty, 33);
1231        stream
1232            .set_ty(Type::deserialize(stream_ty).unwrap())
1233            .unwrap();
1234        assert_eq!(stream.state, State::Drain);
1235    }
1236
1237    #[test]
1238    fn data_before_headers() {
1239        let mut stream = <Stream>::new(0, false);
1240
1241        let mut d = vec![42; 128];
1242        let mut b = octets::OctetsMut::with_slice(&mut d);
1243
1244        let data = Frame::Data {
1245            payload: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
1246        };
1247
1248        data.to_bytes(&mut b).unwrap();
1249
1250        let mut cursor = std::io::Cursor::new(d);
1251
1252        // Parse the DATA frame type.
1253        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1254
1255        let frame_ty = stream.try_consume_varint().unwrap();
1256        assert_eq!(frame_ty, DATA_FRAME_TYPE_ID);
1257
1258        assert_eq!(stream.set_frame_type(frame_ty), Err(Error::FrameUnexpected));
1259    }
1260
1261    #[test]
1262    fn additional_headers() {
1263        let mut stream = Stream::new(0, false);
1264
1265        let mut d = vec![42; 128];
1266        let mut b = octets::OctetsMut::with_slice(&mut d);
1267
1268        let header_block = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
1269        let payload = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
1270        let info_hdrs = Frame::Headers {
1271            header_block: header_block.clone(),
1272        };
1273        let non_info_hdrs = Frame::Headers {
1274            header_block: header_block.clone(),
1275        };
1276        let trailers = Frame::Headers { header_block };
1277        let data = Frame::Data {
1278            payload: payload.clone(),
1279        };
1280
1281        info_hdrs.to_bytes(&mut b).unwrap();
1282        non_info_hdrs.to_bytes(&mut b).unwrap();
1283        data.to_bytes(&mut b).unwrap();
1284        trailers.to_bytes(&mut b).unwrap();
1285
1286        let mut cursor = std::io::Cursor::new(d);
1287
1288        // Parse the HEADERS frame type.
1289        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1290
1291        let frame_ty = stream.try_consume_varint().unwrap();
1292        assert_eq!(frame_ty, HEADERS_FRAME_TYPE_ID);
1293
1294        stream.set_frame_type(frame_ty).unwrap();
1295        assert_eq!(stream.state, State::FramePayloadLen);
1296
1297        // Parse the HEADERS frame payload length.
1298        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1299
1300        let frame_payload_len = stream.try_consume_varint().unwrap();
1301        assert_eq!(frame_payload_len, 12);
1302
1303        stream.set_frame_payload_len(frame_payload_len).unwrap();
1304        assert_eq!(stream.state, State::FramePayload);
1305
1306        // Parse the HEADERS frame.
1307        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1308
1309        assert_eq!(stream.try_consume_frame(), Ok((info_hdrs, 12)));
1310        assert_eq!(stream.state, State::FrameType);
1311
1312        // Parse the non-info HEADERS frame type.
1313        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1314
1315        let frame_ty = stream.try_consume_varint().unwrap();
1316        assert_eq!(frame_ty, HEADERS_FRAME_TYPE_ID);
1317
1318        stream.set_frame_type(frame_ty).unwrap();
1319        assert_eq!(stream.state, State::FramePayloadLen);
1320
1321        // Parse the HEADERS frame payload length.
1322        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1323
1324        let frame_payload_len = stream.try_consume_varint().unwrap();
1325        assert_eq!(frame_payload_len, 12);
1326
1327        stream.set_frame_payload_len(frame_payload_len).unwrap();
1328        assert_eq!(stream.state, State::FramePayload);
1329
1330        // Parse the HEADERS frame.
1331        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1332
1333        assert_eq!(stream.try_consume_frame(), Ok((non_info_hdrs, 12)));
1334        assert_eq!(stream.state, State::FrameType);
1335
1336        // Parse the DATA frame type.
1337        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1338
1339        let frame_ty = stream.try_consume_varint().unwrap();
1340        assert_eq!(frame_ty, DATA_FRAME_TYPE_ID);
1341
1342        stream.set_frame_type(frame_ty).unwrap();
1343        assert_eq!(stream.state, State::FramePayloadLen);
1344
1345        // Parse the DATA frame payload length.
1346        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1347
1348        let frame_payload_len = stream.try_consume_varint().unwrap();
1349        assert_eq!(frame_payload_len, 12);
1350
1351        stream.set_frame_payload_len(frame_payload_len).unwrap();
1352        assert_eq!(stream.state, State::Data);
1353
1354        // Parse the DATA payload.
1355        let mut recv_buf = vec![0; payload.len()];
1356        assert_eq!(
1357            stream.try_consume_data_for_tests(&mut cursor, &mut recv_buf),
1358            Ok(payload.len())
1359        );
1360        assert_eq!(payload, recv_buf);
1361
1362        assert_eq!(stream.state, State::FrameType);
1363
1364        // Parse the trailing HEADERS frame type.
1365        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1366
1367        let frame_ty = stream.try_consume_varint().unwrap();
1368        assert_eq!(frame_ty, HEADERS_FRAME_TYPE_ID);
1369
1370        stream.set_frame_type(frame_ty).unwrap();
1371        assert_eq!(stream.state, State::FramePayloadLen);
1372
1373        // Parse the HEADERS frame payload length.
1374        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1375
1376        let frame_payload_len = stream.try_consume_varint().unwrap();
1377        assert_eq!(frame_payload_len, 12);
1378
1379        stream.set_frame_payload_len(frame_payload_len).unwrap();
1380        assert_eq!(stream.state, State::FramePayload);
1381
1382        // Parse the HEADERS frame.
1383        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1384
1385        assert_eq!(stream.try_consume_frame(), Ok((trailers, 12)));
1386        assert_eq!(stream.state, State::FrameType);
1387    }
1388
1389    #[test]
1390    fn zero_length_goaway() {
1391        let mut d = vec![42; 128];
1392        let mut b = octets::OctetsMut::with_slice(&mut d);
1393
1394        let frame = Frame::Settings {
1395            max_field_section_size: None,
1396            qpack_max_table_capacity: None,
1397            qpack_blocked_streams: None,
1398            connect_protocol_enabled: None,
1399            h3_datagram: None,
1400            grease: None,
1401            additional_settings: None,
1402            raw: Some(vec![]),
1403        };
1404
1405        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
1406        frame.to_bytes(&mut b).unwrap();
1407
1408        // Write a 0-length payload frame.
1409        b.put_varint(GOAWAY_FRAME_TYPE_ID).unwrap();
1410        b.put_varint(0).unwrap();
1411
1412        let mut cursor = std::io::Cursor::new(d);
1413
1414        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
1415            .unwrap();
1416
1417        // Skip SETTINGS frame type.
1418        parse_skip_frame(&mut stream, &mut cursor).unwrap();
1419
1420        // Parse frame type.
1421        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1422        let frame_ty = stream.try_consume_varint().unwrap();
1423        assert_eq!(frame_ty, GOAWAY_FRAME_TYPE_ID);
1424
1425        stream.set_frame_type(frame_ty).unwrap();
1426        assert_eq!(stream.state, State::FramePayloadLen);
1427
1428        // Parse frame payload length.
1429        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1430        let frame_payload_len = stream.try_consume_varint().unwrap();
1431        assert_eq!(
1432            Err(Error::FrameError),
1433            stream.set_frame_payload_len(frame_payload_len)
1434        );
1435    }
1436
1437    #[test]
1438    fn zero_length_push_promise() {
1439        let mut d = vec![42; 128];
1440        let mut b = octets::OctetsMut::with_slice(&mut d);
1441
1442        let mut stream = <Stream>::new(0, false);
1443
1444        assert_eq!(stream.ty, Some(Type::Request));
1445        assert_eq!(stream.state, State::FrameType);
1446
1447        // Write a 0-length payload frame.
1448        b.put_varint(PUSH_PROMISE_FRAME_TYPE_ID).unwrap();
1449        b.put_varint(0).unwrap();
1450
1451        let mut cursor = std::io::Cursor::new(d);
1452
1453        // Parse frame type.
1454        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1455        let frame_ty = stream.try_consume_varint().unwrap();
1456        assert_eq!(frame_ty, PUSH_PROMISE_FRAME_TYPE_ID);
1457
1458        stream.set_frame_type(frame_ty).unwrap();
1459        assert_eq!(stream.state, State::FramePayloadLen);
1460
1461        // Parse frame payload length.
1462        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1463        let frame_payload_len = stream.try_consume_varint().unwrap();
1464        assert_eq!(
1465            Err(Error::FrameError),
1466            stream.set_frame_payload_len(frame_payload_len)
1467        );
1468    }
1469
1470    #[test]
1471    fn zero_length_cancel_push() {
1472        let mut d = vec![42; 128];
1473        let mut b = octets::OctetsMut::with_slice(&mut d);
1474
1475        let frame = Frame::Settings {
1476            max_field_section_size: None,
1477            qpack_max_table_capacity: None,
1478            qpack_blocked_streams: None,
1479            connect_protocol_enabled: None,
1480            h3_datagram: None,
1481            grease: None,
1482            additional_settings: None,
1483            raw: Some(vec![]),
1484        };
1485
1486        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
1487        frame.to_bytes(&mut b).unwrap();
1488
1489        // Write a 0-length payload frame.
1490        b.put_varint(CANCEL_PUSH_FRAME_TYPE_ID).unwrap();
1491        b.put_varint(0).unwrap();
1492
1493        let mut cursor = std::io::Cursor::new(d);
1494
1495        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
1496            .unwrap();
1497
1498        // Skip SETTINGS frame type.
1499        parse_skip_frame(&mut stream, &mut cursor).unwrap();
1500
1501        // Parse frame type.
1502        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1503        let frame_ty = stream.try_consume_varint().unwrap();
1504        assert_eq!(frame_ty, CANCEL_PUSH_FRAME_TYPE_ID);
1505
1506        stream.set_frame_type(frame_ty).unwrap();
1507        assert_eq!(stream.state, State::FramePayloadLen);
1508
1509        // Parse frame payload length.
1510        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1511        let frame_payload_len = stream.try_consume_varint().unwrap();
1512        assert_eq!(
1513            Err(Error::FrameError),
1514            stream.set_frame_payload_len(frame_payload_len)
1515        );
1516    }
1517
1518    #[test]
1519    fn zero_length_max_push_id() {
1520        let mut d = vec![42; 128];
1521        let mut b = octets::OctetsMut::with_slice(&mut d);
1522
1523        let frame = Frame::Settings {
1524            max_field_section_size: None,
1525            qpack_max_table_capacity: None,
1526            qpack_blocked_streams: None,
1527            connect_protocol_enabled: None,
1528            h3_datagram: None,
1529            grease: None,
1530            additional_settings: None,
1531            raw: Some(vec![]),
1532        };
1533
1534        let mut stream = open_uni(&mut b, HTTP3_CONTROL_STREAM_TYPE_ID).unwrap();
1535        frame.to_bytes(&mut b).unwrap();
1536
1537        // Write a 0-length payload frame.
1538        b.put_varint(MAX_PUSH_FRAME_TYPE_ID).unwrap();
1539        b.put_varint(0).unwrap();
1540
1541        let mut cursor = std::io::Cursor::new(d);
1542
1543        parse_uni(&mut stream, HTTP3_CONTROL_STREAM_TYPE_ID, &mut cursor)
1544            .unwrap();
1545
1546        // Skip SETTINGS frame type.
1547        parse_skip_frame(&mut stream, &mut cursor).unwrap();
1548
1549        // Parse frame type.
1550        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1551        let frame_ty = stream.try_consume_varint().unwrap();
1552        assert_eq!(frame_ty, MAX_PUSH_FRAME_TYPE_ID);
1553
1554        stream.set_frame_type(frame_ty).unwrap();
1555        assert_eq!(stream.state, State::FramePayloadLen);
1556
1557        // Parse frame payload length.
1558        stream.try_fill_buffer_for_tests(&mut cursor).unwrap();
1559        let frame_payload_len = stream.try_consume_varint().unwrap();
1560        assert_eq!(
1561            Err(Error::FrameError),
1562            stream.set_frame_payload_len(frame_payload_len)
1563        );
1564    }
1565}