sender.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 {Boolean} [options.fin=false] Specifies whether or not to set the
  36. * FIN bit
  37. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  38. * `data`
  39. * @param {Number} options.opcode The opcode
  40. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  41. * modified
  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|Buffer)} [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.length) {
  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. if (typeof data === 'string') {
  108. buf.write(data, 2);
  109. } else {
  110. buf.set(data, 2);
  111. }
  112. }
  113. if (this._deflating) {
  114. this.enqueue([this.doClose, buf, mask, cb]);
  115. } else {
  116. this.doClose(buf, mask, cb);
  117. }
  118. }
  119. /**
  120. * Frames and sends a close message.
  121. *
  122. * @param {Buffer} data The message to send
  123. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  124. * @param {Function} [cb] Callback
  125. * @private
  126. */
  127. doClose(data, mask, cb) {
  128. this.sendFrame(
  129. Sender.frame(data, {
  130. fin: true,
  131. rsv1: false,
  132. opcode: 0x08,
  133. mask,
  134. readOnly: false
  135. }),
  136. cb
  137. );
  138. }
  139. /**
  140. * Sends a ping message to the other peer.
  141. *
  142. * @param {*} data The message to send
  143. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  144. * @param {Function} [cb] Callback
  145. * @public
  146. */
  147. ping(data, mask, cb) {
  148. const buf = toBuffer(data);
  149. if (buf.length > 125) {
  150. throw new RangeError('The data size must not be greater than 125 bytes');
  151. }
  152. if (this._deflating) {
  153. this.enqueue([this.doPing, buf, mask, toBuffer.readOnly, cb]);
  154. } else {
  155. this.doPing(buf, mask, toBuffer.readOnly, cb);
  156. }
  157. }
  158. /**
  159. * Frames and sends a ping message.
  160. *
  161. * @param {Buffer} data The message to send
  162. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  163. * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified
  164. * @param {Function} [cb] Callback
  165. * @private
  166. */
  167. doPing(data, mask, readOnly, cb) {
  168. this.sendFrame(
  169. Sender.frame(data, {
  170. fin: true,
  171. rsv1: false,
  172. opcode: 0x09,
  173. mask,
  174. readOnly
  175. }),
  176. cb
  177. );
  178. }
  179. /**
  180. * Sends a pong message to the other peer.
  181. *
  182. * @param {*} data The message to send
  183. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  184. * @param {Function} [cb] Callback
  185. * @public
  186. */
  187. pong(data, mask, cb) {
  188. const buf = toBuffer(data);
  189. if (buf.length > 125) {
  190. throw new RangeError('The data size must not be greater than 125 bytes');
  191. }
  192. if (this._deflating) {
  193. this.enqueue([this.doPong, buf, mask, toBuffer.readOnly, cb]);
  194. } else {
  195. this.doPong(buf, mask, toBuffer.readOnly, cb);
  196. }
  197. }
  198. /**
  199. * Frames and sends a pong message.
  200. *
  201. * @param {Buffer} data The message to send
  202. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  203. * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified
  204. * @param {Function} [cb] Callback
  205. * @private
  206. */
  207. doPong(data, mask, readOnly, cb) {
  208. this.sendFrame(
  209. Sender.frame(data, {
  210. fin: true,
  211. rsv1: false,
  212. opcode: 0x0a,
  213. mask,
  214. readOnly
  215. }),
  216. cb
  217. );
  218. }
  219. /**
  220. * Sends a data message to the other peer.
  221. *
  222. * @param {*} data The message to send
  223. * @param {Object} options Options object
  224. * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
  225. * or text
  226. * @param {Boolean} [options.compress=false] Specifies whether or not to
  227. * compress `data`
  228. * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
  229. * last one
  230. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  231. * `data`
  232. * @param {Function} [cb] Callback
  233. * @public
  234. */
  235. send(data, options, cb) {
  236. const buf = toBuffer(data);
  237. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  238. let opcode = options.binary ? 2 : 1;
  239. let rsv1 = options.compress;
  240. if (this._firstFragment) {
  241. this._firstFragment = false;
  242. if (
  243. rsv1 &&
  244. perMessageDeflate &&
  245. perMessageDeflate.params[
  246. perMessageDeflate._isServer
  247. ? 'server_no_context_takeover'
  248. : 'client_no_context_takeover'
  249. ]
  250. ) {
  251. rsv1 = buf.length >= perMessageDeflate._threshold;
  252. }
  253. this._compress = rsv1;
  254. } else {
  255. rsv1 = false;
  256. opcode = 0;
  257. }
  258. if (options.fin) this._firstFragment = true;
  259. if (perMessageDeflate) {
  260. const opts = {
  261. fin: options.fin,
  262. rsv1,
  263. opcode,
  264. mask: options.mask,
  265. readOnly: toBuffer.readOnly
  266. };
  267. if (this._deflating) {
  268. this.enqueue([this.dispatch, buf, this._compress, opts, cb]);
  269. } else {
  270. this.dispatch(buf, this._compress, opts, cb);
  271. }
  272. } else {
  273. this.sendFrame(
  274. Sender.frame(buf, {
  275. fin: options.fin,
  276. rsv1: false,
  277. opcode,
  278. mask: options.mask,
  279. readOnly: toBuffer.readOnly
  280. }),
  281. cb
  282. );
  283. }
  284. }
  285. /**
  286. * Dispatches a data message.
  287. *
  288. * @param {Buffer} data The message to send
  289. * @param {Boolean} [compress=false] Specifies whether or not to compress
  290. * `data`
  291. * @param {Object} options Options object
  292. * @param {Number} options.opcode The opcode
  293. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  294. * FIN bit
  295. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  296. * `data`
  297. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  298. * modified
  299. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  300. * RSV1 bit
  301. * @param {Function} [cb] Callback
  302. * @private
  303. */
  304. dispatch(data, compress, options, cb) {
  305. if (!compress) {
  306. this.sendFrame(Sender.frame(data, options), cb);
  307. return;
  308. }
  309. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  310. this._bufferedBytes += data.length;
  311. this._deflating = true;
  312. perMessageDeflate.compress(data, options.fin, (_, buf) => {
  313. if (this._socket.destroyed) {
  314. const err = new Error(
  315. 'The socket was closed while data was being compressed'
  316. );
  317. if (typeof cb === 'function') cb(err);
  318. for (let i = 0; i < this._queue.length; i++) {
  319. const callback = this._queue[i][4];
  320. if (typeof callback === 'function') callback(err);
  321. }
  322. return;
  323. }
  324. this._bufferedBytes -= data.length;
  325. this._deflating = false;
  326. options.readOnly = false;
  327. this.sendFrame(Sender.frame(buf, options), cb);
  328. this.dequeue();
  329. });
  330. }
  331. /**
  332. * Executes queued send operations.
  333. *
  334. * @private
  335. */
  336. dequeue() {
  337. while (!this._deflating && this._queue.length) {
  338. const params = this._queue.shift();
  339. this._bufferedBytes -= params[1].length;
  340. Reflect.apply(params[0], this, params.slice(1));
  341. }
  342. }
  343. /**
  344. * Enqueues a send operation.
  345. *
  346. * @param {Array} params Send operation parameters.
  347. * @private
  348. */
  349. enqueue(params) {
  350. this._bufferedBytes += params[1].length;
  351. this._queue.push(params);
  352. }
  353. /**
  354. * Sends a frame.
  355. *
  356. * @param {Buffer[]} list The frame to send
  357. * @param {Function} [cb] Callback
  358. * @private
  359. */
  360. sendFrame(list, cb) {
  361. if (list.length === 2) {
  362. this._socket.cork();
  363. this._socket.write(list[0]);
  364. this._socket.write(list[1], cb);
  365. this._socket.uncork();
  366. } else {
  367. this._socket.write(list[0], cb);
  368. }
  369. }
  370. }
  371. module.exports = Sender;