zlib: add sync versions for convenience methods
[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 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 (util.isFunction(opts)) {
112     callback = opts;
113     opts = {};
114   }
115   return zlibBuffer(new Deflate(opts), buffer, callback);
116 };
117
118 exports.gzip = function(buffer, opts, callback) {
119   if (util.isFunction(opts)) {
120     callback = opts;
121     opts = {};
122   }
123   return zlibBuffer(new Gzip(opts), buffer, callback);
124 };
125
126 exports.deflateRaw = function(buffer, opts, callback) {
127   if (util.isFunction(opts)) {
128     callback = opts;
129     opts = {};
130   }
131   return zlibBuffer(new DeflateRaw(opts), buffer, callback);
132 };
133
134 exports.unzip = function(buffer, opts, callback) {
135   if (util.isFunction(opts)) {
136     callback = opts;
137     opts = {};
138   }
139   return zlibBuffer(new Unzip(opts), buffer, callback);
140 };
141
142 exports.inflate = function(buffer, opts, callback) {
143   if (util.isFunction(opts)) {
144     callback = opts;
145     opts = {};
146   }
147   return zlibBuffer(new Inflate(opts), buffer, callback);
148 };
149
150 exports.gunzip = function(buffer, opts, callback) {
151   if (util.isFunction(opts)) {
152     callback = opts;
153     opts = {};
154   }
155   return zlibBuffer(new Gunzip(opts), buffer, callback);
156 };
157
158 exports.inflateRaw = function(buffer, opts, callback) {
159   if (util.isFunction(opts)) {
160     callback = opts;
161     opts = {};
162   }
163   return zlibBuffer(new InflateRaw(opts), buffer, callback);
164 };
165
166 function zlibBuffer(engine, buffer, callback) {
167   if (!util.isFunction(callback)) {
168     return zlibBufferSync(engine, buffer, callback);
169   }
170
171   var buffers = [];
172   var nread = 0;
173
174   engine.on('error', onError);
175   engine.on('end', onEnd);
176
177   engine.end(buffer);
178   flow();
179
180   function flow() {
181     var chunk;
182     while (null !== (chunk = engine.read())) {
183       buffers.push(chunk);
184       nread += chunk.length;
185     }
186     engine.once('readable', flow);
187   }
188
189   function onError(err) {
190     engine.removeListener('end', onEnd);
191     engine.removeListener('readable', flow);
192     callback(err);
193   }
194
195   function onEnd() {
196     var buf = Buffer.concat(buffers, nread);
197     buffers = [];
198     callback(null, buf);
199     engine.close();
200   }
201 }
202
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');
208
209   var flushFlag = binding.Z_FINISH;
210
211   return engine._processChunk(buffer, flushFlag);
212 }
213
214 // generic zlib
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);
219 }
220
221 function Inflate(opts) {
222   if (!(this instanceof Inflate)) return new Inflate(opts);
223   Zlib.call(this, opts, binding.INFLATE);
224 }
225
226
227
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);
232 }
233
234 function Gunzip(opts) {
235   if (!(this instanceof Gunzip)) return new Gunzip(opts);
236   Zlib.call(this, opts, binding.GUNZIP);
237 }
238
239
240
241 // raw - no header
242 function DeflateRaw(opts) {
243   if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
244   Zlib.call(this, opts, binding.DEFLATERAW);
245 }
246
247 function InflateRaw(opts) {
248   if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
249   Zlib.call(this, opts, binding.INFLATERAW);
250 }
251
252
253 // auto-detect header.
254 function Unzip(opts) {
255   if (!(this instanceof Unzip)) return new Unzip(opts);
256   Zlib.call(this, opts, binding.UNZIP);
257 }
258
259
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.
264
265 function Zlib(opts, mode) {
266   this._opts = opts = opts || {};
267   this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
268
269   Transform.call(this, opts);
270
271   if (opts.flush) {
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);
279     }
280   }
281   this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
282
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);
287     }
288   }
289
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);
294     }
295   }
296
297   if (opts.level) {
298     if (opts.level < exports.Z_MIN_LEVEL ||
299         opts.level > exports.Z_MAX_LEVEL) {
300       throw new Error('Invalid compression level: ' + opts.level);
301     }
302   }
303
304   if (opts.memLevel) {
305     if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||
306         opts.memLevel > exports.Z_MAX_MEMLEVEL) {
307       throw new Error('Invalid memLevel: ' + opts.memLevel);
308     }
309   }
310
311   if (opts.strategy) {
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);
318     }
319   }
320
321   if (opts.dictionary) {
322     if (!util.isBuffer(opts.dictionary)) {
323       throw new Error('Invalid dictionary: it should be a Buffer instance');
324     }
325   }
326
327   this._binding = new binding.Zlib(mode);
328
329   var self = this;
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;
336
337     var error = new Error(message);
338     error.errno = errno;
339     error.code = exports.codes[errno];
340     self.emit('error', error);
341   };
342
343   var level = exports.Z_DEFAULT_COMPRESSION;
344   if (util.isNumber(opts.level)) level = opts.level;
345
346   var strategy = exports.Z_DEFAULT_STRATEGY;
347   if (util.isNumber(opts.strategy)) strategy = opts.strategy;
348
349   this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
350                      level,
351                      opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
352                      strategy,
353                      opts.dictionary);
354
355   this._buffer = new Buffer(this._chunkSize);
356   this._offset = 0;
357   this._closed = false;
358   this._level = level;
359   this._strategy = strategy;
360
361   this.once('end', this.close);
362 }
363
364 util.inherits(Zlib, Transform);
365
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);
370   }
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);
377   }
378
379   if (this._level !== level || this._strategy !== strategy) {
380     var self = this;
381     this.flush(binding.Z_SYNC_FLUSH, function() {
382       self._binding.params(level, strategy);
383       if (!self._hadError) {
384         self._level = level;
385         self._strategy = strategy;
386         if (callback) callback();
387       }
388     });
389   } else {
390     process.nextTick(callback);
391   }
392 };
393
394 Zlib.prototype.reset = function() {
395   return this._binding.reset();
396 };
397
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);
402 };
403
404 Zlib.prototype.flush = function(kind, callback) {
405   var ws = this._writableState;
406
407   if (util.isFunction(kind) || (util.isUndefined(kind) && !callback)) {
408     callback = kind;
409     kind = binding.Z_FULL_FLUSH;
410   }
411
412   if (ws.ended) {
413     if (callback)
414       process.nextTick(callback);
415   } else if (ws.ending) {
416     if (callback)
417       this.once('end', callback);
418   } else if (ws.needDrain) {
419     var self = this;
420     this.once('drain', function() {
421       self.flush(callback);
422     });
423   } else {
424     this._flushFlag = kind;
425     this.write(new Buffer(0), '', callback);
426   }
427 };
428
429 Zlib.prototype.close = function(callback) {
430   if (callback)
431     process.nextTick(callback);
432
433   if (this._closed)
434     return;
435
436   this._closed = true;
437
438   this._binding.close();
439
440   var self = this;
441   process.nextTick(function() {
442     self.emit('close');
443   });
444 };
445
446 Zlib.prototype._transform = function(chunk, encoding, cb) {
447   var flushFlag;
448   var ws = this._writableState;
449   var ending = ws.ending || ws.ended;
450   var last = ending && (!chunk || ws.length === chunk.length);
451
452   if (!util.isNull(chunk) && !util.isBuffer(chunk))
453     return cb(new Error('invalid input'));
454
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
458   // goodness.
459   if (last)
460     flushFlag = binding.Z_FINISH;
461   else {
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;
467     }
468   }
469
470   var self = this;
471   this._processChunk(chunk, flushFlag, cb);
472 };
473
474 Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
475   var availInBefore = chunk && chunk.length;
476   var availOutBefore = this._chunkSize - this._offset;
477   var inOff = 0;
478
479   var self = this;
480
481   var async = util.isFunction(cb);
482
483   if (!async) {
484     var buffers = [];
485     var nread = 0;
486
487     var error;
488     this.on('error', function(er) {
489       error = er;
490     });
491
492     do {
493       var res = this._binding.writeSync(flushFlag,
494                                         chunk, // in
495                                         inOff, // in_off
496                                         availInBefore, // in_len
497                                         this._buffer, // out
498                                         this._offset, //out_off
499                                         availOutBefore); // out_len
500     } while (!this._hadError && callback(res[0], res[1]));
501
502     if (this._hadError) {
503       throw error;
504     }
505
506     var buf = Buffer.concat(buffers, nread);
507     this.close();
508
509     return buf;
510   }
511
512   var req = this._binding.write(flushFlag,
513                                 chunk, // in
514                                 inOff, // in_off
515                                 availInBefore, // in_len
516                                 this._buffer, // out
517                                 this._offset, //out_off
518                                 availOutBefore); // out_len
519
520   req.buffer = chunk;
521   req.callback = callback;
522
523   function callback(availInAfter, availOutAfter) {
524     if (self._hadError)
525       return;
526
527     var have = availOutBefore - availOutAfter;
528     assert(have >= 0, 'have should not go down');
529
530     if (have > 0) {
531       var out = self._buffer.slice(self._offset, self._offset + have);
532       self._offset += have;
533       // serve some output to the consumer.
534       if (async) {
535         self.push(out);
536       } else {
537         buffers.push(out);
538         nread += out.length;
539       }
540     }
541
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;
545       self._offset = 0;
546       self._buffer = new Buffer(self._chunkSize);
547     }
548
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;
556
557       if (!async)
558         return true;
559
560       var newReq = self._binding.write(flushFlag,
561                                        chunk,
562                                        inOff,
563                                        availInBefore,
564                                        self._buffer,
565                                        self._offset,
566                                        self._chunkSize);
567       newReq.callback = callback; // this same function
568       newReq.buffer = chunk;
569       return;
570     }
571
572     if (!async)
573       return false;
574
575     // finished with the chunk.
576     cb();
577   }
578 };
579
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);