PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/packages/firepad/node_modules/firebase/node_modules/faye-websocket/node_modules/websocket-driver/lib/websocket/driver/hybi.js

https://gitlab.com/xxtxx/atom-settings
JavaScript | 424 lines | 350 code | 73 blank | 1 comment | 85 complexity | 6050d53033d71afe33454dfdada4a5fa MD5 | raw file
  1. var crypto = require('crypto'),
  2. util = require('util'),
  3. Base = require('./base'),
  4. Reader = require('./hybi/stream_reader');
  5. var Hybi = function(request, url, options) {
  6. Base.apply(this, arguments);
  7. this._reset();
  8. this._reader = new Reader();
  9. this._stage = 0;
  10. this._masking = this._options.masking;
  11. this._protocols = this._options.protocols || [];
  12. this._requireMasking = this._options.requireMasking;
  13. this._pingCallbacks = {};
  14. if (typeof this._protocols === 'string')
  15. this._protocols = this._protocols.split(/\s*,\s*/);
  16. if (!this._request) return;
  17. var protos = this._request.headers['sec-websocket-protocol'],
  18. supported = this._protocols;
  19. if (protos !== undefined) {
  20. if (typeof protos === 'string') protos = protos.split(/\s*,\s*/);
  21. this.protocol = protos.filter(function(p) { return supported.indexOf(p) >= 0 })[0];
  22. }
  23. var version = this._request.headers['sec-websocket-version'];
  24. this.version = 'hybi-' + version;
  25. };
  26. util.inherits(Hybi, Base);
  27. Hybi.mask = function(payload, mask, offset) {
  28. if (!mask || mask.length === 0) return payload;
  29. offset = offset || 0;
  30. for (var i = 0, n = payload.length - offset; i < n; i++) {
  31. payload[offset + i] = payload[offset + i] ^ mask[i % 4];
  32. }
  33. return payload;
  34. };
  35. Hybi.generateAccept = function(key) {
  36. var sha1 = crypto.createHash('sha1');
  37. sha1.update(key + Hybi.GUID);
  38. return sha1.digest('base64');
  39. };
  40. Hybi.GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
  41. var instance = {
  42. BYTE: 255,
  43. FIN: 128,
  44. MASK: 128,
  45. RSV1: 64,
  46. RSV2: 32,
  47. RSV3: 16,
  48. OPCODE: 15,
  49. LENGTH: 127,
  50. OPCODES: {
  51. continuation: 0,
  52. text: 1,
  53. binary: 2,
  54. close: 8,
  55. ping: 9,
  56. pong: 10
  57. },
  58. OPCODE_CODES: [0, 1, 2, 8, 9, 10],
  59. FRAGMENTED_OPCODES: [0, 1, 2],
  60. OPENING_OPCODES: [1, 2],
  61. TWO_POWERS: [0, 1, 2, 3, 4, 5, 6, 7].map(function(n) { return Math.pow(2, 8 * n) }),
  62. ERRORS: {
  63. normal_closure: 1000,
  64. going_away: 1001,
  65. protocol_error: 1002,
  66. unacceptable: 1003,
  67. encoding_error: 1007,
  68. policy_violation: 1008,
  69. too_large: 1009,
  70. extension_error: 1010,
  71. unexpected_condition: 1011
  72. },
  73. ERROR_CODES: [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011],
  74. MIN_RESERVED_ERROR: 3000,
  75. MAX_RESERVED_ERROR: 4999,
  76. // http://www.w3.org/International/questions/qa-forms-utf-8.en.php
  77. UTF8_MATCH: /^([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$/,
  78. parse: function(data) {
  79. this._reader.put(data);
  80. var buffer = true;
  81. while (buffer) {
  82. switch (this._stage) {
  83. case 0:
  84. buffer = this._reader.read(1);
  85. if (buffer) this._parseOpcode(buffer[0]);
  86. break;
  87. case 1:
  88. buffer = this._reader.read(1);
  89. if (buffer) this._parseLength(buffer[0]);
  90. break;
  91. case 2:
  92. buffer = this._reader.read(this._lengthSize);
  93. if (buffer) this._parseExtendedLength(buffer);
  94. break;
  95. case 3:
  96. buffer = this._reader.read(4);
  97. if (buffer) {
  98. this._mask = buffer;
  99. this._stage = 4;
  100. }
  101. break;
  102. case 4:
  103. buffer = this._reader.read(this._length);
  104. if (buffer) {
  105. this._emitFrame(buffer);
  106. this._stage = 0;
  107. }
  108. break;
  109. default:
  110. buffer = null;
  111. }
  112. }
  113. },
  114. frame: function(data, type, code) {
  115. if (this.readyState <= 0) return this._queue([data, type, code]);
  116. if (this.readyState !== 1) return false;
  117. if (data instanceof Array) data = new Buffer(data);
  118. var isText = (typeof data === 'string'),
  119. opcode = this.OPCODES[type || (isText ? 'text' : 'binary')],
  120. buffer = isText ? new Buffer(data, 'utf8') : data,
  121. insert = code ? 2 : 0,
  122. length = buffer.length + insert,
  123. header = (length <= 125) ? 2 : (length <= 65535 ? 4 : 10),
  124. offset = header + (this._masking ? 4 : 0),
  125. masked = this._masking ? this.MASK : 0,
  126. frame = new Buffer(length + offset),
  127. BYTE = this.BYTE,
  128. mask, i;
  129. frame[0] = this.FIN | opcode;
  130. if (length <= 125) {
  131. frame[1] = masked | length;
  132. } else if (length <= 65535) {
  133. frame[1] = masked | 126;
  134. frame[2] = Math.floor(length / 256);
  135. frame[3] = length & BYTE;
  136. } else {
  137. frame[1] = masked | 127;
  138. frame[2] = Math.floor(length / Math.pow(2,56)) & BYTE;
  139. frame[3] = Math.floor(length / Math.pow(2,48)) & BYTE;
  140. frame[4] = Math.floor(length / Math.pow(2,40)) & BYTE;
  141. frame[5] = Math.floor(length / Math.pow(2,32)) & BYTE;
  142. frame[6] = Math.floor(length / Math.pow(2,24)) & BYTE;
  143. frame[7] = Math.floor(length / Math.pow(2,16)) & BYTE;
  144. frame[8] = Math.floor(length / Math.pow(2,8)) & BYTE;
  145. frame[9] = length & BYTE;
  146. }
  147. if (code) {
  148. frame[offset] = Math.floor(code / 256) & BYTE;
  149. frame[offset+1] = code & BYTE;
  150. }
  151. buffer.copy(frame, offset + insert);
  152. if (this._masking) {
  153. mask = [Math.floor(Math.random() * 256), Math.floor(Math.random() * 256),
  154. Math.floor(Math.random() * 256), Math.floor(Math.random() * 256)];
  155. new Buffer(mask).copy(frame, header);
  156. Hybi.mask(frame, mask, offset);
  157. }
  158. this._write(frame);
  159. return true;
  160. },
  161. text: function(message) {
  162. return this.frame(message, 'text');
  163. },
  164. binary: function(message) {
  165. return this.frame(message, 'binary');
  166. },
  167. ping: function(message, callback) {
  168. message = message || '';
  169. if (callback) this._pingCallbacks[message] = callback;
  170. return this.frame(message, 'ping');
  171. },
  172. close: function(reason, code) {
  173. reason = reason || '';
  174. code = code || this.ERRORS.normal_closure;
  175. if (this.readyState === 0) {
  176. this.readyState = 3;
  177. this.emit('close', new Base.CloseEvent(code, reason));
  178. return true;
  179. } else if (this.readyState === 1) {
  180. this.frame(reason, 'close', code);
  181. this.readyState = 2;
  182. return true;
  183. } else {
  184. return false;
  185. }
  186. },
  187. _handshakeResponse: function() {
  188. var secKey = this._request.headers['sec-websocket-key'];
  189. if (!secKey) return '';
  190. var headers = [
  191. 'HTTP/1.1 101 Switching Protocols',
  192. 'Upgrade: websocket',
  193. 'Connection: Upgrade',
  194. 'Sec-WebSocket-Accept: ' + Hybi.generateAccept(secKey)
  195. ];
  196. if (this.protocol)
  197. headers.push('Sec-WebSocket-Protocol: ' + this.protocol);
  198. return new Buffer(headers.concat(this.__headers.toString(), '').join('\r\n'), 'utf8');
  199. },
  200. _shutdown: function(code, reason) {
  201. this.frame(reason, 'close', code);
  202. this.readyState = 3;
  203. this._stage = 5;
  204. this.emit('close', new Base.CloseEvent(code, reason));
  205. },
  206. _fail: function(type, message) {
  207. this.emit('error', new Error(message));
  208. this._shutdown(this.ERRORS[type], message);
  209. },
  210. _parseOpcode: function(data) {
  211. var rsvs = [this.RSV1, this.RSV2, this.RSV3].map(function(rsv) {
  212. return (data & rsv) === rsv;
  213. });
  214. if (rsvs.filter(function(rsv) { return rsv }).length > 0)
  215. return this._fail('protocol_error',
  216. 'One or more reserved bits are on: reserved1 = ' + (rsvs[0] ? 1 : 0) +
  217. ', reserved2 = ' + (rsvs[1] ? 1 : 0) +
  218. ', reserved3 = ' + (rsvs[2] ? 1 : 0));
  219. this._final = (data & this.FIN) === this.FIN;
  220. this._opcode = (data & this.OPCODE);
  221. if (this.OPCODE_CODES.indexOf(this._opcode) < 0)
  222. return this._fail('protocol_error', 'Unrecognized frame opcode: ' + this._opcode);
  223. if (this.FRAGMENTED_OPCODES.indexOf(this._opcode) < 0 && !this._final)
  224. return this._fail('protocol_error', 'Received fragmented control frame: opcode = ' + this._opcode);
  225. if (this._mode && this.OPENING_OPCODES.indexOf(this._opcode) >= 0)
  226. return this._fail('protocol_error', 'Received new data frame but previous continuous frame is unfinished');
  227. this._stage = 1;
  228. },
  229. _parseLength: function(data) {
  230. this._masked = (data & this.MASK) === this.MASK;
  231. if (this._requireMasking && !this._masked)
  232. return this._fail('unacceptable', 'Received unmasked frame but masking is required');
  233. this._length = (data & this.LENGTH);
  234. if (this._length >= 0 && this._length <= 125) {
  235. if (!this._checkFrameLength()) return;
  236. this._stage = this._masked ? 3 : 4;
  237. } else {
  238. this._lengthSize = (this._length === 126 ? 2 : 8);
  239. this._stage = 2;
  240. }
  241. },
  242. _parseExtendedLength: function(buffer) {
  243. this._length = this._getInteger(buffer);
  244. if (this.FRAGMENTED_OPCODES.indexOf(this._opcode) < 0 && this._length > 125)
  245. return this._fail('protocol_error', 'Received control frame having too long payload: ' + this._length);
  246. if (!this._checkFrameLength()) return;
  247. this._stage = this._masked ? 3 : 4;
  248. },
  249. _checkFrameLength: function() {
  250. if (this.__blength + this._length > this._maxLength) {
  251. this._fail('too_large', 'WebSocket frame length too large');
  252. return false;
  253. } else {
  254. return true;
  255. }
  256. },
  257. _emitFrame: function(buffer) {
  258. var payload = Hybi.mask(buffer, this._mask),
  259. isFinal = this._final,
  260. opcode = this._opcode;
  261. this._final = this._opcode = this._length = this._lengthSize = this._masked = this._mask = null;
  262. if (opcode === this.OPCODES.continuation) {
  263. if (!this._mode) return this._fail('protocol_error', 'Received unexpected continuation frame');
  264. this._buffer(payload);
  265. if (isFinal) {
  266. var message = this._concatBuffer();
  267. if (this._mode === 'text') message = this._encode(message);
  268. this._reset();
  269. if (message === null)
  270. this._fail('encoding_error', 'Could not decode a text frame as UTF-8');
  271. else
  272. this.emit('message', new Base.MessageEvent(message));
  273. }
  274. }
  275. else if (opcode === this.OPCODES.text) {
  276. if (isFinal) {
  277. var message = this._encode(payload);
  278. if (message === null)
  279. this._fail('encoding_error', 'Could not decode a text frame as UTF-8');
  280. else
  281. this.emit('message', new Base.MessageEvent(message));
  282. } else {
  283. this._mode = 'text';
  284. this._buffer(payload);
  285. }
  286. }
  287. else if (opcode === this.OPCODES.binary) {
  288. if (isFinal) {
  289. this.emit('message', new Base.MessageEvent(payload));
  290. } else {
  291. this._mode = 'binary';
  292. this._buffer(payload);
  293. }
  294. }
  295. else if (opcode === this.OPCODES.close) {
  296. var code = (payload.length >= 2) ? 256 * payload[0] + payload[1] : null,
  297. reason = (payload.length > 2) ? this._encode(payload.slice(2)) : null;
  298. if (!(payload.length === 0) &&
  299. !(code !== null && code >= this.MIN_RESERVED_ERROR && code <= this.MAX_RESERVED_ERROR) &&
  300. this.ERROR_CODES.indexOf(code) < 0)
  301. code = this.ERRORS.protocol_error;
  302. if (payload.length > 125 || (payload.length > 2 && !reason))
  303. code = this.ERRORS.protocol_error;
  304. this._shutdown(code, reason || '');
  305. }
  306. else if (opcode === this.OPCODES.ping) {
  307. this.frame(payload, 'pong');
  308. }
  309. else if (opcode === this.OPCODES.pong) {
  310. var callbacks = this._pingCallbacks,
  311. message = this._encode(payload),
  312. callback = callbacks[message];
  313. delete callbacks[message];
  314. if (callback) callback()
  315. }
  316. },
  317. _buffer: function(fragment) {
  318. this.__buffer.push(fragment);
  319. this.__blength += fragment.length;
  320. },
  321. _concatBuffer: function() {
  322. var buffer = new Buffer(this.__blength),
  323. offset = 0;
  324. for (var i = 0, n = this.__buffer.length; i < n; i++) {
  325. this.__buffer[i].copy(buffer, offset);
  326. offset += this.__buffer[i].length;
  327. }
  328. return buffer;
  329. },
  330. _reset: function() {
  331. this._mode = null;
  332. this.__buffer = [];
  333. this.__blength = 0;
  334. },
  335. _encode: function(buffer) {
  336. try {
  337. var string = buffer.toString('binary', 0, buffer.length);
  338. if (!this.UTF8_MATCH.test(string)) return null;
  339. } catch (e) {}
  340. return buffer.toString('utf8', 0, buffer.length);
  341. },
  342. _getInteger: function(bytes) {
  343. var number = 0;
  344. for (var i = 0, n = bytes.length; i < n; i++)
  345. number += bytes[i] * this.TWO_POWERS[n - 1 - i];
  346. return number;
  347. }
  348. };
  349. for (var key in instance)
  350. Hybi.prototype[key] = instance[key];
  351. module.exports = Hybi;