websocket.js 33 KB

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