sender.js 11 KB

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