Front end of the Slack clone application.

Sender.js 10KB

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