Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

websocket.js 30KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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. if (res.headers.upgrade.toLowerCase() !== 'websocket') {
  692. abortHandshake(websocket, socket, 'Invalid Upgrade header');
  693. return;
  694. }
  695. const digest = createHash('sha1')
  696. .update(key + GUID)
  697. .digest('base64');
  698. if (res.headers['sec-websocket-accept'] !== digest) {
  699. abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
  700. return;
  701. }
  702. const serverProt = res.headers['sec-websocket-protocol'];
  703. const protList = (protocols || '').split(/, */);
  704. let protError;
  705. if (!protocols && serverProt) {
  706. protError = 'Server sent a subprotocol but none was requested';
  707. } else if (protocols && !serverProt) {
  708. protError = 'Server sent no subprotocol';
  709. } else if (serverProt && !protList.includes(serverProt)) {
  710. protError = 'Server sent an invalid subprotocol';
  711. }
  712. if (protError) {
  713. abortHandshake(websocket, socket, protError);
  714. return;
  715. }
  716. if (serverProt) websocket._protocol = serverProt;
  717. const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
  718. if (secWebSocketExtensions !== undefined) {
  719. if (!perMessageDeflate) {
  720. const message =
  721. 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
  722. 'was requested';
  723. abortHandshake(websocket, socket, message);
  724. return;
  725. }
  726. let extensions;
  727. try {
  728. extensions = parse(secWebSocketExtensions);
  729. } catch (err) {
  730. const message = 'Invalid Sec-WebSocket-Extensions header';
  731. abortHandshake(websocket, socket, message);
  732. return;
  733. }
  734. const extensionNames = Object.keys(extensions);
  735. if (extensionNames.length) {
  736. if (
  737. extensionNames.length !== 1 ||
  738. extensionNames[0] !== PerMessageDeflate.extensionName
  739. ) {
  740. const message =
  741. 'Server indicated an extension that was not requested';
  742. abortHandshake(websocket, socket, message);
  743. return;
  744. }
  745. try {
  746. perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
  747. } catch (err) {
  748. const message = 'Invalid Sec-WebSocket-Extensions header';
  749. abortHandshake(websocket, socket, message);
  750. return;
  751. }
  752. websocket._extensions[PerMessageDeflate.extensionName] =
  753. perMessageDeflate;
  754. }
  755. }
  756. websocket.setSocket(socket, head, opts.maxPayload);
  757. });
  758. }
  759. /**
  760. * Emit the `'error'` and `'close'` event.
  761. *
  762. * @param {WebSocket} websocket The WebSocket instance
  763. * @param {Error} The error to emit
  764. * @private
  765. */
  766. function emitErrorAndClose(websocket, err) {
  767. websocket._readyState = WebSocket.CLOSING;
  768. websocket.emit('error', err);
  769. websocket.emitClose();
  770. }
  771. /**
  772. * Create a `net.Socket` and initiate a connection.
  773. *
  774. * @param {Object} options Connection options
  775. * @return {net.Socket} The newly created socket used to start the connection
  776. * @private
  777. */
  778. function netConnect(options) {
  779. options.path = options.socketPath;
  780. return net.connect(options);
  781. }
  782. /**
  783. * Create a `tls.TLSSocket` and initiate a connection.
  784. *
  785. * @param {Object} options Connection options
  786. * @return {tls.TLSSocket} The newly created socket used to start the connection
  787. * @private
  788. */
  789. function tlsConnect(options) {
  790. options.path = undefined;
  791. if (!options.servername && options.servername !== '') {
  792. options.servername = net.isIP(options.host) ? '' : options.host;
  793. }
  794. return tls.connect(options);
  795. }
  796. /**
  797. * Abort the handshake and emit an error.
  798. *
  799. * @param {WebSocket} websocket The WebSocket instance
  800. * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
  801. * abort or the socket to destroy
  802. * @param {String} message The error message
  803. * @private
  804. */
  805. function abortHandshake(websocket, stream, message) {
  806. websocket._readyState = WebSocket.CLOSING;
  807. const err = new Error(message);
  808. Error.captureStackTrace(err, abortHandshake);
  809. if (stream.setHeader) {
  810. stream.abort();
  811. if (stream.socket && !stream.socket.destroyed) {
  812. //
  813. // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
  814. // called after the request completed. See
  815. // https://github.com/websockets/ws/issues/1869.
  816. //
  817. stream.socket.destroy();
  818. }
  819. stream.once('abort', websocket.emitClose.bind(websocket));
  820. websocket.emit('error', err);
  821. } else {
  822. stream.destroy(err);
  823. stream.once('error', websocket.emit.bind(websocket, 'error'));
  824. stream.once('close', websocket.emitClose.bind(websocket));
  825. }
  826. }
  827. /**
  828. * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
  829. * when the `readyState` attribute is `CLOSING` or `CLOSED`.
  830. *
  831. * @param {WebSocket} websocket The WebSocket instance
  832. * @param {*} [data] The data to send
  833. * @param {Function} [cb] Callback
  834. * @private
  835. */
  836. function sendAfterClose(websocket, data, cb) {
  837. if (data) {
  838. const length = toBuffer(data).length;
  839. //
  840. // The `_bufferedAmount` property is used only when the peer is a client and
  841. // the opening handshake fails. Under these circumstances, in fact, the
  842. // `setSocket()` method is not called, so the `_socket` and `_sender`
  843. // properties are set to `null`.
  844. //
  845. if (websocket._socket) websocket._sender._bufferedBytes += length;
  846. else websocket._bufferedAmount += length;
  847. }
  848. if (cb) {
  849. const err = new Error(
  850. `WebSocket is not open: readyState ${websocket.readyState} ` +
  851. `(${readyStates[websocket.readyState]})`
  852. );
  853. cb(err);
  854. }
  855. }
  856. /**
  857. * The listener of the `Receiver` `'conclude'` event.
  858. *
  859. * @param {Number} code The status code
  860. * @param {String} reason The reason for closing
  861. * @private
  862. */
  863. function receiverOnConclude(code, reason) {
  864. const websocket = this[kWebSocket];
  865. websocket._closeFrameReceived = true;
  866. websocket._closeMessage = reason;
  867. websocket._closeCode = code;
  868. if (websocket._socket[kWebSocket] === undefined) return;
  869. websocket._socket.removeListener('data', socketOnData);
  870. process.nextTick(resume, websocket._socket);
  871. if (code === 1005) websocket.close();
  872. else websocket.close(code, reason);
  873. }
  874. /**
  875. * The listener of the `Receiver` `'drain'` event.
  876. *
  877. * @private
  878. */
  879. function receiverOnDrain() {
  880. this[kWebSocket]._socket.resume();
  881. }
  882. /**
  883. * The listener of the `Receiver` `'error'` event.
  884. *
  885. * @param {(RangeError|Error)} err The emitted error
  886. * @private
  887. */
  888. function receiverOnError(err) {
  889. const websocket = this[kWebSocket];
  890. if (websocket._socket[kWebSocket] !== undefined) {
  891. websocket._socket.removeListener('data', socketOnData);
  892. //
  893. // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
  894. // https://github.com/websockets/ws/issues/1940.
  895. //
  896. process.nextTick(resume, websocket._socket);
  897. websocket.close(err[kStatusCode]);
  898. }
  899. websocket.emit('error', err);
  900. }
  901. /**
  902. * The listener of the `Receiver` `'finish'` event.
  903. *
  904. * @private
  905. */
  906. function receiverOnFinish() {
  907. this[kWebSocket].emitClose();
  908. }
  909. /**
  910. * The listener of the `Receiver` `'message'` event.
  911. *
  912. * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message
  913. * @private
  914. */
  915. function receiverOnMessage(data) {
  916. this[kWebSocket].emit('message', data);
  917. }
  918. /**
  919. * The listener of the `Receiver` `'ping'` event.
  920. *
  921. * @param {Buffer} data The data included in the ping frame
  922. * @private
  923. */
  924. function receiverOnPing(data) {
  925. const websocket = this[kWebSocket];
  926. websocket.pong(data, !websocket._isServer, NOOP);
  927. websocket.emit('ping', data);
  928. }
  929. /**
  930. * The listener of the `Receiver` `'pong'` event.
  931. *
  932. * @param {Buffer} data The data included in the pong frame
  933. * @private
  934. */
  935. function receiverOnPong(data) {
  936. this[kWebSocket].emit('pong', data);
  937. }
  938. /**
  939. * Resume a readable stream
  940. *
  941. * @param {Readable} stream The readable stream
  942. * @private
  943. */
  944. function resume(stream) {
  945. stream.resume();
  946. }
  947. /**
  948. * The listener of the `net.Socket` `'close'` event.
  949. *
  950. * @private
  951. */
  952. function socketOnClose() {
  953. const websocket = this[kWebSocket];
  954. this.removeListener('close', socketOnClose);
  955. this.removeListener('data', socketOnData);
  956. this.removeListener('end', socketOnEnd);
  957. websocket._readyState = WebSocket.CLOSING;
  958. let chunk;
  959. //
  960. // The close frame might not have been received or the `'end'` event emitted,
  961. // for example, if the socket was destroyed due to an error. Ensure that the
  962. // `receiver` stream is closed after writing any remaining buffered data to
  963. // it. If the readable side of the socket is in flowing mode then there is no
  964. // buffered data as everything has been already written and `readable.read()`
  965. // will return `null`. If instead, the socket is paused, any possible buffered
  966. // data will be read as a single chunk.
  967. //
  968. if (
  969. !this._readableState.endEmitted &&
  970. !websocket._closeFrameReceived &&
  971. !websocket._receiver._writableState.errorEmitted &&
  972. (chunk = websocket._socket.read()) !== null
  973. ) {
  974. websocket._receiver.write(chunk);
  975. }
  976. websocket._receiver.end();
  977. this[kWebSocket] = undefined;
  978. clearTimeout(websocket._closeTimer);
  979. if (
  980. websocket._receiver._writableState.finished ||
  981. websocket._receiver._writableState.errorEmitted
  982. ) {
  983. websocket.emitClose();
  984. } else {
  985. websocket._receiver.on('error', receiverOnFinish);
  986. websocket._receiver.on('finish', receiverOnFinish);
  987. }
  988. }
  989. /**
  990. * The listener of the `net.Socket` `'data'` event.
  991. *
  992. * @param {Buffer} chunk A chunk of data
  993. * @private
  994. */
  995. function socketOnData(chunk) {
  996. if (!this[kWebSocket]._receiver.write(chunk)) {
  997. this.pause();
  998. }
  999. }
  1000. /**
  1001. * The listener of the `net.Socket` `'end'` event.
  1002. *
  1003. * @private
  1004. */
  1005. function socketOnEnd() {
  1006. const websocket = this[kWebSocket];
  1007. websocket._readyState = WebSocket.CLOSING;
  1008. websocket._receiver.end();
  1009. this.end();
  1010. }
  1011. /**
  1012. * The listener of the `net.Socket` `'error'` event.
  1013. *
  1014. * @private
  1015. */
  1016. function socketOnError() {
  1017. const websocket = this[kWebSocket];
  1018. this.removeListener('error', socketOnError);
  1019. this.on('error', NOOP);
  1020. if (websocket) {
  1021. websocket._readyState = WebSocket.CLOSING;
  1022. this.destroy();
  1023. }
  1024. }