Skip to content

Commit

Permalink
[perf] Skip masking and unmasking if the masking key is zero
Browse files Browse the repository at this point in the history
  • Loading branch information
lpinca committed Dec 20, 2021
1 parent eb2e3a8 commit 35d45c2
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 15 deletions.
8 changes: 7 additions & 1 deletion lib/receiver.js
Expand Up @@ -417,7 +417,13 @@ class Receiver extends Writable {
}

data = this.consume(this._payloadLength);
if (this._masked) unmask(data, this._mask);

if (
this._masked &&
(this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0
) {
unmask(data, this._mask);
}
}

if (this._opcode > 0x07) return this.controlMessage(data);
Expand Down
32 changes: 22 additions & 10 deletions lib/sender.js
Expand Up @@ -65,8 +65,26 @@ class Sender {
* @public
*/
static frame(data, options) {
const merge = options.mask && options.readOnly;
let offset = options.mask ? 6 : 2;
let mask;
let merge = false;
let offset = 2;
let skipMasking = false;

if (options.mask) {
mask = options.maskBuffer || maskBuffer;

if (options.generateMask) {
options.generateMask(mask);
} else {
randomFillSync(mask, 0, 4);
}

skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
if (options.readOnly && !skipMasking) merge = true;

offset = 6;
}

let payloadLength = data.length;

if (data.length >= 65536) {
Expand All @@ -93,20 +111,14 @@ class Sender {

if (!options.mask) return [target, data];

const mask = options.maskBuffer ? options.maskBuffer : maskBuffer;

if (options.generateMask) {
options.generateMask(mask);
} else {
randomFillSync(mask, 0, 4);
}

target[1] |= 0x80;
target[offset - 4] = mask[0];
target[offset - 3] = mask[1];
target[offset - 2] = mask[2];
target[offset - 1] = mask[3];

if (skipMasking) return [target, data];

if (merge) {
applyMask(data, mask, target, offset, data.length);
return [target];
Expand Down
11 changes: 7 additions & 4 deletions test/websocket.test.js
Expand Up @@ -128,13 +128,14 @@ describe('WebSocket', () => {
});

it('honors the `generateMask` option', (done) => {
const data = Buffer.from('foo');
const wss = new WebSocket.Server({ port: 0 }, () => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`, {
generateMask() {}
});

ws.on('open', () => {
ws.send('foo');
ws.send(data);
});

ws.on('close', (code, reason) => {
Expand All @@ -152,9 +153,11 @@ describe('WebSocket', () => {
chunks.push(chunk);
});

ws.on('message', () => {
assert.ok(
Buffer.concat(chunks).slice(2, 6).equals(Buffer.alloc(4))
ws.on('message', (message) => {
assert.deepStrictEqual(message, data);
assert.deepStrictEqual(
Buffer.concat(chunks).slice(2, 6),
Buffer.alloc(4)
);

ws.close();
Expand Down

0 comments on commit 35d45c2

Please sign in to comment.