Skip to content

Commit

Permalink
Rename SocketAddr::unix to from_path
Browse files Browse the repository at this point in the history
And change it to disallow NULL bytes.
  • Loading branch information
Thomasdezeeuw committed Jan 24, 2022
1 parent f2cdb57 commit c1cd200
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions library/std/src/os/unix/net/addr.rs
Expand Up @@ -131,7 +131,8 @@ impl SocketAddr {
///
/// # Errors
///
/// Returns an error if the path is longer than `SUN_LEN`.
/// Returns an error if the path is longer than `SUN_LEN` or if it contains
/// NULL bytes.
///
/// # Examples
///
Expand All @@ -141,27 +142,35 @@ impl SocketAddr {
/// use std::path::Path;
///
/// # fn main() -> std::io::Result<()> {
/// let address = SocketAddr::unix("/path/to/socket")?;
/// let address = SocketAddr::from_path("/path/to/socket")?;
/// assert_eq!(address.as_pathname(), Some(Path::new("/path/to/socket")));
/// # Ok(())
/// # }
/// ```
///
/// Creating a `SocketAddr` with a NULL byte results in an error.
///
/// ```
/// #![feature(unix_socket_creation)]
/// use std::os::unix::net::SocketAddr;
///
/// assert!(SocketAddr::from_path("/path/with/\0/bytes").is_err());
/// ```
#[unstable(feature = "unix_socket_creation", issue = "65275")]
pub fn unix<P>(path: P) -> io::Result<SocketAddr>
pub fn from_path<P>(path: P) -> io::Result<SocketAddr>
where
P: AsRef<Path>,
{
// SAFETY: All zeros is a valid representation for `sockaddr_un`.
let mut storage: libc::sockaddr_un = unsafe { mem::zeroed() };

let bytes = path.as_ref().as_os_str().as_bytes();
let too_long = match bytes.first() {
None => false,
// linux abstract namespaces aren't null-terminated.
Some(&0) => bytes.len() > storage.sun_path.len(),
Some(_) => bytes.len() >= storage.sun_path.len(),
};
if too_long {
if bytes.contains(&b'\0') {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path can't contain null bytes",
));
} else if bytes.len() >= storage.sun_path.len() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path must be shorter than SUN_LEN",
Expand All @@ -184,12 +193,7 @@ impl SocketAddr {
let base = &storage as *const _ as usize;
let path = &storage.sun_path as *const _ as usize;
let sun_path_offset = path - base;
let length = sun_path_offset
+ bytes.len()
+ match bytes.first() {
Some(&0) | None => 0,
Some(_) => 1,
};
let length = sun_path_offset + bytes.len() + 1;

Ok(SocketAddr { addr: storage, len: length as _ })
}
Expand Down

0 comments on commit c1cd200

Please sign in to comment.