websocket-server.js 15 KB

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