websocket.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. 'use strict';
  2. const EventEmitter = require('events');
  3. const crypto = require('crypto');
  4. const https = require('https');
  5. const http = require('http');
  6. const url = require('url');
  7. const PerMessageDeflate = require('./permessage-deflate');
  8. const EventTarget = require('./event-target');
  9. const extension = require('./extension');
  10. const constants = require('./constants');
  11. const Receiver = require('./receiver');
  12. const Sender = require('./sender');
  13. const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
  14. const protocolVersions = [8, 13];
  15. const closeTimeout = 30 * 1000; // Allow 30 seconds to terminate the connection cleanly.
  16. /**
  17. * Class representing a WebSocket.
  18. *
  19. * @extends EventEmitter
  20. */
  21. class WebSocket extends EventEmitter {
  22. /**
  23. * Create a new `WebSocket`.
  24. *
  25. * @param {String} address The URL to which to connect
  26. * @param {(String|String[])} protocols The subprotocols
  27. * @param {Object} options Connection options
  28. */
  29. constructor (address, protocols, options) {
  30. super();
  31. this.readyState = WebSocket.CONNECTING;
  32. this.protocol = '';
  33. this._binaryType = constants.BINARY_TYPES[0];
  34. this._finalize = this.finalize.bind(this);
  35. this._closeFrameReceived = false;
  36. this._closeFrameSent = false;
  37. this._closeMessage = '';
  38. this._closeTimer = null;
  39. this._finalized = false;
  40. this._closeCode = 1006;
  41. this._extensions = {};
  42. this._isServer = true;
  43. this._receiver = null;
  44. this._sender = null;
  45. this._socket = null;
  46. this._error = null;
  47. if (address !== null) {
  48. if (!protocols) {
  49. protocols = [];
  50. } else if (typeof protocols === 'string') {
  51. protocols = [protocols];
  52. } else if (!Array.isArray(protocols)) {
  53. options = protocols;
  54. protocols = [];
  55. }
  56. initAsClient.call(this, address, protocols, options);
  57. }
  58. }
  59. get CONNECTING () { return WebSocket.CONNECTING; }
  60. get CLOSING () { return WebSocket.CLOSING; }
  61. get CLOSED () { return WebSocket.CLOSED; }
  62. get OPEN () { return WebSocket.OPEN; }
  63. /**
  64. * This deviates from the WHATWG interface since ws doesn't support the required
  65. * default "blob" type (instead we define a custom "nodebuffer" type).
  66. *
  67. * @type {String}
  68. */
  69. get binaryType () {
  70. return this._binaryType;
  71. }
  72. set binaryType (type) {
  73. if (constants.BINARY_TYPES.indexOf(type) < 0) return;
  74. this._binaryType = type;
  75. //
  76. // Allow to change `binaryType` on the fly.
  77. //
  78. if (this._receiver) this._receiver._binaryType = type;
  79. }
  80. /**
  81. * @type {Number}
  82. */
  83. get bufferedAmount () {
  84. if (!this._socket) return 0;
  85. //
  86. // `socket.bufferSize` is `undefined` if the socket is closed.
  87. //
  88. return (this._socket.bufferSize || 0) + this._sender._bufferedBytes;
  89. }
  90. /**
  91. * @type {String}
  92. */
  93. get extensions () {
  94. return Object.keys(this._extensions).join();
  95. }
  96. /**
  97. * Set up the socket and the internal resources.
  98. *
  99. * @param {net.Socket} socket The network socket between the server and client
  100. * @param {Buffer} head The first packet of the upgraded stream
  101. * @param {Number} maxPayload The maximum allowed message size
  102. * @private
  103. */
  104. setSocket (socket, head, maxPayload) {
  105. socket.setTimeout(0);
  106. socket.setNoDelay();
  107. socket.on('close', this._finalize);
  108. socket.on('error', this._finalize);
  109. socket.on('end', this._finalize);
  110. this._receiver = new Receiver(this._extensions, maxPayload, this.binaryType);
  111. this._sender = new Sender(socket, this._extensions);
  112. this._socket = socket;
  113. if (head.length > 0) socket.unshift(head);
  114. socket.on('data', this._receiver.add);
  115. this._receiver.onmessage = (data) => this.emit('message', data);
  116. this._receiver.onping = (data) => {
  117. this.pong(data, !this._isServer, constants.NOOP);
  118. this.emit('ping', data);
  119. };
  120. this._receiver.onpong = (data) => this.emit('pong', data);
  121. this._receiver.onclose = (code, reason) => {
  122. //
  123. // Discard any additional data that is received on the socket.
  124. //
  125. this._socket.removeListener('data', this._receiver.add);
  126. this._closeFrameReceived = true;
  127. this._closeMessage = reason;
  128. this._closeCode = code;
  129. if (code === 1005) this.close();
  130. else this.close(code, reason);
  131. };
  132. this._receiver.onerror = (error, code) => {
  133. if (this._error) return;
  134. this._closeCode = code;
  135. if (!this._finalized) this.finalize(error);
  136. else this.emit('error', error);
  137. };
  138. this.readyState = WebSocket.OPEN;
  139. this.emit('open');
  140. }
  141. /**
  142. * Clean up internal resources and emit the `'close'` event.
  143. *
  144. * @param {(Boolean|Error)} error Indicates whether or not an error occurred
  145. * @private
  146. */
  147. finalize (error) {
  148. if (this._finalized) return;
  149. this.readyState = WebSocket.CLOSING;
  150. this._finalized = true;
  151. if (!this._socket) {
  152. //
  153. // `error` is always an `Error` instance in this case.
  154. //
  155. this.emit('error', error);
  156. this.readyState = WebSocket.CLOSED;
  157. this.emit('close', this._closeCode, this._closeMessage);
  158. return;
  159. }
  160. clearTimeout(this._closeTimer);
  161. this._socket.removeListener('data', this._receiver.add);
  162. this._socket.removeListener('close', this._finalize);
  163. this._socket.removeListener('error', this._finalize);
  164. this._socket.removeListener('end', this._finalize);
  165. this._socket.on('error', constants.NOOP);
  166. if (error) {
  167. if (error !== true) this._error = error;
  168. this._socket.destroy();
  169. } else {
  170. this._socket.end();
  171. }
  172. this._receiver.cleanup(() => {
  173. const err = this._error;
  174. if (err) {
  175. this._error = null;
  176. this.emit('error', err);
  177. }
  178. this.readyState = WebSocket.CLOSED;
  179. if (this._extensions[PerMessageDeflate.extensionName]) {
  180. this._extensions[PerMessageDeflate.extensionName].cleanup();
  181. }
  182. this.emit('close', this._closeCode, this._closeMessage);
  183. });
  184. }
  185. /**
  186. * Start a closing handshake.
  187. *
  188. * +----------+ +-----------+ +----------+
  189. * + - - -|ws.close()|---->|close frame|-->|ws.close()|- - - -
  190. * +----------+ +-----------+ +----------+ |
  191. * | +----------+ +-----------+ |
  192. * |ws.close()|<----|close frame|<--------+ |
  193. * +----------+ +-----------+ |
  194. * CLOSING | +---+ | CLOSING
  195. * | +---|fin|<------------+
  196. * | | | +---+ |
  197. * | | +---+ +-------------+
  198. * | +----------+-->|fin|----->|ws.finalize()| - - +
  199. * | +---+ +-------------+
  200. * | +-------------+ |
  201. * - - -|ws.finalize()|<--+
  202. * +-------------+
  203. *
  204. * @param {Number} code Status code explaining why the connection is closing
  205. * @param {String} data A string explaining why the connection is closing
  206. * @public
  207. */
  208. close (code, data) {
  209. if (this.readyState === WebSocket.CLOSED) return;
  210. if (this.readyState === WebSocket.CONNECTING) {
  211. this._req.abort();
  212. this.finalize(
  213. new Error('WebSocket was closed before the connection was established')
  214. );
  215. return;
  216. }
  217. if (this.readyState === WebSocket.CLOSING) {
  218. if (this._closeFrameSent && this._closeFrameReceived) this._socket.end();
  219. return;
  220. }
  221. this.readyState = WebSocket.CLOSING;
  222. this._sender.close(code, data, !this._isServer, (err) => {
  223. //
  224. // This error is handled by the `'error'` listener on the socket. We only
  225. // want to know if the close frame has been sent here.
  226. //
  227. if (err) return;
  228. this._closeFrameSent = true;
  229. if (!this._finalized) {
  230. if (this._closeFrameReceived) this._socket.end();
  231. //
  232. // Ensure that the connection is cleaned up even when the closing
  233. // handshake fails.
  234. //
  235. this._closeTimer = setTimeout(this._finalize, closeTimeout, true);
  236. }
  237. });
  238. }
  239. /**
  240. * Send a ping.
  241. *
  242. * @param {*} data The data to send
  243. * @param {Boolean} mask Indicates whether or not to mask `data`
  244. * @param {Function} cb Callback which is executed when the ping is sent
  245. * @public
  246. */
  247. ping (data, mask, cb) {
  248. if (typeof data === 'function') {
  249. cb = data;
  250. data = mask = undefined;
  251. } else if (typeof mask === 'function') {
  252. cb = mask;
  253. mask = undefined;
  254. }
  255. if (this.readyState !== WebSocket.OPEN) {
  256. const err = new Error(
  257. `WebSocket is not open: readyState ${this.readyState} ` +
  258. `(${readyStates[this.readyState]})`
  259. );
  260. if (cb) return cb(err);
  261. throw err;
  262. }
  263. if (typeof data === 'number') data = data.toString();
  264. if (mask === undefined) mask = !this._isServer;
  265. this._sender.ping(data || constants.EMPTY_BUFFER, mask, cb);
  266. }
  267. /**
  268. * Send a pong.
  269. *
  270. * @param {*} data The data to send
  271. * @param {Boolean} mask Indicates whether or not to mask `data`
  272. * @param {Function} cb Callback which is executed when the pong is sent
  273. * @public
  274. */
  275. pong (data, mask, cb) {
  276. if (typeof data === 'function') {
  277. cb = data;
  278. data = mask = undefined;
  279. } else if (typeof mask === 'function') {
  280. cb = mask;
  281. mask = undefined;
  282. }
  283. if (this.readyState !== WebSocket.OPEN) {
  284. const err = new Error(
  285. `WebSocket is not open: readyState ${this.readyState} ` +
  286. `(${readyStates[this.readyState]})`
  287. );
  288. if (cb) return cb(err);
  289. throw err;
  290. }
  291. if (typeof data === 'number') data = data.toString();
  292. if (mask === undefined) mask = !this._isServer;
  293. this._sender.pong(data || constants.EMPTY_BUFFER, mask, cb);
  294. }
  295. /**
  296. * Send a data message.
  297. *
  298. * @param {*} data The message to send
  299. * @param {Object} options Options object
  300. * @param {Boolean} options.compress Specifies whether or not to compress `data`
  301. * @param {Boolean} options.binary Specifies whether `data` is binary or text
  302. * @param {Boolean} options.fin Specifies whether the fragment is the last one
  303. * @param {Boolean} options.mask Specifies whether or not to mask `data`
  304. * @param {Function} cb Callback which is executed when data is written out
  305. * @public
  306. */
  307. send (data, options, cb) {
  308. if (typeof options === 'function') {
  309. cb = options;
  310. options = {};
  311. }
  312. if (this.readyState !== WebSocket.OPEN) {
  313. const err = new Error(
  314. `WebSocket is not open: readyState ${this.readyState} ` +
  315. `(${readyStates[this.readyState]})`
  316. );
  317. if (cb) return cb(err);
  318. throw err;
  319. }
  320. if (typeof data === 'number') data = data.toString();
  321. const opts = Object.assign({
  322. binary: typeof data !== 'string',
  323. mask: !this._isServer,
  324. compress: true,
  325. fin: true
  326. }, options);
  327. if (!this._extensions[PerMessageDeflate.extensionName]) {
  328. opts.compress = false;
  329. }
  330. this._sender.send(data || constants.EMPTY_BUFFER, opts, cb);
  331. }
  332. /**
  333. * Forcibly close the connection.
  334. *
  335. * @public
  336. */
  337. terminate () {
  338. if (this.readyState === WebSocket.CLOSED) return;
  339. if (this.readyState === WebSocket.CONNECTING) {
  340. this._req.abort();
  341. this.finalize(
  342. new Error('WebSocket was closed before the connection was established')
  343. );
  344. return;
  345. }
  346. this.finalize(true);
  347. }
  348. }
  349. readyStates.forEach((readyState, i) => {
  350. WebSocket[readyStates[i]] = i;
  351. });
  352. //
  353. // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
  354. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
  355. //
  356. ['open', 'error', 'close', 'message'].forEach((method) => {
  357. Object.defineProperty(WebSocket.prototype, `on${method}`, {
  358. /**
  359. * Return the listener of the event.
  360. *
  361. * @return {(Function|undefined)} The event listener or `undefined`
  362. * @public
  363. */
  364. get () {
  365. const listeners = this.listeners(method);
  366. for (var i = 0; i < listeners.length; i++) {
  367. if (listeners[i]._listener) return listeners[i]._listener;
  368. }
  369. },
  370. /**
  371. * Add a listener for the event.
  372. *
  373. * @param {Function} listener The listener to add
  374. * @public
  375. */
  376. set (listener) {
  377. const listeners = this.listeners(method);
  378. for (var i = 0; i < listeners.length; i++) {
  379. //
  380. // Remove only the listeners added via `addEventListener`.
  381. //
  382. if (listeners[i]._listener) this.removeListener(method, listeners[i]);
  383. }
  384. this.addEventListener(method, listener);
  385. }
  386. });
  387. });
  388. WebSocket.prototype.addEventListener = EventTarget.addEventListener;
  389. WebSocket.prototype.removeEventListener = EventTarget.removeEventListener;
  390. module.exports = WebSocket;
  391. /**
  392. * Initialize a WebSocket client.
  393. *
  394. * @param {String} address The URL to which to connect
  395. * @param {String[]} protocols The list of subprotocols
  396. * @param {Object} options Connection options
  397. * @param {String} options.protocol Value of the `Sec-WebSocket-Protocol` header
  398. * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate
  399. * @param {Number} options.handshakeTimeout Timeout in milliseconds for the handshake request
  400. * @param {String} options.localAddress Local interface to bind for network connections
  401. * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version` header
  402. * @param {Object} options.headers An object containing request headers
  403. * @param {String} options.origin Value of the `Origin` or `Sec-WebSocket-Origin` header
  404. * @param {http.Agent} options.agent Use the specified Agent
  405. * @param {String} options.host Value of the `Host` header
  406. * @param {Number} options.family IP address family to use during hostname lookup (4 or 6).
  407. * @param {Function} options.checkServerIdentity A function to validate the server hostname
  408. * @param {Boolean} options.rejectUnauthorized Verify or not the server certificate
  409. * @param {String} options.passphrase The passphrase for the private key or pfx
  410. * @param {String} options.ciphers The ciphers to use or exclude
  411. * @param {String} options.ecdhCurve The curves for ECDH key agreement to use or exclude
  412. * @param {(String|String[]|Buffer|Buffer[])} options.cert The certificate key
  413. * @param {(String|String[]|Buffer|Buffer[])} options.key The private key
  414. * @param {(String|Buffer)} options.pfx The private key, certificate, and CA certs
  415. * @param {(String|String[]|Buffer|Buffer[])} options.ca Trusted certificates
  416. * @private
  417. */
  418. function initAsClient (address, protocols, options) {
  419. options = Object.assign({
  420. protocolVersion: protocolVersions[1],
  421. protocol: protocols.join(','),
  422. perMessageDeflate: true,
  423. handshakeTimeout: null,
  424. localAddress: null,
  425. headers: null,
  426. family: null,
  427. origin: null,
  428. agent: null,
  429. host: null,
  430. //
  431. // SSL options.
  432. //
  433. checkServerIdentity: null,
  434. rejectUnauthorized: null,
  435. passphrase: null,
  436. ciphers: null,
  437. ecdhCurve: null,
  438. cert: null,
  439. key: null,
  440. pfx: null,
  441. ca: null
  442. }, options);
  443. if (protocolVersions.indexOf(options.protocolVersion) === -1) {
  444. throw new RangeError(
  445. `Unsupported protocol version: ${options.protocolVersion} ` +
  446. `(supported versions: ${protocolVersions.join(', ')})`
  447. );
  448. }
  449. this._isServer = false;
  450. this.url = address;
  451. const serverUrl = url.parse(address);
  452. const isUnixSocket = serverUrl.protocol === 'ws+unix:';
  453. if (!serverUrl.host && (!isUnixSocket || !serverUrl.path)) {
  454. throw new Error(`Invalid URL: ${address}`);
  455. }
  456. const isSecure = serverUrl.protocol === 'wss:' || serverUrl.protocol === 'https:';
  457. const key = crypto.randomBytes(16).toString('base64');
  458. const httpObj = isSecure ? https : http;
  459. var perMessageDeflate;
  460. const requestOptions = {
  461. port: serverUrl.port || (isSecure ? 443 : 80),
  462. host: serverUrl.hostname,
  463. path: '/',
  464. headers: {
  465. 'Sec-WebSocket-Version': options.protocolVersion,
  466. 'Sec-WebSocket-Key': key,
  467. 'Connection': 'Upgrade',
  468. 'Upgrade': 'websocket'
  469. }
  470. };
  471. if (options.headers) Object.assign(requestOptions.headers, options.headers);
  472. if (options.perMessageDeflate) {
  473. perMessageDeflate = new PerMessageDeflate(
  474. options.perMessageDeflate !== true ? options.perMessageDeflate : {},
  475. false
  476. );
  477. requestOptions.headers['Sec-WebSocket-Extensions'] = extension.format({
  478. [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
  479. });
  480. }
  481. if (options.protocol) {
  482. requestOptions.headers['Sec-WebSocket-Protocol'] = options.protocol;
  483. }
  484. if (options.origin) {
  485. if (options.protocolVersion < 13) {
  486. requestOptions.headers['Sec-WebSocket-Origin'] = options.origin;
  487. } else {
  488. requestOptions.headers.Origin = options.origin;
  489. }
  490. }
  491. if (options.host) requestOptions.headers.Host = options.host;
  492. if (serverUrl.auth) requestOptions.auth = serverUrl.auth;
  493. if (options.localAddress) requestOptions.localAddress = options.localAddress;
  494. if (options.family) requestOptions.family = options.family;
  495. if (isUnixSocket) {
  496. const parts = serverUrl.path.split(':');
  497. requestOptions.socketPath = parts[0];
  498. requestOptions.path = parts[1];
  499. } else if (serverUrl.path) {
  500. //
  501. // Make sure that path starts with `/`.
  502. //
  503. if (serverUrl.path.charAt(0) !== '/') {
  504. requestOptions.path = `/${serverUrl.path}`;
  505. } else {
  506. requestOptions.path = serverUrl.path;
  507. }
  508. }
  509. var agent = options.agent;
  510. //
  511. // A custom agent is required for these options.
  512. //
  513. if (
  514. options.rejectUnauthorized != null ||
  515. options.checkServerIdentity ||
  516. options.passphrase ||
  517. options.ciphers ||
  518. options.ecdhCurve ||
  519. options.cert ||
  520. options.key ||
  521. options.pfx ||
  522. options.ca
  523. ) {
  524. if (options.passphrase) requestOptions.passphrase = options.passphrase;
  525. if (options.ciphers) requestOptions.ciphers = options.ciphers;
  526. if (options.ecdhCurve) requestOptions.ecdhCurve = options.ecdhCurve;
  527. if (options.cert) requestOptions.cert = options.cert;
  528. if (options.key) requestOptions.key = options.key;
  529. if (options.pfx) requestOptions.pfx = options.pfx;
  530. if (options.ca) requestOptions.ca = options.ca;
  531. if (options.checkServerIdentity) {
  532. requestOptions.checkServerIdentity = options.checkServerIdentity;
  533. }
  534. if (options.rejectUnauthorized != null) {
  535. requestOptions.rejectUnauthorized = options.rejectUnauthorized;
  536. }
  537. if (!agent) agent = new httpObj.Agent(requestOptions);
  538. }
  539. if (agent) requestOptions.agent = agent;
  540. this._req = httpObj.get(requestOptions);
  541. if (options.handshakeTimeout) {
  542. this._req.setTimeout(options.handshakeTimeout, () => {
  543. this._req.abort();
  544. this.finalize(new Error('Opening handshake has timed out'));
  545. });
  546. }
  547. this._req.on('error', (error) => {
  548. if (this._req.aborted) return;
  549. this._req = null;
  550. this.finalize(error);
  551. });
  552. this._req.on('response', (res) => {
  553. if (!this.emit('unexpected-response', this._req, res)) {
  554. this._req.abort();
  555. this.finalize(new Error(`Unexpected server response: ${res.statusCode}`));
  556. }
  557. });
  558. this._req.on('upgrade', (res, socket, head) => {
  559. this.emit('upgrade', res);
  560. //
  561. // The user may have closed the connection from a listener of the `upgrade`
  562. // event.
  563. //
  564. if (this.readyState !== WebSocket.CONNECTING) return;
  565. this._req = null;
  566. const digest = crypto.createHash('sha1')
  567. .update(key + constants.GUID, 'binary')
  568. .digest('base64');
  569. if (res.headers['sec-websocket-accept'] !== digest) {
  570. socket.destroy();
  571. return this.finalize(new Error('Invalid Sec-WebSocket-Accept header'));
  572. }
  573. const serverProt = res.headers['sec-websocket-protocol'];
  574. const protList = (options.protocol || '').split(/, */);
  575. var protError;
  576. if (!options.protocol && serverProt) {
  577. protError = 'Server sent a subprotocol but none was requested';
  578. } else if (options.protocol && !serverProt) {
  579. protError = 'Server sent no subprotocol';
  580. } else if (serverProt && protList.indexOf(serverProt) === -1) {
  581. protError = 'Server sent an invalid subprotocol';
  582. }
  583. if (protError) {
  584. socket.destroy();
  585. return this.finalize(new Error(protError));
  586. }
  587. if (serverProt) this.protocol = serverProt;
  588. if (perMessageDeflate) {
  589. try {
  590. const extensions = extension.parse(
  591. res.headers['sec-websocket-extensions']
  592. );
  593. if (extensions[PerMessageDeflate.extensionName]) {
  594. perMessageDeflate.accept(
  595. extensions[PerMessageDeflate.extensionName]
  596. );
  597. this._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  598. }
  599. } catch (err) {
  600. socket.destroy();
  601. this.finalize(new Error('Invalid Sec-WebSocket-Extensions header'));
  602. return;
  603. }
  604. }
  605. this.setSocket(socket, head, 0);
  606. });
  607. }