rustls/msgs/
deframer.rs

1use alloc::vec::Vec;
2use core::ops::Range;
3use std::io;
4
5use super::base::Payload;
6use super::codec::Codec;
7use super::message::PlainMessage;
8use crate::enums::{ContentType, ProtocolVersion};
9use crate::error::{Error, InvalidMessage, PeerMisbehaved};
10use crate::msgs::codec;
11use crate::msgs::message::{MessageError, OpaqueMessage};
12use crate::record_layer::{Decrypted, RecordLayer};
13
14/// This deframer works to reconstruct TLS messages from a stream of arbitrary-sized reads.
15///
16/// It buffers incoming data into a `Vec` through `read()`, and returns messages through `pop()`.
17/// QUIC connections will call `push()` to append handshake payload data directly.
18#[derive(Default)]
19pub struct MessageDeframer {
20    /// Set if the peer is not talking TLS, but some other
21    /// protocol.  The caller should abort the connection, because
22    /// the deframer cannot recover.
23    last_error: Option<Error>,
24
25    /// Buffer of data read from the socket, in the process of being parsed into messages.
26    ///
27    /// For buffer size management, checkout out the `read()` method.
28    buf: Vec<u8>,
29
30    /// If we're in the middle of joining a handshake payload, this is the metadata.
31    joining_hs: Option<HandshakePayloadMeta>,
32
33    /// What size prefix of `buf` is used.
34    used: usize,
35}
36
37impl MessageDeframer {
38    /// Return any decrypted messages that the deframer has been able to parse.
39    ///
40    /// Returns an `Error` if the deframer failed to parse some message contents or if decryption
41    /// failed, `Ok(None)` if no full message is buffered or if trial decryption failed, and
42    /// `Ok(Some(_))` if a valid message was found and decrypted successfully.
43    pub fn pop(
44        &mut self,
45        record_layer: &mut RecordLayer,
46        negotiated_version: Option<ProtocolVersion>,
47    ) -> Result<Option<Deframed>, Error> {
48        if let Some(last_err) = self.last_error.clone() {
49            return Err(last_err);
50        } else if self.used == 0 {
51            return Ok(None);
52        }
53
54        // We loop over records we've received but not processed yet.
55        // For records that decrypt as `Handshake`, we keep the current state of the joined
56        // handshake message payload in `self.joining_hs`, appending to it as we see records.
57        let expected_len = loop {
58            let start = match &self.joining_hs {
59                Some(meta) => {
60                    match meta.expected_len {
61                        // We're joining a handshake payload, and we've seen the full payload.
62                        Some(len) if len <= meta.payload.len() => break len,
63                        // Not enough data, and we can't parse any more out of the buffer (QUIC).
64                        _ if meta.quic => return Ok(None),
65                        // Try parsing some more of the encrypted buffered data.
66                        _ => meta.message.end,
67                    }
68                }
69                None => 0,
70            };
71
72            // Does our `buf` contain a full message?  It does if it is big enough to
73            // contain a header, and that header has a length which falls within `buf`.
74            // If so, deframe it and place the message onto the frames output queue.
75            let mut rd = codec::Reader::init(&self.buf[start..self.used]);
76            let m = match OpaqueMessage::read(&mut rd) {
77                Ok(m) => m,
78                Err(msg_err) => {
79                    let err_kind = match msg_err {
80                        MessageError::TooShortForHeader | MessageError::TooShortForLength => {
81                            return Ok(None)
82                        }
83                        MessageError::InvalidEmptyPayload => InvalidMessage::InvalidEmptyPayload,
84                        MessageError::MessageTooLarge => InvalidMessage::MessageTooLarge,
85                        MessageError::InvalidContentType => InvalidMessage::InvalidContentType,
86                        MessageError::UnknownProtocolVersion => {
87                            InvalidMessage::UnknownProtocolVersion
88                        }
89                    };
90
91                    return Err(self.set_err(err_kind));
92                }
93            };
94
95            // Return CCS messages and early plaintext alerts immediately without decrypting.
96            let end = start + rd.used();
97            let version_is_tls13 = matches!(negotiated_version, Some(ProtocolVersion::TLSv1_3));
98            let allowed_plaintext = match m.typ {
99                // CCS messages are always plaintext.
100                ContentType::ChangeCipherSpec => true,
101                // Alerts are allowed to be plaintext if-and-only-if:
102                // * The negotiated protocol version is TLS 1.3. - In TLS 1.2 it is unambiguous when
103                //   keying changes based on the CCS message. Only TLS 1.3 requires these heuristics.
104                // * We have not yet decrypted any messages from the peer - if we have we don't
105                //   expect any plaintext.
106                // * The payload size is indicative of a plaintext alert message.
107                ContentType::Alert
108                    if version_is_tls13
109                        && !record_layer.has_decrypted()
110                        && m.payload().len() <= 2 =>
111                {
112                    true
113                }
114                // In other circumstances, we expect all messages to be encrypted.
115                _ => false,
116            };
117            if self.joining_hs.is_none() && allowed_plaintext {
118                // This is unencrypted. We check the contents later.
119                self.discard(end);
120                return Ok(Some(Deframed {
121                    want_close_before_decrypt: false,
122                    aligned: true,
123                    trial_decryption_finished: false,
124                    message: m.into_plain_message(),
125                }));
126            }
127
128            // Decrypt the encrypted message (if necessary).
129            let msg = match record_layer.decrypt_incoming(m) {
130                Ok(Some(decrypted)) => {
131                    let Decrypted {
132                        want_close_before_decrypt,
133                        plaintext,
134                    } = decrypted;
135                    debug_assert!(!want_close_before_decrypt);
136                    plaintext
137                }
138                // This was rejected early data, discard it. If we currently have a handshake
139                // payload in progress, this counts as interleaved, so we error out.
140                Ok(None) if self.joining_hs.is_some() => {
141                    return Err(self.set_err(
142                        PeerMisbehaved::RejectedEarlyDataInterleavedWithHandshakeMessage,
143                    ));
144                }
145                Ok(None) => {
146                    self.discard(end);
147                    continue;
148                }
149                Err(e) => return Err(e),
150            };
151
152            if self.joining_hs.is_some() && msg.typ != ContentType::Handshake {
153                // "Handshake messages MUST NOT be interleaved with other record
154                // types.  That is, if a handshake message is split over two or more
155                // records, there MUST NOT be any other records between them."
156                // https://www.rfc-editor.org/rfc/rfc8446#section-5.1
157                return Err(self.set_err(PeerMisbehaved::MessageInterleavedWithHandshakeMessage));
158            }
159
160            // If it's not a handshake message, just return it -- no joining necessary.
161            if msg.typ != ContentType::Handshake {
162                let end = start + rd.used();
163                self.discard(end);
164                return Ok(Some(Deframed {
165                    want_close_before_decrypt: false,
166                    aligned: true,
167                    trial_decryption_finished: false,
168                    message: msg,
169                }));
170            }
171
172            // If we don't know the payload size yet or if the payload size is larger
173            // than the currently buffered payload, we need to wait for more data.
174            match self.append_hs(msg.version, &msg.payload.0, end, false)? {
175                HandshakePayloadState::Blocked => return Ok(None),
176                HandshakePayloadState::Complete(len) => break len,
177                HandshakePayloadState::Continue => continue,
178            }
179        };
180
181        let meta = self.joining_hs.as_mut().unwrap(); // safe after calling `append_hs()`
182
183        // We can now wrap the complete handshake payload in a `PlainMessage`, to be returned.
184        let message = PlainMessage {
185            typ: ContentType::Handshake,
186            version: meta.version,
187            payload: Payload::new(&self.buf[meta.payload.start..meta.payload.start + expected_len]),
188        };
189
190        // But before we return, update the `joining_hs` state to skip past this payload.
191        if meta.payload.len() > expected_len {
192            // If we have another (beginning of) a handshake payload left in the buffer, update
193            // the payload start to point past the payload we're about to yield, and update the
194            // `expected_len` to match the state of that remaining payload.
195            meta.payload.start += expected_len;
196            meta.expected_len = payload_size(&self.buf[meta.payload.start..meta.payload.end])?;
197        } else {
198            // Otherwise, we've yielded the last handshake payload in the buffer, so we can
199            // discard all of the bytes that we're previously buffered as handshake data.
200            let end = meta.message.end;
201            self.joining_hs = None;
202            self.discard(end);
203        }
204
205        Ok(Some(Deframed {
206            want_close_before_decrypt: false,
207            aligned: self.joining_hs.is_none(),
208            trial_decryption_finished: true,
209            message,
210        }))
211    }
212
213    /// Fuses this deframer's error and returns the set value.
214    ///
215    /// Any future calls to `pop` will return `err` again.
216    fn set_err(&mut self, err: impl Into<Error>) -> Error {
217        let err = err.into();
218        self.last_error = Some(err.clone());
219        err
220    }
221
222    /// Allow pushing handshake messages directly into the buffer.
223    pub(crate) fn push(&mut self, version: ProtocolVersion, payload: &[u8]) -> Result<(), Error> {
224        if self.used > 0 && self.joining_hs.is_none() {
225            return Err(Error::General(
226                "cannot push QUIC messages into unrelated connection".into(),
227            ));
228        } else if let Err(err) = self.prepare_read() {
229            return Err(Error::General(err.into()));
230        }
231
232        let end = self.used + payload.len();
233        self.append_hs(version, payload, end, true)?;
234        self.used = end;
235        Ok(())
236    }
237
238    /// Write the handshake message contents into the buffer and update the metadata.
239    ///
240    /// Returns true if a complete message is found.
241    fn append_hs(
242        &mut self,
243        version: ProtocolVersion,
244        payload: &[u8],
245        end: usize,
246        quic: bool,
247    ) -> Result<HandshakePayloadState, Error> {
248        let meta = match &mut self.joining_hs {
249            Some(meta) => {
250                debug_assert_eq!(meta.quic, quic);
251
252                // We're joining a handshake message to the previous one here.
253                // Write it into the buffer and update the metadata.
254
255                let dst = &mut self.buf[meta.payload.end..meta.payload.end + payload.len()];
256                dst.copy_from_slice(payload);
257                meta.message.end = end;
258                meta.payload.end += payload.len();
259
260                // If we haven't parsed the payload size yet, try to do so now.
261                if meta.expected_len.is_none() {
262                    meta.expected_len =
263                        payload_size(&self.buf[meta.payload.start..meta.payload.end])?;
264                }
265
266                meta
267            }
268            None => {
269                // We've found a new handshake message here.
270                // Write it into the buffer and create the metadata.
271
272                let expected_len = payload_size(payload)?;
273                let dst = &mut self.buf[..payload.len()];
274                dst.copy_from_slice(payload);
275                self.joining_hs
276                    .insert(HandshakePayloadMeta {
277                        message: Range { start: 0, end },
278                        payload: Range {
279                            start: 0,
280                            end: payload.len(),
281                        },
282                        version,
283                        expected_len,
284                        quic,
285                    })
286            }
287        };
288
289        Ok(match meta.expected_len {
290            Some(len) if len <= meta.payload.len() => HandshakePayloadState::Complete(len),
291            _ => match self.used > meta.message.end {
292                true => HandshakePayloadState::Continue,
293                false => HandshakePayloadState::Blocked,
294            },
295        })
296    }
297
298    /// Read some bytes from `rd`, and add them to our internal buffer.
299    #[allow(clippy::comparison_chain)]
300    pub fn read(&mut self, rd: &mut dyn io::Read) -> io::Result<usize> {
301        if let Err(err) = self.prepare_read() {
302            return Err(io::Error::new(io::ErrorKind::InvalidData, err));
303        }
304
305        // Try to do the largest reads possible. Note that if
306        // we get a message with a length field out of range here,
307        // we do a zero length read.  That looks like an EOF to
308        // the next layer up, which is fine.
309        let new_bytes = rd.read(&mut self.buf[self.used..])?;
310        self.used += new_bytes;
311        Ok(new_bytes)
312    }
313
314    /// Resize the internal `buf` if necessary for reading more bytes.
315    fn prepare_read(&mut self) -> Result<(), &'static str> {
316        // We allow a maximum of 64k of buffered data for handshake messages only. Enforce this
317        // by varying the maximum allowed buffer size here based on whether a prefix of a
318        // handshake payload is currently being buffered. Given that the first read of such a
319        // payload will only ever be 4k bytes, the next time we come around here we allow a
320        // larger buffer size. Once the large message and any following handshake messages in
321        // the same flight have been consumed, `pop()` will call `discard()` to reset `used`.
322        // At this point, the buffer resizing logic below should reduce the buffer size.
323        let allow_max = match self.joining_hs {
324            Some(_) => MAX_HANDSHAKE_SIZE as usize,
325            None => OpaqueMessage::MAX_WIRE_SIZE,
326        };
327
328        if self.used >= allow_max {
329            return Err("message buffer full");
330        }
331
332        // If we can and need to increase the buffer size to allow a 4k read, do so. After
333        // dealing with a large handshake message (exceeding `OpaqueMessage::MAX_WIRE_SIZE`),
334        // make sure to reduce the buffer size again (large messages should be rare).
335        // Also, reduce the buffer size if there are neither full nor partial messages in it,
336        // which usually means that the other side suspended sending data.
337        let need_capacity = Ord::min(allow_max, self.used + READ_SIZE);
338        if need_capacity > self.buf.len() {
339            self.buf.resize(need_capacity, 0);
340        } else if self.used == 0 || self.buf.len() > allow_max {
341            self.buf.resize(need_capacity, 0);
342            self.buf.shrink_to(need_capacity);
343        }
344
345        Ok(())
346    }
347
348    /// Returns true if we have messages for the caller
349    /// to process, either whole messages in our output
350    /// queue or partial messages in our buffer.
351    pub fn has_pending(&self) -> bool {
352        self.used > 0
353    }
354
355    /// Discard `taken` bytes from the start of our buffer.
356    fn discard(&mut self, taken: usize) {
357        #[allow(clippy::comparison_chain)]
358        if taken < self.used {
359            /* Before:
360             * +----------+----------+----------+
361             * | taken    | pending  |xxxxxxxxxx|
362             * +----------+----------+----------+
363             * 0          ^ taken    ^ self.used
364             *
365             * After:
366             * +----------+----------+----------+
367             * | pending  |xxxxxxxxxxxxxxxxxxxxx|
368             * +----------+----------+----------+
369             * 0          ^ self.used
370             */
371
372            self.buf
373                .copy_within(taken..self.used, 0);
374            self.used -= taken;
375        } else if taken == self.used {
376            self.used = 0;
377        }
378    }
379}
380
381enum HandshakePayloadState {
382    /// Waiting for more data.
383    Blocked,
384    /// We have a complete handshake message.
385    Complete(usize),
386    /// More records available for processing.
387    Continue,
388}
389
390struct HandshakePayloadMeta {
391    /// The range of bytes from the deframer buffer that contains data processed so far.
392    ///
393    /// This will need to be discarded as the last of the handshake message is `pop()`ped.
394    message: Range<usize>,
395    /// The range of bytes from the deframer buffer that contains payload.
396    payload: Range<usize>,
397    /// The protocol version as found in the decrypted handshake message.
398    version: ProtocolVersion,
399    /// The expected size of the handshake payload, if available.
400    ///
401    /// If the received payload exceeds 4 bytes (the handshake payload header), we update
402    /// `expected_len` to contain the payload length as advertised (at most 16_777_215 bytes).
403    expected_len: Option<usize>,
404    /// True if this is a QUIC handshake message.
405    ///
406    /// In the case of QUIC, we get a plaintext handshake data directly from the CRYPTO stream,
407    /// so there's no need to unwrap and decrypt the outer TLS record. This is implemented
408    /// by directly calling `MessageDeframer::push()` from the connection.
409    quic: bool,
410}
411
412/// Determine the expected length of the payload as advertised in the header.
413///
414/// Returns `Err` if the advertised length is larger than what we want to accept
415/// (`MAX_HANDSHAKE_SIZE`), `Ok(None)` if the buffer is too small to contain a complete header,
416/// and `Ok(Some(len))` otherwise.
417fn payload_size(buf: &[u8]) -> Result<Option<usize>, Error> {
418    if buf.len() < HEADER_SIZE {
419        return Ok(None);
420    }
421
422    let (header, _) = buf.split_at(HEADER_SIZE);
423    match codec::u24::read_bytes(&header[1..]) {
424        Ok(len) if len.0 > MAX_HANDSHAKE_SIZE => Err(Error::InvalidMessage(
425            InvalidMessage::HandshakePayloadTooLarge,
426        )),
427        Ok(len) => Ok(Some(HEADER_SIZE + usize::from(len))),
428        _ => Ok(None),
429    }
430}
431
432#[derive(Debug)]
433pub struct Deframed {
434    pub(crate) want_close_before_decrypt: bool,
435    pub(crate) aligned: bool,
436    pub(crate) trial_decryption_finished: bool,
437    pub message: PlainMessage,
438}
439
440const HEADER_SIZE: usize = 1 + 3;
441
442/// TLS allows for handshake messages of up to 16MB.  We
443/// restrict that to 64KB to limit potential for denial-of-
444/// service.
445const MAX_HANDSHAKE_SIZE: u32 = 0xffff;
446
447const READ_SIZE: usize = 4096;
448
449#[cfg(test)]
450mod tests {
451    use super::MessageDeframer;
452    use crate::msgs::message::{Message, OpaqueMessage};
453    use crate::record_layer::RecordLayer;
454    use crate::{ContentType, Error, InvalidMessage};
455
456    use std::io;
457
458    const FIRST_MESSAGE: &[u8] = include_bytes!("../testdata/deframer-test.1.bin");
459    const SECOND_MESSAGE: &[u8] = include_bytes!("../testdata/deframer-test.2.bin");
460
461    const EMPTY_APPLICATIONDATA_MESSAGE: &[u8] =
462        include_bytes!("../testdata/deframer-empty-applicationdata.bin");
463
464    const INVALID_EMPTY_MESSAGE: &[u8] = include_bytes!("../testdata/deframer-invalid-empty.bin");
465    const INVALID_CONTENTTYPE_MESSAGE: &[u8] =
466        include_bytes!("../testdata/deframer-invalid-contenttype.bin");
467    const INVALID_VERSION_MESSAGE: &[u8] =
468        include_bytes!("../testdata/deframer-invalid-version.bin");
469    const INVALID_LENGTH_MESSAGE: &[u8] = include_bytes!("../testdata/deframer-invalid-length.bin");
470
471    fn input_bytes(d: &mut MessageDeframer, bytes: &[u8]) -> io::Result<usize> {
472        let mut rd = io::Cursor::new(bytes);
473        d.read(&mut rd)
474    }
475
476    fn input_bytes_concat(
477        d: &mut MessageDeframer,
478        bytes1: &[u8],
479        bytes2: &[u8],
480    ) -> io::Result<usize> {
481        let mut bytes = vec![0u8; bytes1.len() + bytes2.len()];
482        bytes[..bytes1.len()].clone_from_slice(bytes1);
483        bytes[bytes1.len()..].clone_from_slice(bytes2);
484        let mut rd = io::Cursor::new(&bytes);
485        d.read(&mut rd)
486    }
487
488    struct ErrorRead {
489        error: Option<io::Error>,
490    }
491
492    impl ErrorRead {
493        fn new(error: io::Error) -> Self {
494            Self { error: Some(error) }
495        }
496    }
497
498    impl io::Read for ErrorRead {
499        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
500            for (i, b) in buf.iter_mut().enumerate() {
501                *b = i as u8;
502            }
503
504            let error = self.error.take().unwrap();
505            Err(error)
506        }
507    }
508
509    fn input_error(d: &mut MessageDeframer) {
510        let error = io::Error::from(io::ErrorKind::TimedOut);
511        let mut rd = ErrorRead::new(error);
512        d.read(&mut rd)
513            .expect_err("error not propagated");
514    }
515
516    fn input_whole_incremental(d: &mut MessageDeframer, bytes: &[u8]) {
517        let before = d.used;
518
519        for i in 0..bytes.len() {
520            assert_len(1, input_bytes(d, &bytes[i..i + 1]));
521            assert!(d.has_pending());
522        }
523
524        assert_eq!(before + bytes.len(), d.used);
525    }
526
527    fn assert_len(want: usize, got: io::Result<usize>) {
528        if let Ok(gotval) = got {
529            assert_eq!(gotval, want);
530        } else {
531            panic!("read failed, expected {:?} bytes", want);
532        }
533    }
534
535    fn pop_first(d: &mut MessageDeframer, rl: &mut RecordLayer) {
536        let m = d
537            .pop(rl, None)
538            .unwrap()
539            .unwrap()
540            .message;
541        assert_eq!(m.typ, ContentType::Handshake);
542        Message::try_from(m).unwrap();
543    }
544
545    fn pop_second(d: &mut MessageDeframer, rl: &mut RecordLayer) {
546        let m = d
547            .pop(rl, None)
548            .unwrap()
549            .unwrap()
550            .message;
551        assert_eq!(m.typ, ContentType::Alert);
552        Message::try_from(m).unwrap();
553    }
554
555    #[test]
556    fn check_incremental() {
557        let mut d = MessageDeframer::default();
558        assert!(!d.has_pending());
559        input_whole_incremental(&mut d, FIRST_MESSAGE);
560        assert!(d.has_pending());
561
562        let mut rl = RecordLayer::new();
563        pop_first(&mut d, &mut rl);
564        assert!(!d.has_pending());
565        assert!(d.last_error.is_none());
566    }
567
568    #[test]
569    fn check_incremental_2() {
570        let mut d = MessageDeframer::default();
571        assert!(!d.has_pending());
572        input_whole_incremental(&mut d, FIRST_MESSAGE);
573        assert!(d.has_pending());
574        input_whole_incremental(&mut d, SECOND_MESSAGE);
575        assert!(d.has_pending());
576
577        let mut rl = RecordLayer::new();
578        pop_first(&mut d, &mut rl);
579        assert!(d.has_pending());
580        pop_second(&mut d, &mut rl);
581        assert!(!d.has_pending());
582        assert!(d.last_error.is_none());
583    }
584
585    #[test]
586    fn check_whole() {
587        let mut d = MessageDeframer::default();
588        assert!(!d.has_pending());
589        assert_len(FIRST_MESSAGE.len(), input_bytes(&mut d, FIRST_MESSAGE));
590        assert!(d.has_pending());
591
592        let mut rl = RecordLayer::new();
593        pop_first(&mut d, &mut rl);
594        assert!(!d.has_pending());
595        assert!(d.last_error.is_none());
596    }
597
598    #[test]
599    fn check_whole_2() {
600        let mut d = MessageDeframer::default();
601        assert!(!d.has_pending());
602        assert_len(FIRST_MESSAGE.len(), input_bytes(&mut d, FIRST_MESSAGE));
603        assert_len(SECOND_MESSAGE.len(), input_bytes(&mut d, SECOND_MESSAGE));
604
605        let mut rl = RecordLayer::new();
606        pop_first(&mut d, &mut rl);
607        pop_second(&mut d, &mut rl);
608        assert!(!d.has_pending());
609        assert!(d.last_error.is_none());
610    }
611
612    #[test]
613    fn test_two_in_one_read() {
614        let mut d = MessageDeframer::default();
615        assert!(!d.has_pending());
616        assert_len(
617            FIRST_MESSAGE.len() + SECOND_MESSAGE.len(),
618            input_bytes_concat(&mut d, FIRST_MESSAGE, SECOND_MESSAGE),
619        );
620
621        let mut rl = RecordLayer::new();
622        pop_first(&mut d, &mut rl);
623        pop_second(&mut d, &mut rl);
624        assert!(!d.has_pending());
625        assert!(d.last_error.is_none());
626    }
627
628    #[test]
629    fn test_two_in_one_read_shortest_first() {
630        let mut d = MessageDeframer::default();
631        assert!(!d.has_pending());
632        assert_len(
633            FIRST_MESSAGE.len() + SECOND_MESSAGE.len(),
634            input_bytes_concat(&mut d, SECOND_MESSAGE, FIRST_MESSAGE),
635        );
636
637        let mut rl = RecordLayer::new();
638        pop_second(&mut d, &mut rl);
639        pop_first(&mut d, &mut rl);
640        assert!(!d.has_pending());
641        assert!(d.last_error.is_none());
642    }
643
644    #[test]
645    fn test_incremental_with_nonfatal_read_error() {
646        let mut d = MessageDeframer::default();
647        assert_len(3, input_bytes(&mut d, &FIRST_MESSAGE[..3]));
648        input_error(&mut d);
649        assert_len(
650            FIRST_MESSAGE.len() - 3,
651            input_bytes(&mut d, &FIRST_MESSAGE[3..]),
652        );
653
654        let mut rl = RecordLayer::new();
655        pop_first(&mut d, &mut rl);
656        assert!(!d.has_pending());
657        assert!(d.last_error.is_none());
658    }
659
660    #[test]
661    fn test_invalid_contenttype_errors() {
662        let mut d = MessageDeframer::default();
663        assert_len(
664            INVALID_CONTENTTYPE_MESSAGE.len(),
665            input_bytes(&mut d, INVALID_CONTENTTYPE_MESSAGE),
666        );
667
668        let mut rl = RecordLayer::new();
669        assert_eq!(
670            d.pop(&mut rl, None).unwrap_err(),
671            Error::InvalidMessage(InvalidMessage::InvalidContentType)
672        );
673    }
674
675    #[test]
676    fn test_invalid_version_errors() {
677        let mut d = MessageDeframer::default();
678        assert_len(
679            INVALID_VERSION_MESSAGE.len(),
680            input_bytes(&mut d, INVALID_VERSION_MESSAGE),
681        );
682
683        let mut rl = RecordLayer::new();
684        assert_eq!(
685            d.pop(&mut rl, None).unwrap_err(),
686            Error::InvalidMessage(InvalidMessage::UnknownProtocolVersion)
687        );
688    }
689
690    #[test]
691    fn test_invalid_length_errors() {
692        let mut d = MessageDeframer::default();
693        assert_len(
694            INVALID_LENGTH_MESSAGE.len(),
695            input_bytes(&mut d, INVALID_LENGTH_MESSAGE),
696        );
697
698        let mut rl = RecordLayer::new();
699        assert_eq!(
700            d.pop(&mut rl, None).unwrap_err(),
701            Error::InvalidMessage(InvalidMessage::MessageTooLarge)
702        );
703    }
704
705    #[test]
706    fn test_empty_applicationdata() {
707        let mut d = MessageDeframer::default();
708        assert_len(
709            EMPTY_APPLICATIONDATA_MESSAGE.len(),
710            input_bytes(&mut d, EMPTY_APPLICATIONDATA_MESSAGE),
711        );
712
713        let mut rl = RecordLayer::new();
714        let m = d
715            .pop(&mut rl, None)
716            .unwrap()
717            .unwrap()
718            .message;
719        assert_eq!(m.typ, ContentType::ApplicationData);
720        assert_eq!(m.payload.0.len(), 0);
721        assert!(!d.has_pending());
722        assert!(d.last_error.is_none());
723    }
724
725    #[test]
726    fn test_invalid_empty_errors() {
727        let mut d = MessageDeframer::default();
728        assert_len(
729            INVALID_EMPTY_MESSAGE.len(),
730            input_bytes(&mut d, INVALID_EMPTY_MESSAGE),
731        );
732
733        let mut rl = RecordLayer::new();
734        assert_eq!(
735            d.pop(&mut rl, None).unwrap_err(),
736            Error::InvalidMessage(InvalidMessage::InvalidEmptyPayload)
737        );
738        // CorruptMessage has been fused
739        assert_eq!(
740            d.pop(&mut rl, None).unwrap_err(),
741            Error::InvalidMessage(InvalidMessage::InvalidEmptyPayload)
742        );
743    }
744
745    #[test]
746    fn test_limited_buffer() {
747        const PAYLOAD_LEN: usize = 16_384;
748        let mut message = Vec::with_capacity(16_389);
749        message.push(0x17); // ApplicationData
750        message.extend(&[0x03, 0x04]); // ProtocolVersion
751        message.extend((PAYLOAD_LEN as u16).to_be_bytes()); // payload length
752        message.extend(&[0; PAYLOAD_LEN]);
753
754        let mut d = MessageDeframer::default();
755        assert_len(4096, input_bytes(&mut d, &message));
756        assert_len(4096, input_bytes(&mut d, &message));
757        assert_len(4096, input_bytes(&mut d, &message));
758        assert_len(4096, input_bytes(&mut d, &message));
759        assert_len(
760            OpaqueMessage::MAX_WIRE_SIZE - 16_384,
761            input_bytes(&mut d, &message),
762        );
763        assert!(input_bytes(&mut d, &message).is_err());
764    }
765}