]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/vxworks/net.rs
Rollup merge of #63004 - JohnTitor:add-tests-for-54062, r=Centril
[rust.git] / src / libstd / sys / vxworks / net.rs
1 use crate::ffi::CStr;
2 use crate::io;
3 use crate::io::{IoSlice, IoSliceMut};
4 use libc::{self, c_int, c_void, size_t, sockaddr, socklen_t, EAI_SYSTEM, MSG_PEEK};
5 use crate::mem;
6 use crate::net::{SocketAddr, Shutdown};
7 use crate::str;
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};
12 use crate::cmp;
13
14 pub use crate::sys::{cvt, cvt_r};
15
16 #[allow(unused_extern_crates)]
17 pub extern crate libc as netc;
18
19 pub type wrlen_t = size_t;
20
21
22 const SOCK_CLOEXEC: c_int = 0;
23 const SO_NOSIGPIPE: c_int = 0;
24
25 pub struct Socket(FileDesc);
26
27 pub fn init() {}
28
29 pub fn cvt_gai(err: c_int) -> io::Result<()> {
30     if err == 0 {
31         return Ok(())
32     }
33
34     // We may need to trigger a glibc workaround. See on_resolver_failure() for details.
35     on_resolver_failure();
36
37     if err == EAI_SYSTEM {
38         return Err(io::Error::last_os_error())
39     }
40
41     let detail = unsafe {
42         str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap()
43             .to_owned()
44     };
45     Err(io::Error::new(io::ErrorKind::Other,
46                        &format!("failed to lookup address information: {}",
47                                 detail)[..]))
48 }
49
50 impl Socket {
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,
55         };
56         Socket::new_raw(fam, ty)
57     }
58
59     pub fn new_raw(fam: c_int, ty: c_int) -> io::Result<Socket> {
60         unsafe {
61             let fd = cvt(libc::socket(fam, ty, 0))?;
62             let fd = FileDesc::new(fd);
63             fd.set_cloexec()?;
64             let socket = Socket(fd);
65             Ok(socket)
66         }
67     }
68
69     pub fn new_pair(_fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> {
70             unimplemented!();
71     }
72
73     pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
74         self.set_nonblocking(true)?;
75         let r = unsafe {
76             let (addrp, len) = addr.into_inner();
77             cvt(libc::connect(self.0.raw(), addrp, len))
78         };
79         self.set_nonblocking(false)?;
80
81         match r {
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),
86         }
87
88         let mut pollfd = libc::pollfd {
89             fd: self.0.raw(),
90             events: libc::POLLOUT,
91             revents: 0,
92         };
93
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"));
97         }
98
99         let start = Instant::now();
100
101         loop {
102             let elapsed = start.elapsed();
103             if elapsed >= timeout {
104                 return Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out"));
105             }
106
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);
111             if timeout == 0 {
112                 timeout = 1;
113             }
114
115             let timeout = cmp::min(timeout, c_int::max_value() as u64) as c_int;
116
117             match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
118                 -1 => {
119                     let err = io::Error::last_os_error();
120                     if err.kind() != io::ErrorKind::Interrupted {
121                         return Err(err);
122                     }
123                 }
124                 0 => {}
125                 _ => {
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()?
130                             .unwrap_or_else(|| {
131                                 io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP")
132                             });
133                         return Err(e);
134                     }
135
136                     return Ok(());
137                 }
138             }
139         }
140     }
141
142     pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t)
143                   -> io::Result<Socket> {
144         // Unfortunately the only known way right now to accept a socket and
145         // atomically set the CLOEXEC flag is to use the `accept4` syscall on
146         // Linux. This was added in 2.6.28, however, and because we support
147         // 2.6.18 we must detect this support dynamically.
148         let fd = cvt_r(|| unsafe {
149             libc::accept(self.0.raw(), storage, len)
150         })?;
151         let fd = FileDesc::new(fd);
152         fd.set_cloexec()?;
153         Ok(Socket(fd))
154     }
155
156     pub fn duplicate(&self) -> io::Result<Socket> {
157         self.0.duplicate().map(Socket)
158     }
159
160     fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
161         let ret = cvt(unsafe {
162             libc::recv(self.0.raw(),
163                        buf.as_mut_ptr() as *mut c_void,
164                        buf.len(),
165                        flags)
166         })?;
167         Ok(ret as usize)
168     }
169
170     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
171         self.recv_with_flags(buf, 0)
172     }
173
174     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
175         self.recv_with_flags(buf, MSG_PEEK)
176     }
177
178     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
179         self.0.read_vectored(bufs)
180     }
181
182     fn recv_from_with_flags(&self, buf: &mut [u8], flags: c_int)
183                             -> io::Result<(usize, SocketAddr)> {
184         let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
185         let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t;
186
187         let n = cvt(unsafe {
188             libc::recvfrom(self.0.raw(),
189                         buf.as_mut_ptr() as *mut c_void,
190                         buf.len(),
191                         flags,
192                         &mut storage as *mut _ as *mut _,
193                         &mut addrlen)
194         })?;
195         Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?))
196     }
197
198     pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
199         self.recv_from_with_flags(buf, 0)
200     }
201
202     pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
203         self.recv_from_with_flags(buf, MSG_PEEK)
204     }
205
206     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
207         self.0.write(buf)
208     }
209
210     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
211         self.0.write_vectored(bufs)
212     }
213
214     pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
215         let timeout = match dur {
216             Some(dur) => {
217                 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
218                     return Err(io::Error::new(io::ErrorKind::InvalidInput,
219                                               "cannot set a 0 duration timeout"));
220                 }
221
222                 let secs = if dur.as_secs() > libc::time_t::max_value() as u64 {
223                     libc::time_t::max_value()
224                 } else {
225                     dur.as_secs() as libc::time_t
226                 };
227                 let mut timeout = libc::timeval {
228                     tv_sec: secs,
229                     tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t,
230                 };
231                 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
232                     timeout.tv_usec = 1;
233                 }
234                 timeout
235             }
236             None => {
237                 libc::timeval {
238                     tv_sec: 0,
239                     tv_usec: 0,
240                 }
241             }
242         };
243         setsockopt(self, libc::SOL_SOCKET, kind, timeout)
244     }
245
246     pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
247         let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
248         if raw.tv_sec == 0 && raw.tv_usec == 0 {
249             Ok(None)
250         } else {
251             let sec = raw.tv_sec as u64;
252             let nsec = (raw.tv_usec as u32) * 1000;
253             Ok(Some(Duration::new(sec, nsec)))
254         }
255     }
256
257     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
258         let how = match how {
259             Shutdown::Write => libc::SHUT_WR,
260             Shutdown::Read => libc::SHUT_RD,
261             Shutdown::Both => libc::SHUT_RDWR,
262         };
263         cvt(unsafe { libc::shutdown(self.0.raw(), how) })?;
264         Ok(())
265     }
266
267     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
268         setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
269     }
270
271     pub fn nodelay(&self) -> io::Result<bool> {
272         let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
273         Ok(raw != 0)
274     }
275
276     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
277         let mut nonblocking = nonblocking as libc::c_int;
278         cvt(unsafe { libc::ioctl(*self.as_inner(), libc::FIONBIO, &mut nonblocking) }).map(|_| ())
279     }
280
281     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
282         let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
283         if raw == 0 {
284             Ok(None)
285         } else {
286             Ok(Some(io::Error::from_raw_os_error(raw as i32)))
287         }
288     }
289 }
290
291 impl AsInner<c_int> for Socket {
292     fn as_inner(&self) -> &c_int { self.0.as_inner() }
293 }
294
295 impl FromInner<c_int> for Socket {
296     fn from_inner(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) }
297 }
298
299 impl IntoInner<c_int> for Socket {
300     fn into_inner(self) -> c_int { self.0.into_raw() }
301 }
302
303 // In versions of glibc prior to 2.26, there's a bug where the DNS resolver
304 // will cache the contents of /etc/resolv.conf, so changes to that file on disk
305 // can be ignored by a long-running program. That can break DNS lookups on e.g.
306 // laptops where the network comes and goes. See
307 // https://sourceware.org/bugzilla/show_bug.cgi?id=984. Note however that some
308 // distros including Debian have patched glibc to fix this for a long time.
309 //
310 // A workaround for this bug is to call the res_init libc function, to clear
311 // the cached configs. Unfortunately, while we believe glibc's implementation
312 // of res_init is thread-safe, we know that other implementations are not
313 // (https://github.com/rust-lang/rust/issues/43592). Code here in libstd could
314 // try to synchronize its res_init calls with a Mutex, but that wouldn't
315 // protect programs that call into libc in other ways. So instead of calling
316 // res_init unconditionally, we call it only when we detect we're linking
317 // against glibc version < 2.26. (That is, when we both know its needed and
318 // believe it's thread-safe).
319 #[cfg(target_env = "gnu")]
320 fn on_resolver_failure() {
321 /*
322     use crate::sys;
323
324     // If the version fails to parse, we treat it the same as "not glibc".
325     if let Some(version) = sys::os::glibc_version() {
326         if version < (2, 26) {
327             unsafe { libc::res_init() };
328         }
329     }
330     */
331 }
332
333 #[cfg(not(target_env = "gnu"))]
334 fn on_resolver_failure() {}
335
336 #[cfg(all(test, taget_env = "gnu"))]
337 mod test {
338     use super::*;
339
340     #[test]
341     fn test_res_init() {
342         // This mostly just tests that the weak linkage doesn't panic wildly...
343         res_init_if_glibc_before_2_26().unwrap();
344     }
345
346     #[test]
347     fn test_parse_glibc_version() {
348         let cases = [
349             ("0.0", Some((0, 0))),
350             ("01.+2", Some((1, 2))),
351             ("3.4.5.six", Some((3, 4))),
352             ("1", None),
353             ("1.-2", None),
354             ("1.foo", None),
355             ("foo.1", None),
356         ];
357         for &(version_str, parsed) in cases.iter() {
358             assert_eq!(parsed, parse_glibc_version(version_str));
359         }
360     }
361 }