Skip to main content

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

1use libc::{MSG_PEEK, c_int, c_void, size_t, sockaddr, socklen_t};
2
3#[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
4use crate::ffi::CStr;
5use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut};
6use crate::net::{Shutdown, SocketAddr};
7use crate::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd};
8use crate::sys::fd::FileDesc;
9use crate::sys::net::{getsockopt, setsockopt};
10use crate::sys::pal::IsMinusOne;
11use crate::sys::{AsInner, FromInner, IntoInner};
12use crate::time::{Duration, Instant};
13use crate::{cmp, mem};
14
15cfg_select! {
16    target_vendor = "apple" => {
17        use libc::SO_LINGER_SEC as SO_LINGER;
18    }
19    _ => {
20        use libc::SO_LINGER;
21    }
22}
23
24pub(super) use libc as netc;
25
26use super::{socket_addr_from_c, socket_addr_to_c};
27pub use crate::sys::{cvt, cvt_r};
28
29#[expect(non_camel_case_types)]
30pub type wrlen_t = size_t;
31
32pub struct Socket(FileDesc);
33
34pub fn init() {}
35
36pub fn cvt_gai(err: c_int) -> io::Result<()> {
37    if err == 0 {
38        return Ok(());
39    }
40
41    // We may need to trigger a glibc workaround. See on_resolver_failure() for details.
42    on_resolver_failure();
43
44    #[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
45    if err == libc::EAI_SYSTEM {
46        return Err(io::Error::last_os_error());
47    }
48
49    #[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
50    let detail = unsafe {
51        // We can't always expect a UTF-8 environment. When we don't get that luxury,
52        // it's better to give a low-quality error message than none at all.
53        CStr::from_ptr(libc::gai_strerror(err)).to_string_lossy()
54    };
55
56    #[cfg(any(target_os = "espidf", target_os = "nuttx"))]
57    let detail = "";
58
59    Err(io::Error::new(
60        io::ErrorKind::Uncategorized,
61        &format!("failed to lookup address information: {detail}")[..],
62    ))
63}
64
65impl Socket {
66    pub fn new(family: c_int, ty: c_int) -> io::Result<Socket> {
67        cfg_select! {
68            any(
69                target_os = "android",
70                target_os = "dragonfly",
71                target_os = "freebsd",
72                target_os = "illumos",
73                target_os = "hurd",
74                target_os = "linux",
75                target_os = "netbsd",
76                target_os = "openbsd",
77                target_os = "cygwin",
78                target_os = "nto",
79                target_os = "qnx",
80                target_os = "solaris",
81            ) => {
82                // On platforms that support it we pass the SOCK_CLOEXEC
83                // flag to atomically create the socket and set it as
84                // CLOEXEC. On Linux this was added in 2.6.27.
85                let fd = cvt(unsafe { libc::socket(family, ty | libc::SOCK_CLOEXEC, 0) })?;
86                let socket = Socket(unsafe { FileDesc::from_raw_fd(fd) });
87
88                // DragonFlyBSD, FreeBSD and NetBSD use `SO_NOSIGPIPE` as a `setsockopt`
89                // flag to disable `SIGPIPE` emission on socket.
90                #[cfg(any(target_os = "freebsd", target_os = "netbsd", target_os = "dragonfly"))]
91                unsafe {
92                    setsockopt(&socket, libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1)?
93                };
94
95                Ok(socket)
96            }
97            _ => {
98                let fd = cvt(unsafe { libc::socket(family, ty, 0) })?;
99                let fd = unsafe { FileDesc::from_raw_fd(fd) };
100                fd.set_cloexec()?;
101                let socket = Socket(fd);
102
103                // macOS and iOS use `SO_NOSIGPIPE` as a `setsockopt`
104                // flag to disable `SIGPIPE` emission on socket.
105                #[cfg(target_vendor = "apple")]
106                unsafe {
107                    setsockopt(&socket, libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1)?
108                };
109
110                Ok(socket)
111            }
112        }
113    }
114
115    #[cfg(not(any(target_os = "vxworks", target_os = "wasi")))]
116    pub fn new_pair(fam: c_int, ty: c_int) -> io::Result<(Socket, Socket)> {
117        unsafe {
118            let mut fds = [0, 0];
119
120            cfg_select! {
121                any(
122                    target_os = "android",
123                    target_os = "dragonfly",
124                    target_os = "freebsd",
125                    target_os = "illumos",
126                    target_os = "linux",
127                    target_os = "hurd",
128                    target_os = "netbsd",
129                    target_os = "openbsd",
130                    target_os = "cygwin",
131                    target_os = "nto",
132                    target_os = "qnx",
133                ) => {
134                    // Like above, set cloexec atomically
135                    cvt(libc::socketpair(fam, ty | libc::SOCK_CLOEXEC, 0, fds.as_mut_ptr()))?;
136                    Ok((
137                        Socket(FileDesc::from_raw_fd(fds[0])),
138                        Socket(FileDesc::from_raw_fd(fds[1])),
139                    ))
140                }
141                _ => {
142                    cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?;
143                    let a = FileDesc::from_raw_fd(fds[0]);
144                    let b = FileDesc::from_raw_fd(fds[1]);
145                    a.set_cloexec()?;
146                    b.set_cloexec()?;
147                    Ok((Socket(a), Socket(b)))
148                }
149            }
150        }
151    }
152
153    #[cfg(target_os = "vxworks")]
154    pub fn new_pair(_fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> {
155        unimplemented!()
156    }
157
158    pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> {
159        let (addr, len) = socket_addr_to_c(addr);
160        loop {
161            let result = unsafe { libc::connect(self.as_raw_fd(), addr.as_ptr(), len) };
162            if result.is_minus_one() {
163                let err = crate::sys::io::errno();
164                match err {
165                    libc::EINTR => continue,
166                    libc::EISCONN => return Ok(()),
167                    _ => return Err(io::Error::from_raw_os_error(err)),
168                }
169            }
170            return Ok(());
171        }
172    }
173
174    pub fn poll_connected(&self, timeout: Duration) -> io::Result<()> {
175        let mut pollfd: libc::pollfd = unsafe { mem::zeroed() };
176        pollfd.fd = self.as_raw_fd();
177        pollfd.events = libc::POLLOUT;
178
179        if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
180            return Err(io::Error::ZERO_TIMEOUT);
181        }
182
183        let start = Instant::now();
184
185        loop {
186            let elapsed = start.elapsed();
187            if elapsed >= timeout {
188                return Err(io::const_error!(io::ErrorKind::TimedOut, "connection timed out"));
189            }
190
191            let timeout = timeout - elapsed;
192            let mut timeout = timeout
193                .as_secs()
194                .saturating_mul(1_000)
195                .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
196            if timeout == 0 {
197                timeout = 1;
198            }
199
200            let timeout = cmp::min(timeout, c_int::MAX as u64) as c_int;
201
202            match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
203                -1 => {
204                    let err = io::Error::last_os_error();
205                    if !err.is_interrupted() {
206                        return Err(err);
207                    }
208                }
209                0 => {}
210                _ => {
211                    // A completed connect makes the socket writable, but that doesn't guarantee it
212                    // succeeded: whether a failed connect also sets `POLLERR`/`POLLHUP` is
213                    // platform-specific. On Linux a clean `revents` means success. Elsewhere
214                    // (`illumos`, `VxWorks`) only `SO_ERROR` holds the actual status.
215                    let failure_shows_in_revents =
216                        cfg!(any(target_os = "linux", target_os = "android"));
217                    let hup_or_err = pollfd.revents & (libc::POLLHUP | libc::POLLERR) != 0;
218
219                    if failure_shows_in_revents && !hup_or_err {
220                        return Ok(());
221                    }
222
223                    if let Some(e) = self.take_error()? {
224                        return Err(e);
225                    }
226
227                    if hup_or_err {
228                        return Err(io::const_error!(
229                            io::ErrorKind::Uncategorized,
230                            "no error set after POLLHUP"
231                        ));
232                    }
233                    return Ok(());
234                }
235            }
236        }
237    }
238
239    pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) -> io::Result<Socket> {
240        // Unfortunately the only known way right now to accept a socket and
241        // atomically set the CLOEXEC flag is to use the `accept4` syscall on
242        // platforms that support it. On Linux, this was added in 2.6.28,
243        // glibc 2.10 and musl 0.9.5.
244        cfg_select! {
245            any(
246                target_os = "android",
247                target_os = "dragonfly",
248                target_os = "freebsd",
249                target_os = "illumos",
250                target_os = "linux",
251                target_os = "hurd",
252                target_os = "netbsd",
253                target_os = "openbsd",
254                target_os = "cygwin",
255            ) => unsafe {
256                let fd =
257                    cvt_r(|| libc::accept4(self.as_raw_fd(), storage, len, libc::SOCK_CLOEXEC))?;
258                Ok(Socket(FileDesc::from_raw_fd(fd)))
259            },
260            _ => unsafe {
261                let fd = cvt_r(|| libc::accept(self.as_raw_fd(), storage, len))?;
262                let fd = FileDesc::from_raw_fd(fd);
263                fd.set_cloexec()?;
264                Ok(Socket(fd))
265            },
266        }
267    }
268
269    pub fn duplicate(&self) -> io::Result<Socket> {
270        self.0.duplicate().map(Socket)
271    }
272
273    #[cfg(not(target_os = "wasi"))]
274    pub fn send_with_flags(&self, buf: &[u8], flags: c_int) -> io::Result<usize> {
275        let len = cmp::min(buf.len(), super::MAX_SEND_LEN) as wrlen_t;
276        let ret = cvt(unsafe {
277            libc::send(self.as_raw_fd(), buf.as_ptr() as *const c_void, len, flags)
278        })?;
279        Ok(ret as usize)
280    }
281
282    fn recv_with_flags(&self, mut buf: BorrowedCursor<'_, u8>, flags: c_int) -> io::Result<()> {
283        let ret = cvt(unsafe {
284            libc::recv(
285                self.as_raw_fd(),
286                buf.as_mut().as_mut_ptr() as *mut c_void,
287                buf.capacity(),
288                flags,
289            )
290        })?;
291        unsafe {
292            buf.advance(ret as usize);
293        }
294        Ok(())
295    }
296
297    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
298        let mut buf = BorrowedBuf::from(buf);
299        self.recv_with_flags(buf.unfilled(), 0)?;
300        Ok(buf.len())
301    }
302
303    pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
304        let mut buf = BorrowedBuf::from(buf);
305        self.recv_with_flags(buf.unfilled(), MSG_PEEK)?;
306        Ok(buf.len())
307    }
308
309    pub fn read_buf(&self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
310        self.recv_with_flags(buf, 0)
311    }
312
313    pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
314        self.0.read_vectored(bufs)
315    }
316
317    #[inline]
318    pub fn is_read_vectored(&self) -> bool {
319        self.0.is_read_vectored()
320    }
321
322    fn recv_from_with_flags(
323        &self,
324        buf: &mut [u8],
325        flags: c_int,
326    ) -> io::Result<(usize, SocketAddr)> {
327        // The `recvfrom` function will fill in the storage with the address,
328        // so we don't need to zero it here.
329        // reference: https://linux.die.net/man/2/recvfrom
330        let mut storage: mem::MaybeUninit<libc::sockaddr_storage> = mem::MaybeUninit::uninit();
331        let mut addrlen = size_of_val(&storage) as libc::socklen_t;
332
333        let n = cvt(unsafe {
334            libc::recvfrom(
335                self.as_raw_fd(),
336                buf.as_mut_ptr() as *mut c_void,
337                buf.len(),
338                flags,
339                (&raw mut storage) as *mut _,
340                &mut addrlen,
341            )
342        })?;
343        Ok((n as usize, unsafe { socket_addr_from_c(storage.as_ptr(), addrlen as usize)? }))
344    }
345
346    pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
347        self.recv_from_with_flags(buf, 0)
348    }
349
350    #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
351    pub fn recv_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
352        let n = cvt(unsafe { libc::recvmsg(self.as_raw_fd(), msg, libc::MSG_CMSG_CLOEXEC) })?;
353        Ok(n as usize)
354    }
355
356    pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
357        self.recv_from_with_flags(buf, MSG_PEEK)
358    }
359
360    #[cfg(not(target_os = "wasi"))]
361    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
362        self.0.write(buf)
363    }
364
365    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
366        self.0.write_vectored(bufs)
367    }
368
369    #[inline]
370    pub fn is_write_vectored(&self) -> bool {
371        self.0.is_write_vectored()
372    }
373
374    #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
375    pub fn send_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
376        let n = cvt(unsafe { libc::sendmsg(self.as_raw_fd(), msg, 0) })?;
377        Ok(n as usize)
378    }
379
380    pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
381        let timeout = match dur {
382            Some(dur) => {
383                if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
384                    return Err(io::Error::ZERO_TIMEOUT);
385                }
386
387                let secs = if dur.as_secs() > libc::time_t::MAX as u64 {
388                    libc::time_t::MAX
389                } else {
390                    dur.as_secs() as libc::time_t
391                };
392                let mut timeout = libc::timeval { tv_sec: secs, tv_usec: dur.subsec_micros() as _ };
393                if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
394                    timeout.tv_usec = 1;
395                }
396                timeout
397            }
398            None => libc::timeval { tv_sec: 0, tv_usec: 0 },
399        };
400        unsafe { setsockopt(self, libc::SOL_SOCKET, kind, timeout) }
401    }
402
403    pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
404        let raw: libc::timeval = unsafe { getsockopt(self, libc::SOL_SOCKET, kind)? };
405        if raw.tv_sec == 0 && raw.tv_usec == 0 {
406            Ok(None)
407        } else {
408            let sec = raw.tv_sec as u64;
409            let nsec = (raw.tv_usec as u32) * 1000;
410            Ok(Some(Duration::new(sec, nsec)))
411        }
412    }
413
414    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
415        let how = match how {
416            Shutdown::Write => libc::SHUT_WR,
417            Shutdown::Read => libc::SHUT_RD,
418            Shutdown::Both => libc::SHUT_RDWR,
419        };
420        cvt(unsafe { libc::shutdown(self.as_raw_fd(), how) })?;
421        Ok(())
422    }
423
424    #[cfg(not(target_os = "cygwin"))]
425    pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
426        let linger = libc::linger {
427            l_onoff: linger.is_some() as c_int,
428            l_linger: cmp::min(linger.unwrap_or_default().as_secs(), c_int::MAX as u64) as c_int,
429        };
430
431        unsafe { setsockopt(self, libc::SOL_SOCKET, SO_LINGER, linger) }
432    }
433
434    #[cfg(target_os = "cygwin")]
435    pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
436        let linger = libc::linger {
437            l_onoff: linger.is_some() as libc::c_ushort,
438            l_linger: cmp::min(linger.unwrap_or_default().as_secs(), libc::c_ushort::MAX as u64)
439                as libc::c_ushort,
440        };
441
442        unsafe { setsockopt(self, libc::SOL_SOCKET, SO_LINGER, linger) }
443    }
444
445    pub fn linger(&self) -> io::Result<Option<Duration>> {
446        let val: libc::linger = unsafe { getsockopt(self, libc::SOL_SOCKET, SO_LINGER)? };
447
448        Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64)))
449    }
450
451    pub fn set_keepalive(&self, keepalive: bool) -> io::Result<()> {
452        unsafe { setsockopt(self, libc::SOL_SOCKET, libc::SO_KEEPALIVE, keepalive as c_int) }
453    }
454
455    pub fn keepalive(&self) -> io::Result<bool> {
456        let raw: c_int = unsafe { getsockopt(self, libc::SOL_SOCKET, libc::SO_KEEPALIVE)? };
457        Ok(raw != 0)
458    }
459
460    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
461        unsafe { setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int) }
462    }
463
464    pub fn nodelay(&self) -> io::Result<bool> {
465        let raw: c_int = unsafe { getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)? };
466        Ok(raw != 0)
467    }
468
469    #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
470    pub fn set_quickack(&self, quickack: bool) -> io::Result<()> {
471        unsafe { setsockopt(self, libc::IPPROTO_TCP, libc::TCP_QUICKACK, quickack as c_int) }
472    }
473
474    #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
475    pub fn quickack(&self) -> io::Result<bool> {
476        let raw: c_int = unsafe { getsockopt(self, libc::IPPROTO_TCP, libc::TCP_QUICKACK)? };
477        Ok(raw != 0)
478    }
479
480    // bionic libc makes no use of this flag
481    #[cfg(target_os = "linux")]
482    pub fn set_deferaccept(&self, accept: Duration) -> io::Result<()> {
483        let val = cmp::min(accept.as_secs(), c_int::MAX as u64) as c_int;
484        unsafe { setsockopt(self, libc::IPPROTO_TCP, libc::TCP_DEFER_ACCEPT, val) }
485    }
486
487    #[cfg(target_os = "linux")]
488    pub fn deferaccept(&self) -> io::Result<Duration> {
489        let raw: c_int = unsafe { getsockopt(self, libc::IPPROTO_TCP, libc::TCP_DEFER_ACCEPT)? };
490        Ok(Duration::from_secs(raw as _))
491    }
492
493    #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
494    pub fn set_acceptfilter(&self, name: &CStr) -> io::Result<()> {
495        if !name.to_bytes().is_empty() {
496            const AF_NAME_MAX: usize = 16;
497            let mut buf = [0; AF_NAME_MAX];
498            for (src, dst) in name.to_bytes().iter().zip(&mut buf[..AF_NAME_MAX - 1]) {
499                *dst = *src as libc::c_char;
500            }
501            let mut arg: libc::accept_filter_arg = unsafe { mem::zeroed() };
502            arg.af_name = buf;
503            unsafe { setsockopt(self, libc::SOL_SOCKET, libc::SO_ACCEPTFILTER, &mut arg) }
504        } else {
505            unsafe {
506                setsockopt(
507                    self,
508                    libc::SOL_SOCKET,
509                    libc::SO_ACCEPTFILTER,
510                    core::ptr::null_mut() as *mut c_void,
511                )
512            }
513        }
514    }
515
516    #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
517    pub fn acceptfilter(&self) -> io::Result<&CStr> {
518        let arg: libc::accept_filter_arg =
519            unsafe { getsockopt(self, libc::SOL_SOCKET, libc::SO_ACCEPTFILTER)? };
520        let s: &[u8] =
521            unsafe { core::slice::from_raw_parts(arg.af_name.as_ptr() as *const u8, 16) };
522        let name = CStr::from_bytes_with_nul(s).unwrap();
523        Ok(name)
524    }
525
526    #[cfg(any(target_os = "solaris", target_os = "illumos"))]
527    pub fn set_exclbind(&self, excl: bool) -> io::Result<()> {
528        // not yet on libc crate
529        const SO_EXCLBIND: i32 = 0x1015;
530        unsafe { setsockopt(self, libc::SOL_SOCKET, SO_EXCLBIND, excl) }
531    }
532
533    #[cfg(any(target_os = "solaris", target_os = "illumos"))]
534    pub fn exclbind(&self) -> io::Result<bool> {
535        // not yet on libc crate
536        const SO_EXCLBIND: i32 = 0x1015;
537        let raw: c_int = unsafe { getsockopt(self, libc::SOL_SOCKET, SO_EXCLBIND)? };
538        Ok(raw != 0)
539    }
540
541    #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
542    pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
543        unsafe { setsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED, passcred as libc::c_int) }
544    }
545
546    #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
547    pub fn passcred(&self) -> io::Result<bool> {
548        let passcred: libc::c_int =
549            unsafe { getsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED)? };
550        Ok(passcred != 0)
551    }
552
553    #[cfg(target_os = "netbsd")]
554    pub fn set_local_creds(&self, local_creds: bool) -> io::Result<()> {
555        unsafe { setsockopt(self, 0 as libc::c_int, libc::LOCAL_CREDS, local_creds as libc::c_int) }
556    }
557
558    #[cfg(target_os = "netbsd")]
559    pub fn local_creds(&self) -> io::Result<bool> {
560        let local_creds: libc::c_int =
561            unsafe { getsockopt(self, 0 as libc::c_int, libc::LOCAL_CREDS)? };
562        Ok(local_creds != 0)
563    }
564
565    #[cfg(target_os = "freebsd")]
566    pub fn set_local_creds_persistent(&self, local_creds_persistent: bool) -> io::Result<()> {
567        unsafe {
568            setsockopt(
569                self,
570                libc::AF_LOCAL,
571                libc::LOCAL_CREDS_PERSISTENT,
572                local_creds_persistent as libc::c_int,
573            )
574        }
575    }
576
577    #[cfg(target_os = "freebsd")]
578    pub fn local_creds_persistent(&self) -> io::Result<bool> {
579        let local_creds_persistent: libc::c_int =
580            unsafe { getsockopt(self, libc::AF_LOCAL, libc::LOCAL_CREDS_PERSISTENT)? };
581        Ok(local_creds_persistent != 0)
582    }
583
584    #[cfg(not(any(target_os = "solaris", target_os = "illumos", target_os = "vita")))]
585    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
586        let mut nonblocking = nonblocking as libc::c_int;
587        cvt(unsafe { libc::ioctl(self.as_raw_fd(), libc::FIONBIO, &mut nonblocking) }).map(drop)
588    }
589
590    #[cfg(target_os = "vita")]
591    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
592        let option = nonblocking as libc::c_int;
593        unsafe { setsockopt(self, libc::SOL_SOCKET, libc::SO_NONBLOCK, option) }
594    }
595
596    #[cfg(any(target_os = "solaris", target_os = "illumos"))]
597    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
598        // FIONBIO is inadequate for sockets on illumos/Solaris, so use the
599        // fcntl(F_[GS]ETFL)-based method provided by FileDesc instead.
600        self.0.set_nonblocking(nonblocking)
601    }
602
603    #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
604    pub fn set_mark(&self, mark: u32) -> io::Result<()> {
605        #[cfg(target_os = "linux")]
606        let option = libc::SO_MARK;
607        #[cfg(target_os = "freebsd")]
608        let option = libc::SO_USER_COOKIE;
609        #[cfg(target_os = "openbsd")]
610        let option = libc::SO_RTABLE;
611        unsafe { setsockopt(self, libc::SOL_SOCKET, option, mark as libc::c_int) }
612    }
613
614    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
615        let raw: c_int = unsafe { getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)? };
616        if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
617    }
618
619    pub fn as_raw(&self) -> RawFd {
620        self.as_raw_fd()
621    }
622}
623
624impl AsInner<FileDesc> for Socket {
625    #[inline]
626    fn as_inner(&self) -> &FileDesc {
627        &self.0
628    }
629}
630
631impl IntoInner<FileDesc> for Socket {
632    fn into_inner(self) -> FileDesc {
633        self.0
634    }
635}
636
637impl FromInner<FileDesc> for Socket {
638    fn from_inner(file_desc: FileDesc) -> Self {
639        Self(file_desc)
640    }
641}
642
643impl AsFd for Socket {
644    fn as_fd(&self) -> BorrowedFd<'_> {
645        self.0.as_fd()
646    }
647}
648
649impl AsRawFd for Socket {
650    #[inline]
651    fn as_raw_fd(&self) -> RawFd {
652        self.0.as_raw_fd()
653    }
654}
655
656impl IntoRawFd for Socket {
657    fn into_raw_fd(self) -> RawFd {
658        self.0.into_raw_fd()
659    }
660}
661
662impl FromRawFd for Socket {
663    unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
664        Self(FromRawFd::from_raw_fd(raw_fd))
665    }
666}
667
668// In versions of glibc prior to 2.26, there's a bug where the DNS resolver
669// will cache the contents of /etc/resolv.conf, so changes to that file on disk
670// can be ignored by a long-running program. That can break DNS lookups on e.g.
671// laptops where the network comes and goes. See
672// https://sourceware.org/bugzilla/show_bug.cgi?id=984. Note however that some
673// distros including Debian have patched glibc to fix this for a long time.
674//
675// A workaround for this bug is to call the res_init libc function, to clear
676// the cached configs. Unfortunately, while we believe glibc's implementation
677// of res_init is thread-safe, we know that other implementations are not
678// (https://github.com/rust-lang/rust/issues/43592). Code here in std could
679// try to synchronize its res_init calls with a Mutex, but that wouldn't
680// protect programs that call into libc in other ways. So instead of calling
681// res_init unconditionally, we call it only when we detect we're linking
682// against glibc version < 2.26. (That is, when we both know its needed and
683// believe it's thread-safe).
684#[cfg(all(target_os = "linux", target_env = "gnu"))]
685fn on_resolver_failure() {
686    use crate::sys;
687
688    // If the version fails to parse, we treat it the same as "not glibc".
689    if let Some(version) = sys::pal::conf::glibc_version() {
690        if version < (2, 26) {
691            unsafe { libc::res_init() };
692        }
693    }
694}
695
696#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
697fn on_resolver_failure() {}