1use 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#[non_exhaustive]
29#[derive(Clone, Debug)]
30pub struct ListenerInfo {
31 pub id: ListenerId,
33 pub name: Option<String>,
35 pub local: Endpoint,
37 pub backlog: Option<u32>,
39 pub transport: Transport,
41 pub proxy: ProxyMode,
43 pub tls: bool,
45}
46
47pub(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
61const 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#[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 pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<TcpListener, NetError> {
135 TcpListener::bind_with(addr, ListenOptions::new())
136 }
137
138 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 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 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 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 pub(crate) fn set_tls(&mut self, on: bool) {
280 self.info.tls = on;
281 }
282
283 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 #[must_use]
294 pub fn info(&self) -> &ListenerInfo {
295 &self.info
296 }
297
298 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 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 #[must_use]
349 pub fn into_std(self) -> std::net::TcpListener {
350 self.inner
351 }
352
353 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#[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 pub fn new() -> ConnectOptions {
453 ConnectOptions::default()
454 }
455
456 pub fn timeout(mut self, total: Duration) -> ConnectOptions {
458 self.timeout = total;
459 self
460 }
461
462 pub fn local_addr(mut self, addr: SocketAddr) -> ConnectOptions {
464 self.local_addr = Some(addr);
465 self
466 }
467
468 pub fn tcp_options(mut self, options: TcpOptions) -> ConnectOptions {
470 self.tcp = options;
471 self
472 }
473
474 pub fn limits(mut self, limits: Limits) -> ConnectOptions {
476 self.limits = limits;
477 self
478 }
479
480 pub fn happy_eyeballs(mut self, on: bool) -> ConnectOptions {
485 self.happy_eyeballs = on;
486 self
487 }
488
489 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
497pub struct TcpConnection {
521 link: Option<Link>,
522}
523
524impl TcpConnection {
525 pub fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpConnection, NetError> {
531 TcpConnection::connect_with(addr, ConnectOptions::new())
532 }
533
534 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 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 #[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 None => unreachable_link(),
663 }
664 }
665
666 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 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 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 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 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 pub fn send(&mut self, buf: &[u8]) -> Result<usize, NetError> {
749 self.link()?.write(buf)
750 }
751
752 pub fn send_all(&mut self, buf: &[u8]) -> Result<(), NetError> {
759 self.link()?.write_all(buf)
760 }
761
762 pub fn send_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, NetError> {
768 self.link()?.write_vectored(bufs)
769 }
770
771 pub fn send_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), NetError> {
777 self.link()?.write_all_vectored(bufs)
778 }
779
780 pub fn shutdown(&mut self, how: Shutdown) -> Result<(), NetError> {
786 self.link()?.shutdown(how)
787 }
788
789 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 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 #[must_use]
818 pub fn info(&self) -> &ConnectionInfo {
819 &self.link_ref().info
820 }
821
822 #[must_use]
824 pub fn id(&self) -> ConnectionId {
825 self.link_ref().info.id
826 }
827
828 #[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 #[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 #[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 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 pub fn set_phase(&mut self, phase: Phase) {
869 if let Ok(link) = self.link() {
870 link.set_phase(phase);
871 }
872 }
873
874 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 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 #[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 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 std::process::abort()
953}
954
955fn 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
972fn 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
985const MAX_RACING: usize = 16;
987const RACE_SPACING: Duration = Duration::from_millis(10);
988
989fn 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
1114fn 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 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 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 #[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 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 #[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}