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