1use libc::{MSG_PEEK, c_int, c_void, size_t, sockaddr, socklen_t};
2
3use crate::ffi::CStr;
4use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut};
5use crate::net::{Shutdown, SocketAddr};
6use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd};
7use crate::sys::fd::FileDesc;
8use crate::sys::net::{getsockopt, setsockopt};
9use crate::sys::pal::IsMinusOne;
10use crate::sys_common::{AsInner, FromInner, IntoInner};
11use crate::time::{Duration, Instant};
12use crate::{cmp, mem};
13
14cfg_if::cfg_if! {
15 if #[cfg(target_vendor = "apple")] {
16 use libc::SO_LINGER_SEC as SO_LINGER;
17 } else {
18 use libc::SO_LINGER;
19 }
20}
21
22pub(super) use libc as netc;
23
24use super::{socket_addr_from_c, socket_addr_to_c};
25pub use crate::sys::{cvt, cvt_r};
26
27#[expect(non_camel_case_types)]
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<()> {
35 if err == 0 {
36 return Ok(());
37 }
38
39 on_resolver_failure();
41
42 #[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
43 if err == libc::EAI_SYSTEM {
44 return Err(io::Error::last_os_error());
45 }
46
47 #[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
48 let detail = unsafe {
49 CStr::from_ptr(libc::gai_strerror(err)).to_string_lossy()
52 };
53
54 #[cfg(any(target_os = "espidf", target_os = "nuttx"))]
55 let detail = "";
56
57 Err(io::Error::new(
58 io::ErrorKind::Uncategorized,
59 &format!("failed to lookup address information: {detail}")[..],
60 ))
61}
62
63impl Socket {
64 pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
65 let fam = match *addr {
66 SocketAddr::V4(..) => libc::AF_INET,
67 SocketAddr::V6(..) => libc::AF_INET6,
68 };
69 Socket::new_raw(fam, ty)
70 }
71
72 pub fn new_raw(fam: c_int, ty: c_int) -> io::Result<Socket> {
73 unsafe {
74 cfg_if::cfg_if! {
75 if #[cfg(any(
76 target_os = "android",
77 target_os = "dragonfly",
78 target_os = "freebsd",
79 target_os = "illumos",
80 target_os = "hurd",
81 target_os = "linux",
82 target_os = "netbsd",
83 target_os = "openbsd",
84 target_os = "nto",
85 target_os = "solaris",
86 ))] {
87 let fd = cvt(libc::socket(fam, ty | libc::SOCK_CLOEXEC, 0))?;
91 let socket = Socket(FileDesc::from_raw_fd(fd));
92
93 #[cfg(any(target_os = "freebsd", target_os = "netbsd", target_os = "dragonfly"))]
96 setsockopt(&socket, libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1)?;
97
98 Ok(socket)
99 } else {
100 let fd = cvt(libc::socket(fam, ty, 0))?;
101 let fd = FileDesc::from_raw_fd(fd);
102 fd.set_cloexec()?;
103 let socket = Socket(fd);
104
105 #[cfg(target_vendor = "apple")]
108 setsockopt(&socket, libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1)?;
109
110 Ok(socket)
111 }
112 }
113 }
114 }
115
116 #[cfg(not(target_os = "vxworks"))]
117 pub fn new_pair(fam: c_int, ty: c_int) -> io::Result<(Socket, Socket)> {
118 unsafe {
119 let mut fds = [0, 0];
120
121 cfg_if::cfg_if! {
122 if #[cfg(any(
123 target_os = "android",
124 target_os = "dragonfly",
125 target_os = "freebsd",
126 target_os = "illumos",
127 target_os = "linux",
128 target_os = "hurd",
129 target_os = "netbsd",
130 target_os = "openbsd",
131 target_os = "nto",
132 ))] {
133 cvt(libc::socketpair(fam, ty | libc::SOCK_CLOEXEC, 0, fds.as_mut_ptr()))?;
135 Ok((Socket(FileDesc::from_raw_fd(fds[0])), Socket(FileDesc::from_raw_fd(fds[1]))))
136 } else {
137 cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?;
138 let a = FileDesc::from_raw_fd(fds[0]);
139 let b = FileDesc::from_raw_fd(fds[1]);
140 a.set_cloexec()?;
141 b.set_cloexec()?;
142 Ok((Socket(a), Socket(b)))
143 }
144 }
145 }
146 }
147
148 #[cfg(target_os = "vxworks")]
149 pub fn new_pair(_fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> {
150 unimplemented!()
151 }
152
153 pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> {
154 let (addr, len) = socket_addr_to_c(addr);
155 loop {
156 let result = unsafe { libc::connect(self.as_raw_fd(), addr.as_ptr(), len) };
157 if result.is_minus_one() {
158 let err = crate::sys::os::errno();
159 match err {
160 libc::EINTR => continue,
161 libc::EISCONN => return Ok(()),
162 _ => return Err(io::Error::from_raw_os_error(err)),
163 }
164 }
165 return Ok(());
166 }
167 }
168
169 pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
170 self.set_nonblocking(true)?;
171 let r = unsafe {
172 let (addr, len) = socket_addr_to_c(addr);
173 cvt(libc::connect(self.as_raw_fd(), addr.as_ptr(), len))
174 };
175 self.set_nonblocking(false)?;
176
177 match r {
178 Ok(_) => return Ok(()),
179 Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {}
181 Err(e) => return Err(e),
182 }
183
184 let mut pollfd = libc::pollfd { fd: self.as_raw_fd(), events: libc::POLLOUT, revents: 0 };
185
186 if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
187 return Err(io::Error::ZERO_TIMEOUT);
188 }
189
190 let start = Instant::now();
191
192 loop {
193 let elapsed = start.elapsed();
194 if elapsed >= timeout {
195 return Err(io::const_error!(io::ErrorKind::TimedOut, "connection timed out"));
196 }
197
198 let timeout = timeout - elapsed;
199 let mut timeout = timeout
200 .as_secs()
201 .saturating_mul(1_000)
202 .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
203 if timeout == 0 {
204 timeout = 1;
205 }
206
207 let timeout = cmp::min(timeout, c_int::MAX as u64) as c_int;
208
209 match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
210 -1 => {
211 let err = io::Error::last_os_error();
212 if !err.is_interrupted() {
213 return Err(err);
214 }
215 }
216 0 => {}
217 _ => {
218 if cfg!(target_os = "vxworks") {
219 if let Some(e) = self.take_error()? {
223 return Err(e);
224 }
225 } else {
226 if pollfd.revents & (libc::POLLHUP | libc::POLLERR) != 0 {
229 let e = self.take_error()?.unwrap_or_else(|| {
230 io::const_error!(
231 io::ErrorKind::Uncategorized,
232 "no error set after POLLHUP",
233 )
234 });
235 return Err(e);
236 }
237 }
238
239 return Ok(());
240 }
241 }
242 }
243 }
244
245 pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) -> io::Result<Socket> {
246 cfg_if::cfg_if! {
251 if #[cfg(any(
252 target_os = "android",
253 target_os = "dragonfly",
254 target_os = "freebsd",
255 target_os = "illumos",
256 target_os = "linux",
257 target_os = "hurd",
258 target_os = "netbsd",
259 target_os = "openbsd",
260 ))] {
261 unsafe {
262 let fd = cvt_r(|| libc::accept4(self.as_raw_fd(), storage, len, libc::SOCK_CLOEXEC))?;
263 Ok(Socket(FileDesc::from_raw_fd(fd)))
264 }
265 } else {
266 unsafe {
267 let fd = cvt_r(|| libc::accept(self.as_raw_fd(), storage, len))?;
268 let fd = FileDesc::from_raw_fd(fd);
269 fd.set_cloexec()?;
270 Ok(Socket(fd))
271 }
272 }
273 }
274 }
275
276 pub fn duplicate(&self) -> io::Result<Socket> {
277 self.0.duplicate().map(Socket)
278 }
279
280 fn recv_with_flags(&self, mut buf: BorrowedCursor<'_>, flags: c_int) -> io::Result<()> {
281 let ret = cvt(unsafe {
282 libc::recv(
283 self.as_raw_fd(),
284 buf.as_mut().as_mut_ptr() as *mut c_void,
285 buf.capacity(),
286 flags,
287 )
288 })?;
289 unsafe {
290 buf.advance_unchecked(ret as usize);
291 }
292 Ok(())
293 }
294
295 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
296 let mut buf = BorrowedBuf::from(buf);
297 self.recv_with_flags(buf.unfilled(), 0)?;
298 Ok(buf.len())
299 }
300
301 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
302 let mut buf = BorrowedBuf::from(buf);
303 self.recv_with_flags(buf.unfilled(), MSG_PEEK)?;
304 Ok(buf.len())
305 }
306
307 pub fn read_buf(&self, buf: BorrowedCursor<'_>) -> io::Result<()> {
308 self.recv_with_flags(buf, 0)
309 }
310
311 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
312 self.0.read_vectored(bufs)
313 }
314
315 #[inline]
316 pub fn is_read_vectored(&self) -> bool {
317 self.0.is_read_vectored()
318 }
319
320 fn recv_from_with_flags(
321 &self,
322 buf: &mut [u8],
323 flags: c_int,
324 ) -> io::Result<(usize, SocketAddr)> {
325 let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
326 let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t;
327
328 let n = cvt(unsafe {
329 libc::recvfrom(
330 self.as_raw_fd(),
331 buf.as_mut_ptr() as *mut c_void,
332 buf.len(),
333 flags,
334 (&raw mut storage) as *mut _,
335 &mut addrlen,
336 )
337 })?;
338 Ok((n as usize, unsafe { socket_addr_from_c(&storage, addrlen as usize)? }))
339 }
340
341 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
342 self.recv_from_with_flags(buf, 0)
343 }
344
345 #[cfg(any(target_os = "android", target_os = "linux"))]
346 pub fn recv_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
347 let n = cvt(unsafe { libc::recvmsg(self.as_raw_fd(), msg, libc::MSG_CMSG_CLOEXEC) })?;
348 Ok(n as usize)
349 }
350
351 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
352 self.recv_from_with_flags(buf, MSG_PEEK)
353 }
354
355 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
356 self.0.write(buf)
357 }
358
359 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
360 self.0.write_vectored(bufs)
361 }
362
363 #[inline]
364 pub fn is_write_vectored(&self) -> bool {
365 self.0.is_write_vectored()
366 }
367
368 #[cfg(any(target_os = "android", target_os = "linux"))]
369 pub fn send_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
370 let n = cvt(unsafe { libc::sendmsg(self.as_raw_fd(), msg, 0) })?;
371 Ok(n as usize)
372 }
373
374 pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
375 let timeout = match dur {
376 Some(dur) => {
377 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
378 return Err(io::Error::ZERO_TIMEOUT);
379 }
380
381 let secs = if dur.as_secs() > libc::time_t::MAX as u64 {
382 libc::time_t::MAX
383 } else {
384 dur.as_secs() as libc::time_t
385 };
386 let mut timeout = libc::timeval {
387 tv_sec: secs,
388 tv_usec: dur.subsec_micros() as libc::suseconds_t,
389 };
390 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
391 timeout.tv_usec = 1;
392 }
393 timeout
394 }
395 None => libc::timeval { tv_sec: 0, tv_usec: 0 },
396 };
397 setsockopt(self, libc::SOL_SOCKET, kind, timeout)
398 }
399
400 pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
401 let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
402 if raw.tv_sec == 0 && raw.tv_usec == 0 {
403 Ok(None)
404 } else {
405 let sec = raw.tv_sec as u64;
406 let nsec = (raw.tv_usec as u32) * 1000;
407 Ok(Some(Duration::new(sec, nsec)))
408 }
409 }
410
411 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
412 let how = match how {
413 Shutdown::Write => libc::SHUT_WR,
414 Shutdown::Read => libc::SHUT_RD,
415 Shutdown::Both => libc::SHUT_RDWR,
416 };
417 cvt(unsafe { libc::shutdown(self.as_raw_fd(), how) })?;
418 Ok(())
419 }
420
421 pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
422 let linger = libc::linger {
423 l_onoff: linger.is_some() as libc::c_int,
424 l_linger: linger.unwrap_or_default().as_secs() as libc::c_int,
425 };
426
427 setsockopt(self, libc::SOL_SOCKET, SO_LINGER, linger)
428 }
429
430 pub fn linger(&self) -> io::Result<Option<Duration>> {
431 let val: libc::linger = getsockopt(self, libc::SOL_SOCKET, SO_LINGER)?;
432
433 Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64)))
434 }
435
436 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
437 setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
438 }
439
440 pub fn nodelay(&self) -> io::Result<bool> {
441 let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
442 Ok(raw != 0)
443 }
444
445 #[cfg(any(target_os = "android", target_os = "linux",))]
446 pub fn set_quickack(&self, quickack: bool) -> io::Result<()> {
447 setsockopt(self, libc::IPPROTO_TCP, libc::TCP_QUICKACK, quickack as c_int)
448 }
449
450 #[cfg(any(target_os = "android", target_os = "linux",))]
451 pub fn quickack(&self) -> io::Result<bool> {
452 let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_QUICKACK)?;
453 Ok(raw != 0)
454 }
455
456 #[cfg(target_os = "linux")]
458 pub fn set_deferaccept(&self, accept: u32) -> io::Result<()> {
459 setsockopt(self, libc::IPPROTO_TCP, libc::TCP_DEFER_ACCEPT, accept as c_int)
460 }
461
462 #[cfg(target_os = "linux")]
463 pub fn deferaccept(&self) -> io::Result<u32> {
464 let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_DEFER_ACCEPT)?;
465 Ok(raw as u32)
466 }
467
468 #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
469 pub fn set_acceptfilter(&self, name: &CStr) -> io::Result<()> {
470 if !name.to_bytes().is_empty() {
471 const AF_NAME_MAX: usize = 16;
472 let mut buf = [0; AF_NAME_MAX];
473 for (src, dst) in name.to_bytes().iter().zip(&mut buf[..AF_NAME_MAX - 1]) {
474 *dst = *src as libc::c_char;
475 }
476 let mut arg: libc::accept_filter_arg = unsafe { mem::zeroed() };
477 arg.af_name = buf;
478 setsockopt(self, libc::SOL_SOCKET, libc::SO_ACCEPTFILTER, &mut arg)
479 } else {
480 setsockopt(
481 self,
482 libc::SOL_SOCKET,
483 libc::SO_ACCEPTFILTER,
484 core::ptr::null_mut() as *mut c_void,
485 )
486 }
487 }
488
489 #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
490 pub fn acceptfilter(&self) -> io::Result<&CStr> {
491 let arg: libc::accept_filter_arg =
492 getsockopt(self, libc::SOL_SOCKET, libc::SO_ACCEPTFILTER)?;
493 let s: &[u8] =
494 unsafe { core::slice::from_raw_parts(arg.af_name.as_ptr() as *const u8, 16) };
495 let name = CStr::from_bytes_with_nul(s).unwrap();
496 Ok(name)
497 }
498
499 #[cfg(any(target_os = "android", target_os = "linux",))]
500 pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
501 setsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED, passcred as libc::c_int)
502 }
503
504 #[cfg(any(target_os = "android", target_os = "linux",))]
505 pub fn passcred(&self) -> io::Result<bool> {
506 let passcred: libc::c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED)?;
507 Ok(passcred != 0)
508 }
509
510 #[cfg(target_os = "netbsd")]
511 pub fn set_local_creds(&self, local_creds: bool) -> io::Result<()> {
512 setsockopt(self, 0 as libc::c_int, libc::LOCAL_CREDS, local_creds as libc::c_int)
513 }
514
515 #[cfg(target_os = "netbsd")]
516 pub fn local_creds(&self) -> io::Result<bool> {
517 let local_creds: libc::c_int = getsockopt(self, 0 as libc::c_int, libc::LOCAL_CREDS)?;
518 Ok(local_creds != 0)
519 }
520
521 #[cfg(target_os = "freebsd")]
522 pub fn set_local_creds_persistent(&self, local_creds_persistent: bool) -> io::Result<()> {
523 setsockopt(
524 self,
525 libc::AF_LOCAL,
526 libc::LOCAL_CREDS_PERSISTENT,
527 local_creds_persistent as libc::c_int,
528 )
529 }
530
531 #[cfg(target_os = "freebsd")]
532 pub fn local_creds_persistent(&self) -> io::Result<bool> {
533 let local_creds_persistent: libc::c_int =
534 getsockopt(self, libc::AF_LOCAL, libc::LOCAL_CREDS_PERSISTENT)?;
535 Ok(local_creds_persistent != 0)
536 }
537
538 #[cfg(not(any(target_os = "solaris", target_os = "illumos", target_os = "vita")))]
539 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
540 let mut nonblocking = nonblocking as libc::c_int;
541 cvt(unsafe { libc::ioctl(self.as_raw_fd(), libc::FIONBIO, &mut nonblocking) }).map(drop)
542 }
543
544 #[cfg(target_os = "vita")]
545 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
546 let option = nonblocking as libc::c_int;
547 setsockopt(self, libc::SOL_SOCKET, libc::SO_NONBLOCK, option)
548 }
549
550 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
551 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
552 self.0.set_nonblocking(nonblocking)
555 }
556
557 #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
558 pub fn set_mark(&self, mark: u32) -> io::Result<()> {
559 #[cfg(target_os = "linux")]
560 let option = libc::SO_MARK;
561 #[cfg(target_os = "freebsd")]
562 let option = libc::SO_USER_COOKIE;
563 #[cfg(target_os = "openbsd")]
564 let option = libc::SO_RTABLE;
565 setsockopt(self, libc::SOL_SOCKET, option, mark as libc::c_int)
566 }
567
568 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
569 let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
570 if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
571 }
572
573 pub fn as_raw(&self) -> RawFd {
575 self.as_raw_fd()
576 }
577}
578
579impl AsInner<FileDesc> for Socket {
580 #[inline]
581 fn as_inner(&self) -> &FileDesc {
582 &self.0
583 }
584}
585
586impl IntoInner<FileDesc> for Socket {
587 fn into_inner(self) -> FileDesc {
588 self.0
589 }
590}
591
592impl FromInner<FileDesc> for Socket {
593 fn from_inner(file_desc: FileDesc) -> Self {
594 Self(file_desc)
595 }
596}
597
598impl AsFd for Socket {
599 fn as_fd(&self) -> BorrowedFd<'_> {
600 self.0.as_fd()
601 }
602}
603
604impl AsRawFd for Socket {
605 #[inline]
606 fn as_raw_fd(&self) -> RawFd {
607 self.0.as_raw_fd()
608 }
609}
610
611impl IntoRawFd for Socket {
612 fn into_raw_fd(self) -> RawFd {
613 self.0.into_raw_fd()
614 }
615}
616
617impl FromRawFd for Socket {
618 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
619 Self(FromRawFd::from_raw_fd(raw_fd))
620 }
621}
622
623#[cfg(all(target_os = "linux", target_env = "gnu"))]
640fn on_resolver_failure() {
641 use crate::sys;
642
643 if let Some(version) = sys::os::glibc_version() {
645 if version < (2, 26) {
646 unsafe { libc::res_init() };
647 }
648 }
649}
650
651#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
652fn on_resolver_failure() {}