Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80529 views
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
var Transform = require('_stream_transform');
23
24
var binding = require('./binding');
25
var util = require('util');
26
var assert = require('assert').ok;
27
28
// zlib doesn't provide these, so kludge them in following the same
29
// const naming scheme zlib uses.
30
binding.Z_MIN_WINDOWBITS = 8;
31
binding.Z_MAX_WINDOWBITS = 15;
32
binding.Z_DEFAULT_WINDOWBITS = 15;
33
34
// fewer than 64 bytes per chunk is stupid.
35
// technically it could work with as few as 8, but even 64 bytes
36
// is absurdly low. Usually a MB or more is best.
37
binding.Z_MIN_CHUNK = 64;
38
binding.Z_MAX_CHUNK = Infinity;
39
binding.Z_DEFAULT_CHUNK = (16 * 1024);
40
41
binding.Z_MIN_MEMLEVEL = 1;
42
binding.Z_MAX_MEMLEVEL = 9;
43
binding.Z_DEFAULT_MEMLEVEL = 8;
44
45
binding.Z_MIN_LEVEL = -1;
46
binding.Z_MAX_LEVEL = 9;
47
binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
48
49
// expose all the zlib constants
50
Object.keys(binding).forEach(function(k) {
51
if (k.match(/^Z/)) exports[k] = binding[k];
52
});
53
54
// translation table for return codes.
55
exports.codes = {
56
Z_OK: binding.Z_OK,
57
Z_STREAM_END: binding.Z_STREAM_END,
58
Z_NEED_DICT: binding.Z_NEED_DICT,
59
Z_ERRNO: binding.Z_ERRNO,
60
Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
61
Z_DATA_ERROR: binding.Z_DATA_ERROR,
62
Z_MEM_ERROR: binding.Z_MEM_ERROR,
63
Z_BUF_ERROR: binding.Z_BUF_ERROR,
64
Z_VERSION_ERROR: binding.Z_VERSION_ERROR
65
};
66
67
Object.keys(exports.codes).forEach(function(k) {
68
exports.codes[exports.codes[k]] = k;
69
});
70
71
exports.Deflate = Deflate;
72
exports.Inflate = Inflate;
73
exports.Gzip = Gzip;
74
exports.Gunzip = Gunzip;
75
exports.DeflateRaw = DeflateRaw;
76
exports.InflateRaw = InflateRaw;
77
exports.Unzip = Unzip;
78
79
exports.createDeflate = function(o) {
80
return new Deflate(o);
81
};
82
83
exports.createInflate = function(o) {
84
return new Inflate(o);
85
};
86
87
exports.createDeflateRaw = function(o) {
88
return new DeflateRaw(o);
89
};
90
91
exports.createInflateRaw = function(o) {
92
return new InflateRaw(o);
93
};
94
95
exports.createGzip = function(o) {
96
return new Gzip(o);
97
};
98
99
exports.createGunzip = function(o) {
100
return new Gunzip(o);
101
};
102
103
exports.createUnzip = function(o) {
104
return new Unzip(o);
105
};
106
107
108
// Convenience methods.
109
// compress/decompress a string or buffer in one step.
110
exports.deflate = function(buffer, opts, callback) {
111
if (typeof opts === 'function') {
112
callback = opts;
113
opts = {};
114
}
115
return zlibBuffer(new Deflate(opts), buffer, callback);
116
};
117
118
exports.deflateSync = function(buffer, opts) {
119
return zlibBufferSync(new Deflate(opts), buffer);
120
};
121
122
exports.gzip = function(buffer, opts, callback) {
123
if (typeof opts === 'function') {
124
callback = opts;
125
opts = {};
126
}
127
return zlibBuffer(new Gzip(opts), buffer, callback);
128
};
129
130
exports.gzipSync = function(buffer, opts) {
131
return zlibBufferSync(new Gzip(opts), buffer);
132
};
133
134
exports.deflateRaw = function(buffer, opts, callback) {
135
if (typeof opts === 'function') {
136
callback = opts;
137
opts = {};
138
}
139
return zlibBuffer(new DeflateRaw(opts), buffer, callback);
140
};
141
142
exports.deflateRawSync = function(buffer, opts) {
143
return zlibBufferSync(new DeflateRaw(opts), buffer);
144
};
145
146
exports.unzip = function(buffer, opts, callback) {
147
if (typeof opts === 'function') {
148
callback = opts;
149
opts = {};
150
}
151
return zlibBuffer(new Unzip(opts), buffer, callback);
152
};
153
154
exports.unzipSync = function(buffer, opts) {
155
return zlibBufferSync(new Unzip(opts), buffer);
156
};
157
158
exports.inflate = function(buffer, opts, callback) {
159
if (typeof opts === 'function') {
160
callback = opts;
161
opts = {};
162
}
163
return zlibBuffer(new Inflate(opts), buffer, callback);
164
};
165
166
exports.inflateSync = function(buffer, opts) {
167
return zlibBufferSync(new Inflate(opts), buffer);
168
};
169
170
exports.gunzip = function(buffer, opts, callback) {
171
if (typeof opts === 'function') {
172
callback = opts;
173
opts = {};
174
}
175
return zlibBuffer(new Gunzip(opts), buffer, callback);
176
};
177
178
exports.gunzipSync = function(buffer, opts) {
179
return zlibBufferSync(new Gunzip(opts), buffer);
180
};
181
182
exports.inflateRaw = function(buffer, opts, callback) {
183
if (typeof opts === 'function') {
184
callback = opts;
185
opts = {};
186
}
187
return zlibBuffer(new InflateRaw(opts), buffer, callback);
188
};
189
190
exports.inflateRawSync = function(buffer, opts) {
191
return zlibBufferSync(new InflateRaw(opts), buffer);
192
};
193
194
function zlibBuffer(engine, buffer, callback) {
195
var buffers = [];
196
var nread = 0;
197
198
engine.on('error', onError);
199
engine.on('end', onEnd);
200
201
engine.end(buffer);
202
flow();
203
204
function flow() {
205
var chunk;
206
while (null !== (chunk = engine.read())) {
207
buffers.push(chunk);
208
nread += chunk.length;
209
}
210
engine.once('readable', flow);
211
}
212
213
function onError(err) {
214
engine.removeListener('end', onEnd);
215
engine.removeListener('readable', flow);
216
callback(err);
217
}
218
219
function onEnd() {
220
var buf = Buffer.concat(buffers, nread);
221
buffers = [];
222
callback(null, buf);
223
engine.close();
224
}
225
}
226
227
function zlibBufferSync(engine, buffer) {
228
if (typeof buffer === 'string')
229
buffer = new Buffer(buffer);
230
if (!Buffer.isBuffer(buffer))
231
throw new TypeError('Not a string or buffer');
232
233
var flushFlag = binding.Z_FINISH;
234
235
return engine._processChunk(buffer, flushFlag);
236
}
237
238
// generic zlib
239
// minimal 2-byte header
240
function Deflate(opts) {
241
if (!(this instanceof Deflate)) return new Deflate(opts);
242
Zlib.call(this, opts, binding.DEFLATE);
243
}
244
245
function Inflate(opts) {
246
if (!(this instanceof Inflate)) return new Inflate(opts);
247
Zlib.call(this, opts, binding.INFLATE);
248
}
249
250
251
252
// gzip - bigger header, same deflate compression
253
function Gzip(opts) {
254
if (!(this instanceof Gzip)) return new Gzip(opts);
255
Zlib.call(this, opts, binding.GZIP);
256
}
257
258
function Gunzip(opts) {
259
if (!(this instanceof Gunzip)) return new Gunzip(opts);
260
Zlib.call(this, opts, binding.GUNZIP);
261
}
262
263
264
265
// raw - no header
266
function DeflateRaw(opts) {
267
if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
268
Zlib.call(this, opts, binding.DEFLATERAW);
269
}
270
271
function InflateRaw(opts) {
272
if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
273
Zlib.call(this, opts, binding.INFLATERAW);
274
}
275
276
277
// auto-detect header.
278
function Unzip(opts) {
279
if (!(this instanceof Unzip)) return new Unzip(opts);
280
Zlib.call(this, opts, binding.UNZIP);
281
}
282
283
284
// the Zlib class they all inherit from
285
// This thing manages the queue of requests, and returns
286
// true or false if there is anything in the queue when
287
// you call the .write() method.
288
289
function Zlib(opts, mode) {
290
this._opts = opts = opts || {};
291
this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
292
293
Transform.call(this, opts);
294
295
if (opts.flush) {
296
if (opts.flush !== binding.Z_NO_FLUSH &&
297
opts.flush !== binding.Z_PARTIAL_FLUSH &&
298
opts.flush !== binding.Z_SYNC_FLUSH &&
299
opts.flush !== binding.Z_FULL_FLUSH &&
300
opts.flush !== binding.Z_FINISH &&
301
opts.flush !== binding.Z_BLOCK) {
302
throw new Error('Invalid flush flag: ' + opts.flush);
303
}
304
}
305
this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
306
307
if (opts.chunkSize) {
308
if (opts.chunkSize < exports.Z_MIN_CHUNK ||
309
opts.chunkSize > exports.Z_MAX_CHUNK) {
310
throw new Error('Invalid chunk size: ' + opts.chunkSize);
311
}
312
}
313
314
if (opts.windowBits) {
315
if (opts.windowBits < exports.Z_MIN_WINDOWBITS ||
316
opts.windowBits > exports.Z_MAX_WINDOWBITS) {
317
throw new Error('Invalid windowBits: ' + opts.windowBits);
318
}
319
}
320
321
if (opts.level) {
322
if (opts.level < exports.Z_MIN_LEVEL ||
323
opts.level > exports.Z_MAX_LEVEL) {
324
throw new Error('Invalid compression level: ' + opts.level);
325
}
326
}
327
328
if (opts.memLevel) {
329
if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||
330
opts.memLevel > exports.Z_MAX_MEMLEVEL) {
331
throw new Error('Invalid memLevel: ' + opts.memLevel);
332
}
333
}
334
335
if (opts.strategy) {
336
if (opts.strategy != exports.Z_FILTERED &&
337
opts.strategy != exports.Z_HUFFMAN_ONLY &&
338
opts.strategy != exports.Z_RLE &&
339
opts.strategy != exports.Z_FIXED &&
340
opts.strategy != exports.Z_DEFAULT_STRATEGY) {
341
throw new Error('Invalid strategy: ' + opts.strategy);
342
}
343
}
344
345
if (opts.dictionary) {
346
if (!Buffer.isBuffer(opts.dictionary)) {
347
throw new Error('Invalid dictionary: it should be a Buffer instance');
348
}
349
}
350
351
this._binding = new binding.Zlib(mode);
352
353
var self = this;
354
this._hadError = false;
355
this._binding.onerror = function(message, errno) {
356
// there is no way to cleanly recover.
357
// continuing only obscures problems.
358
self._binding = null;
359
self._hadError = true;
360
361
var error = new Error(message);
362
error.errno = errno;
363
error.code = exports.codes[errno];
364
self.emit('error', error);
365
};
366
367
var level = exports.Z_DEFAULT_COMPRESSION;
368
if (typeof opts.level === 'number') level = opts.level;
369
370
var strategy = exports.Z_DEFAULT_STRATEGY;
371
if (typeof opts.strategy === 'number') strategy = opts.strategy;
372
373
this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
374
level,
375
opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
376
strategy,
377
opts.dictionary);
378
379
this._buffer = new Buffer(this._chunkSize);
380
this._offset = 0;
381
this._closed = false;
382
this._level = level;
383
this._strategy = strategy;
384
385
this.once('end', this.close);
386
}
387
388
util.inherits(Zlib, Transform);
389
390
Zlib.prototype.params = function(level, strategy, callback) {
391
if (level < exports.Z_MIN_LEVEL ||
392
level > exports.Z_MAX_LEVEL) {
393
throw new RangeError('Invalid compression level: ' + level);
394
}
395
if (strategy != exports.Z_FILTERED &&
396
strategy != exports.Z_HUFFMAN_ONLY &&
397
strategy != exports.Z_RLE &&
398
strategy != exports.Z_FIXED &&
399
strategy != exports.Z_DEFAULT_STRATEGY) {
400
throw new TypeError('Invalid strategy: ' + strategy);
401
}
402
403
if (this._level !== level || this._strategy !== strategy) {
404
var self = this;
405
this.flush(binding.Z_SYNC_FLUSH, function() {
406
self._binding.params(level, strategy);
407
if (!self._hadError) {
408
self._level = level;
409
self._strategy = strategy;
410
if (callback) callback();
411
}
412
});
413
} else {
414
process.nextTick(callback);
415
}
416
};
417
418
Zlib.prototype.reset = function() {
419
return this._binding.reset();
420
};
421
422
// This is the _flush function called by the transform class,
423
// internally, when the last chunk has been written.
424
Zlib.prototype._flush = function(callback) {
425
this._transform(new Buffer(0), '', callback);
426
};
427
428
Zlib.prototype.flush = function(kind, callback) {
429
var ws = this._writableState;
430
431
if (typeof kind === 'function' || (kind === void 0 && !callback)) {
432
callback = kind;
433
kind = binding.Z_FULL_FLUSH;
434
}
435
436
if (ws.ended) {
437
if (callback)
438
process.nextTick(callback);
439
} else if (ws.ending) {
440
if (callback)
441
this.once('end', callback);
442
} else if (ws.needDrain) {
443
var self = this;
444
this.once('drain', function() {
445
self.flush(callback);
446
});
447
} else {
448
this._flushFlag = kind;
449
this.write(new Buffer(0), '', callback);
450
}
451
};
452
453
Zlib.prototype.close = function(callback) {
454
if (callback)
455
process.nextTick(callback);
456
457
if (this._closed)
458
return;
459
460
this._closed = true;
461
462
this._binding.close();
463
464
var self = this;
465
process.nextTick(function() {
466
self.emit('close');
467
});
468
};
469
470
Zlib.prototype._transform = function(chunk, encoding, cb) {
471
var flushFlag;
472
var ws = this._writableState;
473
var ending = ws.ending || ws.ended;
474
var last = ending && (!chunk || ws.length === chunk.length);
475
476
if (!chunk === null && !Buffer.isBuffer(chunk))
477
return cb(new Error('invalid input'));
478
479
// If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.
480
// If it's explicitly flushing at some other time, then we use
481
// Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
482
// goodness.
483
if (last)
484
flushFlag = binding.Z_FINISH;
485
else {
486
flushFlag = this._flushFlag;
487
// once we've flushed the last of the queue, stop flushing and
488
// go back to the normal behavior.
489
if (chunk.length >= ws.length) {
490
this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
491
}
492
}
493
494
var self = this;
495
this._processChunk(chunk, flushFlag, cb);
496
};
497
498
Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
499
var availInBefore = chunk && chunk.length;
500
var availOutBefore = this._chunkSize - this._offset;
501
var inOff = 0;
502
503
var self = this;
504
505
var async = typeof cb === 'function';
506
507
if (!async) {
508
var buffers = [];
509
var nread = 0;
510
511
var error;
512
this.on('error', function(er) {
513
error = er;
514
});
515
516
do {
517
var res = this._binding.writeSync(flushFlag,
518
chunk, // in
519
inOff, // in_off
520
availInBefore, // in_len
521
this._buffer, // out
522
this._offset, //out_off
523
availOutBefore); // out_len
524
} while (!this._hadError && callback(res[0], res[1]));
525
526
if (this._hadError) {
527
throw error;
528
}
529
530
var buf = Buffer.concat(buffers, nread);
531
this.close();
532
533
return buf;
534
}
535
536
var req = this._binding.write(flushFlag,
537
chunk, // in
538
inOff, // in_off
539
availInBefore, // in_len
540
this._buffer, // out
541
this._offset, //out_off
542
availOutBefore); // out_len
543
544
req.buffer = chunk;
545
req.callback = callback;
546
547
function callback(availInAfter, availOutAfter) {
548
if (self._hadError)
549
return;
550
551
var have = availOutBefore - availOutAfter;
552
assert(have >= 0, 'have should not go down');
553
554
if (have > 0) {
555
var out = self._buffer.slice(self._offset, self._offset + have);
556
self._offset += have;
557
// serve some output to the consumer.
558
if (async) {
559
self.push(out);
560
} else {
561
buffers.push(out);
562
nread += out.length;
563
}
564
}
565
566
// exhausted the output buffer, or used all the input create a new one.
567
if (availOutAfter === 0 || self._offset >= self._chunkSize) {
568
availOutBefore = self._chunkSize;
569
self._offset = 0;
570
self._buffer = new Buffer(self._chunkSize);
571
}
572
573
if (availOutAfter === 0) {
574
// Not actually done. Need to reprocess.
575
// Also, update the availInBefore to the availInAfter value,
576
// so that if we have to hit it a third (fourth, etc.) time,
577
// it'll have the correct byte counts.
578
inOff += (availInBefore - availInAfter);
579
availInBefore = availInAfter;
580
581
if (!async)
582
return true;
583
584
var newReq = self._binding.write(flushFlag,
585
chunk,
586
inOff,
587
availInBefore,
588
self._buffer,
589
self._offset,
590
self._chunkSize);
591
newReq.callback = callback; // this same function
592
newReq.buffer = chunk;
593
return;
594
}
595
596
if (!async)
597
return false;
598
599
// finished with the chunk.
600
cb();
601
}
602
};
603
604
util.inherits(Deflate, Zlib);
605
util.inherits(Inflate, Zlib);
606
util.inherits(Gzip, Zlib);
607
util.inherits(Gunzip, Zlib);
608
util.inherits(DeflateRaw, Zlib);
609
util.inherits(InflateRaw, Zlib);
610
util.inherits(Unzip, Zlib);
611
612