Skip to main content

std/os/windows/net/
addr.rs

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