]> git.proxmox.com Git - rustc.git/blame - library/std/src/sys/unix/net.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / library / std / src / sys / unix / net.rs
CommitLineData
60c5eb7d 1use crate::cmp;
532ac7d7 2use crate::ffi::CStr;
48663c56 3use crate::io::{self, IoSlice, IoSliceMut};
532ac7d7 4use crate::mem;
60c5eb7d 5use crate::net::{Shutdown, SocketAddr};
94222f64 6use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd};
532ac7d7
XL
7use crate::str;
8use crate::sys::fd::FileDesc;
532ac7d7 9use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr};
60c5eb7d 10use crate::sys_common::{AsInner, FromInner, IntoInner};
532ac7d7 11use crate::time::{Duration, Instant};
532ac7d7 12
94222f64
XL
13use libc::{c_int, c_void, size_t, sockaddr, socklen_t, MSG_PEEK};
14
15cfg_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}
532ac7d7
XL
22
23pub use crate::sys::{cvt, cvt_r};
24
25#[allow(unused_extern_crates)]
7453a54e 26pub extern crate libc as netc;
85aaf69f
SL
27
28pub type wrlen_t = size_t;
29
30pub struct Socket(FileDesc);
31
32pub fn init() {}
33
34pub fn cvt_gai(err: c_int) -> io::Result<()> {
9e0c209e 35 if err == 0 {
60c5eb7d 36 return Ok(());
9e0c209e 37 }
2c00a5a8
XL
38
39 // We may need to trigger a glibc workaround. See on_resolver_failure() for details.
40 on_resolver_failure();
41
94222f64
XL
42 #[cfg(not(target_os = "espidf"))]
43 if err == libc::EAI_SYSTEM {
60c5eb7d 44 return Err(io::Error::last_os_error());
9e0c209e 45 }
85aaf69f 46
94222f64 47 #[cfg(not(target_os = "espidf"))]
85aaf69f 48 let detail = unsafe {
60c5eb7d 49 str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap().to_owned()
85aaf69f 50 };
94222f64
XL
51
52 #[cfg(target_os = "espidf")]
53 let detail = "";
54
60c5eb7d 55 Err(io::Error::new(
136023e0 56 io::ErrorKind::Uncategorized,
5e7ed085 57 &format!("failed to lookup address information: {detail}")[..],
60c5eb7d 58 ))
85aaf69f
SL
59}
60
61impl Socket {
62 pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
c34b1796
AL
63 let fam = match *addr {
64 SocketAddr::V4(..) => libc::AF_INET,
65 SocketAddr::V6(..) => libc::AF_INET6,
85aaf69f 66 };
54a0048b
SL
67 Socket::new_raw(fam, ty)
68 }
69
70 pub fn new_raw(fam: c_int, ty: c_int) -> io::Result<Socket> {
85aaf69f 71 unsafe {
3dfed10e 72 cfg_if::cfg_if! {
29967ef6
XL
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",
17df50a5 80 target_os = "openbsd",
29967ef6
XL
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.
3dfed10e 85 let fd = cvt(libc::socket(fam, ty | libc::SOCK_CLOEXEC, 0))?;
94222f64 86 Ok(Socket(FileDesc::from_raw_fd(fd)))
3dfed10e
XL
87 } else {
88 let fd = cvt(libc::socket(fam, ty, 0))?;
94222f64 89 let fd = FileDesc::from_raw_fd(fd);
3dfed10e
XL
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)
7453a54e
SL
99 }
100 }
85aaf69f
SL
101 }
102 }
103
29967ef6 104 #[cfg(not(target_os = "vxworks"))]
54a0048b
SL
105 pub fn new_pair(fam: c_int, ty: c_int) -> io::Result<(Socket, Socket)> {
106 unsafe {
107 let mut fds = [0, 0];
108
3dfed10e 109 cfg_if::cfg_if! {
29967ef6
XL
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",
17df50a5 117 target_os = "openbsd",
29967ef6 118 ))] {
3dfed10e
XL
119 // Like above, set cloexec atomically
120 cvt(libc::socketpair(fam, ty | libc::SOCK_CLOEXEC, 0, fds.as_mut_ptr()))?;
94222f64 121 Ok((Socket(FileDesc::from_raw_fd(fds[0])), Socket(FileDesc::from_raw_fd(fds[1]))))
3dfed10e
XL
122 } else {
123 cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?;
94222f64
XL
124 let a = FileDesc::from_raw_fd(fds[0]);
125 let b = FileDesc::from_raw_fd(fds[1]);
3dfed10e
XL
126 a.set_cloexec()?;
127 b.set_cloexec()?;
128 Ok((Socket(a), Socket(b)))
54a0048b
SL
129 }
130 }
54a0048b
SL
131 }
132 }
133
29967ef6
XL
134 #[cfg(target_os = "vxworks")]
135 pub fn new_pair(_fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> {
136 unimplemented!()
137 }
138
041b39d2
XL
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();
94222f64 143 cvt(libc::connect(self.as_raw_fd(), addrp, len))
041b39d2
XL
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
94222f64 154 let mut pollfd = libc::pollfd { fd: self.as_raw_fd(), events: libc::POLLOUT, revents: 0 };
041b39d2
XL
155
156 if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
5099ac24 157 return Err(io::const_io_error!(
60c5eb7d 158 io::ErrorKind::InvalidInput,
5099ac24 159 "cannot set a 0 duration timeout",
60c5eb7d 160 ));
041b39d2
XL
161 }
162
163 let start = Instant::now();
164
165 loop {
166 let elapsed = start.elapsed();
167 if elapsed >= timeout {
5099ac24 168 return Err(io::const_io_error!(io::ErrorKind::TimedOut, "connection timed out"));
041b39d2
XL
169 }
170
171 let timeout = timeout - elapsed;
60c5eb7d
XL
172 let mut timeout = timeout
173 .as_secs()
041b39d2
XL
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
f035d41b 180 let timeout = cmp::min(timeout, c_int::MAX as u64) as c_int;
041b39d2
XL
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 _ => {
abe05a73
XL
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 {
60c5eb7d 194 let e = self.take_error()?.unwrap_or_else(|| {
5099ac24 195 io::const_io_error!(
136023e0 196 io::ErrorKind::Uncategorized,
5099ac24 197 "no error set after POLLHUP",
cdc7bbd5 198 )
60c5eb7d 199 });
abe05a73 200 return Err(e);
041b39d2 201 }
abe05a73 202
041b39d2
XL
203 return Ok(());
204 }
205 }
206 }
207 }
208
60c5eb7d 209 pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) -> io::Result<Socket> {
7453a54e
SL
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
29967ef6
XL
212 // platforms that support it. On Linux, this was added in 2.6.28,
213 // glibc 2.10 and musl 0.9.5.
3dfed10e 214 cfg_if::cfg_if! {
29967ef6 215 if #[cfg(any(
6a06907d 216 target_os = "android",
29967ef6
XL
217 target_os = "dragonfly",
218 target_os = "freebsd",
219 target_os = "illumos",
220 target_os = "linux",
221 target_os = "netbsd",
17df50a5 222 target_os = "openbsd",
29967ef6 223 ))] {
94222f64
XL
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 }
3dfed10e 228 } else {
94222f64
XL
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 }
7453a54e
SL
235 }
236 }
85aaf69f
SL
237 }
238
239 pub fn duplicate(&self) -> io::Result<Socket> {
7453a54e 240 self.0.duplicate().map(Socket)
85aaf69f
SL
241 }
242
8bb4bdeb
XL
243 fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
244 let ret = cvt(unsafe {
94222f64 245 libc::recv(self.as_raw_fd(), buf.as_mut_ptr() as *mut c_void, buf.len(), flags)
8bb4bdeb
XL
246 })?;
247 Ok(ret as usize)
248 }
249
85aaf69f 250 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
8bb4bdeb
XL
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
48663c56 258 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
9fa01778
XL
259 self.0.read_vectored(bufs)
260 }
261
f9f354fc
XL
262 #[inline]
263 pub fn is_read_vectored(&self) -> bool {
264 self.0.is_read_vectored()
265 }
266
60c5eb7d
XL
267 fn recv_from_with_flags(
268 &self,
269 buf: &mut [u8],
270 flags: c_int,
271 ) -> io::Result<(usize, SocketAddr)> {
8bb4bdeb
XL
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 {
60c5eb7d 276 libc::recvfrom(
94222f64 277 self.as_raw_fd(),
60c5eb7d
XL
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 )
8bb4bdeb
XL
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
923072b8 292 #[cfg(any(target_os = "android", target_os = "linux"))]
fc512014 293 pub fn recv_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
94222f64 294 let n = cvt(unsafe { libc::recvmsg(self.as_raw_fd(), msg, libc::MSG_CMSG_CLOEXEC) })?;
fc512014
XL
295 Ok(n as usize)
296 }
297
8bb4bdeb
XL
298 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
299 self.recv_from_with_flags(buf, MSG_PEEK)
85aaf69f 300 }
62682a34 301
54a0048b
SL
302 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
303 self.0.write(buf)
304 }
305
48663c56 306 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
9fa01778
XL
307 self.0.write_vectored(bufs)
308 }
309
f9f354fc
XL
310 #[inline]
311 pub fn is_write_vectored(&self) -> bool {
312 self.0.is_write_vectored()
313 }
314
923072b8 315 #[cfg(any(target_os = "android", target_os = "linux"))]
fc512014 316 pub fn send_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
94222f64 317 let n = cvt(unsafe { libc::sendmsg(self.as_raw_fd(), msg, 0) })?;
fc512014
XL
318 Ok(n as usize)
319 }
320
62682a34
SL
321 pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
322 let timeout = match dur {
323 Some(dur) => {
c1a9b12d 324 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
5099ac24 325 return Err(io::const_io_error!(
60c5eb7d 326 io::ErrorKind::InvalidInput,
5099ac24 327 "cannot set a 0 duration timeout",
60c5eb7d 328 ));
62682a34
SL
329 }
330
f035d41b
XL
331 let secs = if dur.as_secs() > libc::time_t::MAX as u64 {
332 libc::time_t::MAX
62682a34 333 } else {
c1a9b12d 334 dur.as_secs() as libc::time_t
62682a34
SL
335 };
336 let mut timeout = libc::timeval {
337 tv_sec: secs,
74b04a01 338 tv_usec: dur.subsec_micros() as libc::suseconds_t,
62682a34
SL
339 };
340 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
341 timeout.tv_usec = 1;
342 }
343 timeout
344 }
60c5eb7d 345 None => libc::timeval { tv_sec: 0, tv_usec: 0 },
62682a34
SL
346 };
347 setsockopt(self, libc::SOL_SOCKET, kind, timeout)
348 }
349
350 pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
54a0048b 351 let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
62682a34
SL
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 }
92a42be0
SL
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 };
94222f64 367 cvt(unsafe { libc::shutdown(self.as_raw_fd(), how) })?;
92a42be0
SL
368 Ok(())
369 }
54a0048b 370
94222f64
XL
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
54a0048b
SL
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
fc512014
XL
395 #[cfg(any(target_os = "android", target_os = "linux",))]
396 pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
397 setsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED, passcred as libc::c_int)
398 }
399
400 #[cfg(any(target_os = "android", target_os = "linux",))]
401 pub fn passcred(&self) -> io::Result<bool> {
402 let passcred: libc::c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED)?;
403 Ok(passcred != 0)
404 }
405
04454e1e
FG
406 #[cfg(target_os = "netbsd")]
407 pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
408 setsockopt(self, 0 as libc::c_int, libc::LOCAL_CREDS, passcred as libc::c_int)
409 }
410
411 #[cfg(target_os = "netbsd")]
412 pub fn passcred(&self) -> io::Result<bool> {
413 let passcred: libc::c_int = getsockopt(self, 0 as libc::c_int, libc::LOCAL_CREDS)?;
414 Ok(passcred != 0)
415 }
416
ba9703b0 417 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
54a0048b 418 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
9e0c209e 419 let mut nonblocking = nonblocking as libc::c_int;
94222f64 420 cvt(unsafe { libc::ioctl(self.as_raw_fd(), libc::FIONBIO, &mut nonblocking) }).map(drop)
54a0048b
SL
421 }
422
ba9703b0
XL
423 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
424 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
425 // FIONBIO is inadequate for sockets on illumos/Solaris, so use the
426 // fcntl(F_[GS]ETFL)-based method provided by FileDesc instead.
427 self.0.set_nonblocking(nonblocking)
428 }
429
54a0048b
SL
430 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
431 let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
60c5eb7d 432 if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
54a0048b 433 }
94222f64
XL
434
435 // This is used by sys_common code to abstract over Windows and Unix.
436 pub fn as_raw(&self) -> RawFd {
437 self.as_raw_fd()
438 }
439}
440
441impl AsInner<FileDesc> for Socket {
442 fn as_inner(&self) -> &FileDesc {
443 &self.0
444 }
445}
446
447impl IntoInner<FileDesc> for Socket {
448 fn into_inner(self) -> FileDesc {
449 self.0
450 }
451}
452
453impl FromInner<FileDesc> for Socket {
454 fn from_inner(file_desc: FileDesc) -> Self {
455 Self(file_desc)
456 }
457}
458
459impl AsFd for Socket {
460 fn as_fd(&self) -> BorrowedFd<'_> {
461 self.0.as_fd()
462 }
85aaf69f
SL
463}
464
94222f64
XL
465impl AsRawFd for Socket {
466 fn as_raw_fd(&self) -> RawFd {
467 self.0.as_raw_fd()
60c5eb7d 468 }
85aaf69f 469}
c34b1796 470
94222f64
XL
471impl IntoRawFd for Socket {
472 fn into_raw_fd(self) -> RawFd {
473 self.0.into_raw_fd()
60c5eb7d 474 }
c34b1796 475}
c1a9b12d 476
94222f64
XL
477impl FromRawFd for Socket {
478 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
479 Self(FromRawFd::from_raw_fd(raw_fd))
60c5eb7d 480 }
c1a9b12d 481}
ea8adc8c
XL
482
483// In versions of glibc prior to 2.26, there's a bug where the DNS resolver
484// will cache the contents of /etc/resolv.conf, so changes to that file on disk
485// can be ignored by a long-running program. That can break DNS lookups on e.g.
486// laptops where the network comes and goes. See
487// https://sourceware.org/bugzilla/show_bug.cgi?id=984. Note however that some
488// distros including Debian have patched glibc to fix this for a long time.
489//
490// A workaround for this bug is to call the res_init libc function, to clear
491// the cached configs. Unfortunately, while we believe glibc's implementation
492// of res_init is thread-safe, we know that other implementations are not
493// (https://github.com/rust-lang/rust/issues/43592). Code here in libstd could
494// try to synchronize its res_init calls with a Mutex, but that wouldn't
495// protect programs that call into libc in other ways. So instead of calling
496// res_init unconditionally, we call it only when we detect we're linking
497// against glibc version < 2.26. (That is, when we both know its needed and
498// believe it's thread-safe).
a2a8927a 499#[cfg(all(target_os = "linux", target_env = "gnu"))]
2c00a5a8 500fn on_resolver_failure() {
532ac7d7 501 use crate::sys;
0531ce1d 502
ea8adc8c 503 // If the version fails to parse, we treat it the same as "not glibc".
0531ce1d
XL
504 if let Some(version) = sys::os::glibc_version() {
505 if version < (2, 26) {
506 unsafe { libc::res_init() };
ea8adc8c
XL
507 }
508 }
ea8adc8c
XL
509}
510
a2a8927a 511#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
2c00a5a8 512fn on_resolver_failure() {}