Skip to content

Omit binary body in FullHttpMessageFormatter #128

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## Unreleased

- Omitted binary body in FullHttpMessageFormatter. `[binary stream omitted]` will be shown instead.

### Added

- New Header authentication method for arbitrary header authentication.
Expand Down
21 changes: 21 additions & 0 deletions spec/Formatter/FullHttpMessageFormatterSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -227,4 +227,25 @@ function it_does_not_format_no_seekable_response(ResponseInterface $response, St
STR;
$this->formatResponse($response)->shouldReturn($expectedMessage);
}

function it_omits_body_with_null_bytes(RequestInterface $request, StreamInterface $stream)
{
$this->beConstructedWith(1);

$stream->isSeekable()->willReturn(true);
$stream->rewind()->shouldBeCalled();
$stream->__toString()->willReturn("\0");
$request->getBody()->willReturn($stream);
$request->getMethod()->willReturn('GET');
$request->getRequestTarget()->willReturn('/foo');
$request->getProtocolVersion()->willReturn('1.1');
$request->getHeaders()->willReturn([]);

$expectedMessage = <<<STR
GET /foo HTTP/1.1

[binary stream omitted]
STR;
$this->formatRequest($request)->shouldReturn($expectedMessage);
}
}
18 changes: 11 additions & 7 deletions src/Formatter/FullHttpMessageFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,20 +76,24 @@ public function formatResponse(ResponseInterface $response)
*/
private function addBody(MessageInterface $request, $message)
{
$message .= "\n";
$stream = $request->getBody();
if (!$stream->isSeekable() || 0 === $this->maxBodyLength) {
// Do not read the stream
return $message."\n";
return $message;
}

if (null === $this->maxBodyLength) {
$message .= "\n".$stream->__toString();
} else {
$message .= "\n".mb_substr($stream->__toString(), 0, $this->maxBodyLength);
$data = $stream->__toString();
$stream->rewind();

if (preg_match('/[\x00-\x1F\x7F]/', $data)) {
return $message.'[binary stream omitted]';
}

$stream->rewind();
if (null === $this->maxBodyLength) {
return $message.$data;
}

return $message;
return $message.mb_substr($data, 0, $this->maxBodyLength);
}
}