3 use crate::io::{self, IoSlice, IoSliceMut};
5 use crate::net::{Shutdown, SocketAddr};
6 use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd};
8 use crate::sys::fd::FileDesc;
9 use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr};
10 use crate::sys_common::{AsInner, FromInner, IntoInner};
11 use crate::time::{Duration, Instant};
13 use libc::{c_int, c_void, size_t, sockaddr, socklen_t, MSG_PEEK};
16 if #[cfg(target_vendor = "apple")] {
17 use libc::SO_LINGER_SEC as SO_LINGER;
23 pub use crate::sys::{cvt, cvt_r};
25 #[allow(unused_extern_crates)]
26 pub extern crate libc as netc;
28 pub type wrlen_t = size_t;
30 pub struct Socket(FileDesc);
34 pub fn cvt_gai(err: c_int) -> io::Result<()> {
39 // We may need to trigger a glibc workaround. See on_resolver_failure() for details.
40 on_resolver_failure();
42 #[cfg(not(target_os = "espidf"))]
43 if err == libc::EAI_SYSTEM {
44 return Err(io::Error::last_os_error());
47 #[cfg(not(target_os = "espidf"))]
49 str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap().to_owned()
52 #[cfg(target_os = "espidf")]
56 io::ErrorKind::Uncategorized,
57 &format!("failed to lookup address information: {detail}")[..],
62 pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
63 let fam = match *addr {
64 SocketAddr::V4(..) => libc::AF_INET,
65 SocketAddr::V6(..) => libc::AF_INET6,
67 Socket::new_raw(fam, ty)
70 pub fn new_raw(fam: c_int, ty: c_int) -> io::Result<Socket> {
74 target_os = "android",
75 target_os = "dragonfly",
76 target_os = "freebsd",
77 target_os = "illumos",
80 target_os = "openbsd",
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(libc::socket(fam, ty | libc::SOCK_CLOEXEC, 0))?;
86 Ok(Socket(FileDesc::from_raw_fd(fd)))
88 let fd = cvt(libc::socket(fam, ty, 0))?;
89 let fd = FileDesc::from_raw_fd(fd);
91 let socket = Socket(fd);
93 // macOS and iOS use `SO_NOSIGPIPE` as a `setsockopt`
94 // flag to disable `SIGPIPE` emission on socket.
95 #[cfg(target_vendor = "apple")]
96 setsockopt(&socket, libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1)?;
104 #[cfg(not(target_os = "vxworks"))]
105 pub fn new_pair(fam: c_int, ty: c_int) -> io::Result<(Socket, Socket)> {
107 let mut fds = [0, 0];
111 target_os = "android",
112 target_os = "dragonfly",
113 target_os = "freebsd",
114 target_os = "illumos",
116 target_os = "netbsd",
117 target_os = "openbsd",
119 // Like above, set cloexec atomically
120 cvt(libc::socketpair(fam, ty | libc::SOCK_CLOEXEC, 0, fds.as_mut_ptr()))?;
121 Ok((Socket(FileDesc::from_raw_fd(fds[0])), Socket(FileDesc::from_raw_fd(fds[1]))))
123 cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?;
124 let a = FileDesc::from_raw_fd(fds[0]);
125 let b = FileDesc::from_raw_fd(fds[1]);
128 Ok((Socket(a), Socket(b)))
134 #[cfg(target_os = "vxworks")]
135 pub fn new_pair(_fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> {
139 pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
140 self.set_nonblocking(true)?;
142 let (addr, len) = addr.into_inner();
143 cvt(libc::connect(self.as_raw_fd(), addr.as_ptr(), len))
145 self.set_nonblocking(false)?;
148 Ok(_) => return Ok(()),
149 // there's no ErrorKind for EINPROGRESS :(
150 Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {}
151 Err(e) => return Err(e),
154 let mut pollfd = libc::pollfd { fd: self.as_raw_fd(), events: libc::POLLOUT, revents: 0 };
156 if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
157 return Err(io::const_io_error!(
158 io::ErrorKind::InvalidInput,
159 "cannot set a 0 duration timeout",
163 let start = Instant::now();
166 let elapsed = start.elapsed();
167 if elapsed >= timeout {
168 return Err(io::const_io_error!(io::ErrorKind::TimedOut, "connection timed out"));
171 let timeout = timeout - elapsed;
172 let mut timeout = timeout
174 .saturating_mul(1_000)
175 .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
180 let timeout = cmp::min(timeout, c_int::MAX as u64) as c_int;
182 match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
184 let err = io::Error::last_os_error();
185 if err.kind() != io::ErrorKind::Interrupted {
191 // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look
192 // for POLLHUP rather than read readiness
193 if pollfd.revents & libc::POLLHUP != 0 {
194 let e = self.take_error()?.unwrap_or_else(|| {
196 io::ErrorKind::Uncategorized,
197 "no error set after POLLHUP",
209 pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) -> io::Result<Socket> {
210 // Unfortunately the only known way right now to accept a socket and
211 // atomically set the CLOEXEC flag is to use the `accept4` syscall on
212 // platforms that support it. On Linux, this was added in 2.6.28,
213 // glibc 2.10 and musl 0.9.5.
216 target_os = "android",
217 target_os = "dragonfly",
218 target_os = "freebsd",
219 target_os = "illumos",
221 target_os = "netbsd",
222 target_os = "openbsd",
225 let fd = cvt_r(|| libc::accept4(self.as_raw_fd(), storage, len, libc::SOCK_CLOEXEC))?;
226 Ok(Socket(FileDesc::from_raw_fd(fd)))
230 let fd = cvt_r(|| libc::accept(self.as_raw_fd(), storage, len))?;
231 let fd = FileDesc::from_raw_fd(fd);
239 pub fn duplicate(&self) -> io::Result<Socket> {
240 self.0.duplicate().map(Socket)
243 fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
244 let ret = cvt(unsafe {
245 libc::recv(self.as_raw_fd(), buf.as_mut_ptr() as *mut c_void, buf.len(), flags)
250 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
251 self.recv_with_flags(buf, 0)
254 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
255 self.recv_with_flags(buf, MSG_PEEK)
258 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
259 self.0.read_vectored(bufs)
263 pub fn is_read_vectored(&self) -> bool {
264 self.0.is_read_vectored()
267 fn recv_from_with_flags(
271 ) -> io::Result<(usize, SocketAddr)> {
272 let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
273 let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t;
278 buf.as_mut_ptr() as *mut c_void,
281 &mut storage as *mut _ as *mut _,
285 Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?))
288 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
289 self.recv_from_with_flags(buf, 0)
292 #[cfg(any(target_os = "android", target_os = "linux"))]
293 pub fn recv_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
294 let n = cvt(unsafe { libc::recvmsg(self.as_raw_fd(), msg, libc::MSG_CMSG_CLOEXEC) })?;
298 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
299 self.recv_from_with_flags(buf, MSG_PEEK)
302 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
306 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
307 self.0.write_vectored(bufs)
311 pub fn is_write_vectored(&self) -> bool {
312 self.0.is_write_vectored()
315 #[cfg(any(target_os = "android", target_os = "linux"))]
316 pub fn send_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
317 let n = cvt(unsafe { libc::sendmsg(self.as_raw_fd(), msg, 0) })?;
321 pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
322 let timeout = match dur {
324 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
325 return Err(io::const_io_error!(
326 io::ErrorKind::InvalidInput,
327 "cannot set a 0 duration timeout",
331 let secs = if dur.as_secs() > libc::time_t::MAX as u64 {
334 dur.as_secs() as libc::time_t
336 let mut timeout = libc::timeval {
338 tv_usec: dur.subsec_micros() as libc::suseconds_t,
340 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
345 None => libc::timeval { tv_sec: 0, tv_usec: 0 },
347 setsockopt(self, libc::SOL_SOCKET, kind, timeout)
350 pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
351 let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
352 if raw.tv_sec == 0 && raw.tv_usec == 0 {
355 let sec = raw.tv_sec as u64;
356 let nsec = (raw.tv_usec as u32) * 1000;
357 Ok(Some(Duration::new(sec, nsec)))
361 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
362 let how = match how {
363 Shutdown::Write => libc::SHUT_WR,
364 Shutdown::Read => libc::SHUT_RD,
365 Shutdown::Both => libc::SHUT_RDWR,
367 cvt(unsafe { libc::shutdown(self.as_raw_fd(), how) })?;
371 pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
372 let linger = libc::linger {
373 l_onoff: linger.is_some() as libc::c_int,
374 l_linger: linger.unwrap_or_default().as_secs() as libc::c_int,
377 setsockopt(self, libc::SOL_SOCKET, SO_LINGER, linger)
380 pub fn linger(&self) -> io::Result<Option<Duration>> {
381 let val: libc::linger = getsockopt(self, libc::SOL_SOCKET, SO_LINGER)?;
383 Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64)))
386 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
387 setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
390 pub fn nodelay(&self) -> io::Result<bool> {
391 let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
395 #[cfg(any(target_os = "android", target_os = "linux",))]
396 pub fn set_quickack(&self, quickack: bool) -> io::Result<()> {
397 setsockopt(self, libc::IPPROTO_TCP, libc::TCP_QUICKACK, quickack as c_int)
400 #[cfg(any(target_os = "android", target_os = "linux",))]
401 pub fn quickack(&self) -> io::Result<bool> {
402 let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_QUICKACK)?;
406 #[cfg(any(target_os = "android", target_os = "linux",))]
407 pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
408 setsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED, passcred as libc::c_int)
411 #[cfg(any(target_os = "android", target_os = "linux",))]
412 pub fn passcred(&self) -> io::Result<bool> {
413 let passcred: libc::c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED)?;
417 #[cfg(target_os = "netbsd")]
418 pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
419 setsockopt(self, 0 as libc::c_int, libc::LOCAL_CREDS, passcred as libc::c_int)
422 #[cfg(target_os = "netbsd")]
423 pub fn passcred(&self) -> io::Result<bool> {
424 let passcred: libc::c_int = getsockopt(self, 0 as libc::c_int, libc::LOCAL_CREDS)?;
428 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
429 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
430 let mut nonblocking = nonblocking as libc::c_int;
431 cvt(unsafe { libc::ioctl(self.as_raw_fd(), libc::FIONBIO, &mut nonblocking) }).map(drop)
434 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
435 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
436 // FIONBIO is inadequate for sockets on illumos/Solaris, so use the
437 // fcntl(F_[GS]ETFL)-based method provided by FileDesc instead.
438 self.0.set_nonblocking(nonblocking)
441 #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
442 pub fn set_mark(&self, mark: u32) -> io::Result<()> {
443 #[cfg(target_os = "linux")]
444 let option = libc::SO_MARK;
445 #[cfg(target_os = "freebsd")]
446 let option = libc::SO_USER_COOKIE;
447 #[cfg(target_os = "openbsd")]
448 let option = libc::SO_RTABLE;
449 setsockopt(self, libc::SOL_SOCKET, option, mark as libc::c_int)
452 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
453 let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
454 if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
457 // This is used by sys_common code to abstract over Windows and Unix.
458 pub fn as_raw(&self) -> RawFd {
463 impl AsInner<FileDesc> for Socket {
464 fn as_inner(&self) -> &FileDesc {
469 impl IntoInner<FileDesc> for Socket {
470 fn into_inner(self) -> FileDesc {
475 impl FromInner<FileDesc> for Socket {
476 fn from_inner(file_desc: FileDesc) -> Self {
481 impl AsFd for Socket {
482 fn as_fd(&self) -> BorrowedFd<'_> {
487 impl AsRawFd for Socket {
488 fn as_raw_fd(&self) -> RawFd {
493 impl IntoRawFd for Socket {
494 fn into_raw_fd(self) -> RawFd {
499 impl FromRawFd for Socket {
500 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
501 Self(FromRawFd::from_raw_fd(raw_fd))
505 // In versions of glibc prior to 2.26, there's a bug where the DNS resolver
506 // will cache the contents of /etc/resolv.conf, so changes to that file on disk
507 // can be ignored by a long-running program. That can break DNS lookups on e.g.
508 // laptops where the network comes and goes. See
509 // https://sourceware.org/bugzilla/show_bug.cgi?id=984. Note however that some
510 // distros including Debian have patched glibc to fix this for a long time.
512 // A workaround for this bug is to call the res_init libc function, to clear
513 // the cached configs. Unfortunately, while we believe glibc's implementation
514 // of res_init is thread-safe, we know that other implementations are not
515 // (https://github.com/rust-lang/rust/issues/43592). Code here in std could
516 // try to synchronize its res_init calls with a Mutex, but that wouldn't
517 // protect programs that call into libc in other ways. So instead of calling
518 // res_init unconditionally, we call it only when we detect we're linking
519 // against glibc version < 2.26. (That is, when we both know its needed and
520 // believe it's thread-safe).
521 #[cfg(all(target_os = "linux", target_env = "gnu"))]
522 fn on_resolver_failure() {
525 // If the version fails to parse, we treat it the same as "not glibc".
526 if let Some(version) = sys::os::glibc_version() {
527 if version < (2, 26) {
528 unsafe { libc::res_init() };
533 #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
534 fn on_resolver_failure() {}