Skip to content

Commit

Permalink
buffer: validate list elements in Buffer.concat
Browse files Browse the repository at this point in the history
Without this change, if any of the elements in the list to be concatenated is
not a Buffer instance, the method fails with "buf.copy is not a function".
Make an isBuffer check before using the copy method so that we can throw with
a better message.

Fixes: #4949
PR-URL: #4951
Reviewed-By: Colin Ihrig <[email protected]>
Reviewed-By: Sakthipriyan Vairamani <[email protected]>
Reviewed-By: Roman Klauke <[email protected]>
  • Loading branch information
targos authored and rvagg committed Feb 8, 2016
1 parent 5de3dc5 commit 58d67e2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
4 changes: 3 additions & 1 deletion lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ Buffer.isEncoding = function(encoding) {

Buffer.concat = function(list, length) {
if (!Array.isArray(list))
throw new TypeError('list argument must be an Array of Buffers.');
throw new TypeError('list argument must be an Array of Buffers');

if (list.length === 0)
return new Buffer(0);
Expand All @@ -236,6 +236,8 @@ Buffer.concat = function(list, length) {
var pos = 0;
for (let i = 0; i < list.length; i++) {
var buf = list[i];
if (!Buffer.isBuffer(buf))
throw new TypeError('list argument must be an Array of Buffers');
buf.copy(buffer, pos);
pos += buf.length;
}
Expand Down
18 changes: 14 additions & 4 deletions test/parallel/test-buffer-concat.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,18 @@ assert(flatOne !== one[0]);
assert(flatLong.toString() === (new Array(10 + 1).join('asdf')));
assert(flatLongLen.toString() === (new Array(10 + 1).join('asdf')));

assert.throws(function() {
Buffer.concat([42]);
}, TypeError);
assertWrongList();
assertWrongList(null);
assertWrongList(new Buffer('hello'));
assertWrongList([42]);
assertWrongList(['hello', 'world']);
assertWrongList(['hello', new Buffer('world')]);

console.log('ok');
function assertWrongList(value) {
assert.throws(function() {
Buffer.concat(value);
}, function(err) {
return err instanceof TypeError &&
err.message === 'list argument must be an Array of Buffers';
});
}

0 comments on commit 58d67e2

Please sign in to comment.