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: mem::MaybeUninit<libc::sockaddr_storage> = mem::MaybeUninit::uninit();
329 let mut addrlen = size_of_val(&storage) as libc::socklen_t;
330
331 let n = cvt(unsafe {
332 libc::recvfrom(
333 self.as_raw_fd(),
334 buf.as_mut_ptr() as *mut c_void,
335 buf.len(),
336 flags,
337 (&raw mut storage) as *mut _,
338 &mut addrlen,
339 )
340 })?;
341 Ok((n as usize, unsafe { socket_addr_from_c(storage.as_ptr(), addrlen as usize)? }))
342 }
343
344 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
345 self.recv_from_with_flags(buf, 0)
346 }
347
348 #[cfg(any(target_os = "android", target_os = "linux"))]
349 pub fn recv_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
350 let n = cvt(unsafe { libc::recvmsg(self.as_raw_fd(), msg, libc::MSG_CMSG_CLOEXEC) })?;
351 Ok(n as usize)
352 }
353
354 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
355 self.recv_from_with_flags(buf, MSG_PEEK)
356 }
357
358 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
359 self.0.write(buf)
360 }
361
362 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
363 self.0.write_vectored(bufs)
364 }
365
366 #[inline]
367 pub fn is_write_vectored(&self) -> bool {
368 self.0.is_write_vectored()
369 }
370
371 #[cfg(any(target_os = "android", target_os = "linux"))]
372 pub fn send_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
373 let n = cvt(unsafe { libc::sendmsg(self.as_raw_fd(), msg, 0) })?;
374 Ok(n as usize)
375 }
376
377 pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
378 let timeout = match dur {
379 Some(dur) => {
380 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
381 return Err(io::Error::ZERO_TIMEOUT);
382 }
383
384 let secs = if dur.as_secs() > libc::time_t::MAX as u64 {
385 libc::time_t::MAX
386 } else {
387 dur.as_secs() as libc::time_t
388 };
389 let mut timeout = libc::timeval {
390 tv_sec: secs,
391 tv_usec: dur.subsec_micros() as libc::suseconds_t,
392 };
393 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
394 timeout.tv_usec = 1;
395 }
396 timeout
397 }
398 None => libc::timeval { tv_sec: 0, tv_usec: 0 },
399 };
400 setsockopt(self, libc::SOL_SOCKET, kind, timeout)
401 }
402
403 pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
404 let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
405 if raw.tv_sec == 0 && raw.tv_usec == 0 {
406 Ok(None)
407 } else {
408 let sec = raw.tv_sec as u64;
409 let nsec = (raw.tv_usec as u32) * 1000;
410 Ok(Some(Duration::new(sec, nsec)))
411 }
412 }
413
414 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
415 let how = match how {
416 Shutdown::Write => libc::SHUT_WR,
417 Shutdown::Read => libc::SHUT_RD,
418 Shutdown::Both => libc::SHUT_RDWR,
419 };
420 cvt(unsafe { libc::shutdown(self.as_raw_fd(), how) })?;
421 Ok(())
422 }
423
424 pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
425 let linger = libc::linger {
426 l_onoff: linger.is_some() as libc::c_int,
427 l_linger: linger.unwrap_or_default().as_secs() as libc::c_int,
428 };
429
430 setsockopt(self, libc::SOL_SOCKET, SO_LINGER, linger)
431 }
432
433 pub fn linger(&self) -> io::Result<Option<Duration>> {
434 let val: libc::linger = getsockopt(self, libc::SOL_SOCKET, SO_LINGER)?;
435
436 Ok((val.l_onoff != 0).then(|| Duration::from_secs(val.l_linger as u64)))
437 }
438
439 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
440 setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
441 }
442
443 pub fn nodelay(&self) -> io::Result<bool> {
444 let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
445 Ok(raw != 0)
446 }
447
448 #[cfg(any(target_os = "android", target_os = "linux",))]
449 pub fn set_quickack(&self, quickack: bool) -> io::Result<()> {
450 setsockopt(self, libc::IPPROTO_TCP, libc::TCP_QUICKACK, quickack as c_int)
451 }
452
453 #[cfg(any(target_os = "android", target_os = "linux",))]
454 pub fn quickack(&self) -> io::Result<bool> {
455 let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_QUICKACK)?;
456 Ok(raw != 0)
457 }
458
459 #[cfg(target_os = "linux")]
461 pub fn set_deferaccept(&self, accept: u32) -> io::Result<()> {
462 setsockopt(self, libc::IPPROTO_TCP, libc::TCP_DEFER_ACCEPT, accept as c_int)
463 }
464
465 #[cfg(target_os = "linux")]
466 pub fn deferaccept(&self) -> io::Result<u32> {
467 let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_DEFER_ACCEPT)?;
468 Ok(raw as u32)
469 }
470
471 #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
472 pub fn set_acceptfilter(&self, name: &CStr) -> io::Result<()> {
473 if !name.to_bytes().is_empty() {
474 const AF_NAME_MAX: usize = 16;
475 let mut buf = [0; AF_NAME_MAX];
476 for (src, dst) in name.to_bytes().iter().zip(&mut buf[..AF_NAME_MAX - 1]) {
477 *dst = *src as libc::c_char;
478 }
479 let mut arg: libc::accept_filter_arg = unsafe { mem::zeroed() };
480 arg.af_name = buf;
481 setsockopt(self, libc::SOL_SOCKET, libc::SO_ACCEPTFILTER, &mut arg)
482 } else {
483 setsockopt(
484 self,
485 libc::SOL_SOCKET,
486 libc::SO_ACCEPTFILTER,
487 core::ptr::null_mut() as *mut c_void,
488 )
489 }
490 }
491
492 #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
493 pub fn acceptfilter(&self) -> io::Result<&CStr> {
494 let arg: libc::accept_filter_arg =
495 getsockopt(self, libc::SOL_SOCKET, libc::SO_ACCEPTFILTER)?;
496 let s: &[u8] =
497 unsafe { core::slice::from_raw_parts(arg.af_name.as_ptr() as *const u8, 16) };
498 let name = CStr::from_bytes_with_nul(s).unwrap();
499 Ok(name)
500 }
501
502 #[cfg(any(target_os = "android", target_os = "linux",))]
503 pub fn set_passcred(&self, passcred: bool) -> io::Result<()> {
504 setsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED, passcred as libc::c_int)
505 }
506
507 #[cfg(any(target_os = "android", target_os = "linux",))]
508 pub fn passcred(&self) -> io::Result<bool> {
509 let passcred: libc::c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_PASSCRED)?;
510 Ok(passcred != 0)
511 }
512
513 #[cfg(target_os = "netbsd")]
514 pub fn set_local_creds(&self, local_creds: bool) -> io::Result<()> {
515 setsockopt(self, 0 as libc::c_int, libc::LOCAL_CREDS, local_creds as libc::c_int)
516 }
517
518 #[cfg(target_os = "netbsd")]
519 pub fn local_creds(&self) -> io::Result<bool> {
520 let local_creds: libc::c_int = getsockopt(self, 0 as libc::c_int, libc::LOCAL_CREDS)?;
521 Ok(local_creds != 0)
522 }
523
524 #[cfg(target_os = "freebsd")]
525 pub fn set_local_creds_persistent(&self, local_creds_persistent: bool) -> io::Result<()> {
526 setsockopt(
527 self,
528 libc::AF_LOCAL,
529 libc::LOCAL_CREDS_PERSISTENT,
530 local_creds_persistent as libc::c_int,
531 )
532 }
533
534 #[cfg(target_os = "freebsd")]
535 pub fn local_creds_persistent(&self) -> io::Result<bool> {
536 let local_creds_persistent: libc::c_int =
537 getsockopt(self, libc::AF_LOCAL, libc::LOCAL_CREDS_PERSISTENT)?;
538 Ok(local_creds_persistent != 0)
539 }
540
541 #[cfg(not(any(target_os = "solaris", target_os = "illumos", target_os = "vita")))]
542 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
543 let mut nonblocking = nonblocking as libc::c_int;
544 cvt(unsafe { libc::ioctl(self.as_raw_fd(), libc::FIONBIO, &mut nonblocking) }).map(drop)
545 }
546
547 #[cfg(target_os = "vita")]
548 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
549 let option = nonblocking as libc::c_int;
550 setsockopt(self, libc::SOL_SOCKET, libc::SO_NONBLOCK, option)
551 }
552
553 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
554 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
555 self.0.set_nonblocking(nonblocking)
558 }
559
560 #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
561 pub fn set_mark(&self, mark: u32) -> io::Result<()> {
562 #[cfg(target_os = "linux")]
563 let option = libc::SO_MARK;
564 #[cfg(target_os = "freebsd")]
565 let option = libc::SO_USER_COOKIE;
566 #[cfg(target_os = "openbsd")]
567 let option = libc::SO_RTABLE;
568 setsockopt(self, libc::SOL_SOCKET, option, mark as libc::c_int)
569 }
570
571 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
572 let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
573 if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
574 }
575
576 pub fn as_raw(&self) -> RawFd {
578 self.as_raw_fd()
579 }
580}
581
582impl AsInner<FileDesc> for Socket {
583 #[inline]
584 fn as_inner(&self) -> &FileDesc {
585 &self.0
586 }
587}
588
589impl IntoInner<FileDesc> for Socket {
590 fn into_inner(self) -> FileDesc {
591 self.0
592 }
593}
594
595impl FromInner<FileDesc> for Socket {
596 fn from_inner(file_desc: FileDesc) -> Self {
597 Self(file_desc)
598 }
599}
600
601impl AsFd for Socket {
602 fn as_fd(&self) -> BorrowedFd<'_> {
603 self.0.as_fd()
604 }
605}
606
607impl AsRawFd for Socket {
608 #[inline]
609 fn as_raw_fd(&self) -> RawFd {
610 self.0.as_raw_fd()
611 }
612}
613
614impl IntoRawFd for Socket {
615 fn into_raw_fd(self) -> RawFd {
616 self.0.into_raw_fd()
617 }
618}
619
620impl FromRawFd for Socket {
621 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
622 Self(FromRawFd::from_raw_fd(raw_fd))
623 }
624}
625
626#[cfg(all(target_os = "linux", target_env = "gnu"))]
643fn on_resolver_failure() {
644 use crate::sys;
645
646 if let Some(version) = sys::os::glibc_version() {
648 if version < (2, 26) {
649 unsafe { libc::res_init() };
650 }
651 }
652}
653
654#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
655fn on_resolver_failure() {}