]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/net.rs
Auto merge of #84039 - jyn514:uplift-atomic-ordering, r=wesleywiser
[rust.git] / library / std / src / sys / unix / net.rs
1 use crate::cmp;
2 use crate::ffi::CStr;
3 use crate::io::{self, IoSlice, IoSliceMut};
4 use crate::mem;
5 use crate::net::{Shutdown, SocketAddr};
6 use crate::str;
7 use crate::sys::fd::FileDesc;
8 use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr};
9 use crate::sys_common::{AsInner, FromInner, IntoInner};
10 use crate::time::{Duration, Instant};
11
12 use libc::{c_int, c_void, size_t, sockaddr, socklen_t, MSG_PEEK};
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 pub struct Socket(FileDesc);
22
23 pub fn init() {}
24
25 pub fn cvt_gai(err: c_int) -> io::Result<()> {
26     if err == 0 {
27         return Ok(());
28     }
29
30     // We may need to trigger a glibc workaround. See on_resolver_failure() for details.
31     on_resolver_failure();
32
33     #[cfg(not(target_os = "espidf"))]
34     if err == libc::EAI_SYSTEM {
35         return Err(io::Error::last_os_error());
36     }
37
38     #[cfg(not(target_os = "espidf"))]
39     let detail = unsafe {
40         str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap().to_owned()
41     };
42
43     #[cfg(target_os = "espidf")]
44     let detail = "";
45
46     Err(io::Error::new(
47         io::ErrorKind::Uncategorized,
48         &format!("failed to lookup address information: {}", detail)[..],
49     ))
50 }
51
52 impl Socket {
53     pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
54         let fam = match *addr {
55             SocketAddr::V4(..) => libc::AF_INET,
56             SocketAddr::V6(..) => libc::AF_INET6,
57         };
58         Socket::new_raw(fam, ty)
59     }
60
61     pub fn new_raw(fam: c_int, ty: c_int) -> io::Result<Socket> {
62         unsafe {
63             cfg_if::cfg_if! {
64                 if #[cfg(any(
65                     target_os = "android",
66                     target_os = "dragonfly",
67                     target_os = "freebsd",
68                     target_os = "illumos",
69                     target_os = "linux",
70                     target_os = "netbsd",
71                     target_os = "openbsd",
72                 ))] {
73                     // On platforms that support it we pass the SOCK_CLOEXEC
74                     // flag to atomically create the socket and set it as
75                     // CLOEXEC. On Linux this was added in 2.6.27.
76                     let fd = cvt(libc::socket(fam, ty | libc::SOCK_CLOEXEC, 0))?;
77                     Ok(Socket(FileDesc::new(fd)))
78                 } else {
79                     let fd = cvt(libc::socket(fam, ty, 0))?;
80                     let fd = FileDesc::new(fd);
81                     fd.set_cloexec()?;
82                     let socket = Socket(fd);
83
84                     // macOS and iOS use `SO_NOSIGPIPE` as a `setsockopt`
85                     // flag to disable `SIGPIPE` emission on socket.
86                     #[cfg(target_vendor = "apple")]
87                     setsockopt(&socket, libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1)?;
88
89                     Ok(socket)
90                 }
91             }
92         }
93     }
94
95     #[cfg(not(target_os = "vxworks"))]
96     pub fn new_pair(fam: c_int, ty: c_int) -> io::Result<(Socket, Socket)> {
97         unsafe {
98             let mut fds = [0, 0];
99
100             cfg_if::cfg_if! {
101                 if #[cfg(any(
102                     target_os = "android",
103                     target_os = "dragonfly",
104                     target_os = "freebsd",
105                     target_os = "illumos",
106                     target_os = "linux",
107                     target_os = "netbsd",
108                     target_os = "openbsd",
109                 ))] {
110                     // Like above, set cloexec atomically
111                     cvt(libc::socketpair(fam, ty | libc::SOCK_CLOEXEC, 0, fds.as_mut_ptr()))?;
112                     Ok((Socket(FileDesc::new(fds[0])), Socket(FileDesc::new(fds[1]))))
113                 } else {
114                     cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?;
115                     let a = FileDesc::new(fds[0]);
116                     let b = FileDesc::new(fds[1]);
117                     a.set_cloexec()?;
118                     b.set_cloexec()?;
119                     Ok((Socket(a), Socket(b)))
120                 }
121             }
122         }
123     }
124
125     #[cfg(target_os = "vxworks")]
126     pub fn new_pair(_fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> {
127         unimplemented!()
128     }
129
130     pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
131         self.set_nonblocking(true)?;
132         let r = unsafe {
133             let (addrp, len) = addr.into_inner();
134             cvt(libc::connect(self.0.raw(), addrp, len))
135         };
136         self.set_nonblocking(false)?;
137
138         match r {
139             Ok(_) => return Ok(()),
140             // there's no ErrorKind for EINPROGRESS :(
141             Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {}
142             Err(e) => return Err(e),
143         }
144
145         let mut pollfd = libc::pollfd { fd: self.0.raw(), events: libc::POLLOUT, revents: 0 };
146
147         if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
148             return Err(io::Error::new_const(
149                 io::ErrorKind::InvalidInput,
150                 &"cannot set a 0 duration timeout",
151             ));
152         }
153
154         let start = Instant::now();
155
156         loop {
157             let elapsed = start.elapsed();
158             if elapsed >= timeout {
159                 return Err(io::Error::new_const(io::ErrorKind::TimedOut, &"connection timed out"));
160             }
161
162             let timeout = timeout - elapsed;
163             let mut timeout = timeout
164                 .as_secs()
165                 .saturating_mul(1_000)
166                 .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
167             if timeout == 0 {
168                 timeout = 1;
169             }
170
171             let timeout = cmp::min(timeout, c_int::MAX as u64) as c_int;
172
173             match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
174                 -1 => {
175                     let err = io::Error::last_os_error();
176                     if err.kind() != io::ErrorKind::Interrupted {
177                         return Err(err);
178                     }
179                 }
180                 0 => {}
181                 _ => {
182                     // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look
183                     // for POLLHUP rather than read readiness
184                     if pollfd.revents & libc::POLLHUP != 0 {
185                         let e = self.take_error()?.unwrap_or_else(|| {
186                             io::Error::new_const(
187                                 io::ErrorKind::Uncategorized,
188                                 &"no error set after POLLHUP",
189                             )
190                         });
191                         return Err(e);
192                     }
193
194                     return Ok(());
195                 }
196             }
197         }
198     }
199
200     pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) -> io::Result<Socket> {
201         // Unfortunately the only known way right now to accept a socket and
202         // atomically set the CLOEXEC flag is to use the `accept4` syscall on
203         // platforms that support it. On Linux, this was added in 2.6.28,
204         // glibc 2.10 and musl 0.9.5.
205         cfg_if::cfg_if! {
206             if #[cfg(any(
207                 target_os = "android",
208                 target_os = "dragonfly",
209                 target_os = "freebsd",
210                 target_os = "illumos",
211                 target_os = "linux",
212                 target_os = "netbsd",
213                 target_os = "openbsd",
214             ))] {
215                 let fd = cvt_r(|| unsafe {
216                     libc::accept4(self.0.raw(), storage, len, libc::SOCK_CLOEXEC)
217                 })?;
218                 Ok(Socket(FileDesc::new(fd)))
219             } else {
220                 let fd = cvt_r(|| unsafe { libc::accept(self.0.raw(), storage, len) })?;
221                 let fd = FileDesc::new(fd);
222                 fd.set_cloexec()?;
223                 Ok(Socket(fd))
224             }
225         }
226     }
227
228     pub fn duplicate(&self) -> io::Result<Socket> {
229         self.0.duplicate().map(Socket)
230     }
231
232     fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
233         let ret = cvt(unsafe {
234             libc::recv(self.0.raw(), buf.as_mut_ptr() as *mut c_void, buf.len(), flags)
235         })?;
236         Ok(ret as usize)
237     }
238
239     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
240         self.recv_with_flags(buf, 0)
241     }
242
243     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
244         self.recv_with_flags(buf, MSG_PEEK)
245     }
246
247     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
248         self.0.read_vectored(bufs)
249     }
250
251     #[inline]
252     pub fn is_read_vectored(&self) -> bool {
253         self.0.is_read_vectored()
254     }
255
256     fn recv_from_with_flags(
257         &self,
258         buf: &mut [u8],
259         flags: c_int,
260     ) -> io::Result<(usize, SocketAddr)> {
261         let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
262         let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t;
263
264         let n = cvt(unsafe {
265             libc::recvfrom(
266                 self.0.raw(),
267                 buf.as_mut_ptr() as *mut c_void,
268                 buf.len(),
269                 flags,
270                 &mut storage as *mut _ as *mut _,
271                 &mut addrlen,
272             )
273         })?;
274         Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?))
275     }
276
277     pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
278         self.recv_from_with_flags(buf, 0)
279     }
280
281     #[cfg(any(
282         target_os = "android",
283         target_os = "dragonfly",
284         target_os = "emscripten",
285         target_os = "freebsd",
286         target_os = "linux",
287         target_os = "netbsd",
288         target_os = "openbsd",
289     ))]
290     pub fn recv_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
291         let n = cvt(unsafe { libc::recvmsg(self.0.raw(), msg, libc::MSG_CMSG_CLOEXEC) })?;
292         Ok(n as usize)
293     }
294
295     pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
296         self.recv_from_with_flags(buf, MSG_PEEK)
297     }
298
299     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
300         self.0.write(buf)
301     }
302
303     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
304         self.0.write_vectored(bufs)
305     }
306
307     #[inline]
308     pub fn is_write_vectored(&self) -> bool {
309         self.0.is_write_vectored()
310     }
311
312     #[cfg(any(
313         target_os = "android",
314         target_os = "dragonfly",
315         target_os = "emscripten",
316         target_os = "freebsd",
317         target_os = "linux",
318         target_os = "netbsd",
319         target_os = "openbsd",
320     ))]
321     pub fn send_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
322         let n = cvt(unsafe { libc::sendmsg(self.0.raw(), msg, 0) })?;
323         Ok(n as usize)
324     }
325
326     pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
327         let timeout = match dur {
328             Some(dur) => {
329                 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
330                     return Err(io::Error::new_const(
331                         io::ErrorKind::InvalidInput,
332                         &"cannot set a 0 duration timeout",
333                     ));
334                 }
335
336                 let secs = if dur.as_secs() > libc::time_t::MAX as u64 {
337                     libc::time_t::MAX
338                 } else {
339                     dur.as_secs() as libc::time_t
340                 };
341                 let mut timeout = libc::timeval {
342                     tv_sec: secs,
343                     tv_usec: dur.subsec_micros() as libc::suseconds_t,
344                 };
345                 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
346                     timeout.tv_usec = 1;
347                 }
348                 timeout
349             }
350             None => libc::timeval { tv_sec: 0, tv_usec: 0 },
351         };
352         setsockopt(self, libc::SOL_SOCKET, kind, timeout)
353     }
354
355     pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
356         let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
357         if raw.tv_sec == 0 && raw.tv_usec == 0 {
358             Ok(None)
359         } else {
360             let sec = raw.tv_sec as u64;
361             let nsec = (raw.tv_usec as u32) * 1000;
362             Ok(Some(Duration::new(sec, nsec)))
363         }
364     }
365
366     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
367         let how = match how {
368             Shutdown::Write => libc::SHUT_WR,
369             Shutdown::Read => libc::SHUT_RD,
370             Shutdown::Both => libc::SHUT_RDWR,
371         };
372         cvt(unsafe { libc::shutdown(self.0.raw(), how) })?;
373         Ok(())
374     }
375
376     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
377         setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
378     }
379
380     pub fn nodelay(&self) -> io::Result<bool> {
381         let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
382         Ok(raw != 0)
383     }
384
385     #[cfg(any(target_os = "android", target_os = "linux",))]
386     pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
387         setsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED, passcred as libc::c_int)
388     }
389
390     #[cfg(any(target_os = "android", target_os = "linux",))]
391     pub fn passcred(&self) -> io::Result<bool> {
392         let passcred: libc::c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED)?;
393         Ok(passcred != 0)
394     }
395
396     #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
397     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
398         let mut nonblocking = nonblocking as libc::c_int;
399         cvt(unsafe { libc::ioctl(*self.as_inner(), libc::FIONBIO, &mut nonblocking) }).map(drop)
400     }
401
402     #[cfg(any(target_os = "solaris", target_os = "illumos"))]
403     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
404         // FIONBIO is inadequate for sockets on illumos/Solaris, so use the
405         // fcntl(F_[GS]ETFL)-based method provided by FileDesc instead.
406         self.0.set_nonblocking(nonblocking)
407     }
408
409     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
410         let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
411         if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
412     }
413 }
414
415 impl AsInner<c_int> for Socket {
416     fn as_inner(&self) -> &c_int {
417         self.0.as_inner()
418     }
419 }
420
421 impl FromInner<c_int> for Socket {
422     fn from_inner(fd: c_int) -> Socket {
423         Socket(FileDesc::new(fd))
424     }
425 }
426
427 impl IntoInner<c_int> for Socket {
428     fn into_inner(self) -> c_int {
429         self.0.into_raw()
430     }
431 }
432
433 // In versions of glibc prior to 2.26, there's a bug where the DNS resolver
434 // will cache the contents of /etc/resolv.conf, so changes to that file on disk
435 // can be ignored by a long-running program. That can break DNS lookups on e.g.
436 // laptops where the network comes and goes. See
437 // https://sourceware.org/bugzilla/show_bug.cgi?id=984. Note however that some
438 // distros including Debian have patched glibc to fix this for a long time.
439 //
440 // A workaround for this bug is to call the res_init libc function, to clear
441 // the cached configs. Unfortunately, while we believe glibc's implementation
442 // of res_init is thread-safe, we know that other implementations are not
443 // (https://github.com/rust-lang/rust/issues/43592). Code here in libstd could
444 // try to synchronize its res_init calls with a Mutex, but that wouldn't
445 // protect programs that call into libc in other ways. So instead of calling
446 // res_init unconditionally, we call it only when we detect we're linking
447 // against glibc version < 2.26. (That is, when we both know its needed and
448 // believe it's thread-safe).
449 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
450 fn on_resolver_failure() {
451     use crate::sys;
452
453     // If the version fails to parse, we treat it the same as "not glibc".
454     if let Some(version) = sys::os::glibc_version() {
455         if version < (2, 26) {
456             unsafe { libc::res_init() };
457         }
458     }
459 }
460
461 #[cfg(any(not(target_env = "gnu"), target_os = "vxworks"))]
462 fn on_resolver_failure() {}