Skip to content

Do not close a socket descriptor twice after a failed bind or connect - #25792

Open
lacatoire wants to merge 1 commit into
php:PHP-8.4from
lacatoire:fix/sockets-failed-bind-double-close-PHP-8.4
Open

lacatoire wants to merge 1 commit into
php:PHP-8.4from
lacatoire:fix/sockets-failed-bind-double-close-PHP-8.4

Conversation

@lacatoire

Copy link
Copy Markdown
Member

When bind(), connect() or listen() fails, socket_addrinfo_bind(), socket_addrinfo_connect() and socket_create_listen() close the descriptor, then destroy the new Socket, whose destructor closes the same descriptor again because bsd_socket is never reset. In a thread-safe build, another thread can get that descriptor number in between and lose it. This resets bsd_socket to -1 after each explicit close.

To reproduce

<?php
$ai = socket_addrinfo_lookup('127.0.0.1', '1', ['ai_socktype' => SOCK_STREAM, 'ai_family' => AF_INET]);
var_dump(@socket_addrinfo_connect($ai[0]));

Under strace -e trace=close, before (PHP 8.4.28):

close(5)                                = 0
close(5)                                = -1 EBADF (Bad file descriptor)

After: a single close(5). The added test checks that the failure paths still return false; the double close itself is only visible under strace.

On failure, socket_addrinfo_bind(), socket_addrinfo_connect() and
socket_create_listen() closed the descriptor, then destroyed the new
Socket, whose destructor closed the same descriptor again. In a
thread-safe build another thread could get that descriptor in between
and lose it. Reset bsd_socket after the explicit close.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants