receiver.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. 'use strict';
  2. const stream = require('stream');
  3. const PerMessageDeflate = require('./permessage-deflate');
  4. const bufferUtil = require('./buffer-util');
  5. const validation = require('./validation');
  6. const constants = require('./constants');
  7. const GET_INFO = 0;
  8. const GET_PAYLOAD_LENGTH_16 = 1;
  9. const GET_PAYLOAD_LENGTH_64 = 2;
  10. const GET_MASK = 3;
  11. const GET_DATA = 4;
  12. const INFLATING = 5;
  13. /**
  14. * HyBi Receiver implementation.
  15. *
  16. * @extends stream.Writable
  17. */
  18. class Receiver extends stream.Writable {
  19. /**
  20. * Creates a Receiver instance.
  21. *
  22. * @param {String} binaryType The type for binary data
  23. * @param {Object} extensions An object containing the negotiated extensions
  24. * @param {Number} maxPayload The maximum allowed message length
  25. */
  26. constructor(binaryType, extensions, maxPayload) {
  27. super();
  28. this._binaryType = binaryType || constants.BINARY_TYPES[0];
  29. this[constants.kWebSocket] = undefined;
  30. this._extensions = extensions || {};
  31. this._maxPayload = maxPayload | 0;
  32. this._bufferedBytes = 0;
  33. this._buffers = [];
  34. this._compressed = false;
  35. this._payloadLength = 0;
  36. this._mask = undefined;
  37. this._fragmented = 0;
  38. this._masked = false;
  39. this._fin = false;
  40. this._opcode = 0;
  41. this._totalPayloadLength = 0;
  42. this._messageLength = 0;
  43. this._fragments = [];
  44. this._state = GET_INFO;
  45. this._loop = false;
  46. }
  47. /**
  48. * Implements `Writable.prototype._write()`.
  49. *
  50. * @param {Buffer} chunk The chunk of data to write
  51. * @param {String} encoding The character encoding of `chunk`
  52. * @param {Function} cb Callback
  53. */
  54. _write(chunk, encoding, cb) {
  55. if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
  56. this._bufferedBytes += chunk.length;
  57. this._buffers.push(chunk);
  58. this.startLoop(cb);
  59. }
  60. /**
  61. * Consumes `n` bytes from the buffered data.
  62. *
  63. * @param {Number} n The number of bytes to consume
  64. * @return {Buffer} The consumed bytes
  65. * @private
  66. */
  67. consume(n) {
  68. this._bufferedBytes -= n;
  69. if (n === this._buffers[0].length) return this._buffers.shift();
  70. if (n < this._buffers[0].length) {
  71. const buf = this._buffers[0];
  72. this._buffers[0] = buf.slice(n);
  73. return buf.slice(0, n);
  74. }
  75. const dst = Buffer.allocUnsafe(n);
  76. do {
  77. const buf = this._buffers[0];
  78. if (n >= buf.length) {
  79. this._buffers.shift().copy(dst, dst.length - n);
  80. } else {
  81. buf.copy(dst, dst.length - n, 0, n);
  82. this._buffers[0] = buf.slice(n);
  83. }
  84. n -= buf.length;
  85. } while (n > 0);
  86. return dst;
  87. }
  88. /**
  89. * Starts the parsing loop.
  90. *
  91. * @param {Function} cb Callback
  92. * @private
  93. */
  94. startLoop(cb) {
  95. var err;
  96. this._loop = true;
  97. do {
  98. switch (this._state) {
  99. case GET_INFO:
  100. err = this.getInfo();
  101. break;
  102. case GET_PAYLOAD_LENGTH_16:
  103. err = this.getPayloadLength16();
  104. break;
  105. case GET_PAYLOAD_LENGTH_64:
  106. err = this.getPayloadLength64();
  107. break;
  108. case GET_MASK:
  109. this.getMask();
  110. break;
  111. case GET_DATA:
  112. err = this.getData(cb);
  113. break;
  114. default:
  115. // `INFLATING`
  116. this._loop = false;
  117. return;
  118. }
  119. } while (this._loop);
  120. cb(err);
  121. }
  122. /**
  123. * Reads the first two bytes of a frame.
  124. *
  125. * @return {(RangeError|undefined)} A possible error
  126. * @private
  127. */
  128. getInfo() {
  129. if (this._bufferedBytes < 2) {
  130. this._loop = false;
  131. return;
  132. }
  133. const buf = this.consume(2);
  134. if ((buf[0] & 0x30) !== 0x00) {
  135. this._loop = false;
  136. return error(RangeError, 'RSV2 and RSV3 must be clear', true, 1002);
  137. }
  138. const compressed = (buf[0] & 0x40) === 0x40;
  139. if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
  140. this._loop = false;
  141. return error(RangeError, 'RSV1 must be clear', true, 1002);
  142. }
  143. this._fin = (buf[0] & 0x80) === 0x80;
  144. this._opcode = buf[0] & 0x0f;
  145. this._payloadLength = buf[1] & 0x7f;
  146. if (this._opcode === 0x00) {
  147. if (compressed) {
  148. this._loop = false;
  149. return error(RangeError, 'RSV1 must be clear', true, 1002);
  150. }
  151. if (!this._fragmented) {
  152. this._loop = false;
  153. return error(RangeError, 'invalid opcode 0', true, 1002);
  154. }
  155. this._opcode = this._fragmented;
  156. } else if (this._opcode === 0x01 || this._opcode === 0x02) {
  157. if (this._fragmented) {
  158. this._loop = false;
  159. return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
  160. }
  161. this._compressed = compressed;
  162. } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
  163. if (!this._fin) {
  164. this._loop = false;
  165. return error(RangeError, 'FIN must be set', true, 1002);
  166. }
  167. if (compressed) {
  168. this._loop = false;
  169. return error(RangeError, 'RSV1 must be clear', true, 1002);
  170. }
  171. if (this._payloadLength > 0x7d) {
  172. this._loop = false;
  173. return error(
  174. RangeError,
  175. `invalid payload length ${this._payloadLength}`,
  176. true,
  177. 1002
  178. );
  179. }
  180. } else {
  181. this._loop = false;
  182. return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
  183. }
  184. if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
  185. this._masked = (buf[1] & 0x80) === 0x80;
  186. if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
  187. else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
  188. else return this.haveLength();
  189. }
  190. /**
  191. * Gets extended payload length (7+16).
  192. *
  193. * @return {(RangeError|undefined)} A possible error
  194. * @private
  195. */
  196. getPayloadLength16() {
  197. if (this._bufferedBytes < 2) {
  198. this._loop = false;
  199. return;
  200. }
  201. this._payloadLength = this.consume(2).readUInt16BE(0);
  202. return this.haveLength();
  203. }
  204. /**
  205. * Gets extended payload length (7+64).
  206. *
  207. * @return {(RangeError|undefined)} A possible error
  208. * @private
  209. */
  210. getPayloadLength64() {
  211. if (this._bufferedBytes < 8) {
  212. this._loop = false;
  213. return;
  214. }
  215. const buf = this.consume(8);
  216. const num = buf.readUInt32BE(0);
  217. //
  218. // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
  219. // if payload length is greater than this number.
  220. //
  221. if (num > Math.pow(2, 53 - 32) - 1) {
  222. this._loop = false;
  223. return error(
  224. RangeError,
  225. 'Unsupported WebSocket frame: payload length > 2^53 - 1',
  226. false,
  227. 1009
  228. );
  229. }
  230. this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
  231. return this.haveLength();
  232. }
  233. /**
  234. * Payload length has been read.
  235. *
  236. * @return {(RangeError|undefined)} A possible error
  237. * @private
  238. */
  239. haveLength() {
  240. if (this._payloadLength && this._opcode < 0x08) {
  241. this._totalPayloadLength += this._payloadLength;
  242. if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
  243. this._loop = false;
  244. return error(RangeError, 'Max payload size exceeded', false, 1009);
  245. }
  246. }
  247. if (this._masked) this._state = GET_MASK;
  248. else this._state = GET_DATA;
  249. }
  250. /**
  251. * Reads mask bytes.
  252. *
  253. * @private
  254. */
  255. getMask() {
  256. if (this._bufferedBytes < 4) {
  257. this._loop = false;
  258. return;
  259. }
  260. this._mask = this.consume(4);
  261. this._state = GET_DATA;
  262. }
  263. /**
  264. * Reads data bytes.
  265. *
  266. * @param {Function} cb Callback
  267. * @return {(Error|RangeError|undefined)} A possible error
  268. * @private
  269. */
  270. getData(cb) {
  271. var data = constants.EMPTY_BUFFER;
  272. if (this._payloadLength) {
  273. if (this._bufferedBytes < this._payloadLength) {
  274. this._loop = false;
  275. return;
  276. }
  277. data = this.consume(this._payloadLength);
  278. if (this._masked) bufferUtil.unmask(data, this._mask);
  279. }
  280. if (this._opcode > 0x07) return this.controlMessage(data);
  281. if (this._compressed) {
  282. this._state = INFLATING;
  283. this.decompress(data, cb);
  284. return;
  285. }
  286. if (data.length) {
  287. //
  288. // This message is not compressed so its lenght is the sum of the payload
  289. // length of all fragments.
  290. //
  291. this._messageLength = this._totalPayloadLength;
  292. this._fragments.push(data);
  293. }
  294. return this.dataMessage();
  295. }
  296. /**
  297. * Decompresses data.
  298. *
  299. * @param {Buffer} data Compressed data
  300. * @param {Function} cb Callback
  301. * @private
  302. */
  303. decompress(data, cb) {
  304. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  305. perMessageDeflate.decompress(data, this._fin, (err, buf) => {
  306. if (err) return cb(err);
  307. if (buf.length) {
  308. this._messageLength += buf.length;
  309. if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
  310. return cb(
  311. error(RangeError, 'Max payload size exceeded', false, 1009)
  312. );
  313. }
  314. this._fragments.push(buf);
  315. }
  316. const er = this.dataMessage();
  317. if (er) return cb(er);
  318. this.startLoop(cb);
  319. });
  320. }
  321. /**
  322. * Handles a data message.
  323. *
  324. * @return {(Error|undefined)} A possible error
  325. * @private
  326. */
  327. dataMessage() {
  328. if (this._fin) {
  329. const messageLength = this._messageLength;
  330. const fragments = this._fragments;
  331. this._totalPayloadLength = 0;
  332. this._messageLength = 0;
  333. this._fragmented = 0;
  334. this._fragments = [];
  335. if (this._opcode === 2) {
  336. var data;
  337. if (this._binaryType === 'nodebuffer') {
  338. data = toBuffer(fragments, messageLength);
  339. } else if (this._binaryType === 'arraybuffer') {
  340. data = toArrayBuffer(toBuffer(fragments, messageLength));
  341. } else {
  342. data = fragments;
  343. }
  344. this.emit('message', data);
  345. } else {
  346. const buf = toBuffer(fragments, messageLength);
  347. if (!validation.isValidUTF8(buf)) {
  348. this._loop = false;
  349. return error(Error, 'invalid UTF-8 sequence', true, 1007);
  350. }
  351. this.emit('message', buf.toString());
  352. }
  353. }
  354. this._state = GET_INFO;
  355. }
  356. /**
  357. * Handles a control message.
  358. *
  359. * @param {Buffer} data Data to handle
  360. * @return {(Error|RangeError|undefined)} A possible error
  361. * @private
  362. */
  363. controlMessage(data) {
  364. if (this._opcode === 0x08) {
  365. this._loop = false;
  366. if (data.length === 0) {
  367. this.emit('conclude', 1005, '');
  368. this.end();
  369. } else if (data.length === 1) {
  370. return error(RangeError, 'invalid payload length 1', true, 1002);
  371. } else {
  372. const code = data.readUInt16BE(0);
  373. if (!validation.isValidStatusCode(code)) {
  374. return error(RangeError, `invalid status code ${code}`, true, 1002);
  375. }
  376. const buf = data.slice(2);
  377. if (!validation.isValidUTF8(buf)) {
  378. return error(Error, 'invalid UTF-8 sequence', true, 1007);
  379. }
  380. this.emit('conclude', code, buf.toString());
  381. this.end();
  382. }
  383. } else if (this._opcode === 0x09) {
  384. this.emit('ping', data);
  385. } else {
  386. this.emit('pong', data);
  387. }
  388. this._state = GET_INFO;
  389. }
  390. }
  391. module.exports = Receiver;
  392. /**
  393. * Builds an error object.
  394. *
  395. * @param {(Error|RangeError)} ErrorCtor The error constructor
  396. * @param {String} message The error message
  397. * @param {Boolean} prefix Specifies whether or not to add a default prefix to
  398. * `message`
  399. * @param {Number} statusCode The status code
  400. * @return {(Error|RangeError)} The error
  401. * @private
  402. */
  403. function error(ErrorCtor, message, prefix, statusCode) {
  404. const err = new ErrorCtor(
  405. prefix ? `Invalid WebSocket frame: ${message}` : message
  406. );
  407. Error.captureStackTrace(err, error);
  408. err[constants.kStatusCode] = statusCode;
  409. return err;
  410. }
  411. /**
  412. * Makes a buffer from a list of fragments.
  413. *
  414. * @param {Buffer[]} fragments The list of fragments composing the message
  415. * @param {Number} messageLength The length of the message
  416. * @return {Buffer}
  417. * @private
  418. */
  419. function toBuffer(fragments, messageLength) {
  420. if (fragments.length === 1) return fragments[0];
  421. if (fragments.length > 1) return bufferUtil.concat(fragments, messageLength);
  422. return constants.EMPTY_BUFFER;
  423. }
  424. /**
  425. * Converts a buffer to an `ArrayBuffer`.
  426. *
  427. * @param {Buffer} buf The buffer to convert
  428. * @return {ArrayBuffer} Converted buffer
  429. */
  430. function toArrayBuffer(buf) {
  431. if (buf.byteLength === buf.buffer.byteLength) {
  432. return buf.buffer;
  433. }
  434. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
  435. }