websocket-server.js 17 KB

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