b2043e3fbcacda656a9eda92656608402e9566ea
[platform/upstream/libpng.git] / contrib / tools / pngfix.c
1 /* pngfix.c
2  *
3  * Copyright (c) 2014-2016 John Cunningham Bowler
4  *
5  * Last changed in libpng 1.6.21 [January 15, 2016]
6  *
7  * This code is released under the libpng license.
8  * For conditions of distribution and use, see the disclaimer
9  * and license in png.h
10  *
11  * Tool to check and fix the zlib inflate 'too far back' problem.
12  * See the usage message for more information.
13  */
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <string.h>
17 #include <ctype.h>
18 #include <limits.h>
19 #include <errno.h>
20 #include <assert.h>
21
22 #define implies(x,y) assert(!(x) || (y))
23
24 #ifdef __GNUC__
25    /* This is used to fix the error:
26     *
27     * pngfix.c:
28     * In function 'zlib_advance':
29     * pngfix.c:181:13: error: assuming signed overflow does not
30     *   occur when simplifying conditional to constant [-Werror=strict-overflow]
31     */
32 #  define FIX_GCC volatile
33 #else
34 #  define FIX_GCC
35 #endif
36
37 #define PROGRAM_NAME "pngfix"
38
39 /* Define the following to use this program against your installed libpng,
40  * rather than the one being built here:
41  */
42 #ifdef PNG_FREESTANDING_TESTS
43 #  include <png.h>
44 #else
45 #  include "../../png.h"
46 #endif
47
48 #if PNG_LIBPNG_VER < 10603 /* 1.6.3 */
49 #  error "pngfix will not work with libpng prior to 1.6.3"
50 #endif
51
52 #ifdef PNG_SETJMP_SUPPORTED
53 #include <setjmp.h>
54
55 #if defined(PNG_READ_SUPPORTED) && defined(PNG_EASY_ACCESS_SUPPORTED) &&\
56    (defined(PNG_READ_DEINTERLACE_SUPPORTED) ||\
57     defined(PNG_READ_INTERLACING_SUPPORTED))
58
59 /* zlib.h defines the structure z_stream, an instance of which is included
60  * in this structure and is required for decompressing the LZ compressed
61  * data in PNG files.
62  */
63 #ifndef ZLIB_CONST
64    /* We must ensure that zlib uses 'const' in declarations. */
65 #  define ZLIB_CONST
66 #endif
67 #include <zlib.h>
68 #ifdef const
69    /* zlib.h sometimes #defines const to nothing, undo this. */
70 #  undef const
71 #endif
72
73 /* zlib.h has mediocre z_const use before 1.2.6, this stuff is for compatibility
74  * with older builds.
75  */
76 #if ZLIB_VERNUM < 0x1260
77 #  define PNGZ_MSG_CAST(s) constcast(char*,s)
78 #  define PNGZ_INPUT_CAST(b) constcast(png_bytep,b)
79 #else
80 #  define PNGZ_MSG_CAST(s) (s)
81 #  define PNGZ_INPUT_CAST(b) (b)
82 #endif
83
84 #ifndef PNG_MAXIMUM_INFLATE_WINDOW
85 #  error "pngfix not supported in this libpng version"
86 #endif
87
88 #if ZLIB_VERNUM >= 0x1240
89
90 /* Copied from pngpriv.h */
91 #ifdef __cplusplus
92 #  define voidcast(type, value) static_cast<type>(value)
93 #  define constcast(type, value) const_cast<type>(value)
94 #  define aligncast(type, value) \
95    static_cast<type>(static_cast<void*>(value))
96 #  define aligncastconst(type, value) \
97    static_cast<type>(static_cast<const void*>(value))
98 #else
99 #  define voidcast(type, value) (value)
100 #  define constcast(type, value) ((type)(value))
101 #  define aligncast(type, value) ((void*)(value))
102 #  define aligncastconst(type, value) ((const void*)(value))
103 #endif /* __cplusplus */
104
105 #if PNG_LIBPNG_VER < 10700
106 /* Chunk tags (copied from pngpriv.h) */
107 #define PNG_32b(b,s) ((png_uint_32)(b) << (s))
108 #define PNG_U32(b1,b2,b3,b4) \
109    (PNG_32b(b1,24) | PNG_32b(b2,16) | PNG_32b(b3,8) | PNG_32b(b4,0))
110
111 /* Constants for known chunk types. */
112 #define png_IDAT PNG_U32( 73,  68,  65,  84)
113 #define png_IEND PNG_U32( 73,  69,  78,  68)
114 #define png_IHDR PNG_U32( 73,  72,  68,  82)
115 #define png_PLTE PNG_U32( 80,  76,  84,  69)
116 #define png_bKGD PNG_U32( 98,  75,  71,  68)
117 #define png_cHRM PNG_U32( 99,  72,  82,  77)
118 #define png_fRAc PNG_U32(102,  82,  65,  99) /* registered, not defined */
119 #define png_gAMA PNG_U32(103,  65,  77,  65)
120 #define png_gIFg PNG_U32(103,  73,  70, 103)
121 #define png_gIFt PNG_U32(103,  73,  70, 116) /* deprecated */
122 #define png_gIFx PNG_U32(103,  73,  70, 120)
123 #define png_hIST PNG_U32(104,  73,  83,  84)
124 #define png_iCCP PNG_U32(105,  67,  67,  80)
125 #define png_iTXt PNG_U32(105,  84,  88, 116)
126 #define png_oFFs PNG_U32(111,  70,  70, 115)
127 #define png_pCAL PNG_U32(112,  67,  65,  76)
128 #define png_pHYs PNG_U32(112,  72,  89, 115)
129 #define png_sBIT PNG_U32(115,  66,  73,  84)
130 #define png_sCAL PNG_U32(115,  67,  65,  76)
131 #define png_sPLT PNG_U32(115,  80,  76,  84)
132 #define png_sRGB PNG_U32(115,  82,  71,  66)
133 #define png_sTER PNG_U32(115,  84,  69,  82)
134 #define png_tEXt PNG_U32(116,  69,  88, 116)
135 #define png_tIME PNG_U32(116,  73,  77,  69)
136 #define png_tRNS PNG_U32(116,  82,  78,  83)
137 #define png_zTXt PNG_U32(122,  84,  88, 116)
138 #endif
139
140 /* The 8-byte signature as a pair of 32-bit quantities */
141 #define sig1 PNG_U32(137,  80,  78,  71)
142 #define sig2 PNG_U32( 13,  10,  26,  10)
143
144 /* Is the chunk critical? */
145 #define CRITICAL(chunk) (((chunk) & PNG_U32(32,0,0,0)) == 0)
146
147 /* Is it safe to copy? */
148 #define SAFE_TO_COPY(chunk) (((chunk) & PNG_U32(0,0,0,32)) != 0)
149
150 /* Fix ups for builds with limited read support */
151 #ifndef PNG_ERROR_TEXT_SUPPORTED
152 #  define png_error(a,b) png_err(a)
153 #endif
154
155 /********************************* UTILITIES **********************************/
156 /* UNREACHED is a value to cause an assert to fail. Because of the way the
157  * assert macro is written the string "UNREACHED" is produced in the error
158  * message.
159  */
160 #define UNREACHED 0
161
162 /* 80-bit number handling - a PNG image can be up to (2^31-1)x(2^31-1) 8-byte
163  * (16-bit RGBA) pixels in size; that's less than 2^65 bytes or 2^68 bits, so
164  * arithmetic of 80-bit numbers is sufficient.  This representation uses an
165  * arbitrary length array of png_uint_16 digits (0..65535).  The representation
166  * is little endian.
167  *
168  * The arithmetic functions take zero to two uarb values together with the
169  * number of digits in those values and write the result to the given uarb
170  * (always the first argument) returning the number of digits in the result.
171  * If the result is negative the return value is also negative (this would
172  * normally be an error).
173  */
174 typedef png_uint_16  udigit; /* A 'unum' is an array of these */
175 typedef png_uint_16p uarb;
176 typedef png_const_uint_16p uarbc;
177
178 #define UDIGITS(unum) ((sizeof unum)/(sizeof (udigit))
179    /* IMPORTANT: only apply this to an array, applied to a pointer the result
180     * will typically be '2', which is not useful.
181     */
182
183 static int
184 uarb_set(uarb result, png_alloc_size_t val)
185    /* Set (initialize) 'result' to 'val'.  The size required for 'result' must
186     * be determined by the caller from a knowledge of the maximum for 'val'.
187     */
188 {
189    int ndigits = 0;
190
191    while (val > 0)
192    {
193       result[ndigits++] = (png_uint_16)(val & 0xffff);
194       val >>= 16;
195    }
196
197    return ndigits;
198 }
199
200 static int
201 uarb_copy(uarb to, uarb from, int idigits)
202    /* Copy a uarb, may reduce the digit count */
203 {
204    int d, odigits;
205
206    for (d=odigits=0; d<idigits; ++d)
207       if ((to[d] = from[d]) != 0)
208          odigits = d+1;
209
210    return odigits;
211 }
212
213 static int
214 uarb_inc(uarb num, int in_digits, png_int_32 add)
215    /* This is a signed 32-bit add, except that to avoid overflow the value added
216     * or subtracted must be no more than 2^31-65536.  A negative result
217     * indicates a negative number (which is an error below).  The size of
218     * 'num' should be max(in_digits+1,2) for arbitrary 'add' but can be just
219     * in_digits+1 if add is known to be in the range -65535..65535.
220     */
221 {
222    FIX_GCC int out_digits = 0;
223
224    while (out_digits < in_digits)
225    {
226       add += num[out_digits];
227       num[out_digits++] = (png_uint_16)(add & 0xffff);
228       add >>= 16;
229    }
230
231    while (add != 0 && add != (-1))
232    {
233       num[out_digits++] = (png_uint_16)(add & 0xffff);
234       add >>= 16;
235    }
236
237    if (add == 0)
238    {
239       while (out_digits > 0 && num[out_digits-1] == 0)
240          --out_digits;
241       return out_digits; /* may be 0 */
242    }
243
244    else /* negative result */
245    {
246       while (out_digits > 1 && num[out_digits-1] == 0xffff)
247          --out_digits;
248
249       return -out_digits;
250    }
251 }
252
253 static int
254 uarb_add32(uarb num, int in_digits, png_uint_32 add)
255    /* As above but this works with any 32-bit value and only does 'add' */
256 {
257    if (in_digits > 0)
258    {
259       in_digits = uarb_inc(num, in_digits, add & 0xffff);
260       return uarb_inc(num+1, in_digits-1, add >> 16)+1;
261    }
262
263    return uarb_set(num, add);
264 }
265
266 static int
267 uarb_mult_digit(uarb acc, int a_digits, uarb num, FIX_GCC int n_digits,
268    png_uint_16 val)
269    /* Primitive one-digit multiply - 'val' must be 0..65535. Note that this
270     * primitive is a multiply and accumulate - the result of *num * val is added
271     * to *acc.
272     *
273     * This is a one-digit multiply, so the product may be up to one digit longer
274     * than 'num', however the add to 'acc' means that the caller must ensure
275     * that 'acc' is at least one digit longer than this *and* at least one digit
276     * longer than the current length of 'acc'.  (Or the caller must otherwise
277     * ensure 'adigits' is adequate from knowledge of the values.)
278     */
279 {
280    /* The digits in *acc, *num and val are in the range 0..65535, so the
281     * result below is at most (65535*65535)+2*65635 = 65535*(65535+2), which is
282     * exactly 0xffffffff.
283     */
284    if (val > 0 && n_digits > 0) /* Else the product is 0 */
285    {
286       png_uint_32 carry = 0;
287       int out_digits = 0;
288
289       while (out_digits < n_digits || carry > 0)
290       {
291          if (out_digits < a_digits)
292             carry += acc[out_digits];
293
294          if (out_digits < n_digits)
295             carry += (png_uint_32)num[out_digits] * val;
296
297          acc[out_digits++] = (png_uint_16)(carry & 0xffff);
298          carry >>= 16;
299       }
300
301       /* So carry is 0 and all the input digits have been consumed. This means
302        * that it is possible to skip any remaining digits in acc.
303        */
304       if (out_digits > a_digits)
305          return out_digits;
306    }
307
308    return a_digits;
309 }
310
311 static int
312 uarb_mult32(uarb acc, int a_digits, uarb num, int n_digits, png_uint_32 val)
313    /* calculate acc += num * val, 'val' may be any 32-bit value, 'acc' and 'num'
314     * may be any value, returns the number of digits in 'acc'.
315     */
316 {
317    if (n_digits > 0 && val > 0)
318    {
319       a_digits = uarb_mult_digit(acc, a_digits, num, n_digits,
320          (png_uint_16)(val & 0xffff));
321
322       val >>= 16;
323       if (val > 0)
324          a_digits = uarb_mult_digit(acc+1, a_digits-1, num, n_digits,
325             (png_uint_16)val) + 1;
326
327       /* Because n_digits and val are >0 the following must be true: */
328       assert(a_digits > 0);
329    }
330
331    return a_digits;
332 }
333
334 static int
335 uarb_shift(uarb inout, int ndigits, unsigned int right_shift)
336    /* Shift inout right by right_shift bits, right_shift must be in the range
337     * 1..15
338     */
339 {
340    FIX_GCC int i = ndigits;
341    png_uint_16 carry = 0;
342
343    assert(right_shift >= 1 && right_shift <= 15);
344
345    while (--i >= 0)
346    {
347       png_uint_16 temp = (png_uint_16)(carry | (inout[i] >> right_shift));
348
349       /* Bottom bits to top bits of carry */
350       carry = (png_uint_16)((inout[i] << (16-right_shift)) & 0xffff);
351
352       inout[i] = temp;
353
354       /* The shift may reduce ndigits */
355       if (i == ndigits-1 && temp == 0)
356          ndigits = i;
357    }
358
359    return ndigits;
360 }
361
362 static int
363 uarb_cmp(uarb a, int adigits, uarb b, int bdigits)
364    /* Return -1/0/+1 according as a<b/a==b/a>b */
365 {
366    if (adigits < bdigits)
367       return -1;
368
369    if (adigits > bdigits)
370       return 1;
371
372    while (adigits-- > 0)
373       if (a[adigits] < b[adigits])
374          return -1;
375
376       else if (a[adigits] > b[adigits])
377          return 1;
378
379    return 0;
380 }
381
382 #if 0 /*UNUSED*/
383 static int
384 uarb_eq32(uarb num, int digits, png_uint_32 val)
385    /* Return true if the uarb is equal to 'val' */
386 {
387    switch (digits)
388    {
389       case 0:  return val == 0;
390       case 1:  return val == num[0];
391       case 2:  return (val & 0xffff) == num[0] && (val >> 16) == num[1];
392       default: return 0;
393    }
394 }
395 #endif
396
397 static void
398 uarb_printx(uarb num, int digits, FILE *out)
399    /* Print 'num' as a hexadecimal number (easier than decimal!) */
400 {
401    while (digits > 0)
402       if (num[--digits] > 0)
403       {
404          fprintf(out, "0x%x", num[digits]);
405
406          while (digits > 0)
407             fprintf(out, "%.4x", num[--digits]);
408       }
409
410       else if (digits == 0) /* the number is 0 */
411          fputs("0x0", out);
412 }
413
414 static void
415 uarb_print(uarb num, int digits, FILE *out)
416    /* Prints 'num' as a decimal if it will fit in an unsigned long, else as a
417     * hexadecimal number.  Notice that the results vary for images over 4GByte
418     * in a system dependent way, and the hexadecimal form doesn't work very well
419     * in awk script input.
420     *
421     *
422     * TODO: write uarb_div10
423     */
424 {
425    if (digits * sizeof (udigit) > sizeof (unsigned long))
426       uarb_printx(num, digits, out);
427
428    else
429    {
430       unsigned long n = 0;
431
432       while (digits > 0)
433          n = (n << 16) + num[--digits];
434
435       fprintf(out, "%lu", n);
436    }
437 }
438
439 /* Generate random bytes.  This uses a boring repeatable algorithm and it
440  * is implemented here so that it gives the same set of numbers on every
441  * architecture.  It's a linear congruential generator (Knuth or Sedgewick
442  * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
443  * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
444  * Generation.)
445  *
446  * (Copied from contrib/libtests/pngvalid.c)
447  */
448 static void
449 make_random_bytes(png_uint_32* seed, void* pv, size_t size)
450 {
451    png_uint_32 u0 = seed[0], u1 = seed[1];
452    png_bytep bytes = voidcast(png_bytep, pv);
453
454    /* There are thirty-three bits; the next bit in the sequence is bit-33 XOR
455     * bit-20.  The top 1 bit is in u1, the bottom 32 are in u0.
456     */
457    size_t i;
458    for (i=0; i<size; ++i)
459    {
460       /* First generate 8 new bits then shift them in at the end. */
461       png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
462       u1 <<= 8;
463       u1 |= u0 >> 24;
464       u0 <<= 8;
465       u0 |= u;
466       *bytes++ = (png_byte)u;
467    }
468
469    seed[0] = u0;
470    seed[1] = u1;
471 }
472
473 /* Clear an object to a random value. */
474 static void
475 clear(void *pv, size_t size)
476 {
477    static png_uint_32 clear_seed[2] = { 0x12345678, 0x9abcdef0 };
478    make_random_bytes(clear_seed, pv, size);
479 }
480
481 #define CLEAR(object) clear(&(object), sizeof (object))
482
483 /* Copied from unreleased 1.7 code.
484  *
485  * CRC checking uses a local pre-built implementation of the Ethernet CRC32.
486  * This is to avoid a function call to the zlib DLL and to optimize the
487  * byte-by-byte case.
488  */
489 static png_uint_32 crc_table[256] =
490 {
491    0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
492    0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
493    0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
494    0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
495    0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
496    0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
497    0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
498    0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
499    0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
500    0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
501    0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
502    0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
503    0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
504    0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
505    0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
506    0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
507    0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
508    0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
509    0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
510    0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
511    0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
512    0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
513    0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
514    0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
515    0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
516    0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
517    0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
518    0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
519    0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
520    0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
521    0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
522    0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
523    0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
524    0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
525    0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
526    0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
527    0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
528    0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
529    0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
530    0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
531    0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
532    0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
533    0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
534    0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
535    0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
536    0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
537    0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
538    0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
539    0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
540    0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
541    0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
542    0x2d02ef8d
543 };
544
545 /* The CRC calculated here *IS* conditioned, the corresponding value used by
546  * zlib and the result value is obtained by XORing with CRC_INIT, which is also
547  * the first value that must be passed in (for the first byte) to crc_one_byte.
548  */
549 #define CRC_INIT 0xffffffff
550
551 static png_uint_32
552 crc_one_byte(png_uint_32 crc, int b)
553 {
554    return crc_table[(crc ^ b) & 0xff] ^ (crc >> 8);
555 }
556
557 static png_uint_32
558 crc_init_4(png_uint_32 value)
559 {
560    /* This is an alternative to the algorithm used in zlib, which requires four
561     * separate tables to parallelize the four byte operations, it only works for
562     * a CRC of the first four bytes of the stream, but this is what happens in
563     * the parser below where length+chunk-name is read and chunk-name used to
564     * initialize the CRC.  Notice that the calculation here avoids repeated
565     * conditioning (xor with 0xffffffff) by storing the conditioned value.
566     */
567    png_uint_32 crc = crc_table[(~value >> 24)] ^ 0xffffff;
568
569    crc = crc_table[(crc ^ (value >> 16)) & 0xff] ^ (crc >> 8);
570    crc = crc_table[(crc ^ (value >> 8)) & 0xff] ^ (crc >> 8);
571    return crc_table[(crc ^ value) & 0xff] ^ (crc >> 8);
572 }
573
574 static int
575 chunk_type_valid(png_uint_32 c)
576    /* Bit whacking approach to chunk name validation that is intended to avoid
577     * branches.  The cost is that it uses a lot of 32-bit constants, which might
578     * be bad on some architectures.
579     */
580 {
581    png_uint_32 t;
582
583    /* Remove bit 5 from all but the reserved byte; this means every
584     * 8-bit unit must be in the range 65-90 to be valid.  So bit 5
585     * must be zero, bit 6 must be set and bit 7 zero.
586     */
587    c &= ~PNG_U32(32,32,0,32);
588    t = (c & ~0x1f1f1f1f) ^ 0x40404040;
589
590    /* Subtract 65 for each 8-bit quantity, this must not overflow
591     * and each byte must then be in the range 0-25.
592     */
593    c -= PNG_U32(65,65,65,65);
594    t |=c ;
595
596    /* Subtract 26, handling the overflow which should set the top
597     * three bits of each byte.
598     */
599    c -= PNG_U32(25,25,25,26);
600    t |= ~c;
601
602    return (t & 0xe0e0e0e0) == 0;
603 }
604
605 /**************************** CONTROL INFORMATION *****************************/
606
607 /* Information about a sequence of IDAT chunks, the chunks have been re-synced
608  * using sync_stream below and the new lengths are recorded here.  Because the
609  * number of chunks is unlimited this is handled using a linked list of these
610  * structures.
611  */
612 struct IDAT_list
613 {
614    struct IDAT_list *next;     /* Linked list */
615    unsigned int      length;   /* Actual length of the array below */
616    unsigned int      count;    /* Number of entries that are valid */
617 #     define IDAT_INIT_LENGTH 16
618    png_uint_32       lengths[IDAT_INIT_LENGTH];
619 };
620
621 static void
622 IDAT_list_init(struct IDAT_list *list)
623 {
624    CLEAR(*list);
625
626    list->next = NULL;
627    list->length = IDAT_INIT_LENGTH;
628 }
629
630 static size_t
631 IDAT_list_size(struct IDAT_list *list, unsigned int length)
632    /* Return the size in bytes of an IDAT_list of the given length. */
633 {
634    if (list != NULL)
635       length = list->length;
636
637    return sizeof *list - sizeof list->lengths +
638       length * sizeof list->lengths[0];
639 }
640
641 static void
642 IDAT_list_end(struct IDAT_list *IDAT_list)
643 {
644    struct IDAT_list *list = IDAT_list->next;
645
646    CLEAR(*IDAT_list);
647
648    while (list != NULL)
649    {
650       struct IDAT_list *next = list->next;
651
652       clear(list, IDAT_list_size(list, 0));
653       free(list);
654       list = next;
655    }
656 }
657
658 static struct IDAT_list *
659 IDAT_list_extend(struct IDAT_list *tail)
660 {
661    /* Use the previous cached value if available. */
662    struct IDAT_list *next = tail->next;
663
664    if (next == NULL)
665    {
666       /* Insert a new, malloc'ed, block of IDAT information buffers, this
667        * one twice as large as the previous one:
668        */
669       unsigned int length = 2 * tail->length;
670
671       if (length < tail->length) /* arithmetic overflow */
672          length = tail->length;
673
674       next = voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length)));
675       CLEAR(*next);
676
677       /* The caller must handle this: */
678       if (next == NULL)
679          return NULL;
680
681       next->next = NULL;
682       next->length = length;
683       tail->next = next;
684    }
685
686    return next;
687 }
688
689 /* GLOBAL CONTROL STRUCTURE */
690 struct global
691 {
692    /* PUBLIC GLOBAL VARIABLES: OWNER INITIALIZE */
693    unsigned int   errors        :1; /* print file errors to stderr */
694    unsigned int   warnings      :1; /* print libpng warnings to stderr */
695    unsigned int   optimize_zlib :1; /* Run optimization search */
696    unsigned int   quiet         :2; /* don't output summaries */
697    unsigned int   verbose       :3; /* various internal tracking */
698    unsigned int   skip          :3; /* Non-critical chunks to skip */
699 #     define SKIP_NONE      0
700 #     define SKIP_BAD_CRC   1    /* Chunks with a bad CRC */
701 #     define SKIP_UNSAFE    2    /* Chunks not safe to copy */
702 #     define SKIP_UNUSED    3    /* Chunks not used by libpng */
703 #     define SKIP_TRANSFORM 4    /* Chunks only used in transforms */
704 #     define SKIP_COLOR     5    /* Everything but tRNS, sBIT, gAMA and sRGB */
705 #     define SKIP_ALL       6    /* Everything but tRNS and sBIT */
706
707    png_uint_32    idat_max;         /* 0 to perform no re-chunking */
708
709    int            status_code;      /* Accumulated status code */
710 #     define TOO_FAR_BACK   0x01 /* found a too-far-back error */
711 #     define CRC_ERROR      0x02 /* fixed an invalid CRC */
712 #     define STREAM_ERROR   0x04 /* damaged PNG stream (may be fixable) */
713 #     define TRUNCATED      0x08 /* truncated but still readable */
714 #     define FILE_ERROR     0x10 /* could not read the file */
715 #     define WRITE_ERROR    0x20 /* write error (this terminates the read) */
716 #     define INTERNAL_ERROR 0x40 /* internal limits/errors encountered */
717
718    /* PUBLIC GLOBAL VARIABLES: USED INTERNALLY BY IDAT READ CODE */
719    struct IDAT_list idat_cache;  /* Cache of file IDAT information buffers */
720       /* The structure is shared across all uses of this global control
721        * structure to avoid reallocation between IDAT streams.
722        */
723 };
724
725 static int
726 global_end(struct global *global)
727 {
728
729    int rc;
730
731    IDAT_list_end(&global->idat_cache);
732    rc = global->status_code;
733    CLEAR(*global);
734    return rc;
735 }
736
737 static void
738 global_init(struct global *global)
739    /* Call this once (and only once) to initialize the control */
740 {
741    CLEAR(*global);
742
743    /* Globals */
744    global->errors        = 0;
745    global->warnings      = 0;
746    global->quiet         = 0;
747    global->verbose       = 0;
748    global->idat_max      = 0;         /* no re-chunking of IDAT */
749    global->optimize_zlib = 0;
750    global->skip          = SKIP_NONE;
751    global->status_code   = 0;
752
753    IDAT_list_init(&global->idat_cache);
754 }
755
756 static int
757 skip_chunk_type(const struct global *global, png_uint_32 type)
758    /* Return true if this chunk is to be skipped according to the --strip
759     * option.  This code needs to recognize all known ancillary chunks in order
760     * to handle the --strip=unsafe option.
761     */
762 {
763    /* Never strip critical chunks: */
764    if (CRITICAL(type))
765       return 0;
766
767    switch (type)
768    {
769       /* Chunks that are treated as, effectively, critical because they affect
770        * correct interpretation of the pixel values:
771        */
772       case png_tRNS: case png_sBIT:
773          return 0;
774
775       /* Chunks that specify gamma encoding which should therefore only be
776        * removed the the user insists:
777        */
778       case png_gAMA: case png_sRGB:
779          if (global->skip >= SKIP_ALL)
780             return 1;
781          return 0;
782
783       /* Chunks that affect color interpretation - not used by libpng and rarely
784        * used by applications, but technically still required for correct
785        * interpretation of the image data:
786        */
787       case png_cHRM: case png_iCCP:
788          if (global->skip >= SKIP_COLOR)
789             return 1;
790          return 0;
791
792       /* Other chunks that are used by libpng in image transformations (as
793        * opposed to known chunks that have get/set APIs but are not otherwise
794        * used.)
795        */
796       case png_bKGD:
797          if (global->skip >= SKIP_TRANSFORM)
798             return 1;
799          return 0;
800
801       /* All other chunks that libpng knows about and affect neither image
802        * interpretation nor libpng transforms - chunks that are effectively
803        * unused by libpng even though libpng might recognize and store them.
804        */
805       case png_fRAc: case png_gIFg: case png_gIFt: case png_gIFx: case png_hIST:
806       case png_iTXt: case png_oFFs: case png_pCAL: case png_pHYs: case png_sCAL:
807       case png_sPLT: case png_sTER: case png_tEXt: case png_tIME: case png_zTXt:
808          if (global->skip >= SKIP_UNUSED)
809             return 1;
810          return 0;
811
812       /* Chunks that libpng does not know about (notice that this depends on the
813        * list above including all known chunks!)  The decision here depends on
814        * whether the safe-to-copy bit is set in the chunk type.
815        */
816       default:
817          if (SAFE_TO_COPY(type))
818          {
819             if (global->skip >= SKIP_UNUSED) /* as above */
820                return 1;
821          }
822
823          else if (global->skip >= SKIP_UNSAFE)
824             return 1;
825
826          return 0;
827    }
828 }
829
830 /* PER-FILE CONTROL STRUCTURE */
831 struct chunk;
832 struct IDAT;
833 struct file
834 {
835    /* ANCESTORS */
836    struct global *global;
837
838    /* PUBLIC PER-FILE VARIABLES: CALLER INITIALIZE */
839    const char *   file_name;
840    const char *   out_name;      /* Name of output file (if required) */
841
842    /* PUBLIC PER-FILE VARIABLES: SET BY PNG READ CODE */
843    /* File specific result codes */
844    int            status_code;   /* Set to a bit mask of the following: */
845    int            read_errno;    /* Records a read error errno */
846    int            write_errno;   /* Records a write error errno */
847
848    /* IHDR information */
849    png_uint_32    width;
850    png_uint_32    height;
851    png_byte       bit_depth;
852    png_byte       color_type;
853    png_byte       compression_method;
854    png_byte       filter_method;
855    png_byte       interlace_method;
856
857    udigit         image_bytes[5];
858    int            image_digits;
859
860    /* PROTECTED PER-FILE VARIABLES: USED BY THE READ CODE */
861    FILE *         file;          /* Original PNG file */
862    FILE *         out;           /* If a new one is being written */
863    jmp_buf        jmpbuf;        /* Set while reading a PNG */
864
865    /* PROTECTED CHUNK SPECIFIC VARIABLES: USED BY CHUNK CODE */
866    /* The following variables are used during reading to record the length, type
867     * and data position of the *next* chunk or, right at the start, the
868     * signature (in length,type).
869     *
870     * When a chunk control structure is instantiated these values are copied
871     * into the structure and can then be overritten with the data for the next
872     * chunk.
873     */
874    fpos_t         data_pos;      /* Position of first byte of chunk data */
875    png_uint_32    length;        /* First word (length or signature start) */
876    png_uint_32    type;          /* Second word (type or signature end) */
877    png_uint_32    crc;           /* Running chunk CRC (used by read_chunk) */
878
879    /* These counts are maintained by the read and write routines below and are
880     * reset by the chunk handling code.  They record the total number of bytes
881     * read or written for the chunk, including the header (length,type) bytes.
882     */
883    png_uint_32    read_count;    /* Count of bytes read (in the chunk) */
884    png_uint_32    write_count;   /* Count of bytes written (in the chunk) */
885    int            state;         /* As defined here: */
886 #     define STATE_SIGNATURE  0  /* The signature is being written */
887 #     define STATE_CHUNKS     1  /* Non-IDAT chunks are being written */
888 #     define STATE_IDAT       2  /* An IDAT stream is being written */
889
890    /* Two pointers used to enable clean-up in the event of fatal errors and to
891     * hold state about the parser process (only one of each at present.)
892     */
893    struct chunk * chunk;
894    struct IDAT *  idat;
895
896    /* Interface to allocate a new chunk or IDAT control structure.  The result
897     * is returned by setting one or other of the above variables.  Note that the
898     * relevant initializer is called by the allocator function.  The alloc_ptr
899     * is used only by the implementation of the allocate function.
900     */
901    void *         alloc_ptr;
902    void         (*alloc)(struct file*,int idat);
903                                   /* idat: allocate IDAT not chunk */
904 };
905
906 /* Valid longjmp (stop) codes are: */
907 #define LIBPNG_WARNING_CODE   1 /* generic png_error */
908 #define LIBPNG_ERROR_CODE     2 /* generic png_error */
909 #define ZLIB_ERROR_CODE       3 /* generic zlib error */
910 #define INVALID_ERROR_CODE    4 /* detected an invalid PNG */
911 #define READ_ERROR_CODE       5 /* read failed */
912 #define WRITE_ERROR_CODE      6 /* error in write */
913 #define UNEXPECTED_ERROR_CODE 7 /* unexpected (internal?) error */
914
915 static void
916 emit_string(const char *str, FILE *out)
917    /* Print a string with spaces replaced by '_' and non-printing characters by
918     * an octal escape.
919     */
920 {
921    for (; *str; ++str)
922       if (isgraph(UCHAR_MAX & *str))
923          putc(*str, out);
924
925       else if (isspace(UCHAR_MAX & *str))
926          putc('_', out);
927
928       else
929          fprintf(out, "\\%.3o", *str);
930 }
931
932 static const char *
933 strcode(int code)
934 {
935    switch (code)
936    {
937       case LIBPNG_WARNING_CODE:   return "warning";
938       case LIBPNG_ERROR_CODE:     return "libpng";
939       case ZLIB_ERROR_CODE:       return "zlib";
940       case INVALID_ERROR_CODE:    return "invalid";
941       case READ_ERROR_CODE:       return "read";
942       case WRITE_ERROR_CODE:      return "write";
943       case UNEXPECTED_ERROR_CODE: return "unexpected";
944       default:                    return "INVALID";
945    }
946 }
947
948 static void
949 emit_error(struct file *file, int code, const char *what)
950    /* Generic error message routine, takes a 'stop' code but can be used
951     * elsewhere.  Always outputs a message.
952     */
953 {
954    const char *reason;
955    int err = 0;
956
957    switch (code)
958    {
959       case LIBPNG_WARNING_CODE:   reason = "libpng warning:"; break;
960       case LIBPNG_ERROR_CODE:     reason = "libpng error:"; break;
961       case ZLIB_ERROR_CODE:       reason = "zlib error:"; break;
962       case INVALID_ERROR_CODE:    reason = "invalid"; break;
963       case READ_ERROR_CODE:       reason = "read failure:";
964                                   err = file->read_errno;
965                                   break;
966       case WRITE_ERROR_CODE:      reason = "write error";
967                                   err = file->write_errno;
968                                   break;
969       case UNEXPECTED_ERROR_CODE: reason = "unexpected error:";
970                                   err = file->read_errno;
971                                   if (err == 0)
972                                      err = file->write_errno;
973                                   break;
974       default:                    reason = "INVALID (internal error):"; break;
975    }
976
977    if (err != 0)
978       fprintf(stderr, "%s: %s %s [%s]\n", file->file_name, reason, what,
979          strerror(err));
980
981    else
982       fprintf(stderr, "%s: %s %s\n", file->file_name, reason, what);
983 }
984
985 static void chunk_end(struct chunk **);
986 static void IDAT_end(struct IDAT **);
987
988 static int
989 file_end(struct file *file)
990 {
991    int rc;
992
993    /* If either of the chunk pointers are set end them here, the IDAT structure
994     * must be deallocated first as it may deallocate the chunk structure.
995     */
996    if (file->idat != NULL)
997       IDAT_end(&file->idat);
998
999    if (file->chunk != NULL)
1000       chunk_end(&file->chunk);
1001
1002    rc = file->status_code;
1003
1004    if (file->file != NULL)
1005       (void)fclose(file->file);
1006
1007    if (file->out != NULL)
1008    {
1009       /* NOTE: this is bitwise |, all the following functions must execute and
1010        * must succeed.
1011        */
1012       if (ferror(file->out) | fflush(file->out) | fclose(file->out))
1013       {
1014          perror(file->out_name);
1015          emit_error(file, READ_ERROR_CODE, "output write error");
1016          rc |= WRITE_ERROR;
1017       }
1018    }
1019
1020    /* Accumulate the result codes */
1021    file->global->status_code |= rc;
1022
1023    CLEAR(*file);
1024
1025    return rc; /* status code: non-zero on read or write error */
1026 }
1027
1028 static int
1029 file_init(struct file *file, struct global *global, const char *file_name,
1030    const char *out_name, void *alloc_ptr, void (*alloc)(struct file*,int))
1031    /* Initialize a file control structure.  This will open the given files as
1032     * well.  The status code returned is 0 on success, non zero (using the flags
1033     * above) on a file open error.
1034     */
1035 {
1036    CLEAR(*file);
1037    file->global = global;
1038
1039    file->file_name = file_name;
1040    file->out_name = out_name;
1041    file->status_code = 0;
1042    file->read_errno = 0;
1043    file->write_errno = 0;
1044
1045    file->file = NULL;
1046    file->out = NULL;
1047    /* jmpbuf is garbage: must be set by read_png */
1048
1049    file->read_count = 0;
1050    file->state = STATE_SIGNATURE;
1051
1052    file->chunk = NULL;
1053    file->idat = NULL;
1054
1055    file->alloc_ptr = alloc_ptr;
1056    file->alloc = alloc;
1057
1058    /* Open the files: */
1059    assert(file_name != NULL);
1060    file->file = fopen(file_name, "rb");
1061
1062    if (file->file == NULL)
1063    {
1064       file->read_errno = errno;
1065       file->status_code |= FILE_ERROR;
1066       /* Always output: please give a readable file! */
1067       perror(file_name);
1068       return FILE_ERROR;
1069    }
1070
1071    if (out_name != NULL)
1072    {
1073       file->out = fopen(out_name, "wb");
1074
1075       if (file->out == NULL)
1076       {
1077          file->write_errno = errno;
1078          file->status_code |= WRITE_ERROR;
1079          perror(out_name);
1080          return WRITE_ERROR;
1081       }
1082    }
1083
1084    return 0;
1085 }
1086
1087 static void
1088 log_error(struct file *file, int code, const char *what)
1089    /* Like emit_error but checks the global 'errors' flag */
1090 {
1091    if (file->global->errors)
1092       emit_error(file, code, what);
1093 }
1094
1095 static char
1096 type_char(png_uint_32 v)
1097 {
1098    /* In fact because chunk::chunk_type is validated prior to any call to this
1099     * function it will always return a-zA-Z, but the extra codes are just there
1100     * to help in finding internal (programming) errors.  Note that the code only
1101     * ever considers the low 7 bits of the value (so it is not necessary for the
1102     * type_name function to mask of the byte.)
1103     */
1104    if (v & 32)
1105       return "!abcdefghijklmnopqrstuvwxyz56789"[(v-96)&31];
1106
1107    else
1108       return "@ABCDEFGHIJKLMNOPQRSTUVWXYZ01234"[(v-64)&31];
1109 }
1110
1111 static void
1112 type_name(png_uint_32 type, FILE *out)
1113 {
1114    putc(type_char(type >> 24), out);
1115    putc(type_char(type >> 16), out);
1116    putc(type_char(type >>  8), out);
1117    putc(type_char(type      ), out);
1118 }
1119
1120 static void
1121 type_sep(FILE *out)
1122 {
1123    putc(':', out);
1124    putc(' ', out);
1125 }
1126
1127 static png_uint_32 current_type(struct file *file, int code);
1128
1129 PNG_NORETURN static void
1130 stop(struct file *file, int code, const char *what)
1131    /* Return control when a PNG file cannot be read. This outputs an 'ERR'
1132     * summary line too.
1133     */
1134 {
1135    log_error(file, code, what);
1136
1137    /* The chunk being read is typically identified by file->chunk or, if this is
1138     * NULL, by file->type.  This may be wrong if libpng reads ahead, but this
1139     * only happens with IDAT where libpng reads the header then jumps around
1140     * finding errors in the previous chunks.  We know that is happening because
1141     * we are at the start of the IDAT (i.e. no IDAT data has yet been written.)
1142     *
1143     * SUMMARY FORMAT (stop):
1144     *
1145     * IDAT ERR status code read-errno write-errno message file
1146     *
1147     * 'uncompressed' will be 0 if there was a problem in the IHDR.  The errno
1148     * values are emit_string(strerror(errno)).
1149     */
1150    if (file->global->quiet < 2) /* need two quiets to stop this. */
1151    {
1152       png_uint_32 type;
1153
1154       if (file->chunk != NULL)
1155          type = current_type(file, code); /* Gropes in struct chunk and IDAT */
1156
1157       else
1158          type = file->type;
1159
1160       if (type)
1161          type_name(type, stdout);
1162
1163       else /* magic: an IDAT header, produces bogons for too many IDATs */
1164          fputs("HEAD", stdout); /* not a registered chunk! */
1165
1166       printf(" ERR %.2x %s ", file->status_code, strcode(code));
1167       /* This only works one strerror at a time, because of the way strerror is
1168        * implemented.
1169        */
1170       emit_string(strerror(file->read_errno), stdout);
1171       putc(' ', stdout);
1172       emit_string(strerror(file->write_errno), stdout);
1173       putc(' ', stdout);
1174       emit_string(what, stdout);
1175       putc(' ', stdout);
1176       fputs(file->file_name, stdout);
1177       putc('\n', stdout);
1178    }
1179
1180    file->status_code |= FILE_ERROR;
1181    longjmp(file->jmpbuf, code);
1182 }
1183
1184 PNG_NORETURN static void
1185 stop_invalid(struct file *file, const char *what)
1186 {
1187    stop(file, INVALID_ERROR_CODE, what);
1188 }
1189
1190 static void
1191 type_message(struct file *file, png_uint_32 type, const char *what)
1192    /* Error message for a chunk; the chunk name comes from 'type' */
1193 {
1194    if (file->global->errors)
1195    {
1196       fputs(file->file_name, stderr);
1197       type_sep(stderr);
1198       type_name(type, stderr);
1199       type_sep(stderr);
1200       fputs(what, stderr);
1201       putc('\n', stderr);
1202    }
1203 }
1204
1205 /* Input file positioning - we jump around in the input file while reading
1206  * stuff, these wrappers deal with the error handling.
1207  */
1208 static void
1209 file_getpos(struct file *file, fpos_t *pos)
1210 {
1211    if (fgetpos(file->file, pos))
1212    {
1213       /* This is unexpected, so perror it */
1214       perror(file->file_name);
1215       stop(file, READ_ERROR_CODE, "fgetpos");
1216    }
1217 }
1218
1219 static void
1220 file_setpos(struct file *file, const fpos_t *pos)
1221 {
1222    if (fsetpos(file->file, pos))
1223    {
1224       perror(file->file_name);
1225       stop(file, READ_ERROR_CODE, "fsetpos");
1226    }
1227 }
1228
1229 static void
1230 getpos(struct file *file)
1231    /* Get the current position and store it in 'data_pos'.  The corresponding
1232     * setpos() function is chunk specific because it uses the copy of the
1233     * position for the specific chunk.
1234     */
1235 {
1236    file_getpos(file, &file->data_pos);
1237 }
1238
1239
1240 /* Read utility - read a single byte, returns a value in the range 0..255 or EOF
1241  * on a read error.  In the latter case status_code and read_errno are updated
1242  * appropriately.
1243  */
1244 static int
1245 read_byte(struct file *file)
1246 {
1247    int ch = getc(file->file);
1248
1249    if (ch >= 0 && ch <= 255)
1250    {
1251       ++(file->read_count);
1252       return ch;
1253    }
1254
1255    else if (ch != EOF)
1256    {
1257       file->status_code |= INTERNAL_ERROR;
1258       file->read_errno = ERANGE; /* out of range character */
1259
1260       /* This is very unexpected; an error message is always output: */
1261       emit_error(file, UNEXPECTED_ERROR_CODE, "file read");
1262    }
1263
1264 #  ifdef EINTR
1265       else if (errno == EINTR) /* Interrupted, try again */
1266       {
1267          errno = 0;
1268          return read_byte(file);
1269       }
1270 #  endif
1271
1272    else
1273    {
1274       /* An error, it doesn't really matter what the error is but it gets
1275        * recorded anyway.
1276        */
1277       if (ferror(file->file))
1278          file->read_errno = errno;
1279
1280       else if (feof(file->file))
1281          file->read_errno = 0; /* I.e. a regular EOF, no error */
1282
1283       else /* unexpected */
1284          file->read_errno = EDOM;
1285    }
1286
1287    /* 'TRUNCATED' is used for all cases of failure to read a byte, because of
1288     * the way libpng works a byte read is never attempted unless the byte is
1289     * expected to be there, so EOF should not occur.
1290     */
1291    file->status_code |= TRUNCATED;
1292    return EOF;
1293 }
1294
1295 static png_byte
1296 reread_byte(struct file *file)
1297    /* Read a byte when an error is not expected to happen because the byte has
1298     * been read before without error.
1299     */
1300 {
1301    int ch = getc(file->file);
1302
1303    if (errno != 0)
1304       file->read_errno = errno;
1305
1306    if (ch < 0 || ch > 255)
1307       stop(file, UNEXPECTED_ERROR_CODE, "reread");
1308
1309    return (png_byte)ch;
1310 }
1311
1312 static png_uint_32
1313 reread_4(struct file *file)
1314    /* The same but for a four byte quantity */
1315 {
1316    png_uint_32 result = 0;
1317    int i = 0;
1318
1319    while (++i <= 4)
1320       result = (result << 8) + reread_byte(file);
1321
1322    return result;
1323 }
1324
1325 static void
1326 skip_12(struct file *file)
1327    /* Skip exactly 12 bytes in the input stream - used to skip a CRC and chunk
1328     * header that has been read before.
1329     */
1330 {
1331    /* Since the chunks were read before this shouldn't fail: */
1332    if (fseek(file->file, 12, SEEK_CUR) != 0)
1333    {
1334       if (errno != 0)
1335          file->read_errno = errno;
1336
1337       stop(file, UNEXPECTED_ERROR_CODE, "reskip");
1338    }
1339 }
1340
1341 static void
1342 write_byte(struct file *file, int b)
1343    /* Write one byte to the output - this causes a fatal error if the write
1344     * fails and the read of this PNG file immediately terminates.  Just
1345     * increments the write count if there is no output file.
1346     */
1347 {
1348    if (file->out != NULL)
1349    {
1350       if (putc(b, file->out) != b)
1351       {
1352          file->write_errno = errno;
1353          file->status_code |= WRITE_ERROR;
1354          stop(file, WRITE_ERROR_CODE, "write byte");
1355       }
1356    }
1357
1358    ++(file->write_count);
1359 }
1360
1361 /* Derivatives of the read/write functions. */
1362 static unsigned int
1363 read_4(struct file *file, png_uint_32 *pu)
1364    /* Read four bytes, returns the number of bytes read successfully and, if all
1365     * four bytes are read, assigns the result to *pu.
1366     */
1367 {
1368    unsigned int i = 0;
1369    png_uint_32 val = 0;
1370
1371    do
1372    {
1373       int ch = read_byte(file);
1374
1375       if (ch == EOF)
1376          return i;
1377
1378       val = (val << 8) + ch;
1379    } while (++i < 4);
1380
1381    *pu = val;
1382    return i;
1383 }
1384
1385 /* CRC handling - read but calculate the CRC while doing so. */
1386 static int
1387 crc_read_many(struct file *file, png_uint_32 length)
1388    /* Reads 'length' bytes and updates the CRC, returns true on success, false
1389     * if the input is truncated.
1390     */
1391 {
1392    if (length > 0)
1393    {
1394       png_uint_32 crc = file->crc;
1395
1396       do
1397       {
1398          int ch = read_byte(file);
1399
1400          if (ch == EOF)
1401             return 0; /* Truncated */
1402
1403          crc = crc_one_byte(crc, ch);
1404       }
1405       while (--length > 0);
1406
1407       file->crc = crc;
1408    }
1409
1410    return 1; /* OK */
1411 }
1412
1413 static int
1414 calc_image_size(struct file *file)
1415    /* Fill in the image_bytes field given the IHDR information, calls stop on
1416     * error.
1417     */
1418 {
1419    png_uint_16 pd = file->bit_depth;
1420
1421    switch (file->color_type)
1422    {
1423       default:
1424          stop_invalid(file, "IHDR: colour type");
1425
1426       invalid_bit_depth:
1427          stop_invalid(file, "IHDR: bit depth");
1428
1429       case 0: /* g */
1430          if (pd != 1 && pd != 2 && pd != 4 && pd != 8 && pd != 16)
1431             goto invalid_bit_depth;
1432          break;
1433
1434       case 3:
1435          if (pd != 1 && pd != 2 && pd != 4 && pd != 8)
1436             goto invalid_bit_depth;
1437          break;
1438
1439       case 2: /* rgb */
1440          if (pd != 8 && pd != 16)
1441             goto invalid_bit_depth;
1442
1443          pd = (png_uint_16)(pd * 3);
1444          break;
1445
1446       case 4: /* ga */
1447          if (pd != 8 && pd != 16)
1448             goto invalid_bit_depth;
1449
1450          pd = (png_uint_16)(pd * 2);
1451          break;
1452
1453       case 6: /* rgba */
1454          if (pd != 8 && pd != 16)
1455             goto invalid_bit_depth;
1456
1457          pd = (png_uint_16)(pd * 4);
1458          break;
1459    }
1460
1461    if (file->width < 1 || file->width > 0x7fffffff)
1462       stop_invalid(file, "IHDR: width");
1463
1464    else if (file->height < 1 || file->height > 0x7fffffff)
1465       stop_invalid(file, "IHDR: height");
1466
1467    else if (file->compression_method != 0)
1468       stop_invalid(file, "IHDR: compression method");
1469
1470    else if (file->filter_method != 0)
1471       stop_invalid(file, "IHDR: filter method");
1472
1473    else switch (file->interlace_method)
1474    {
1475       case PNG_INTERLACE_ADAM7:
1476          /* Interlacing makes the image larger because of the replication of
1477           * both the filter byte and the padding to a byte boundary.
1478           */
1479          {
1480             int pass;
1481             int image_digits = 0;
1482             udigit row_width[2], row_bytes[3];
1483
1484             for (pass=0; pass<=6; ++pass)
1485             {
1486                png_uint_32 pw = PNG_PASS_COLS(file->width, pass);
1487
1488                if (pw > 0)
1489                {
1490                   int  digits;
1491
1492                   /* calculate 1+((pw*pd+7)>>3) in row_bytes */
1493                   digits = uarb_mult_digit(row_bytes, uarb_set(row_bytes, 7),
1494                      row_width, uarb_set(row_width, pw), pd);
1495                   digits = uarb_shift(row_bytes, digits, 3);
1496                   digits = uarb_inc(row_bytes, digits, 1);
1497
1498                   /* Add row_bytes * pass-height to the file image_bytes field
1499                    */
1500                   image_digits = uarb_mult32(file->image_bytes, image_digits,
1501                      row_bytes, digits,
1502                      PNG_PASS_ROWS(file->height, pass));
1503                }
1504             }
1505
1506             file->image_digits = image_digits;
1507          }
1508          break;
1509
1510       case PNG_INTERLACE_NONE:
1511          {
1512             int  digits;
1513             udigit row_width[2], row_bytes[3];
1514
1515             /* As above, but use image_width in place of the pass width: */
1516             digits = uarb_mult_digit(row_bytes, uarb_set(row_bytes, 7),
1517                row_width, uarb_set(row_width, file->width), pd);
1518             digits = uarb_shift(row_bytes, digits, 3);
1519             digits = uarb_inc(row_bytes, digits, 1);
1520
1521             /* Set row_bytes * image-height to the file image_bytes field */
1522             file->image_digits = uarb_mult32(file->image_bytes, 0,
1523                row_bytes, digits, file->height);
1524          }
1525          break;
1526
1527       default:
1528          stop_invalid(file, "IHDR: interlace method");
1529    }
1530
1531    assert(file->image_digits >= 1 && file->image_digits <= 5);
1532    return 1;
1533 }
1534
1535 /* PER-CHUNK CONTROL STRUCTURE
1536  * This structure is instantiated for each chunk, except for the IDAT chunks
1537  * where one chunk control structure is used for the whole of a single stream of
1538  * IDAT chunks (see the IDAT control structure below).
1539  */
1540 struct chunk
1541 {
1542    /* ANCESTORS */
1543    struct file *         file;
1544    struct global *       global;
1545
1546    /* PUBLIC IDAT INFORMATION: SET BY THE ZLIB CODE */
1547    udigit         uncompressed_bytes[5];
1548    int            uncompressed_digits;
1549    udigit         compressed_bytes[5];
1550    int            compressed_digits;
1551
1552    /* PUBLIC PER-CHUNK INFORMATION: USED BY CHUNK READ CODE */
1553    /* This information is filled in by chunk_init from the data in the file
1554     * control structure, but chunk_length may be changed later.
1555     */
1556    fpos_t         chunk_data_pos;    /* Position of first byte of chunk data */
1557    png_uint_32    chunk_length;      /* From header (or modified below) */
1558    png_uint_32    chunk_type;        /* From header */
1559
1560    /* PUBLIC PER-CHUNK INFORMATION: FOR THE CHUNK WRITE CODE */
1561    png_uint_32    write_crc;         /* Output CRC (may differ from read_crc) */
1562    png_uint_32    rewrite_offset;    /* Count of bytes before rewrite. */
1563    int            rewrite_length;    /* Number of bytes left to change */
1564    png_byte       rewrite_buffer[2]; /* Buffer of new byte values */
1565 };
1566
1567 static void
1568 chunk_message(struct chunk *chunk, const char *message)
1569 {
1570    type_message(chunk->file, chunk->chunk_type, message);
1571 }
1572
1573 static void
1574 chunk_end(struct chunk **chunk_var)
1575 {
1576    struct chunk *chunk = *chunk_var;
1577
1578    *chunk_var = NULL;
1579    CLEAR(*chunk);
1580 }
1581
1582 static void
1583 chunk_init(struct chunk * const chunk, struct file * const file)
1584    /* When a chunk is initialized the file length/type/pos are copied into the
1585     * corresponding chunk fields and the new chunk is registered in the file
1586     * structure.  There can only be one chunk at a time.
1587     *
1588     * NOTE: this routine must onely be called from the file alloc routine!
1589     */
1590 {
1591    assert(file->chunk == NULL);
1592
1593    CLEAR(*chunk);
1594
1595    chunk->file = file;
1596    chunk->global = file->global;
1597
1598    chunk->chunk_data_pos = file->data_pos;
1599    chunk->chunk_length = file->length;
1600    chunk->chunk_type = file->type;
1601
1602    /* Compresssed/uncompressed size information (from the zlib control structure
1603     * that is used to check the compressed data in a chunk.)
1604     */
1605    chunk->uncompressed_digits = 0;
1606    chunk->compressed_digits = 0;
1607
1608    file->chunk = chunk;
1609 }
1610
1611 static png_uint_32
1612 current_type(struct file *file, int code)
1613    /* Guess the actual chunk type that causes a stop() */
1614 {
1615    /* This may return png_IDAT for errors detected (late) in the header; that
1616     * includes any inter-chunk consistency check that libpng performs.  Assume
1617     * that if the chunk_type is png_IDAT and the file write count is 8 this is
1618     * what is happening.
1619     */
1620    if (file->chunk != NULL)
1621    {
1622       png_uint_32 type = file->chunk->chunk_type;
1623
1624       /* This is probably wrong for the excess IDATs case, because then libpng
1625        * whines about too many of them (apparently in some cases erroneously)
1626        * when the header is read.
1627        */
1628       if (code <= LIBPNG_ERROR_CODE && type == png_IDAT &&
1629          file->write_count == 8)
1630          type = 0; /* magic */
1631
1632       return type;
1633    }
1634
1635    else
1636       return file->type;
1637 }
1638
1639 static void
1640 setpos(struct chunk *chunk)
1641    /* Reset the position to 'chunk_data_pos' - the start of the data for this
1642     * chunk.  As a side effect the read_count in the file is reset to 8, just
1643     * after the length/type header.
1644     */
1645 {
1646    chunk->file->read_count = 8;
1647    file_setpos(chunk->file, &chunk->chunk_data_pos);
1648 }
1649
1650 /* Specific chunk handling - called for each chunk header, all special chunk
1651  * processing is initiated in these functions.
1652  */
1653 /* The next functions handle special processing for those chunks with LZ data,
1654  * the data is identified and checked for validity.  If there are problems which
1655  * cannot be corrected the routines return false, otherwise true (although
1656  * modification to the zlib header may be required.)
1657  *
1658  * The compressed data is in zlib format (RFC1950) and consequently has a
1659  * minimum length of 7 bytes.
1660  */
1661 static int zlib_check(struct file *file, png_uint_32 offset);
1662
1663 static int
1664 process_zTXt_iCCP(struct file *file)
1665    /* zTXt and iCCP have exactly the same form - keyword, null, compression
1666     * method then compressed data.
1667     */
1668 {
1669    struct chunk *chunk = file->chunk;
1670    png_uint_32 length;
1671    png_uint_32 index = 0;
1672
1673    assert(chunk != NULL && file->idat == NULL);
1674    length = chunk->chunk_length;
1675    setpos(chunk);
1676
1677    while (length >= 9)
1678    {
1679       --length;
1680       ++index;
1681       if (reread_byte(file) == 0) /* keyword null terminator */
1682       {
1683          --length;
1684          ++index;
1685          (void)reread_byte(file); /* compression method */
1686          return zlib_check(file, index);
1687       }
1688    }
1689
1690    chunk_message(chunk, "too short");
1691    return 0; /* skip */
1692 }
1693
1694 static int
1695 process_iTXt(struct file *file)
1696 {
1697    /* Like zTXt but more fields. */
1698    struct chunk *chunk = file->chunk;
1699    png_uint_32 length;
1700    png_uint_32 index = 0;
1701
1702    assert(chunk != NULL && file->idat == NULL);
1703    length = chunk->chunk_length;
1704    setpos(chunk);
1705
1706    while (length >= 5)
1707    {
1708       --length;
1709       ++index;
1710       if (reread_byte(file) == 0) /* keyword null terminator */
1711       {
1712          --length;
1713          ++index;
1714          if (reread_byte(file) == 0) /* uncompressed text */
1715             return 1; /* nothing to check */
1716
1717          --length;
1718          ++index;
1719          (void)reread_byte(file); /* compression method */
1720
1721          /* Skip the language tag (null terminated). */
1722          while (length >= 9)
1723          {
1724             --length;
1725             ++index;
1726             if (reread_byte(file) == 0) /* terminator */
1727             {
1728                /* Skip the translated keyword */
1729                while (length >= 8)
1730                {
1731                   --length;
1732                   ++index;
1733                   if (reread_byte(file) == 0) /* terminator */
1734                      return zlib_check(file, index);
1735                }
1736             }
1737          }
1738
1739          /* Ran out of bytes in the compressed case. */
1740          break;
1741       }
1742    }
1743
1744    log_error(file, INVALID_ERROR_CODE, "iTXt chunk length");
1745
1746    return 0; /* skip */
1747 }
1748
1749 /* IDAT READ/WRITE CONTROL STRUCTURE */
1750 struct IDAT
1751 {
1752    /* ANCESTORS */
1753    struct file *         file;
1754    struct global *       global;
1755
1756    /* PROTECTED IDAT INFORMATION: SET BY THE IDAT READ CODE */
1757    struct IDAT_list *idat_list_head; /* START of the list of IDAT information */
1758    struct IDAT_list *idat_list_tail; /* *END* of the list of IDAT information */
1759
1760    /* PROTECTED IDAT INFORMATION: USED BY THE IDAT WRITE CODE */
1761    struct IDAT_list *idat_cur;       /* Current list entry */
1762    unsigned int      idat_count;     /* And the *current* index into the list */
1763    png_uint_32       idat_index;     /* Index of *next* input byte to write */
1764    png_uint_32       idat_length;    /* Cache of current chunk length */
1765 };
1766
1767 /* NOTE: there is currently no IDAT_reset, so a stream cannot contain more than
1768  * one IDAT sequence (i.e. MNG is not supported).
1769  */
1770
1771 static void
1772 IDAT_end(struct IDAT **idat_var)
1773 {
1774    struct IDAT *idat = *idat_var;
1775    struct file *file = idat->file;
1776
1777    *idat_var = NULL;
1778
1779    CLEAR(*idat);
1780
1781    assert(file->chunk != NULL);
1782    chunk_end(&file->chunk);
1783
1784    /* Regardless of why the IDAT was killed set the state back to CHUNKS (it may
1785     * already be CHUNKS because the state isn't changed until process_IDAT
1786     * returns; a stop will cause IDAT_end to be entered in state CHUNKS!)
1787     */
1788    file->state = STATE_CHUNKS;
1789 }
1790
1791 static void
1792 IDAT_init(struct IDAT * const idat, struct file * const file)
1793    /* When the chunk is png_IDAT instantiate an IDAT control structure in place
1794     * of a chunk control structure.  The IDAT will instantiate a chunk control
1795     * structure using the file alloc routine.
1796     *
1797     * NOTE: this routine must only be called from the file alloc routine!
1798     */
1799 {
1800    assert(file->chunk == NULL);
1801    assert(file->idat == NULL);
1802
1803    CLEAR(*idat);
1804
1805    idat->file = file;
1806    idat->global = file->global;
1807
1808    /* Initialize the tail to the pre-allocated buffer and set the count to 0
1809     * (empty.)
1810     */
1811    idat->global->idat_cache.count = 0;
1812    idat->idat_list_head = idat->idat_list_tail = &idat->global->idat_cache;
1813
1814    /* Now the chunk.  The allocator calls the initializer of the new chunk and
1815     * stores the result in file->chunk:
1816     */
1817    file->alloc(file, 0/*chunk*/);
1818    assert(file->chunk != NULL);
1819
1820    /* And store this for cleanup (and to check for double alloc or failure to
1821     * free.)
1822     */
1823    file->idat = idat;
1824 }
1825
1826 static png_uint_32
1827 rechunk_length(struct IDAT *idat)
1828    /* Return the length for the next IDAT chunk, taking into account
1829     * rechunking.
1830     */
1831 {
1832    png_uint_32 len = idat->global->idat_max;
1833
1834    if (len == 0) /* use original chunk lengths */
1835    {
1836       const struct IDAT_list *cur;
1837       unsigned int count;
1838
1839       if (idat->idat_index == 0) /* at the new chunk (first time) */
1840          return idat->idat_length; /* use the cache */
1841
1842       /* Otherwise rechunk_length is called at the end of a chunk for the length
1843        * of the next one.
1844        */
1845       cur = idat->idat_cur;
1846       count = idat->idat_count;
1847
1848       assert(idat->idat_index == idat->idat_length &&
1849          idat->idat_length == cur->lengths[count]);
1850
1851       /* Return length of the *next* chunk */
1852       if (++count < cur->count)
1853          return cur->lengths[count];
1854
1855       /* End of this list */
1856       assert(cur != idat->idat_list_tail);
1857       cur = cur->next;
1858       assert(cur != NULL && cur->count > 0);
1859       return cur->lengths[0];
1860    }
1861
1862    else /* rechunking */
1863    {
1864       /* The chunk size is the lesser of file->idat_max and the number
1865        * of remaining bytes.
1866        */
1867       png_uint_32 have = idat->idat_length - idat->idat_index;
1868
1869       if (len > have)
1870       {
1871          struct IDAT_list *cur = idat->idat_cur;
1872          unsigned int j = idat->idat_count+1; /* the next IDAT in the list */
1873
1874          do
1875          {
1876             /* Add up the remaining bytes.  This can't overflow because the
1877              * individual lengths are always <= 0x7fffffff, so when we add two
1878              * of them overflow is not possible.
1879              */
1880             assert(cur != NULL);
1881
1882             for (;;)
1883             {
1884                /* NOTE: IDAT_list::count here, not IDAT_list::length */
1885                for (; j < cur->count; ++j)
1886                {
1887                   have += cur->lengths[j];
1888                   if (len <= have)
1889                      return len;
1890                }
1891
1892                /* If this was the end return the count of the available bytes */
1893                if (cur == idat->idat_list_tail)
1894                   return have;
1895
1896                cur = cur->next;
1897                j = 0;
1898             }
1899          }
1900          while (len > have);
1901       }
1902
1903       return len;
1904    }
1905 }
1906
1907 static int
1908 process_IDAT(struct file *file)
1909    /* Process the IDAT stream, this is the more complex than the preceding
1910     * cases because the compressed data is spread across multiple IDAT chunks
1911     * (typically).  Rechunking of the data is not handled here; all this
1912     * function does is establish whether the zlib header needs to be modified.
1913     *
1914     * Initially the function returns false, indicating that the chunk should not
1915     * be written.  It does this until the last IDAT chunk is passed in, then it
1916     * checks the zlib data and returns true.
1917     *
1918     * It does not return false on a fatal error; it calls stop instead.
1919     *
1920     * The caller must have an instantiated (IDAT) control structure and it must
1921     * have extent over the whole read of the IDAT stream.  For a PNG this means
1922     * the whole PNG read, for MNG it could have lesser extent.
1923     */
1924 {
1925    struct IDAT_list *list;
1926
1927    assert(file->idat != NULL && file->chunk != NULL);
1928
1929    /* We need to first check the entire sequence of IDAT chunks to ensure the
1930     * stream is in sync.  Do this by building a list of all the chunks and
1931     * recording the length of each because the length may have been fixed up by
1932     * sync_stream below.
1933     *
1934     * At the end of the list of chunks, where the type of the next chunk is not
1935     * png_IDAT, process the whole stream using the list data to check validity
1936     * then return control to the start and rewrite everything.
1937     */
1938    list = file->idat->idat_list_tail;
1939
1940    if (list->count == list->length)
1941    {
1942       list = IDAT_list_extend(list);
1943
1944       if (list == NULL)
1945          stop(file, READ_ERROR_CODE, "out of memory");
1946
1947       /* Move to the next block */
1948       list->count = 0;
1949       file->idat->idat_list_tail = list;
1950    }
1951
1952    /* And fill in the next IDAT information buffer. */
1953    list->lengths[(list->count)++] = file->chunk->chunk_length;
1954
1955    /* The type of the next chunk was recorded in the file control structure by
1956     * the caller, if this is png_IDAT return 'skip' to the caller.
1957     */
1958    if (file->type == png_IDAT)
1959       return 0; /* skip this for the moment */
1960
1961    /* This is the final IDAT chunk, so run the tests to check for the too far
1962     * back error and possibly optimize the window bits.  This means going back
1963     * to the start of the first chunk data, which is stored in the original
1964     * chunk allocation.
1965     */
1966    setpos(file->chunk);
1967
1968    if (zlib_check(file, 0))
1969    {
1970       struct IDAT *idat;
1971       int cmp;
1972
1973       /* The IDAT stream was successfully uncompressed; see whether it
1974        * contained the correct number of bytes of image data.
1975        */
1976       cmp = uarb_cmp(file->image_bytes, file->image_digits,
1977          file->chunk->uncompressed_bytes, file->chunk->uncompressed_digits);
1978
1979       if (cmp < 0)
1980          type_message(file, png_IDAT, "extra uncompressed data");
1981
1982       else if (cmp > 0)
1983          stop(file, LIBPNG_ERROR_CODE, "IDAT: uncompressed data too small");
1984
1985       /* Return the stream to the start of the first IDAT chunk; the length
1986        * is set in the write case below but the input chunk variables must be
1987        * set (once) here:
1988        */
1989       setpos(file->chunk);
1990
1991       idat = file->idat;
1992       idat->idat_cur = idat->idat_list_head;
1993       idat->idat_length = idat->idat_cur->lengths[0];
1994       idat->idat_count = 0; /* Count of chunks read in current list */
1995       idat->idat_index = 0; /* Index into chunk data */
1996
1997       /* Update the chunk length to the correct value for the IDAT chunk: */
1998       file->chunk->chunk_length = rechunk_length(idat);
1999
2000       /* Change the state to writing IDAT chunks */
2001       file->state = STATE_IDAT;
2002
2003       return 1;
2004    }
2005
2006    else /* Failure to decompress the IDAT stream; give up. */
2007       stop(file, ZLIB_ERROR_CODE, "could not uncompress IDAT");
2008 }
2009
2010 /* ZLIB CONTROL STRUCTURE */
2011 struct zlib
2012 {
2013    /* ANCESTORS */
2014    struct IDAT *  idat;          /* NOTE: May be NULL */
2015    struct chunk * chunk;
2016    struct file *  file;
2017    struct global *global;
2018
2019    /* GLOBAL ZLIB INFORMATION: SET BY THE CALLER */
2020    png_uint_32    rewrite_offset;
2021
2022    /* GLOBAL ZLIB INFORMATION: SET BY THE ZLIB READ CODE */
2023    udigit         compressed_bytes[5];
2024    int            compressed_digits;
2025    udigit         uncompressed_bytes[5];
2026    int            uncompressed_digits;
2027    int            file_bits;             /* window bits from the file */
2028    int            ok_bits;               /* Set <16 on a successful read */
2029    int            cksum;                 /* Set on a checksum error */
2030
2031    /* PROTECTED ZLIB INFORMATION: USED BY THE ZLIB ROUTINES */
2032    z_stream       z;
2033    png_uint_32    extra_bytes;   /* Count of extra compressed bytes */
2034    int            state;
2035    int            rc;            /* Last return code */
2036    int            window_bits;   /* 0 if no change */
2037    png_byte       header[2];
2038 };
2039
2040 static const char *
2041 zlib_flevel(struct zlib *zlib)
2042 {
2043    switch (zlib->header[1] >> 6)
2044    {
2045       case 0:  return "supfast";
2046       case 1:  return "stdfast";
2047       case 2:  return "default";
2048       case 3:  return "maximum";
2049       default: assert(UNREACHED);
2050    }
2051
2052    return "COMPILER BUG";
2053 }
2054
2055 static const char *
2056 zlib_rc(struct zlib *zlib)
2057    /* Return a string for the zlib return code */
2058 {
2059    switch (zlib->rc)
2060    {
2061       case Z_OK:              return "Z_OK";
2062       case Z_STREAM_END:      return "Z_STREAM_END";
2063       case Z_NEED_DICT:       return "Z_NEED_DICT";
2064       case Z_ERRNO:           return "Z_ERRNO";
2065       case Z_STREAM_ERROR:    return "Z_STREAM_ERROR";
2066       case Z_DATA_ERROR:      return "Z_DATA_ERROR";
2067       case Z_MEM_ERROR:       return "Z_MEM_ERROR";
2068       case Z_BUF_ERROR:       return "Z_BUF_ERROR";
2069       case Z_VERSION_ERROR:   return "Z_VERSION_ERROR";
2070       default:                return "Z_*INVALID_RC*";
2071    }
2072 }
2073
2074 static void
2075 zlib_message(struct zlib *zlib, int unexpected)
2076    /* Output a message given a zlib rc */
2077 {
2078    if (zlib->global->errors)
2079    {
2080       const char *reason = zlib->z.msg;
2081
2082       if (reason == NULL)
2083          reason = "[no message]";
2084
2085       fputs(zlib->file->file_name, stderr);
2086       type_sep(stderr);
2087       type_name(zlib->chunk->chunk_type, stderr);
2088       fprintf(stderr, ": %szlib error: %d (%s) (%s)\n",
2089          unexpected ? "unexpected " : "", zlib->rc, zlib_rc(zlib), reason);
2090    }
2091 }
2092
2093 static void
2094 zlib_end(struct zlib *zlib)
2095 {
2096    /* Output the summary line now; this ensures a summary line always gets
2097     * output regardless of the manner of exit.
2098     */
2099    if (!zlib->global->quiet)
2100    {
2101       if (zlib->ok_bits < 16) /* stream was read ok */
2102       {
2103          const char *reason;
2104
2105          if (zlib->cksum)
2106             reason = "CHK"; /* checksum error */
2107
2108          else if (zlib->ok_bits > zlib->file_bits)
2109             reason = "TFB"; /* fixing a too-far-back error */
2110
2111          else if (zlib->ok_bits == zlib->file_bits)
2112             reason = "OK ";
2113
2114          else
2115             reason = "OPT"; /* optimizing window bits */
2116
2117          /* SUMMARY FORMAT (for a successful zlib inflate):
2118           *
2119           * IDAT reason flevel file-bits ok-bits compressed uncompressed file
2120           */
2121          type_name(zlib->chunk->chunk_type, stdout);
2122          printf(" %s %s %d %d ", reason, zlib_flevel(zlib), zlib->file_bits,
2123             zlib->ok_bits);
2124          uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout);
2125          putc(' ', stdout);
2126          uarb_print(zlib->uncompressed_bytes, zlib->uncompressed_digits,
2127             stdout);
2128          putc(' ', stdout);
2129          fputs(zlib->file->file_name, stdout);
2130          putc('\n', stdout);
2131       }
2132
2133       else
2134       {
2135          /* This is a zlib read error; the chunk will be skipped.  For an IDAT
2136           * stream this will also cause a fatal read error (via stop()).
2137           *
2138           * SUMMARY FORMAT:
2139           *
2140           * IDAT SKP flevel file-bits z-rc compressed message file
2141           *
2142           * z-rc is the zlib failure code; message is the error message with
2143           * spaces replaced by '-'.  The compressed byte count indicates where
2144           * in the zlib stream the error occurred.
2145           */
2146          type_name(zlib->chunk->chunk_type, stdout);
2147          printf(" SKP %s %d %s ", zlib_flevel(zlib), zlib->file_bits,
2148             zlib_rc(zlib));
2149          uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout);
2150          putc(' ', stdout);
2151          emit_string(zlib->z.msg ? zlib->z.msg : "[no_message]", stdout);
2152          putc(' ', stdout);
2153          fputs(zlib->file->file_name, stdout);
2154          putc('\n', stdout);
2155       }
2156    }
2157
2158    if (zlib->state >= 0)
2159    {
2160       zlib->rc = inflateEnd(&zlib->z);
2161
2162       if (zlib->rc != Z_OK)
2163          zlib_message(zlib, 1/*unexpected*/);
2164    }
2165
2166    CLEAR(*zlib);
2167 }
2168
2169 static int
2170 zlib_reset(struct zlib *zlib, int window_bits)
2171    /* Reinitializes a zlib with a different window_bits */
2172 {
2173    assert(zlib->state >= 0); /* initialized by zlib_init */
2174
2175    zlib->z.next_in = Z_NULL;
2176    zlib->z.avail_in = 0;
2177    zlib->z.next_out = Z_NULL;
2178    zlib->z.avail_out = 0;
2179
2180    zlib->window_bits = window_bits;
2181    zlib->compressed_digits = 0;
2182    zlib->uncompressed_digits = 0;
2183
2184    zlib->state = 0; /* initialized, once */
2185    zlib->rc = inflateReset2(&zlib->z, 0);
2186    if (zlib->rc != Z_OK)
2187    {
2188       zlib_message(zlib, 1/*unexpected*/);
2189       return 0;
2190    }
2191
2192    return 1;
2193 }
2194
2195 static int
2196 zlib_init(struct zlib *zlib, struct IDAT *idat, struct chunk *chunk,
2197    int window_bits, png_uint_32 offset)
2198    /* Initialize a zlib_control; the result is true/false */
2199 {
2200    CLEAR(*zlib);
2201
2202    zlib->idat = idat;
2203    zlib->chunk = chunk;
2204    zlib->file = chunk->file;
2205    zlib->global = chunk->global;
2206    zlib->rewrite_offset = offset; /* never changed for this zlib */
2207
2208    /* *_out does not need to be set: */
2209    zlib->z.next_in = Z_NULL;
2210    zlib->z.avail_in = 0;
2211    zlib->z.zalloc = Z_NULL;
2212    zlib->z.zfree = Z_NULL;
2213    zlib->z.opaque = Z_NULL;
2214
2215    zlib->state = -1;
2216    zlib->window_bits = window_bits;
2217
2218    zlib->compressed_digits = 0;
2219    zlib->uncompressed_digits = 0;
2220
2221    /* These values are sticky across reset (in addition to the stuff in the
2222     * first block, which is actually constant.)
2223     */
2224    zlib->file_bits = 24;
2225    zlib->ok_bits = 16; /* unset */
2226    zlib->cksum = 0; /* set when a checksum error is detected */
2227
2228    /* '0' means use the header; inflateInit2 should always succeed because it
2229     * does nothing apart from allocating the internal zstate.
2230     */
2231    zlib->rc = inflateInit2(&zlib->z, 0);
2232    if (zlib->rc != Z_OK)
2233    {
2234       zlib_message(zlib, 1/*unexpected*/);
2235       return 0;
2236    }
2237
2238    else
2239    {
2240       zlib->state = 0; /* initialized */
2241       return 1;
2242    }
2243 }
2244
2245 static int
2246 max_window_bits(uarbc size, int ndigits)
2247    /* Return the zlib stream window bits required for data of the given size. */
2248 {
2249    png_uint_16 cb;
2250
2251    if (ndigits > 1)
2252       return 15;
2253
2254    cb = size[0];
2255
2256    if (cb > 16384) return 15;
2257    if (cb >  8192) return 14;
2258    if (cb >  4096) return 13;
2259    if (cb >  2048) return 12;
2260    if (cb >  1024) return 11;
2261    if (cb >   512) return 10;
2262    if (cb >   256) return  9;
2263    return 8;
2264 }
2265
2266 static int
2267 zlib_advance(struct zlib *zlib, png_uint_32 nbytes)
2268    /* Read nbytes compressed bytes; the stream will be initialized if required.
2269     * Bytes are always being reread and errors are fatal.  The return code is as
2270     * follows:
2271     *
2272     *    -1: saw the "too far back" error
2273     *     0: ok, keep going
2274     *     1: saw Z_STREAM_END (zlib->extra_bytes indicates too much data)
2275     *     2: a zlib error that cannot be corrected (error message already
2276     *        output if required.)
2277     */
2278 #  define ZLIB_TOO_FAR_BACK (-1)
2279 #  define ZLIB_OK           0
2280 #  define ZLIB_STREAM_END   1
2281 #  define ZLIB_FATAL        2
2282 {
2283    int state = zlib->state;
2284    int endrc = ZLIB_OK;
2285    png_uint_32 in_bytes = 0;
2286    struct file *file = zlib->file;
2287
2288    assert(state >= 0);
2289
2290    while (in_bytes < nbytes && endrc == ZLIB_OK)
2291    {
2292       png_uint_32 out_bytes;
2293       int flush;
2294       png_byte bIn = reread_byte(file);
2295       png_byte bOut;
2296
2297       switch (state)
2298       {
2299          case 0: /* first header byte */
2300             {
2301                int file_bits = 8+(bIn >> 4);
2302                int new_bits = zlib->window_bits;
2303
2304                zlib->file_bits = file_bits;
2305
2306                /* Check against the existing value - it may not need to be
2307                 * changed.  Note that a bogus file_bits is allowed through once,
2308                 * to see if it works, but the window_bits value is set to 15,
2309                 * the maximum.
2310                 */
2311                if (new_bits == 0) /* no change */
2312                   zlib->window_bits = ((file_bits > 15) ? 15 : file_bits);
2313
2314                else if (new_bits != file_bits) /* rewrite required */
2315                   bIn = (png_byte)((bIn & 0xf) + ((new_bits-8) << 4));
2316             }
2317
2318             zlib->header[0] = bIn;
2319             zlib->state = state = 1;
2320             break;
2321
2322          case 1: /* second header byte */
2323             {
2324                int b2 = bIn & 0xe0; /* top 3 bits */
2325
2326                /* The checksum calculation, on the first 11 bits: */
2327                b2 += 0x1f - ((zlib->header[0] << 8) + b2) % 0x1f;
2328
2329                /* Update the checksum byte if required: */
2330                if (bIn != b2)
2331                {
2332                   /* If the first byte wasn't changed this indicates an error in
2333                    * the checksum calculation; signal this by setting 'cksum'.
2334                    */
2335                   if (zlib->file_bits == zlib->window_bits)
2336                      zlib->cksum = 1;
2337
2338                   bIn = (png_byte)b2;
2339                }
2340             }
2341
2342             zlib->header[1] = bIn;
2343             zlib->state = state = 2;
2344             break;
2345
2346          default: /* After the header bytes */
2347             break;
2348       }
2349
2350       /* For some streams, perhaps only those compressed with 'superfast
2351        * compression' (which results in a lot of copying) Z_BUF_ERROR can happen
2352        * immediately after all output has been flushed on the next input byte.
2353        * This is handled below when Z_BUF_ERROR is detected by adding an output
2354        * byte.
2355        */
2356       zlib->z.next_in = &bIn;
2357       zlib->z.avail_in = 1;
2358       zlib->z.next_out = &bOut;
2359       zlib->z.avail_out = 0;     /* Initially */
2360
2361       /* Initially use Z_NO_FLUSH in an attempt to persuade zlib to look at this
2362        * byte without confusing what is going on with output.
2363        */
2364       flush = Z_NO_FLUSH;
2365       out_bytes = 0;
2366
2367       /* NOTE: expression 3 is only evaluted on 'continue', because of the
2368        * 'break' at the end of this loop below.
2369        */
2370       for (;endrc == ZLIB_OK;
2371          flush = Z_SYNC_FLUSH,
2372          zlib->z.next_out = &bOut,
2373          zlib->z.avail_out = 1,
2374          ++out_bytes)
2375       {
2376          zlib->rc = inflate(&zlib->z, flush);
2377          out_bytes -= zlib->z.avail_out;
2378
2379          switch (zlib->rc)
2380          {
2381             case Z_BUF_ERROR:
2382                if (zlib->z.avail_out == 0)
2383                   continue; /* Try another output byte. */
2384
2385                if (zlib->z.avail_in == 0)
2386                   break; /* Try another input byte */
2387
2388                /* Both avail_out and avail_in are 1 yet zlib returned a code
2389                 * indicating no progress was possible.  This is unexpected.
2390                 */
2391                zlib_message(zlib, 1/*unexpected*/);
2392                endrc = ZLIB_FATAL; /* stop processing */
2393                break;
2394
2395             case Z_OK:
2396                /* Zlib is supposed to have made progress: */
2397                assert(zlib->z.avail_out == 0 || zlib->z.avail_in == 0);
2398                continue;
2399
2400             case Z_STREAM_END:
2401                /* This is the successful end. */
2402                zlib->state = 3; /* end of stream */
2403                endrc = ZLIB_STREAM_END;
2404                break;
2405
2406             case Z_NEED_DICT:
2407                zlib_message(zlib, 0/*stream error*/);
2408                endrc = ZLIB_FATAL;
2409                break;
2410
2411             case Z_DATA_ERROR:
2412                /* The too far back error can be corrected, others cannot: */
2413                if (zlib->z.msg != NULL &&
2414                   strcmp(zlib->z.msg, "invalid distance too far back") == 0)
2415                {
2416                   endrc = ZLIB_TOO_FAR_BACK;
2417                   break;
2418                }
2419                /* FALL THROUGH */
2420
2421             default:
2422                zlib_message(zlib, 0/*stream error*/);
2423                endrc = ZLIB_FATAL;
2424                break;
2425          } /* switch (inflate rc) */
2426
2427          /* Control gets here when further output is not possible; endrc may
2428           * still be ZLIB_OK if more input is required.
2429           */
2430          break;
2431       } /* for (output bytes) */
2432
2433       /* Keep a running count of output byte produced: */
2434       zlib->uncompressed_digits = uarb_add32(zlib->uncompressed_bytes,
2435          zlib->uncompressed_digits, out_bytes);
2436
2437       /* Keep going, the loop will terminate when endrc is no longer set to
2438        * ZLIB_OK or all the input bytes have been consumed; meanwhile keep
2439        * adding input bytes.
2440        */
2441       assert(zlib->z.avail_in == 0 || endrc != ZLIB_OK);
2442
2443       in_bytes += 1 - zlib->z.avail_in;
2444    } /* while (input bytes) */
2445
2446    assert(in_bytes == nbytes || endrc != ZLIB_OK);
2447
2448    /* Update the running total of input bytes consumed */
2449    zlib->compressed_digits = uarb_add32(zlib->compressed_bytes,
2450       zlib->compressed_digits, in_bytes - zlib->z.avail_in);
2451
2452    /* At the end of the stream update the chunk with the accumulated
2453     * information if it is an improvement:
2454     */
2455    if (endrc == ZLIB_STREAM_END && zlib->window_bits < zlib->ok_bits)
2456    {
2457       struct chunk *chunk = zlib->chunk;
2458
2459       chunk->uncompressed_digits = uarb_copy(chunk->uncompressed_bytes,
2460          zlib->uncompressed_bytes, zlib->uncompressed_digits);
2461       chunk->compressed_digits = uarb_copy(chunk->compressed_bytes,
2462          zlib->compressed_bytes, zlib->compressed_digits);
2463       chunk->rewrite_buffer[0] = zlib->header[0];
2464       chunk->rewrite_buffer[1] = zlib->header[1];
2465
2466       if (zlib->window_bits != zlib->file_bits || zlib->cksum)
2467       {
2468          /* A rewrite is required */
2469          chunk->rewrite_offset = zlib->rewrite_offset;
2470          chunk->rewrite_length = 2;
2471       }
2472
2473       else
2474       {
2475          chunk->rewrite_offset = 0;
2476          chunk->rewrite_length = 0;
2477       }
2478
2479       if (in_bytes < nbytes)
2480          chunk_message(chunk, "extra compressed data");
2481
2482       zlib->extra_bytes = nbytes - in_bytes;
2483       zlib->ok_bits = zlib->window_bits;
2484    }
2485
2486    return endrc;
2487 }
2488
2489 static int
2490 zlib_run(struct zlib *zlib)
2491    /* Like zlib_advance but also handles a stream of IDAT chunks. */
2492 {
2493    /* The 'extra_bytes' field is set by zlib_advance if there is extra
2494     * compressed data in the chunk it handles (if it sees Z_STREAM_END before
2495     * all the input data has been used.)  This function uses the value to update
2496     * the correct chunk length, so the problem should only ever be detected once
2497     * for each chunk.  zlib_advance outputs the error message, though see the
2498     * IDAT specific check below.
2499     */
2500    zlib->extra_bytes = 0;
2501
2502    if (zlib->idat != NULL)
2503    {
2504       struct IDAT_list *list = zlib->idat->idat_list_head;
2505       struct IDAT_list *last = zlib->idat->idat_list_tail;
2506       int        skip = 0;
2507
2508       /* 'rewrite_offset' is the offset of the LZ data within the chunk, for
2509        * IDAT it should be 0:
2510        */
2511       assert(zlib->rewrite_offset == 0);
2512
2513       /* Process each IDAT_list in turn; the caller has left the stream
2514        * positioned at the start of the first IDAT chunk data.
2515        */
2516       for (;;)
2517       {
2518          const unsigned int count = list->count;
2519          unsigned int i;
2520
2521          for (i = 0; i<count; ++i)
2522          {
2523             int rc;
2524
2525             if (skip > 0) /* Skip CRC and next IDAT header */
2526                skip_12(zlib->file);
2527
2528             skip = 12; /* for the next time */
2529
2530             rc = zlib_advance(zlib, list->lengths[i]);
2531
2532             switch (rc)
2533             {
2534                case ZLIB_OK: /* keep going */
2535                   break;
2536
2537                case ZLIB_STREAM_END: /* stop */
2538                   /* There may be extra chunks; if there are and one of them is
2539                    * not zero length output the 'extra data' message.  Only do
2540                    * this check if errors are being output.
2541                    */
2542                   if (zlib->global->errors && zlib->extra_bytes == 0)
2543                   {
2544                      struct IDAT_list *check = list;
2545                      int j = i+1, jcount = count;
2546
2547                      for (;;)
2548                      {
2549                         for (; j<jcount; ++j)
2550                            if (check->lengths[j] > 0)
2551                            {
2552                               chunk_message(zlib->chunk,
2553                                  "extra compressed data");
2554                               goto end_check;
2555                            }
2556
2557                         if (check == last)
2558                            break;
2559
2560                         check = check->next;
2561                         jcount = check->count;
2562                         j = 0;
2563                      }
2564                   }
2565
2566                end_check:
2567                   /* Terminate the list at the current position, reducing the
2568                    * length of the last IDAT too if required.
2569                    */
2570                   list->lengths[i] -= zlib->extra_bytes;
2571                   list->count = i+1;
2572                   zlib->idat->idat_list_tail = list;
2573                   /* FALL THROUGH */
2574
2575                default:
2576                   return rc;
2577             }
2578          }
2579
2580          /* At the end of the compressed data and Z_STREAM_END was not seen. */
2581          if (list == last)
2582             return ZLIB_OK;
2583
2584          list = list->next;
2585       }
2586    }
2587
2588    else
2589    {
2590       struct chunk *chunk = zlib->chunk;
2591       int rc;
2592
2593       assert(zlib->rewrite_offset < chunk->chunk_length);
2594
2595       rc = zlib_advance(zlib, chunk->chunk_length - zlib->rewrite_offset);
2596
2597       /* The extra bytes in the chunk are handled now by adjusting the chunk
2598        * length to exclude them; the zlib data is always stored at the end of
2599        * the PNG chunk (although clearly this is not necessary.)  zlib_advance
2600        * has already output a warning message.
2601        */
2602       chunk->chunk_length -= zlib->extra_bytes;
2603       return rc;
2604    }
2605 }
2606
2607 static int /* global function; not a member function */
2608 zlib_check(struct file *file, png_uint_32 offset)
2609    /* Check the stream of zlib compressed data in either idat (if given) or (if
2610     * not) chunk.  In fact it is zlib_run that handles the difference in reading
2611     * a single chunk and a list of IDAT chunks.
2612     *
2613     * In either case the input file must be positioned at the first byte of zlib
2614     * compressed data (the first header byte).
2615     *
2616     * The return value is true on success, including the case where the zlib
2617     * header may need to be rewritten, and false on an unrecoverable error.
2618     *
2619     * In the case of IDAT chunks 'offset' should be 0.
2620     */
2621 {
2622    fpos_t start_pos;
2623    struct zlib zlib;
2624
2625    /* Record the start of the LZ data to allow a re-read. */
2626    file_getpos(file, &start_pos);
2627
2628    /* First test the existing (file) window bits: */
2629    if (zlib_init(&zlib, file->idat, file->chunk, 0/*window bits*/, offset))
2630    {
2631       int min_bits, max_bits, rc;
2632
2633       /* The first run using the existing window bits. */
2634       rc = zlib_run(&zlib);
2635
2636       switch (rc)
2637       {
2638          case ZLIB_TOO_FAR_BACK:
2639             /* too far back error */
2640             file->status_code |= TOO_FAR_BACK;
2641             min_bits = zlib.window_bits + 1;
2642             max_bits = 15;
2643             break;
2644
2645          case ZLIB_STREAM_END:
2646             if (!zlib.global->optimize_zlib &&
2647                zlib.window_bits == zlib.file_bits && !zlib.cksum)
2648             {
2649                /* The trivial case where the stream is ok and optimization was
2650                 * not requested.
2651                 */
2652                zlib_end(&zlib);
2653                return 1;
2654             }
2655
2656             max_bits = max_window_bits(zlib.uncompressed_bytes,
2657                zlib.uncompressed_digits);
2658             if (zlib.ok_bits < max_bits)
2659                max_bits = zlib.ok_bits;
2660             min_bits = 8;
2661
2662             /* cksum is set if there is an error in the zlib header checksum
2663              * calculation in the original file (and this may be the only reason
2664              * a rewrite is required).  We can't rely on the file window bits in
2665              * this case, so do the optimization anyway.
2666              */
2667             if (zlib.cksum)
2668                chunk_message(zlib.chunk, "zlib checkum");
2669             break;
2670
2671
2672          case ZLIB_OK:
2673             /* Truncated stream; unrecoverable, gets converted to ZLIB_FATAL */
2674             zlib.z.msg = PNGZ_MSG_CAST("[truncated]");
2675             zlib_message(&zlib, 0/*expected*/);
2676             /* FALL THROUGH */
2677
2678          default:
2679             /* Unrecoverable error; skip the chunk; a zlib_message has already
2680              * been output.
2681              */
2682             zlib_end(&zlib);
2683             return 0;
2684       }
2685
2686       /* Optimize window bits or fix a too-far-back error.  min_bits and
2687        * max_bits have been set appropriately, ok_bits records the bit value
2688        * known to work.
2689        */
2690       while (min_bits < max_bits || max_bits < zlib.ok_bits/*if 16*/)
2691       {
2692          int test_bits = (min_bits + max_bits) >> 1;
2693
2694          if (zlib_reset(&zlib, test_bits))
2695          {
2696             file_setpos(file, &start_pos);
2697             rc = zlib_run(&zlib);
2698
2699             switch (rc)
2700             {
2701                case ZLIB_TOO_FAR_BACK:
2702                   min_bits = test_bits+1;
2703                   if (min_bits > max_bits)
2704                   {
2705                      /* This happens when the stream really is damaged and it
2706                       * contains a distance code that addresses bytes before
2707                       * the start of the uncompressed data.
2708                       */
2709                      assert(test_bits == 15);
2710
2711                      /* Output the error that wasn't output before: */
2712                      if (zlib.z.msg == NULL)
2713                         zlib.z.msg = PNGZ_MSG_CAST(
2714                            "invalid distance too far back");
2715                      zlib_message(&zlib, 0/*stream error*/);
2716                      zlib_end(&zlib);
2717                      return 0;
2718                   }
2719                   break;
2720
2721                case ZLIB_STREAM_END: /* success */
2722                   max_bits = test_bits;
2723                   break;
2724
2725                default:
2726                   /* A fatal error; this happens if a too-far-back error was
2727                    * hiding a more serious error, zlib_advance has already
2728                    * output a zlib_message.
2729                    */
2730                   zlib_end(&zlib);
2731                   return 0;
2732             }
2733          }
2734
2735          else /* inflateReset2 failed */
2736          {
2737             zlib_end(&zlib);
2738             return 0;
2739          }
2740       }
2741
2742       /* The loop guarantees this */
2743       assert(zlib.ok_bits == max_bits);
2744       zlib_end(&zlib);
2745       return 1;
2746    }
2747
2748    else /* zlib initialization failed - skip the chunk */
2749    {
2750       zlib_end(&zlib);
2751       return 0;
2752    }
2753 }
2754
2755 /***************************** LIBPNG CALLBACKS *******************************/
2756 /* The strategy here is to run a regular libpng PNG file read but examine the
2757  * input data (from the file) before passing it to libpng so as to be aware of
2758  * the state we expect libpng to be in.  Warning and error callbacks are also
2759  * intercepted so that they can be quieted and interpreted.  Interpretation
2760  * depends on a somewhat risky string match for known error messages; let us
2761  * hope that this can be fixed in the next version of libpng.
2762  *
2763  * The control structure is pointed to by the libpng error pointer.  It contains
2764  * that set of structures which must persist across multiple read callbacks,
2765  * which is pretty much everything except the 'zlib' control structure.
2766  *
2767  * The file structure is instantiated in the caller of the per-file routine, but
2768  * the per-file routine contains the chunk and IDAT control structures.
2769  */
2770 /* The three routines read_chunk, process_chunk and sync_stream can only be
2771  * called via a call to read_chunk and only exit at a return from process_chunk.
2772  * These routines could have been written as one confusing large routine,
2773  * instead this code relies on the compiler to do tail call elimination.  The
2774  * possible calls are as follows:
2775  *
2776  * read_chunk
2777  *    -> sync_stream
2778  *       -> process_chunk
2779  *    -> process_chunk
2780  *       -> read_chunk
2781  *       returns
2782  */
2783 static void read_chunk(struct file *file);
2784 static void
2785 process_chunk(struct file *file, png_uint_32 file_crc, png_uint_32 next_length,
2786    png_uint_32 next_type)
2787    /* Called when the chunk data has been read, next_length and next_type
2788     * will be set for the next chunk (or 0 if this is IEND).
2789     *
2790     * When this routine returns, chunk_length and chunk_type will be set for the
2791     * next chunk to write because if a chunk is skipped this return calls back
2792     * to read_chunk.
2793     */
2794 {
2795    const png_uint_32 type = file->type;
2796
2797    if (file->global->verbose > 1)
2798    {
2799       fputs("  ", stderr);
2800       type_name(file->type, stderr);
2801       fprintf(stderr, " %lu 0x%.8x 0x%.8x\n", (unsigned long)file->length,
2802          file->crc ^ 0xffffffff, file_crc);
2803    }
2804
2805    /* The basic structure seems correct but the CRC may not match, in this
2806     * case assume that it is simply a bad CRC, either wrongly calculated or
2807     * because of damaged stream data.
2808     */
2809    if ((file->crc ^ 0xffffffff) != file_crc)
2810    {
2811       /* The behavior is set by the 'skip' setting; if it is anything other
2812        * than SKIP_BAD_CRC ignore the bad CRC and return the chunk, with a
2813        * corrected CRC and possibly processed, to libpng.  Otherwise skip the
2814        * chunk, which will result in a fatal error if the chunk is critical.
2815        */
2816       file->status_code |= CRC_ERROR;
2817
2818       /* Ignore the bad CRC  */
2819       if (file->global->skip != SKIP_BAD_CRC)
2820          type_message(file, type, "bad CRC");
2821
2822       /* This will cause an IEND with a bad CRC to stop */
2823       else if (CRITICAL(type))
2824          stop(file, READ_ERROR_CODE, "bad CRC in critical chunk");
2825
2826       else
2827       {
2828          type_message(file, type, "skipped: bad CRC");
2829
2830          /* NOTE: this cannot be reached for IEND because it is critical. */
2831          goto skip_chunk;
2832       }
2833    }
2834
2835    /* Check for other 'skip' cases and handle these; these only apply to
2836     * ancillary chunks (and not tRNS, which should probably have been a critical
2837     * chunk.)
2838     */
2839    if (skip_chunk_type(file->global, type))
2840       goto skip_chunk;
2841
2842    /* The chunk may still be skipped if problems are detected in the LZ data,
2843     * however the LZ data check requires a chunk.  Handle this by instantiating
2844     * a chunk unless an IDAT is already instantiated (IDAT control structures
2845     * instantiate their own chunk.)
2846     */
2847    if (type != png_IDAT)
2848       file->alloc(file, 0/*chunk*/);
2849
2850    else if (file->idat == NULL)
2851       file->alloc(file, 1/*IDAT*/);
2852
2853    else
2854    {
2855       /* The chunk length must be updated for process_IDAT */
2856       assert(file->chunk != NULL);
2857       assert(file->chunk->chunk_type == png_IDAT);
2858       file->chunk->chunk_length = file->length;
2859    }
2860
2861    /* Record the 'next' information too, now that the original values for
2862     * this chunk have been copied.  Notice that the IDAT chunks only make a
2863     * copy of the position of the first chunk, this is fine - process_IDAT does
2864     * not need the position of this chunk.
2865     */
2866    file->length = next_length;
2867    file->type = next_type;
2868    getpos(file);
2869
2870    /* Do per-type processing, note that if this code does not return from the
2871     * function the chunk will be skipped.  The rewrite is cancelled here so that
2872     * it can be set in the per-chunk processing.
2873     */
2874    file->chunk->rewrite_length = 0;
2875    file->chunk->rewrite_offset = 0;
2876    switch (type)
2877    {
2878       default:
2879          return;
2880
2881       case png_IHDR:
2882          /* Read this now and update the control structure with the information
2883           * it contains.  The header is validated completely to ensure this is a
2884           * PNG.
2885           */
2886          {
2887             struct chunk *chunk = file->chunk;
2888
2889             if (chunk->chunk_length != 13)
2890                stop_invalid(file, "IHDR length");
2891
2892             /* Read all the IHDR information and validate it. */
2893             setpos(chunk);
2894             file->width = reread_4(file);
2895             file->height = reread_4(file);
2896             file->bit_depth = reread_byte(file);
2897             file->color_type = reread_byte(file);
2898             file->compression_method = reread_byte(file);
2899             file->filter_method = reread_byte(file);
2900             file->interlace_method = reread_byte(file);
2901
2902             /* This validates all the fields, and calls stop_invalid if
2903              * there is a problem.
2904              */
2905             calc_image_size(file);
2906          }
2907          return;
2908
2909          /* Ancillary chunks that require further processing: */
2910       case png_zTXt: case png_iCCP:
2911          if (process_zTXt_iCCP(file))
2912             return;
2913          chunk_end(&file->chunk);
2914          file_setpos(file, &file->data_pos);
2915          break;
2916
2917       case png_iTXt:
2918          if (process_iTXt(file))
2919             return;
2920          chunk_end(&file->chunk);
2921          file_setpos(file, &file->data_pos);
2922          break;
2923
2924       case png_IDAT:
2925          if (process_IDAT(file))
2926             return;
2927          /* First pass: */
2928          assert(next_type == png_IDAT);
2929          break;
2930    }
2931
2932    /* Control reaches this point if the chunk must be skipped.  For chunks other
2933     * than IDAT this means that the zlib compressed data is fatally damanged and
2934     * the chunk will not be passed to libpng.  For IDAT it means that the end of
2935     * the IDAT stream has not yet been reached and we must handle the next
2936     * (IDAT) chunk.  If the LZ data in an IDAT stream cannot be read 'stop' must
2937     * be used to halt parsing of the PNG.
2938     */
2939    read_chunk(file);
2940    return;
2941
2942    /* This is the generic code to skip the current chunk; simply jump to the
2943     * next one.
2944     */
2945 skip_chunk:
2946    file->length = next_length;
2947    file->type = next_type;
2948    getpos(file);
2949    read_chunk(file);
2950 }
2951
2952 static png_uint_32
2953 get32(png_bytep buffer, int offset)
2954    /* Read a 32-bit value from an 8-byte circular buffer (used only below).
2955     */
2956 {
2957    return
2958       (buffer[ offset    & 7] << 24) +
2959       (buffer[(offset+1) & 7] << 16) +
2960       (buffer[(offset+2) & 7] <<  8) +
2961       (buffer[(offset+3) & 7]      );
2962 }
2963
2964 static void
2965 sync_stream(struct file *file)
2966    /* The stream seems to be messed up, attempt to resync from the current chunk
2967     * header.  Executes stop on a fatal error, otherwise calls process_chunk.
2968     */
2969 {
2970    png_uint_32 file_crc;
2971
2972    file->status_code |= STREAM_ERROR;
2973
2974    if (file->global->verbose)
2975    {
2976       fputs(" SYNC ", stderr);
2977       type_name(file->type, stderr);
2978       putc('\n', stderr);
2979    }
2980
2981    /* Return to the start of the chunk data */
2982    file_setpos(file, &file->data_pos);
2983    file->read_count = 8;
2984
2985    if (read_4(file, &file_crc) == 4) /* else completely truncated */
2986    {
2987       /* Ignore the recorded chunk length, proceed through the data looking for
2988        * a leading sequence of bytes that match the CRC in the following four
2989        * bytes.  Each time a match is found check the next 8 bytes for a valid
2990        * length, chunk-type pair.
2991        */
2992       png_uint_32 length;
2993       png_uint_32 type = file->type;
2994       png_uint_32 crc = crc_init_4(type);
2995       png_byte buffer[8];
2996       unsigned int nread = 0, nused = 0;
2997
2998       for (length=0; length <= 0x7fffffff; ++length)
2999       {
3000          int ch;
3001
3002          if ((crc ^ 0xffffffff) == file_crc)
3003          {
3004             /* A match on the CRC; for IEND this is sufficient, but for anything
3005              * else expect a following chunk header.
3006              */
3007             if (type == png_IEND)
3008             {
3009                file->length = length;
3010                process_chunk(file, file_crc, 0, 0);
3011                return;
3012             }
3013
3014             else
3015             {
3016                /* Need 8 bytes */
3017                while (nread < 8+nused)
3018                {
3019                   ch = read_byte(file);
3020                   if (ch == EOF)
3021                      goto truncated;
3022                   buffer[(nread++) & 7] = (png_byte)ch;
3023                }
3024
3025                /* Prevent overflow */
3026                nread -= nused & ~7;
3027                nused -= nused & ~7; /* or, nused &= 7 ;-) */
3028
3029                /* Examine the 8 bytes for a valid chunk header. */
3030                {
3031                   png_uint_32 next_length = get32(buffer, nused);
3032
3033                   if (next_length < 0x7fffffff)
3034                   {
3035                      png_uint_32 next_type = get32(buffer, nused+4);
3036
3037                      if (chunk_type_valid(next_type))
3038                      {
3039                         file->read_count -= 8;
3040                         process_chunk(file, file_crc, next_length, next_type);
3041                         return;
3042                      }
3043                   }
3044
3045                   /* Not valid, keep going. */
3046                }
3047             }
3048          }
3049
3050          /* This catches up with the circular buffer which gets filled above
3051           * while checking a chunk header.  This code is slightly tricky - if
3052           * the chunk_type is IEND the buffer will never be used, if it is not
3053           * the code will always read ahead exactly 8 bytes and pass this on to
3054           * process_chunk.  So the invariant that IEND leaves the file position
3055           * after the IEND CRC and other chunk leave it after the *next* chunk
3056           * header is not broken.
3057           */
3058          if (nread <= nused)
3059          {
3060             ch = read_byte(file);
3061
3062             if (ch == EOF)
3063                goto truncated;
3064          }
3065
3066          else
3067             ch = buffer[(++nused) & 7];
3068
3069          crc = crc_one_byte(crc, file_crc >> 24);
3070          file_crc = (file_crc << 8) + ch;
3071       }
3072
3073       /* Control gets to here if when 0x7fffffff bytes (plus 8) have been read,
3074        * ok, treat this as a damaged stream too:
3075        */
3076    }
3077
3078 truncated:
3079    stop(file, READ_ERROR_CODE, "damaged PNG stream");
3080 }
3081
3082 static void
3083 read_chunk(struct file *file)
3084    /* On entry file::data_pos must be set to the position of the first byte
3085     * of the chunk data *and* the input file must be at this position.  This
3086     * routine (via process_chunk) instantiates a chunk or IDAT control structure
3087     * based on file::length and file::type and also resets these fields and
3088     * file::data_pos for the chunk after this one.  For an IDAT chunk the whole
3089     * stream of IDATs will be read, until something other than an IDAT is
3090     * encountered, and the file fields will be set for the chunk after the end
3091     * of the stream of IDATs.
3092     *
3093     * For IEND the file::type field will be set to 0, and nothing beyond the end
3094     * of the IEND chunk will have been read.
3095     */
3096 {
3097    png_uint_32 length = file->length;
3098    png_uint_32 type = file->type;
3099
3100    /* After IEND file::type is set to 0, if libpng attempts to read
3101     * more data at this point this is a bug in libpng.
3102     */
3103    if (type == 0)
3104       stop(file, UNEXPECTED_ERROR_CODE, "read beyond IEND");
3105
3106    if (file->global->verbose > 2)
3107    {
3108       fputs("   ", stderr);
3109       type_name(type, stderr);
3110       fprintf(stderr, " %lu\n", (unsigned long)length);
3111    }
3112
3113    /* Start the read_crc calculation with the chunk type, then read to the end
3114     * of the chunk data (without processing it in any way) to check that it is
3115     * all there and calculate the CRC.
3116     */
3117    file->crc = crc_init_4(type);
3118    if (crc_read_many(file, length)) /* else it was truncated */
3119    {
3120       png_uint_32 file_crc; /* CRC read from file */
3121       unsigned int nread = read_4(file, &file_crc);
3122
3123       if (nread == 4)
3124       {
3125          if (type != png_IEND) /* do not read beyond IEND */
3126          {
3127             png_uint_32 next_length;
3128
3129             nread += read_4(file, &next_length);
3130             if (nread == 8 && next_length <= 0x7fffffff)
3131             {
3132                png_uint_32 next_type;
3133
3134                nread += read_4(file, &next_type);
3135
3136                if (nread == 12 && chunk_type_valid(next_type))
3137                {
3138                   /* Adjust the read count back to the correct value for this
3139                    * chunk.
3140                    */
3141                   file->read_count -= 8;
3142                   process_chunk(file, file_crc, next_length, next_type);
3143                   return;
3144                }
3145             }
3146          }
3147
3148          else /* IEND */
3149          {
3150             process_chunk(file, file_crc, 0, 0);
3151             return;
3152          }
3153       }
3154    }
3155
3156    /* Control gets to here if the the stream seems invalid or damaged in some
3157     * way.  Either there was a problem reading all the expected data (this
3158     * chunk's data, its CRC and the length and type of the next chunk) or the
3159     * next chunk length/type are invalid.  Notice that the cases that end up
3160     * here all correspond to cases that would otherwise terminate the read of
3161     * the PNG file.
3162     */
3163    sync_stream(file);
3164 }
3165
3166 /* This returns a file* from a png_struct in an implementation specific way. */
3167 static struct file *get_control(png_const_structrp png_ptr);
3168
3169 static void PNGCBAPI
3170 error_handler(png_structp png_ptr, png_const_charp message)
3171 {
3172    stop(get_control(png_ptr),  LIBPNG_ERROR_CODE, message);
3173 }
3174
3175 static void PNGCBAPI
3176 warning_handler(png_structp png_ptr, png_const_charp message)
3177 {
3178    struct file *file = get_control(png_ptr);
3179
3180    if (file->global->warnings)
3181       emit_error(file, LIBPNG_WARNING_CODE, message);
3182 }
3183
3184 /* Read callback - this is where the work gets done to check the stream before
3185  * passing it to libpng
3186  */
3187 static void PNGCBAPI
3188 read_callback(png_structp png_ptr, png_bytep buffer, size_t count)
3189    /* Return 'count' bytes to libpng in 'buffer' */
3190 {
3191    struct file *file = get_control(png_ptr);
3192    png_uint_32 type, length; /* For the chunk be *WRITTEN* */
3193    struct chunk *chunk;
3194
3195    /* libpng should always ask for at least one byte */
3196    if (count == 0)
3197       stop(file, UNEXPECTED_ERROR_CODE, "read callback for 0 bytes");
3198
3199    /* The callback always reads ahead by 8 bytes - the signature or chunk header
3200     * - these bytes are stored in chunk_length and chunk_type.  This block is
3201     * executed once for the signature and once for the first chunk right at the
3202     * start.
3203     */
3204    if (file->read_count < 8)
3205    {
3206       assert(file->read_count == 0);
3207       assert((file->status_code & TRUNCATED) == 0);
3208
3209       (void)read_4(file, &file->length);
3210
3211       if (file->read_count == 4)
3212          (void)read_4(file, &file->type);
3213
3214       if (file->read_count < 8)
3215       {
3216          assert((file->status_code & TRUNCATED) != 0);
3217          stop(file, READ_ERROR_CODE, "not a PNG (too short)");
3218       }
3219
3220       if (file->state == STATE_SIGNATURE)
3221       {
3222          if (file->length != sig1 || file->type != sig2)
3223             stop(file, LIBPNG_ERROR_CODE, "not a PNG (signature)");
3224
3225          /* Else write it (this is the initialization of write_count, prior to
3226           * this it contains CLEAR garbage.)
3227           */
3228          file->write_count = 0;
3229       }
3230
3231       else
3232       {
3233          assert(file->state == STATE_CHUNKS);
3234
3235          /* The first chunk must be a well formed IHDR (this could be relaxed to
3236           * use the checks in process_chunk, but that seems unnecessary.)
3237           */
3238          if (file->length != 13 || file->type != png_IHDR)
3239             stop(file, LIBPNG_ERROR_CODE, "not a PNG (IHDR)");
3240
3241          /* The position of the data must be stored too */
3242          getpos(file);
3243       }
3244    }
3245
3246    /* Retrieve previous state (because the read callbacks are made pretty much
3247     * byte-by-byte in the sequential reader prior to 1.7).
3248     */
3249    chunk = file->chunk;
3250
3251    if (chunk != NULL)
3252    {
3253       length = chunk->chunk_length;
3254       type = chunk->chunk_type;
3255    }
3256
3257    else
3258    {
3259       /* This is the signature case; for IDAT and other chunks these values will
3260        * be overwritten when read_chunk is called below.
3261        */
3262       length = file->length;
3263       type = file->type;
3264    }
3265
3266    do
3267    {
3268       png_uint_32 b;
3269
3270       /* Complete the read of a chunk; as a side effect this also instantiates
3271        * a chunk control structure and sets the file length/type/data_pos fields
3272        * for the *NEXT* chunk header.
3273        *
3274        * NOTE: at an IDAT any following IDAT chunks will also be read and the
3275        * next_ fields will refer to the chunk after the last IDAT.
3276        *
3277        * NOTE: read_chunk only returns when it has read a chunk that must now be
3278        * written.
3279        */
3280       if (file->state != STATE_SIGNATURE && chunk == NULL)
3281       {
3282          assert(file->read_count == 8);
3283          assert(file->idat == NULL);
3284          read_chunk(file);
3285          chunk = file->chunk;
3286          assert(chunk != NULL);
3287
3288          /* Do the initialization that was not done before. */
3289          length = chunk->chunk_length;
3290          type = chunk->chunk_type;
3291
3292          /* And start writing the new chunk. */
3293          file->write_count = 0;
3294       }
3295
3296       /* The chunk_ fields describe a chunk that must be written, or hold the
3297        * signature.  Write the header first.  In the signature case this
3298        * rewrites the signature.
3299        */
3300       switch (file->write_count)
3301       {
3302          case 0: b = length >> 24; break;
3303          case 1: b = length >> 16; break;
3304          case 2: b = length >>  8; break;
3305          case 3: b = length      ; break;
3306
3307          case 4: b = type >> 24; break;
3308          case 5: b = type >> 16; break;
3309          case 6: b = type >>  8; break;
3310          case 7: b = type      ; break;
3311
3312          case 8:
3313             /* The header has been written.  If this is really the signature
3314              * that's all that is required and we can go to normal chunk
3315              * processing.
3316              */
3317             if (file->state == STATE_SIGNATURE)
3318             {
3319                /* The signature has been written, the tail call to read_callback
3320                 * below (it's just a goto to the start with a decent compiler)
3321                 * will read the IHDR header ahead and validate it.
3322                 */
3323                assert(length == sig1 && type == sig2);
3324                file->read_count = 0; /* Forces a header read */
3325                file->state = STATE_CHUNKS; /* IHDR: checked above */
3326                read_callback(png_ptr, buffer, count);
3327                return;
3328             }
3329
3330             else
3331             {
3332                assert(chunk != NULL);
3333
3334                /* Set up for write, notice that repositioning the input stream
3335                 * is only necessary if something is to be read from it.  Also
3336                 * notice that for the IDAT stream this must only happen once -
3337                 * on the first IDAT - to get back to the start of the list and
3338                 * this is done inside process_IDAT:
3339                 */
3340                chunk->write_crc = crc_init_4(type);
3341                if (file->state != STATE_IDAT && length > 0)
3342                   setpos(chunk);
3343             }
3344             /* FALL THROUGH */
3345
3346          default:
3347             assert(chunk != NULL);
3348
3349             /* NOTE: the arithmetic below overflows and gives a large positive
3350              * png_uint_32 value until the whole chunk data has been written.
3351              */
3352             switch (file->write_count - length)
3353             {
3354                /* Write the chunk data, normally this just comes from
3355                 * the file.  The only exception is for that part of a
3356                 * chunk which is zlib data and which must be rewritten,
3357                 * and IDAT chunks which can be completely
3358                 * reconstructed.
3359                 */
3360                default:
3361                   if (file->state == STATE_IDAT)
3362                   {
3363                      struct IDAT *idat = file->idat;
3364
3365                      assert(idat != NULL);
3366
3367                      /* Read an IDAT byte from the input stream of IDAT chunks.
3368                       * Because the IDAT stream can be re-chunked this stream is
3369                       * held in the struct IDAT members.  The chunk members, in
3370                       * particular chunk_length (and therefore the length local)
3371                       * refer to the output chunk.
3372                       */
3373                      while (idat->idat_index >= idat->idat_length)
3374                      {
3375                         /* Advance one chunk */
3376                         struct IDAT_list *cur = idat->idat_cur;
3377
3378                         assert(idat->idat_index == idat->idat_length);
3379                         assert(cur != NULL && cur->count > 0);
3380
3381                         /* NOTE: IDAT_list::count here, not IDAT_list::length */
3382                         if (++(idat->idat_count) >= cur->count)
3383                         {
3384                            assert(idat->idat_count == cur->count);
3385
3386                            /* Move on to the next IDAT_list: */
3387                            cur = cur->next;
3388
3389                            /* This is an internal error - read beyond the end of
3390                             * the pre-calculated stream.
3391                             */
3392                            if (cur == NULL || cur->count == 0)
3393                               stop(file, UNEXPECTED_ERROR_CODE,
3394                                  "read beyond end of IDAT");
3395
3396                            idat->idat_count = 0;
3397                            idat->idat_cur = cur;
3398                         }
3399
3400                         idat->idat_index = 0;
3401                         /* Zero length IDAT chunks are permitted, so the length
3402                          * here may be 0.
3403                          */
3404                         idat->idat_length = cur->lengths[idat->idat_count];
3405
3406                         /* And skip 12 bytes to the next chunk data */
3407                         skip_12(file);
3408                      }
3409
3410                      /* The index is always that of the next byte, the rest of
3411                       * the information is always the current IDAT chunk and the
3412                       * current list.
3413                       */
3414                      ++(idat->idat_index);
3415                   }
3416
3417                   /* Read the byte from the stream. */
3418                   b = reread_byte(file);
3419
3420                   /* If the byte must be rewritten handle that here */
3421                   if (chunk->rewrite_length > 0)
3422                   {
3423                      if (chunk->rewrite_offset > 0)
3424                         --(chunk->rewrite_offset);
3425
3426                      else
3427                      {
3428                         b = chunk->rewrite_buffer[0];
3429                         memmove(chunk->rewrite_buffer, chunk->rewrite_buffer+1,
3430                            (sizeof chunk->rewrite_buffer)-
3431                               (sizeof chunk->rewrite_buffer[0]));
3432
3433                         --(chunk->rewrite_length);
3434                      }
3435                   }
3436
3437                   chunk->write_crc = crc_one_byte(chunk->write_crc, b);
3438                   break;
3439
3440                /* The CRC is written at:
3441                 *
3442                 *    chunk_write == chunk_length+8..chunk_length+11
3443                 *
3444                 * so 8 to 11.  The CRC is not (yet) conditioned.
3445                 */
3446                case  8: b = chunk->write_crc >> 24; goto write_crc;
3447                case  9: b = chunk->write_crc >> 16; goto write_crc;
3448                case 10: b = chunk->write_crc >>  8; goto write_crc;
3449                case 11:
3450                   /* This must happen before the chunk_end below: */
3451                   b = chunk->write_crc;
3452
3453                   if (file->global->verbose > 2)
3454                   {
3455                      fputs("   ", stderr);
3456                      type_name(type, stderr);
3457                      fprintf(stderr, " %lu 0x%.8x\n", (unsigned long)length,
3458                         chunk->write_crc ^ 0xffffffff);
3459                   }
3460
3461                   /* The IDAT stream is written without a call to read_chunk
3462                    * until the end is reached.  rechunk_length() calculates the
3463                    * length of the output chunks.  Control gets to this point at
3464                    * the end of an *output* chunk - the length calculated by
3465                    * rechunk_length.  If this corresponds to the end of the
3466                    * input stream stop writing IDAT chunks, otherwise continue.
3467                    */
3468                   if (file->state == STATE_IDAT &&
3469                      (file->idat->idat_index < file->idat->idat_length ||
3470                       1+file->idat->idat_count < file->idat->idat_cur->count ||
3471                       file->idat->idat_cur != file->idat->idat_list_tail))
3472                   {
3473                      /* Write another IDAT chunk.  Call rechunk_length to
3474                       * calculate the length required.
3475                       */
3476                      length = chunk->chunk_length = rechunk_length(file->idat);
3477                      assert(type == png_IDAT);
3478                      file->write_count = 0; /* for the new chunk */
3479                      --(file->write_count); /* fake out the increment below */
3480                   }
3481
3482                   else
3483                   {
3484                      /* Entered at the end of a non-IDAT chunk and at the end of
3485                       * the IDAT stream.  The rewrite should have been cleared.
3486                       */
3487                      if (chunk->rewrite_length > 0 || chunk->rewrite_offset > 0)
3488                         stop(file, UNEXPECTED_ERROR_CODE, "pending rewrite");
3489
3490                      /* This is the last byte so reset chunk_read for the next
3491                       * chunk and move the input file to the position after the
3492                       * *next* chunk header if required.
3493                       */
3494                      file->read_count = 8;
3495                      file_setpos(file, &file->data_pos);
3496
3497                      if (file->idat == NULL)
3498                         chunk_end(&file->chunk);
3499
3500                      else
3501                         IDAT_end(&file->idat);
3502                   }
3503
3504                write_crc:
3505                   b ^= 0xff; /* conditioning */
3506                   break;
3507             }
3508             break;
3509       }
3510
3511       /* Write one byte */
3512       b &= 0xff;
3513       *buffer++ = (png_byte)b;
3514       --count;
3515       write_byte(file, (png_byte)b); /* increments chunk_write */
3516    }
3517    while (count > 0);
3518 }
3519
3520 /* Bundle the file and an uninitialized chunk and IDAT control structure
3521  * together to allow implementation of the chunk/IDAT allocate routine.
3522  */
3523 struct control
3524 {
3525    struct file  file;
3526    struct chunk chunk;
3527    struct IDAT  idat;
3528 };
3529
3530 static int
3531 control_end(struct control *control)
3532 {
3533    return file_end(&control->file);
3534 }
3535
3536 static struct file *
3537 get_control(png_const_structrp png_ptr)
3538 {
3539    /* This just returns the (file*).  The chunk and idat control structures
3540     * don't always exist.
3541     */
3542    struct control *control = voidcast(struct control*,
3543       png_get_error_ptr(png_ptr));
3544    return &control->file;
3545 }
3546
3547 static void
3548 allocate(struct file *file, int allocate_idat)
3549 {
3550    struct control *control = voidcast(struct control*, file->alloc_ptr);
3551
3552    if (allocate_idat)
3553    {
3554       assert(file->idat == NULL);
3555       IDAT_init(&control->idat, file);
3556    }
3557
3558    else /* chunk */
3559    {
3560       assert(file->chunk == NULL);
3561       chunk_init(&control->chunk, file);
3562    }
3563 }
3564
3565 static int
3566 control_init(struct control *control, struct global *global,
3567    const char *file_name, const char *out_name)
3568    /* This wraps file_init(&control::file) and simply returns the result from
3569     * file_init.
3570     */
3571 {
3572    return file_init(&control->file, global, file_name, out_name, control,
3573       allocate);
3574 }
3575
3576 static int
3577 read_png(struct control *control)
3578    /* Read a PNG, return 0 on success else an error (status) code; a bit mask as
3579     * defined for file::status_code as above.
3580     */
3581 {
3582    png_structp png_ptr;
3583    png_infop info_ptr = NULL;
3584    volatile int rc;
3585
3586    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, control,
3587       error_handler, warning_handler);
3588
3589    if (png_ptr == NULL)
3590    {
3591       /* This is not really expected. */
3592       log_error(&control->file, LIBPNG_ERROR_CODE, "OOM allocating png_struct");
3593       control->file.status_code |= INTERNAL_ERROR;
3594       return LIBPNG_ERROR_CODE;
3595    }
3596
3597    rc = setjmp(control->file.jmpbuf);
3598    if (rc == 0)
3599    {
3600 #     ifdef PNG_SET_USER_LIMITS_SUPPORTED
3601          /* Remove any limits on the size of PNG files that can be read,
3602           * without this we may reject files based on built-in safety
3603           * limits.
3604           */
3605          png_set_user_limits(png_ptr, 0x7fffffff, 0x7fffffff);
3606          png_set_chunk_cache_max(png_ptr, 0);
3607          png_set_chunk_malloc_max(png_ptr, 0);
3608 #     endif
3609
3610       png_set_read_fn(png_ptr, control, read_callback);
3611
3612       info_ptr = png_create_info_struct(png_ptr);
3613       if (info_ptr == NULL)
3614          png_error(png_ptr, "OOM allocating info structure");
3615
3616       if (control->file.global->verbose)
3617          fprintf(stderr, " INFO\n");
3618
3619       png_read_info(png_ptr, info_ptr);
3620
3621       {
3622         png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
3623         int passes = png_set_interlace_handling(png_ptr);
3624         int pass;
3625
3626         png_start_read_image(png_ptr);
3627
3628         for (pass = 0; pass < passes; ++pass)
3629         {
3630            png_uint_32 y = height;
3631
3632            /* NOTE: this skips asking libpng to return either version of
3633             * the image row, but libpng still reads the rows.
3634             */
3635            while (y-- > 0)
3636               png_read_row(png_ptr, NULL, NULL);
3637         }
3638       }
3639
3640       if (control->file.global->verbose)
3641          fprintf(stderr, " END\n");
3642
3643       /* Make sure to read to the end of the file: */
3644       png_read_end(png_ptr, info_ptr);
3645    }
3646
3647    png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
3648    return rc;
3649 }
3650
3651 static int
3652 one_file(struct global *global, const char *file_name, const char *out_name)
3653 {
3654    int rc;
3655    struct control control;
3656
3657    if (global->verbose)
3658       fprintf(stderr, "FILE %s -> %s\n", file_name,
3659          out_name ? out_name : "<none>");
3660
3661    /* Although control_init can return a failure code the structure is always
3662     * initialized, so control_end can be used to accumulate any status codes.
3663     */
3664    rc = control_init(&control, global, file_name, out_name);
3665
3666    if (rc == 0)
3667       rc = read_png(&control);
3668
3669    rc |= control_end(&control);
3670
3671    return rc;
3672 }
3673
3674 static void
3675 usage(const char *prog)
3676 {
3677    /* ANSI C-90 limits strings to 509 characters, so use a string array: */
3678    size_t i;
3679    static const char *usage_string[] = {
3680 "  Tests, optimizes and optionally fixes the zlib header in PNG files.",
3681 "  Optionally, when fixing, strips ancilliary chunks from the file.",
3682 0,
3683 "OPTIONS",
3684 "  OPERATION",
3685 "      By default files are just checked for readability with a summary of the",
3686 "      of zlib issues founds for each compressed chunk and the IDAT stream in",
3687 "      the file.",
3688 "    --optimize (-o):",
3689 "      Find the smallest deflate window size for the compressed data.",
3690 "    --strip=[none|crc|unsafe|unused|transform|color|all]:",
3691 "        none (default):   Retain all chunks.",
3692 "        crc:    Remove chunks with a bad CRC.",
3693 "        unsafe: Remove chunks that may be unsafe to retain if the image data",
3694 "                is modified.  This is set automatically if --max is given but",
3695 "                may be cancelled by a later --strip=none.",
3696 "        unused: Remove chunks not used by libpng when decoding an image.",
3697 "                This retains any chunks that might be used by libpng image",
3698 "                transformations.",
3699 "        transform: unused+bKGD.",
3700 "        color:  transform+iCCP and cHRM.",
3701 "        all:    color+gAMA and sRGB.",
3702 "      Only ancillary chunks are ever removed.  In addition the tRNS and sBIT",
3703 "      chunks are never removed as they affect exact interpretation of the",
3704 "      image pixel values.  The following known chunks are treated specially",
3705 "      by the above options:",
3706 "        gAMA, sRGB [all]: These specify the gamma encoding used for the pixel",
3707 "            values.",
3708 "        cHRM, iCCP [color]: These specify how colors are encoded.  iCCP also",
3709 "            specifies the exact encoding of a pixel value; however, in",
3710 "            practice most programs will ignore it.",
3711 "        bKGD [transform]: This is used by libpng transforms."
3712 "    --max=<number>:",
3713 "      Use IDAT chunks sized <number>.  If no number is given the the IDAT",
3714 "      chunks will be the maximum size permitted; 2^31-1 bytes.  If the option",
3715 "      is omitted the original chunk sizes will not be changed.  When the",
3716 "      option is given --strip=unsafe is set automatically. This may be",
3717 "      cancelled if you know that all unknown unsafe-to-copy chunks really are",
3718 "      safe to copy across an IDAT size change.  This is true of all chunks",
3719 "      that have ever been formally proposed as PNG extensions.",
3720 "  MESSAGES",
3721 "      By default the program only outputs summaries for each file.",
3722 "    --quiet (-q):",
3723 "      Do not output the summaries except for files that cannot be read. With",
3724 "      two --quiets these are not output either.",
3725 "    --errors (-e):",
3726 "      Output errors from libpng and the program (except too-far-back).",
3727 "    --warnings (-w):",
3728 "      Output warnings from libpng.",
3729 "  OUTPUT",
3730 "      By default nothing is written.",
3731 "    --out=<file>:",
3732 "      Write the optimized/corrected version of the next PNG to <file>.  This",
3733 "      overrides the following two options",
3734 "    --suffix=<suffix>:",
3735 "      Set --out=<name><suffix> for all following files unless overridden on",
3736 "      a per-file basis by explicit --out.",
3737 "    --prefix=<prefix>:",
3738 "      Set --out=<prefix><name> for all the following files unless overridden",
3739 "      on a per-file basis by explicit --out.",
3740 "      These two options can be used together to produce a suffix and prefix.",
3741 "  INTERNAL OPTIONS",
3742 #if 0 /*NYI*/
3743 #ifdef PNG_MAXIMUM_INFLATE_WINDOW
3744 "    --test:",
3745 "      Test the PNG_MAXIMUM_INFLATE_WINDOW option.  Setting this disables",
3746 "      output as this would produce a broken file.",
3747 #endif
3748 #endif
3749 0,
3750 "EXIT CODES",
3751 "  *** SUBJECT TO CHANGE ***",
3752 "  The program exit code is value in the range 0..127 holding a bit mask of",
3753 "  the following codes.  Notice that the results for each file are combined",
3754 "  together - check one file at a time to get a meaningful error code!",
3755 "    0x01: The zlib too-far-back error existed in at least one chunk.",
3756 "    0x02: At least one chunk had a CRC error.",
3757 "    0x04: A chunk length was incorrect.",
3758 "    0x08: The file was truncated.",
3759 "  Errors less than 16 are potentially recoverable, for a single file if the",
3760 "  exit code is less than 16 the file could be read (with corrections if a",
3761 "  non-zero code is returned).",
3762 "    0x10: The file could not be read, even with corrections.",
3763 "    0x20: The output file could not be written.",
3764 "    0x40: An unexpected, potentially internal, error occurred.",
3765 "  If the command line arguments are incorrect the program exits with exit",
3766 "  255.  Some older operating systems only support 7-bit exit codes, on those",
3767 "  systems it is suggested that this program is first tested by supplying",
3768 "  invalid arguments.",
3769 0,
3770 "DESCRIPTION",
3771 "  " PROGRAM_NAME ":",
3772 "  checks each PNG file on the command line for errors.  By default errors are",
3773 "  not output and the program just returns an exit code and prints a summary.",
3774 "  With the --quiet (-q) option the summaries are suppressed too and the",
3775 "  program only outputs unexpected errors (internal errors and file open",
3776 "  errors).",
3777 "  Various known problems in PNG files are fixed while the file is being read",
3778 "  The exit code says what problems were fixed.  In particular the zlib error:",
3779 0,
3780 "        \"invalid distance too far back\"",
3781 0,
3782 "  caused by an incorrect optimization of a zlib stream is fixed in any",
3783 "  compressed chunk in which it is encountered.  An integrity problem of the",
3784 "  PNG stream caused by a bug in libpng which wrote an incorrect chunk length",
3785 "  is also fixed.  Chunk CRC errors are automatically fixed up.",
3786 0,
3787 "  Setting one of the \"OUTPUT\" options causes the possibly modified file to",
3788 "  be written to a new file.",
3789 0,
3790 "  Notice that some PNG files with the zlib optimization problem can still be",
3791 "  read by libpng under some circumstances.  This program will still detect",
3792 "  and, if requested, correct the error.",
3793 0,
3794 "  The program will reliably process all files on the command line unless",
3795 "  either an invalid argument causes the usage message (this message) to be",
3796 "  produced or the program crashes.",
3797 0,
3798 "  The summary lines describe issues encountered with the zlib compressed",
3799 "  stream of a chunk.  They have the following format, which is SUBJECT TO",
3800 "  CHANGE in the future:",
3801 0,
3802 "     chunk reason comp-level p1 p2 p3 p4 file",
3803 0,
3804 "  p1 through p4 vary according to the 'reason'.  There are always 8 space",
3805 "  separated fields.  Reasons specific formats are:",
3806 0,
3807 "     chunk ERR status code read-errno write-errno message file",
3808 "     chunk SKP comp-level file-bits zlib-rc compressed message file",
3809 "     chunk ??? comp-level file-bits ok-bits compressed uncompress file",
3810 0,
3811 "  The various fields are",
3812 0,
3813 "$1 chunk:      The chunk type of a chunk in the file or 'HEAD' if a problem",
3814 "               is reported by libpng at the start of the IDAT stream.",
3815 "$2 reason:     One of:",
3816 "          CHK: A zlib header checksum was detected and fixed.",
3817 "          TFB: The zlib too far back error was detected and fixed.",
3818 "          OK : No errors were detected in the zlib stream and optimization",
3819 "               was not requested, or was not possible.",
3820 "          OPT: The zlib stream window bits value could be improved (and was).",
3821 "          SKP: The chunk was skipped because of a zlib issue (zlib-rc) with",
3822 "               explanation 'message'",
3823 "          ERR: The read of the file was aborted.  The parameters explain why.",
3824 "$3 status:     For 'ERR' the accumulated status code from 'EXIT CODES' above.",
3825 "               This is printed as a 2 digit hexadecimal value",
3826 "   comp-level: The recorded compression level (FLEVEL) of a zlib stream",
3827 "               expressed as a string {supfast,stdfast,default,maximum}",
3828 "$4 code:       The file exit code; where stop was called, as a fairly terse",
3829 "               string {warning,libpng,zlib,invalid,read,write,unexpected}.",
3830 "   file-bits:  The zlib window bits recorded in the file.",
3831 "$5 read-errno: A system errno value from a read translated by strerror(3).",
3832 "   zlib-rc:    A zlib return code as a string (see zlib.h).",
3833 "   ok-bits:    The smallest zlib window bits value that works.",
3834 "$6 write-errno:A system errno value from a write translated by strerror(3).",
3835 "   compressed: The count of compressed bytes in the zlib stream, when the",
3836 "               reason is 'SKP'; this is a count of the bytes read from the",
3837 "               stream when the fatal error was encountered.",
3838 "$7 message:    An error message (spaces replaced by _, as in all parameters),",
3839 "   uncompress: The count of bytes from uncompressing the zlib stream; this",
3840 "               may not be the same as the number of bytes in the image.",
3841 "$8 file:       The name of the file (this may contain spaces).",
3842 };
3843
3844    fprintf(stderr, "Usage: %s {[options] png-file}\n", prog);
3845
3846    for (i=0; i < (sizeof usage_string)/(sizeof usage_string[0]); ++i)
3847    {
3848       if (usage_string[i] != 0)
3849          fputs(usage_string[i], stderr);
3850
3851       fputc('\n', stderr);
3852    }
3853
3854    exit(255);
3855 }
3856
3857 int
3858 main(int argc, const char **argv)
3859 {
3860    char temp_name[FILENAME_MAX+1];
3861    const char *  prog = *argv;
3862    const char *  outfile = NULL;
3863    const char *  suffix = NULL;
3864    const char *  prefix = NULL;
3865    int           done = 0; /* if at least one file is processed */
3866    struct global global;
3867
3868    global_init(&global);
3869
3870    while (--argc > 0)
3871    {
3872       ++argv;
3873
3874       if (strcmp(*argv, "--debug") == 0)
3875       {
3876          /* To help debugging problems: */
3877          global.errors = global.warnings = 1;
3878          global.quiet = 0;
3879          global.verbose = 7;
3880       }
3881
3882       else if (strncmp(*argv, "--max=", 6) == 0)
3883       {
3884          global.idat_max = (png_uint_32)atol(6+*argv);
3885
3886          if (global.skip < SKIP_UNSAFE)
3887             global.skip = SKIP_UNSAFE;
3888       }
3889
3890       else if (strcmp(*argv, "--max") == 0)
3891       {
3892          global.idat_max = 0x7fffffff;
3893
3894          if (global.skip < SKIP_UNSAFE)
3895             global.skip = SKIP_UNSAFE;
3896       }
3897
3898       else if (strcmp(*argv, "--optimize") == 0 || strcmp(*argv, "-o") == 0)
3899          global.optimize_zlib = 1;
3900
3901       else if (strncmp(*argv, "--out=", 6) == 0)
3902          outfile = 6+*argv;
3903
3904       else if (strncmp(*argv, "--suffix=", 9) == 0)
3905          suffix = 9+*argv;
3906
3907       else if (strncmp(*argv, "--prefix=", 9) == 0)
3908          prefix = 9+*argv;
3909
3910       else if (strcmp(*argv, "--strip=none") == 0)
3911          global.skip = SKIP_NONE;
3912
3913       else if (strcmp(*argv, "--strip=crc") == 0)
3914          global.skip = SKIP_BAD_CRC;
3915
3916       else if (strcmp(*argv, "--strip=unsafe") == 0)
3917          global.skip = SKIP_UNSAFE;
3918
3919       else if (strcmp(*argv, "--strip=unused") == 0)
3920          global.skip = SKIP_UNUSED;
3921
3922       else if (strcmp(*argv, "--strip=transform") == 0)
3923          global.skip = SKIP_TRANSFORM;
3924
3925       else if (strcmp(*argv, "--strip=color") == 0)
3926          global.skip = SKIP_COLOR;
3927
3928       else if (strcmp(*argv, "--strip=all") == 0)
3929          global.skip = SKIP_ALL;
3930
3931       else if (strcmp(*argv, "--errors") == 0 || strcmp(*argv, "-e") == 0)
3932          global.errors = 1;
3933
3934       else if (strcmp(*argv, "--warnings") == 0 || strcmp(*argv, "-w") == 0)
3935          global.warnings = 1;
3936
3937       else if (strcmp(*argv, "--quiet") == 0 || strcmp(*argv, "-q") == 0)
3938       {
3939          if (global.quiet)
3940             global.quiet = 2;
3941
3942          else
3943             global.quiet = 1;
3944       }
3945
3946       else if (strcmp(*argv, "--verbose") == 0 || strcmp(*argv, "-v") == 0)
3947          ++global.verbose;
3948
3949 #if 0
3950       /* NYI */
3951 #     ifdef PNG_MAXIMUM_INFLATE_WINDOW
3952          else if (strcmp(*argv, "--test") == 0)
3953             ++set_option;
3954 #     endif
3955 #endif
3956
3957       else if ((*argv)[0] == '-')
3958          usage(prog);
3959
3960       else
3961       {
3962          size_t outlen = strlen(*argv);
3963
3964          if (outfile == NULL) /* else this takes precedence */
3965          {
3966             /* Consider the prefix/suffix options */
3967             if (prefix != NULL)
3968             {
3969                size_t prefixlen = strlen(prefix);
3970
3971                if (prefixlen+outlen > FILENAME_MAX)
3972                {
3973                   fprintf(stderr, "%s: output file name too long: %s%s%s\n",
3974                      prog, prefix, *argv, suffix ? suffix : "");
3975                   global.status_code |= WRITE_ERROR;
3976                   continue;
3977                }
3978
3979                memcpy(temp_name, prefix, prefixlen);
3980                memcpy(temp_name+prefixlen, *argv, outlen);
3981                outlen += prefixlen;
3982                outfile = temp_name;
3983             }
3984
3985             else if (suffix != NULL)
3986                memcpy(temp_name, *argv, outlen);
3987
3988             temp_name[outlen] = 0;
3989
3990             if (suffix != NULL)
3991             {
3992                size_t suffixlen = strlen(suffix);
3993
3994                if (outlen+suffixlen > FILENAME_MAX)
3995                {
3996                   fprintf(stderr, "%s: output file name too long: %s%s\n",
3997                      prog, *argv, suffix);
3998                   global.status_code |= WRITE_ERROR;
3999                   continue;
4000                }
4001
4002                memcpy(temp_name+outlen, suffix, suffixlen);
4003                outlen += suffixlen;
4004                temp_name[outlen] = 0;
4005                outfile = temp_name;
4006             }
4007          }
4008
4009          (void)one_file(&global, *argv, outfile);
4010          ++done;
4011          outfile = NULL;
4012       }
4013    }
4014
4015    if (!done)
4016       usage(prog);
4017
4018    return global_end(&global);
4019 }
4020
4021 #else /* ZLIB_VERNUM < 0x1240 */
4022 int
4023 main(void)
4024 {
4025    fprintf(stderr,
4026       "pngfix needs libpng with a zlib >=1.2.4 (not 0x%x)\n",
4027       ZLIB_VERNUM);
4028    return 77;
4029 }
4030 #endif /* ZLIB_VERNUM */
4031
4032 #else /* No read support */
4033
4034 int
4035 main(void)
4036 {
4037    fprintf(stderr, "pngfix does not work without read deinterlace support\n");
4038    return 77;
4039 }
4040 #endif /* PNG_READ_SUPPORTED && PNG_EASY_ACCESS_SUPPORTED */
4041 #else /* No setjmp support */
4042 int
4043 main(void)
4044 {
4045    fprintf(stderr, "pngfix does not work without setjmp support\n");
4046    return 77;
4047 }
4048 #endif /* PNG_SETJMP_SUPPORTED */
4049