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 (addrp, len) = addr.into_inner();
143 cvt(libc::connect(self.as_raw_fd(), addrp, 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)
293 target_os = "android",
294 target_os = "dragonfly",
295 target_os = "emscripten",
296 target_os = "freebsd",
298 target_os = "netbsd",
299 target_os = "openbsd",
301 pub fn recv_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
302 let n = cvt(unsafe { libc::recvmsg(self.as_raw_fd(), msg, libc::MSG_CMSG_CLOEXEC) })?;
306 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
307 self.recv_from_with_flags(buf, MSG_PEEK)
310 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
314 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
315 self.0.write_vectored(bufs)
319 pub fn is_write_vectored(&self) -> bool {
320 self.0.is_write_vectored()
324 target_os = "android",
325 target_os = "dragonfly",
326 target_os = "emscripten",
327 target_os = "freebsd",
329 target_os = "netbsd",
330 target_os = "openbsd",
332 pub fn send_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
333 let n = cvt(unsafe { libc::sendmsg(self.as_raw_fd(), msg, 0) })?;
337 pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
338 let timeout = match dur {
340 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
341 return Err(io::const_io_error!(
342 io::ErrorKind::InvalidInput,
343 "cannot set a 0 duration timeout",
347 let secs = if dur.as_secs() > libc::time_t::MAX as u64 {
350 dur.as_secs() as libc::time_t
352 let mut timeout = libc::timeval {
354 tv_usec: dur.subsec_micros() as libc::suseconds_t,
356 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
361 None => libc::timeval { tv_sec: 0, tv_usec: 0 },
363 setsockopt(self, libc::SOL_SOCKET, kind, timeout)
366 pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
367 let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
368 if raw.tv_sec == 0 && raw.tv_usec == 0 {
371 let sec = raw.tv_sec as u64;
372 let nsec = (raw.tv_usec as u32) * 1000;
373 Ok(Some(Duration::new(sec, nsec)))
377 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
378 let how = match how {
379 Shutdown::Write => libc::SHUT_WR,
380 Shutdown::Read => libc::SHUT_RD,
381 Shutdown::Both => libc::SHUT_RDWR,
383 cvt(unsafe { libc::shutdown(self.as_raw_fd(), how) })?;
387 pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
388 let linger = libc::linger {
389 l_onoff: linger.is_some() as libc::c_int,
390 l_linger: linger.unwrap_or_default().as_secs() as libc::c_int,
393 setsockopt(self, libc::SOL_SOCKET, SO_LINGER, linger)
396 pub fn linger(&self) -> io::Result<Option<Duration>> {
397 let val: libc::linger = getsockopt(self, libc::SOL_SOCKET, SO_LINGER)?;
399 Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64)))
402 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
403 setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
406 pub fn nodelay(&self) -> io::Result<bool> {
407 let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
411 #[cfg(any(target_os = "android", target_os = "linux",))]
412 pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
413 setsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED, passcred as libc::c_int)
416 #[cfg(any(target_os = "android", target_os = "linux",))]
417 pub fn passcred(&self) -> io::Result<bool> {
418 let passcred: libc::c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED)?;
422 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
423 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
424 let mut nonblocking = nonblocking as libc::c_int;
425 cvt(unsafe { libc::ioctl(self.as_raw_fd(), libc::FIONBIO, &mut nonblocking) }).map(drop)
428 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
429 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
430 // FIONBIO is inadequate for sockets on illumos/Solaris, so use the
431 // fcntl(F_[GS]ETFL)-based method provided by FileDesc instead.
432 self.0.set_nonblocking(nonblocking)
435 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
436 let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
437 if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
440 // This is used by sys_common code to abstract over Windows and Unix.
441 pub fn as_raw(&self) -> RawFd {
446 impl AsInner<FileDesc> for Socket {
447 fn as_inner(&self) -> &FileDesc {
452 impl IntoInner<FileDesc> for Socket {
453 fn into_inner(self) -> FileDesc {
458 impl FromInner<FileDesc> for Socket {
459 fn from_inner(file_desc: FileDesc) -> Self {
464 impl AsFd for Socket {
465 fn as_fd(&self) -> BorrowedFd<'_> {
470 impl AsRawFd for Socket {
471 fn as_raw_fd(&self) -> RawFd {
476 impl IntoRawFd for Socket {
477 fn into_raw_fd(self) -> RawFd {
482 impl FromRawFd for Socket {
483 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
484 Self(FromRawFd::from_raw_fd(raw_fd))
488 // In versions of glibc prior to 2.26, there's a bug where the DNS resolver
489 // will cache the contents of /etc/resolv.conf, so changes to that file on disk
490 // can be ignored by a long-running program. That can break DNS lookups on e.g.
491 // laptops where the network comes and goes. See
492 // https://sourceware.org/bugzilla/show_bug.cgi?id=984. Note however that some
493 // distros including Debian have patched glibc to fix this for a long time.
495 // A workaround for this bug is to call the res_init libc function, to clear
496 // the cached configs. Unfortunately, while we believe glibc's implementation
497 // of res_init is thread-safe, we know that other implementations are not
498 // (https://github.com/rust-lang/rust/issues/43592). Code here in libstd could
499 // try to synchronize its res_init calls with a Mutex, but that wouldn't
500 // protect programs that call into libc in other ways. So instead of calling
501 // res_init unconditionally, we call it only when we detect we're linking
502 // against glibc version < 2.26. (That is, when we both know its needed and
503 // believe it's thread-safe).
504 #[cfg(all(target_os = "linux", target_env = "gnu"))]
505 fn on_resolver_failure() {
508 // If the version fails to parse, we treat it the same as "not glibc".
509 if let Some(version) = sys::os::glibc_version() {
510 if version < (2, 26) {
511 unsafe { libc::res_init() };
516 #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
517 fn on_resolver_failure() {}