You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

905 lines
24 KiB

  1. 'use strict';
  2. const EventEmitter = require('events');
  3. const https = require('https');
  4. const http = require('http');
  5. const net = require('net');
  6. const tls = require('tls');
  7. const { randomBytes, createHash } = require('crypto');
  8. const { URL } = require('url');
  9. const PerMessageDeflate = require('./permessage-deflate');
  10. const Receiver = require('./receiver');
  11. const Sender = require('./sender');
  12. const {
  13. BINARY_TYPES,
  14. EMPTY_BUFFER,
  15. GUID,
  16. kStatusCode,
  17. kWebSocket,
  18. NOOP
  19. } = require('./constants');
  20. const { addEventListener, removeEventListener } = require('./event-target');
  21. const { format, parse } = require('./extension');
  22. const { toBuffer } = require('./buffer-util');
  23. const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
  24. const protocolVersions = [8, 13];
  25. const closeTimeout = 30 * 1000;
  26. /**
  27. * Class representing a WebSocket.
  28. *
  29. * @extends EventEmitter
  30. */
  31. class WebSocket extends EventEmitter {
  32. /**
  33. * Create a new `WebSocket`.
  34. *
  35. * @param {(String|url.URL)} address The URL to which to connect
  36. * @param {(String|String[])} protocols The subprotocols
  37. * @param {Object} options Connection options
  38. */
  39. constructor(address, protocols, options) {
  40. super();
  41. this.readyState = WebSocket.CONNECTING;
  42. this.protocol = '';
  43. this._binaryType = BINARY_TYPES[0];
  44. this._closeFrameReceived = false;
  45. this._closeFrameSent = false;
  46. this._closeMessage = '';
  47. this._closeTimer = null;
  48. this._closeCode = 1006;
  49. this._extensions = {};
  50. this._receiver = null;
  51. this._sender = null;
  52. this._socket = null;
  53. if (address !== null) {
  54. this._bufferedAmount = 0;
  55. this._isServer = false;
  56. this._redirects = 0;
  57. if (Array.isArray(protocols)) {
  58. protocols = protocols.join(', ');
  59. } else if (typeof protocols === 'object' && protocols !== null) {
  60. options = protocols;
  61. protocols = undefined;
  62. }
  63. initAsClient(this, address, protocols, options);
  64. } else {
  65. this._isServer = true;
  66. }
  67. }
  68. get CONNECTING() {
  69. return WebSocket.CONNECTING;
  70. }
  71. get CLOSING() {
  72. return WebSocket.CLOSING;
  73. }
  74. get CLOSED() {
  75. return WebSocket.CLOSED;
  76. }
  77. get OPEN() {
  78. return WebSocket.OPEN;
  79. }
  80. /**
  81. * This deviates from the WHATWG interface since ws doesn't support the
  82. * required default "blob" type (instead we define a custom "nodebuffer"
  83. * type).
  84. *
  85. * @type {String}
  86. */
  87. get binaryType() {
  88. return this._binaryType;
  89. }
  90. set binaryType(type) {
  91. if (!BINARY_TYPES.includes(type)) return;
  92. this._binaryType = type;
  93. //
  94. // Allow to change `binaryType` on the fly.
  95. //
  96. if (this._receiver) this._receiver._binaryType = type;
  97. }
  98. /**
  99. * @type {Number}
  100. */
  101. get bufferedAmount() {
  102. if (!this._socket) return this._bufferedAmount;
  103. return this._socket._writableState.length + this._sender._bufferedBytes;
  104. }
  105. /**
  106. * @type {String}
  107. */
  108. get extensions() {
  109. return Object.keys(this._extensions).join();
  110. }
  111. /**
  112. * Set up the socket and the internal resources.
  113. *
  114. * @param {net.Socket} socket The network socket between the server and client
  115. * @param {Buffer} head The first packet of the upgraded stream
  116. * @param {Number} maxPayload The maximum allowed message size
  117. * @private
  118. */
  119. setSocket(socket, head, maxPayload) {
  120. const receiver = new Receiver(
  121. this._binaryType,
  122. this._extensions,
  123. this._isServer,
  124. maxPayload
  125. );
  126. this._sender = new Sender(socket, this._extensions);
  127. this._receiver = receiver;
  128. this._socket = socket;
  129. receiver[kWebSocket] = this;
  130. socket[kWebSocket] = this;
  131. receiver.on('conclude', receiverOnConclude);
  132. receiver.on('drain', receiverOnDrain);
  133. receiver.on('error', receiverOnError);
  134. receiver.on('message', receiverOnMessage);
  135. receiver.on('ping', receiverOnPing);
  136. receiver.on('pong', receiverOnPong);
  137. socket.setTimeout(0);
  138. socket.setNoDelay();
  139. if (head.length > 0) socket.unshift(head);
  140. socket.on('close', socketOnClose);
  141. socket.on('data', socketOnData);
  142. socket.on('end', socketOnEnd);
  143. socket.on('error', socketOnError);
  144. this.readyState = WebSocket.OPEN;
  145. this.emit('open');
  146. }
  147. /**
  148. * Emit the `'close'` event.
  149. *
  150. * @private
  151. */
  152. emitClose() {
  153. if (!this._socket) {
  154. this.readyState = WebSocket.CLOSED;
  155. this.emit('close', this._closeCode, this._closeMessage);
  156. return;
  157. }
  158. if (this._extensions[PerMessageDeflate.extensionName]) {
  159. this._extensions[PerMessageDeflate.extensionName].cleanup();
  160. }
  161. this._receiver.removeAllListeners();
  162. this.readyState = WebSocket.CLOSED;
  163. this.emit('close', this._closeCode, this._closeMessage);
  164. }
  165. /**
  166. * Start a closing handshake.
  167. *
  168. * +----------+ +-----------+ +----------+
  169. * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
  170. * | +----------+ +-----------+ +----------+ |
  171. * +----------+ +-----------+ |
  172. * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
  173. * +----------+ +-----------+ |
  174. * | | | +---+ |
  175. * +------------------------+-->|fin| - - - -
  176. * | +---+ | +---+
  177. * - - - - -|fin|<---------------------+
  178. * +---+
  179. *
  180. * @param {Number} code Status code explaining why the connection is closing
  181. * @param {String} data A string explaining why the connection is closing
  182. * @public
  183. */
  184. close(code, data) {
  185. if (this.readyState === WebSocket.CLOSED) return;
  186. if (this.readyState === WebSocket.CONNECTING) {
  187. const msg = 'WebSocket was closed before the connection was established';
  188. return abortHandshake(this, this._req, msg);
  189. }
  190. if (this.readyState === WebSocket.CLOSING) {
  191. if (this._closeFrameSent && this._closeFrameReceived) this._socket.end();
  192. return;
  193. }
  194. this.readyState = WebSocket.CLOSING;
  195. this._sender.close(code, data, !this._isServer, (err) => {
  196. //
  197. // This error is handled by the `'error'` listener on the socket. We only
  198. // want to know if the close frame has been sent here.
  199. //
  200. if (err) return;
  201. this._closeFrameSent = true;
  202. if (this._closeFrameReceived) this._socket.end();
  203. });
  204. //
  205. // Specify a timeout for the closing handshake to complete.
  206. //
  207. this._closeTimer = setTimeout(
  208. this._socket.destroy.bind(this._socket),
  209. closeTimeout
  210. );
  211. }
  212. /**
  213. * Send a ping.
  214. *
  215. * @param {*} data The data to send
  216. * @param {Boolean} mask Indicates whether or not to mask `data`
  217. * @param {Function} cb Callback which is executed when the ping is sent
  218. * @public
  219. */
  220. ping(data, mask, cb) {
  221. if (this.readyState === WebSocket.CONNECTING) {
  222. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  223. }
  224. if (typeof data === 'function') {
  225. cb = data;
  226. data = mask = undefined;
  227. } else if (typeof mask === 'function') {
  228. cb = mask;
  229. mask = undefined;
  230. }
  231. if (typeof data === 'number') data = data.toString();
  232. if (this.readyState !== WebSocket.OPEN) {
  233. sendAfterClose(this, data, cb);
  234. return;
  235. }
  236. if (mask === undefined) mask = !this._isServer;
  237. this._sender.ping(data || EMPTY_BUFFER, mask, cb);
  238. }
  239. /**
  240. * Send a pong.
  241. *
  242. * @param {*} data The data to send
  243. * @param {Boolean} mask Indicates whether or not to mask `data`
  244. * @param {Function} cb Callback which is executed when the pong is sent
  245. * @public
  246. */
  247. pong(data, mask, cb) {
  248. if (this.readyState === WebSocket.CONNECTING) {
  249. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  250. }
  251. if (typeof data === 'function') {
  252. cb = data;
  253. data = mask = undefined;
  254. } else if (typeof mask === 'function') {
  255. cb = mask;
  256. mask = undefined;
  257. }
  258. if (typeof data === 'number') data = data.toString();
  259. if (this.readyState !== WebSocket.OPEN) {
  260. sendAfterClose(this, data, cb);
  261. return;
  262. }
  263. if (mask === undefined) mask = !this._isServer;
  264. this._sender.pong(data || EMPTY_BUFFER, mask, cb);
  265. }
  266. /**
  267. * Send a data message.
  268. *
  269. * @param {*} data The message to send
  270. * @param {Object} options Options object
  271. * @param {Boolean} options.compress Specifies whether or not to compress
  272. * `data`
  273. * @param {Boolean} options.binary Specifies whether `data` is binary or text
  274. * @param {Boolean} options.fin Specifies whether the fragment is the last one
  275. * @param {Boolean} options.mask Specifies whether or not to mask `data`
  276. * @param {Function} cb Callback which is executed when data is written out
  277. * @public
  278. */
  279. send(data, options, cb) {
  280. if (this.readyState === WebSocket.CONNECTING) {
  281. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  282. }
  283. if (typeof options === 'function') {
  284. cb = options;
  285. options = {};
  286. }
  287. if (typeof data === 'number') data = data.toString();
  288. if (this.readyState !== WebSocket.OPEN) {
  289. sendAfterClose(this, data, cb);
  290. return;
  291. }
  292. const opts = {
  293. binary: typeof data !== 'string',
  294. mask: !this._isServer,
  295. compress: true,
  296. fin: true,
  297. ...options
  298. };
  299. if (!this._extensions[PerMessageDeflate.extensionName]) {
  300. opts.compress = false;
  301. }
  302. this._sender.send(data || EMPTY_BUFFER, opts, cb);
  303. }
  304. /**
  305. * Forcibly close the connection.
  306. *
  307. * @public
  308. */
  309. terminate() {
  310. if (this.readyState === WebSocket.CLOSED) return;
  311. if (this.readyState === WebSocket.CONNECTING) {
  312. const msg = 'WebSocket was closed before the connection was established';
  313. return abortHandshake(this, this._req, msg);
  314. }
  315. if (this._socket) {
  316. this.readyState = WebSocket.CLOSING;
  317. this._socket.destroy();
  318. }
  319. }
  320. }
  321. readyStates.forEach((readyState, i) => {
  322. WebSocket[readyState] = i;
  323. });
  324. //
  325. // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
  326. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
  327. //
  328. ['open', 'error', 'close', 'message'].forEach((method) => {
  329. Object.defineProperty(WebSocket.prototype, `on${method}`, {
  330. /**
  331. * Return the listener of the event.
  332. *
  333. * @return {(Function|undefined)} The event listener or `undefined`
  334. * @public
  335. */
  336. get() {
  337. const listeners = this.listeners(method);
  338. for (let i = 0; i < listeners.length; i++) {
  339. if (listeners[i]._listener) return listeners[i]._listener;
  340. }
  341. return undefined;
  342. },
  343. /**
  344. * Add a listener for the event.
  345. *
  346. * @param {Function} listener The listener to add
  347. * @public
  348. */
  349. set(listener) {
  350. const listeners = this.listeners(method);
  351. for (let i = 0; i < listeners.length; i++) {
  352. //
  353. // Remove only the listeners added via `addEventListener`.
  354. //
  355. if (listeners[i]._listener) this.removeListener(method, listeners[i]);
  356. }
  357. this.addEventListener(method, listener);
  358. }
  359. });
  360. });
  361. WebSocket.prototype.addEventListener = addEventListener;
  362. WebSocket.prototype.removeEventListener = removeEventListener;
  363. module.exports = WebSocket;
  364. /**
  365. * Initialize a WebSocket client.
  366. *
  367. * @param {WebSocket} websocket The client to initialize
  368. * @param {(String|url.URL)} address The URL to which to connect
  369. * @param {String} protocols The subprotocols
  370. * @param {Object} options Connection options
  371. * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable
  372. * permessage-deflate
  373. * @param {Number} options.handshakeTimeout Timeout in milliseconds for the
  374. * handshake request
  375. * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version`
  376. * header
  377. * @param {String} options.origin Value of the `Origin` or
  378. * `Sec-WebSocket-Origin` header
  379. * @param {Number} options.maxPayload The maximum allowed message size
  380. * @param {Boolean} options.followRedirects Whether or not to follow redirects
  381. * @param {Number} options.maxRedirects The maximum number of redirects allowed
  382. * @private
  383. */
  384. function initAsClient(websocket, address, protocols, options) {
  385. const opts = {
  386. protocolVersion: protocolVersions[1],
  387. maxPayload: 100 * 1024 * 1024,
  388. perMessageDeflate: true,
  389. followRedirects: false,
  390. maxRedirects: 10,
  391. ...options,
  392. createConnection: undefined,
  393. socketPath: undefined,
  394. hostname: undefined,
  395. protocol: undefined,
  396. timeout: undefined,
  397. method: undefined,
  398. host: undefined,
  399. path: undefined,
  400. port: undefined
  401. };
  402. if (!protocolVersions.includes(opts.protocolVersion)) {
  403. throw new RangeError(
  404. `Unsupported protocol version: ${opts.protocolVersion} ` +
  405. `(supported versions: ${protocolVersions.join(', ')})`
  406. );
  407. }
  408. let parsedUrl;
  409. if (address instanceof URL) {
  410. parsedUrl = address;
  411. websocket.url = address.href;
  412. } else {
  413. parsedUrl = new URL(address);
  414. websocket.url = address;
  415. }
  416. const isUnixSocket = parsedUrl.protocol === 'ws+unix:';
  417. if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {
  418. throw new Error(`Invalid URL: ${websocket.url}`);
  419. }
  420. const isSecure =
  421. parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';
  422. const defaultPort = isSecure ? 443 : 80;
  423. const key = randomBytes(16).toString('base64');
  424. const get = isSecure ? https.get : http.get;
  425. let perMessageDeflate;
  426. opts.createConnection = isSecure ? tlsConnect : netConnect;
  427. opts.defaultPort = opts.defaultPort || defaultPort;
  428. opts.port = parsedUrl.port || defaultPort;
  429. opts.host = parsedUrl.hostname.startsWith('[')
  430. ? parsedUrl.hostname.slice(1, -1)
  431. : parsedUrl.hostname;
  432. opts.headers = {
  433. 'Sec-WebSocket-Version': opts.protocolVersion,
  434. 'Sec-WebSocket-Key': key,
  435. Connection: 'Upgrade',
  436. Upgrade: 'websocket',
  437. ...opts.headers
  438. };
  439. opts.path = parsedUrl.pathname + parsedUrl.search;
  440. opts.timeout = opts.handshakeTimeout;
  441. if (opts.perMessageDeflate) {
  442. perMessageDeflate = new PerMessageDeflate(
  443. opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
  444. false,
  445. opts.maxPayload
  446. );
  447. opts.headers['Sec-WebSocket-Extensions'] = format({
  448. [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
  449. });
  450. }
  451. if (protocols) {
  452. opts.headers['Sec-WebSocket-Protocol'] = protocols;
  453. }
  454. if (opts.origin) {
  455. if (opts.protocolVersion < 13) {
  456. opts.headers['Sec-WebSocket-Origin'] = opts.origin;
  457. } else {
  458. opts.headers.Origin = opts.origin;
  459. }
  460. }
  461. if (parsedUrl.username || parsedUrl.password) {
  462. opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
  463. }
  464. if (isUnixSocket) {
  465. const parts = opts.path.split(':');
  466. opts.socketPath = parts[0];
  467. opts.path = parts[1];
  468. }
  469. let req = (websocket._req = get(opts));
  470. if (opts.timeout) {
  471. req.on('timeout', () => {
  472. abortHandshake(websocket, req, 'Opening handshake has timed out');
  473. });
  474. }
  475. req.on('error', (err) => {
  476. if (websocket._req.aborted) return;
  477. req = websocket._req = null;
  478. websocket.readyState = WebSocket.CLOSING;
  479. websocket.emit('error', err);
  480. websocket.emitClose();
  481. });
  482. req.on('response', (res) => {
  483. const location = res.headers.location;
  484. const statusCode = res.statusCode;
  485. if (
  486. location &&
  487. opts.followRedirects &&
  488. statusCode >= 300 &&
  489. statusCode < 400
  490. ) {
  491. if (++websocket._redirects > opts.maxRedirects) {
  492. abortHandshake(websocket, req, 'Maximum redirects exceeded');
  493. return;
  494. }
  495. req.abort();
  496. const addr = new URL(location, address);
  497. initAsClient(websocket, addr, protocols, options);
  498. } else if (!websocket.emit('unexpected-response', req, res)) {
  499. abortHandshake(
  500. websocket,
  501. req,
  502. `Unexpected server response: ${res.statusCode}`
  503. );
  504. }
  505. });
  506. req.on('upgrade', (res, socket, head) => {
  507. websocket.emit('upgrade', res);
  508. //
  509. // The user may have closed the connection from a listener of the `upgrade`
  510. // event.
  511. //
  512. if (websocket.readyState !== WebSocket.CONNECTING) return;
  513. req = websocket._req = null;
  514. const digest = createHash('sha1')
  515. .update(key + GUID)
  516. .digest('base64');
  517. if (res.headers['sec-websocket-accept'] !== digest) {
  518. abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
  519. return;
  520. }
  521. const serverProt = res.headers['sec-websocket-protocol'];
  522. const protList = (protocols || '').split(/, */);
  523. let protError;
  524. if (!protocols && serverProt) {
  525. protError = 'Server sent a subprotocol but none was requested';
  526. } else if (protocols && !serverProt) {
  527. protError = 'Server sent no subprotocol';
  528. } else if (serverProt && !protList.includes(serverProt)) {
  529. protError = 'Server sent an invalid subprotocol';
  530. }
  531. if (protError) {
  532. abortHandshake(websocket, socket, protError);
  533. return;
  534. }
  535. if (serverProt) websocket.protocol = serverProt;
  536. if (perMessageDeflate) {
  537. try {
  538. const extensions = parse(res.headers['sec-websocket-extensions']);
  539. if (extensions[PerMessageDeflate.extensionName]) {
  540. perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
  541. websocket._extensions[
  542. PerMessageDeflate.extensionName
  543. ] = perMessageDeflate;
  544. }
  545. } catch (err) {
  546. abortHandshake(
  547. websocket,
  548. socket,
  549. 'Invalid Sec-WebSocket-Extensions header'
  550. );
  551. return;
  552. }
  553. }
  554. websocket.setSocket(socket, head, opts.maxPayload);
  555. });
  556. }
  557. /**
  558. * Create a `net.Socket` and initiate a connection.
  559. *
  560. * @param {Object} options Connection options
  561. * @return {net.Socket} The newly created socket used to start the connection
  562. * @private
  563. */
  564. function netConnect(options) {
  565. options.path = options.socketPath;
  566. return net.connect(options);
  567. }
  568. /**
  569. * Create a `tls.TLSSocket` and initiate a connection.
  570. *
  571. * @param {Object} options Connection options
  572. * @return {tls.TLSSocket} The newly created socket used to start the connection
  573. * @private
  574. */
  575. function tlsConnect(options) {
  576. options.path = undefined;
  577. if (!options.servername && options.servername !== '') {
  578. options.servername = options.host;
  579. }
  580. return tls.connect(options);
  581. }
  582. /**
  583. * Abort the handshake and emit an error.
  584. *
  585. * @param {WebSocket} websocket The WebSocket instance
  586. * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the
  587. * socket to destroy
  588. * @param {String} message The error message
  589. * @private
  590. */
  591. function abortHandshake(websocket, stream, message) {
  592. websocket.readyState = WebSocket.CLOSING;
  593. const err = new Error(message);
  594. Error.captureStackTrace(err, abortHandshake);
  595. if (stream.setHeader) {
  596. stream.abort();
  597. stream.once('abort', websocket.emitClose.bind(websocket));
  598. websocket.emit('error', err);
  599. } else {
  600. stream.destroy(err);
  601. stream.once('error', websocket.emit.bind(websocket, 'error'));
  602. stream.once('close', websocket.emitClose.bind(websocket));
  603. }
  604. }
  605. /**
  606. * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
  607. * when the `readyState` attribute is `CLOSING` or `CLOSED`.
  608. *
  609. * @param {WebSocket} websocket The WebSocket instance
  610. * @param {*} data The data to send
  611. * @param {Function} cb Callback
  612. * @private
  613. */
  614. function sendAfterClose(websocket, data, cb) {
  615. if (data) {
  616. const length = toBuffer(data).length;
  617. //
  618. // The `_bufferedAmount` property is used only when the peer is a client and
  619. // the opening handshake fails. Under these circumstances, in fact, the
  620. // `setSocket()` method is not called, so the `_socket` and `_sender`
  621. // properties are set to `null`.
  622. //
  623. if (websocket._socket) websocket._sender._bufferedBytes += length;
  624. else websocket._bufferedAmount += length;
  625. }
  626. if (cb) {
  627. const err = new Error(
  628. `WebSocket is not open: readyState ${websocket.readyState} ` +
  629. `(${readyStates[websocket.readyState]})`
  630. );
  631. cb(err);
  632. }
  633. }
  634. /**
  635. * The listener of the `Receiver` `'conclude'` event.
  636. *
  637. * @param {Number} code The status code
  638. * @param {String} reason The reason for closing
  639. * @private
  640. */
  641. function receiverOnConclude(code, reason) {
  642. const websocket = this[kWebSocket];
  643. websocket._socket.removeListener('data', socketOnData);
  644. websocket._socket.resume();
  645. websocket._closeFrameReceived = true;
  646. websocket._closeMessage = reason;
  647. websocket._closeCode = code;
  648. if (code === 1005) websocket.close();
  649. else websocket.close(code, reason);
  650. }
  651. /**
  652. * The listener of the `Receiver` `'drain'` event.
  653. *
  654. * @private
  655. */
  656. function receiverOnDrain() {
  657. this[kWebSocket]._socket.resume();
  658. }
  659. /**
  660. * The listener of the `Receiver` `'error'` event.
  661. *
  662. * @param {(RangeError|Error)} err The emitted error
  663. * @private
  664. */
  665. function receiverOnError(err) {
  666. const websocket = this[kWebSocket];
  667. websocket._socket.removeListener('data', socketOnData);
  668. websocket.readyState = WebSocket.CLOSING;
  669. websocket._closeCode = err[kStatusCode];
  670. websocket.emit('error', err);
  671. websocket._socket.destroy();
  672. }
  673. /**
  674. * The listener of the `Receiver` `'finish'` event.
  675. *
  676. * @private
  677. */
  678. function receiverOnFinish() {
  679. this[kWebSocket].emitClose();
  680. }
  681. /**
  682. * The listener of the `Receiver` `'message'` event.
  683. *
  684. * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message
  685. * @private
  686. */
  687. function receiverOnMessage(data) {
  688. this[kWebSocket].emit('message', data);
  689. }
  690. /**
  691. * The listener of the `Receiver` `'ping'` event.
  692. *
  693. * @param {Buffer} data The data included in the ping frame
  694. * @private
  695. */
  696. function receiverOnPing(data) {
  697. const websocket = this[kWebSocket];
  698. websocket.pong(data, !websocket._isServer, NOOP);
  699. websocket.emit('ping', data);
  700. }
  701. /**
  702. * The listener of the `Receiver` `'pong'` event.
  703. *
  704. * @param {Buffer} data The data included in the pong frame
  705. * @private
  706. */
  707. function receiverOnPong(data) {
  708. this[kWebSocket].emit('pong', data);
  709. }
  710. /**
  711. * The listener of the `net.Socket` `'close'` event.
  712. *
  713. * @private
  714. */
  715. function socketOnClose() {
  716. const websocket = this[kWebSocket];
  717. this.removeListener('close', socketOnClose);
  718. this.removeListener('end', socketOnEnd);
  719. websocket.readyState = WebSocket.CLOSING;
  720. //
  721. // The close frame might not have been received or the `'end'` event emitted,
  722. // for example, if the socket was destroyed due to an error. Ensure that the
  723. // `receiver` stream is closed after writing any remaining buffered data to
  724. // it. If the readable side of the socket is in flowing mode then there is no
  725. // buffered data as everything has been already written and `readable.read()`
  726. // will return `null`. If instead, the socket is paused, any possible buffered
  727. // data will be read as a single chunk and emitted synchronously in a single
  728. // `'data'` event.
  729. //
  730. websocket._socket.read();
  731. websocket._receiver.end();
  732. this.removeListener('data', socketOnData);
  733. this[kWebSocket] = undefined;
  734. clearTimeout(websocket._closeTimer);
  735. if (
  736. websocket._receiver._writableState.finished ||
  737. websocket._receiver._writableState.errorEmitted
  738. ) {
  739. websocket.emitClose();
  740. } else {
  741. websocket._receiver.on('error', receiverOnFinish);
  742. websocket._receiver.on('finish', receiverOnFinish);
  743. }
  744. }
  745. /**
  746. * The listener of the `net.Socket` `'data'` event.
  747. *
  748. * @param {Buffer} chunk A chunk of data
  749. * @private
  750. */
  751. function socketOnData(chunk) {
  752. if (!this[kWebSocket]._receiver.write(chunk)) {
  753. this.pause();
  754. }
  755. }
  756. /**
  757. * The listener of the `net.Socket` `'end'` event.
  758. *
  759. * @private
  760. */
  761. function socketOnEnd() {
  762. const websocket = this[kWebSocket];
  763. websocket.readyState = WebSocket.CLOSING;
  764. websocket._receiver.end();
  765. this.end();
  766. }
  767. /**
  768. * The listener of the `net.Socket` `'error'` event.
  769. *
  770. * @private
  771. */
  772. function socketOnError() {
  773. const websocket = this[kWebSocket];
  774. this.removeListener('error', socketOnError);
  775. this.on('error', NOOP);
  776. if (websocket) {
  777. websocket.readyState = WebSocket.CLOSING;
  778. this.destroy();
  779. }
  780. }