]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/net.rs
Rollup merge of #101072 - tmandry:llvm-is-vanilla, r=Mark-Simulacrum
[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 (addr, len) = addr.into_inner();
143             cvt(libc::connect(self.as_raw_fd(), addr.as_ptr(), 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::const_io_error!(
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::const_io_error!(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::const_io_error!(
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(target_os = "android", target_os = "linux"))]
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(target_os = "android", target_os = "linux"))]
316     pub fn send_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
317         let n = cvt(unsafe { libc::sendmsg(self.as_raw_fd(), msg, 0) })?;
318         Ok(n as usize)
319     }
320
321     pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
322         let timeout = match dur {
323             Some(dur) => {
324                 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
325                     return Err(io::const_io_error!(
326                         io::ErrorKind::InvalidInput,
327                         "cannot set a 0 duration timeout",
328                     ));
329                 }
330
331                 let secs = if dur.as_secs() > libc::time_t::MAX as u64 {
332                     libc::time_t::MAX
333                 } else {
334                     dur.as_secs() as libc::time_t
335                 };
336                 let mut timeout = libc::timeval {
337                     tv_sec: secs,
338                     tv_usec: dur.subsec_micros() as libc::suseconds_t,
339                 };
340                 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
341                     timeout.tv_usec = 1;
342                 }
343                 timeout
344             }
345             None => libc::timeval { tv_sec: 0, tv_usec: 0 },
346         };
347         setsockopt(self, libc::SOL_SOCKET, kind, timeout)
348     }
349
350     pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
351         let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
352         if raw.tv_sec == 0 && raw.tv_usec == 0 {
353             Ok(None)
354         } else {
355             let sec = raw.tv_sec as u64;
356             let nsec = (raw.tv_usec as u32) * 1000;
357             Ok(Some(Duration::new(sec, nsec)))
358         }
359     }
360
361     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
362         let how = match how {
363             Shutdown::Write => libc::SHUT_WR,
364             Shutdown::Read => libc::SHUT_RD,
365             Shutdown::Both => libc::SHUT_RDWR,
366         };
367         cvt(unsafe { libc::shutdown(self.as_raw_fd(), how) })?;
368         Ok(())
369     }
370
371     pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
372         let linger = libc::linger {
373             l_onoff: linger.is_some() as libc::c_int,
374             l_linger: linger.unwrap_or_default().as_secs() as libc::c_int,
375         };
376
377         setsockopt(self, libc::SOL_SOCKET, SO_LINGER, linger)
378     }
379
380     pub fn linger(&self) -> io::Result<Option<Duration>> {
381         let val: libc::linger = getsockopt(self, libc::SOL_SOCKET, SO_LINGER)?;
382
383         Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64)))
384     }
385
386     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
387         setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
388     }
389
390     pub fn nodelay(&self) -> io::Result<bool> {
391         let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
392         Ok(raw != 0)
393     }
394
395     #[cfg(any(target_os = "android", target_os = "linux",))]
396     pub fn set_quickack(&self, quickack: bool) -> io::Result<()> {
397         setsockopt(self, libc::IPPROTO_TCP, libc::TCP_QUICKACK, quickack as c_int)
398     }
399
400     #[cfg(any(target_os = "android", target_os = "linux",))]
401     pub fn quickack(&self) -> io::Result<bool> {
402         let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_QUICKACK)?;
403         Ok(raw != 0)
404     }
405
406     #[cfg(any(target_os = "android", target_os = "linux",))]
407     pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
408         setsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED, passcred as libc::c_int)
409     }
410
411     #[cfg(any(target_os = "android", target_os = "linux",))]
412     pub fn passcred(&self) -> io::Result<bool> {
413         let passcred: libc::c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED)?;
414         Ok(passcred != 0)
415     }
416
417     #[cfg(target_os = "netbsd")]
418     pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
419         setsockopt(self, 0 as libc::c_int, libc::LOCAL_CREDS, passcred as libc::c_int)
420     }
421
422     #[cfg(target_os = "netbsd")]
423     pub fn passcred(&self) -> io::Result<bool> {
424         let passcred: libc::c_int = getsockopt(self, 0 as libc::c_int, libc::LOCAL_CREDS)?;
425         Ok(passcred != 0)
426     }
427
428     #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
429     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
430         let mut nonblocking = nonblocking as libc::c_int;
431         cvt(unsafe { libc::ioctl(self.as_raw_fd(), libc::FIONBIO, &mut nonblocking) }).map(drop)
432     }
433
434     #[cfg(any(target_os = "solaris", target_os = "illumos"))]
435     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
436         // FIONBIO is inadequate for sockets on illumos/Solaris, so use the
437         // fcntl(F_[GS]ETFL)-based method provided by FileDesc instead.
438         self.0.set_nonblocking(nonblocking)
439     }
440
441     #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
442     pub fn set_mark(&self, mark: u32) -> io::Result<()> {
443         #[cfg(target_os = "linux")]
444         let option = libc::SO_MARK;
445         #[cfg(target_os = "freebsd")]
446         let option = libc::SO_USER_COOKIE;
447         #[cfg(target_os = "openbsd")]
448         let option = libc::SO_RTABLE;
449         setsockopt(self, libc::SOL_SOCKET, option, mark as libc::c_int)
450     }
451
452     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
453         let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
454         if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
455     }
456
457     // This is used by sys_common code to abstract over Windows and Unix.
458     pub fn as_raw(&self) -> RawFd {
459         self.as_raw_fd()
460     }
461 }
462
463 impl AsInner<FileDesc> for Socket {
464     fn as_inner(&self) -> &FileDesc {
465         &self.0
466     }
467 }
468
469 impl IntoInner<FileDesc> for Socket {
470     fn into_inner(self) -> FileDesc {
471         self.0
472     }
473 }
474
475 impl FromInner<FileDesc> for Socket {
476     fn from_inner(file_desc: FileDesc) -> Self {
477         Self(file_desc)
478     }
479 }
480
481 impl AsFd for Socket {
482     fn as_fd(&self) -> BorrowedFd<'_> {
483         self.0.as_fd()
484     }
485 }
486
487 impl AsRawFd for Socket {
488     fn as_raw_fd(&self) -> RawFd {
489         self.0.as_raw_fd()
490     }
491 }
492
493 impl IntoRawFd for Socket {
494     fn into_raw_fd(self) -> RawFd {
495         self.0.into_raw_fd()
496     }
497 }
498
499 impl FromRawFd for Socket {
500     unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
501         Self(FromRawFd::from_raw_fd(raw_fd))
502     }
503 }
504
505 // In versions of glibc prior to 2.26, there's a bug where the DNS resolver
506 // will cache the contents of /etc/resolv.conf, so changes to that file on disk
507 // can be ignored by a long-running program. That can break DNS lookups on e.g.
508 // laptops where the network comes and goes. See
509 // https://sourceware.org/bugzilla/show_bug.cgi?id=984. Note however that some
510 // distros including Debian have patched glibc to fix this for a long time.
511 //
512 // A workaround for this bug is to call the res_init libc function, to clear
513 // the cached configs. Unfortunately, while we believe glibc's implementation
514 // of res_init is thread-safe, we know that other implementations are not
515 // (https://github.com/rust-lang/rust/issues/43592). Code here in libstd could
516 // try to synchronize its res_init calls with a Mutex, but that wouldn't
517 // protect programs that call into libc in other ways. So instead of calling
518 // res_init unconditionally, we call it only when we detect we're linking
519 // against glibc version < 2.26. (That is, when we both know its needed and
520 // believe it's thread-safe).
521 #[cfg(all(target_os = "linux", target_env = "gnu"))]
522 fn on_resolver_failure() {
523     use crate::sys;
524
525     // If the version fails to parse, we treat it the same as "not glibc".
526     if let Some(version) = sys::os::glibc_version() {
527         if version < (2, 26) {
528             unsafe { libc::res_init() };
529         }
530     }
531 }
532
533 #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
534 fn on_resolver_failure() {}