Skip to main content

net_io/
tcp.rs

1//! TCP listeners and connections.
2
3use std::io::{self, IoSlice, IoSliceMut, Read, Write};
4use std::net::{Shutdown, SocketAddr, ToSocketAddrs};
5use std::sync::{Arc, Mutex, PoisonError};
6use std::time::{Duration, Instant};
7
8use crate::accept::{Accepted, Acceptor};
9use crate::driver::DriverKind;
10use crate::error::{CloseReason, ConfigReason, LimitKind, NetError, RefusalCause, TimeoutKind};
11use crate::gate::{AdmitStage, Gate, GateCell, KillHandle, guarded};
12use crate::id::{ConnectionId, ListenerId, WorkerId};
13use crate::info::{ConnectionInfo, Endpoint, Origin, Transport};
14use crate::limits::{Effective, Limits};
15use crate::link::{ClockRef, Got, Link, WakeSource};
16use crate::opts::{ListenOptions, SocketOptions, TcpOptions};
17use crate::proxy::ProxyMode;
18use crate::session::Phase;
19use crate::sys::{self, AddrFailure, AsSock, Interest, KillSlot, Ready};
20
21/// Facts about one bound listener.
22///
23/// ```
24/// let listener = net_io::listen("127.0.0.1:0")?;
25/// assert!(listener.info().local.socket_addr().is_some());
26/// # Ok::<(), net_io::NetError>(())
27/// ```
28#[non_exhaustive]
29#[derive(Clone, Debug)]
30pub struct ListenerInfo {
31    /// The listener's index in its server (0 for a plain listener).
32    pub id: ListenerId,
33    /// Its name, if one was given.
34    pub name: Option<String>,
35    /// The bound address.
36    pub local: Endpoint,
37    /// The effective backlog; `None` when it cannot be read (macOS, adopted sockets).
38    pub backlog: Option<u32>,
39    /// The kind of socket.
40    pub transport: Transport,
41    /// Whether it expects a PROXY header.
42    pub proxy: ProxyMode,
43    /// Whether it serves TLS.
44    pub tls: bool,
45}
46
47/// Linux silently caps the backlog at `net.core.somaxconn`; read it once.
48pub(crate) fn effective_backlog(requested: u32) -> Option<u32> {
49    if cfg!(target_os = "linux") {
50        let cap = std::fs::read_to_string("/proc/sys/net/core/somaxconn")
51            .ok()
52            .and_then(|s| s.trim().parse::<u32>().ok());
53        Some(cap.map_or(requested, |c| requested.min(c)))
54    } else if cfg!(windows) {
55        Some(requested)
56    } else {
57        None
58    }
59}
60
61/// Whether accepted sockets inherit the listener's options (spike S-4, decision D-055).
62const OPTIONS_INHERITED: bool = cfg!(any(target_os = "linux", windows));
63
64pub(crate) fn bind_error(addr: SocketAddr, e: io::Error) -> NetError {
65    match sys::classify_addr_error(&e) {
66        AddrFailure::InUse => NetError::AddrInUse { addr },
67        AddrFailure::NotAvailable => NetError::AddrNotAvailable { addr },
68        AddrFailure::Permission => NetError::PermissionDenied { what: "bind" },
69        _ if e.kind() == io::ErrorKind::Unsupported => NetError::Unsupported {
70            feature: "SO_REUSEPORT",
71            platform: std::env::consts::OS,
72        },
73        _ => NetError::Bind { addr, source: e },
74    }
75}
76
77fn connect_error(addr: SocketAddr, after: Duration, e: io::Error) -> NetError {
78    match sys::classify_addr_error(&e) {
79        AddrFailure::Refused => NetError::ConnectionRefused { addr },
80        AddrFailure::HostUnreachable => NetError::HostUnreachable { addr },
81        AddrFailure::NetworkUnreachable => NetError::NetworkUnreachable { addr },
82        AddrFailure::TimedOut => NetError::ConnectTimeout { addr, after },
83        AddrFailure::NotAvailable => NetError::AddrNotAvailable { addr },
84        AddrFailure::Permission => NetError::PermissionDenied { what: "connect" },
85        _ => NetError::Os {
86            op: "connect",
87            source: e,
88        },
89    }
90}
91
92fn resolve<A: ToSocketAddrs>(addr: A) -> Result<Vec<SocketAddr>, NetError> {
93    let addrs: Vec<SocketAddr> = addr
94        .to_socket_addrs()
95        .map_err(|e| NetError::Os {
96            op: "resolve",
97            source: e,
98        })?
99        .collect();
100    if addrs.is_empty() {
101        return Err(NetError::NoAddresses);
102    }
103    Ok(addrs)
104}
105
106/// A listening TCP socket created by net-io, so options that must precede `bind` can be set.
107///
108/// # Examples
109///
110/// ```no_run
111/// let listener = net_io::listen("0.0.0.0:7000")?;
112/// loop {
113///     let (mut conn, info) = listener.accept()?;
114///     println!("connection {} from {:?}", info.id, info.client_addr());
115///     conn.send_all(b"hello\n")?;
116///     conn.close()?;
117/// }
118/// # Ok::<(), net_io::NetError>(())
119/// ```
120#[derive(Debug)]
121pub struct TcpListener {
122    inner: std::net::TcpListener,
123    info: ListenerInfo,
124    tcp: TcpOptions,
125    acceptor: Mutex<Acceptor>,
126}
127
128impl TcpListener {
129    /// Binds with safe defaults (see [`crate::listen`]).
130    ///
131    /// # Errors
132    ///
133    /// `AddrInUse`, `PermissionDenied`, `AddrNotAvailable`, `NoAddresses`, `Bind`.
134    pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<TcpListener, NetError> {
135        TcpListener::bind_with(addr, ListenOptions::new())
136    }
137
138    /// Binds with `options`, applied in the order `docs/API.md` gives.
139    ///
140    /// # Errors
141    ///
142    /// As [`TcpListener::bind`]; `Unsupported` for an option the platform lacks.
143    pub fn bind_with<A: ToSocketAddrs>(
144        addr: A,
145        options: ListenOptions,
146    ) -> Result<TcpListener, NetError> {
147        let mut last = NetError::NoAddresses;
148        for a in resolve(addr)? {
149            match sys::tcp_listener(a, &options.params()) {
150                Ok(l) => return TcpListener::finish(l, options, ListenerId(0), None),
151                Err(e) => last = bind_error(a, e),
152            }
153        }
154        Err(last)
155    }
156
157    pub(crate) fn finish(
158        inner: std::net::TcpListener,
159        options: ListenOptions,
160        id: ListenerId,
161        name: Option<String>,
162    ) -> Result<TcpListener, NetError> {
163        let local = inner
164            .local_addr()
165            .map_err(|e| NetError::from_os("getsockname", e))?;
166        if OPTIONS_INHERITED && !options.tcp.is_empty() {
167            options.tcp.apply(&inner, local.is_ipv6())?;
168        }
169        Ok(TcpListener {
170            info: ListenerInfo {
171                id,
172                name,
173                local: Endpoint::Ip(local),
174                backlog: effective_backlog(options.backlog),
175                transport: Transport::Tcp,
176                proxy: ProxyMode::Off,
177                tls: false,
178            },
179            inner,
180            tcp: options.tcp,
181            acceptor: Mutex::new(Acceptor::new()),
182        })
183    }
184
185    /// Blocks until a connection arrives; applies per-connection options, normalizes
186    /// the peer, issues a `ConnectionId`. No admission: a plain listener has no gate.
187    ///
188    /// # Errors
189    ///
190    /// `Limit { which: Descriptors }` when exhaustion persists past one backoff step; `Os`.
191    pub fn accept(&self) -> Result<(TcpConnection, ConnectionInfo), NetError> {
192        match self.accept_until(None)? {
193            Some(pair) => Ok(pair),
194            None => Err(NetError::TimedOut {
195                kind: TimeoutKind::Read,
196            }),
197        }
198    }
199
200    /// As [`TcpListener::accept`], but `Ok(None)` when nothing arrived within `timeout`.
201    ///
202    /// # Errors
203    ///
204    /// As [`TcpListener::accept`].
205    ///
206    /// ```
207    /// let listener = net_io::listen("127.0.0.1:0")?;
208    /// let got = listener.accept_timeout(std::time::Duration::from_millis(10))?;
209    /// assert!(got.is_none());
210    /// # Ok::<(), net_io::NetError>(())
211    /// ```
212    pub fn accept_timeout(
213        &self,
214        timeout: Duration,
215    ) -> Result<Option<(TcpConnection, ConnectionInfo)>, NetError> {
216        self.accept_until(Some(Instant::now() + timeout))
217    }
218
219    fn accept_until(
220        &self,
221        deadline: Option<Instant>,
222    ) -> Result<Option<(TcpConnection, ConnectionInfo)>, NetError> {
223        let mut paused_once = false;
224        loop {
225            let outcome = self
226                .acceptor
227                .lock()
228                .unwrap_or_else(PoisonError::into_inner)
229                .accept(&self.inner);
230            match outcome {
231                Accepted::Conn((stream, peer)) => {
232                    let conn = TcpConnection::accepted(stream, peer, &self.tcp, self.info.id)?;
233                    let info = conn.info().clone();
234                    return Ok(Some((conn, info)));
235                }
236                Accepted::Skipped(_) => continue,
237                Accepted::Again => {
238                    let timeout = match deadline {
239                        None => None,
240                        Some(d) => {
241                            let left = d.saturating_duration_since(Instant::now());
242                            if left.is_zero() {
243                                return Ok(None);
244                            }
245                            Some(left)
246                        }
247                    };
248                    match sys::wait(self.inner.sock(), Interest::Read, None, timeout) {
249                        Ok(Ready::TimedOut) => return Ok(None),
250                        Ok(_) => continue,
251                        Err(e) => return Err(NetError::from_os("poll", e)),
252                    }
253                }
254                Accepted::Pause(backoff) => {
255                    if paused_once {
256                        return Err(NetError::Limit {
257                            which: LimitKind::Descriptors,
258                        });
259                    }
260                    paused_once = true;
261                    std::thread::sleep(backoff);
262                }
263                Accepted::Failed(e) => return Err(NetError::from_os("accept", e)),
264            }
265        }
266    }
267
268    pub(crate) fn std(&self) -> &std::net::TcpListener {
269        &self.inner
270    }
271
272    /// Records the listener's id and name in its facts (adopted listeners).
273    pub(crate) fn set_identity(&mut self, id: ListenerId, name: Option<String>) {
274        self.info.id = id;
275        self.info.name = name;
276    }
277
278    /// Records whether the listener serves TLS in its facts.
279    pub(crate) fn set_tls(&mut self, on: bool) {
280        self.info.tls = on;
281    }
282
283    /// Records the listener's PROXY requirement in its facts.
284    pub(crate) fn set_proxy_mode(&mut self, mode: crate::proxy::ProxyMode) {
285        self.info.proxy = mode;
286    }
287
288    pub(crate) fn tcp_options(&self) -> &TcpOptions {
289        &self.tcp
290    }
291
292    /// Facts about this listener.
293    #[must_use]
294    pub fn info(&self) -> &ListenerInfo {
295        &self.info
296    }
297
298    /// The bound address.
299    ///
300    /// # Errors
301    ///
302    /// `Os` when `getsockname` fails.
303    pub fn local_addr(&self) -> Result<SocketAddr, NetError> {
304        self.inner
305            .local_addr()
306            .map_err(|e| NetError::from_os("getsockname", e))
307    }
308
309    /// Adopts an existing listening socket (checked with `SO_ACCEPTCONN` and `SO_TYPE`).
310    ///
311    /// # Errors
312    ///
313    /// `InvalidConfig { field: "socket", reason: NotListening }`.
314    ///
315    /// ```
316    /// let std_listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
317    /// let listener = net_io::TcpListener::from_std(std_listener)?;
318    /// assert!(listener.local_addr().is_ok());
319    /// # Ok::<(), net_io::NetError>(())
320    /// ```
321    pub fn from_std(listener: std::net::TcpListener) -> Result<TcpListener, NetError> {
322        match sys::is_listening_stream(listener.sock()) {
323            Ok(true) => {}
324            Ok(false) => {
325                return Err(NetError::InvalidConfig {
326                    field: "socket",
327                    reason: ConfigReason::NotListening,
328                });
329            }
330            Err(e) => return Err(NetError::from_os("getsockopt", e)),
331        }
332        listener
333            .set_nonblocking(true)
334            .map_err(|e| NetError::from_os("ioctl", e))?;
335        TcpListener::finish(
336            listener,
337            ListenOptions::new().tcp_options(TcpOptions::new()),
338            ListenerId(0),
339            None,
340        )
341        .map(|mut l| {
342            l.info.backlog = None;
343            l
344        })
345    }
346
347    /// Gives the socket up (it stays non-blocking).
348    #[must_use]
349    pub fn into_std(self) -> std::net::TcpListener {
350        self.inner
351    }
352
353    /// A second handle to the same listening socket.
354    ///
355    /// # Errors
356    ///
357    /// `Os` when duplication fails.
358    pub fn try_clone(&self) -> Result<TcpListener, NetError> {
359        let inner = self
360            .inner
361            .try_clone()
362            .map_err(|e| NetError::from_os("dup", e))?;
363        Ok(TcpListener {
364            inner,
365            info: self.info.clone(),
366            tcp: self.tcp,
367            acceptor: Mutex::new(Acceptor::new()),
368        })
369    }
370}
371
372#[cfg(unix)]
373impl std::os::fd::AsFd for TcpListener {
374    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
375        self.inner.as_fd()
376    }
377}
378
379#[cfg(unix)]
380impl From<TcpListener> for std::os::fd::OwnedFd {
381    fn from(l: TcpListener) -> std::os::fd::OwnedFd {
382        l.inner.into()
383    }
384}
385
386#[cfg(unix)]
387impl TryFrom<std::os::fd::OwnedFd> for TcpListener {
388    type Error = NetError;
389    fn try_from(fd: std::os::fd::OwnedFd) -> Result<TcpListener, NetError> {
390        TcpListener::from_std(std::net::TcpListener::from(fd))
391    }
392}
393
394#[cfg(windows)]
395impl std::os::windows::io::AsSocket for TcpListener {
396    fn as_socket(&self) -> std::os::windows::io::BorrowedSocket<'_> {
397        self.inner.as_socket()
398    }
399}
400
401#[cfg(windows)]
402impl From<TcpListener> for std::os::windows::io::OwnedSocket {
403    fn from(l: TcpListener) -> std::os::windows::io::OwnedSocket {
404        l.inner.into()
405    }
406}
407
408#[cfg(windows)]
409impl TryFrom<std::os::windows::io::OwnedSocket> for TcpListener {
410    type Error = NetError;
411    fn try_from(s: std::os::windows::io::OwnedSocket) -> Result<TcpListener, NetError> {
412        TcpListener::from_std(std::net::TcpListener::from(s))
413    }
414}
415
416/// Options for an outbound connection.
417///
418/// ```no_run
419/// use net_io::{ConnectOptions, TcpConnection};
420/// use std::time::Duration;
421/// let options = ConnectOptions::new().timeout(Duration::from_secs(3));
422/// let conn = TcpConnection::connect_host("example.com", 443, options)?;
423/// println!("connected to {}", conn.peer_addr());
424/// # Ok::<(), net_io::NetError>(())
425/// ```
426#[must_use]
427#[derive(Clone, Debug)]
428pub struct ConnectOptions {
429    timeout: Duration,
430    local_addr: Option<SocketAddr>,
431    tcp: TcpOptions,
432    limits: Limits,
433    happy_eyeballs: bool,
434    attempt_delay: Duration,
435}
436
437impl Default for ConnectOptions {
438    fn default() -> ConnectOptions {
439        ConnectOptions {
440            timeout: Duration::from_secs(10),
441            local_addr: None,
442            tcp: TcpOptions::new().nodelay(true),
443            limits: Limits::default(),
444            happy_eyeballs: false,
445            attempt_delay: Duration::from_millis(250),
446        }
447    }
448}
449
450impl ConnectOptions {
451    /// Timeout 10 s, `TCP_NODELAY` on, no local bind.
452    pub fn new() -> ConnectOptions {
453        ConnectOptions::default()
454    }
455
456    /// The total time for all attempts.
457    pub fn timeout(mut self, total: Duration) -> ConnectOptions {
458        self.timeout = total;
459        self
460    }
461
462    /// Binds to this address before connecting.
463    pub fn local_addr(mut self, addr: SocketAddr) -> ConnectOptions {
464        self.local_addr = Some(addr);
465        self
466    }
467
468    /// Options applied before the connect.
469    pub fn tcp_options(mut self, options: TcpOptions) -> ConnectOptions {
470        self.tcp = options;
471        self
472    }
473
474    /// Limits for the connection.
475    pub fn limits(mut self, limits: Limits) -> ConnectOptions {
476        self.limits = limits;
477        self
478    }
479
480    /// Happy Eyeballs (RFC 8305, simplified because `std` resolution returns both
481    /// families at once): attempts overlap instead of waiting for each other, IPv6
482    /// first and the families interleaved, and the first established connection wins.
483    /// The total timeout still bounds everything; the others are reset.
484    pub fn happy_eyeballs(mut self, on: bool) -> ConnectOptions {
485        self.happy_eyeballs = on;
486        self
487    }
488
489    /// How long an attempt runs alone before the next one starts (250 ms; held to
490    /// 100 ms through 2 s). An attempt that fails starts the next at once.
491    pub fn attempt_delay(mut self, d: Duration) -> ConnectOptions {
492        self.attempt_delay = d.clamp(Duration::from_millis(100), Duration::from_secs(2));
493        self
494    }
495}
496
497/// A connected TCP socket that carries its own limits.
498///
499/// Every read honours the current phase's deadline (a connection from `accept`
500/// starts `Idle` under the idle timeout; one from `connect` starts `Receiving`
501/// under the read timeout), the exchange deadline, and the inbound minimum
502/// rate; every write honours the write deadline and the outbound minimum rate.
503/// One owner: other threads act on it only through its [`KillHandle`].
504///
505/// # Examples
506///
507/// ```no_run
508/// use net_io::{Limits, Phase};
509/// use std::time::{Duration, Instant};
510///
511/// let mut conn = net_io::connect("127.0.0.1:7000")?;
512/// conn.set_limits(Limits::builder().read_timeout(Duration::from_secs(5)).build()?);
513/// conn.set_phase(Phase::Receiving);
514/// conn.set_exchange_deadline(Some(Instant::now() + Duration::from_secs(20)));
515/// let mut buf = [0u8; 1024];
516/// let n = conn.recv(&mut buf)?;
517/// # let _ = n;
518/// # Ok::<(), net_io::NetError>(())
519/// ```
520pub struct TcpConnection {
521    link: Option<Link>,
522}
523
524impl TcpConnection {
525    /// Connects with a 10 s timeout across every resolved address (see [`crate::connect`]).
526    ///
527    /// # Errors
528    ///
529    /// `ConnectTimeout`, `ConnectionRefused`, `HostUnreachable`, `NetworkUnreachable`, `NoAddresses`.
530    pub fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpConnection, NetError> {
531        TcpConnection::connect_with(addr, ConnectOptions::new())
532    }
533
534    /// Connects with `options`.
535    ///
536    /// # Errors
537    ///
538    /// As [`TcpConnection::connect`].
539    pub fn connect_with<A: ToSocketAddrs>(
540        addr: A,
541        options: ConnectOptions,
542    ) -> Result<TcpConnection, NetError> {
543        let addrs = resolve(addr)?;
544        TcpConnection::connect_addrs(&addrs, &options)
545    }
546
547    /// Resolves `host` with the standard library and connects to the addresses in
548    /// order; each attempt gets the remaining time divided by the remaining
549    /// addresses (at least 1 s).
550    ///
551    /// # Errors
552    ///
553    /// `NoAddresses`, or the last connect error.
554    pub fn connect_host(
555        host: &str,
556        port: u16,
557        options: ConnectOptions,
558    ) -> Result<TcpConnection, NetError> {
559        let addrs = resolve((host, port))?;
560        TcpConnection::connect_addrs(&addrs, &options)
561    }
562
563    fn connect_addrs(
564        addrs: &[SocketAddr],
565        options: &ConnectOptions,
566    ) -> Result<TcpConnection, NetError> {
567        if options.happy_eyeballs && addrs.len() > 1 {
568            return connect_racing(addrs, options);
569        }
570        let start = Instant::now();
571        let deadline = start + options.timeout;
572        let mut last = NetError::NoAddresses;
573        for (i, addr) in addrs.iter().enumerate() {
574            let left = deadline.saturating_duration_since(Instant::now());
575            if left.is_zero() {
576                break;
577            }
578            let remaining = (addrs.len() - i) as u32;
579            let attempt = (left / remaining).max(Duration::from_secs(1)).min(left);
580            match connect_one(*addr, options, attempt) {
581                Ok(conn) => return Ok(conn),
582                Err(e) => last = e,
583            }
584        }
585        if matches!(last, NetError::NoAddresses) {
586            if let Some(addr) = addrs.first() {
587                last = NetError::ConnectTimeout {
588                    addr: *addr,
589                    after: options.timeout,
590                };
591            }
592        }
593        Err(last)
594    }
595
596    pub(crate) fn accepted(
597        stream: std::net::TcpStream,
598        peer: SocketAddr,
599        tcp: &TcpOptions,
600        listener: ListenerId,
601    ) -> Result<TcpConnection, NetError> {
602        let local = stream
603            .local_addr()
604            .map_err(|e| NetError::from_os("getsockname", e))?;
605        if !OPTIONS_INHERITED && !tcp.is_empty() {
606            tcp.apply(&stream, local.is_ipv6())?;
607        }
608        let info = ConnectionInfo::new_tcp(
609            crate::id::issue_single(),
610            Some(listener),
611            WorkerId(0),
612            Origin::Accepted,
613            local,
614            peer,
615            Instant::now(),
616        );
617        let limits = Arc::new(Limits::default().effective(DriverKind::Blocking));
618        Ok(TcpConnection::from_link(Link::new(
619            sys::Stream::Tcp(stream),
620            info,
621            limits,
622            ClockRef::Monotonic,
623            Arc::new(KillSlot::new()),
624            WakeSource::Thread,
625            Phase::Idle,
626        )))
627    }
628
629    pub(crate) fn from_link(link: Link) -> TcpConnection {
630        TcpConnection { link: Some(link) }
631    }
632
633    /// The process at an end of a named pipe.
634    #[cfg(all(windows, feature = "local"))]
635    pub(crate) fn pipe_pid(&self, server: bool) -> Result<u32, NetError> {
636        match &self.link_ref().stream {
637            sys::Stream::Pipe(p) => if server {
638                p.server_pid()
639            } else {
640                p.client_pid()
641            }
642            .map_err(|e| NetError::from_os("GetNamedPipeClientProcessId", e)),
643            _ => Err(NetError::Unsupported {
644                feature: "client_pid on a socket",
645                platform: std::env::consts::OS,
646            }),
647        }
648    }
649
650    pub(crate) fn take_link(&mut self) -> Option<Link> {
651        self.link.take()
652    }
653
654    pub(crate) fn link(&mut self) -> Result<&mut Link, NetError> {
655        self.link.as_mut().ok_or(NetError::Closed)
656    }
657
658    pub(crate) fn link_ref(&self) -> &Link {
659        match &self.link {
660            Some(l) => l,
661            // Only `take_link` (crate-internal, at the end of a handler) empties it.
662            None => unreachable_link(),
663        }
664    }
665
666    /// One receive; `Ok(0)` means the peer closed its side. A zero-length `buf`
667    /// returns `Ok(0)` without a system call (check `buf.len()`).
668    ///
669    /// # Errors
670    ///
671    /// `TimedOut { kind }`, `SlowPeer { In }`, `ConnectionReset`, `Killed`, `Closed`.
672    pub fn recv(&mut self, buf: &mut [u8]) -> Result<usize, NetError> {
673        let link = self.link()?;
674        loop {
675            match link.read(buf)? {
676                Got::Data(n) => return Ok(n),
677                Got::Eof => return Ok(0),
678                Got::Woken => continue,
679            }
680        }
681    }
682
683    /// Receives until `buf` is full.
684    ///
685    /// # Errors
686    ///
687    /// As [`TcpConnection::recv`]; `Closed` when the peer closes first.
688    pub fn recv_exact(&mut self, buf: &mut [u8]) -> Result<(), NetError> {
689        let mut filled = 0;
690        while filled < buf.len() {
691            match self.recv(&mut buf[filled..])? {
692                0 => return Err(NetError::Closed),
693                n => filled += n,
694            }
695        }
696        Ok(())
697    }
698
699    /// One receive into the first non-empty slice.
700    ///
701    /// # Errors
702    ///
703    /// As [`TcpConnection::recv`].
704    pub fn recv_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, NetError> {
705        match bufs.iter_mut().find(|b| !b.is_empty()) {
706            Some(first) => self.recv(first),
707            None => Ok(0),
708        }
709    }
710
711    /// Reads without consuming (`MSG_PEEK`), within the read timeout.
712    ///
713    /// # Errors
714    ///
715    /// As [`TcpConnection::recv`]; `Unsupported` on a TLS connection.
716    pub fn peek(&self, buf: &mut [u8]) -> Result<usize, NetError> {
717        let link = self.link_ref();
718        if buf.is_empty() {
719            return Ok(0);
720        }
721        if link.has_tls() {
722            // The socket holds ciphertext; peeking at it would mean nothing here.
723            return Err(NetError::Unsupported {
724                feature: "peek on a TLS connection",
725                platform: std::env::consts::OS,
726            });
727        }
728        let timeout = link.limits.read_timeout;
729        match link.stream.wait(Interest::Read, None, Some(timeout)) {
730            Ok(Ready::TimedOut) => {
731                return Err(NetError::TimedOut {
732                    kind: TimeoutKind::Read,
733                });
734            }
735            Ok(_) => {}
736            Err(e) => return Err(NetError::from_os("poll", e)),
737        }
738        link.stream
739            .peek(buf)
740            .map_err(|e| NetError::from_os("recv", e))
741    }
742
743    /// One send after the gate check; may be partial.
744    ///
745    /// # Errors
746    ///
747    /// `TimedOut`, `SlowPeer { Out }`, `BrokenPipe`, `ConnectionReset`, `EgressDenied`, `Killed`.
748    pub fn send(&mut self, buf: &[u8]) -> Result<usize, NetError> {
749        self.link()?.write(buf)
750    }
751
752    /// Sends all of `buf`, continuing from the exact offset; the gate check runs
753    /// before every system call.
754    ///
755    /// # Errors
756    ///
757    /// As [`TcpConnection::send`].
758    pub fn send_all(&mut self, buf: &[u8]) -> Result<(), NetError> {
759        self.link()?.write_all(buf)
760    }
761
762    /// One vectored send (up to 64 slices) after the gate check; may be partial.
763    ///
764    /// # Errors
765    ///
766    /// As [`TcpConnection::send`].
767    pub fn send_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, NetError> {
768        self.link()?.write_vectored(bufs)
769    }
770
771    /// Sends every slice, advancing them in place (no copy).
772    ///
773    /// # Errors
774    ///
775    /// As [`TcpConnection::send`].
776    pub fn send_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), NetError> {
777        self.link()?.write_all_vectored(bufs)
778    }
779
780    /// Half-close: `Write` sends FIN and keeps reading; `Read` stops reading.
781    ///
782    /// # Errors
783    ///
784    /// `Closed`, `Os`.
785    pub fn shutdown(&mut self, how: Shutdown) -> Result<(), NetError> {
786        self.link()?.shutdown(how)
787    }
788
789    /// Graceful close: FIN, then reads and discards up to 64 KiB for up to 2 s so
790    /// unread input does not cause an RST that destroys the last response.
791    ///
792    /// # Errors
793    ///
794    /// None in this version; the signature leaves room for a flush error.
795    pub fn close(mut self) -> Result<(), NetError> {
796        if let Some(link) = self.link.take() {
797            let reason = link.reason_or(CloseReason::SessionClosed);
798            link.finish(reason);
799        }
800        Ok(())
801    }
802
803    /// Abortive close: RST, kernel resources freed at once.
804    pub fn abort(mut self) {
805        if let Some(link) = self.link.take() {
806            let reason = link.reason_or(CloseReason::SessionError);
807            let reason = if reason.is_abortive() {
808                reason
809            } else {
810                CloseReason::SessionError
811            };
812            link.finish(reason);
813        }
814    }
815
816    /// What net-io knows about this connection.
817    #[must_use]
818    pub fn info(&self) -> &ConnectionInfo {
819        &self.link_ref().info
820    }
821
822    /// The connection's id.
823    #[must_use]
824    pub fn id(&self) -> ConnectionId {
825        self.link_ref().info.id
826    }
827
828    /// The socket peer.
829    #[must_use]
830    pub fn peer_addr(&self) -> SocketAddr {
831        self.link_ref()
832            .info
833            .peer
834            .socket_addr()
835            .unwrap_or_else(|| SocketAddr::from(([0, 0, 0, 0], 0)))
836    }
837
838    /// Our end.
839    #[must_use]
840    pub fn local_addr(&self) -> SocketAddr {
841        self.link_ref()
842            .info
843            .local
844            .socket_addr()
845            .unwrap_or_else(|| SocketAddr::from(([0, 0, 0, 0], 0)))
846    }
847
848    /// A handle other threads can use to abort this connection.
849    #[must_use]
850    pub fn kill_handle(&self) -> KillHandle {
851        let link = self.link_ref();
852        KillHandle {
853            slot: link.slot.clone(),
854            generation: link.generation,
855            id: link.info.id,
856        }
857    }
858
859    /// Replaces the limits from the next operation on (unset values: blocking-driver defaults).
860    pub fn set_limits(&mut self, limits: Limits) {
861        if let Ok(link) = self.link() {
862            let e: Effective = limits.effective(DriverKind::Blocking);
863            link.set_limits(e);
864        }
865    }
866
867    /// Chooses which deadlines apply.
868    pub fn set_phase(&mut self, phase: Phase) {
869        if let Ok(link) = self.link() {
870            link.set_phase(phase);
871        }
872    }
873
874    /// The deadline for the current exchange (`None` clears it).
875    pub fn set_exchange_deadline(&mut self, at: Option<Instant>) {
876        if let Ok(link) = self.link() {
877            link.set_exchange_deadline(at);
878        }
879    }
880
881    /// Registers this dialed connection with `gate` (`Gate::admit` with
882    /// `AdmitStage::Dialed`): from then on `Gate::check` runs before every write
883    /// and `Gate::closed` runs once at close, so a back-channel or outbound
884    /// connection can be revoked like an accepted one.
885    ///
886    /// # Errors
887    ///
888    /// `Refused { cause: Gate(code) }` when the gate refuses (the connection is
889    /// then aborted and later calls return `Closed`); `InvalidConfig { field:
890    /// "gate" }` when a gate is already set; `Closed`.
891    ///
892    /// ```no_run
893    /// use std::sync::Arc;
894    /// let mut upstream = net_io::connect("10.0.0.9:9000")?;
895    /// upstream.set_gate(Arc::new(net_io::AllowAll))?;
896    /// upstream.send_all(b"PING\r\n")?;
897    /// # Ok::<(), net_io::NetError>(())
898    /// ```
899    pub fn set_gate<G: Gate>(&mut self, gate: Arc<G>) -> Result<(), NetError> {
900        let link = self.link()?;
901        if link.gate.is_some() {
902            return Err(NetError::InvalidConfig {
903                field: "gate",
904                reason: ConfigReason::Inconsistent,
905            });
906        }
907        let code = match guarded(|| gate.admit(&link.info, AdmitStage::Dialed)) {
908            Some(Ok(admitted)) => {
909                link.info.lane = admitted.lane;
910                link.info.gate = admitted.tag;
911                link.gate = Some(Box::new(GateCell {
912                    gate,
913                    ticket: Some(admitted.ticket),
914                }));
915                return Ok(());
916            }
917            Some(Err(refusal)) => refusal.code(),
918            None => 0,
919        };
920        let cause = RefusalCause::Gate(code);
921        if let Some(link) = self.link.take() {
922            link.finish(CloseReason::Refused(cause));
923        }
924        Err(NetError::Refused { cause })
925    }
926
927    /// Live socket options.
928    #[must_use]
929    pub fn options(&self) -> SocketOptions<'_> {
930        let link = self.link_ref();
931        SocketOptions {
932            sock: link.stream.sock(),
933            v6: link.info.local.socket_addr().is_some_and(|a| a.is_ipv6()),
934        }
935    }
936
937    /// The socket's pending error (`SO_ERROR`).
938    ///
939    /// # Errors
940    ///
941    /// `Os` when the OS call fails.
942    pub fn take_error(&self) -> Result<Option<io::Error>, NetError> {
943        sys::take_error(self.link_ref().stream.sock())
944            .map_err(|e| NetError::from_os("getsockopt", e))
945    }
946}
947
948#[cold]
949fn unreachable_link() -> ! {
950    // A TcpConnection is emptied only by the server after its handler returned,
951    // when no code can reach it any more.
952    std::process::abort()
953}
954
955/// A non-blocking socket ready to connect to `addr`.
956fn dial_socket(
957    addr: SocketAddr,
958    options: &ConnectOptions,
959) -> Result<std::net::TcpStream, NetError> {
960    let owned = sys::tcp_socket(addr.is_ipv6()).map_err(|e| NetError::from_os("socket", e))?;
961    let stream = std::net::TcpStream::from(owned);
962    stream
963        .set_nonblocking(true)
964        .map_err(|e| NetError::from_os("ioctl", e))?;
965    options.tcp.apply(&stream, addr.is_ipv6())?;
966    if let Some(local) = options.local_addr {
967        sys::bind_to(stream.sock(), local).map_err(|e| bind_error(local, e))?;
968    }
969    Ok(stream)
970}
971
972/// IPv6 first, then the families take turns.
973fn interleaved(addrs: &[SocketAddr]) -> Vec<SocketAddr> {
974    let (v6, v4): (Vec<_>, Vec<_>) = addrs.iter().copied().partition(SocketAddr::is_ipv6);
975    let (mut v6, mut v4) = (v6.into_iter(), v4.into_iter());
976    let mut out = Vec::with_capacity(addrs.len());
977    loop {
978        match (v6.next(), v4.next()) {
979            (None, None) => return out,
980            (a, b) => out.extend(a.into_iter().chain(b)),
981        }
982    }
983}
984
985/// At most this many attempts run at once, and never two start closer than this.
986const MAX_RACING: usize = 16;
987const RACE_SPACING: Duration = Duration::from_millis(10);
988
989/// Happy Eyeballs: see [`ConnectOptions::happy_eyeballs`]. Dropping a losing attempt
990/// resets it, so nothing lingers half open at the far end.
991fn connect_racing(
992    addrs: &[SocketAddr],
993    options: &ConnectOptions,
994) -> Result<TcpConnection, NetError> {
995    let ordered = interleaved(addrs);
996    let start = Instant::now();
997    let deadline = start + options.timeout;
998    let mut racing: Vec<(std::net::TcpStream, SocketAddr, Instant)> = Vec::new();
999    let mut queue = ordered.iter().copied();
1000    let mut waiting = queue.next();
1001    let mut next_at = start;
1002    let mut last_start: Option<Instant> = None;
1003    let mut last = NetError::NoAddresses;
1004    loop {
1005        let now = Instant::now();
1006        if now >= deadline {
1007            break;
1008        }
1009        let spaced = last_start.map_or(now, |t| t + RACE_SPACING);
1010        if let Some(addr) = waiting.filter(|_| {
1011            racing.len() < MAX_RACING && now >= spaced && (now >= next_at || racing.is_empty())
1012        }) {
1013            waiting = queue.next();
1014            last_start = Some(now);
1015            next_at = now + options.attempt_delay;
1016            let stream = match dial_socket(addr, options) {
1017                Ok(s) => s,
1018                Err(e) => {
1019                    last = e;
1020                    next_at = now;
1021                    continue;
1022                }
1023            };
1024            match sys::connect_start(stream.sock(), addr) {
1025                Ok(false) => return dialed(stream, addr, options),
1026                Ok(true) => racing.push((stream, addr, now)),
1027                Err(e) => {
1028                    last = connect_error(addr, Duration::ZERO, e);
1029                    next_at = now;
1030                }
1031            }
1032            continue;
1033        }
1034        if racing.is_empty() && waiting.is_none() {
1035            break;
1036        }
1037        let mut until = deadline;
1038        if waiting.is_some() {
1039            until = until.min(next_at.max(spaced).max(now + Duration::from_millis(1)));
1040        }
1041        let wait = until.saturating_duration_since(now);
1042        if racing.is_empty() {
1043            std::thread::sleep(wait);
1044            continue;
1045        }
1046        let socks: Vec<_> = racing.iter().map(|(s, ..)| s.sock()).collect();
1047        let ready = sys::wait_writable(&socks, wait).map_err(|e| NetError::from_os("poll", e))?;
1048        drop(socks);
1049        for i in (0..racing.len()).rev() {
1050            if ready & (1 << i) == 0 {
1051                continue;
1052            }
1053            let (stream, addr, began) = racing.swap_remove(i);
1054            match sys::take_error(stream.sock()) {
1055                Ok(None) => {
1056                    for (loser, ..) in &racing {
1057                        let _ = sys::set_linger(loser.sock(), Some(Duration::ZERO));
1058                    }
1059                    return dialed(stream, addr, options);
1060                }
1061                Ok(Some(e)) => {
1062                    last = connect_error(addr, began.elapsed(), e);
1063                    next_at = Instant::now();
1064                }
1065                Err(e) => last = NetError::from_os("getsockopt", e),
1066            }
1067        }
1068    }
1069    for (loser, ..) in &racing {
1070        let _ = sys::set_linger(loser.sock(), Some(Duration::ZERO));
1071    }
1072    if matches!(last, NetError::NoAddresses) {
1073        if let Some(addr) = ordered.first() {
1074            last = NetError::ConnectTimeout {
1075                addr: *addr,
1076                after: options.timeout,
1077            };
1078        }
1079    }
1080    Err(last)
1081}
1082
1083fn connect_one(
1084    addr: SocketAddr,
1085    options: &ConnectOptions,
1086    attempt: Duration,
1087) -> Result<TcpConnection, NetError> {
1088    let stream = dial_socket(addr, options)?;
1089    let started = Instant::now();
1090    match sys::connect_start(stream.sock(), addr) {
1091        Ok(false) => {}
1092        Ok(true) => {
1093            match sys::wait(stream.sock(), Interest::Write, None, Some(attempt)) {
1094                Ok(Ready::TimedOut) => {
1095                    return Err(NetError::ConnectTimeout {
1096                        addr,
1097                        after: attempt,
1098                    });
1099                }
1100                Ok(_) => {}
1101                Err(e) => return Err(NetError::from_os("poll", e)),
1102            }
1103            match sys::take_error(stream.sock()) {
1104                Ok(None) => {}
1105                Ok(Some(e)) => return Err(connect_error(addr, started.elapsed(), e)),
1106                Err(e) => return Err(NetError::from_os("getsockopt", e)),
1107            }
1108        }
1109        Err(e) => return Err(connect_error(addr, started.elapsed(), e)),
1110    }
1111    dialed(stream, addr, options)
1112}
1113
1114/// A connection from a socket that just connected to `addr`.
1115fn dialed(
1116    stream: std::net::TcpStream,
1117    addr: SocketAddr,
1118    options: &ConnectOptions,
1119) -> Result<TcpConnection, NetError> {
1120    sys::prepare_dialed(&stream).map_err(|e| NetError::from_os("ioctl", e))?;
1121    let local = stream
1122        .local_addr()
1123        .map_err(|e| NetError::from_os("getsockname", e))?;
1124    let info = ConnectionInfo::new_tcp(
1125        crate::id::issue_single(),
1126        None,
1127        WorkerId(0),
1128        Origin::Dialed,
1129        local,
1130        crate::addr::normalize_socket(addr),
1131        Instant::now(),
1132    );
1133    Ok(TcpConnection::from_link(Link::new(
1134        sys::Stream::Tcp(stream),
1135        info,
1136        Arc::new(options.limits.effective(DriverKind::Blocking)),
1137        ClockRef::Monotonic,
1138        Arc::new(KillSlot::new()),
1139        WakeSource::Thread,
1140        Phase::Receiving,
1141    )))
1142}
1143
1144impl Read for TcpConnection {
1145    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1146        self.recv(buf).map_err(io::Error::from)
1147    }
1148}
1149
1150impl Write for TcpConnection {
1151    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1152        self.send(buf).map_err(io::Error::from)
1153    }
1154
1155    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1156        self.send_vectored(bufs).map_err(io::Error::from)
1157    }
1158
1159    fn flush(&mut self) -> io::Result<()> {
1160        Ok(())
1161    }
1162}
1163
1164impl Drop for TcpConnection {
1165    /// Never blocks: FIN, then close without the linger; use `close()` for the full graceful close.
1166    fn drop(&mut self) {
1167        if let Some(link) = self.link.take() {
1168            let reason = link.reason_or(CloseReason::SessionClosed);
1169            link.finish_quick(reason);
1170        }
1171    }
1172}
1173
1174impl std::fmt::Debug for TcpConnection {
1175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1176        match &self.link {
1177            Some(l) => f
1178                .debug_struct("TcpConnection")
1179                .field("info", &l.info)
1180                .finish(),
1181            None => f.write_str("TcpConnection(closed)"),
1182        }
1183    }
1184}
1185
1186#[cfg(unix)]
1187impl std::os::fd::AsFd for TcpConnection {
1188    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
1189        std::os::fd::AsFd::as_fd(&self.link_ref().stream)
1190    }
1191}
1192
1193#[cfg(windows)]
1194impl std::os::windows::io::AsSocket for TcpConnection {
1195    fn as_socket(&self) -> std::os::windows::io::BorrowedSocket<'_> {
1196        std::os::windows::io::AsSocket::as_socket(&self.link_ref().stream)
1197    }
1198}
1199
1200#[cfg(test)]
1201mod tests {
1202    use super::*;
1203
1204    #[test]
1205    fn test_listen_accept_echo_round_trip() {
1206        let l = TcpListener::bind("127.0.0.1:0").unwrap();
1207        let addr = l.local_addr().unwrap();
1208        let t = std::thread::spawn(move || {
1209            let (mut c, info) = l.accept().unwrap();
1210            assert_eq!(info.origin, Origin::Accepted);
1211            let mut buf = [0u8; 4];
1212            c.recv_exact(&mut buf).unwrap();
1213            c.send_all(&buf).unwrap();
1214            c.close().unwrap();
1215        });
1216        let mut c = TcpConnection::connect(addr).unwrap();
1217        c.send_all(b"ping").unwrap();
1218        let mut buf = [0u8; 4];
1219        c.recv_exact(&mut buf).unwrap();
1220        assert_eq!(&buf, b"ping");
1221        assert_eq!(c.recv(&mut buf).unwrap(), 0);
1222        t.join().unwrap();
1223    }
1224
1225    #[test]
1226    fn test_connect_refused_maps_to_connection_refused() {
1227        // Bind then drop to get a free port with nothing listening.
1228        let port = std::net::TcpListener::bind("127.0.0.1:0")
1229            .unwrap()
1230            .local_addr()
1231            .unwrap()
1232            .port();
1233        let err = TcpConnection::connect_with(
1234            ("127.0.0.1", port),
1235            ConnectOptions::new().timeout(Duration::from_secs(5)),
1236        )
1237        .unwrap_err();
1238        assert!(
1239            matches!(
1240                err,
1241                NetError::ConnectionRefused { .. } | NetError::ConnectTimeout { .. }
1242            ),
1243            "{err:?}"
1244        );
1245    }
1246
1247    #[test]
1248    fn test_bind_in_use_maps_to_addr_in_use() {
1249        let a = TcpListener::bind("127.0.0.1:0").unwrap();
1250        let err = TcpListener::bind(a.local_addr().unwrap()).unwrap_err();
1251        assert!(matches!(err, NetError::AddrInUse { .. }), "{err:?}");
1252    }
1253
1254    /// Edge cases 127 and 128: bind errors map by class, whatever the OS's number.
1255    #[test]
1256    fn test_bind_errors_map_by_class() {
1257        #[cfg(unix)]
1258        use crate::sys::errno::{EACCES as ACCESS, EADDRNOTAVAIL as NOT_AVAILABLE};
1259        #[cfg(windows)]
1260        use crate::sys::errno::{WSAEACCES as ACCESS, WSAEADDRNOTAVAIL as NOT_AVAILABLE};
1261        let addr: SocketAddr = "[::1]:80".parse().unwrap();
1262        let e = bind_error(addr, io::Error::from_raw_os_error(NOT_AVAILABLE));
1263        assert!(matches!(e, NetError::AddrNotAvailable { .. }), "{e:?}");
1264        let e = bind_error(addr, io::Error::from_raw_os_error(ACCESS));
1265        assert!(matches!(e, NetError::PermissionDenied { .. }), "{e:?}");
1266    }
1267
1268    #[test]
1269    fn test_read_timeout_fires() {
1270        let l = TcpListener::bind("127.0.0.1:0").unwrap();
1271        let addr = l.local_addr().unwrap();
1272        let _server = std::thread::spawn(move || {
1273            let (c, _) = l.accept().unwrap();
1274            std::thread::sleep(Duration::from_secs(2));
1275            drop(c);
1276        });
1277        let limits = Limits::builder()
1278            .read_timeout(Duration::from_millis(200))
1279            .min_rate(crate::limits::MinRate::off())
1280            .build()
1281            .unwrap();
1282        let mut c =
1283            TcpConnection::connect_with(addr, ConnectOptions::new().limits(limits)).unwrap();
1284        let mut buf = [0u8; 8];
1285        let start = Instant::now();
1286        let err = c.recv(&mut buf).unwrap_err();
1287        assert!(
1288            matches!(
1289                err,
1290                NetError::TimedOut {
1291                    kind: TimeoutKind::Read
1292                }
1293            ),
1294            "{err:?}"
1295        );
1296        assert!(start.elapsed() < Duration::from_secs(2));
1297    }
1298
1299    #[test]
1300    fn test_kill_wakes_blocked_recv() {
1301        let l = TcpListener::bind("127.0.0.1:0").unwrap();
1302        let addr = l.local_addr().unwrap();
1303        let _server = std::thread::spawn(move || {
1304            let (c, _) = l.accept().unwrap();
1305            std::thread::sleep(Duration::from_secs(3));
1306            drop(c);
1307        });
1308        let mut c = TcpConnection::connect(addr).unwrap();
1309        let kill = c.kill_handle();
1310        std::thread::spawn(move || {
1311            std::thread::sleep(Duration::from_millis(100));
1312            assert!(kill.kill(crate::error::KillReason(4)));
1313        });
1314        let mut buf = [0u8; 8];
1315        let start = Instant::now();
1316        let err = c.recv(&mut buf).unwrap_err();
1317        assert!(matches!(err, NetError::Killed { .. }), "{err:?}");
1318        assert!(start.elapsed() < Duration::from_secs(2));
1319    }
1320
1321    #[test]
1322    fn test_interleaved_starts_with_v6_and_takes_turns() {
1323        let a = |t: &str| t.parse::<SocketAddr>().unwrap();
1324        let (v4a, v4b, v4c) = (a("1.1.1.1:1"), a("2.2.2.2:1"), a("3.3.3.3:1"));
1325        let (v6a, v6b) = (a("[::1]:1"), a("[::2]:1"));
1326        assert_eq!(
1327            interleaved(&[v4a, v4b, v4c, v6a, v6b]),
1328            [v6a, v4a, v6b, v4b, v4c]
1329        );
1330        assert_eq!(interleaved(&[v4a, v4b]), [v4a, v4b]);
1331        assert!(interleaved(&[]).is_empty());
1332    }
1333
1334    #[test]
1335    fn test_attempt_delay_is_held_to_its_range() {
1336        let low = ConnectOptions::new().attempt_delay(Duration::from_millis(1));
1337        assert_eq!(low.attempt_delay, Duration::from_millis(100));
1338        let high = ConnectOptions::new().attempt_delay(Duration::from_secs(9));
1339        assert_eq!(high.attempt_delay, Duration::from_secs(2));
1340    }
1341
1342    #[test]
1343    fn test_racing_a_refused_address_moves_on_at_once() {
1344        let closed = {
1345            let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1346            l.local_addr().unwrap()
1347        };
1348        let live = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1349        let options = ConnectOptions::new()
1350            .happy_eyeballs(true)
1351            .attempt_delay(Duration::from_secs(2));
1352        let started = Instant::now();
1353        let c = TcpConnection::connect_addrs(&[closed, live.local_addr().unwrap()], &options);
1354        assert_eq!(c.unwrap().peer_addr(), live.local_addr().unwrap());
1355        // Windows retries a refused connect for about 2 s before it reports it.
1356        if cfg!(unix) {
1357            assert!(
1358                started.elapsed() < Duration::from_secs(2),
1359                "no attempt delay"
1360            );
1361        }
1362    }
1363
1364    #[test]
1365    fn test_racing_every_address_refused_reports_the_last() {
1366        let closed: Vec<SocketAddr> = (0..2)
1367            .map(|_| {
1368                let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1369                l.local_addr().unwrap()
1370            })
1371            .collect();
1372        let options = ConnectOptions::new()
1373            .timeout(Duration::from_secs(5))
1374            .happy_eyeballs(true);
1375        let e = TcpConnection::connect_addrs(&closed, &options).err();
1376        assert!(
1377            matches!(e, Some(NetError::ConnectionRefused { .. })),
1378            "{e:?}"
1379        );
1380    }
1381
1382    /// A silent address (documentation range: nothing answers it) cannot hold the
1383    /// connection up longer than the attempt delay.
1384    #[test]
1385    fn test_racing_a_silent_address_starts_the_next_after_the_delay() {
1386        let silent: SocketAddr = "192.0.2.1:9".parse().unwrap();
1387        let live = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1388        let options = ConnectOptions::new()
1389            .timeout(Duration::from_secs(5))
1390            .happy_eyeballs(true)
1391            .attempt_delay(Duration::from_millis(100));
1392        let started = Instant::now();
1393        let c = TcpConnection::connect_addrs(&[silent, live.local_addr().unwrap()], &options);
1394        assert_eq!(c.unwrap().peer_addr(), live.local_addr().unwrap());
1395        assert!(started.elapsed() < Duration::from_secs(2));
1396    }
1397}