1use crate::bstr::ByteStr;
2use crate::ffi::OsStr;
3#[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "cygwin"))]
4use crate::os::net::linux_ext;
5use crate::os::unix::ffi::OsStrExt;
6use crate::path::Path;
7use crate::sealed::Sealed;
8use crate::sys::cvt;
9use crate::{fmt, io, mem, ptr};
10
11#[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 = mem::offset_of!(libc::sockaddr_un, sun_path);
25
26pub(super) fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
27 let mut addr: libc::sockaddr_un = unsafe { mem::zeroed() };
29 addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
30
31 let bytes = path.as_os_str().as_bytes();
32
33 if bytes.contains(&0) {
34 return Err(io::const_error!(
35 io::ErrorKind::InvalidInput,
36 "paths must not contain interior null bytes",
37 ));
38 }
39
40 if bytes.len() >= addr.sun_path.len() {
41 return Err(io::const_error!(
42 io::ErrorKind::InvalidInput,
43 "path must be shorter than SUN_LEN",
44 ));
45 }
46 unsafe {
51 ptr::copy_nonoverlapping(bytes.as_ptr(), addr.sun_path.as_mut_ptr().cast(), bytes.len())
52 };
53
54 let mut len = SUN_PATH_OFFSET + bytes.len();
55 match bytes.get(0) {
56 Some(&0) | None => {}
57 Some(_) => len += 1,
58 }
59 Ok((addr, len as libc::socklen_t))
60}
61
62enum AddressKind<'a> {
63 Unnamed,
64 Pathname(&'a Path),
65 Abstract(&'a ByteStr),
66}
67
68#[derive(Clone)]
85#[stable(feature = "unix_socket", since = "1.10.0")]
86pub struct SocketAddr {
87 pub(super) addr: libc::sockaddr_un,
88 pub(super) len: libc::socklen_t,
89}
90
91impl SocketAddr {
92 pub(super) fn new<F>(f: F) -> io::Result<SocketAddr>
93 where
94 F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int,
95 {
96 unsafe {
97 let mut addr: libc::sockaddr_un = mem::zeroed();
98 let mut len = size_of::<libc::sockaddr_un>() as libc::socklen_t;
99 cvt(f((&raw mut addr) as *mut _, &mut len))?;
100 SocketAddr::from_parts(addr, len)
101 }
102 }
103
104 pub(super) fn from_parts(
105 addr: libc::sockaddr_un,
106 mut len: libc::socklen_t,
107 ) -> io::Result<SocketAddr> {
108 if cfg!(target_os = "openbsd") {
109 let sun_path: &[u8] =
113 unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&addr.sun_path) };
114 len = core::slice::memchr::memchr(0, sun_path)
115 .map_or(len, |new_len| (new_len + SUN_PATH_OFFSET) as libc::socklen_t);
116 }
117
118 if len == 0 {
119 len = SUN_PATH_OFFSET as libc::socklen_t; } else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t {
123 return Err(io::const_error!(
124 io::ErrorKind::InvalidInput,
125 "file descriptor did not correspond to a Unix socket",
126 ));
127 }
128
129 Ok(SocketAddr { addr, len })
130 }
131
132 #[stable(feature = "unix_socket_creation", since = "1.61.0")]
160 pub fn from_pathname<P>(path: P) -> io::Result<SocketAddr>
161 where
162 P: AsRef<Path>,
163 {
164 sockaddr_un(path.as_ref()).map(|(addr, len)| SocketAddr { addr, len })
165 }
166
167 #[cfg_attr(
187 not(any(target_os = "nto", target_os = "vxworks")),
190 doc = "```"
191 )]
192 #[cfg_attr(
193 any(target_os = "nto", target_os = "vxworks"),
194 doc = "```ignore"
195 )]
196 #[must_use]
206 #[stable(feature = "unix_socket", since = "1.10.0")]
207 pub fn is_unnamed(&self) -> bool {
208 matches!(self.address(), AddressKind::Unnamed)
209 }
210
211 #[cfg_attr(
232 not(any(target_os = "nto", target_os = "vxworks")),
235 doc = "```"
236 )]
237 #[cfg_attr(
238 any(target_os = "nto", target_os = "vxworks"),
239 doc = "```ignore"
240 )]
241 #[stable(feature = "unix_socket", since = "1.10.0")]
251 #[must_use]
252 pub fn as_pathname(&self) -> Option<&Path> {
253 if let AddressKind::Pathname(path) = self.address() { Some(path) } else { None }
254 }
255
256 fn address(&self) -> AddressKind<'_> {
257 let len = self.len as usize - SUN_PATH_OFFSET;
258 let path = unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&self.addr.sun_path) };
259
260 if len == 0
262 || (cfg!(not(any(target_os = "linux", target_os = "android", target_os = "cygwin")))
263 && self.addr.sun_path[0] == 0)
264 {
265 AddressKind::Unnamed
266 } else if self.addr.sun_path[0] == 0 {
267 AddressKind::Abstract(ByteStr::from_bytes(&path[1..len]))
268 } else {
269 AddressKind::Pathname(OsStr::from_bytes(&path[..len - 1]).as_ref())
270 }
271 }
272}
273
274#[stable(feature = "unix_socket_abstract", since = "1.70.0")]
275impl Sealed for SocketAddr {}
276
277#[doc(cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin")))]
278#[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "cygwin"))]
279#[stable(feature = "unix_socket_abstract", since = "1.70.0")]
280impl linux_ext::addr::SocketAddrExt for SocketAddr {
281 fn as_abstract_name(&self) -> Option<&[u8]> {
282 if let AddressKind::Abstract(name) = self.address() { Some(name.as_bytes()) } else { None }
283 }
284
285 fn from_abstract_name<N>(name: N) -> crate::io::Result<Self>
286 where
287 N: AsRef<[u8]>,
288 {
289 let name = name.as_ref();
290 unsafe {
291 let mut addr: libc::sockaddr_un = mem::zeroed();
292 addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
293
294 if name.len() + 1 > addr.sun_path.len() {
295 return Err(io::const_error!(
296 io::ErrorKind::InvalidInput,
297 "abstract socket name must be shorter than SUN_LEN",
298 ));
299 }
300
301 crate::ptr::copy_nonoverlapping(
302 name.as_ptr(),
303 addr.sun_path.as_mut_ptr().add(1) as *mut u8,
304 name.len(),
305 );
306 let len = (SUN_PATH_OFFSET + 1 + name.len()) as libc::socklen_t;
307 SocketAddr::from_parts(addr, len)
308 }
309 }
310}
311
312#[stable(feature = "unix_socket", since = "1.10.0")]
313impl fmt::Debug for SocketAddr {
314 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
315 match self.address() {
316 AddressKind::Unnamed => write!(fmt, "(unnamed)"),
317 AddressKind::Abstract(name) => write!(fmt, "{name:?} (abstract)"),
318 AddressKind::Pathname(path) => write!(fmt, "{path:?} (pathname)"),
319 }
320 }
321}