diff options
author | Feross Aboukhadijeh <feross@feross.org> | 2016-05-30 08:50:40 +0300 |
---|---|---|
committer | Feross Aboukhadijeh <feross@feross.org> | 2016-05-30 08:50:40 +0300 |
commit | 69227bd5899294d43b9bee0f5a075a8190b1af75 (patch) | |
tree | 1bf6f42ee64c9b0e1c86862422ef7764e91599eb /lib/webconn.js | |
parent | 7fb250f6767796bdc88f9a1d4536dbc6c731e465 (diff) |
Use safe-buffer
Use the new Buffer APIs from Node v6 for added security. For example,
Buffer.from() will throw if passed a number, unlike Buffer() which
allocated UNINITIALIZED memory.
Use the safe-buffer package for compatibility with previous versions of
Node.js, including v4.x, v0.12, and v0.10.
https://github.com/feross/safe-buffer
Diffstat (limited to 'lib/webconn.js')
-rw-r--r-- | lib/webconn.js | 23 |
1 files changed, 16 insertions, 7 deletions
diff --git a/lib/webconn.js b/lib/webconn.js index bff2f89..c52dad6 100644 --- a/lib/webconn.js +++ b/lib/webconn.js @@ -1,6 +1,7 @@ module.exports = WebConn var BitField = require('bitfield') +var Buffer = require('safe-buffer').Buffer var debug = require('debug')('webtorrent:webconn') var get = require('simple-get') var inherits = require('inherits') @@ -101,7 +102,12 @@ WebConn.prototype.httpRequest = function (pieceIndex, offset, length, cb) { // Send requests in parallel and wait for them all to come back var numRequestsSucceeded = 0 var hasError = false - if (requests.length > 1) var ret = new Buffer(length) + + var ret + if (requests.length > 1) { + ret = Buffer.alloc(length) + } + requests.forEach(function (request) { var url = request.url var start = request.start @@ -129,14 +135,17 @@ WebConn.prototype.httpRequest = function (pieceIndex, offset, length, cb) { return cb(new Error('Unexpected HTTP status code ' + res.statusCode)) } debug('Got data of length %d', data.length) + if (requests.length === 1) { // Common case: fetch piece in a single HTTP request, return directly - return cb(null, data) - } - // Rare case: reconstruct multiple HTTP requests across 2+ files into one piece buffer - data.copy(ret, request.fileOffsetInRange) - if (++numRequestsSucceeded === requests.length) { - cb(null, ret) + cb(null, data) + } else { + // Rare case: reconstruct multiple HTTP requests across 2+ files into one + // piece buffer + data.copy(ret, request.fileOffsetInRange) + if (++numRequestsSucceeded === requests.length) { + cb(null, ret) + } } }) }) |