Skip to content

Commit fbc01e5

Browse files
committed
Add abstract namespace support for Unix domain sockets
1 parent 3f46b82 commit fbc01e5

File tree

5 files changed

+363
-5
lines changed

5 files changed

+363
-5
lines changed

library/std/src/os/unix/net/addr.rs

Lines changed: 81 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::ffi::OsStr;
22
use crate::os::unix::ffi::OsStrExt;
33
use crate::path::Path;
44
use crate::sys::cvt;
5-
use crate::{ascii, fmt, io, iter, mem};
5+
use crate::{ascii, fmt, io, iter, mem, ptr};
66

77
// FIXME(#43348): Make libc adapt #[doc(cfg(...))] so we don't need these fake definitions here?
88
#[cfg(not(unix))]
@@ -92,8 +92,8 @@ impl<'a> fmt::Display for AsciiEscaped<'a> {
9292
#[derive(Clone)]
9393
#[stable(feature = "unix_socket", since = "1.10.0")]
9494
pub struct SocketAddr {
95-
addr: libc::sockaddr_un,
96-
len: libc::socklen_t,
95+
pub(super) addr: libc::sockaddr_un,
96+
pub(super) len: libc::socklen_t,
9797
}
9898

9999
impl SocketAddr {
@@ -196,6 +196,30 @@ impl SocketAddr {
196196
if let AddressKind::Pathname(path) = self.address() { Some(path) } else { None }
197197
}
198198

199+
/// Returns the contents of this address if it is an abstract namespace
200+
/// without the leading null byte.
201+
///
202+
/// # Examples
203+
///
204+
/// ```no_run
205+
/// #![feature(unix_socket_abstract)]
206+
/// use std::os::unix::net::{UnixListener, SocketAddr};
207+
///
208+
/// fn main() -> std::io::Result<()> {
209+
/// let namespace = b"hidden";
210+
/// let namespace_addr = SocketAddr::from_abstract_namespace(&namespace[..])?;
211+
/// let socket = UnixListener::bind_addr(&namespace_addr)?;
212+
/// let local_addr = socket.local_addr().expect("Couldn't get local address");
213+
/// assert_eq!(local_addr.as_abstract_namespace(), Some(&namespace[..]));
214+
/// Ok(())
215+
/// }
216+
/// ```
217+
#[cfg(any(doc, target_os = "android", target_os = "linux",))]
218+
#[unstable(feature = "unix_socket_abstract", issue = "42048")]
219+
pub fn as_abstract_namespace(&self) -> Option<&[u8]> {
220+
if let AddressKind::Abstract(name) = self.address() { Some(name) } else { None }
221+
}
222+
199223
fn address(&self) -> AddressKind<'_> {
200224
let len = self.len as usize - sun_path_offset(&self.addr);
201225
let path = unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&self.addr.sun_path) };
@@ -212,6 +236,60 @@ impl SocketAddr {
212236
AddressKind::Pathname(OsStr::from_bytes(&path[..len - 1]).as_ref())
213237
}
214238
}
239+
240+
/// Creates an abstract domain socket address from a namespace
241+
///
242+
/// An abstract address does not create a file unlike traditional path-based
243+
/// Unix sockets. The advantage of this is that the address will disappear when
244+
/// the socket bound to it is closed, so no filesystem clean up is required.
245+
///
246+
/// The leading null byte for the abstract namespace is automatically added.
247+
///
248+
/// This is a Linux-specific extension. See more at [`unix(7)`].
249+
///
250+
/// [`unix(7)`]: https://man7.org/linux/man-pages/man7/unix.7.html
251+
///
252+
/// # Errors
253+
///
254+
/// This will return an error if the given namespace is too long
255+
///
256+
/// # Examples
257+
///
258+
/// ```no_run
259+
/// #![feature(unix_socket_abstract)]
260+
/// use std::os::unix::net::{UnixListener, SocketAddr};
261+
///
262+
/// fn main() -> std::io::Result<()> {
263+
/// let addr = SocketAddr::from_abstract_namespace(b"hidden")?;
264+
/// let listener = match UnixListener::bind_addr(&addr) {
265+
/// Ok(sock) => sock,
266+
/// Err(err) => {
267+
/// println!("Couldn't bind: {:?}", err);
268+
/// return Err(err);
269+
/// }
270+
/// };
271+
/// Ok(())
272+
/// }
273+
/// ```
274+
#[cfg(any(doc, target_os = "android", target_os = "linux",))]
275+
#[unstable(feature = "unix_socket_abstract", issue = "42048")]
276+
pub fn from_abstract_namespace(namespace: &[u8]) -> io::Result<SocketAddr> {
277+
unsafe {
278+
let mut addr: libc::sockaddr_un = mem::zeroed();
279+
addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
280+
281+
if namespace.len() + 1 > addr.sun_path.len() {
282+
return Err(io::Error::new_const(
283+
io::ErrorKind::InvalidInput,
284+
&"namespace must be shorter than SUN_LEN",
285+
));
286+
}
287+
288+
ptr::copy_nonoverlapping(namespace.as_ptr(), addr.sun_path.as_mut_ptr().offset(1) as *mut u8, namespace.len());
289+
let len = (sun_path_offset(&addr) + 1 + namespace.len()) as libc::socklen_t;
290+
SocketAddr::from_parts(addr, len)
291+
}
292+
}
215293
}
216294

217295
#[stable(feature = "unix_socket", since = "1.10.0")]

library/std/src/os/unix/net/datagram.rs

Lines changed: 93 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,35 @@ impl UnixDatagram {
112112
}
113113
}
114114

115+
/// Creates a Unix datagram socket bound to an address.
116+
///
117+
/// # Examples
118+
///
119+
/// ```no_run
120+
/// #![feature(unix_socket_abstract)]
121+
/// use std::os::unix::net::{UnixDatagram, SocketAddr};
122+
///
123+
/// fn main() -> std::io::Result<()> {
124+
/// let addr = SocketAddr::from_abstract_namespace(b"hidden")?; // Linux only
125+
/// let sock = match UnixDatagram::bind_addr(&addr) {
126+
/// Ok(sock) => sock,
127+
/// Err(err) => {
128+
/// println!("Couldn't bind: {:?}", err);
129+
/// return Err(err);
130+
/// }
131+
/// };
132+
/// Ok(())
133+
/// }
134+
/// ```
135+
#[unstable(feature = "unix_socket_abstract", issue = "42048")]
136+
pub fn bind_addr(socket_addr: &SocketAddr) -> io::Result<UnixDatagram> {
137+
unsafe {
138+
let socket = UnixDatagram::unbound()?;
139+
cvt(libc::bind(*socket.0.as_inner(), &socket_addr.addr as *const _ as *const _, socket_addr.len as _))?;
140+
Ok(socket)
141+
}
142+
}
143+
115144
/// Creates a Unix Datagram socket which is not bound to any address.
116145
///
117146
/// # Examples
@@ -156,7 +185,7 @@ impl UnixDatagram {
156185
Ok((UnixDatagram(i1), UnixDatagram(i2)))
157186
}
158187

159-
/// Connects the socket to the specified address.
188+
/// Connects the socket to the specified path address.
160189
///
161190
/// The [`send`] method may be used to send data to the specified address.
162191
/// [`recv`] and [`recv_from`] will only receive data from that address.
@@ -192,6 +221,35 @@ impl UnixDatagram {
192221
Ok(())
193222
}
194223

224+
/// Connects the socket to an address.
225+
///
226+
/// # Examples
227+
///
228+
/// ```no_run
229+
/// #![feature(unix_socket_abstract)]
230+
/// use std::os::unix::net::{UnixDatagram, SocketAddr};
231+
///
232+
/// fn main() -> std::io::Result<()> {
233+
/// let addr = SocketAddr::from_abstract_namespace(b"hidden")?; // Linux only
234+
/// let sock = UnixDatagram::unbound()?;
235+
/// match sock.connect_addr(&addr) {
236+
/// Ok(sock) => sock,
237+
/// Err(e) => {
238+
/// println!("Couldn't connect: {:?}", e);
239+
/// return Err(e)
240+
/// }
241+
/// };
242+
/// Ok(())
243+
/// }
244+
/// ```
245+
#[unstable(feature = "unix_socket_abstract", issue = "42048")]
246+
pub fn connect_addr(&self, socket_addr: &SocketAddr) -> io::Result<()> {
247+
unsafe {
248+
cvt(libc::connect(*self.0.as_inner(), &socket_addr.addr as *const _ as *const _, socket_addr.len))?;
249+
}
250+
Ok(())
251+
}
252+
195253
/// Creates a new independently owned handle to the underlying socket.
196254
///
197255
/// The returned `UnixDatagram` is a reference to the same socket that this
@@ -473,6 +531,40 @@ impl UnixDatagram {
473531
}
474532
}
475533

534+
/// Sends data on the socket to the specified [SocketAddr].
535+
///
536+
/// On success, returns the number of bytes written.
537+
///
538+
/// [SocketAddr]: crate::os::unix::net::SocketAddr
539+
///
540+
/// # Examples
541+
///
542+
/// ```no_run
543+
/// #![feature(unix_socket_abstract)]
544+
/// use std::os::unix::net::{UnixDatagram, SocketAddr};
545+
///
546+
/// fn main() -> std::io::Result<()> {
547+
/// let addr = SocketAddr::from_abstract_namespace(b"hidden")?;
548+
/// let sock = UnixDatagram::unbound()?;
549+
/// sock.send_to_addr(b"bacon egg and cheese", &addr).expect("send_to_addr function failed");
550+
/// Ok(())
551+
/// }
552+
/// ```
553+
#[unstable(feature = "unix_socket_abstract", issue = "42048")]
554+
pub fn send_to_addr(&self, buf: &[u8], socket_addr: &SocketAddr) -> io::Result<usize> {
555+
unsafe {
556+
let count = cvt(libc::sendto(
557+
*self.0.as_inner(),
558+
buf.as_ptr() as *const _,
559+
buf.len(),
560+
MSG_NOSIGNAL,
561+
&socket_addr.addr as *const _ as *const _,
562+
socket_addr.len,
563+
))?;
564+
Ok(count as usize)
565+
}
566+
}
567+
476568
/// Sends data on the socket to the socket's peer.
477569
///
478570
/// The peer address may be set by the `connect` method, and this method

library/std/src/os/unix/net/listener.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,40 @@ impl UnixListener {
8181
}
8282
}
8383

84+
/// Creates a new `UnixListener` bound to the specified [`socket address`].
85+
///
86+
/// [`socket address`]: crate::os::unix::net::SocketAddr
87+
///
88+
/// # Examples
89+
///
90+
/// ```no_run
91+
/// #![feature(unix_socket_abstract)]
92+
/// use std::os::unix::net::{UnixListener, SocketAddr};
93+
///
94+
/// fn main() -> std::io::Result<()> {
95+
/// let addr = SocketAddr::from_abstract_namespace(b"namespace")?; // Linux only
96+
/// let listener = match UnixListener::bind_addr(&addr) {
97+
/// Ok(sock) => sock,
98+
/// Err(err) => {
99+
/// println!("Couldn't bind: {:?}", err);
100+
/// return Err(err);
101+
/// }
102+
/// };
103+
/// Ok(())
104+
/// }
105+
/// ```
106+
#[unstable(feature = "unix_socket_abstract", issue = "42048")]
107+
pub fn bind_addr(socket_addr: &SocketAddr) -> io::Result<UnixListener> {
108+
unsafe {
109+
let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
110+
cvt(libc::bind(*inner.as_inner(), &socket_addr.addr as *const _ as *const _, socket_addr.len as _))?;
111+
cvt(libc::listen(*inner.as_inner(), 128))?;
112+
113+
Ok(UnixListener(inner))
114+
}
115+
}
116+
117+
84118
/// Accepts a new incoming connection to this listener.
85119
///
86120
/// This function will block the calling thread until a new Unix connection

library/std/src/os/unix/net/stream.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,37 @@ impl UnixStream {
104104
}
105105
}
106106

107+
/// Connects to the socket specified by [`address`].
108+
///
109+
/// [`address`]: crate::os::unix::net::SocketAddr
110+
///
111+
/// # Examples
112+
///
113+
/// ```no_run
114+
/// #![feature(unix_socket_abstract)]
115+
/// use std::os::unix::net::{UnixStream, SocketAddr};
116+
///
117+
/// fn main() -> std::io::Result<()> {
118+
/// let addr = SocketAddr::from_abstract_namespace(b"hidden")?; // Linux only
119+
/// match UnixStream::connect_addr(&addr) {
120+
/// Ok(sock) => sock,
121+
/// Err(e) => {
122+
/// println!("Couldn't connect: {:?}", e);
123+
/// return Err(e)
124+
/// }
125+
/// };
126+
/// Ok(())
127+
/// }
128+
/// ````
129+
#[unstable(feature = "unix_socket_abstract", issue = "42048")]
130+
pub fn connect_addr(socket_addr: &SocketAddr) -> io::Result<UnixStream> {
131+
unsafe {
132+
let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
133+
cvt(libc::connect(*inner.as_inner(), &socket_addr.addr as *const _ as *const _, socket_addr.len))?;
134+
Ok(UnixStream(inner))
135+
}
136+
}
137+
107138
/// Creates an unnamed pair of connected sockets.
108139
///
109140
/// Returns two `UnixStream`s which are connected to each other.

0 commit comments

Comments
 (0)