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