3 use crate::io::{IoSlice, IoSliceMut};
4 use libc::{self, c_int, c_void, size_t, sockaddr, socklen_t, EAI_SYSTEM, MSG_PEEK};
6 use crate::net::{SocketAddr, Shutdown};
8 use crate::sys::fd::FileDesc;
9 use crate::sys_common::{AsInner, FromInner, IntoInner};
10 use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr};
11 use crate::time::{Duration, Instant};
14 pub use crate::sys::{cvt, cvt_r};
16 #[allow(unused_extern_crates)]
17 pub extern crate libc as netc;
19 pub type wrlen_t = size_t;
22 const SOCK_CLOEXEC: c_int = 0;
23 const SO_NOSIGPIPE: c_int = 0;
25 pub struct Socket(FileDesc);
29 pub fn cvt_gai(err: c_int) -> io::Result<()> {
34 // We may need to trigger a glibc workaround. See on_resolver_failure() for details.
35 on_resolver_failure();
37 if err == EAI_SYSTEM {
38 return Err(io::Error::last_os_error())
42 str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap()
45 Err(io::Error::new(io::ErrorKind::Other,
46 &format!("failed to lookup address information: {}",
51 pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
52 let fam = match *addr {
53 SocketAddr::V4(..) => libc::AF_INET,
54 SocketAddr::V6(..) => libc::AF_INET6,
56 Socket::new_raw(fam, ty)
59 pub fn new_raw(fam: c_int, ty: c_int) -> io::Result<Socket> {
61 let fd = cvt(libc::socket(fam, ty, 0))?;
62 let fd = FileDesc::new(fd);
64 let socket = Socket(fd);
69 pub fn new_pair(_fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> {
73 pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
74 self.set_nonblocking(true)?;
76 let (addrp, len) = addr.into_inner();
77 cvt(libc::connect(self.0.raw(), addrp, len))
79 self.set_nonblocking(false)?;
82 Ok(_) => return Ok(()),
83 // there's no ErrorKind for EINPROGRESS :(
84 Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {}
85 Err(e) => return Err(e),
88 let mut pollfd = libc::pollfd {
90 events: libc::POLLOUT,
94 if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
95 return Err(io::Error::new(io::ErrorKind::InvalidInput,
96 "cannot set a 0 duration timeout"));
99 let start = Instant::now();
102 let elapsed = start.elapsed();
103 if elapsed >= timeout {
104 return Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out"));
107 let timeout = timeout - elapsed;
108 let mut timeout = timeout.as_secs()
109 .saturating_mul(1_000)
110 .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
115 let timeout = cmp::min(timeout, c_int::max_value() as u64) as c_int;
117 match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
119 let err = io::Error::last_os_error();
120 if err.kind() != io::ErrorKind::Interrupted {
126 // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look
127 // for POLLHUP rather than read readiness
128 if pollfd.revents & libc::POLLHUP != 0 {
129 let e = self.take_error()?
131 io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP")
142 pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t)
143 -> io::Result<Socket> {
144 let fd = cvt_r(|| unsafe {
145 libc::accept(self.0.raw(), storage, len)
147 let fd = FileDesc::new(fd);
152 pub fn duplicate(&self) -> io::Result<Socket> {
153 self.0.duplicate().map(Socket)
156 fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
157 let ret = cvt(unsafe {
158 libc::recv(self.0.raw(),
159 buf.as_mut_ptr() as *mut c_void,
166 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
167 self.recv_with_flags(buf, 0)
170 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
171 self.recv_with_flags(buf, MSG_PEEK)
174 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
175 self.0.read_vectored(bufs)
178 fn recv_from_with_flags(&self, buf: &mut [u8], flags: c_int)
179 -> io::Result<(usize, SocketAddr)> {
180 let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
181 let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t;
184 libc::recvfrom(self.0.raw(),
185 buf.as_mut_ptr() as *mut c_void,
188 &mut storage as *mut _ as *mut _,
191 Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?))
194 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
195 self.recv_from_with_flags(buf, 0)
198 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
199 self.recv_from_with_flags(buf, MSG_PEEK)
202 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
206 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
207 self.0.write_vectored(bufs)
210 pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
211 let timeout = match dur {
213 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
214 return Err(io::Error::new(io::ErrorKind::InvalidInput,
215 "cannot set a 0 duration timeout"));
218 let secs = if dur.as_secs() > libc::time_t::max_value() as u64 {
219 libc::time_t::max_value()
221 dur.as_secs() as libc::time_t
223 let mut timeout = libc::timeval {
225 tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t,
227 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
239 setsockopt(self, libc::SOL_SOCKET, kind, timeout)
242 pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
243 let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
244 if raw.tv_sec == 0 && raw.tv_usec == 0 {
247 let sec = raw.tv_sec as u64;
248 let nsec = (raw.tv_usec as u32) * 1000;
249 Ok(Some(Duration::new(sec, nsec)))
253 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
254 let how = match how {
255 Shutdown::Write => libc::SHUT_WR,
256 Shutdown::Read => libc::SHUT_RD,
257 Shutdown::Both => libc::SHUT_RDWR,
259 cvt(unsafe { libc::shutdown(self.0.raw(), how) })?;
263 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
264 setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
267 pub fn nodelay(&self) -> io::Result<bool> {
268 let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
272 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
273 let mut nonblocking = nonblocking as libc::c_int;
274 cvt(unsafe { libc::ioctl(*self.as_inner(), libc::FIONBIO, &mut nonblocking) }).map(|_| ())
277 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
278 let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
282 Ok(Some(io::Error::from_raw_os_error(raw as i32)))
287 impl AsInner<c_int> for Socket {
288 fn as_inner(&self) -> &c_int { self.0.as_inner() }
291 impl FromInner<c_int> for Socket {
292 fn from_inner(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) }
295 impl IntoInner<c_int> for Socket {
296 fn into_inner(self) -> c_int { self.0.into_raw() }
299 // In versions of glibc prior to 2.26, there's a bug where the DNS resolver
300 // will cache the contents of /etc/resolv.conf, so changes to that file on disk
301 // can be ignored by a long-running program. That can break DNS lookups on e.g.
302 // laptops where the network comes and goes. See
303 // https://sourceware.org/bugzilla/show_bug.cgi?id=984. Note however that some
304 // distros including Debian have patched glibc to fix this for a long time.
306 // A workaround for this bug is to call the res_init libc function, to clear
307 // the cached configs. Unfortunately, while we believe glibc's implementation
308 // of res_init is thread-safe, we know that other implementations are not
309 // (https://github.com/rust-lang/rust/issues/43592). Code here in libstd could
310 // try to synchronize its res_init calls with a Mutex, but that wouldn't
311 // protect programs that call into libc in other ways. So instead of calling
312 // res_init unconditionally, we call it only when we detect we're linking
313 // against glibc version < 2.26. (That is, when we both know its needed and
314 // believe it's thread-safe).
315 #[cfg(target_env = "gnu")]
316 fn on_resolver_failure() {
320 // If the version fails to parse, we treat it the same as "not glibc".
321 if let Some(version) = sys::os::glibc_version() {
322 if version < (2, 26) {
323 unsafe { libc::res_init() };
329 #[cfg(not(target_env = "gnu"))]
330 fn on_resolver_failure() {}
332 #[cfg(all(test, taget_env = "gnu"))]
338 // This mostly just tests that the weak linkage doesn't panic wildly...
339 res_init_if_glibc_before_2_26().unwrap();
343 fn test_parse_glibc_version() {
345 ("0.0", Some((0, 0))),
346 ("01.+2", Some((1, 2))),
347 ("3.4.5.six", Some((3, 4))),
353 for &(version_str, parsed) in cases.iter() {
354 assert_eq!(parsed, parse_glibc_version(version_str));