socket.js 15 KB

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