Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

receiver.js 12KB

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