socket.js 16 KB

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