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
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
886
887
888
889
890
891
892
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use crate::{
    either::Either,
    event::{self, builder::StreamTcpConnectErrorReason, EndpointPublisher},
    msg,
    path::secret,
    stream::{
        application::Stream,
        client::{rpc as rpc_internal, tokio as client},
        endpoint,
        environment::{
            tokio::{self as env, Environment},
            udp as udp_pool, Environment as _,
        },
        recv, socket,
    },
};
use s2n_quic::server::Name;
use s2n_quic_core::time::{Clock, Timestamp};
use std::{io, net::SocketAddr, sync::Arc, time::Duration};
use tokio::net::TcpStream;

pub mod rpc {
    pub use crate::stream::client::rpc::{InMemoryResponse, Request, Response};
}

// This trait is a solution to abstract handshake_with_entry,
// local_addr, and map methods
#[allow(async_fn_in_trait)]
pub trait Handshake: Clone {
    /// Handshake with the remote peer
    async fn handshake_with_entry(
        &self,
        remote_handshake_addr: SocketAddr,
        server_name: Name,
    ) -> std::io::Result<(secret::map::Peer, secret::HandshakeKind)>;

    fn local_addr(&self) -> std::io::Result<SocketAddr>;

    fn map(&self) -> &secret::Map;
}

impl Handshake for crate::psk::client::Provider {
    async fn handshake_with_entry(
        &self,
        remote_handshake_addr: SocketAddr,
        server_name: Name,
    ) -> std::io::Result<(secret::map::Peer, secret::HandshakeKind)> {
        self.handshake_with_entry(remote_handshake_addr, server_name)
            .await
    }

    fn local_addr(&self) -> std::io::Result<SocketAddr> {
        self.local_addr()
    }

    fn map(&self) -> &secret::Map {
        self.map()
    }
}

#[derive(Clone)]
pub struct Client<H: Handshake + Clone, S: event::Subscriber + Clone> {
    env: Environment<S>,
    handshake: H,
    default_protocol: socket::Protocol,
    linger: Option<Duration>,
}

impl<H: Handshake + Clone, S: event::Subscriber + Clone> Client<H, S> {
    #[inline]
    pub fn new(handshake: H, subscriber: S) -> io::Result<Self> {
        Self::builder().build(handshake, subscriber)
    }

    #[inline]
    pub fn builder() -> Builder {
        Builder::default()
    }

    pub fn drop_state(&self) {
        self.handshake.map().drop_state()
    }

    pub fn handshake_state(&self) -> &H {
        &self.handshake
    }

    #[inline]
    pub async fn handshake_with(
        &self,
        remote_handshake_addr: SocketAddr,
        server_name: Name,
    ) -> io::Result<secret::HandshakeKind> {
        let (_peer, kind) = self
            .handshake
            .handshake_with_entry(remote_handshake_addr, server_name)
            .await?;
        Ok(kind)
    }

    #[inline]
    async fn handshake_for_connect(
        &self,
        remote_handshake_addr: SocketAddr,
        server_name: Name,
    ) -> io::Result<secret::map::Peer> {
        let (peer, _kind) = self
            .handshake
            .handshake_with_entry(remote_handshake_addr, server_name)
            .await?;
        Ok(peer)
    }

    /// Connects using the preferred protocol
    #[inline]
    pub async fn connect(
        &self,
        handshake_addr: SocketAddr,
        acceptor_addr: SocketAddr,
        server_name: Name,
    ) -> io::Result<Stream<S>> {
        match self.default_protocol {
            socket::Protocol::Udp => {
                self.connect_udp(handshake_addr, acceptor_addr, server_name)
                    .await
            }
            socket::Protocol::Tcp => {
                self.connect_tcp(handshake_addr, acceptor_addr, server_name)
                    .await
            }
            protocol => Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("invalid default protocol {protocol:?}"),
            )),
        }
    }

    /// Makes an RPC request using the preferred protocol
    pub async fn rpc<Req, Res>(
        &self,
        handshake_addr: SocketAddr,
        acceptor_addr: SocketAddr,
        request: Req,
        response: Res,
        server_name: Name,
    ) -> io::Result<Res::Output>
    where
        Req: rpc::Request,
        Res: rpc::Response,
    {
        match self.default_protocol {
            socket::Protocol::Udp => {
                self.rpc_udp(
                    handshake_addr,
                    acceptor_addr,
                    request,
                    response,
                    server_name,
                )
                .await
            }
            socket::Protocol::Tcp => {
                self.rpc_tcp(
                    handshake_addr,
                    acceptor_addr,
                    request,
                    response,
                    server_name,
                )
                .await
            }
            protocol => Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("invalid default protocol {protocol:?}"),
            )),
        }
    }

    /// Connects using the UDP transport layer
    #[inline]
    pub async fn connect_udp(
        &self,
        handshake_addr: SocketAddr,
        acceptor_addr: SocketAddr,
        server_name: Name,
    ) -> io::Result<Stream<S>> {
        // ensure we have a secret for the peer
        let handshake = self.handshake_for_connect(handshake_addr, server_name);

        let mut stream = client::connect_udp(handshake, acceptor_addr, &self.env).await?;
        Self::write_prelude(&mut stream).await?;
        Ok(stream)
    }

    /// Makes an RPC request using the UDP transport layer
    #[inline]
    pub async fn rpc_udp<Req, Res>(
        &self,
        handshake_addr: SocketAddr,
        acceptor_addr: SocketAddr,
        request: Req,
        response: Res,
        server_name: Name,
    ) -> io::Result<Res::Output>
    where
        Req: rpc::Request,
        Res: rpc::Response,
    {
        // ensure we have a secret for the peer
        let handshake = self.handshake_for_connect(handshake_addr, server_name);

        let stream = client::connect_udp(handshake, acceptor_addr, &self.env).await?;
        rpc_internal::from_stream(stream, request, response).await
    }

    /// Connects using the TCP transport layer
    #[inline]
    pub async fn connect_tcp(
        &self,
        handshake_addr: SocketAddr,
        acceptor_addr: SocketAddr,
        server_name: Name,
    ) -> io::Result<Stream<S>> {
        // ensure we have a secret for the peer
        let handshake = self.handshake_for_connect(handshake_addr, server_name);

        let mut stream =
            client::connect_tcp(handshake, acceptor_addr, &self.env, self.linger).await?;
        Self::write_prelude(&mut stream).await?;
        Ok(stream)
    }

    /// Connects using the TLS over TCP transport layer.
    ///
    /// Note that the handshake and acceptor addresses must be the same for TLS.
    #[inline]
    pub async fn connect_tls(
        &self,
        addr: SocketAddr,
        server_name: Name,
        config: &impl crate::stream::TlsConnectionBuilder,
    ) -> io::Result<Stream<S>> {
        let stream = client::connect_tls(
            addr,
            server_name,
            config,
            &self.env,
            self.linger,
            self.handshake.map(),
        )
        .await?;
        Ok(stream)
    }

    /// Makes an RPC request using the TCP transport layer
    #[inline]
    pub async fn rpc_tcp<Req, Res>(
        &self,
        handshake_addr: SocketAddr,
        acceptor_addr: SocketAddr,
        request: Req,
        response: Res,
        server_name: Name,
    ) -> io::Result<Res::Output>
    where
        Req: rpc::Request,
        Res: rpc::Response,
    {
        // ensure we have a secret for the peer
        let handshake = self.handshake_for_connect(handshake_addr, server_name);

        let stream = client::connect_tcp(handshake, acceptor_addr, &self.env, self.linger).await?;
        rpc_internal::from_stream(stream, request, response).await
    }

    /// Connects using the TLS over TCP transport layer with a pre-existing TCP stream.
    #[inline]
    pub async fn connect_tls_with(
        &self,
        stream: TcpStream,
        server_name: Name,
        config: &impl crate::stream::TlsConnectionBuilder,
    ) -> io::Result<Stream<S>> {
        let stream = client::connect_tls_with(
            stream,
            server_name,
            config,
            &self.env,
            self.linger,
            self.handshake.map(),
        )
        .await?;
        Ok(stream)
    }

    /// Connects with a pre-existing TCP stream
    #[inline]
    pub async fn connect_tcp_with(
        &self,
        handshake_addr: SocketAddr,
        stream: TcpStream,
        server_name: Name,
    ) -> io::Result<Stream<S>> {
        // ensure we have a secret for the peer
        let handshake = self
            .handshake_for_connect(handshake_addr, server_name)
            .await?;

        let mut stream = client::connect_tcp_with(handshake, stream, &self.env).await?;
        Self::write_prelude(&mut stream).await?;
        Ok(stream)
    }

    #[inline]
    async fn write_prelude(stream: &mut Stream<S>) -> io::Result<()> {
        // TODO should we actually write the prelude here or should we do late sealer binding on
        // the first packet to reduce secret reordering on the peer

        stream
            .write_from(&mut s2n_quic_core::buffer::reader::storage::Empty)
            .await
            .map(|_| ())
    }
}

#[derive(Default)]
pub struct Builder {
    default_protocol: Option<socket::Protocol>,
    background_threads: Option<usize>,
    linger: Option<Duration>,
    send_buffer: Option<usize>,
    recv_buffer: Option<usize>,
}

impl Builder {
    pub fn with_tcp(self, enabled: bool) -> Self {
        self.with_default_protocol(if enabled {
            socket::Protocol::Tcp
        } else {
            socket::Protocol::Udp
        })
    }

    pub fn with_udp(self, enabled: bool) -> Self {
        self.with_default_protocol(if enabled {
            socket::Protocol::Udp
        } else {
            socket::Protocol::Tcp
        })
    }

    pub fn with_default_protocol(mut self, protocol: socket::Protocol) -> Self {
        self.default_protocol = Some(protocol);
        self
    }

    pub fn with_background_threads(mut self, threads: usize) -> Self {
        self.background_threads = Some(threads);
        self
    }

    pub fn with_linger(mut self, linger: Duration) -> Self {
        self.linger = Some(linger);
        self
    }

    /// Sets the send buffer for the OS socket handle.
    ///
    /// See `SO_SNDBUF` for more information.
    ///
    /// Note that this only applies to sockets that are created by s2n-quic-dc. Any sockets
    /// provided by the application will not inherit this value.
    pub fn with_send_buffer(mut self, bytes: usize) -> Self {
        self.send_buffer = Some(bytes);
        self
    }

    /// Sets the recv buffer for the OS socket handle.
    ///
    /// See `SO_RCVBUF` for more information.
    ///
    /// Note that this only applies to sockets that are created by s2n-quic-dc. Any sockets
    /// provided by the application will not inherit this value.
    pub fn with_recv_buffer(mut self, bytes: usize) -> Self {
        self.recv_buffer = Some(bytes);
        self
    }

    #[inline]
    pub fn build<H: Handshake + Clone, S: event::Subscriber + Clone>(
        self,
        handshake: H,
        subscriber: S,
    ) -> io::Result<Client<H, S>> {
        // bind the sockets to the same address family as the handshake
        let mut local_addr = handshake.local_addr()?;
        local_addr.set_port(0);
        let mut options = socket::Options::new(local_addr);

        options.send_buffer = self.send_buffer;
        options.recv_buffer = self.recv_buffer;

        let mut env = env::Builder::new(subscriber).with_socket_options(options);

        let pool = udp_pool::Config::new(handshake.map().clone());
        env = env.with_pool(pool);

        if let Some(threads) = self.background_threads {
            env = env.with_threads(threads);
        }
        let env = env.build()?;

        // default to UDP
        let default_protocol = self.default_protocol.unwrap_or(socket::Protocol::Udp);

        let linger = self.linger;

        Ok(Client {
            env,
            handshake,
            default_protocol,
            linger,
        })
    }
}

/// Connects using the UDP transport layer
///
/// Callers should send data immediately after calling this to ensure minimal
/// credential reordering.
#[inline]
pub async fn connect_udp<H, Sub>(
    handshake: H,
    acceptor_addr: SocketAddr,
    env: &Environment<Sub>,
) -> io::Result<Stream<Sub>>
where
    H: core::future::Future<Output = io::Result<secret::map::Peer>>,
    Sub: event::Subscriber + Clone,
{
    // ensure we have a secret for the peer
    let entry = handshake.await?;

    // TODO emit events (https://github.com/aws/s2n-quic/issues/2676)

    // TODO potentially branch on not using the recv pool if we're under a certain concurrency?
    let stream = if env.has_recv_pool() {
        let peer = env::udp::Pooled(acceptor_addr.into());
        endpoint::open_stream(env, entry, peer, None)?
    } else {
        let peer = env::udp::Owned(acceptor_addr.into(), recv_buffer());
        endpoint::open_stream(env, entry, peer, None)?
    };

    // build the stream inside the application context
    let stream = stream.connect()?;

    debug_assert_eq!(stream.protocol(), socket::Protocol::Udp);

    Ok(stream)
}

struct DropGuard<'a, S: event::Subscriber + Clone> {
    env: &'a Environment<S>,
    start: Timestamp,
    reason: Option<StreamTcpConnectErrorReason>,
}

impl<S: event::Subscriber + Clone> Drop for DropGuard<'_, S> {
    fn drop(&mut self) {
        if let Some(reason) = self.reason.take() {
            let now = self.env.clock().get_time();
            self.env
                .endpoint_publisher_with_time(now)
                .on_stream_connect_error(event::builder::StreamConnectError {
                    reason,
                    latency: now.saturating_duration_since(self.start),
                });
        }
    }
}

/// Connects using the TCP transport layer
///
/// Callers should send data immediately after calling this to ensure minimal
/// credential reordering.
#[inline]
pub async fn connect_tcp<H, Sub>(
    handshake: H,
    acceptor_addr: SocketAddr,
    env: &Environment<Sub>,
    linger: Option<Duration>,
) -> io::Result<Stream<Sub>>
where
    H: core::future::Future<Output = io::Result<secret::map::Peer>>,
    Sub: event::Subscriber + Clone,
{
    let start = env.clock().get_time();
    // This emits the error event in case this future gets dropped.
    let mut guard = DropGuard {
        env,
        reason: Some(StreamTcpConnectErrorReason::AbortedPendingBoth),
        start,
    };

    let connect = TcpStream::connect(acceptor_addr);

    tokio::pin!(handshake);
    tokio::pin!(connect);

    // We race the TCP connect() future with either retrieving cached path secret or handshaking to
    // produce those credentials.
    //
    // This should lower our worst-case latency from 3 RTT = TCP (1 RTT) + QUIC (~2 RTT) to just ~2 RTT.
    let mut error = None;
    let mut socket = None;
    let mut peer = None;
    while (socket.is_none() || peer.is_none()) && error.is_none() {
        tokio::select! {
            connected = &mut connect, if socket.is_none() => {
                let now = env.clock().get_time();
                env.endpoint_publisher_with_time(now).on_stream_tcp_connect(event::builder::StreamTcpConnect {
                    error: connected.is_err(),
                    latency: now.saturating_duration_since(start),
                });
                match connected {
                    Ok(v) => {
                        socket = Some(Ok(v));
                        guard.reason = match guard.reason.clone() {
                            Some(StreamTcpConnectErrorReason::AbortedPendingBoth) => Some(
                                StreamTcpConnectErrorReason::AbortedPendingHandshake
                            ),
                            other => other,
                        };
                    },
                    Err(e) => {
                        guard.reason = Some(StreamTcpConnectErrorReason::TcpConnect);
                        error = Some(e);
                        socket = Some(Err(()));
                    }
                }
            }
            handshaked = &mut handshake, if peer.is_none() => {
                match handshaked {
                    Ok(v) => {
                        peer = Some(Ok(v));
                        guard.reason = match guard.reason.clone() {
                            Some(StreamTcpConnectErrorReason::AbortedPendingBoth) => Some(
                                StreamTcpConnectErrorReason::AbortedPendingConnect
                            ),
                            other => other,
                        };
                    },
                    Err(e) => {
                        guard.reason = Some(StreamTcpConnectErrorReason::Handshake);
                        error = Some(e);
                        peer = Some(Err(()));
                    }
                }
            }
        }
    }

    // Clear the guard, we were successful. This stops emitting a metric indicating we dropped
    // before the stream was connected.
    if error.is_none() {
        guard.reason = None;
    }

    env.endpoint_publisher()
        .on_stream_connect(event::builder::StreamConnect {
            error: error.is_some(),
            handshake_success: match &peer {
                Some(Ok(_)) => event::builder::MaybeBoolCounter::Success,
                Some(Err(_)) => event::builder::MaybeBoolCounter::Failure,
                None => event::builder::MaybeBoolCounter::Aborted,
            },
            tcp_success: match &socket {
                Some(Ok(_)) => event::builder::MaybeBoolCounter::Success,
                Some(Err(_)) => event::builder::MaybeBoolCounter::Failure,
                None => event::builder::MaybeBoolCounter::Aborted,
            },
        });

    let (Some(Ok(socket)), Some(Ok(entry))) = (socket, peer) else {
        #[expect(
            clippy::unwrap_used,
            reason = "if socket or peer isn't present the error is always set, as documented above"
        )]
        return Err(error.unwrap());
    };

    // Make sure TCP_NODELAY is set
    let _ = socket.set_nodelay(true);

    if linger.is_some() {
        #[allow(deprecated)]
        let _ = socket.set_linger(linger);
    }

    // if the acceptor_ip isn't known, then ask the socket to resolve it for us
    let peer_addr = if acceptor_addr.ip().is_unspecified() {
        socket.peer_addr()?
    } else {
        acceptor_addr
    }
    .into();
    let local_port = socket.local_addr()?.port();

    let peer = env::tcp::Registered {
        socket,
        peer_addr,
        local_port,
        recv_buffer: recv_buffer(),
    };

    let stream = endpoint::open_stream(env, entry, peer, None)?;

    // build the stream inside the application context
    let stream = stream.connect()?;

    debug_assert_eq!(stream.protocol(), socket::Protocol::Tcp);

    Ok(stream)
}

/// Connects with a pre-existing TCP stream
///
/// Callers should send data immediately after calling this to ensure minimal
/// credential reordering.
///
/// # Note
///
/// The provided `map` must contain a shared secret for the `handshake_addr`
#[inline]
pub async fn connect_tcp_with<Sub>(
    entry: secret::map::Peer,
    socket: TcpStream,
    env: &Environment<Sub>,
) -> io::Result<Stream<Sub>>
where
    Sub: event::Subscriber + Clone,
{
    let local_port = socket.local_addr()?.port();
    let peer_addr = socket.peer_addr()?.into();

    let peer = env::tcp::Registered {
        socket,
        peer_addr,
        local_port,
        recv_buffer: recv_buffer(),
    };

    // TODO emit events (https://github.com/aws/s2n-quic/issues/2676)

    let stream = endpoint::open_stream(env, entry, peer, None)?;

    // build the stream inside the application context
    let stream = stream.connect()?;

    debug_assert_eq!(stream.protocol(), socket::Protocol::Tcp);

    Ok(stream)
}

#[inline]
fn recv_buffer() -> recv::shared::RecvBuffer {
    // TODO replace this with a parameter once everything is in place
    let recv_buffer = recv::buffer::Local::new(msg::recv::Message::new(9000), None);
    Either::A(recv_buffer)
}

/// Connects and negotiated TLS 1.3
#[inline]
pub async fn connect_tls<Sub>(
    addr: SocketAddr,
    server_name: Name,
    config: &impl crate::stream::TlsConnectionBuilder,
    env: &Environment<Sub>,
    linger: Option<Duration>,
    // FIXME: Do we really need the map for this?
    map: &crate::path::secret::Map,
) -> io::Result<Stream<Sub>>
where
    Sub: event::Subscriber + Clone,
{
    let start = env.clock().get_time();
    // This emits the error event in case this future gets dropped.
    let mut guard = DropGuard {
        env,
        reason: Some(StreamTcpConnectErrorReason::AbortedPendingBoth),
        start,
    };

    let connected = TcpStream::connect(addr).await;
    let kernel_start_time = env.clock().get_time();
    env.endpoint_publisher_with_time(kernel_start_time)
        .on_stream_tcp_connect(event::builder::StreamTcpConnect {
            error: connected.is_err(),
            latency: kernel_start_time.saturating_duration_since(start),
        });
    let socket = match connected {
        Ok(v) => {
            guard.reason = Some(StreamTcpConnectErrorReason::AbortedPendingHandshake);
            v
        }
        Err(e) => {
            guard.reason = Some(StreamTcpConnectErrorReason::TcpConnect);
            return Err(e);
        }
    };

    let stream = NegotiateTls {
        socket,
        addr,
        server_name,
        config,
        env,
        linger,
        map,
        start,
        kernel_start_time,
        guard,
    }
    .negotiate()
    .await?;

    Ok(stream)
}

/// Negotiates TLS 1.3 over a pre-existing TCP stream
#[inline]
pub async fn connect_tls_with<Sub>(
    socket: TcpStream,
    server_name: Name,
    config: &impl crate::stream::TlsConnectionBuilder,
    env: &Environment<Sub>,
    linger: Option<Duration>,
    // FIXME: Do we really need the map for this?
    map: &crate::path::secret::Map,
) -> io::Result<Stream<Sub>>
where
    Sub: event::Subscriber + Clone,
{
    let start = env.clock().get_time();

    // The peer address is resolved from the provided socket. This is done before arming the guard
    // below so that a failure here doesn't emit a connect error event for a handshake we never
    // started.
    let addr = socket.peer_addr()?;

    // This emits the error event in case this future gets dropped. The TCP connection is already
    // established, so we begin waiting on the handshake.
    let guard = DropGuard {
        env,
        reason: Some(StreamTcpConnectErrorReason::AbortedPendingHandshake),
        start,
    };

    let stream = NegotiateTls {
        socket,
        addr,
        server_name,
        config,
        env,
        linger,
        map,
        start,
        // The TCP connection was established before this call, so there is no TCP connect step to
        // time: using `start` as the kernel start time reports a zero TCP latency for the TLS
        // event emitted during negotiation.
        kernel_start_time: start,
        guard,
    }
    .negotiate()
    .await?;

    Ok(stream)
}

/// Negotiates TLS 1.3 over a connected TCP socket and builds the resulting stream.
///
/// This is the shared tail of [`connect_tls`] and [`connect_tls_with`]: those functions differ
/// only in how the socket is obtained.
struct NegotiateTls<'a, C, Sub>
where
    C: crate::stream::TlsConnectionBuilder,
    Sub: event::Subscriber + Clone,
{
    /// A connected TCP socket to negotiate TLS over.
    socket: TcpStream,
    /// The peer address of `socket`.
    addr: SocketAddr,
    /// The server name to request during the TLS handshake.
    server_name: Name,
    /// Builds the s2n-tls connection used for negotiation.
    config: &'a C,
    env: &'a Environment<Sub>,
    /// `SO_LINGER` to apply to `socket`, if any.
    linger: Option<Duration>,
    // FIXME: Do we really need the map for this?
    map: &'a crate::path::secret::Map,
    /// When the connect attempt began.
    start: Timestamp,
    /// When the TCP connection was established. Equal to `start` when the socket was already
    /// connected by the caller.
    kernel_start_time: Timestamp,
    guard: DropGuard<'a, Sub>,
}

impl<C, Sub> NegotiateTls<'_, C, Sub>
where
    C: crate::stream::TlsConnectionBuilder,
    Sub: event::Subscriber + Clone,
{
    #[inline]
    async fn negotiate(self) -> io::Result<Stream<Sub>> {
        let NegotiateTls {
            socket,
            addr,
            server_name,
            config,
            env,
            linger,
            map,
            start,
            kernel_start_time,
            mut guard,
        } = self;

        // Make sure TCP_NODELAY is set
        let _ = socket.set_nodelay(true);

        if linger.is_some() {
            #[allow(deprecated)]
            let _ = socket.set_linger(linger);
        }

        let mut connection = config.build_connection(s2n_tls::enums::Mode::Client)?;
        (*connection).as_mut().set_server_name(&server_name)?;

        let socket = Arc::new(crate::stream::socket::application::Single(socket));
        let mut connection =
            crate::stream::tls::S2nTlsConnection::from_connection(socket.clone(), connection)?;

        let res = connection.negotiate(None).await;

        let negotiate_end = env.clock().get_time();

        let remote_address: s2n_quic_core::inet::SocketAddress = addr.into();

        env.endpoint_publisher_with_time(negotiate_end)
            .on_stream_tls_connect(event::builder::StreamTlsConnect {
                error: res.is_err(),
                remote_address: &remote_address,
                tcp_latency: kernel_start_time.saturating_duration_since(start),
                tls_latency: negotiate_end.saturating_duration_since(kernel_start_time),
            });

        if let Err(error) = &res {
            env.endpoint_publisher_with_time(negotiate_end)
                .on_stream_tls_connect_error(event::builder::StreamTlsConnectError {
                    remote_address: &remote_address,
                    error,
                });
        }

        // Return if negotiation failed.
        res?;

        guard.reason = None;

        // 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.

        crate::stream::tls::build_stream(
            kernel_start_time,
            addr,
            socket,
            connection,
            env,
            map,
            s2n_quic_core::endpoint::Type::Client,
        )?
        .build()
    }
}