You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

358 lines
9.3 KiB

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