sender.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. 'use strict';
  2. const crypto = require('crypto');
  3. const PerMessageDeflate = require('./permessage-deflate');
  4. const bufferUtil = require('./buffer-util');
  5. const validation = require('./validation');
  6. const constants = require('./constants');
  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 = data.length < 1024 || (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. if (payloadLength === 126) {
  54. target.writeUInt16BE(data.length, 2);
  55. } else if (payloadLength === 127) {
  56. target.writeUInt32BE(0, 2);
  57. target.writeUInt32BE(data.length, 6);
  58. }
  59. if (!options.mask) {
  60. target[1] = payloadLength;
  61. if (merge) {
  62. data.copy(target, offset);
  63. return [target];
  64. }
  65. return [target, data];
  66. }
  67. const mask = crypto.randomBytes(4);
  68. target[1] = payloadLength | 0x80;
  69. target[offset - 4] = mask[0];
  70. target[offset - 3] = mask[1];
  71. target[offset - 2] = mask[2];
  72. target[offset - 1] = mask[3];
  73. if (merge) {
  74. bufferUtil.mask(data, mask, target, offset, data.length);
  75. return [target];
  76. }
  77. bufferUtil.mask(data, mask, data, 0, data.length);
  78. return [target, data];
  79. }
  80. /**
  81. * Sends a close message to the other peer.
  82. *
  83. * @param {(Number|undefined)} code The status code component of the body
  84. * @param {String} data The message component of the body
  85. * @param {Boolean} mask Specifies whether or not to mask the message
  86. * @param {Function} cb Callback
  87. * @public
  88. */
  89. close(code, data, mask, cb) {
  90. var buf;
  91. if (code === undefined) {
  92. buf = constants.EMPTY_BUFFER;
  93. } else if (
  94. typeof code !== 'number' ||
  95. !validation.isValidStatusCode(code)
  96. ) {
  97. throw new TypeError('First argument must be a valid error code number');
  98. } else if (data === undefined || data === '') {
  99. buf = Buffer.allocUnsafe(2);
  100. buf.writeUInt16BE(code, 0);
  101. } else {
  102. buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data));
  103. buf.writeUInt16BE(code, 0);
  104. buf.write(data, 2);
  105. }
  106. if (this._deflating) {
  107. this.enqueue([this.doClose, buf, mask, cb]);
  108. } else {
  109. this.doClose(buf, mask, cb);
  110. }
  111. }
  112. /**
  113. * Frames and sends a close message.
  114. *
  115. * @param {Buffer} data The message to send
  116. * @param {Boolean} mask Specifies whether or not to mask `data`
  117. * @param {Function} cb Callback
  118. * @private
  119. */
  120. doClose(data, mask, cb) {
  121. this.sendFrame(
  122. Sender.frame(data, {
  123. fin: true,
  124. rsv1: false,
  125. opcode: 0x08,
  126. mask,
  127. readOnly: false
  128. }),
  129. cb
  130. );
  131. }
  132. /**
  133. * Sends a ping message to the other peer.
  134. *
  135. * @param {*} data The message to send
  136. * @param {Boolean} mask Specifies whether or not to mask `data`
  137. * @param {Function} cb Callback
  138. * @public
  139. */
  140. ping(data, mask, cb) {
  141. var readOnly = true;
  142. if (!Buffer.isBuffer(data)) {
  143. if (data instanceof ArrayBuffer) {
  144. data = Buffer.from(data);
  145. } else if (ArrayBuffer.isView(data)) {
  146. data = viewToBuffer(data);
  147. } else {
  148. data = Buffer.from(data);
  149. readOnly = false;
  150. }
  151. }
  152. if (this._deflating) {
  153. this.enqueue([this.doPing, data, mask, readOnly, cb]);
  154. } else {
  155. this.doPing(data, mask, readOnly, cb);
  156. }
  157. }
  158. /**
  159. * Frames and sends a ping message.
  160. *
  161. * @param {*} data The message to send
  162. * @param {Boolean} mask Specifies whether or not to mask `data`
  163. * @param {Boolean} readOnly 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 Specifies whether or not to mask `data`
  184. * @param {Function} cb Callback
  185. * @public
  186. */
  187. pong(data, mask, cb) {
  188. var readOnly = true;
  189. if (!Buffer.isBuffer(data)) {
  190. if (data instanceof ArrayBuffer) {
  191. data = Buffer.from(data);
  192. } else if (ArrayBuffer.isView(data)) {
  193. data = viewToBuffer(data);
  194. } else {
  195. data = Buffer.from(data);
  196. readOnly = false;
  197. }
  198. }
  199. if (this._deflating) {
  200. this.enqueue([this.doPong, data, mask, readOnly, cb]);
  201. } else {
  202. this.doPong(data, mask, readOnly, cb);
  203. }
  204. }
  205. /**
  206. * Frames and sends a pong message.
  207. *
  208. * @param {*} data The message to send
  209. * @param {Boolean} mask Specifies whether or not to mask `data`
  210. * @param {Boolean} readOnly Specifies whether `data` can be modified
  211. * @param {Function} cb Callback
  212. * @private
  213. */
  214. doPong(data, mask, readOnly, cb) {
  215. this.sendFrame(
  216. Sender.frame(data, {
  217. fin: true,
  218. rsv1: false,
  219. opcode: 0x0a,
  220. mask,
  221. readOnly
  222. }),
  223. cb
  224. );
  225. }
  226. /**
  227. * Sends a data message to the other peer.
  228. *
  229. * @param {*} data The message to send
  230. * @param {Object} options Options object
  231. * @param {Boolean} options.compress Specifies whether or not to compress `data`
  232. * @param {Boolean} options.binary Specifies whether `data` is binary or text
  233. * @param {Boolean} options.fin Specifies whether the fragment is the last one
  234. * @param {Boolean} options.mask Specifies whether or not to mask `data`
  235. * @param {Function} cb Callback
  236. * @public
  237. */
  238. send(data, options, cb) {
  239. var opcode = options.binary ? 2 : 1;
  240. var rsv1 = options.compress;
  241. var readOnly = true;
  242. if (!Buffer.isBuffer(data)) {
  243. if (data instanceof ArrayBuffer) {
  244. data = Buffer.from(data);
  245. } else if (ArrayBuffer.isView(data)) {
  246. data = viewToBuffer(data);
  247. } else {
  248. data = Buffer.from(data);
  249. readOnly = false;
  250. }
  251. }
  252. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  253. if (this._firstFragment) {
  254. this._firstFragment = false;
  255. if (rsv1 && perMessageDeflate) {
  256. rsv1 = data.length >= perMessageDeflate._threshold;
  257. }
  258. this._compress = rsv1;
  259. } else {
  260. rsv1 = false;
  261. opcode = 0;
  262. }
  263. if (options.fin) this._firstFragment = true;
  264. if (perMessageDeflate) {
  265. const opts = {
  266. fin: options.fin,
  267. rsv1,
  268. opcode,
  269. mask: options.mask,
  270. readOnly
  271. };
  272. if (this._deflating) {
  273. this.enqueue([this.dispatch, data, this._compress, opts, cb]);
  274. } else {
  275. this.dispatch(data, this._compress, opts, cb);
  276. }
  277. } else {
  278. this.sendFrame(
  279. Sender.frame(data, {
  280. fin: options.fin,
  281. rsv1: false,
  282. opcode,
  283. mask: options.mask,
  284. readOnly
  285. }),
  286. cb
  287. );
  288. }
  289. }
  290. /**
  291. * Dispatches a data message.
  292. *
  293. * @param {Buffer} data The message to send
  294. * @param {Boolean} compress Specifies whether or not to compress `data`
  295. * @param {Object} options Options object
  296. * @param {Number} options.opcode The opcode
  297. * @param {Boolean} options.readOnly Specifies whether `data` can be modified
  298. * @param {Boolean} options.fin Specifies whether or not to set the FIN bit
  299. * @param {Boolean} options.mask Specifies whether or not to mask `data`
  300. * @param {Boolean} options.rsv1 Specifies whether or not to set the 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._deflating = true;
  311. perMessageDeflate.compress(data, options.fin, (_, buf) => {
  312. this._deflating = false;
  313. options.readOnly = false;
  314. this.sendFrame(Sender.frame(buf, options), cb);
  315. this.dequeue();
  316. });
  317. }
  318. /**
  319. * Executes queued send operations.
  320. *
  321. * @private
  322. */
  323. dequeue() {
  324. while (!this._deflating && this._queue.length) {
  325. const params = this._queue.shift();
  326. this._bufferedBytes -= params[1].length;
  327. params[0].apply(this, params.slice(1));
  328. }
  329. }
  330. /**
  331. * Enqueues a send operation.
  332. *
  333. * @param {Array} params Send operation parameters.
  334. * @private
  335. */
  336. enqueue(params) {
  337. this._bufferedBytes += params[1].length;
  338. this._queue.push(params);
  339. }
  340. /**
  341. * Sends a frame.
  342. *
  343. * @param {Buffer[]} list The frame to send
  344. * @param {Function} cb Callback
  345. * @private
  346. */
  347. sendFrame(list, cb) {
  348. if (list.length === 2) {
  349. this._socket.write(list[0]);
  350. this._socket.write(list[1], cb);
  351. } else {
  352. this._socket.write(list[0], cb);
  353. }
  354. }
  355. }
  356. module.exports = Sender;
  357. /**
  358. * Converts an `ArrayBuffer` view into a buffer.
  359. *
  360. * @param {(DataView|TypedArray)} view The view to convert
  361. * @return {Buffer} Converted view
  362. * @private
  363. */
  364. function viewToBuffer(view) {
  365. const buf = Buffer.from(view.buffer);
  366. if (view.byteLength !== view.buffer.byteLength) {
  367. return buf.slice(view.byteOffset, view.byteOffset + view.byteLength);
  368. }
  369. return buf;
  370. }