socket: use accept4 when available

Linux, *BSD, and Solaris support accept4 system call that enables the
caller to assign additional flags and save some extra system calls. It
can come in handy when O_NONBLOCK or/and FD_CLOEXEC is/are required on a
socket after being accepted.

Ref:
https://man7.org/linux/man-pages/man2/accept.2.html
https://man.freebsd.org/cgi/man.cgi?query=accept4
https://man.dragonflybsd.org/?command=accept&section=2
https://man.openbsd.org/accept.2
https://man.netbsd.org/accept.2
https://docs.oracle.com/cd/E88353_01/html/E37843/accept4-3c.html
https://www.gnu.org/software/gnulib/manual/html_node/accept4.html

Closes #16979
This commit is contained in:
Andy Pan 2025-04-05 23:55:32 +08:00 committed by Daniel Stenberg
parent 2f5e4e0db4
commit 3d02872be7
No known key found for this signature in database
GPG key ID: 5CC908FDB71E12C2
8 changed files with 52 additions and 2 deletions

View file

@ -2144,7 +2144,12 @@ static CURLcode cf_tcp_accept_connect(struct Curl_cfilter *cf,
if(0 == getsockname(ctx->sock, (struct sockaddr *) &add, &size)) {
size = sizeof(add);
#ifdef HAVE_ACCEPT4
s_accepted = accept4(ctx->sock, (struct sockaddr *) &add, &size,
SOCK_NONBLOCK | SOCK_CLOEXEC);
#else
s_accepted = accept(ctx->sock, (struct sockaddr *) &add, &size);
#endif
}
if(CURL_SOCKET_BAD == s_accepted) {
@ -2153,7 +2158,9 @@ static CURLcode cf_tcp_accept_connect(struct Curl_cfilter *cf,
}
infof(data, "Connection accepted from server");
#ifndef HAVE_ACCEPT4
(void)curlx_nonblock(s_accepted, TRUE); /* enable non-blocking */
#endif
/* Replace any filter on SECONDARY with one listening on this socket */
ctx->listening = FALSE;
ctx->accepted = TRUE;