rustls/
common_state.rs

1use crate::enums::{AlertDescription, ContentType, HandshakeType, ProtocolVersion};
2use crate::error::{Error, InvalidMessage, PeerMisbehaved};
3use crate::key;
4#[cfg(feature = "logging")]
5use crate::log::{debug, warn};
6use crate::msgs::alert::AlertMessagePayload;
7use crate::msgs::base::Payload;
8use crate::msgs::enums::{AlertLevel, KeyUpdateRequest};
9use crate::msgs::fragmenter::MessageFragmenter;
10#[cfg(feature = "quic")]
11use crate::msgs::message::MessagePayload;
12use crate::msgs::message::{BorrowedPlainMessage, Message, OpaqueMessage, PlainMessage};
13#[cfg(feature = "quic")]
14use crate::quic;
15use crate::record_layer;
16#[cfg(feature = "secret_extraction")]
17use crate::suites::PartiallyExtractedSecrets;
18use crate::suites::SupportedCipherSuite;
19#[cfg(feature = "tls12")]
20use crate::tls12::ConnectionSecrets;
21use crate::vecbuf::ChunkVecBuffer;
22
23/// Connection state common to both client and server connections.
24pub struct CommonState {
25    pub(crate) negotiated_version: Option<ProtocolVersion>,
26    pub(crate) side: Side,
27    pub(crate) record_layer: record_layer::RecordLayer,
28    pub(crate) suite: Option<SupportedCipherSuite>,
29    pub(crate) alpn_protocol: Option<Vec<u8>>,
30    pub(crate) aligned_handshake: bool,
31    pub(crate) may_send_application_data: bool,
32    pub(crate) may_receive_application_data: bool,
33    pub(crate) early_traffic: bool,
34    sent_fatal_alert: bool,
35    /// If the peer has signaled end of stream.
36    pub(crate) has_received_close_notify: bool,
37    pub(crate) has_seen_eof: bool,
38    pub(crate) received_middlebox_ccs: u8,
39    pub(crate) peer_certificates: Option<Vec<key::Certificate>>,
40    message_fragmenter: MessageFragmenter,
41    pub(crate) received_plaintext: ChunkVecBuffer,
42    sendable_plaintext: ChunkVecBuffer,
43    pub(crate) sendable_tls: ChunkVecBuffer,
44    queued_key_update_message: Option<Vec<u8>>,
45
46    #[allow(dead_code)] // only read for QUIC
47    /// Protocol whose key schedule should be used. Unused for TLS < 1.3.
48    pub(crate) protocol: Protocol,
49    #[cfg(feature = "quic")]
50    pub(crate) quic: quic::Quic,
51    #[cfg(feature = "secret_extraction")]
52    pub(crate) enable_secret_extraction: bool,
53}
54
55impl CommonState {
56    pub(crate) fn new(side: Side) -> Self {
57        Self {
58            negotiated_version: None,
59            side,
60            record_layer: record_layer::RecordLayer::new(),
61            suite: None,
62            alpn_protocol: None,
63            aligned_handshake: true,
64            may_send_application_data: false,
65            may_receive_application_data: false,
66            early_traffic: false,
67            sent_fatal_alert: false,
68            has_received_close_notify: false,
69            has_seen_eof: false,
70            received_middlebox_ccs: 0,
71            peer_certificates: None,
72            message_fragmenter: MessageFragmenter::default(),
73            received_plaintext: ChunkVecBuffer::new(Some(DEFAULT_RECEIVED_PLAINTEXT_LIMIT)),
74            sendable_plaintext: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
75            sendable_tls: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
76            queued_key_update_message: None,
77
78            protocol: Protocol::Tcp,
79            #[cfg(feature = "quic")]
80            quic: quic::Quic::default(),
81            #[cfg(feature = "secret_extraction")]
82            enable_secret_extraction: false,
83        }
84    }
85
86    /// Returns true if the caller should call [`Connection::write_tls`] as soon as possible.
87    ///
88    /// [`Connection::write_tls`]: crate::Connection::write_tls
89    pub fn wants_write(&self) -> bool {
90        !self.sendable_tls.is_empty()
91    }
92
93    /// Returns true if the connection is currently performing the TLS handshake.
94    ///
95    /// During this time plaintext written to the connection is buffered in memory. After
96    /// [`Connection::process_new_packets()`] has been called, this might start to return `false`
97    /// while the final handshake packets still need to be extracted from the connection's buffers.
98    ///
99    /// [`Connection::process_new_packets()`]: crate::Connection::process_new_packets
100    pub fn is_handshaking(&self) -> bool {
101        !(self.may_send_application_data && self.may_receive_application_data)
102    }
103
104    /// Retrieves the certificate chain used by the peer to authenticate.
105    ///
106    /// The order of the certificate chain is as it appears in the TLS
107    /// protocol: the first certificate relates to the peer, the
108    /// second certifies the first, the third certifies the second, and
109    /// so on.
110    ///
111    /// This is made available for both full and resumed handshakes.
112    ///
113    /// For clients, this is the certificate chain of the server.
114    ///
115    /// For servers, this is the certificate chain of the client,
116    /// if client authentication was completed.
117    ///
118    /// The return value is None until this value is available.
119    pub fn peer_certificates(&self) -> Option<&[key::Certificate]> {
120        self.peer_certificates.as_deref()
121    }
122
123    /// Retrieves the protocol agreed with the peer via ALPN.
124    ///
125    /// A return value of `None` after handshake completion
126    /// means no protocol was agreed (because no protocols
127    /// were offered or accepted by the peer).
128    pub fn alpn_protocol(&self) -> Option<&[u8]> {
129        self.get_alpn_protocol()
130    }
131
132    /// Retrieves the ciphersuite agreed with the peer.
133    ///
134    /// This returns None until the ciphersuite is agreed.
135    pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
136        self.suite
137    }
138
139    /// Retrieves the protocol version agreed with the peer.
140    ///
141    /// This returns `None` until the version is agreed.
142    pub fn protocol_version(&self) -> Option<ProtocolVersion> {
143        self.negotiated_version
144    }
145
146    pub(crate) fn is_tls13(&self) -> bool {
147        matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
148    }
149
150    pub(crate) fn process_main_protocol<Data>(
151        &mut self,
152        msg: Message,
153        mut state: Box<dyn State<Data>>,
154        data: &mut Data,
155    ) -> Result<Box<dyn State<Data>>, Error> {
156        // For TLS1.2, outside of the handshake, send rejection alerts for
157        // renegotiation requests.  These can occur any time.
158        if self.may_receive_application_data && !self.is_tls13() {
159            let reject_ty = match self.side {
160                Side::Client => HandshakeType::HelloRequest,
161                Side::Server => HandshakeType::ClientHello,
162            };
163            if msg.is_handshake_type(reject_ty) {
164                self.send_warning_alert(AlertDescription::NoRenegotiation);
165                return Ok(state);
166            }
167        }
168
169        let mut cx = Context { common: self, data };
170        match state.handle(&mut cx, msg) {
171            Ok(next) => {
172                state = next;
173                Ok(state)
174            }
175            Err(e @ Error::InappropriateMessage { .. })
176            | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
177                Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
178            }
179            Err(e) => Err(e),
180        }
181    }
182
183    /// Send plaintext application data, fragmenting and
184    /// encrypting it as it goes out.
185    ///
186    /// If internal buffers are too small, this function will not accept
187    /// all the data.
188    pub(crate) fn send_some_plaintext(&mut self, data: &[u8]) -> usize {
189        self.perhaps_write_key_update();
190        self.send_plain(data, Limit::Yes)
191    }
192
193    pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
194        debug_assert!(self.early_traffic);
195        debug_assert!(self.record_layer.is_encrypting());
196
197        if data.is_empty() {
198            // Don't send empty fragments.
199            return 0;
200        }
201
202        self.send_appdata_encrypt(data, Limit::Yes)
203    }
204
205    // Changing the keys must not span any fragmented handshake
206    // messages.  Otherwise the defragmented messages will have
207    // been protected with two different record layer protections,
208    // which is illegal.  Not mentioned in RFC.
209    pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
210        if !self.aligned_handshake {
211            Err(self.send_fatal_alert(
212                AlertDescription::UnexpectedMessage,
213                PeerMisbehaved::KeyEpochWithPendingFragment,
214            ))
215        } else {
216            Ok(())
217        }
218    }
219
220    /// Fragment `m`, encrypt the fragments, and then queue
221    /// the encrypted fragments for sending.
222    pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
223        let iter = self
224            .message_fragmenter
225            .fragment_message(&m);
226        for m in iter {
227            self.send_single_fragment(m);
228        }
229    }
230
231    /// Like send_msg_encrypt, but operate on an appdata directly.
232    fn send_appdata_encrypt(&mut self, payload: &[u8], limit: Limit) -> usize {
233        // Here, the limit on sendable_tls applies to encrypted data,
234        // but we're respecting it for plaintext data -- so we'll
235        // be out by whatever the cipher+record overhead is.  That's a
236        // constant and predictable amount, so it's not a terrible issue.
237        let len = match limit {
238            Limit::Yes => self
239                .sendable_tls
240                .apply_limit(payload.len()),
241            Limit::No => payload.len(),
242        };
243
244        let iter = self.message_fragmenter.fragment_slice(
245            ContentType::ApplicationData,
246            ProtocolVersion::TLSv1_2,
247            &payload[..len],
248        );
249        for m in iter {
250            self.send_single_fragment(m);
251        }
252
253        len
254    }
255
256    fn send_single_fragment(&mut self, m: BorrowedPlainMessage) {
257        // Close connection once we start to run out of
258        // sequence space.
259        if self
260            .record_layer
261            .wants_close_before_encrypt()
262        {
263            self.send_close_notify();
264        }
265
266        // Refuse to wrap counter at all costs.  This
267        // is basically untestable unfortunately.
268        if self.record_layer.encrypt_exhausted() {
269            return;
270        }
271
272        let em = self.record_layer.encrypt_outgoing(m);
273        self.queue_tls_message(em);
274    }
275
276    /// Encrypt and send some plaintext `data`.  `limit` controls
277    /// whether the per-connection buffer limits apply.
278    ///
279    /// Returns the number of bytes written from `data`: this might
280    /// be less than `data.len()` if buffer limits were exceeded.
281    fn send_plain(&mut self, data: &[u8], limit: Limit) -> usize {
282        if !self.may_send_application_data {
283            // If we haven't completed handshaking, buffer
284            // plaintext to send once we do.
285            let len = match limit {
286                Limit::Yes => self
287                    .sendable_plaintext
288                    .append_limited_copy(data),
289                Limit::No => self
290                    .sendable_plaintext
291                    .append(data.to_vec()),
292            };
293            return len;
294        }
295
296        debug_assert!(self.record_layer.is_encrypting());
297
298        if data.is_empty() {
299            // Don't send empty fragments.
300            return 0;
301        }
302
303        self.send_appdata_encrypt(data, limit)
304    }
305
306    pub(crate) fn start_outgoing_traffic(&mut self) {
307        self.may_send_application_data = true;
308        self.flush_plaintext();
309    }
310
311    pub(crate) fn start_traffic(&mut self) {
312        self.may_receive_application_data = true;
313        self.start_outgoing_traffic();
314    }
315
316    /// Sets a limit on the internal buffers used to buffer
317    /// unsent plaintext (prior to completing the TLS handshake)
318    /// and unsent TLS records.  This limit acts only on application
319    /// data written through [`Connection::writer`].
320    ///
321    /// By default the limit is 64KB.  The limit can be set
322    /// at any time, even if the current buffer use is higher.
323    ///
324    /// [`None`] means no limit applies, and will mean that written
325    /// data is buffered without bound -- it is up to the application
326    /// to appropriately schedule its plaintext and TLS writes to bound
327    /// memory usage.
328    ///
329    /// For illustration: `Some(1)` means a limit of one byte applies:
330    /// [`Connection::writer`] will accept only one byte, encrypt it and
331    /// add a TLS header.  Once this is sent via [`Connection::write_tls`],
332    /// another byte may be sent.
333    ///
334    /// # Internal write-direction buffering
335    /// rustls has two buffers whose size are bounded by this setting:
336    ///
337    /// ## Buffering of unsent plaintext data prior to handshake completion
338    ///
339    /// Calls to [`Connection::writer`] before or during the handshake
340    /// are buffered (up to the limit specified here).  Once the
341    /// handshake completes this data is encrypted and the resulting
342    /// TLS records are added to the outgoing buffer.
343    ///
344    /// ## Buffering of outgoing TLS records
345    ///
346    /// This buffer is used to store TLS records that rustls needs to
347    /// send to the peer.  It is used in these two circumstances:
348    ///
349    /// - by [`Connection::process_new_packets`] when a handshake or alert
350    ///   TLS record needs to be sent.
351    /// - by [`Connection::writer`] post-handshake: the plaintext is
352    ///   encrypted and the resulting TLS record is buffered.
353    ///
354    /// This buffer is emptied by [`Connection::write_tls`].
355    ///
356    /// [`Connection::writer`]: crate::Connection::writer
357    /// [`Connection::write_tls`]: crate::Connection::write_tls
358    /// [`Connection::process_new_packets`]: crate::Connection::process_new_packets
359    pub fn set_buffer_limit(&mut self, limit: Option<usize>) {
360        self.sendable_plaintext.set_limit(limit);
361        self.sendable_tls.set_limit(limit);
362    }
363
364    /// Send any buffered plaintext.  Plaintext is buffered if
365    /// written during handshake.
366    fn flush_plaintext(&mut self) {
367        if !self.may_send_application_data {
368            return;
369        }
370
371        while let Some(buf) = self.sendable_plaintext.pop() {
372            self.send_plain(&buf, Limit::No);
373        }
374    }
375
376    // Put m into sendable_tls for writing.
377    fn queue_tls_message(&mut self, m: OpaqueMessage) {
378        self.sendable_tls.append(m.encode());
379    }
380
381    /// Send a raw TLS message, fragmenting it if needed.
382    pub(crate) fn send_msg(&mut self, m: Message, must_encrypt: bool) {
383        #[cfg(feature = "quic")]
384        {
385            if let Protocol::Quic = self.protocol {
386                if let MessagePayload::Alert(alert) = m.payload {
387                    self.quic.alert = Some(alert.description);
388                } else {
389                    debug_assert!(
390                        matches!(m.payload, MessagePayload::Handshake { .. }),
391                        "QUIC uses TLS for the cryptographic handshake only"
392                    );
393                    let mut bytes = Vec::new();
394                    m.payload.encode(&mut bytes);
395                    self.quic
396                        .hs_queue
397                        .push_back((must_encrypt, bytes));
398                }
399                return;
400            }
401        }
402        if !must_encrypt {
403            let msg = &m.into();
404            let iter = self
405                .message_fragmenter
406                .fragment_message(msg);
407            for m in iter {
408                self.queue_tls_message(m.to_unencrypted_opaque());
409            }
410        } else {
411            self.send_msg_encrypt(m.into());
412        }
413    }
414
415    pub(crate) fn take_received_plaintext(&mut self, bytes: Payload) {
416        self.received_plaintext.append(bytes.0);
417    }
418
419    #[cfg(feature = "tls12")]
420    pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
421        let (dec, enc) = secrets.make_cipher_pair(side);
422        self.record_layer
423            .prepare_message_encrypter(enc);
424        self.record_layer
425            .prepare_message_decrypter(dec);
426    }
427
428    #[cfg(feature = "quic")]
429    pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
430        self.send_fatal_alert(AlertDescription::MissingExtension, why)
431    }
432
433    fn send_warning_alert(&mut self, desc: AlertDescription) {
434        warn!("Sending warning alert {:?}", desc);
435        self.send_warning_alert_no_log(desc);
436    }
437
438    pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
439        // Reject unknown AlertLevels.
440        if let AlertLevel::Unknown(_) = alert.level {
441            return Err(self.send_fatal_alert(
442                AlertDescription::IllegalParameter,
443                Error::AlertReceived(alert.description),
444            ));
445        }
446
447        // If we get a CloseNotify, make a note to declare EOF to our
448        // caller.  But do not treat unauthenticated alerts like this.
449        if self.may_receive_application_data && alert.description == AlertDescription::CloseNotify {
450            self.has_received_close_notify = true;
451            return Ok(());
452        }
453
454        // Warnings are nonfatal for TLS1.2, but outlawed in TLS1.3
455        // (except, for no good reason, user_cancelled).
456        let err = Error::AlertReceived(alert.description);
457        if alert.level == AlertLevel::Warning {
458            if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
459                return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
460            } else {
461                warn!("TLS alert warning received: {:#?}", alert);
462                return Ok(());
463            }
464        }
465
466        Err(err)
467    }
468
469    pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
470        self.send_fatal_alert(
471            match &err {
472                Error::InvalidCertificate(e) => e.clone().into(),
473                Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
474                _ => AlertDescription::HandshakeFailure,
475            },
476            err,
477        )
478    }
479
480    pub(crate) fn send_fatal_alert(
481        &mut self,
482        desc: AlertDescription,
483        err: impl Into<Error>,
484    ) -> Error {
485        debug_assert!(!self.sent_fatal_alert);
486        let m = Message::build_alert(AlertLevel::Fatal, desc);
487        self.send_msg(m, self.record_layer.is_encrypting());
488        self.sent_fatal_alert = true;
489        err.into()
490    }
491
492    /// Queues a close_notify warning alert to be sent in the next
493    /// [`Connection::write_tls`] call.  This informs the peer that the
494    /// connection is being closed.
495    ///
496    /// [`Connection::write_tls`]: crate::Connection::write_tls
497    pub fn send_close_notify(&mut self) {
498        debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
499        self.send_warning_alert_no_log(AlertDescription::CloseNotify);
500    }
501
502    fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
503        let m = Message::build_alert(AlertLevel::Warning, desc);
504        self.send_msg(m, self.record_layer.is_encrypting());
505    }
506
507    pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
508        self.message_fragmenter
509            .set_max_fragment_size(new)
510    }
511
512    pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
513        self.alpn_protocol
514            .as_ref()
515            .map(AsRef::as_ref)
516    }
517
518    /// Returns true if the caller should call [`Connection::read_tls`] as soon
519    /// as possible.
520    ///
521    /// If there is pending plaintext data to read with [`Connection::reader`],
522    /// this returns false.  If your application respects this mechanism,
523    /// only one full TLS message will be buffered by rustls.
524    ///
525    /// [`Connection::reader`]: crate::Connection::reader
526    /// [`Connection::read_tls`]: crate::Connection::read_tls
527    pub fn wants_read(&self) -> bool {
528        // We want to read more data all the time, except when we have unprocessed plaintext.
529        // This provides back-pressure to the TCP buffers. We also don't want to read more after
530        // the peer has sent us a close notification.
531        //
532        // In the handshake case we don't have readable plaintext before the handshake has
533        // completed, but also don't want to read if we still have sendable tls.
534        self.received_plaintext.is_empty()
535            && !self.has_received_close_notify
536            && (self.may_send_application_data || self.sendable_tls.is_empty())
537    }
538
539    pub(crate) fn current_io_state(&self) -> IoState {
540        IoState {
541            tls_bytes_to_write: self.sendable_tls.len(),
542            plaintext_bytes_to_read: self.received_plaintext.len(),
543            peer_has_closed: self.has_received_close_notify,
544        }
545    }
546
547    pub(crate) fn is_quic(&self) -> bool {
548        #[cfg(feature = "quic")]
549        {
550            self.protocol == Protocol::Quic
551        }
552        #[cfg(not(feature = "quic"))]
553        false
554    }
555
556    pub(crate) fn should_update_key(
557        &mut self,
558        key_update_request: &KeyUpdateRequest,
559    ) -> Result<bool, Error> {
560        match key_update_request {
561            KeyUpdateRequest::UpdateNotRequested => Ok(false),
562            KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
563            _ => Err(self.send_fatal_alert(
564                AlertDescription::IllegalParameter,
565                InvalidMessage::InvalidKeyUpdate,
566            )),
567        }
568    }
569
570    pub(crate) fn enqueue_key_update_notification(&mut self) {
571        let message = PlainMessage::from(Message::build_key_update_notify());
572        self.queued_key_update_message = Some(
573            self.record_layer
574                .encrypt_outgoing(message.borrow())
575                .encode(),
576        );
577    }
578
579    pub(crate) fn perhaps_write_key_update(&mut self) {
580        if let Some(message) = self.queued_key_update_message.take() {
581            self.sendable_tls.append(message);
582        }
583    }
584}
585
586/// Values of this structure are returned from [`Connection::process_new_packets`]
587/// and tell the caller the current I/O state of the TLS connection.
588///
589/// [`Connection::process_new_packets`]: crate::Connection::process_new_packets
590#[derive(Debug, Eq, PartialEq)]
591pub struct IoState {
592    tls_bytes_to_write: usize,
593    plaintext_bytes_to_read: usize,
594    peer_has_closed: bool,
595}
596
597impl IoState {
598    /// How many bytes could be written by [`Connection::write_tls`] if called
599    /// right now.  A non-zero value implies [`CommonState::wants_write`].
600    ///
601    /// [`Connection::write_tls`]: crate::Connection::write_tls
602    pub fn tls_bytes_to_write(&self) -> usize {
603        self.tls_bytes_to_write
604    }
605
606    /// How many plaintext bytes could be obtained via [`std::io::Read`]
607    /// without further I/O.
608    pub fn plaintext_bytes_to_read(&self) -> usize {
609        self.plaintext_bytes_to_read
610    }
611
612    /// True if the peer has sent us a close_notify alert.  This is
613    /// the TLS mechanism to securely half-close a TLS connection,
614    /// and signifies that the peer will not send any further data
615    /// on this connection.
616    ///
617    /// This is also signalled via returning `Ok(0)` from
618    /// [`std::io::Read`], after all the received bytes have been
619    /// retrieved.
620    pub fn peer_has_closed(&self) -> bool {
621        self.peer_has_closed
622    }
623}
624
625pub(crate) trait State<Data>: Send + Sync {
626    fn handle(
627        self: Box<Self>,
628        cx: &mut Context<'_, Data>,
629        message: Message,
630    ) -> Result<Box<dyn State<Data>>, Error>;
631
632    fn export_keying_material(
633        &self,
634        _output: &mut [u8],
635        _label: &[u8],
636        _context: Option<&[u8]>,
637    ) -> Result<(), Error> {
638        Err(Error::HandshakeNotComplete)
639    }
640
641    #[cfg(feature = "secret_extraction")]
642    fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
643        Err(Error::HandshakeNotComplete)
644    }
645
646    fn handle_decrypt_error(&self) {}
647}
648
649pub(crate) struct Context<'a, Data> {
650    pub(crate) common: &'a mut CommonState,
651    pub(crate) data: &'a mut Data,
652}
653
654/// Side of the connection.
655#[derive(Clone, Copy, Debug, PartialEq)]
656pub enum Side {
657    /// A client initiates the connection.
658    Client,
659    /// A server waits for a client to connect.
660    Server,
661}
662
663impl Side {
664    pub(crate) fn peer(&self) -> Self {
665        match self {
666            Self::Client => Self::Server,
667            Self::Server => Self::Client,
668        }
669    }
670}
671
672#[derive(Copy, Clone, Eq, PartialEq, Debug)]
673pub(crate) enum Protocol {
674    Tcp,
675    #[cfg(feature = "quic")]
676    Quic,
677}
678
679enum Limit {
680    Yes,
681    No,
682}
683
684const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
685const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;