Stream incorrectly reports write-only pipe (STDOUT) as readable
IMSoP opened this issue · comments
If you wrap a Stream object around a FIFO that is open only for writing, such as the standard output of a CLI script, it incorrectly reports it as "readable", but then errors when you try to read from it.
To reproduce, use this file:
<?php
require 'vendor/autoload.php';
$stream = new \Slim\Psr7\Stream(STDOUT);
if ( $stream->isReadable() ) {
echo "Stream claims to be readable; reading it...\n";
$stream->read(14);
}
else {
echo "Stream does not claim to be readable.\n";
}
Executed as php test.php
, it gives the expected output:
Stream does not claim to be readable.
But if the output is redirected to a pipe, e.g. with php test.php | cat
it fails:
Stream claims to be readable; reading it...
[26-Jan-2022 17:20:31 UTC] PHP Fatal error: Uncaught RuntimeException: Could not read from stream. in Slim-Psr7/src/Stream.php:343
Stack trace:
#0 Slim-Psr7/test.php(8): Slim\Psr7\Stream->read()
#1 {main}
thrown in Slim-Psr7/src/Stream.php on line 343
The problem is that isReadable()
always returns true
if isPipe()
returns true, rather than checking its actual mode. I'm not sure if this is just an optimisation which could be removed, or if there are different flags which need to be checked if it's a pipe.