gzip.c (18002B)
1 /* see LICENSE file for copyright and license details */ 2 3 /* deflate decoder adapted from puff.c, mark adlers rfc 1951 reference 4 * decoder. zlib license: copyright (c) 2002-2013 mark adler, provided 5 * as-is, free to use/alter/redistribute, origin not misrepresented, 6 * this notice kept. see zlib.net */ 7 8 #include <setjmp.h> 9 #include <stdint.h> 10 #include <stdio.h> 11 #include <stdlib.h> 12 #include <string.h> 13 #include <time.h> 14 #include <unistd.h> 15 16 #include "util.h" 17 18 #define MAXBITS 15 19 #define MAXLCODES 286 20 #define MAXDCODES 30 21 #define MAXCODES (MAXLCODES + MAXDCODES) 22 #define FIXLCODES 288 23 24 struct InflateState { 25 unsigned char *out; 26 unsigned long outlen; 27 unsigned long outcnt; 28 29 const unsigned char *in; 30 unsigned long inlen; 31 unsigned long incnt; 32 int bitbuf; 33 int bitcnt; 34 35 jmp_buf env; 36 }; 37 38 struct Huffman { 39 short *count; 40 short *symbol; 41 }; 42 43 static int 44 inflate_bits(struct InflateState *s, int need) 45 { 46 long val; 47 48 val = s->bitbuf; 49 while (s->bitcnt < need) { 50 if (s->incnt == s->inlen) 51 longjmp(s->env, 1); 52 val |= (long)(s->in[s->incnt++]) << s->bitcnt; 53 s->bitcnt += 8; 54 } 55 56 s->bitbuf = (int)(val >> need); 57 s->bitcnt -= need; 58 59 return (int)(val & ((1L << need) - 1)); 60 } 61 62 static int 63 inflate_stored(struct InflateState *s) 64 { 65 unsigned len; 66 67 s->bitbuf = 0; 68 s->bitcnt = 0; 69 70 if (s->incnt + 4 > s->inlen) 71 return 2; 72 len = s->in[s->incnt++]; 73 len |= s->in[s->incnt++] << 8; 74 if (s->in[s->incnt++] != (~len & 0xff) || s->in[s->incnt++] != ((~len >> 8) & 0xff)) 75 return -2; 76 77 if (s->incnt + len > s->inlen) 78 return 2; 79 if (s->out != NULL) { 80 if (s->outcnt + len > s->outlen) 81 return 1; 82 while (len--) 83 s->out[s->outcnt++] = s->in[s->incnt++]; 84 } else { 85 s->outcnt += len; 86 s->incnt += len; 87 } 88 89 return 0; 90 } 91 92 /* codes are bit-reversed on the wire, rebuilt one bit at a time here */ 93 static int 94 inflate_decode(struct InflateState *s, const struct Huffman *h) 95 { 96 int len, code, first, count, index; 97 int bitbuf, left; 98 short *next; 99 100 bitbuf = s->bitbuf; 101 left = s->bitcnt; 102 code = first = index = 0; 103 len = 1; 104 next = h->count + 1; 105 for (;;) { 106 while (left--) { 107 code |= bitbuf & 1; 108 bitbuf >>= 1; 109 count = *next++; 110 if (code - count < first) { 111 s->bitbuf = bitbuf; 112 s->bitcnt = (s->bitcnt - len) & 7; 113 return h->symbol[index + (code - first)]; 114 } 115 index += count; 116 first += count; 117 first <<= 1; 118 code <<= 1; 119 len++; 120 } 121 left = (MAXBITS + 1) - len; 122 if (left == 0) 123 break; 124 if (s->incnt == s->inlen) 125 longjmp(s->env, 1); 126 bitbuf = s->in[s->incnt++]; 127 if (left > 8) 128 left = 8; 129 } 130 return -10; 131 } 132 133 /* 0: complete code, > 0: incomplete but usable, < 0: over-subscribed */ 134 static int 135 huffman_construct(struct Huffman *h, const short *length, int n) 136 { 137 int symbol, len, left; 138 short offs[MAXBITS + 1]; 139 140 for (len = 0; len <= MAXBITS; len++) 141 h->count[len] = 0; 142 for (symbol = 0; symbol < n; symbol++) 143 (h->count[length[symbol]])++; 144 if (h->count[0] == n) 145 return 0; 146 147 left = 1; 148 for (len = 1; len <= MAXBITS; len++) { 149 left <<= 1; 150 left -= h->count[len]; 151 if (left < 0) 152 return left; 153 } 154 155 offs[1] = 0; 156 for (len = 1; len < MAXBITS; len++) 157 offs[len + 1] = offs[len] + h->count[len]; 158 159 for (symbol = 0; symbol < n; symbol++) 160 if (length[symbol] != 0) 161 h->symbol[offs[length[symbol]]++] = symbol; 162 163 return left; 164 } 165 166 static int 167 inflate_codes(struct InflateState *s, const struct Huffman *lencode, const struct Huffman *distcode) 168 { 169 int symbol, len; 170 unsigned dist; 171 static const short lens[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 172 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; 173 static const short lext[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 174 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; 175 static const short dists[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 176 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 177 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; 178 static const short dext[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 179 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; 180 181 do { 182 symbol = inflate_decode(s, lencode); 183 if (symbol < 0) 184 return symbol; 185 if (symbol < 256) { 186 if (s->out != NULL) { 187 if (s->outcnt == s->outlen) 188 return 1; 189 s->out[s->outcnt] = symbol; 190 } 191 s->outcnt++; 192 } else if (symbol > 256) { 193 symbol -= 257; 194 if (symbol >= 29) 195 return -10; 196 len = lens[symbol] + inflate_bits(s, lext[symbol]); 197 198 symbol = inflate_decode(s, distcode); 199 if (symbol < 0) 200 return symbol; 201 dist = dists[symbol] + inflate_bits(s, dext[symbol]); 202 if (dist > s->outcnt) 203 return -11; 204 205 if (s->out != NULL) { 206 if (s->outcnt + len > s->outlen) 207 return 1; 208 while (len--) { 209 s->out[s->outcnt] = s->out[s->outcnt - dist]; 210 s->outcnt++; 211 } 212 } else { 213 s->outcnt += len; 214 } 215 } 216 } while (symbol != 256); 217 218 return 0; 219 } 220 221 static int 222 inflate_fixed(struct InflateState *s) 223 { 224 static int built; 225 static short lencnt[MAXBITS + 1], lensym[FIXLCODES]; 226 static short distcnt[MAXBITS + 1], distsym[MAXDCODES]; 227 static struct Huffman lencode, distcode; 228 229 if (!built) { 230 int symbol; 231 short lengths[FIXLCODES]; 232 233 lencode.count = lencnt; 234 lencode.symbol = lensym; 235 distcode.count = distcnt; 236 distcode.symbol = distsym; 237 238 for (symbol = 0; symbol < 144; symbol++) 239 lengths[symbol] = 8; 240 for (; symbol < 256; symbol++) 241 lengths[symbol] = 9; 242 for (; symbol < 280; symbol++) 243 lengths[symbol] = 7; 244 for (; symbol < FIXLCODES; symbol++) 245 lengths[symbol] = 8; 246 huffman_construct(&lencode, lengths, FIXLCODES); 247 248 for (symbol = 0; symbol < MAXDCODES; symbol++) 249 lengths[symbol] = 5; 250 huffman_construct(&distcode, lengths, MAXDCODES); 251 252 built = 1; 253 } 254 255 return inflate_codes(s, &lencode, &distcode); 256 } 257 258 static int 259 inflate_dynamic(struct InflateState *s) 260 { 261 int nlen, ndist, ncode, index, err; 262 short lengths[MAXCODES]; 263 short lencnt[MAXBITS + 1], lensym[MAXLCODES]; 264 short distcnt[MAXBITS + 1], distsym[MAXDCODES]; 265 struct Huffman lencode, distcode; 266 static const short order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; 267 268 lencode.count = lencnt; 269 lencode.symbol = lensym; 270 distcode.count = distcnt; 271 distcode.symbol = distsym; 272 273 nlen = inflate_bits(s, 5) + 257; 274 ndist = inflate_bits(s, 5) + 1; 275 ncode = inflate_bits(s, 4) + 4; 276 if (nlen > MAXLCODES || ndist > MAXDCODES) 277 return -3; 278 279 for (index = 0; index < ncode; index++) 280 lengths[order[index]] = inflate_bits(s, 3); 281 for (; index < 19; index++) 282 lengths[order[index]] = 0; 283 284 err = huffman_construct(&lencode, lengths, 19); 285 if (err != 0) 286 return -4; 287 288 index = 0; 289 while (index < nlen + ndist) { 290 int symbol, len; 291 292 symbol = inflate_decode(s, &lencode); 293 if (symbol < 0) 294 return symbol; 295 if (symbol < 16) { 296 lengths[index++] = symbol; 297 } else { 298 len = 0; 299 if (symbol == 16) { 300 if (index == 0) 301 return -5; 302 len = lengths[index - 1]; 303 symbol = 3 + inflate_bits(s, 2); 304 } else if (symbol == 17) { 305 symbol = 3 + inflate_bits(s, 3); 306 } else { 307 symbol = 11 + inflate_bits(s, 7); 308 } 309 if (index + symbol > nlen + ndist) 310 return -6; 311 while (symbol--) 312 lengths[index++] = len; 313 } 314 } 315 316 if (lengths[256] == 0) 317 return -9; 318 319 err = huffman_construct(&lencode, lengths, nlen); 320 if (err && (err < 0 || nlen != lencode.count[0] + lencode.count[1])) 321 return -7; 322 323 err = huffman_construct(&distcode, lengths + nlen, ndist); 324 if (err && (err < 0 || ndist != distcode.count[0] + distcode.count[1])) 325 return -8; 326 327 return inflate_codes(s, &lencode, &distcode); 328 } 329 330 /* raw deflate (rfc 1951) decoder; dest null just computes destlen */ 331 static int 332 inflate_raw( 333 unsigned char *dest, 334 unsigned long *destlen, 335 const unsigned char *source, 336 unsigned long *sourcelen 337 ) 338 { 339 struct InflateState s; 340 int last, type, err; 341 342 s.out = dest; 343 s.outlen = *destlen; 344 s.outcnt = 0; 345 346 s.in = source; 347 s.inlen = *sourcelen; 348 s.incnt = 0; 349 s.bitbuf = 0; 350 s.bitcnt = 0; 351 352 if (setjmp(s.env) != 0) { 353 err = 2; 354 } else { 355 do { 356 last = inflate_bits(&s, 1); 357 type = inflate_bits(&s, 2); 358 err = type == 0 ? inflate_stored(&s) 359 : type == 1 ? inflate_fixed(&s) 360 : type == 2 ? inflate_dynamic(&s) 361 : -1; 362 if (err != 0) 363 break; 364 } while (!last); 365 } 366 367 if (err <= 0) { 368 *destlen = s.outcnt; 369 *sourcelen = s.incnt; 370 } 371 return err; 372 } 373 374 static uint32_t crc32_table[256]; 375 376 static void 377 crc32_init(void) 378 { 379 uint32_t c; 380 int n, k; 381 382 for (n = 0; n < 256; n++) { 383 c = (uint32_t)n; 384 for (k = 0; k < 8; k++) 385 c = (c & 1) ? (0xedb88320u ^ (c >> 1)) : (c >> 1); 386 crc32_table[n] = c; 387 } 388 } 389 390 static uint32_t 391 crc32_update(uint32_t crc, const unsigned char *buf, size_t len) 392 { 393 crc = ~crc; 394 while (len--) 395 crc = crc32_table[(crc ^ *buf++) & 0xff] ^ (crc >> 8); 396 return ~crc; 397 } 398 399 static uint32_t 400 get_le32(const unsigned char *p) 401 { 402 return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); 403 } 404 405 static void 406 put_le32(unsigned char *p, uint32_t v) 407 { 408 p[0] = v & 0xff; 409 p[1] = (v >> 8) & 0xff; 410 p[2] = (v >> 16) & 0xff; 411 p[3] = (v >> 24) & 0xff; 412 } 413 414 /* FLG bits in the gzip header (rfc 1952) */ 415 enum GzipFlag { 416 GZ_FTEXT = 1 << 0, 417 GZ_FHCRC = 1 << 1, 418 GZ_FEXTRA = 1 << 2, 419 GZ_FNAME = 1 << 3, 420 GZ_FCOMMENT = 1 << 4, 421 }; 422 423 static unsigned char * 424 read_all(FILE *fp, size_t *len) 425 { 426 unsigned char *buf; 427 size_t cap, n; 428 ssize_t r; 429 430 cap = 1 << 16; 431 buf = emalloc(cap); 432 n = 0; 433 for (;;) { 434 if (n == cap) { 435 cap *= 2; 436 buf = erealloc(buf, cap); 437 } 438 r = fread(buf + n, 1, cap - n, fp); 439 if (r <= 0) 440 break; 441 n += (size_t)r; 442 } 443 if (ferror(fp)) 444 eprintf("read:"); 445 *len = n; 446 return buf; 447 } 448 449 /* decodes one gzip member; multi-member streams are not supported */ 450 static void 451 gunzip(const unsigned char *in, size_t inlen, FILE *out) 452 { 453 size_t pos, hdr; 454 unsigned flg; 455 unsigned char *dest; 456 unsigned long destlen, srclen; 457 uint32_t want_crc, want_isize, got_crc; 458 int err; 459 460 if (inlen < 18 || in[0] != 0x1f || in[1] != 0x8b) 461 eprintf("gzip: not in gzip format\n"); 462 if (in[2] != 8) 463 eprintf("gzip: unsupported compression method\n"); 464 465 flg = in[3]; 466 pos = 10; 467 468 if (flg & GZ_FEXTRA) { 469 unsigned xlen; 470 if (pos + 2 > inlen) 471 eprintf("gzip: truncated header\n"); 472 xlen = in[pos] | (in[pos + 1] << 8); 473 pos += 2 + xlen; 474 } 475 if (flg & GZ_FNAME) { 476 while (pos < inlen && in[pos] != '\0') 477 pos++; 478 pos++; 479 } 480 if (flg & GZ_FCOMMENT) { 481 while (pos < inlen && in[pos] != '\0') 482 pos++; 483 pos++; 484 } 485 if (flg & GZ_FHCRC) 486 pos += 2; 487 if (pos + 8 > inlen) 488 eprintf("gzip: truncated header\n"); 489 490 hdr = pos; 491 492 /* first pass just measures destlen, second pass does the real decode */ 493 destlen = 0; 494 srclen = (unsigned long)(inlen - hdr - 8); 495 err = inflate_raw(NULL, &destlen, in + hdr, &srclen); 496 if (err != 0) 497 eprintf("gzip: corrupt compressed data\n"); 498 499 dest = emalloc(destlen ? destlen : 1); 500 srclen = (unsigned long)(inlen - hdr - 8); 501 destlen = destlen ? destlen : 1; 502 err = inflate_raw(dest, &destlen, in + hdr, &srclen); 503 if (err != 0) 504 eprintf("gzip: corrupt compressed data\n"); 505 506 want_crc = get_le32(in + hdr + srclen); 507 want_isize = get_le32(in + hdr + srclen + 4); 508 got_crc = crc32_update(0, dest, destlen); 509 if (got_crc != want_crc) 510 eprintf("gzip: crc mismatch\n"); 511 if ((uint32_t)destlen != want_isize) 512 eprintf("gzip: size mismatch\n"); 513 514 if (fwrite(dest, 1, destlen, out) != destlen) 515 eprintf("write:"); 516 free(dest); 517 } 518 519 /* stored (uncompressed) deflate blocks: no compression, always valid */ 520 static void 521 gzip_write_stored(const unsigned char *in, size_t len, FILE *out) 522 { 523 unsigned char hdr[5]; 524 size_t chunk; 525 int last; 526 527 if (len == 0) { 528 hdr[0] = 1; 529 hdr[1] = hdr[2] = hdr[3] = hdr[4] = 0; 530 if (fwrite(hdr, 1, 5, out) != 5) 531 eprintf("write:"); 532 return; 533 } 534 535 while (len > 0) { 536 chunk = len > 65535 ? 65535 : len; 537 last = chunk == len; 538 539 hdr[0] = last ? 1 : 0; 540 hdr[1] = chunk & 0xff; 541 hdr[2] = (chunk >> 8) & 0xff; 542 hdr[3] = (~chunk) & 0xff; 543 hdr[4] = ((~chunk) >> 8) & 0xff; 544 545 if (fwrite(hdr, 1, 5, out) != 5 || fwrite(in, 1, chunk, out) != chunk) 546 eprintf("write:"); 547 548 in += chunk; 549 len -= chunk; 550 } 551 } 552 553 static void 554 gzip_compress(const unsigned char *in, size_t len, const char *name, FILE *out) 555 { 556 unsigned char hdr[10]; 557 unsigned char trl[8]; 558 uint32_t crc; 559 560 hdr[0] = 0x1f; 561 hdr[1] = 0x8b; 562 hdr[2] = 8; 563 hdr[3] = name ? GZ_FNAME : 0; 564 put_le32(hdr + 4, 0); 565 hdr[8] = 0; 566 hdr[9] = 255; 567 if (fwrite(hdr, 1, 10, out) != 10) 568 eprintf("write:"); 569 if (name && (fwrite(name, 1, strlen(name) + 1, out) != strlen(name) + 1)) 570 eprintf("write:"); 571 572 gzip_write_stored(in, len, out); 573 574 crc = crc32_update(0, in, len); 575 put_le32(trl, crc); 576 put_le32(trl + 4, (uint32_t)len); 577 if (fwrite(trl, 1, 8, out) != 8) 578 eprintf("write:"); 579 } 580 581 static char * 582 strip_gz_suffix(const char *name) 583 { 584 size_t n = strlen(name); 585 if (n > 3 && strcmp(name + n - 3, ".gz") == 0) 586 return estrndup(name, n - 3); 587 return NULL; 588 } 589 590 static void 591 usage(void) 592 { 593 eprintf("usage: %s [-cdfkn] [-1..-9] [file ...]\n", argv0); 594 } 595 596 // gzip's long names, which scripts and build systems write, as the letters 597 // they stand for 598 static void 599 short_names(int argc, char *argv[]) 600 { 601 static const struct { 602 const char *name, *letter; 603 } names[] = { 604 {"--stdout", "-c"}, 605 {"--to-stdout", "-c"}, 606 {"--decompress", "-d"}, 607 {"--uncompress", "-d"}, 608 {"--force", "-f"}, 609 {"--keep", "-k"}, 610 {"--no-name", "-n"}, 611 {"--fast", "-1"}, 612 {"--best", "-9"}, 613 }; 614 int i; 615 size_t j; 616 617 for (i = 1; i < argc && argv[i][0] == '-' && strcmp(argv[i], "--") != 0; i++) 618 for (j = 0; j < LEN(names); j++) 619 if (!strcmp(argv[i], names[j].name)) 620 argv[i] = (char *)names[j].letter; 621 } 622 623 // ?man gzip: compress or decompress files 624 // ?man arguments: [file ...] 625 // ?man with no files, reads standard input and writes standard output 626 // ?man compressing replaces each file with file.gz; decompressing 627 // ?man reverses that. only single-member gzip streams are read back. the 628 // ?man long names of other gzips are taken for their letters: --stdout and 629 // ?man its alias --to-stdout, --decompress and its alias --uncompress, 630 // ?man then --force, --keep, --no-name, --fast and --best 631 int 632 main(int argc, char *argv[]) 633 { 634 int dflag = 0, cflag = 0, fflag = 0, kflag = 0, nflag = 0; 635 int i; 636 char outname[4096]; 637 638 short_names(argc, argv); 639 ARGBEGIN 640 { 641 // ?man -c: write to standard output, keep the input file 642 case 'c': 643 cflag = 1; 644 break; 645 // ?man -d: decompress instead of compress 646 case 'd': 647 dflag = 1; 648 break; 649 // ?man -f: accepted for compatibility, no effect 650 case 'f': 651 fflag = 1; 652 break; 653 // ?man -k: keep the input file instead of removing it 654 case 'k': 655 kflag = 1; 656 break; 657 // ?man -n: omit the original file name from the header 658 case 'n': 659 nflag = 1; 660 break; 661 // ?man -1: accepted for compatibility, no effect (stored blocks only) 662 case '1': 663 case '2': 664 case '3': 665 case '4': 666 case '5': 667 case '6': 668 case '7': 669 case '8': 670 case '9': 671 break; 672 default: 673 usage(); 674 } 675 ARGEND 676 677 (void) 678 fflag; 679 crc32_init(); 680 681 if (argc == 0) { 682 unsigned char *buf; 683 size_t len; 684 685 buf = read_all(stdin, &len); 686 if (dflag) 687 gunzip(buf, len, stdout); 688 else 689 gzip_compress(buf, len, NULL, stdout); 690 free(buf); 691 return 0; 692 } 693 694 for (i = 0; i < argc; i++) { 695 FILE *fp; 696 unsigned char *buf; 697 size_t len; 698 char *stripped; 699 700 fp = fopen(argv[i], "rb"); 701 if (!fp) { 702 weprintf("open %s:", argv[i]); 703 continue; 704 } 705 buf = read_all(fp, &len); 706 fclose(fp); 707 708 if (dflag) { 709 if (cflag) { 710 gunzip(buf, len, stdout); 711 } else { 712 stripped = strip_gz_suffix(argv[i]); 713 if (!stripped) 714 eprintf("gzip: %s: unknown suffix, ignored\n", argv[i]); 715 strlcpy(outname, stripped, sizeof(outname)); 716 free(stripped); 717 718 fp = fopen(outname, "wb"); 719 if (!fp) 720 eprintf("open %s:", outname); 721 gunzip(buf, len, fp); 722 if (fclose(fp)) 723 eprintf("close %s:", outname); 724 if (!kflag && unlink(argv[i]) < 0) 725 weprintf("unlink %s:", argv[i]); 726 } 727 } else { 728 if (cflag) { 729 gzip_compress(buf, len, NULL, stdout); 730 } else { 731 strlcpy(outname, argv[i], sizeof(outname)); 732 strlcat(outname, ".gz", sizeof(outname)); 733 734 fp = fopen(outname, "wb"); 735 if (!fp) 736 eprintf("open %s:", outname); 737 gzip_compress(buf, len, nflag ? NULL : argv[i], fp); 738 if (fclose(fp)) 739 eprintf("close %s:", outname); 740 if (!kflag && unlink(argv[i]) < 0) 741 weprintf("unlink %s:", argv[i]); 742 } 743 } 744 745 free(buf); 746 } 747 748 return 0; 749 }