Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

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