socket.js 11 KB

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