From 47f205d68c871c1dc8da9441bd0f632fc8eecb0a Mon Sep 17 00:00:00 2001 From: David Carlier Date: Wed, 19 Jun 2024 19:19:53 +0100 Subject: [PATCH] ext/sockets: socket_accept setting fcntl's FD_CLOEXEC on unixes. mainly for scenarios when pcntl_fork/pcntl_exec are involved so when the latter is executed, we avoid unwarranted effects with the file descriptors, instead the socket will be closed on success. --- ext/sockets/sockets.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/ext/sockets/sockets.c b/ext/sockets/sockets.c index 284cc02beaaba..a0cb5a25a7de7 100644 --- a/ext/sockets/sockets.c +++ b/ext/sockets/sockets.c @@ -269,6 +269,28 @@ static bool php_accept_connect(php_socket *in_sock, php_socket *out_sock, struct return 0; } +#if !defined(PHP_WIN32) + /** + * accept4 could had been used but not all platforms support it (e.g. Haiku, solaris < 11.4, ...) + * win32, not having any concept of child process, has no need to address it. + */ + int mode; + + if ((mode = fcntl(out_sock->bsd_socket, F_GETFD)) < 0) { + PHP_SOCKET_ERROR(out_sock, "unable to get fcntl mode on the socket", errno); + return 0; + } + + int cloexec = (mode | FD_CLOEXEC); + + if (mode != cloexec) { + if (fcntl(out_sock->bsd_socket, F_SETFD, cloexec) < 0) { + PHP_SOCKET_ERROR(out_sock, "unable to set cloexec mode on the socket", errno); + return 0; + } + } +#endif + out_sock->error = 0; out_sock->blocking = 1; out_sock->type = la->sa_family;