@@ -131,7 +131,8 @@ impl SocketAddr {
131
131
///
132
132
/// # Errors
133
133
///
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.
135
136
///
136
137
/// # Examples
137
138
///
@@ -141,27 +142,35 @@ impl SocketAddr {
141
142
/// use std::path::Path;
142
143
///
143
144
/// # fn main() -> std::io::Result<()> {
144
- /// let address = SocketAddr::unix ("/path/to/socket")?;
145
+ /// let address = SocketAddr::from_path ("/path/to/socket")?;
145
146
/// assert_eq!(address.as_pathname(), Some(Path::new("/path/to/socket")));
146
147
/// # Ok(())
147
148
/// # }
148
149
/// ```
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
+ /// ```
149
159
#[ 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 >
151
161
where
152
162
P : AsRef < Path > ,
153
163
{
154
164
// SAFETY: All zeros is a valid representation for `sockaddr_un`.
155
165
let mut storage: libc:: sockaddr_un = unsafe { mem:: zeroed ( ) } ;
156
166
157
167
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 ( ) {
165
174
return Err ( io:: Error :: new (
166
175
io:: ErrorKind :: InvalidInput ,
167
176
"path must be shorter than SUN_LEN" ,
@@ -184,12 +193,7 @@ impl SocketAddr {
184
193
let base = & storage as * const _ as usize ;
185
194
let path = & storage. sun_path as * const _ as usize ;
186
195
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 ;
193
197
194
198
Ok ( SocketAddr { addr : storage, len : length as _ } )
195
199
}
0 commit comments