sender.js 10 KB

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