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