Skip to content

Make HttpClient::responseBody more robust #7

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 2 commits into from
Dec 16, 2016
Merged
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
32 changes: 28 additions & 4 deletions src/HttpClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ void HttpClient::resetState()
{
iState = eIdle;
iStatusCode = 0;
iContentLength = 0;
iContentLength = kNoContentLengthHeader;
iBodyLengthConsumed = 0;
iContentLengthPtr = kContentLengthPrefix;
iHttpResponseTimeout = kHttpResponseTimeout;
Expand Down Expand Up @@ -521,12 +521,35 @@ String HttpClient::responseBody()

if (bodyLength > 0)
{
response.reserve(bodyLength);
// try to reserve bodyLength bytes
if (response.reserve(bodyLength) == 0) {
// String reserve failed
return String((const char*)NULL);
}
}

while (available())
// keep on timedRead'ing, until:
// - we have a content length: body length equals consumed or no bytes
// available
// - no content length: no bytes are available
while (iBodyLengthConsumed != bodyLength)
{
response += (char)read();
int c = timedRead();

if (c == -1) {
// read timed out, done
break;
}

if (!response.concat((char)c)) {
// adding char failed
return String((const char*)NULL);
}
}

if (bodyLength > 0 && (unsigned int)bodyLength != response.length()) {
// failure, we did not read in reponse content length bytes
return String((const char*)NULL);
}

return response;
Expand Down Expand Up @@ -663,6 +686,7 @@ int HttpClient::readHeader()
// Just in case we get multiple Content-Length headers, this
// will ensure we just get the value of the last one
iContentLength = 0;
iBodyLengthConsumed = 0;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the rationale of this, does it fix a bug?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it was to reset state when a HttpClient is reused.

}
}
else if ((iContentLengthPtr == kContentLengthPrefix) && (c == '\r'))
Expand Down