Commit cd402519619 for php
commit cd4025196199ab5090a8e8a5d7d4183047acd198
Author: lacatoire <la.catoire@gmail.com>
Date: Thu Nov 26 10:18:03 2026 +0100
Fix fd leak in compress.zlib:// when gzdopen() fails (#25794)
The compress.zlib:// wrapper passes a duplicate file descriptor to
gzdopen(). If gzdopen() rejects the mode, the wrapper closes the inner
stream but leaks the duplicate. Close the duplicate on failure.
Closes #25794
diff --git a/NEWS b/NEWS
index 2767862cb8c..a5b81877ebc 100644
--- a/NEWS
+++ b/NEWS
@@ -340,6 +340,8 @@ PHP NEWS
- Zlib:
. Fixed gzwrite() and fwrite() on a compress.zlib:// stream reporting a
failed write as a successful write of 0 bytes. (lacatoire)
+ . Fixed a file descriptor leak when opening a compress.zlib:// stream
+ fails. (lacatoire)
19 Nov 2026, PHP 8.4.28
diff --git a/ext/zlib/tests/compress_zlib_gzdopen_fd_leak.phpt b/ext/zlib/tests/compress_zlib_gzdopen_fd_leak.phpt
new file mode 100644
index 00000000000..f06eac31c0e
--- /dev/null
+++ b/ext/zlib/tests/compress_zlib_gzdopen_fd_leak.phpt
@@ -0,0 +1,35 @@
+--TEST--
+compress.zlib:// does not leak a file descriptor when gzdopen() rejects the mode
+--EXTENSIONS--
+zlib
+--SKIPIF--
+<?php
+if (!is_dir('/proc/self/fd')) die('skip requires /proc/self/fd');
+?>
+--FILE--
+<?php
+$file = __DIR__ . '/compress_zlib_gzdopen_fd_leak.tmp';
+$countFds = fn() => count(scandir('/proc/self/fd'));
+
+$before = $countFds();
+for ($i = 0; $i < 10; $i++) {
+ var_dump(@touch('compress.zlib://' . $file));
+}
+var_dump($countFds() - $before);
+?>
+--CLEAN--
+<?php
+@unlink(__DIR__ . '/compress_zlib_gzdopen_fd_leak.tmp');
+?>
+--EXPECT--
+bool(false)
+bool(false)
+bool(false)
+bool(false)
+bool(false)
+bool(false)
+bool(false)
+bool(false)
+bool(false)
+bool(false)
+int(0)
diff --git a/ext/zlib/zlib_fopen_wrapper.c b/ext/zlib/zlib_fopen_wrapper.c
index a30ae2fa169..69677f87897 100644
--- a/ext/zlib/zlib_fopen_wrapper.c
+++ b/ext/zlib/zlib_fopen_wrapper.c
@@ -178,9 +178,11 @@ php_stream *php_stream_gzopen(php_stream_wrapper *wrapper, const char *path, con
php_socket_t fd;
if (SUCCESS == php_stream_cast(innerstream, PHP_STREAM_AS_FD, (void **) &fd, REPORT_ERRORS)) {
+ int gz_fd = dup(fd);
+
self = emalloc(sizeof(*self));
self->stream = innerstream;
- self->gz_file = gzdopen(dup(fd), mode);
+ self->gz_file = gzdopen(gz_fd, mode);
if (self->gz_file) {
zval *zlevel = context ? php_stream_context_get_option(context, "zlib", "level") : NULL;
@@ -195,6 +197,8 @@ php_stream *php_stream_gzopen(php_stream_wrapper *wrapper, const char *path, con
}
gzclose(self->gz_file);
+ } else if (gz_fd >= 0) {
+ close(gz_fd);
}
efree(self);