Skip to main content

wasmtime_wasi/sockets/
tcp.rs

1use crate::runtime::with_ambient_tokio_runtime;
2use crate::sockets::{
3    ErrorCode, MaybeReady, SocketAddrCheck, SocketAddrUse, SocketAddressFamily, WasiSocketsCtx,
4    get_receive_buffer_size, get_send_buffer_size, get_unicast_hop_limit, is_valid_address_family,
5    is_valid_remote_address, is_valid_unicast_address, set_receive_buffer_size,
6    set_send_buffer_size, set_unicast_hop_limit, unspecified_addr,
7};
8use rustix::fd::AsFd;
9use rustix::io::Errno;
10use rustix::net::sockopt;
11use std::fmt::Debug;
12use std::future::poll_fn;
13use std::mem;
14use std::net::SocketAddr;
15use std::sync::Arc;
16use std::task::{Poll, ready};
17use std::time::Duration;
18
19/// Value taken from rust std library.
20const DEFAULT_BACKLOG: u32 = 128;
21
22const NANOS_PER_SEC: u64 = 1_000_000_000;
23
24/// The state of a TCP socket.
25///
26/// This represents the various states a socket can be in during the
27/// activities of listening, accepting, and connecting.
28enum TcpState {
29    /// The initial state for a newly-created socket.
30    ///
31    /// The socket may be bound to a local address in this state, but doesn't
32    /// have to.
33    ///
34    /// From here a socket can transition to `Listening` or `Connecting`.
35    Default(tokio::net::TcpSocket),
36
37    /// The socket is now listening and waiting for an incoming connection.
38    ///
39    /// Sockets will not leave this state.
40    Listening(Arc<tokio::net::TcpListener>),
41
42    /// An outgoing connection is started.
43    ///
44    /// This is created via the `start_connect` method. The payload is a future
45    /// for the eventual result of the connect.
46    ///
47    /// From here a socket can transition to `Connected` or `Closed`.
48    Connecting(MaybeReady<Result<tokio::net::TcpStream, ErrorCode>>),
49
50    /// A connection has been established.
51    ///
52    /// This is created either via `finish_connect` or for freshly accepted
53    /// sockets from a TCP listener.
54    ///
55    /// A socket will not transition out of this state.
56    Connected {
57        stream: Arc<tokio::net::TcpStream>,
58        /// Cached peer address, returned by `accept` or the first successful
59        /// `peer_addr` query. The stream may no longer report it after a reset.
60        peer: Option<SocketAddr>,
61        receive_taken: bool,
62        send_taken: bool,
63    },
64
65    /// The socket is closed and no more operations can be performed.
66    Closed(ErrorCode),
67}
68impl TcpState {
69    fn connected(stream: tokio::net::TcpStream, peer: Option<SocketAddr>) -> Self {
70        TcpState::Connected {
71            stream: Arc::new(stream),
72            peer,
73            receive_taken: false,
74            send_taken: false,
75        }
76    }
77    fn take(&mut self) -> Self {
78        mem::replace(self, TcpState::Closed(ErrorCode::Other))
79    }
80}
81impl Debug for TcpState {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        match self {
84            Self::Default(_) => f.debug_tuple("Default").finish(),
85            Self::Listening { .. } => f.debug_tuple("Listening").finish(),
86            Self::Connecting(..) => f.debug_tuple("Connecting").finish(),
87            Self::Connected { .. } => f.debug_tuple("Connected").finish(),
88            Self::Closed(..) => write!(f, "Closed"),
89        }
90    }
91}
92
93/// A host TCP socket, plus associated bookkeeping.
94pub struct TcpSocket {
95    /// The current state in the bind/listen/accept/connect progression.
96    tcp_state: TcpState,
97
98    /// The desired listen queue size.
99    listen_backlog_size: u32,
100
101    family: SocketAddressFamily,
102
103    /// The checks to perform before doing any noteworthy syscall.
104    permissions: SocketAddrCheck,
105
106    /// Persisted socket options to manually apply to newly accepted client
107    /// sockets on platforms that don't inherit socket options from the listener.
108    listener_options: NonInheritedOptions,
109
110    /// Cached value of whether the socket is bound. Various methods use the
111    /// `.is_bound()` method, so we cache it to avoid redundant syscalls.
112    is_bound: bool,
113}
114
115impl TcpSocket {
116    /// Create a new socket in the given family.
117    pub(crate) fn new(
118        ctx: &WasiSocketsCtx,
119        family: SocketAddressFamily,
120    ) -> Result<Self, ErrorCode> {
121        ctx.allowed_network_uses.check_allowed_tcp()?;
122
123        let socket = with_ambient_tokio_runtime(|| socket(family))?;
124
125        Ok(Self {
126            tcp_state: TcpState::Default(socket),
127            listen_backlog_size: DEFAULT_BACKLOG,
128            family,
129            is_bound: false,
130            listener_options: Default::default(),
131            permissions: ctx.socket_addr_check.clone(),
132        })
133    }
134
135    fn as_fd(&self) -> Result<rustix::fd::BorrowedFd<'_>, ErrorCode> {
136        match &self.tcp_state {
137            TcpState::Default(socket) => Ok(socket.as_fd()),
138            TcpState::Connected { stream, .. } => Ok(stream.as_fd()),
139            TcpState::Listening(listener) => Ok(listener.as_fd()),
140            TcpState::Connecting(..) => Err(ErrorCode::InvalidState),
141            TcpState::Closed(err) => Err(*err),
142        }
143    }
144
145    pub(crate) fn is_bound(&mut self) -> bool {
146        // Once bound, a TCP socket can never become unbound again. So we can
147        // skip all work after a previous call has already determined the
148        // socket to be bound.
149        if !self.is_bound {
150            self.is_bound = match &self.tcp_state {
151                TcpState::Default(socket) => socket
152                    .local_addr()
153                    .is_ok_and(|addr| addr != unspecified_addr(self.family)),
154                _ => true,
155            };
156        }
157        self.is_bound
158    }
159
160    pub(crate) async fn bind(&mut self, addr: SocketAddr) -> Result<(), ErrorCode> {
161        if self.is_bound() {
162            return Err(ErrorCode::InvalidState);
163        }
164        let TcpState::Default(sock) = &self.tcp_state else {
165            return Err(ErrorCode::InvalidState);
166        };
167
168        if !is_valid_unicast_address(addr.ip()) || !is_valid_address_family(addr.ip(), self.family)
169        {
170            return Err(ErrorCode::InvalidArgument);
171        }
172
173        self.permissions.check(addr, SocketAddrUse::TcpBind).await?;
174        bind(sock, addr)?;
175        Ok(())
176    }
177
178    pub(crate) fn start_connect(&mut self, addr: SocketAddr) -> Result<(), ErrorCode> {
179        let TcpState::Default(_) = &self.tcp_state else {
180            return Err(ErrorCode::InvalidState);
181        };
182
183        let permissions = self.permissions.clone();
184        let family = self.family;
185        let already_bound = self.is_bound();
186
187        if !is_valid_unicast_address(addr.ip())
188            || !is_valid_remote_address(addr)
189            || !is_valid_address_family(addr.ip(), family)
190        {
191            return Err(ErrorCode::InvalidArgument);
192        };
193
194        let TcpState::Default(sock) = self.tcp_state.take() else {
195            unreachable!();
196        };
197
198        self.tcp_state = TcpState::Connecting(MaybeReady::new(Box::pin(async move {
199            // Perform all checks before doing any syscalls.
200            {
201                if !already_bound {
202                    // If not explicitly bound, the OS will implicitly bind the
203                    // socket to an ephemeral port when connecting. Unlike other
204                    // operations (e.g. `listen`), we will *not* do the implicit
205                    // bind ourselves because that may accelerate port exhaustion.
206                    // For more info, see IP_BIND_ADDRESS_NO_PORT (Linux) or
207                    // SO_REUSE_UNICASTPORT (Windows).
208                    //
209                    // Instead we check the permission to bind, but not perform
210                    // the actual bind:
211                    let implicit = unspecified_addr(family);
212                    permissions.check(implicit, SocketAddrUse::TcpBind).await?;
213                }
214
215                permissions.check(addr, SocketAddrUse::TcpConnect).await?;
216            }
217
218            let stream = sock.connect(addr).await?;
219            Ok(stream)
220        })));
221
222        Ok(())
223    }
224
225    pub(crate) fn poll_finish_connect(
226        &mut self,
227        cx: &mut std::task::Context<'_>,
228    ) -> Poll<Result<(), ErrorCode>> {
229        match &mut self.tcp_state {
230            TcpState::Connecting(connect) => {
231                ready!(with_ambient_tokio_runtime(|| connect.poll_ready(cx)));
232            }
233            TcpState::Connected { .. } => return Poll::Ready(Ok(())),
234            TcpState::Closed(e) => return Poll::Ready(Err(*e)),
235            _ => return Poll::Ready(Err(ErrorCode::InvalidState)),
236        }
237        let TcpState::Connecting(connect) = self.tcp_state.take() else {
238            unreachable!();
239        };
240
241        match connect.unwrap_ready() {
242            Ok(stream) => {
243                self.tcp_state = TcpState::connected(stream, None);
244                Poll::Ready(Ok(()))
245            }
246            Err(err) => {
247                self.tcp_state = TcpState::Closed(err);
248                Poll::Ready(Err(err))
249            }
250        }
251    }
252
253    pub(crate) async fn listen(&mut self) -> Result<TcpListenStream, ErrorCode> {
254        let already_bound = self.is_bound();
255        let sock = match self.tcp_state.take() {
256            TcpState::Default(sock) => sock,
257            tcp_state => {
258                self.tcp_state = tcp_state;
259                return Err(ErrorCode::InvalidState);
260            }
261        };
262
263        // Perform all checks before doing any syscalls.
264        {
265            if already_bound {
266                self.permissions
267                    .check(sock.local_addr()?, SocketAddrUse::TcpListen)
268                    .await?;
269            } else {
270                let implicit = unspecified_addr(self.family);
271                self.permissions
272                    .check(implicit, SocketAddrUse::TcpBind)
273                    .await?;
274                self.permissions
275                    .check(implicit, SocketAddrUse::TcpListen)
276                    .await?;
277            }
278        }
279
280        // Some platforms automatically perform an implicit bind as part of
281        // the `listen` syscall. However this is not ubiquitous behavior:
282        // - Linux mentions it in their docs [0] that they perform an
283        //   implicit bind. This behavior has been experimentally verified.
284        // - Windows requires a `bind` before `listen`. This is both
285        //   documented [1] and experimentally verified.
286        // - Other platforms (e.g. macOS, FreeBSD) do not explicitly
287        //   document it either way and instead leave it up to the
288        //   individual protocol to decide [2]. However, experiments
289        //   show that MacOS in fact _does_ perform an implicit bind.
290        //
291        // Thus to ensure consistent behavior across all platforms, we
292        // perform the implicit bind ourselves here for unbound sockets.
293        //
294        // [0]: https://man7.org/linux/man-pages/man7/ip.7.html
295        // > An ephemeral port is allocated to a socket in the following
296        // > circumstances: (...) listen(2) is called on a stream socket
297        // > that was not previously bound;
298        //
299        // [1]: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-listen
300        // > WSAEINVAL: The socket has not been bound with bind.
301        //
302        // [2]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/listen.html
303        // > EDESTADDRREQ: The socket is not bound to a local address,
304        // > and the protocol does not support listening on an unbound
305        // > socket.
306        if !already_bound {
307            let implicit = unspecified_addr(self.family);
308            bind(&sock, implicit)?;
309        }
310
311        let listener = with_ambient_tokio_runtime(|| sock.listen(self.listen_backlog_size));
312        let listener = listener.map_err(|err| {
313            match Errno::from_io_error(&err) {
314                // See: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-listen#:~:text=WSAEMFILE
315                // According to the docs, `listen` can return EMFILE on Windows.
316                // This is odd, because we're not trying to create a new socket
317                // or file descriptor of any kind. So we rewrite it to less
318                // surprising error code.
319                //
320                // At the time of writing, this behavior has never been experimentally
321                // observed by any of the wasmtime authors, so we're relying fully
322                // on Microsoft's documentation here.
323                #[cfg(windows)]
324                Some(Errno::MFILE) => Errno::NOBUFS.into(),
325
326                _ => err,
327            }
328        })?;
329        let listener = Arc::new(listener);
330        self.tcp_state = TcpState::Listening(listener.clone());
331
332        Ok(TcpListenStream {
333            inner: listener,
334            listener_options: self.listener_options.clone(),
335            family: self.family,
336            permissions: self.permissions.clone(),
337            pending_accept: None,
338        })
339    }
340
341    pub(crate) fn take_send_stream(&mut self) -> Result<TcpSendStream, ErrorCode> {
342        match &mut self.tcp_state {
343            TcpState::Connected {
344                stream, send_taken, ..
345            } if !*send_taken => {
346                *send_taken = true;
347                Ok(TcpSendStream {
348                    inner: stream.clone(),
349                })
350            }
351            TcpState::Closed(err) => Err(*err),
352            _ => Err(ErrorCode::InvalidState),
353        }
354    }
355
356    pub(crate) fn take_receive_stream(&mut self) -> Result<TcpReceiveStream, ErrorCode> {
357        match &mut self.tcp_state {
358            TcpState::Connected {
359                stream,
360                receive_taken,
361                ..
362            } if !*receive_taken => {
363                *receive_taken = true;
364                Ok(TcpReceiveStream {
365                    inner: stream.clone(),
366                })
367            }
368            TcpState::Closed(err) => Err(*err),
369            _ => Err(ErrorCode::InvalidState),
370        }
371    }
372
373    pub(crate) fn local_address(&mut self) -> Result<SocketAddr, ErrorCode> {
374        if !self.is_bound() {
375            return Err(ErrorCode::InvalidState);
376        }
377
378        match &self.tcp_state {
379            TcpState::Default(socket) => Ok(socket.local_addr()?),
380            TcpState::Connecting(_) => Err(ErrorCode::InvalidState),
381            TcpState::Connected { stream, .. } => Ok(stream.local_addr()?),
382            TcpState::Listening(listener) => Ok(listener.local_addr()?),
383            TcpState::Closed(err) => Err(*err),
384        }
385    }
386
387    pub(crate) fn remote_address(&mut self) -> Result<SocketAddr, ErrorCode> {
388        match &mut self.tcp_state {
389            TcpState::Connected {
390                peer: Some(peer), ..
391            } => Ok(*peer),
392            TcpState::Connected { stream, peer, .. } => {
393                let addr = stream.peer_addr()?;
394                *peer = Some(addr);
395                Ok(addr)
396            }
397            TcpState::Closed(err) => Err(*err),
398            _ => Err(ErrorCode::InvalidState),
399        }
400    }
401
402    pub(crate) fn is_listening(&self) -> bool {
403        matches!(self.tcp_state, TcpState::Listening(_))
404    }
405
406    pub(crate) fn address_family(&self) -> SocketAddressFamily {
407        self.family
408    }
409
410    pub(crate) fn set_listen_backlog_size(&mut self, value: u64) -> Result<(), ErrorCode> {
411        const MIN_BACKLOG: u32 = 1;
412        const MAX_BACKLOG: u32 = i32::MAX as u32; // OS'es will most likely limit it down even further.
413
414        if value == 0 {
415            return Err(ErrorCode::InvalidArgument);
416        }
417        // Silently clamp backlog size. This is OK for us to do, because operating systems do this too.
418        let value = value
419            .try_into()
420            .unwrap_or(MAX_BACKLOG)
421            .clamp(MIN_BACKLOG, MAX_BACKLOG);
422        match &self.tcp_state {
423            TcpState::Default(..) => {
424                // Socket not listening yet. Stash value for first invocation to `listen`.
425                self.listen_backlog_size = value;
426                Ok(())
427            }
428            TcpState::Listening(listener) => {
429                // Try to update the backlog by calling `listen` again.
430                // Not all platforms support this. We'll only update our own value if the OS supports changing the backlog size after the fact.
431                if rustix::net::listen(&listener, value.try_into().unwrap_or(i32::MAX)).is_err() {
432                    return Err(ErrorCode::NotSupported);
433                }
434                self.listen_backlog_size = value;
435                Ok(())
436            }
437            TcpState::Closed(err) => Err(*err),
438            _ => Err(ErrorCode::InvalidState),
439        }
440    }
441
442    pub(crate) fn keep_alive_enabled(&self) -> Result<bool, ErrorCode> {
443        let fd = self.as_fd()?;
444        let v = sockopt::socket_keepalive(fd)?;
445        Ok(v)
446    }
447
448    pub(crate) fn set_keep_alive_enabled(&self, value: bool) -> Result<(), ErrorCode> {
449        let fd = self.as_fd()?;
450        sockopt::set_socket_keepalive(fd, value)?;
451        Ok(())
452    }
453
454    pub(crate) fn keep_alive_idle_time(&self) -> Result<u64, ErrorCode> {
455        let fd = self.as_fd()?;
456        let v = sockopt::tcp_keepidle(fd)?;
457        Ok(v.as_nanos().try_into().unwrap_or(u64::MAX))
458    }
459
460    pub(crate) fn set_keep_alive_idle_time(&mut self, value: u64) -> Result<(), ErrorCode> {
461        if value == 0 {
462            // WIT: "If the provided value is 0, an `invalid-argument` error is returned."
463            return Err(ErrorCode::InvalidArgument);
464        }
465        let fd = self.as_fd()?;
466        let value = clamp_keep_alive_time(value);
467        sockopt::set_tcp_keepidle(fd, Duration::from_nanos(value))?;
468        self.listener_options.set_keep_alive_idle_time(value);
469        Ok(())
470    }
471
472    pub(crate) fn keep_alive_interval(&self) -> Result<u64, ErrorCode> {
473        let fd = self.as_fd()?;
474        let v = sockopt::tcp_keepintvl(fd)?;
475        Ok(v.as_nanos().try_into().unwrap_or(u64::MAX))
476    }
477
478    pub(crate) fn set_keep_alive_interval(&self, value: u64) -> Result<(), ErrorCode> {
479        if value == 0 {
480            // WIT: "If the provided value is 0, an `invalid-argument` error is returned."
481            return Err(ErrorCode::InvalidArgument);
482        }
483        let fd = self.as_fd()?;
484        let value = clamp_keep_alive_time(value);
485        sockopt::set_tcp_keepintvl(fd, Duration::from_nanos(value))?;
486        Ok(())
487    }
488
489    pub(crate) fn keep_alive_count(&self) -> Result<u32, ErrorCode> {
490        let fd = self.as_fd()?;
491        let v = sockopt::tcp_keepcnt(fd)?;
492        Ok(v)
493    }
494
495    pub(crate) fn set_keep_alive_count(&self, value: u32) -> Result<(), ErrorCode> {
496        if value == 0 {
497            // WIT: "If the provided value is 0, an `invalid-argument` error is returned."
498            return Err(ErrorCode::InvalidArgument);
499        }
500        let value = clamp_keep_alive_count(value);
501        let fd = self.as_fd()?;
502        sockopt::set_tcp_keepcnt(fd, value)?;
503        Ok(())
504    }
505
506    pub(crate) fn hop_limit(&self) -> Result<u8, ErrorCode> {
507        let fd = self.as_fd()?;
508        let n = get_unicast_hop_limit(fd, self.family)?;
509        Ok(n)
510    }
511
512    pub(crate) fn set_hop_limit(&mut self, value: u8) -> Result<(), ErrorCode> {
513        {
514            let fd = self.as_fd()?;
515            set_unicast_hop_limit(fd, self.family, value)?;
516        }
517        self.listener_options.set_hop_limit(value);
518        Ok(())
519    }
520
521    pub(crate) fn receive_buffer_size(&self) -> Result<u64, ErrorCode> {
522        let fd = self.as_fd()?;
523        let n = get_receive_buffer_size(fd)?;
524        Ok(n)
525    }
526
527    pub(crate) fn set_receive_buffer_size(&mut self, value: u64) -> Result<(), ErrorCode> {
528        let res = {
529            let fd = self.as_fd()?;
530            set_receive_buffer_size(fd, value)?
531        };
532        self.listener_options.set_receive_buffer_size(res);
533        Ok(())
534    }
535
536    pub(crate) fn send_buffer_size(&self) -> Result<u64, ErrorCode> {
537        let fd = self.as_fd()?;
538        let n = get_send_buffer_size(fd)?;
539        Ok(n)
540    }
541
542    pub(crate) fn set_send_buffer_size(&mut self, value: u64) -> Result<(), ErrorCode> {
543        let res = {
544            let fd = self.as_fd()?;
545            set_send_buffer_size(fd, value)?
546        };
547        self.listener_options.set_send_buffer_size(res);
548        Ok(())
549    }
550}
551
552pub(crate) struct TcpListenStream {
553    inner: Arc<tokio::net::TcpListener>,
554    family: SocketAddressFamily,
555    listener_options: NonInheritedOptions,
556    permissions: SocketAddrCheck,
557    pending_accept: Option<MaybeReady<Result<(tokio::net::TcpStream, SocketAddr), ErrorCode>>>,
558}
559impl TcpListenStream {
560    pub(crate) fn poll_accept(&mut self, cx: &mut std::task::Context<'_>) -> Poll<TcpSocket> {
561        ready!(self.poll_ready(cx));
562        let result = self.pending_accept.take().unwrap().unwrap_ready();
563        Poll::Ready(TcpSocket {
564            tcp_state: match result {
565                Ok((client, peer)) => {
566                    self.listener_options.apply(self.family, &client);
567                    TcpState::connected(client, Some(peer))
568                }
569                Err(err) => TcpState::Closed(err),
570            },
571            listen_backlog_size: DEFAULT_BACKLOG,
572            family: self.family,
573            is_bound: true,
574            listener_options: Default::default(),
575            permissions: self.permissions.clone(),
576        })
577    }
578
579    pub(crate) fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> Poll<()> {
580        if self.pending_accept.is_none() {
581            let listener = self.inner.clone();
582            let permissions = self.permissions.clone();
583
584            self.pending_accept = Some(MaybeReady::new(Box::pin(async move {
585                loop {
586                    match accept(&listener).await {
587                        Ok((client, addr)) => {
588                            if permissions
589                                .check(addr, SocketAddrUse::TcpAccept)
590                                .await
591                                .is_ok()
592                            {
593                                return Ok((client, addr));
594                            } else {
595                                reset(client);
596                                continue;
597                            }
598                        }
599                        Err(err) => {
600                            return Err(err.into());
601                        }
602                    }
603                }
604            })));
605        }
606
607        with_ambient_tokio_runtime(|| {
608            self.pending_accept
609                .as_mut()
610                .unwrap()
611                .poll_ready(cx)
612                .map(|_| ())
613        })
614    }
615}
616
617pub(crate) struct TcpSendStream {
618    inner: Arc<tokio::net::TcpStream>,
619}
620impl TcpSendStream {
621    pub(crate) fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> Poll<()> {
622        self.inner.poll_write_ready(cx).map(|_| ())
623    }
624
625    pub(crate) fn poll_write(
626        &mut self,
627        cx: &mut std::task::Context<'_>,
628        buf: &[u8],
629    ) -> Poll<Result<usize, ErrorCode>> {
630        loop {
631            return match self.inner.try_write(buf) {
632                Ok(n) => Poll::Ready(Ok(n)),
633                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
634                    match self.inner.poll_write_ready(cx) {
635                        Poll::Ready(Ok(())) => continue,
636                        Poll::Ready(Err(e)) => Poll::Ready(Err(e.into())),
637                        Poll::Pending => Poll::Pending,
638                    }
639                }
640                Err(e) => Poll::Ready(Err(match Errno::from_io_error(&e) {
641                    #[cfg(windows)]
642                    Some(Errno::SHUTDOWN) | Some(Errno::CONNABORTED) => ErrorCode::ConnectionBroken,
643                    #[cfg(not(windows))]
644                    Some(Errno::PIPE) => ErrorCode::ConnectionBroken,
645
646                    _ => e.into(),
647                })),
648            };
649        }
650    }
651    pub(crate) async fn write(&mut self, buf: &[u8]) -> Result<usize, ErrorCode> {
652        poll_fn(|cx| self.poll_write(cx, buf)).await
653    }
654}
655impl Drop for TcpSendStream {
656    fn drop(&mut self) {
657        _ = rustix::net::shutdown(&self.inner, rustix::net::Shutdown::Write);
658    }
659}
660
661pub(crate) struct TcpReceiveStream {
662    inner: Arc<tokio::net::TcpStream>,
663}
664impl TcpReceiveStream {
665    pub(crate) fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> Poll<()> {
666        self.inner.poll_read_ready(cx).map(|_| ())
667    }
668
669    pub(crate) fn poll_read(
670        &mut self,
671        cx: &mut std::task::Context<'_>,
672        buf: &mut [u8],
673    ) -> Poll<Result<usize, ErrorCode>> {
674        if buf.is_empty() {
675            return Poll::Ready(Ok(0));
676        }
677        loop {
678            return match self.inner.try_read(buf) {
679                Ok(0) => Poll::Ready(Ok(0)),
680                Ok(n) => Poll::Ready(Ok(n)),
681                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
682                    match self.inner.poll_read_ready(cx) {
683                        Poll::Ready(Ok(())) => continue,
684                        Poll::Ready(Err(e)) => Poll::Ready(Err(e.into())),
685                        Poll::Pending => Poll::Pending,
686                    }
687                }
688                Err(e) => Poll::Ready(Err(e.into())),
689            };
690        }
691    }
692}
693impl Drop for TcpReceiveStream {
694    fn drop(&mut self) {
695        _ = rustix::net::shutdown(&self.inner, rustix::net::Shutdown::Read);
696    }
697}
698
699#[cfg(not(target_os = "macos"))]
700pub use inherits_option::*;
701#[cfg(not(target_os = "macos"))]
702mod inherits_option {
703    use crate::sockets::SocketAddressFamily;
704    use tokio::net::TcpStream;
705
706    #[derive(Default, Clone)]
707    pub struct NonInheritedOptions;
708
709    impl NonInheritedOptions {
710        pub fn set_keep_alive_idle_time(&mut self, _value: u64) {}
711
712        pub fn set_hop_limit(&mut self, _value: u8) {}
713
714        pub fn set_receive_buffer_size(&mut self, _value: usize) {}
715
716        pub fn set_send_buffer_size(&mut self, _value: usize) {}
717
718        pub(crate) fn apply(&self, _family: SocketAddressFamily, _stream: &TcpStream) {}
719    }
720}
721
722#[cfg(target_os = "macos")]
723pub use does_not_inherit_options::*;
724#[cfg(target_os = "macos")]
725mod does_not_inherit_options {
726    use crate::sockets::SocketAddressFamily;
727    use rustix::net::sockopt;
728    use std::sync::Arc;
729    use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering::Relaxed};
730    use std::time::Duration;
731    use tokio::net::TcpStream;
732
733    // The socket options below are not automatically inherited from the listener
734    // on all platforms. So we keep track of which options have been explicitly
735    // set and manually apply those values to newly accepted clients.
736    #[derive(Default, Clone)]
737    pub struct NonInheritedOptions(Arc<Inner>);
738
739    #[derive(Default)]
740    struct Inner {
741        receive_buffer_size: AtomicUsize,
742        send_buffer_size: AtomicUsize,
743        hop_limit: AtomicU8,
744        keep_alive_idle_time: AtomicU64, // nanoseconds
745    }
746
747    impl NonInheritedOptions {
748        pub fn set_keep_alive_idle_time(&mut self, value: u64) {
749            self.0.keep_alive_idle_time.store(value, Relaxed);
750        }
751
752        pub fn set_hop_limit(&mut self, value: u8) {
753            self.0.hop_limit.store(value, Relaxed);
754        }
755
756        pub fn set_receive_buffer_size(&mut self, value: usize) {
757            self.0.receive_buffer_size.store(value, Relaxed);
758        }
759
760        pub fn set_send_buffer_size(&mut self, value: usize) {
761            self.0.send_buffer_size.store(value, Relaxed);
762        }
763
764        pub(crate) fn apply(&self, family: SocketAddressFamily, stream: &TcpStream) {
765            // Manually inherit socket options from listener. We only have to
766            // do this on platforms that don't already do this automatically
767            // and only if a specific value was explicitly set on the listener.
768
769            let receive_buffer_size = self.0.receive_buffer_size.load(Relaxed);
770            if receive_buffer_size > 0 {
771                // Ignore potential error.
772                _ = sockopt::set_socket_recv_buffer_size(&stream, receive_buffer_size);
773            }
774
775            let send_buffer_size = self.0.send_buffer_size.load(Relaxed);
776            if send_buffer_size > 0 {
777                // Ignore potential error.
778                _ = sockopt::set_socket_send_buffer_size(&stream, send_buffer_size);
779            }
780
781            // For some reason, IP_TTL is inherited, but IPV6_UNICAST_HOPS isn't.
782            if family == SocketAddressFamily::Ipv6 {
783                let hop_limit = self.0.hop_limit.load(Relaxed);
784                if hop_limit > 0 {
785                    // Ignore potential error.
786                    _ = sockopt::set_ipv6_unicast_hops(&stream, Some(hop_limit));
787                }
788            }
789
790            let keep_alive_idle_time = self.0.keep_alive_idle_time.load(Relaxed);
791            if keep_alive_idle_time > 0 {
792                // Ignore potential error.
793                _ = sockopt::set_tcp_keepidle(&stream, Duration::from_nanos(keep_alive_idle_time));
794            }
795        }
796    }
797}
798
799fn socket(family: SocketAddressFamily) -> std::io::Result<tokio::net::TcpSocket> {
800    match family {
801        SocketAddressFamily::Ipv4 => tokio::net::TcpSocket::new_v4(),
802        SocketAddressFamily::Ipv6 => {
803            let socket = tokio::net::TcpSocket::new_v6()?;
804
805            // From the WASI spec:
806            // > On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't
807            // > be configured otherwise.
808            sockopt::set_ipv6_v6only(&socket, true)?;
809            Ok(socket)
810        }
811    }
812}
813
814fn bind(socket: &tokio::net::TcpSocket, local_address: SocketAddr) -> Result<(), ErrorCode> {
815    // From the WASI spec:
816    // > The bind operation shouldn't be affected by the TIME_WAIT state of a
817    // > recently closed socket on the same local address. In practice this
818    // > means that the SO_REUSEADDR socket option should be set implicitly on
819    // > all platforms, except on Windows where this is the default behavior
820    // > and SO_REUSEADDR performs something different.
821    #[cfg(not(windows))]
822    {
823        _ = sockopt::set_socket_reuseaddr(&socket, true);
824    }
825
826    // Perform the OS bind call.
827    socket
828        .bind(local_address)
829        .map_err(|err| match Errno::from_io_error(&err) {
830            // From https://pubs.opengroup.org/onlinepubs/9699919799/functions/bind.html:
831            // > [EAFNOSUPPORT] The specified address is not a valid address for the address family of the specified socket
832            //
833            // The most common reasons for this error should have already
834            // been handled by our own validation.. This error mapping is here
835            // just in case there is an edge case we didn't catch.
836            Some(Errno::AFNOSUPPORT) => ErrorCode::InvalidArgument,
837            // See: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-bind#:~:text=WSAENOBUFS
838            // Windows returns WSAENOBUFS when the ephemeral ports have been exhausted.
839            #[cfg(windows)]
840            Some(Errno::NOBUFS) => ErrorCode::AddressInUse,
841            _ => err.into(),
842        })
843}
844
845async fn accept(
846    listener: &tokio::net::TcpListener,
847) -> std::io::Result<(tokio::net::TcpStream, SocketAddr)> {
848    listener
849        .accept()
850        .await
851        .map_err(|err| match Errno::from_io_error(&err) {
852            // From: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-accept#:~:text=WSAEINPROGRESS
853            // > WSAEINPROGRESS: A blocking Windows Sockets 1.1 call is in progress,
854            // > or the service provider is still processing a callback function.
855            //
856            // wasi-sockets doesn't have an equivalent to the EINPROGRESS error,
857            // because in POSIX this error is only returned by a non-blocking
858            // `connect` and wasi-sockets has a different solution for that.
859            #[cfg(windows)]
860            Some(Errno::INPROGRESS) => Errno::INTR.into(),
861
862            // Normalize Linux' non-standard behavior.
863            //
864            // From https://man7.org/linux/man-pages/man2/accept.2.html:
865            // > Linux accept() passes already-pending network errors on the
866            // > new socket as an error code from accept(). This behavior
867            // > differs from other BSD socket implementations. (...)
868            #[cfg(target_os = "linux")]
869            Some(
870                Errno::CONNRESET
871                | Errno::NETRESET
872                | Errno::HOSTUNREACH
873                | Errno::HOSTDOWN
874                | Errno::NETDOWN
875                | Errno::NETUNREACH
876                | Errno::PROTO
877                | Errno::NOPROTOOPT
878                | Errno::NONET
879                | Errno::OPNOTSUPP,
880            ) => Errno::CONNABORTED.into(),
881
882            _ => err,
883        })
884}
885
886fn reset(socket: tokio::net::TcpStream) {
887    _ = socket.set_zero_linger();
888    drop(socket);
889}
890
891fn clamp_keep_alive_time(value: u64) -> u64 {
892    // Ensure that the value passed to the actual syscall never gets rounded down to 0.
893    const MIN: u64 = 1 * NANOS_PER_SEC;
894
895    // Cap it at Linux' maximum, which appears to have the lowest limit across our supported platforms.
896    const MAX: u64 = (i16::MAX as u64) * NANOS_PER_SEC;
897
898    value.clamp(MIN, MAX)
899}
900
901fn clamp_keep_alive_count(value: u32) -> u32 {
902    const MIN_CNT: u32 = 1;
903    // Cap it at Linux' maximum, which appears to have the lowest limit across our supported platforms.
904    const MAX_CNT: u32 = i8::MAX as u32;
905
906    value.clamp(MIN_CNT, MAX_CNT)
907}
908
909#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
910mod tests {
911    use super::*;
912    use crate::WasiCtxBuilder;
913
914    #[tokio::test]
915    async fn accepted_remote_address_survives_reset() {
916        let mut ctx = WasiCtxBuilder::new();
917        ctx.inherit_network().allow_tcp(true);
918        let ctx = ctx.build();
919        let mut socket = TcpSocket::new(&ctx.sockets, SocketAddressFamily::Ipv4).unwrap();
920        socket.bind("127.0.0.1:0".parse().unwrap()).await.unwrap();
921        let mut listener = socket.listen().await.unwrap();
922
923        let client = tokio::net::TcpStream::connect(socket.local_address().unwrap())
924            .await
925            .unwrap();
926        let peer = client.local_addr().unwrap();
927
928        // Complete the OS accept, but leave the result pending for poll_accept.
929        poll_fn(|cx| listener.poll_ready(cx)).await;
930        client.set_zero_linger().unwrap();
931        drop(client);
932
933        let mut accepted = poll_fn(|cx| listener.poll_accept(cx)).await;
934        let mut input = accepted.take_receive_stream().unwrap();
935        let mut byte = [0];
936        let read = tokio::time::timeout(
937            Duration::from_secs(5),
938            poll_fn(|cx| input.poll_read(cx, &mut byte)),
939        )
940        .await
941        .unwrap();
942        assert!(matches!(read, Err(ErrorCode::ConnectionReset)));
943
944        // The OS no longer answers getpeername, but accept already had the
945        // address and the accepted socket must still report it.
946        let TcpState::Connected { stream, .. } = &accepted.tcp_state else {
947            panic!("expected an accepted connection");
948        };
949        assert!(stream.peer_addr().is_err());
950        assert_eq!(accepted.remote_address().unwrap(), peer);
951    }
952
953    #[tokio::test]
954    async fn connected_remote_address_survives_reset() {
955        let mut ctx = WasiCtxBuilder::new();
956        ctx.inherit_network().allow_tcp(true);
957        let ctx = ctx.build();
958        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
959        let peer = listener.local_addr().unwrap();
960
961        let mut client = TcpSocket::new(&ctx.sockets, SocketAddressFamily::Ipv4).unwrap();
962        client.start_connect(peer).unwrap();
963        poll_fn(|cx| client.poll_finish_connect(cx)).await.unwrap();
964        let (server, _) = listener.accept().await.unwrap();
965
966        // Query the outgoing socket's peer while the connection is healthy.
967        assert_eq!(client.remote_address().unwrap(), peer);
968        server.set_zero_linger().unwrap();
969        drop(server);
970
971        let mut input = client.take_receive_stream().unwrap();
972        let mut byte = [0];
973        let read = tokio::time::timeout(
974            Duration::from_secs(5),
975            poll_fn(|cx| input.poll_read(cx, &mut byte)),
976        )
977        .await
978        .unwrap();
979        assert!(matches!(read, Err(ErrorCode::ConnectionReset)));
980
981        // Subsequent queries must use the previously observed peer address.
982        let TcpState::Connected { stream, .. } = &client.tcp_state else {
983            panic!("expected an outgoing connection");
984        };
985        assert!(stream.peer_addr().is_err());
986        assert_eq!(client.remote_address().unwrap(), peer);
987    }
988}