1 /* $Id: tif_zip.c,v 1.37 2017-05-10 15:21:16 erouault Exp $ */
2 
3 /*
4  * Copyright (c) 1995-1997 Sam Leffler
5  * Copyright (c) 1995-1997 Silicon Graphics, Inc.
6  *
7  * Permission to use, copy, modify, distribute, and sell this software and
8  * its documentation for any purpose is hereby granted without fee, provided
9  * that (i) the above copyright notices and this permission notice appear in
10  * all copies of the software and related documentation, and (ii) the names of
11  * Sam Leffler and Silicon Graphics may not be used in any advertising or
12  * publicity relating to the software without the specific, prior written
13  * permission of Sam Leffler and Silicon Graphics.
14  *
15  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
18  *
19  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24  * OF THIS SOFTWARE.
25  */
26 
27 #include "tiffiop.h"
28 #ifdef ZIP_SUPPORT
29 /*
30  * TIFF Library.
31  *
32  * ZIP (aka Deflate) Compression Support
33  *
34  * This file is simply an interface to the zlib library written by
35  * Jean-loup Gailly and Mark Adler.  You must use version 1.0 or later
36  * of the library: this code assumes the 1.0 API and also depends on
37  * the ability to write the zlib header multiple times (one per strip)
38  * which was not possible with versions prior to 0.95.  Note also that
39  * older versions of this codec avoided this bug by suppressing the header
40  * entirely.  This means that files written with the old library cannot
41  * be read; they should be converted to a different compression scheme
42  * and then reconverted.
43  *
44  * The data format used by the zlib library is described in the files
45  * zlib-3.1.doc, deflate-1.1.doc and gzip-4.1.doc, available in the
46  * directory ftp://ftp.uu.net/pub/archiving/zip/doc.  The library was
47  * last found at ftp://ftp.uu.net/pub/archiving/zip/zlib/zlib-0.99.tar.gz.
48  */
49 #include "tif_predict.h"
50 #include "zlib.h"
51 
52 #include <stdio.h>
53 
54 /*
55  * Sigh, ZLIB_VERSION is defined as a string so there's no
56  * way to do a proper check here.  Instead we guess based
57  * on the presence of #defines that were added between the
58  * 0.95 and 1.0 distributions.
59  */
60 #if !defined(Z_NO_COMPRESSION) || !defined(Z_DEFLATED)
61 #error "Antiquated ZLIB software; you must use version 1.0 or later"
62 #endif
63 
64 #define SAFE_MSG(sp)   ((sp)->stream.msg == NULL ? "" : (sp)->stream.msg)
65 
66 /*
67  * State block for each open TIFF
68  * file using ZIP compression/decompression.
69  */
70 typedef struct {
71 	TIFFPredictorState predict;
72         z_stream        stream;
73 	int             zipquality;            /* compression level */
74 	int             state;                 /* state flags */
75 #define ZSTATE_INIT_DECODE 0x01
76 #define ZSTATE_INIT_ENCODE 0x02
77 
78 	TIFFVGetMethod  vgetparent;            /* super-class method */
79 	TIFFVSetMethod  vsetparent;            /* super-class method */
80 } ZIPState;
81 
82 #define ZState(tif)             ((ZIPState*) (tif)->tif_data)
83 #define DecoderState(tif)       ZState(tif)
84 #define EncoderState(tif)       ZState(tif)
85 
86 static int ZIPEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s);
87 static int ZIPDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s);
88 
89 static int
ZIPFixupTags(TIFF * tif)90 ZIPFixupTags(TIFF* tif)
91 {
92 	(void) tif;
93 	return (1);
94 }
95 
96 static int
ZIPSetupDecode(TIFF * tif)97 ZIPSetupDecode(TIFF* tif)
98 {
99 	static const char module[] = "ZIPSetupDecode";
100 	ZIPState* sp = DecoderState(tif);
101 
102 	assert(sp != NULL);
103 
104         /* if we were last encoding, terminate this mode */
105 	if (sp->state & ZSTATE_INIT_ENCODE) {
106 	    deflateEnd(&sp->stream);
107 	    sp->state = 0;
108 	}
109 
110 	/* This function can possibly be called several times by */
111 	/* PredictorSetupDecode() if this function succeeds but */
112 	/* PredictorSetup() fails */
113 	if ((sp->state & ZSTATE_INIT_DECODE) == 0 &&
114 	    inflateInit(&sp->stream) != Z_OK) {
115 		TIFFErrorExt(tif->tif_clientdata, module, "%s", SAFE_MSG(sp));
116 		return (0);
117 	} else {
118 		sp->state |= ZSTATE_INIT_DECODE;
119 		return (1);
120 	}
121 }
122 
123 /*
124  * Setup state for decoding a strip.
125  */
126 static int
ZIPPreDecode(TIFF * tif,uint16 s)127 ZIPPreDecode(TIFF* tif, uint16 s)
128 {
129 	static const char module[] = "ZIPPreDecode";
130 	ZIPState* sp = DecoderState(tif);
131 
132 	(void) s;
133 	assert(sp != NULL);
134 
135 	if( (sp->state & ZSTATE_INIT_DECODE) == 0 )
136             tif->tif_setupdecode( tif );
137 
138 	sp->stream.next_in = tif->tif_rawdata;
139 	assert(sizeof(sp->stream.avail_in)==4);  /* if this assert gets raised,
140 	    we need to simplify this code to reflect a ZLib that is likely updated
141 	    to deal with 8byte memory sizes, though this code will respond
142 	    appropriately even before we simplify it */
143 	sp->stream.avail_in = (uInt) tif->tif_rawcc;
144 	if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc)
145 	{
146 		TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
147 		return (0);
148 	}
149 	return (inflateReset(&sp->stream) == Z_OK);
150 }
151 
152 static int
ZIPDecode(TIFF * tif,uint8 * op,tmsize_t occ,uint16 s)153 ZIPDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
154 {
155 	static const char module[] = "ZIPDecode";
156 	ZIPState* sp = DecoderState(tif);
157 
158 	(void) s;
159 	assert(sp != NULL);
160 	assert(sp->state == ZSTATE_INIT_DECODE);
161 
162         sp->stream.next_in = tif->tif_rawcp;
163 	sp->stream.avail_in = (uInt) tif->tif_rawcc;
164 
165 	sp->stream.next_out = op;
166 	assert(sizeof(sp->stream.avail_out)==4);  /* if this assert gets raised,
167 	    we need to simplify this code to reflect a ZLib that is likely updated
168 	    to deal with 8byte memory sizes, though this code will respond
169 	    appropriately even before we simplify it */
170 	sp->stream.avail_out = (uInt) occ;
171 	if ((tmsize_t)sp->stream.avail_out != occ)
172 	{
173 		TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
174 		return (0);
175 	}
176 	do {
177 		int state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
178 		if (state == Z_STREAM_END)
179 			break;
180 		if (state == Z_DATA_ERROR) {
181 			TIFFErrorExt(tif->tif_clientdata, module,
182 			    "Decoding error at scanline %lu, %s",
183 			     (unsigned long) tif->tif_row, SAFE_MSG(sp));
184 			if (inflateSync(&sp->stream) != Z_OK)
185 				return (0);
186 			continue;
187 		}
188 		if (state != Z_OK) {
189 			TIFFErrorExt(tif->tif_clientdata, module,
190 				     "ZLib error: %s", SAFE_MSG(sp));
191 			return (0);
192 		}
193 	} while (sp->stream.avail_out > 0);
194 	if (sp->stream.avail_out != 0) {
195 		TIFFErrorExt(tif->tif_clientdata, module,
196 		    "Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)",
197 		    (unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out);
198 		return (0);
199 	}
200 
201         tif->tif_rawcp = sp->stream.next_in;
202         tif->tif_rawcc = sp->stream.avail_in;
203 
204 	return (1);
205 }
206 
207 static int
ZIPSetupEncode(TIFF * tif)208 ZIPSetupEncode(TIFF* tif)
209 {
210 	static const char module[] = "ZIPSetupEncode";
211 	ZIPState* sp = EncoderState(tif);
212 
213 	assert(sp != NULL);
214 	if (sp->state & ZSTATE_INIT_DECODE) {
215 		inflateEnd(&sp->stream);
216 		sp->state = 0;
217 	}
218 
219 	if (deflateInit(&sp->stream, sp->zipquality) != Z_OK) {
220 		TIFFErrorExt(tif->tif_clientdata, module, "%s", SAFE_MSG(sp));
221 		return (0);
222 	} else {
223 		sp->state |= ZSTATE_INIT_ENCODE;
224 		return (1);
225 	}
226 }
227 
228 /*
229  * Reset encoding state at the start of a strip.
230  */
231 static int
ZIPPreEncode(TIFF * tif,uint16 s)232 ZIPPreEncode(TIFF* tif, uint16 s)
233 {
234 	static const char module[] = "ZIPPreEncode";
235 	ZIPState *sp = EncoderState(tif);
236 
237 	(void) s;
238 	assert(sp != NULL);
239 	if( sp->state != ZSTATE_INIT_ENCODE )
240             tif->tif_setupencode( tif );
241 
242 	sp->stream.next_out = tif->tif_rawdata;
243 	assert(sizeof(sp->stream.avail_out)==4);  /* if this assert gets raised,
244 	    we need to simplify this code to reflect a ZLib that is likely updated
245 	    to deal with 8byte memory sizes, though this code will respond
246 	    appropriately even before we simplify it */
247 	sp->stream.avail_out = (uInt)tif->tif_rawdatasize;
248 	if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
249 	{
250 		TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
251 		return (0);
252 	}
253 	return (deflateReset(&sp->stream) == Z_OK);
254 }
255 
256 /*
257  * Encode a chunk of pixels.
258  */
259 static int
ZIPEncode(TIFF * tif,uint8 * bp,tmsize_t cc,uint16 s)260 ZIPEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
261 {
262 	static const char module[] = "ZIPEncode";
263 	ZIPState *sp = EncoderState(tif);
264 
265 	assert(sp != NULL);
266 	assert(sp->state == ZSTATE_INIT_ENCODE);
267 
268 	(void) s;
269 	sp->stream.next_in = bp;
270 	assert(sizeof(sp->stream.avail_in)==4);  /* if this assert gets raised,
271 	    we need to simplify this code to reflect a ZLib that is likely updated
272 	    to deal with 8byte memory sizes, though this code will respond
273 	    appropriately even before we simplify it */
274 	sp->stream.avail_in = (uInt) cc;
275 	if ((tmsize_t)sp->stream.avail_in != cc)
276 	{
277 		TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
278 		return (0);
279 	}
280 	do {
281 		if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) {
282 			TIFFErrorExt(tif->tif_clientdata, module,
283 				     "Encoder error: %s",
284 				     SAFE_MSG(sp));
285 			return (0);
286 		}
287 		if (sp->stream.avail_out == 0) {
288 			tif->tif_rawcc = tif->tif_rawdatasize;
289 			TIFFFlushData1(tif);
290 			sp->stream.next_out = tif->tif_rawdata;
291 			sp->stream.avail_out = (uInt) tif->tif_rawdatasize;  /* this is a safe typecast, as check is made already in ZIPPreEncode */
292 		}
293 	} while (sp->stream.avail_in > 0);
294 	return (1);
295 }
296 
297 /*
298  * Finish off an encoded strip by flushing the last
299  * string and tacking on an End Of Information code.
300  */
301 static int
ZIPPostEncode(TIFF * tif)302 ZIPPostEncode(TIFF* tif)
303 {
304 	static const char module[] = "ZIPPostEncode";
305 	ZIPState *sp = EncoderState(tif);
306 	int state;
307 
308 	sp->stream.avail_in = 0;
309 	do {
310 		state = deflate(&sp->stream, Z_FINISH);
311 		switch (state) {
312 		case Z_STREAM_END:
313 		case Z_OK:
314 			if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
315 			{
316 				tif->tif_rawcc =  tif->tif_rawdatasize - sp->stream.avail_out;
317 				TIFFFlushData1(tif);
318 				sp->stream.next_out = tif->tif_rawdata;
319 				sp->stream.avail_out = (uInt) tif->tif_rawdatasize;  /* this is a safe typecast, as check is made already in ZIPPreEncode */
320 			}
321 			break;
322 		default:
323 			TIFFErrorExt(tif->tif_clientdata, module,
324 				     "ZLib error: %s", SAFE_MSG(sp));
325 			return (0);
326 		}
327 	} while (state != Z_STREAM_END);
328 	return (1);
329 }
330 
331 static void
ZIPCleanup(TIFF * tif)332 ZIPCleanup(TIFF* tif)
333 {
334 	ZIPState* sp = ZState(tif);
335 
336 	assert(sp != 0);
337 
338 	(void)TIFFPredictorCleanup(tif);
339 
340 	tif->tif_tagmethods.vgetfield = sp->vgetparent;
341 	tif->tif_tagmethods.vsetfield = sp->vsetparent;
342 
343 	if (sp->state & ZSTATE_INIT_ENCODE) {
344 		deflateEnd(&sp->stream);
345 		sp->state = 0;
346 	} else if( sp->state & ZSTATE_INIT_DECODE) {
347 		inflateEnd(&sp->stream);
348 		sp->state = 0;
349 	}
350 	_TIFFfree(sp);
351 	tif->tif_data = NULL;
352 
353 	_TIFFSetDefaultCompressionState(tif);
354 }
355 
356 static int
ZIPVSetField(TIFF * tif,uint32 tag,va_list ap)357 ZIPVSetField(TIFF* tif, uint32 tag, va_list ap)
358 {
359 	static const char module[] = "ZIPVSetField";
360 	ZIPState* sp = ZState(tif);
361 
362 	switch (tag) {
363 	case TIFFTAG_ZIPQUALITY:
364 		sp->zipquality = (int) va_arg(ap, int);
365 		if ( sp->state&ZSTATE_INIT_ENCODE ) {
366 			if (deflateParams(&sp->stream,
367 			    sp->zipquality, Z_DEFAULT_STRATEGY) != Z_OK) {
368 				TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
369 					     SAFE_MSG(sp));
370 				return (0);
371 			}
372 		}
373 		return (1);
374 	default:
375 		return (*sp->vsetparent)(tif, tag, ap);
376 	}
377 	/*NOTREACHED*/
378 }
379 
380 static int
ZIPVGetField(TIFF * tif,uint32 tag,va_list ap)381 ZIPVGetField(TIFF* tif, uint32 tag, va_list ap)
382 {
383 	ZIPState* sp = ZState(tif);
384 
385 	switch (tag) {
386 	case TIFFTAG_ZIPQUALITY:
387 		*va_arg(ap, int*) = sp->zipquality;
388 		break;
389 	default:
390 		return (*sp->vgetparent)(tif, tag, ap);
391 	}
392 	return (1);
393 }
394 
395 static const TIFFField zipFields[] = {
396     { TIFFTAG_ZIPQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "", NULL },
397 };
398 
399 int
TIFFInitZIP(TIFF * tif,int scheme)400 TIFFInitZIP(TIFF* tif, int scheme)
401 {
402 	static const char module[] = "TIFFInitZIP";
403 	ZIPState* sp;
404 
405 	assert( (scheme == COMPRESSION_DEFLATE)
406 		|| (scheme == COMPRESSION_ADOBE_DEFLATE));
407 
408 	/*
409 	 * Merge codec-specific tag information.
410 	 */
411 	if (!_TIFFMergeFields(tif, zipFields, TIFFArrayCount(zipFields))) {
412 		TIFFErrorExt(tif->tif_clientdata, module,
413 			     "Merging Deflate codec-specific tags failed");
414 		return 0;
415 	}
416 
417 	/*
418 	 * Allocate state block so tag methods have storage to record values.
419 	 */
420 	tif->tif_data = (uint8*) _TIFFmalloc(sizeof (ZIPState));
421 	if (tif->tif_data == NULL)
422 		goto bad;
423 	sp = ZState(tif);
424 	sp->stream.zalloc = NULL;
425 	sp->stream.zfree = NULL;
426 	sp->stream.opaque = NULL;
427 	sp->stream.data_type = Z_BINARY;
428 
429 	/*
430 	 * Override parent get/set field methods.
431 	 */
432 	sp->vgetparent = tif->tif_tagmethods.vgetfield;
433 	tif->tif_tagmethods.vgetfield = ZIPVGetField; /* hook for codec tags */
434 	sp->vsetparent = tif->tif_tagmethods.vsetfield;
435 	tif->tif_tagmethods.vsetfield = ZIPVSetField; /* hook for codec tags */
436 
437 	/* Default values for codec-specific fields */
438 	sp->zipquality = Z_DEFAULT_COMPRESSION;	/* default comp. level */
439 	sp->state = 0;
440 
441 	/*
442 	 * Install codec methods.
443 	 */
444 	tif->tif_fixuptags = ZIPFixupTags;
445 	tif->tif_setupdecode = ZIPSetupDecode;
446 	tif->tif_predecode = ZIPPreDecode;
447 	tif->tif_decoderow = ZIPDecode;
448 	tif->tif_decodestrip = ZIPDecode;
449 	tif->tif_decodetile = ZIPDecode;
450 	tif->tif_setupencode = ZIPSetupEncode;
451 	tif->tif_preencode = ZIPPreEncode;
452 	tif->tif_postencode = ZIPPostEncode;
453 	tif->tif_encoderow = ZIPEncode;
454 	tif->tif_encodestrip = ZIPEncode;
455 	tif->tif_encodetile = ZIPEncode;
456 	tif->tif_cleanup = ZIPCleanup;
457 	/*
458 	 * Setup predictor setup.
459 	 */
460 	(void) TIFFPredictorInit(tif);
461 	return (1);
462 bad:
463 	TIFFErrorExt(tif->tif_clientdata, module,
464 		     "No space for ZIP state block");
465 	return (0);
466 }
467 #endif /* ZIP_SUPPORT */
468 
469 /* vim: set ts=8 sts=8 sw=8 noet: */
470 /*
471  * Local Variables:
472  * mode: c
473  * c-basic-offset: 8
474  * fill-column: 78
475  * End:
476  */
477