Skip to main content

std/sys/net/connection/socket/
mod.rs

1#[cfg(test)]
2#[cfg(not(target_os = "l4re"))]
3mod tests;
4
5use crate::ffi::{c_int, c_void};
6use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut};
7use crate::mem::MaybeUninit;
8use crate::net::{
9    Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs,
10};
11use crate::sys::helpers::run_with_cstr;
12use crate::sys::net::connection::each_addr;
13use crate::sys::{AsInner, FromInner};
14use crate::time::Duration;
15use crate::{cmp, fmt, mem, ptr};
16
17cfg_select! {
18    target_os = "hermit" => {
19        mod hermit;
20        pub use hermit::*;
21    }
22    target_os = "solid_asp3" => {
23        mod solid;
24        pub use solid::*;
25    }
26    any(target_family = "unix", target_os = "wasi") => {
27        mod unix;
28        pub use unix::*;
29    }
30    target_os = "windows" => {
31        mod windows;
32        pub use windows::*;
33    }
34    _ => {}
35}
36
37use netc as c;
38
39// Similarly to reads (see READ_LIMIT), the `send` syscall on most platforms
40// takes a `size_t` length, but returns an `ssize_t` of bytes written. So the
41// actual maximum number of bytes we can send in one call is SSIZE_MAX.
42//
43// On Apple targets however, apparently the 64-bit libc is either buggy or
44// intentionally showing odd behavior by rejecting send calls with a size
45// larger than INT_MAX. So cap the send size to INT_MAX.
46//
47// Meanwhile on QNX, reads/writes/sends larger than INT_MAX return the wrong
48// number of bytes written (eg, writing 2^31 bytes returns (2^64 - 2^31) instead
49// of the correct byte count).
50//
51// On Windows, the relevant syscall takes an `i32` (unlike for read/write!),
52// so we need to clamp to i32::MAX.
53const MAX_SEND_LEN: usize = cfg_select! {
54    any(target_vendor = "apple", target_os = "nto", target_os = "qnx") => c_int::MAX as usize,
55    target_os = "windows" => i32::MAX as usize,
56    _ => libc::ssize_t::MAX as usize,
57};
58
59/// Some systems support setting the nonblocking mode upon socket creation, which
60/// saves a syscall.
61const SOCK_NONBLOCK: i32 = cfg_select! {
62    any(
63        target_os = "dragonfly",
64        target_os = "freebsd",
65        target_os = "hermit",
66        target_os = "illumos",
67        target_os = "linux",
68        target_os = "netbsd",
69        target_os = "openbsd",
70    ) => c::SOCK_NONBLOCK,
71    _ => 0,
72};
73
74cfg_select! {
75    any(
76        target_os = "dragonfly",
77        target_os = "freebsd",
78        target_os = "openbsd",
79        target_os = "netbsd",
80        target_os = "illumos",
81        target_os = "solaris",
82        target_os = "haiku",
83        target_os = "l4re",
84        target_os = "nto",
85        target_os = "qnx",
86        target_os = "nuttx",
87        target_vendor = "apple",
88    ) => {
89        use c::{IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP, IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP};
90    }
91    _ => {
92        use c::{IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP};
93    }
94}
95
96cfg_select! {
97    any(
98        target_os = "linux",
99        target_os = "android",
100        target_os = "hurd",
101        target_os = "dragonfly",
102        target_os = "freebsd",
103        target_os = "openbsd",
104        target_os = "netbsd",
105        target_os = "solaris",
106        target_os = "illumos",
107        target_os = "haiku",
108        target_os = "nto",
109        target_os = "qnx",
110        target_os = "cygwin",
111    ) => {
112        use libc::MSG_NOSIGNAL;
113    }
114    _ => {
115        const MSG_NOSIGNAL: c_int = 0x0;
116    }
117}
118
119cfg_select! {
120    any(
121        target_os = "dragonfly",
122        target_os = "freebsd",
123        target_os = "openbsd",
124        target_os = "netbsd",
125        target_os = "solaris",
126        target_os = "illumos",
127        target_os = "nto",
128        target_os = "qnx",
129    ) => {
130        use crate::ffi::c_uchar;
131        type IpV4MultiCastType = c_uchar;
132    }
133    _ => {
134        type IpV4MultiCastType = c_int;
135    }
136}
137
138////////////////////////////////////////////////////////////////////////////////
139// address conversions
140////////////////////////////////////////////////////////////////////////////////
141
142fn ip_v4_addr_to_c(addr: &Ipv4Addr) -> c::in_addr {
143    // `s_addr` is stored as BE on all machines and the array is in BE order.
144    // So the native endian conversion method is used so that it's never swapped.
145    c::in_addr { s_addr: u32::from_ne_bytes(addr.octets()) }
146}
147
148fn ip_v6_addr_to_c(addr: &Ipv6Addr) -> c::in6_addr {
149    c::in6_addr { s6_addr: addr.octets() }
150}
151
152fn ip_v4_addr_from_c(addr: c::in_addr) -> Ipv4Addr {
153    Ipv4Addr::from(addr.s_addr.to_ne_bytes())
154}
155
156fn ip_v6_addr_from_c(addr: c::in6_addr) -> Ipv6Addr {
157    Ipv6Addr::from(addr.s6_addr)
158}
159
160fn socket_addr_v4_to_c(addr: &SocketAddrV4) -> c::sockaddr_in {
161    c::sockaddr_in {
162        sin_family: c::AF_INET as c::sa_family_t,
163        sin_port: addr.port().to_be(),
164        sin_addr: ip_v4_addr_to_c(addr.ip()),
165        ..unsafe { mem::zeroed() }
166    }
167}
168
169fn socket_addr_v6_to_c(addr: &SocketAddrV6) -> c::sockaddr_in6 {
170    c::sockaddr_in6 {
171        sin6_family: c::AF_INET6 as c::sa_family_t,
172        sin6_port: addr.port().to_be(),
173        sin6_addr: ip_v6_addr_to_c(addr.ip()),
174        sin6_flowinfo: addr.flowinfo(),
175        sin6_scope_id: addr.scope_id(),
176        ..unsafe { mem::zeroed() }
177    }
178}
179
180fn socket_addr_v4_from_c(addr: c::sockaddr_in) -> SocketAddrV4 {
181    SocketAddrV4::new(ip_v4_addr_from_c(addr.sin_addr), u16::from_be(addr.sin_port))
182}
183
184fn socket_addr_v6_from_c(addr: c::sockaddr_in6) -> SocketAddrV6 {
185    SocketAddrV6::new(
186        ip_v6_addr_from_c(addr.sin6_addr),
187        u16::from_be(addr.sin6_port),
188        addr.sin6_flowinfo,
189        addr.sin6_scope_id,
190    )
191}
192
193/// A type with the same memory layout as `c::sockaddr`. Used in converting Rust level
194/// SocketAddr* types into their system representation. The benefit of this specific
195/// type over using `c::sockaddr_storage` is that this type is exactly as large as it
196/// needs to be and not a lot larger. And it can be initialized more cleanly from Rust.
197#[repr(C)]
198union SocketAddrCRepr {
199    v4: c::sockaddr_in,
200    v6: c::sockaddr_in6,
201}
202
203impl SocketAddrCRepr {
204    fn as_ptr(&self) -> *const c::sockaddr {
205        self as *const _ as *const c::sockaddr
206    }
207}
208
209fn socket_addr_to_c(addr: &SocketAddr) -> (SocketAddrCRepr, c::socklen_t) {
210    match addr {
211        SocketAddr::V4(a) => {
212            let sockaddr = SocketAddrCRepr { v4: socket_addr_v4_to_c(a) };
213            (sockaddr, size_of::<c::sockaddr_in>() as c::socklen_t)
214        }
215        SocketAddr::V6(a) => {
216            let sockaddr = SocketAddrCRepr { v6: socket_addr_v6_to_c(a) };
217            (sockaddr, size_of::<c::sockaddr_in6>() as c::socklen_t)
218        }
219    }
220}
221
222fn addr_family(addr: &SocketAddr) -> c_int {
223    match addr {
224        SocketAddr::V4(..) => c::AF_INET,
225        SocketAddr::V6(..) => c::AF_INET6,
226    }
227}
228
229/// Converts the C socket address stored in `storage` to a Rust `SocketAddr`.
230///
231/// # Safety
232/// * `storage` must contain a valid C socket address whose length is no larger
233///   than `len`.
234unsafe fn socket_addr_from_c(
235    storage: *const c::sockaddr_storage,
236    len: usize,
237) -> io::Result<SocketAddr> {
238    match (*storage).ss_family as c_int {
239        c::AF_INET => {
240            assert!(len >= size_of::<c::sockaddr_in>());
241            Ok(SocketAddr::V4(socket_addr_v4_from_c(unsafe {
242                *(storage as *const _ as *const c::sockaddr_in)
243            })))
244        }
245        c::AF_INET6 => {
246            assert!(len >= size_of::<c::sockaddr_in6>());
247            Ok(SocketAddr::V6(socket_addr_v6_from_c(unsafe {
248                *(storage as *const _ as *const c::sockaddr_in6)
249            })))
250        }
251        _ => Err(io::const_error!(ErrorKind::InvalidInput, "invalid argument")),
252    }
253}
254
255////////////////////////////////////////////////////////////////////////////////
256// sockaddr and misc bindings
257////////////////////////////////////////////////////////////////////////////////
258
259/// Sets the value of a socket option.
260///
261/// # Safety
262/// `T` must be the type associated with the given socket option.
263pub unsafe fn setsockopt<T>(
264    sock: &Socket,
265    level: c_int,
266    option_name: c_int,
267    option_value: T,
268) -> io::Result<()> {
269    let option_len = size_of::<T>() as c::socklen_t;
270    // SAFETY:
271    // * `sock` is opened for the duration of this call, as `sock` owns the socket.
272    // * the pointer to `option_value` is readable at a size of `size_of::<T>`
273    //   bytes
274    // * the value of `option_value` has a valid type for the given socket option
275    //   (guaranteed by caller).
276    cvt(unsafe {
277        c::setsockopt(
278            sock.as_raw(),
279            level,
280            option_name,
281            (&raw const option_value) as *const _,
282            option_len,
283        )
284    })?;
285    Ok(())
286}
287
288/// Gets the value of a socket option.
289///
290/// # Safety
291/// `T` must be the type associated with the given socket option.
292pub unsafe fn getsockopt<T: Copy>(
293    sock: &Socket,
294    level: c_int,
295    option_name: c_int,
296) -> io::Result<T> {
297    let mut option_value = MaybeUninit::<T>::zeroed();
298    let mut option_len = size_of::<T>() as c::socklen_t;
299
300    // SAFETY:
301    // * `sock` is opened for the duration of this call, as `sock` owns the socket.
302    // * the pointer to `option_value` is writable and the stack allocation has
303    //   space for `size_of::<T>` bytes.
304    cvt(unsafe {
305        c::getsockopt(
306            sock.as_raw(),
307            level,
308            option_name,
309            option_value.as_mut_ptr().cast(),
310            &mut option_len,
311        )
312    })?;
313
314    // SAFETY: the `getsockopt` call succeeded and the caller guarantees that
315    //         `T` is the type of this option, thus `option_value` must have
316    //         been initialized by the system.
317    Ok(unsafe { option_value.assume_init() })
318}
319
320/// Wraps a call to a platform function that returns a socket address.
321///
322/// # Safety
323/// * if `f` returns a success (i.e. `cvt` returns `Ok` when called on the
324///   return value), the buffer provided to `f` must have been initialized
325///   with a valid C socket address, the length of which must be written
326///   to the second argument.
327unsafe fn sockname<F>(f: F) -> io::Result<SocketAddr>
328where
329    F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int,
330{
331    let mut storage = MaybeUninit::<c::sockaddr_storage>::zeroed();
332    let mut len = size_of::<c::sockaddr_storage>() as c::socklen_t;
333    cvt(f(storage.as_mut_ptr().cast(), &mut len))?;
334    // SAFETY:
335    // The caller guarantees that the storage has been successfully initialized
336    // and its size written to `len` if `f` returns a success.
337    unsafe { socket_addr_from_c(storage.as_ptr(), len as usize) }
338}
339
340#[cfg(target_os = "android")]
341fn to_ipv6mr_interface(value: u32) -> c_int {
342    value as c_int
343}
344
345#[cfg(not(target_os = "android"))]
346fn to_ipv6mr_interface(value: u32) -> crate::ffi::c_uint {
347    value as crate::ffi::c_uint
348}
349
350////////////////////////////////////////////////////////////////////////////////
351// lookup_host
352////////////////////////////////////////////////////////////////////////////////
353
354pub struct LookupHost {
355    original: *mut c::addrinfo,
356    cur: *mut c::addrinfo,
357    port: u16,
358}
359
360impl Iterator for LookupHost {
361    type Item = SocketAddr;
362    fn next(&mut self) -> Option<SocketAddr> {
363        loop {
364            unsafe {
365                let cur = self.cur.as_ref()?;
366                self.cur = cur.ai_next;
367                match socket_addr_from_c(cur.ai_addr.cast(), cur.ai_addrlen as usize) {
368                    Ok(mut addr) => {
369                        addr.set_port(self.port);
370                        return Some(addr);
371                    }
372                    Err(_) => continue,
373                }
374            }
375        }
376    }
377}
378
379unsafe impl Sync for LookupHost {}
380unsafe impl Send for LookupHost {}
381
382impl Drop for LookupHost {
383    fn drop(&mut self) {
384        unsafe { c::freeaddrinfo(self.original) }
385    }
386}
387
388pub fn lookup_host(host: &str, port: u16) -> io::Result<LookupHost> {
389    init();
390    run_with_cstr(host.as_bytes(), &|c_host| {
391        let mut hints: c::addrinfo = unsafe { mem::zeroed() };
392        hints.ai_socktype = c::SOCK_STREAM;
393        let mut res = ptr::null_mut();
394        unsafe {
395            cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res))
396                .map(|_| LookupHost { original: res, cur: res, port })
397        }
398    })
399}
400
401////////////////////////////////////////////////////////////////////////////////
402// TCP streams
403////////////////////////////////////////////////////////////////////////////////
404
405pub struct TcpStream {
406    inner: Socket,
407}
408
409impl TcpStream {
410    pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
411        init();
412        return each_addr(addr, inner);
413
414        fn inner(addr: &SocketAddr) -> io::Result<TcpStream> {
415            let sock = Socket::new(addr_family(addr), c::SOCK_STREAM)?;
416            sock.connect(addr)?;
417            Ok(TcpStream { inner: sock })
418        }
419    }
420
421    pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
422        init();
423
424        let sock = Socket::new(addr_family(addr), c::SOCK_STREAM | SOCK_NONBLOCK)?;
425        if SOCK_NONBLOCK == 0 {
426            // The `SOCK_NONBLOCK` option is unsupported...
427            sock.set_nonblocking(true)?;
428        }
429
430        match sock.connect(addr) {
431            Ok(()) => {
432                sock.set_nonblocking(false)?;
433                return Ok(TcpStream { inner: sock });
434            }
435            #[cfg(not(target_os = "windows"))]
436            Err(ref e) if e.raw_os_error() == Some(c::EINPROGRESS) => {}
437            #[cfg(target_os = "windows")]
438            Err(ref e) if e.raw_os_error() == Some(crate::sys::pal::c::WSAEWOULDBLOCK) => {}
439            Err(e) => return Err(e),
440        }
441
442        sock.set_nonblocking(false)?;
443        sock.poll_connected(timeout)?;
444        Ok(TcpStream { inner: sock })
445    }
446
447    #[inline]
448    pub fn socket(&self) -> &Socket {
449        &self.inner
450    }
451
452    pub fn into_socket(self) -> Socket {
453        self.inner
454    }
455
456    pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
457        self.inner.set_timeout(dur, c::SO_RCVTIMEO)
458    }
459
460    pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
461        self.inner.set_timeout(dur, c::SO_SNDTIMEO)
462    }
463
464    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
465        self.inner.timeout(c::SO_RCVTIMEO)
466    }
467
468    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
469        self.inner.timeout(c::SO_SNDTIMEO)
470    }
471
472    pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
473        self.inner.peek(buf)
474    }
475
476    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
477        self.inner.read(buf)
478    }
479
480    pub fn read_buf(&self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
481        self.inner.read_buf(buf)
482    }
483
484    pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
485        self.inner.read_vectored(bufs)
486    }
487
488    #[inline]
489    pub fn is_read_vectored(&self) -> bool {
490        self.inner.is_read_vectored()
491    }
492
493    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
494        let len = cmp::min(buf.len(), MAX_SEND_LEN) as wrlen_t;
495        let ret = cvt(unsafe {
496            c::send(self.inner.as_raw(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL)
497        })?;
498        Ok(ret as usize)
499    }
500
501    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
502        self.inner.write_vectored(bufs)
503    }
504
505    #[inline]
506    pub fn is_write_vectored(&self) -> bool {
507        self.inner.is_write_vectored()
508    }
509
510    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
511        unsafe { sockname(|buf, len| c::getpeername(self.inner.as_raw(), buf, len)) }
512    }
513
514    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
515        unsafe { sockname(|buf, len| c::getsockname(self.inner.as_raw(), buf, len)) }
516    }
517
518    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
519        self.inner.shutdown(how)
520    }
521
522    pub fn duplicate(&self) -> io::Result<TcpStream> {
523        self.inner.duplicate().map(|s| TcpStream { inner: s })
524    }
525
526    pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
527        self.inner.set_linger(linger)
528    }
529
530    pub fn linger(&self) -> io::Result<Option<Duration>> {
531        self.inner.linger()
532    }
533
534    pub fn set_keepalive(&self, keepalive: bool) -> io::Result<()> {
535        self.inner.set_keepalive(keepalive)
536    }
537
538    pub fn keepalive(&self) -> io::Result<bool> {
539        self.inner.keepalive()
540    }
541
542    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
543        self.inner.set_nodelay(nodelay)
544    }
545
546    pub fn nodelay(&self) -> io::Result<bool> {
547        self.inner.nodelay()
548    }
549
550    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
551        unsafe { setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int) }
552    }
553
554    pub fn ttl(&self) -> io::Result<u32> {
555        let raw: c_int = unsafe { getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)? };
556        Ok(raw as u32)
557    }
558
559    pub fn set_hop_limit_v6(&self, limit: u8) -> io::Result<()> {
560        cfg_select! {
561            any(target_family = "unix", target_os = "windows") => unsafe {
562                setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_UNICAST_HOPS, limit as c_int)
563            },
564            _ => {
565                let _ = limit;
566                Err(io::Error::new(ErrorKind::Unsupported, "not supported on this platform"))
567            }
568        }
569    }
570
571    pub fn hop_limit_v6(&self) -> io::Result<u8> {
572        cfg_select! {
573            any(target_family = "unix", target_os = "windows") => {
574                let raw: c_int =
575                    unsafe { getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_UNICAST_HOPS)? };
576                Ok(raw as u8)
577            }
578            _ => Err(io::Error::new(ErrorKind::Unsupported, "not supported on this platform")),
579        }
580    }
581
582    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
583        self.inner.take_error()
584    }
585
586    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
587        self.inner.set_nonblocking(nonblocking)
588    }
589}
590
591impl AsInner<Socket> for TcpStream {
592    #[inline]
593    fn as_inner(&self) -> &Socket {
594        &self.inner
595    }
596}
597
598impl FromInner<Socket> for TcpStream {
599    fn from_inner(socket: Socket) -> TcpStream {
600        TcpStream { inner: socket }
601    }
602}
603
604impl fmt::Debug for TcpStream {
605    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
606        let mut res = f.debug_struct("TcpStream");
607
608        if let Ok(addr) = self.socket_addr() {
609            res.field("addr", &addr);
610        }
611
612        if let Ok(peer) = self.peer_addr() {
613            res.field("peer", &peer);
614        }
615
616        let name = if cfg!(windows) { "socket" } else { "fd" };
617        res.field(name, &self.inner.as_raw()).finish()
618    }
619}
620
621////////////////////////////////////////////////////////////////////////////////
622// TCP listeners
623////////////////////////////////////////////////////////////////////////////////
624
625pub struct TcpListener {
626    inner: Socket,
627}
628
629impl TcpListener {
630    pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
631        init();
632        return each_addr(addr, inner);
633
634        fn inner(addr: &SocketAddr) -> io::Result<TcpListener> {
635            let sock = Socket::new(addr_family(addr), c::SOCK_STREAM)?;
636
637            // On platforms with Berkeley-derived sockets, this allows to quickly
638            // rebind a socket, without needing to wait for the OS to clean up the
639            // previous one.
640            //
641            // On Windows, this allows rebinding sockets which are actively in use,
642            // which allows “socket hijacking”, so we explicitly don't set it here.
643            // https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
644            #[cfg(not(windows))]
645            unsafe {
646                setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR, 1 as c_int)?
647            };
648
649            // Bind our new socket
650            let (addr, len) = socket_addr_to_c(addr);
651            cvt(unsafe { c::bind(sock.as_raw(), addr.as_ptr(), len as _) })?;
652
653            let backlog = if cfg!(target_os = "horizon") {
654                // The 3DS doesn't support a big connection backlog. Sometimes
655                // it allows up to about 37, but other times it doesn't even
656                // accept 32. There may be a global limitation causing this.
657                20
658            } else if cfg!(target_os = "haiku") {
659                // Haiku does not support a queue length > 32
660                // https://github.com/haiku/haiku/blob/979a0bc487864675517fb2fab28f87dc8bf43041/headers/posix/sys/socket.h#L81
661                32
662            } else {
663                // The default for all other platforms
664                128
665            };
666
667            // Start listening
668            cvt(unsafe { c::listen(sock.as_raw(), backlog) })?;
669            Ok(TcpListener { inner: sock })
670        }
671    }
672
673    #[inline]
674    pub fn socket(&self) -> &Socket {
675        &self.inner
676    }
677
678    pub fn into_socket(self) -> Socket {
679        self.inner
680    }
681
682    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
683        unsafe { sockname(|buf, len| c::getsockname(self.inner.as_raw(), buf, len)) }
684    }
685
686    pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
687        // The `accept` function will fill in the storage with the address,
688        // so we don't need to zero it here.
689        // reference: https://linux.die.net/man/2/accept4
690        let mut storage = MaybeUninit::<c::sockaddr_storage>::uninit();
691        let mut len = size_of::<c::sockaddr_storage>() as c::socklen_t;
692        let sock = self.inner.accept(storage.as_mut_ptr() as *mut _, &mut len)?;
693        let addr = unsafe { socket_addr_from_c(storage.as_ptr(), len as usize)? };
694        Ok((TcpStream { inner: sock }, addr))
695    }
696
697    pub fn duplicate(&self) -> io::Result<TcpListener> {
698        self.inner.duplicate().map(|s| TcpListener { inner: s })
699    }
700
701    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
702        unsafe { setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int) }
703    }
704
705    pub fn ttl(&self) -> io::Result<u32> {
706        let raw: c_int = unsafe { getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)? };
707        Ok(raw as u32)
708    }
709
710    pub fn set_hop_limit_v6(&self, limit: u8) -> io::Result<()> {
711        cfg_select! {
712            any(target_family = "unix", target_os = "windows") => unsafe {
713                setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_UNICAST_HOPS, limit as c_int)
714            },
715            _ => {
716                let _ = limit;
717                Err(io::Error::new(ErrorKind::Unsupported, "not supported on this platform"))
718            }
719        }
720    }
721
722    pub fn hop_limit_v6(&self) -> io::Result<u8> {
723        cfg_select! {
724            any(target_family = "unix", target_os = "windows") => {
725                let raw: c_int =
726                    unsafe { getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_UNICAST_HOPS)? };
727                Ok(raw as u8)
728            }
729            _ => Err(io::Error::new(ErrorKind::Unsupported, "not supported on this platform")),
730        }
731    }
732
733    pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
734        unsafe { setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY, only_v6 as c_int) }
735    }
736
737    pub fn only_v6(&self) -> io::Result<bool> {
738        let raw: c_int = unsafe { getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY)? };
739        Ok(raw != 0)
740    }
741
742    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
743        self.inner.take_error()
744    }
745
746    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
747        self.inner.set_nonblocking(nonblocking)
748    }
749}
750
751impl FromInner<Socket> for TcpListener {
752    fn from_inner(socket: Socket) -> TcpListener {
753        TcpListener { inner: socket }
754    }
755}
756
757impl fmt::Debug for TcpListener {
758    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
759        let mut res = f.debug_struct("TcpListener");
760
761        if let Ok(addr) = self.socket_addr() {
762            res.field("addr", &addr);
763        }
764
765        let name = if cfg!(windows) { "socket" } else { "fd" };
766        res.field(name, &self.inner.as_raw()).finish()
767    }
768}
769
770////////////////////////////////////////////////////////////////////////////////
771// UDP
772////////////////////////////////////////////////////////////////////////////////
773
774pub struct UdpSocket {
775    inner: Socket,
776}
777
778impl UdpSocket {
779    pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
780        init();
781        return each_addr(addr, inner);
782
783        fn inner(addr: &SocketAddr) -> io::Result<UdpSocket> {
784            let sock = Socket::new(addr_family(addr), c::SOCK_DGRAM)?;
785            let (addr, len) = socket_addr_to_c(addr);
786            cvt(unsafe { c::bind(sock.as_raw(), addr.as_ptr(), len as _) })?;
787            Ok(UdpSocket { inner: sock })
788        }
789    }
790
791    #[inline]
792    pub fn socket(&self) -> &Socket {
793        &self.inner
794    }
795
796    pub fn into_socket(self) -> Socket {
797        self.inner
798    }
799
800    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
801        unsafe { sockname(|buf, len| c::getpeername(self.inner.as_raw(), buf, len)) }
802    }
803
804    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
805        unsafe { sockname(|buf, len| c::getsockname(self.inner.as_raw(), buf, len)) }
806    }
807
808    pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
809        self.inner.recv_from(buf)
810    }
811
812    pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
813        self.inner.peek_from(buf)
814    }
815
816    pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> {
817        if buf.len() > MAX_SEND_LEN {
818            return Err(io::Error::from_raw_os_error(c::EMSGSIZE));
819        }
820        let (dst, dstlen) = socket_addr_to_c(dst);
821        let ret = cvt(unsafe {
822            c::sendto(
823                self.inner.as_raw(),
824                buf.as_ptr() as *const c_void,
825                buf.len() as wrlen_t,
826                MSG_NOSIGNAL,
827                dst.as_ptr(),
828                dstlen,
829            )
830        })?;
831        Ok(ret as usize)
832    }
833
834    pub fn duplicate(&self) -> io::Result<UdpSocket> {
835        self.inner.duplicate().map(|s| UdpSocket { inner: s })
836    }
837
838    pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
839        self.inner.set_timeout(dur, c::SO_RCVTIMEO)
840    }
841
842    pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
843        self.inner.set_timeout(dur, c::SO_SNDTIMEO)
844    }
845
846    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
847        self.inner.timeout(c::SO_RCVTIMEO)
848    }
849
850    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
851        self.inner.timeout(c::SO_SNDTIMEO)
852    }
853
854    pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
855        unsafe { setsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST, broadcast as c_int) }
856    }
857
858    pub fn broadcast(&self) -> io::Result<bool> {
859        let raw: c_int = unsafe { getsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST)? };
860        Ok(raw != 0)
861    }
862
863    pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
864        unsafe {
865            setsockopt(
866                &self.inner,
867                c::IPPROTO_IP,
868                c::IP_MULTICAST_LOOP,
869                multicast_loop_v4 as IpV4MultiCastType,
870            )
871        }
872    }
873
874    pub fn multicast_loop_v4(&self) -> io::Result<bool> {
875        let raw: IpV4MultiCastType =
876            unsafe { getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_LOOP)? };
877        Ok(raw != 0)
878    }
879
880    pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
881        let ttl: u8 = multicast_ttl_v4
882            .try_into()
883            .map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?;
884        unsafe {
885            setsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL, ttl as IpV4MultiCastType)
886        }
887    }
888
889    pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
890        let raw: IpV4MultiCastType =
891            unsafe { getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL)? };
892        Ok(raw as u32)
893    }
894
895    pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
896        unsafe {
897            setsockopt(
898                &self.inner,
899                c::IPPROTO_IPV6,
900                c::IPV6_MULTICAST_LOOP,
901                multicast_loop_v6 as c_int,
902            )
903        }
904    }
905
906    pub fn multicast_loop_v6(&self) -> io::Result<bool> {
907        let raw: c_int =
908            unsafe { getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP)? };
909        Ok(raw != 0)
910    }
911
912    pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
913        let mreq = c::ip_mreq {
914            imr_multiaddr: ip_v4_addr_to_c(multiaddr),
915            imr_interface: ip_v4_addr_to_c(interface),
916        };
917        unsafe { setsockopt(&self.inner, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreq) }
918    }
919
920    pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
921        let mreq = c::ipv6_mreq {
922            ipv6mr_multiaddr: ip_v6_addr_to_c(multiaddr),
923            ipv6mr_interface: to_ipv6mr_interface(interface),
924        };
925        unsafe { setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq) }
926    }
927
928    pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
929        let mreq = c::ip_mreq {
930            imr_multiaddr: ip_v4_addr_to_c(multiaddr),
931            imr_interface: ip_v4_addr_to_c(interface),
932        };
933        unsafe { setsockopt(&self.inner, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreq) }
934    }
935
936    pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
937        let mreq = c::ipv6_mreq {
938            ipv6mr_multiaddr: ip_v6_addr_to_c(multiaddr),
939            ipv6mr_interface: to_ipv6mr_interface(interface),
940        };
941        unsafe { setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq) }
942    }
943
944    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
945        unsafe { setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int) }
946    }
947
948    pub fn ttl(&self) -> io::Result<u32> {
949        let raw: c_int = unsafe { getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)? };
950        Ok(raw as u32)
951    }
952
953    pub fn set_hop_limit_v6(&self, limit: u8) -> io::Result<()> {
954        cfg_select! {
955            any(target_family = "unix", target_os = "windows") => unsafe {
956                setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_UNICAST_HOPS, limit as c_int)
957            },
958            _ => {
959                let _ = limit;
960                Err(io::Error::new(ErrorKind::Unsupported, "not supported on this platform"))
961            }
962        }
963    }
964
965    pub fn hop_limit_v6(&self) -> io::Result<u8> {
966        cfg_select! {
967            any(target_family = "unix", target_os = "windows") => {
968                let raw: c_int =
969                    unsafe { getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_UNICAST_HOPS)? };
970                Ok(raw as u8)
971            }
972            _ => Err(io::Error::new(ErrorKind::Unsupported, "not supported on this platform")),
973        }
974    }
975
976    pub fn set_multicast_hop_limit_v6(&self, limit: u8) -> io::Result<()> {
977        cfg_select! {
978            any(target_family = "unix", target_os = "windows") => unsafe {
979                setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_HOPS, limit as c_int)
980            },
981            _ => {
982                let _ = limit;
983                Err(io::Error::new(ErrorKind::Unsupported, "not supported on this platform"))
984            }
985        }
986    }
987
988    pub fn multicast_hop_limit_v6(&self) -> io::Result<u8> {
989        cfg_select! {
990            any(target_family = "unix", target_os = "windows") => {
991                let raw: c_int =
992                    unsafe { getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_HOPS)? };
993                Ok(raw as u8)
994            }
995            _ => Err(io::Error::new(ErrorKind::Unsupported, "not supported on this platform")),
996        }
997    }
998
999    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
1000        self.inner.take_error()
1001    }
1002
1003    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
1004        self.inner.set_nonblocking(nonblocking)
1005    }
1006
1007    pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
1008        self.inner.read(buf)
1009    }
1010
1011    pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
1012        self.inner.peek(buf)
1013    }
1014
1015    pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
1016        if buf.len() > MAX_SEND_LEN {
1017            return Err(io::Error::from_raw_os_error(c::EMSGSIZE));
1018        }
1019        let ret = cvt(unsafe {
1020            c::send(
1021                self.inner.as_raw(),
1022                buf.as_ptr() as *const c_void,
1023                buf.len() as wrlen_t,
1024                MSG_NOSIGNAL,
1025            )
1026        })?;
1027        Ok(ret as usize)
1028    }
1029
1030    pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
1031        return each_addr(addr, |addr| inner(self, addr));
1032
1033        fn inner(this: &UdpSocket, addr: &SocketAddr) -> io::Result<()> {
1034            let (addr, len) = socket_addr_to_c(addr);
1035            cvt_r(|| unsafe { c::connect(this.inner.as_raw(), addr.as_ptr(), len) }).map(drop)
1036        }
1037    }
1038}
1039
1040impl FromInner<Socket> for UdpSocket {
1041    fn from_inner(socket: Socket) -> UdpSocket {
1042        UdpSocket { inner: socket }
1043    }
1044}
1045
1046impl fmt::Debug for UdpSocket {
1047    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1048        let mut res = f.debug_struct("UdpSocket");
1049
1050        if let Ok(addr) = self.socket_addr() {
1051            res.field("addr", &addr);
1052        }
1053
1054        let name = if cfg!(windows) { "socket" } else { "fd" };
1055        res.field(name, &self.inner.as_raw()).finish()
1056    }
1057}