rustls 0.24.0-dev.1

Rustls is a modern TLS library written in Rust.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt::{self, Debug};
use core::ops::{Deref, DerefMut};
use std::io::{self, BufRead, Read};

use kernel::KernelConnection;
use pki_types::FipsStatus;

use crate::common_state::{
    CommonState, ConnectionOutput, ConnectionOutputs, Event, Output, OutputEvent,
};
use crate::error::{ApiMisuse, Error};
use crate::kernel::KernelState;
use crate::msgs::{Delocator, Message, Random, ServerExtensionsInput};
use crate::quic::QuicOutput;
use crate::server::{ChooseConfig, ServerConfig, ServerSide};
use crate::suites::{ExtractedSecrets, PartiallyExtractedSecrets};
use crate::sync::Arc;
use crate::tls13::key_schedule::KeyScheduleTrafficSend;
use crate::vecbuf::ChunkVecBuffer;

// pub so that it can be re-exported from the crate root
pub mod kernel;

mod receive;
pub(crate) use receive::{Input, MessageIter, ReceivePath, TrafficTemperCounters};
pub use receive::{SliceInput, TlsInputBuffer, VecInput};

mod send;
use send::DEFAULT_BUFFER_LIMIT;
pub use send::WrittenInto;
pub(crate) use send::{SendOutput, SendPath};

pub(crate) mod split;
use split::SplitConnection;

use crate::crypto::cipher::OutboundPlain;

/// A trait generalizing over buffered client or server connections.
pub trait Connection: Debug + Deref<Target = ConnectionOutputs> {
    /// Writes TLS messages to `wr`.
    ///
    /// On success, this function returns `Ok(n)` where `n` is a number of bytes written to `wr`
    /// (after encoding and encryption).
    ///
    /// After this function returns, the connection buffer may not yet be fully flushed. The
    /// [`Self::wants_write()`] function can be used to check if the output buffer is
    /// empty.
    fn write_tls(&mut self, wr: &mut dyn io::Write) -> Result<usize, io::Error>;

    /// Returns true if the caller should call [`Self::process_new_packets()`] as soon as possible.
    ///
    /// If there is pending plaintext data to read with [`Self::reader()`],
    /// this returns false.  If your application respects this mechanism,
    /// only one full TLS message will be buffered by rustls.
    fn wants_read(&self) -> bool;

    /// Returns true if the caller should call [`Self::write_tls()`] as soon as possible.
    fn wants_write(&self) -> bool;

    /// Returns an object that allows reading plaintext.
    fn reader(&mut self) -> Reader<'_>;

    /// Returns an object that allows writing plaintext.
    fn writer(&mut self) -> Writer<'_>;

    /// Processes any new packets from the buffer supplied in `buf`.
    ///
    /// Errors from this function relate to TLS protocol errors, and
    /// are fatal to the connection.  Future calls after an error will do
    /// no new work and will return the same error. After an error is
    /// received from this function, you should not continue to fill up the buffer.
    /// However, you may call the other methods on the connection, including [`Self::writer()`],
    /// [`Self::send_close_notify()`], and [`Self::write_tls()`]. Most likely you will want to
    /// call [`Self::write_tls()`] to send any alerts queued by the error and then
    /// close the underlying connection.
    ///
    /// Success from this function comes with some sundry state data
    /// about the connection.
    fn process_new_packets(&mut self, input: &mut dyn TlsInputBuffer) -> Result<IoState, Error>;

    /// Returns an object that can derive key material from the agreed connection secrets.
    ///
    /// See [RFC5705][] for more details on what this is for.
    ///
    /// This function can be called at most once per connection.
    ///
    /// This function will error:
    ///
    /// - if called prior to the handshake completing; (check with
    ///   [`Self::is_handshaking()`] first).
    /// - if called more than once per connection.
    ///
    /// [RFC5705]: https://datatracker.ietf.org/doc/html/rfc5705
    fn exporter(&mut self) -> Result<KeyingMaterialExporter, Error>;

    /// Extract secrets, so they can be used when configuring kTLS, for example.
    ///
    /// Should be used with care as it exposes secret key material.
    fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error>;

    /// Sets a limit on the internal buffers used to buffer
    /// unsent plaintext (prior to completing the TLS handshake)
    /// and unsent TLS records.  This limit acts only on application
    /// data written through [`Self::writer()`].
    ///
    /// By default the limit is 64KB.  The limit can be set
    /// at any time, even if the current buffer use is higher.
    ///
    /// [`None`] means no limit applies, and will mean that written
    /// data is buffered without bound -- it is up to the application
    /// to appropriately schedule its plaintext and TLS writes to bound
    /// memory usage.
    ///
    /// For illustration: `Some(1)` means a limit of one byte applies:
    /// [`Self::writer()`] will accept only one byte, encrypt it and
    /// add a TLS header.  Once this is sent via [`Self::write_tls()`],
    /// another byte may be sent.
    ///
    /// # Internal write-direction buffering
    /// rustls has two buffers whose size are bounded by this setting:
    ///
    /// ## Buffering of unsent plaintext data prior to handshake completion
    ///
    /// Calls to [`Self::writer()`] before or during the handshake
    /// are buffered (up to the limit specified here).  Once the
    /// handshake completes this data is encrypted and the resulting
    /// TLS records are added to the outgoing buffer.
    ///
    /// ## Buffering of outgoing TLS records
    ///
    /// This buffer is used to store TLS records that rustls needs to
    /// send to the peer.  It is used in these two circumstances:
    ///
    /// - by [`Self::process_new_packets()`] when a handshake or alert
    ///   TLS record needs to be sent.
    /// - by [`Self::writer()`] post-handshake: the plaintext is
    ///   encrypted and the resulting TLS record is buffered.
    ///
    /// This buffer is emptied by [`Self::write_tls()`].
    fn set_buffer_limit(&mut self, limit: Option<usize>);

    /// Sets a limit on the internal buffers used to buffer decoded plaintext.
    ///
    /// See [`Self::set_buffer_limit()`] for more information on how limits are applied.
    fn set_plaintext_buffer_limit(&mut self, limit: Option<usize>);

    /// Sends a TLS1.3 `key_update` message to refresh a connection's keys.
    ///
    /// This call refreshes our encryption keys. Once the peer receives the message,
    /// it refreshes _its_ encryption and decryption keys and sends a response.
    /// Once we receive that response, we refresh our decryption keys to match.
    /// At the end of this process, keys in both directions have been refreshed.
    ///
    /// Note that this process does not happen synchronously: this call just
    /// arranges that the `key_update` message will be included in the next
    /// [`Self::write_tls()`] output.
    ///
    /// This fails with [`Error::HandshakeNotComplete`] if called before the initial
    /// handshake is complete, or if a version prior to TLS1.3 is negotiated.
    ///
    /// # Usage advice
    /// Note that other implementations (including rustls) may enforce limits on
    /// the number of `key_update` messages allowed on a given connection to prevent
    /// denial of service.  Therefore, this should be called sparingly.
    ///
    /// rustls implicitly and automatically refreshes traffic keys when needed
    /// according to the selected cipher suite's cryptographic constraints.  There
    /// is therefore no need to call this manually to avoid cryptographic keys
    /// "wearing out".
    ///
    /// The main reason to call this manually is to roll keys when it is known
    /// a connection will be idle for a long period.
    fn refresh_traffic_keys(&mut self) -> Result<(), Error>;

    /// Queues a `close_notify` warning alert to be sent in the next [`Self::write_tls`] call.
    ///
    /// This informs the peer that the connection is being closed.
    ///
    /// Does nothing if any `close_notify` or fatal alert was already sent.
    fn send_close_notify(&mut self);

    /// Returns true if the connection is currently performing the TLS handshake.
    ///
    /// During this time plaintext written to the connection is buffered in memory. After
    /// [`Self::process_new_packets()`] has been called, this might start to return `false`
    /// while the final handshake packets still need to be extracted from the connection's buffers.
    fn is_handshaking(&self) -> bool;

    /// Return the FIPS validation status of the connection.
    ///
    /// This is different from [`CryptoProvider::fips()`][]:
    /// it is concerned only with cryptography, whereas this _also_ covers TLS-level
    /// configuration that NIST recommends, as well as ECH HPKE suites if applicable.
    ///
    /// [`CryptoProvider::fips()`]: crate::crypto::CryptoProvider::fips()
    fn fips(&self) -> FipsStatus;
}

/// TLS connection state with side-specific data (`Side`).
///
/// This is one of the core abstractions of the rustls API. It represents a single connection
/// to a peer, and holds all the state associated with that connection. Note that it does
/// not hold any IO objects: the application is responsible for reading and writing TLS records.
/// If you want an object that does hold IO objects, see `rustls_util::Stream` and
/// `rustls_util::StreamOwned`.
///
/// This object is generic over the `Side` type parameter, which must implement the marker trait
/// [`SideData`]. This is used to store side-specific data.
pub(crate) struct ConnectionCommon<Side: SideData> {
    pub(crate) core: ConnectionCore<Side>,
    buffers: Buffers,
}

impl<Side: SideData> ConnectionCommon<Side> {
    pub(crate) fn new(core: ConnectionCore<Side>) -> Self {
        Self {
            core,
            buffers: Buffers::new(),
        }
    }

    #[inline]
    pub(crate) fn process_new_packets(
        &mut self,
        input: &mut dyn TlsInputBuffer,
    ) -> Result<IoState, Error> {
        if input.has_seen_eof() {
            self.buffers.has_seen_eof = true;
        } else if self
            .buffers
            .received_plaintext
            .is_full()
        {
            return Err(ApiMisuse::ReceivedPlaintextBufferFull.into());
        }

        let mut iter = MessageIter::new(input, None, &mut self.core);
        while let Some(result) = iter.next() {
            let payload = result?.reborrow(&Delocator::new(iter.input().slice_mut()));
            self.buffers
                .received_plaintext
                .append(payload.into_vec());
        }

        input.discard(
            self.core
                .common
                .recv
                .deframer
                .take_discard(),
        );

        // Release unsent buffered plaintext.
        if self.send.may_send_application_data
            && !self
                .buffers
                .sendable_plaintext
                .is_empty()
        {
            self.core
                .common
                .send
                .send_buffered_plaintext(&mut self.buffers.sendable_plaintext);
        }

        Ok(IoState::new(
            &self.core.common.send,
            &self.core.common.recv,
            &self.buffers,
        ))
    }

    pub(crate) fn wants_read(&self) -> bool {
        // We want to read more data all the time, except when we have unprocessed plaintext.
        // This provides back-pressure to the TCP buffers. We also don't want to read more after
        // the peer has sent us a close notification.
        //
        // In the handshake case we don't have readable plaintext before the handshake has
        // completed, but also don't want to read if we still have sendable tls.
        self.buffers
            .received_plaintext
            .is_empty()
            && !self.recv.has_received_close_notify
            && (self.send.may_send_application_data || self.send.sendable_tls.is_empty())
    }

    pub(crate) fn exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
        self.core.exporter()
    }

    /// Extract secrets, so they can be used when configuring kTLS, for example.
    /// Should be used with care as it exposes secret key material.
    pub(crate) fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
        self.core.dangerous_extract_secrets()
    }

    pub(crate) fn set_buffer_limit(&mut self, limit: Option<usize>) {
        self.buffers
            .sendable_plaintext
            .set_limit(limit);
        self.send.sendable_tls.set_limit(limit);
    }

    pub(crate) fn set_plaintext_buffer_limit(&mut self, limit: Option<usize>) {
        self.buffers
            .received_plaintext
            .set_limit(limit);
    }

    pub(crate) fn refresh_traffic_keys(&mut self) -> Result<(), Error> {
        self.core
            .common
            .send
            .refresh_traffic_keys()
    }

    pub(crate) fn split(self) -> Result<SplitConnection<Side>, Error> {
        // `SplitConnection` cannot be used to progress a handshake.
        if self.is_handshaking() {
            return Err(ApiMisuse::SplitDuringHandshake.into());
        }

        // We are about to drop `Buffers`
        if !self.buffers.is_empty() {
            return Err(ApiMisuse::SplitWithPendingBuffers.into());
        }

        SplitConnection::try_from(self.core)
    }
}

impl<Side: SideData> ConnectionCommon<Side> {
    /// Returns an object that allows reading plaintext.
    pub(crate) fn reader(&mut self) -> Reader<'_> {
        let common = &mut self.core.common;
        let has_received_close_notify = common.recv.has_received_close_notify;
        Reader {
            received_plaintext: &mut self.buffers.received_plaintext,
            // Are we done? i.e., have we processed all received messages, and received a
            // close_notify to indicate that no new messages will arrive?
            has_received_close_notify,
            has_seen_eof: self.buffers.has_seen_eof,
        }
    }

    /// Returns an object that allows writing plaintext.
    pub(crate) fn writer(&mut self) -> Writer<'_> {
        Writer::new(self)
    }

    pub(crate) fn write_tls(&mut self, wr: &mut dyn io::Write) -> Result<usize, io::Error> {
        self.send.sendable_tls.write_to(wr)
    }
}

impl<Side: SideData> Deref for ConnectionCommon<Side> {
    type Target = CommonState;

    fn deref(&self) -> &Self::Target {
        &self.core.common
    }
}

impl<Side: SideData> DerefMut for ConnectionCommon<Side> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.core.common
    }
}

pub(crate) struct ConnectionCore<Side: SideData> {
    pub(crate) state: Result<Side::State, Error>,
    pub(crate) side: Side::Data,
    pub(crate) common: CommonState,
}

impl<Side: SideData> ConnectionCore<Side> {
    pub(crate) fn new(state: Side::State, side: Side::Data, common: CommonState) -> Self {
        Self {
            state: Ok(state),
            side,
            common,
        }
    }

    pub(crate) fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
        Ok(self
            .dangerous_into_kernel_connection()?
            .0)
    }

    pub(crate) fn dangerous_into_kernel_connection(
        mut self,
    ) -> Result<(ExtractedSecrets, KernelConnection<Side>), Error> {
        if self.common.is_handshaking() {
            return Err(Error::HandshakeNotComplete);
        }
        Self::from_parts_into_kernel_connection(
            &mut self.common.send,
            self.common.recv,
            self.common.outputs,
            self.state?,
        )
    }

    pub(crate) fn from_parts_into_kernel_connection(
        send: &mut SendPath,
        recv: ReceivePath,
        outputs: ConnectionOutputs,
        state: Side::State,
    ) -> Result<(ExtractedSecrets, KernelConnection<Side>), Error> {
        if !send.sendable_tls.is_empty() {
            return Err(ApiMisuse::SecretExtractionWithPendingSendableData.into());
        }

        let read_seq = recv.decrypt_state.read_seq();
        let write_seq = send.encrypt_state.write_seq();

        let tls13_key_schedule = send.tls13_key_schedule.take();

        let (secrets, state) = state.into_external_state(&tls13_key_schedule)?;
        let secrets = ExtractedSecrets {
            tx: (write_seq, secrets.tx),
            rx: (read_seq, secrets.rx),
        };
        let external = KernelConnection::new(state, outputs, tls13_key_schedule)?;

        Ok((secrets, external))
    }

    pub(crate) fn exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
        match self.common.exporter.take() {
            Some(inner) => Ok(KeyingMaterialExporter { inner }),
            None if self.common.is_handshaking() => Err(Error::HandshakeNotComplete),
            None => Err(ApiMisuse::ExporterAlreadyUsed.into()),
        }
    }

    pub(crate) fn early_exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
        match self.common.early_exporter.take() {
            Some(inner) => Ok(KeyingMaterialExporter { inner }),
            None => Err(ApiMisuse::ExporterAlreadyUsed.into()),
        }
    }
}

impl ConnectionCore<ServerSide> {
    pub(crate) fn accepted(
        &mut self,
        choose: Box<ChooseConfig>,
        exts: ServerExtensionsInput,
        quic: Option<&mut dyn QuicOutput>,
        config: Arc<ServerConfig>,
    ) -> Result<(), Error> {
        self.common
            .send
            .set_max_fragment_size(config.max_fragment_size)?;
        self.common.fips = config.fips();

        let mut output = SideCommonOutput {
            side: &mut self.side,
            quic,
            common: &mut self.common,
        };

        self.state = Ok(choose.use_config(config, exts, &mut output)?);
        Ok(())
    }
}

/// Common items for buffered, std::io-using connections.
pub(crate) struct Buffers {
    pub(crate) received_plaintext: ChunkVecBuffer,
    pub(crate) sendable_plaintext: ChunkVecBuffer,
    pub(crate) has_seen_eof: bool,
}

impl Buffers {
    fn new() -> Self {
        Self {
            received_plaintext: ChunkVecBuffer::new(Some(DEFAULT_RECEIVED_PLAINTEXT_LIMIT)),
            sendable_plaintext: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
            has_seen_eof: false,
        }
    }

    fn is_empty(&self) -> bool {
        self.received_plaintext.is_empty() && self.sendable_plaintext.is_empty()
    }
}

/// A structure that implements [`std::io::Read`] for reading plaintext.
pub struct Reader<'a> {
    pub(super) received_plaintext: &'a mut ChunkVecBuffer,
    pub(super) has_received_close_notify: bool,
    pub(super) has_seen_eof: bool,
}

impl<'a> Reader<'a> {
    /// Check the connection's state if no bytes are available for reading.
    fn check_no_bytes_state(&self) -> io::Result<()> {
        match (self.has_received_close_notify, self.has_seen_eof) {
            // cleanly closed; don't care about TCP EOF: express this as Ok(0)
            (true, _) => Ok(()),
            // unclean closure
            (false, true) => Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                UNEXPECTED_EOF_MESSAGE,
            )),
            // connection still going, but needs more data: signal `WouldBlock` so that
            // the caller knows this
            (false, false) => Err(io::ErrorKind::WouldBlock.into()),
        }
    }

    /// Obtain a chunk of plaintext data received from the peer over this TLS connection.
    ///
    /// This method consumes `self` so that it can return a slice whose lifetime is bounded by
    /// the [`Connection`] that created this [`Reader`].
    pub fn into_first_chunk(self) -> io::Result<&'a [u8]> {
        match self.received_plaintext.chunk() {
            Some(chunk) => Ok(chunk),
            None => {
                self.check_no_bytes_state()?;
                Ok(&[])
            }
        }
    }
}

impl Read for Reader<'_> {
    /// Obtain plaintext data received from the peer over this TLS connection.
    ///
    /// If the peer closes the TLS session cleanly, this returns `Ok(0)`  once all
    /// the pending data has been read. No further data can be received on that
    /// connection, so the underlying TCP connection should be half-closed too.
    ///
    /// If the peer closes the TLS session uncleanly (a TCP EOF without sending a
    /// `close_notify` alert) this function returns a `std::io::Error` of type
    /// `ErrorKind::UnexpectedEof` once any pending data has been read.
    ///
    /// Note that support for `close_notify` varies in peer TLS libraries: many do not
    /// support it and uncleanly close the TCP connection (this might be
    /// vulnerable to truncation attacks depending on the application protocol).
    /// This means applications using rustls must both handle EOF
    /// from this function, *and* unexpected EOF of the underlying TCP connection.
    ///
    /// If there are no bytes to read, this returns `Err(ErrorKind::WouldBlock.into())`.
    ///
    /// You may learn the number of bytes available at any time by inspecting
    /// the return of [`Connection::process_new_packets()`].
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let len = self.received_plaintext.read(buf);
        if len > 0 || buf.is_empty() {
            return Ok(len);
        }

        self.check_no_bytes_state()
            .map(|()| len)
    }
}

impl BufRead for Reader<'_> {
    /// Obtain a chunk of plaintext data received from the peer over this TLS connection.
    /// This reads the same data as [`Reader::read()`], but returns a reference instead of
    /// copying the data.
    ///
    /// The caller should call [`Reader::consume()`] afterward to advance the buffer.
    ///
    /// See [`Reader::into_first_chunk()`] for a version of this function that returns a
    /// buffer with a longer lifetime.
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        Reader {
            // reborrow
            received_plaintext: self.received_plaintext,
            ..*self
        }
        .into_first_chunk()
    }

    fn consume(&mut self, amt: usize) {
        self.received_plaintext
            .consume_first_chunk(amt)
    }
}

const UNEXPECTED_EOF_MESSAGE: &str = "peer closed connection without sending TLS close_notify: \
https://docs.rs/rustls/latest/rustls/manual/_03_howto/index.html#unexpected-eof";

/// A structure that implements [`std::io::Write`] for writing plaintext.
pub struct Writer<'a> {
    sink: &'a mut dyn PlaintextSink,
}

impl<'a> Writer<'a> {
    /// Create a new Writer.
    ///
    /// This is not an external interface.  Get one of these objects
    /// from [`Connection::writer()`].
    pub(crate) fn new(sink: &'a mut dyn PlaintextSink) -> Self {
        Writer { sink }
    }
}

impl io::Write for Writer<'_> {
    /// Send the plaintext `buf` to the peer, encrypting and authenticating it.
    ///
    /// Once this function succeeds you should call [`Connection::write_tls()`] which will output
    /// the corresponding TLS records.
    ///
    /// This function buffers plaintext sent before the TLS handshake completes, and sends it as soon
    /// as it can.  See [`Connection::set_buffer_limit()`] to control the size of this buffer.
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.sink.write(buf)
    }

    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
        self.sink.write_vectored(bufs)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.sink.flush()
    }
}

/// Internal trait implemented by the [`ServerConnection`]/[`ClientConnection`]
/// allowing them to be the subject of a [`Writer`].
///
/// [`ServerConnection`]: crate::ServerConnection
/// [`ClientConnection`]: crate::ClientConnection
pub(crate) trait PlaintextSink {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize>;
    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize>;
    fn flush(&mut self) -> io::Result<()>;
}

impl<Side: SideData> PlaintextSink for ConnectionCommon<Side> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let len = self
            .core
            .common
            .send
            .buffer_plaintext(buf.into(), &mut self.buffers.sendable_plaintext);
        self.send.maybe_refresh_traffic_keys();
        Ok(len)
    }

    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
        let payload_owner: Vec<&[u8]>;
        let payload = match bufs.len() {
            0 => return Ok(0),
            1 => OutboundPlain::Single(bufs[0].deref()),
            _ => {
                payload_owner = bufs
                    .iter()
                    .map(|io_slice| io_slice.deref())
                    .collect();

                OutboundPlain::new(&payload_owner)
            }
        };
        let len = self
            .core
            .common
            .send
            .buffer_plaintext(payload, &mut self.buffers.sendable_plaintext);
        self.send.maybe_refresh_traffic_keys();
        Ok(len)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

/// An object of this type can export keying material.
pub struct KeyingMaterialExporter {
    pub(crate) inner: Box<dyn Exporter>,
}

impl KeyingMaterialExporter {
    /// Derives key material from the agreed connection secrets.
    ///
    /// This function fills in `output` with `output.len()` bytes of key
    /// material derived from a master connection secret using `label`
    /// and `context` for diversification. Ownership of the buffer is taken
    /// by the function and returned via the Ok result to ensure no key
    /// material leaks if the function fails.
    ///
    /// See [RFC5705][] for more details on what this does and is for.  In
    /// other libraries this is often named `SSL_export_keying_material()`
    /// or `SslExportKeyingMaterial()`.
    ///
    /// This function is not meaningful if `output.len()` is zero and will
    /// return an error in that case.
    ///
    /// [RFC5705]: https://datatracker.ietf.org/doc/html/rfc5705
    pub fn derive<T: AsMut<[u8]>>(
        &self,
        label: &[u8],
        context: Option<&[u8]>,
        mut output: T,
    ) -> Result<T, Error> {
        if output.as_mut().is_empty() {
            return Err(ApiMisuse::ExporterOutputZeroLength.into());
        }

        self.inner
            .derive(label, context, output.as_mut())
            .map(|_| output)
    }
}

impl Debug for KeyingMaterialExporter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("KeyingMaterialExporter")
            .finish_non_exhaustive()
    }
}

/// This trait is for any object that can export keying material.
///
/// The terminology comes from [RFC5705](https://datatracker.ietf.org/doc/html/rfc5705)
/// but doesn't really involve "exporting" key material (in the usual meaning of "export"
/// -- of moving an artifact from one domain to another) but is best thought of as key
/// diversification using an existing secret.  That secret is implicit in this interface,
/// so is assumed to be held by `self`. The secret should be zeroized in `drop()`.
///
/// There are several such internal implementations, depending on the context
/// and protocol version.
pub(crate) trait Exporter: Send + Sync {
    /// Fills in `output` with derived keying material.
    ///
    /// This is deterministic depending on a base secret (implicit in `self`),
    /// plus the `label` and `context` values.
    ///
    /// Must fill in `output` entirely, or return an error.
    fn derive(&self, label: &[u8], context: Option<&[u8]>, output: &mut [u8]) -> Result<(), Error>;
}

#[derive(Debug)]
pub(crate) struct ConnectionRandoms {
    pub(crate) client: [u8; 32],
    pub(crate) server: [u8; 32],
}

impl ConnectionRandoms {
    pub(crate) fn new(client: Random, server: Random) -> Self {
        Self {
            client: client.0,
            server: server.0,
        }
    }
}

/// Values of this structure are returned from [`Connection::process_new_packets()`]
/// and tell the caller the current I/O state of the TLS connection.
#[derive(Debug, Eq, PartialEq)]
pub struct IoState {
    tls_bytes_to_write: usize,
    plaintext_bytes_to_read: usize,
    peer_has_closed: bool,
}

impl IoState {
    pub(crate) fn new(send: &SendPath, recv: &ReceivePath, buffers: &Buffers) -> Self {
        Self {
            tls_bytes_to_write: send.sendable_tls.len(),
            plaintext_bytes_to_read: buffers.received_plaintext.len(),
            peer_has_closed: recv.has_received_close_notify,
        }
    }

    /// How many bytes could be written by [`Connection::write_tls()`] if called right now.
    ///
    /// A non-zero value implies [`CommonState::wants_write()`].
    pub fn tls_bytes_to_write(&self) -> usize {
        self.tls_bytes_to_write
    }

    /// How many plaintext bytes could be obtained via [`std::io::Read`] without further I/O.
    pub fn plaintext_bytes_to_read(&self) -> usize {
        self.plaintext_bytes_to_read
    }

    /// True if the peer has sent us a close_notify alert.
    ///
    /// This is the TLS mechanism to securely half-close a TLS connection, and signifies that
    /// the peer will not send any further data on this connection.
    ///
    /// This is also signalled via returning `Ok(0)` from [`std::io::Read`], after all the
    /// received bytes have been retrieved.
    pub fn peer_has_closed(&self) -> bool {
        self.peer_has_closed
    }
}

pub(crate) struct SideCommonOutput<'a, 'q> {
    pub(crate) side: &'a mut dyn SideOutput,
    pub(crate) quic: Option<&'q mut dyn QuicOutput>,
    pub(crate) common: &'a mut CommonState,
}

impl<'q> Output<'_> for SideCommonOutput<'_, 'q> {
    fn emit(&mut self, ev: Event<'_>) {
        self.side.emit(ev);
    }

    fn output(&mut self, ev: OutputEvent<'_>) {
        if let OutputEvent::ProtocolVersion(ver) = ev {
            self.common.recv.negotiated_version = Some(ver);
            self.common.send.negotiated_version(ver);
        }
        self.common.outputs.handle(ev);
    }

    fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool) {
        match self.quic() {
            Some(quic) => quic.send_msg(m, must_encrypt),
            None => self
                .common
                .send
                .send_msg(m, must_encrypt),
        }
    }

    fn quic(&mut self) -> Option<&mut dyn QuicOutput> {
        match self.quic.as_mut() {
            Some(q) => Some(&mut **q),
            None => None,
        }
    }

    fn start_traffic(&mut self) {
        self.common
            .recv
            .may_receive_application_data = true;
        self.common
            .send
            .start_outgoing_traffic();
    }

    fn receive(&mut self) -> &mut ReceivePath {
        &mut self.common.recv
    }

    fn send(&mut self) -> &mut dyn SendOutput {
        &mut self.common.send
    }
}

/// Data specific to the peer's side (client or server).
#[expect(private_bounds)]
pub trait SideData: private::Side {}

pub(crate) mod private {
    use super::*;

    pub(crate) trait Side: Debug {
        /// Data storage type.
        type Data: SideOutput;
        /// State machine type.
        type State: StateMachine;
    }

    pub(crate) trait SideOutput {
        fn emit(&mut self, ev: Event<'_>);
    }
}

use private::SideOutput;

pub(crate) trait StateMachine: Sized {
    fn handle<'m>(self, input: Input<'m>, output: &mut dyn Output<'m>) -> Result<Self, Error>;
    fn wants_input(&self) -> bool;
    fn is_traffic(&self) -> bool;
    fn handle_decrypt_error(&mut self);
    fn into_external_state(
        self,
        send_keys: &Option<Box<KeyScheduleTrafficSend>>,
    ) -> Result<(PartiallyExtractedSecrets, Box<dyn KernelState + 'static>), Error>;
}

const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;