sender.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */
  2. 'use strict';
  3. const { Duplex } = require('stream');
  4. const { randomFillSync } = require('crypto');
  5. const PerMessageDeflate = require('./permessage-deflate');
  6. const { EMPTY_BUFFER } = require('./constants');
  7. const { isValidStatusCode } = require('./validation');
  8. const { mask: applyMask, toBuffer } = require('./buffer-util');
  9. const kByteLength = Symbol('kByteLength');
  10. const maskBuffer = Buffer.alloc(4);
  11. /**
  12. * HyBi Sender implementation.
  13. */
  14. class Sender {
  15. /**
  16. * Creates a Sender instance.
  17. *
  18. * @param {Duplex} socket The connection socket
  19. * @param {Object} [extensions] An object containing the negotiated extensions
  20. * @param {Function} [generateMask] The function used to generate the masking
  21. * key
  22. */
  23. constructor(socket, extensions, generateMask) {
  24. this._extensions = extensions || {};
  25. if (generateMask) {
  26. this._generateMask = generateMask;
  27. this._maskBuffer = Buffer.alloc(4);
  28. }
  29. this._socket = socket;
  30. this._firstFragment = true;
  31. this._compress = false;
  32. this._bufferedBytes = 0;
  33. this._deflating = false;
  34. this._queue = [];
  35. }
  36. /**
  37. * Frames a piece of data according to the HyBi WebSocket protocol.
  38. *
  39. * @param {(Buffer|String)} data The data to frame
  40. * @param {Object} options Options object
  41. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  42. * FIN bit
  43. * @param {Function} [options.generateMask] The function used to generate the
  44. * masking key
  45. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  46. * `data`
  47. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  48. * key
  49. * @param {Number} options.opcode The opcode
  50. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  51. * modified
  52. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  53. * RSV1 bit
  54. * @return {(Buffer|String)[]} The framed data
  55. * @public
  56. */
  57. static frame(data, options) {
  58. let mask;
  59. let merge = false;
  60. let offset = 2;
  61. let skipMasking = false;
  62. if (options.mask) {
  63. mask = options.maskBuffer || maskBuffer;
  64. if (options.generateMask) {
  65. options.generateMask(mask);
  66. } else {
  67. randomFillSync(mask, 0, 4);
  68. }
  69. skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
  70. offset = 6;
  71. }
  72. let dataLength;
  73. if (typeof data === 'string') {
  74. if (
  75. (!options.mask || skipMasking) &&
  76. options[kByteLength] !== undefined
  77. ) {
  78. dataLength = options[kByteLength];
  79. } else {
  80. data = Buffer.from(data);
  81. dataLength = data.length;
  82. }
  83. } else {
  84. dataLength = data.length;
  85. merge = options.mask && options.readOnly && !skipMasking;
  86. }
  87. let payloadLength = dataLength;
  88. if (dataLength >= 65536) {
  89. offset += 8;
  90. payloadLength = 127;
  91. } else if (dataLength > 125) {
  92. offset += 2;
  93. payloadLength = 126;
  94. }
  95. const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
  96. target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
  97. if (options.rsv1) target[0] |= 0x40;
  98. target[1] = payloadLength;
  99. if (payloadLength === 126) {
  100. target.writeUInt16BE(dataLength, 2);
  101. } else if (payloadLength === 127) {
  102. target[2] = target[3] = 0;
  103. target.writeUIntBE(dataLength, 4, 6);
  104. }
  105. if (!options.mask) return [target, data];
  106. target[1] |= 0x80;
  107. target[offset - 4] = mask[0];
  108. target[offset - 3] = mask[1];
  109. target[offset - 2] = mask[2];
  110. target[offset - 1] = mask[3];
  111. if (skipMasking) return [target, data];
  112. if (merge) {
  113. applyMask(data, mask, target, offset, dataLength);
  114. return [target];
  115. }
  116. applyMask(data, mask, data, 0, dataLength);
  117. return [target, data];
  118. }
  119. /**
  120. * Sends a close message to the other peer.
  121. *
  122. * @param {Number} [code] The status code component of the body
  123. * @param {(String|Buffer)} [data] The message component of the body
  124. * @param {Boolean} [mask=false] Specifies whether or not to mask the message
  125. * @param {Function} [cb] Callback
  126. * @public
  127. */
  128. close(code, data, mask, cb) {
  129. let buf;
  130. if (code === undefined) {
  131. buf = EMPTY_BUFFER;
  132. } else if (typeof code !== 'number' || !isValidStatusCode(code)) {
  133. throw new TypeError('First argument must be a valid error code number');
  134. } else if (data === undefined || !data.length) {
  135. buf = Buffer.allocUnsafe(2);
  136. buf.writeUInt16BE(code, 0);
  137. } else {
  138. const length = Buffer.byteLength(data);
  139. if (length > 123) {
  140. throw new RangeError('The message must not be greater than 123 bytes');
  141. }
  142. buf = Buffer.allocUnsafe(2 + length);
  143. buf.writeUInt16BE(code, 0);
  144. if (typeof data === 'string') {
  145. buf.write(data, 2);
  146. } else {
  147. buf.set(data, 2);
  148. }
  149. }
  150. const options = {
  151. [kByteLength]: buf.length,
  152. fin: true,
  153. generateMask: this._generateMask,
  154. mask,
  155. maskBuffer: this._maskBuffer,
  156. opcode: 0x08,
  157. readOnly: false,
  158. rsv1: false
  159. };
  160. if (this._deflating) {
  161. this.enqueue([this.dispatch, buf, false, options, cb]);
  162. } else {
  163. this.sendFrame(Sender.frame(buf, options), cb);
  164. }
  165. }
  166. /**
  167. * Sends a ping message to the other peer.
  168. *
  169. * @param {*} data The message to send
  170. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  171. * @param {Function} [cb] Callback
  172. * @public
  173. */
  174. ping(data, mask, cb) {
  175. let byteLength;
  176. let readOnly;
  177. if (typeof data === 'string') {
  178. byteLength = Buffer.byteLength(data);
  179. readOnly = false;
  180. } else {
  181. data = toBuffer(data);
  182. byteLength = data.length;
  183. readOnly = toBuffer.readOnly;
  184. }
  185. if (byteLength > 125) {
  186. throw new RangeError('The data size must not be greater than 125 bytes');
  187. }
  188. const options = {
  189. [kByteLength]: byteLength,
  190. fin: true,
  191. generateMask: this._generateMask,
  192. mask,
  193. maskBuffer: this._maskBuffer,
  194. opcode: 0x09,
  195. readOnly,
  196. rsv1: false
  197. };
  198. if (this._deflating) {
  199. this.enqueue([this.dispatch, data, false, options, cb]);
  200. } else {
  201. this.sendFrame(Sender.frame(data, options), cb);
  202. }
  203. }
  204. /**
  205. * Sends a pong message to the other peer.
  206. *
  207. * @param {*} data The message to send
  208. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  209. * @param {Function} [cb] Callback
  210. * @public
  211. */
  212. pong(data, mask, cb) {
  213. let byteLength;
  214. let readOnly;
  215. if (typeof data === 'string') {
  216. byteLength = Buffer.byteLength(data);
  217. readOnly = false;
  218. } else {
  219. data = toBuffer(data);
  220. byteLength = data.length;
  221. readOnly = toBuffer.readOnly;
  222. }
  223. if (byteLength > 125) {
  224. throw new RangeError('The data size must not be greater than 125 bytes');
  225. }
  226. const options = {
  227. [kByteLength]: byteLength,
  228. fin: true,
  229. generateMask: this._generateMask,
  230. mask,
  231. maskBuffer: this._maskBuffer,
  232. opcode: 0x0a,
  233. readOnly,
  234. rsv1: false
  235. };
  236. if (this._deflating) {
  237. this.enqueue([this.dispatch, data, false, options, cb]);
  238. } else {
  239. this.sendFrame(Sender.frame(data, options), cb);
  240. }
  241. }
  242. /**
  243. * Sends a data message to the other peer.
  244. *
  245. * @param {*} data The message to send
  246. * @param {Object} options Options object
  247. * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
  248. * or text
  249. * @param {Boolean} [options.compress=false] Specifies whether or not to
  250. * compress `data`
  251. * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
  252. * last one
  253. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  254. * `data`
  255. * @param {Function} [cb] Callback
  256. * @public
  257. */
  258. send(data, options, cb) {
  259. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  260. let opcode = options.binary ? 2 : 1;
  261. let rsv1 = options.compress;
  262. let byteLength;
  263. let readOnly;
  264. if (typeof data === 'string') {
  265. byteLength = Buffer.byteLength(data);
  266. readOnly = false;
  267. } else {
  268. data = toBuffer(data);
  269. byteLength = data.length;
  270. readOnly = toBuffer.readOnly;
  271. }
  272. if (this._firstFragment) {
  273. this._firstFragment = false;
  274. if (
  275. rsv1 &&
  276. perMessageDeflate &&
  277. perMessageDeflate.params[
  278. perMessageDeflate._isServer
  279. ? 'server_no_context_takeover'
  280. : 'client_no_context_takeover'
  281. ]
  282. ) {
  283. rsv1 = byteLength >= perMessageDeflate._threshold;
  284. }
  285. this._compress = rsv1;
  286. } else {
  287. rsv1 = false;
  288. opcode = 0;
  289. }
  290. if (options.fin) this._firstFragment = true;
  291. if (perMessageDeflate) {
  292. const opts = {
  293. [kByteLength]: byteLength,
  294. fin: options.fin,
  295. generateMask: this._generateMask,
  296. mask: options.mask,
  297. maskBuffer: this._maskBuffer,
  298. opcode,
  299. readOnly,
  300. rsv1
  301. };
  302. if (this._deflating) {
  303. this.enqueue([this.dispatch, data, this._compress, opts, cb]);
  304. } else {
  305. this.dispatch(data, this._compress, opts, cb);
  306. }
  307. } else {
  308. this.sendFrame(
  309. Sender.frame(data, {
  310. [kByteLength]: byteLength,
  311. fin: options.fin,
  312. generateMask: this._generateMask,
  313. mask: options.mask,
  314. maskBuffer: this._maskBuffer,
  315. opcode,
  316. readOnly,
  317. rsv1: false
  318. }),
  319. cb
  320. );
  321. }
  322. }
  323. /**
  324. * Dispatches a message.
  325. *
  326. * @param {(Buffer|String)} data The message to send
  327. * @param {Boolean} [compress=false] Specifies whether or not to compress
  328. * `data`
  329. * @param {Object} options Options object
  330. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  331. * FIN bit
  332. * @param {Function} [options.generateMask] The function used to generate the
  333. * masking key
  334. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  335. * `data`
  336. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  337. * key
  338. * @param {Number} options.opcode The opcode
  339. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  340. * modified
  341. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  342. * RSV1 bit
  343. * @param {Function} [cb] Callback
  344. * @private
  345. */
  346. dispatch(data, compress, options, cb) {
  347. if (!compress) {
  348. this.sendFrame(Sender.frame(data, options), cb);
  349. return;
  350. }
  351. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  352. this._bufferedBytes += options[kByteLength];
  353. this._deflating = true;
  354. perMessageDeflate.compress(data, options.fin, (_, buf) => {
  355. if (this._socket.destroyed) {
  356. const err = new Error(
  357. 'The socket was closed while data was being compressed'
  358. );
  359. if (typeof cb === 'function') cb(err);
  360. for (let i = 0; i < this._queue.length; i++) {
  361. const params = this._queue[i];
  362. const callback = params[params.length - 1];
  363. if (typeof callback === 'function') callback(err);
  364. }
  365. return;
  366. }
  367. this._bufferedBytes -= options[kByteLength];
  368. this._deflating = false;
  369. options.readOnly = false;
  370. this.sendFrame(Sender.frame(buf, options), cb);
  371. this.dequeue();
  372. });
  373. }
  374. /**
  375. * Executes queued send operations.
  376. *
  377. * @private
  378. */
  379. dequeue() {
  380. while (!this._deflating && this._queue.length) {
  381. const params = this._queue.shift();
  382. this._bufferedBytes -= params[3][kByteLength];
  383. Reflect.apply(params[0], this, params.slice(1));
  384. }
  385. }
  386. /**
  387. * Enqueues a send operation.
  388. *
  389. * @param {Array} params Send operation parameters.
  390. * @private
  391. */
  392. enqueue(params) {
  393. this._bufferedBytes += params[3][kByteLength];
  394. this._queue.push(params);
  395. }
  396. /**
  397. * Sends a frame.
  398. *
  399. * @param {Buffer[]} list The frame to send
  400. * @param {Function} [cb] Callback
  401. * @private
  402. */
  403. sendFrame(list, cb) {
  404. if (list.length === 2) {
  405. this._socket.cork();
  406. this._socket.write(list[0]);
  407. this._socket.write(list[1], cb);
  408. this._socket.uncork();
  409. } else {
  410. this._socket.write(list[0], cb);
  411. }
  412. }
  413. }
  414. module.exports = Sender;