websocket.js 32 KB

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