sender.js 10 KB

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