[php-src] PR #22235: Fix stream_context_set_option() mutating the default context
| From: | nicolas-grekas | Date: | Fri, 05 Jun 2026 16:07:03 +0000 |
| Subject: | [php-src] PR #22235: Fix stream_context_set_option() mutating the default context | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-36311@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/22235
Author: nicolas-grekas
### Summary
In 8.6-dev, calling
stream_context_set_option() on a stream opened **without an
explicit context** mutates the global **default** context, leaking the options into every other
context-less stream.
```php
$a = fopen('php://memory', 'r+');
stream_context_set_option($a, 'http', 'filename', 'test.txt');
$b = fopen('php://memory', 'r+');
var_dump(stream_context_get_options($b)); // 8.6: ['http' => ['filename'
=> 'test.txt']], 8.5: []
var_dump(stream_context_get_options(stream_context_get_default())); // 8.6: polluted, 8.5: []
```
### Root cause
Regression from #20524 (stream errors RFC, commit f2b371e747d). It added this to
_php_stream_open_wrapper_ex():
```c
if (stream->ctx == NULL && context != NULL && !persistent) {
php_stream_context_set(stream, context);
}
```
php_stream_context_from_zval() substitutes FG(default_context) when no
context is passed, so a context-less fopen() now attaches the default context to the
stream **by reference**. A later stream_context_set_option($stream, ...) resolves the
stream's context via decode_context_param() and mutates that shared default
context.
### Fix
Attach only an explicitly provided context, never the implicitly substituted default:
```c
if (stream->ctx == NULL && context != NULL && context != FG(default_context)
&& !persistent) {
```
The intent of the original line (attaching explicit contexts to wrappers like php://
that do not self-attach) is preserved. Stream errors are unaffected:
php_stream_error_operation_end() already falls back to FG(default_context)
when the stream has no context, and
error_mode/error_store/error_handler cannot be set on the
default context anyway.
### Tests
Added ext/standard/tests/streams/stream_context_set_option_no_default_leak.phpt. The
full ext/standard/tests/streams, ext/standard/tests/http and
context-related file/network suites pass.