diff --git a/BufferList.js b/BufferList.js index 6dad448..802020f 100644 --- a/BufferList.js +++ b/BufferList.js @@ -134,12 +134,13 @@ BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { if (bytes > l) { this._bufs[i].copy(dst, bufoff, start) + bufoff += l } else { this._bufs[i].copy(dst, bufoff, start, start + bytes) + bufoff += l break } - bufoff += l bytes -= l if (start) { @@ -147,6 +148,9 @@ BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { } } + // safeguard so that we don't return uninitialized memory + if (dst.length > bufoff) return dst.slice(0, bufoff) + return dst } @@ -188,6 +192,11 @@ BufferList.prototype.toString = function toString (encoding, start, end) { } BufferList.prototype.consume = function consume (bytes) { + // first, normalize the argument, in accordance with how Buffer does it + bytes = Math.trunc(bytes) + // do nothing if not a positive number + if (Number.isNaN(bytes) || bytes <= 0) return this + while (this._bufs.length) { if (bytes >= this._bufs[0].length) { bytes -= this._bufs[0].length diff --git a/test/test.js b/test/test.js index cb1f257..e03bb85 100644 --- a/test/test.js +++ b/test/test.js @@ -463,6 +463,22 @@ tape('test toString encoding', function (t) { t.end() }) +tape('uninitialized memory', function (t) { + const secret = crypto.randomBytes(256) + for (let i = 0; i < 1e6; i++) { + const clone = Buffer.from(secret) + const bl = new BufferList() + bl.append(Buffer.from('a')) + bl.consume(-1024) + const buf = bl.slice(1) + if (buf.indexOf(clone) !== -1) { + t.fail(`Match (at ${i})`) + break + } + } + t.end() +}) + !process.browser && tape('test stream', function (t) { const random = crypto.randomBytes(65534)