Skip to main content

libc_rs/
net.rs

1//! Socket, UNIX domain, and Virtio-Vsock syscall wrappers.
2
3use core::mem::size_of;
4
5use crate::errno::{EINVAL, ENAMETOOLONG, Errno, SysResult};
6use crate::fd::RawFd;
7use crate::raw::{nr, syscall2, syscall3, syscall4, syscall5, syscall6};
8
9/// Unspecified address family.
10pub const AF_UNSPEC: i32 = 0;
11/// Unix domain sockets address family.
12pub const AF_UNIX: i32 = 1;
13/// IPv4 Internet protocols address family.
14pub const AF_INET: i32 = 2;
15/// IPv6 Internet protocols address family.
16pub const AF_INET6: i32 = 10;
17/// Virtio vsock address family.
18pub const AF_VSOCK: i32 = 40;
19
20/// Dummy protocol for TCP / IP level.
21pub const IPPROTO_IP: i32 = 0;
22/// Internet Control Message Protocol.
23pub const IPPROTO_ICMP: i32 = 1;
24/// Transmission Control Protocol.
25pub const IPPROTO_TCP: i32 = 6;
26/// User Datagram Protocol.
27pub const IPPROTO_UDP: i32 = 17;
28/// IPv6 header protocol level.
29pub const IPPROTO_IPV6: i32 = 41;
30
31/// Sequenced, reliable, two-way connection-based byte streams.
32pub const SOCK_STREAM: i32 = 1;
33/// Connectionless, unreliable datagrams.
34pub const SOCK_DGRAM: i32 = 2;
35/// Set `O_NONBLOCK` on the new open file description.
36pub const SOCK_NONBLOCK: i32 = 0x800;
37/// Set close-on-exec (`FD_CLOEXEC`) on the new descriptor.
38pub const SOCK_CLOEXEC: i32 = 0x80000;
39
40/// Disable Nagle's algorithm (`IPPROTO_TCP`).
41pub const TCP_NODELAY: i32 = 1;
42/// Start keepalives after this period (`IPPROTO_TCP`).
43pub const TCP_KEEPIDLE: i32 = 4;
44/// Interval between keepalives (`IPPROTO_TCP`).
45pub const TCP_KEEPINTVL: i32 = 5;
46/// Number of keepalives before death (`IPPROTO_TCP`).
47pub const TCP_KEEPCNT: i32 = 6;
48
49/// Socket level for `getsockopt` / `setsockopt`.
50pub const SOL_SOCKET: i32 = 1;
51/// Allow reuse of local addresses.
52pub const SO_REUSEADDR: i32 = 2;
53/// Get and clear pending socket error.
54pub const SO_ERROR: i32 = 4;
55/// Send buffer size (`SOL_SOCKET`).
56pub const SO_SNDBUF: i32 = 7;
57/// Receive buffer size (`SOL_SOCKET`).
58pub const SO_RCVBUF: i32 = 8;
59/// Enable keep-alive messages on connection-oriented sockets.
60pub const SO_KEEPALIVE: i32 = 9;
61/// Allow multiple sockets to bind to the same port (`SOL_SOCKET`).
62pub const SO_REUSEPORT: i32 = 15;
63/// Receive timeout option.
64pub const SO_RCVTIMEO: i32 = 20;
65/// Send timeout option.
66pub const SO_SNDTIMEO: i32 = 21;
67
68/// Restrict `AF_INET6` socket to IPv6 communications only (`IPPROTO_IPV6`).
69pub const IPV6_V6ONLY: i32 = 26;
70
71/// Nonblocking I/O for a single send/recv call.
72pub const MSG_DONTWAIT: i32 = 0x40;
73/// Wait for full request or error.
74pub const MSG_WAITALL: i32 = 0x100;
75/// Do not generate `SIGPIPE` on peer close.
76pub const MSG_NOSIGNAL: i32 = 0x4000;
77
78/// Shut down the reading side of a socket.
79pub const SHUT_RD: i32 = 0;
80/// Shut down the writing side of a socket.
81pub const SHUT_WR: i32 = 1;
82/// Shut down both reading and writing sides of a socket.
83pub const SHUT_RDWR: i32 = 2;
84
85/// Wildcard vsock context ID.
86pub const VMADDR_CID_ANY: u32 = u32::MAX;
87/// Local loopback vsock context ID.
88pub const VMADDR_CID_LOCAL: u32 = 1;
89/// Host hypervisor vsock context ID.
90pub const VMADDR_CID_HOST: u32 = 2;
91
92/// Kernel `sockaddr_un` structure for UNIX domain sockets.
93#[repr(C)]
94#[derive(Clone, Copy, Debug)]
95pub struct SockAddrUn {
96    pub sun_family: u16,
97    pub sun_path: [u8; 108],
98}
99
100impl SockAddrUn {
101    /// Builds a NUL-terminated [`SockAddrUn`] and its effective `socklen_t` from `path`.
102    ///
103    /// Reserves 1 trailing NUL byte so `path.len() >= 108` fails with `ENAMETOOLONG`,
104    /// and rejects interior NUL bytes or empty paths with `EINVAL`.
105    pub fn from_path(path: &[u8]) -> SysResult<(Self, u32)> {
106        if path.is_empty() || path.contains(&0) {
107            return Err(Errno(EINVAL));
108        }
109        if path.len() >= 108 {
110            return Err(Errno(ENAMETOOLONG));
111        }
112        let mut addr = Self {
113            sun_family: AF_UNIX as u16,
114            sun_path: [0u8; 108],
115        };
116        addr.sun_path[..path.len()].copy_from_slice(path);
117        let addrlen = (size_of::<u16>() + path.len() + 1) as u32;
118        Ok((addr, addrlen))
119    }
120}
121
122/// Kernel `sockaddr_vm` structure for `AF_VSOCK` sockets.
123#[repr(C)]
124#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
125pub struct SockAddrVm {
126    pub svm_family: u16,
127    pub svm_reserved1: u16,
128    pub svm_port: u32,
129    pub svm_cid: u32,
130    pub svm_flags: u8,
131    pub svm_zero: [u8; 3],
132}
133
134impl SockAddrVm {
135    /// Constructs an `AF_VSOCK` socket address for `(cid, port)`.
136    #[must_use]
137    pub const fn new(cid: u32, port: u32) -> Self {
138        Self {
139            svm_family: AF_VSOCK as u16,
140            svm_reserved1: 0,
141            svm_port: port,
142            svm_cid: cid,
143            svm_flags: 0,
144            svm_zero: [0; 3],
145        }
146    }
147}
148
149/// IPv4 address (`struct in_addr`) in network byte order.
150#[repr(C)]
151#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
152pub struct InAddr {
153    pub s_addr: u32,
154}
155
156impl InAddr {
157    /// Constructs an [`InAddr`] from 4 octets in network byte order.
158    #[must_use]
159    pub const fn from_octets(octets: [u8; 4]) -> Self {
160        Self {
161            s_addr: u32::from_ne_bytes(octets),
162        }
163    }
164
165    /// Returns the 4 octets of this IPv4 address.
166    #[must_use]
167    pub const fn octets(self) -> [u8; 4] {
168        self.s_addr.to_ne_bytes()
169    }
170}
171
172/// Kernel `sockaddr_in` structure for `AF_INET` sockets.
173#[repr(C)]
174#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
175pub struct SockAddrIn {
176    pub sin_family: u16,
177    pub sin_port: u16,
178    pub sin_addr: InAddr,
179    pub sin_zero: [u8; 8],
180}
181
182impl SockAddrIn {
183    /// Constructs an `AF_INET` socket address for `(ip, port)` with `port` in host byte order.
184    #[must_use]
185    pub const fn new(ip: [u8; 4], port: u16) -> Self {
186        Self {
187            sin_family: AF_INET as u16,
188            sin_port: port.to_be(),
189            sin_addr: InAddr {
190                s_addr: u32::from_ne_bytes(ip),
191            },
192            sin_zero: [0; 8],
193        }
194    }
195
196    /// Returns the IPv4 octets.
197    #[must_use]
198    pub const fn ip(&self) -> [u8; 4] {
199        self.sin_addr.s_addr.to_ne_bytes()
200    }
201
202    /// Returns the port in host byte order.
203    #[must_use]
204    pub const fn port(&self) -> u16 {
205        u16::from_be(self.sin_port)
206    }
207}
208
209/// IPv6 address (`struct in6_addr`) in network byte order.
210#[repr(C)]
211#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
212pub struct In6Addr {
213    pub s6_addr: [u8; 16],
214}
215
216/// Kernel `sockaddr_in6` structure for `AF_INET6` sockets.
217#[repr(C)]
218#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
219pub struct SockAddrIn6 {
220    pub sin6_family: u16,
221    pub sin6_port: u16,
222    pub sin6_flowinfo: u32,
223    pub sin6_addr: In6Addr,
224    pub sin6_scope_id: u32,
225}
226
227impl SockAddrIn6 {
228    /// Constructs an `AF_INET6` socket address for `(ip, port, flowinfo, scope_id)` with `port` in host byte order.
229    #[must_use]
230    pub const fn new(ip: [u8; 16], port: u16, flowinfo: u32, scope_id: u32) -> Self {
231        Self {
232            sin6_family: AF_INET6 as u16,
233            sin6_port: port.to_be(),
234            sin6_flowinfo: flowinfo,
235            sin6_addr: In6Addr { s6_addr: ip },
236            sin6_scope_id: scope_id,
237        }
238    }
239
240    /// Returns the IPv6 octets.
241    #[must_use]
242    pub const fn ip(&self) -> [u8; 16] {
243        self.sin6_addr.s6_addr
244    }
245
246    /// Returns the port in host byte order.
247    #[must_use]
248    pub const fn port(&self) -> u16 {
249        u16::from_be(self.sin6_port)
250    }
251}
252
253/// Generic socket address storage (`struct sockaddr_storage`, 128 bytes).
254#[repr(C, align(8))]
255#[derive(Clone, Copy, Debug)]
256pub struct SockAddrStorage {
257    pub ss_family: u16,
258    pub ss_data: [u8; 126],
259}
260
261impl Default for SockAddrStorage {
262    fn default() -> Self {
263        Self {
264            ss_family: 0,
265            ss_data: [0u8; 126],
266        }
267    }
268}
269
270const _: () = {
271    assert!(size_of::<SockAddrVm>() == 16);
272    assert!(size_of::<InAddr>() == 4);
273    assert!(size_of::<SockAddrIn>() == 16);
274    assert!(size_of::<In6Addr>() == 16);
275    assert!(size_of::<SockAddrIn6>() == 28);
276    assert!(size_of::<SockAddrStorage>() == 128);
277};
278
279/// Creates an endpoint for communication and returns its file descriptor.
280pub fn socket(domain: i32, ty: i32, protocol: i32) -> SysResult<RawFd> {
281    // SAFETY: `SOCKET` takes three scalar integer arguments.
282    unsafe {
283        syscall3(nr::SOCKET, domain as usize, ty as usize, protocol as usize).map(|fd| fd as RawFd)
284    }
285}
286
287/// Creates an unnamed pair of connected sockets.
288pub fn socketpair(domain: i32, ty: i32, protocol: i32) -> SysResult<[RawFd; 2]> {
289    let mut sv = [0i32; 2];
290    // SAFETY: `sv` is a valid 2-element `i32` array on the stack.
291    unsafe {
292        syscall4(
293            nr::SOCKETPAIR,
294            domain as usize,
295            ty as usize,
296            protocol as usize,
297            sv.as_mut_ptr() as usize,
298        )?;
299    }
300    Ok(sv)
301}
302
303/// Binds `fd` to the raw socket address `[addr..addr + addrlen]`.
304///
305/// # Safety
306///
307/// `addr` must point to at least `addrlen` readable bytes containing a valid kernel `sockaddr`.
308pub unsafe fn bind_raw(fd: RawFd, addr: *const u8, addrlen: u32) -> SysResult<()> {
309    // SAFETY: Caller guarantees `addr` and `addrlen` describe a valid readable buffer.
310    unsafe {
311        syscall3(nr::BIND, fd as usize, addr as usize, addrlen as usize)?;
312    }
313    Ok(())
314}
315
316/// Binds an `AF_UNIX` socket `fd` to `path`.
317pub fn bind_unix(fd: RawFd, path: &[u8]) -> SysResult<()> {
318    let (addr, len) = SockAddrUn::from_path(path)?;
319    // SAFETY: `addr` is a stack `SockAddrUn` and `len <= size_of::<SockAddrUn>()`.
320    unsafe { bind_raw(fd, core::ptr::from_ref(&addr).cast::<u8>(), len) }
321}
322
323/// Binds an `AF_VSOCK` socket `fd` to `addr`.
324pub fn bind_vsock(fd: RawFd, addr: &SockAddrVm) -> SysResult<()> {
325    // SAFETY: `addr` is a valid `SockAddrVm` of size 16 bytes.
326    unsafe {
327        bind_raw(
328            fd,
329            core::ptr::from_ref(addr).cast::<u8>(),
330            size_of::<SockAddrVm>() as u32,
331        )
332    }
333}
334
335/// Binds an `AF_INET` socket `fd` to `addr`.
336pub fn bind_in(fd: RawFd, addr: &SockAddrIn) -> SysResult<()> {
337    // SAFETY: `addr` is a valid `SockAddrIn` of size 16 bytes.
338    unsafe {
339        bind_raw(
340            fd,
341            core::ptr::from_ref(addr).cast::<u8>(),
342            size_of::<SockAddrIn>() as u32,
343        )
344    }
345}
346
347/// Binds an `AF_INET6` socket `fd` to `addr`.
348pub fn bind_in6(fd: RawFd, addr: &SockAddrIn6) -> SysResult<()> {
349    // SAFETY: `addr` is a valid `SockAddrIn6` of size 28 bytes.
350    unsafe {
351        bind_raw(
352            fd,
353            core::ptr::from_ref(addr).cast::<u8>(),
354            size_of::<SockAddrIn6>() as u32,
355        )
356    }
357}
358
359/// Connects `fd` to the raw socket address `[addr..addr + addrlen]`.
360///
361/// # Safety
362///
363/// `addr` must point to at least `addrlen` readable bytes containing a valid kernel `sockaddr`.
364pub unsafe fn connect_raw(fd: RawFd, addr: *const u8, addrlen: u32) -> SysResult<()> {
365    // SAFETY: Caller guarantees `addr` and `addrlen` describe a valid readable buffer.
366    unsafe {
367        syscall3(nr::CONNECT, fd as usize, addr as usize, addrlen as usize)?;
368    }
369    Ok(())
370}
371
372/// Connects an `AF_UNIX` socket `fd` to `path`.
373pub fn connect_unix(fd: RawFd, path: &[u8]) -> SysResult<()> {
374    let (addr, len) = SockAddrUn::from_path(path)?;
375    // SAFETY: `addr` is a stack `SockAddrUn` and `len <= size_of::<SockAddrUn>()`.
376    unsafe { connect_raw(fd, core::ptr::from_ref(&addr).cast::<u8>(), len) }
377}
378
379/// Connects an `AF_VSOCK` socket `fd` to `addr`.
380pub fn connect_vsock(fd: RawFd, addr: &SockAddrVm) -> SysResult<()> {
381    // SAFETY: `addr` is a valid `SockAddrVm` of size 16 bytes.
382    unsafe {
383        connect_raw(
384            fd,
385            core::ptr::from_ref(addr).cast::<u8>(),
386            size_of::<SockAddrVm>() as u32,
387        )
388    }
389}
390
391/// Connects an `AF_INET` socket `fd` to `addr`.
392pub fn connect_in(fd: RawFd, addr: &SockAddrIn) -> SysResult<()> {
393    // SAFETY: `addr` is a valid `SockAddrIn` of size 16 bytes.
394    unsafe {
395        connect_raw(
396            fd,
397            core::ptr::from_ref(addr).cast::<u8>(),
398            size_of::<SockAddrIn>() as u32,
399        )
400    }
401}
402
403/// Connects an `AF_INET6` socket `fd` to `addr`.
404pub fn connect_in6(fd: RawFd, addr: &SockAddrIn6) -> SysResult<()> {
405    // SAFETY: `addr` is a valid `SockAddrIn6` of size 28 bytes.
406    unsafe {
407        connect_raw(
408            fd,
409            core::ptr::from_ref(addr).cast::<u8>(),
410            size_of::<SockAddrIn6>() as u32,
411        )
412    }
413}
414
415/// Marks `fd` as a passive socket with maximum pending connection queue `backlog`.
416pub fn listen(fd: RawFd, backlog: i32) -> SysResult<()> {
417    // SAFETY: `LISTEN` takes scalar descriptor and backlog arguments.
418    unsafe {
419        syscall2(nr::LISTEN, fd as usize, backlog as usize)?;
420    }
421    Ok(())
422}
423
424/// Accepts a connection on `fd` with `flags`, optionally writing the peer address into `addr`.
425///
426/// # Safety
427///
428/// Either `addr` and `addrlen` must both be null, or `addrlen` must point to a valid `u32`
429/// initialized to the byte capacity of `addr` and `addr` must be writable for that many bytes.
430pub unsafe fn accept4_raw(
431    fd: RawFd,
432    addr: *mut u8,
433    addrlen: *mut u32,
434    flags: i32,
435) -> SysResult<RawFd> {
436    // SAFETY: Caller upholds the pointer validity contract for `addr` and `addrlen`.
437    unsafe {
438        syscall4(
439            nr::ACCEPT4,
440            fd as usize,
441            addr as usize,
442            addrlen as usize,
443            flags as usize,
444        )
445        .map(|v| v as RawFd)
446    }
447}
448
449/// Accepts a connection on `fd` without peer address capture.
450pub fn accept(fd: RawFd) -> SysResult<RawFd> {
451    accept4(fd, 0)
452}
453
454/// Accepts a connection on `fd` with `flags` (`SOCK_NONBLOCK`, `SOCK_CLOEXEC`) without peer address capture.
455pub fn accept4(fd: RawFd, flags: i32) -> SysResult<RawFd> {
456    // SAFETY: Null address and length pointers are explicitly allowed by `accept4`.
457    unsafe { accept4_raw(fd, core::ptr::null_mut(), core::ptr::null_mut(), flags) }
458}
459
460/// Accepts an `AF_INET` connection on `fd` with `flags`, returning `(client_fd, peer_addr)`.
461pub fn accept_in(fd: RawFd, flags: i32) -> SysResult<(RawFd, SockAddrIn)> {
462    let mut addr = SockAddrIn::default();
463    let mut len = size_of::<SockAddrIn>() as u32;
464    // SAFETY: `addr` and `len` are valid stack variables sized for `SockAddrIn`.
465    let client = unsafe {
466        accept4_raw(
467            fd,
468            core::ptr::from_mut(&mut addr).cast::<u8>(),
469            core::ptr::from_mut(&mut len),
470            flags,
471        )?
472    };
473    Ok((client, addr))
474}
475
476/// Accepts an `AF_INET6` connection on `fd` with `flags`, returning `(client_fd, peer_addr)`.
477pub fn accept_in6(fd: RawFd, flags: i32) -> SysResult<(RawFd, SockAddrIn6)> {
478    let mut addr = SockAddrIn6::default();
479    let mut len = size_of::<SockAddrIn6>() as u32;
480    // SAFETY: `addr` and `len` are valid stack variables sized for `SockAddrIn6`.
481    let client = unsafe {
482        accept4_raw(
483            fd,
484            core::ptr::from_mut(&mut addr).cast::<u8>(),
485            core::ptr::from_mut(&mut len),
486            flags,
487        )?
488    };
489    Ok((client, addr))
490}
491
492/// Sends `len` bytes from `buf` on connected socket `fd` with `flags`.
493///
494/// # Safety
495///
496/// `buf` must be valid for reads of `len` bytes (or `len == 0`).
497pub unsafe fn send_raw(fd: RawFd, buf: *const u8, len: usize, flags: i32) -> SysResult<usize> {
498    // SAFETY: Caller guarantees `buf` is readable for `len` bytes; `dest_addr = 0, addrlen = 0`
499    // is the standard AArch64 `sendto` encoding for `send`.
500    unsafe {
501        syscall6(
502            nr::SENDTO,
503            fd as usize,
504            buf as usize,
505            len,
506            flags as usize,
507            0,
508            0,
509        )
510    }
511}
512
513/// Sends `buf` on connected socket `fd` with `flags`.
514pub fn send(fd: RawFd, buf: &[u8], flags: i32) -> SysResult<usize> {
515    // SAFETY: `buf.as_ptr()` is valid for `buf.len()` bytes.
516    unsafe { send_raw(fd, buf.as_ptr(), buf.len(), flags) }
517}
518
519/// Receives up to `len` bytes into `buf` from socket `fd` with `flags`.
520///
521/// # Safety
522///
523/// `buf` must be valid for writes of `len` bytes (or `len == 0`).
524pub unsafe fn recv_raw(fd: RawFd, buf: *mut u8, len: usize, flags: i32) -> SysResult<usize> {
525    // SAFETY: Caller guarantees `buf` is writable for `len` bytes; `src_addr = 0, addrlen = 0`
526    // is the standard AArch64 `recvfrom` encoding for `recv`.
527    unsafe {
528        syscall6(
529            nr::RECVFROM,
530            fd as usize,
531            buf as usize,
532            len,
533            flags as usize,
534            0,
535            0,
536        )
537    }
538}
539
540/// Receives bytes into `buf` from socket `fd` with `flags`.
541pub fn recv(fd: RawFd, buf: &mut [u8], flags: i32) -> SysResult<usize> {
542    // SAFETY: `buf.as_mut_ptr()` is valid for `buf.len()` writable bytes.
543    unsafe { recv_raw(fd, buf.as_mut_ptr(), buf.len(), flags) }
544}
545
546/// Sends `buf` to an `AF_INET` destination `addr` on socket `fd` with `flags`.
547pub fn sendto_in(fd: RawFd, buf: &[u8], flags: i32, addr: &SockAddrIn) -> SysResult<usize> {
548    // SAFETY: `buf` and `addr` are valid references for their respective byte lengths.
549    unsafe {
550        syscall6(
551            nr::SENDTO,
552            fd as usize,
553            buf.as_ptr() as usize,
554            buf.len(),
555            flags as usize,
556            core::ptr::from_ref(addr) as usize,
557            size_of::<SockAddrIn>(),
558        )
559    }
560}
561
562/// Sends `buf` to an `AF_INET6` destination `addr` on socket `fd` with `flags`.
563pub fn sendto_in6(fd: RawFd, buf: &[u8], flags: i32, addr: &SockAddrIn6) -> SysResult<usize> {
564    // SAFETY: `buf` and `addr` are valid references for their respective byte lengths.
565    unsafe {
566        syscall6(
567            nr::SENDTO,
568            fd as usize,
569            buf.as_ptr() as usize,
570            buf.len(),
571            flags as usize,
572            core::ptr::from_ref(addr) as usize,
573            size_of::<SockAddrIn6>(),
574        )
575    }
576}
577
578/// Receives a datagram into `buf` on `AF_INET` socket `fd` with `flags`, returning `(bytes_read, src_addr)`.
579pub fn recvfrom_in(fd: RawFd, buf: &mut [u8], flags: i32) -> SysResult<(usize, SockAddrIn)> {
580    let mut addr = SockAddrIn::default();
581    let mut addrlen = size_of::<SockAddrIn>() as u32;
582    // SAFETY: `buf`, `addr`, and `addrlen` are valid writable buffers.
583    let n = unsafe {
584        syscall6(
585            nr::RECVFROM,
586            fd as usize,
587            buf.as_mut_ptr() as usize,
588            buf.len(),
589            flags as usize,
590            core::ptr::from_mut(&mut addr) as usize,
591            core::ptr::from_mut(&mut addrlen) as usize,
592        )?
593    };
594    Ok((n, addr))
595}
596
597/// Receives a datagram into `buf` on `AF_INET6` socket `fd` with `flags`, returning `(bytes_read, src_addr)`.
598pub fn recvfrom_in6(fd: RawFd, buf: &mut [u8], flags: i32) -> SysResult<(usize, SockAddrIn6)> {
599    let mut addr = SockAddrIn6::default();
600    let mut addrlen = size_of::<SockAddrIn6>() as u32;
601    // SAFETY: `buf`, `addr`, and `addrlen` are valid writable buffers.
602    let n = unsafe {
603        syscall6(
604            nr::RECVFROM,
605            fd as usize,
606            buf.as_mut_ptr() as usize,
607            buf.len(),
608            flags as usize,
609            core::ptr::from_mut(&mut addr) as usize,
610            core::ptr::from_mut(&mut addrlen) as usize,
611        )?
612    };
613    Ok((n, addr))
614}
615
616/// Queries the local address bound to `fd`.
617///
618/// # Safety
619///
620/// `addrlen` must point to a valid `u32` initialized to the byte capacity of `addr`,
621/// and `addr` must be writable for that many bytes.
622pub unsafe fn getsockname_raw(fd: RawFd, addr: *mut u8, addrlen: *mut u32) -> SysResult<()> {
623    // SAFETY: Caller guarantees `addr` and `addrlen` are valid writable pointers.
624    unsafe {
625        syscall3(
626            nr::GETSOCKNAME,
627            fd as usize,
628            addr as usize,
629            addrlen as usize,
630        )?;
631    }
632    Ok(())
633}
634
635/// Queries the peer address connected to `fd`.
636///
637/// # Safety
638///
639/// `addrlen` must point to a valid `u32` initialized to the byte capacity of `addr`,
640/// and `addr` must be writable for that many bytes.
641pub unsafe fn getpeername_raw(fd: RawFd, addr: *mut u8, addrlen: *mut u32) -> SysResult<()> {
642    // SAFETY: Caller guarantees `addr` and `addrlen` are valid writable pointers.
643    unsafe {
644        syscall3(
645            nr::GETPEERNAME,
646            fd as usize,
647            addr as usize,
648            addrlen as usize,
649        )?;
650    }
651    Ok(())
652}
653
654/// Queries the local `AF_INET` address bound to `fd`.
655pub fn getsockname_in(fd: RawFd) -> SysResult<SockAddrIn> {
656    let mut addr = SockAddrIn::default();
657    let mut len = size_of::<SockAddrIn>() as u32;
658    // SAFETY: `addr` and `len` are valid stack variables sized for `SockAddrIn`.
659    unsafe {
660        getsockname_raw(
661            fd,
662            core::ptr::from_mut(&mut addr).cast::<u8>(),
663            core::ptr::from_mut(&mut len),
664        )?;
665    }
666    Ok(addr)
667}
668
669/// Queries the local `AF_INET6` address bound to `fd`.
670pub fn getsockname_in6(fd: RawFd) -> SysResult<SockAddrIn6> {
671    let mut addr = SockAddrIn6::default();
672    let mut len = size_of::<SockAddrIn6>() as u32;
673    // SAFETY: `addr` and `len` are valid stack variables sized for `SockAddrIn6`.
674    unsafe {
675        getsockname_raw(
676            fd,
677            core::ptr::from_mut(&mut addr).cast::<u8>(),
678            core::ptr::from_mut(&mut len),
679        )?;
680    }
681    Ok(addr)
682}
683
684/// Enables or disables `TCP_NODELAY` on `fd`.
685pub fn set_tcp_nodelay(fd: RawFd, nodelay: bool) -> SysResult<()> {
686    let val: i32 = i32::from(nodelay);
687    // SAFETY: `val` is a 4-byte `i32` on the stack.
688    unsafe {
689        setsockopt_raw(
690            fd,
691            IPPROTO_TCP,
692            TCP_NODELAY,
693            core::ptr::from_ref(&val).cast::<u8>(),
694            size_of::<i32>() as u32,
695        )
696    }
697}
698
699/// Queries and clears any pending `SO_ERROR` on `fd`.
700pub fn get_so_error(fd: RawFd) -> SysResult<i32> {
701    let mut err: i32 = 0;
702    let mut len = size_of::<i32>() as u32;
703    // SAFETY: `err` and `len` are valid stack variables for a 4-byte `i32` option value.
704    unsafe {
705        getsockopt_raw(
706            fd,
707            SOL_SOCKET,
708            SO_ERROR,
709            core::ptr::from_mut(&mut err).cast::<u8>(),
710            core::ptr::from_mut(&mut len),
711        )?;
712    }
713    Ok(err)
714}
715
716/// Sets a raw socket option on `fd`.
717///
718/// # Safety
719///
720/// `optval` must be readable for `optlen` bytes (or null if `optlen == 0`).
721pub unsafe fn setsockopt_raw(
722    fd: RawFd,
723    level: i32,
724    optname: i32,
725    optval: *const u8,
726    optlen: u32,
727) -> SysResult<()> {
728    // SAFETY: Caller guarantees `optval` points to `optlen` readable bytes.
729    unsafe {
730        syscall5(
731            nr::SETSOCKOPT,
732            fd as usize,
733            level as usize,
734            optname as usize,
735            optval as usize,
736            optlen as usize,
737        )?;
738    }
739    Ok(())
740}
741
742/// Gets a raw socket option from `fd`.
743///
744/// # Safety
745///
746/// `optlen` must point to a valid `u32` initialized to the byte capacity of `optval`,
747/// and `optval` must be writable for that many bytes.
748pub unsafe fn getsockopt_raw(
749    fd: RawFd,
750    level: i32,
751    optname: i32,
752    optval: *mut u8,
753    optlen: *mut u32,
754) -> SysResult<()> {
755    // SAFETY: Caller guarantees `optval` and `optlen` are valid writable pointers.
756    unsafe {
757        syscall5(
758            nr::GETSOCKOPT,
759            fd as usize,
760            level as usize,
761            optname as usize,
762            optval as usize,
763            optlen as usize,
764        )?;
765    }
766    Ok(())
767}
768
769/// Shuts down part or all of a full-duplex connection on `fd`.
770pub fn shutdown(fd: RawFd, how: i32) -> SysResult<()> {
771    // SAFETY: `SHUTDOWN` takes scalar `fd` and `how` arguments.
772    unsafe {
773        syscall2(nr::SHUTDOWN, fd as usize, how as usize)?;
774    }
775    Ok(())
776}
777
778#[cfg(test)]
779mod tests {
780    use super::*;
781
782    #[test]
783    fn sockaddr_un_from_path_validates_bounds_and_interior_nul() {
784        let (addr, len) = SockAddrUn::from_path(b"/run/test.sock").unwrap();
785        assert_eq!(addr.sun_family, AF_UNIX as u16);
786        assert_eq!(len, (2 + b"/run/test.sock".len() + 1) as u32);
787        assert_eq!(&addr.sun_path[..14], b"/run/test.sock");
788        assert_eq!(addr.sun_path[14], 0);
789
790        let max_ok = [b'a'; 107];
791        let (_, max_len) = SockAddrUn::from_path(&max_ok).unwrap();
792        assert_eq!(max_len, 110);
793
794        let too_long = [b'a'; 108];
795        assert_eq!(
796            SockAddrUn::from_path(&too_long).unwrap_err(),
797            Errno(ENAMETOOLONG)
798        );
799
800        assert_eq!(SockAddrUn::from_path(b"").unwrap_err(), Errno(EINVAL));
801        assert_eq!(
802            SockAddrUn::from_path(b"/tmp/bad\0path").unwrap_err(),
803            Errno(EINVAL)
804        );
805    }
806
807    #[test]
808    fn vsock_addr_constructor_sets_family_cid_and_port() {
809        let vm = SockAddrVm::new(VMADDR_CID_HOST, 5000);
810        assert_eq!(vm.svm_family, AF_VSOCK as u16);
811        assert_eq!(vm.svm_cid, VMADDR_CID_HOST);
812        assert_eq!(vm.svm_port, 5000);
813    }
814
815    #[test]
816    fn ipv4_and_ipv6_sockaddr_layouts_and_byte_order() {
817        let v4 = SockAddrIn::new([127, 0, 0, 1], 8080);
818        assert_eq!(v4.sin_family, AF_INET as u16);
819        assert_eq!(v4.sin_port, 8080u16.to_be());
820        assert_eq!(v4.sin_addr.s_addr, u32::from_ne_bytes([127, 0, 0, 1]));
821        assert_eq!(v4.ip(), [127, 0, 0, 1]);
822        assert_eq!(v4.port(), 8080);
823
824        let ip6 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];
825        let v6 = SockAddrIn6::new(ip6, 443, 0x1234, 2);
826        assert_eq!(v6.sin6_family, AF_INET6 as u16);
827        assert_eq!(v6.sin6_port, 443u16.to_be());
828        assert_eq!(v6.sin6_flowinfo, 0x1234);
829        assert_eq!(v6.sin6_addr.s6_addr, ip6);
830        assert_eq!(v6.sin6_scope_id, 2);
831        assert_eq!(v6.ip(), ip6);
832        assert_eq!(v6.port(), 443);
833    }
834}