1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-02-24 10:03:27 +01:00

Only read up to Content-Length in stream wrapper

This commit updates the stream wrapper to only read up to the number of
bytes returned in the Content-Length header when draining a stream
synchronously.
This commit is contained in:
Michael Dowling 2016-06-30 11:43:58 -07:00
parent 502b40014c
commit a6ed049497
2 changed files with 40 additions and 4 deletions

View File

@ -119,7 +119,11 @@ class StreamHandler
}
if ($sink !== $stream) {
$this->drain($stream, $sink);
$this->drain(
$stream,
$sink,
$response->getHeaderLine('Content-Length')
);
}
$this->invokeStats($options, $request, $startTime, $response, null);
@ -181,13 +185,27 @@ class StreamHandler
*
* @param StreamInterface $source
* @param StreamInterface $sink
* @param string $contentLength Header specifying the amount of
* data to read.
*
* @return StreamInterface
* @throws \RuntimeException when the sink option is invalid.
*/
private function drain(StreamInterface $source, StreamInterface $sink)
{
Psr7\copy_to_stream($source, $sink);
private function drain(
StreamInterface $source,
StreamInterface $sink,
$contentLength
) {
// If a content-length header is provided, then stop reading once
// that number of bytes has been read. This can prevent infinitely
// reading from a stream when dealing with servers that do not honor
// Connection: Close headers.
Psr7\copy_to_stream(
$source,
$sink,
strlen($contentLength) > 0 ? (int) $contentLength : -1
);
$sink->seek(0);
$source->close();

View File

@ -142,6 +142,24 @@ class StreamHandlerTest extends \PHPUnit_Framework_TestCase
unlink($tmpfname);
}
public function testDrainsResponseAndReadsOnlyContentLengthBytes()
{
Server::flush();
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => 8,
], 'hi there... This has way too much data!')
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
$this->assertEquals('hi there', stream_get_contents($stream));
fclose($stream);
}
public function testAutomaticallyDecompressGzip()
{
Server::flush();