Skip to content

Fix the maximum path length allowable on MacOS, NetBSD, and DragonFlyBSD for Unix Domain Sockets - #161149

Open
asder8215 wants to merge 7 commits into
rust-lang:mainfrom
asder8215:bsd_sockaddr_un
Open

asder8215 wants to merge 7 commits into
rust-lang:mainfrom
asder8215:bsd_sockaddr_un

Conversation

@asder8215

@asder8215 asder8215 commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

View all comments

This PR fixes the issue described in #160684. In doing so, it also refactors the SockAddr API to support a max-sized sockaddr_un struct in a unix platform-agnostic way.

For example, on MacOS, NetBSD, and DragonFlyBSD the maximum path length for a Unix Domain sockets on those platforms is actually 253 bytes. We can't rely on the length of the sun_path field in libc::sockaddr_un:

pub struct sockaddr_un {
        pub sun_len: u8,
        pub sun_family: sa_family_t,
        pub sun_path: [c_char; 104],
}

As it's acknowledged within each of the aforementioned BSD platform that the 104 bytes number is a gag number and people can actually malloc a larger size than sizeof(libc::sockaddr_un) with a path name up to 253 bytes (excluding nul). I assume the sun_path field is more akin to a flexible array member in C.

To clarify, the max valid characters a socket path can have on certain unix-based platforms are as follows:

  • Darwin (apple), NetBSD, and DragonFlyBSD: 253 bytes
  • OpenBSD/FreeBSD: 103 bytes (nothing changed for these platforms because it's sun_path is 104 bytes, including +1 for the nul byte)
  • Solaris/Illumos: 1023 bytes (though each path component are limited to 255 bytes still)
  • AIX: 1023 bytes (which is already the fixed sized length of the sun_path array in libc::sockaddr_un)

I was also looking at this hacker news forum as well, and according to the user wahern, the bind/connect max path for Unix domain sockets on Solaris/AIX is 1023. Currently, we received confirmation from @psumbera here that Solaris/Illumos does accept a path of up to 1023 non-nul bytes for Unix Domain sockets. Unfortunately, I couldn't confirm this behavior for AIX because the source code is closed-source and I don't have access to these OSes. If someone has access to one of these OSes and can confirm this, that could be a future PR to adjust the Path limits for AIX.

All other platforms still considers their maximum socket path size based on the prescribed length of the sun_path field in libc::sockaddr_un.

Implementation Details

Since we can't use libc::sockaddr_un to reliably contain the max socket path for Darwin, NetBSD, and DragonFlyBSD, this PR changes from using libc::sockaddr_un to a constant-sized zeroed buffer that captures the max size of a Unix domain socket (what their maximum 'sockaddr_un' could be) on each platform (i.e [0; SOCK_MAX_SIZE]).

To clarify some things about SOCK_MAX_SIZE, which is defined as follows:

/// The max socket address size in bytes
const SOCK_MAX_SIZE: usize = cfg_select! {
    any(target_vendor = "apple", target_os = "dragonfly") => {
        // Apple and DragonFly utilize `SOCK_MAXADDRLEN` to define
        // the maximum size that the `sockaddr_un` struct could be.
        // SOCK_MAXADDRLEN = 255 on these platforms, and it's based on
        // sizeof(sa_len) (a u8) + sizeof(sun_family) (a u8) + 253 bytes
        // (excluding nul). We add +1 for nul byte just in case.
        // See https://github.com/rust-lang/rust/issues/160684
        libc::SOCK_MAXADDRLEN as usize + 1
    }
    any(target_os = "netbsd") => {
        // NetBSD uses `UCHAR_MAX` (essentially a `u8::MAX`) + 1 as defined by `sockaddr_big` here:
        // https://github.com/IIJ-NetBSD/netbsd-src/blob/cc2b5d89fa44/sys/sys/socket.h#L272-L287
        libc::c_uchar::MAX as usize + 1
    }
    any(target_os = "illumos", target_os = "solaris") => {
        // On top of a two byte header for the socket family, Solaris and Illumos has
        // a `sun_path` that can be dynamically allocated and holds up to MAXPATHLEN
        // (which is set to PATH_MAX) bytes, including the nul-terminating byte.
        // See this comment: https://github.com/rust-lang/rust/pull/161149#issuecomment-7003143698
        SUN_PATH_OFFSET + libc::PATH_MAX as usize
    }
    _ => {
        // All other platforms max socket address size is based on
        // the size of their sockaddr_un struct
        size_of::<libc::sockaddr_un>()
    }
};

// A check to see if it's safe to downcast SOCK_MAX_SIZE to libc::socklen_t
// (a u32)
const _: () = assert!(SOCK_MAX_SIZE <= libc::socklen_t::MAX as usize);

*Note: libc::SOCK_MAXADDRLEN is 255 on MacOS/DragonFly, it includes a byte for the sun_len, a byte for sun_family, and 253 bytes for sun_path.

We add +1 for the maximum size of a socket struct in MacOS, DragonFlyBSD, and NetBSD just as insurance to include the nul byte when we're given a maximum valid path size of 253 bytes. While the length of the path is technically encoded into the sun_len of the sockaddr_un struct in BSD-based platforms (where they can subtract the value sun_len holds by the offset to sun_path), not all the BSD platforms that allow a path up to 253 bytes may approach copying or accessing the path in this manner, and could check for if the nul byte exists at the end of sun_path/provided path. Platforms that utilize libc::sockaddr_un already account for the nul byte within the prescribed length of their sun_path field, so that furthers the point that we want make sure a nul byte exists even when we reach the max 253 bytes for our path.

On a separate note, one difference to point out between the definition of libc::sockaddr_un struct in BSD-based platforms and Linux is that Linux's libc::sockaddr_un does not have a sun_len, it only contains a u16 sun_family, and constant sized sun_path field. Since this wasn't done prior to this PR, we ensure that the area that should contain the sun_len field contains the size of the entire socket (i.e. sun_len, sun_family, and sun_path). This is in consideration without the trailing nul byte from the path field, which makes sense because if our socket struct has a path of 253 bytes, it is impossible for sun_len to account for that as it is limited between 0-255 since it is a u8 field.

Our SocketAddr API now looks as follows (credit to @tgross35 for most of this API design):

#[derive(Clone)]
#[repr(C)]
pub(super) struct SockaddrBuf {
    /// Size of the socket address, `sun_family` and `sun_path`
    /// fields from `libc::sockaddr_un` included
    len: libc::socklen_t,
    /// Stack allocated buffer that contains full size of what `libc::sockaddr_un`
    /// could be (as `sun_path` field defined for `sockaddr_un` does not represent
    /// the maximum path length of a Unix Domain socket name)
    buf: [u8; SOCK_MAX_SIZE],
    /// Make it sound to cast the struct to/from a `sockaddr_un`
    align: [libc::sockaddr_un; 0],
}

impl SockaddrBuf {
    /* API for use in Rust */

    /// This returns an empty Unix Domain socket address with a
    /// length value containing the current size of the `sockaddr_un`
    pub(super) fn default() -> SockaddrBuf { ... }

    /// Extracts the `sun_path` value from the socket address buffer.
    fn path(&self) -> &[u8] { ... }

    /// Sets the socket address path for `sockaddr_un` in `SocketaddrBuf`.
    fn set_path(&mut self, bytes: &[u8]) -> io::Result<()>  { ... }

    /// Extracts the `sun_path` value from the abstract socket address buffer (excludes initial
    /// nul byte).
    fn abstract_path(&self) -> &[u8] { ... }

    /// Sets the abstract socket address path for `sockaddr_un` in `SocketaddrBuf`.
    fn set_abstract_path(&mut self, bytes: &[u8]) -> io::Result<()> { ... }

    /// Extracts the `sun_family` value from the socket address buffer.
    fn sun_family(&self) -> libc::sa_family_t { ... }

    /* API for use in sockets in abstract namespace + interop with C */

    /// Types passed to libc calls that read a socket address.
    pub(super) fn as_libc_input(&self) -> (*const libc::sockaddr, libc::socklen_t) { ... }

    /// Types passed to libc calls that write a socket address. Length is first set to the
    /// max allowed.
    ///
    /// Note that using this API _must_ be followed by a call to `update_from_libc`.
    // Note that returning two raw pointers from a single `&mut self` function call rather than
    // two `&mut self -> *mut T` function calls is required to pass Miri with stacked borrows.
    pub(super) fn as_max_libc_output(&mut self) -> (*mut libc::sockaddr, *mut libc::socklen_t) { ... }

    /// Some platforms encode things differently. Call this after a `libc` call to adjust length
    /// and validate as needed.
    pub(super) fn update_from_libc(&mut self) -> io::Result<()> { ... }
}

#[derive(Clone)]
#[stable(feature = "unix_socket", since = "1.10.0")]
pub struct SocketAddr {
    pub(super) sock: SockaddrBuf,
}

impl SocketAddr {
...
    /// Constructs a Unix Domain socket address from a given `Path`
    pub(super) fn from_path(path: &Path) -> io::Result<SocketAddr> { ... }
...
}

SockaddrBuf acts as an internal helper struct that has its own API to access + mutate its len field, implicit sun_path and sun_family fields within the buffer, and is able to pass itself as mutable or const inputs to libc syscalls within UnixDatagram, UnixListener, UnixStream, and a couple of the socket ancillary functions. The whole goal with the SockaddrBuf API is to mask the [0; SOCK_MAX_SIZE] buffer field and have other parts of Rust's Unix Domain socket library utilize methods that returns reasonable/understandable outputs or it's clear to know what you're modifying (e.g. SockaddrBuf::set_path to set the sun_path field of the [0; SOCK_MAX_SIZE] buffer).

Only one new function is introduced on SockAddr, which is SockAddr::from_path; this function does essentially the same thing as pub(super) fn sockaddr_un that we had before (the error checking and construction of SockAddr is done in SockAddr::from_path, but the mutation of the sun_path field in [0; SOCK_MAX_SIZE] is done through SockaddrBuf). A lot of other refactoring with methods and functions in SockAddr has been done to keep everything done mostly through SockaddrBuf. The internal SockAddr::from_parts function was removed since it wasn't necessary with being able to create a default blank SockaddrBuf struct and being able to modify that struct through the SockaddrBuf's API.

Other changes made

  • long_path updated to also show that on MacOS/DragonFlyBSD/NetBSD would trigger the InvalidInput case from giving it a Path longer than 253 bytes. Previously, this test was failing on apple platforms because the long path provided was a fixed string with 108 characters and that was never going to trigger the InvalidInput case on apple platforms. The os error it returned was that socket path did not exist (as the test does not create the socket via bind), not that the file path was too long.
  • created a new test test_unix_datagram_max_path that confirms on all platforms that it'll take a path with the maximum number of valid character (e.g. 107 on Linux, 103 on OpenBSD/FreeBSD, and 253 on DragonFlyBSD/Darwin/NetBSD)
  • Refactoring done for Unix Domain sockets' Unix*::bind/Unix*::connect/Unix*::peer_addr/Unix*::local_addr/UnixDatagram::send_to, etc. to adjust to SocketaddrBuf's API.
  • Removed sock_addr_without_trailing_nul and sock_addr_pathname_fills_sun_path tests. It was there in place to test for behavior in SockAddr::from_part, but now that SockAddr::from_part has been removed and a good chunk of SockAddr's API revolves around SockAddrBuf's API, which is tested through the current tests we have, these tests are no longer necessary.

A couple other resources that substantiate information about the maximum unix domain socket address path is 253 bytes:

cc @tgross35

@rustbot rustbot added O-unix Operating system: Unix-like S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels Aug 15, 2026
@rustbot

rustbot commented Aug 15, 2026

Copy link
Copy Markdown
Collaborator

r? @Mark-Simulacrum

rustbot has assigned @Mark-Simulacrum.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

Why was this reviewer chosen?

The reviewer was selected based on:

  • Owners of files modified in this PR: @ChrisDenton, libs
  • @ChrisDenton, libs expanded to 13 candidates
  • Random selection from 6 candidates

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@Mark-Simulacrum Mark-Simulacrum left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if we can add some unit tests (not sure we actually would run those in CI, but better than nothing) that assert we got the right value? E.g., we would pass paths with the expected max length + 1 character + null byte and confirm the kernel used the path we expected, without the extra character. For platforms with a mandatory null byte we should be able to confirm in unit tests that the kernel indeed expects it, I think?

View changes since this review

Comment thread library/std/src/os/unix/net/addr.rs Resolved
Comment thread library/std/src/os/unix/net/addr.rs Resolved
Comment thread library/std/src/os/unix/net/addr.rs Resolved
Comment thread library/std/src/os/unix/net/addr.rs Resolved
@Mark-Simulacrum Mark-Simulacrum added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Aug 22, 2026
@asder8215

asder8215 commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor Author

@Mark-Simulacrum I added a test based around using SUN_PATH_MAX_LEN. The test tests whether we can bind to a socket to the maximally allowed path size (253 bytes on certain BSD platforms, otherwise libc::sockaddr_un's sun_path length).

This should confirm whether the kernel bind call succeeded on a path with that maximally allowed path length. Let me know if there are any other tests you want me to specifically add.

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Aug 23, 2026
Comment thread library/std/src/os/unix/net/addr.rs Resolved
Comment thread library/std/src/os/unix/net/addr.rs Resolved
Comment thread library/std/src/os/unix/net/addr.rs Resolved
@Mark-Simulacrum Mark-Simulacrum added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Aug 30, 2026
@asder8215

Copy link
Copy Markdown
Contributor Author

@rustbot ready

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Sep 2, 2026
@Mark-Simulacrum

Copy link
Copy Markdown
Member

Can you reply to my comments in the GitHub UI? I think you addressed them only partially with the push?

@bors try jobs=various,distbsd,aarch64-apple-1,dist--apple

@rust-bors

This comment has been minimized.

rust-bors Bot pushed a commit that referenced this pull request Sep 5, 2026
Fix the maximum path length allowable on MacOS, NetBSD, and DragonFlyBSD for Unix Domain Sockets


try-job: *various*
try-job: dist*bsd
try-job: aarch64-apple-1
try-job: dist-*-apple
@asder8215

Copy link
Copy Markdown
Contributor Author

Can you reply to my comments in the GitHub UI?

Are you talking about the commit message? Or the review comments?

I can update the commit message for former, but the latter on my end it shows that I've replied to them all.

@Mark-Simulacrum

Copy link
Copy Markdown
Member

#161149 (comment) seems to be without reply. #161149 (comment) also looks partially unaddressed.

In order to properly review and update the code here, building a mental model for what the limits are and how platforms behave is useful. Right now the pieces I've pulled from your comments are (some of these are maybe incorrect):

  • Some platforms require a len encoded into the structure we pass, either u8 or u16 in size
  • Some platforms null-terminate the path passed (possibly required, possibly not required if the full space is used?)
  • Some platforms allow larger structures (e.g., you found the Solaris post referencing ~1023 byte path)

But that isn't reflected coherently in a single place in the code or in the PR description as far as I can tell. The newly added comment on the max path length partially reflects this... but it's missing discussion of why the +1 and whether null bytes matter or not. The gap on the static assert (that maybe will fail CI, not sure if we have that target in the runners I launched?) touches on that as well.

It sounds to me like if we want to be as close to the limits as possible, we need to have a constant or function that goes through the checks needed -- I think this gets part or all of the way there from an implementation perspective, but it's just as important to build that clear narrative as getting the raw behavior right.

@asder8215

Copy link
Copy Markdown
Contributor Author

Since this was mostly reviewed by Trevor already, I hope you don't mind me reassigning this PR to him.

r? @tgross35

@rustbot rustbot assigned tgross35 and unassigned Mark-Simulacrum Oct 19, 2026
@rustbot

rustbot commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator

tgross35 is currently at their maximum review capacity.
They may take a while to respond.

@rust-bors

This comment has been minimized.

@rustbot

This comment has been minimized.

@rust-bors

This comment has been minimized.

@rustbot

This comment has been minimized.

kawaz added a commit to kawaz/sockat-rs that referenced this pull request Nov 18, 2026
) が merge されたら、std にそのまま渡す長さを追従させる
@asder8215

Copy link
Copy Markdown
Contributor Author

Hi @xingxue-ibm and @psumbera. I was wondering if either of you know about the max length of a unix domain socket address path that can be contained within AIX/Solaris' sockaddr_un structs?

Context is that it looks like MacOS/NetBSD/DragonFlyBSD supports binding/connecting to a socket with up to 253 valid characters. Their sockaddr_un structs can be dynamically allocated, treating the last sun_path field kind of like a flexible array member even though it has a static size (assume it's just due to legacy code conventions?). In this hacker news forum, it mentions that the bind/connect max path for AIX/Solaris unix domain sockets is 1023 chars. Is that value correct?

@psumbera

Copy link
Copy Markdown
Contributor

For Solaris, I can confirm that 1023 bytes is the maximum pathname length, excluding the terminating NUL. I checked the current Solaris 11.4 ON sources: although sockaddr_un declares sun_path[108] (explicitly described as a "gag"), sockfs treats an AF_UNIX address as variable-sized and allocates/checks it using MAXPATHLEN, which is 1024 bytes including the terminating NUL.

So Rust can use a Solaris buffer of SUN_PATH_OFFSET + PATH_MAX bytes (1026: two-byte family plus 1023 pathname bytes plus NUL), rather than size_of::<sockaddr_un>(). One test caveat: a single pathname component is still limited to 255 bytes, so a 1023-byte test path would need nested directories. I can only confirm Solaris, not AIX.

@asder8215

asder8215 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

@psumbera I was taking a look at the link associated with MAXPATHLEN, and I just wanted to check in to ask about what the +1 in here is for?:

if (so->so_family == AF_UNIX) {
		so->so_mode |= SM_FDPASSING | SM_OPTDATA;
		if (sti->sti_addr_size == -1) {
			/* MAXPATHLEN + soun_family + nul termination */
			sti->sti_addr_size = (t_scalar_t)(MAXPATHLEN +
			    sizeof (short) + 1);
		}

This would be 1024 + 2 + 1 = 1027, right? If the MAXPATHLEN includes the nul terminating byte at the end of the sockaddr_un struct (which my understanding is that the path is the last field of the sockaddr struct, so the struct is safely nul-terminated too), is there any reason for the +1 or is that an extraneous byte?

// 1023 bytes with a max path component byte of 255.
#[cfg(any(target_os = "illumos", target_os = "solaris"))]
#[test]
fn test_solaris_datagram_max_path() {

@asder8215 asder8215 Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tgross35 whenever you can, could you run bors try on this Illumos/Solaris test to verify that this test passes?

View changes since the review

@rust-log-analyzer

This comment has been minimized.

…ddr::default, SocketAddr::set_path, SocketAddr:set_len, SocketAddr::sun_family_from_addr), use safer methods (e.g. copy_from_slice over ptr::copy_nonoverlapping), and updated a few tests in unix/net/tests
… API to utilize SockaddrBuf as a medium to pass as a mutable or const input to C socket interop calls
…ask construction and access to certain fields of the sockaddr_un through SockaddrBuf::abstract_path and SockaddrBuf::set_abstract_path
…mentations as well as minor changes or refactoring unix/net/listener.rs + unix/net/ancillar.rs
@rustbot

rustbot commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed.

Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers.

…anch containing the correct max socket address size/path length

On Solaris/Illumos, their Unix Domain sockets are allowed to be binded/connected to a path of up to PATH_MAX - 1 non-nul bytes. A caveat to keep in mind is that the max length of a path component on these platforms is still 255 non-nul bytes; a separate test has been made exclusively for Solaris/Illumos to test the succesful binding of a socket to a PATH_MAX - 1 path length
@xingxue-ibm

Copy link
Copy Markdown
Contributor

Hi @xingxue-ibm and @psumbera. I was wondering if either of you know about the max length of a unix domain socket address path that can be contained within AIX/Solaris' sockaddr_un structs?

Context is that it looks like MacOS/NetBSD/DragonFlyBSD supports binding/connecting to a socket with up to 253 valid characters. Their sockaddr_un structs can be dynamically allocated, treating the last sun_path field kind of like a flexible array member even though it has a static size (assume it's just due to legacy code conventions?). In this hacker news forum, it mentions that the bind/connect max path for AIX/Solaris unix domain sockets is 1023 chars. Is that value correct?

On AIX, the maximum Unix domain socket pathname length is 1023 bytes including the terminating NUL byte, matching PATH_MAX = 1023. The AIX /usr/include/sys/un.h has the following:

  struct sockaddr_un {
      uchar_t     sun_len;        /* sockaddr len including null */
      sa_family_t sun_family;     /* AF_UNIX */
      char        sun_path[1023]; /* changed from 104 to PATH_MAX to support long user names */
  };

In the Rust libc crate, libc::sockaddr_un on AIX is defined with sun_path: [c_char; 1023].

@asder8215

Copy link
Copy Markdown
Contributor Author

Okay, so I think this refactor/redesign for SocketAddr covers all the Unix platforms that use this API.

@tgross35 lmk if there's anything else I should refactor or change here. Also, I'm not sure if this PR requires a libs discussion/nominated label since it does change behavior for MacOS/NetBSD/DragonFlyBSD/Solaris, so just in case:

@rustbot label +I-libs-nominated

@rustbot rustbot added the I-libs-nominated Nominated for discussion during a libs team meeting. label Nov 24, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

I-libs-nominated Nominated for discussion during a libs team meeting. O-unix Operating system: Unix-like S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants