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};
15 pub use crate::sys::{cvt, cvt_r};
17 #[allow(unused_extern_crates)]
18 pub extern crate libc as netc;
20 pub type wrlen_t = size_t;
22 pub struct Socket(FileDesc);
26 pub fn cvt_gai(err: c_int) -> io::Result<()> {
31 // We may need to trigger a glibc workaround. See on_resolver_failure() for details.
32 on_resolver_failure();
34 #[cfg(not(target_os = "espidf"))]
35 if err == libc::EAI_SYSTEM {
36 return Err(io::Error::last_os_error());
39 #[cfg(not(target_os = "espidf"))]
41 str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap().to_owned()
44 #[cfg(target_os = "espidf")]
48 io::ErrorKind::Uncategorized,
49 &format!("failed to lookup address information: {}", detail)[..],
54 pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
55 let fam = match *addr {
56 SocketAddr::V4(..) => libc::AF_INET,
57 SocketAddr::V6(..) => libc::AF_INET6,
59 Socket::new_raw(fam, ty)
62 pub fn new_raw(fam: c_int, ty: c_int) -> io::Result<Socket> {
66 target_os = "android",
67 target_os = "dragonfly",
68 target_os = "freebsd",
69 target_os = "illumos",
72 target_os = "openbsd",
74 // On platforms that support it we pass the SOCK_CLOEXEC
75 // flag to atomically create the socket and set it as
76 // CLOEXEC. On Linux this was added in 2.6.27.
77 let fd = cvt(libc::socket(fam, ty | libc::SOCK_CLOEXEC, 0))?;
78 Ok(Socket(FileDesc::from_raw_fd(fd)))
80 let fd = cvt(libc::socket(fam, ty, 0))?;
81 let fd = FileDesc::from_raw_fd(fd);
83 let socket = Socket(fd);
85 // macOS and iOS use `SO_NOSIGPIPE` as a `setsockopt`
86 // flag to disable `SIGPIPE` emission on socket.
87 #[cfg(target_vendor = "apple")]
88 setsockopt(&socket, libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1)?;
96 #[cfg(not(target_os = "vxworks"))]
97 pub fn new_pair(fam: c_int, ty: c_int) -> io::Result<(Socket, Socket)> {
103 target_os = "android",
104 target_os = "dragonfly",
105 target_os = "freebsd",
106 target_os = "illumos",
108 target_os = "netbsd",
109 target_os = "openbsd",
111 // Like above, set cloexec atomically
112 cvt(libc::socketpair(fam, ty | libc::SOCK_CLOEXEC, 0, fds.as_mut_ptr()))?;
113 Ok((Socket(FileDesc::from_raw_fd(fds[0])), Socket(FileDesc::from_raw_fd(fds[1]))))
115 cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?;
116 let a = FileDesc::from_raw_fd(fds[0]);
117 let b = FileDesc::from_raw_fd(fds[1]);
120 Ok((Socket(a), Socket(b)))
126 #[cfg(target_os = "vxworks")]
127 pub fn new_pair(_fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> {
131 pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
132 self.set_nonblocking(true)?;
134 let (addrp, len) = addr.into_inner();
135 cvt(libc::connect(self.as_raw_fd(), addrp, len))
137 self.set_nonblocking(false)?;
140 Ok(_) => return Ok(()),
141 // there's no ErrorKind for EINPROGRESS :(
142 Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {}
143 Err(e) => return Err(e),
146 let mut pollfd = libc::pollfd { fd: self.as_raw_fd(), events: libc::POLLOUT, revents: 0 };
148 if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
149 return Err(io::Error::new_const(
150 io::ErrorKind::InvalidInput,
151 &"cannot set a 0 duration timeout",
155 let start = Instant::now();
158 let elapsed = start.elapsed();
159 if elapsed >= timeout {
160 return Err(io::Error::new_const(io::ErrorKind::TimedOut, &"connection timed out"));
163 let timeout = timeout - elapsed;
164 let mut timeout = timeout
166 .saturating_mul(1_000)
167 .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
172 let timeout = cmp::min(timeout, c_int::MAX as u64) as c_int;
174 match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
176 let err = io::Error::last_os_error();
177 if err.kind() != io::ErrorKind::Interrupted {
183 // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look
184 // for POLLHUP rather than read readiness
185 if pollfd.revents & libc::POLLHUP != 0 {
186 let e = self.take_error()?.unwrap_or_else(|| {
187 io::Error::new_const(
188 io::ErrorKind::Uncategorized,
189 &"no error set after POLLHUP",
201 pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) -> io::Result<Socket> {
202 // Unfortunately the only known way right now to accept a socket and
203 // atomically set the CLOEXEC flag is to use the `accept4` syscall on
204 // platforms that support it. On Linux, this was added in 2.6.28,
205 // glibc 2.10 and musl 0.9.5.
208 target_os = "android",
209 target_os = "dragonfly",
210 target_os = "freebsd",
211 target_os = "illumos",
213 target_os = "netbsd",
214 target_os = "openbsd",
217 let fd = cvt_r(|| libc::accept4(self.as_raw_fd(), storage, len, libc::SOCK_CLOEXEC))?;
218 Ok(Socket(FileDesc::from_raw_fd(fd)))
222 let fd = cvt_r(|| libc::accept(self.as_raw_fd(), storage, len))?;
223 let fd = FileDesc::from_raw_fd(fd);
231 pub fn duplicate(&self) -> io::Result<Socket> {
232 self.0.duplicate().map(Socket)
235 fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
236 let ret = cvt(unsafe {
237 libc::recv(self.as_raw_fd(), buf.as_mut_ptr() as *mut c_void, buf.len(), flags)
242 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
243 self.recv_with_flags(buf, 0)
246 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
247 self.recv_with_flags(buf, MSG_PEEK)
250 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
251 self.0.read_vectored(bufs)
255 pub fn is_read_vectored(&self) -> bool {
256 self.0.is_read_vectored()
259 fn recv_from_with_flags(
263 ) -> io::Result<(usize, SocketAddr)> {
264 let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
265 let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t;
270 buf.as_mut_ptr() as *mut c_void,
273 &mut storage as *mut _ as *mut _,
277 Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?))
280 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
281 self.recv_from_with_flags(buf, 0)
285 target_os = "android",
286 target_os = "dragonfly",
287 target_os = "emscripten",
288 target_os = "freebsd",
290 target_os = "netbsd",
291 target_os = "openbsd",
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()
316 target_os = "android",
317 target_os = "dragonfly",
318 target_os = "emscripten",
319 target_os = "freebsd",
321 target_os = "netbsd",
322 target_os = "openbsd",
324 pub fn send_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
325 let n = cvt(unsafe { libc::sendmsg(self.as_raw_fd(), msg, 0) })?;
329 pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
330 let timeout = match dur {
332 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
333 return Err(io::Error::new_const(
334 io::ErrorKind::InvalidInput,
335 &"cannot set a 0 duration timeout",
339 let secs = if dur.as_secs() > libc::time_t::MAX as u64 {
342 dur.as_secs() as libc::time_t
344 let mut timeout = libc::timeval {
346 tv_usec: dur.subsec_micros() as libc::suseconds_t,
348 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
353 None => libc::timeval { tv_sec: 0, tv_usec: 0 },
355 setsockopt(self, libc::SOL_SOCKET, kind, timeout)
358 pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
359 let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
360 if raw.tv_sec == 0 && raw.tv_usec == 0 {
363 let sec = raw.tv_sec as u64;
364 let nsec = (raw.tv_usec as u32) * 1000;
365 Ok(Some(Duration::new(sec, nsec)))
369 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
370 let how = match how {
371 Shutdown::Write => libc::SHUT_WR,
372 Shutdown::Read => libc::SHUT_RD,
373 Shutdown::Both => libc::SHUT_RDWR,
375 cvt(unsafe { libc::shutdown(self.as_raw_fd(), how) })?;
379 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
380 setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
383 pub fn nodelay(&self) -> io::Result<bool> {
384 let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
388 #[cfg(any(target_os = "android", target_os = "linux",))]
389 pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
390 setsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED, passcred as libc::c_int)
393 #[cfg(any(target_os = "android", target_os = "linux",))]
394 pub fn passcred(&self) -> io::Result<bool> {
395 let passcred: libc::c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED)?;
399 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
400 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
401 let mut nonblocking = nonblocking as libc::c_int;
402 cvt(unsafe { libc::ioctl(self.as_raw_fd(), libc::FIONBIO, &mut nonblocking) }).map(drop)
405 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
406 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
407 // FIONBIO is inadequate for sockets on illumos/Solaris, so use the
408 // fcntl(F_[GS]ETFL)-based method provided by FileDesc instead.
409 self.0.set_nonblocking(nonblocking)
412 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
413 let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
414 if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
417 // This is used by sys_common code to abstract over Windows and Unix.
418 pub fn as_raw(&self) -> RawFd {
423 impl AsInner<FileDesc> for Socket {
424 fn as_inner(&self) -> &FileDesc {
429 impl IntoInner<FileDesc> for Socket {
430 fn into_inner(self) -> FileDesc {
435 impl FromInner<FileDesc> for Socket {
436 fn from_inner(file_desc: FileDesc) -> Self {
441 impl AsFd for Socket {
442 fn as_fd(&self) -> BorrowedFd<'_> {
447 impl AsRawFd for Socket {
448 fn as_raw_fd(&self) -> RawFd {
453 impl IntoRawFd for Socket {
454 fn into_raw_fd(self) -> RawFd {
459 impl FromRawFd for Socket {
460 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
461 Self(FromRawFd::from_raw_fd(raw_fd))
465 // In versions of glibc prior to 2.26, there's a bug where the DNS resolver
466 // will cache the contents of /etc/resolv.conf, so changes to that file on disk
467 // can be ignored by a long-running program. That can break DNS lookups on e.g.
468 // laptops where the network comes and goes. See
469 // https://sourceware.org/bugzilla/show_bug.cgi?id=984. Note however that some
470 // distros including Debian have patched glibc to fix this for a long time.
472 // A workaround for this bug is to call the res_init libc function, to clear
473 // the cached configs. Unfortunately, while we believe glibc's implementation
474 // of res_init is thread-safe, we know that other implementations are not
475 // (https://github.com/rust-lang/rust/issues/43592). Code here in libstd could
476 // try to synchronize its res_init calls with a Mutex, but that wouldn't
477 // protect programs that call into libc in other ways. So instead of calling
478 // res_init unconditionally, we call it only when we detect we're linking
479 // against glibc version < 2.26. (That is, when we both know its needed and
480 // believe it's thread-safe).
481 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
482 fn on_resolver_failure() {
485 // If the version fails to parse, we treat it the same as "not glibc".
486 if let Some(version) = sys::os::glibc_version() {
487 if version < (2, 26) {
488 unsafe { libc::res_init() };
493 #[cfg(any(not(target_env = "gnu"), target_os = "vxworks"))]
494 fn on_resolver_failure() {}