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