s2n-quic-dc 0.88.0

Internal crate used by s2n-quic
Documentation
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

//! Provides support code for TLS streams.
//!
//! TLS is integrated into dcQUIC streams via s2n-tls, with two primary phases:
//!
//! * Handshaking (`poll_negotiate`) is handled with raw socket operations, i.e., s2n-tls directly
//!   reads/writes from the underlying socket.
//! * Dataplane I/O (`poll_send` / `poll_recv`) are handled via s2n-quic-dc owned buffers. s2n-tls
//!   operations read/write from in-memory buffers that are filled / emptied by s2n-quic-dc. This
//!   means that sending/receiving doesn't need to setup async state in s2n-tls since all
//!   operations finish synchronously. (EWOULDBLOCK is still needed when reading, but registering
//!   read interest and refilling the buffer is handled by wrapping s2n-quic-dc code).
//!
//! A future revision is expected to replace the dataplane I/O with a non-s2n-tls backed
//! implementation that will reduce intermediate buffering / copies that the current strategy
//! forces. This will also eliminate the Mutex wrapping the s2n-tls connection.

use s2n_quic_core::{
    buffer::{reader::Incremental, writer::Storage as _, Writer as _},
    event::IntoEvent,
    inet::ExplicitCongestionNotification,
    time::{Clock, Timestamp},
    varint::VarInt,
};
use std::{
    cell::UnsafeCell,
    io,
    sync::{Arc, Mutex},
    task::Poll,
    time::Duration,
};
use tokio::net::TcpStream;

use crate::{
    msg,
    stream::{
        environment::{tokio::Environment, Environment as _},
        recv,
        socket::{application::Single, Application},
    },
};

mod cert_chain;

pub use cert_chain::CertificateChain;

pub struct S2nTlsConnection {
    socket: Arc<Single<TcpStream>>,
    connection: Mutex<(Conn, ReadState)>,
    cert_chain: Option<CertificateChain>,
}

struct ReadState {
    reader: Incremental,
    buffer: bytes::BytesMut,
}

pub type Conn = Box<dyn AsMut<s2n_tls::connection::Connection> + Send>;

pub trait ConnectionBuilder: Send + Sync {
    fn build_connection(&self, mode: s2n_tls::enums::Mode) -> Result<Conn, s2n_tls::error::Error>;
}

impl<B> ConnectionBuilder for B
where
    B: s2n_tls::connection::Builder + Send + Sync,
    B::Output: Send + 'static,
{
    fn build_connection(&self, mode: s2n_tls::enums::Mode) -> Result<Conn, s2n_tls::error::Error> {
        Ok(Box::new(self.build_connection(mode)?))
    }
}

impl S2nTlsConnection {
    pub fn from_connection(
        socket: Arc<Single<TcpStream>>,
        mut connection: Conn,
    ) -> io::Result<Self> {
        (*connection)
            .as_mut()
            .set_blinding(s2n_tls::enums::Blinding::SelfService)?;

        Ok(S2nTlsConnection {
            socket,
            connection: Mutex::new((
                connection,
                ReadState {
                    reader: Incremental::new(VarInt::ZERO),
                    buffer: bytes::BytesMut::with_capacity(8192),
                },
            )),
            cert_chain: None,
        })
    }

    pub(crate) async fn negotiate(
        &mut self,
        mut initial_read_buffer: Option<crate::msg::recv::Message>,
    ) -> io::Result<()> {
        std::future::poll_fn(|cx| -> Poll<io::Result<()>> {
            #[expect(
                clippy::unwrap_used,
                reason = "lock is only poisoned if another thread already panicked while holding it"
            )]
            let s2n_connection = &mut self.connection.get_mut().unwrap().0;

            let context = NegotiateContext {
                socket: &self.socket,
                waker: cx.waker(),
                initial_read_buffer: initial_read_buffer.as_mut(),
            };

            let mut connection = CallbackResetGuard {
                conn: (**s2n_connection).as_mut(),
                reset_write: true,
                reset_read: true,
            };

            connection.set_receive_callback(Some(recv_direct_cb))?;
            connection.set_send_callback(Some(send_direct_cb))?;
            connection.set_waker(Some(cx.waker()))?;

            let mut connection = connection.set_context(&context);

            let res = match connection.poll_negotiate() {
                Poll::Ready(Ok(_)) => {
                    drop(connection);

                    // No trailing bytes allowed. The connection when initially accepted shouldn't
                    // have any additional records after the ClientHello -- such records require
                    // the server to have responded with something, which can only happen after
                    // ClientHello is read by s2n-tls here. If there is extra data that is treated
                    // as an error and the connection is closed.
                    if let Some(buffer) = &mut initial_read_buffer {
                        if !buffer.is_empty() {
                            let e = io::Error::new(
                                std::io::ErrorKind::InvalidData,
                                "received data pre-handshake",
                            );
                            return Poll::Ready(Err(e));
                        }
                    }

                    self.cert_chain = Some(CertificateChain::new(
                        (**s2n_connection).as_mut().peer_cert_chain()?,
                    )?);

                    Poll::Ready(Ok(()))
                }
                Poll::Ready(Err(e)) => Poll::Ready(Err(e.into())),
                Poll::Pending => Poll::Pending,
            };

            res
        })
        .await
    }

    #[expect(
        clippy::unwrap_used,
        clippy::unwrap_in_result,
        reason = "lock is only poisoned if another thread already panicked while holding it"
    )]
    pub(crate) fn write<M, R>(
        &self,
        message: &mut M,
        reader: &mut R,
        is_fin: bool,
    ) -> Result<(), crate::stream::send::Error>
    where
        M: super::send::application::state::Message,
        R: s2n_quic_core::buffer::reader::storage::Infallible,
    {
        let mut guard = self.connection.lock().unwrap();
        let conn = CallbackResetGuard {
            conn: (*guard.0).as_mut(),
            reset_write: true,
            reset_read: false,
        };

        let mut conn = conn.set_context_mut(message);
        conn.set_send_callback(Some(send_io_cb::<M>))
            .expect("infallible");

        // FIXME: If the application writes a large payload, this loop ends up buffering that
        // payload inside the s2n-quic-dc buffer before we even start transmitting to the network.
        // This ends up using more memory than strictly needed, and likely increasing end-to-end
        // latency. We should consider limiting how much encrypted data we are willing to buffer.
        while !reader.buffer_is_empty() {
            let Ok(chunk) = reader.read_chunk(usize::MAX);
            let mut consumed = 0;
            while consumed < chunk.len() {
                match conn.poll_send(&chunk) {
                    Poll::Ready(Ok(l)) => consumed += l,
                    Poll::Ready(Err(e)) => {
                        tracing::warn!("s2n_tls::poll_send() = Err({:?})", &e);
                        return Err(crate::stream::send::Error::new(
                            crate::stream::send::ErrorKind::FatalError,
                        ));
                    }
                    Poll::Pending => unreachable!(
                        "TODO: verify, but s2n-tls shouldn't block when the network doesn't"
                    ),
                }
            }
        }

        if is_fin {
            match conn.poll_shutdown_send() {
                Poll::Ready(Ok(_)) => {}
                Poll::Ready(Err(e)) => {
                    tracing::warn!("s2n_tls::poll_shutdown_send() = Err({:?})", &e);
                    return Err(crate::stream::send::Error::new(
                        crate::stream::send::ErrorKind::FatalError,
                    ));
                }
                Poll::Pending => unreachable!(
                    "TODO: verify, but s2n-tls shouldn't block when the network doesn't"
                ),
            }
        }

        Ok(())
    }

    /// Process TLS frames in `input` and write decrypted results into `output`.
    #[expect(
        clippy::unwrap_used,
        clippy::unwrap_in_result,
        reason = "lock poisoning only occurs if another thread already panicked while holding it; setting a receive callback is effectively infallible in the s2n-tls Rust bindings"
    )]
    pub(crate) fn read(
        &self,
        input: &mut super::recv::shared::RecvBuffer,
        output: &mut s2n_quic_core::buffer::duplex::Interposer<
            '_,
            impl s2n_quic_core::buffer::writer::Storage,
            s2n_quic_core::buffer::Reassembler,
        >,
    ) -> Result<(), super::recv::Error> {
        let mut guard = self.connection.lock().unwrap();
        let (conn, read_state) = &mut *guard;
        let conn = CallbackResetGuard {
            conn: (**conn).as_mut(),
            reset_write: false,
            reset_read: true,
        };

        let mut conn = conn.set_context_mut(input);
        conn.set_receive_callback(Some(recv_io_cb)).unwrap();

        // FIXME: We should be reading directly into `output`, but currently Interposer doesn't
        // expose the spare capacity as a buffer we can write to. That's probably fixable since we
        // have some bound on the size
        // (https://docs.rs/s2n-tls/latest/s2n_tls/connection/struct.Connection.html#method.peek_len)
        // but for now this works if a bit less efficiently than we'd like.
        read_state.buffer.reserve(8192);
        match conn.poll_recv_uninitialized(read_state.buffer.spare_capacity_mut()) {
            Poll::Ready(Ok(len)) => {
                // SAFETY: s2n-tls just informed us it filled the buffer by `len` bytes.
                unsafe {
                    let original = read_state.buffer.len();
                    read_state.buffer.set_len(
                        original
                            .checked_add(len)
                            .expect("single buffer cannot exceed isize::MAX, so cannot overflow"),
                    );
                }

                let is_fin = len == 0;

                let mut reader = match read_state
                    .reader
                    .with_storage(&mut read_state.buffer, is_fin)
                {
                    Ok(r) => r,
                    Err(s2n_quic_core::buffer::Error::OutOfRange) => {
                        return Err(super::recv::Error::new(
                            super::recv::ErrorKind::MaxDataExceeded,
                        ))
                    }
                    Err(s2n_quic_core::buffer::Error::InvalidFin) => {
                        return Err(super::recv::Error::new(super::recv::ErrorKind::InvalidFin))
                    }
                };

                match output.read_from(&mut reader) {
                    Ok(()) => {}
                    Err(s2n_quic_core::buffer::Error::OutOfRange) => {
                        return Err(super::recv::Error::new(
                            super::recv::ErrorKind::MaxDataExceeded,
                        ))
                    }
                    Err(s2n_quic_core::buffer::Error::InvalidFin) => {
                        return Err(super::recv::Error::new(super::recv::ErrorKind::InvalidFin))
                    }
                }
            }
            Poll::Ready(Err(e)) => {
                tracing::warn!("s2n_tls::poll_recv() = Err({:?})", &e);
                return Err(super::recv::Error::new(super::recv::ErrorKind::Decode));
            }
            Poll::Pending => {
                // Fall through, we expect to hit this case if we've consumed from recv::Buffer but
                // didn't get enough data to return any to the application.
            }
        }

        Ok(())
    }

    pub(crate) fn peer_cert_chain(&self) -> Option<&CertificateChain> {
        self.cert_chain.as_ref()
    }

    /// Returns whether this is an inbound connection likely originating from a synthetic caller.
    ///
    /// Returns false if we're not sure.
    pub(crate) fn is_synthetic(&self) -> bool {
        #[expect(
            clippy::unwrap_used,
            reason = "lock is only poisoned if another thread already panicked while holding it"
        )]
        let mut guard = self.connection.lock().unwrap();
        let conn: &mut s2n_tls::connection::Connection = (*guard.0).as_mut();
        let Ok(ch) = conn.client_hello() else {
            return false;
        };
        let Ok(random) = ch.random() else {
            return false;
        };
        random.starts_with(b"s2n-proctor")
    }
}

/// `NegotiateContext` for poll_negotiate.
///
/// This is registered with s2n-tls during poll_negotiate for the callbacks to call, used with
/// [`recv_direct_cb`] and [`send_direct_cb`].
struct NegotiateContext<'a> {
    socket: &'a Single<TcpStream>,
    waker: &'a std::task::Waker,
    initial_read_buffer: Option<&'a mut crate::msg::recv::Message>,
}

/// The function should return the number of bytes received, or set errno and return an error code < 0.
#[allow(clippy::extra_unused_lifetimes)]
unsafe extern "C" fn recv_direct_cb<'a>(
    ctx: *mut core::ffi::c_void,
    buf: *mut u8,
    len: u32,
) -> i32 {
    #[expect(
        clippy::unwrap_used,
        reason = "ctx is the non-null NegotiateContext pointer we set on the connection before s2n-tls invokes this callback"
    )]
    let ctx = ctx.cast::<NegotiateContext<'a>>().as_mut::<'a>().unwrap();

    let mut cx = std::task::Context::from_waker(ctx.waker);

    // FIXME: The output is not necessarily initialized, but we don't currently have an
    // uninit-compatible socket read API. In practice the buffer isn't read from but this is
    // potential undefined behavior.
    let buf = std::slice::from_raw_parts_mut(buf, len as usize);

    // Consume from the initial read buffer before we read from the socket.
    if let Some(initial_read_buffer) = ctx.initial_read_buffer.as_mut() {
        let peeked = initial_read_buffer.peek();

        let consumed = std::cmp::min(buf.len(), peeked.len());
        buf[..consumed].copy_from_slice(&peeked[..consumed]);
        initial_read_buffer.consume(consumed);

        if consumed > 0 {
            return consumed as i32;
        }
    }

    let buf = std::io::IoSliceMut::new(buf);
    let mut addr = Default::default();
    let mut cmsg = Default::default();

    match ctx
        .socket
        .read_application()
        .poll_recv(&mut cx, &mut addr, &mut cmsg, &mut [buf])
    {
        Poll::Ready(Ok(r)) => r as i32,
        Poll::Ready(Err(e)) => {
            nix::errno::Errno::try_from(e)
                .unwrap_or(nix::errno::Errno::EIO)
                .set();
            -1
        }
        Poll::Pending => {
            nix::errno::Errno::EWOULDBLOCK.set();
            -1
        }
    }
}

/// The function should return the number of bytes sent or set errno and return an error code < 0.
#[allow(clippy::extra_unused_lifetimes)]
unsafe extern "C" fn send_direct_cb<'a>(
    ctx: *mut core::ffi::c_void,
    buf: *const u8,
    len: u32,
) -> i32 {
    #[expect(
        clippy::unwrap_used,
        reason = "ctx is the non-null NegotiateContext pointer we set on the connection before s2n-tls invokes this callback"
    )]
    let ctx = ctx.cast::<NegotiateContext<'a>>().as_ref::<'a>().unwrap();

    let mut cx = std::task::Context::from_waker(ctx.waker);

    let buf = std::slice::from_raw_parts(buf, len as usize);
    let buf = std::io::IoSlice::new(buf);

    let addr = Default::default();
    let ecn = Default::default();

    match ctx
        .socket
        .write_application()
        .poll_send(&mut cx, &addr, ecn, &[buf])
    {
        Poll::Ready(Ok(r)) => r as i32,
        Poll::Ready(Err(e)) => {
            nix::errno::Errno::try_from(e)
                .unwrap_or(nix::errno::Errno::EIO)
                .set();
            -1
        }
        Poll::Pending => {
            nix::errno::Errno::EWOULDBLOCK.set();
            -1
        }
    }
}

/// The function should return the number of bytes sent or set errno and return an error code < 0.
unsafe extern "C" fn send_io_cb<'a, M>(ctx: *mut core::ffi::c_void, buf: *const u8, len: u32) -> i32
where
    M: 'a + super::send::application::state::Message,
{
    #[expect(
        clippy::unwrap_used,
        reason = "ctx is the non-null message context pointer we set on the connection before s2n-tls invokes this callback"
    )]
    let message = ctx.cast::<M>().as_mut::<'a>().unwrap();

    // Clamp the length such that we can never fail when converting the written length into an i32
    // for the return type.
    let len = len.clamp(0, i32::MAX as u32);

    let mut buf = std::slice::from_raw_parts(buf, len as usize);

    while !buf.is_empty() {
        #[expect(
            clippy::unwrap_used,
            reason = "the split point is clamped to at most buf.len(), so split_off is always in range"
        )]
        let part = buf
            .split_off(..buf.len().clamp(0, u16::MAX as usize))
            .unwrap();
        // FIXME: this return whether it allocated or not, we should have the event for that here too.
        message.push(part.len(), |mut b| {
            b.put_slice(part);

            crate::stream::send::application::transmission::Event {
                packet_number: VarInt::ZERO,
                info: crate::stream::send::application::transmission::Info {
                    // Soundness critical to get this right - it's used to set the segment length we
                    // wrote to the socket.
                    packet_len: part.len() as u16,
                    retransmission: None,
                    stream_offset: VarInt::ZERO,
                    payload_len: 0,
                    included_fin: Default::default(),
                    time_sent: unsafe { Timestamp::from_duration(Duration::from_millis(1)) },
                    ecn: Default::default(),
                },
                has_more_app_data: false,
            }
        });
    }

    #[expect(
        clippy::unwrap_used,
        reason = "clamped original length such that this is infallible"
    )]
    i32::try_from(len).unwrap()
}

/// The function should return the number of bytes received, or set errno and return an error code < 0.
#[allow(clippy::extra_unused_lifetimes)]
unsafe extern "C" fn recv_io_cb<'a>(ctx: *mut core::ffi::c_void, buf: *mut u8, len: u32) -> i32 {
    // Note that we intentionally aren't assuming unique access, since we intend to call from
    // multiple threads.
    #[expect(
        clippy::unwrap_used,
        reason = "ctx is the non-null RecvBuffer context pointer we set on the connection before s2n-tls invokes this callback"
    )]
    let mut ctx = ctx
        .cast::<super::recv::shared::RecvBuffer>()
        .as_mut::<'a>()
        .unwrap();

    let crate::either::Either::A(a) = &mut ctx else {
        unreachable!("only local buffer for TLS stream");
    };

    let output = bytes::buf::UninitSlice::from_raw_parts_mut(buf, len as usize);
    let written = a.copy_into(output);
    if written == 0 {
        if a.saw_fin() {
            0
        } else {
            nix::errno::Errno::EWOULDBLOCK.set();
            -1
        }
    } else {
        written as i32
    }
}

unsafe extern "C" fn unreachable_recv_io_cb(_: *mut core::ffi::c_void, _: *mut u8, _: u32) -> i32 {
    unreachable!(
        "s2n-tls should not call I/O callbacks outside of application controlled send/receive"
    );
}

unsafe extern "C" fn unreachable_send_io_cb(
    _: *mut core::ffi::c_void,
    _: *const u8,
    _: u32,
) -> i32 {
    unreachable!(
        "s2n-tls should not call I/O callbacks outside of application controlled send/receive"
    );
}

struct CallbackResetGuard<'a> {
    conn: &'a mut s2n_tls::connection::Connection,
    reset_write: bool,
    reset_read: bool,
}

// These setters ensure that we capture the given reference for the duration of
// `CallbackResetGuard`, ensuring it can't get dropped earlier. In the mutable case, it also can't
// be accessed at all.
impl<'a> CallbackResetGuard<'a> {
    fn set_context<T>(self, context: &'a T) -> Self {
        // SAFETY: These are reset in Drop, and we ensure that context lives at least that long by
        // capturing it for the same lifetime as connection.
        //
        // This also relies on a module-wide invariant that the T here is the same as used in callbacks
        // set in surrounding code.
        unsafe {
            if self.reset_write {
                self.conn
                    .set_send_context(context as *const T as *mut std::ffi::c_void)
                    .expect("infallible");
            }
            if self.reset_read {
                self.conn
                    .set_receive_context(context as *const T as *mut std::ffi::c_void)
                    .expect("infallible");
            }
            self
        }
    }

    fn set_context_mut<T>(self, context: &'a mut T) -> Self {
        // SAFETY: These are reset in Drop, and we ensure that context lives at least that long by
        // capturing it for the same lifetime as connection.
        //
        // This also relies on a module-wide invariant that the T here is the same as used in callbacks
        // set in surrounding code.
        unsafe {
            if self.reset_write {
                self.conn
                    .set_send_context(context as *mut _ as *mut std::ffi::c_void)
                    .expect("infallible");
            }
            if self.reset_read {
                self.conn
                    .set_receive_context(context as *mut _ as *mut std::ffi::c_void)
                    .expect("infallible");
            }
            self
        }
    }
}

impl std::ops::Deref for CallbackResetGuard<'_> {
    type Target = s2n_tls::connection::Connection;

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

impl std::ops::DerefMut for CallbackResetGuard<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.conn
    }
}

impl Drop for CallbackResetGuard<'_> {
    fn drop(&mut self) {
        // SAFETY: Resetting the callbacks is effectively infallible in Rust, they are only doing
        // more than a field write if managed send I/O is enabled in s2n-tls (which it never is for
        // s2n-tls Rust bindings). We need to reset them for soundness so our only option is to
        // abort if we got that wrong.
        //
        // If we panicked then the unwind could run destructors invoking the old callbacks, which
        // would potentially reference already freed memory: the context is pointing to the stack.
        unsafe {
            if self.reset_write {
                self.conn
                    .set_send_context(std::ptr::null_mut())
                    .unwrap_or_else(|_| std::process::abort());
                self.conn
                    .set_send_callback(Some(unreachable_send_io_cb))
                    .unwrap_or_else(|_| std::process::abort());
            }
            if self.reset_read {
                self.conn
                    .set_receive_context(std::ptr::null_mut())
                    .unwrap_or_else(|_| std::process::abort());
                self.conn
                    .set_receive_callback(Some(unreachable_recv_io_cb))
                    .unwrap_or_else(|_| std::process::abort());
            }
        }
    }
}

#[allow(clippy::unwrap_in_result, reason = "see unwraps below")]
pub(crate) fn build_stream<Sub>(
    kernel_start_time: Timestamp,
    addr: std::net::SocketAddr,
    socket: Arc<Single<TcpStream>>,
    s2n_connection: crate::stream::tls::S2nTlsConnection,
    env: &Environment<Sub>,
    // FIXME: Do we really need the map for this?
    map: &crate::path::secret::Map,
    endpoint_type: s2n_quic_core::endpoint::Type,
) -> io::Result<crate::stream::application::Builder<Sub>>
where
    Sub: crate::event::Subscriber + Clone,
{
    // The handshake is complete at this point, so the stream should be considered open. Eventually
    // at this point we'll want to export the TLS keys from the connection and add those into the
    // state below. Right now though we're continuing to use s2n-tls for maintaining relevant
    // state.

    // if the ip isn't known, then ask the socket to resolve it for us
    let peer_addr = if addr.ip().is_unspecified() {
        socket.0.peer_addr()?
    } else {
        addr
    };

    #[expect(
        clippy::unwrap_used,
        reason = "VarInt::ZERO is a constant that is always a valid normal stream Id"
    )]
    let stream_id = crate::packet::stream::Id::normal(VarInt::ZERO).unwrap();

    let params = s2n_quic_core::dc::ApplicationParams::new(
        1 << 14,
        &Default::default(),
        &Default::default(),
    );

    let meta = crate::event::api::ConnectionMeta {
        id: 0, // TODO use an actual connection ID
        timestamp: env.clock().get_time().into_event(),
    };
    let info = crate::event::api::ConnectionInfo {};

    let subscriber = env.subscriber().clone();
    let subscriber_ctx = subscriber.create_connection_context(&meta, &info);

    // Fake up a secret -- this will need some reworking to store the keys in the TLS state
    // probably?
    let mut secret = [0; 32];
    #[expect(clippy::unwrap_used, reason = "entropy failure is unrecoverable")]
    aws_lc_rs::rand::fill(&mut secret).unwrap();
    let secret = crate::path::secret::schedule::Secret::new(
        crate::path::secret::schedule::Ciphersuite::AES_GCM_128_SHA256,
        s2n_quic_core::dc::SUPPORTED_VERSIONS[0],
        endpoint_type,
        &secret,
    );

    let common = {
        let application = crate::stream::send::application::state::State { is_reliable: true };

        let fixed = crate::stream::shared::FixedValues {
            remote_ip: UnsafeCell::new(peer_addr.ip().into()),
            application: UnsafeCell::new(application),
            credentials: UnsafeCell::new(crate::credentials::Credentials {
                id: crate::credentials::Id::from([1; 16]),
                key_id: VarInt::ZERO,
            }),
        };

        crate::stream::shared::Common {
            clock: env.clock().clone(),
            gso: env.gso(),
            remote_port: peer_addr.port().into(),
            remote_queue_id: stream_id.queue_id().as_u64().into(),
            local_queue_id: u64::MAX.into(),
            last_peer_activity: Default::default(),
            fixed,
            closed_halves: 0u8.into(),
            subscriber: crate::stream::shared::Subscriber {
                subscriber,
                context: subscriber_ctx,
            },
            s2n_connection: Some(s2n_connection),
        }
    };

    let pair = crate::path::secret::map::ApplicationPair::new(
        &secret,
        VarInt::ZERO,
        crate::path::secret::schedule::Initiator::Local,
        // Not currently actually using these credentials.
        crate::path::secret::map::Dedup::disabled(),
    );
    let shared = Arc::new(crate::stream::shared::Shared {
        receiver: crate::stream::recv::shared::State::new(
            stream_id,
            &params,
            crate::stream::TransportFeatures::TCP,
            crate::stream::recv::shared::RecvBuffer::A(recv::buffer::Local::new(
                // FIXME: Maybe use a larger buffer fitting the TLS record size (14kb)?
                msg::recv::Message::new(9000),
                None,
            )),
            endpoint_type,
            &env.clock(),
        ),
        sender: crate::stream::send::shared::State::new(
            crate::stream::send::flow::non_blocking::State::new(VarInt::MAX),
            crate::stream::send::path::Info {
                max_datagram_size: params.max_datagram_size(),
                send_quantum: 10,
                ecn: ExplicitCongestionNotification::Ect0,
                next_expected_control_packet: VarInt::ZERO,
            },
            None,
        ),
        crypto: crate::stream::shared::Crypto::new(pair.sealer, pair.opener, None, map),
        application_data: None,
        common,
    });

    let read = crate::stream::recv::application::Builder::new(endpoint_type, env.reader_rt());
    let write = crate::stream::send::application::Builder::new(env.writer_rt());

    Ok(crate::stream::application::Builder {
        read,
        write,
        shared,
        sockets: Box::new(socket),
        kernel_start_time,
        app_queue_time: None,
    })
}

#[cfg(test)]
mod test;