Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
buffer, crypto: fix buffer decoding
Browse files Browse the repository at this point in the history
Before this commit, DecodeWrite() mistakenly tried to convert buffers to
UTF-8 strings which:

  a) produced invalid character sequences when the buffer contained
     octets > 127, and
  b) lead to spurious test failures because DecodeWrite() wrote less bytes
     than DecodeBytes() said it would, with the remainder either containing
     zeros or garbage

Fix that by simply copying the buffer's data to the target buffer when the
encoding is BINARY or by converting the buffer to a binary string when it's
UTF8 or ASCII.

Fixes #3651, #3866.
  • Loading branch information
bnoordhuis committed Aug 14, 2012
1 parent 100e163 commit 786e1e8
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/node.cc
Expand Up @@ -1184,7 +1184,25 @@ ssize_t DecodeWrite(char *buf,
return -1;
}

Local<String> str = val->ToString();
bool is_buffer = Buffer::HasInstance(val);

if (is_buffer && encoding == BINARY) { // fast path, copy buffer data
const char* data = Buffer::Data(val.As<Object>());
size_t size = Buffer::Length(val.As<Object>());
size_t len = size < buflen ? size : buflen;
memcpy(buf, data, len);
return len;
}

Local<String> str;

if (is_buffer) { // slow path, convert to binary string
Local<Value> arg = String::New("binary");
str = MakeCallback(val.As<Object>(), "toString", 1, &arg)->ToString();
}
else {
str = val->ToString();
}

if (encoding == UTF8) {
str->WriteUtf8(buf, buflen, NULL, String::HINT_MANY_WRITES_EXPECTED);
Expand Down

0 comments on commit 786e1e8

Please sign in to comment.