websocket-server.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */
  2. 'use strict';
  3. const EventEmitter = require('events');
  4. const http = require('http');
  5. const { Duplex } = require('stream');
  6. const { createHash } = require('crypto');
  7. const extension = require('./extension');
  8. const PerMessageDeflate = require('./permessage-deflate');
  9. const subprotocol = require('./subprotocol');
  10. const WebSocket = require('./websocket');
  11. const { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants');
  12. const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
  13. const RUNNING = 0;
  14. const CLOSING = 1;
  15. const CLOSED = 2;
  16. /**
  17. * Class representing a WebSocket server.
  18. *
  19. * @extends EventEmitter
  20. */
  21. class WebSocketServer extends EventEmitter {
  22. /**
  23. * Create a `WebSocketServer` instance.
  24. *
  25. * @param {Object} options Configuration options
  26. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
  27. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  28. * multiple times in the same tick
  29. * @param {Boolean} [options.autoPong=true] Specifies whether or not to
  30. * automatically send a pong in response to a ping
  31. * @param {Number} [options.backlog=511] The maximum length of the queue of
  32. * pending connections
  33. * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
  34. * track clients
  35. * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
  36. * wait for the closing handshake to finish after `websocket.close()` is
  37. * called
  38. * @param {Function} [options.handleProtocols] A hook to handle protocols
  39. * @param {String} [options.host] The hostname where to bind the server
  40. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  41. * size
  42. * @param {Boolean} [options.noServer=false] Enable no server mode
  43. * @param {String} [options.path] Accept only connections matching this path
  44. * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
  45. * permessage-deflate
  46. * @param {Number} [options.port] The port where to bind the server
  47. * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
  48. * server to use
  49. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  50. * not to skip UTF-8 validation for text and close messages
  51. * @param {Function} [options.verifyClient] A hook to reject connections
  52. * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
  53. * class to use. It must be the `WebSocket` class or class that extends it
  54. * @param {Function} [callback] A listener for the `listening` event
  55. */
  56. constructor(options, callback) {
  57. super();
  58. options = {
  59. allowSynchronousEvents: true,
  60. autoPong: true,
  61. maxPayload: 100 * 1024 * 1024,
  62. skipUTF8Validation: false,
  63. perMessageDeflate: false,
  64. handleProtocols: null,
  65. clientTracking: true,
  66. closeTimeout: CLOSE_TIMEOUT,
  67. verifyClient: null,
  68. noServer: false,
  69. backlog: null, // use default (511 as implemented in net.js)
  70. server: null,
  71. host: null,
  72. path: null,
  73. port: null,
  74. WebSocket,
  75. ...options
  76. };
  77. if (
  78. (options.port == null && !options.server && !options.noServer) ||
  79. (options.port != null && (options.server || options.noServer)) ||
  80. (options.server && options.noServer)
  81. ) {
  82. throw new TypeError(
  83. 'One and only one of the "port", "server", or "noServer" options ' +
  84. 'must be specified'
  85. );
  86. }
  87. if (options.port != null) {
  88. this._server = http.createServer((req, res) => {
  89. const body = http.STATUS_CODES[426];
  90. res.writeHead(426, {
  91. 'Content-Length': body.length,
  92. 'Content-Type': 'text/plain'
  93. });
  94. res.end(body);
  95. });
  96. this._server.listen(
  97. options.port,
  98. options.host,
  99. options.backlog,
  100. callback
  101. );
  102. } else if (options.server) {
  103. this._server = options.server;
  104. }
  105. if (this._server) {
  106. const emitConnection = this.emit.bind(this, 'connection');
  107. this._removeListeners = addListeners(this._server, {
  108. listening: this.emit.bind(this, 'listening'),
  109. error: this.emit.bind(this, 'error'),
  110. upgrade: (req, socket, head) => {
  111. this.handleUpgrade(req, socket, head, emitConnection);
  112. }
  113. });
  114. }
  115. if (options.perMessageDeflate === true) options.perMessageDeflate = {};
  116. if (options.clientTracking) {
  117. this.clients = new Set();
  118. this._shouldEmitClose = false;
  119. }
  120. this.options = options;
  121. this._state = RUNNING;
  122. }
  123. /**
  124. * Returns the bound address, the address family name, and port of the server
  125. * as reported by the operating system if listening on an IP socket.
  126. * If the server is listening on a pipe or UNIX domain socket, the name is
  127. * returned as a string.
  128. *
  129. * @return {(Object|String|null)} The address of the server
  130. * @public
  131. */
  132. address() {
  133. if (this.options.noServer) {
  134. throw new Error('The server is operating in "noServer" mode');
  135. }
  136. if (!this._server) return null;
  137. return this._server.address();
  138. }
  139. /**
  140. * Stop the server from accepting new connections and emit the `'close'` event
  141. * when all existing connections are closed.
  142. *
  143. * @param {Function} [cb] A one-time listener for the `'close'` event
  144. * @public
  145. */
  146. close(cb) {
  147. if (this._state === CLOSED) {
  148. if (cb) {
  149. this.once('close', () => {
  150. cb(new Error('The server is not running'));
  151. });
  152. }
  153. process.nextTick(emitClose, this);
  154. return;
  155. }
  156. if (cb) this.once('close', cb);
  157. if (this._state === CLOSING) return;
  158. this._state = CLOSING;
  159. if (this.options.noServer || this.options.server) {
  160. if (this._server) {
  161. this._removeListeners();
  162. this._removeListeners = this._server = null;
  163. }
  164. if (this.clients) {
  165. if (!this.clients.size) {
  166. process.nextTick(emitClose, this);
  167. } else {
  168. this._shouldEmitClose = true;
  169. }
  170. } else {
  171. process.nextTick(emitClose, this);
  172. }
  173. } else {
  174. const server = this._server;
  175. this._removeListeners();
  176. this._removeListeners = this._server = null;
  177. //
  178. // The HTTP/S server was created internally. Close it, and rely on its
  179. // `'close'` event.
  180. //
  181. server.close(() => {
  182. emitClose(this);
  183. });
  184. }
  185. }
  186. /**
  187. * See if a given request should be handled by this server instance.
  188. *
  189. * @param {http.IncomingMessage} req Request object to inspect
  190. * @return {Boolean} `true` if the request is valid, else `false`
  191. * @public
  192. */
  193. shouldHandle(req) {
  194. if (this.options.path) {
  195. const index = req.url.indexOf('?');
  196. const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
  197. if (pathname !== this.options.path) return false;
  198. }
  199. return true;
  200. }
  201. /**
  202. * Handle a HTTP Upgrade request.
  203. *
  204. * @param {http.IncomingMessage} req The request object
  205. * @param {Duplex} socket The network socket between the server and client
  206. * @param {Buffer} head The first packet of the upgraded stream
  207. * @param {Function} cb Callback
  208. * @public
  209. */
  210. handleUpgrade(req, socket, head, cb) {
  211. socket.on('error', socketOnError);
  212. const key = req.headers['sec-websocket-key'];
  213. const upgrade = req.headers.upgrade;
  214. const version = +req.headers['sec-websocket-version'];
  215. if (req.method !== 'GET') {
  216. const message = 'Invalid HTTP method';
  217. abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
  218. return;
  219. }
  220. if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
  221. const message = 'Invalid Upgrade header';
  222. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  223. return;
  224. }
  225. if (key === undefined || !keyRegex.test(key)) {
  226. const message = 'Missing or invalid Sec-WebSocket-Key header';
  227. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  228. return;
  229. }
  230. if (version !== 13 && version !== 8) {
  231. const message = 'Missing or invalid Sec-WebSocket-Version header';
  232. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
  233. 'Sec-WebSocket-Version': '13, 8'
  234. });
  235. return;
  236. }
  237. if (!this.shouldHandle(req)) {
  238. abortHandshake(socket, 400);
  239. return;
  240. }
  241. const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
  242. let protocols = new Set();
  243. if (secWebSocketProtocol !== undefined) {
  244. try {
  245. protocols = subprotocol.parse(secWebSocketProtocol);
  246. } catch (err) {
  247. const message = 'Invalid Sec-WebSocket-Protocol header';
  248. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  249. return;
  250. }
  251. }
  252. const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
  253. const extensions = {};
  254. if (
  255. this.options.perMessageDeflate &&
  256. secWebSocketExtensions !== undefined
  257. ) {
  258. const perMessageDeflate = new PerMessageDeflate(
  259. this.options.perMessageDeflate,
  260. true,
  261. this.options.maxPayload
  262. );
  263. try {
  264. const offers = extension.parse(secWebSocketExtensions);
  265. if (offers[PerMessageDeflate.extensionName]) {
  266. perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
  267. extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  268. }
  269. } catch (err) {
  270. const message =
  271. 'Invalid or unacceptable Sec-WebSocket-Extensions header';
  272. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  273. return;
  274. }
  275. }
  276. //
  277. // Optionally call external client verification handler.
  278. //
  279. if (this.options.verifyClient) {
  280. const info = {
  281. origin:
  282. req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
  283. secure: !!(req.socket.authorized || req.socket.encrypted),
  284. req
  285. };
  286. if (this.options.verifyClient.length === 2) {
  287. this.options.verifyClient(info, (verified, code, message, headers) => {
  288. if (!verified) {
  289. return abortHandshake(socket, code || 401, message, headers);
  290. }
  291. this.completeUpgrade(
  292. extensions,
  293. key,
  294. protocols,
  295. req,
  296. socket,
  297. head,
  298. cb
  299. );
  300. });
  301. return;
  302. }
  303. if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
  304. }
  305. this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
  306. }
  307. /**
  308. * Upgrade the connection to WebSocket.
  309. *
  310. * @param {Object} extensions The accepted extensions
  311. * @param {String} key The value of the `Sec-WebSocket-Key` header
  312. * @param {Set} protocols The subprotocols
  313. * @param {http.IncomingMessage} req The request object
  314. * @param {Duplex} socket The network socket between the server and client
  315. * @param {Buffer} head The first packet of the upgraded stream
  316. * @param {Function} cb Callback
  317. * @throws {Error} If called more than once with the same socket
  318. * @private
  319. */
  320. completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
  321. //
  322. // Destroy the socket if the client has already sent a FIN packet.
  323. //
  324. if (!socket.readable || !socket.writable) return socket.destroy();
  325. if (socket[kWebSocket]) {
  326. throw new Error(
  327. 'server.handleUpgrade() was called more than once with the same ' +
  328. 'socket, possibly due to a misconfiguration'
  329. );
  330. }
  331. if (this._state > RUNNING) return abortHandshake(socket, 503);
  332. const digest = createHash('sha1')
  333. .update(key + GUID)
  334. .digest('base64');
  335. const headers = [
  336. 'HTTP/1.1 101 Switching Protocols',
  337. 'Upgrade: websocket',
  338. 'Connection: Upgrade',
  339. `Sec-WebSocket-Accept: ${digest}`
  340. ];
  341. const ws = new this.options.WebSocket(null, undefined, this.options);
  342. if (protocols.size) {
  343. //
  344. // Optionally call external protocol selection handler.
  345. //
  346. const protocol = this.options.handleProtocols
  347. ? this.options.handleProtocols(protocols, req)
  348. : protocols.values().next().value;
  349. if (protocol) {
  350. headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
  351. ws._protocol = protocol;
  352. }
  353. }
  354. if (extensions[PerMessageDeflate.extensionName]) {
  355. const params = extensions[PerMessageDeflate.extensionName].params;
  356. const value = extension.format({
  357. [PerMessageDeflate.extensionName]: [params]
  358. });
  359. headers.push(`Sec-WebSocket-Extensions: ${value}`);
  360. ws._extensions = extensions;
  361. }
  362. //
  363. // Allow external modification/inspection of handshake headers.
  364. //
  365. this.emit('headers', headers, req);
  366. socket.write(headers.concat('\r\n').join('\r\n'));
  367. socket.removeListener('error', socketOnError);
  368. ws.setSocket(socket, head, {
  369. allowSynchronousEvents: this.options.allowSynchronousEvents,
  370. maxPayload: this.options.maxPayload,
  371. skipUTF8Validation: this.options.skipUTF8Validation
  372. });
  373. if (this.clients) {
  374. this.clients.add(ws);
  375. ws.on('close', () => {
  376. this.clients.delete(ws);
  377. if (this._shouldEmitClose && !this.clients.size) {
  378. process.nextTick(emitClose, this);
  379. }
  380. });
  381. }
  382. cb(ws, req);
  383. }
  384. }
  385. module.exports = WebSocketServer;
  386. /**
  387. * Add event listeners on an `EventEmitter` using a map of <event, listener>
  388. * pairs.
  389. *
  390. * @param {EventEmitter} server The event emitter
  391. * @param {Object.<String, Function>} map The listeners to add
  392. * @return {Function} A function that will remove the added listeners when
  393. * called
  394. * @private
  395. */
  396. function addListeners(server, map) {
  397. for (const event of Object.keys(map)) server.on(event, map[event]);
  398. return function removeListeners() {
  399. for (const event of Object.keys(map)) {
  400. server.removeListener(event, map[event]);
  401. }
  402. };
  403. }
  404. /**
  405. * Emit a `'close'` event on an `EventEmitter`.
  406. *
  407. * @param {EventEmitter} server The event emitter
  408. * @private
  409. */
  410. function emitClose(server) {
  411. server._state = CLOSED;
  412. server.emit('close');
  413. }
  414. /**
  415. * Handle socket errors.
  416. *
  417. * @private
  418. */
  419. function socketOnError() {
  420. this.destroy();
  421. }
  422. /**
  423. * Close the connection when preconditions are not fulfilled.
  424. *
  425. * @param {Duplex} socket The socket of the upgrade request
  426. * @param {Number} code The HTTP response status code
  427. * @param {String} [message] The HTTP response body
  428. * @param {Object} [headers] Additional HTTP response headers
  429. * @private
  430. */
  431. function abortHandshake(socket, code, message, headers) {
  432. //
  433. // The socket is writable unless the user destroyed or ended it before calling
  434. // `server.handleUpgrade()` or in the `verifyClient` function, which is a user
  435. // error. Handling this does not make much sense as the worst that can happen
  436. // is that some of the data written by the user might be discarded due to the
  437. // call to `socket.end()` below, which triggers an `'error'` event that in
  438. // turn causes the socket to be destroyed.
  439. //
  440. message = message || http.STATUS_CODES[code];
  441. headers = {
  442. Connection: 'close',
  443. 'Content-Type': 'text/html',
  444. 'Content-Length': Buffer.byteLength(message),
  445. ...headers
  446. };
  447. socket.once('finish', socket.destroy);
  448. socket.end(
  449. `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
  450. Object.keys(headers)
  451. .map((h) => `${h}: ${headers[h]}`)
  452. .join('\r\n') +
  453. '\r\n\r\n' +
  454. message
  455. );
  456. }
  457. /**
  458. * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
  459. * one listener for it, otherwise call `abortHandshake()`.
  460. *
  461. * @param {WebSocketServer} server The WebSocket server
  462. * @param {http.IncomingMessage} req The request object
  463. * @param {Duplex} socket The socket of the upgrade request
  464. * @param {Number} code The HTTP response status code
  465. * @param {String} message The HTTP response body
  466. * @param {Object} [headers] The HTTP response headers
  467. * @private
  468. */
  469. function abortHandshakeOrEmitwsClientError(
  470. server,
  471. req,
  472. socket,
  473. code,
  474. message,
  475. headers
  476. ) {
  477. if (server.listenerCount('wsClientError')) {
  478. const err = new Error(message);
  479. Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
  480. server.emit('wsClientError', err, socket, req);
  481. } else {
  482. abortHandshake(socket, code, message, headers);
  483. }
  484. }