Commit 7bb309f8 authored by Medicean's avatar Medicean Committed by Medicean

Enhance(Modules/Request): 新增WebSocket连接方式支持,仅RAW模式下可用

parent 3ef6b5ab
...@@ -11,11 +11,11 @@ const fs = require('fs'), ...@@ -11,11 +11,11 @@ const fs = require('fs'),
through = require('through'), through = require('through'),
CONF = require('./config'), CONF = require('./config'),
superagent = require('superagent'), superagent = require('superagent'),
superagentProxy = require('superagent-proxy'); superagentProxy = require('superagent-proxy'),
const { ws = require('ws');
Readable const { Readable } = require("stream");
} = require("stream"); const ProxyAgent = require('proxy-agent');
let wsclients = {};
let logger; let logger;
// 请求UA // 请求UA
const USER_AGENT = require('random-fake-useragent'); const USER_AGENT = require('random-fake-useragent');
...@@ -166,6 +166,42 @@ class Request { ...@@ -166,6 +166,42 @@ class Request {
} }
} }
parseWebSocket(tag_s, tag_e, chunkCallBack, sock, callback) {
const tagHexS = Buffer.from(tag_s).toString('hex');
const tagHexE = Buffer.from(tag_e).toString('hex');
let foundTagS = false;
let foundTagE = false;
sock.data = '';
sock.on("message", function(chunk) {
let chunkHex = Buffer.from(chunk).toString('hex');
let temp = '';
if (chunkHex.indexOf(tagHexS) >= 0 && chunkHex.lastIndexOf(tagHexE) >= 0) {
let index_s = chunkHex.indexOf(tagHexS);
let index_e = chunkHex.lastIndexOf(tagHexE);
temp = chunkHex.substr(index_s + tagHexS.length, index_e - index_s - tagHexS.length);
foundTagS = foundTagE = // 如果只包含前截断,则截取后边
true;
} else if (chunkHex.indexOf(tagHexS) >= 0 && chunkHex.lastIndexOf(tagHexE) === -1) {
temp = chunkHex.split(tagHexS)[1];
foundTagS = // 如果只包含后截断,则截取前边
true;
} else if (chunkHex.indexOf(tagHexS) === -1 && chunkHex.lastIndexOf(tagHexE) >= 0) {
temp = chunkHex.split(tagHexE)[0];
foundTagE = // 如果有没有,那就是中途迷路的数据啦 ^.^
true;
} else if (foundTagS && !foundTagE) {
temp = chunkHex;
}
let finalData = Buffer.from(temp, 'hex');
chunkCallBack(finalData);
sock.data += finalData;
});
sock.on("close", function() {
logger.info(`ws onclose data.size=${sock.data.length}`, sock.data);
callback(null, Buffer.from(sock.data, 'binary'));
});
}
/** /**
* 监听HTTP请求 * 监听HTTP请求
* @param {Object} event ipcMain事件对象 * @param {Object} event ipcMain事件对象
...@@ -178,6 +214,50 @@ class Request { ...@@ -178,6 +214,50 @@ class Request {
if (opts['url'].match(CONF.urlblacklist)) { if (opts['url'].match(CONF.urlblacklist)) {
return event.sender.send('request-error-' + opts['hash'], "Blacklist URL"); return event.sender.send('request-error-' + opts['hash'], "Blacklist URL");
} }
// ws
if (opts['useWebSocket'] == 1) {
let wsopts = {
agent: new ProxyAgent(APROXY_CONF['uri']),
}
let sock = new ws(opts['url'], wsopts);
sock.on("open", function() {
let _tmp = encodeURIComponent(opts.data[opts['pwd']]).replace(/asunescape\((.+?)\)/g, function($, $1) {
return unescape($1);
});
_tmp = unescape(_tmp);
logger.debug('onRequest::wsopen-send', _tmp);
sock.send(_tmp);
});
sock.on("error", function(err) {
event.sender.send('request-error-' + opts['hash'], err);
});
self.parseWebSocket(opts['tag_s'], opts['tag_e'], (chunk) => {
event.sender.send('request-chunk-' + opts['hash'], chunk);
sock.close();
}, sock, (err, ret) => {
if (!ret) {
return event.sender.send('request-error-' + opts['hash'], err);
}
let buff = Buffer.from(ret);
let text = '';
let encoding = detectEncoding(buff, {
defaultEncoding: "unknown"
});
logger.debug("detect encoding:", encoding);
encoding = encoding != "unknown" ? encoding : opts['encode'];
text = iconv.decode(buff, encoding);
if (err && text == "") {
return event.sender.send('request-error-' + opts['hash'], err);
};
event.sender.send('request-' + opts['hash'], {
text: text,
buff: buff,
encoding: encoding
});
});
return;
};
// http
self.reqContentType = "form"; self.reqContentType = "form";
let _request = superagent.post(opts['url']); let _request = superagent.post(opts['url']);
self.buildHeaders(_request, opts); self.buildHeaders(_request, opts);
...@@ -305,6 +385,38 @@ class Request { ...@@ -305,6 +385,38 @@ class Request {
let indexStart = -1; let indexStart = -1;
let indexEnd = -1; let indexEnd = -1;
let tempData = []; let tempData = [];
// ws
if (opts['useWebSocket'] == 1) {
let wsopts = {
agent: new ProxyAgent(APROXY_CONF['uri']),
}
let sock = new ws(opts['url'], wsopts);
sock.on("open", function() {
let _tmp = encodeURIComponent(opts.data[opts['pwd']]).replace(/asunescape\((.+?)\)/g, function($, $1) {
return unescape($1);
});
_tmp = unescape(_tmp);
logger.debug('onDownlaod::wsopen-send', _tmp);
sock.send(_tmp);
});
sock.on("error", function(err) {
event.sender.send('download-error-' + opts['hash'], err);
});
self.parseWebSocket(opts['tag_s'], opts['tag_e'], (chunk) => {
event.sender.send('download-progress-' + opts['hash'], chunk.length);
sock.close();
}, sock, (err, ret) => {
if (!ret) {
return event.sender.send('download-error-' + opts['hash'], err);
}
rs.write(ret);
rs.close();
event.sender.send('download-' + opts['hash'], ret.length);
});
return;
};
self.reqContentType = "form"; self.reqContentType = "form";
let _request = superagent.post(opts['url']); let _request = superagent.post(opts['url']);
// 设置headers // 设置headers
......
../esprima/bin/esparse.js ../esprima-fb/bin/esparse.js
\ No newline at end of file \ No newline at end of file
../esprima/bin/esvalidate.js ../esprima-fb/bin/esvalidate.js
\ No newline at end of file \ No newline at end of file
...@@ -138,6 +138,11 @@ ...@@ -138,6 +138,11 @@
"resolved": "https://registry.npm.taobao.org/async/download/async-0.2.10.tgz", "resolved": "https://registry.npm.taobao.org/async/download/async-0.2.10.tgz",
"integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E=" "integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E="
}, },
"node_modules/async-limiter": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.1.tgz",
"integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ=="
},
"node_modules/asynckit": { "node_modules/asynckit": {
"version": "0.4.0", "version": "0.4.0",
"resolved": "http://registry.npm.taobao.org/asynckit/download/asynckit-0.4.0.tgz", "resolved": "http://registry.npm.taobao.org/asynckit/download/asynckit-0.4.0.tgz",
...@@ -2166,23 +2171,11 @@ ...@@ -2166,23 +2171,11 @@
"integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=" "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus="
}, },
"node_modules/ws": { "node_modules/ws": {
"version": "8.8.0", "version": "6.1.4",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.8.0.tgz", "resolved": "https://registry.npmjs.org/ws/-/ws-6.1.4.tgz",
"integrity": "sha512-JDAgSYQ1ksuwqfChJusw1LSJ8BizJ2e/vVu5Lxjq3YvNJNlROv1ui4i+c/kUUrPheBvQl4c5UbERhTwKa6QBJQ==", "integrity": "sha512-eqZfL+NE/YQc1/ZynhojeV8q+H050oR8AZ2uIev7RU10svA9ZnJUddHcOUZTJLinZ9yEfdA2kSATS2qZK5fhJA==",
"engines": { "dependencies": {
"node": ">=10.0.0" "async-limiter": "~1.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": "^5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
} }
}, },
"node_modules/xml-name-validator": { "node_modules/xml-name-validator": {
......
coverage
.nyc_output
\ No newline at end of file
{
"check-coverage": false,
"lines": 99,
"statements": 99,
"functions": 99,
"branches": 99,
"include": [
"index.js"
]
}
\ No newline at end of file
language: node_js
node_js:
- "6"
- "8"
- "10"
- "node"
script: npm run travis
cache:
yarn: true
The MIT License (MIT)
Copyright (c) 2017 Samuel Reed <samuel.trace.reed@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
function Queue(options) {
if (!(this instanceof Queue)) {
return new Queue(options);
}
options = options || {};
this.concurrency = options.concurrency || Infinity;
this.pending = 0;
this.jobs = [];
this.cbs = [];
this._done = done.bind(this);
}
var arrayAddMethods = [
'push',
'unshift',
'splice'
];
arrayAddMethods.forEach(function(method) {
Queue.prototype[method] = function() {
var methodResult = Array.prototype[method].apply(this.jobs, arguments);
this._run();
return methodResult;
};
});
Object.defineProperty(Queue.prototype, 'length', {
get: function() {
return this.pending + this.jobs.length;
}
});
Queue.prototype._run = function() {
if (this.pending === this.concurrency) {
return;
}
if (this.jobs.length) {
var job = this.jobs.shift();
this.pending++;
job(this._done);
this._run();
}
if (this.pending === 0) {
while (this.cbs.length !== 0) {
var cb = this.cbs.pop();
process.nextTick(cb);
}
}
};
Queue.prototype.onDone = function(cb) {
if (typeof cb === 'function') {
this.cbs.push(cb);
this._run();
}
};
function done() {
this.pending--;
this._run();
}
module.exports = Queue;
{
"name": "async-limiter",
"version": "1.0.1",
"description": "asynchronous function queue with adjustable concurrency",
"keywords": [
"throttle",
"async",
"limiter",
"asynchronous",
"job",
"task",
"concurrency",
"concurrent"
],
"dependencies": {},
"devDependencies": {
"coveralls": "^3.0.3",
"eslint": "^5.16.0",
"eslint-plugin-mocha": "^5.3.0",
"intelli-espower-loader": "^1.0.1",
"mocha": "^6.1.4",
"nyc": "^14.1.1",
"power-assert": "^1.6.1"
},
"scripts": {
"test": "mocha --require intelli-espower-loader test/",
"travis": "npm run lint && npm run test",
"coverage": "nyc npm test && nyc report --reporter=text-lcov | coveralls",
"example": "node example",
"lint": "eslint ."
},
"repository": "https://github.com/strml/async-limiter.git",
"author": "Samuel Reed <samuel.trace.reed@gmail.com",
"license": "MIT"
}
# Async-Limiter
A module for limiting concurrent asynchronous actions in flight. Forked from [queue](https://github.com/jessetane/queue).
[![npm](http://img.shields.io/npm/v/async-limiter.svg?style=flat-square)](http://www.npmjs.org/async-limiter)
[![tests](https://img.shields.io/travis/STRML/async-limiter.svg?style=flat-square&branch=master)](https://travis-ci.org/STRML/async-limiter)
[![coverage](https://img.shields.io/coveralls/STRML/async-limiter.svg?style=flat-square&branch=master)](https://coveralls.io/r/STRML/async-limiter)
This module exports a class `Limiter` that implements some of the `Array` API.
Pass async functions (ones that accept a callback or return a promise) to an instance's additive array methods.
## Motivation
Certain functions, like `zlib`, have [undesirable behavior](https://github.com/nodejs/node/issues/8871#issuecomment-250915913) when
run at infinite concurrency.
In this case, it is actually faster, and takes far less memory, to limit concurrency.
This module should do the absolute minimum work necessary to queue up functions. PRs are welcome that would
make this module faster or lighter, but new functionality is not desired.
Style should confirm to nodejs/node style.
## Example
``` javascript
var Limiter = require('async-limiter')
var t = new Limiter({concurrency: 2});
var results = []
// add jobs using the familiar Array API
t.push(function (cb) {
results.push('two')
cb()
})
t.push(
function (cb) {
results.push('four')
cb()
},
function (cb) {
results.push('five')
cb()
}
)
t.unshift(function (cb) {
results.push('one')
cb()
})
t.splice(2, 0, function (cb) {
results.push('three')
cb()
})
// Jobs run automatically. If you want a callback when all are done,
// call 'onDone()'.
t.onDone(function () {
console.log('all done:', results)
})
```
## Zlib Example
```js
const zlib = require('zlib');
const Limiter = require('async-limiter');
const message = {some: "data"};
const payload = new Buffer(JSON.stringify(message));
// Try with different concurrency values to see how this actually
// slows significantly with higher concurrency!
//
// 5: 1398.607ms
// 10: 1375.668ms
// Infinity: 4423.300ms
//
const t = new Limiter({concurrency: 5});
function deflate(payload, cb) {
t.push(function(done) {
zlib.deflate(payload, function(err, buffer) {
done();
cb(err, buffer);
});
});
}
console.time('deflate');
for(let i = 0; i < 30000; ++i) {
deflate(payload, function (err, buffer) {});
}
t.onDone(function() {
console.timeEnd('deflate');
});
```
## Install
`npm install async-limiter`
## Test
`npm test`
## API
### `var t = new Limiter([opts])`
Constructor. `opts` may contain inital values for:
* `t.concurrency`
## Instance methods
### `t.onDone(fn)`
`fn` will be called once and only once, when the queue is empty.
## Instance methods mixed in from `Array`
Mozilla has docs on how these methods work [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).
### `t.push(element1, ..., elementN)`
### `t.unshift(element1, ..., elementN)`
### `t.splice(index , howMany[, element1[, ...[, elementN]]])`
## Properties
### `t.concurrency`
Max number of jobs the queue should process concurrently, defaults to `Infinity`.
### `t.length`
Jobs pending + jobs to process (readonly).
The MIT License (MIT)
Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com> Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
......
# ws: a Node.js WebSocket library # ws: a Node.js WebSocket library
[![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws) [![Version npm](https://img.shields.io/npm/v/ws.svg)](https://www.npmjs.com/package/ws)
[![CI](https://img.shields.io/github/workflow/status/websockets/ws/CI/master?label=CI&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster) [![Linux Build](https://img.shields.io/travis/websockets/ws/master.svg)](https://travis-ci.org/websockets/ws)
[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg?logo=coveralls)](https://coveralls.io/github/websockets/ws) [![Windows Build](https://ci.appveyor.com/api/projects/status/github/websockets/ws?branch=master&svg=true)](https://ci.appveyor.com/project/lpinca/ws)
[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg)](https://coveralls.io/r/websockets/ws?branch=master)
ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and
server implementation. server implementation.
...@@ -22,7 +23,7 @@ can use one of the many wrappers available on npm, like ...@@ -22,7 +23,7 @@ can use one of the many wrappers available on npm, like
- [Protocol support](#protocol-support) - [Protocol support](#protocol-support)
- [Installing](#installing) - [Installing](#installing)
- [Opt-in for performance](#opt-in-for-performance) - [Opt-in for performance and spec compliance](#opt-in-for-performance-and-spec-compliance)
- [API docs](#api-docs) - [API docs](#api-docs)
- [WebSocket compression](#websocket-compression) - [WebSocket compression](#websocket-compression)
- [Usage examples](#usage-examples) - [Usage examples](#usage-examples)
...@@ -31,11 +32,10 @@ can use one of the many wrappers available on npm, like ...@@ -31,11 +32,10 @@ can use one of the many wrappers available on npm, like
- [Simple server](#simple-server) - [Simple server](#simple-server)
- [External HTTP/S server](#external-https-server) - [External HTTP/S server](#external-https-server)
- [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server)
- [Client authentication](#client-authentication)
- [Server broadcast](#server-broadcast) - [Server broadcast](#server-broadcast)
- [Round-trip time](#round-trip-time) - [echo.websocket.org demo](#echowebsocketorg-demo)
- [Use the Node.js streams API](#use-the-nodejs-streams-api)
- [Other examples](#other-examples) - [Other examples](#other-examples)
- [Error handling best practices](#error-handling-best-practices)
- [FAQ](#faq) - [FAQ](#faq)
- [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client)
- [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections)
...@@ -55,7 +55,7 @@ can use one of the many wrappers available on npm, like ...@@ -55,7 +55,7 @@ can use one of the many wrappers available on npm, like
npm install ws npm install ws
``` ```
### Opt-in for performance ### Opt-in for performance and spec compliance
There are 2 optional modules that can be installed along side with the ws There are 2 optional modules that can be installed along side with the ws
module. These modules are binary addons which improve certain operations. module. These modules are binary addons which improve certain operations.
...@@ -66,19 +66,11 @@ necessarily need to have a C++ compiler installed on your machine. ...@@ -66,19 +66,11 @@ necessarily need to have a C++ compiler installed on your machine.
operations such as masking and unmasking the data payload of the WebSocket operations such as masking and unmasking the data payload of the WebSocket
frames. frames.
- `npm install --save-optional utf-8-validate`: Allows to efficiently check if a - `npm install --save-optional utf-8-validate`: Allows to efficiently check if a
message contains valid UTF-8. message contains valid UTF-8 as required by the spec.
To not even try to require and use these modules, use the
[`WS_NO_BUFFER_UTIL`](./doc/ws.md#ws_no_buffer_util) and
[`WS_NO_UTF_8_VALIDATE`](./doc/ws.md#ws_no_utf_8_validate) environment
variables. These might be useful to enhance security in systems where a user can
put a package in the package search path of an application of another user, due
to how the Node.js resolver algorithm works.
## API docs ## API docs
See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and See [`/doc/ws.md`](./doc/ws.md) for Node.js-like docs for the ws classes.
utility functions.
## WebSocket compression ## WebSocket compression
...@@ -104,9 +96,9 @@ into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. ...@@ -104,9 +96,9 @@ into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs].
See [the docs][ws-server-options] for more options. See [the docs][ws-server-options] for more options.
```js ```js
import WebSocket, { WebSocketServer } from 'ws'; const WebSocket = require('ws');
const wss = new WebSocketServer({ const wss = new WebSocket.Server({
port: 8080, port: 8080,
perMessageDeflate: { perMessageDeflate: {
zlibDeflateOptions: { zlibDeflateOptions: {
...@@ -125,7 +117,7 @@ const wss = new WebSocketServer({ ...@@ -125,7 +117,7 @@ const wss = new WebSocketServer({
// Below options specified as default values. // Below options specified as default values.
concurrencyLimit: 10, // Limits zlib concurrency for perf. concurrencyLimit: 10, // Limits zlib concurrency for perf.
threshold: 1024 // Size (in bytes) below which messages threshold: 1024 // Size (in bytes) below which messages
// should not be compressed if context takeover is disabled. // should not be compressed.
} }
}); });
``` ```
...@@ -135,7 +127,7 @@ server. To always disable the extension on the client set the ...@@ -135,7 +127,7 @@ server. To always disable the extension on the client set the
`perMessageDeflate` option to `false`. `perMessageDeflate` option to `false`.
```js ```js
import WebSocket from 'ws'; const WebSocket = require('ws');
const ws = new WebSocket('ws://www.host.com/path', { const ws = new WebSocket('ws://www.host.com/path', {
perMessageDeflate: false perMessageDeflate: false
...@@ -147,7 +139,7 @@ const ws = new WebSocket('ws://www.host.com/path', { ...@@ -147,7 +139,7 @@ const ws = new WebSocket('ws://www.host.com/path', {
### Sending and receiving text data ### Sending and receiving text data
```js ```js
import WebSocket from 'ws'; const WebSocket = require('ws');
const ws = new WebSocket('ws://www.host.com/path'); const ws = new WebSocket('ws://www.host.com/path');
...@@ -155,15 +147,15 @@ ws.on('open', function open() { ...@@ -155,15 +147,15 @@ ws.on('open', function open() {
ws.send('something'); ws.send('something');
}); });
ws.on('message', function message(data) { ws.on('message', function incoming(data) {
console.log('received: %s', data); console.log(data);
}); });
``` ```
### Sending binary data ### Sending binary data
```js ```js
import WebSocket from 'ws'; const WebSocket = require('ws');
const ws = new WebSocket('ws://www.host.com/path'); const ws = new WebSocket('ws://www.host.com/path');
...@@ -181,13 +173,13 @@ ws.on('open', function open() { ...@@ -181,13 +173,13 @@ ws.on('open', function open() {
### Simple server ### Simple server
```js ```js
import { WebSocketServer } from 'ws'; const WebSocket = require('ws');
const wss = new WebSocketServer({ port: 8080 }); const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) { wss.on('connection', function connection(ws) {
ws.on('message', function message(data) { ws.on('message', function incoming(message) {
console.log('received: %s', data); console.log('received: %s', message);
}); });
ws.send('something'); ws.send('something');
...@@ -197,19 +189,19 @@ wss.on('connection', function connection(ws) { ...@@ -197,19 +189,19 @@ wss.on('connection', function connection(ws) {
### External HTTP/S server ### External HTTP/S server
```js ```js
import { createServer } from 'https'; const fs = require('fs');
import { readFileSync } from 'fs'; const https = require('https');
import { WebSocketServer } from 'ws'; const WebSocket = require('ws');
const server = createServer({ const server = new https.createServer({
cert: readFileSync('/path/to/cert.pem'), cert: fs.readFileSync('/path/to/cert.pem'),
key: readFileSync('/path/to/key.pem') key: fs.readFileSync('/path/to/key.pem')
}); });
const wss = new WebSocketServer({ server }); const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(ws) { wss.on('connection', function connection(ws) {
ws.on('message', function message(data) { ws.on('message', function incoming(message) {
console.log('received: %s', data); console.log('received: %s', message);
}); });
ws.send('something'); ws.send('something');
...@@ -221,13 +213,12 @@ server.listen(8080); ...@@ -221,13 +213,12 @@ server.listen(8080);
### Multiple servers sharing a single HTTP/S server ### Multiple servers sharing a single HTTP/S server
```js ```js
import { createServer } from 'http'; const http = require('http');
import { parse } from 'url'; const WebSocket = require('ws');
import { WebSocketServer } from 'ws';
const server = createServer(); const server = http.createServer();
const wss1 = new WebSocketServer({ noServer: true }); const wss1 = new WebSocket.Server({ noServer: true });
const wss2 = new WebSocketServer({ noServer: true }); const wss2 = new WebSocket.Server({ noServer: true });
wss1.on('connection', function connection(ws) { wss1.on('connection', function connection(ws) {
// ... // ...
...@@ -238,7 +229,7 @@ wss2.on('connection', function connection(ws) { ...@@ -238,7 +229,7 @@ wss2.on('connection', function connection(ws) {
}); });
server.on('upgrade', function upgrade(request, socket, head) { server.on('upgrade', function upgrade(request, socket, head) {
const { pathname } = parse(request.url); const pathname = url.parse(request.url).pathname;
if (pathname === '/foo') { if (pathname === '/foo') {
wss1.handleUpgrade(request, socket, head, function done(ws) { wss1.handleUpgrade(request, socket, head, function done(ws) {
...@@ -256,87 +247,42 @@ server.on('upgrade', function upgrade(request, socket, head) { ...@@ -256,87 +247,42 @@ server.on('upgrade', function upgrade(request, socket, head) {
server.listen(8080); server.listen(8080);
``` ```
### Client authentication
```js
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
const server = createServer();
const wss = new WebSocketServer({ noServer: true });
wss.on('connection', function connection(ws, request, client) {
ws.on('message', function message(data) {
console.log(`Received message ${data} from user ${client}`);
});
});
server.on('upgrade', function upgrade(request, socket, head) {
// This function is not defined on purpose. Implement it with your own logic.
authenticate(request, function next(err, client) {
if (err || !client) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request, client);
});
});
});
server.listen(8080);
```
Also see the provided [example][session-parse-example] using `express-session`.
### Server broadcast ### Server broadcast
A client WebSocket broadcasting to all connected WebSocket clients, including
itself.
```js ```js
import WebSocket, { WebSocketServer } from 'ws'; const WebSocket = require('ws');
const wss = new WebSocketServer({ port: 8080 }); const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) { // Broadcast to all.
ws.on('message', function message(data, isBinary) { wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) { wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) { if (client.readyState === WebSocket.OPEN) {
client.send(data, { binary: isBinary }); client.send(data);
} }
}); });
}); };
});
```
A client WebSocket broadcasting to every other connected WebSocket clients,
excluding itself.
```js
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) { wss.on('connection', function connection(ws) {
ws.on('message', function message(data, isBinary) { ws.on('message', function incoming(data) {
// Broadcast to everyone else.
wss.clients.forEach(function each(client) { wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) { if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data, { binary: isBinary }); client.send(data);
} }
}); });
}); });
}); });
``` ```
### Round-trip time ### echo.websocket.org demo
```js ```js
import WebSocket from 'ws'; const WebSocket = require('ws');
const ws = new WebSocket('wss://websocket-echo.com/'); const ws = new WebSocket('wss://echo.websocket.org/', {
origin: 'https://websocket.org'
});
ws.on('open', function open() { ws.on('open', function open() {
console.log('connected'); console.log('connected');
...@@ -347,8 +293,8 @@ ws.on('close', function close() { ...@@ -347,8 +293,8 @@ ws.on('close', function close() {
console.log('disconnected'); console.log('disconnected');
}); });
ws.on('message', function message(data) { ws.on('message', function incoming(data) {
console.log(`Round-trip time: ${Date.now() - data} ms`); console.log(`Roundtrip time: ${Date.now() - data} ms`);
setTimeout(function timeout() { setTimeout(function timeout() {
ws.send(Date.now()); ws.send(Date.now());
...@@ -356,19 +302,6 @@ ws.on('message', function message(data) { ...@@ -356,19 +302,6 @@ ws.on('message', function message(data) {
}); });
``` ```
### Use the Node.js streams API
```js
import WebSocket, { createWebSocketStream } from 'ws';
const ws = new WebSocket('wss://websocket-echo.com/');
const duplex = createWebSocketStream(ws, { encoding: 'utf8' });
duplex.pipe(process.stdout);
process.stdin.pipe(duplex);
```
### Other examples ### Other examples
For a full example with a browser client communicating with a ws server, see the For a full example with a browser client communicating with a ws server, see the
...@@ -376,6 +309,30 @@ examples folder. ...@@ -376,6 +309,30 @@ examples folder.
Otherwise, see the test cases. Otherwise, see the test cases.
## Error handling best practices
```js
// If the WebSocket is closed before the following send is attempted
ws.send('something');
// Errors (both immediate and async write errors) can be detected in an optional
// callback. The callback is also the only way of being notified that data has
// actually been sent.
ws.send('something', function ack(error) {
// If error is not defined, the send has been completed, otherwise the error
// object will indicate what failed.
});
// Immediate errors can also be handled with `try...catch`, but **note** that
// since sends are inherently asynchronous, socket write failures will *not* be
// captured when this technique is used.
try {
ws.send('something');
} catch (e) {
/* handle error */
}
```
## FAQ ## FAQ
### How to get the IP address of the client? ### How to get the IP address of the client?
...@@ -383,12 +340,12 @@ Otherwise, see the test cases. ...@@ -383,12 +340,12 @@ Otherwise, see the test cases.
The remote IP address can be obtained from the raw socket. The remote IP address can be obtained from the raw socket.
```js ```js
import { WebSocketServer } from 'ws'; const WebSocket = require('ws');
const wss = new WebSocketServer({ port: 8080 }); const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws, req) { wss.on('connection', function connection(ws, req) {
const ip = req.socket.remoteAddress; const ip = req.connection.remoteAddress;
}); });
``` ```
...@@ -397,7 +354,7 @@ the `X-Forwarded-For` header. ...@@ -397,7 +354,7 @@ the `X-Forwarded-For` header.
```js ```js
wss.on('connection', function connection(ws, req) { wss.on('connection', function connection(ws, req) {
const ip = req.headers['x-forwarded-for'].split(',')[0].trim(); const ip = req.headers['x-forwarded-for'].split(/\s*,\s*/)[0];
}); });
``` ```
...@@ -411,13 +368,15 @@ In these cases ping messages can be used as a means to verify that the remote ...@@ -411,13 +368,15 @@ In these cases ping messages can be used as a means to verify that the remote
endpoint is still responsive. endpoint is still responsive.
```js ```js
import { WebSocketServer } from 'ws'; const WebSocket = require('ws');
function noop() {}
function heartbeat() { function heartbeat() {
this.isAlive = true; this.isAlive = true;
} }
const wss = new WebSocketServer({ port: 8080 }); const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) { wss.on('connection', function connection(ws) {
ws.isAlive = true; ws.isAlive = true;
...@@ -429,13 +388,9 @@ const interval = setInterval(function ping() { ...@@ -429,13 +388,9 @@ const interval = setInterval(function ping() {
if (ws.isAlive === false) return ws.terminate(); if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false; ws.isAlive = false;
ws.ping(); ws.ping(noop);
}); });
}, 30000); }, 30000);
wss.on('close', function close() {
clearInterval(interval);
});
``` ```
Pong messages are automatically sent in response to ping messages as required by Pong messages are automatically sent in response to ping messages as required by
...@@ -446,21 +401,20 @@ without knowing it. You might want to add a ping listener on your clients to ...@@ -446,21 +401,20 @@ without knowing it. You might want to add a ping listener on your clients to
prevent that. A simple implementation would be: prevent that. A simple implementation would be:
```js ```js
import WebSocket from 'ws'; const WebSocket = require('ws');
function heartbeat() { function heartbeat() {
clearTimeout(this.pingTimeout); clearTimeout(this.pingTimeout);
// Use `WebSocket#terminate()`, which immediately destroys the connection, // Use `WebSocket#terminate()` and not `WebSocket#close()`. Delay should be
// instead of `WebSocket#close()`, which waits for the close timer. // equal to the interval at which your server sends out pings plus a
// Delay should be equal to the interval at which your server // conservative assumption of the latency.
// sends out pings plus a conservative assumption of the latency.
this.pingTimeout = setTimeout(() => { this.pingTimeout = setTimeout(() => {
this.terminate(); this.terminate();
}, 30000 + 1000); }, 30000 + 1000);
} }
const client = new WebSocket('wss://websocket-echo.com/'); const client = new WebSocket('wss://echo.websocket.org/');
client.on('open', heartbeat); client.on('open', heartbeat);
client.on('ping', heartbeat); client.on('ping', heartbeat);
...@@ -482,14 +436,14 @@ We're using the GitHub [releases][changelog] for changelog entries. ...@@ -482,14 +436,14 @@ We're using the GitHub [releases][changelog] for changelog entries.
[MIT](LICENSE) [MIT](LICENSE)
[changelog]: https://github.com/websockets/ws/releases
[client-report]: http://websockets.github.io/ws/autobahn/clients/
[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent [https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent
[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent
[client-report]: http://websockets.github.io/ws/autobahn/clients/
[server-report]: http://websockets.github.io/ws/autobahn/servers/
[permessage-deflate]: https://tools.ietf.org/html/rfc7692
[changelog]: https://github.com/websockets/ws/releases
[node-zlib-bug]: https://github.com/nodejs/node/issues/8871 [node-zlib-bug]: https://github.com/nodejs/node/issues/8871
[node-zlib-deflaterawdocs]: [node-zlib-deflaterawdocs]:
https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options
[permessage-deflate]: https://tools.ietf.org/html/rfc7692 [ws-server-options]:
[server-report]: http://websockets.github.io/ws/autobahn/servers/ https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback
[session-parse-example]: ./examples/express-session-parse
[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent
[ws-server-options]: ./doc/ws.md#new-websocketserveroptions-callback
'use strict'; 'use strict';
module.exports = function () { module.exports = function() {
throw new Error( throw new Error(
'ws does not work in the browser. Browser clients must use the native ' + 'ws does not work in the browser. Browser clients must use the native ' +
'WebSocket object' 'WebSocket object'
......
...@@ -2,12 +2,8 @@ ...@@ -2,12 +2,8 @@
const WebSocket = require('./lib/websocket'); const WebSocket = require('./lib/websocket');
WebSocket.createWebSocketStream = require('./lib/stream');
WebSocket.Server = require('./lib/websocket-server'); WebSocket.Server = require('./lib/websocket-server');
WebSocket.Receiver = require('./lib/receiver'); WebSocket.Receiver = require('./lib/receiver');
WebSocket.Sender = require('./lib/sender'); WebSocket.Sender = require('./lib/sender');
WebSocket.WebSocket = WebSocket;
WebSocket.WebSocketServer = WebSocket.Server;
module.exports = WebSocket; module.exports = WebSocket;
'use strict'; 'use strict';
const { EMPTY_BUFFER } = require('./constants');
/** /**
* Merges an array of buffers into a new buffer. * Merges an array of buffers into a new buffer.
* *
...@@ -11,20 +9,15 @@ const { EMPTY_BUFFER } = require('./constants'); ...@@ -11,20 +9,15 @@ const { EMPTY_BUFFER } = require('./constants');
* @public * @public
*/ */
function concat(list, totalLength) { function concat(list, totalLength) {
if (list.length === 0) return EMPTY_BUFFER;
if (list.length === 1) return list[0];
const target = Buffer.allocUnsafe(totalLength); const target = Buffer.allocUnsafe(totalLength);
let offset = 0; var offset = 0;
for (let i = 0; i < list.length; i++) { for (var i = 0; i < list.length; i++) {
const buf = list[i]; const buf = list[i];
target.set(buf, offset); buf.copy(target, offset);
offset += buf.length; offset += buf.length;
} }
if (offset < totalLength) return target.slice(0, offset);
return target; return target;
} }
...@@ -39,7 +32,7 @@ function concat(list, totalLength) { ...@@ -39,7 +32,7 @@ function concat(list, totalLength) {
* @public * @public
*/ */
function _mask(source, mask, output, offset, length) { function _mask(source, mask, output, offset, length) {
for (let i = 0; i < length; i++) { for (var i = 0; i < length; i++) {
output[offset + i] = source[i] ^ mask[i & 3]; output[offset + i] = source[i] ^ mask[i & 3];
} }
} }
...@@ -52,76 +45,28 @@ function _mask(source, mask, output, offset, length) { ...@@ -52,76 +45,28 @@ function _mask(source, mask, output, offset, length) {
* @public * @public
*/ */
function _unmask(buffer, mask) { function _unmask(buffer, mask) {
for (let i = 0; i < buffer.length; i++) { // Required until https://github.com/nodejs/node/issues/9006 is resolved.
const length = buffer.length;
for (var i = 0; i < length; i++) {
buffer[i] ^= mask[i & 3]; buffer[i] ^= mask[i & 3];
} }
} }
/** try {
* Converts a buffer to an `ArrayBuffer`.
*
* @param {Buffer} buf The buffer to convert
* @return {ArrayBuffer} Converted buffer
* @public
*/
function toArrayBuffer(buf) {
if (buf.byteLength === buf.buffer.byteLength) {
return buf.buffer;
}
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
}
/**
* Converts `data` to a `Buffer`.
*
* @param {*} data The data to convert
* @return {Buffer} The buffer
* @throws {TypeError}
* @public
*/
function toBuffer(data) {
toBuffer.readOnly = true;
if (Buffer.isBuffer(data)) return data;
let buf;
if (data instanceof ArrayBuffer) {
buf = Buffer.from(data);
} else if (ArrayBuffer.isView(data)) {
buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
} else {
buf = Buffer.from(data);
toBuffer.readOnly = false;
}
return buf;
}
module.exports = {
concat,
mask: _mask,
toArrayBuffer,
toBuffer,
unmask: _unmask
};
/* istanbul ignore else */
if (!process.env.WS_NO_BUFFER_UTIL) {
try {
const bufferUtil = require('bufferutil'); const bufferUtil = require('bufferutil');
const bu = bufferUtil.BufferUtil || bufferUtil;
module.exports.mask = function (source, mask, output, offset, length) { module.exports = {
mask(source, mask, output, offset, length) {
if (length < 48) _mask(source, mask, output, offset, length); if (length < 48) _mask(source, mask, output, offset, length);
else bufferUtil.mask(source, mask, output, offset, length); else bu.mask(source, mask, output, offset, length);
}; },
unmask(buffer, mask) {
module.exports.unmask = function (buffer, mask) {
if (buffer.length < 32) _unmask(buffer, mask); if (buffer.length < 32) _unmask(buffer, mask);
else bufferUtil.unmask(buffer, mask); else bu.unmask(buffer, mask);
},
concat
}; };
} catch (e) { } catch (e) /* istanbul ignore next */ {
// Continue regardless of the error. module.exports = { concat, mask: _mask, unmask: _unmask };
}
} }
...@@ -2,11 +2,9 @@ ...@@ -2,11 +2,9 @@
module.exports = { module.exports = {
BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'],
EMPTY_BUFFER: Buffer.alloc(0),
GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
kListener: Symbol('kListener'),
kStatusCode: Symbol('status-code'), kStatusCode: Symbol('status-code'),
kWebSocket: Symbol('websocket'), kWebSocket: Symbol('websocket'),
EMPTY_BUFFER: Buffer.alloc(0),
NOOP: () => {} NOOP: () => {}
}; };
'use strict'; 'use strict';
const { kForOnEventAttribute, kListener } = require('./constants');
const kCode = Symbol('kCode');
const kData = Symbol('kData');
const kError = Symbol('kError');
const kMessage = Symbol('kMessage');
const kReason = Symbol('kReason');
const kTarget = Symbol('kTarget');
const kType = Symbol('kType');
const kWasClean = Symbol('kWasClean');
/** /**
* Class representing an event. * Class representing an event.
*
* @private
*/ */
class Event { class Event {
/** /**
* Create a new `Event`. * Create a new `Event`.
* *
* @param {String} type The name of the event * @param {String} type The name of the event
* @throws {TypeError} If the `type` argument is not specified * @param {Object} target A reference to the target to which the event was dispatched
*/ */
constructor(type) { constructor(type, target) {
this[kTarget] = null; this.target = target;
this[kType] = type; this.type = type;
} }
}
/** /**
* @type {*} * Class representing a message event.
*
* @extends Event
* @private
*/ */
get target() { class MessageEvent extends Event {
return this[kTarget];
}
/** /**
* @type {String} * Create a new `MessageEvent`.
*
* @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data
* @param {WebSocket} target A reference to the target to which the event was dispatched
*/ */
get type() { constructor(data, target) {
return this[kType]; super('message', target);
this.data = data;
} }
} }
Object.defineProperty(Event.prototype, 'target', { enumerable: true });
Object.defineProperty(Event.prototype, 'type', { enumerable: true });
/** /**
* Class representing a close event. * Class representing a close event.
* *
* @extends Event * @extends Event
* @private
*/ */
class CloseEvent extends Event { class CloseEvent extends Event {
/** /**
* Create a new `CloseEvent`. * Create a new `CloseEvent`.
* *
* @param {String} type The name of the event * @param {Number} code The status code explaining why the connection is being closed
* @param {Object} [options] A dictionary object that allows for setting * @param {String} reason A human-readable string explaining why the connection is closing
* attributes via object members of the same name * @param {WebSocket} target A reference to the target to which the event was dispatched
* @param {Number} [options.code=0] The status code explaining why the
* connection was closed
* @param {String} [options.reason=''] A human-readable string explaining why
* the connection was closed
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
* connection was cleanly closed
*/
constructor(type, options = {}) {
super(type);
this[kCode] = options.code === undefined ? 0 : options.code;
this[kReason] = options.reason === undefined ? '' : options.reason;
this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
}
/**
* @type {Number}
*/
get code() {
return this[kCode];
}
/**
* @type {String}
*/ */
get reason() { constructor(code, reason, target) {
return this[kReason]; super('close', target);
}
/** this.wasClean = target._closeFrameReceived && target._closeFrameSent;
* @type {Boolean} this.reason = reason;
*/ this.code = code;
get wasClean() {
return this[kWasClean];
} }
} }
Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
/** /**
* Class representing an error event. * Class representing an open event.
* *
* @extends Event * @extends Event
* @private
*/ */
class ErrorEvent extends Event { class OpenEvent extends Event {
/** /**
* Create a new `ErrorEvent`. * Create a new `OpenEvent`.
* *
* @param {String} type The name of the event * @param {WebSocket} target A reference to the target to which the event was dispatched
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.error=null] The error that generated this event
* @param {String} [options.message=''] The error message
*/
constructor(type, options = {}) {
super(type);
this[kError] = options.error === undefined ? null : options.error;
this[kMessage] = options.message === undefined ? '' : options.message;
}
/**
* @type {*}
*/
get error() {
return this[kError];
}
/**
* @type {String}
*/ */
get message() { constructor(target) {
return this[kMessage]; super('open', target);
} }
} }
Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
/** /**
* Class representing a message event. * Class representing an error event.
* *
* @extends Event * @extends Event
* @private
*/ */
class MessageEvent extends Event { class ErrorEvent extends Event {
/** /**
* Create a new `MessageEvent`. * Create a new `ErrorEvent`.
* *
* @param {String} type The name of the event * @param {Object} error The error that generated this event
* @param {Object} [options] A dictionary object that allows for setting * @param {WebSocket} target A reference to the target to which the event was dispatched
* attributes via object members of the same name
* @param {*} [options.data=null] The message content
*/ */
constructor(type, options = {}) { constructor(error, target) {
super(type); super('error', target);
this[kData] = options.data === undefined ? null : options.data;
}
/** this.message = error.message;
* @type {*} this.error = error;
*/
get data() {
return this[kData];
} }
} }
Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
/** /**
* This provides methods for emulating the `EventTarget` interface. It's not * This provides methods for emulating the `EventTarget` interface. It's not
* meant to be used directly. * meant to be used directly.
...@@ -177,90 +109,62 @@ const EventTarget = { ...@@ -177,90 +109,62 @@ const EventTarget = {
/** /**
* Register an event listener. * Register an event listener.
* *
* @param {String} type A string representing the event type to listen for * @param {String} method A string representing the event type to listen for
* @param {Function} listener The listener to add * @param {Function} listener The listener to add
* @param {Object} [options] An options object specifies characteristics about
* the event listener
* @param {Boolean} [options.once=false] A `Boolean` indicating that the
* listener should be invoked at most once after being added. If `true`,
* the listener would be automatically removed when invoked.
* @public * @public
*/ */
addEventListener(type, listener, options = {}) { addEventListener(method, listener) {
let wrapper; if (typeof listener !== 'function') return;
if (type === 'message') { function onMessage(data) {
wrapper = function onMessage(data, isBinary) { listener.call(this, new MessageEvent(data, this));
const event = new MessageEvent('message', { }
data: isBinary ? data : data.toString()
});
event[kTarget] = this;
listener.call(this, event);
};
} else if (type === 'close') {
wrapper = function onClose(code, message) {
const event = new CloseEvent('close', {
code,
reason: message.toString(),
wasClean: this._closeFrameReceived && this._closeFrameSent
});
event[kTarget] = this;
listener.call(this, event);
};
} else if (type === 'error') {
wrapper = function onError(error) {
const event = new ErrorEvent('error', {
error,
message: error.message
});
event[kTarget] = this; function onClose(code, message) {
listener.call(this, event); listener.call(this, new CloseEvent(code, message, this));
}; }
} else if (type === 'open') {
wrapper = function onOpen() {
const event = new Event('open');
event[kTarget] = this; function onError(error) {
listener.call(this, event); listener.call(this, new ErrorEvent(error, this));
};
} else {
return;
} }
wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; function onOpen() {
wrapper[kListener] = listener; listener.call(this, new OpenEvent(this));
}
if (options.once) { if (method === 'message') {
this.once(type, wrapper); onMessage._listener = listener;
this.on(method, onMessage);
} else if (method === 'close') {
onClose._listener = listener;
this.on(method, onClose);
} else if (method === 'error') {
onError._listener = listener;
this.on(method, onError);
} else if (method === 'open') {
onOpen._listener = listener;
this.on(method, onOpen);
} else { } else {
this.on(type, wrapper); this.on(method, listener);
} }
}, },
/** /**
* Remove an event listener. * Remove an event listener.
* *
* @param {String} type A string representing the event type to remove * @param {String} method A string representing the event type to remove
* @param {Function} handler The listener to remove * @param {Function} listener The listener to remove
* @public * @public
*/ */
removeEventListener(type, handler) { removeEventListener(method, listener) {
for (const listener of this.listeners(type)) { const listeners = this.listeners(method);
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
this.removeListener(type, listener); for (var i = 0; i < listeners.length; i++) {
break; if (listeners[i] === listener || listeners[i]._listener === listener) {
this.removeListener(method, listeners[i]);
} }
} }
} }
}; };
module.exports = { module.exports = EventTarget;
CloseEvent,
ErrorEvent,
Event,
EventTarget,
MessageEvent
};
'use strict'; 'use strict';
const { tokenChars } = require('./validation'); //
// Allowed token characters:
//
// '!', '#', '$', '%', '&', ''', '*', '+', '-',
// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
//
// tokenChars[32] === 0 // ' '
// tokenChars[33] === 1 // '!'
// tokenChars[34] === 0 // '"'
// ...
//
// prettier-ignore
const tokenChars = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
];
/** /**
* Adds an offer to the map of extension offers or a parameter to the map of * Adds an offer to the map of extension offers or a parameter to the map of
...@@ -13,8 +34,8 @@ const { tokenChars } = require('./validation'); ...@@ -13,8 +34,8 @@ const { tokenChars } = require('./validation');
* @private * @private
*/ */
function push(dest, name, elem) { function push(dest, name, elem) {
if (dest[name] === undefined) dest[name] = [elem]; if (Object.prototype.hasOwnProperty.call(dest, name)) dest[name].push(elem);
else dest[name].push(elem); else dest[name] = [elem];
} }
/** /**
...@@ -25,28 +46,26 @@ function push(dest, name, elem) { ...@@ -25,28 +46,26 @@ function push(dest, name, elem) {
* @public * @public
*/ */
function parse(header) { function parse(header) {
const offers = Object.create(null); const offers = {};
let params = Object.create(null);
let mustUnescape = false; if (header === undefined || header === '') return offers;
let isEscaping = false;
let inQuotes = false; var params = {};
let extensionName; var mustUnescape = false;
let paramName; var isEscaping = false;
let start = -1; var inQuotes = false;
let code = -1; var extensionName;
let end = -1; var paramName;
let i = 0; var start = -1;
var end = -1;
for (; i < header.length; i++) {
code = header.charCodeAt(i); for (var i = 0; i < header.length; i++) {
const code = header.charCodeAt(i);
if (extensionName === undefined) { if (extensionName === undefined) {
if (end === -1 && tokenChars[code] === 1) { if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i; if (start === -1) start = i;
} else if ( } else if (code === 0x20 /* ' ' */ || code === 0x09 /* '\t' */) {
i !== 0 &&
(code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
) {
if (end === -1 && start !== -1) end = i; if (end === -1 && start !== -1) end = i;
} else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
if (start === -1) { if (start === -1) {
...@@ -57,7 +76,7 @@ function parse(header) { ...@@ -57,7 +76,7 @@ function parse(header) {
const name = header.slice(start, end); const name = header.slice(start, end);
if (code === 0x2c) { if (code === 0x2c) {
push(offers, name, params); push(offers, name, params);
params = Object.create(null); params = {};
} else { } else {
extensionName = name; extensionName = name;
} }
...@@ -80,7 +99,7 @@ function parse(header) { ...@@ -80,7 +99,7 @@ function parse(header) {
push(params, header.slice(start, end), true); push(params, header.slice(start, end), true);
if (code === 0x2c) { if (code === 0x2c) {
push(offers, extensionName, params); push(offers, extensionName, params);
params = Object.create(null); params = {};
extensionName = undefined; extensionName = undefined;
} }
...@@ -127,7 +146,7 @@ function parse(header) { ...@@ -127,7 +146,7 @@ function parse(header) {
} }
if (end === -1) end = i; if (end === -1) end = i;
let value = header.slice(start, end); var value = header.slice(start, end);
if (mustUnescape) { if (mustUnescape) {
value = value.replace(/\\/g, ''); value = value.replace(/\\/g, '');
mustUnescape = false; mustUnescape = false;
...@@ -135,7 +154,7 @@ function parse(header) { ...@@ -135,7 +154,7 @@ function parse(header) {
push(params, paramName, value); push(params, paramName, value);
if (code === 0x2c) { if (code === 0x2c) {
push(offers, extensionName, params); push(offers, extensionName, params);
params = Object.create(null); params = {};
extensionName = undefined; extensionName = undefined;
} }
...@@ -147,14 +166,14 @@ function parse(header) { ...@@ -147,14 +166,14 @@ function parse(header) {
} }
} }
if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { if (start === -1 || inQuotes) {
throw new SyntaxError('Unexpected end of input'); throw new SyntaxError('Unexpected end of input');
} }
if (end === -1) end = i; if (end === -1) end = i;
const token = header.slice(start, end); const token = header.slice(start, end);
if (extensionName === undefined) { if (extensionName === undefined) {
push(offers, token, params); push(offers, token, {});
} else { } else {
if (paramName === undefined) { if (paramName === undefined) {
push(params, token, true); push(params, token, true);
...@@ -179,14 +198,14 @@ function parse(header) { ...@@ -179,14 +198,14 @@ function parse(header) {
function format(extensions) { function format(extensions) {
return Object.keys(extensions) return Object.keys(extensions)
.map((extension) => { .map((extension) => {
let configurations = extensions[extension]; var configurations = extensions[extension];
if (!Array.isArray(configurations)) configurations = [configurations]; if (!Array.isArray(configurations)) configurations = [configurations];
return configurations return configurations
.map((params) => { .map((params) => {
return [extension] return [extension]
.concat( .concat(
Object.keys(params).map((k) => { Object.keys(params).map((k) => {
let values = params[k]; var values = params[k];
if (!Array.isArray(values)) values = [values]; if (!Array.isArray(values)) values = [values];
return values return values
.map((v) => (v === true ? k : `${k}=${v}`)) .map((v) => (v === true ? k : `${k}=${v}`))
......
'use strict';
const kDone = Symbol('kDone');
const kRun = Symbol('kRun');
/**
* A very simple job queue with adjustable concurrency. Adapted from
* https://github.com/STRML/async-limiter
*/
class Limiter {
/**
* Creates a new `Limiter`.
*
* @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
* to run concurrently
*/
constructor(concurrency) {
this[kDone] = () => {
this.pending--;
this[kRun]();
};
this.concurrency = concurrency || Infinity;
this.jobs = [];
this.pending = 0;
}
/**
* Adds a job to the queue.
*
* @param {Function} job The job to run
* @public
*/
add(job) {
this.jobs.push(job);
this[kRun]();
}
/**
* Removes a job from the queue and runs it if possible.
*
* @private
*/
[kRun]() {
if (this.pending === this.concurrency) return;
if (this.jobs.length) {
const job = this.jobs.shift();
this.pending++;
job(this[kDone]);
}
}
}
module.exports = Limiter;
'use strict'; 'use strict';
const Limiter = require('async-limiter');
const zlib = require('zlib'); const zlib = require('zlib');
const bufferUtil = require('./buffer-util'); const bufferUtil = require('./buffer-util');
const Limiter = require('./limiter'); const { kStatusCode, NOOP } = require('./constants');
const { kStatusCode } = require('./constants');
const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
const EMPTY_BLOCK = Buffer.from([0x00]);
const kPerMessageDeflate = Symbol('permessage-deflate'); const kPerMessageDeflate = Symbol('permessage-deflate');
const kTotalLength = Symbol('total-length'); const kTotalLength = Symbol('total-length');
const kCallback = Symbol('callback'); const kCallback = Symbol('callback');
...@@ -29,26 +31,24 @@ class PerMessageDeflate { ...@@ -29,26 +31,24 @@ class PerMessageDeflate {
/** /**
* Creates a PerMessageDeflate instance. * Creates a PerMessageDeflate instance.
* *
* @param {Object} [options] Configuration options * @param {Object} options Configuration options
* @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support * @param {Boolean} options.serverNoContextTakeover Request/accept disabling
* for, or request, a custom client window size * of server context takeover
* @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ * @param {Boolean} options.clientNoContextTakeover Advertise/acknowledge
* acknowledge disabling of client context takeover * disabling of client context takeover
* @param {Number} [options.concurrencyLimit=10] The number of concurrent * @param {(Boolean|Number)} options.serverMaxWindowBits Request/confirm the
* calls to zlib
* @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
* use of a custom server window size * use of a custom server window size
* @param {Boolean} [options.serverNoContextTakeover=false] Request/accept * @param {(Boolean|Number)} options.clientMaxWindowBits Advertise support
* disabling of server context takeover * for, or request, a custom client window size
* @param {Number} [options.threshold=1024] Size (in bytes) below which * @param {Object} options.zlibDeflateOptions Options to pass to zlib on deflate
* messages should not be compressed if context takeover is disabled * @param {Object} options.zlibInflateOptions Options to pass to zlib on inflate
* @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on * @param {Number} options.threshold Size (in bytes) below which messages
* deflate * should not be compressed
* @param {Object} [options.zlibInflateOptions] Options to pass to zlib on * @param {Number} options.concurrencyLimit The number of concurrent calls to
* inflate * zlib
* @param {Boolean} [isServer=false] Create the instance in either server or * @param {Boolean} isServer Create the instance in either server or client
* client mode * mode
* @param {Number} [maxPayload=0] The maximum allowed message length * @param {Number} maxPayload The maximum allowed message length
*/ */
constructor(options, isServer, maxPayload) { constructor(options, isServer, maxPayload) {
this._maxPayload = maxPayload | 0; this._maxPayload = maxPayload | 0;
...@@ -66,7 +66,7 @@ class PerMessageDeflate { ...@@ -66,7 +66,7 @@ class PerMessageDeflate {
this._options.concurrencyLimit !== undefined this._options.concurrencyLimit !== undefined
? this._options.concurrencyLimit ? this._options.concurrencyLimit
: 10; : 10;
zlibLimiter = new Limiter(concurrency); zlibLimiter = new Limiter({ concurrency });
} }
} }
...@@ -133,18 +133,8 @@ class PerMessageDeflate { ...@@ -133,18 +133,8 @@ class PerMessageDeflate {
} }
if (this._deflate) { if (this._deflate) {
const callback = this._deflate[kCallback];
this._deflate.close(); this._deflate.close();
this._deflate = null; this._deflate = null;
if (callback) {
callback(
new Error(
'The deflate stream was closed while data was being processed'
)
);
}
} }
} }
...@@ -243,7 +233,7 @@ class PerMessageDeflate { ...@@ -243,7 +233,7 @@ class PerMessageDeflate {
normalizeParams(configurations) { normalizeParams(configurations) {
configurations.forEach((params) => { configurations.forEach((params) => {
Object.keys(params).forEach((key) => { Object.keys(params).forEach((key) => {
let value = params[key]; var value = params[key];
if (value.length > 1) { if (value.length > 1) {
throw new Error(`Parameter "${key}" must have only a single value`); throw new Error(`Parameter "${key}" must have only a single value`);
...@@ -294,7 +284,7 @@ class PerMessageDeflate { ...@@ -294,7 +284,7 @@ class PerMessageDeflate {
} }
/** /**
* Decompress data. Concurrency limited. * Decompress data. Concurrency limited by async-limiter.
* *
* @param {Buffer} data Compressed data * @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Boolean} fin Specifies whether or not this is the last fragment
...@@ -302,7 +292,7 @@ class PerMessageDeflate { ...@@ -302,7 +292,7 @@ class PerMessageDeflate {
* @public * @public
*/ */
decompress(data, fin, callback) { decompress(data, fin, callback) {
zlibLimiter.add((done) => { zlibLimiter.push((done) => {
this._decompress(data, fin, (err, result) => { this._decompress(data, fin, (err, result) => {
done(); done();
callback(err, result); callback(err, result);
...@@ -311,15 +301,15 @@ class PerMessageDeflate { ...@@ -311,15 +301,15 @@ class PerMessageDeflate {
} }
/** /**
* Compress data. Concurrency limited. * Compress data. Concurrency limited by async-limiter.
* *
* @param {(Buffer|String)} data Data to compress * @param {Buffer} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback * @param {Function} callback Callback
* @public * @public
*/ */
compress(data, fin, callback) { compress(data, fin, callback) {
zlibLimiter.add((done) => { zlibLimiter.push((done) => {
this._compress(data, fin, (err, result) => { this._compress(data, fin, (err, result) => {
done(); done();
callback(err, result); callback(err, result);
...@@ -345,10 +335,9 @@ class PerMessageDeflate { ...@@ -345,10 +335,9 @@ class PerMessageDeflate {
? zlib.Z_DEFAULT_WINDOWBITS ? zlib.Z_DEFAULT_WINDOWBITS
: this.params[key]; : this.params[key];
this._inflate = zlib.createInflateRaw({ this._inflate = zlib.createInflateRaw(
...this._options.zlibInflateOptions, Object.assign({}, this._options.zlibInflateOptions, { windowBits })
windowBits );
});
this._inflate[kPerMessageDeflate] = this; this._inflate[kPerMessageDeflate] = this;
this._inflate[kTotalLength] = 0; this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = []; this._inflate[kBuffers] = [];
...@@ -376,16 +365,12 @@ class PerMessageDeflate { ...@@ -376,16 +365,12 @@ class PerMessageDeflate {
this._inflate[kTotalLength] this._inflate[kTotalLength]
); );
if (this._inflate._readableState.endEmitted) { if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._inflate.close(); this._inflate.close();
this._inflate = null; this._inflate = null;
} else { } else {
this._inflate[kTotalLength] = 0; this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = []; this._inflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._inflate.reset();
}
} }
callback(null, data); callback(null, data);
...@@ -395,12 +380,17 @@ class PerMessageDeflate { ...@@ -395,12 +380,17 @@ class PerMessageDeflate {
/** /**
* Compress data. * Compress data.
* *
* @param {(Buffer|String)} data Data to compress * @param {Buffer} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback * @param {Function} callback Callback
* @private * @private
*/ */
_compress(data, fin, callback) { _compress(data, fin, callback) {
if (!data || data.length === 0) {
process.nextTick(callback, null, EMPTY_BLOCK);
return;
}
const endpoint = this._isServer ? 'server' : 'client'; const endpoint = this._isServer ? 'server' : 'client';
if (!this._deflate) { if (!this._deflate) {
...@@ -410,46 +400,48 @@ class PerMessageDeflate { ...@@ -410,46 +400,48 @@ class PerMessageDeflate {
? zlib.Z_DEFAULT_WINDOWBITS ? zlib.Z_DEFAULT_WINDOWBITS
: this.params[key]; : this.params[key];
this._deflate = zlib.createDeflateRaw({ this._deflate = zlib.createDeflateRaw(
...this._options.zlibDeflateOptions, Object.assign({}, this._options.zlibDeflateOptions, { windowBits })
windowBits );
});
this._deflate[kTotalLength] = 0; this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = []; this._deflate[kBuffers] = [];
//
// An `'error'` event is emitted, only on Node.js < 10.0.0, if the
// `zlib.DeflateRaw` instance is closed while data is being processed.
// This can happen if `PerMessageDeflate#cleanup()` is called at the wrong
// time due to an abnormal WebSocket closure.
//
this._deflate.on('error', NOOP);
this._deflate.on('data', deflateOnData); this._deflate.on('data', deflateOnData);
} }
this._deflate[kCallback] = callback;
this._deflate.write(data); this._deflate.write(data);
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
if (!this._deflate) { if (!this._deflate) {
// //
// The deflate stream was closed while data was being processed. // This `if` statement is only needed for Node.js < 10.0.0 because as of
// commit https://github.com/nodejs/node/commit/5e3f5164, the flush
// callback is no longer called if the deflate stream is closed while
// data is being processed.
// //
return; return;
} }
let data = bufferUtil.concat( var data = bufferUtil.concat(
this._deflate[kBuffers], this._deflate[kBuffers],
this._deflate[kTotalLength] this._deflate[kTotalLength]
); );
if (fin) data = data.slice(0, data.length - 4); if (fin) data = data.slice(0, data.length - 4);
// if (fin && this.params[`${endpoint}_no_context_takeover`]) {
// Ensure that the callback will not be called again in this._deflate.close();
// `PerMessageDeflate#cleanup()`. this._deflate = null;
// } else {
this._deflate[kCallback] = null;
this._deflate[kTotalLength] = 0; this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = []; this._deflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._deflate.reset();
} }
callback(null, data); callback(null, data);
...@@ -488,7 +480,6 @@ function inflateOnData(chunk) { ...@@ -488,7 +480,6 @@ function inflateOnData(chunk) {
} }
this[kError] = new RangeError('Max payload size exceeded'); this[kError] = new RangeError('Max payload size exceeded');
this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
this[kError][kStatusCode] = 1009; this[kError][kStatusCode] = 1009;
this.removeListener('data', inflateOnData); this.removeListener('data', inflateOnData);
this.reset(); this.reset();
......
'use strict'; 'use strict';
const { Writable } = require('stream'); const stream = require('stream');
const PerMessageDeflate = require('./permessage-deflate'); const PerMessageDeflate = require('./permessage-deflate');
const { const bufferUtil = require('./buffer-util');
BINARY_TYPES, const validation = require('./validation');
EMPTY_BUFFER, const constants = require('./constants');
kStatusCode,
kWebSocket
} = require('./constants');
const { concat, toArrayBuffer, unmask } = require('./buffer-util');
const { isValidStatusCode, isValidUTF8 } = require('./validation');
const GET_INFO = 0; const GET_INFO = 0;
const GET_PAYLOAD_LENGTH_16 = 1; const GET_PAYLOAD_LENGTH_16 = 1;
...@@ -22,31 +17,23 @@ const INFLATING = 5; ...@@ -22,31 +17,23 @@ const INFLATING = 5;
/** /**
* HyBi Receiver implementation. * HyBi Receiver implementation.
* *
* @extends Writable * @extends stream.Writable
*/ */
class Receiver extends Writable { class Receiver extends stream.Writable {
/** /**
* Creates a Receiver instance. * Creates a Receiver instance.
* *
* @param {Object} [options] Options object * @param {String} binaryType The type for binary data
* @param {String} [options.binaryType=nodebuffer] The type for binary data * @param {Object} extensions An object containing the negotiated extensions
* @param {Object} [options.extensions] An object containing the negotiated * @param {Number} maxPayload The maximum allowed message length
* extensions
* @param {Boolean} [options.isServer=false] Specifies whether to operate in
* client or server mode
* @param {Number} [options.maxPayload=0] The maximum allowed message length
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
*/ */
constructor(options = {}) { constructor(binaryType, extensions, maxPayload) {
super(); super();
this._binaryType = options.binaryType || BINARY_TYPES[0]; this._binaryType = binaryType || constants.BINARY_TYPES[0];
this._extensions = options.extensions || {}; this[constants.kWebSocket] = undefined;
this._isServer = !!options.isServer; this._extensions = extensions || {};
this._maxPayload = options.maxPayload | 0; this._maxPayload = maxPayload | 0;
this._skipUTF8Validation = !!options.skipUTF8Validation;
this[kWebSocket] = undefined;
this._bufferedBytes = 0; this._bufferedBytes = 0;
this._buffers = []; this._buffers = [];
...@@ -73,7 +60,6 @@ class Receiver extends Writable { ...@@ -73,7 +60,6 @@ class Receiver extends Writable {
* @param {Buffer} chunk The chunk of data to write * @param {Buffer} chunk The chunk of data to write
* @param {String} encoding The character encoding of `chunk` * @param {String} encoding The character encoding of `chunk`
* @param {Function} cb Callback * @param {Function} cb Callback
* @private
*/ */
_write(chunk, encoding, cb) { _write(chunk, encoding, cb) {
if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
...@@ -105,12 +91,11 @@ class Receiver extends Writable { ...@@ -105,12 +91,11 @@ class Receiver extends Writable {
do { do {
const buf = this._buffers[0]; const buf = this._buffers[0];
const offset = dst.length - n;
if (n >= buf.length) { if (n >= buf.length) {
dst.set(this._buffers.shift(), offset); this._buffers.shift().copy(dst, dst.length - n);
} else { } else {
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); buf.copy(dst, dst.length - n, 0, n);
this._buffers[0] = buf.slice(n); this._buffers[0] = buf.slice(n);
} }
...@@ -127,7 +112,7 @@ class Receiver extends Writable { ...@@ -127,7 +112,7 @@ class Receiver extends Writable {
* @private * @private
*/ */
startLoop(cb) { startLoop(cb) {
let err; var err;
this._loop = true; this._loop = true;
do { do {
...@@ -173,26 +158,14 @@ class Receiver extends Writable { ...@@ -173,26 +158,14 @@ class Receiver extends Writable {
if ((buf[0] & 0x30) !== 0x00) { if ((buf[0] & 0x30) !== 0x00) {
this._loop = false; this._loop = false;
return error( return error(RangeError, 'RSV2 and RSV3 must be clear', true, 1002);
RangeError,
'RSV2 and RSV3 must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_RSV_2_3'
);
} }
const compressed = (buf[0] & 0x40) === 0x40; const compressed = (buf[0] & 0x40) === 0x40;
if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
this._loop = false; this._loop = false;
return error( return error(RangeError, 'RSV1 must be clear', true, 1002);
RangeError,
'RSV1 must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_RSV_1'
);
} }
this._fin = (buf[0] & 0x80) === 0x80; this._fin = (buf[0] & 0x80) === 0x80;
...@@ -202,61 +175,31 @@ class Receiver extends Writable { ...@@ -202,61 +175,31 @@ class Receiver extends Writable {
if (this._opcode === 0x00) { if (this._opcode === 0x00) {
if (compressed) { if (compressed) {
this._loop = false; this._loop = false;
return error( return error(RangeError, 'RSV1 must be clear', true, 1002);
RangeError,
'RSV1 must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_RSV_1'
);
} }
if (!this._fragmented) { if (!this._fragmented) {
this._loop = false; this._loop = false;
return error( return error(RangeError, 'invalid opcode 0', true, 1002);
RangeError,
'invalid opcode 0',
true,
1002,
'WS_ERR_INVALID_OPCODE'
);
} }
this._opcode = this._fragmented; this._opcode = this._fragmented;
} else if (this._opcode === 0x01 || this._opcode === 0x02) { } else if (this._opcode === 0x01 || this._opcode === 0x02) {
if (this._fragmented) { if (this._fragmented) {
this._loop = false; this._loop = false;
return error( return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
'WS_ERR_INVALID_OPCODE'
);
} }
this._compressed = compressed; this._compressed = compressed;
} else if (this._opcode > 0x07 && this._opcode < 0x0b) { } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
if (!this._fin) { if (!this._fin) {
this._loop = false; this._loop = false;
return error( return error(RangeError, 'FIN must be set', true, 1002);
RangeError,
'FIN must be set',
true,
1002,
'WS_ERR_EXPECTED_FIN'
);
} }
if (compressed) { if (compressed) {
this._loop = false; this._loop = false;
return error( return error(RangeError, 'RSV1 must be clear', true, 1002);
RangeError,
'RSV1 must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_RSV_1'
);
} }
if (this._payloadLength > 0x7d) { if (this._payloadLength > 0x7d) {
...@@ -265,46 +208,17 @@ class Receiver extends Writable { ...@@ -265,46 +208,17 @@ class Receiver extends Writable {
RangeError, RangeError,
`invalid payload length ${this._payloadLength}`, `invalid payload length ${this._payloadLength}`,
true, true,
1002, 1002
'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
); );
} }
} else { } else {
this._loop = false; this._loop = false;
return error( return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
'WS_ERR_INVALID_OPCODE'
);
} }
if (!this._fin && !this._fragmented) this._fragmented = this._opcode; if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
this._masked = (buf[1] & 0x80) === 0x80; this._masked = (buf[1] & 0x80) === 0x80;
if (this._isServer) {
if (!this._masked) {
this._loop = false;
return error(
RangeError,
'MASK must be set',
true,
1002,
'WS_ERR_EXPECTED_MASK'
);
}
} else if (this._masked) {
this._loop = false;
return error(
RangeError,
'MASK must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_MASK'
);
}
if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
else return this.haveLength(); else return this.haveLength();
...@@ -351,8 +265,7 @@ class Receiver extends Writable { ...@@ -351,8 +265,7 @@ class Receiver extends Writable {
RangeError, RangeError,
'Unsupported WebSocket frame: payload length > 2^53 - 1', 'Unsupported WebSocket frame: payload length > 2^53 - 1',
false, false,
1009, 1009
'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
); );
} }
...@@ -371,13 +284,7 @@ class Receiver extends Writable { ...@@ -371,13 +284,7 @@ class Receiver extends Writable {
this._totalPayloadLength += this._payloadLength; this._totalPayloadLength += this._payloadLength;
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
this._loop = false; this._loop = false;
return error( return error(RangeError, 'Max payload size exceeded', false, 1009);
RangeError,
'Max payload size exceeded',
false,
1009,
'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
);
} }
} }
...@@ -408,7 +315,7 @@ class Receiver extends Writable { ...@@ -408,7 +315,7 @@ class Receiver extends Writable {
* @private * @private
*/ */
getData(cb) { getData(cb) {
let data = EMPTY_BUFFER; var data = constants.EMPTY_BUFFER;
if (this._payloadLength) { if (this._payloadLength) {
if (this._bufferedBytes < this._payloadLength) { if (this._bufferedBytes < this._payloadLength) {
...@@ -417,13 +324,7 @@ class Receiver extends Writable { ...@@ -417,13 +324,7 @@ class Receiver extends Writable {
} }
data = this.consume(this._payloadLength); data = this.consume(this._payloadLength);
if (this._masked) bufferUtil.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); if (this._opcode > 0x07) return this.controlMessage(data);
...@@ -436,7 +337,7 @@ class Receiver extends Writable { ...@@ -436,7 +337,7 @@ class Receiver extends Writable {
if (data.length) { if (data.length) {
// //
// This message is not compressed so its length is the sum of the payload // This message is not compressed so its lenght is the sum of the payload
// length of all fragments. // length of all fragments.
// //
this._messageLength = this._totalPayloadLength; this._messageLength = this._totalPayloadLength;
...@@ -463,13 +364,7 @@ class Receiver extends Writable { ...@@ -463,13 +364,7 @@ class Receiver extends Writable {
this._messageLength += buf.length; this._messageLength += buf.length;
if (this._messageLength > this._maxPayload && this._maxPayload > 0) { if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
return cb( return cb(
error( error(RangeError, 'Max payload size exceeded', false, 1009)
RangeError,
'Max payload size exceeded',
false,
1009,
'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
)
); );
} }
...@@ -500,32 +395,26 @@ class Receiver extends Writable { ...@@ -500,32 +395,26 @@ class Receiver extends Writable {
this._fragments = []; this._fragments = [];
if (this._opcode === 2) { if (this._opcode === 2) {
let data; var data;
if (this._binaryType === 'nodebuffer') { if (this._binaryType === 'nodebuffer') {
data = concat(fragments, messageLength); data = toBuffer(fragments, messageLength);
} else if (this._binaryType === 'arraybuffer') { } else if (this._binaryType === 'arraybuffer') {
data = toArrayBuffer(concat(fragments, messageLength)); data = toArrayBuffer(toBuffer(fragments, messageLength));
} else { } else {
data = fragments; data = fragments;
} }
this.emit('message', data, true); this.emit('message', data);
} else { } else {
const buf = concat(fragments, messageLength); const buf = toBuffer(fragments, messageLength);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) { if (!validation.isValidUTF8(buf)) {
this._loop = false; this._loop = false;
return error( return error(Error, 'invalid UTF-8 sequence', true, 1007);
Error,
'invalid UTF-8 sequence',
true,
1007,
'WS_ERR_INVALID_UTF8'
);
} }
this.emit('message', buf, false); this.emit('message', buf.toString());
} }
} }
...@@ -544,42 +433,24 @@ class Receiver extends Writable { ...@@ -544,42 +433,24 @@ class Receiver extends Writable {
this._loop = false; this._loop = false;
if (data.length === 0) { if (data.length === 0) {
this.emit('conclude', 1005, EMPTY_BUFFER); this.emit('conclude', 1005, '');
this.end(); this.end();
} else if (data.length === 1) { } else if (data.length === 1) {
return error( return error(RangeError, 'invalid payload length 1', true, 1002);
RangeError,
'invalid payload length 1',
true,
1002,
'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
);
} else { } else {
const code = data.readUInt16BE(0); const code = data.readUInt16BE(0);
if (!isValidStatusCode(code)) { if (!validation.isValidStatusCode(code)) {
return error( return error(RangeError, `invalid status code ${code}`, true, 1002);
RangeError,
`invalid status code ${code}`,
true,
1002,
'WS_ERR_INVALID_CLOSE_CODE'
);
} }
const buf = data.slice(2); const buf = data.slice(2);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) { if (!validation.isValidUTF8(buf)) {
return error( return error(Error, 'invalid UTF-8 sequence', true, 1007);
Error,
'invalid UTF-8 sequence',
true,
1007,
'WS_ERR_INVALID_UTF8'
);
} }
this.emit('conclude', code, buf); this.emit('conclude', code, buf.toString());
this.end(); this.end();
} }
} else if (this._opcode === 0x09) { } else if (this._opcode === 0x09) {
...@@ -597,22 +468,48 @@ module.exports = Receiver; ...@@ -597,22 +468,48 @@ module.exports = Receiver;
/** /**
* Builds an error object. * Builds an error object.
* *
* @param {function(new:Error|RangeError)} ErrorCtor The error constructor * @param {(Error|RangeError)} ErrorCtor The error constructor
* @param {String} message The error message * @param {String} message The error message
* @param {Boolean} prefix Specifies whether or not to add a default prefix to * @param {Boolean} prefix Specifies whether or not to add a default prefix to
* `message` * `message`
* @param {Number} statusCode The status code * @param {Number} statusCode The status code
* @param {String} errorCode The exposed error code
* @return {(Error|RangeError)} The error * @return {(Error|RangeError)} The error
* @private * @private
*/ */
function error(ErrorCtor, message, prefix, statusCode, errorCode) { function error(ErrorCtor, message, prefix, statusCode) {
const err = new ErrorCtor( const err = new ErrorCtor(
prefix ? `Invalid WebSocket frame: ${message}` : message prefix ? `Invalid WebSocket frame: ${message}` : message
); );
Error.captureStackTrace(err, error); Error.captureStackTrace(err, error);
err.code = errorCode; err[constants.kStatusCode] = statusCode;
err[kStatusCode] = statusCode;
return err; return err;
} }
/**
* Makes a buffer from a list of fragments.
*
* @param {Buffer[]} fragments The list of fragments composing the message
* @param {Number} messageLength The length of the message
* @return {Buffer}
* @private
*/
function toBuffer(fragments, messageLength) {
if (fragments.length === 1) return fragments[0];
if (fragments.length > 1) return bufferUtil.concat(fragments, messageLength);
return constants.EMPTY_BUFFER;
}
/**
* Converts a buffer to an `ArrayBuffer`.
*
* @param {Buffer} buf The buffer to convert
* @return {ArrayBuffer} Converted buffer
*/
function toArrayBuffer(buf) {
if (buf.byteLength === buf.buffer.byteLength) {
return buf.buffer;
}
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
}
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls$" }] */
'use strict'; 'use strict';
const net = require('net'); const crypto = require('crypto');
const tls = require('tls');
const { randomFillSync } = require('crypto');
const PerMessageDeflate = require('./permessage-deflate'); const PerMessageDeflate = require('./permessage-deflate');
const { EMPTY_BUFFER } = require('./constants'); const bufferUtil = require('./buffer-util');
const { isValidStatusCode } = require('./validation'); const validation = require('./validation');
const { mask: applyMask, toBuffer } = require('./buffer-util'); const constants = require('./constants');
const kByteLength = Symbol('kByteLength');
const maskBuffer = Buffer.alloc(4);
/** /**
* HyBi Sender implementation. * HyBi Sender implementation.
...@@ -21,19 +14,11 @@ class Sender { ...@@ -21,19 +14,11 @@ class Sender {
/** /**
* Creates a Sender instance. * Creates a Sender instance.
* *
* @param {(net.Socket|tls.Socket)} socket The connection socket * @param {net.Socket} socket The connection socket
* @param {Object} [extensions] An object containing the negotiated extensions * @param {Object} extensions An object containing the negotiated extensions
* @param {Function} [generateMask] The function used to generate the masking
* key
*/ */
constructor(socket, extensions, generateMask) { constructor(socket, extensions) {
this._extensions = extensions || {}; this._extensions = extensions || {};
if (generateMask) {
this._generateMask = generateMask;
this._maskBuffer = Buffer.alloc(4);
}
this._socket = socket; this._socket = socket;
this._firstFragment = true; this._firstFragment = true;
...@@ -47,288 +32,260 @@ class Sender { ...@@ -47,288 +32,260 @@ class Sender {
/** /**
* Frames a piece of data according to the HyBi WebSocket protocol. * Frames a piece of data according to the HyBi WebSocket protocol.
* *
* @param {(Buffer|String)} data The data to frame * @param {Buffer} data The data to frame
* @param {Object} options Options object * @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode * @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * @param {Boolean} options.readOnly Specifies whether `data` can be modified
* modified * @param {Boolean} options.fin Specifies whether or not to set the FIN bit
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * @param {Boolean} options.mask Specifies whether or not to mask `data`
* RSV1 bit * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit
* @return {(Buffer|String)[]} The framed data * @return {Buffer[]} The framed data as a list of `Buffer` instances
* @public * @public
*/ */
static frame(data, options) { static frame(data, options) {
let mask; const merge = data.length < 1024 || (options.mask && options.readOnly);
let merge = false; var offset = options.mask ? 6 : 2;
let offset = 2; var payloadLength = data.length;
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 (data.length >= 65536) {
offset = 6;
}
let dataLength;
if (typeof data === 'string') {
if (
(!options.mask || skipMasking) &&
options[kByteLength] !== undefined
) {
dataLength = options[kByteLength];
} else {
data = Buffer.from(data);
dataLength = data.length;
}
} else {
dataLength = data.length;
merge = options.mask && options.readOnly && !skipMasking;
}
let payloadLength = dataLength;
if (dataLength >= 65536) {
offset += 8; offset += 8;
payloadLength = 127; payloadLength = 127;
} else if (dataLength > 125) { } else if (data.length > 125) {
offset += 2; offset += 2;
payloadLength = 126; payloadLength = 126;
} }
const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); const target = Buffer.allocUnsafe(merge ? data.length + offset : offset);
target[0] = options.fin ? options.opcode | 0x80 : options.opcode; target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
if (options.rsv1) target[0] |= 0x40; if (options.rsv1) target[0] |= 0x40;
target[1] = payloadLength;
if (payloadLength === 126) { if (payloadLength === 126) {
target.writeUInt16BE(dataLength, 2); target.writeUInt16BE(data.length, 2);
} else if (payloadLength === 127) { } else if (payloadLength === 127) {
target[2] = target[3] = 0; target.writeUInt32BE(0, 2);
target.writeUIntBE(dataLength, 4, 6); target.writeUInt32BE(data.length, 6);
} }
if (!options.mask) return [target, data]; if (!options.mask) {
target[1] = payloadLength;
if (merge) {
data.copy(target, offset);
return [target];
}
target[1] |= 0x80; return [target, data];
}
const mask = crypto.randomBytes(4);
target[1] = payloadLength | 0x80;
target[offset - 4] = mask[0]; target[offset - 4] = mask[0];
target[offset - 3] = mask[1]; target[offset - 3] = mask[1];
target[offset - 2] = mask[2]; target[offset - 2] = mask[2];
target[offset - 1] = mask[3]; target[offset - 1] = mask[3];
if (skipMasking) return [target, data];
if (merge) { if (merge) {
applyMask(data, mask, target, offset, dataLength); bufferUtil.mask(data, mask, target, offset, data.length);
return [target]; return [target];
} }
applyMask(data, mask, data, 0, dataLength); bufferUtil.mask(data, mask, data, 0, data.length);
return [target, data]; return [target, data];
} }
/** /**
* Sends a close message to the other peer. * Sends a close message to the other peer.
* *
* @param {Number} [code] The status code component of the body * @param {(Number|undefined)} code The status code component of the body
* @param {(String|Buffer)} [data] The message component of the body * @param {String} data The message component of the body
* @param {Boolean} [mask=false] Specifies whether or not to mask the message * @param {Boolean} mask Specifies whether or not to mask the message
* @param {Function} [cb] Callback * @param {Function} cb Callback
* @public * @public
*/ */
close(code, data, mask, cb) { close(code, data, mask, cb) {
let buf; var buf;
if (code === undefined) { if (code === undefined) {
buf = EMPTY_BUFFER; buf = constants.EMPTY_BUFFER;
} else if (typeof code !== 'number' || !isValidStatusCode(code)) { } else if (
typeof code !== 'number' ||
!validation.isValidStatusCode(code)
) {
throw new TypeError('First argument must be a valid error code number'); throw new TypeError('First argument must be a valid error code number');
} else if (data === undefined || !data.length) { } else if (data === undefined || data === '') {
buf = Buffer.allocUnsafe(2); buf = Buffer.allocUnsafe(2);
buf.writeUInt16BE(code, 0); buf.writeUInt16BE(code, 0);
} else { } else {
const length = Buffer.byteLength(data); buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data));
if (length > 123) {
throw new RangeError('The message must not be greater than 123 bytes');
}
buf = Buffer.allocUnsafe(2 + length);
buf.writeUInt16BE(code, 0); buf.writeUInt16BE(code, 0);
if (typeof data === 'string') {
buf.write(data, 2); buf.write(data, 2);
}
if (this._deflating) {
this.enqueue([this.doClose, buf, mask, cb]);
} else { } else {
buf.set(data, 2); this.doClose(buf, mask, cb);
} }
} }
const options = { /**
[kByteLength]: buf.length, * Frames and sends a close message.
*
* @param {Buffer} data The message to send
* @param {Boolean} mask Specifies whether or not to mask `data`
* @param {Function} cb Callback
* @private
*/
doClose(data, mask, cb) {
this.sendFrame(
Sender.frame(data, {
fin: true, fin: true,
generateMask: this._generateMask, rsv1: false,
mask,
maskBuffer: this._maskBuffer,
opcode: 0x08, opcode: 0x08,
readOnly: false, mask,
rsv1: false readOnly: false
}; }),
cb
if (this._deflating) { );
this.enqueue([this.dispatch, buf, false, options, cb]);
} else {
this.sendFrame(Sender.frame(buf, options), cb);
}
} }
/** /**
* Sends a ping message to the other peer. * Sends a ping message to the other peer.
* *
* @param {*} data The message to send * @param {*} data The message to send
* @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Boolean} mask Specifies whether or not to mask `data`
* @param {Function} [cb] Callback * @param {Function} cb Callback
* @public * @public
*/ */
ping(data, mask, cb) { ping(data, mask, cb) {
let byteLength; var readOnly = true;
let readOnly;
if (typeof data === 'string') { if (!Buffer.isBuffer(data)) {
byteLength = Buffer.byteLength(data); if (data instanceof ArrayBuffer) {
readOnly = false; data = Buffer.from(data);
} else if (ArrayBuffer.isView(data)) {
data = viewToBuffer(data);
} else { } else {
data = toBuffer(data); data = Buffer.from(data);
byteLength = data.length; readOnly = false;
readOnly = toBuffer.readOnly;
} }
if (byteLength > 125) {
throw new RangeError('The data size must not be greater than 125 bytes');
} }
const options = {
[kByteLength]: byteLength,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 0x09,
readOnly,
rsv1: false
};
if (this._deflating) { if (this._deflating) {
this.enqueue([this.dispatch, data, false, options, cb]); this.enqueue([this.doPing, data, mask, readOnly, cb]);
} else { } else {
this.sendFrame(Sender.frame(data, options), cb); this.doPing(data, mask, readOnly, cb);
}
} }
/**
* Frames and sends a ping message.
*
* @param {*} data The message to send
* @param {Boolean} mask Specifies whether or not to mask `data`
* @param {Boolean} readOnly Specifies whether `data` can be modified
* @param {Function} cb Callback
* @private
*/
doPing(data, mask, readOnly, cb) {
this.sendFrame(
Sender.frame(data, {
fin: true,
rsv1: false,
opcode: 0x09,
mask,
readOnly
}),
cb
);
} }
/** /**
* Sends a pong message to the other peer. * Sends a pong message to the other peer.
* *
* @param {*} data The message to send * @param {*} data The message to send
* @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Boolean} mask Specifies whether or not to mask `data`
* @param {Function} [cb] Callback * @param {Function} cb Callback
* @public * @public
*/ */
pong(data, mask, cb) { pong(data, mask, cb) {
let byteLength; var readOnly = true;
let readOnly;
if (typeof data === 'string') { if (!Buffer.isBuffer(data)) {
byteLength = Buffer.byteLength(data); if (data instanceof ArrayBuffer) {
readOnly = false; data = Buffer.from(data);
} else if (ArrayBuffer.isView(data)) {
data = viewToBuffer(data);
} else { } else {
data = toBuffer(data); data = Buffer.from(data);
byteLength = data.length; readOnly = false;
readOnly = toBuffer.readOnly;
} }
if (byteLength > 125) {
throw new RangeError('The data size must not be greater than 125 bytes');
} }
const options = {
[kByteLength]: byteLength,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 0x0a,
readOnly,
rsv1: false
};
if (this._deflating) { if (this._deflating) {
this.enqueue([this.dispatch, data, false, options, cb]); this.enqueue([this.doPong, data, mask, readOnly, cb]);
} else { } else {
this.sendFrame(Sender.frame(data, options), cb); this.doPong(data, mask, readOnly, cb);
} }
} }
/**
* Frames and sends a pong message.
*
* @param {*} data The message to send
* @param {Boolean} mask Specifies whether or not to mask `data`
* @param {Boolean} readOnly Specifies whether `data` can be modified
* @param {Function} cb Callback
* @private
*/
doPong(data, mask, readOnly, cb) {
this.sendFrame(
Sender.frame(data, {
fin: true,
rsv1: false,
opcode: 0x0a,
mask,
readOnly
}),
cb
);
}
/** /**
* Sends a data message to the other peer. * Sends a data message to the other peer.
* *
* @param {*} data The message to send * @param {*} data The message to send
* @param {Object} options Options object * @param {Object} options Options object
* @param {Boolean} [options.binary=false] Specifies whether `data` is binary * @param {Boolean} options.compress Specifies whether or not to compress `data`
* or text * @param {Boolean} options.binary Specifies whether `data` is binary or text
* @param {Boolean} [options.compress=false] Specifies whether or not to * @param {Boolean} options.fin Specifies whether the fragment is the last one
* compress `data` * @param {Boolean} options.mask Specifies whether or not to mask `data`
* @param {Boolean} [options.fin=false] Specifies whether the fragment is the * @param {Function} cb Callback
* last one
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Function} [cb] Callback
* @public * @public
*/ */
send(data, options, cb) { send(data, options, cb) {
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; var opcode = options.binary ? 2 : 1;
let opcode = options.binary ? 2 : 1; var rsv1 = options.compress;
let rsv1 = options.compress; var readOnly = true;
let byteLength;
let readOnly;
if (typeof data === 'string') { if (!Buffer.isBuffer(data)) {
byteLength = Buffer.byteLength(data); if (data instanceof ArrayBuffer) {
readOnly = false; data = Buffer.from(data);
} else if (ArrayBuffer.isView(data)) {
data = viewToBuffer(data);
} else { } else {
data = toBuffer(data); data = Buffer.from(data);
byteLength = data.length; readOnly = false;
readOnly = toBuffer.readOnly;
} }
}
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
if (this._firstFragment) { if (this._firstFragment) {
this._firstFragment = false; this._firstFragment = false;
if ( if (rsv1 && perMessageDeflate) {
rsv1 && rsv1 = data.length >= perMessageDeflate._threshold;
perMessageDeflate &&
perMessageDeflate.params[
perMessageDeflate._isServer
? 'server_no_context_takeover'
: 'client_no_context_takeover'
]
) {
rsv1 = byteLength >= perMessageDeflate._threshold;
} }
this._compress = rsv1; this._compress = rsv1;
} else { } else {
...@@ -340,14 +297,11 @@ class Sender { ...@@ -340,14 +297,11 @@ class Sender {
if (perMessageDeflate) { if (perMessageDeflate) {
const opts = { const opts = {
[kByteLength]: byteLength,
fin: options.fin, fin: options.fin,
generateMask: this._generateMask, rsv1,
mask: options.mask,
maskBuffer: this._maskBuffer,
opcode, opcode,
readOnly, mask: options.mask,
rsv1 readOnly
}; };
if (this._deflating) { if (this._deflating) {
...@@ -358,14 +312,11 @@ class Sender { ...@@ -358,14 +312,11 @@ class Sender {
} else { } else {
this.sendFrame( this.sendFrame(
Sender.frame(data, { Sender.frame(data, {
[kByteLength]: byteLength,
fin: options.fin, fin: options.fin,
generateMask: this._generateMask, rsv1: false,
mask: options.mask,
maskBuffer: this._maskBuffer,
opcode, opcode,
readOnly, mask: options.mask,
rsv1: false readOnly
}), }),
cb cb
); );
...@@ -373,26 +324,17 @@ class Sender { ...@@ -373,26 +324,17 @@ class Sender {
} }
/** /**
* Dispatches a message. * Dispatches a data message.
* *
* @param {(Buffer|String)} data The message to send * @param {Buffer} data The message to send
* @param {Boolean} [compress=false] Specifies whether or not to compress * @param {Boolean} compress Specifies whether or not to compress `data`
* `data`
* @param {Object} options Options object * @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode * @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * @param {Boolean} options.readOnly Specifies whether `data` can be modified
* modified * @param {Boolean} options.fin Specifies whether or not to set the FIN bit
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * @param {Boolean} options.mask Specifies whether or not to mask `data`
* RSV1 bit * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit
* @param {Function} [cb] Callback * @param {Function} cb Callback
* @private * @private
*/ */
dispatch(data, compress, options, cb) { dispatch(data, compress, options, cb) {
...@@ -403,27 +345,8 @@ class Sender { ...@@ -403,27 +345,8 @@ class Sender {
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
this._bufferedBytes += options[kByteLength];
this._deflating = true; this._deflating = true;
perMessageDeflate.compress(data, options.fin, (_, buf) => { perMessageDeflate.compress(data, options.fin, (_, buf) => {
if (this._socket.destroyed) {
const err = new Error(
'The socket was closed while data was being compressed'
);
if (typeof cb === 'function') cb(err);
for (let i = 0; i < this._queue.length; i++) {
const params = this._queue[i];
const callback = params[params.length - 1];
if (typeof callback === 'function') callback(err);
}
return;
}
this._bufferedBytes -= options[kByteLength];
this._deflating = false; this._deflating = false;
options.readOnly = false; options.readOnly = false;
this.sendFrame(Sender.frame(buf, options), cb); this.sendFrame(Sender.frame(buf, options), cb);
...@@ -440,8 +363,8 @@ class Sender { ...@@ -440,8 +363,8 @@ class Sender {
while (!this._deflating && this._queue.length) { while (!this._deflating && this._queue.length) {
const params = this._queue.shift(); const params = this._queue.shift();
this._bufferedBytes -= params[3][kByteLength]; this._bufferedBytes -= params[1].length;
Reflect.apply(params[0], this, params.slice(1)); params[0].apply(this, params.slice(1));
} }
} }
...@@ -452,7 +375,7 @@ class Sender { ...@@ -452,7 +375,7 @@ class Sender {
* @private * @private
*/ */
enqueue(params) { enqueue(params) {
this._bufferedBytes += params[3][kByteLength]; this._bufferedBytes += params[1].length;
this._queue.push(params); this._queue.push(params);
} }
...@@ -460,15 +383,13 @@ class Sender { ...@@ -460,15 +383,13 @@ class Sender {
* Sends a frame. * Sends a frame.
* *
* @param {Buffer[]} list The frame to send * @param {Buffer[]} list The frame to send
* @param {Function} [cb] Callback * @param {Function} cb Callback
* @private * @private
*/ */
sendFrame(list, cb) { sendFrame(list, cb) {
if (list.length === 2) { if (list.length === 2) {
this._socket.cork();
this._socket.write(list[0]); this._socket.write(list[0]);
this._socket.write(list[1], cb); this._socket.write(list[1], cb);
this._socket.uncork();
} else { } else {
this._socket.write(list[0], cb); this._socket.write(list[0], cb);
} }
...@@ -476,3 +397,20 @@ class Sender { ...@@ -476,3 +397,20 @@ class Sender {
} }
module.exports = Sender; module.exports = Sender;
/**
* Converts an `ArrayBuffer` view into a buffer.
*
* @param {(DataView|TypedArray)} view The view to convert
* @return {Buffer} Converted view
* @private
*/
function viewToBuffer(view) {
const buf = Buffer.from(view.buffer);
if (view.byteLength !== view.buffer.byteLength) {
return buf.slice(view.byteOffset, view.byteOffset + view.byteLength);
}
return buf;
}
'use strict';
const { Duplex } = require('stream');
/**
* Emits the `'close'` event on a stream.
*
* @param {Duplex} stream The stream.
* @private
*/
function emitClose(stream) {
stream.emit('close');
}
/**
* The listener of the `'end'` event.
*
* @private
*/
function duplexOnEnd() {
if (!this.destroyed && this._writableState.finished) {
this.destroy();
}
}
/**
* The listener of the `'error'` event.
*
* @param {Error} err The error
* @private
*/
function duplexOnError(err) {
this.removeListener('error', duplexOnError);
this.destroy();
if (this.listenerCount('error') === 0) {
// Do not suppress the throwing behavior.
this.emit('error', err);
}
}
/**
* Wraps a `WebSocket` in a duplex stream.
*
* @param {WebSocket} ws The `WebSocket` to wrap
* @param {Object} [options] The options for the `Duplex` constructor
* @return {Duplex} The duplex stream
* @public
*/
function createWebSocketStream(ws, options) {
let terminateOnDestroy = true;
const duplex = new Duplex({
...options,
autoDestroy: false,
emitClose: false,
objectMode: false,
writableObjectMode: false
});
ws.on('message', function message(msg, isBinary) {
const data =
!isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
if (!duplex.push(data)) ws.pause();
});
ws.once('error', function error(err) {
if (duplex.destroyed) return;
// Prevent `ws.terminate()` from being called by `duplex._destroy()`.
//
// - If the `'error'` event is emitted before the `'open'` event, then
// `ws.terminate()` is a noop as no socket is assigned.
// - Otherwise, the error is re-emitted by the listener of the `'error'`
// event of the `Receiver` object. The listener already closes the
// connection by calling `ws.close()`. This allows a close frame to be
// sent to the other peer. If `ws.terminate()` is called right after this,
// then the close frame might not be sent.
terminateOnDestroy = false;
duplex.destroy(err);
});
ws.once('close', function close() {
if (duplex.destroyed) return;
duplex.push(null);
});
duplex._destroy = function (err, callback) {
if (ws.readyState === ws.CLOSED) {
callback(err);
process.nextTick(emitClose, duplex);
return;
}
let called = false;
ws.once('error', function error(err) {
called = true;
callback(err);
});
ws.once('close', function close() {
if (!called) callback(err);
process.nextTick(emitClose, duplex);
});
if (terminateOnDestroy) ws.terminate();
};
duplex._final = function (callback) {
if (ws.readyState === ws.CONNECTING) {
ws.once('open', function open() {
duplex._final(callback);
});
return;
}
// If the value of the `_socket` property is `null` it means that `ws` is a
// client websocket and the handshake failed. In fact, when this happens, a
// socket is never assigned to the websocket. Wait for the `'error'` event
// that will be emitted by the websocket.
if (ws._socket === null) return;
if (ws._socket._writableState.finished) {
callback();
if (duplex._readableState.endEmitted) duplex.destroy();
} else {
ws._socket.once('finish', function finish() {
// `duplex` is not destroyed here because the `'end'` event will be
// emitted on `duplex` after this `'finish'` event. The EOF signaling
// `null` chunk is, in fact, pushed when the websocket emits `'close'`.
callback();
});
ws.close();
}
};
duplex._read = function () {
if (ws.isPaused) ws.resume();
};
duplex._write = function (chunk, encoding, callback) {
if (ws.readyState === ws.CONNECTING) {
ws.once('open', function open() {
duplex._write(chunk, encoding, callback);
});
return;
}
ws.send(chunk, callback);
};
duplex.on('end', duplexOnEnd);
duplex.on('error', duplexOnError);
return duplex;
}
module.exports = createWebSocketStream;
'use strict';
const { tokenChars } = require('./validation');
/**
* Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
*
* @param {String} header The field value of the header
* @return {Set} The subprotocol names
* @public
*/
function parse(header) {
const protocols = new Set();
let start = -1;
let end = -1;
let i = 0;
for (i; i < header.length; i++) {
const code = header.charCodeAt(i);
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (
i !== 0 &&
(code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
) {
if (end === -1 && start !== -1) end = i;
} else if (code === 0x2c /* ',' */) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
const protocol = header.slice(start, end);
if (protocols.has(protocol)) {
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
}
protocols.add(protocol);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
}
if (start === -1 || end !== -1) {
throw new SyntaxError('Unexpected end of input');
}
const protocol = header.slice(start, i);
if (protocols.has(protocol)) {
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
}
protocols.add(protocol);
return protocols;
}
module.exports = { parse };
'use strict'; 'use strict';
// try {
// Allowed token characters: const isValidUTF8 = require('utf-8-validate');
//
// '!', '#', '$', '%', '&', ''', '*', '+', '-', exports.isValidUTF8 =
// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' typeof isValidUTF8 === 'object'
// ? isValidUTF8.Validation.isValidUTF8 // utf-8-validate@<3.0.0
// tokenChars[32] === 0 // ' ' : isValidUTF8;
// tokenChars[33] === 1 // '!' } catch (e) /* istanbul ignore next */ {
// tokenChars[34] === 0 // '"' exports.isValidUTF8 = () => true;
// ... }
//
// prettier-ignore
const tokenChars = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
];
/** /**
* Checks if a status code is allowed in a close frame. * Checks if a status code is allowed in a close frame.
...@@ -30,96 +18,13 @@ const tokenChars = [ ...@@ -30,96 +18,13 @@ const tokenChars = [
* @return {Boolean} `true` if the status code is valid, else `false` * @return {Boolean} `true` if the status code is valid, else `false`
* @public * @public
*/ */
function isValidStatusCode(code) { exports.isValidStatusCode = (code) => {
return ( return (
(code >= 1000 && (code >= 1000 &&
code <= 1014 && code <= 1013 &&
code !== 1004 && code !== 1004 &&
code !== 1005 && code !== 1005 &&
code !== 1006) || code !== 1006) ||
(code >= 3000 && code <= 4999) (code >= 3000 && code <= 4999)
); );
}
/**
* Checks if a given buffer contains only correct UTF-8.
* Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
* Markus Kuhn.
*
* @param {Buffer} buf The buffer to check
* @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
* @public
*/
function _isValidUTF8(buf) {
const len = buf.length;
let i = 0;
while (i < len) {
if ((buf[i] & 0x80) === 0) {
// 0xxxxxxx
i++;
} else if ((buf[i] & 0xe0) === 0xc0) {
// 110xxxxx 10xxxxxx
if (
i + 1 === len ||
(buf[i + 1] & 0xc0) !== 0x80 ||
(buf[i] & 0xfe) === 0xc0 // Overlong
) {
return false;
}
i += 2;
} else if ((buf[i] & 0xf0) === 0xe0) {
// 1110xxxx 10xxxxxx 10xxxxxx
if (
i + 2 >= len ||
(buf[i + 1] & 0xc0) !== 0x80 ||
(buf[i + 2] & 0xc0) !== 0x80 ||
(buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
(buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
) {
return false;
}
i += 3;
} else if ((buf[i] & 0xf8) === 0xf0) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
if (
i + 3 >= len ||
(buf[i + 1] & 0xc0) !== 0x80 ||
(buf[i + 2] & 0xc0) !== 0x80 ||
(buf[i + 3] & 0xc0) !== 0x80 ||
(buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
(buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
buf[i] > 0xf4 // > U+10FFFF
) {
return false;
}
i += 4;
} else {
return false;
}
}
return true;
}
module.exports = {
isValidStatusCode,
isValidUTF8: _isValidUTF8,
tokenChars
}; };
/* istanbul ignore else */
if (!process.env.WS_NO_UTF_8_VALIDATE) {
try {
const isValidUTF8 = require('utf-8-validate');
module.exports.isValidUTF8 = function (buf) {
return buf.length < 150 ? _isValidUTF8(buf) : isValidUTF8(buf);
};
} catch (e) {
// Continue regardless of the error.
}
}
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */
'use strict'; 'use strict';
const EventEmitter = require('events'); const EventEmitter = require('events');
const crypto = require('crypto');
const http = require('http'); const http = require('http');
const https = require('https');
const net = require('net');
const tls = require('tls');
const { createHash } = require('crypto');
const extension = require('./extension');
const PerMessageDeflate = require('./permessage-deflate'); const PerMessageDeflate = require('./permessage-deflate');
const subprotocol = require('./subprotocol'); const extension = require('./extension');
const constants = require('./constants');
const WebSocket = require('./websocket'); const WebSocket = require('./websocket');
const { GUID, kWebSocket } = require('./constants');
const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
const RUNNING = 0;
const CLOSING = 1;
const CLOSED = 2;
/** /**
* Class representing a WebSocket server. * Class representing a WebSocket server.
...@@ -31,34 +19,24 @@ class WebSocketServer extends EventEmitter { ...@@ -31,34 +19,24 @@ class WebSocketServer extends EventEmitter {
* Create a `WebSocketServer` instance. * Create a `WebSocketServer` instance.
* *
* @param {Object} options Configuration options * @param {Object} options Configuration options
* @param {Number} [options.backlog=511] The maximum length of the queue of * @param {String} options.host The hostname where to bind the server
* pending connections * @param {Number} options.port The port where to bind the server
* @param {Boolean} [options.clientTracking=true] Specifies whether or not to * @param {http.Server} options.server A pre-created HTTP/S server to use
* track clients * @param {Function} options.verifyClient An hook to reject connections
* @param {Function} [options.handleProtocols] A hook to handle protocols * @param {Function} options.handleProtocols An hook to handle protocols
* @param {String} [options.host] The hostname where to bind the server * @param {String} options.path Accept only connections matching this path
* @param {Number} [options.maxPayload=104857600] The maximum allowed message * @param {Boolean} options.noServer Enable no server mode
* size * @param {Boolean} options.clientTracking Specifies whether or not to track clients
* @param {Boolean} [options.noServer=false] Enable no server mode * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate
* @param {String} [options.path] Accept only connections matching this path * @param {Number} options.maxPayload The maximum allowed message size
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable * @param {Function} callback A listener for the `listening` event
* permessage-deflate
* @param {Number} [options.port] The port where to bind the server
* @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
* server to use
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @param {Function} [options.verifyClient] A hook to reject connections
* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
* class to use. It must be the `WebSocket` class or class that extends it
* @param {Function} [callback] A listener for the `listening` event
*/ */
constructor(options, callback) { constructor(options, callback) {
super(); super();
options = { options = Object.assign(
{
maxPayload: 100 * 1024 * 1024, maxPayload: 100 * 1024 * 1024,
skipUTF8Validation: false,
perMessageDeflate: false, perMessageDeflate: false,
handleProtocols: null, handleProtocols: null,
clientTracking: true, clientTracking: true,
...@@ -68,19 +46,14 @@ class WebSocketServer extends EventEmitter { ...@@ -68,19 +46,14 @@ class WebSocketServer extends EventEmitter {
server: null, server: null,
host: null, host: null,
path: null, path: null,
port: null, port: null
WebSocket, },
...options options
}; );
if ( if (options.port == null && !options.server && !options.noServer) {
(options.port == null && !options.server && !options.noServer) ||
(options.port != null && (options.server || options.noServer)) ||
(options.server && options.noServer)
) {
throw new TypeError( throw new TypeError(
'One and only one of the "port", "server", or "noServer" options ' + 'One of the "port", "server", or "noServer" options must be specified'
'must be specified'
); );
} }
...@@ -105,25 +78,20 @@ class WebSocketServer extends EventEmitter { ...@@ -105,25 +78,20 @@ class WebSocketServer extends EventEmitter {
} }
if (this._server) { if (this._server) {
const emitConnection = this.emit.bind(this, 'connection');
this._removeListeners = addListeners(this._server, { this._removeListeners = addListeners(this._server, {
listening: this.emit.bind(this, 'listening'), listening: this.emit.bind(this, 'listening'),
error: this.emit.bind(this, 'error'), error: this.emit.bind(this, 'error'),
upgrade: (req, socket, head) => { upgrade: (req, socket, head) => {
this.handleUpgrade(req, socket, head, emitConnection); this.handleUpgrade(req, socket, head, (ws) => {
this.emit('connection', ws, req);
});
} }
}); });
} }
if (options.perMessageDeflate === true) options.perMessageDeflate = {}; if (options.perMessageDeflate === true) options.perMessageDeflate = {};
if (options.clientTracking) { if (options.clientTracking) this.clients = new Set();
this.clients = new Set();
this._shouldEmitClose = false;
}
this.options = options; this.options = options;
this._state = RUNNING;
} }
/** /**
...@@ -145,58 +113,37 @@ class WebSocketServer extends EventEmitter { ...@@ -145,58 +113,37 @@ class WebSocketServer extends EventEmitter {
} }
/** /**
* Stop the server from accepting new connections and emit the `'close'` event * Close the server.
* when all existing connections are closed.
* *
* @param {Function} [cb] A one-time listener for the `'close'` event * @param {Function} cb Callback
* @public * @public
*/ */
close(cb) { close(cb) {
if (this._state === CLOSED) {
if (cb) {
this.once('close', () => {
cb(new Error('The server is not running'));
});
}
process.nextTick(emitClose, this);
return;
}
if (cb) this.once('close', cb); if (cb) this.once('close', cb);
if (this._state === CLOSING) return; //
this._state = CLOSING; // Terminate all associated clients.
//
if (this.options.noServer || this.options.server) {
if (this._server) {
this._removeListeners();
this._removeListeners = this._server = null;
}
if (this.clients) { if (this.clients) {
if (!this.clients.size) { for (const client of this.clients) client.terminate();
process.nextTick(emitClose, this);
} else {
this._shouldEmitClose = true;
} }
} else {
process.nextTick(emitClose, this);
}
} else {
const server = this._server; const server = this._server;
if (server) {
this._removeListeners(); this._removeListeners();
this._removeListeners = this._server = null; this._removeListeners = this._server = null;
// //
// The HTTP/S server was created internally. Close it, and rely on its // Close the http server if it was internally created.
// `'close'` event.
// //
server.close(() => { if (this.options.port != null) {
emitClose(this); server.close(() => this.emit('close'));
}); return;
}
} }
process.nextTick(emitClose, this);
} }
/** /**
...@@ -221,8 +168,7 @@ class WebSocketServer extends EventEmitter { ...@@ -221,8 +168,7 @@ class WebSocketServer extends EventEmitter {
* Handle a HTTP Upgrade request. * Handle a HTTP Upgrade request.
* *
* @param {http.IncomingMessage} req The request object * @param {http.IncomingMessage} req The request object
* @param {(net.Socket|tls.Socket)} socket The network socket between the * @param {net.Socket} socket The network socket between the server and client
* server and client
* @param {Buffer} head The first packet of the upgraded stream * @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback * @param {Function} cb Callback
* @public * @public
...@@ -230,58 +176,20 @@ class WebSocketServer extends EventEmitter { ...@@ -230,58 +176,20 @@ class WebSocketServer extends EventEmitter {
handleUpgrade(req, socket, head, cb) { handleUpgrade(req, socket, head, cb) {
socket.on('error', socketOnError); socket.on('error', socketOnError);
const key = req.headers['sec-websocket-key'];
const version = +req.headers['sec-websocket-version']; const version = +req.headers['sec-websocket-version'];
if (req.method !== 'GET') {
const message = 'Invalid HTTP method';
abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
return;
}
if (req.headers.upgrade.toLowerCase() !== 'websocket') {
const message = 'Invalid Upgrade header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (!key || !keyRegex.test(key)) {
const message = 'Missing or invalid Sec-WebSocket-Key header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (version !== 8 && version !== 13) {
const message = 'Missing or invalid Sec-WebSocket-Version header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (!this.shouldHandle(req)) {
abortHandshake(socket, 400);
return;
}
const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
let protocols = new Set();
if (secWebSocketProtocol !== undefined) {
try {
protocols = subprotocol.parse(secWebSocketProtocol);
} catch (err) {
const message = 'Invalid Sec-WebSocket-Protocol header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
}
const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
const extensions = {}; const extensions = {};
if ( if (
this.options.perMessageDeflate && req.method !== 'GET' ||
secWebSocketExtensions !== undefined req.headers.upgrade.toLowerCase() !== 'websocket' ||
!req.headers['sec-websocket-key'] ||
(version !== 8 && version !== 13) ||
!this.shouldHandle(req)
) { ) {
return abortHandshake(socket, 400);
}
if (this.options.perMessageDeflate) {
const perMessageDeflate = new PerMessageDeflate( const perMessageDeflate = new PerMessageDeflate(
this.options.perMessageDeflate, this.options.perMessageDeflate,
true, true,
...@@ -289,17 +197,14 @@ class WebSocketServer extends EventEmitter { ...@@ -289,17 +197,14 @@ class WebSocketServer extends EventEmitter {
); );
try { try {
const offers = extension.parse(secWebSocketExtensions); const offers = extension.parse(req.headers['sec-websocket-extensions']);
if (offers[PerMessageDeflate.extensionName]) { if (offers[PerMessageDeflate.extensionName]) {
perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
extensions[PerMessageDeflate.extensionName] = perMessageDeflate; extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
} }
} catch (err) { } catch (err) {
const message = return abortHandshake(socket, 400);
'Invalid or unacceptable Sec-WebSocket-Extensions header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
} }
} }
...@@ -310,7 +215,7 @@ class WebSocketServer extends EventEmitter { ...@@ -310,7 +215,7 @@ class WebSocketServer extends EventEmitter {
const info = { const info = {
origin: origin:
req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
secure: !!(req.socket.authorized || req.socket.encrypted), secure: !!(req.connection.authorized || req.connection.encrypted),
req req
}; };
...@@ -320,15 +225,7 @@ class WebSocketServer extends EventEmitter { ...@@ -320,15 +225,7 @@ class WebSocketServer extends EventEmitter {
return abortHandshake(socket, code || 401, message, headers); return abortHandshake(socket, code || 401, message, headers);
} }
this.completeUpgrade( this.completeUpgrade(extensions, req, socket, head, cb);
extensions,
key,
protocols,
req,
socket,
head,
cb
);
}); });
return; return;
} }
...@@ -336,62 +233,55 @@ class WebSocketServer extends EventEmitter { ...@@ -336,62 +233,55 @@ class WebSocketServer extends EventEmitter {
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
} }
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); this.completeUpgrade(extensions, req, socket, head, cb);
} }
/** /**
* Upgrade the connection to WebSocket. * Upgrade the connection to WebSocket.
* *
* @param {Object} extensions The accepted extensions * @param {Object} extensions The accepted extensions
* @param {String} key The value of the `Sec-WebSocket-Key` header
* @param {Set} protocols The subprotocols
* @param {http.IncomingMessage} req The request object * @param {http.IncomingMessage} req The request object
* @param {(net.Socket|tls.Socket)} socket The network socket between the * @param {net.Socket} socket The network socket between the server and client
* server and client
* @param {Buffer} head The first packet of the upgraded stream * @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback * @param {Function} cb Callback
* @throws {Error} If called more than once with the same socket
* @private * @private
*/ */
completeUpgrade(extensions, key, protocols, req, socket, head, cb) { completeUpgrade(extensions, req, socket, head, cb) {
// //
// Destroy the socket if the client has already sent a FIN packet. // Destroy the socket if the client has already sent a FIN packet.
// //
if (!socket.readable || !socket.writable) return socket.destroy(); if (!socket.readable || !socket.writable) return socket.destroy();
if (socket[kWebSocket]) { const key = crypto
throw new Error( .createHash('sha1')
'server.handleUpgrade() was called more than once with the same ' + .update(req.headers['sec-websocket-key'] + constants.GUID, 'binary')
'socket, possibly due to a misconfiguration'
);
}
if (this._state > RUNNING) return abortHandshake(socket, 503);
const digest = createHash('sha1')
.update(key + GUID)
.digest('base64'); .digest('base64');
const headers = [ const headers = [
'HTTP/1.1 101 Switching Protocols', 'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket', 'Upgrade: websocket',
'Connection: Upgrade', 'Connection: Upgrade',
`Sec-WebSocket-Accept: ${digest}` `Sec-WebSocket-Accept: ${key}`
]; ];
const ws = new this.options.WebSocket(null); const ws = new WebSocket(null);
var protocol = req.headers['sec-websocket-protocol'];
if (protocol) {
protocol = protocol.trim().split(/ *, */);
if (protocols.size) {
// //
// Optionally call external protocol selection handler. // Optionally call external protocol selection handler.
// //
const protocol = this.options.handleProtocols if (this.options.handleProtocols) {
? this.options.handleProtocols(protocols, req) protocol = this.options.handleProtocols(protocol, req);
: protocols.values().next().value; } else {
protocol = protocol[0];
}
if (protocol) { if (protocol) {
headers.push(`Sec-WebSocket-Protocol: ${protocol}`); headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
ws._protocol = protocol; ws.protocol = protocol;
} }
} }
...@@ -412,23 +302,14 @@ class WebSocketServer extends EventEmitter { ...@@ -412,23 +302,14 @@ class WebSocketServer extends EventEmitter {
socket.write(headers.concat('\r\n').join('\r\n')); socket.write(headers.concat('\r\n').join('\r\n'));
socket.removeListener('error', socketOnError); socket.removeListener('error', socketOnError);
ws.setSocket(socket, head, { ws.setSocket(socket, head, this.options.maxPayload);
maxPayload: this.options.maxPayload,
skipUTF8Validation: this.options.skipUTF8Validation
});
if (this.clients) { if (this.clients) {
this.clients.add(ws); this.clients.add(ws);
ws.on('close', () => { ws.on('close', () => this.clients.delete(ws));
this.clients.delete(ws);
if (this._shouldEmitClose && !this.clients.size) {
process.nextTick(emitClose, this);
}
});
} }
cb(ws, req); cb(ws);
} }
} }
...@@ -440,8 +321,7 @@ module.exports = WebSocketServer; ...@@ -440,8 +321,7 @@ module.exports = WebSocketServer;
* *
* @param {EventEmitter} server The event emitter * @param {EventEmitter} server The event emitter
* @param {Object.<String, Function>} map The listeners to add * @param {Object.<String, Function>} map The listeners to add
* @return {Function} A function that will remove the added listeners when * @return {Function} A function that will remove the added listeners when called
* called
* @private * @private
*/ */
function addListeners(server, map) { function addListeners(server, map) {
...@@ -461,12 +341,11 @@ function addListeners(server, map) { ...@@ -461,12 +341,11 @@ function addListeners(server, map) {
* @private * @private
*/ */
function emitClose(server) { function emitClose(server) {
server._state = CLOSED;
server.emit('close'); server.emit('close');
} }
/** /**
* Handle socket errors. * Handle premature socket errors.
* *
* @private * @private
*/ */
...@@ -477,32 +356,25 @@ function socketOnError() { ...@@ -477,32 +356,25 @@ function socketOnError() {
/** /**
* Close the connection when preconditions are not fulfilled. * Close the connection when preconditions are not fulfilled.
* *
* @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request * @param {net.Socket} socket The socket of the upgrade request
* @param {Number} code The HTTP response status code * @param {Number} code The HTTP response status code
* @param {String} [message] The HTTP response body * @param {String} [message] The HTTP response body
* @param {Object} [headers] Additional HTTP response headers * @param {Object} [headers] Additional HTTP response headers
* @private * @private
*/ */
function abortHandshake(socket, code, message, headers) { function abortHandshake(socket, code, message, headers) {
// if (socket.writable) {
// The socket is writable unless the user destroyed or ended it before calling
// `server.handleUpgrade()` or in the `verifyClient` function, which is a user
// error. Handling this does not make much sense as the worst that can happen
// is that some of the data written by the user might be discarded due to the
// call to `socket.end()` below, which triggers an `'error'` event that in
// turn causes the socket to be destroyed.
//
message = message || http.STATUS_CODES[code]; message = message || http.STATUS_CODES[code];
headers = { headers = Object.assign(
{
Connection: 'close', Connection: 'close',
'Content-Type': 'text/html', 'Content-type': 'text/html',
'Content-Length': Buffer.byteLength(message), 'Content-Length': Buffer.byteLength(message)
...headers },
}; headers
);
socket.once('finish', socket.destroy);
socket.end( socket.write(
`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
Object.keys(headers) Object.keys(headers)
.map((h) => `${h}: ${headers[h]}`) .map((h) => `${h}: ${headers[h]}`)
...@@ -510,26 +382,8 @@ function abortHandshake(socket, code, message, headers) { ...@@ -510,26 +382,8 @@ function abortHandshake(socket, code, message, headers) {
'\r\n\r\n' + '\r\n\r\n' +
message message
); );
}
/**
* Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
* one listener for it, otherwise call `abortHandshake()`.
*
* @param {WebSocketServer} server The WebSocket server
* @param {http.IncomingMessage} req The request object
* @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request
* @param {Number} code The HTTP response status code
* @param {String} message The HTTP response body
* @private
*/
function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
if (server.listenerCount('wsClientError')) {
const err = new Error(message);
Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
server.emit('wsClientError', err, socket, req);
} else {
abortHandshake(socket, code, message);
} }
socket.removeListener('error', socketOnError);
socket.destroy();
} }
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Readable$" }] */
'use strict'; 'use strict';
const EventEmitter = require('events'); const EventEmitter = require('events');
const crypto = require('crypto');
const https = require('https'); const https = require('https');
const http = require('http'); const http = require('http');
const net = require('net'); const net = require('net');
const tls = require('tls'); const tls = require('tls');
const { randomBytes, createHash } = require('crypto'); const url = require('url');
const { Readable } = require('stream');
const { URL } = require('url');
const PerMessageDeflate = require('./permessage-deflate'); const PerMessageDeflate = require('./permessage-deflate');
const EventTarget = require('./event-target');
const extension = require('./extension');
const constants = require('./constants');
const Receiver = require('./receiver'); const Receiver = require('./receiver');
const Sender = require('./sender'); const Sender = require('./sender');
const {
BINARY_TYPES,
EMPTY_BUFFER,
GUID,
kForOnEventAttribute,
kListener,
kStatusCode,
kWebSocket,
NOOP
} = require('./constants');
const {
EventTarget: { addEventListener, removeEventListener }
} = require('./event-target');
const { format, parse } = require('./extension');
const { toBuffer } = require('./buffer-util');
const closeTimeout = 30 * 1000;
const kAborted = Symbol('kAborted');
const protocolVersions = [8, 13];
const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; const kWebSocket = constants.kWebSocket;
const protocolVersions = [8, 13];
const closeTimeout = 30 * 1000; // Allow 30 seconds to terminate the connection cleanly.
/** /**
* Class representing a WebSocket. * Class representing a WebSocket.
...@@ -45,53 +29,56 @@ class WebSocket extends EventEmitter { ...@@ -45,53 +29,56 @@ class WebSocket extends EventEmitter {
/** /**
* Create a new `WebSocket`. * Create a new `WebSocket`.
* *
* @param {(String|URL)} address The URL to which to connect * @param {(String|url.Url|url.URL)} address The URL to which to connect
* @param {(String|String[])} [protocols] The subprotocols * @param {(String|String[])} protocols The subprotocols
* @param {Object} [options] Connection options * @param {Object} options Connection options
*/ */
constructor(address, protocols, options) { constructor(address, protocols, options) {
super(); super();
this._binaryType = BINARY_TYPES[0]; this.readyState = WebSocket.CONNECTING;
this._closeCode = 1006; this.protocol = '';
this._binaryType = constants.BINARY_TYPES[0];
this._closeFrameReceived = false; this._closeFrameReceived = false;
this._closeFrameSent = false; this._closeFrameSent = false;
this._closeMessage = EMPTY_BUFFER; this._closeMessage = '';
this._closeTimer = null; this._closeTimer = null;
this._closeCode = 1006;
this._extensions = {}; this._extensions = {};
this._paused = false; this._isServer = true;
this._protocol = '';
this._readyState = WebSocket.CONNECTING;
this._receiver = null; this._receiver = null;
this._sender = null; this._sender = null;
this._socket = null; this._socket = null;
if (address !== null) { if (address !== null) {
this._bufferedAmount = 0; if (Array.isArray(protocols)) {
this._isServer = false; protocols = protocols.join(', ');
this._redirects = 0; } else if (typeof protocols === 'object' && protocols !== null) {
if (protocols === undefined) {
protocols = [];
} else if (!Array.isArray(protocols)) {
if (typeof protocols === 'object' && protocols !== null) {
options = protocols; options = protocols;
protocols = []; protocols = undefined;
} else { }
protocols = [protocols];
initAsClient.call(this, address, protocols, options);
} }
} }
initAsClient(this, address, protocols, options); get CONNECTING() {
} else { return WebSocket.CONNECTING;
this._isServer = true;
} }
get CLOSING() {
return WebSocket.CLOSING;
}
get CLOSED() {
return WebSocket.CLOSED;
}
get OPEN() {
return WebSocket.OPEN;
} }
/** /**
* This deviates from the WHATWG interface since ws doesn't support the * This deviates from the WHATWG interface since ws doesn't support the required
* required default "blob" type (instead we define a custom "nodebuffer" * default "blob" type (instead we define a custom "nodebuffer" type).
* type).
* *
* @type {String} * @type {String}
*/ */
...@@ -100,7 +87,7 @@ class WebSocket extends EventEmitter { ...@@ -100,7 +87,7 @@ class WebSocket extends EventEmitter {
} }
set binaryType(type) { set binaryType(type) {
if (!BINARY_TYPES.includes(type)) return; if (!constants.BINARY_TYPES.includes(type)) return;
this._binaryType = type; this._binaryType = type;
...@@ -114,9 +101,12 @@ class WebSocket extends EventEmitter { ...@@ -114,9 +101,12 @@ class WebSocket extends EventEmitter {
* @type {Number} * @type {Number}
*/ */
get bufferedAmount() { get bufferedAmount() {
if (!this._socket) return this._bufferedAmount; if (!this._socket) return 0;
return this._socket._writableState.length + this._sender._bufferedBytes; //
// `socket.bufferSize` is `undefined` if the socket is closed.
//
return (this._socket.bufferSize || 0) + this._sender._bufferedBytes;
} }
/** /**
...@@ -126,90 +116,22 @@ class WebSocket extends EventEmitter { ...@@ -126,90 +116,22 @@ class WebSocket extends EventEmitter {
return Object.keys(this._extensions).join(); return Object.keys(this._extensions).join();
} }
/**
* @type {Boolean}
*/
get isPaused() {
return this._paused;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onclose() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onerror() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onopen() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onmessage() {
return null;
}
/**
* @type {String}
*/
get protocol() {
return this._protocol;
}
/**
* @type {Number}
*/
get readyState() {
return this._readyState;
}
/**
* @type {String}
*/
get url() {
return this._url;
}
/** /**
* Set up the socket and the internal resources. * Set up the socket and the internal resources.
* *
* @param {(net.Socket|tls.Socket)} socket The network socket between the * @param {net.Socket} socket The network socket between the server and client
* server and client
* @param {Buffer} head The first packet of the upgraded stream * @param {Buffer} head The first packet of the upgraded stream
* @param {Object} options Options object * @param {Number} maxPayload The maximum allowed message size
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Number} [options.maxPayload=0] The maximum allowed message size
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @private * @private
*/ */
setSocket(socket, head, options) { setSocket(socket, head, maxPayload) {
const receiver = new Receiver({ const receiver = new Receiver(
binaryType: this.binaryType, this._binaryType,
extensions: this._extensions, this._extensions,
isServer: this._isServer, maxPayload
maxPayload: options.maxPayload, );
skipUTF8Validation: options.skipUTF8Validation
});
this._sender = new Sender(socket, this._extensions, options.generateMask); this._sender = new Sender(socket, this._extensions);
this._receiver = receiver; this._receiver = receiver;
this._socket = socket; this._socket = socket;
...@@ -233,7 +155,7 @@ class WebSocket extends EventEmitter { ...@@ -233,7 +155,7 @@ class WebSocket extends EventEmitter {
socket.on('end', socketOnEnd); socket.on('end', socketOnEnd);
socket.on('error', socketOnError); socket.on('error', socketOnError);
this._readyState = WebSocket.OPEN; this.readyState = WebSocket.OPEN;
this.emit('open'); this.emit('open');
} }
...@@ -243,8 +165,9 @@ class WebSocket extends EventEmitter { ...@@ -243,8 +165,9 @@ class WebSocket extends EventEmitter {
* @private * @private
*/ */
emitClose() { emitClose() {
this.readyState = WebSocket.CLOSED;
if (!this._socket) { if (!this._socket) {
this._readyState = WebSocket.CLOSED;
this.emit('close', this._closeCode, this._closeMessage); this.emit('close', this._closeCode, this._closeMessage);
return; return;
} }
...@@ -254,7 +177,6 @@ class WebSocket extends EventEmitter { ...@@ -254,7 +177,6 @@ class WebSocket extends EventEmitter {
} }
this._receiver.removeAllListeners(); this._receiver.removeAllListeners();
this._readyState = WebSocket.CLOSED;
this.emit('close', this._closeCode, this._closeMessage); this.emit('close', this._closeCode, this._closeMessage);
} }
...@@ -273,9 +195,8 @@ class WebSocket extends EventEmitter { ...@@ -273,9 +195,8 @@ class WebSocket extends EventEmitter {
* - - - - -|fin|<---------------------+ * - - - - -|fin|<---------------------+
* +---+ * +---+
* *
* @param {Number} [code] Status code explaining why the connection is closing * @param {Number} code Status code explaining why the connection is closing
* @param {(String|Buffer)} [data] The reason why the connection is * @param {String} data A string explaining why the connection is closing
* closing
* @public * @public
*/ */
close(code, data) { close(code, data) {
...@@ -286,17 +207,11 @@ class WebSocket extends EventEmitter { ...@@ -286,17 +207,11 @@ class WebSocket extends EventEmitter {
} }
if (this.readyState === WebSocket.CLOSING) { if (this.readyState === WebSocket.CLOSING) {
if ( if (this._closeFrameSent && this._closeFrameReceived) this._socket.end();
this._closeFrameSent &&
(this._closeFrameReceived || this._receiver._writableState.errorEmitted)
) {
this._socket.end();
}
return; return;
} }
this._readyState = WebSocket.CLOSING; this.readyState = WebSocket.CLOSING;
this._sender.close(code, data, !this._isServer, (err) => { this._sender.close(code, data, !this._isServer, (err) => {
// //
// This error is handled by the `'error'` listener on the socket. We only // This error is handled by the `'error'` listener on the socket. We only
...@@ -306,53 +221,30 @@ class WebSocket extends EventEmitter { ...@@ -306,53 +221,30 @@ class WebSocket extends EventEmitter {
this._closeFrameSent = true; this._closeFrameSent = true;
if ( if (this._socket.writable) {
this._closeFrameReceived || if (this._closeFrameReceived) this._socket.end();
this._receiver._writableState.errorEmitted
) {
this._socket.end();
}
});
// //
// Specify a timeout for the closing handshake to complete. // Ensure that the connection is closed even if the closing handshake
// fails.
// //
this._closeTimer = setTimeout( this._closeTimer = setTimeout(
this._socket.destroy.bind(this._socket), this._socket.destroy.bind(this._socket),
closeTimeout closeTimeout
); );
} }
});
/**
* Pause the socket.
*
* @public
*/
pause() {
if (
this.readyState === WebSocket.CONNECTING ||
this.readyState === WebSocket.CLOSED
) {
return;
}
this._paused = true;
this._socket.pause();
} }
/** /**
* Send a ping. * Send a ping.
* *
* @param {*} [data] The data to send * @param {*} data The data to send
* @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Boolean} mask Indicates whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when the ping is sent * @param {Function} cb Callback which is executed when the ping is sent
* @public * @public
*/ */
ping(data, mask, cb) { ping(data, mask, cb) {
if (this.readyState === WebSocket.CONNECTING) {
throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
}
if (typeof data === 'function') { if (typeof data === 'function') {
cb = data; cb = data;
data = mask = undefined; data = mask = undefined;
...@@ -361,30 +253,30 @@ class WebSocket extends EventEmitter { ...@@ -361,30 +253,30 @@ class WebSocket extends EventEmitter {
mask = undefined; mask = undefined;
} }
if (typeof data === 'number') data = data.toString();
if (this.readyState !== WebSocket.OPEN) { if (this.readyState !== WebSocket.OPEN) {
sendAfterClose(this, data, cb); const err = new Error(
return; `WebSocket is not open: readyState ${this.readyState} ` +
`(${readyStates[this.readyState]})`
);
if (cb) return cb(err);
throw err;
} }
if (typeof data === 'number') data = data.toString();
if (mask === undefined) mask = !this._isServer; if (mask === undefined) mask = !this._isServer;
this._sender.ping(data || EMPTY_BUFFER, mask, cb); this._sender.ping(data || constants.EMPTY_BUFFER, mask, cb);
} }
/** /**
* Send a pong. * Send a pong.
* *
* @param {*} [data] The data to send * @param {*} data The data to send
* @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Boolean} mask Indicates whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when the pong is sent * @param {Function} cb Callback which is executed when the pong is sent
* @public * @public
*/ */
pong(data, mask, cb) { pong(data, mask, cb) {
if (this.readyState === WebSocket.CONNECTING) {
throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
}
if (typeof data === 'function') { if (typeof data === 'function') {
cb = data; cb = data;
data = mask = undefined; data = mask = undefined;
...@@ -393,79 +285,66 @@ class WebSocket extends EventEmitter { ...@@ -393,79 +285,66 @@ class WebSocket extends EventEmitter {
mask = undefined; mask = undefined;
} }
if (typeof data === 'number') data = data.toString();
if (this.readyState !== WebSocket.OPEN) { if (this.readyState !== WebSocket.OPEN) {
sendAfterClose(this, data, cb); const err = new Error(
return; `WebSocket is not open: readyState ${this.readyState} ` +
} `(${readyStates[this.readyState]})`
);
if (mask === undefined) mask = !this._isServer;
this._sender.pong(data || EMPTY_BUFFER, mask, cb);
}
/** if (cb) return cb(err);
* Resume the socket. throw err;
*
* @public
*/
resume() {
if (
this.readyState === WebSocket.CONNECTING ||
this.readyState === WebSocket.CLOSED
) {
return;
} }
this._paused = false; if (typeof data === 'number') data = data.toString();
if (!this._receiver._writableState.needDrain) this._socket.resume(); if (mask === undefined) mask = !this._isServer;
this._sender.pong(data || constants.EMPTY_BUFFER, mask, cb);
} }
/** /**
* Send a data message. * Send a data message.
* *
* @param {*} data The message to send * @param {*} data The message to send
* @param {Object} [options] Options object * @param {Object} options Options object
* @param {Boolean} [options.binary] Specifies whether `data` is binary or * @param {Boolean} options.compress Specifies whether or not to compress `data`
* text * @param {Boolean} options.binary Specifies whether `data` is binary or text
* @param {Boolean} [options.compress] Specifies whether or not to compress * @param {Boolean} options.fin Specifies whether the fragment is the last one
* `data` * @param {Boolean} options.mask Specifies whether or not to mask `data`
* @param {Boolean} [options.fin=true] Specifies whether the fragment is the * @param {Function} cb Callback which is executed when data is written out
* last one
* @param {Boolean} [options.mask] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when data is written out
* @public * @public
*/ */
send(data, options, cb) { send(data, options, cb) {
if (this.readyState === WebSocket.CONNECTING) {
throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
}
if (typeof options === 'function') { if (typeof options === 'function') {
cb = options; cb = options;
options = {}; options = {};
} }
if (typeof data === 'number') data = data.toString();
if (this.readyState !== WebSocket.OPEN) { if (this.readyState !== WebSocket.OPEN) {
sendAfterClose(this, data, cb); const err = new Error(
return; `WebSocket is not open: readyState ${this.readyState} ` +
`(${readyStates[this.readyState]})`
);
if (cb) return cb(err);
throw err;
} }
const opts = { if (typeof data === 'number') data = data.toString();
const opts = Object.assign(
{
binary: typeof data !== 'string', binary: typeof data !== 'string',
mask: !this._isServer, mask: !this._isServer,
compress: true, compress: true,
fin: true, fin: true
...options },
}; options
);
if (!this._extensions[PerMessageDeflate.extensionName]) { if (!this._extensions[PerMessageDeflate.extensionName]) {
opts.compress = false; opts.compress = false;
} }
this._sender.send(data || EMPTY_BUFFER, opts, cb); this._sender.send(data || constants.EMPTY_BUFFER, opts, cb);
} }
/** /**
...@@ -481,94 +360,14 @@ class WebSocket extends EventEmitter { ...@@ -481,94 +360,14 @@ class WebSocket extends EventEmitter {
} }
if (this._socket) { if (this._socket) {
this._readyState = WebSocket.CLOSING; this.readyState = WebSocket.CLOSING;
this._socket.destroy(); this._socket.destroy();
} }
} }
} }
/** readyStates.forEach((readyState, i) => {
* @constant {Number} CONNECTING WebSocket[readyState] = i;
* @memberof WebSocket
*/
Object.defineProperty(WebSocket, 'CONNECTING', {
enumerable: true,
value: readyStates.indexOf('CONNECTING')
});
/**
* @constant {Number} CONNECTING
* @memberof WebSocket.prototype
*/
Object.defineProperty(WebSocket.prototype, 'CONNECTING', {
enumerable: true,
value: readyStates.indexOf('CONNECTING')
});
/**
* @constant {Number} OPEN
* @memberof WebSocket
*/
Object.defineProperty(WebSocket, 'OPEN', {
enumerable: true,
value: readyStates.indexOf('OPEN')
});
/**
* @constant {Number} OPEN
* @memberof WebSocket.prototype
*/
Object.defineProperty(WebSocket.prototype, 'OPEN', {
enumerable: true,
value: readyStates.indexOf('OPEN')
});
/**
* @constant {Number} CLOSING
* @memberof WebSocket
*/
Object.defineProperty(WebSocket, 'CLOSING', {
enumerable: true,
value: readyStates.indexOf('CLOSING')
});
/**
* @constant {Number} CLOSING
* @memberof WebSocket.prototype
*/
Object.defineProperty(WebSocket.prototype, 'CLOSING', {
enumerable: true,
value: readyStates.indexOf('CLOSING')
});
/**
* @constant {Number} CLOSED
* @memberof WebSocket
*/
Object.defineProperty(WebSocket, 'CLOSED', {
enumerable: true,
value: readyStates.indexOf('CLOSED')
});
/**
* @constant {Number} CLOSED
* @memberof WebSocket.prototype
*/
Object.defineProperty(WebSocket.prototype, 'CLOSED', {
enumerable: true,
value: readyStates.indexOf('CLOSED')
});
[
'binaryType',
'bufferedAmount',
'extensions',
'isPaused',
'protocol',
'readyState',
'url'
].forEach((property) => {
Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
}); });
// //
...@@ -577,421 +376,249 @@ Object.defineProperty(WebSocket.prototype, 'CLOSED', { ...@@ -577,421 +376,249 @@ Object.defineProperty(WebSocket.prototype, 'CLOSED', {
// //
['open', 'error', 'close', 'message'].forEach((method) => { ['open', 'error', 'close', 'message'].forEach((method) => {
Object.defineProperty(WebSocket.prototype, `on${method}`, { Object.defineProperty(WebSocket.prototype, `on${method}`, {
enumerable: true, /**
* Return the listener of the event.
*
* @return {(Function|undefined)} The event listener or `undefined`
* @public
*/
get() { get() {
for (const listener of this.listeners(method)) { const listeners = this.listeners(method);
if (listener[kForOnEventAttribute]) return listener[kListener]; for (var i = 0; i < listeners.length; i++) {
if (listeners[i]._listener) return listeners[i]._listener;
} }
return null; return undefined;
}, },
set(handler) { /**
for (const listener of this.listeners(method)) { * Add a listener for the event.
if (listener[kForOnEventAttribute]) { *
this.removeListener(method, listener); * @param {Function} listener The listener to add
break; * @public
} */
set(listener) {
const listeners = this.listeners(method);
for (var i = 0; i < listeners.length; i++) {
//
// Remove only the listeners added via `addEventListener`.
//
if (listeners[i]._listener) this.removeListener(method, listeners[i]);
} }
this.addEventListener(method, listener);
if (typeof handler !== 'function') return;
this.addEventListener(method, handler, {
[kForOnEventAttribute]: true
});
} }
}); });
}); });
WebSocket.prototype.addEventListener = addEventListener; WebSocket.prototype.addEventListener = EventTarget.addEventListener;
WebSocket.prototype.removeEventListener = removeEventListener; WebSocket.prototype.removeEventListener = EventTarget.removeEventListener;
module.exports = WebSocket; module.exports = WebSocket;
/** /**
* Initialize a WebSocket client. * Initialize a WebSocket client.
* *
* @param {WebSocket} websocket The client to initialize * @param {(String|url.Url|url.URL)} address The URL to which to connect
* @param {(String|URL)} address The URL to which to connect * @param {String} protocols The subprotocols
* @param {Array} protocols The subprotocols * @param {Object} options Connection options
* @param {Object} [options] Connection options * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate
* @param {Boolean} [options.followRedirects=false] Whether or not to follow * @param {Number} options.handshakeTimeout Timeout in milliseconds for the handshake request
* redirects * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version` header
* @param {Function} [options.generateMask] The function used to generate the * @param {String} options.origin Value of the `Origin` or `Sec-WebSocket-Origin` header
* masking key * @param {Number} options.maxPayload The maximum allowed message size
* @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
* handshake request
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
* size
* @param {Number} [options.maxRedirects=10] The maximum number of redirects
* allowed
* @param {String} [options.origin] Value of the `Origin` or
* `Sec-WebSocket-Origin` header
* @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
* permessage-deflate
* @param {Number} [options.protocolVersion=13] Value of the
* `Sec-WebSocket-Version` header
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @private * @private
*/ */
function initAsClient(websocket, address, protocols, options) { function initAsClient(address, protocols, options) {
const opts = { options = Object.assign(
{
protocolVersion: protocolVersions[1], protocolVersion: protocolVersions[1],
maxPayload: 100 * 1024 * 1024,
skipUTF8Validation: false,
perMessageDeflate: true, perMessageDeflate: true,
followRedirects: false, maxPayload: 100 * 1024 * 1024
maxRedirects: 10, },
...options, options,
{
createConnection: undefined, createConnection: undefined,
socketPath: undefined, socketPath: undefined,
hostname: undefined, hostname: undefined,
protocol: undefined, protocol: undefined,
timeout: undefined, timeout: undefined,
method: 'GET', method: undefined,
auth: undefined,
host: undefined, host: undefined,
path: undefined, path: undefined,
port: undefined port: undefined
}; }
);
if (!protocolVersions.includes(opts.protocolVersion)) { if (!protocolVersions.includes(options.protocolVersion)) {
throw new RangeError( throw new RangeError(
`Unsupported protocol version: ${opts.protocolVersion} ` + `Unsupported protocol version: ${options.protocolVersion} ` +
`(supported versions: ${protocolVersions.join(', ')})` `(supported versions: ${protocolVersions.join(', ')})`
); );
} }
let parsedUrl; this._isServer = false;
var parsedUrl;
if (address instanceof URL) { if (typeof address === 'object' && address.href !== undefined) {
parsedUrl = address; parsedUrl = address;
websocket._url = address.href; this.url = address.href;
} else { } else {
try { //
parsedUrl = new URL(address); // The WHATWG URL constructor is not available on Node.js < 6.13.0
} catch (e) { //
throw new SyntaxError(`Invalid URL: ${address}`); parsedUrl = url.URL ? new url.URL(address) : url.parse(address);
} this.url = address;
websocket._url = address;
} }
const isSecure = parsedUrl.protocol === 'wss:';
const isUnixSocket = parsedUrl.protocol === 'ws+unix:'; const isUnixSocket = parsedUrl.protocol === 'ws+unix:';
let invalidURLMessage;
if (parsedUrl.protocol !== 'ws:' && !isSecure && !isUnixSocket) {
invalidURLMessage =
'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"';
} else if (isUnixSocket && !parsedUrl.pathname) {
invalidURLMessage = "The URL's pathname is empty";
} else if (parsedUrl.hash) {
invalidURLMessage = 'The URL contains a fragment identifier';
}
if (invalidURLMessage) {
const err = new SyntaxError(invalidURLMessage);
if (websocket._redirects === 0) { if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {
throw err; throw new Error(`Invalid URL: ${this.url}`);
} else {
emitErrorAndClose(websocket, err);
return;
}
} }
const isSecure =
parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';
const defaultPort = isSecure ? 443 : 80; const defaultPort = isSecure ? 443 : 80;
const key = randomBytes(16).toString('base64'); const key = crypto.randomBytes(16).toString('base64');
const request = isSecure ? https.request : http.request; const httpObj = isSecure ? https : http;
const protocolSet = new Set(); const path = parsedUrl.search
let perMessageDeflate; ? `${parsedUrl.pathname || '/'}${parsedUrl.search}`
: parsedUrl.pathname || '/';
opts.createConnection = isSecure ? tlsConnect : netConnect; var perMessageDeflate;
opts.defaultPort = opts.defaultPort || defaultPort;
opts.port = parsedUrl.port || defaultPort; options.createConnection = isSecure ? tlsConnect : netConnect;
opts.host = parsedUrl.hostname.startsWith('[') options.defaultPort = options.defaultPort || defaultPort;
options.port = parsedUrl.port || defaultPort;
options.host = parsedUrl.hostname.startsWith('[')
? parsedUrl.hostname.slice(1, -1) ? parsedUrl.hostname.slice(1, -1)
: parsedUrl.hostname; : parsedUrl.hostname;
opts.headers = { options.headers = Object.assign(
'Sec-WebSocket-Version': opts.protocolVersion, {
'Sec-WebSocket-Version': options.protocolVersion,
'Sec-WebSocket-Key': key, 'Sec-WebSocket-Key': key,
Connection: 'Upgrade', Connection: 'Upgrade',
Upgrade: 'websocket', Upgrade: 'websocket'
...opts.headers },
}; options.headers
opts.path = parsedUrl.pathname + parsedUrl.search; );
opts.timeout = opts.handshakeTimeout; options.path = path;
options.timeout = options.handshakeTimeout;
if (opts.perMessageDeflate) { if (options.perMessageDeflate) {
perMessageDeflate = new PerMessageDeflate( perMessageDeflate = new PerMessageDeflate(
opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, options.perMessageDeflate !== true ? options.perMessageDeflate : {},
false, false,
opts.maxPayload options.maxPayload
); );
opts.headers['Sec-WebSocket-Extensions'] = format({ options.headers['Sec-WebSocket-Extensions'] = extension.format({
[PerMessageDeflate.extensionName]: perMessageDeflate.offer() [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
}); });
} }
if (protocols.length) { if (protocols) {
for (const protocol of protocols) { options.headers['Sec-WebSocket-Protocol'] = protocols;
if (
typeof protocol !== 'string' ||
!subprotocolRegex.test(protocol) ||
protocolSet.has(protocol)
) {
throw new SyntaxError(
'An invalid or duplicated subprotocol was specified'
);
}
protocolSet.add(protocol);
}
opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
} }
if (opts.origin) { if (options.origin) {
if (opts.protocolVersion < 13) { if (options.protocolVersion < 13) {
opts.headers['Sec-WebSocket-Origin'] = opts.origin; options.headers['Sec-WebSocket-Origin'] = options.origin;
} else { } else {
opts.headers.Origin = opts.origin; options.headers.Origin = options.origin;
} }
} }
if (parsedUrl.username || parsedUrl.password) { if (parsedUrl.auth) {
opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; options.auth = parsedUrl.auth;
} else if (parsedUrl.username || parsedUrl.password) {
options.auth = `${parsedUrl.username}:${parsedUrl.password}`;
} }
if (isUnixSocket) { if (isUnixSocket) {
const parts = opts.path.split(':'); const parts = path.split(':');
opts.socketPath = parts[0]; options.socketPath = parts[0];
opts.path = parts[1]; options.path = parts[1];
} }
let req; var req = (this._req = httpObj.get(options));
if (opts.followRedirects) {
if (websocket._redirects === 0) {
websocket._originalSecure = isSecure;
websocket._originalHost = parsedUrl.host;
const headers = options && options.headers;
//
// Shallow copy the user provided options so that headers can be changed
// without mutating the original object.
//
options = { ...options, headers: {} };
if (headers) { if (options.handshakeTimeout) {
for (const [key, value] of Object.entries(headers)) {
options.headers[key.toLowerCase()] = value;
}
}
} else if (websocket.listenerCount('redirect') === 0) {
const isSameHost = parsedUrl.host === websocket._originalHost;
if (!isSameHost || (websocket._originalSecure && !isSecure)) {
//
// Match curl 7.77.0 behavior and drop the following headers. These
// headers are also dropped when following a redirect to a subdomain.
//
delete opts.headers.authorization;
delete opts.headers.cookie;
if (!isSameHost) delete opts.headers.host;
opts.auth = undefined;
}
}
//
// Match curl 7.77.0 behavior and make the first `Authorization` header win.
// If the `Authorization` header is set, then there is nothing to do as it
// will take precedence.
//
if (opts.auth && !options.headers.authorization) {
options.headers.authorization =
'Basic ' + Buffer.from(opts.auth).toString('base64');
}
req = websocket._req = request(opts);
if (websocket._redirects) {
//
// Unlike what is done for the `'upgrade'` event, no early exit is
// triggered here if the user calls `websocket.close()` or
// `websocket.terminate()` from a listener of the `'redirect'` event. This
// is because the user can also call `request.destroy()` with an error
// before calling `websocket.close()` or `websocket.terminate()` and this
// would result in an error being emitted on the `request` object with no
// `'error'` event listeners attached.
//
websocket.emit('redirect', websocket.url, req);
}
} else {
req = websocket._req = request(opts);
}
if (opts.timeout) {
req.on('timeout', () => { req.on('timeout', () => {
abortHandshake(websocket, req, 'Opening handshake has timed out'); abortHandshake(this, req, 'Opening handshake has timed out');
}); });
} }
req.on('error', (err) => { req.on('error', (err) => {
if (req === null || req[kAborted]) return; if (this._req.aborted) return;
req = websocket._req = null; req = this._req = null;
emitErrorAndClose(websocket, err); this.readyState = WebSocket.CLOSING;
this.emit('error', err);
this.emitClose();
}); });
req.on('response', (res) => { req.on('response', (res) => {
const location = res.headers.location; if (this.emit('unexpected-response', req, res)) return;
const statusCode = res.statusCode;
if (
location &&
opts.followRedirects &&
statusCode >= 300 &&
statusCode < 400
) {
if (++websocket._redirects > opts.maxRedirects) {
abortHandshake(websocket, req, 'Maximum redirects exceeded');
return;
}
req.abort();
let addr;
try {
addr = new URL(location, address);
} catch (e) {
const err = new SyntaxError(`Invalid URL: ${location}`);
emitErrorAndClose(websocket, err);
return;
}
initAsClient(websocket, addr, protocols, options); abortHandshake(this, req, `Unexpected server response: ${res.statusCode}`);
} else if (!websocket.emit('unexpected-response', req, res)) {
abortHandshake(
websocket,
req,
`Unexpected server response: ${res.statusCode}`
);
}
}); });
req.on('upgrade', (res, socket, head) => { req.on('upgrade', (res, socket, head) => {
websocket.emit('upgrade', res); this.emit('upgrade', res);
// //
// The user may have closed the connection from a listener of the // The user may have closed the connection from a listener of the `upgrade`
// `'upgrade'` event. // event.
// //
if (websocket.readyState !== WebSocket.CONNECTING) return; if (this.readyState !== WebSocket.CONNECTING) return;
req = websocket._req = null;
if (res.headers.upgrade.toLowerCase() !== 'websocket') { req = this._req = null;
abortHandshake(websocket, socket, 'Invalid Upgrade header');
return;
}
const digest = createHash('sha1') const digest = crypto
.update(key + GUID) .createHash('sha1')
.update(key + constants.GUID, 'binary')
.digest('base64'); .digest('base64');
if (res.headers['sec-websocket-accept'] !== digest) { if (res.headers['sec-websocket-accept'] !== digest) {
abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); abortHandshake(this, socket, 'Invalid Sec-WebSocket-Accept header');
return; return;
} }
const serverProt = res.headers['sec-websocket-protocol']; const serverProt = res.headers['sec-websocket-protocol'];
let protError; const protList = (protocols || '').split(/, */);
var protError;
if (serverProt !== undefined) { if (!protocols && serverProt) {
if (!protocolSet.size) {
protError = 'Server sent a subprotocol but none was requested'; protError = 'Server sent a subprotocol but none was requested';
} else if (!protocolSet.has(serverProt)) { } else if (protocols && !serverProt) {
protError = 'Server sent an invalid subprotocol';
}
} else if (protocolSet.size) {
protError = 'Server sent no subprotocol'; protError = 'Server sent no subprotocol';
} else if (serverProt && !protList.includes(serverProt)) {
protError = 'Server sent an invalid subprotocol';
} }
if (protError) { if (protError) {
abortHandshake(websocket, socket, protError); abortHandshake(this, socket, protError);
return; return;
} }
if (serverProt) websocket._protocol = serverProt; if (serverProt) this.protocol = serverProt;
const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
if (secWebSocketExtensions !== undefined) {
if (!perMessageDeflate) {
const message =
'Server sent a Sec-WebSocket-Extensions header but no extension ' +
'was requested';
abortHandshake(websocket, socket, message);
return;
}
let extensions;
if (perMessageDeflate) {
try { try {
extensions = parse(secWebSocketExtensions); const extensions = extension.parse(
} catch (err) { res.headers['sec-websocket-extensions']
const message = 'Invalid Sec-WebSocket-Extensions header'; );
abortHandshake(websocket, socket, message);
return;
}
const extensionNames = Object.keys(extensions);
if (
extensionNames.length !== 1 ||
extensionNames[0] !== PerMessageDeflate.extensionName
) {
const message = 'Server indicated an extension that was not requested';
abortHandshake(websocket, socket, message);
return;
}
try { if (extensions[PerMessageDeflate.extensionName]) {
perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
this._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
}
} catch (err) { } catch (err) {
const message = 'Invalid Sec-WebSocket-Extensions header'; abortHandshake(this, socket, 'Invalid Sec-WebSocket-Extensions header');
abortHandshake(websocket, socket, message);
return; return;
} }
websocket._extensions[PerMessageDeflate.extensionName] =
perMessageDeflate;
} }
websocket.setSocket(socket, head, { this.setSocket(socket, head, options.maxPayload);
generateMask: opts.generateMask,
maxPayload: opts.maxPayload,
skipUTF8Validation: opts.skipUTF8Validation
}); });
});
req.end();
}
/**
* Emit the `'error'` and `'close'` events.
*
* @param {WebSocket} websocket The WebSocket instance
* @param {Error} The error to emit
* @private
*/
function emitErrorAndClose(websocket, err) {
websocket._readyState = WebSocket.CLOSING;
websocket.emit('error', err);
websocket.emitClose();
} }
/** /**
...@@ -1002,7 +629,13 @@ function emitErrorAndClose(websocket, err) { ...@@ -1002,7 +629,13 @@ function emitErrorAndClose(websocket, err) {
* @private * @private
*/ */
function netConnect(options) { function netConnect(options) {
options.path = options.socketPath; //
// Override `options.path` only if `options` is a copy of the original options
// object. This is always true on Node.js >= 8 but not on Node.js 6 where
// `options.socketPath` might be `undefined` even if the `socketPath` option
// was originally set.
//
if (options.protocolVersion) options.path = options.socketPath;
return net.connect(options); return net.connect(options);
} }
...@@ -1015,11 +648,7 @@ function netConnect(options) { ...@@ -1015,11 +648,7 @@ function netConnect(options) {
*/ */
function tlsConnect(options) { function tlsConnect(options) {
options.path = undefined; options.path = undefined;
options.servername = options.servername || options.host;
if (!options.servername && options.servername !== '') {
options.servername = net.isIP(options.host) ? '' : options.host;
}
return tls.connect(options); return tls.connect(options);
} }
...@@ -1027,31 +656,21 @@ function tlsConnect(options) { ...@@ -1027,31 +656,21 @@ function tlsConnect(options) {
* Abort the handshake and emit an error. * Abort the handshake and emit an error.
* *
* @param {WebSocket} websocket The WebSocket instance * @param {WebSocket} websocket The WebSocket instance
* @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the
* abort or the socket to destroy * socket to destroy
* @param {String} message The error message * @param {String} message The error message
* @private * @private
*/ */
function abortHandshake(websocket, stream, message) { function abortHandshake(websocket, stream, message) {
websocket._readyState = WebSocket.CLOSING; websocket.readyState = WebSocket.CLOSING;
const err = new Error(message); const err = new Error(message);
Error.captureStackTrace(err, abortHandshake); Error.captureStackTrace(err, abortHandshake);
if (stream.setHeader) { if (stream.setHeader) {
stream[kAborted] = true;
stream.abort(); stream.abort();
stream.once('abort', websocket.emitClose.bind(websocket));
if (stream.socket && !stream.socket.destroyed) { websocket.emit('error', err);
//
// On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
// called after the request completed. See
// https://github.com/websockets/ws/issues/1869.
//
stream.socket.destroy();
}
process.nextTick(emitErrorAndClose, websocket, err);
} else { } else {
stream.destroy(err); stream.destroy(err);
stream.once('error', websocket.emit.bind(websocket, 'error')); stream.once('error', websocket.emit.bind(websocket, 'error'));
...@@ -1059,57 +678,23 @@ function abortHandshake(websocket, stream, message) { ...@@ -1059,57 +678,23 @@ function abortHandshake(websocket, stream, message) {
} }
} }
/**
* Handle cases where the `ping()`, `pong()`, or `send()` methods are called
* when the `readyState` attribute is `CLOSING` or `CLOSED`.
*
* @param {WebSocket} websocket The WebSocket instance
* @param {*} [data] The data to send
* @param {Function} [cb] Callback
* @private
*/
function sendAfterClose(websocket, data, cb) {
if (data) {
const length = toBuffer(data).length;
//
// The `_bufferedAmount` property is used only when the peer is a client and
// the opening handshake fails. Under these circumstances, in fact, the
// `setSocket()` method is not called, so the `_socket` and `_sender`
// properties are set to `null`.
//
if (websocket._socket) websocket._sender._bufferedBytes += length;
else websocket._bufferedAmount += length;
}
if (cb) {
const err = new Error(
`WebSocket is not open: readyState ${websocket.readyState} ` +
`(${readyStates[websocket.readyState]})`
);
cb(err);
}
}
/** /**
* The listener of the `Receiver` `'conclude'` event. * The listener of the `Receiver` `'conclude'` event.
* *
* @param {Number} code The status code * @param {Number} code The status code
* @param {Buffer} reason The reason for closing * @param {String} reason The reason for closing
* @private * @private
*/ */
function receiverOnConclude(code, reason) { function receiverOnConclude(code, reason) {
const websocket = this[kWebSocket]; const websocket = this[kWebSocket];
websocket._socket.removeListener('data', socketOnData);
websocket._socket.resume();
websocket._closeFrameReceived = true; websocket._closeFrameReceived = true;
websocket._closeMessage = reason; websocket._closeMessage = reason;
websocket._closeCode = code; websocket._closeCode = code;
if (websocket._socket[kWebSocket] === undefined) return;
websocket._socket.removeListener('data', socketOnData);
process.nextTick(resume, websocket._socket);
if (code === 1005) websocket.close(); if (code === 1005) websocket.close();
else websocket.close(code, reason); else websocket.close(code, reason);
} }
...@@ -1120,9 +705,7 @@ function receiverOnConclude(code, reason) { ...@@ -1120,9 +705,7 @@ function receiverOnConclude(code, reason) {
* @private * @private
*/ */
function receiverOnDrain() { function receiverOnDrain() {
const websocket = this[kWebSocket]; this[kWebSocket]._socket.resume();
if (!websocket.isPaused) websocket._socket.resume();
} }
/** /**
...@@ -1134,19 +717,12 @@ function receiverOnDrain() { ...@@ -1134,19 +717,12 @@ function receiverOnDrain() {
function receiverOnError(err) { function receiverOnError(err) {
const websocket = this[kWebSocket]; const websocket = this[kWebSocket];
if (websocket._socket[kWebSocket] !== undefined) {
websocket._socket.removeListener('data', socketOnData); websocket._socket.removeListener('data', socketOnData);
// websocket.readyState = WebSocket.CLOSING;
// On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See websocket._closeCode = err[constants.kStatusCode];
// https://github.com/websockets/ws/issues/1940.
//
process.nextTick(resume, websocket._socket);
websocket.close(err[kStatusCode]);
}
websocket.emit('error', err); websocket.emit('error', err);
websocket._socket.destroy();
} }
/** /**
...@@ -1161,12 +737,11 @@ function receiverOnFinish() { ...@@ -1161,12 +737,11 @@ function receiverOnFinish() {
/** /**
* The listener of the `Receiver` `'message'` event. * The listener of the `Receiver` `'message'` event.
* *
* @param {Buffer|ArrayBuffer|Buffer[])} data The message * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message
* @param {Boolean} isBinary Specifies whether the message is binary or not
* @private * @private
*/ */
function receiverOnMessage(data, isBinary) { function receiverOnMessage(data) {
this[kWebSocket].emit('message', data, isBinary); this[kWebSocket].emit('message', data);
} }
/** /**
...@@ -1178,7 +753,7 @@ function receiverOnMessage(data, isBinary) { ...@@ -1178,7 +753,7 @@ function receiverOnMessage(data, isBinary) {
function receiverOnPing(data) { function receiverOnPing(data) {
const websocket = this[kWebSocket]; const websocket = this[kWebSocket];
websocket.pong(data, !websocket._isServer, NOOP); websocket.pong(data, !websocket._isServer, constants.NOOP);
websocket.emit('ping', data); websocket.emit('ping', data);
} }
...@@ -1192,16 +767,6 @@ function receiverOnPong(data) { ...@@ -1192,16 +767,6 @@ function receiverOnPong(data) {
this[kWebSocket].emit('pong', data); this[kWebSocket].emit('pong', data);
} }
/**
* Resume a readable stream
*
* @param {Readable} stream The readable stream
* @private
*/
function resume(stream) {
stream.resume();
}
/** /**
* The listener of the `net.Socket` `'close'` event. * The listener of the `net.Socket` `'close'` event.
* *
...@@ -1211,12 +776,9 @@ function socketOnClose() { ...@@ -1211,12 +776,9 @@ function socketOnClose() {
const websocket = this[kWebSocket]; const websocket = this[kWebSocket];
this.removeListener('close', socketOnClose); this.removeListener('close', socketOnClose);
this.removeListener('data', socketOnData);
this.removeListener('end', socketOnEnd); this.removeListener('end', socketOnEnd);
websocket._readyState = WebSocket.CLOSING; websocket.readyState = WebSocket.CLOSING;
let chunk;
// //
// The close frame might not have been received or the `'end'` event emitted, // The close frame might not have been received or the `'end'` event emitted,
...@@ -1225,19 +787,13 @@ function socketOnClose() { ...@@ -1225,19 +787,13 @@ function socketOnClose() {
// it. If the readable side of the socket is in flowing mode then there is no // it. If the readable side of the socket is in flowing mode then there is no
// buffered data as everything has been already written and `readable.read()` // buffered data as everything has been already written and `readable.read()`
// will return `null`. If instead, the socket is paused, any possible buffered // will return `null`. If instead, the socket is paused, any possible buffered
// data will be read as a single chunk. // data will be read as a single chunk and emitted synchronously in a single
// `'data'` event.
// //
if ( websocket._socket.read();
!this._readableState.endEmitted &&
!websocket._closeFrameReceived &&
!websocket._receiver._writableState.errorEmitted &&
(chunk = websocket._socket.read()) !== null
) {
websocket._receiver.write(chunk);
}
websocket._receiver.end(); websocket._receiver.end();
this.removeListener('data', socketOnData);
this[kWebSocket] = undefined; this[kWebSocket] = undefined;
clearTimeout(websocket._closeTimer); clearTimeout(websocket._closeTimer);
...@@ -1273,7 +829,7 @@ function socketOnData(chunk) { ...@@ -1273,7 +829,7 @@ function socketOnData(chunk) {
function socketOnEnd() { function socketOnEnd() {
const websocket = this[kWebSocket]; const websocket = this[kWebSocket];
websocket._readyState = WebSocket.CLOSING; websocket.readyState = WebSocket.CLOSING;
websocket._receiver.end(); websocket._receiver.end();
this.end(); this.end();
} }
...@@ -1287,10 +843,10 @@ function socketOnError() { ...@@ -1287,10 +843,10 @@ function socketOnError() {
const websocket = this[kWebSocket]; const websocket = this[kWebSocket];
this.removeListener('error', socketOnError); this.removeListener('error', socketOnError);
this.on('error', NOOP); this.on('error', constants.NOOP);
if (websocket) { if (websocket) {
websocket._readyState = WebSocket.CLOSING; websocket.readyState = WebSocket.CLOSING;
this.destroy(); this.destroy();
} }
} }
{ {
"name": "ws", "name": "ws",
"version": "8.8.0", "version": "6.1.4",
"description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
"keywords": [ "keywords": [
"HyBi", "HyBi",
...@@ -16,46 +16,30 @@ ...@@ -16,46 +16,30 @@
"author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)", "author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
"license": "MIT", "license": "MIT",
"main": "index.js", "main": "index.js",
"exports": {
"import": "./wrapper.mjs",
"require": "./index.js"
},
"browser": "browser.js", "browser": "browser.js",
"engines": {
"node": ">=10.0.0"
},
"files": [ "files": [
"browser.js", "browser.js",
"index.js", "index.js",
"lib/*.js", "lib/*.js"
"wrapper.mjs"
], ],
"scripts": { "scripts": {
"test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js", "test": "npm run lint && nyc --reporter=html --reporter=text mocha test/*.test.js",
"integration": "mocha --throw-deprecation test/*.integration.js", "integration": "npm run lint && mocha test/*.integration.js",
"lint": "eslint --ignore-path .gitignore . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\"" "lint": "eslint . --ignore-path .gitignore && prettylint '**/*.{json,md}' --ignore-path .gitignore"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": "^5.0.2"
}, },
"peerDependenciesMeta": { "dependencies": {
"bufferutil": { "async-limiter": "~1.0.0"
"optional": true
},
"utf-8-validate": {
"optional": true
}
}, },
"devDependencies": { "devDependencies": {
"benchmark": "^2.1.4", "benchmark": "~2.1.4",
"bufferutil": "^4.0.1", "bufferutil": "~4.0.0",
"eslint": "^8.0.0", "eslint": "~5.14.0",
"eslint-config-prettier": "^8.1.0", "eslint-config-prettier": "~4.0.0",
"eslint-plugin-prettier": "^4.0.0", "eslint-plugin-prettier": "~3.0.0",
"mocha": "^8.4.0", "mocha": "~5.2.0",
"nyc": "^15.0.0", "nyc": "~13.3.0",
"prettier": "^2.0.5", "prettier": "~1.16.1",
"utf-8-validate": "^5.0.2" "prettylint": "~1.0.0",
"utf-8-validate": "~5.0.0"
} }
} }
import createWebSocketStream from './lib/stream.js';
import Receiver from './lib/receiver.js';
import Sender from './lib/sender.js';
import WebSocket from './lib/websocket.js';
import WebSocketServer from './lib/websocket-server.js';
export { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer };
export default WebSocket;
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
"iconv-lite": "0.4.23", "iconv-lite": "0.4.23",
"jschardet": "1.6.0", "jschardet": "1.6.0",
"marked": "0.6.2", "marked": "0.6.2",
"mime": "2.6.0",
"nedb": "1.5.1", "nedb": "1.5.1",
"node-rsa": "1.0.5", "node-rsa": "1.0.5",
"random-fake-useragent": "0.1.0", "random-fake-useragent": "0.1.0",
...@@ -22,7 +23,7 @@ ...@@ -22,7 +23,7 @@
"superagent-proxy": "3.0.0", "superagent-proxy": "3.0.0",
"tar": "4.4.18", "tar": "4.4.18",
"through": "2.3.8", "through": "2.3.8",
"ws": "8.8.0", "ws": "6.1.4",
"xml2js": "0.4.23" "xml2js": "0.4.23"
} }
}, },
...@@ -160,6 +161,11 @@ ...@@ -160,6 +161,11 @@
"resolved": "https://registry.npm.taobao.org/async/download/async-0.2.10.tgz", "resolved": "https://registry.npm.taobao.org/async/download/async-0.2.10.tgz",
"integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E=" "integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E="
}, },
"node_modules/async-limiter": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.1.tgz",
"integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ=="
},
"node_modules/asynckit": { "node_modules/asynckit": {
"version": "0.4.0", "version": "0.4.0",
"resolved": "http://registry.npm.taobao.org/asynckit/download/asynckit-0.4.0.tgz", "resolved": "http://registry.npm.taobao.org/asynckit/download/asynckit-0.4.0.tgz",
...@@ -2188,23 +2194,11 @@ ...@@ -2188,23 +2194,11 @@
"integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=" "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus="
}, },
"node_modules/ws": { "node_modules/ws": {
"version": "8.8.0", "version": "6.1.4",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.8.0.tgz", "resolved": "https://registry.npmjs.org/ws/-/ws-6.1.4.tgz",
"integrity": "sha512-JDAgSYQ1ksuwqfChJusw1LSJ8BizJ2e/vVu5Lxjq3YvNJNlROv1ui4i+c/kUUrPheBvQl4c5UbERhTwKa6QBJQ==", "integrity": "sha512-eqZfL+NE/YQc1/ZynhojeV8q+H050oR8AZ2uIev7RU10svA9ZnJUddHcOUZTJLinZ9yEfdA2kSATS2qZK5fhJA==",
"engines": { "dependencies": {
"node": ">=10.0.0" "async-limiter": "~1.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": "^5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
} }
}, },
"node_modules/xml-name-validator": { "node_modules/xml-name-validator": {
...@@ -2364,6 +2358,11 @@ ...@@ -2364,6 +2358,11 @@
"resolved": "https://registry.npm.taobao.org/async/download/async-0.2.10.tgz", "resolved": "https://registry.npm.taobao.org/async/download/async-0.2.10.tgz",
"integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E=" "integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E="
}, },
"async-limiter": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.1.tgz",
"integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ=="
},
"asynckit": { "asynckit": {
"version": "0.4.0", "version": "0.4.0",
"resolved": "http://registry.npm.taobao.org/asynckit/download/asynckit-0.4.0.tgz", "resolved": "http://registry.npm.taobao.org/asynckit/download/asynckit-0.4.0.tgz",
...@@ -4006,10 +4005,12 @@ ...@@ -4006,10 +4005,12 @@
"integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=" "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus="
}, },
"ws": { "ws": {
"version": "8.8.0", "version": "6.1.4",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.8.0.tgz", "resolved": "https://registry.npmjs.org/ws/-/ws-6.1.4.tgz",
"integrity": "sha512-JDAgSYQ1ksuwqfChJusw1LSJ8BizJ2e/vVu5Lxjq3YvNJNlROv1ui4i+c/kUUrPheBvQl4c5UbERhTwKa6QBJQ==", "integrity": "sha512-eqZfL+NE/YQc1/ZynhojeV8q+H050oR8AZ2uIev7RU10svA9ZnJUddHcOUZTJLinZ9yEfdA2kSATS2qZK5fhJA==",
"requires": {} "requires": {
"async-limiter": "~1.0.0"
}
}, },
"xml-name-validator": { "xml-name-validator": {
"version": "2.0.1", "version": "2.0.1",
......
...@@ -17,14 +17,15 @@ ...@@ -17,14 +17,15 @@
"superagent-proxy": "3.0.0", "superagent-proxy": "3.0.0",
"tar": "4.4.18", "tar": "4.4.18",
"through": "2.3.8", "through": "2.3.8",
"ws": "8.8.0", "ws": "6.1.4",
"mime": "2.6.0",
"xml2js": "0.4.23" "xml2js": "0.4.23"
}, },
"scripts": { "scripts": {
"start": "AntSword app.js", "start": "AntSword app.js",
"build": "npm start" "build": "npm start"
}, },
"author": "antoor <u@uyu.us>", "author": "antoor",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",
......
...@@ -316,12 +316,16 @@ class Base { ...@@ -316,12 +316,16 @@ class Base {
opts: this.__opts__, opts: this.__opts__,
rsa: this.rsaEncrypt() rsa: this.rsaEncrypt()
} }
let useRaw = this.__opts__['type'].endsWith("raw") || (this.constructor.supportRawBody && (this.__opts__['otherConf'] || {})['use-raw-body'] === 1);
let useWebSocket = (this.__opts__['url'].startsWith('ws://') || this.__opts__['url'].startsWith('wss://'));
return new Promise((res, rej) => { return new Promise((res, rej) => {
console.log(this.__opts__['type'].endsWith("raw") || (this.constructor.supportRawBody && (this.__opts__['otherConf'] || {})['use-raw-body'] === 1))
// 随机ID(用于监听数据来源) // 随机ID(用于监听数据来源)
const hash = (String(+new Date) + String(Math.random())) const hash = (String(+new Date) + String(Math.random()))
.substr(10, 10) .substr(10, 10)
.replace('.', '_'); .replace('.', '_');
console.log(hash);
// 监听数据返回 // 监听数据返回
antSword['ipcRenderer'] antSword['ipcRenderer']
// 请求完毕返回数据{text,buff} // 请求完毕返回数据{text,buff}
...@@ -369,7 +373,8 @@ class Base { ...@@ -369,7 +373,8 @@ class Base {
addMassData: (this.__opts__['otherConf'] || {})['add-MassData'] === 1, addMassData: (this.__opts__['otherConf'] || {})['add-MassData'] === 1,
randomPrefix: parseInt((this.__opts__['otherConf'] || {})['random-Prefix']), randomPrefix: parseInt((this.__opts__['otherConf'] || {})['random-Prefix']),
useRandomVariable: (this.__opts__['otherConf'] || {})['use-random-variable'] === 1, useRandomVariable: (this.__opts__['otherConf'] || {})['use-random-variable'] === 1,
useRaw: this.__opts__['type'].endsWith("raw") || (this.constructor.supportRawBody && (this.__opts__['otherConf'] || {})['use-raw-body'] === 1), useRaw: useRaw,
useWebSocket: useWebSocket,
timeout: parseInt((this.__opts__['otherConf'] || {})['request-timeout']), timeout: parseInt((this.__opts__['otherConf'] || {})['request-timeout']),
headers: (this.__opts__['httpConf'] || {})['headers'] || {}, headers: (this.__opts__['httpConf'] || {})['headers'] || {},
body: (this.__opts__['httpConf'] || {})['body'] || {} body: (this.__opts__['httpConf'] || {})['body'] || {}
...@@ -386,6 +391,9 @@ class Base { ...@@ -386,6 +391,9 @@ class Base {
*/ */
download(savePath, postCode, progressCallback) { download(savePath, postCode, progressCallback) {
const opt = this.complete(postCode, true); const opt = this.complete(postCode, true);
let useRaw = this.__opts__['type'].endsWith("raw") || (this.constructor.supportRawBody && (this.__opts__['otherConf'] || {})['use-raw-body'] === 1);
let useWebSocket = (this.__opts__['url'].startsWith('ws://') || this.__opts__['url'].startsWith('wss://'));
return new Promise((ret, rej) => { return new Promise((ret, rej) => {
// 随机ID(用于监听数据来源) // 随机ID(用于监听数据来源)
const hash = (String(+new Date) + String(Math.random())) const hash = (String(+new Date) + String(Math.random()))
...@@ -410,6 +418,7 @@ class Base { ...@@ -410,6 +418,7 @@ class Base {
// 发送请求数据 // 发送请求数据
.send('download', { .send('download', {
url: this.__opts__['url'], url: this.__opts__['url'],
pwd: this.__opts__['pwd'],
hash: hash, hash: hash,
path: savePath, path: savePath,
data: opt['data'], data: opt['data'],
...@@ -424,6 +433,8 @@ class Base { ...@@ -424,6 +433,8 @@ class Base {
addMassData: (this.__opts__['otherConf'] || {})['add-MassData'] === 1, addMassData: (this.__opts__['otherConf'] || {})['add-MassData'] === 1,
randomPrefix: parseInt((this.__opts__['otherConf'] || {})['random-Prefix']), randomPrefix: parseInt((this.__opts__['otherConf'] || {})['random-Prefix']),
useRandomVariable: (this.__opts__['otherConf'] || {})['use-random-variable'] === 1, useRandomVariable: (this.__opts__['otherConf'] || {})['use-random-variable'] === 1,
useRaw: useRaw,
useWebSocket: useWebSocket,
timeout: parseInt((this.__opts__['otherConf'] || {})['request-timeout']), timeout: parseInt((this.__opts__['otherConf'] || {})['request-timeout']),
headers: (this.__opts__['httpConf'] || {})['headers'] || {}, headers: (this.__opts__['httpConf'] || {})['headers'] || {},
body: (this.__opts__['httpConf'] || {})['body'] || {} body: (this.__opts__['httpConf'] || {})['body'] || {}
......
...@@ -83,17 +83,17 @@ module.exports = (arg1, arg2, arg3) => ({ ...@@ -83,17 +83,17 @@ module.exports = (arg1, arg2, arg3) => ({
_: `command_exists() { command -v "$@" > /dev/null 2>&1; }; _: `command_exists() { command -v "$@" > /dev/null 2>&1; };
if command_exists md5sum; then if command_exists md5sum; then
asmd5=$(md5sum #{path}|awk '{print $1}'); asmd5=$(md5sum #{path}|awk '{print $1}');
echo -n "MD5\\t$asmd5\\n"; echo -n "MD5\t$asmd5\n";
elif command_exists busybox && busybox --list-modules | grep -q md5sum; then elif command_exists busybox && busybox --list-modules | grep -q md5sum; then
asmd5=$(busybox md5sum #{path}|awk '{print $1}'); asmd5=$(busybox md5sum #{path}|awk '{print $1}');
echo -n "MD5\\t$asmd5\\n"; echo -n "MD5\t$asmd5\n";
fi; fi;
if command_exists sha1sum; then if command_exists sha1sum; then
assha1=$(sha1sum #{path}|awk '{print $1}'); assha1=$(sha1sum #{path}|awk '{print $1}');
echo -n "SHA1\\t$assha1\\n"; echo -n "SHA1\t$assha1\n";
elif command_exists busybox && busybox --list-modules | grep -q sha1sum; then elif command_exists busybox && busybox --list-modules | grep -q sha1sum; then
assha1=$(busybox sha1sum #{path}|awk '{print $1}'); assha1=$(busybox sha1sum #{path}|awk '{print $1}');
echo -n "SHA1\\t$assha1\\n"; echo -n "SHA1\t$assha1\n";
fi; fi;
`.replace(/\n\s+/g, ''), `.replace(/\n\s+/g, ''),
}, },
......
...@@ -544,7 +544,7 @@ class FileManager { ...@@ -544,7 +544,7 @@ class FileManager {
width: 800, width: 800,
height: 600, height: 600,
}); });
var filemime = mime.lookup(name); var filemime = mime.getType(name);
let savepath = PATH.join(process.env.AS_WORKDIR, `antData/.temp/`, Buffer.from(name).toString("hex")); let savepath = PATH.join(process.env.AS_WORKDIR, `antData/.temp/`, Buffer.from(name).toString("hex"));
win.cell.lastChild['style']['overflow'] = 'scroll'; win.cell.lastChild['style']['overflow'] = 'scroll';
win.cell.lastChild['style']['textAlign'] = 'center'; win.cell.lastChild['style']['textAlign'] = 'center';
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment