websocket.js 29 KB

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