You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

512 lines
14 KiB

  1. 'use strict';
  2. const zlib = require('zlib');
  3. const bufferUtil = require('./buffer-util');
  4. const Limiter = require('./limiter');
  5. const { kStatusCode, NOOP } = require('./constants');
  6. const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
  7. const kPerMessageDeflate = Symbol('permessage-deflate');
  8. const kTotalLength = Symbol('total-length');
  9. const kCallback = Symbol('callback');
  10. const kBuffers = Symbol('buffers');
  11. const kError = Symbol('error');
  12. //
  13. // We limit zlib concurrency, which prevents severe memory fragmentation
  14. // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
  15. // and https://github.com/websockets/ws/issues/1202
  16. //
  17. // Intentionally global; it's the global thread pool that's an issue.
  18. //
  19. let zlibLimiter;
  20. /**
  21. * permessage-deflate implementation.
  22. */
  23. class PerMessageDeflate {
  24. /**
  25. * Creates a PerMessageDeflate instance.
  26. *
  27. * @param {Object} options Configuration options
  28. * @param {Boolean} options.serverNoContextTakeover Request/accept disabling
  29. * of server context takeover
  30. * @param {Boolean} options.clientNoContextTakeover Advertise/acknowledge
  31. * disabling of client context takeover
  32. * @param {(Boolean|Number)} options.serverMaxWindowBits Request/confirm the
  33. * use of a custom server window size
  34. * @param {(Boolean|Number)} options.clientMaxWindowBits Advertise support
  35. * for, or request, a custom client window size
  36. * @param {Object} options.zlibDeflateOptions Options to pass to zlib on deflate
  37. * @param {Object} options.zlibInflateOptions Options to pass to zlib on inflate
  38. * @param {Number} options.threshold Size (in bytes) below which messages
  39. * should not be compressed
  40. * @param {Number} options.concurrencyLimit The number of concurrent calls to
  41. * zlib
  42. * @param {Boolean} isServer Create the instance in either server or client
  43. * mode
  44. * @param {Number} maxPayload The maximum allowed message length
  45. */
  46. constructor(options, isServer, maxPayload) {
  47. this._maxPayload = maxPayload | 0;
  48. this._options = options || {};
  49. this._threshold =
  50. this._options.threshold !== undefined ? this._options.threshold : 1024;
  51. this._isServer = !!isServer;
  52. this._deflate = null;
  53. this._inflate = null;
  54. this.params = null;
  55. if (!zlibLimiter) {
  56. const concurrency =
  57. this._options.concurrencyLimit !== undefined
  58. ? this._options.concurrencyLimit
  59. : 10;
  60. zlibLimiter = new Limiter(concurrency);
  61. }
  62. }
  63. /**
  64. * @type {String}
  65. */
  66. static get extensionName() {
  67. return 'permessage-deflate';
  68. }
  69. /**
  70. * Create an extension negotiation offer.
  71. *
  72. * @return {Object} Extension parameters
  73. * @public
  74. */
  75. offer() {
  76. const params = {};
  77. if (this._options.serverNoContextTakeover) {
  78. params.server_no_context_takeover = true;
  79. }
  80. if (this._options.clientNoContextTakeover) {
  81. params.client_no_context_takeover = true;
  82. }
  83. if (this._options.serverMaxWindowBits) {
  84. params.server_max_window_bits = this._options.serverMaxWindowBits;
  85. }
  86. if (this._options.clientMaxWindowBits) {
  87. params.client_max_window_bits = this._options.clientMaxWindowBits;
  88. } else if (this._options.clientMaxWindowBits == null) {
  89. params.client_max_window_bits = true;
  90. }
  91. return params;
  92. }
  93. /**
  94. * Accept an extension negotiation offer/response.
  95. *
  96. * @param {Array} configurations The extension negotiation offers/reponse
  97. * @return {Object} Accepted configuration
  98. * @public
  99. */
  100. accept(configurations) {
  101. configurations = this.normalizeParams(configurations);
  102. this.params = this._isServer
  103. ? this.acceptAsServer(configurations)
  104. : this.acceptAsClient(configurations);
  105. return this.params;
  106. }
  107. /**
  108. * Releases all resources used by the extension.
  109. *
  110. * @public
  111. */
  112. cleanup() {
  113. if (this._inflate) {
  114. this._inflate.close();
  115. this._inflate = null;
  116. }
  117. if (this._deflate) {
  118. const callback = this._deflate[kCallback];
  119. this._deflate.close();
  120. this._deflate = null;
  121. if (callback) {
  122. callback(
  123. new Error(
  124. 'The deflate stream was closed while data was being processed'
  125. )
  126. );
  127. }
  128. }
  129. }
  130. /**
  131. * Accept an extension negotiation offer.
  132. *
  133. * @param {Array} offers The extension negotiation offers
  134. * @return {Object} Accepted configuration
  135. * @private
  136. */
  137. acceptAsServer(offers) {
  138. const opts = this._options;
  139. const accepted = offers.find((params) => {
  140. if (
  141. (opts.serverNoContextTakeover === false &&
  142. params.server_no_context_takeover) ||
  143. (params.server_max_window_bits &&
  144. (opts.serverMaxWindowBits === false ||
  145. (typeof opts.serverMaxWindowBits === 'number' &&
  146. opts.serverMaxWindowBits > params.server_max_window_bits))) ||
  147. (typeof opts.clientMaxWindowBits === 'number' &&
  148. !params.client_max_window_bits)
  149. ) {
  150. return false;
  151. }
  152. return true;
  153. });
  154. if (!accepted) {
  155. throw new Error('None of the extension offers can be accepted');
  156. }
  157. if (opts.serverNoContextTakeover) {
  158. accepted.server_no_context_takeover = true;
  159. }
  160. if (opts.clientNoContextTakeover) {
  161. accepted.client_no_context_takeover = true;
  162. }
  163. if (typeof opts.serverMaxWindowBits === 'number') {
  164. accepted.server_max_window_bits = opts.serverMaxWindowBits;
  165. }
  166. if (typeof opts.clientMaxWindowBits === 'number') {
  167. accepted.client_max_window_bits = opts.clientMaxWindowBits;
  168. } else if (
  169. accepted.client_max_window_bits === true ||
  170. opts.clientMaxWindowBits === false
  171. ) {
  172. delete accepted.client_max_window_bits;
  173. }
  174. return accepted;
  175. }
  176. /**
  177. * Accept the extension negotiation response.
  178. *
  179. * @param {Array} response The extension negotiation response
  180. * @return {Object} Accepted configuration
  181. * @private
  182. */
  183. acceptAsClient(response) {
  184. const params = response[0];
  185. if (
  186. this._options.clientNoContextTakeover === false &&
  187. params.client_no_context_takeover
  188. ) {
  189. throw new Error('Unexpected parameter "client_no_context_takeover"');
  190. }
  191. if (!params.client_max_window_bits) {
  192. if (typeof this._options.clientMaxWindowBits === 'number') {
  193. params.client_max_window_bits = this._options.clientMaxWindowBits;
  194. }
  195. } else if (
  196. this._options.clientMaxWindowBits === false ||
  197. (typeof this._options.clientMaxWindowBits === 'number' &&
  198. params.client_max_window_bits > this._options.clientMaxWindowBits)
  199. ) {
  200. throw new Error(
  201. 'Unexpected or invalid parameter "client_max_window_bits"'
  202. );
  203. }
  204. return params;
  205. }
  206. /**
  207. * Normalize parameters.
  208. *
  209. * @param {Array} configurations The extension negotiation offers/reponse
  210. * @return {Array} The offers/response with normalized parameters
  211. * @private
  212. */
  213. normalizeParams(configurations) {
  214. configurations.forEach((params) => {
  215. Object.keys(params).forEach((key) => {
  216. let value = params[key];
  217. if (value.length > 1) {
  218. throw new Error(`Parameter "${key}" must have only a single value`);
  219. }
  220. value = value[0];
  221. if (key === 'client_max_window_bits') {
  222. if (value !== true) {
  223. const num = +value;
  224. if (!Number.isInteger(num) || num < 8 || num > 15) {
  225. throw new TypeError(
  226. `Invalid value for parameter "${key}": ${value}`
  227. );
  228. }
  229. value = num;
  230. } else if (!this._isServer) {
  231. throw new TypeError(
  232. `Invalid value for parameter "${key}": ${value}`
  233. );
  234. }
  235. } else if (key === 'server_max_window_bits') {
  236. const num = +value;
  237. if (!Number.isInteger(num) || num < 8 || num > 15) {
  238. throw new TypeError(
  239. `Invalid value for parameter "${key}": ${value}`
  240. );
  241. }
  242. value = num;
  243. } else if (
  244. key === 'client_no_context_takeover' ||
  245. key === 'server_no_context_takeover'
  246. ) {
  247. if (value !== true) {
  248. throw new TypeError(
  249. `Invalid value for parameter "${key}": ${value}`
  250. );
  251. }
  252. } else {
  253. throw new Error(`Unknown parameter "${key}"`);
  254. }
  255. params[key] = value;
  256. });
  257. });
  258. return configurations;
  259. }
  260. /**
  261. * Decompress data. Concurrency limited.
  262. *
  263. * @param {Buffer} data Compressed data
  264. * @param {Boolean} fin Specifies whether or not this is the last fragment
  265. * @param {Function} callback Callback
  266. * @public
  267. */
  268. decompress(data, fin, callback) {
  269. zlibLimiter.add((done) => {
  270. this._decompress(data, fin, (err, result) => {
  271. done();
  272. callback(err, result);
  273. });
  274. });
  275. }
  276. /**
  277. * Compress data. Concurrency limited.
  278. *
  279. * @param {Buffer} data Data to compress
  280. * @param {Boolean} fin Specifies whether or not this is the last fragment
  281. * @param {Function} callback Callback
  282. * @public
  283. */
  284. compress(data, fin, callback) {
  285. zlibLimiter.add((done) => {
  286. this._compress(data, fin, (err, result) => {
  287. done();
  288. callback(err, result);
  289. });
  290. });
  291. }
  292. /**
  293. * Decompress data.
  294. *
  295. * @param {Buffer} data Compressed data
  296. * @param {Boolean} fin Specifies whether or not this is the last fragment
  297. * @param {Function} callback Callback
  298. * @private
  299. */
  300. _decompress(data, fin, callback) {
  301. const endpoint = this._isServer ? 'client' : 'server';
  302. if (!this._inflate) {
  303. const key = `${endpoint}_max_window_bits`;
  304. const windowBits =
  305. typeof this.params[key] !== 'number'
  306. ? zlib.Z_DEFAULT_WINDOWBITS
  307. : this.params[key];
  308. this._inflate = zlib.createInflateRaw({
  309. ...this._options.zlibInflateOptions,
  310. windowBits
  311. });
  312. this._inflate[kPerMessageDeflate] = this;
  313. this._inflate[kTotalLength] = 0;
  314. this._inflate[kBuffers] = [];
  315. this._inflate.on('error', inflateOnError);
  316. this._inflate.on('data', inflateOnData);
  317. }
  318. this._inflate[kCallback] = callback;
  319. this._inflate.write(data);
  320. if (fin) this._inflate.write(TRAILER);
  321. this._inflate.flush(() => {
  322. const err = this._inflate[kError];
  323. if (err) {
  324. this._inflate.close();
  325. this._inflate = null;
  326. callback(err);
  327. return;
  328. }
  329. const data = bufferUtil.concat(
  330. this._inflate[kBuffers],
  331. this._inflate[kTotalLength]
  332. );
  333. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  334. this._inflate.close();
  335. this._inflate = null;
  336. } else {
  337. this._inflate[kTotalLength] = 0;
  338. this._inflate[kBuffers] = [];
  339. }
  340. callback(null, data);
  341. });
  342. }
  343. /**
  344. * Compress data.
  345. *
  346. * @param {Buffer} data Data to compress
  347. * @param {Boolean} fin Specifies whether or not this is the last fragment
  348. * @param {Function} callback Callback
  349. * @private
  350. */
  351. _compress(data, fin, callback) {
  352. const endpoint = this._isServer ? 'server' : 'client';
  353. if (!this._deflate) {
  354. const key = `${endpoint}_max_window_bits`;
  355. const windowBits =
  356. typeof this.params[key] !== 'number'
  357. ? zlib.Z_DEFAULT_WINDOWBITS
  358. : this.params[key];
  359. this._deflate = zlib.createDeflateRaw({
  360. ...this._options.zlibDeflateOptions,
  361. windowBits
  362. });
  363. this._deflate[kTotalLength] = 0;
  364. this._deflate[kBuffers] = [];
  365. //
  366. // An `'error'` event is emitted, only on Node.js < 10.0.0, if the
  367. // `zlib.DeflateRaw` instance is closed while data is being processed.
  368. // This can happen if `PerMessageDeflate#cleanup()` is called at the wrong
  369. // time due to an abnormal WebSocket closure.
  370. //
  371. this._deflate.on('error', NOOP);
  372. this._deflate.on('data', deflateOnData);
  373. }
  374. this._deflate[kCallback] = callback;
  375. this._deflate.write(data);
  376. this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
  377. if (!this._deflate) {
  378. //
  379. // The deflate stream was closed while data was being processed.
  380. //
  381. return;
  382. }
  383. let data = bufferUtil.concat(
  384. this._deflate[kBuffers],
  385. this._deflate[kTotalLength]
  386. );
  387. if (fin) data = data.slice(0, data.length - 4);
  388. //
  389. // Ensure that the callback will not be called again in
  390. // `PerMessageDeflate#cleanup()`.
  391. //
  392. this._deflate[kCallback] = null;
  393. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  394. this._deflate.close();
  395. this._deflate = null;
  396. } else {
  397. this._deflate[kTotalLength] = 0;
  398. this._deflate[kBuffers] = [];
  399. }
  400. callback(null, data);
  401. });
  402. }
  403. }
  404. module.exports = PerMessageDeflate;
  405. /**
  406. * The listener of the `zlib.DeflateRaw` stream `'data'` event.
  407. *
  408. * @param {Buffer} chunk A chunk of data
  409. * @private
  410. */
  411. function deflateOnData(chunk) {
  412. this[kBuffers].push(chunk);
  413. this[kTotalLength] += chunk.length;
  414. }
  415. /**
  416. * The listener of the `zlib.InflateRaw` stream `'data'` event.
  417. *
  418. * @param {Buffer} chunk A chunk of data
  419. * @private
  420. */
  421. function inflateOnData(chunk) {
  422. this[kTotalLength] += chunk.length;
  423. if (
  424. this[kPerMessageDeflate]._maxPayload < 1 ||
  425. this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
  426. ) {
  427. this[kBuffers].push(chunk);
  428. return;
  429. }
  430. this[kError] = new RangeError('Max payload size exceeded');
  431. this[kError][kStatusCode] = 1009;
  432. this.removeListener('data', inflateOnData);
  433. this.reset();
  434. }
  435. /**
  436. * The listener of the `zlib.InflateRaw` stream `'error'` event.
  437. *
  438. * @param {Error} err The emitted error
  439. * @private
  440. */
  441. function inflateOnError(err) {
  442. //
  443. // There is no need to call `Zlib#close()` as the handle is automatically
  444. // closed when an error is emitted.
  445. //
  446. this[kPerMessageDeflate]._inflate = null;
  447. err[kStatusCode] = 1007;
  448. this[kCallback](err);
  449. }