Skip to content

Commit

Permalink
Fixing buffer deprecation warning.
Browse files Browse the repository at this point in the history
  • Loading branch information
theturtle32 committed Sep 20, 2018
1 parent d8fe2c4 commit 5daf2f9
Show file tree
Hide file tree
Showing 9 changed files with 41 additions and 28 deletions.
3 changes: 2 additions & 1 deletion lib/WebSocketClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ var https = require('https');
var url = require('url');
var crypto = require('crypto');
var WebSocketConnection = require('./WebSocketConnection');
var bufferAllocUnsafe = utils.bufferAllocUnsafe;

var protocolSeparators = [
'(', ')', '<', '>', '@',
Expand Down Expand Up @@ -166,7 +167,7 @@ WebSocketClient.prototype.connect = function(requestUrl, protocols, origin, head
this.url.port = defaultPorts[this.url.protocol];
}

var nonce = new Buffer(16);
var nonce = bufferAllocUnsafe(16);
for (var i=0; i < 16; i++) {
nonce[i] = Math.round(Math.random()*0xFF);
}
Expand Down
14 changes: 8 additions & 6 deletions lib/WebSocketConnection.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ var EventEmitter = require('events').EventEmitter;
var WebSocketFrame = require('./WebSocketFrame');
var BufferList = require('../vendor/FastBufferList');
var Validation = require('./Validation').Validation;
var bufferAllocUnsafe = utils.bufferAllocUnsafe;
var bufferFromString = utils.bufferFromString;

// Connected, fully-open, ready to send and receive frames
const STATE_OPEN = 'open';
Expand Down Expand Up @@ -73,8 +75,8 @@ function WebSocketConnection(socket, extensions, protocol, maskOutgoingPackets,
// We re-use the same buffers for the mask and frame header for all frames
// received on each connection to avoid a small memory allocation for each
// frame.
this.maskBytes = new Buffer(4);
this.frameHeader = new Buffer(10);
this.maskBytes = bufferAllocUnsafe(4);
this.frameHeader = bufferAllocUnsafe(10);

// the BufferList will handle the data streaming in
this.bufferList = new BufferList();
Expand Down Expand Up @@ -585,7 +587,7 @@ WebSocketConnection.prototype.processFrame = function(frame) {
// message now. We also have to decode the utf-8 data
// for text frames after combining all the fragments.
var bytesCopied = 0;
var binaryPayload = new Buffer(this.fragmentationSize);
var binaryPayload = bufferAllocUnsafe(this.fragmentationSize);
var opcode = this.frameQueue[0].opcode;
this.frameQueue.forEach(function (currentFrame) {
currentFrame.binaryPayload.copy(binaryPayload, bytesCopied);
Expand Down Expand Up @@ -725,7 +727,7 @@ WebSocketConnection.prototype.send = function(data, cb) {
};

WebSocketConnection.prototype.sendUTF = function(data, cb) {
data = new Buffer(data.toString(), 'utf8');
data = bufferFromString(data.toString(), 'utf8');
this._debug('sendUTF: %d bytes', data.length);
var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
frame.opcode = 0x01; // WebSocketOpcode.TEXT_FRAME
Expand All @@ -751,7 +753,7 @@ WebSocketConnection.prototype.ping = function(data) {
frame.fin = true;
if (data) {
if (!Buffer.isBuffer(data)) {
data = new Buffer(data.toString(), 'utf8');
data = bufferFromString(data.toString(), 'utf8');
}
if (data.length > 125) {
this._debug('WebSocket: Data for ping is longer than 125 bytes. Truncating.');
Expand Down Expand Up @@ -844,7 +846,7 @@ WebSocketConnection.prototype.sendCloseFrame = function(reasonCode, description,
frame.opcode = 0x08; // WebSocketOpcode.CONNECTION_CLOSE
frame.closeStatus = reasonCode;
if (typeof(description) === 'string') {
frame.binaryPayload = new Buffer(description, 'utf8');
frame.binaryPayload = bufferFromString(description, 'utf8');
}

this.sendFrame(frame, cb);
Expand Down
9 changes: 5 additions & 4 deletions lib/WebSocketFrame.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
***********************************************************************/

var bufferUtil = require('./BufferUtil').BufferUtil;
var bufferAllocUnsafe = require('./utils').bufferAllocUnsafe;

const DECODE_HEADER = 1;
const WAITING_FOR_16_BIT_LENGTH = 2;
Expand Down Expand Up @@ -130,7 +131,7 @@ WebSocketFrame.prototype.addData = function(bufferList) {
}

if (this.length === 0) {
this.binaryPayload = new Buffer(0);
this.binaryPayload = bufferAllocUnsafe(0);
this.parseState = COMPLETE;
return true;
}
Expand All @@ -145,7 +146,7 @@ WebSocketFrame.prototype.addData = function(bufferList) {
if (this.opcode === 0x08) { // WebSocketOpcode.CONNECTION_CLOSE
if (this.length === 1) {
// Invalid length for a close frame. Must be zero or at least two.
this.binaryPayload = new Buffer(0);
this.binaryPayload = bufferAllocUnsafe(0);
this.invalidCloseFrameLength = true;
}
if (this.length >= 2) {
Expand Down Expand Up @@ -203,7 +204,7 @@ WebSocketFrame.prototype.toBuffer = function(nullMask) {
if (this.binaryPayload) {
this.length += this.binaryPayload.length;
}
data = new Buffer(this.length);
data = bufferAllocUnsafe(this.length);
data.writeUInt16BE(this.closeStatus, 0);
if (this.length > 2) {
this.binaryPayload.copy(data, 2);
Expand Down Expand Up @@ -232,7 +233,7 @@ WebSocketFrame.prototype.toBuffer = function(nullMask) {
headerLength += 8;
}

var output = new Buffer(this.length + headerLength + (this.mask ? 4 : 0));
var output = bufferAllocUnsafe(this.length + headerLength + (this.mask ? 4 : 0));

// write the frame header
output[0] = firstByte;
Expand Down
10 changes: 8 additions & 2 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,15 @@ exports.eventEmitterListenerCount =
require('events').EventEmitter.listenerCount ||
function(emitter, type) { return emitter.listeners(type).length; };

exports.bufferAllocUnsafe = Buffer.allocUnsafe ?
Buffer.allocUnsafe :
function oldBufferAllocUnsafe(size) { return new Buffer(size); };



exports.bufferFromString = Buffer.from ?
Buffer.from :
function oldBufferFromString(string, encoding) {
return new Buffer(string, encoding);
};

exports.BufferingLogger = function createBufferingLogger(identifier, uniqueID) {
var logFunction = require('debug')(identifier);
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"dependencies": {
"debug": "^2.2.0",
"nan": "^2.3.3",
"typedarray-to-buffer": "^3.1.2",
"typedarray-to-buffer": "^3.1.5",
"yaeti": "^0.0.6"
},
"devDependencies": {
Expand All @@ -39,7 +39,7 @@
"gulp-jshint": "^2.0.4",
"jshint-stylish": "^2.2.1",
"jshint": "^2.0.0",
"tape": "^4.0.1"
"tape": "^4.9.1"
},
"config": {
"verbose": false
Expand Down
2 changes: 1 addition & 1 deletion test/autobahn/fuzzingclient.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

"servers": [
{
"agent": "WebSocket-Node 1.0.25",
"agent": "WebSocket-Node 1.0.27",
"url": "ws://127.0.0.1:8080",
"options": {"version": 18}
}
Expand Down
3 changes: 2 additions & 1 deletion test/scripts/fragmentation-test-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

var WebSocketServer = require('../../lib/WebSocketServer');
var WebSocketRouter = require('../../lib/WebSocketRouter');
var bufferAllocUnsafe = require('../../lib/utils').bufferAllocUnsafe;
var http = require('http');
var fs = require('fs');

Expand Down Expand Up @@ -121,7 +122,7 @@ router.mount('*', 'fragmentation-test', function(request) {
requestedLength = parseInt(match[1], 10);

// Generate random binary data.
var buffer = new Buffer(requestedLength);
var buffer = bufferAllocUnsafe(requestedLength);
for (var i=0; i < requestedLength; i++) {
buffer[i] = Math.ceil(Math.random()*255);
}
Expand Down
12 changes: 8 additions & 4 deletions test/unit/websocketFrame.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@
var test = require('tape');
var bufferEqual = require('buffer-equal');
var WebSocketFrame = require('../../lib/WebSocketFrame');
var utils = require('../../lib/utils');
var bufferAllocUnsafe = utils.bufferAllocUnsafe;
var bufferFromString = utils.bufferFromString;


test('Serializing a WebSocket Frame with no data', function(t) {
t.plan(2);

// WebSocketFrame uses a per-connection buffer for the mask bytes
// and the frame header to avoid allocating tons of small chunks of RAM.
var maskBytesBuffer = new Buffer(4);
var frameHeaderBuffer = new Buffer(10);
var maskBytesBuffer = bufferAllocUnsafe(4);
var frameHeaderBuffer = bufferAllocUnsafe(10);

var frameBytes;
var frame = new WebSocketFrame(maskBytesBuffer, frameHeaderBuffer, {});
Expand All @@ -24,9 +28,9 @@ test('Serializing a WebSocket Frame with no data', function(t) {

t.assert(
bufferEqual
(frameBytes, new Buffer('898000000000', 'hex')),
(frameBytes, bufferFromString('898000000000', 'hex')),
'Generated bytes should be correct'
);

t.end();
});
});
12 changes: 5 additions & 7 deletions vendor/FastBufferList.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// Treat a linked list of buffers as a single variable-size buffer.
var Buffer = require('buffer').Buffer;
var EventEmitter = require('events').EventEmitter;
var bufferAllocUnsafe = require('../lib/utils').bufferAllocUnsafe;

module.exports = BufferList;
module.exports.BufferList = BufferList; // backwards compatibility
Expand All @@ -21,9 +22,6 @@ function BufferList(opts) {
// makes take() return a Buffer instead.
self.encoding = opts.encoding;

// constructor to use for Buffer-esque operations
self.construct = opts.construct || Buffer;

var head = { next : null, buffer : null };
var last = { next : null, buffer : null };

Expand Down Expand Up @@ -68,7 +66,7 @@ function BufferList(opts) {
// If fn's result is a true value, cut out early.
// Returns this (self).
self.forEach = function (fn) {
if (!head.buffer) return new self.construct(0);
if (!head.buffer) return bufferAllocUnsafe(0);

if (head.buffer.length - offset <= 0) return self;
var firstBuf = head.buffer.slice(offset);
Expand All @@ -87,11 +85,11 @@ function BufferList(opts) {
// Create a single Buffer out of all the chunks or some subset specified by
// start and one-past the end (like slice) in bytes.
self.join = function (start, end) {
if (!head.buffer) return new self.construct(0);
if (!head.buffer) return bufferAllocUnsafe(0);
if (start == undefined) start = 0;
if (end == undefined) end = self.length;

var big = new self.construct(end - start);
var big = bufferAllocUnsafe(end - start);
var ix = 0;
self.forEach(function (buffer) {
if (start < (ix + buffer.length) && ix < end) {
Expand All @@ -111,7 +109,7 @@ function BufferList(opts) {
};

self.joinInto = function (targetBuffer, targetStart, sourceStart, sourceEnd) {
if (!head.buffer) return new self.construct(0);
if (!head.buffer) return new bufferAllocUnsafe(0);
if (sourceStart == undefined) sourceStart = 0;
if (sourceEnd == undefined) sourceEnd = self.length;

Expand Down

0 comments on commit 5daf2f9

Please sign in to comment.