Creating a unix domain socket with a particular mode?

When creating an ordinary file, it's possible to specify the mode of the new file.
Is something similar possible when creating a unix domain socket?

Specifically, I have code lines like these:

    let path = PathBuf::from("/var/run/axum/rust-test/socket");
    let uds = UnixListener::bind(path).unwrap();

I want to modify it so that the resulting file gets mode 0777.

Set the umask to zero before binding the socket. You need the libc crate for this.

use libc::umask;

let old_umask;
unsafe { old_umask = umask(0); }
let uds = UnixListener::bind(path)?;
unsafe { umask(old_umask); }

Thanks. Do you know why one has to resort to unsafe code just to set the umask of the process?

You are calling a C function. That's always unsafe.

There are crates that wrap the unsafe code in a safe interface. For example, the nix crate can do it.

The nix crate looks great, thanks. I browsed a little bit around nix' code, but I didn't figure out:
How does the wrapping make unsafe code safe? How does Rust know that it's suddenly safe? Is there a language construct which allows one to assert, that a piece of code is now to be considered safe?

That's what happens when you use an unsafe block in a non-unsafe function.

1 Like

Rust doesn't, you assert that the code is safe by wrapping it in an unsafe block. Yes it sounds a bit illogical; try looking at it as a trust_me_i_know_what_im_doing block.