3 const EventEmitter = require('events');
4 const https = require('https');
5 const http = require('http');
6 const net = require('net');
7 const tls = require('tls');
8 const { randomBytes, createHash } = require('crypto');
9 const { URL } = require('url');
11 const PerMessageDeflate = require('./permessage-deflate');
12 const Receiver = require('./receiver');
13 const Sender = require('./sender');
21 } = require('./constants');
22 const { addEventListener, removeEventListener } = require('./event-target');
23 const { format, parse } = require('./extension');
24 const { toBuffer } = require('./buffer-util');
26 const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
27 const protocolVersions = [8, 13];
28 const closeTimeout = 30 * 1000;
31 * Class representing a WebSocket.
33 * @extends EventEmitter
35 class WebSocket extends EventEmitter {
37 * Create a new `WebSocket`.
39 * @param {(String|url.URL)} address The URL to which to connect
40 * @param {(String|String[])} [protocols] The subprotocols
41 * @param {Object} [options] Connection options
43 constructor(address, protocols, options) {
46 this._binaryType = BINARY_TYPES[0];
47 this._closeCode = 1006;
48 this._closeFrameReceived = false;
49 this._closeFrameSent = false;
50 this._closeMessage = '';
51 this._closeTimer = null;
52 this._extensions = {};
54 this._readyState = WebSocket.CONNECTING;
55 this._receiver = null;
59 if (address !== null) {
60 this._bufferedAmount = 0;
61 this._isServer = false;
64 if (Array.isArray(protocols)) {
65 protocols = protocols.join(', ');
66 } else if (typeof protocols === 'object' && protocols !== null) {
68 protocols = undefined;
71 initAsClient(this, address, protocols, options);
73 this._isServer = true;
78 * This deviates from the WHATWG interface since ws doesn't support the
79 * required default "blob" type (instead we define a custom "nodebuffer"
85 return this._binaryType;
88 set binaryType(type) {
89 if (!BINARY_TYPES.includes(type)) return;
91 this._binaryType = type;
94 // Allow to change `binaryType` on the fly.
96 if (this._receiver) this._receiver._binaryType = type;
102 get bufferedAmount() {
103 if (!this._socket) return this._bufferedAmount;
105 return this._socket._writableState.length + this._sender._bufferedBytes;
112 return Object.keys(this._extensions).join();
119 return this._protocol;
126 return this._readyState;
137 * Set up the socket and the internal resources.
139 * @param {net.Socket} socket The network socket between the server and client
140 * @param {Buffer} head The first packet of the upgraded stream
141 * @param {Number} [maxPayload=0] The maximum allowed message size
144 setSocket(socket, head, maxPayload) {
145 const receiver = new Receiver(
152 this._sender = new Sender(socket, this._extensions);
153 this._receiver = receiver;
154 this._socket = socket;
156 receiver[kWebSocket] = this;
157 socket[kWebSocket] = this;
159 receiver.on('conclude', receiverOnConclude);
160 receiver.on('drain', receiverOnDrain);
161 receiver.on('error', receiverOnError);
162 receiver.on('message', receiverOnMessage);
163 receiver.on('ping', receiverOnPing);
164 receiver.on('pong', receiverOnPong);
166 socket.setTimeout(0);
169 if (head.length > 0) socket.unshift(head);
171 socket.on('close', socketOnClose);
172 socket.on('data', socketOnData);
173 socket.on('end', socketOnEnd);
174 socket.on('error', socketOnError);
176 this._readyState = WebSocket.OPEN;
181 * Emit the `'close'` event.
187 this._readyState = WebSocket.CLOSED;
188 this.emit('close', this._closeCode, this._closeMessage);
192 if (this._extensions[PerMessageDeflate.extensionName]) {
193 this._extensions[PerMessageDeflate.extensionName].cleanup();
196 this._receiver.removeAllListeners();
197 this._readyState = WebSocket.CLOSED;
198 this.emit('close', this._closeCode, this._closeMessage);
202 * Start a closing handshake.
204 * +----------+ +-----------+ +----------+
205 * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
206 * | +----------+ +-----------+ +----------+ |
207 * +----------+ +-----------+ |
208 * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
209 * +----------+ +-----------+ |
211 * +------------------------+-->|fin| - - - -
213 * - - - - -|fin|<---------------------+
216 * @param {Number} [code] Status code explaining why the connection is closing
217 * @param {String} [data] A string explaining why the connection is closing
221 if (this.readyState === WebSocket.CLOSED) return;
222 if (this.readyState === WebSocket.CONNECTING) {
223 const msg = 'WebSocket was closed before the connection was established';
224 return abortHandshake(this, this._req, msg);
227 if (this.readyState === WebSocket.CLOSING) {
228 if (this._closeFrameSent && this._closeFrameReceived) this._socket.end();
232 this._readyState = WebSocket.CLOSING;
233 this._sender.close(code, data, !this._isServer, (err) => {
235 // This error is handled by the `'error'` listener on the socket. We only
236 // want to know if the close frame has been sent here.
240 this._closeFrameSent = true;
241 if (this._closeFrameReceived) this._socket.end();
245 // Specify a timeout for the closing handshake to complete.
247 this._closeTimer = setTimeout(
248 this._socket.destroy.bind(this._socket),
256 * @param {*} [data] The data to send
257 * @param {Boolean} [mask] Indicates whether or not to mask `data`
258 * @param {Function} [cb] Callback which is executed when the ping is sent
261 ping(data, mask, cb) {
262 if (this.readyState === WebSocket.CONNECTING) {
263 throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
266 if (typeof data === 'function') {
268 data = mask = undefined;
269 } else if (typeof mask === 'function') {
274 if (typeof data === 'number') data = data.toString();
276 if (this.readyState !== WebSocket.OPEN) {
277 sendAfterClose(this, data, cb);
281 if (mask === undefined) mask = !this._isServer;
282 this._sender.ping(data || EMPTY_BUFFER, mask, cb);
288 * @param {*} [data] The data to send
289 * @param {Boolean} [mask] Indicates whether or not to mask `data`
290 * @param {Function} [cb] Callback which is executed when the pong is sent
293 pong(data, mask, cb) {
294 if (this.readyState === WebSocket.CONNECTING) {
295 throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
298 if (typeof data === 'function') {
300 data = mask = undefined;
301 } else if (typeof mask === 'function') {
306 if (typeof data === 'number') data = data.toString();
308 if (this.readyState !== WebSocket.OPEN) {
309 sendAfterClose(this, data, cb);
313 if (mask === undefined) mask = !this._isServer;
314 this._sender.pong(data || EMPTY_BUFFER, mask, cb);
318 * Send a data message.
320 * @param {*} data The message to send
321 * @param {Object} [options] Options object
322 * @param {Boolean} [options.compress] Specifies whether or not to compress
324 * @param {Boolean} [options.binary] Specifies whether `data` is binary or
326 * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
328 * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
329 * @param {Function} [cb] Callback which is executed when data is written out
332 send(data, options, cb) {
333 if (this.readyState === WebSocket.CONNECTING) {
334 throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
337 if (typeof options === 'function') {
342 if (typeof data === 'number') data = data.toString();
344 if (this.readyState !== WebSocket.OPEN) {
345 sendAfterClose(this, data, cb);
350 binary: typeof data !== 'string',
351 mask: !this._isServer,
357 if (!this._extensions[PerMessageDeflate.extensionName]) {
358 opts.compress = false;
361 this._sender.send(data || EMPTY_BUFFER, opts, cb);
365 * Forcibly close the connection.
370 if (this.readyState === WebSocket.CLOSED) return;
371 if (this.readyState === WebSocket.CONNECTING) {
372 const msg = 'WebSocket was closed before the connection was established';
373 return abortHandshake(this, this._req, msg);
377 this._readyState = WebSocket.CLOSING;
378 this._socket.destroy();
383 readyStates.forEach((readyState, i) => {
384 const descriptor = { enumerable: true, value: i };
386 Object.defineProperty(WebSocket.prototype, readyState, descriptor);
387 Object.defineProperty(WebSocket, readyState, descriptor);
397 ].forEach((property) => {
398 Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
402 // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
403 // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
405 ['open', 'error', 'close', 'message'].forEach((method) => {
406 Object.defineProperty(WebSocket.prototype, `on${method}`, {
410 * Return the listener of the event.
412 * @return {(Function|undefined)} The event listener or `undefined`
416 const listeners = this.listeners(method);
417 for (let i = 0; i < listeners.length; i++) {
418 if (listeners[i]._listener) return listeners[i]._listener;
424 * Add a listener for the event.
426 * @param {Function} listener The listener to add
430 const listeners = this.listeners(method);
431 for (let i = 0; i < listeners.length; i++) {
433 // Remove only the listeners added via `addEventListener`.
435 if (listeners[i]._listener) this.removeListener(method, listeners[i]);
437 this.addEventListener(method, listener);
442 WebSocket.prototype.addEventListener = addEventListener;
443 WebSocket.prototype.removeEventListener = removeEventListener;
445 module.exports = WebSocket;
448 * Initialize a WebSocket client.
450 * @param {WebSocket} websocket The client to initialize
451 * @param {(String|url.URL)} address The URL to which to connect
452 * @param {String} [protocols] The subprotocols
453 * @param {Object} [options] Connection options
454 * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
456 * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
458 * @param {Number} [options.protocolVersion=13] Value of the
459 * `Sec-WebSocket-Version` header
460 * @param {String} [options.origin] Value of the `Origin` or
461 * `Sec-WebSocket-Origin` header
462 * @param {Number} [options.maxPayload=104857600] The maximum allowed message
464 * @param {Boolean} [options.followRedirects=false] Whether or not to follow
466 * @param {Number} [options.maxRedirects=10] The maximum number of redirects
470 function initAsClient(websocket, address, protocols, options) {
472 protocolVersion: protocolVersions[1],
473 maxPayload: 100 * 1024 * 1024,
474 perMessageDeflate: true,
475 followRedirects: false,
478 createConnection: undefined,
479 socketPath: undefined,
489 if (!protocolVersions.includes(opts.protocolVersion)) {
490 throw new RangeError(
491 `Unsupported protocol version: ${opts.protocolVersion} ` +
492 `(supported versions: ${protocolVersions.join(', ')})`
498 if (address instanceof URL) {
500 websocket._url = address.href;
502 parsedUrl = new URL(address);
503 websocket._url = address;
506 const isUnixSocket = parsedUrl.protocol === 'ws+unix:';
508 if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {
509 throw new Error(`Invalid URL: ${websocket.url}`);
513 parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';
514 const defaultPort = isSecure ? 443 : 80;
515 const key = randomBytes(16).toString('base64');
516 const get = isSecure ? https.get : http.get;
517 let perMessageDeflate;
519 opts.createConnection = isSecure ? tlsConnect : netConnect;
520 opts.defaultPort = opts.defaultPort || defaultPort;
521 opts.port = parsedUrl.port || defaultPort;
522 opts.host = parsedUrl.hostname.startsWith('[')
523 ? parsedUrl.hostname.slice(1, -1)
524 : parsedUrl.hostname;
526 'Sec-WebSocket-Version': opts.protocolVersion,
527 'Sec-WebSocket-Key': key,
528 Connection: 'Upgrade',
529 Upgrade: 'websocket',
532 opts.path = parsedUrl.pathname + parsedUrl.search;
533 opts.timeout = opts.handshakeTimeout;
535 if (opts.perMessageDeflate) {
536 perMessageDeflate = new PerMessageDeflate(
537 opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
541 opts.headers['Sec-WebSocket-Extensions'] = format({
542 [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
546 opts.headers['Sec-WebSocket-Protocol'] = protocols;
549 if (opts.protocolVersion < 13) {
550 opts.headers['Sec-WebSocket-Origin'] = opts.origin;
552 opts.headers.Origin = opts.origin;
555 if (parsedUrl.username || parsedUrl.password) {
556 opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
560 const parts = opts.path.split(':');
562 opts.socketPath = parts[0];
563 opts.path = parts[1];
566 let req = (websocket._req = get(opts));
569 req.on('timeout', () => {
570 abortHandshake(websocket, req, 'Opening handshake has timed out');
574 req.on('error', (err) => {
575 if (req === null || req.aborted) return;
577 req = websocket._req = null;
578 websocket._readyState = WebSocket.CLOSING;
579 websocket.emit('error', err);
580 websocket.emitClose();
583 req.on('response', (res) => {
584 const location = res.headers.location;
585 const statusCode = res.statusCode;
589 opts.followRedirects &&
593 if (++websocket._redirects > opts.maxRedirects) {
594 abortHandshake(websocket, req, 'Maximum redirects exceeded');
600 const addr = new URL(location, address);
602 initAsClient(websocket, addr, protocols, options);
603 } else if (!websocket.emit('unexpected-response', req, res)) {
607 `Unexpected server response: ${res.statusCode}`
612 req.on('upgrade', (res, socket, head) => {
613 websocket.emit('upgrade', res);
616 // The user may have closed the connection from a listener of the `upgrade`
619 if (websocket.readyState !== WebSocket.CONNECTING) return;
621 req = websocket._req = null;
623 const digest = createHash('sha1')
627 if (res.headers['sec-websocket-accept'] !== digest) {
628 abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
632 const serverProt = res.headers['sec-websocket-protocol'];
633 const protList = (protocols || '').split(/, */);
636 if (!protocols && serverProt) {
637 protError = 'Server sent a subprotocol but none was requested';
638 } else if (protocols && !serverProt) {
639 protError = 'Server sent no subprotocol';
640 } else if (serverProt && !protList.includes(serverProt)) {
641 protError = 'Server sent an invalid subprotocol';
645 abortHandshake(websocket, socket, protError);
649 if (serverProt) websocket._protocol = serverProt;
651 if (perMessageDeflate) {
653 const extensions = parse(res.headers['sec-websocket-extensions']);
655 if (extensions[PerMessageDeflate.extensionName]) {
656 perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
657 websocket._extensions[
658 PerMessageDeflate.extensionName
659 ] = perMessageDeflate;
665 'Invalid Sec-WebSocket-Extensions header'
671 websocket.setSocket(socket, head, opts.maxPayload);
676 * Create a `net.Socket` and initiate a connection.
678 * @param {Object} options Connection options
679 * @return {net.Socket} The newly created socket used to start the connection
682 function netConnect(options) {
683 options.path = options.socketPath;
684 return net.connect(options);
688 * Create a `tls.TLSSocket` and initiate a connection.
690 * @param {Object} options Connection options
691 * @return {tls.TLSSocket} The newly created socket used to start the connection
694 function tlsConnect(options) {
695 options.path = undefined;
697 if (!options.servername && options.servername !== '') {
698 options.servername = net.isIP(options.host) ? '' : options.host;
701 return tls.connect(options);
705 * Abort the handshake and emit an error.
707 * @param {WebSocket} websocket The WebSocket instance
708 * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the
710 * @param {String} message The error message
713 function abortHandshake(websocket, stream, message) {
714 websocket._readyState = WebSocket.CLOSING;
716 const err = new Error(message);
717 Error.captureStackTrace(err, abortHandshake);
719 if (stream.setHeader) {
721 stream.once('abort', websocket.emitClose.bind(websocket));
722 websocket.emit('error', err);
725 stream.once('error', websocket.emit.bind(websocket, 'error'));
726 stream.once('close', websocket.emitClose.bind(websocket));
731 * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
732 * when the `readyState` attribute is `CLOSING` or `CLOSED`.
734 * @param {WebSocket} websocket The WebSocket instance
735 * @param {*} [data] The data to send
736 * @param {Function} [cb] Callback
739 function sendAfterClose(websocket, data, cb) {
741 const length = toBuffer(data).length;
744 // The `_bufferedAmount` property is used only when the peer is a client and
745 // the opening handshake fails. Under these circumstances, in fact, the
746 // `setSocket()` method is not called, so the `_socket` and `_sender`
747 // properties are set to `null`.
749 if (websocket._socket) websocket._sender._bufferedBytes += length;
750 else websocket._bufferedAmount += length;
754 const err = new Error(
755 `WebSocket is not open: readyState ${websocket.readyState} ` +
756 `(${readyStates[websocket.readyState]})`
763 * The listener of the `Receiver` `'conclude'` event.
765 * @param {Number} code The status code
766 * @param {String} reason The reason for closing
769 function receiverOnConclude(code, reason) {
770 const websocket = this[kWebSocket];
772 websocket._socket.removeListener('data', socketOnData);
773 websocket._socket.resume();
775 websocket._closeFrameReceived = true;
776 websocket._closeMessage = reason;
777 websocket._closeCode = code;
779 if (code === 1005) websocket.close();
780 else websocket.close(code, reason);
784 * The listener of the `Receiver` `'drain'` event.
788 function receiverOnDrain() {
789 this[kWebSocket]._socket.resume();
793 * The listener of the `Receiver` `'error'` event.
795 * @param {(RangeError|Error)} err The emitted error
798 function receiverOnError(err) {
799 const websocket = this[kWebSocket];
801 websocket._socket.removeListener('data', socketOnData);
803 websocket._readyState = WebSocket.CLOSING;
804 websocket._closeCode = err[kStatusCode];
805 websocket.emit('error', err);
806 websocket._socket.destroy();
810 * The listener of the `Receiver` `'finish'` event.
814 function receiverOnFinish() {
815 this[kWebSocket].emitClose();
819 * The listener of the `Receiver` `'message'` event.
821 * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message
824 function receiverOnMessage(data) {
825 this[kWebSocket].emit('message', data);
829 * The listener of the `Receiver` `'ping'` event.
831 * @param {Buffer} data The data included in the ping frame
834 function receiverOnPing(data) {
835 const websocket = this[kWebSocket];
837 websocket.pong(data, !websocket._isServer, NOOP);
838 websocket.emit('ping', data);
842 * The listener of the `Receiver` `'pong'` event.
844 * @param {Buffer} data The data included in the pong frame
847 function receiverOnPong(data) {
848 this[kWebSocket].emit('pong', data);
852 * The listener of the `net.Socket` `'close'` event.
856 function socketOnClose() {
857 const websocket = this[kWebSocket];
859 this.removeListener('close', socketOnClose);
860 this.removeListener('end', socketOnEnd);
862 websocket._readyState = WebSocket.CLOSING;
865 // The close frame might not have been received or the `'end'` event emitted,
866 // for example, if the socket was destroyed due to an error. Ensure that the
867 // `receiver` stream is closed after writing any remaining buffered data to
868 // it. If the readable side of the socket is in flowing mode then there is no
869 // buffered data as everything has been already written and `readable.read()`
870 // will return `null`. If instead, the socket is paused, any possible buffered
871 // data will be read as a single chunk and emitted synchronously in a single
874 websocket._socket.read();
875 websocket._receiver.end();
877 this.removeListener('data', socketOnData);
878 this[kWebSocket] = undefined;
880 clearTimeout(websocket._closeTimer);
883 websocket._receiver._writableState.finished ||
884 websocket._receiver._writableState.errorEmitted
886 websocket.emitClose();
888 websocket._receiver.on('error', receiverOnFinish);
889 websocket._receiver.on('finish', receiverOnFinish);
894 * The listener of the `net.Socket` `'data'` event.
896 * @param {Buffer} chunk A chunk of data
899 function socketOnData(chunk) {
900 if (!this[kWebSocket]._receiver.write(chunk)) {
906 * The listener of the `net.Socket` `'end'` event.
910 function socketOnEnd() {
911 const websocket = this[kWebSocket];
913 websocket._readyState = WebSocket.CLOSING;
914 websocket._receiver.end();
919 * The listener of the `net.Socket` `'error'` event.
923 function socketOnError() {
924 const websocket = this[kWebSocket];
926 this.removeListener('error', socketOnError);
927 this.on('error', NOOP);
930 websocket._readyState = WebSocket.CLOSING;