Skip to content

Commit

Permalink
Use stream_get_contents instead of fread for ResourceInputStream
Browse files Browse the repository at this point in the history
This fixes an issue with TLS streams: https://github.com/amphp/artax/issues/138.

We still use  for UDP, because stream_get_contents might read multiple packages there if I'm not mistaken.
  • Loading branch information
kelunik committed Oct 8, 2017
1 parent 0064341 commit 9484664
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/ResourceInputStream.php
Expand Up @@ -27,14 +27,15 @@ final class ResourceInputStream implements InputStream {

/**
* @param resource $stream Stream resource.
* @param int $chunkSize Chunk size per `fread()` operation.
* @param int $chunkSize Chunk size per read operation.
*/
public function __construct($stream, int $chunkSize = self::DEFAULT_CHUNK_SIZE) {
if (!\is_resource($stream) || \get_resource_type($stream) !== 'stream') {
throw new \Error("Expected a valid stream");
}

$meta = \stream_get_meta_data($stream);
$isUdp = $meta["stream_type"] === "udp_socket";

if (\strpos($meta["mode"], "r") === false && \strpos($meta["mode"], "+") === false) {
throw new \Error("Expected a readable stream");
Expand All @@ -48,9 +49,12 @@ public function __construct($stream, int $chunkSize = self::DEFAULT_CHUNK_SIZE)
$deferred = &$this->deferred;
$readable = &$this->readable;

$this->watcher = Loop::onReadable($this->resource, static function ($watcher, $stream) use (&$deferred, &$readable, $chunkSize) {
// Error reporting suppressed since fread() produces a warning if the stream has been shutdown
$data = @\fread($stream, $chunkSize);
$this->watcher = Loop::onReadable($this->resource, static function ($watcher, $stream) use (&$deferred, &$readable, $chunkSize, $isUdp) {
if ($isUdp) {
$data = @\fread($stream, $chunkSize);
} else {
$data = @\stream_get_contents($stream, $chunkSize);
}

\assert($data !== false, "Trying to read from a previously fclose()'d resource. Do NOT manually fclose() resources the loop still has a reference to.");
if ($data === '' && \feof($stream)) {
Expand Down

0 comments on commit 9484664

Please sign in to comment.