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