Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
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.

socket.js 13KB

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