2acde58fd4053ea10704a3eede4bf00f16fb09be
[platform/upstream/nodejs.git] / lib / zlib.js
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 = process.binding('zlib');
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 var bkeys = Object.keys(binding);
51 for (var bk = 0; bk < bkeys.length; bk++) {
52   var bkey = bkeys[bk];
53   if (bkey.match(/^Z/)) exports[bkey] = binding[bkey];
54 }
55
56 // translation table for return codes.
57 exports.codes = {
58   Z_OK: binding.Z_OK,
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
67 };
68
69 var ckeys = Object.keys(exports.codes);
70 for (var ck = 0; ck < ckeys.length; ck++) {
71   var ckey = ckeys[ck];
72   exports.codes[exports.codes[ckey]] = ckey;
73 }
74
75 exports.Deflate = Deflate;
76 exports.Inflate = Inflate;
77 exports.Gzip = Gzip;
78 exports.Gunzip = Gunzip;
79 exports.DeflateRaw = DeflateRaw;
80 exports.InflateRaw = InflateRaw;
81 exports.Unzip = Unzip;
82
83 exports.createDeflate = function(o) {
84   return new Deflate(o);
85 };
86
87 exports.createInflate = function(o) {
88   return new Inflate(o);
89 };
90
91 exports.createDeflateRaw = function(o) {
92   return new DeflateRaw(o);
93 };
94
95 exports.createInflateRaw = function(o) {
96   return new InflateRaw(o);
97 };
98
99 exports.createGzip = function(o) {
100   return new Gzip(o);
101 };
102
103 exports.createGunzip = function(o) {
104   return new Gunzip(o);
105 };
106
107 exports.createUnzip = function(o) {
108   return new Unzip(o);
109 };
110
111
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)) {
116     callback = opts;
117     opts = {};
118   }
119   return zlibBuffer(new Deflate(opts), buffer, callback);
120 };
121
122 exports.deflateSync = function(buffer, opts) {
123   return zlibBufferSync(new Deflate(opts), buffer);
124 };
125
126 exports.gzip = function(buffer, opts, callback) {
127   if (util.isFunction(opts)) {
128     callback = opts;
129     opts = {};
130   }
131   return zlibBuffer(new Gzip(opts), buffer, callback);
132 };
133
134 exports.gzipSync = function(buffer, opts) {
135   return zlibBufferSync(new Gzip(opts), buffer);
136 };
137
138 exports.deflateRaw = function(buffer, opts, callback) {
139   if (util.isFunction(opts)) {
140     callback = opts;
141     opts = {};
142   }
143   return zlibBuffer(new DeflateRaw(opts), buffer, callback);
144 };
145
146 exports.deflateRawSync = function(buffer, opts) {
147   return zlibBufferSync(new DeflateRaw(opts), buffer);
148 };
149
150 exports.unzip = function(buffer, opts, callback) {
151   if (util.isFunction(opts)) {
152     callback = opts;
153     opts = {};
154   }
155   return zlibBuffer(new Unzip(opts), buffer, callback);
156 };
157
158 exports.unzipSync = function(buffer, opts) {
159   return zlibBufferSync(new Unzip(opts), buffer);
160 };
161
162 exports.inflate = function(buffer, opts, callback) {
163   if (util.isFunction(opts)) {
164     callback = opts;
165     opts = {};
166   }
167   return zlibBuffer(new Inflate(opts), buffer, callback);
168 };
169
170 exports.inflateSync = function(buffer, opts) {
171   return zlibBufferSync(new Inflate(opts), buffer);
172 };
173
174 exports.gunzip = function(buffer, opts, callback) {
175   if (util.isFunction(opts)) {
176     callback = opts;
177     opts = {};
178   }
179   return zlibBuffer(new Gunzip(opts), buffer, callback);
180 };
181
182 exports.gunzipSync = function(buffer, opts) {
183   return zlibBufferSync(new Gunzip(opts), buffer);
184 };
185
186 exports.inflateRaw = function(buffer, opts, callback) {
187   if (util.isFunction(opts)) {
188     callback = opts;
189     opts = {};
190   }
191   return zlibBuffer(new InflateRaw(opts), buffer, callback);
192 };
193
194 exports.inflateRawSync = function(buffer, opts) {
195   return zlibBufferSync(new InflateRaw(opts), buffer);
196 };
197
198 function zlibBuffer(engine, buffer, callback) {
199   var buffers = [];
200   var nread = 0;
201
202   engine.on('error', onError);
203   engine.on('end', onEnd);
204
205   engine.end(buffer);
206   flow();
207
208   function flow() {
209     var chunk;
210     while (null !== (chunk = engine.read())) {
211       buffers.push(chunk);
212       nread += chunk.length;
213     }
214     engine.once('readable', flow);
215   }
216
217   function onError(err) {
218     engine.removeListener('end', onEnd);
219     engine.removeListener('readable', flow);
220     callback(err);
221   }
222
223   function onEnd() {
224     var buf = Buffer.concat(buffers, nread);
225     buffers = [];
226     callback(null, buf);
227     engine.close();
228   }
229 }
230
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');
236
237   var flushFlag = binding.Z_FINISH;
238
239   return engine._processChunk(buffer, flushFlag);
240 }
241
242 // generic zlib
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);
247 }
248
249 function Inflate(opts) {
250   if (!(this instanceof Inflate)) return new Inflate(opts);
251   Zlib.call(this, opts, binding.INFLATE);
252 }
253
254
255
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);
260 }
261
262 function Gunzip(opts) {
263   if (!(this instanceof Gunzip)) return new Gunzip(opts);
264   Zlib.call(this, opts, binding.GUNZIP);
265 }
266
267
268
269 // raw - no header
270 function DeflateRaw(opts) {
271   if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
272   Zlib.call(this, opts, binding.DEFLATERAW);
273 }
274
275 function InflateRaw(opts) {
276   if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
277   Zlib.call(this, opts, binding.INFLATERAW);
278 }
279
280
281 // auto-detect header.
282 function Unzip(opts) {
283   if (!(this instanceof Unzip)) return new Unzip(opts);
284   Zlib.call(this, opts, binding.UNZIP);
285 }
286
287
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.
292
293 function Zlib(opts, mode) {
294   this._opts = opts = opts || {};
295   this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
296
297   Transform.call(this, opts);
298
299   if (opts.flush) {
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);
307     }
308   }
309   this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
310
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);
315     }
316   }
317
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);
322     }
323   }
324
325   if (opts.level) {
326     if (opts.level < exports.Z_MIN_LEVEL ||
327         opts.level > exports.Z_MAX_LEVEL) {
328       throw new Error('Invalid compression level: ' + opts.level);
329     }
330   }
331
332   if (opts.memLevel) {
333     if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||
334         opts.memLevel > exports.Z_MAX_MEMLEVEL) {
335       throw new Error('Invalid memLevel: ' + opts.memLevel);
336     }
337   }
338
339   if (opts.strategy) {
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);
346     }
347   }
348
349   if (opts.dictionary) {
350     if (!util.isBuffer(opts.dictionary)) {
351       throw new Error('Invalid dictionary: it should be a Buffer instance');
352     }
353   }
354
355   this._handle = new binding.Zlib(mode);
356
357   var self = this;
358   this._hadError = false;
359   this._handle.onerror = function(message, errno) {
360     // there is no way to cleanly recover.
361     // continuing only obscures problems.
362     self._handle = null;
363     self._hadError = true;
364
365     var error = new Error(message);
366     error.errno = errno;
367     error.code = exports.codes[errno];
368     self.emit('error', error);
369   };
370
371   var level = exports.Z_DEFAULT_COMPRESSION;
372   if (util.isNumber(opts.level)) level = opts.level;
373
374   var strategy = exports.Z_DEFAULT_STRATEGY;
375   if (util.isNumber(opts.strategy)) strategy = opts.strategy;
376
377   this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
378                     level,
379                     opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
380                     strategy,
381                     opts.dictionary);
382
383   this._buffer = new Buffer(this._chunkSize);
384   this._offset = 0;
385   this._closed = false;
386   this._level = level;
387   this._strategy = strategy;
388
389   this.once('end', this.close);
390 }
391
392 util.inherits(Zlib, Transform);
393
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);
398   }
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);
405   }
406
407   if (this._level !== level || this._strategy !== strategy) {
408     var self = this;
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) {
413         self._level = level;
414         self._strategy = strategy;
415         if (callback) callback();
416       }
417     });
418   } else {
419     process.nextTick(callback);
420   }
421 };
422
423 Zlib.prototype.reset = function() {
424   assert(!this._closed, 'zlib binding closed');
425   return this._handle.reset();
426 };
427
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);
432 };
433
434 Zlib.prototype.flush = function(kind, callback) {
435   var ws = this._writableState;
436
437   if (util.isFunction(kind) || (util.isUndefined(kind) && !callback)) {
438     callback = kind;
439     kind = binding.Z_FULL_FLUSH;
440   }
441
442   if (ws.ended) {
443     if (callback)
444       process.nextTick(callback);
445   } else if (ws.ending) {
446     if (callback)
447       this.once('end', callback);
448   } else if (ws.needDrain) {
449     var self = this;
450     this.once('drain', function() {
451       self.flush(callback);
452     });
453   } else {
454     this._flushFlag = kind;
455     this.write(new Buffer(0), '', callback);
456   }
457 };
458
459 Zlib.prototype.close = function(callback) {
460   if (callback)
461     process.nextTick(callback);
462
463   if (this._closed)
464     return;
465
466   this._closed = true;
467
468   this._handle.close();
469
470   var self = this;
471   process.nextTick(function() {
472     self.emit('close');
473   });
474 };
475
476 Zlib.prototype._transform = function(chunk, encoding, cb) {
477   var flushFlag;
478   var ws = this._writableState;
479   var ending = ws.ending || ws.ended;
480   var last = ending && (!chunk || ws.length === chunk.length);
481
482   if (!util.isNull(chunk) && !util.isBuffer(chunk))
483     return cb(new Error('invalid input'));
484
485   if (this._closed)
486     return cb(new Error('zlib binding closed'));
487
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
491   // goodness.
492   if (last)
493     flushFlag = binding.Z_FINISH;
494   else {
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;
500     }
501   }
502
503   this._processChunk(chunk, flushFlag, cb);
504 };
505
506 Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
507   var availInBefore = chunk && chunk.length;
508   var availOutBefore = this._chunkSize - this._offset;
509   var inOff = 0;
510
511   var self = this;
512
513   var async = util.isFunction(cb);
514
515   if (!async) {
516     var buffers = [];
517     var nread = 0;
518
519     var error;
520     this.on('error', function(er) {
521       error = er;
522     });
523
524     assert(!this._closed, 'zlib binding closed');
525     do {
526       var res = this._handle.writeSync(flushFlag,
527                                        chunk, // in
528                                        inOff, // in_off
529                                        availInBefore, // in_len
530                                        this._buffer, // out
531                                        this._offset, //out_off
532                                        availOutBefore); // out_len
533     } while (!this._hadError && callback(res[0], res[1]));
534
535     if (this._hadError) {
536       throw error;
537     }
538
539     var buf = Buffer.concat(buffers, nread);
540     this.close();
541
542     return buf;
543   }
544
545   assert(!this._closed, 'zlib binding closed');
546   var req = this._handle.write(flushFlag,
547                                chunk, // in
548                                inOff, // in_off
549                                availInBefore, // in_len
550                                this._buffer, // out
551                                this._offset, //out_off
552                                availOutBefore); // out_len
553
554   req.buffer = chunk;
555   req.callback = callback;
556
557   function callback(availInAfter, availOutAfter) {
558     if (self._hadError)
559       return;
560
561     var have = availOutBefore - availOutAfter;
562     assert(have >= 0, 'have should not go down');
563
564     if (have > 0) {
565       var out = self._buffer.slice(self._offset, self._offset + have);
566       self._offset += have;
567       // serve some output to the consumer.
568       if (async) {
569         self.push(out);
570       } else {
571         buffers.push(out);
572         nread += out.length;
573       }
574     }
575
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;
579       self._offset = 0;
580       self._buffer = new Buffer(self._chunkSize);
581     }
582
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;
590
591       if (availOutAfter !== 0) {
592         // There is still some data available for reading.
593         // This is usually a concatenated stream, so, reset and restart.
594         self.reset();
595         self._offset = 0;
596       }
597
598       if (!async)
599         return true;
600
601       var newReq = self._handle.write(flushFlag,
602                                       chunk,
603                                       inOff,
604                                       availInBefore,
605                                       self._buffer,
606                                       self._offset,
607                                       self._chunkSize);
608       newReq.callback = callback; // this same function
609       newReq.buffer = chunk;
610       return;
611     }
612
613     if (!async)
614       return false;
615
616     // finished with the chunk.
617     cb();
618   }
619 };
620
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);