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 var bkeys = Object.keys(binding);
51 for (var bk = 0; bk < bkeys.length; bk++) {
53 if (bkey.match(/^Z/)) exports[bkey] = binding[bkey];
56 // translation table for return codes.
59 Z_STREAM_END: binding.Z_STREAM_END,
60 Z_NEED_DICT: binding.Z_NEED_DICT,
61 Z_ERRNO: binding.Z_ERRNO,
62 Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
63 Z_DATA_ERROR: binding.Z_DATA_ERROR,
64 Z_MEM_ERROR: binding.Z_MEM_ERROR,
65 Z_BUF_ERROR: binding.Z_BUF_ERROR,
66 Z_VERSION_ERROR: binding.Z_VERSION_ERROR
69 var ckeys = Object.keys(exports.codes);
70 for (var ck = 0; ck < ckeys.length; ck++) {
72 exports.codes[exports.codes[ckey]] = ckey;
75 exports.Deflate = Deflate;
76 exports.Inflate = Inflate;
78 exports.Gunzip = Gunzip;
79 exports.DeflateRaw = DeflateRaw;
80 exports.InflateRaw = InflateRaw;
81 exports.Unzip = Unzip;
83 exports.createDeflate = function(o) {
84 return new Deflate(o);
87 exports.createInflate = function(o) {
88 return new Inflate(o);
91 exports.createDeflateRaw = function(o) {
92 return new DeflateRaw(o);
95 exports.createInflateRaw = function(o) {
96 return new InflateRaw(o);
99 exports.createGzip = function(o) {
103 exports.createGunzip = function(o) {
104 return new Gunzip(o);
107 exports.createUnzip = function(o) {
112 // Convenience methods.
113 // compress/decompress a string or buffer in one step.
114 exports.deflate = function(buffer, opts, callback) {
115 if (util.isFunction(opts)) {
119 return zlibBuffer(new Deflate(opts), buffer, callback);
122 exports.deflateSync = function(buffer, opts) {
123 return zlibBufferSync(new Deflate(opts), buffer);
126 exports.gzip = function(buffer, opts, callback) {
127 if (util.isFunction(opts)) {
131 return zlibBuffer(new Gzip(opts), buffer, callback);
134 exports.gzipSync = function(buffer, opts) {
135 return zlibBufferSync(new Gzip(opts), buffer);
138 exports.deflateRaw = function(buffer, opts, callback) {
139 if (util.isFunction(opts)) {
143 return zlibBuffer(new DeflateRaw(opts), buffer, callback);
146 exports.deflateRawSync = function(buffer, opts) {
147 return zlibBufferSync(new DeflateRaw(opts), buffer);
150 exports.unzip = function(buffer, opts, callback) {
151 if (util.isFunction(opts)) {
155 return zlibBuffer(new Unzip(opts), buffer, callback);
158 exports.unzipSync = function(buffer, opts) {
159 return zlibBufferSync(new Unzip(opts), buffer);
162 exports.inflate = function(buffer, opts, callback) {
163 if (util.isFunction(opts)) {
167 return zlibBuffer(new Inflate(opts), buffer, callback);
170 exports.inflateSync = function(buffer, opts) {
171 return zlibBufferSync(new Inflate(opts), buffer);
174 exports.gunzip = function(buffer, opts, callback) {
175 if (util.isFunction(opts)) {
179 return zlibBuffer(new Gunzip(opts), buffer, callback);
182 exports.gunzipSync = function(buffer, opts) {
183 return zlibBufferSync(new Gunzip(opts), buffer);
186 exports.inflateRaw = function(buffer, opts, callback) {
187 if (util.isFunction(opts)) {
191 return zlibBuffer(new InflateRaw(opts), buffer, callback);
194 exports.inflateRawSync = function(buffer, opts) {
195 return zlibBufferSync(new InflateRaw(opts), buffer);
198 function zlibBuffer(engine, buffer, callback) {
202 engine.on('error', onError);
203 engine.on('end', onEnd);
210 while (null !== (chunk = engine.read())) {
212 nread += chunk.length;
214 engine.once('readable', flow);
217 function onError(err) {
218 engine.removeListener('end', onEnd);
219 engine.removeListener('readable', flow);
224 var buf = Buffer.concat(buffers, nread);
231 function zlibBufferSync(engine, buffer) {
232 if (util.isString(buffer))
233 buffer = new Buffer(buffer);
234 if (!util.isBuffer(buffer))
235 throw new TypeError('Not a string or buffer');
237 var flushFlag = binding.Z_FINISH;
239 return engine._processChunk(buffer, flushFlag);
243 // minimal 2-byte header
244 function Deflate(opts) {
245 if (!(this instanceof Deflate)) return new Deflate(opts);
246 Zlib.call(this, opts, binding.DEFLATE);
249 function Inflate(opts) {
250 if (!(this instanceof Inflate)) return new Inflate(opts);
251 Zlib.call(this, opts, binding.INFLATE);
256 // gzip - bigger header, same deflate compression
257 function Gzip(opts) {
258 if (!(this instanceof Gzip)) return new Gzip(opts);
259 Zlib.call(this, opts, binding.GZIP);
262 function Gunzip(opts) {
263 if (!(this instanceof Gunzip)) return new Gunzip(opts);
264 Zlib.call(this, opts, binding.GUNZIP);
270 function DeflateRaw(opts) {
271 if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
272 Zlib.call(this, opts, binding.DEFLATERAW);
275 function InflateRaw(opts) {
276 if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
277 Zlib.call(this, opts, binding.INFLATERAW);
281 // auto-detect header.
282 function Unzip(opts) {
283 if (!(this instanceof Unzip)) return new Unzip(opts);
284 Zlib.call(this, opts, binding.UNZIP);
288 // the Zlib class they all inherit from
289 // This thing manages the queue of requests, and returns
290 // true or false if there is anything in the queue when
291 // you call the .write() method.
293 function Zlib(opts, mode) {
294 this._opts = opts = opts || {};
295 this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
297 Transform.call(this, opts);
300 if (opts.flush !== binding.Z_NO_FLUSH &&
301 opts.flush !== binding.Z_PARTIAL_FLUSH &&
302 opts.flush !== binding.Z_SYNC_FLUSH &&
303 opts.flush !== binding.Z_FULL_FLUSH &&
304 opts.flush !== binding.Z_FINISH &&
305 opts.flush !== binding.Z_BLOCK) {
306 throw new Error('Invalid flush flag: ' + opts.flush);
309 this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
311 if (opts.chunkSize) {
312 if (opts.chunkSize < exports.Z_MIN_CHUNK ||
313 opts.chunkSize > exports.Z_MAX_CHUNK) {
314 throw new Error('Invalid chunk size: ' + opts.chunkSize);
318 if (opts.windowBits) {
319 if (opts.windowBits < exports.Z_MIN_WINDOWBITS ||
320 opts.windowBits > exports.Z_MAX_WINDOWBITS) {
321 throw new Error('Invalid windowBits: ' + opts.windowBits);
326 if (opts.level < exports.Z_MIN_LEVEL ||
327 opts.level > exports.Z_MAX_LEVEL) {
328 throw new Error('Invalid compression level: ' + opts.level);
333 if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||
334 opts.memLevel > exports.Z_MAX_MEMLEVEL) {
335 throw new Error('Invalid memLevel: ' + opts.memLevel);
340 if (opts.strategy != exports.Z_FILTERED &&
341 opts.strategy != exports.Z_HUFFMAN_ONLY &&
342 opts.strategy != exports.Z_RLE &&
343 opts.strategy != exports.Z_FIXED &&
344 opts.strategy != exports.Z_DEFAULT_STRATEGY) {
345 throw new Error('Invalid strategy: ' + opts.strategy);
349 if (opts.dictionary) {
350 if (!util.isBuffer(opts.dictionary)) {
351 throw new Error('Invalid dictionary: it should be a Buffer instance');
355 this._handle = new binding.Zlib(mode);
358 this._hadError = false;
359 this._handle.onerror = function(message, errno) {
360 // there is no way to cleanly recover.
361 // continuing only obscures problems.
363 self._hadError = true;
365 var error = new Error(message);
367 error.code = exports.codes[errno];
368 self.emit('error', error);
371 var level = exports.Z_DEFAULT_COMPRESSION;
372 if (util.isNumber(opts.level)) level = opts.level;
374 var strategy = exports.Z_DEFAULT_STRATEGY;
375 if (util.isNumber(opts.strategy)) strategy = opts.strategy;
377 this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
379 opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
383 this._buffer = new Buffer(this._chunkSize);
385 this._closed = false;
387 this._strategy = strategy;
389 this.once('end', this.close);
392 util.inherits(Zlib, Transform);
394 Zlib.prototype.params = function(level, strategy, callback) {
395 if (level < exports.Z_MIN_LEVEL ||
396 level > exports.Z_MAX_LEVEL) {
397 throw new RangeError('Invalid compression level: ' + level);
399 if (strategy != exports.Z_FILTERED &&
400 strategy != exports.Z_HUFFMAN_ONLY &&
401 strategy != exports.Z_RLE &&
402 strategy != exports.Z_FIXED &&
403 strategy != exports.Z_DEFAULT_STRATEGY) {
404 throw new TypeError('Invalid strategy: ' + strategy);
407 if (this._level !== level || this._strategy !== strategy) {
409 this.flush(binding.Z_SYNC_FLUSH, function() {
410 assert(!self._closed, 'zlib binding closed');
411 self._handle.params(level, strategy);
412 if (!self._hadError) {
414 self._strategy = strategy;
415 if (callback) callback();
419 process.nextTick(callback);
423 Zlib.prototype.reset = function() {
424 assert(!this._closed, 'zlib binding closed');
425 return this._handle.reset();
428 // This is the _flush function called by the transform class,
429 // internally, when the last chunk has been written.
430 Zlib.prototype._flush = function(callback) {
431 this._transform(new Buffer(0), '', callback);
434 Zlib.prototype.flush = function(kind, callback) {
435 var ws = this._writableState;
437 if (util.isFunction(kind) || (util.isUndefined(kind) && !callback)) {
439 kind = binding.Z_FULL_FLUSH;
444 process.nextTick(callback);
445 } else if (ws.ending) {
447 this.once('end', callback);
448 } else if (ws.needDrain) {
450 this.once('drain', function() {
451 self.flush(callback);
454 this._flushFlag = kind;
455 this.write(new Buffer(0), '', callback);
459 Zlib.prototype.close = function(callback) {
461 process.nextTick(callback);
468 this._handle.close();
471 process.nextTick(function() {
476 Zlib.prototype._transform = function(chunk, encoding, cb) {
478 var ws = this._writableState;
479 var ending = ws.ending || ws.ended;
480 var last = ending && (!chunk || ws.length === chunk.length);
482 if (!util.isNull(chunk) && !util.isBuffer(chunk))
483 return cb(new Error('invalid input'));
486 return cb(new Error('zlib binding closed'));
488 // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.
489 // If it's explicitly flushing at some other time, then we use
490 // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
493 flushFlag = binding.Z_FINISH;
495 flushFlag = this._flushFlag;
496 // once we've flushed the last of the queue, stop flushing and
497 // go back to the normal behavior.
498 if (chunk.length >= ws.length) {
499 this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
503 this._processChunk(chunk, flushFlag, cb);
506 Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
507 var availInBefore = chunk && chunk.length;
508 var availOutBefore = this._chunkSize - this._offset;
513 var async = util.isFunction(cb);
520 this.on('error', function(er) {
524 assert(!this._closed, 'zlib binding closed');
526 var res = this._handle.writeSync(flushFlag,
529 availInBefore, // in_len
531 this._offset, //out_off
532 availOutBefore); // out_len
533 } while (!this._hadError && callback(res[0], res[1]));
535 if (this._hadError) {
539 var buf = Buffer.concat(buffers, nread);
545 assert(!this._closed, 'zlib binding closed');
546 var req = this._handle.write(flushFlag,
549 availInBefore, // in_len
551 this._offset, //out_off
552 availOutBefore); // out_len
555 req.callback = callback;
557 function callback(availInAfter, availOutAfter) {
561 var have = availOutBefore - availOutAfter;
562 assert(have >= 0, 'have should not go down');
565 var out = self._buffer.slice(self._offset, self._offset + have);
566 self._offset += have;
567 // serve some output to the consumer.
576 // exhausted the output buffer, or used all the input create a new one.
577 if (availOutAfter === 0 || self._offset >= self._chunkSize) {
578 availOutBefore = self._chunkSize;
580 self._buffer = new Buffer(self._chunkSize);
583 if (availOutAfter === 0 || availInAfter > 0) {
584 // Not actually done. Need to reprocess.
585 // Also, update the availInBefore to the availInAfter value,
586 // so that if we have to hit it a third (fourth, etc.) time,
587 // it'll have the correct byte counts.
588 inOff += (availInBefore - availInAfter);
589 availInBefore = availInAfter;
591 if (availOutAfter !== 0) {
592 // There is still some data available for reading.
593 // This is usually a concatenated stream, so, reset and restart.
601 var newReq = self._handle.write(flushFlag,
608 newReq.callback = callback; // this same function
609 newReq.buffer = chunk;
616 // finished with the chunk.
621 util.inherits(Deflate, Zlib);
622 util.inherits(Inflate, Zlib);
623 util.inherits(Gzip, Zlib);
624 util.inherits(Gunzip, Zlib);
625 util.inherits(DeflateRaw, Zlib);
626 util.inherits(InflateRaw, Zlib);
627 util.inherits(Unzip, Zlib);