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 // On linux we first attempt to pass the SOCK_CLOEXEC flag to
62 // atomically create the socket and set it as CLOEXEC. Support for
63 // this option, however, was added in 2.6.27, and we still support
64 // 2.6.18 as a kernel, so if the returned error is EINVAL we
65 // fallthrough to the fallback.
66 if cfg!(target_os = "linux") {
67 match cvt(libc::socket(fam, ty | SOCK_CLOEXEC, 0)) {
68 Ok(fd) => return Ok(Socket(FileDesc::new(fd))),
69 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}
70 Err(e) => return Err(e),
74 let fd = cvt(libc::socket(fam, ty, 0))?;
75 let fd = FileDesc::new(fd);
77 let socket = Socket(fd);
82 pub fn new_pair(_fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> {
86 pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
87 self.set_nonblocking(true)?;
89 let (addrp, len) = addr.into_inner();
90 cvt(libc::connect(self.0.raw(), addrp, len))
92 self.set_nonblocking(false)?;
95 Ok(_) => return Ok(()),
96 // there's no ErrorKind for EINPROGRESS :(
97 Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {}
98 Err(e) => return Err(e),
101 let mut pollfd = libc::pollfd {
103 events: libc::POLLOUT,
107 if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
108 return Err(io::Error::new(io::ErrorKind::InvalidInput,
109 "cannot set a 0 duration timeout"));
112 let start = Instant::now();
115 let elapsed = start.elapsed();
116 if elapsed >= timeout {
117 return Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out"));
120 let timeout = timeout - elapsed;
121 let mut timeout = timeout.as_secs()
122 .saturating_mul(1_000)
123 .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
128 let timeout = cmp::min(timeout, c_int::max_value() as u64) as c_int;
130 match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
132 let err = io::Error::last_os_error();
133 if err.kind() != io::ErrorKind::Interrupted {
139 // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look
140 // for POLLHUP rather than read readiness
141 if pollfd.revents & libc::POLLHUP != 0 {
142 let e = self.take_error()?
144 io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP")
155 pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t)
156 -> io::Result<Socket> {
157 // Unfortunately the only known way right now to accept a socket and
158 // atomically set the CLOEXEC flag is to use the `accept4` syscall on
159 // Linux. This was added in 2.6.28, however, and because we support
160 // 2.6.18 we must detect this support dynamically.
161 let fd = cvt_r(|| unsafe {
162 libc::accept(self.0.raw(), storage, len)
164 let fd = FileDesc::new(fd);
169 pub fn duplicate(&self) -> io::Result<Socket> {
170 self.0.duplicate().map(Socket)
173 fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
174 let ret = cvt(unsafe {
175 libc::recv(self.0.raw(),
176 buf.as_mut_ptr() as *mut c_void,
183 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
184 self.recv_with_flags(buf, 0)
187 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
188 self.recv_with_flags(buf, MSG_PEEK)
191 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
192 self.0.read_vectored(bufs)
195 fn recv_from_with_flags(&self, buf: &mut [u8], flags: c_int)
196 -> io::Result<(usize, SocketAddr)> {
197 let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
198 let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t;
201 libc::recvfrom(self.0.raw(),
202 buf.as_mut_ptr() as *mut c_void,
205 &mut storage as *mut _ as *mut _,
208 Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?))
211 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
212 self.recv_from_with_flags(buf, 0)
215 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
216 self.recv_from_with_flags(buf, MSG_PEEK)
219 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
223 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
224 self.0.write_vectored(bufs)
227 pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
228 let timeout = match dur {
230 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
231 return Err(io::Error::new(io::ErrorKind::InvalidInput,
232 "cannot set a 0 duration timeout"));
235 let secs = if dur.as_secs() > libc::time_t::max_value() as u64 {
236 libc::time_t::max_value()
238 dur.as_secs() as libc::time_t
240 let mut timeout = libc::timeval {
242 tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t,
244 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
256 setsockopt(self, libc::SOL_SOCKET, kind, timeout)
259 pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
260 let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
261 if raw.tv_sec == 0 && raw.tv_usec == 0 {
264 let sec = raw.tv_sec as u64;
265 let nsec = (raw.tv_usec as u32) * 1000;
266 Ok(Some(Duration::new(sec, nsec)))
270 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
271 let how = match how {
272 Shutdown::Write => libc::SHUT_WR,
273 Shutdown::Read => libc::SHUT_RD,
274 Shutdown::Both => libc::SHUT_RDWR,
276 cvt(unsafe { libc::shutdown(self.0.raw(), how) })?;
280 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
281 setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
284 pub fn nodelay(&self) -> io::Result<bool> {
285 let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
289 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
290 let mut nonblocking = nonblocking as libc::c_int;
291 cvt(unsafe { libc::ioctl(*self.as_inner(), libc::FIONBIO, &mut nonblocking) }).map(|_| ())
294 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
295 let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
299 Ok(Some(io::Error::from_raw_os_error(raw as i32)))
304 impl AsInner<c_int> for Socket {
305 fn as_inner(&self) -> &c_int { self.0.as_inner() }
308 impl FromInner<c_int> for Socket {
309 fn from_inner(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) }
312 impl IntoInner<c_int> for Socket {
313 fn into_inner(self) -> c_int { self.0.into_raw() }
316 // In versions of glibc prior to 2.26, there's a bug where the DNS resolver
317 // will cache the contents of /etc/resolv.conf, so changes to that file on disk
318 // can be ignored by a long-running program. That can break DNS lookups on e.g.
319 // laptops where the network comes and goes. See
320 // https://sourceware.org/bugzilla/show_bug.cgi?id=984. Note however that some
321 // distros including Debian have patched glibc to fix this for a long time.
323 // A workaround for this bug is to call the res_init libc function, to clear
324 // the cached configs. Unfortunately, while we believe glibc's implementation
325 // of res_init is thread-safe, we know that other implementations are not
326 // (https://github.com/rust-lang/rust/issues/43592). Code here in libstd could
327 // try to synchronize its res_init calls with a Mutex, but that wouldn't
328 // protect programs that call into libc in other ways. So instead of calling
329 // res_init unconditionally, we call it only when we detect we're linking
330 // against glibc version < 2.26. (That is, when we both know its needed and
331 // believe it's thread-safe).
332 #[cfg(target_env = "gnu")]
333 fn on_resolver_failure() {
337 // If the version fails to parse, we treat it the same as "not glibc".
338 if let Some(version) = sys::os::glibc_version() {
339 if version < (2, 26) {
340 unsafe { libc::res_init() };
346 #[cfg(not(target_env = "gnu"))]
347 fn on_resolver_failure() {}
349 #[cfg(all(test, taget_env = "gnu"))]
355 // This mostly just tests that the weak linkage doesn't panic wildly...
356 res_init_if_glibc_before_2_26().unwrap();
360 fn test_parse_glibc_version() {
362 ("0.0", Some((0, 0))),
363 ("01.+2", Some((1, 2))),
364 ("3.4.5.six", Some((3, 4))),
370 for &(version_str, parsed) in cases.iter() {
371 assert_eq!(parsed, parse_glibc_version(version_str));