Skip to main content

mio/sys/unix/
tcp.rs

1use std::io;
2use std::mem::{size_of, MaybeUninit};
3use std::net::{self, SocketAddr};
4#[cfg(not(target_os = "hermit"))]
5use std::os::fd::{AsRawFd, FromRawFd};
6// TODO: once <https://github.com/rust-lang/rust/issues/126198> is fixed this
7// can use `std::os::fd` and be merged with the above.
8#[cfg(target_os = "hermit")]
9use std::os::hermit::io::{AsRawFd, FromRawFd};
10
11use crate::sys::unix::net::{new_socket, socket_addr, to_socket_addr};
12
13pub(crate) fn new_for_addr(address: SocketAddr) -> io::Result<libc::c_int> {
14    let domain = match address {
15        SocketAddr::V4(_) => libc::AF_INET,
16        SocketAddr::V6(_) => libc::AF_INET6,
17    };
18    new_socket(domain, libc::SOCK_STREAM)
19}
20
21pub(crate) fn bind(socket: &net::TcpListener, addr: SocketAddr) -> io::Result<()> {
22    let (raw_addr, raw_addr_length) = socket_addr(&addr);
23    syscall!(bind(socket.as_raw_fd(), raw_addr.as_ptr(), raw_addr_length))?;
24    Ok(())
25}
26
27pub(crate) fn connect(socket: &net::TcpStream, addr: SocketAddr) -> io::Result<()> {
28    let (raw_addr, raw_addr_length) = socket_addr(&addr);
29
30    match syscall!(connect(
31        socket.as_raw_fd(),
32        raw_addr.as_ptr(),
33        raw_addr_length
34    )) {
35        Err(err) if err.raw_os_error() != Some(libc::EINPROGRESS) => Err(err),
36        _ => Ok(()),
37    }
38}
39
40pub(crate) fn listen(socket: &net::TcpListener, backlog: i32) -> io::Result<()> {
41    syscall!(listen(socket.as_raw_fd(), backlog))?;
42    Ok(())
43}
44
45pub(crate) fn set_reuseaddr(socket: &net::TcpListener, reuseaddr: bool) -> io::Result<()> {
46    let val: libc::c_int = i32::from(reuseaddr);
47    syscall!(setsockopt(
48        socket.as_raw_fd(),
49        libc::SOL_SOCKET,
50        libc::SO_REUSEADDR,
51        &val as *const libc::c_int as *const libc::c_void,
52        size_of::<libc::c_int>() as libc::socklen_t,
53    ))?;
54    Ok(())
55}
56
57pub(crate) fn accept(listener: &net::TcpListener) -> io::Result<(net::TcpStream, SocketAddr)> {
58    let mut addr: MaybeUninit<libc::sockaddr_storage> = MaybeUninit::uninit();
59    let mut length = size_of::<libc::sockaddr_storage>() as libc::socklen_t;
60
61    // On platforms that support it we can use `accept4(2)` to set `NONBLOCK`
62    // and `CLOEXEC` in the call to accept the connection.
63    #[cfg(any(
64        // Android x86's seccomp profile forbids calls to `accept4(2)`
65        // See https://github.com/tokio-rs/mio/issues/1445 for details
66        all(not(target_arch="x86"), target_os = "android"),
67        target_os = "dragonfly",
68        target_os = "freebsd",
69        target_os = "fuchsia",
70        target_os = "hurd",
71        target_os = "illumos",
72        target_os = "linux",
73        target_os = "netbsd",
74        target_os = "openbsd",
75        target_os = "solaris",
76        target_os = "cygwin",
77        target_os = "nuttx",
78    ))]
79    let stream = {
80        syscall!(accept4(
81            listener.as_raw_fd(),
82            addr.as_mut_ptr() as *mut _,
83            &mut length,
84            libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK,
85        ))
86        .map(|socket| unsafe { net::TcpStream::from_raw_fd(socket) })
87    }?;
88
89    // But not all platforms have the `accept4(2)` call. Luckily BSD (derived)
90    // OSs inherit the non-blocking flag from the listener, so we just have to
91    // set `CLOEXEC`.
92    #[cfg(any(
93        target_os = "aix",
94        target_os = "haiku",
95        target_os = "ios",
96        target_os = "macos",
97        target_os = "redox",
98        target_os = "tvos",
99        target_os = "visionos",
100        target_os = "watchos",
101        target_os = "espidf",
102        target_os = "vita",
103        target_os = "hermit",
104        target_os = "nto",
105        target_os = "wasi",
106        target_os = "horizon",
107        all(target_arch = "x86", target_os = "android"),
108    ))]
109    let stream = {
110        syscall!(accept(
111            listener.as_raw_fd(),
112            addr.as_mut_ptr() as *mut _,
113            &mut length
114        ))
115        .map(|socket| unsafe { net::TcpStream::from_raw_fd(socket) })
116        .and_then(|s| {
117            #[cfg(not(any(target_os = "espidf", target_os = "vita", target_os = "wasi")))]
118            syscall!(fcntl(s.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC))?;
119
120            // See https://github.com/tokio-rs/mio/issues/1450
121            #[cfg(any(
122                all(target_arch = "x86", target_os = "android"),
123                target_os = "aix",
124                target_os = "espidf",
125                target_os = "vita",
126                target_os = "hermit",
127                target_os = "nto",
128            ))]
129            syscall!(fcntl(s.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK))?;
130
131            // Once https://github.com/WebAssembly/wasi-libc/pull/742 lands and
132            // makes it into Rust std, we can remove this and switch to using
133            // `fcntl` above.
134            #[cfg(target_os = "wasi")]
135            syscall!(ioctl(s.as_raw_fd(), libc::FIONBIO, &mut 1))?;
136
137            Ok(s)
138        })
139    }?;
140
141    // This is safe because `accept` calls above ensures the address
142    // initialised.
143    unsafe { to_socket_addr(addr.as_ptr()) }.map(|addr| (stream, addr))
144}