crystal-lang / crystal

The Crystal Programming Language
https://crystal-lang.org
Apache License 2.0
19.21k stars 1.61k forks source link

Fix: use `SOCK_CLOEXEC` with `FD_CLOEXEC` fallback #14672

Closed ysbaddaden closed 2 weeks ago

ysbaddaden commented 3 weeks ago

Harmonizes the implementations between Darwin and other POSIX platforms for the "close on exec" behavior.

When SOCK_CLOEXEC is available, we always use it in the socket, socketpair and accept4 syscalls. When SOCK_CLOEXEC isn't available, we don't delay to Socket#initialize_handle anymore to set FD_CLOEXEC for Darwin only, but immediately call fcntl to set it after the above syscalls.

The accept4 syscall is non-standard but widely available: Linux, all supported BSD, except for Darwin (obviously).

The patch also fixes an issue where TCP and UNIX client sockets didn't have FD_CLOEXEC on POSIX platforms... except for Darwin.

closes #14650

ysbaddaden commented 3 weeks ago

Follow up: we'll want to prevent fork when SOCK_CLOEXEC isn't available (i.e. Darwin only) with a readers-writer-lock, so we don't hit a race where thread 1 creates a socket while thread 2 forks then execs, which would leak the file descriptor to the executed process (oops).

Prior art: Go is doing that.

ysbaddaden commented 3 weeks ago

suggestion: add/rework specs.