Skip to main content

std/os/windows/net/
addr.rs

1#![unstable(feature = "windows_unix_domain_sockets", issue = "150487")]
2use crate::byte_str::ByteStr;
3use crate::ffi::OsStr;
4use crate::macros::rustdoc_skip_body;
5use crate::path::Path;
6#[cfg(not(doc))]
7use crate::sys::c::{AF_UNIX, SOCKADDR, SOCKADDR_UN};
8use crate::sys::cvt_nz;
9use crate::{fmt, io, mem, ptr};
10
11#[cfg(not(doc))]
12pub fn sockaddr_un(path: &Path) -> io::Result<(SOCKADDR_UN, usize)> {
13    // SAFETY: All zeros is a valid representation for `sockaddr_un`.
14    let mut addr: SOCKADDR_UN = unsafe { mem::zeroed() };
15    addr.sun_family = AF_UNIX;
16
17    // path to UTF-8 bytes
18    let bytes = path
19        .to_str()
20        .ok_or(io::const_error!(io::ErrorKind::InvalidInput, "path must be valid UTF-8"))?
21        .as_bytes();
22    if bytes.len() >= addr.sun_path.len() {
23        return Err(io::const_error!(io::ErrorKind::InvalidInput, "path too long"));
24    }
25    // SAFETY: `bytes` and `addr.sun_path` are not overlapping and
26    // both point to valid memory.
27    // NOTE: We zeroed the memory above, so the path is already null
28    // terminated.
29    unsafe {
30        ptr::copy_nonoverlapping(bytes.as_ptr(), addr.sun_path.as_mut_ptr().cast(), bytes.len())
31    };
32
33    let len = SUN_PATH_OFFSET + bytes.len() + 1;
34    Ok((addr, len))
35}
36#[cfg(not(doc))]
37const SUN_PATH_OFFSET: usize = mem::offset_of!(SOCKADDR_UN, sun_path);
38pub struct SocketAddr {
39    #[cfg(not(doc))]
40    pub(super) addr: SOCKADDR_UN,
41    pub(super) len: u32, // Use u32 here as same as libc::socklen_t
42}
43impl fmt::Debug for SocketAddr {
44    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
45        match self.address() {
46            AddressKind::Unnamed => write!(fmt, "(unnamed)"),
47            AddressKind::Abstract(name) => write!(fmt, "{name:?} (abstract)"),
48            AddressKind::Pathname(path) => write!(fmt, "{path:?} (pathname)"),
49        }
50    }
51}
52
53impl SocketAddr {
54    #[cfg(not(doc))]
55    pub(super) fn new<F>(f: F) -> io::Result<SocketAddr>
56    where
57        F: FnOnce(*mut SOCKADDR, *mut i32) -> i32,
58    {
59        unsafe {
60            let mut addr: SOCKADDR_UN = mem::zeroed();
61            let mut len = mem::size_of::<SOCKADDR_UN>() as i32;
62            cvt_nz(f(&raw mut addr as *mut _, &mut len))?;
63            SocketAddr::from_parts(addr, len)
64        }
65    }
66    #[cfg(not(doc))]
67    pub(super) fn from_parts(addr: SOCKADDR_UN, len: i32) -> io::Result<SocketAddr> {
68        if addr.sun_family != AF_UNIX {
69            Err(io::const_error!(io::ErrorKind::InvalidInput, "invalid address family"))
70        } else if len < SUN_PATH_OFFSET as _ || len > mem::size_of::<SOCKADDR_UN>() as _ {
71            Err(io::const_error!(io::ErrorKind::InvalidInput, "invalid address length"))
72        } else {
73            Ok(SocketAddr { addr, len: len as _ })
74        }
75    }
76
77    /// Returns the contents of this address if it is a `pathname` address.
78    ///
79    /// # Examples
80    ///
81    /// With a pathname:
82    ///
83    #[cfg_attr(windows, doc = "```no_run")]
84    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
85    /// #![feature(windows_unix_domain_sockets)]
86    /// use std::os::windows::net::UnixListener;
87    /// use std::path::Path;
88    ///
89    /// fn main() -> std::io::Result<()> {
90    ///     let socket = UnixListener::bind("/tmp/sock")?;
91    ///     let addr = socket.local_addr().expect("Couldn't get local address");
92    ///     assert_eq!(addr.as_pathname(), Some(Path::new("/tmp/sock")));
93    ///     Ok(())
94    /// }
95    /// ```
96    pub fn as_pathname(&self) -> Option<&Path> {
97        if let AddressKind::Pathname(path) = self.address() { Some(path) } else { None }
98    }
99
100    /// Constructs a `SockAddr` with the family `AF_UNIX` and the provided path.
101    ///
102    /// # Errors
103    ///
104    /// Returns an error if the path is longer than `SUN_LEN` or if it contains
105    /// NULL bytes.
106    ///
107    /// # Examples
108    ///
109    #[cfg_attr(windows, doc = "```no_run")]
110    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
111    /// #![feature(windows_unix_domain_sockets)]
112    /// use std::os::windows::net::SocketAddr;
113    /// use std::path::Path;
114    ///
115    /// # fn main() -> std::io::Result<()> {
116    /// let address = SocketAddr::from_pathname("/path/to/socket")?;
117    /// assert_eq!(address.as_pathname(), Some(Path::new("/path/to/socket")));
118    /// # Ok(())
119    /// # }
120    /// ```
121    ///
122    /// Creating a `SocketAddr` with a NULL byte results in an error.
123    ///
124    #[cfg_attr(windows, doc = "```no_run")]
125    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
126    /// #![feature(windows_unix_domain_sockets)]
127    /// use std::os::windows::net::SocketAddr;
128    ///
129    /// assert!(SocketAddr::from_pathname("/path/with/\0/bytes").is_err());
130    /// ```
131    #[rustdoc_skip_body]
132    pub fn from_pathname<P>(path: P) -> io::Result<SocketAddr>
133    where
134        P: AsRef<Path>,
135    {
136        sockaddr_un(path.as_ref()).map(|(addr, len)| SocketAddr { addr, len: len as _ })
137    }
138
139    #[rustdoc_skip_body]
140    fn address(&self) -> AddressKind<'_> {
141        let len = self.len as usize - SUN_PATH_OFFSET;
142        let path = unsafe { mem::transmute::<&[i8], &[u8]>(&self.addr.sun_path) };
143
144        if len == 0 {
145            AddressKind::Unnamed
146        } else if self.addr.sun_path[0] == 0 {
147            AddressKind::Abstract(ByteStr::from_bytes(&path[1..len]))
148        } else {
149            AddressKind::Pathname(unsafe {
150                OsStr::from_encoded_bytes_unchecked(&path[..len - 1]).as_ref()
151            })
152        }
153    }
154
155    /// Returns `true` if the address is unnamed.
156    ///
157    /// # Examples
158    ///
159    /// A named address:
160    ///
161    #[cfg_attr(windows, doc = "```no_run")]
162    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
163    /// #![feature(windows_unix_domain_sockets)]
164    /// use std::os::windows::net::UnixListener;
165    ///
166    /// fn main() -> std::io::Result<()> {
167    ///     let socket = UnixListener::bind("/tmp/sock")?;
168    ///     let addr = socket.local_addr().expect("Couldn't get local address");
169    ///     assert_eq!(addr.is_unnamed(), false);
170    ///     Ok(())
171    /// }
172    /// ```
173    pub fn is_unnamed(&self) -> bool {
174        matches!(self.address(), AddressKind::Unnamed)
175    }
176}
177enum AddressKind<'a> {
178    Unnamed,
179    Pathname(&'a Path),
180    Abstract(&'a ByteStr),
181}