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