websocket-server.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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 =
  205. req.headers['sec-websocket-key'] !== undefined
  206. ? req.headers['sec-websocket-key']
  207. : false;
  208. const version = +req.headers['sec-websocket-version'];
  209. if (
  210. req.method !== 'GET' ||
  211. req.headers.upgrade.toLowerCase() !== 'websocket' ||
  212. !key ||
  213. !keyRegex.test(key) ||
  214. (version !== 8 && version !== 13) ||
  215. !this.shouldHandle(req)
  216. ) {
  217. return abortHandshake(socket, 400);
  218. }
  219. const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
  220. let protocols = new Set();
  221. if (secWebSocketProtocol !== undefined) {
  222. try {
  223. protocols = subprotocol.parse(secWebSocketProtocol);
  224. } catch (err) {
  225. return abortHandshake(socket, 400);
  226. }
  227. }
  228. const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
  229. const extensions = {};
  230. if (
  231. this.options.perMessageDeflate &&
  232. secWebSocketExtensions !== undefined
  233. ) {
  234. const perMessageDeflate = new PerMessageDeflate(
  235. this.options.perMessageDeflate,
  236. true,
  237. this.options.maxPayload
  238. );
  239. try {
  240. const offers = extension.parse(secWebSocketExtensions);
  241. if (offers[PerMessageDeflate.extensionName]) {
  242. perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
  243. extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  244. }
  245. } catch (err) {
  246. return abortHandshake(socket, 400);
  247. }
  248. }
  249. //
  250. // Optionally call external client verification handler.
  251. //
  252. if (this.options.verifyClient) {
  253. const info = {
  254. origin:
  255. req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
  256. secure: !!(req.socket.authorized || req.socket.encrypted),
  257. req
  258. };
  259. if (this.options.verifyClient.length === 2) {
  260. this.options.verifyClient(info, (verified, code, message, headers) => {
  261. if (!verified) {
  262. return abortHandshake(socket, code || 401, message, headers);
  263. }
  264. this.completeUpgrade(
  265. extensions,
  266. key,
  267. protocols,
  268. req,
  269. socket,
  270. head,
  271. cb
  272. );
  273. });
  274. return;
  275. }
  276. if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
  277. }
  278. this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
  279. }
  280. /**
  281. * Upgrade the connection to WebSocket.
  282. *
  283. * @param {Object} extensions The accepted extensions
  284. * @param {String} key The value of the `Sec-WebSocket-Key` header
  285. * @param {Set} protocols The subprotocols
  286. * @param {http.IncomingMessage} req The request object
  287. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  288. * server and client
  289. * @param {Buffer} head The first packet of the upgraded stream
  290. * @param {Function} cb Callback
  291. * @throws {Error} If called more than once with the same socket
  292. * @private
  293. */
  294. completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
  295. //
  296. // Destroy the socket if the client has already sent a FIN packet.
  297. //
  298. if (!socket.readable || !socket.writable) return socket.destroy();
  299. if (socket[kWebSocket]) {
  300. throw new Error(
  301. 'server.handleUpgrade() was called more than once with the same ' +
  302. 'socket, possibly due to a misconfiguration'
  303. );
  304. }
  305. if (this._state > RUNNING) return abortHandshake(socket, 503);
  306. const digest = createHash('sha1')
  307. .update(key + GUID)
  308. .digest('base64');
  309. const headers = [
  310. 'HTTP/1.1 101 Switching Protocols',
  311. 'Upgrade: websocket',
  312. 'Connection: Upgrade',
  313. `Sec-WebSocket-Accept: ${digest}`
  314. ];
  315. const ws = new this.options.WebSocket(null);
  316. if (protocols.size) {
  317. //
  318. // Optionally call external protocol selection handler.
  319. //
  320. const protocol = this.options.handleProtocols
  321. ? this.options.handleProtocols(protocols, req)
  322. : protocols.values().next().value;
  323. if (protocol) {
  324. headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
  325. ws._protocol = protocol;
  326. }
  327. }
  328. if (extensions[PerMessageDeflate.extensionName]) {
  329. const params = extensions[PerMessageDeflate.extensionName].params;
  330. const value = extension.format({
  331. [PerMessageDeflate.extensionName]: [params]
  332. });
  333. headers.push(`Sec-WebSocket-Extensions: ${value}`);
  334. ws._extensions = extensions;
  335. }
  336. //
  337. // Allow external modification/inspection of handshake headers.
  338. //
  339. this.emit('headers', headers, req);
  340. socket.write(headers.concat('\r\n').join('\r\n'));
  341. socket.removeListener('error', socketOnError);
  342. ws.setSocket(socket, head, {
  343. maxPayload: this.options.maxPayload,
  344. skipUTF8Validation: this.options.skipUTF8Validation
  345. });
  346. if (this.clients) {
  347. this.clients.add(ws);
  348. ws.on('close', () => {
  349. this.clients.delete(ws);
  350. if (this._shouldEmitClose && !this.clients.size) {
  351. process.nextTick(emitClose, this);
  352. }
  353. });
  354. }
  355. cb(ws, req);
  356. }
  357. }
  358. module.exports = WebSocketServer;
  359. /**
  360. * Add event listeners on an `EventEmitter` using a map of <event, listener>
  361. * pairs.
  362. *
  363. * @param {EventEmitter} server The event emitter
  364. * @param {Object.<String, Function>} map The listeners to add
  365. * @return {Function} A function that will remove the added listeners when
  366. * called
  367. * @private
  368. */
  369. function addListeners(server, map) {
  370. for (const event of Object.keys(map)) server.on(event, map[event]);
  371. return function removeListeners() {
  372. for (const event of Object.keys(map)) {
  373. server.removeListener(event, map[event]);
  374. }
  375. };
  376. }
  377. /**
  378. * Emit a `'close'` event on an `EventEmitter`.
  379. *
  380. * @param {EventEmitter} server The event emitter
  381. * @private
  382. */
  383. function emitClose(server) {
  384. server._state = CLOSED;
  385. server.emit('close');
  386. }
  387. /**
  388. * Handle premature socket errors.
  389. *
  390. * @private
  391. */
  392. function socketOnError() {
  393. this.destroy();
  394. }
  395. /**
  396. * Close the connection when preconditions are not fulfilled.
  397. *
  398. * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request
  399. * @param {Number} code The HTTP response status code
  400. * @param {String} [message] The HTTP response body
  401. * @param {Object} [headers] Additional HTTP response headers
  402. * @private
  403. */
  404. function abortHandshake(socket, code, message, headers) {
  405. if (socket.writable) {
  406. message = message || http.STATUS_CODES[code];
  407. headers = {
  408. Connection: 'close',
  409. 'Content-Type': 'text/html',
  410. 'Content-Length': Buffer.byteLength(message),
  411. ...headers
  412. };
  413. socket.write(
  414. `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
  415. Object.keys(headers)
  416. .map((h) => `${h}: ${headers[h]}`)
  417. .join('\r\n') +
  418. '\r\n\r\n' +
  419. message
  420. );
  421. }
  422. socket.removeListener('error', socketOnError);
  423. socket.destroy();
  424. }