1 // Copyright Joyent, Inc. and other Node contributors.
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:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
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.
22 var Transform = require('_stream_transform');
24 var binding = process.binding('zlib');
25 var util = require('util');
26 var assert = require('assert').ok;
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;
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);
41 binding.Z_MIN_MEMLEVEL = 1;
42 binding.Z_MAX_MEMLEVEL = 9;
43 binding.Z_DEFAULT_MEMLEVEL = 8;
45 binding.Z_MIN_LEVEL = -1;
46 binding.Z_MAX_LEVEL = 9;
47 binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
49 // expose all the zlib constants
50 Object.keys(binding).forEach(function(k) {
51 if (k.match(/^Z/)) exports[k] = binding[k];
54 // translation table for return codes.
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
67 Object.keys(exports.codes).forEach(function(k) {
68 exports.codes[exports.codes[k]] = k;
71 exports.Deflate = Deflate;
72 exports.Inflate = Inflate;
74 exports.Gunzip = Gunzip;
75 exports.DeflateRaw = DeflateRaw;
76 exports.InflateRaw = InflateRaw;
77 exports.Unzip = Unzip;
79 exports.createDeflate = function(o) {
80 return new Deflate(o);
83 exports.createInflate = function(o) {
84 return new Inflate(o);
87 exports.createDeflateRaw = function(o) {
88 return new DeflateRaw(o);
91 exports.createInflateRaw = function(o) {
92 return new InflateRaw(o);
95 exports.createGzip = function(o) {
99 exports.createGunzip = function(o) {
100 return new Gunzip(o);
103 exports.createUnzip = function(o) {
108 // Convenience methods.
109 // compress/decompress a string or buffer in one step.
110 exports.deflate = function(buffer, opts, callback) {
111 if (util.isFunction(opts)) {
115 return zlibBuffer(new Deflate(opts), buffer, callback);
118 exports.gzip = function(buffer, opts, callback) {
119 if (util.isFunction(opts)) {
123 return zlibBuffer(new Gzip(opts), buffer, callback);
126 exports.deflateRaw = function(buffer, opts, callback) {
127 if (util.isFunction(opts)) {
131 return zlibBuffer(new DeflateRaw(opts), buffer, callback);
134 exports.unzip = function(buffer, opts, callback) {
135 if (util.isFunction(opts)) {
139 return zlibBuffer(new Unzip(opts), buffer, callback);
142 exports.inflate = function(buffer, opts, callback) {
143 if (util.isFunction(opts)) {
147 return zlibBuffer(new Inflate(opts), buffer, callback);
150 exports.gunzip = function(buffer, opts, callback) {
151 if (util.isFunction(opts)) {
155 return zlibBuffer(new Gunzip(opts), buffer, callback);
158 exports.inflateRaw = function(buffer, opts, callback) {
159 if (util.isFunction(opts)) {
163 return zlibBuffer(new InflateRaw(opts), buffer, callback);
166 function zlibBuffer(engine, buffer, callback) {
167 if (!util.isFunction(callback)) {
168 return zlibBufferSync(engine, buffer, callback);
174 engine.on('error', onError);
175 engine.on('end', onEnd);
182 while (null !== (chunk = engine.read())) {
184 nread += chunk.length;
186 engine.once('readable', flow);
189 function onError(err) {
190 engine.removeListener('end', onEnd);
191 engine.removeListener('readable', flow);
196 var buf = Buffer.concat(buffers, nread);
203 function zlibBufferSync(engine, buffer, callback) {
204 if (util.isString(buffer))
205 buffer = new Buffer(buffer);
206 if (!util.isBuffer(buffer))
207 throw new TypeError('Not a string or buffer');
209 var flushFlag = binding.Z_FINISH;
211 return engine._processChunk(buffer, flushFlag);
215 // minimal 2-byte header
216 function Deflate(opts) {
217 if (!(this instanceof Deflate)) return new Deflate(opts);
218 Zlib.call(this, opts, binding.DEFLATE);
221 function Inflate(opts) {
222 if (!(this instanceof Inflate)) return new Inflate(opts);
223 Zlib.call(this, opts, binding.INFLATE);
228 // gzip - bigger header, same deflate compression
229 function Gzip(opts) {
230 if (!(this instanceof Gzip)) return new Gzip(opts);
231 Zlib.call(this, opts, binding.GZIP);
234 function Gunzip(opts) {
235 if (!(this instanceof Gunzip)) return new Gunzip(opts);
236 Zlib.call(this, opts, binding.GUNZIP);
242 function DeflateRaw(opts) {
243 if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
244 Zlib.call(this, opts, binding.DEFLATERAW);
247 function InflateRaw(opts) {
248 if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
249 Zlib.call(this, opts, binding.INFLATERAW);
253 // auto-detect header.
254 function Unzip(opts) {
255 if (!(this instanceof Unzip)) return new Unzip(opts);
256 Zlib.call(this, opts, binding.UNZIP);
260 // the Zlib class they all inherit from
261 // This thing manages the queue of requests, and returns
262 // true or false if there is anything in the queue when
263 // you call the .write() method.
265 function Zlib(opts, mode) {
266 this._opts = opts = opts || {};
267 this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
269 Transform.call(this, opts);
272 if (opts.flush !== binding.Z_NO_FLUSH &&
273 opts.flush !== binding.Z_PARTIAL_FLUSH &&
274 opts.flush !== binding.Z_SYNC_FLUSH &&
275 opts.flush !== binding.Z_FULL_FLUSH &&
276 opts.flush !== binding.Z_FINISH &&
277 opts.flush !== binding.Z_BLOCK) {
278 throw new Error('Invalid flush flag: ' + opts.flush);
281 this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
283 if (opts.chunkSize) {
284 if (opts.chunkSize < exports.Z_MIN_CHUNK ||
285 opts.chunkSize > exports.Z_MAX_CHUNK) {
286 throw new Error('Invalid chunk size: ' + opts.chunkSize);
290 if (opts.windowBits) {
291 if (opts.windowBits < exports.Z_MIN_WINDOWBITS ||
292 opts.windowBits > exports.Z_MAX_WINDOWBITS) {
293 throw new Error('Invalid windowBits: ' + opts.windowBits);
298 if (opts.level < exports.Z_MIN_LEVEL ||
299 opts.level > exports.Z_MAX_LEVEL) {
300 throw new Error('Invalid compression level: ' + opts.level);
305 if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||
306 opts.memLevel > exports.Z_MAX_MEMLEVEL) {
307 throw new Error('Invalid memLevel: ' + opts.memLevel);
312 if (opts.strategy != exports.Z_FILTERED &&
313 opts.strategy != exports.Z_HUFFMAN_ONLY &&
314 opts.strategy != exports.Z_RLE &&
315 opts.strategy != exports.Z_FIXED &&
316 opts.strategy != exports.Z_DEFAULT_STRATEGY) {
317 throw new Error('Invalid strategy: ' + opts.strategy);
321 if (opts.dictionary) {
322 if (!util.isBuffer(opts.dictionary)) {
323 throw new Error('Invalid dictionary: it should be a Buffer instance');
327 this._binding = new binding.Zlib(mode);
330 this._hadError = false;
331 this._binding.onerror = function(message, errno) {
332 // there is no way to cleanly recover.
333 // continuing only obscures problems.
334 self._binding = null;
335 self._hadError = true;
337 var error = new Error(message);
339 error.code = exports.codes[errno];
340 self.emit('error', error);
343 var level = exports.Z_DEFAULT_COMPRESSION;
344 if (util.isNumber(opts.level)) level = opts.level;
346 var strategy = exports.Z_DEFAULT_STRATEGY;
347 if (util.isNumber(opts.strategy)) strategy = opts.strategy;
349 this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
351 opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
355 this._buffer = new Buffer(this._chunkSize);
357 this._closed = false;
359 this._strategy = strategy;
361 this.once('end', this.close);
364 util.inherits(Zlib, Transform);
366 Zlib.prototype.params = function(level, strategy, callback) {
367 if (level < exports.Z_MIN_LEVEL ||
368 level > exports.Z_MAX_LEVEL) {
369 throw new RangeError('Invalid compression level: ' + level);
371 if (strategy != exports.Z_FILTERED &&
372 strategy != exports.Z_HUFFMAN_ONLY &&
373 strategy != exports.Z_RLE &&
374 strategy != exports.Z_FIXED &&
375 strategy != exports.Z_DEFAULT_STRATEGY) {
376 throw new TypeError('Invalid strategy: ' + strategy);
379 if (this._level !== level || this._strategy !== strategy) {
381 this.flush(binding.Z_SYNC_FLUSH, function() {
382 self._binding.params(level, strategy);
383 if (!self._hadError) {
385 self._strategy = strategy;
386 if (callback) callback();
390 process.nextTick(callback);
394 Zlib.prototype.reset = function() {
395 return this._binding.reset();
398 // This is the _flush function called by the transform class,
399 // internally, when the last chunk has been written.
400 Zlib.prototype._flush = function(callback) {
401 this._transform(new Buffer(0), '', callback);
404 Zlib.prototype.flush = function(kind, callback) {
405 var ws = this._writableState;
407 if (util.isFunction(kind) || (util.isUndefined(kind) && !callback)) {
409 kind = binding.Z_FULL_FLUSH;
414 process.nextTick(callback);
415 } else if (ws.ending) {
417 this.once('end', callback);
418 } else if (ws.needDrain) {
420 this.once('drain', function() {
421 self.flush(callback);
424 this._flushFlag = kind;
425 this.write(new Buffer(0), '', callback);
429 Zlib.prototype.close = function(callback) {
431 process.nextTick(callback);
438 this._binding.close();
441 process.nextTick(function() {
446 Zlib.prototype._transform = function(chunk, encoding, cb) {
448 var ws = this._writableState;
449 var ending = ws.ending || ws.ended;
450 var last = ending && (!chunk || ws.length === chunk.length);
452 if (!util.isNull(chunk) && !util.isBuffer(chunk))
453 return cb(new Error('invalid input'));
455 // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.
456 // If it's explicitly flushing at some other time, then we use
457 // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
460 flushFlag = binding.Z_FINISH;
462 flushFlag = this._flushFlag;
463 // once we've flushed the last of the queue, stop flushing and
464 // go back to the normal behavior.
465 if (chunk.length >= ws.length) {
466 this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
471 this._processChunk(chunk, flushFlag, cb);
474 Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
475 var availInBefore = chunk && chunk.length;
476 var availOutBefore = this._chunkSize - this._offset;
481 var async = util.isFunction(cb);
488 this.on('error', function(er) {
493 var res = this._binding.writeSync(flushFlag,
496 availInBefore, // in_len
498 this._offset, //out_off
499 availOutBefore); // out_len
500 } while (!this._hadError && callback(res[0], res[1]));
502 if (this._hadError) {
506 var buf = Buffer.concat(buffers, nread);
512 var req = this._binding.write(flushFlag,
515 availInBefore, // in_len
517 this._offset, //out_off
518 availOutBefore); // out_len
521 req.callback = callback;
523 function callback(availInAfter, availOutAfter) {
527 var have = availOutBefore - availOutAfter;
528 assert(have >= 0, 'have should not go down');
531 var out = self._buffer.slice(self._offset, self._offset + have);
532 self._offset += have;
533 // serve some output to the consumer.
542 // exhausted the output buffer, or used all the input create a new one.
543 if (availOutAfter === 0 || self._offset >= self._chunkSize) {
544 availOutBefore = self._chunkSize;
546 self._buffer = new Buffer(self._chunkSize);
549 if (availOutAfter === 0) {
550 // Not actually done. Need to reprocess.
551 // Also, update the availInBefore to the availInAfter value,
552 // so that if we have to hit it a third (fourth, etc.) time,
553 // it'll have the correct byte counts.
554 inOff += (availInBefore - availInAfter);
555 availInBefore = availInAfter;
560 var newReq = self._binding.write(flushFlag,
567 newReq.callback = callback; // this same function
568 newReq.buffer = chunk;
575 // finished with the chunk.
580 util.inherits(Deflate, Zlib);
581 util.inherits(Inflate, Zlib);
582 util.inherits(Gzip, Zlib);
583 util.inherits(Gunzip, Zlib);
584 util.inherits(DeflateRaw, Zlib);
585 util.inherits(InflateRaw, Zlib);
586 util.inherits(Unzip, Zlib);