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.

483 lines
14 KiB

4 years ago
  1. 'use strict';
  2. var Buffer = require('safe-buffer').Buffer,
  3. crypto = require('crypto'),
  4. util = require('util'),
  5. Extensions = require('websocket-extensions'),
  6. Base = require('./base'),
  7. Frame = require('./hybi/frame'),
  8. Message = require('./hybi/message');
  9. var Hybi = function(request, url, options) {
  10. Base.apply(this, arguments);
  11. this._extensions = new Extensions();
  12. this._stage = 0;
  13. this._masking = this._options.masking;
  14. this._protocols = this._options.protocols || [];
  15. this._requireMasking = this._options.requireMasking;
  16. this._pingCallbacks = {};
  17. if (typeof this._protocols === 'string')
  18. this._protocols = this._protocols.split(/ *, */);
  19. if (!this._request) return;
  20. var protos = this._request.headers['sec-websocket-protocol'],
  21. supported = this._protocols;
  22. if (protos !== undefined) {
  23. if (typeof protos === 'string') protos = protos.split(/ *, */);
  24. this.protocol = protos.filter(function(p) { return supported.indexOf(p) >= 0 })[0];
  25. }
  26. this.version = 'hybi-' + Hybi.VERSION;
  27. };
  28. util.inherits(Hybi, Base);
  29. Hybi.VERSION = '13';
  30. Hybi.mask = function(payload, mask, offset) {
  31. if (!mask || mask.length === 0) return payload;
  32. offset = offset || 0;
  33. for (var i = 0, n = payload.length - offset; i < n; i++) {
  34. payload[offset + i] = payload[offset + i] ^ mask[i % 4];
  35. }
  36. return payload;
  37. };
  38. Hybi.generateAccept = function(key) {
  39. var sha1 = crypto.createHash('sha1');
  40. sha1.update(key + Hybi.GUID);
  41. return sha1.digest('base64');
  42. };
  43. Hybi.GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
  44. var instance = {
  45. FIN: 0x80,
  46. MASK: 0x80,
  47. RSV1: 0x40,
  48. RSV2: 0x20,
  49. RSV3: 0x10,
  50. OPCODE: 0x0F,
  51. LENGTH: 0x7F,
  52. OPCODES: {
  53. continuation: 0,
  54. text: 1,
  55. binary: 2,
  56. close: 8,
  57. ping: 9,
  58. pong: 10
  59. },
  60. OPCODE_CODES: [0, 1, 2, 8, 9, 10],
  61. MESSAGE_OPCODES: [0, 1, 2],
  62. OPENING_OPCODES: [1, 2],
  63. ERRORS: {
  64. normal_closure: 1000,
  65. going_away: 1001,
  66. protocol_error: 1002,
  67. unacceptable: 1003,
  68. encoding_error: 1007,
  69. policy_violation: 1008,
  70. too_large: 1009,
  71. extension_error: 1010,
  72. unexpected_condition: 1011
  73. },
  74. ERROR_CODES: [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011],
  75. DEFAULT_ERROR_CODE: 1000,
  76. MIN_RESERVED_ERROR: 3000,
  77. MAX_RESERVED_ERROR: 4999,
  78. // http://www.w3.org/International/questions/qa-forms-utf-8.en.php
  79. 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})*$/,
  80. addExtension: function(extension) {
  81. this._extensions.add(extension);
  82. return true;
  83. },
  84. parse: function(chunk) {
  85. this._reader.put(chunk);
  86. var buffer = true;
  87. while (buffer) {
  88. switch (this._stage) {
  89. case 0:
  90. buffer = this._reader.read(1);
  91. if (buffer) this._parseOpcode(buffer[0]);
  92. break;
  93. case 1:
  94. buffer = this._reader.read(1);
  95. if (buffer) this._parseLength(buffer[0]);
  96. break;
  97. case 2:
  98. buffer = this._reader.read(this._frame.lengthBytes);
  99. if (buffer) this._parseExtendedLength(buffer);
  100. break;
  101. case 3:
  102. buffer = this._reader.read(4);
  103. if (buffer) {
  104. this._stage = 4;
  105. this._frame.maskingKey = buffer;
  106. }
  107. break;
  108. case 4:
  109. buffer = this._reader.read(this._frame.length);
  110. if (buffer) {
  111. this._stage = 0;
  112. this._emitFrame(buffer);
  113. }
  114. break;
  115. default:
  116. buffer = null;
  117. }
  118. }
  119. },
  120. text: function(message) {
  121. if (this.readyState > 1) return false;
  122. return this.frame(message, 'text');
  123. },
  124. binary: function(message) {
  125. if (this.readyState > 1) return false;
  126. return this.frame(message, 'binary');
  127. },
  128. ping: function(message, callback) {
  129. if (this.readyState > 1) return false;
  130. message = message || '';
  131. if (callback) this._pingCallbacks[message] = callback;
  132. return this.frame(message, 'ping');
  133. },
  134. pong: function(message) {
  135. if (this.readyState > 1) return false;
  136. message = message ||'';
  137. return this.frame(message, 'pong');
  138. },
  139. close: function(reason, code) {
  140. reason = reason || '';
  141. code = code || this.ERRORS.normal_closure;
  142. if (this.readyState <= 0) {
  143. this.readyState = 3;
  144. this.emit('close', new Base.CloseEvent(code, reason));
  145. return true;
  146. } else if (this.readyState === 1) {
  147. this.readyState = 2;
  148. this._extensions.close(function() { this.frame(reason, 'close', code) }, this);
  149. return true;
  150. } else {
  151. return false;
  152. }
  153. },
  154. frame: function(buffer, type, code) {
  155. if (this.readyState <= 0) return this._queue([buffer, type, code]);
  156. if (this.readyState > 2) return false;
  157. if (buffer instanceof Array) buffer = Buffer.from(buffer);
  158. if (typeof buffer === 'number') buffer = buffer.toString();
  159. var message = new Message(),
  160. isText = (typeof buffer === 'string'),
  161. payload, copy;
  162. message.rsv1 = message.rsv2 = message.rsv3 = false;
  163. message.opcode = this.OPCODES[type || (isText ? 'text' : 'binary')];
  164. payload = isText ? Buffer.from(buffer, 'utf8') : buffer;
  165. if (code) {
  166. copy = payload;
  167. payload = Buffer.allocUnsafe(2 + copy.length);
  168. payload.writeUInt16BE(code, 0);
  169. copy.copy(payload, 2);
  170. }
  171. message.data = payload;
  172. var onMessageReady = function(message) {
  173. var frame = new Frame();
  174. frame.final = true;
  175. frame.rsv1 = message.rsv1;
  176. frame.rsv2 = message.rsv2;
  177. frame.rsv3 = message.rsv3;
  178. frame.opcode = message.opcode;
  179. frame.masked = !!this._masking;
  180. frame.length = message.data.length;
  181. frame.payload = message.data;
  182. if (frame.masked) frame.maskingKey = crypto.randomBytes(4);
  183. this._sendFrame(frame);
  184. };
  185. if (this.MESSAGE_OPCODES.indexOf(message.opcode) >= 0)
  186. this._extensions.processOutgoingMessage(message, function(error, message) {
  187. if (error) return this._fail('extension_error', error.message);
  188. onMessageReady.call(this, message);
  189. }, this);
  190. else
  191. onMessageReady.call(this, message);
  192. return true;
  193. },
  194. _sendFrame: function(frame) {
  195. var length = frame.length,
  196. header = (length <= 125) ? 2 : (length <= 65535 ? 4 : 10),
  197. offset = header + (frame.masked ? 4 : 0),
  198. buffer = Buffer.allocUnsafe(offset + length),
  199. masked = frame.masked ? this.MASK : 0;
  200. buffer[0] = (frame.final ? this.FIN : 0) |
  201. (frame.rsv1 ? this.RSV1 : 0) |
  202. (frame.rsv2 ? this.RSV2 : 0) |
  203. (frame.rsv3 ? this.RSV3 : 0) |
  204. frame.opcode;
  205. if (length <= 125) {
  206. buffer[1] = masked | length;
  207. } else if (length <= 65535) {
  208. buffer[1] = masked | 126;
  209. buffer.writeUInt16BE(length, 2);
  210. } else {
  211. buffer[1] = masked | 127;
  212. buffer.writeUInt32BE(Math.floor(length / 0x100000000), 2);
  213. buffer.writeUInt32BE(length % 0x100000000, 6);
  214. }
  215. frame.payload.copy(buffer, offset);
  216. if (frame.masked) {
  217. frame.maskingKey.copy(buffer, header);
  218. Hybi.mask(buffer, frame.maskingKey, offset);
  219. }
  220. this._write(buffer);
  221. },
  222. _handshakeResponse: function() {
  223. var secKey = this._request.headers['sec-websocket-key'],
  224. version = this._request.headers['sec-websocket-version'];
  225. if (version !== Hybi.VERSION)
  226. throw new Error('Unsupported WebSocket version: ' + version);
  227. if (typeof secKey !== 'string')
  228. throw new Error('Missing handshake request header: Sec-WebSocket-Key');
  229. this._headers.set('Upgrade', 'websocket');
  230. this._headers.set('Connection', 'Upgrade');
  231. this._headers.set('Sec-WebSocket-Accept', Hybi.generateAccept(secKey));
  232. if (this.protocol) this._headers.set('Sec-WebSocket-Protocol', this.protocol);
  233. var extensions = this._extensions.generateResponse(this._request.headers['sec-websocket-extensions']);
  234. if (extensions) this._headers.set('Sec-WebSocket-Extensions', extensions);
  235. var start = 'HTTP/1.1 101 Switching Protocols',
  236. headers = [start, this._headers.toString(), ''];
  237. return Buffer.from(headers.join('\r\n'), 'utf8');
  238. },
  239. _shutdown: function(code, reason, error) {
  240. delete this._frame;
  241. delete this._message;
  242. this._stage = 5;
  243. var sendCloseFrame = (this.readyState === 1);
  244. this.readyState = 2;
  245. this._extensions.close(function() {
  246. if (sendCloseFrame) this.frame(reason, 'close', code);
  247. this.readyState = 3;
  248. if (error) this.emit('error', new Error(reason));
  249. this.emit('close', new Base.CloseEvent(code, reason));
  250. }, this);
  251. },
  252. _fail: function(type, message) {
  253. if (this.readyState > 1) return;
  254. this._shutdown(this.ERRORS[type], message, true);
  255. },
  256. _parseOpcode: function(octet) {
  257. var rsvs = [this.RSV1, this.RSV2, this.RSV3].map(function(rsv) {
  258. return (octet & rsv) === rsv;
  259. });
  260. var frame = this._frame = new Frame();
  261. frame.final = (octet & this.FIN) === this.FIN;
  262. frame.rsv1 = rsvs[0];
  263. frame.rsv2 = rsvs[1];
  264. frame.rsv3 = rsvs[2];
  265. frame.opcode = (octet & this.OPCODE);
  266. this._stage = 1;
  267. if (!this._extensions.validFrameRsv(frame))
  268. return this._fail('protocol_error',
  269. 'One or more reserved bits are on: reserved1 = ' + (frame.rsv1 ? 1 : 0) +
  270. ', reserved2 = ' + (frame.rsv2 ? 1 : 0) +
  271. ', reserved3 = ' + (frame.rsv3 ? 1 : 0));
  272. if (this.OPCODE_CODES.indexOf(frame.opcode) < 0)
  273. return this._fail('protocol_error', 'Unrecognized frame opcode: ' + frame.opcode);
  274. if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && !frame.final)
  275. return this._fail('protocol_error', 'Received fragmented control frame: opcode = ' + frame.opcode);
  276. if (this._message && this.OPENING_OPCODES.indexOf(frame.opcode) >= 0)
  277. return this._fail('protocol_error', 'Received new data frame but previous continuous frame is unfinished');
  278. },
  279. _parseLength: function(octet) {
  280. var frame = this._frame;
  281. frame.masked = (octet & this.MASK) === this.MASK;
  282. frame.length = (octet & this.LENGTH);
  283. if (frame.length >= 0 && frame.length <= 125) {
  284. this._stage = frame.masked ? 3 : 4;
  285. if (!this._checkFrameLength()) return;
  286. } else {
  287. this._stage = 2;
  288. frame.lengthBytes = (frame.length === 126 ? 2 : 8);
  289. }
  290. if (this._requireMasking && !frame.masked)
  291. return this._fail('unacceptable', 'Received unmasked frame but masking is required');
  292. },
  293. _parseExtendedLength: function(buffer) {
  294. var frame = this._frame;
  295. frame.length = this._readUInt(buffer);
  296. this._stage = frame.masked ? 3 : 4;
  297. if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && frame.length > 125)
  298. return this._fail('protocol_error', 'Received control frame having too long payload: ' + frame.length);
  299. if (!this._checkFrameLength()) return;
  300. },
  301. _checkFrameLength: function() {
  302. var length = this._message ? this._message.length : 0;
  303. if (length + this._frame.length > this._maxLength) {
  304. this._fail('too_large', 'WebSocket frame length too large');
  305. return false;
  306. } else {
  307. return true;
  308. }
  309. },
  310. _emitFrame: function(buffer) {
  311. var frame = this._frame,
  312. payload = frame.payload = Hybi.mask(buffer, frame.maskingKey),
  313. opcode = frame.opcode,
  314. message,
  315. code, reason,
  316. callbacks, callback;
  317. delete this._frame;
  318. if (opcode === this.OPCODES.continuation) {
  319. if (!this._message) return this._fail('protocol_error', 'Received unexpected continuation frame');
  320. this._message.pushFrame(frame);
  321. }
  322. if (opcode === this.OPCODES.text || opcode === this.OPCODES.binary) {
  323. this._message = new Message();
  324. this._message.pushFrame(frame);
  325. }
  326. if (frame.final && this.MESSAGE_OPCODES.indexOf(opcode) >= 0)
  327. return this._emitMessage(this._message);
  328. if (opcode === this.OPCODES.close) {
  329. code = (payload.length >= 2) ? payload.readUInt16BE(0) : null;
  330. reason = (payload.length > 2) ? this._encode(payload.slice(2)) : null;
  331. if (!(payload.length === 0) &&
  332. !(code !== null && code >= this.MIN_RESERVED_ERROR && code <= this.MAX_RESERVED_ERROR) &&
  333. this.ERROR_CODES.indexOf(code) < 0)
  334. code = this.ERRORS.protocol_error;
  335. if (payload.length > 125 || (payload.length > 2 && !reason))
  336. code = this.ERRORS.protocol_error;
  337. this._shutdown(code || this.DEFAULT_ERROR_CODE, reason || '');
  338. }
  339. if (opcode === this.OPCODES.ping) {
  340. this.frame(payload, 'pong');
  341. this.emit('ping', new Base.PingEvent(payload.toString()))
  342. }
  343. if (opcode === this.OPCODES.pong) {
  344. callbacks = this._pingCallbacks;
  345. message = this._encode(payload);
  346. callback = callbacks[message];
  347. delete callbacks[message];
  348. if (callback) callback()
  349. this.emit('pong', new Base.PongEvent(payload.toString()))
  350. }
  351. },
  352. _emitMessage: function(message) {
  353. var message = this._message;
  354. message.read();
  355. delete this._message;
  356. this._extensions.processIncomingMessage(message, function(error, message) {
  357. if (error) return this._fail('extension_error', error.message);
  358. var payload = message.data;
  359. if (message.opcode === this.OPCODES.text) payload = this._encode(payload);
  360. if (payload === null)
  361. return this._fail('encoding_error', 'Could not decode a text frame as UTF-8');
  362. else
  363. this.emit('message', new Base.MessageEvent(payload));
  364. }, this);
  365. },
  366. _encode: function(buffer) {
  367. try {
  368. var string = buffer.toString('binary', 0, buffer.length);
  369. if (!this.UTF8_MATCH.test(string)) return null;
  370. } catch (e) {}
  371. return buffer.toString('utf8', 0, buffer.length);
  372. },
  373. _readUInt: function(buffer) {
  374. if (buffer.length === 2) return buffer.readUInt16BE(0);
  375. return buffer.readUInt32BE(0) * 0x100000000 +
  376. buffer.readUInt32BE(4);
  377. }
  378. };
  379. for (var key in instance)
  380. Hybi.prototype[key] = instance[key];
  381. module.exports = Hybi;