Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

websocket-server.js 13KB

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