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