receiver.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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) 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: // `INFLATING`
  115. this._loop = false;
  116. return;
  117. }
  118. } while (this._loop);
  119. cb(err);
  120. }
  121. /**
  122. * Reads the first two bytes of a frame.
  123. *
  124. * @return {(RangeError|undefined)} A possible error
  125. * @private
  126. */
  127. getInfo () {
  128. if (this._bufferedBytes < 2) {
  129. this._loop = false;
  130. return;
  131. }
  132. const buf = this.consume(2);
  133. if ((buf[0] & 0x30) !== 0x00) {
  134. this._loop = false;
  135. return error(RangeError, 'RSV2 and RSV3 must be clear', true, 1002);
  136. }
  137. const compressed = (buf[0] & 0x40) === 0x40;
  138. if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
  139. this._loop = false;
  140. return error(RangeError, 'RSV1 must be clear', true, 1002);
  141. }
  142. this._fin = (buf[0] & 0x80) === 0x80;
  143. this._opcode = buf[0] & 0x0f;
  144. this._payloadLength = buf[1] & 0x7f;
  145. if (this._opcode === 0x00) {
  146. if (compressed) {
  147. this._loop = false;
  148. return error(RangeError, 'RSV1 must be clear', true, 1002);
  149. }
  150. if (!this._fragmented) {
  151. this._loop = false;
  152. return error(RangeError, 'invalid opcode 0', true, 1002);
  153. }
  154. this._opcode = this._fragmented;
  155. } else if (this._opcode === 0x01 || this._opcode === 0x02) {
  156. if (this._fragmented) {
  157. this._loop = false;
  158. return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
  159. }
  160. this._compressed = compressed;
  161. } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
  162. if (!this._fin) {
  163. this._loop = false;
  164. return error(RangeError, 'FIN must be set', true, 1002);
  165. }
  166. if (compressed) {
  167. this._loop = false;
  168. return error(RangeError, 'RSV1 must be clear', true, 1002);
  169. }
  170. if (this._payloadLength > 0x7d) {
  171. this._loop = false;
  172. return error(
  173. RangeError,
  174. `invalid payload length ${this._payloadLength}`,
  175. true,
  176. 1002
  177. );
  178. }
  179. } else {
  180. this._loop = false;
  181. return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
  182. }
  183. if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
  184. this._masked = (buf[1] & 0x80) === 0x80;
  185. if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
  186. else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
  187. else return this.haveLength();
  188. }
  189. /**
  190. * Gets extended payload length (7+16).
  191. *
  192. * @return {(RangeError|undefined)} A possible error
  193. * @private
  194. */
  195. getPayloadLength16 () {
  196. if (this._bufferedBytes < 2) {
  197. this._loop = false;
  198. return;
  199. }
  200. this._payloadLength = this.consume(2).readUInt16BE(0);
  201. return this.haveLength();
  202. }
  203. /**
  204. * Gets extended payload length (7+64).
  205. *
  206. * @return {(RangeError|undefined)} A possible error
  207. * @private
  208. */
  209. getPayloadLength64 () {
  210. if (this._bufferedBytes < 8) {
  211. this._loop = false;
  212. return;
  213. }
  214. const buf = this.consume(8);
  215. const num = buf.readUInt32BE(0);
  216. //
  217. // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
  218. // if payload length is greater than this number.
  219. //
  220. if (num > Math.pow(2, 53 - 32) - 1) {
  221. this._loop = false;
  222. return error(
  223. RangeError,
  224. 'Unsupported WebSocket frame: payload length > 2^53 - 1',
  225. false,
  226. 1009
  227. );
  228. }
  229. this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
  230. return this.haveLength();
  231. }
  232. /**
  233. * Payload length has been read.
  234. *
  235. * @return {(RangeError|undefined)} A possible error
  236. * @private
  237. */
  238. haveLength () {
  239. if (this._payloadLength && this._opcode < 0x08) {
  240. this._totalPayloadLength += this._payloadLength;
  241. if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
  242. this._loop = false;
  243. return error(RangeError, 'Max payload size exceeded', false, 1009);
  244. }
  245. }
  246. if (this._masked) this._state = GET_MASK;
  247. else this._state = GET_DATA;
  248. }
  249. /**
  250. * Reads mask bytes.
  251. *
  252. * @private
  253. */
  254. getMask () {
  255. if (this._bufferedBytes < 4) {
  256. this._loop = false;
  257. return;
  258. }
  259. this._mask = this.consume(4);
  260. this._state = GET_DATA;
  261. }
  262. /**
  263. * Reads data bytes.
  264. *
  265. * @param {Function} cb Callback
  266. * @return {(Error|RangeError|undefined)} A possible error
  267. * @private
  268. */
  269. getData (cb) {
  270. var data = constants.EMPTY_BUFFER;
  271. if (this._payloadLength) {
  272. if (this._bufferedBytes < this._payloadLength) {
  273. this._loop = false;
  274. return;
  275. }
  276. data = this.consume(this._payloadLength);
  277. if (this._masked) bufferUtil.unmask(data, this._mask);
  278. }
  279. if (this._opcode > 0x07) return this.controlMessage(data);
  280. if (this._compressed) {
  281. this._state = INFLATING;
  282. this.decompress(data, cb);
  283. return;
  284. }
  285. if (data.length) {
  286. //
  287. // This message is not compressed so its lenght is the sum of the payload
  288. // length of all fragments.
  289. //
  290. this._messageLength = this._totalPayloadLength;
  291. this._fragments.push(data);
  292. }
  293. return this.dataMessage();
  294. }
  295. /**
  296. * Decompresses data.
  297. *
  298. * @param {Buffer} data Compressed data
  299. * @param {Function} cb Callback
  300. * @private
  301. */
  302. decompress (data, cb) {
  303. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  304. perMessageDeflate.decompress(data, this._fin, (err, buf) => {
  305. if (err) return cb(err);
  306. if (buf.length) {
  307. this._messageLength += buf.length;
  308. if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
  309. return cb(error(RangeError, 'Max payload size exceeded', false, 1009));
  310. }
  311. this._fragments.push(buf);
  312. }
  313. const er = this.dataMessage();
  314. if (er) return cb(er);
  315. this.startLoop(cb);
  316. });
  317. }
  318. /**
  319. * Handles a data message.
  320. *
  321. * @return {(Error|undefined)} A possible error
  322. * @private
  323. */
  324. dataMessage () {
  325. if (this._fin) {
  326. const messageLength = this._messageLength;
  327. const fragments = this._fragments;
  328. this._totalPayloadLength = 0;
  329. this._messageLength = 0;
  330. this._fragmented = 0;
  331. this._fragments = [];
  332. if (this._opcode === 2) {
  333. var data;
  334. if (this._binaryType === 'nodebuffer') {
  335. data = toBuffer(fragments, messageLength);
  336. } else if (this._binaryType === 'arraybuffer') {
  337. data = toArrayBuffer(toBuffer(fragments, messageLength));
  338. } else {
  339. data = fragments;
  340. }
  341. this.emit('message', data);
  342. } else {
  343. const buf = toBuffer(fragments, messageLength);
  344. if (!validation.isValidUTF8(buf)) {
  345. this._loop = false;
  346. return error(Error, 'invalid UTF-8 sequence', true, 1007);
  347. }
  348. this.emit('message', buf.toString());
  349. }
  350. }
  351. this._state = GET_INFO;
  352. }
  353. /**
  354. * Handles a control message.
  355. *
  356. * @param {Buffer} data Data to handle
  357. * @return {(Error|RangeError|undefined)} A possible error
  358. * @private
  359. */
  360. controlMessage (data) {
  361. if (this._opcode === 0x08) {
  362. this._loop = false;
  363. if (data.length === 0) {
  364. this.emit('conclude', 1005, '');
  365. this.end();
  366. } else if (data.length === 1) {
  367. return error(RangeError, 'invalid payload length 1', true, 1002);
  368. } else {
  369. const code = data.readUInt16BE(0);
  370. if (!validation.isValidStatusCode(code)) {
  371. return error(RangeError, `invalid status code ${code}`, true, 1002);
  372. }
  373. const buf = data.slice(2);
  374. if (!validation.isValidUTF8(buf)) {
  375. return error(Error, 'invalid UTF-8 sequence', true, 1007);
  376. }
  377. this.emit('conclude', code, buf.toString());
  378. this.end();
  379. }
  380. return;
  381. }
  382. if (this._opcode === 0x09) this.emit('ping', data);
  383. else this.emit('pong', data);
  384. this._state = GET_INFO;
  385. }
  386. }
  387. module.exports = Receiver;
  388. /**
  389. * Builds an error object.
  390. *
  391. * @param {(Error|RangeError)} ErrorCtor The error constructor
  392. * @param {String} message The error message
  393. * @param {Boolean} prefix Specifies whether or not to add a default prefix to
  394. * `message`
  395. * @param {Number} statusCode The status code
  396. * @return {(Error|RangeError)} The error
  397. * @private
  398. */
  399. function error (ErrorCtor, message, prefix, statusCode) {
  400. const err = new ErrorCtor(
  401. prefix ? `Invalid WebSocket frame: ${message}` : message
  402. );
  403. Error.captureStackTrace(err, error);
  404. err[constants.kStatusCode] = statusCode;
  405. return err;
  406. }
  407. /**
  408. * Makes a buffer from a list of fragments.
  409. *
  410. * @param {Buffer[]} fragments The list of fragments composing the message
  411. * @param {Number} messageLength The length of the message
  412. * @return {Buffer}
  413. * @private
  414. */
  415. function toBuffer (fragments, messageLength) {
  416. if (fragments.length === 1) return fragments[0];
  417. if (fragments.length > 1) return bufferUtil.concat(fragments, messageLength);
  418. return constants.EMPTY_BUFFER;
  419. }
  420. /**
  421. * Converts a buffer to an `ArrayBuffer`.
  422. *
  423. * @param {Buffer} The buffer to convert
  424. * @return {ArrayBuffer} Converted buffer
  425. */
  426. function toArrayBuffer (buf) {
  427. if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
  428. return buf.buffer;
  429. }
  430. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
  431. }