Skip to main content

std/os/unix/net/
addr.rs

1use crate::byte_str::ByteStr;
2use crate::ffi::OsStr;
3use crate::macros::rustdoc_skip_body;
4#[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "cygwin"))]
5use crate::os::net::linux_ext;
6use crate::os::unix::ffi::OsStrExt;
7use crate::path::Path;
8use crate::sys::cvt;
9use crate::{fmt, io, mem, ptr};
10
11// FIXME(#43348): Make libc adapt #[doc(cfg(...))] so we don't need these fake definitions here?
12#[cfg(not(unix))]
13#[allow(non_camel_case_types)]
14mod libc {
15    pub use core::ffi::c_int;
16    pub type socklen_t = u32;
17    pub struct sockaddr;
18    #[derive(Clone)]
19    pub struct sockaddr_un {
20        pub sun_path: [u8; 1],
21    }
22}
23
24const SUN_PATH_OFFSET: usize = const { k#offset_of(libc::sockaddr_un, sun_path) }mem::offset_of!(libc::sockaddr_un, sun_path);
25
26#[rustdoc_skip_body]
27pub(super) fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
28    // SAFETY: All zeros is a valid representation for `sockaddr_un`.
29    let mut addr: libc::sockaddr_un = unsafe { mem::zeroed() };
30    addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
31
32    let bytes = path.as_os_str().as_bytes();
33
34    if bytes.contains(&0) {
35        return Err(::core::hint::must_use(::core::io::Error::from_static_message(const {
                &::core::io::SimpleMessage {
                        kind: io::ErrorKind::InvalidInput,
                        message: "paths must not contain interior null bytes",
                    }
            }))io::const_error!(
36            io::ErrorKind::InvalidInput,
37            "paths must not contain interior null bytes",
38        ));
39    }
40
41    if bytes.len() >= addr.sun_path.len() {
42        return Err(::core::hint::must_use(::core::io::Error::from_static_message(const {
                &::core::io::SimpleMessage {
                        kind: io::ErrorKind::InvalidInput,
                        message: "path must be shorter than SUN_LEN",
                    }
            }))io::const_error!(
43            io::ErrorKind::InvalidInput,
44            "path must be shorter than SUN_LEN",
45        ));
46    }
47    // SAFETY: `bytes` and `addr.sun_path` are not overlapping and
48    // both point to valid memory.
49    // NOTE: We zeroed the memory above, so the path is already null
50    // terminated.
51    unsafe {
52        ptr::copy_nonoverlapping(bytes.as_ptr(), addr.sun_path.as_mut_ptr().cast(), bytes.len())
53    };
54
55    let mut len = SUN_PATH_OFFSET + bytes.len();
56    match bytes.get(0) {
57        Some(&0) | None => {}
58        Some(_) => {
59            // on QNX7.1 and QNX8 the `len` value returned by the SUN_LEN
60            // macro in its libc does not include the null byte in the count so
61            // don't add it here to match what a C program passes to bind(2) and
62            // similar functions
63            if truecfg!(not(any(target_os = "qnx", target_env = "nto71"))) {
64                len += 1
65            }
66        }
67    }
68    Ok((addr, len as libc::socklen_t))
69}
70
71enum AddressKind<'a> {
72    Unnamed,
73    Pathname(&'a Path),
74    Abstract(&'a ByteStr),
75}
76
77/// An address associated with a Unix socket.
78///
79/// # Examples
80///
81#[cfg_attr(target_family = "unix", doc = "```")]
82#[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
83/// # if cfg!(skip_unsupported_miri_tests) { return; }
84/// use std::os::unix::net::UnixListener;
85///
86/// let socket = match UnixListener::bind("/tmp/sock") {
87///     Ok(sock) => sock,
88///     Err(e) => {
89///         println!("Couldn't bind: {e:?}");
90///         return
91///     }
92/// };
93/// let addr = socket.local_addr().expect("`UnixListener::local_addr` should not fail");
94/// ```
95#[derive(#[automatically_derived]#[stable(feature = "unix_socket", since = "1.10.0")]
impl ::core::clone::Clone for SocketAddr {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        SocketAddr {
            addr: ::core::clone::Clone::clone(&self.addr),
            len: ::core::clone::Clone::clone(&self.len),
        }
    }
}Clone)]
96#[stable(feature = "unix_socket", since = "1.10.0")]
97pub struct SocketAddr {
98    pub(super) addr: libc::sockaddr_un,
99    pub(super) len: libc::socklen_t,
100}
101
102impl SocketAddr {
103    pub(super) fn new<F>(f: F) -> io::Result<SocketAddr>
104    where
105        F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int,
106    {
107        unsafe {
108            let mut addr: libc::sockaddr_un = mem::zeroed();
109            let mut len = size_of::<libc::sockaddr_un>() as libc::socklen_t;
110            cvt(f((&raw mut addr) as *mut _, &mut len))?;
111            SocketAddr::from_parts(addr, len)
112        }
113    }
114
115    #[rustdoc_skip_body]
116    pub(super) fn from_parts(
117        addr: libc::sockaddr_un,
118        mut len: libc::socklen_t,
119    ) -> io::Result<SocketAddr> {
120        if falsecfg!(target_os = "openbsd") {
121            // on OpenBSD, getsockname(2) returns the actual size of the socket address,
122            // and not the len of the content. Figure out the length for ourselves.
123            // https://marc.info/?l=openbsd-bugs&m=170105481926736&w=2
124            let sun_path: &[u8] =
125                unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&addr.sun_path) };
126            len = core::slice::memchr::memchr(0, sun_path)
127                .map_or(len, |new_len| (new_len + SUN_PATH_OFFSET) as libc::socklen_t);
128        }
129
130        len = len.min(size_of::<libc::sockaddr_un>() as libc::socklen_t);
131
132        if len == 0 {
133            // When there is a datagram from unnamed unix socket
134            // linux returns zero bytes of address
135            len = SUN_PATH_OFFSET as libc::socklen_t; // i.e., zero-length address
136        } else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t {
137            return Err(::core::hint::must_use(::core::io::Error::from_static_message(const {
                &::core::io::SimpleMessage {
                        kind: io::ErrorKind::InvalidInput,
                        message: "file descriptor did not correspond to a Unix socket",
                    }
            }))io::const_error!(
138                io::ErrorKind::InvalidInput,
139                "file descriptor did not correspond to a Unix socket",
140            ));
141        }
142
143        Ok(SocketAddr { addr, len })
144    }
145
146    /// Constructs a `SockAddr` with the family `AF_UNIX` and the provided path.
147    ///
148    /// # Errors
149    ///
150    /// Returns an error if the path is longer than `SUN_LEN` or if it contains
151    /// NULL bytes.
152    ///
153    /// # Examples
154    ///
155    #[cfg_attr(target_family = "unix", doc = "```")]
156    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
157    /// use std::os::unix::net::SocketAddr;
158    /// use std::path::Path;
159    ///
160    /// # fn main() -> std::io::Result<()> {
161    /// let address = SocketAddr::from_pathname("/path/to/socket")?;
162    /// assert_eq!(address.as_pathname(), Some(Path::new("/path/to/socket")));
163    /// # Ok(())
164    /// # }
165    /// ```
166    ///
167    /// Creating a `SocketAddr` with a NULL byte results in an error.
168    ///
169    #[cfg_attr(target_family = "unix", doc = "```")]
170    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
171    /// use std::os::unix::net::SocketAddr;
172    ///
173    /// assert!(SocketAddr::from_pathname("/path/with/\0/bytes").is_err());
174    /// ```
175    #[stable(feature = "unix_socket_creation", since = "1.61.0")]
176    pub fn from_pathname<P>(path: P) -> io::Result<SocketAddr>
177    where
178        P: AsRef<Path>,
179    {
180        sockaddr_un(path.as_ref()).map(|(addr, len)| SocketAddr { addr, len })
181    }
182
183    /// Returns `true` if the address is unnamed.
184    ///
185    /// # Examples
186    ///
187    /// A named address:
188    ///
189    #[cfg_attr(target_family = "unix", doc = "```no_run")]
190    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
191    /// use std::os::unix::net::UnixListener;
192    ///
193    /// fn main() -> std::io::Result<()> {
194    ///     let socket = UnixListener::bind("/tmp/sock")?;
195    ///     let addr = socket.local_addr().expect("`UnixListener::local_addr` should not fail");
196    ///     assert_eq!(addr.is_unnamed(), false);
197    ///     Ok(())
198    /// }
199    /// ```
200    ///
201    /// An unnamed address:
202    ///
203    #[cfg_attr(target_family = "unix", doc = "```")]
204    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
205    /// use std::os::unix::net::UnixDatagram;
206    ///
207    /// fn main() -> std::io::Result<()> {
208    /// #   if cfg!(skip_unsupported_miri_tests) { return Ok(()); }
209    ///     let socket = UnixDatagram::unbound()?;
210    ///     let addr = socket.local_addr().expect("`UnixListener::local_addr` should not fail");
211    ///     assert_eq!(addr.is_unnamed(), true);
212    ///     Ok(())
213    /// }
214    /// ```
215    #[must_use]
216    #[stable(feature = "unix_socket", since = "1.10.0")]
217    pub fn is_unnamed(&self) -> bool {
218        #[allow(non_exhaustive_omitted_patterns)] match self.address() {
    AddressKind::Unnamed => true,
    _ => false,
}matches!(self.address(), AddressKind::Unnamed)
219    }
220
221    /// Returns the contents of this address if it is a `pathname` address.
222    ///
223    /// # Examples
224    ///
225    /// With a pathname:
226    ///
227    #[cfg_attr(target_family = "unix", doc = "```no_run")]
228    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
229    /// use std::os::unix::net::UnixListener;
230    /// use std::path::Path;
231    ///
232    /// fn main() -> std::io::Result<()> {
233    ///     let socket = UnixListener::bind("/tmp/sock")?;
234    ///     let addr = socket.local_addr().expect("`UnixListener::local_addr` should not fail");
235    ///     assert_eq!(addr.as_pathname(), Some(Path::new("/tmp/sock")));
236    ///     Ok(())
237    /// }
238    /// ```
239    ///
240    /// Without a pathname:
241    ///
242    #[cfg_attr(target_family = "unix", doc = "```")]
243    #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
244    /// use std::os::unix::net::UnixDatagram;
245    ///
246    /// fn main() -> std::io::Result<()> {
247    /// #   if cfg!(skip_unsupported_miri_tests) { return Ok(()); }
248    ///     let socket = UnixDatagram::unbound()?;
249    ///     let addr = socket.local_addr().expect("`UnixListener::local_addr` should not fail");
250    ///     assert_eq!(addr.as_pathname(), None);
251    ///     Ok(())
252    /// }
253    /// ```
254    #[stable(feature = "unix_socket", since = "1.10.0")]
255    #[must_use]
256    pub fn as_pathname(&self) -> Option<&Path> {
257        if let AddressKind::Pathname(path) = self.address() { Some(path) } else { None }
258    }
259
260    #[rustdoc_skip_body]
261    fn address(&self) -> AddressKind<'_> {
262        let len = self.len as usize - SUN_PATH_OFFSET;
263        let path = unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&self.addr.sun_path) };
264
265        // macOS seems to return a len of 16 and a zeroed sun_path for unnamed addresses
266        if len == 0
267            || (falsecfg!(not(any(target_os = "linux", target_os = "android", target_os = "cygwin")))
268                && self.addr.sun_path[0] == 0)
269        {
270            AddressKind::Unnamed
271        } else if self.addr.sun_path[0] == 0 {
272            AddressKind::Abstract(ByteStr::from_bytes(&path[1..len]))
273        } else {
274            // linux adds a trailing NUL and counts it in the length, freebsd, netbsd
275            // and qnx do not, and a caller may bind(2) without one either. unix(7)
276            // gives the portable rule: strnlen(sun_path, len - offsetof(sun_path))
277            let end = core::slice::memchr::memchr(0, &path[..len]).unwrap_or(len);
278            AddressKind::Pathname(OsStr::from_bytes(&path[..end]).as_ref())
279        }
280    }
281}
282
283// #[doc(cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin")))] // commented out for std.noratrieb.dev
284#[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "cygwin"))]
285#[stable(feature = "unix_socket_abstract", since = "1.70.0")]
286impl linux_ext::addr::SocketAddrExt for SocketAddr {
287    fn as_abstract_name(&self) -> Option<&[u8]> {
288        if let AddressKind::Abstract(name) = self.address() { Some(name.as_bytes()) } else { None }
289    }
290
291    #[rustdoc_skip_body]
292    fn from_abstract_name<N>(name: N) -> io::Result<Self>
293    where
294        N: AsRef<[u8]>,
295    {
296        let name = name.as_ref();
297        unsafe {
298            let mut addr: libc::sockaddr_un = mem::zeroed();
299            addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
300
301            if name.len() + 1 > addr.sun_path.len() {
302                return Err(::core::hint::must_use(::core::io::Error::from_static_message(const {
                &::core::io::SimpleMessage {
                        kind: io::ErrorKind::InvalidInput,
                        message: "abstract socket name must be shorter than SUN_LEN",
                    }
            }))io::const_error!(
303                    io::ErrorKind::InvalidInput,
304                    "abstract socket name must be shorter than SUN_LEN",
305                ));
306            }
307
308            crate::ptr::copy_nonoverlapping(
309                name.as_ptr(),
310                addr.sun_path.as_mut_ptr().add(1) as *mut u8,
311                name.len(),
312            );
313            let len = (SUN_PATH_OFFSET + 1 + name.len()) as libc::socklen_t;
314            SocketAddr::from_parts(addr, len)
315        }
316    }
317}
318
319#[stable(feature = "unix_socket", since = "1.10.0")]
320impl fmt::Debug for SocketAddr {
321    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
322        match self.address() {
323            AddressKind::Unnamed => fmt.write_fmt(format_args!("(unnamed)"))write!(fmt, "(unnamed)"),
324            AddressKind::Abstract(name) => fmt.write_fmt(format_args!("{0:?} (abstract)", name))write!(fmt, "{name:?} (abstract)"),
325            AddressKind::Pathname(path) => fmt.write_fmt(format_args!("{0:?} (pathname)", path))write!(fmt, "{path:?} (pathname)"),
326        }
327    }
328}