A Twitch.tv viewer reward and games system.
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.

292 lines
7.0 KiB

12 years ago
  1. var Parser = require('./Parser');
  2. var Sequences = require('./sequences');
  3. var Packets = require('./packets');
  4. var Auth = require('./Auth');
  5. var Stream = require('stream').Stream;
  6. var Util = require('util');
  7. var PacketWriter = require('./PacketWriter');
  8. module.exports = Protocol;
  9. Util.inherits(Protocol, Stream);
  10. function Protocol(options) {
  11. Stream.call(this);
  12. options = options || {};
  13. this.readable = true;
  14. this.writable = true;
  15. this._parser = new Parser({onPacket: this._parsePacket.bind(this)});
  16. this._config = options.config || {};
  17. this._connection = options.connection;
  18. this._callback = null;
  19. this._fatalError = null;
  20. this._quitSequence = null;
  21. this._handshakeSequence = null;
  22. this._destroyed = false;
  23. this._queue = [];
  24. this._handshakeInitializationPacket = null;
  25. }
  26. Protocol.prototype.write = function(buffer) {
  27. this._parser.write(buffer);
  28. return true;
  29. };
  30. Protocol.prototype.handshake = function(cb) {
  31. return this._handshakeSequence = this._enqueue(new Sequences.Handshake(this._config, cb));
  32. };
  33. Protocol.prototype.query = function(options, cb) {
  34. return this._enqueue(new Sequences.Query(options, cb));
  35. };
  36. Protocol.prototype.changeUser = function(options, cb) {
  37. return this._enqueue(new Sequences.ChangeUser(options, cb));
  38. };
  39. Protocol.prototype.ping = function(cb) {
  40. return this._enqueue(new Sequences.Ping(cb));
  41. };
  42. Protocol.prototype.stats = function(cb) {
  43. return this._enqueue(new Sequences.Statistics(cb));
  44. };
  45. Protocol.prototype.quit = function(cb) {
  46. return this._quitSequence = this._enqueue(new Sequences.Quit(cb));
  47. };
  48. Protocol.prototype.end = function() {
  49. var expected = (this._quitSequence && this._queue[0] === this._quitSequence);
  50. if (expected) {
  51. this._quitSequence.end();
  52. this.emit('end');
  53. return;
  54. }
  55. var err = new Error('Connection lost: The server closed the connection.');
  56. err.fatal = true;
  57. err.code = 'PROTOCOL_CONNECTION_LOST';
  58. this._delegateError(err);
  59. };
  60. Protocol.prototype.pause = function() {
  61. this._parser.pause();
  62. };
  63. Protocol.prototype.resume = function() {
  64. this._parser.resume();
  65. };
  66. Protocol.prototype._enqueue = function(sequence) {
  67. if (!this._validateEnqueue(sequence)) {
  68. return sequence;
  69. }
  70. this._queue.push(sequence);
  71. var self = this;
  72. sequence
  73. .on('error', function(err) {
  74. self._delegateError(err, sequence);
  75. })
  76. .on('packet', function(packet) {
  77. self._emitPacket(packet);
  78. })
  79. .on('end', function() {
  80. self._dequeue();
  81. });
  82. if (this._queue.length === 1) {
  83. this._parser.resetPacketNumber();
  84. sequence.start();
  85. }
  86. return sequence;
  87. };
  88. Protocol.prototype._validateEnqueue = function(sequence) {
  89. var err;
  90. var prefix = 'Cannot enqueue ' + sequence.constructor.name + ' after ';
  91. if (this._quitSequence) {
  92. err = new Error(prefix + 'invoking quit.');
  93. err.code = 'PROTOCOL_ENQUEUE_AFTER_QUIT';
  94. } else if (this._destroyed) {
  95. err = new Error(prefix + 'being destroyed.');
  96. err.code = 'PROTOCOL_ENQUEUE_AFTER_DESTROY';
  97. } else if (this._handshakeSequence && sequence.constructor === Sequences.Handshake) {
  98. err = new Error(prefix + 'already enqueuing a Handshake.');
  99. err.code = 'PROTOCOL_ENQUEUE_HANDSHAKE_TWICE';
  100. } else {
  101. return true;
  102. }
  103. var self = this;
  104. err.fatal = false;
  105. sequence
  106. .on('error', function(err) {
  107. self._delegateError(err, sequence);
  108. })
  109. .end(err);
  110. return false;
  111. };
  112. Protocol.prototype._parsePacket = function() {
  113. var sequence = this._queue[0];
  114. var Packet = this._determinePacket(sequence);
  115. var packet = new Packet();
  116. // Special case: Faster dispatch, and parsing done inside sequence
  117. if (Packet === Packets.RowDataPacket) {
  118. sequence.RowDataPacket(packet, this._parser, this._connection);
  119. if (this._config.debug) {
  120. this._debugPacket(true, packet);
  121. }
  122. return;
  123. }
  124. packet.parse(this._parser);
  125. if (this._config.debug) {
  126. this._debugPacket(true, packet);
  127. }
  128. if (Packet === Packets.HandshakeInitializationPacket) {
  129. this._handshakeInitializationPacket = packet;
  130. }
  131. sequence[Packet.name](packet);
  132. };
  133. Protocol.prototype._emitPacket = function(packet) {
  134. var packetWriter = new PacketWriter();
  135. packet.write(packetWriter);
  136. this.emit('data', packetWriter.toBuffer(this._parser));
  137. if (this._config.debug) {
  138. this._debugPacket(false, packet)
  139. }
  140. };
  141. Protocol.prototype._determinePacket = function(sequence) {
  142. var firstByte = this._parser.peak();
  143. if (sequence.determinePacket) {
  144. var Packet = sequence.determinePacket(firstByte, this._parser);
  145. if (Packet) {
  146. return Packet;
  147. }
  148. }
  149. switch (firstByte) {
  150. case 0x00: return Packets.OkPacket;
  151. case 0xfe: return Packets.EofPacket;
  152. case 0xff: return Packets.ErrorPacket;
  153. }
  154. throw new Error('Could not determine packet, firstByte = ' + firstByte);
  155. };
  156. Protocol.prototype._dequeue = function() {
  157. // No point in advancing the queue, we are dead
  158. if (this._fatalError) {
  159. return;
  160. }
  161. this._queue.shift();
  162. var sequence = this._queue[0];
  163. if (!sequence) {
  164. this.emit('drain');
  165. return;
  166. }
  167. this._parser.resetPacketNumber();
  168. if (sequence.constructor == Sequences.ChangeUser) {
  169. sequence.start(this._handshakeInitializationPacket);
  170. return;
  171. }
  172. sequence.start();
  173. };
  174. Protocol.prototype.handleNetworkError = function(err) {
  175. err.fatal = true;
  176. var sequence = this._queue[0];
  177. if (sequence) {
  178. sequence.end(err)
  179. } else {
  180. this._delegateError(err);
  181. }
  182. };
  183. Protocol.prototype._delegateError = function(err, sequence) {
  184. // Stop delegating errors after the first fatal error
  185. if (this._fatalError) {
  186. return;
  187. }
  188. if (err.fatal) {
  189. this._fatalError = err;
  190. }
  191. if (this._shouldErrorBubbleUp(err, sequence)) {
  192. // Can't use regular 'error' event here as that always destroys the pipe
  193. // between socket and protocol which is not what we want (unless the
  194. // exception was fatal).
  195. this.emit('unhandledError', err);
  196. } else if (err.fatal) {
  197. this._queue.forEach(function(sequence) {
  198. sequence.end(err);
  199. });
  200. }
  201. // Make sure the stream we are piping to is getting closed
  202. if (err.fatal) {
  203. this.emit('end', err);
  204. }
  205. };
  206. Protocol.prototype._shouldErrorBubbleUp = function(err, sequence) {
  207. if (sequence) {
  208. if (sequence.hasErrorHandler()) {
  209. return false;
  210. } else if (!err.fatal) {
  211. return true;
  212. }
  213. }
  214. return (err.fatal && !this._hasPendingErrorHandlers());
  215. };
  216. Protocol.prototype._hasPendingErrorHandlers = function() {
  217. return this._queue.some(function(sequence) {
  218. return sequence.hasErrorHandler();
  219. });
  220. };
  221. Protocol.prototype.destroy = function() {
  222. this._destroyed = true;
  223. this._parser.pause();
  224. };
  225. Protocol.prototype._debugPacket = function(incoming, packet) {
  226. var headline = (incoming)
  227. ? '<-- '
  228. : '--> ';
  229. headline = headline + packet.constructor.name;
  230. console.log(headline);
  231. console.log(packet);
  232. console.log('');
  233. };