websocket-server.js 15 KB

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