websocket.js 36 KB

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