websocket.js 33 KB

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