websocket.js 36 KB

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