node/lib/zlib.js

636 lines
17 KiB
JavaScript
Raw Normal View History

'use strict';
const Buffer = require('buffer').Buffer;
const Transform = require('_stream_transform');
const binding = process.binding('zlib');
const util = require('util');
const assert = require('assert').ok;
const kMaxLength = require('buffer').kMaxLength;
const kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' +
'than 0x' + kMaxLength.toString(16) + ' bytes';
2011-09-06 23:13:05 +00:00
const constants = process.binding('constants').zlib;
2011-09-06 23:13:05 +00:00
// These should be considered deprecated
2011-09-06 23:13:05 +00:00
// expose all the zlib constants
const bkeys = Object.keys(constants);
for (var bk = 0; bk < bkeys.length; bk++) {
var bkey = bkeys[bk];
Object.defineProperty(exports, bkey, {
enumerable: true, value: constants[bkey], writable: false
});
}
2011-09-06 23:13:05 +00:00
Object.defineProperty(exports, 'constants', {
configurable: false,
enumerable: true,
value: constants
});
// translation table for return codes.
const codes = {
Z_OK: constants.Z_OK,
Z_STREAM_END: constants.Z_STREAM_END,
Z_NEED_DICT: constants.Z_NEED_DICT,
Z_ERRNO: constants.Z_ERRNO,
Z_STREAM_ERROR: constants.Z_STREAM_ERROR,
Z_DATA_ERROR: constants.Z_DATA_ERROR,
Z_MEM_ERROR: constants.Z_MEM_ERROR,
Z_BUF_ERROR: constants.Z_BUF_ERROR,
Z_VERSION_ERROR: constants.Z_VERSION_ERROR
};
const ckeys = Object.keys(codes);
for (var ck = 0; ck < ckeys.length; ck++) {
var ckey = ckeys[ck];
codes[codes[ckey]] = ckey;
}
2011-09-06 23:13:05 +00:00
Object.defineProperty(exports, 'codes', {
enumerable: true, value: Object.freeze(codes), writable: false
});
2011-09-06 23:13:05 +00:00
exports.Deflate = Deflate;
exports.Inflate = Inflate;
exports.Gzip = Gzip;
exports.Gunzip = Gunzip;
exports.DeflateRaw = DeflateRaw;
exports.InflateRaw = InflateRaw;
exports.Unzip = Unzip;
2011-09-18 06:03:36 +00:00
exports.createDeflate = function(o) {
return new Deflate(o);
};
exports.createInflate = function(o) {
return new Inflate(o);
};
exports.createDeflateRaw = function(o) {
return new DeflateRaw(o);
};
exports.createInflateRaw = function(o) {
return new InflateRaw(o);
};
exports.createGzip = function(o) {
return new Gzip(o);
};
exports.createGunzip = function(o) {
return new Gunzip(o);
};
exports.createUnzip = function(o) {
return new Unzip(o);
};
2011-09-06 23:13:05 +00:00
// Convenience methods.
// compress/decompress a string or buffer in one step.
exports.deflate = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Deflate(opts), buffer, callback);
};
2014-02-03 07:55:47 +00:00
exports.deflateSync = function(buffer, opts) {
return zlibBufferSync(new Deflate(opts), buffer);
};
exports.gzip = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Gzip(opts), buffer, callback);
};
2014-02-03 07:55:47 +00:00
exports.gzipSync = function(buffer, opts) {
return zlibBufferSync(new Gzip(opts), buffer);
};
exports.deflateRaw = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new DeflateRaw(opts), buffer, callback);
};
2014-02-03 07:55:47 +00:00
exports.deflateRawSync = function(buffer, opts) {
return zlibBufferSync(new DeflateRaw(opts), buffer);
};
exports.unzip = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Unzip(opts), buffer, callback);
};
2014-02-03 07:55:47 +00:00
exports.unzipSync = function(buffer, opts) {
return zlibBufferSync(new Unzip(opts), buffer);
};
exports.inflate = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Inflate(opts), buffer, callback);
};
2014-02-03 07:55:47 +00:00
exports.inflateSync = function(buffer, opts) {
return zlibBufferSync(new Inflate(opts), buffer);
};
exports.gunzip = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Gunzip(opts), buffer, callback);
};
2014-02-03 07:55:47 +00:00
exports.gunzipSync = function(buffer, opts) {
return zlibBufferSync(new Gunzip(opts), buffer);
};
exports.inflateRaw = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new InflateRaw(opts), buffer, callback);
};
2014-02-03 07:55:47 +00:00
exports.inflateRawSync = function(buffer, opts) {
return zlibBufferSync(new InflateRaw(opts), buffer);
};
2014-02-03 07:55:47 +00:00
function zlibBuffer(engine, buffer, callback) {
var buffers = [];
var nread = 0;
2012-10-02 23:15:39 +00:00
engine.on('error', onError);
engine.on('end', onEnd);
engine.end(buffer);
flow();
function flow() {
var chunk;
while (null !== (chunk = engine.read())) {
buffers.push(chunk);
nread += chunk.length;
}
engine.once('readable', flow);
}
function onError(err) {
engine.removeListener('end', onEnd);
2012-10-02 23:15:39 +00:00
engine.removeListener('readable', flow);
callback(err);
}
function onEnd() {
var buf;
var err = null;
if (nread >= kMaxLength) {
err = new RangeError(kRangeErrorMessage);
} else {
buf = Buffer.concat(buffers, nread);
}
buffers = [];
Merge remote-tracking branch 'ry/v0.8' into master Conflicts: AUTHORS ChangeLog deps/npm/html/api/bin.html deps/npm/html/api/bugs.html deps/npm/html/api/commands.html deps/npm/html/api/config.html deps/npm/html/api/deprecate.html deps/npm/html/api/docs.html deps/npm/html/api/edit.html deps/npm/html/api/explore.html deps/npm/html/api/help-search.html deps/npm/html/api/init.html deps/npm/html/api/install.html deps/npm/html/api/link.html deps/npm/html/api/load.html deps/npm/html/api/ls.html deps/npm/html/api/npm.html deps/npm/html/api/outdated.html deps/npm/html/api/owner.html deps/npm/html/api/pack.html deps/npm/html/api/prefix.html deps/npm/html/api/prune.html deps/npm/html/api/publish.html deps/npm/html/api/rebuild.html deps/npm/html/api/restart.html deps/npm/html/api/root.html deps/npm/html/api/run-script.html deps/npm/html/api/search.html deps/npm/html/api/shrinkwrap.html deps/npm/html/api/start.html deps/npm/html/api/stop.html deps/npm/html/api/submodule.html deps/npm/html/api/tag.html deps/npm/html/api/test.html deps/npm/html/api/uninstall.html deps/npm/html/api/unpublish.html deps/npm/html/api/update.html deps/npm/html/api/version.html deps/npm/html/api/view.html deps/npm/html/api/whoami.html deps/npm/html/doc/README.html deps/npm/html/doc/adduser.html deps/npm/html/doc/bin.html deps/npm/html/doc/bugs.html deps/npm/html/doc/build.html deps/npm/html/doc/bundle.html deps/npm/html/doc/cache.html deps/npm/html/doc/changelog.html deps/npm/html/doc/coding-style.html deps/npm/html/doc/completion.html deps/npm/html/doc/config.html deps/npm/html/doc/dedupe.html deps/npm/html/doc/deprecate.html deps/npm/html/doc/developers.html deps/npm/html/doc/disputes.html deps/npm/html/doc/docs.html deps/npm/html/doc/edit.html deps/npm/html/doc/explore.html deps/npm/html/doc/faq.html deps/npm/html/doc/folders.html deps/npm/html/doc/global.html deps/npm/html/doc/help-search.html deps/npm/html/doc/help.html deps/npm/html/doc/index.html deps/npm/html/doc/init.html deps/npm/html/doc/install.html deps/npm/html/doc/json.html deps/npm/html/doc/link.html deps/npm/html/doc/ls.html deps/npm/html/doc/npm.html deps/npm/html/doc/outdated.html deps/npm/html/doc/owner.html deps/npm/html/doc/pack.html deps/npm/html/doc/prefix.html deps/npm/html/doc/prune.html deps/npm/html/doc/publish.html deps/npm/html/doc/rebuild.html deps/npm/html/doc/registry.html deps/npm/html/doc/removing-npm.html deps/npm/html/doc/restart.html deps/npm/html/doc/rm.html deps/npm/html/doc/root.html deps/npm/html/doc/run-script.html deps/npm/html/doc/scripts.html deps/npm/html/doc/search.html deps/npm/html/doc/semver.html deps/npm/html/doc/shrinkwrap.html deps/npm/html/doc/star.html deps/npm/html/doc/start.html deps/npm/html/doc/stop.html deps/npm/html/doc/submodule.html deps/npm/html/doc/tag.html deps/npm/html/doc/test.html deps/npm/html/doc/uninstall.html deps/npm/html/doc/unpublish.html deps/npm/html/doc/update.html deps/npm/html/doc/version.html deps/npm/html/doc/view.html deps/npm/html/doc/whoami.html deps/npm/man/man1/global.1 deps/npm/man/man1/ls.1 deps/npm/man/man1/npm.1 deps/npm/man/man1/rm.1 deps/npm/man/man3/npm.3 deps/npm/node_modules/glob/glob.js deps/npm/node_modules/glob/package.json deps/npm/node_modules/node-gyp/package.json deps/npm/node_modules/npm-registry-client/package.json deps/npm/node_modules/npmconf/package.json deps/npm/node_modules/read-installed/package.json deps/npm/node_modules/rimraf/package.json deps/npm/node_modules/rimraf/rimraf.js deps/npm/package.json deps/uv/src/win/error.c doc/api/crypto.markdown lib/zlib.js src/node_version.h src/node_zlib.cc test/simple/test-buffer.js
2013-02-07 00:29:30 +00:00
engine.close();
callback(err, buf);
}
}
2014-02-03 07:55:47 +00:00
function zlibBufferSync(engine, buffer) {
if (typeof buffer === 'string')
buffer = Buffer.from(buffer);
if (!(buffer instanceof Buffer))
throw new TypeError('Not a string or buffer');
var flushFlag = engine._finishFlushFlag;
return engine._processChunk(buffer, flushFlag);
}
2011-09-06 23:13:05 +00:00
// generic zlib
// minimal 2-byte header
function Deflate(opts) {
2011-09-26 18:50:20 +00:00
if (!(this instanceof Deflate)) return new Deflate(opts);
Zlib.call(this, opts, constants.DEFLATE);
2011-09-06 23:13:05 +00:00
}
function Inflate(opts) {
if (!(this instanceof Inflate)) return new Inflate(opts);
Zlib.call(this, opts, constants.INFLATE);
2011-09-06 23:13:05 +00:00
}
// gzip - bigger header, same deflate compression
function Gzip(opts) {
if (!(this instanceof Gzip)) return new Gzip(opts);
Zlib.call(this, opts, constants.GZIP);
2011-09-06 23:13:05 +00:00
}
function Gunzip(opts) {
if (!(this instanceof Gunzip)) return new Gunzip(opts);
Zlib.call(this, opts, constants.GUNZIP);
2011-09-06 23:13:05 +00:00
}
// raw - no header
function DeflateRaw(opts) {
if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
Zlib.call(this, opts, constants.DEFLATERAW);
2011-09-06 23:13:05 +00:00
}
function InflateRaw(opts) {
if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
Zlib.call(this, opts, constants.INFLATERAW);
2011-09-06 23:13:05 +00:00
}
// auto-detect header.
function Unzip(opts) {
if (!(this instanceof Unzip)) return new Unzip(opts);
Zlib.call(this, opts, constants.UNZIP);
2011-09-06 23:13:05 +00:00
}
function isValidFlushFlag(flag) {
return flag === constants.Z_NO_FLUSH ||
flag === constants.Z_PARTIAL_FLUSH ||
flag === constants.Z_SYNC_FLUSH ||
flag === constants.Z_FULL_FLUSH ||
flag === constants.Z_FINISH ||
flag === constants.Z_BLOCK;
}
2011-09-06 23:13:05 +00:00
// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.
function Zlib(opts, mode) {
2011-09-06 23:13:05 +00:00
this._opts = opts = opts || {};
this._chunkSize = opts.chunkSize || constants.Z_DEFAULT_CHUNK;
2012-10-02 23:15:39 +00:00
Transform.call(this, opts);
if (opts.flush && !isValidFlushFlag(opts.flush)) {
throw new Error('Invalid flush flag: ' + opts.flush);
}
if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
throw new Error('Invalid flush flag: ' + opts.finishFlush);
}
this._flushFlag = opts.flush || constants.Z_NO_FLUSH;
this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ?
opts.finishFlush : constants.Z_FINISH;
2011-09-06 23:13:05 +00:00
if (opts.chunkSize) {
if (opts.chunkSize < constants.Z_MIN_CHUNK) {
2011-09-18 06:03:36 +00:00
throw new Error('Invalid chunk size: ' + opts.chunkSize);
2011-09-06 23:13:05 +00:00
}
}
if (opts.windowBits) {
if (opts.windowBits < constants.Z_MIN_WINDOWBITS ||
opts.windowBits > constants.Z_MAX_WINDOWBITS) {
2011-09-18 06:03:36 +00:00
throw new Error('Invalid windowBits: ' + opts.windowBits);
2011-09-06 23:13:05 +00:00
}
}
if (opts.level) {
if (opts.level < constants.Z_MIN_LEVEL ||
opts.level > constants.Z_MAX_LEVEL) {
2011-09-18 06:03:36 +00:00
throw new Error('Invalid compression level: ' + opts.level);
2011-09-06 23:13:05 +00:00
}
}
if (opts.memLevel) {
if (opts.memLevel < constants.Z_MIN_MEMLEVEL ||
opts.memLevel > constants.Z_MAX_MEMLEVEL) {
2011-09-18 06:03:36 +00:00
throw new Error('Invalid memLevel: ' + opts.memLevel);
2011-09-06 23:13:05 +00:00
}
}
if (opts.strategy) {
if (opts.strategy != constants.Z_FILTERED &&
opts.strategy != constants.Z_HUFFMAN_ONLY &&
opts.strategy != constants.Z_RLE &&
opts.strategy != constants.Z_FIXED &&
opts.strategy != constants.Z_DEFAULT_STRATEGY) {
2011-09-18 06:03:36 +00:00
throw new Error('Invalid strategy: ' + opts.strategy);
2011-09-06 23:13:05 +00:00
}
}
2011-12-02 07:53:56 +00:00
if (opts.dictionary) {
if (!(opts.dictionary instanceof Buffer)) {
2011-12-02 07:53:56 +00:00
throw new Error('Invalid dictionary: it should be a Buffer instance');
}
}
this._handle = new binding.Zlib(mode);
var self = this;
2012-10-02 23:15:39 +00:00
this._hadError = false;
this._handle.onerror = function(message, errno) {
// there is no way to cleanly recover.
// continuing only obscures problems.
_close(self);
self._hadError = true;
var error = new Error(message);
error.errno = errno;
error.code = exports.codes[errno];
self.emit('error', error);
};
var level = constants.Z_DEFAULT_COMPRESSION;
if (typeof opts.level === 'number') level = opts.level;
var strategy = constants.Z_DEFAULT_STRATEGY;
if (typeof opts.strategy === 'number') strategy = opts.strategy;
this._handle.init(opts.windowBits || constants.Z_DEFAULT_WINDOWBITS,
level,
opts.memLevel || constants.Z_DEFAULT_MEMLEVEL,
strategy,
opts.dictionary);
2011-09-06 23:13:05 +00:00
this._buffer = Buffer.allocUnsafe(this._chunkSize);
2011-09-06 23:13:05 +00:00
this._offset = 0;
this._level = level;
this._strategy = strategy;
this.once('end', this.close);
Object.defineProperty(this, '_closed', {
get: () => { return !this._handle; },
configurable: true,
enumerable: true
});
2011-09-06 23:13:05 +00:00
}
2012-10-02 23:15:39 +00:00
util.inherits(Zlib, Transform);
2011-09-06 23:13:05 +00:00
Zlib.prototype.params = function(level, strategy, callback) {
if (level < constants.Z_MIN_LEVEL ||
level > constants.Z_MAX_LEVEL) {
throw new RangeError('Invalid compression level: ' + level);
}
if (strategy != constants.Z_FILTERED &&
strategy != constants.Z_HUFFMAN_ONLY &&
strategy != constants.Z_RLE &&
strategy != constants.Z_FIXED &&
strategy != constants.Z_DEFAULT_STRATEGY) {
throw new TypeError('Invalid strategy: ' + strategy);
}
if (this._level !== level || this._strategy !== strategy) {
var self = this;
this.flush(constants.Z_SYNC_FLUSH, function flushCallback() {
assert(self._handle, 'zlib binding closed');
self._handle.params(level, strategy);
if (!self._hadError) {
self._level = level;
self._strategy = strategy;
if (callback) callback();
}
});
} else {
process.nextTick(callback);
}
};
Zlib.prototype.reset = function() {
assert(this._handle, 'zlib binding closed');
return this._handle.reset();
};
// This is the _flush function called by the transform class,
// internally, when the last chunk has been written.
Zlib.prototype._flush = function(callback) {
this._transform(Buffer.alloc(0), '', callback);
2011-09-06 23:13:05 +00:00
};
Zlib.prototype.flush = function(kind, callback) {
2012-10-02 23:15:39 +00:00
var ws = this._writableState;
if (typeof kind === 'function' || (kind === undefined && !callback)) {
callback = kind;
kind = constants.Z_FULL_FLUSH;
}
if (ws.ended) {
if (callback)
process.nextTick(callback);
} else if (ws.ending) {
if (callback)
this.once('end', callback);
} else if (ws.needDrain) {
if (callback) {
const drainHandler = () => this.flush(kind, callback);
this.once('drain', drainHandler);
}
} else {
this._flushFlag = kind;
this.write(Buffer.alloc(0), '', callback);
}
2011-09-06 23:13:05 +00:00
};
Zlib.prototype.close = function(callback) {
_close(this, callback);
process.nextTick(emitCloseNT, this);
};
function _close(engine, callback) {
if (callback)
process.nextTick(callback);
// Caller may invoke .close after a zlib error (which will null _handle).
if (!engine._handle)
return;
engine._handle.close();
engine._handle = null;
}
function emitCloseNT(self) {
self.emit('close');
}
Zlib.prototype._transform = function(chunk, encoding, cb) {
2012-10-02 23:15:39 +00:00
var flushFlag;
var ws = this._writableState;
var ending = ws.ending || ws.ended;
var last = ending && (!chunk || ws.length === chunk.length);
if (chunk !== null && !(chunk instanceof Buffer))
2012-10-02 23:15:39 +00:00
return cb(new Error('invalid input'));
if (!this._handle)
return cb(new Error('zlib binding closed'));
// If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
// (or whatever flag was provided using opts.finishFlush).
2012-10-02 23:15:39 +00:00
// If it's explicitly flushing at some other time, then we use
// Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
// goodness.
if (last)
flushFlag = this._finishFlushFlag;
else {
flushFlag = this._flushFlag;
// once we've flushed the last of the queue, stop flushing and
// go back to the normal behavior.
if (chunk.length >= ws.length) {
this._flushFlag = this._opts.flush || constants.Z_NO_FLUSH;
}
}
2011-09-06 23:13:05 +00:00
this._processChunk(chunk, flushFlag, cb);
};
Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
2011-09-06 23:13:05 +00:00
var availInBefore = chunk && chunk.length;
var availOutBefore = this._chunkSize - this._offset;
var inOff = 0;
2012-10-02 23:15:39 +00:00
var self = this;
var async = typeof cb === 'function';
if (!async) {
var buffers = [];
var nread = 0;
var error;
this.on('error', function(er) {
error = er;
});
assert(this._handle, 'zlib binding closed');
do {
var res = this._handle.writeSync(flushFlag,
chunk, // in
inOff, // in_off
availInBefore, // in_len
this._buffer, // out
this._offset, //out_off
availOutBefore); // out_len
} while (!this._hadError && callback(res[0], res[1]));
if (this._hadError) {
throw error;
}
if (nread >= kMaxLength) {
_close(this);
throw new RangeError(kRangeErrorMessage);
}
var buf = Buffer.concat(buffers, nread);
_close(this);
return buf;
}
assert(this._handle, 'zlib binding closed');
var req = this._handle.write(flushFlag,
chunk, // in
inOff, // in_off
availInBefore, // in_len
this._buffer, // out
this._offset, //out_off
availOutBefore); // out_len
2011-09-06 23:13:05 +00:00
req.buffer = chunk;
req.callback = callback;
2013-07-01 09:42:57 +00:00
function callback(availInAfter, availOutAfter) {
// When the callback is used in an async write, the callback's
// context is the `req` object that was created. The req object
// is === this._handle, and that's why it's important to null
// out the values after they are done being used. `this._handle`
// can stay in memory longer than the callback and buffer are needed.
if (this) {
this.buffer = null;
this.callback = null;
}
2012-10-02 23:15:39 +00:00
if (self._hadError)
return;
var have = availOutBefore - availOutAfter;
assert(have >= 0, 'have should not go down');
2011-09-06 23:13:05 +00:00
if (have > 0) {
var out = self._buffer.slice(self._offset, self._offset + have);
self._offset += have;
2012-10-02 23:15:39 +00:00
// serve some output to the consumer.
if (async) {
self.push(out);
} else {
buffers.push(out);
nread += out.length;
}
2011-09-06 23:13:05 +00:00
}
2012-10-02 23:15:39 +00:00
// exhausted the output buffer, or used all the input create a new one.
2011-09-06 23:13:05 +00:00
if (availOutAfter === 0 || self._offset >= self._chunkSize) {
availOutBefore = self._chunkSize;
2011-09-06 23:13:05 +00:00
self._offset = 0;
self._buffer = Buffer.allocUnsafe(self._chunkSize);
2011-09-06 23:13:05 +00:00
}
if (availOutAfter === 0) {
2011-09-06 23:13:05 +00:00
// Not actually done. Need to reprocess.
// Also, update the availInBefore to the availInAfter value,
// so that if we have to hit it a third (fourth, etc.) time,
// it'll have the correct byte counts.
2011-09-06 23:13:05 +00:00
inOff += (availInBefore - availInAfter);
availInBefore = availInAfter;
if (!async)
return true;
var newReq = self._handle.write(flushFlag,
chunk,
inOff,
availInBefore,
self._buffer,
self._offset,
self._chunkSize);
2011-09-06 23:13:05 +00:00
newReq.callback = callback; // this same function
newReq.buffer = chunk;
return;
}
if (!async)
return false;
2011-09-06 23:13:05 +00:00
// finished with the chunk.
2012-10-02 23:15:39 +00:00
cb();
2011-09-06 23:13:05 +00:00
}
};
util.inherits(Deflate, Zlib);
util.inherits(Inflate, Zlib);
util.inherits(Gzip, Zlib);
util.inherits(Gunzip, Zlib);
util.inherits(DeflateRaw, Zlib);
util.inherits(InflateRaw, Zlib);
util.inherits(Unzip, Zlib);