websocket-server.js 16 KB

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