sender.js 12 KB

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