This commit is contained in:
Javier Casares 2026-11-03 16:45:29 +00:00
commit 600aac43b6
12 changed files with 13867 additions and 164910 deletions

View file

@ -0,0 +1,431 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use GuzzleHttp\Psr7\StreamWrapper;
use GuzzleHttp\Psr7\Utils;
use Psr\Http\Message\StreamInterface;
/**
* Decodes the chunked transfer coding of a response body read from the
* unfiltered transport stream, with the framing rules libcurl applies.
*
* Each read returns the decoded bytes that are already available, waiting on
* the transport only when there are none, so the transport's idle timeout
* governs every wait. The body ends as soon as the last chunk and trailer
* section have been decoded, without another transport read. A body that ends
* early or has malformed framing fails the read once the bytes decoded before
* the fault have been returned, and every later read fails the same way.
*
* @internal
*/
final class ChunkedBodyStream implements StreamInterface
{
use NonSerializableTrait;
use StreamDecoratorTrait;
private const READ_SIZE = 8192;
private const MAX_SIZE_DIGITS = 17;
// libcurl's trailer line and header section limits.
private const MAX_TRAILER_LINE_LENGTH = 4093;
private const MAX_TRAILER_SECTION_LENGTH = 307200;
private const SIZE = 0;
private const SIZE_LINE = 1;
private const DATA = 2;
private const DATA_END = 3;
private const TRAILER = 4;
private const TRAILER_CR = 5;
private const FINAL_CR = 6;
private const DONE = 7;
private StreamInterface $stream;
private string $buffer = '';
private int $offset = 0;
private int $state = self::SIZE;
private string $digits = '';
private int $remaining = 0;
private string $line = '';
private int $trailerLength = 0;
private int $position = 0;
private ?\RuntimeException $failure = null;
private bool $detachable = true;
public function __construct(StreamInterface $stream)
{
$this->stream = $stream;
}
public function __clone()
{
// A clone shares the transport, so detaching it would break this body.
$this->detachable = false;
}
public function read(int $length): string
{
if ($this->failure !== null) {
throw $this->failure;
}
if ($length < 0) {
throw new \RuntimeException('Length parameter cannot be negative');
}
do {
$data = $this->decode($length);
} while ($data === '' && $length > 0 && !$this->eof() && $this->fill());
$this->position = TransferByteCounter::add(
$this->position,
\strlen($data),
'Response body exceeds the maximum integer size supported on this platform'
);
return $data;
}
public function eof(): bool
{
return $this->state === self::DONE;
}
/**
* @return mixed
*/
public function getMetadata(?string $key = null)
{
// A failed body has not timed out, whatever a stale flag on the
// transport says, so callers report the failure itself.
if ($this->failure !== null && $key === 'timed_out') {
return false;
}
$metadata = $this->stream->getMetadata($key);
if ($this->failure !== null && $key === null && \is_array($metadata)) {
$metadata['timed_out'] = false;
}
return $metadata;
}
public function tell(): int
{
return $this->position;
}
public function getSize(): ?int
{
return null;
}
public function isSeekable(): bool
{
return false;
}
public function seek(int $offset, int $whence = \SEEK_SET): void
{
throw new \RuntimeException('Cannot seek a chunked response body');
}
public function isWritable(): bool
{
return false;
}
public function write(string $string): int
{
throw new \RuntimeException('Cannot write to a chunked response body');
}
public function close(): void
{
$this->buffer = '';
$this->offset = 0;
$this->detachable = false;
$this->stream->close();
}
public function detach()
{
if (!$this->detachable) {
return null;
}
if ($this->state === self::DONE) {
return $this->stream->detach();
}
if ($this->buffer === '' && $this->failure === null) {
$resource = $this->stream->detach();
if (\is_resource($resource)) {
// Nothing has been decoded yet, so PHP's filter can take over.
\stream_filter_append($resource, 'dechunk', \STREAM_FILTER_READ);
}
return $resource;
}
// PHP's filter cannot resume part way through a chunk, so hand the
// decoder over to a resource that keeps decoding the rest of the body.
$decoder = clone $this;
$this->buffer = '';
$this->offset = 0;
$this->detachable = false;
$this->stream = Utils::streamFor('');
$this->stream->detach();
return StreamWrapper::getResource($decoder);
}
/**
* Appends what the transport has available to the buffer, waiting for at
* least one byte.
*/
private function fill(): bool
{
$data = $this->stream->read(self::READ_SIZE);
if ($data === '') {
if (!$this->stream->eof()) {
return false;
}
$this->failure = new \RuntimeException('Response body ended before the chunked body was complete');
throw $this->failure;
}
$this->buffer = \substr($this->buffer, $this->offset).$data;
$this->offset = 0;
return true;
}
/**
* Decodes up to $length bytes from the buffer, and any framing after them,
* so the end of the body is noticed without another transport read.
*/
private function decode(int $length): string
{
$data = '';
try {
while ($this->offset < \strlen($this->buffer) && $this->state !== self::DONE) {
if ($this->state === self::DATA) {
$take = \min($this->remaining, $length - \strlen($data), \strlen($this->buffer) - $this->offset);
if ($take === 0) {
break;
}
$data .= \substr($this->buffer, $this->offset, $take);
$this->offset += $take;
$this->remaining -= $take;
if ($this->remaining === 0) {
$this->state = self::DATA_END;
}
} elseif ($this->state === self::SIZE) {
$chunks = $this->digits === '' ? $this->decodeChunks($length - \strlen($data)) : null;
if ($chunks === null) {
$this->decodeSize();
} else {
$data .= $chunks;
}
} elseif ($this->state === self::SIZE_LINE) {
$this->skipSizeLine();
} elseif ($this->state === self::DATA_END) {
$this->decodeDataEnd();
} else {
$this->decodeTrailer();
}
}
} catch (\RuntimeException $e) {
$this->failure = $e;
if ($data === '') {
throw $e;
}
}
return $data;
}
/**
* Decodes buffered chunks in bulk, up to $length bytes, and leaves the
* state machine at the first chunk that needs more care. Returns null when
* it consumes nothing.
*/
private function decodeChunks(int $length): ?string
{
$buffer = $this->buffer;
$end = \strlen($buffer);
$offset = $this->offset;
$data = '';
while (true) {
// Up to seven digits keep the size an int on every platform.
$digits = \strspn($buffer, '0123456789abcdefABCDEF', $offset, 8);
if ($digits === 0 || $digits === 8) {
break;
}
$lineEnd = \strpos($buffer, "\n", $offset + $digits);
if ($lineEnd === false) {
break;
}
$size = (int) \hexdec(\substr($buffer, $offset, $digits));
$offset = $lineEnd + 1;
if ($size === 0) {
$this->state = self::TRAILER;
break;
}
if ($size > $length || $offset + $size > $end) {
$this->remaining = $size;
$this->state = self::DATA;
break;
}
$data .= \substr($buffer, $offset, $size);
$length -= $size;
$offset += $size;
if ($offset + 1 < $end && $buffer[$offset] === "\r" && $buffer[$offset + 1] === "\n") {
$offset += 2;
} elseif ($offset < $end && $buffer[$offset] === "\n") {
++$offset;
} else {
$this->state = self::DATA_END;
break;
}
}
if ($offset === $this->offset) {
return null;
}
$this->offset = $offset;
return $data;
}
private function decodeSize(): void
{
$count = \strspn($this->buffer, '0123456789abcdefABCDEF', $this->offset);
$this->digits .= \substr($this->buffer, $this->offset, $count);
$this->offset += $count;
if (\strlen($this->digits) > self::MAX_SIZE_DIGITS) {
throw new \RuntimeException('Invalid chunked response body: invalid chunk size');
}
if ($this->offset === \strlen($this->buffer)) {
return;
}
if ($this->digits === '') {
throw new \RuntimeException('Invalid chunked response body: invalid chunk size');
}
$significant = \ltrim($this->digits, '0');
if (\strlen($significant) > 16 || (\strlen($significant) === 16 && $significant[0] > '7')) {
throw new \RuntimeException('Invalid chunked response body: invalid chunk size');
}
$size = \hexdec($this->digits);
if (!\is_int($size)) {
throw new \OverflowException('Chunk size exceeds the maximum integer size supported on this platform');
}
$this->digits = '';
$this->remaining = $size;
$this->state = self::SIZE_LINE;
}
private function skipSizeLine(): void
{
// Chunk extensions, and anything else up to the line feed, are ignored
// the way libcurl ignores them.
$end = \strpos($this->buffer, "\n", $this->offset);
if ($end === false) {
$this->offset = \strlen($this->buffer);
return;
}
$this->offset = $end + 1;
$this->state = $this->remaining === 0 ? self::TRAILER : self::DATA;
}
private function decodeDataEnd(): void
{
$this->offset += \strspn($this->buffer, "\r", $this->offset);
if ($this->offset === \strlen($this->buffer)) {
return;
}
if ($this->buffer[$this->offset] !== "\n") {
throw new \RuntimeException('Invalid chunked response body: missing CRLF after chunk data');
}
++$this->offset;
$this->state = self::SIZE;
}
private function decodeTrailer(): void
{
if ($this->state !== self::TRAILER) {
if ($this->buffer[$this->offset] !== "\n") {
throw new \RuntimeException('Invalid chunked response body: invalid trailer section');
}
++$this->offset;
$this->state = $this->state === self::FINAL_CR ? self::DONE : self::TRAILER;
return;
}
$count = \strcspn($this->buffer, "\r\n", $this->offset);
$this->line .= \substr($this->buffer, $this->offset, $count);
$this->offset += $count;
$this->trailerLength += $count;
if (\strlen($this->line) > self::MAX_TRAILER_LINE_LENGTH || $this->trailerLength > self::MAX_TRAILER_SECTION_LENGTH) {
throw new \RuntimeException('Invalid chunked response body: invalid trailer section');
}
if ($this->offset === \strlen($this->buffer)) {
return;
}
$carriageReturn = $this->buffer[$this->offset] === "\r";
++$this->offset;
if ($this->line === '') {
$this->state = $carriageReturn ? self::FINAL_CR : self::DONE;
return;
}
if (\strpos($this->line, "\0") !== false || \strpos($this->line, ':') === false) {
throw new \RuntimeException('Invalid chunked response body: invalid trailer section');
}
$this->line = '';
if ($carriageReturn) {
$this->state = self::TRAILER_CR;
}
}
}

View file

@ -20,4 +20,13 @@ final class Clock
{
return \hrtime(true) / 1e9;
}
public static function sleep(int $microseconds): void
{
while ($microseconds > 0) {
$slice = \min($microseconds, 0xFFFFFFFF);
\usleep($slice);
$microseconds -= $slice;
}
}
}

View file

@ -91,7 +91,9 @@ final class CurlFactory implements CurlFactoryInterface
];
private const CURL_RESPONSE_TRANSFER_ERRORS = [
8 => true, // CURLE_WEIRD_SERVER_REPLY
18 => true, // CURLE_PARTIAL_FILE
23 => true, // CURLE_WRITE_ERROR from libcurl's content decoders
61 => true, // CURLE_BAD_CONTENT_ENCODING
];

View file

@ -88,7 +88,7 @@ final class CurlHandler
HostValidator::assertRequestHost($request);
if (isset($options['delay'])) {
\usleep((int) ($options['delay'] * 1000));
Clock::sleep((int) ($options['delay'] * 1000));
}
// A Multiplexing::NONE request option holds unconditionally here:

View file

@ -319,7 +319,7 @@ final class CurlMultiHandler
// Never null: assigned below before any wait can invoke this.
/** @var Promise<ResponseInterface, mixed> $promise */
if ($easy->deferredSettled || !P\Is::pending($promise)) {
if ($easy->deferredSettled || !P\State::isPending($promise)) {
return;
}
@ -773,7 +773,7 @@ final class CurlMultiHandler
$this->addHandleToMulti($id, $entry['easy']);
} catch (\Throwable $e) {
$rejection = $this->discardPendingRequest($id, $entry, $e);
if (P\Is::pending($entry['deferred'])) {
if (P\State::isPending($entry['deferred'])) {
$entry['deferred']->reject($rejection);
}
}
@ -880,7 +880,7 @@ final class CurlMultiHandler
// If there are no transfers, then sleep for the next delay,
// unless ready queue work could change what is pending.
if (!$this->active && $this->delays && $queue->isEmpty()) {
\usleep($this->timeToNext());
Clock::sleep($this->timeToNext());
}
$this->tick();
}
@ -912,7 +912,7 @@ final class CurlMultiHandler
// If the transfer is delayed, then sleep until it is due, unless
// ready queue work could cancel or replace it first.
if (!$this->active && isset($this->delays[$id]) && $queue->isEmpty()) {
\usleep($this->timeToNext());
Clock::sleep($this->timeToNext());
}
$this->tickFor($id, $waitToken);
}
@ -1028,7 +1028,7 @@ final class CurlMultiHandler
'attached' => !empty($entry['attached']),
];
if ($explicit && P\Is::pending($entry['deferred'])) {
if ($explicit && P\State::isPending($entry['deferred'])) {
$this->captureFailure($failure, function () use ($entry): void {
$entry['deferred']->reject(new HandlerClosedException('The cURL multi handler was closed before the transfer completed.', $entry['easy']->request));
});
@ -1097,7 +1097,7 @@ final class CurlMultiHandler
});
}
if ($reject && P\Is::pending($entry['deferred'])) {
if ($reject && P\State::isPending($entry['deferred'])) {
$this->captureFailure($failure, function () use ($entry): void {
$entry['deferred']->reject(new HandlerClosedException('The cURL multi handler was closed before the transfer completed.', $entry['easy']->request));
});
@ -1249,7 +1249,7 @@ final class CurlMultiHandler
// throw. User code may have settled it directly; a settled
// promise must not abort the rest of the snapshot.
$rejection = $this->discardPendingRequest($id, $entry, $e);
if (P\Is::pending($entry['deferred'])) {
if (P\State::isPending($entry['deferred'])) {
$entry['deferred']->reject($rejection);
}
}
@ -1394,7 +1394,7 @@ final class CurlMultiHandler
if ($displaced !== null) {
// Never silently discard a tracked entry; settle it first.
unset($this->handles[$id], $this->delays[$id], $this->deferredAdds[$id]);
if (P\Is::pending($displaced['deferred'])) {
if (P\State::isPending($displaced['deferred'])) {
$message = \sprintf('cURL multi handler transfer %d was displaced by another request that reused its native cURL handle ID.', $id);
$response = $displaced['easy']->response;
$failure = $response !== null
@ -1538,7 +1538,7 @@ final class CurlMultiHandler
try {
$result = CurlFactory::finish($this, $entry['easy'], $this->factory);
} catch (\Throwable $e) {
if (P\Is::pending($entry['deferred'])) {
if (P\State::isPending($entry['deferred'])) {
$entry['easy']->deferredSettled = true;
$entry['deferred']->reject($e);
}
@ -1546,7 +1546,7 @@ final class CurlMultiHandler
continue;
}
if (P\Is::pending($entry['deferred'])) {
if (P\State::isPending($entry['deferred'])) {
$entry['easy']->deferredSettled = true;
$entry['deferred']->resolve($result);
}

View file

@ -13,14 +13,11 @@ use Psr\Http\Message\StreamInterface;
* Decorates the transport stream of a buffered response so every read
* observes the wall-clock deadline of the "timeout" request option.
*
* The transport resource must be in non-blocking mode: PHP's filtered
* stream reads (chunked and compressed responses) otherwise block until
* the full requested length arrives, so a deadline check between reads
* never runs while a server keeps sending small pieces of data. Reads
* return whatever bytes are available and poll briefly for more, so the
* deadline is checked between packets rather than between buffers. The
* wait is a bounded sleep because stream_select() cannot watch a stream
* that carries a filter.
* The transport resource must be in non-blocking mode: a blocking read waits
* for data up to the transport's own timeout, so a deadline check between reads
* never runs while the server stalls. Reads return whatever bytes are available
* and poll briefly for more, so the deadline is checked between packets rather
* than between buffers.
*
* @internal
*/
@ -37,8 +34,6 @@ final class DeadlineSourceStream implements StreamInterface
private ?float $readTimeout;
private bool $timedOut = false;
/**
* @param StreamInterface $stream Transport stream in non-blocking mode.
* @param float $deadline Deadline based on Clock::now().
@ -58,8 +53,6 @@ final class DeadlineSourceStream implements StreamInterface
while (true) {
$remaining = $this->deadline - Clock::now();
if ($remaining <= 0) {
$this->timedOut = true;
throw new TimeoutException('Unable to read from stream: timed out');
}
@ -76,8 +69,6 @@ final class DeadlineSourceStream implements StreamInterface
$idleStart = $now;
}
if ($this->readTimeout !== null && $now - $idleStart >= $this->readTimeout) {
$this->timedOut = true;
throw new TimeoutException('Unable to read from stream: timed out');
}
@ -88,27 +79,4 @@ final class DeadlineSourceStream implements StreamInterface
\usleep((int) \ceil($wait * 1e6));
}
}
/**
* Reports the deadline timeout through the timed_out metadata: reads on
* a decoding layer above this stream surface as a generic read failure,
* and its timeout recovery consults this stream's metadata to classify
* the failure. The transport itself never reports timed_out while in
* non-blocking mode.
*
* @return mixed
*/
public function getMetadata(?string $key = null)
{
if ($key === 'timed_out') {
return $this->timedOut || $this->stream->getMetadata($key) === true;
}
$metadata = $this->stream->getMetadata($key);
if ($key === null && \is_array($metadata) && $this->timedOut) {
$metadata['timed_out'] = true;
}
return $metadata;
}
}

View file

@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
/**
* Ends a streamed response body at its declared Content-Length.
*
* Reads never consume bytes beyond the response message, and the body reaches
* EOF without waiting for the server to close the connection. A transport that
* ends before the declared length fails the read instead of looking like a
* complete body.
*
* @internal
*/
final class DeclaredLengthStream implements StreamInterface
{
use NonSerializableTrait;
use StreamDecoratorTrait;
private StreamInterface $stream;
private int $remaining;
private ?\RuntimeException $failure = null;
public function __construct(StreamInterface $stream, int $declaredLength)
{
$this->stream = $stream;
$this->remaining = $declaredLength;
}
public function __clone()
{
// Detaching a clone must not detach this body's transport.
$this->stream = clone $this->stream;
}
public function eof(): bool
{
return $this->remaining === 0;
}
public function isSeekable(): bool
{
return false;
}
public function seek(int $offset, int $whence = \SEEK_SET): void
{
throw new \RuntimeException('Cannot seek a response body bounded by its declared Content-Length');
}
/**
* @return mixed
*/
public function getMetadata(?string $key = null)
{
// A failed body has not timed out, whatever a stale flag on the
// transport says, so callers report the failure itself.
if ($this->failure !== null && $key === 'timed_out') {
return false;
}
$metadata = $this->stream->getMetadata($key);
if ($this->failure !== null && $key === null && \is_array($metadata)) {
$metadata['timed_out'] = false;
}
return $metadata;
}
public function read(int $length): string
{
if ($length < 0) {
throw new \RuntimeException('Length parameter cannot be negative');
}
if ($this->failure !== null) {
throw $this->failure;
}
if ($length === 0 || $this->remaining === 0) {
return '';
}
$data = $this->stream->read(\min($length, $this->remaining));
if ($data === '' && $this->stream->eof()) {
$this->failure = new \RuntimeException('Response body ended before the declared Content-Length was reached');
throw $this->failure;
}
$this->remaining -= \strlen($data);
return $data;
}
}

View file

@ -164,7 +164,9 @@ final class HeaderProcessor
* @param array<string, string[]> $headers
*
* @throws \RuntimeException when Content-Length is malformed, conflicting,
* or combined with Transfer-Encoding
* or combined with Transfer-Encoding, or when a
* transfer coding is unsupported or follows
* chunked on the same field line
*/
public static function validateResponseFraming(
string $method,
@ -188,9 +190,58 @@ final class HeaderProcessor
throw new \RuntimeException('A response must not contain both Content-Length and Transfer-Encoding');
}
self::parseTransferEncoding($headers);
return $length;
}
/**
* Returns whether the response uses the chunked transfer coding.
*
* Guzzle never asks for a transfer coding, so like libcurl 8.14 and newer
* it accepts only identity and chunked, with nothing but chunked after
* chunked on the same field line. Empty list elements are ignored.
*
* @param array<string, string[]> $headers
*
* @throws \RuntimeException when a coding is unsupported or follows chunked
* on the same field line
*/
public static function parseTransferEncoding(array $headers): bool
{
$chunked = false;
foreach ($headers as $name => $values) {
if (!Psr7\Utils::caselessEquals((string) $name, 'Transfer-Encoding')) {
continue;
}
foreach ($values as $value) {
$afterChunked = false;
foreach (\explode(',', $value) as $coding) {
$coding = \trim($coding, " \t");
if ($coding === '') {
continue;
}
if (Psr7\Utils::caselessEquals($coding, 'chunked')) {
$chunked = true;
$afterChunked = true;
} elseif ($afterChunked) {
throw new \RuntimeException('Invalid Transfer-Encoding response header: chunked is not the final transfer coding');
} elseif (!Psr7\Utils::caselessEquals($coding, 'identity')) {
throw new \RuntimeException(\sprintf(
'Invalid Transfer-Encoding response header: unsupported transfer coding "%s"',
Psr7\DiagnosticValue::escape($coding)
));
}
}
}
}
return $chunked;
}
/**
* Removes every case-insensitive occurrence of a header and returns all
* removed values in their original field order.

View file

@ -0,0 +1,330 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Psr7\StreamWrapper;
use GuzzleHttp\Psr7\Utils;
use Psr\Http\Message\StreamInterface;
/**
* Inflates a gzip or deflate encoded response body as the encoded bytes arrive.
*
* Unlike the zlib.inflate stream filter, a read returns the bytes decoded so
* far instead of waiting to fill the requested length, and invalid compressed
* data always fails the read. As with libcurl, data after the compressed
* stream, beyond up to 4 bytes after raw deflate data, fails the read that
* follows the last decoded byte.
*
* @internal
*/
final class InflateBodyStream implements StreamInterface
{
use NonSerializableTrait;
private const CHUNK_SIZE = 8192;
private const INVALID_DATA = 'Unable to decode the response body: invalid gzip or deflate data';
private const TRAILING_DATA = 'Unable to decode the response body: unexpected data after the compressed stream';
private ?StreamInterface $stream;
private bool $deflate;
/** @var \InflateContext|resource|null */
private $context;
private string $header = '';
private string $buffer = '';
private int $offset = 0;
private int $position = 0;
private bool $finished = false;
private int $trailingAllowance = 0;
private bool $detachable = true;
private ?\RuntimeException $error = null;
/**
* @param bool $deflate Whether the body is labelled "deflate", which also
* accepts raw deflate data like libcurl does.
*/
public function __construct(StreamInterface $stream, bool $deflate = false)
{
$this->stream = $stream;
$this->deflate = $deflate;
}
public function __toString(): string
{
return $this->getContents();
}
public function getContents(): string
{
return Utils::copyToString($this);
}
public function close(): void
{
$stream = $this->stream;
$this->release();
if ($stream !== null) {
$stream->close();
}
}
public function detach()
{
if ($this->stream === null || !$this->detachable) {
return null;
}
// Hand the decoder over to a resource that keeps yielding decoded
// bytes. That decoder cannot be detached again, so casting the resource
// to a descriptor fails instead of recursing.
$stream = clone $this;
$stream->detachable = false;
$this->release();
return StreamWrapper::getResource($stream);
}
public function getSize(): ?int
{
return null;
}
public function tell(): int
{
$this->attached();
return $this->position;
}
public function eof(): bool
{
$stream = $this->attached();
// A failed body never ends, so resource readers see the failure
// instead of a clean end of the stream.
return $this->error === null && $this->offset === \strlen($this->buffer) && $stream->eof();
}
public function isSeekable(): bool
{
return false;
}
public function seek(int $offset, int $whence = \SEEK_SET): void
{
throw new \RuntimeException('Stream is not seekable');
}
public function rewind(): void
{
$this->seek(0);
}
public function isWritable(): bool
{
return false;
}
public function write(string $string): int
{
throw new \RuntimeException('Cannot write to a non-writable stream');
}
public function isReadable(): bool
{
return $this->stream !== null && $this->stream->isReadable();
}
public function read(int $length): string
{
$stream = $this->attached();
if ($length < 0) {
throw new \RuntimeException('Length parameter cannot be negative');
}
if ($length === 0) {
return '';
}
while ($this->offset === \strlen($this->buffer)) {
if ($this->error !== null) {
throw $this->error;
}
$encoded = $stream->read(self::CHUNK_SIZE);
if ($encoded === '') {
return '';
}
if ($this->finished) {
if ($this->allowTrailing(\strlen($encoded))) {
continue;
}
throw $this->fail(self::TRAILING_DATA);
}
$this->buffer = $this->inflate($encoded);
$this->offset = 0;
}
// Slice by offset, since a single inflate_add() call can return
// megabytes of highly compressible data.
$data = (string) \substr($this->buffer, $this->offset, $length);
$this->offset += \strlen($data);
$this->position = TransferByteCounter::add(
$this->position,
\strlen($data),
'Response body exceeds the maximum integer size supported on this platform'
);
return $data;
}
/**
* @return mixed
*/
public function getMetadata(?string $key = null)
{
if ($this->stream === null) {
return $key === null ? [] : null;
}
// A decoding failure is not a timeout, even when Windows leaves the
// transport's timed_out flag set after a read drains PHP's buffer.
if ($key === 'timed_out' && $this->error !== null) {
return false;
}
$metadata = $this->stream->getMetadata($key);
if ($key === null && $this->error !== null && \is_array($metadata)) {
$metadata['timed_out'] = false;
}
return $metadata;
}
private function inflate(string $encoded, ?int $encoding = null): string
{
$retry = false;
if ($this->context === null) {
$this->header .= $encoded;
if (\strlen($this->header) < 2) {
return '';
}
$encoded = $this->header;
$this->header = '';
if (!\function_exists('inflate_init')) {
throw $this->fail('Unable to decode the response body: the zlib extension is not loaded');
}
// inflate_init() has no automatic header detection, so pick the
// format the way zlib does for the window bits 15 + 32 that the
// zlib.inflate filter is given.
$encoding = $encoding ?? (\strncmp($encoded, "\x1f\x8b", 2) === 0 ? \ZLIB_ENCODING_GZIP : \ZLIB_ENCODING_DEFLATE);
$retry = $this->deflate && $encoding === \ZLIB_ENCODING_DEFLATE;
$context = \inflate_init($encoding);
if ($context === false) {
throw $this->fail(self::INVALID_DATA);
}
$this->context = $context;
}
$readBefore = \inflate_get_read_len($this->context);
// Application error handlers also see @-suppressed warnings, so keep
// the warning inflate_add() emits before returning false from them.
\set_error_handler(static function (): bool {
return true;
});
try {
$decoded = \inflate_add($this->context, $encoded);
} finally {
\restore_error_handler();
}
if ($decoded === false) {
// Like libcurl, decode deflate data that zlib rejects in the first
// call as raw deflate, which may be followed by up to 4 unknown
// bytes such as the checksum of a zlib stream missing its header.
if ($retry) {
$this->context = null;
$this->trailingAllowance = 4;
return $this->inflate($encoded, \ZLIB_ENCODING_RAW);
}
throw $this->fail(self::INVALID_DATA);
}
$this->finished = \inflate_get_status($this->context) === \ZLIB_STREAM_END;
if ($this->finished) {
$consumed = \inflate_get_read_len($this->context) - $readBefore;
if ($consumed < 0) {
// zlib counts input in an unsigned long, which wraps at 4 GiB
// on Windows and 32-bit builds.
$consumed += 0x100000000;
}
if (!$this->allowTrailing(\strlen($encoded) - (int) $consumed)) {
// Throw only after the bytes decoded so far have been read.
$this->fail(self::TRAILING_DATA);
}
}
return $decoded;
}
private function allowTrailing(int $length): bool
{
if ($length > $this->trailingAllowance) {
return false;
}
$this->trailingAllowance -= $length;
return true;
}
private function attached(): StreamInterface
{
if ($this->stream === null) {
throw new \RuntimeException('Stream is detached');
}
return $this->stream;
}
private function release(): void
{
$this->stream = null;
$this->context = null;
$this->buffer = '';
$this->offset = 0;
}
private function fail(string $message): \RuntimeException
{
return $this->error = new \RuntimeException($message);
}
}

View file

@ -102,7 +102,7 @@ final class MockHandler implements \Countable
}
if (isset($options['delay']) && \is_numeric($options['delay'])) {
\usleep((int) ($options['delay'] * 1000));
Clock::sleep((int) ($options['delay'] * 1000));
}
if (isset($options['on_stats']) && !\is_callable($options['on_stats'])) {

View file

@ -105,10 +105,6 @@ final class StreamHandler
*/
private const DEFAULT_IDLE_TIMEOUT_MS = 60000;
private array $lastHeaders = [];
private ?float $lastDeadline = null;
private ?\Throwable $onStatsException = null;
private string $transportSharingMode;
@ -180,7 +176,7 @@ final class StreamHandler
// Sleep if there is a delay specified.
if (isset($options['delay'])) {
\usleep((int) ($options['delay'] * 1000));
Clock::sleep((int) ($options['delay'] * 1000));
}
$multiplex = $options['multiplex'] ?? null;
@ -234,11 +230,17 @@ final class StreamHandler
$request = $request->withHeader('Content-Length', (string) \strlen($body));
}
$deadline = null;
$stream = $this->createStream($request, $options, $body, $deadline);
$headers = \stream_get_meta_data($stream)['wrapper_data'];
return $this->createResponse(
$request,
$options,
$this->createStream($request, $options, $body),
$startTime
$stream,
\is_array($headers) ? $headers : [],
$startTime,
$deadline
);
} catch (\InvalidArgumentException $e) {
throw $e;
@ -392,13 +394,11 @@ final class StreamHandler
#[\SensitiveParameter]
array $options,
$stream,
?float $startTime
#[\SensitiveParameter]
array $hdrs,
?float $startTime,
?float $deadline
): PromiseInterface {
$hdrs = $this->lastHeaders;
$this->lastHeaders = [];
$deadline = $this->lastDeadline;
$this->lastDeadline = null;
try {
[$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs);
} catch (\Throwable $e) {
@ -408,8 +408,10 @@ final class StreamHandler
$canHaveBody = HeaderProcessor::responseCanHaveBody($request->getMethod(), $status);
$framingFailure = null;
$declaredLength = null;
$chunked = false;
try {
$declaredLength = HeaderProcessor::validateResponseFraming($request->getMethod(), $status, $headers);
$chunked = $canHaveBody && HeaderProcessor::parseTransferEncoding($headers);
if (empty($options['stream'])) {
HeaderProcessor::assertContentLengthWithinPlatformLimit($declaredLength);
}
@ -417,26 +419,35 @@ final class StreamHandler
$framingFailure = $e;
}
if ($framingFailure === null) {
try {
$headers = $this->decodeChunkedResponse($headers, $stream, $canHaveBody);
} catch (\RuntimeException $e) {
$framingFailure = $e;
}
if ($chunked) {
HeaderProcessor::removeHeader('Transfer-Encoding', $headers);
} elseif (!$canHaveBody) {
$headers = self::removeChunkedTransferCoding($headers);
}
$streamFactory = self::requireStreamFactory($options[RequestOptions::STREAM_FACTORY] ?? new Psr7\HttpFactory());
$responseFactory = self::requireResponseFactory($options[RequestOptions::RESPONSE_FACTORY] ?? new Psr7\HttpFactory());
// Wrap the transport resource with the configured stream factory, and
// decorate buffered transfers with the deadline source before optional
// content decoding layers an InflateStream on top, so every read that
// pulls from the transport observes the deadline.
// decorate buffered transfers with the deadline source before framing
// and optional content decoding layer on top, so every read that pulls
// from the transport observes the deadline.
$resource = $stream;
$stream = $streamFactory->createStreamFromResource($stream);
if ($framingFailure === null && $deadline !== null && empty($options['stream'])) {
$stream = self::createDeadlineSource($stream, $resource, $deadline, $options);
}
if ($chunked || !empty($options['stream'])) {
$stream = new TransportStream($stream);
}
if ($chunked) {
$stream = new ChunkedBodyStream($stream);
} elseif (!empty($options['stream'])) {
$length = HeaderProcessor::contentLengthToInt($declaredLength);
if ($length !== null) {
$stream = new DeclaredLengthStream($stream, $length);
}
}
$encodedBody = null;
if ($framingFailure === null) {
@ -633,21 +644,15 @@ final class StreamHandler
}
/**
* Applies the HTTP wrapper's normal chunked-response handling.
* Removes Transfer-Encoding values that start with chunked from a response
* that cannot have a body, as PHP's HTTP wrapper did.
*
* @param array<string, string[]> $headers
* @param resource $stream
* @param bool $decodeBody Whether to attach the dechunk filter
*
* @return array<string, string[]>
*
* @throws \RuntimeException when the dechunk filter cannot be attached
*/
private function decodeChunkedResponse(array $headers, $stream, bool $decodeBody): array
private static function removeChunkedTransferCoding(array $headers): array
{
$decodedHeaders = $headers;
$decode = false;
foreach ($headers as $name => $values) {
if (!Psr7\Utils::caselessEquals((string) $name, 'Transfer-Encoding')) {
continue;
@ -655,33 +660,19 @@ final class StreamHandler
$remaining = [];
foreach ($values as $value) {
// Match PHP's legacy auto_decode prefix check so moving the
// filter does not change which responses are dechunked.
if (Psr7\Utils::caselessEquals(\substr($value, 0, 7), 'chunked')) {
$decode = true;
} else {
if (!Psr7\Utils::caselessEquals(\substr($value, 0, 7), 'chunked')) {
$remaining[] = $value;
}
}
if ($remaining === []) {
unset($decodedHeaders[$name]);
unset($headers[$name]);
} else {
$decodedHeaders[$name] = $remaining;
$headers[$name] = $remaining;
}
}
if (!$decode) {
return $headers;
}
if ($decodeBody) {
$this->createResource(static function () use ($stream) {
return \stream_filter_append($stream, 'dechunk', \STREAM_FILTER_READ);
});
}
return $decodedHeaders;
return $headers;
}
/**
@ -707,7 +698,7 @@ final class StreamHandler
$stream = $encodedBody;
}
$stream = new Psr7\InflateStream($stream);
$stream = new InflateBodyStream($stream, $encoding[0] === 'deflate');
$headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']];
// Remove content-encoding header
@ -745,7 +736,6 @@ final class StreamHandler
try {
// Buffered paths reject unrepresentable lengths before draining.
$declaredLength = HeaderProcessor::contentLengthToInt($declaredResponseBodyLength);
$declaredLength = $declaredLength !== null && $declaredLength > 0 ? $declaredLength : null;
$copyLimit = $encodedBody === null ? $declaredLength ?? -1 : -1;
try {
@ -857,12 +847,11 @@ final class StreamHandler
/**
* Decorates the transport stream so each buffered-body read observes the
* remaining wall-clock budget of the "timeout" request option, bounded
* by the "read_timeout" idle timeout when that is shorter. The transport
* is switched to non-blocking mode because filtered reads (chunked and
* compressed responses) otherwise block until a full buffer arrives,
* which would keep the deadline from being enforced between small pieces
* of data.
* remaining wall-clock budget of the "timeout" request option, bounded by
* the "read_timeout" idle timeout when that is shorter. The transport is
* switched to non-blocking mode because a blocking read waits for data up
* to the transport's own timeout, which would keep the deadline from being
* enforced while the server stalls.
*
* @param resource $resource
*/
@ -943,7 +932,8 @@ final class StreamHandler
RequestInterface $request,
#[\SensitiveParameter]
array $options,
string $body
string $body,
?float &$deadline
) {
// Report a stream-open failure against the request passed here, not the
// Connection: close clone built for the wire.
@ -1029,8 +1019,8 @@ final class StreamHandler
);
try {
$resource = $this->createResource(function () use ($uri, $contextResource, $idleTimeout, $timeout) {
$this->lastDeadline = $timeout > 0 ? Clock::now() + $timeout / 1000 : null;
$resource = $this->createResource(function () use ($uri, $contextResource, $idleTimeout, $timeout, &$deadline) {
$deadline = $timeout > 0 ? Clock::now() + $timeout / 1000 : null;
// Blank the from ini setting for the transfer so ambient
// configuration cannot leak into a From header; the wrapper
@ -1044,13 +1034,6 @@ final class StreamHandler
}
}
// PHP 8.5 deprecates the local $http_response_header variable.
if (function_exists('http_get_last_response_headers')) {
$http_response_header = \http_get_last_response_headers();
}
$this->lastHeaders = $http_response_header ?? [];
if (false === $resource) {
return false;
}

View file

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
/**
* Decorates the stream that wraps a response transport so a read never waits
* on the network while PHP still holds bytes it has already received.
*
* Before PHP 8.3, a blocking read longer than the bytes PHP has buffered
* returns them only after the next packet or EOF, which holds back body bytes
* that arrived with the headers. PHP only fixed this for TLS in 8.4.24 and
* 8.5.9. On Windows such a read can also mark the transport as timed out
* although it returned bytes. Capping each read at the buffered length serves
* it from PHP's buffer alone.
*
* @internal
*/
final class TransportStream implements StreamInterface
{
use NonSerializableTrait;
use StreamDecoratorTrait;
private StreamInterface $stream;
public function __construct(StreamInterface $stream)
{
$this->stream = $stream;
}
public function __clone()
{
// Detaching a clone must not detach this body's transport.
$this->stream = clone $this->stream;
}
public function read(int $length): string
{
$buffered = $this->stream->getMetadata('unread_bytes');
return $this->stream->read(\is_int($buffered) && $buffered > 0 ? \min($length, $buffered) : $length);
}
}