]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/vxworks/net.rs
686cea49a6ea8066089a438e17e1b7253f3d3e97
[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             // 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),
71                 }
72             }
73
74             let fd = cvt(libc::socket(fam, ty, 0))?;
75             let fd = FileDesc::new(fd);
76             fd.set_cloexec()?;
77             let socket = Socket(fd);
78             Ok(socket)
79         }
80     }
81
82     pub fn new_pair(_fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> {
83             unimplemented!();
84     }
85
86     pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
87         self.set_nonblocking(true)?;
88         let r = unsafe {
89             let (addrp, len) = addr.into_inner();
90             cvt(libc::connect(self.0.raw(), addrp, len))
91         };
92         self.set_nonblocking(false)?;
93
94         match r {
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),
99         }
100
101         let mut pollfd = libc::pollfd {
102             fd: self.0.raw(),
103             events: libc::POLLOUT,
104             revents: 0,
105         };
106
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"));
110         }
111
112         let start = Instant::now();
113
114         loop {
115             let elapsed = start.elapsed();
116             if elapsed >= timeout {
117                 return Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out"));
118             }
119
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);
124             if timeout == 0 {
125                 timeout = 1;
126             }
127
128             let timeout = cmp::min(timeout, c_int::max_value() as u64) as c_int;
129
130             match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
131                 -1 => {
132                     let err = io::Error::last_os_error();
133                     if err.kind() != io::ErrorKind::Interrupted {
134                         return Err(err);
135                     }
136                 }
137                 0 => {}
138                 _ => {
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()?
143                             .unwrap_or_else(|| {
144                                 io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP")
145                             });
146                         return Err(e);
147                     }
148
149                     return Ok(());
150                 }
151             }
152         }
153     }
154
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)
163         })?;
164         let fd = FileDesc::new(fd);
165         fd.set_cloexec()?;
166         Ok(Socket(fd))
167     }
168
169     pub fn duplicate(&self) -> io::Result<Socket> {
170         self.0.duplicate().map(Socket)
171     }
172
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,
177                        buf.len(),
178                        flags)
179         })?;
180         Ok(ret as usize)
181     }
182
183     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
184         self.recv_with_flags(buf, 0)
185     }
186
187     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
188         self.recv_with_flags(buf, MSG_PEEK)
189     }
190
191     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
192         self.0.read_vectored(bufs)
193     }
194
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;
199
200         let n = cvt(unsafe {
201             libc::recvfrom(self.0.raw(),
202                         buf.as_mut_ptr() as *mut c_void,
203                         buf.len(),
204                         flags,
205                         &mut storage as *mut _ as *mut _,
206                         &mut addrlen)
207         })?;
208         Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?))
209     }
210
211     pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
212         self.recv_from_with_flags(buf, 0)
213     }
214
215     pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
216         self.recv_from_with_flags(buf, MSG_PEEK)
217     }
218
219     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
220         self.0.write(buf)
221     }
222
223     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
224         self.0.write_vectored(bufs)
225     }
226
227     pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
228         let timeout = match dur {
229             Some(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"));
233                 }
234
235                 let secs = if dur.as_secs() > libc::time_t::max_value() as u64 {
236                     libc::time_t::max_value()
237                 } else {
238                     dur.as_secs() as libc::time_t
239                 };
240                 let mut timeout = libc::timeval {
241                     tv_sec: secs,
242                     tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t,
243                 };
244                 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
245                     timeout.tv_usec = 1;
246                 }
247                 timeout
248             }
249             None => {
250                 libc::timeval {
251                     tv_sec: 0,
252                     tv_usec: 0,
253                 }
254             }
255         };
256         setsockopt(self, libc::SOL_SOCKET, kind, timeout)
257     }
258
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 {
262             Ok(None)
263         } else {
264             let sec = raw.tv_sec as u64;
265             let nsec = (raw.tv_usec as u32) * 1000;
266             Ok(Some(Duration::new(sec, nsec)))
267         }
268     }
269
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,
275         };
276         cvt(unsafe { libc::shutdown(self.0.raw(), how) })?;
277         Ok(())
278     }
279
280     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
281         setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
282     }
283
284     pub fn nodelay(&self) -> io::Result<bool> {
285         let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
286         Ok(raw != 0)
287     }
288
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(|_| ())
292     }
293
294     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
295         let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
296         if raw == 0 {
297             Ok(None)
298         } else {
299             Ok(Some(io::Error::from_raw_os_error(raw as i32)))
300         }
301     }
302 }
303
304 impl AsInner<c_int> for Socket {
305     fn as_inner(&self) -> &c_int { self.0.as_inner() }
306 }
307
308 impl FromInner<c_int> for Socket {
309     fn from_inner(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) }
310 }
311
312 impl IntoInner<c_int> for Socket {
313     fn into_inner(self) -> c_int { self.0.into_raw() }
314 }
315
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.
322 //
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() {
334 /*
335     use crate::sys;
336
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() };
341         }
342     }
343     */
344 }
345
346 #[cfg(not(target_env = "gnu"))]
347 fn on_resolver_failure() {}
348
349 #[cfg(all(test, taget_env = "gnu"))]
350 mod test {
351     use super::*;
352
353     #[test]
354     fn test_res_init() {
355         // This mostly just tests that the weak linkage doesn't panic wildly...
356         res_init_if_glibc_before_2_26().unwrap();
357     }
358
359     #[test]
360     fn test_parse_glibc_version() {
361         let cases = [
362             ("0.0", Some((0, 0))),
363             ("01.+2", Some((1, 2))),
364             ("3.4.5.six", Some((3, 4))),
365             ("1", None),
366             ("1.-2", None),
367             ("1.foo", None),
368             ("foo.1", None),
369         ];
370         for &(version_str, parsed) in cases.iter() {
371             assert_eq!(parsed, parse_glibc_version(version_str));
372         }
373     }
374 }