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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Socket = void 0;
  4. const events_1 = require("events");
  5. const debug_1 = require("debug");
  6. const timers_1 = require("timers");
  7. const debug = (0, debug_1.default)("engine:socket");
  8. class Socket extends events_1.EventEmitter {
  9. /**
  10. * Client class (abstract).
  11. *
  12. * @api private
  13. */
  14. constructor(id, server, transport, req, protocol) {
  15. super();
  16. this.id = id;
  17. this.server = server;
  18. this.upgrading = false;
  19. this.upgraded = false;
  20. this.readyState = "opening";
  21. this.writeBuffer = [];
  22. this.packetsFn = [];
  23. this.sentCallbackFn = [];
  24. this.cleanupFn = [];
  25. this.request = req;
  26. this.protocol = protocol;
  27. // Cache IP since it might not be in the req later
  28. if (req.websocket && req.websocket._socket) {
  29. this.remoteAddress = req.websocket._socket.remoteAddress;
  30. }
  31. else {
  32. this.remoteAddress = req.connection.remoteAddress;
  33. }
  34. this.checkIntervalTimer = null;
  35. this.upgradeTimeoutTimer = null;
  36. this.pingTimeoutTimer = null;
  37. this.pingIntervalTimer = null;
  38. this.setTransport(transport);
  39. this.onOpen();
  40. }
  41. get readyState() {
  42. return this._readyState;
  43. }
  44. set readyState(state) {
  45. debug("readyState updated from %s to %s", this._readyState, state);
  46. this._readyState = state;
  47. }
  48. /**
  49. * Called upon transport considered open.
  50. *
  51. * @api private
  52. */
  53. onOpen() {
  54. this.readyState = "open";
  55. // sends an `open` packet
  56. this.transport.sid = this.id;
  57. this.sendPacket("open", JSON.stringify({
  58. sid: this.id,
  59. upgrades: this.getAvailableUpgrades(),
  60. pingInterval: this.server.opts.pingInterval,
  61. pingTimeout: this.server.opts.pingTimeout,
  62. maxPayload: this.server.opts.maxHttpBufferSize
  63. }));
  64. if (this.server.opts.initialPacket) {
  65. this.sendPacket("message", this.server.opts.initialPacket);
  66. }
  67. this.emit("open");
  68. if (this.protocol === 3) {
  69. // in protocol v3, the client sends a ping, and the server answers with a pong
  70. this.resetPingTimeout(this.server.opts.pingInterval + this.server.opts.pingTimeout);
  71. }
  72. else {
  73. // in protocol v4, the server sends a ping, and the client answers with a pong
  74. this.schedulePing();
  75. }
  76. }
  77. /**
  78. * Called upon transport packet.
  79. *
  80. * @param {Object} packet
  81. * @api private
  82. */
  83. onPacket(packet) {
  84. if ("open" !== this.readyState) {
  85. return debug("packet received with closed socket");
  86. }
  87. // export packet event
  88. debug(`received packet ${packet.type}`);
  89. this.emit("packet", packet);
  90. // Reset ping timeout on any packet, incoming data is a good sign of
  91. // other side's liveness
  92. this.resetPingTimeout(this.server.opts.pingInterval + this.server.opts.pingTimeout);
  93. switch (packet.type) {
  94. case "ping":
  95. if (this.transport.protocol !== 3) {
  96. this.onError("invalid heartbeat direction");
  97. return;
  98. }
  99. debug("got ping");
  100. this.sendPacket("pong");
  101. this.emit("heartbeat");
  102. break;
  103. case "pong":
  104. if (this.transport.protocol === 3) {
  105. this.onError("invalid heartbeat direction");
  106. return;
  107. }
  108. debug("got pong");
  109. this.pingIntervalTimer.refresh();
  110. this.emit("heartbeat");
  111. break;
  112. case "error":
  113. this.onClose("parse error");
  114. break;
  115. case "message":
  116. this.emit("data", packet.data);
  117. this.emit("message", packet.data);
  118. break;
  119. }
  120. }
  121. /**
  122. * Called upon transport error.
  123. *
  124. * @param {Error} error object
  125. * @api private
  126. */
  127. onError(err) {
  128. debug("transport error");
  129. this.onClose("transport error", err);
  130. }
  131. /**
  132. * Pings client every `this.pingInterval` and expects response
  133. * within `this.pingTimeout` or closes connection.
  134. *
  135. * @api private
  136. */
  137. schedulePing() {
  138. this.pingIntervalTimer = (0, timers_1.setTimeout)(() => {
  139. debug("writing ping packet - expecting pong within %sms", this.server.opts.pingTimeout);
  140. this.sendPacket("ping");
  141. this.resetPingTimeout(this.server.opts.pingTimeout);
  142. }, this.server.opts.pingInterval);
  143. }
  144. /**
  145. * Resets ping timeout.
  146. *
  147. * @api private
  148. */
  149. resetPingTimeout(timeout) {
  150. (0, timers_1.clearTimeout)(this.pingTimeoutTimer);
  151. this.pingTimeoutTimer = (0, timers_1.setTimeout)(() => {
  152. if (this.readyState === "closed")
  153. return;
  154. this.onClose("ping timeout");
  155. }, timeout);
  156. }
  157. /**
  158. * Attaches handlers for the given transport.
  159. *
  160. * @param {Transport} transport
  161. * @api private
  162. */
  163. setTransport(transport) {
  164. const onError = this.onError.bind(this);
  165. const onPacket = this.onPacket.bind(this);
  166. const flush = this.flush.bind(this);
  167. const onClose = this.onClose.bind(this, "transport close");
  168. this.transport = transport;
  169. this.transport.once("error", onError);
  170. this.transport.on("packet", onPacket);
  171. this.transport.on("drain", flush);
  172. this.transport.once("close", onClose);
  173. // this function will manage packet events (also message callbacks)
  174. this.setupSendCallback();
  175. this.cleanupFn.push(function () {
  176. transport.removeListener("error", onError);
  177. transport.removeListener("packet", onPacket);
  178. transport.removeListener("drain", flush);
  179. transport.removeListener("close", onClose);
  180. });
  181. }
  182. /**
  183. * Upgrades socket to the given transport
  184. *
  185. * @param {Transport} transport
  186. * @api private
  187. */
  188. maybeUpgrade(transport) {
  189. debug('might upgrade socket transport from "%s" to "%s"', this.transport.name, transport.name);
  190. this.upgrading = true;
  191. // set transport upgrade timer
  192. this.upgradeTimeoutTimer = (0, timers_1.setTimeout)(() => {
  193. debug("client did not complete upgrade - closing transport");
  194. cleanup();
  195. if ("open" === transport.readyState) {
  196. transport.close();
  197. }
  198. }, this.server.opts.upgradeTimeout);
  199. const onPacket = packet => {
  200. if ("ping" === packet.type && "probe" === packet.data) {
  201. debug("got probe ping packet, sending pong");
  202. transport.send([{ type: "pong", data: "probe" }]);
  203. this.emit("upgrading", transport);
  204. clearInterval(this.checkIntervalTimer);
  205. this.checkIntervalTimer = setInterval(check, 100);
  206. }
  207. else if ("upgrade" === packet.type && this.readyState !== "closed") {
  208. debug("got upgrade packet - upgrading");
  209. cleanup();
  210. this.transport.discard();
  211. this.upgraded = true;
  212. this.clearTransport();
  213. this.setTransport(transport);
  214. this.emit("upgrade", transport);
  215. this.flush();
  216. if (this.readyState === "closing") {
  217. transport.close(() => {
  218. this.onClose("forced close");
  219. });
  220. }
  221. }
  222. else {
  223. cleanup();
  224. transport.close();
  225. }
  226. };
  227. // we force a polling cycle to ensure a fast upgrade
  228. const check = () => {
  229. if ("polling" === this.transport.name && this.transport.writable) {
  230. debug("writing a noop packet to polling for fast upgrade");
  231. this.transport.send([{ type: "noop" }]);
  232. }
  233. };
  234. const cleanup = () => {
  235. this.upgrading = false;
  236. clearInterval(this.checkIntervalTimer);
  237. this.checkIntervalTimer = null;
  238. (0, timers_1.clearTimeout)(this.upgradeTimeoutTimer);
  239. this.upgradeTimeoutTimer = null;
  240. transport.removeListener("packet", onPacket);
  241. transport.removeListener("close", onTransportClose);
  242. transport.removeListener("error", onError);
  243. this.removeListener("close", onClose);
  244. };
  245. const onError = err => {
  246. debug("client did not complete upgrade - %s", err);
  247. cleanup();
  248. transport.close();
  249. transport = null;
  250. };
  251. const onTransportClose = () => {
  252. onError("transport closed");
  253. };
  254. const onClose = () => {
  255. onError("socket closed");
  256. };
  257. transport.on("packet", onPacket);
  258. transport.once("close", onTransportClose);
  259. transport.once("error", onError);
  260. this.once("close", onClose);
  261. }
  262. /**
  263. * Clears listeners and timers associated with current transport.
  264. *
  265. * @api private
  266. */
  267. clearTransport() {
  268. let cleanup;
  269. const toCleanUp = this.cleanupFn.length;
  270. for (let i = 0; i < toCleanUp; i++) {
  271. cleanup = this.cleanupFn.shift();
  272. cleanup();
  273. }
  274. // silence further transport errors and prevent uncaught exceptions
  275. this.transport.on("error", function () {
  276. debug("error triggered by discarded transport");
  277. });
  278. // ensure transport won't stay open
  279. this.transport.close();
  280. (0, timers_1.clearTimeout)(this.pingTimeoutTimer);
  281. }
  282. /**
  283. * Called upon transport considered closed.
  284. * Possible reasons: `ping timeout`, `client error`, `parse error`,
  285. * `transport error`, `server close`, `transport close`
  286. */
  287. onClose(reason, description) {
  288. if ("closed" !== this.readyState) {
  289. this.readyState = "closed";
  290. // clear timers
  291. (0, timers_1.clearTimeout)(this.pingIntervalTimer);
  292. (0, timers_1.clearTimeout)(this.pingTimeoutTimer);
  293. clearInterval(this.checkIntervalTimer);
  294. this.checkIntervalTimer = null;
  295. (0, timers_1.clearTimeout)(this.upgradeTimeoutTimer);
  296. // clean writeBuffer in next tick, so developers can still
  297. // grab the writeBuffer on 'close' event
  298. process.nextTick(() => {
  299. this.writeBuffer = [];
  300. });
  301. this.packetsFn = [];
  302. this.sentCallbackFn = [];
  303. this.clearTransport();
  304. this.emit("close", reason, description);
  305. }
  306. }
  307. /**
  308. * Setup and manage send callback
  309. *
  310. * @api private
  311. */
  312. setupSendCallback() {
  313. // the message was sent successfully, execute the callback
  314. const onDrain = () => {
  315. if (this.sentCallbackFn.length > 0) {
  316. const seqFn = this.sentCallbackFn.splice(0, 1)[0];
  317. if ("function" === typeof seqFn) {
  318. debug("executing send callback");
  319. seqFn(this.transport);
  320. }
  321. else if (Array.isArray(seqFn)) {
  322. debug("executing batch send callback");
  323. const l = seqFn.length;
  324. let i = 0;
  325. for (; i < l; i++) {
  326. if ("function" === typeof seqFn[i]) {
  327. seqFn[i](this.transport);
  328. }
  329. }
  330. }
  331. }
  332. };
  333. this.transport.on("drain", onDrain);
  334. this.cleanupFn.push(() => {
  335. this.transport.removeListener("drain", onDrain);
  336. });
  337. }
  338. /**
  339. * Sends a message packet.
  340. *
  341. * @param {Object} data
  342. * @param {Object} options
  343. * @param {Function} callback
  344. * @return {Socket} for chaining
  345. * @api public
  346. */
  347. send(data, options, callback) {
  348. this.sendPacket("message", data, options, callback);
  349. return this;
  350. }
  351. write(data, options, callback) {
  352. this.sendPacket("message", data, options, callback);
  353. return this;
  354. }
  355. /**
  356. * Sends a packet.
  357. *
  358. * @param {String} type - packet type
  359. * @param {String} data
  360. * @param {Object} options
  361. * @param {Function} callback
  362. *
  363. * @api private
  364. */
  365. sendPacket(type, data, options, callback) {
  366. if ("function" === typeof options) {
  367. callback = options;
  368. options = null;
  369. }
  370. options = options || {};
  371. options.compress = false !== options.compress;
  372. if ("closing" !== this.readyState && "closed" !== this.readyState) {
  373. debug('sending packet "%s" (%s)', type, data);
  374. const packet = {
  375. type,
  376. options
  377. };
  378. if (data)
  379. packet.data = data;
  380. // exports packetCreate event
  381. this.emit("packetCreate", packet);
  382. this.writeBuffer.push(packet);
  383. // add send callback to object, if defined
  384. if (callback)
  385. this.packetsFn.push(callback);
  386. this.flush();
  387. }
  388. }
  389. /**
  390. * Attempts to flush the packets buffer.
  391. *
  392. * @api private
  393. */
  394. flush() {
  395. if ("closed" !== this.readyState &&
  396. this.transport.writable &&
  397. this.writeBuffer.length) {
  398. debug("flushing buffer to transport");
  399. this.emit("flush", this.writeBuffer);
  400. this.server.emit("flush", this, this.writeBuffer);
  401. const wbuf = this.writeBuffer;
  402. this.writeBuffer = [];
  403. if (!this.transport.supportsFraming) {
  404. this.sentCallbackFn.push(this.packetsFn);
  405. }
  406. else {
  407. this.sentCallbackFn.push.apply(this.sentCallbackFn, this.packetsFn);
  408. }
  409. this.packetsFn = [];
  410. this.transport.send(wbuf);
  411. this.emit("drain");
  412. this.server.emit("drain", this);
  413. }
  414. }
  415. /**
  416. * Get available upgrades for this socket.
  417. *
  418. * @api private
  419. */
  420. getAvailableUpgrades() {
  421. const availableUpgrades = [];
  422. const allUpgrades = this.server.upgrades(this.transport.name);
  423. let i = 0;
  424. const l = allUpgrades.length;
  425. for (; i < l; ++i) {
  426. const upg = allUpgrades[i];
  427. if (this.server.opts.transports.indexOf(upg) !== -1) {
  428. availableUpgrades.push(upg);
  429. }
  430. }
  431. return availableUpgrades;
  432. }
  433. /**
  434. * Closes the socket and underlying transport.
  435. *
  436. * @param {Boolean} discard - optional, discard the transport
  437. * @return {Socket} for chaining
  438. * @api public
  439. */
  440. close(discard) {
  441. if ("open" !== this.readyState)
  442. return;
  443. this.readyState = "closing";
  444. if (this.writeBuffer.length) {
  445. this.once("drain", this.closeTransport.bind(this, discard));
  446. return;
  447. }
  448. this.closeTransport(discard);
  449. }
  450. /**
  451. * Closes the underlying transport.
  452. *
  453. * @param {Boolean} discard
  454. * @api private
  455. */
  456. closeTransport(discard) {
  457. if (discard)
  458. this.transport.discard();
  459. this.transport.close(this.onClose.bind(this, "forced close"));
  460. }
  461. }
  462. exports.Socket = Socket;