websocket.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  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._originalUnixSocket = isUnixSocket;
  598. websocket._originalSecure = isSecure;
  599. websocket._originalHostOrSocketPath = isUnixSocket
  600. ? opts.socketPath
  601. : parsedUrl.host;
  602. const headers = options && options.headers;
  603. //
  604. // Shallow copy the user provided options so that headers can be changed
  605. // without mutating the original object.
  606. //
  607. options = { ...options, headers: {} };
  608. if (headers) {
  609. for (const [key, value] of Object.entries(headers)) {
  610. options.headers[key.toLowerCase()] = value;
  611. }
  612. }
  613. } else {
  614. const isSameHost = isUnixSocket
  615. ? websocket._originalUnixSocket
  616. ? opts.socketPath === websocket._originalHostOrSocketPath
  617. : false
  618. : websocket._originalUnixSocket
  619. ? false
  620. : parsedUrl.host === websocket._originalHostOrSocketPath;
  621. if (!isSameHost || (websocket._originalSecure && !isSecure)) {
  622. //
  623. // Match curl 7.77.0 behavior and drop the following headers. These
  624. // headers are also dropped when following a redirect to a subdomain.
  625. //
  626. delete opts.headers.authorization;
  627. delete opts.headers.cookie;
  628. if (!isSameHost) delete opts.headers.host;
  629. opts.auth = undefined;
  630. }
  631. }
  632. //
  633. // Match curl 7.77.0 behavior and make the first `Authorization` header win.
  634. // If the `Authorization` header is set, then there is nothing to do as it
  635. // will take precedence.
  636. //
  637. if (opts.auth && !options.headers.authorization) {
  638. options.headers.authorization =
  639. 'Basic ' + Buffer.from(opts.auth).toString('base64');
  640. }
  641. }
  642. let req = (websocket._req = get(opts));
  643. if (opts.timeout) {
  644. req.on('timeout', () => {
  645. abortHandshake(websocket, req, 'Opening handshake has timed out');
  646. });
  647. }
  648. req.on('error', (err) => {
  649. if (req === null || req.aborted) return;
  650. req = websocket._req = null;
  651. emitErrorAndClose(websocket, err);
  652. });
  653. req.on('response', (res) => {
  654. const location = res.headers.location;
  655. const statusCode = res.statusCode;
  656. if (
  657. location &&
  658. opts.followRedirects &&
  659. statusCode >= 300 &&
  660. statusCode < 400
  661. ) {
  662. if (++websocket._redirects > opts.maxRedirects) {
  663. abortHandshake(websocket, req, 'Maximum redirects exceeded');
  664. return;
  665. }
  666. req.abort();
  667. let addr;
  668. try {
  669. addr = new URL(location, address);
  670. } catch (err) {
  671. emitErrorAndClose(websocket, err);
  672. return;
  673. }
  674. initAsClient(websocket, addr, protocols, options);
  675. } else if (!websocket.emit('unexpected-response', req, res)) {
  676. abortHandshake(
  677. websocket,
  678. req,
  679. `Unexpected server response: ${res.statusCode}`
  680. );
  681. }
  682. });
  683. req.on('upgrade', (res, socket, head) => {
  684. websocket.emit('upgrade', res);
  685. //
  686. // The user may have closed the connection from a listener of the `upgrade`
  687. // event.
  688. //
  689. if (websocket.readyState !== WebSocket.CONNECTING) return;
  690. req = websocket._req = null;
  691. const upgrade = res.headers.upgrade;
  692. if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
  693. abortHandshake(websocket, socket, 'Invalid Upgrade header');
  694. return;
  695. }
  696. const digest = createHash('sha1')
  697. .update(key + GUID)
  698. .digest('base64');
  699. if (res.headers['sec-websocket-accept'] !== digest) {
  700. abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
  701. return;
  702. }
  703. const serverProt = res.headers['sec-websocket-protocol'];
  704. const protList = (protocols || '').split(/, */);
  705. let protError;
  706. if (!protocols && serverProt) {
  707. protError = 'Server sent a subprotocol but none was requested';
  708. } else if (protocols && !serverProt) {
  709. protError = 'Server sent no subprotocol';
  710. } else if (serverProt && !protList.includes(serverProt)) {
  711. protError = 'Server sent an invalid subprotocol';
  712. }
  713. if (protError) {
  714. abortHandshake(websocket, socket, protError);
  715. return;
  716. }
  717. if (serverProt) websocket._protocol = serverProt;
  718. const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
  719. if (secWebSocketExtensions !== undefined) {
  720. if (!perMessageDeflate) {
  721. const message =
  722. 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
  723. 'was requested';
  724. abortHandshake(websocket, socket, message);
  725. return;
  726. }
  727. let extensions;
  728. try {
  729. extensions = parse(secWebSocketExtensions);
  730. } catch (err) {
  731. const message = 'Invalid Sec-WebSocket-Extensions header';
  732. abortHandshake(websocket, socket, message);
  733. return;
  734. }
  735. const extensionNames = Object.keys(extensions);
  736. if (extensionNames.length) {
  737. if (
  738. extensionNames.length !== 1 ||
  739. extensionNames[0] !== PerMessageDeflate.extensionName
  740. ) {
  741. const message =
  742. 'Server indicated an extension that was not requested';
  743. abortHandshake(websocket, socket, message);
  744. return;
  745. }
  746. try {
  747. perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
  748. } catch (err) {
  749. const message = 'Invalid Sec-WebSocket-Extensions header';
  750. abortHandshake(websocket, socket, message);
  751. return;
  752. }
  753. websocket._extensions[PerMessageDeflate.extensionName] =
  754. perMessageDeflate;
  755. }
  756. }
  757. websocket.setSocket(socket, head, opts.maxPayload);
  758. });
  759. }
  760. /**
  761. * Emit the `'error'` and `'close'` event.
  762. *
  763. * @param {WebSocket} websocket The WebSocket instance
  764. * @param {Error} The error to emit
  765. * @private
  766. */
  767. function emitErrorAndClose(websocket, err) {
  768. websocket._readyState = WebSocket.CLOSING;
  769. websocket.emit('error', err);
  770. websocket.emitClose();
  771. }
  772. /**
  773. * Create a `net.Socket` and initiate a connection.
  774. *
  775. * @param {Object} options Connection options
  776. * @return {net.Socket} The newly created socket used to start the connection
  777. * @private
  778. */
  779. function netConnect(options) {
  780. options.path = options.socketPath;
  781. return net.connect(options);
  782. }
  783. /**
  784. * Create a `tls.TLSSocket` and initiate a connection.
  785. *
  786. * @param {Object} options Connection options
  787. * @return {tls.TLSSocket} The newly created socket used to start the connection
  788. * @private
  789. */
  790. function tlsConnect(options) {
  791. options.path = undefined;
  792. if (!options.servername && options.servername !== '') {
  793. options.servername = net.isIP(options.host) ? '' : options.host;
  794. }
  795. return tls.connect(options);
  796. }
  797. /**
  798. * Abort the handshake and emit an error.
  799. *
  800. * @param {WebSocket} websocket The WebSocket instance
  801. * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
  802. * abort or the socket to destroy
  803. * @param {String} message The error message
  804. * @private
  805. */
  806. function abortHandshake(websocket, stream, message) {
  807. websocket._readyState = WebSocket.CLOSING;
  808. const err = new Error(message);
  809. Error.captureStackTrace(err, abortHandshake);
  810. if (stream.setHeader) {
  811. stream.abort();
  812. if (stream.socket && !stream.socket.destroyed) {
  813. //
  814. // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
  815. // called after the request completed. See
  816. // https://github.com/websockets/ws/issues/1869.
  817. //
  818. stream.socket.destroy();
  819. }
  820. stream.once('abort', websocket.emitClose.bind(websocket));
  821. websocket.emit('error', err);
  822. } else {
  823. stream.destroy(err);
  824. stream.once('error', websocket.emit.bind(websocket, 'error'));
  825. stream.once('close', websocket.emitClose.bind(websocket));
  826. }
  827. }
  828. /**
  829. * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
  830. * when the `readyState` attribute is `CLOSING` or `CLOSED`.
  831. *
  832. * @param {WebSocket} websocket The WebSocket instance
  833. * @param {*} [data] The data to send
  834. * @param {Function} [cb] Callback
  835. * @private
  836. */
  837. function sendAfterClose(websocket, data, cb) {
  838. if (data) {
  839. const length = toBuffer(data).length;
  840. //
  841. // The `_bufferedAmount` property is used only when the peer is a client and
  842. // the opening handshake fails. Under these circumstances, in fact, the
  843. // `setSocket()` method is not called, so the `_socket` and `_sender`
  844. // properties are set to `null`.
  845. //
  846. if (websocket._socket) websocket._sender._bufferedBytes += length;
  847. else websocket._bufferedAmount += length;
  848. }
  849. if (cb) {
  850. const err = new Error(
  851. `WebSocket is not open: readyState ${websocket.readyState} ` +
  852. `(${readyStates[websocket.readyState]})`
  853. );
  854. cb(err);
  855. }
  856. }
  857. /**
  858. * The listener of the `Receiver` `'conclude'` event.
  859. *
  860. * @param {Number} code The status code
  861. * @param {String} reason The reason for closing
  862. * @private
  863. */
  864. function receiverOnConclude(code, reason) {
  865. const websocket = this[kWebSocket];
  866. websocket._closeFrameReceived = true;
  867. websocket._closeMessage = reason;
  868. websocket._closeCode = code;
  869. if (websocket._socket[kWebSocket] === undefined) return;
  870. websocket._socket.removeListener('data', socketOnData);
  871. process.nextTick(resume, websocket._socket);
  872. if (code === 1005) websocket.close();
  873. else websocket.close(code, reason);
  874. }
  875. /**
  876. * The listener of the `Receiver` `'drain'` event.
  877. *
  878. * @private
  879. */
  880. function receiverOnDrain() {
  881. this[kWebSocket]._socket.resume();
  882. }
  883. /**
  884. * The listener of the `Receiver` `'error'` event.
  885. *
  886. * @param {(RangeError|Error)} err The emitted error
  887. * @private
  888. */
  889. function receiverOnError(err) {
  890. const websocket = this[kWebSocket];
  891. if (websocket._socket[kWebSocket] !== undefined) {
  892. websocket._socket.removeListener('data', socketOnData);
  893. //
  894. // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
  895. // https://github.com/websockets/ws/issues/1940.
  896. //
  897. process.nextTick(resume, websocket._socket);
  898. websocket.close(err[kStatusCode]);
  899. }
  900. websocket.emit('error', err);
  901. }
  902. /**
  903. * The listener of the `Receiver` `'finish'` event.
  904. *
  905. * @private
  906. */
  907. function receiverOnFinish() {
  908. this[kWebSocket].emitClose();
  909. }
  910. /**
  911. * The listener of the `Receiver` `'message'` event.
  912. *
  913. * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message
  914. * @private
  915. */
  916. function receiverOnMessage(data) {
  917. this[kWebSocket].emit('message', data);
  918. }
  919. /**
  920. * The listener of the `Receiver` `'ping'` event.
  921. *
  922. * @param {Buffer} data The data included in the ping frame
  923. * @private
  924. */
  925. function receiverOnPing(data) {
  926. const websocket = this[kWebSocket];
  927. websocket.pong(data, !websocket._isServer, NOOP);
  928. websocket.emit('ping', data);
  929. }
  930. /**
  931. * The listener of the `Receiver` `'pong'` event.
  932. *
  933. * @param {Buffer} data The data included in the pong frame
  934. * @private
  935. */
  936. function receiverOnPong(data) {
  937. this[kWebSocket].emit('pong', data);
  938. }
  939. /**
  940. * Resume a readable stream
  941. *
  942. * @param {Readable} stream The readable stream
  943. * @private
  944. */
  945. function resume(stream) {
  946. stream.resume();
  947. }
  948. /**
  949. * The listener of the `net.Socket` `'close'` event.
  950. *
  951. * @private
  952. */
  953. function socketOnClose() {
  954. const websocket = this[kWebSocket];
  955. this.removeListener('close', socketOnClose);
  956. this.removeListener('data', socketOnData);
  957. this.removeListener('end', socketOnEnd);
  958. websocket._readyState = WebSocket.CLOSING;
  959. let chunk;
  960. //
  961. // The close frame might not have been received or the `'end'` event emitted,
  962. // for example, if the socket was destroyed due to an error. Ensure that the
  963. // `receiver` stream is closed after writing any remaining buffered data to
  964. // it. If the readable side of the socket is in flowing mode then there is no
  965. // buffered data as everything has been already written and `readable.read()`
  966. // will return `null`. If instead, the socket is paused, any possible buffered
  967. // data will be read as a single chunk.
  968. //
  969. if (
  970. !this._readableState.endEmitted &&
  971. !websocket._closeFrameReceived &&
  972. !websocket._receiver._writableState.errorEmitted &&
  973. (chunk = websocket._socket.read()) !== null
  974. ) {
  975. websocket._receiver.write(chunk);
  976. }
  977. websocket._receiver.end();
  978. this[kWebSocket] = undefined;
  979. clearTimeout(websocket._closeTimer);
  980. if (
  981. websocket._receiver._writableState.finished ||
  982. websocket._receiver._writableState.errorEmitted
  983. ) {
  984. websocket.emitClose();
  985. } else {
  986. websocket._receiver.on('error', receiverOnFinish);
  987. websocket._receiver.on('finish', receiverOnFinish);
  988. }
  989. }
  990. /**
  991. * The listener of the `net.Socket` `'data'` event.
  992. *
  993. * @param {Buffer} chunk A chunk of data
  994. * @private
  995. */
  996. function socketOnData(chunk) {
  997. if (!this[kWebSocket]._receiver.write(chunk)) {
  998. this.pause();
  999. }
  1000. }
  1001. /**
  1002. * The listener of the `net.Socket` `'end'` event.
  1003. *
  1004. * @private
  1005. */
  1006. function socketOnEnd() {
  1007. const websocket = this[kWebSocket];
  1008. websocket._readyState = WebSocket.CLOSING;
  1009. websocket._receiver.end();
  1010. this.end();
  1011. }
  1012. /**
  1013. * The listener of the `net.Socket` `'error'` event.
  1014. *
  1015. * @private
  1016. */
  1017. function socketOnError() {
  1018. const websocket = this[kWebSocket];
  1019. this.removeListener('error', socketOnError);
  1020. this.on('error', NOOP);
  1021. if (websocket) {
  1022. websocket._readyState = WebSocket.CLOSING;
  1023. this.destroy();
  1024. }
  1025. }