Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

websocket.js 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. 'use strict';
  2. const EventEmitter = require('events');
  3. const https = require('https');
  4. const http = require('http');
  5. const net = require('net');
  6. const tls = require('tls');
  7. const { randomBytes, createHash } = require('crypto');
  8. const { URL } = require('url');
  9. const PerMessageDeflate = require('./permessage-deflate');
  10. const Receiver = require('./receiver');
  11. const Sender = require('./sender');
  12. const {
  13. BINARY_TYPES,
  14. EMPTY_BUFFER,
  15. GUID,
  16. kStatusCode,
  17. kWebSocket,
  18. NOOP
  19. } = require('./constants');
  20. const { addEventListener, removeEventListener } = require('./event-target');
  21. const { format, parse } = require('./extension');
  22. const { toBuffer } = require('./buffer-util');
  23. const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
  24. const protocolVersions = [8, 13];
  25. const closeTimeout = 30 * 1000;
  26. /**
  27. * Class representing a WebSocket.
  28. *
  29. * @extends EventEmitter
  30. */
  31. class WebSocket extends EventEmitter {
  32. /**
  33. * Create a new `WebSocket`.
  34. *
  35. * @param {(String|url.URL)} address The URL to which to connect
  36. * @param {(String|String[])} [protocols] The subprotocols
  37. * @param {Object} [options] Connection options
  38. */
  39. constructor(address, protocols, options) {
  40. super();
  41. this._binaryType = BINARY_TYPES[0];
  42. this._closeCode = 1006;
  43. this._closeFrameReceived = false;
  44. this._closeFrameSent = false;
  45. this._closeMessage = '';
  46. this._closeTimer = null;
  47. this._extensions = {};
  48. this._protocol = '';
  49. this._readyState = WebSocket.CONNECTING;
  50. this._receiver = null;
  51. this._sender = null;
  52. this._socket = null;
  53. if (address !== null) {
  54. this._bufferedAmount = 0;
  55. this._isServer = false;
  56. this._redirects = 0;
  57. if (Array.isArray(protocols)) {
  58. protocols = protocols.join(', ');
  59. } else if (typeof protocols === 'object' && protocols !== null) {
  60. options = protocols;
  61. protocols = undefined;
  62. }
  63. initAsClient(this, address, protocols, options);
  64. } else {
  65. this._isServer = true;
  66. }
  67. }
  68. /**
  69. * This deviates from the WHATWG interface since ws doesn't support the
  70. * required default "blob" type (instead we define a custom "nodebuffer"
  71. * type).
  72. *
  73. * @type {String}
  74. */
  75. get binaryType() {
  76. return this._binaryType;
  77. }
  78. set binaryType(type) {
  79. if (!BINARY_TYPES.includes(type)) return;
  80. this._binaryType = type;
  81. //
  82. // Allow to change `binaryType` on the fly.
  83. //
  84. if (this._receiver) this._receiver._binaryType = type;
  85. }
  86. /**
  87. * @type {Number}
  88. */
  89. get bufferedAmount() {
  90. if (!this._socket) return this._bufferedAmount;
  91. return this._socket._writableState.length + this._sender._bufferedBytes;
  92. }
  93. /**
  94. * @type {String}
  95. */
  96. get extensions() {
  97. return Object.keys(this._extensions).join();
  98. }
  99. /**
  100. * @type {String}
  101. */
  102. get protocol() {
  103. return this._protocol;
  104. }
  105. /**
  106. * @type {Number}
  107. */
  108. get readyState() {
  109. return this._readyState;
  110. }
  111. /**
  112. * @type {String}
  113. */
  114. get url() {
  115. return this._url;
  116. }
  117. /**
  118. * Set up the socket and the internal resources.
  119. *
  120. * @param {net.Socket} socket The network socket between the server and client
  121. * @param {Buffer} head The first packet of the upgraded stream
  122. * @param {Number} [maxPayload=0] The maximum allowed message size
  123. * @private
  124. */
  125. setSocket(socket, head, maxPayload) {
  126. const receiver = new Receiver(
  127. this.binaryType,
  128. this._extensions,
  129. this._isServer,
  130. maxPayload
  131. );
  132. this._sender = new Sender(socket, this._extensions);
  133. this._receiver = receiver;
  134. this._socket = socket;
  135. receiver[kWebSocket] = this;
  136. socket[kWebSocket] = this;
  137. receiver.on('conclude', receiverOnConclude);
  138. receiver.on('drain', receiverOnDrain);
  139. receiver.on('error', receiverOnError);
  140. receiver.on('message', receiverOnMessage);
  141. receiver.on('ping', receiverOnPing);
  142. receiver.on('pong', receiverOnPong);
  143. socket.setTimeout(0);
  144. socket.setNoDelay();
  145. if (head.length > 0) socket.unshift(head);
  146. socket.on('close', socketOnClose);
  147. socket.on('data', socketOnData);
  148. socket.on('end', socketOnEnd);
  149. socket.on('error', socketOnError);
  150. this._readyState = WebSocket.OPEN;
  151. this.emit('open');
  152. }
  153. /**
  154. * Emit the `'close'` event.
  155. *
  156. * @private
  157. */
  158. emitClose() {
  159. if (!this._socket) {
  160. this._readyState = WebSocket.CLOSED;
  161. this.emit('close', this._closeCode, this._closeMessage);
  162. return;
  163. }
  164. if (this._extensions[PerMessageDeflate.extensionName]) {
  165. this._extensions[PerMessageDeflate.extensionName].cleanup();
  166. }
  167. this._receiver.removeAllListeners();
  168. this._readyState = WebSocket.CLOSED;
  169. this.emit('close', this._closeCode, this._closeMessage);
  170. }
  171. /**
  172. * Start a closing handshake.
  173. *
  174. * +----------+ +-----------+ +----------+
  175. * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
  176. * | +----------+ +-----------+ +----------+ |
  177. * +----------+ +-----------+ |
  178. * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
  179. * +----------+ +-----------+ |
  180. * | | | +---+ |
  181. * +------------------------+-->|fin| - - - -
  182. * | +---+ | +---+
  183. * - - - - -|fin|<---------------------+
  184. * +---+
  185. *
  186. * @param {Number} [code] Status code explaining why the connection is closing
  187. * @param {String} [data] A string explaining why the connection is closing
  188. * @public
  189. */
  190. close(code, data) {
  191. if (this.readyState === WebSocket.CLOSED) return;
  192. if (this.readyState === WebSocket.CONNECTING) {
  193. const msg = 'WebSocket was closed before the connection was established';
  194. return abortHandshake(this, this._req, msg);
  195. }
  196. if (this.readyState === WebSocket.CLOSING) {
  197. if (
  198. this._closeFrameSent &&
  199. (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
  200. ) {
  201. this._socket.end();
  202. }
  203. return;
  204. }
  205. this._readyState = WebSocket.CLOSING;
  206. this._sender.close(code, data, !this._isServer, (err) => {
  207. //
  208. // This error is handled by the `'error'` listener on the socket. We only
  209. // want to know if the close frame has been sent here.
  210. //
  211. if (err) return;
  212. this._closeFrameSent = true;
  213. if (
  214. this._closeFrameReceived ||
  215. this._receiver._writableState.errorEmitted
  216. ) {
  217. this._socket.end();
  218. }
  219. });
  220. //
  221. // Specify a timeout for the closing handshake to complete.
  222. //
  223. this._closeTimer = setTimeout(
  224. this._socket.destroy.bind(this._socket),
  225. closeTimeout
  226. );
  227. }
  228. /**
  229. * Send a ping.
  230. *
  231. * @param {*} [data] The data to send
  232. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  233. * @param {Function} [cb] Callback which is executed when the ping is sent
  234. * @public
  235. */
  236. ping(data, mask, cb) {
  237. if (this.readyState === WebSocket.CONNECTING) {
  238. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  239. }
  240. if (typeof data === 'function') {
  241. cb = data;
  242. data = mask = undefined;
  243. } else if (typeof mask === 'function') {
  244. cb = mask;
  245. mask = undefined;
  246. }
  247. if (typeof data === 'number') data = data.toString();
  248. if (this.readyState !== WebSocket.OPEN) {
  249. sendAfterClose(this, data, cb);
  250. return;
  251. }
  252. if (mask === undefined) mask = !this._isServer;
  253. this._sender.ping(data || EMPTY_BUFFER, mask, cb);
  254. }
  255. /**
  256. * Send a pong.
  257. *
  258. * @param {*} [data] The data to send
  259. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  260. * @param {Function} [cb] Callback which is executed when the pong is sent
  261. * @public
  262. */
  263. pong(data, mask, cb) {
  264. if (this.readyState === WebSocket.CONNECTING) {
  265. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  266. }
  267. if (typeof data === 'function') {
  268. cb = data;
  269. data = mask = undefined;
  270. } else if (typeof mask === 'function') {
  271. cb = mask;
  272. mask = undefined;
  273. }
  274. if (typeof data === 'number') data = data.toString();
  275. if (this.readyState !== WebSocket.OPEN) {
  276. sendAfterClose(this, data, cb);
  277. return;
  278. }
  279. if (mask === undefined) mask = !this._isServer;
  280. this._sender.pong(data || EMPTY_BUFFER, mask, cb);
  281. }
  282. /**
  283. * Send a data message.
  284. *
  285. * @param {*} data The message to send
  286. * @param {Object} [options] Options object
  287. * @param {Boolean} [options.compress] Specifies whether or not to compress
  288. * `data`
  289. * @param {Boolean} [options.binary] Specifies whether `data` is binary or
  290. * text
  291. * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
  292. * last one
  293. * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
  294. * @param {Function} [cb] Callback which is executed when data is written out
  295. * @public
  296. */
  297. send(data, options, cb) {
  298. if (this.readyState === WebSocket.CONNECTING) {
  299. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  300. }
  301. if (typeof options === 'function') {
  302. cb = options;
  303. options = {};
  304. }
  305. if (typeof data === 'number') data = data.toString();
  306. if (this.readyState !== WebSocket.OPEN) {
  307. sendAfterClose(this, data, cb);
  308. return;
  309. }
  310. const opts = {
  311. binary: typeof data !== 'string',
  312. mask: !this._isServer,
  313. compress: true,
  314. fin: true,
  315. ...options
  316. };
  317. if (!this._extensions[PerMessageDeflate.extensionName]) {
  318. opts.compress = false;
  319. }
  320. this._sender.send(data || EMPTY_BUFFER, opts, cb);
  321. }
  322. /**
  323. * Forcibly close the connection.
  324. *
  325. * @public
  326. */
  327. terminate() {
  328. if (this.readyState === WebSocket.CLOSED) return;
  329. if (this.readyState === WebSocket.CONNECTING) {
  330. const msg = 'WebSocket was closed before the connection was established';
  331. return abortHandshake(this, this._req, msg);
  332. }
  333. if (this._socket) {
  334. this._readyState = WebSocket.CLOSING;
  335. this._socket.destroy();
  336. }
  337. }
  338. }
  339. readyStates.forEach((readyState, i) => {
  340. const descriptor = { enumerable: true, value: i };
  341. Object.defineProperty(WebSocket.prototype, readyState, descriptor);
  342. Object.defineProperty(WebSocket, readyState, descriptor);
  343. });
  344. [
  345. 'binaryType',
  346. 'bufferedAmount',
  347. 'extensions',
  348. 'protocol',
  349. 'readyState',
  350. 'url'
  351. ].forEach((property) => {
  352. Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
  353. });
  354. //
  355. // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
  356. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
  357. //
  358. ['open', 'error', 'close', 'message'].forEach((method) => {
  359. Object.defineProperty(WebSocket.prototype, `on${method}`, {
  360. configurable: true,
  361. enumerable: true,
  362. /**
  363. * Return the listener of the event.
  364. *
  365. * @return {(Function|undefined)} The event listener or `undefined`
  366. * @public
  367. */
  368. get() {
  369. const listeners = this.listeners(method);
  370. for (let i = 0; i < listeners.length; i++) {
  371. if (listeners[i]._listener) return listeners[i]._listener;
  372. }
  373. return undefined;
  374. },
  375. /**
  376. * Add a listener for the event.
  377. *
  378. * @param {Function} listener The listener to add
  379. * @public
  380. */
  381. set(listener) {
  382. const listeners = this.listeners(method);
  383. for (let i = 0; i < listeners.length; i++) {
  384. //
  385. // Remove only the listeners added via `addEventListener`.
  386. //
  387. if (listeners[i]._listener) this.removeListener(method, listeners[i]);
  388. }
  389. this.addEventListener(method, listener);
  390. }
  391. });
  392. });
  393. WebSocket.prototype.addEventListener = addEventListener;
  394. WebSocket.prototype.removeEventListener = removeEventListener;
  395. module.exports = WebSocket;
  396. /**
  397. * Initialize a WebSocket client.
  398. *
  399. * @param {WebSocket} websocket The client to initialize
  400. * @param {(String|url.URL)} address The URL to which to connect
  401. * @param {String} [protocols] The subprotocols
  402. * @param {Object} [options] Connection options
  403. * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
  404. * permessage-deflate
  405. * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
  406. * handshake request
  407. * @param {Number} [options.protocolVersion=13] Value of the
  408. * `Sec-WebSocket-Version` header
  409. * @param {String} [options.origin] Value of the `Origin` or
  410. * `Sec-WebSocket-Origin` header
  411. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  412. * size
  413. * @param {Boolean} [options.followRedirects=false] Whether or not to follow
  414. * redirects
  415. * @param {Number} [options.maxRedirects=10] The maximum number of redirects
  416. * allowed
  417. * @private
  418. */
  419. function initAsClient(websocket, address, protocols, options) {
  420. const opts = {
  421. protocolVersion: protocolVersions[1],
  422. maxPayload: 100 * 1024 * 1024,
  423. perMessageDeflate: true,
  424. followRedirects: false,
  425. maxRedirects: 10,
  426. ...options,
  427. createConnection: undefined,
  428. socketPath: undefined,
  429. hostname: undefined,
  430. protocol: undefined,
  431. timeout: undefined,
  432. method: undefined,
  433. host: undefined,
  434. path: undefined,
  435. port: undefined
  436. };
  437. if (!protocolVersions.includes(opts.protocolVersion)) {
  438. throw new RangeError(
  439. `Unsupported protocol version: ${opts.protocolVersion} ` +
  440. `(supported versions: ${protocolVersions.join(', ')})`
  441. );
  442. }
  443. let parsedUrl;
  444. if (address instanceof URL) {
  445. parsedUrl = address;
  446. websocket._url = address.href;
  447. } else {
  448. parsedUrl = new URL(address);
  449. websocket._url = address;
  450. }
  451. const isUnixSocket = parsedUrl.protocol === 'ws+unix:';
  452. if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {
  453. throw new Error(`Invalid URL: ${websocket.url}`);
  454. }
  455. const isSecure =
  456. parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';
  457. const defaultPort = isSecure ? 443 : 80;
  458. const key = randomBytes(16).toString('base64');
  459. const get = isSecure ? https.get : http.get;
  460. let perMessageDeflate;
  461. opts.createConnection = isSecure ? tlsConnect : netConnect;
  462. opts.defaultPort = opts.defaultPort || defaultPort;
  463. opts.port = parsedUrl.port || defaultPort;
  464. opts.host = parsedUrl.hostname.startsWith('[')
  465. ? parsedUrl.hostname.slice(1, -1)
  466. : parsedUrl.hostname;
  467. opts.headers = {
  468. 'Sec-WebSocket-Version': opts.protocolVersion,
  469. 'Sec-WebSocket-Key': key,
  470. Connection: 'Upgrade',
  471. Upgrade: 'websocket',
  472. ...opts.headers
  473. };
  474. opts.path = parsedUrl.pathname + parsedUrl.search;
  475. opts.timeout = opts.handshakeTimeout;
  476. if (opts.perMessageDeflate) {
  477. perMessageDeflate = new PerMessageDeflate(
  478. opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
  479. false,
  480. opts.maxPayload
  481. );
  482. opts.headers['Sec-WebSocket-Extensions'] = format({
  483. [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
  484. });
  485. }
  486. if (protocols) {
  487. opts.headers['Sec-WebSocket-Protocol'] = protocols;
  488. }
  489. if (opts.origin) {
  490. if (opts.protocolVersion < 13) {
  491. opts.headers['Sec-WebSocket-Origin'] = opts.origin;
  492. } else {
  493. opts.headers.Origin = opts.origin;
  494. }
  495. }
  496. if (parsedUrl.username || parsedUrl.password) {
  497. opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
  498. }
  499. if (isUnixSocket) {
  500. const parts = opts.path.split(':');
  501. opts.socketPath = parts[0];
  502. opts.path = parts[1];
  503. }
  504. let req = (websocket._req = get(opts));
  505. if (opts.timeout) {
  506. req.on('timeout', () => {
  507. abortHandshake(websocket, req, 'Opening handshake has timed out');
  508. });
  509. }
  510. req.on('error', (err) => {
  511. if (req === null || req.aborted) return;
  512. req = websocket._req = null;
  513. websocket._readyState = WebSocket.CLOSING;
  514. websocket.emit('error', err);
  515. websocket.emitClose();
  516. });
  517. req.on('response', (res) => {
  518. const location = res.headers.location;
  519. const statusCode = res.statusCode;
  520. if (
  521. location &&
  522. opts.followRedirects &&
  523. statusCode >= 300 &&
  524. statusCode < 400
  525. ) {
  526. if (++websocket._redirects > opts.maxRedirects) {
  527. abortHandshake(websocket, req, 'Maximum redirects exceeded');
  528. return;
  529. }
  530. req.abort();
  531. const addr = new URL(location, address);
  532. initAsClient(websocket, addr, protocols, options);
  533. } else if (!websocket.emit('unexpected-response', req, res)) {
  534. abortHandshake(
  535. websocket,
  536. req,
  537. `Unexpected server response: ${res.statusCode}`
  538. );
  539. }
  540. });
  541. req.on('upgrade', (res, socket, head) => {
  542. websocket.emit('upgrade', res);
  543. //
  544. // The user may have closed the connection from a listener of the `upgrade`
  545. // event.
  546. //
  547. if (websocket.readyState !== WebSocket.CONNECTING) return;
  548. req = websocket._req = null;
  549. const digest = createHash('sha1')
  550. .update(key + GUID)
  551. .digest('base64');
  552. if (res.headers['sec-websocket-accept'] !== digest) {
  553. abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
  554. return;
  555. }
  556. const serverProt = res.headers['sec-websocket-protocol'];
  557. const protList = (protocols || '').split(/, */);
  558. let protError;
  559. if (!protocols && serverProt) {
  560. protError = 'Server sent a subprotocol but none was requested';
  561. } else if (protocols && !serverProt) {
  562. protError = 'Server sent no subprotocol';
  563. } else if (serverProt && !protList.includes(serverProt)) {
  564. protError = 'Server sent an invalid subprotocol';
  565. }
  566. if (protError) {
  567. abortHandshake(websocket, socket, protError);
  568. return;
  569. }
  570. if (serverProt) websocket._protocol = serverProt;
  571. const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
  572. if (secWebSocketExtensions !== undefined) {
  573. if (!perMessageDeflate) {
  574. const message =
  575. 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
  576. 'was requested';
  577. abortHandshake(websocket, socket, message);
  578. return;
  579. }
  580. let extensions;
  581. try {
  582. extensions = parse(secWebSocketExtensions);
  583. } catch (err) {
  584. const message = 'Invalid Sec-WebSocket-Extensions header';
  585. abortHandshake(websocket, socket, message);
  586. return;
  587. }
  588. const extensionNames = Object.keys(extensions);
  589. if (extensionNames.length) {
  590. if (
  591. extensionNames.length !== 1 ||
  592. extensionNames[0] !== PerMessageDeflate.extensionName
  593. ) {
  594. const message =
  595. 'Server indicated an extension that was not requested';
  596. abortHandshake(websocket, socket, message);
  597. return;
  598. }
  599. try {
  600. perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
  601. } catch (err) {
  602. const message = 'Invalid Sec-WebSocket-Extensions header';
  603. abortHandshake(websocket, socket, message);
  604. return;
  605. }
  606. websocket._extensions[PerMessageDeflate.extensionName] =
  607. perMessageDeflate;
  608. }
  609. }
  610. websocket.setSocket(socket, head, opts.maxPayload);
  611. });
  612. }
  613. /**
  614. * Create a `net.Socket` and initiate a connection.
  615. *
  616. * @param {Object} options Connection options
  617. * @return {net.Socket} The newly created socket used to start the connection
  618. * @private
  619. */
  620. function netConnect(options) {
  621. options.path = options.socketPath;
  622. return net.connect(options);
  623. }
  624. /**
  625. * Create a `tls.TLSSocket` and initiate a connection.
  626. *
  627. * @param {Object} options Connection options
  628. * @return {tls.TLSSocket} The newly created socket used to start the connection
  629. * @private
  630. */
  631. function tlsConnect(options) {
  632. options.path = undefined;
  633. if (!options.servername && options.servername !== '') {
  634. options.servername = net.isIP(options.host) ? '' : options.host;
  635. }
  636. return tls.connect(options);
  637. }
  638. /**
  639. * Abort the handshake and emit an error.
  640. *
  641. * @param {WebSocket} websocket The WebSocket instance
  642. * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the
  643. * socket to destroy
  644. * @param {String} message The error message
  645. * @private
  646. */
  647. function abortHandshake(websocket, stream, message) {
  648. websocket._readyState = WebSocket.CLOSING;
  649. const err = new Error(message);
  650. Error.captureStackTrace(err, abortHandshake);
  651. if (stream.setHeader) {
  652. stream.abort();
  653. if (stream.socket && !stream.socket.destroyed) {
  654. //
  655. // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
  656. // called after the request completed. See
  657. // https://github.com/websockets/ws/issues/1869.
  658. //
  659. stream.socket.destroy();
  660. }
  661. stream.once('abort', websocket.emitClose.bind(websocket));
  662. websocket.emit('error', err);
  663. } else {
  664. stream.destroy(err);
  665. stream.once('error', websocket.emit.bind(websocket, 'error'));
  666. stream.once('close', websocket.emitClose.bind(websocket));
  667. }
  668. }
  669. /**
  670. * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
  671. * when the `readyState` attribute is `CLOSING` or `CLOSED`.
  672. *
  673. * @param {WebSocket} websocket The WebSocket instance
  674. * @param {*} [data] The data to send
  675. * @param {Function} [cb] Callback
  676. * @private
  677. */
  678. function sendAfterClose(websocket, data, cb) {
  679. if (data) {
  680. const length = toBuffer(data).length;
  681. //
  682. // The `_bufferedAmount` property is used only when the peer is a client and
  683. // the opening handshake fails. Under these circumstances, in fact, the
  684. // `setSocket()` method is not called, so the `_socket` and `_sender`
  685. // properties are set to `null`.
  686. //
  687. if (websocket._socket) websocket._sender._bufferedBytes += length;
  688. else websocket._bufferedAmount += length;
  689. }
  690. if (cb) {
  691. const err = new Error(
  692. `WebSocket is not open: readyState ${websocket.readyState} ` +
  693. `(${readyStates[websocket.readyState]})`
  694. );
  695. cb(err);
  696. }
  697. }
  698. /**
  699. * The listener of the `Receiver` `'conclude'` event.
  700. *
  701. * @param {Number} code The status code
  702. * @param {String} reason The reason for closing
  703. * @private
  704. */
  705. function receiverOnConclude(code, reason) {
  706. const websocket = this[kWebSocket];
  707. websocket._socket.removeListener('data', socketOnData);
  708. websocket._socket.resume();
  709. websocket._closeFrameReceived = true;
  710. websocket._closeMessage = reason;
  711. websocket._closeCode = code;
  712. if (code === 1005) websocket.close();
  713. else websocket.close(code, reason);
  714. }
  715. /**
  716. * The listener of the `Receiver` `'drain'` event.
  717. *
  718. * @private
  719. */
  720. function receiverOnDrain() {
  721. this[kWebSocket]._socket.resume();
  722. }
  723. /**
  724. * The listener of the `Receiver` `'error'` event.
  725. *
  726. * @param {(RangeError|Error)} err The emitted error
  727. * @private
  728. */
  729. function receiverOnError(err) {
  730. const websocket = this[kWebSocket];
  731. websocket._socket.removeListener('data', socketOnData);
  732. websocket._socket.resume();
  733. websocket.close(err[kStatusCode]);
  734. websocket.emit('error', err);
  735. }
  736. /**
  737. * The listener of the `Receiver` `'finish'` event.
  738. *
  739. * @private
  740. */
  741. function receiverOnFinish() {
  742. this[kWebSocket].emitClose();
  743. }
  744. /**
  745. * The listener of the `Receiver` `'message'` event.
  746. *
  747. * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message
  748. * @private
  749. */
  750. function receiverOnMessage(data) {
  751. this[kWebSocket].emit('message', data);
  752. }
  753. /**
  754. * The listener of the `Receiver` `'ping'` event.
  755. *
  756. * @param {Buffer} data The data included in the ping frame
  757. * @private
  758. */
  759. function receiverOnPing(data) {
  760. const websocket = this[kWebSocket];
  761. websocket.pong(data, !websocket._isServer, NOOP);
  762. websocket.emit('ping', data);
  763. }
  764. /**
  765. * The listener of the `Receiver` `'pong'` event.
  766. *
  767. * @param {Buffer} data The data included in the pong frame
  768. * @private
  769. */
  770. function receiverOnPong(data) {
  771. this[kWebSocket].emit('pong', data);
  772. }
  773. /**
  774. * The listener of the `net.Socket` `'close'` event.
  775. *
  776. * @private
  777. */
  778. function socketOnClose() {
  779. const websocket = this[kWebSocket];
  780. this.removeListener('close', socketOnClose);
  781. this.removeListener('end', socketOnEnd);
  782. websocket._readyState = WebSocket.CLOSING;
  783. //
  784. // The close frame might not have been received or the `'end'` event emitted,
  785. // for example, if the socket was destroyed due to an error. Ensure that the
  786. // `receiver` stream is closed after writing any remaining buffered data to
  787. // it. If the readable side of the socket is in flowing mode then there is no
  788. // buffered data as everything has been already written and `readable.read()`
  789. // will return `null`. If instead, the socket is paused, any possible buffered
  790. // data will be read as a single chunk and emitted synchronously in a single
  791. // `'data'` event.
  792. //
  793. websocket._socket.read();
  794. websocket._receiver.end();
  795. this.removeListener('data', socketOnData);
  796. this[kWebSocket] = undefined;
  797. clearTimeout(websocket._closeTimer);
  798. if (
  799. websocket._receiver._writableState.finished ||
  800. websocket._receiver._writableState.errorEmitted
  801. ) {
  802. websocket.emitClose();
  803. } else {
  804. websocket._receiver.on('error', receiverOnFinish);
  805. websocket._receiver.on('finish', receiverOnFinish);
  806. }
  807. }
  808. /**
  809. * The listener of the `net.Socket` `'data'` event.
  810. *
  811. * @param {Buffer} chunk A chunk of data
  812. * @private
  813. */
  814. function socketOnData(chunk) {
  815. if (!this[kWebSocket]._receiver.write(chunk)) {
  816. this.pause();
  817. }
  818. }
  819. /**
  820. * The listener of the `net.Socket` `'end'` event.
  821. *
  822. * @private
  823. */
  824. function socketOnEnd() {
  825. const websocket = this[kWebSocket];
  826. websocket._readyState = WebSocket.CLOSING;
  827. websocket._receiver.end();
  828. this.end();
  829. }
  830. /**
  831. * The listener of the `net.Socket` `'error'` event.
  832. *
  833. * @private
  834. */
  835. function socketOnError() {
  836. const websocket = this[kWebSocket];
  837. this.removeListener('error', socketOnError);
  838. this.on('error', NOOP);
  839. if (websocket) {
  840. websocket._readyState = WebSocket.CLOSING;
  841. this.destroy();
  842. }
  843. }