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#[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 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 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 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#[cfg_attr(target_family = "unix", doc = "```")]
82#[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
83#[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 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 len = SUN_PATH_OFFSET as libc::socklen_t; } 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 #[cfg_attr(target_family = "unix", doc = "```")]
156 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
157 #[cfg_attr(target_family = "unix", doc = "```")]
170 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
171 #[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 #[cfg_attr(target_family = "unix", doc = "```no_run")]
190 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
191 #[cfg_attr(target_family = "unix", doc = "```")]
204 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
205 #[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 #[cfg_attr(target_family = "unix", doc = "```no_run")]
228 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
229 #[cfg_attr(target_family = "unix", doc = "```")]
243 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
244 #[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 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 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#[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}