From 8be123ac363e19eea61244aaa7a86afcd3a30451 Mon Sep 17 00:00:00 2001 From: EnesKartal Date: Sat, 14 Nov 2026 15:16:35 +0300 Subject: [PATCH] Fix reading Unix addresses whose path fills all of sun_path On Linux, a socket bound to a 108-byte path reports an address length that includes the NUL terminator, which the kernel stores just past sun_path. Converting such an address to SocketAddrUnix, or formatting a SocketAddrAny holding it, indexed sun_path out of bounds and panicked in both backends. Only check for the terminator when it is inside sun_path. Fixes #1741. --- src/backend/libc/net/read_sockaddr.rs | 20 ++++++++++------- src/backend/linux_raw/net/read_sockaddr.rs | 6 ++++- tests/net/unix.rs | 26 ++++++++++++++++++++++ 3 files changed, 43 insertions(+), 9 deletions(-) diff --git a/src/backend/libc/net/read_sockaddr.rs b/src/backend/libc/net/read_sockaddr.rs index 5f8c48ec7..51eae0f25 100644 --- a/src/backend/libc/net/read_sockaddr.rs +++ b/src/backend/libc/net/read_sockaddr.rs @@ -217,15 +217,19 @@ pub(crate) fn read_sockaddr_unix(addr: &SocketAddrAny) -> Result Result(), bytes.len()) }; - assert_eq!(decode.sun_path[len - 1 - offsetof_sun_path], 0); + // A path that fills all of `sun_path` has no room for the NUL + // terminator; Linux stores it just past `sun_path`. + if bytes.len() < decode.sun_path.len() { + assert_eq!(decode.sun_path[bytes.len()], 0); + } SocketAddrUnix::new(bytes) } } diff --git a/tests/net/unix.rs b/tests/net/unix.rs index 57f52f0f8..567b16a49 100644 --- a/tests/net/unix.rs +++ b/tests/net/unix.rs @@ -1012,3 +1012,29 @@ fn test_long_named_address() { assert!(!name.is_unnamed()); } } + +/// Test that a bound pathname that fills all of `sun_path` can be read back. +/// Linux stores the NUL terminator just past `sun_path` and includes it in +/// the returned address length. +#[cfg(linux_kernel)] +#[test] +fn test_getsockname_long_named_address() { + let tmpdir = tempfile::tempdir().unwrap(); + let mut path = tmpdir.path().to_path_buf().into_os_string(); + path.push("/"); + let fill = 108 - path.len(); + path.push("a".repeat(fill)); + let path = std::path::PathBuf::from(path); + assert_eq!(path.as_os_str().len(), 108); + + let sock = socket(AddressFamily::UNIX, SocketType::DGRAM, None).unwrap(); + bind(&sock, &SocketAddrUnix::new(&path).unwrap()).unwrap(); + + let address = rustix::net::getsockname(&sock).unwrap(); + let _ = format!("{address:?}"); + let address = SocketAddrUnix::try_from(address).unwrap(); + assert_eq!( + address.path_bytes(), + Some(std::os::unix::ffi::OsStrExt::as_bytes(path.as_os_str())) + ); +}