Skip to content

Commit c1cd200

Browse files
committed
Rename SocketAddr::unix to from_path
And change it to disallow NULL bytes.
1 parent f2cdb57 commit c1cd200

File tree

1 file changed

+20
-16
lines changed

1 file changed

+20
-16
lines changed

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

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,8 @@ impl SocketAddr {
131131
///
132132
/// # Errors
133133
///
134-
/// Returns an error if the path is longer than `SUN_LEN`.
134+
/// Returns an error if the path is longer than `SUN_LEN` or if it contains
135+
/// NULL bytes.
135136
///
136137
/// # Examples
137138
///
@@ -141,27 +142,35 @@ impl SocketAddr {
141142
/// use std::path::Path;
142143
///
143144
/// # fn main() -> std::io::Result<()> {
144-
/// let address = SocketAddr::unix("/path/to/socket")?;
145+
/// let address = SocketAddr::from_path("/path/to/socket")?;
145146
/// assert_eq!(address.as_pathname(), Some(Path::new("/path/to/socket")));
146147
/// # Ok(())
147148
/// # }
148149
/// ```
150+
///
151+
/// Creating a `SocketAddr` with a NULL byte results in an error.
152+
///
153+
/// ```
154+
/// #![feature(unix_socket_creation)]
155+
/// use std::os::unix::net::SocketAddr;
156+
///
157+
/// assert!(SocketAddr::from_path("/path/with/\0/bytes").is_err());
158+
/// ```
149159
#[unstable(feature = "unix_socket_creation", issue = "65275")]
150-
pub fn unix<P>(path: P) -> io::Result<SocketAddr>
160+
pub fn from_path<P>(path: P) -> io::Result<SocketAddr>
151161
where
152162
P: AsRef<Path>,
153163
{
154164
// SAFETY: All zeros is a valid representation for `sockaddr_un`.
155165
let mut storage: libc::sockaddr_un = unsafe { mem::zeroed() };
156166

157167
let bytes = path.as_ref().as_os_str().as_bytes();
158-
let too_long = match bytes.first() {
159-
None => false,
160-
// linux abstract namespaces aren't null-terminated.
161-
Some(&0) => bytes.len() > storage.sun_path.len(),
162-
Some(_) => bytes.len() >= storage.sun_path.len(),
163-
};
164-
if too_long {
168+
if bytes.contains(&b'\0') {
169+
return Err(io::Error::new(
170+
io::ErrorKind::InvalidInput,
171+
"path can't contain null bytes",
172+
));
173+
} else if bytes.len() >= storage.sun_path.len() {
165174
return Err(io::Error::new(
166175
io::ErrorKind::InvalidInput,
167176
"path must be shorter than SUN_LEN",
@@ -184,12 +193,7 @@ impl SocketAddr {
184193
let base = &storage as *const _ as usize;
185194
let path = &storage.sun_path as *const _ as usize;
186195
let sun_path_offset = path - base;
187-
let length = sun_path_offset
188-
+ bytes.len()
189-
+ match bytes.first() {
190-
Some(&0) | None => 0,
191-
Some(_) => 1,
192-
};
196+
let length = sun_path_offset + bytes.len() + 1;
193197

194198
Ok(SocketAddr { addr: storage, len: length as _ })
195199
}

0 commit comments

Comments
 (0)