1 /* $NetBSD: gzip.c,v 1.122 2024/02/03 22:40:29 mrg Exp $ */ 2 3 /* 4 * Copyright (c) 1997-2024 Matthew R. Green 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 26 * SUCH DAMAGE. 27 */ 28 29 #include <sys/cdefs.h> 30 #ifndef lint 31 __COPYRIGHT("@(#) Copyright (c) 1997-2024 Matthew R. Green. " 32 "All rights reserved."); 33 __RCSID("$NetBSD: gzip.c,v 1.122 2024/02/03 22:40:29 mrg Exp $"); 34 #endif /* not lint */ 35 36 /* 37 * gzip.c -- GPL free gzip using zlib. 38 * 39 * RFC 1950 covers the zlib format 40 * RFC 1951 covers the deflate format 41 * RFC 1952 covers the gzip format 42 * 43 * TODO: 44 * - use mmap where possible 45 * - handle some signals better (remove outfile?) 46 * - make bzip2/compress -v/-t/-l support work as well as possible 47 */ 48 49 #include <sys/param.h> 50 #include <sys/stat.h> 51 #include <sys/time.h> 52 53 #include <inttypes.h> 54 #include <unistd.h> 55 #include <stdio.h> 56 #include <string.h> 57 #include <stdlib.h> 58 #include <err.h> 59 #include <errno.h> 60 #include <fcntl.h> 61 #include <zlib.h> 62 #include <fts.h> 63 #include <libgen.h> 64 #include <stdarg.h> 65 #include <getopt.h> 66 #include <time.h> 67 #include <paths.h> 68 69 #ifndef PRIdOFF 70 #define PRIdOFF PRId64 71 #endif 72 73 /* what type of file are we dealing with */ 74 enum filetype { 75 FT_GZIP, 76 #ifndef NO_BZIP2_SUPPORT 77 FT_BZIP2, 78 #endif 79 #ifndef NO_COMPRESS_SUPPORT 80 FT_Z, 81 #endif 82 #ifndef NO_PACK_SUPPORT 83 FT_PACK, 84 #endif 85 #ifndef NO_XZ_SUPPORT 86 FT_XZ, 87 #endif 88 #ifndef NO_LZ_SUPPORT 89 FT_LZ, 90 #endif 91 FT_LAST, 92 FT_UNKNOWN 93 }; 94 95 #ifndef NO_BZIP2_SUPPORT 96 #include <bzlib.h> 97 98 #define BZ2_SUFFIX ".bz2" 99 #define BZIP2_MAGIC "\102\132\150" 100 #endif 101 102 #ifndef NO_COMPRESS_SUPPORT 103 #define Z_SUFFIX ".Z" 104 #define Z_MAGIC "\037\235" 105 #endif 106 107 #ifndef NO_PACK_SUPPORT 108 #define PACK_MAGIC "\037\036" 109 #endif 110 111 #ifndef NO_XZ_SUPPORT 112 #include <lzma.h> 113 #define XZ_SUFFIX ".xz" 114 #define XZ_MAGIC "\3757zXZ" 115 #endif 116 117 #ifndef NO_LZ_SUPPORT 118 #define LZ_SUFFIX ".lz" 119 #define LZ_MAGIC "LZIP" 120 #endif 121 122 #define GZ_SUFFIX ".gz" 123 124 #define BUFLEN (64 * 1024) 125 126 #define GZIP_MAGIC0 0x1F 127 #define GZIP_MAGIC1 0x8B 128 #define GZIP_OMAGIC1 0x9E 129 130 #define GZIP_TIMESTAMP (off_t)4 131 #define GZIP_ORIGNAME (off_t)10 132 133 #define HEAD_CRC 0x02 134 #define EXTRA_FIELD 0x04 135 #define ORIG_NAME 0x08 136 #define COMMENT 0x10 137 138 #define OS_CODE 3 /* Unix */ 139 140 typedef struct { 141 const char *zipped; 142 int ziplen; 143 const char *normal; /* for unzip - must not be longer than zipped */ 144 } suffixes_t; 145 static suffixes_t suffixes[] = { 146 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N} 147 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S .xxx */ 148 #ifndef SMALL 149 SUFFIX(GZ_SUFFIX, ""), 150 SUFFIX(".z", ""), 151 SUFFIX("-gz", ""), 152 SUFFIX("-z", ""), 153 SUFFIX("_z", ""), 154 SUFFIX(".taz", ".tar"), 155 SUFFIX(".tgz", ".tar"), 156 #ifndef NO_BZIP2_SUPPORT 157 SUFFIX(BZ2_SUFFIX, ""), 158 #endif 159 #ifndef NO_COMPRESS_SUPPORT 160 SUFFIX(Z_SUFFIX, ""), 161 #endif 162 #ifndef NO_XZ_SUPPORT 163 SUFFIX(XZ_SUFFIX, ""), 164 #endif 165 #ifndef NO_LZ_SUPPORT 166 SUFFIX(LZ_SUFFIX, ""), 167 #endif 168 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */ 169 #endif /* SMALL */ 170 #undef SUFFIX 171 }; 172 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0]) 173 #define SUFFIX_MAXLEN 30 174 175 static const char gzip_version[] = "NetBSD gzip 20240203"; 176 177 static int cflag; /* stdout mode */ 178 static int dflag; /* decompress mode */ 179 static int lflag; /* list mode */ 180 static int numflag = 6; /* gzip -1..-9 value */ 181 182 #ifndef SMALL 183 static int fflag; /* force mode */ 184 static int kflag; /* don't delete input files */ 185 static int nflag; /* don't save name/timestamp */ 186 static int Nflag; /* don't restore name/timestamp */ 187 static int qflag; /* quiet mode */ 188 static int rflag; /* recursive mode */ 189 static int tflag; /* test */ 190 static int vflag; /* verbose mode */ 191 static sig_atomic_t print_info = 0; 192 #else 193 #define qflag 0 194 #define tflag 0 195 #endif 196 197 static int exit_value = 0; /* exit value */ 198 199 static const char *infile; /* name of file coming in */ 200 201 static void maybe_err(const char *fmt, ...) __printflike(1, 2) __dead; 202 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \ 203 !defined(NO_XZ_SUPPORT) 204 static void maybe_errx(const char *fmt, ...) __printflike(1, 2) __dead; 205 #endif 206 static void maybe_warn(const char *fmt, ...) __printflike(1, 2); 207 static void maybe_warnx(const char *fmt, ...) __printflike(1, 2); 208 static enum filetype file_gettype(u_char *); 209 #ifdef SMALL 210 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz) 211 #endif 212 static off_t gz_compress(int, int, off_t *, const char *, uint32_t); 213 static off_t gz_uncompress(int, int, char *, size_t, off_t *, const char *); 214 static off_t file_compress(char *, char *, size_t); 215 static off_t file_uncompress(char *, char *, size_t); 216 static void handle_pathname(char *); 217 static void handle_file(char *, struct stat *); 218 static void handle_stdin(void); 219 static void handle_stdout(void); 220 static void print_ratio(off_t, off_t, FILE *); 221 static void print_list(int fd, off_t, const char *, time_t); 222 __dead static void usage(void); 223 __dead static void display_version(void); 224 static const suffixes_t *check_suffix(char *, int); 225 static ssize_t read_retry(int, void *, size_t); 226 static ssize_t write_retry(int, const void *, size_t); 227 static void print_list_out(off_t, off_t, const char*); 228 229 #ifdef SMALL 230 #define infile_set(f,t) infile_set(f) 231 #endif 232 static void infile_set(const char *newinfile, off_t total); 233 234 #ifdef SMALL 235 #define unlink_input(f, sb) unlink(f) 236 #define check_siginfo() /* nothing */ 237 #define setup_signals() /* nothing */ 238 #define infile_newdata(t) /* nothing */ 239 #else 240 static off_t infile_total; /* total expected to read/write */ 241 static off_t infile_current; /* current read/write */ 242 243 static void check_siginfo(void); 244 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd); 245 static void prepend_gzip(char *, int *, char ***); 246 static void handle_dir(char *); 247 static void print_verbage(const char *, const char *, off_t, off_t); 248 static void print_test(const char *, int); 249 static void copymodes(int fd, const struct stat *, const char *file); 250 static int check_outfile(const char *outfile); 251 static void setup_signals(void); 252 static void infile_newdata(size_t newdata); 253 static void infile_clear(void); 254 #endif 255 256 #ifndef NO_BZIP2_SUPPORT 257 static off_t unbzip2(int, int, char *, size_t, off_t *); 258 #endif 259 260 #ifndef NO_COMPRESS_SUPPORT 261 static FILE *zdopen(int); 262 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *); 263 #endif 264 265 #ifndef NO_PACK_SUPPORT 266 static off_t unpack(int, int, char *, size_t, off_t *); 267 #endif 268 269 #ifndef NO_XZ_SUPPORT 270 static off_t unxz(int, int, char *, size_t, off_t *); 271 static off_t unxz_len(int); 272 #endif 273 274 #ifndef NO_LZ_SUPPORT 275 static off_t unlz(int, int, char *, size_t, off_t *); 276 #endif 277 278 #ifdef SMALL 279 #define getopt_long(a,b,c,d,e) getopt(a,b,c) 280 #else 281 static const struct option longopts[] = { 282 { "stdout", no_argument, 0, 'c' }, 283 { "to-stdout", no_argument, 0, 'c' }, 284 { "decompress", no_argument, 0, 'd' }, 285 { "uncompress", no_argument, 0, 'd' }, 286 { "force", no_argument, 0, 'f' }, 287 { "help", no_argument, 0, 'h' }, 288 { "keep", no_argument, 0, 'k' }, 289 { "list", no_argument, 0, 'l' }, 290 { "no-name", no_argument, 0, 'n' }, 291 { "name", no_argument, 0, 'N' }, 292 { "quiet", no_argument, 0, 'q' }, 293 { "recursive", no_argument, 0, 'r' }, 294 { "suffix", required_argument, 0, 'S' }, 295 { "test", no_argument, 0, 't' }, 296 { "verbose", no_argument, 0, 'v' }, 297 { "version", no_argument, 0, 'V' }, 298 { "fast", no_argument, 0, '1' }, 299 { "best", no_argument, 0, '9' }, 300 #if 0 301 /* 302 * This is what else GNU gzip implements. --ascii isn't useful 303 * on NetBSD, and I don't care to have a --license. 304 */ 305 { "ascii", no_argument, 0, 'a' }, 306 { "license", no_argument, 0, 'L' }, 307 #endif 308 { NULL, no_argument, 0, 0 }, 309 }; 310 #endif 311 312 int 313 main(int argc, char **argv) 314 { 315 const char *progname = getprogname(); 316 #ifndef SMALL 317 char *gzip; 318 int len; 319 #endif 320 int ch; 321 322 setup_signals(); 323 324 #ifndef SMALL 325 if ((gzip = getenv("GZIP")) != NULL) 326 prepend_gzip(gzip, &argc, &argv); 327 #endif 328 329 /* 330 * XXX 331 * handle being called `gunzip', `zcat' and `gzcat' 332 */ 333 if (strcmp(progname, "gunzip") == 0) 334 dflag = 1; 335 else if (strcmp(progname, "zcat") == 0 || 336 strcmp(progname, "gzcat") == 0) 337 dflag = cflag = 1; 338 339 #ifdef SMALL 340 #define OPT_LIST "123456789cdhlV" 341 #else 342 #define OPT_LIST "123456789cdfhklNnqrS:tVv" 343 #endif 344 345 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) { 346 switch (ch) { 347 case '1': case '2': case '3': 348 case '4': case '5': case '6': 349 case '7': case '8': case '9': 350 numflag = ch - '0'; 351 break; 352 case 'c': 353 cflag = 1; 354 break; 355 case 'd': 356 dflag = 1; 357 break; 358 case 'l': 359 lflag = 1; 360 dflag = 1; 361 break; 362 case 'V': 363 display_version(); 364 /* NOTREACHED */ 365 #ifndef SMALL 366 case 'f': 367 fflag = 1; 368 break; 369 case 'k': 370 kflag = 1; 371 break; 372 case 'N': 373 nflag = 0; 374 Nflag = 1; 375 break; 376 case 'n': 377 nflag = 1; 378 Nflag = 0; 379 break; 380 case 'q': 381 qflag = 1; 382 break; 383 case 'r': 384 rflag = 1; 385 break; 386 case 'S': 387 len = strlen(optarg); 388 if (len != 0) { 389 if (len > SUFFIX_MAXLEN) 390 errx(1, "incorrect suffix: '%s'", optarg); 391 suffixes[0].zipped = optarg; 392 suffixes[0].ziplen = len; 393 } else { 394 suffixes[NUM_SUFFIXES - 1].zipped = ""; 395 suffixes[NUM_SUFFIXES - 1].ziplen = 0; 396 } 397 break; 398 case 't': 399 cflag = 1; 400 tflag = 1; 401 dflag = 1; 402 break; 403 case 'v': 404 vflag = 1; 405 break; 406 #endif 407 default: 408 usage(); 409 /* NOTREACHED */ 410 } 411 } 412 argv += optind; 413 argc -= optind; 414 415 if (argc == 0) { 416 if (dflag) /* stdin mode */ 417 handle_stdin(); 418 else /* stdout mode */ 419 handle_stdout(); 420 } else { 421 do { 422 handle_pathname(argv[0]); 423 } while (*++argv); 424 } 425 #ifndef SMALL 426 if (qflag == 0 && lflag && argc > 1) 427 print_list(-1, 0, "(totals)", 0); 428 #endif 429 exit(exit_value); 430 } 431 432 /* maybe print a warning */ 433 void 434 maybe_warn(const char *fmt, ...) 435 { 436 va_list ap; 437 438 if (qflag == 0) { 439 va_start(ap, fmt); 440 vwarn(fmt, ap); 441 va_end(ap); 442 } 443 if (exit_value == 0) 444 exit_value = 1; 445 } 446 447 /* ... without an errno. */ 448 void 449 maybe_warnx(const char *fmt, ...) 450 { 451 va_list ap; 452 453 if (qflag == 0) { 454 va_start(ap, fmt); 455 vwarnx(fmt, ap); 456 va_end(ap); 457 } 458 if (exit_value == 0) 459 exit_value = 1; 460 } 461 462 /* maybe print an error */ 463 void 464 maybe_err(const char *fmt, ...) 465 { 466 va_list ap; 467 468 if (qflag == 0) { 469 va_start(ap, fmt); 470 vwarn(fmt, ap); 471 va_end(ap); 472 } 473 exit(2); 474 } 475 476 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \ 477 !defined(NO_XZ_SUPPORT) 478 /* ... without an errno. */ 479 void 480 maybe_errx(const char *fmt, ...) 481 { 482 va_list ap; 483 484 if (qflag == 0) { 485 va_start(ap, fmt); 486 vwarnx(fmt, ap); 487 va_end(ap); 488 } 489 exit(2); 490 } 491 #endif 492 493 #ifndef SMALL 494 /* split up $GZIP and prepend it to the argument list */ 495 static void 496 prepend_gzip(char *gzip, int *argc, char ***argv) 497 { 498 char *s, **nargv, **ac; 499 int nenvarg = 0, i; 500 501 /* scan how many arguments there are */ 502 for (s = gzip;;) { 503 while (*s == ' ' || *s == '\t') 504 s++; 505 if (*s == 0) 506 goto count_done; 507 nenvarg++; 508 while (*s != ' ' && *s != '\t') 509 if (*s++ == 0) 510 goto count_done; 511 } 512 count_done: 513 /* punt early */ 514 if (nenvarg == 0) 515 return; 516 517 *argc += nenvarg; 518 ac = *argv; 519 520 nargv = (char **)malloc((*argc + 1) * sizeof(char *)); 521 if (nargv == NULL) 522 maybe_err("malloc"); 523 524 /* stash this away */ 525 *argv = nargv; 526 527 /* copy the program name first */ 528 i = 0; 529 nargv[i++] = *(ac++); 530 531 /* take a copy of $GZIP and add it to the array */ 532 s = strdup(gzip); 533 if (s == NULL) 534 maybe_err("strdup"); 535 for (;;) { 536 /* Skip whitespaces. */ 537 while (*s == ' ' || *s == '\t') 538 s++; 539 if (*s == 0) 540 goto copy_done; 541 nargv[i++] = s; 542 /* Find the end of this argument. */ 543 while (*s != ' ' && *s != '\t') 544 if (*s++ == 0) 545 /* Argument followed by NUL. */ 546 goto copy_done; 547 /* Terminate by overwriting ' ' or '\t' with NUL. */ 548 *s++ = 0; 549 } 550 copy_done: 551 552 /* copy the original arguments and a NULL */ 553 while (*ac) 554 nargv[i++] = *(ac++); 555 nargv[i] = NULL; 556 } 557 #endif 558 559 /* compress input to output. Return bytes read, -1 on error */ 560 static off_t 561 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime) 562 { 563 z_stream z; 564 char *outbufp, *inbufp; 565 off_t in_tot = 0, out_tot = 0; 566 ssize_t in_size; 567 int i, error; 568 uLong crc; 569 #ifdef SMALL 570 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0, 571 0, 0, 0, 0, 572 0, OS_CODE }; 573 #endif 574 575 outbufp = malloc(BUFLEN); 576 inbufp = malloc(BUFLEN); 577 if (outbufp == NULL || inbufp == NULL) { 578 maybe_err("malloc failed"); 579 goto out; 580 } 581 582 memset(&z, 0, sizeof z); 583 z.zalloc = Z_NULL; 584 z.zfree = Z_NULL; 585 z.opaque = 0; 586 587 #ifdef SMALL 588 memcpy(outbufp, header, sizeof header); 589 i = sizeof header; 590 #else 591 if (nflag != 0) { 592 mtime = 0; 593 origname = ""; 594 } 595 596 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s", 597 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 598 *origname ? ORIG_NAME : 0, 599 mtime & 0xff, 600 (mtime >> 8) & 0xff, 601 (mtime >> 16) & 0xff, 602 (mtime >> 24) & 0xff, 603 numflag == 1 ? 4 : numflag == 9 ? 2 : 0, 604 OS_CODE, origname); 605 if (i >= BUFLEN) 606 /* this need PATH_MAX > BUFLEN ... */ 607 maybe_err("snprintf"); 608 if (*origname) 609 i++; 610 #endif 611 612 z.next_out = (unsigned char *)outbufp + i; 613 z.avail_out = BUFLEN - i; 614 615 error = deflateInit2(&z, numflag, Z_DEFLATED, 616 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY); 617 if (error != Z_OK) { 618 maybe_warnx("deflateInit2 failed"); 619 in_tot = -1; 620 goto out; 621 } 622 623 crc = crc32(0L, Z_NULL, 0); 624 for (;;) { 625 check_siginfo(); 626 if (z.avail_out == 0) { 627 if (write_retry(out, outbufp, BUFLEN) != BUFLEN) { 628 maybe_warn("write"); 629 out_tot = -1; 630 goto out; 631 } 632 633 out_tot += BUFLEN; 634 z.next_out = (unsigned char *)outbufp; 635 z.avail_out = BUFLEN; 636 } 637 638 if (z.avail_in == 0) { 639 in_size = read(in, inbufp, BUFLEN); 640 if (in_size < 0) { 641 maybe_warn("read"); 642 in_tot = -1; 643 goto out; 644 } 645 if (in_size == 0) 646 break; 647 infile_newdata(in_size); 648 649 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size); 650 in_tot += in_size; 651 z.next_in = (unsigned char *)inbufp; 652 z.avail_in = in_size; 653 } 654 655 error = deflate(&z, Z_NO_FLUSH); 656 if (error != Z_OK && error != Z_STREAM_END) { 657 maybe_warnx("deflate failed"); 658 in_tot = -1; 659 goto out; 660 } 661 } 662 663 /* clean up */ 664 for (;;) { 665 size_t len; 666 ssize_t w; 667 668 error = deflate(&z, Z_FINISH); 669 if (error != Z_OK && error != Z_STREAM_END) { 670 maybe_warnx("deflate failed"); 671 in_tot = -1; 672 goto out; 673 } 674 675 len = (char *)z.next_out - outbufp; 676 677 w = write_retry(out, outbufp, len); 678 if (w == -1 || (size_t)w != len) { 679 maybe_warn("write"); 680 out_tot = -1; 681 goto out; 682 } 683 out_tot += len; 684 z.next_out = (unsigned char *)outbufp; 685 z.avail_out = BUFLEN; 686 687 if (error == Z_STREAM_END) 688 break; 689 } 690 691 if (deflateEnd(&z) != Z_OK) { 692 maybe_warnx("deflateEnd failed"); 693 in_tot = -1; 694 goto out; 695 } 696 697 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c", 698 (int)crc & 0xff, 699 (int)(crc >> 8) & 0xff, 700 (int)(crc >> 16) & 0xff, 701 (int)(crc >> 24) & 0xff, 702 (int)in_tot & 0xff, 703 (int)(in_tot >> 8) & 0xff, 704 (int)(in_tot >> 16) & 0xff, 705 (int)(in_tot >> 24) & 0xff); 706 if (i != 8) 707 maybe_err("snprintf"); 708 #if 0 709 if (in_tot > 0xffffffff) 710 maybe_warn("input file size >= 4GB cannot be saved"); 711 #endif 712 if (write_retry(out, outbufp, i) != i) { 713 maybe_warn("write"); 714 in_tot = -1; 715 } else 716 out_tot += i; 717 718 out: 719 if (inbufp != NULL) 720 free(inbufp); 721 if (outbufp != NULL) 722 free(outbufp); 723 if (gsizep) 724 *gsizep = out_tot; 725 return in_tot; 726 } 727 728 /* 729 * uncompress input to output then close the input. return the 730 * uncompressed size written, and put the compressed sized read 731 * into `*gsizep'. 732 */ 733 static off_t 734 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep, 735 const char *filename) 736 { 737 z_stream z; 738 char *outbufp, *inbufp; 739 off_t out_tot = -1, in_tot = 0; 740 uint32_t out_sub_tot = 0; 741 enum { 742 GZSTATE_MAGIC0, 743 GZSTATE_MAGIC1, 744 GZSTATE_METHOD, 745 GZSTATE_FLAGS, 746 GZSTATE_SKIPPING, 747 GZSTATE_EXTRA, 748 GZSTATE_EXTRA2, 749 GZSTATE_EXTRA3, 750 GZSTATE_ORIGNAME, 751 GZSTATE_COMMENT, 752 GZSTATE_HEAD_CRC1, 753 GZSTATE_HEAD_CRC2, 754 GZSTATE_INIT, 755 GZSTATE_READ, 756 GZSTATE_CRC, 757 GZSTATE_LEN, 758 } state = GZSTATE_MAGIC0; 759 int flags = 0, skip_count = 0; 760 int error = Z_STREAM_ERROR, done_reading = 0; 761 uLong crc = 0; 762 ssize_t wr; 763 int needmore = 0; 764 765 #define ADVANCE() { z.next_in++; z.avail_in--; } 766 767 if ((outbufp = malloc(BUFLEN)) == NULL) { 768 maybe_err("malloc failed"); 769 goto out2; 770 } 771 if ((inbufp = malloc(BUFLEN)) == NULL) { 772 maybe_err("malloc failed"); 773 goto out1; 774 } 775 776 memset(&z, 0, sizeof z); 777 z.avail_in = prelen; 778 z.next_in = (unsigned char *)pre; 779 z.avail_out = BUFLEN; 780 z.next_out = (unsigned char *)outbufp; 781 z.zalloc = NULL; 782 z.zfree = NULL; 783 z.opaque = 0; 784 785 in_tot = prelen; 786 out_tot = 0; 787 788 for (;;) { 789 check_siginfo(); 790 if ((z.avail_in == 0 || needmore) && done_reading == 0) { 791 ssize_t in_size; 792 793 if (z.avail_in > 0) { 794 memmove(inbufp, z.next_in, z.avail_in); 795 } 796 z.next_in = (unsigned char *)inbufp; 797 in_size = read(in, z.next_in + z.avail_in, 798 BUFLEN - z.avail_in); 799 800 if (in_size == -1) { 801 maybe_warn("failed to read stdin"); 802 goto stop_and_fail; 803 } else if (in_size == 0) { 804 done_reading = 1; 805 } 806 infile_newdata(in_size); 807 808 z.avail_in += in_size; 809 needmore = 0; 810 811 in_tot += in_size; 812 } 813 if (z.avail_in == 0) { 814 if (done_reading && state != GZSTATE_MAGIC0) { 815 maybe_warnx("%s: unexpected end of file", 816 filename); 817 goto stop_and_fail; 818 } 819 goto stop; 820 } 821 switch (state) { 822 case GZSTATE_MAGIC0: 823 if (*z.next_in != GZIP_MAGIC0) { 824 if (in_tot > 0) { 825 maybe_warnx("%s: trailing garbage " 826 "ignored", filename); 827 goto stop; 828 } 829 maybe_warnx("input not gziped (MAGIC0)"); 830 exit_value = 2; 831 goto stop_and_fail; 832 } 833 ADVANCE(); 834 state++; 835 out_sub_tot = 0; 836 crc = crc32(0L, Z_NULL, 0); 837 break; 838 839 case GZSTATE_MAGIC1: 840 if (*z.next_in != GZIP_MAGIC1 && 841 *z.next_in != GZIP_OMAGIC1) { 842 maybe_warnx("input not gziped (MAGIC1)"); 843 goto stop_and_fail; 844 } 845 ADVANCE(); 846 state++; 847 break; 848 849 case GZSTATE_METHOD: 850 if (*z.next_in != Z_DEFLATED) { 851 maybe_warnx("unknown compression method"); 852 goto stop_and_fail; 853 } 854 ADVANCE(); 855 state++; 856 break; 857 858 case GZSTATE_FLAGS: 859 flags = *z.next_in; 860 ADVANCE(); 861 skip_count = 6; 862 state++; 863 break; 864 865 case GZSTATE_SKIPPING: 866 if (skip_count > 0) { 867 skip_count--; 868 ADVANCE(); 869 } else 870 state++; 871 break; 872 873 case GZSTATE_EXTRA: 874 if ((flags & EXTRA_FIELD) == 0) { 875 state = GZSTATE_ORIGNAME; 876 break; 877 } 878 skip_count = *z.next_in; 879 ADVANCE(); 880 state++; 881 break; 882 883 case GZSTATE_EXTRA2: 884 skip_count |= ((*z.next_in) << 8); 885 ADVANCE(); 886 state++; 887 break; 888 889 case GZSTATE_EXTRA3: 890 if (skip_count > 0) { 891 skip_count--; 892 ADVANCE(); 893 } else 894 state++; 895 break; 896 897 case GZSTATE_ORIGNAME: 898 if ((flags & ORIG_NAME) == 0) { 899 state++; 900 break; 901 } 902 if (*z.next_in == 0) 903 state++; 904 ADVANCE(); 905 break; 906 907 case GZSTATE_COMMENT: 908 if ((flags & COMMENT) == 0) { 909 state++; 910 break; 911 } 912 if (*z.next_in == 0) 913 state++; 914 ADVANCE(); 915 break; 916 917 case GZSTATE_HEAD_CRC1: 918 if (flags & HEAD_CRC) 919 skip_count = 2; 920 else 921 skip_count = 0; 922 state++; 923 break; 924 925 case GZSTATE_HEAD_CRC2: 926 if (skip_count > 0) { 927 skip_count--; 928 ADVANCE(); 929 } else 930 state++; 931 break; 932 933 case GZSTATE_INIT: 934 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) { 935 maybe_warnx("failed to inflateInit"); 936 goto stop_and_fail; 937 } 938 state++; 939 break; 940 941 case GZSTATE_READ: 942 error = inflate(&z, Z_FINISH); 943 switch (error) { 944 /* Z_BUF_ERROR goes with Z_FINISH... */ 945 case Z_BUF_ERROR: 946 if (z.avail_out > 0 && !done_reading) 947 continue; 948 949 case Z_STREAM_END: 950 case Z_OK: 951 break; 952 953 case Z_NEED_DICT: 954 maybe_warnx("Z_NEED_DICT error"); 955 goto stop_and_fail; 956 case Z_DATA_ERROR: 957 maybe_warnx("data stream error"); 958 goto stop_and_fail; 959 case Z_STREAM_ERROR: 960 maybe_warnx("internal stream error"); 961 goto stop_and_fail; 962 case Z_MEM_ERROR: 963 maybe_warnx("memory allocation error"); 964 goto stop_and_fail; 965 966 default: 967 maybe_warn("unknown error from inflate(): %d", 968 error); 969 } 970 wr = BUFLEN - z.avail_out; 971 972 if (wr != 0) { 973 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr); 974 if ( 975 #ifndef SMALL 976 /* don't write anything with -t */ 977 tflag == 0 && 978 #endif 979 write_retry(out, outbufp, wr) != wr) { 980 maybe_warn("error writing to output"); 981 goto stop_and_fail; 982 } 983 984 out_tot += wr; 985 out_sub_tot += wr; 986 } 987 988 if (error == Z_STREAM_END) { 989 inflateEnd(&z); 990 state++; 991 } 992 993 z.next_out = (unsigned char *)outbufp; 994 z.avail_out = BUFLEN; 995 996 break; 997 case GZSTATE_CRC: 998 { 999 uLong origcrc; 1000 1001 if (z.avail_in < 4) { 1002 if (!done_reading) { 1003 needmore = 1; 1004 continue; 1005 } 1006 maybe_warnx("truncated input"); 1007 goto stop_and_fail; 1008 } 1009 origcrc = ((unsigned)z.next_in[0] & 0xff) | 1010 ((unsigned)z.next_in[1] & 0xff) << 8 | 1011 ((unsigned)z.next_in[2] & 0xff) << 16 | 1012 ((unsigned)z.next_in[3] & 0xff) << 24; 1013 if (origcrc != crc) { 1014 maybe_warnx("invalid compressed" 1015 " data--crc error"); 1016 goto stop_and_fail; 1017 } 1018 } 1019 1020 z.avail_in -= 4; 1021 z.next_in += 4; 1022 1023 if (!z.avail_in && done_reading) { 1024 goto stop; 1025 } 1026 state++; 1027 break; 1028 case GZSTATE_LEN: 1029 { 1030 uLong origlen; 1031 1032 if (z.avail_in < 4) { 1033 if (!done_reading) { 1034 needmore = 1; 1035 continue; 1036 } 1037 maybe_warnx("truncated input"); 1038 goto stop_and_fail; 1039 } 1040 origlen = ((unsigned)z.next_in[0] & 0xff) | 1041 ((unsigned)z.next_in[1] & 0xff) << 8 | 1042 ((unsigned)z.next_in[2] & 0xff) << 16 | 1043 ((unsigned)z.next_in[3] & 0xff) << 24; 1044 1045 if (origlen != out_sub_tot) { 1046 maybe_warnx("invalid compressed" 1047 " data--length error"); 1048 goto stop_and_fail; 1049 } 1050 } 1051 1052 z.avail_in -= 4; 1053 z.next_in += 4; 1054 1055 if (error < 0) { 1056 maybe_warnx("decompression error"); 1057 goto stop_and_fail; 1058 } 1059 state = GZSTATE_MAGIC0; 1060 break; 1061 } 1062 continue; 1063 stop_and_fail: 1064 out_tot = -1; 1065 stop: 1066 break; 1067 } 1068 if (state > GZSTATE_INIT) 1069 inflateEnd(&z); 1070 1071 free(inbufp); 1072 out1: 1073 free(outbufp); 1074 out2: 1075 if (gsizep) 1076 *gsizep = in_tot; 1077 return (out_tot); 1078 } 1079 1080 #ifndef SMALL 1081 /* 1082 * set the owner, mode, flags & utimes using the given file descriptor. 1083 * file is only used in possible warning messages. 1084 */ 1085 static void 1086 copymodes(int fd, const struct stat *sbp, const char *file) 1087 { 1088 struct timeval times[2]; 1089 struct stat sb; 1090 1091 /* 1092 * If we have no info on the input, give this file some 1093 * default values and return.. 1094 */ 1095 if (sbp == NULL) { 1096 mode_t mask = umask(022); 1097 1098 (void)fchmod(fd, DEFFILEMODE & ~mask); 1099 (void)umask(mask); 1100 return; 1101 } 1102 sb = *sbp; 1103 1104 /* if the chown fails, remove set-id bits as-per compress(1) */ 1105 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) { 1106 if (errno != EPERM) 1107 maybe_warn("couldn't fchown: %s", file); 1108 sb.st_mode &= ~(S_ISUID|S_ISGID); 1109 } 1110 1111 /* we only allow set-id and the 9 normal permission bits */ 1112 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO; 1113 if (fchmod(fd, sb.st_mode) < 0) 1114 maybe_warn("couldn't fchmod: %s", file); 1115 1116 TIMESPEC_TO_TIMEVAL(×[0], &sb.st_atimespec); 1117 TIMESPEC_TO_TIMEVAL(×[1], &sb.st_mtimespec); 1118 if (futimes(fd, times) < 0) 1119 maybe_warn("couldn't utimes: %s", file); 1120 1121 /* finally, only try flags if they exist already */ 1122 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0) 1123 maybe_warn("couldn't fchflags: %s", file); 1124 } 1125 #endif 1126 1127 /* what sort of file is this? */ 1128 static enum filetype 1129 file_gettype(u_char *buf) 1130 { 1131 1132 if (buf[0] == GZIP_MAGIC0 && 1133 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1)) 1134 return FT_GZIP; 1135 else 1136 #ifndef NO_BZIP2_SUPPORT 1137 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 && 1138 buf[3] >= '0' && buf[3] <= '9') 1139 return FT_BZIP2; 1140 else 1141 #endif 1142 #ifndef NO_COMPRESS_SUPPORT 1143 if (memcmp(buf, Z_MAGIC, 2) == 0) 1144 return FT_Z; 1145 else 1146 #endif 1147 #ifndef NO_PACK_SUPPORT 1148 if (memcmp(buf, PACK_MAGIC, 2) == 0) 1149 return FT_PACK; 1150 else 1151 #endif 1152 #ifndef NO_XZ_SUPPORT 1153 if (memcmp(buf, XZ_MAGIC, 4) == 0) /* XXX: We only have 4 bytes */ 1154 return FT_XZ; 1155 else 1156 #endif 1157 #ifndef NO_LZ_SUPPORT 1158 if (memcmp(buf, LZ_MAGIC, 4) == 0) 1159 return FT_LZ; 1160 else 1161 #endif 1162 return FT_UNKNOWN; 1163 } 1164 1165 #ifndef SMALL 1166 /* check the outfile is OK. */ 1167 static int 1168 check_outfile(const char *outfile) 1169 { 1170 struct stat sb; 1171 int ok = 1; 1172 1173 if (lflag == 0 && stat(outfile, &sb) == 0) { 1174 if (fflag) 1175 unlink(outfile); 1176 else if (isatty(STDIN_FILENO)) { 1177 char ans[10] = { 'n', '\0' }; /* default */ 1178 1179 fprintf(stderr, "%s already exists -- do you wish to " 1180 "overwrite (y or n)? " , outfile); 1181 (void)fgets(ans, sizeof(ans) - 1, stdin); 1182 if (ans[0] != 'y' && ans[0] != 'Y') { 1183 fprintf(stderr, "\tnot overwriting\n"); 1184 ok = 0; 1185 } else 1186 unlink(outfile); 1187 } else { 1188 maybe_warnx("%s already exists -- skipping", outfile); 1189 ok = 0; 1190 } 1191 } 1192 return ok; 1193 } 1194 1195 static void 1196 unlink_input(const char *file, const struct stat *sb) 1197 { 1198 struct stat nsb; 1199 1200 if (kflag) 1201 return; 1202 if (stat(file, &nsb) != 0) 1203 /* Must be gone already */ 1204 return; 1205 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino) 1206 /* Definitely a different file */ 1207 return; 1208 unlink(file); 1209 } 1210 1211 static void 1212 got_siginfo(int signo) 1213 { 1214 1215 print_info = 1; 1216 } 1217 1218 static void 1219 setup_signals(void) 1220 { 1221 1222 signal(SIGINFO, got_siginfo); 1223 } 1224 1225 static void 1226 infile_newdata(size_t newdata) 1227 { 1228 1229 infile_current += newdata; 1230 } 1231 #endif 1232 1233 static void 1234 infile_set(const char *newinfile, off_t total) 1235 { 1236 1237 if (newinfile) 1238 infile = newinfile; 1239 #ifndef SMALL 1240 infile_total = total; 1241 #endif 1242 } 1243 1244 static void 1245 infile_clear(void) 1246 { 1247 1248 infile = NULL; 1249 #ifndef SMALL 1250 infile_total = infile_current = 0; 1251 #endif 1252 } 1253 1254 static const suffixes_t * 1255 check_suffix(char *file, int xlate) 1256 { 1257 const suffixes_t *s; 1258 int len = strlen(file); 1259 char *sp; 1260 1261 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) { 1262 /* if it doesn't fit in "a.suf", don't bother */ 1263 if (s->ziplen >= len) 1264 continue; 1265 sp = file + len - s->ziplen; 1266 if (strcmp(s->zipped, sp) != 0) 1267 continue; 1268 if (xlate) 1269 strcpy(sp, s->normal); 1270 return s; 1271 } 1272 return NULL; 1273 } 1274 1275 /* 1276 * compress the given file: create a corresponding .gz file and remove the 1277 * original. 1278 */ 1279 static off_t 1280 file_compress(char *file, char *outfile, size_t outsize) 1281 { 1282 int in; 1283 int out; 1284 off_t size, in_size; 1285 #ifndef SMALL 1286 struct stat isb, osb; 1287 const suffixes_t *suff; 1288 #endif 1289 1290 in = open(file, O_RDONLY); 1291 if (in == -1) { 1292 maybe_warn("can't open %s", file); 1293 return -1; 1294 } 1295 1296 #ifndef SMALL 1297 if (fstat(in, &isb) != 0) { 1298 close(in); 1299 maybe_warn("can't stat %s", file); 1300 return -1; 1301 } 1302 infile_set(file, isb.st_size); 1303 #endif 1304 1305 if (cflag == 0) { 1306 #ifndef SMALL 1307 if (isb.st_nlink > 1 && fflag == 0) { 1308 maybe_warnx("%s has %d other link%s -- " 1309 "skipping", file, isb.st_nlink - 1, 1310 isb.st_nlink == 1 ? "" : "s"); 1311 close(in); 1312 return -1; 1313 } 1314 1315 if (fflag == 0 && (suff = check_suffix(file, 0)) 1316 && suff->zipped[0] != 0) { 1317 maybe_warnx("%s already has %s suffix -- unchanged", 1318 file, suff->zipped); 1319 close(in); 1320 return -1; 1321 } 1322 #endif 1323 1324 /* Add (usually) .gz to filename */ 1325 if ((size_t)snprintf(outfile, outsize, "%s%s", 1326 file, suffixes[0].zipped) >= outsize) 1327 memcpy(outfile + outsize - suffixes[0].ziplen - 1, 1328 suffixes[0].zipped, suffixes[0].ziplen + 1); 1329 1330 #ifndef SMALL 1331 if (check_outfile(outfile) == 0) { 1332 close(in); 1333 return -1; 1334 } 1335 #endif 1336 } 1337 1338 if (cflag == 0) { 1339 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600); 1340 if (out == -1) { 1341 maybe_warn("could not create output: %s", outfile); 1342 fclose(stdin); 1343 return -1; 1344 } 1345 } else 1346 out = STDOUT_FILENO; 1347 1348 in_size = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime); 1349 1350 (void)close(in); 1351 1352 /* 1353 * If there was an error, in_size will be -1. 1354 * If we compressed to stdout, just return the size. 1355 * Otherwise stat the file and check it is the correct size. 1356 * We only blow away the file if we can stat the output and it 1357 * has the expected size. 1358 */ 1359 if (cflag != 0) 1360 return in_size == -1 ? -1 : size; 1361 1362 #ifndef SMALL 1363 if (fstat(out, &osb) != 0) { 1364 maybe_warn("couldn't stat: %s", outfile); 1365 goto bad_outfile; 1366 } 1367 1368 if (osb.st_size != size) { 1369 maybe_warnx("output file: %s wrong size (%" PRIdOFF 1370 " != %" PRIdOFF "), deleting", 1371 outfile, osb.st_size, size); 1372 goto bad_outfile; 1373 } 1374 1375 copymodes(out, &isb, outfile); 1376 #endif 1377 if (close(out) == -1) 1378 maybe_warn("couldn't close output"); 1379 1380 /* output is good, ok to delete input */ 1381 unlink_input(file, &isb); 1382 return size; 1383 1384 #ifndef SMALL 1385 bad_outfile: 1386 if (close(out) == -1) 1387 maybe_warn("couldn't close output"); 1388 1389 maybe_warnx("leaving original %s", file); 1390 unlink(outfile); 1391 return size; 1392 #endif 1393 } 1394 1395 /* uncompress the given file and remove the original */ 1396 static off_t 1397 file_uncompress(char *file, char *outfile, size_t outsize) 1398 { 1399 struct stat isb, osb; 1400 off_t size; 1401 ssize_t rbytes; 1402 unsigned char fourbytes[4]; 1403 enum filetype method; 1404 int fd, ofd, zfd = -1; 1405 size_t in_size; 1406 #ifndef SMALL 1407 ssize_t rv; 1408 time_t timestamp = 0; 1409 char name[PATH_MAX + 1]; 1410 #endif 1411 1412 /* gather the old name info */ 1413 1414 fd = open(file, O_RDONLY); 1415 if (fd < 0) { 1416 maybe_warn("can't open %s", file); 1417 goto lose; 1418 } 1419 if (fstat(fd, &isb) != 0) { 1420 close(fd); 1421 maybe_warn("can't stat %s", file); 1422 goto lose; 1423 } 1424 if (S_ISREG(isb.st_mode)) 1425 in_size = isb.st_size; 1426 else 1427 in_size = 0; 1428 infile_set(file, in_size); 1429 1430 strlcpy(outfile, file, outsize); 1431 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) { 1432 maybe_warnx("%s: unknown suffix -- ignored", file); 1433 goto lose; 1434 } 1435 1436 rbytes = read(fd, fourbytes, sizeof fourbytes); 1437 if (rbytes != sizeof fourbytes) { 1438 /* we don't want to fail here. */ 1439 #ifndef SMALL 1440 if (fflag) 1441 goto lose; 1442 #endif 1443 if (rbytes == -1) 1444 maybe_warn("can't read %s", file); 1445 else 1446 goto unexpected_EOF; 1447 goto lose; 1448 } 1449 infile_newdata(rbytes); 1450 1451 method = file_gettype(fourbytes); 1452 #ifndef SMALL 1453 if (fflag == 0 && method == FT_UNKNOWN) { 1454 maybe_warnx("%s: not in gzip format", file); 1455 goto lose; 1456 } 1457 1458 #endif 1459 1460 #ifndef SMALL 1461 if (method == FT_GZIP && Nflag) { 1462 unsigned char ts[4]; /* timestamp */ 1463 1464 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP); 1465 if (rv >= 0 && rv < (ssize_t)(sizeof ts)) 1466 goto unexpected_EOF; 1467 if (rv == -1) { 1468 if (!fflag) 1469 maybe_warn("can't read %s", file); 1470 goto lose; 1471 } 1472 infile_newdata(rv); 1473 timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0]; 1474 1475 if (fourbytes[3] & ORIG_NAME) { 1476 rbytes = pread(fd, name, sizeof(name) - 1, GZIP_ORIGNAME); 1477 if (rbytes < 0) { 1478 maybe_warn("can't read %s", file); 1479 goto lose; 1480 } 1481 if (name[0] != '\0') { 1482 char *dp, *nf; 1483 1484 /* Make sure that name is NUL-terminated */ 1485 name[rbytes] = '\0'; 1486 1487 /* strip saved directory name */ 1488 nf = strrchr(name, '/'); 1489 if (nf == NULL) 1490 nf = name; 1491 else 1492 nf++; 1493 1494 /* preserve original directory name */ 1495 dp = strrchr(file, '/'); 1496 if (dp == NULL) 1497 dp = file; 1498 else 1499 dp++; 1500 snprintf(outfile, outsize, "%.*s%.*s", 1501 (int) (dp - file), 1502 file, (int) rbytes, nf); 1503 } 1504 } 1505 } 1506 #endif 1507 lseek(fd, 0, SEEK_SET); 1508 1509 if (cflag == 0 || lflag) { 1510 #ifndef SMALL 1511 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) { 1512 maybe_warnx("%s has %d other links -- skipping", 1513 file, isb.st_nlink - 1); 1514 goto lose; 1515 } 1516 if (nflag == 0 && timestamp) 1517 isb.st_mtime = timestamp; 1518 if (check_outfile(outfile) == 0) 1519 goto lose; 1520 #endif 1521 } 1522 1523 if (cflag) 1524 zfd = STDOUT_FILENO; 1525 else if (lflag) 1526 zfd = -1; 1527 else { 1528 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600); 1529 if (zfd == STDOUT_FILENO) { 1530 /* We won't close STDOUT_FILENO later... */ 1531 zfd = dup(zfd); 1532 close(STDOUT_FILENO); 1533 } 1534 if (zfd == -1) { 1535 maybe_warn("can't open %s", outfile); 1536 goto lose; 1537 } 1538 } 1539 1540 switch (method) { 1541 #ifndef NO_BZIP2_SUPPORT 1542 case FT_BZIP2: 1543 /* XXX */ 1544 if (lflag) { 1545 maybe_warnx("no -l with bzip2 files"); 1546 goto lose; 1547 } 1548 1549 size = unbzip2(fd, zfd, NULL, 0, NULL); 1550 break; 1551 #endif 1552 1553 #ifndef NO_COMPRESS_SUPPORT 1554 case FT_Z: { 1555 FILE *in, *out; 1556 1557 /* XXX */ 1558 if (lflag) { 1559 maybe_warnx("no -l with Lempel-Ziv files"); 1560 goto lose; 1561 } 1562 1563 if ((in = zdopen(fd)) == NULL) { 1564 maybe_warn("zdopen for read: %s", file); 1565 goto lose; 1566 } 1567 1568 out = fdopen(dup(zfd), "w"); 1569 if (out == NULL) { 1570 maybe_warn("fdopen for write: %s", outfile); 1571 fclose(in); 1572 goto lose; 1573 } 1574 1575 size = zuncompress(in, out, NULL, 0, NULL); 1576 /* need to fclose() if ferror() is true... */ 1577 if (ferror(in) | fclose(in)) { 1578 maybe_warn("failed infile fclose"); 1579 unlink(outfile); 1580 (void)fclose(out); 1581 } 1582 if (fclose(out) != 0) { 1583 maybe_warn("failed outfile fclose"); 1584 unlink(outfile); 1585 goto lose; 1586 } 1587 break; 1588 } 1589 #endif 1590 1591 #ifndef NO_PACK_SUPPORT 1592 case FT_PACK: 1593 if (lflag) { 1594 maybe_warnx("no -l with packed files"); 1595 goto lose; 1596 } 1597 1598 size = unpack(fd, zfd, NULL, 0, NULL); 1599 break; 1600 #endif 1601 1602 #ifndef NO_XZ_SUPPORT 1603 case FT_XZ: 1604 if (lflag) { 1605 size = unxz_len(fd); 1606 print_list_out(in_size, size, file); 1607 return -1; 1608 } 1609 size = unxz(fd, zfd, NULL, 0, NULL); 1610 break; 1611 #endif 1612 1613 #ifndef NO_LZ_SUPPORT 1614 case FT_LZ: 1615 if (lflag) { 1616 maybe_warnx("no -l with lzip files"); 1617 goto lose; 1618 } 1619 size = unlz(fd, zfd, NULL, 0, NULL); 1620 break; 1621 #endif 1622 #ifndef SMALL 1623 case FT_UNKNOWN: 1624 if (lflag) { 1625 maybe_warnx("no -l for unknown filetypes"); 1626 goto lose; 1627 } 1628 size = cat_fd(NULL, 0, NULL, fd); 1629 break; 1630 #endif 1631 default: 1632 if (lflag) { 1633 print_list(fd, in_size, outfile, isb.st_mtime); 1634 close(fd); 1635 return -1; /* XXX */ 1636 } 1637 1638 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file); 1639 break; 1640 } 1641 1642 if (close(fd) != 0) 1643 maybe_warn("couldn't close input"); 1644 if (zfd != STDOUT_FILENO && close(zfd) != 0) 1645 maybe_warn("couldn't close output"); 1646 1647 if (size == -1) { 1648 if (cflag == 0) 1649 unlink(outfile); 1650 maybe_warnx("%s: uncompress failed", file); 1651 return -1; 1652 } 1653 1654 /* if testing, or we uncompressed to stdout, this is all we need */ 1655 #ifndef SMALL 1656 if (tflag) 1657 return size; 1658 #endif 1659 /* if we are uncompressing to stdin, don't remove the file. */ 1660 if (cflag) 1661 return size; 1662 1663 /* 1664 * if we create a file... 1665 */ 1666 /* 1667 * if we can't stat the file don't remove the file. 1668 */ 1669 1670 ofd = open(outfile, O_RDWR, 0); 1671 if (ofd == -1) { 1672 maybe_warn("couldn't open (leaving original): %s", 1673 outfile); 1674 return -1; 1675 } 1676 if (fstat(ofd, &osb) != 0) { 1677 maybe_warn("couldn't stat (leaving original): %s", 1678 outfile); 1679 close(ofd); 1680 return -1; 1681 } 1682 if (osb.st_size != size) { 1683 maybe_warnx("stat gave different size: %" PRIdOFF 1684 " != %" PRIdOFF " (leaving original)", 1685 size, osb.st_size); 1686 close(ofd); 1687 unlink(outfile); 1688 return -1; 1689 } 1690 unlink_input(file, &isb); 1691 #ifndef SMALL 1692 copymodes(ofd, &isb, outfile); 1693 #endif 1694 close(ofd); 1695 return size; 1696 1697 unexpected_EOF: 1698 maybe_warnx("%s: unexpected end of file", file); 1699 lose: 1700 if (fd != -1) 1701 close(fd); 1702 if (zfd != -1 && zfd != STDOUT_FILENO) 1703 close(fd); 1704 return -1; 1705 } 1706 1707 #ifndef SMALL 1708 static void 1709 check_siginfo(void) 1710 { 1711 static int ttyfd = -2; 1712 char buf[2048]; 1713 int n; 1714 1715 if (print_info == 0) 1716 return; 1717 1718 if (!infile) 1719 goto out; 1720 1721 if (ttyfd == -2) 1722 ttyfd = open(_PATH_TTY, O_RDWR | O_CLOEXEC); 1723 1724 if (ttyfd == -1) 1725 goto out; 1726 1727 if (infile_total) { 1728 const double pcent = (100.0 * infile_current) / infile_total; 1729 1730 n = snprintf(buf, sizeof(buf), 1731 "%s: %s: done %ju/%ju bytes (%3.2f%%)\n", 1732 getprogname(), infile, (uintmax_t)infile_current, 1733 (uintmax_t)infile_total, pcent); 1734 } else { 1735 n = snprintf(buf, sizeof(buf), "%s: %s: done %ju bytes\n", 1736 getprogname(), infile, (uintmax_t)infile_current); 1737 } 1738 1739 if (n <= 0) 1740 goto out; 1741 1742 write(ttyfd, buf, (size_t)n); 1743 out: 1744 print_info = 0; 1745 } 1746 1747 static off_t 1748 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd) 1749 { 1750 char buf[BUFLEN]; 1751 off_t in_tot; 1752 ssize_t w; 1753 1754 in_tot = count; 1755 w = write_retry(STDOUT_FILENO, prepend, count); 1756 if (w == -1 || (size_t)w != count) { 1757 maybe_warn("write to stdout"); 1758 return -1; 1759 } 1760 for (;;) { 1761 ssize_t rv; 1762 1763 rv = read(fd, buf, sizeof buf); 1764 if (rv == 0) 1765 break; 1766 if (rv < 0) { 1767 maybe_warn("read from fd %d", fd); 1768 break; 1769 } 1770 infile_newdata(rv); 1771 1772 if (write_retry(STDOUT_FILENO, buf, rv) != rv) { 1773 maybe_warn("write to stdout"); 1774 break; 1775 } 1776 in_tot += rv; 1777 } 1778 1779 if (gsizep) 1780 *gsizep = in_tot; 1781 return (in_tot); 1782 } 1783 #endif 1784 1785 static void 1786 handle_stdin(void) 1787 { 1788 struct stat isb; 1789 unsigned char fourbytes[4]; 1790 size_t in_size; 1791 off_t usize, gsize; 1792 enum filetype method; 1793 ssize_t bytes_read; 1794 #ifndef NO_COMPRESS_SUPPORT 1795 FILE *in; 1796 #endif 1797 1798 #ifndef SMALL 1799 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) { 1800 maybe_warnx("standard input is a terminal -- ignoring"); 1801 goto out; 1802 } 1803 #endif 1804 1805 if (fstat(STDIN_FILENO, &isb) < 0) { 1806 maybe_warn("fstat"); 1807 goto out; 1808 } 1809 if (S_ISREG(isb.st_mode)) 1810 in_size = isb.st_size; 1811 else 1812 in_size = 0; 1813 infile_set("(stdin)", in_size); 1814 1815 if (lflag) { 1816 print_list(STDIN_FILENO, in_size, infile, isb.st_mtime); 1817 goto out; 1818 } 1819 1820 bytes_read = read_retry(STDIN_FILENO, fourbytes, sizeof fourbytes); 1821 if (bytes_read == -1) { 1822 maybe_warn("can't read stdin"); 1823 goto out; 1824 } else if (bytes_read != sizeof(fourbytes)) { 1825 maybe_warnx("(stdin): unexpected end of file"); 1826 goto out; 1827 } 1828 1829 method = file_gettype(fourbytes); 1830 switch (method) { 1831 default: 1832 #ifndef SMALL 1833 if (fflag == 0) { 1834 maybe_warnx("unknown compression format"); 1835 goto out; 1836 } 1837 usize = cat_fd(fourbytes, sizeof fourbytes, &gsize, STDIN_FILENO); 1838 break; 1839 #endif 1840 case FT_GZIP: 1841 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO, 1842 (char *)fourbytes, sizeof fourbytes, &gsize, "(stdin)"); 1843 break; 1844 #ifndef NO_BZIP2_SUPPORT 1845 case FT_BZIP2: 1846 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO, 1847 (char *)fourbytes, sizeof fourbytes, &gsize); 1848 break; 1849 #endif 1850 #ifndef NO_COMPRESS_SUPPORT 1851 case FT_Z: 1852 if ((in = zdopen(STDIN_FILENO)) == NULL) { 1853 maybe_warnx("zopen of stdin"); 1854 goto out; 1855 } 1856 1857 usize = zuncompress(in, stdout, (char *)fourbytes, 1858 sizeof fourbytes, &gsize); 1859 fclose(in); 1860 break; 1861 #endif 1862 #ifndef NO_PACK_SUPPORT 1863 case FT_PACK: 1864 usize = unpack(STDIN_FILENO, STDOUT_FILENO, 1865 (char *)fourbytes, sizeof fourbytes, &gsize); 1866 break; 1867 #endif 1868 #ifndef NO_XZ_SUPPORT 1869 case FT_XZ: 1870 usize = unxz(STDIN_FILENO, STDOUT_FILENO, 1871 (char *)fourbytes, sizeof fourbytes, &gsize); 1872 break; 1873 #endif 1874 #ifndef NO_LZ_SUPPORT 1875 case FT_LZ: 1876 usize = unlz(STDIN_FILENO, STDOUT_FILENO, 1877 (char *)fourbytes, sizeof fourbytes, &gsize); 1878 break; 1879 #endif 1880 } 1881 1882 #ifndef SMALL 1883 if (vflag && !tflag && usize != -1 && gsize != -1) 1884 print_verbage(NULL, NULL, usize, gsize); 1885 if (vflag && tflag) 1886 print_test("(stdin)", usize != -1); 1887 #else 1888 (void)&usize; 1889 #endif 1890 1891 out: 1892 infile_clear(); 1893 } 1894 1895 static void 1896 handle_stdout(void) 1897 { 1898 off_t gsize; 1899 #ifndef SMALL 1900 off_t usize; 1901 struct stat sb; 1902 time_t systime; 1903 uint32_t mtime; 1904 int ret; 1905 1906 infile_set("<stdout>", 0); 1907 1908 if (fflag == 0 && isatty(STDOUT_FILENO)) { 1909 maybe_warnx("standard output is a terminal -- ignoring"); 1910 return; 1911 } 1912 1913 /* If stdin is a file use its mtime, otherwise use current time */ 1914 ret = fstat(STDIN_FILENO, &sb); 1915 if (ret < 0) { 1916 maybe_warn("Can't stat stdin"); 1917 return; 1918 } 1919 1920 if (S_ISREG(sb.st_mode)) { 1921 infile_set("<stdout>", sb.st_size); 1922 mtime = (uint32_t)sb.st_mtime; 1923 } else { 1924 systime = time(NULL); 1925 if (systime == -1) { 1926 maybe_warn("time"); 1927 return; 1928 } 1929 mtime = (uint32_t)systime; 1930 } 1931 1932 usize = 1933 #endif 1934 gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime); 1935 #ifndef SMALL 1936 if (vflag && !tflag && usize != -1 && gsize != -1) 1937 print_verbage(NULL, NULL, usize, gsize); 1938 #endif 1939 } 1940 1941 /* do what is asked for, for the path name */ 1942 static void 1943 handle_pathname(char *path) 1944 { 1945 char *opath = path, *s = NULL; 1946 ssize_t len; 1947 int slen; 1948 struct stat sb; 1949 1950 /* check for stdout/stdin */ 1951 if (path[0] == '-' && path[1] == '\0') { 1952 if (dflag) 1953 handle_stdin(); 1954 else 1955 handle_stdout(); 1956 return; 1957 } 1958 1959 retry: 1960 if (stat(path, &sb) != 0) { 1961 /* lets try <path>.gz if we're decompressing */ 1962 if (dflag && s == NULL && errno == ENOENT) { 1963 len = strlen(path); 1964 slen = suffixes[0].ziplen; 1965 s = malloc(len + slen + 1); 1966 if (s == NULL) 1967 maybe_err("malloc"); 1968 memcpy(s, path, len); 1969 memcpy(s + len, suffixes[0].zipped, slen + 1); 1970 path = s; 1971 goto retry; 1972 } 1973 maybe_warn("can't stat: %s", opath); 1974 goto out; 1975 } 1976 1977 if (S_ISDIR(sb.st_mode)) { 1978 #ifndef SMALL 1979 if (rflag) 1980 handle_dir(path); 1981 else 1982 #endif 1983 maybe_warnx("%s is a directory", path); 1984 goto out; 1985 } 1986 1987 if (S_ISREG(sb.st_mode)) 1988 handle_file(path, &sb); 1989 else 1990 maybe_warnx("%s is not a regular file", path); 1991 1992 out: 1993 if (s) 1994 free(s); 1995 } 1996 1997 /* compress/decompress a file */ 1998 static void 1999 handle_file(char *file, struct stat *sbp) 2000 { 2001 off_t usize, gsize; 2002 char outfile[PATH_MAX]; 2003 2004 infile_set(file, sbp->st_size); 2005 if (dflag) { 2006 usize = file_uncompress(file, outfile, sizeof(outfile)); 2007 #ifndef SMALL 2008 if (vflag && tflag) 2009 print_test(file, usize != -1); 2010 #endif 2011 if (usize == -1) 2012 return; 2013 gsize = sbp->st_size; 2014 } else { 2015 gsize = file_compress(file, outfile, sizeof(outfile)); 2016 if (gsize == -1) 2017 return; 2018 usize = sbp->st_size; 2019 } 2020 infile_clear(); 2021 2022 #ifndef SMALL 2023 if (vflag && !tflag) 2024 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize); 2025 #endif 2026 } 2027 2028 #ifndef SMALL 2029 /* this is used with -r to recursively descend directories */ 2030 static void 2031 handle_dir(char *dir) 2032 { 2033 char *path_argv[2]; 2034 FTS *fts; 2035 FTSENT *entry; 2036 2037 path_argv[0] = dir; 2038 path_argv[1] = 0; 2039 fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL); 2040 if (fts == NULL) { 2041 warn("couldn't fts_open %s", dir); 2042 return; 2043 } 2044 2045 while ((entry = fts_read(fts))) { 2046 switch(entry->fts_info) { 2047 case FTS_D: 2048 case FTS_DP: 2049 continue; 2050 2051 case FTS_DNR: 2052 case FTS_ERR: 2053 case FTS_NS: 2054 maybe_warn("%s", entry->fts_path); 2055 continue; 2056 case FTS_F: 2057 handle_file(entry->fts_path, entry->fts_statp); 2058 } 2059 } 2060 (void)fts_close(fts); 2061 } 2062 #endif 2063 2064 /* print a ratio - size reduction as a fraction of uncompressed size */ 2065 static void 2066 print_ratio(off_t in, off_t out, FILE *where) 2067 { 2068 int percent10; /* 10 * percent */ 2069 off_t diff; 2070 char buff[8]; 2071 int len; 2072 2073 diff = in - out/2; 2074 if (in == 0 && out == 0) 2075 percent10 = 0; 2076 else if (diff < 0) 2077 /* 2078 * Output is more than double size of input! print -99.9% 2079 * Quite possibly we've failed to get the original size. 2080 */ 2081 percent10 = -999; 2082 else { 2083 /* 2084 * We only need 12 bits of result from the final division, 2085 * so reduce the values until a 32bit division will suffice. 2086 */ 2087 while (in > 0x100000) { 2088 diff >>= 1; 2089 in >>= 1; 2090 } 2091 if (in != 0) 2092 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000; 2093 else 2094 percent10 = 0; 2095 } 2096 2097 len = snprintf(buff, sizeof buff, "%2.2d.", percent10); 2098 /* Move the '.' to before the last digit */ 2099 buff[len - 1] = buff[len - 2]; 2100 buff[len - 2] = '.'; 2101 fprintf(where, "%5s%%", buff); 2102 } 2103 2104 #ifndef SMALL 2105 /* print compression statistics, and the new name (if there is one!) */ 2106 static void 2107 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize) 2108 { 2109 if (file) 2110 fprintf(stderr, "%s:%s ", file, 2111 strlen(file) < 7 ? "\t\t" : "\t"); 2112 print_ratio(usize, gsize, stderr); 2113 if (nfile) 2114 fprintf(stderr, " -- replaced with %s", nfile); 2115 fprintf(stderr, "\n"); 2116 fflush(stderr); 2117 } 2118 2119 /* print test results */ 2120 static void 2121 print_test(const char *file, int ok) 2122 { 2123 2124 if (exit_value == 0 && ok == 0) 2125 exit_value = 1; 2126 fprintf(stderr, "%s:%s %s\n", file, 2127 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK"); 2128 fflush(stderr); 2129 } 2130 #endif 2131 2132 /* print a file's info ala --list */ 2133 /* eg: 2134 compressed uncompressed ratio uncompressed_name 2135 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar 2136 */ 2137 static void 2138 print_list(int fd, off_t out, const char *outfile, time_t ts) 2139 { 2140 static int first = 1; 2141 #ifndef SMALL 2142 static off_t in_tot, out_tot; 2143 uint32_t crc = 0; 2144 #endif 2145 off_t in = 0, rv; 2146 2147 if (first) { 2148 #ifndef SMALL 2149 if (vflag) 2150 printf("method crc date time "); 2151 #endif 2152 if (qflag == 0) 2153 printf(" compressed uncompressed " 2154 "ratio uncompressed_name\n"); 2155 } 2156 first = 0; 2157 2158 /* print totals? */ 2159 #ifndef SMALL 2160 if (fd == -1) { 2161 in = in_tot; 2162 out = out_tot; 2163 } else 2164 #endif 2165 { 2166 /* read the last 4 bytes - this is the uncompressed size */ 2167 rv = lseek(fd, (off_t)(-8), SEEK_END); 2168 if (rv != -1) { 2169 unsigned char buf[8]; 2170 uint32_t usize; 2171 2172 rv = read(fd, (char *)buf, sizeof(buf)); 2173 if (rv == -1) 2174 maybe_warn("read of uncompressed size"); 2175 else if (rv != sizeof(buf)) 2176 maybe_warnx("read of uncompressed size"); 2177 2178 else { 2179 usize = buf[4]; 2180 usize |= (unsigned int)buf[5] << 8; 2181 usize |= (unsigned int)buf[6] << 16; 2182 usize |= (unsigned int)buf[7] << 24; 2183 in = (off_t)usize; 2184 #ifndef SMALL 2185 crc = buf[0]; 2186 crc |= (unsigned int)buf[1] << 8; 2187 crc |= (unsigned int)buf[2] << 16; 2188 crc |= (unsigned int)buf[3] << 24; 2189 #endif 2190 } 2191 } 2192 } 2193 2194 #ifndef SMALL 2195 if (vflag && fd == -1) 2196 printf(" "); 2197 else if (vflag) { 2198 char *date = ctime(&ts); 2199 2200 /* skip the day, 1/100th second, and year */ 2201 date += 4; 2202 date[12] = 0; 2203 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date); 2204 } 2205 in_tot += in; 2206 out_tot += out; 2207 #endif 2208 print_list_out(out, in, outfile); 2209 } 2210 2211 static void 2212 print_list_out(off_t out, off_t in, const char *outfile) 2213 { 2214 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in); 2215 print_ratio(in, out, stdout); 2216 printf(" %s\n", outfile); 2217 } 2218 2219 /* display the usage of NetBSD gzip */ 2220 static void 2221 usage(void) 2222 { 2223 2224 fprintf(stderr, "%s\n", gzip_version); 2225 fprintf(stderr, 2226 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n" 2227 #ifndef SMALL 2228 " -1 --fast fastest (worst) compression\n" 2229 " -2 .. -8 set compression level\n" 2230 " -9 --best best (slowest) compression\n" 2231 " -c --stdout write to stdout, keep original files\n" 2232 " --to-stdout\n" 2233 " -d --decompress uncompress files\n" 2234 " --uncompress\n" 2235 " -f --force force overwriting & compress links\n" 2236 " -h --help display this help\n" 2237 " -k --keep don't delete input files during operation\n" 2238 " -l --list list compressed file contents\n" 2239 " -N --name save or restore original file name and time stamp\n" 2240 " -n --no-name don't save original file name or time stamp\n" 2241 " -q --quiet output no warnings\n" 2242 " -r --recursive recursively compress files in directories\n" 2243 " -S .suf use suffix .suf instead of .gz\n" 2244 " --suffix .suf\n" 2245 " -t --test test compressed file\n" 2246 " -V --version display program version\n" 2247 " -v --verbose print extra statistics\n", 2248 #else 2249 , 2250 #endif 2251 getprogname()); 2252 exit(0); 2253 } 2254 2255 /* display the version of NetBSD gzip */ 2256 static void 2257 display_version(void) 2258 { 2259 2260 fprintf(stderr, "%s\n", gzip_version); 2261 exit(0); 2262 } 2263 2264 #ifndef NO_BZIP2_SUPPORT 2265 #include "unbzip2.c" 2266 #endif 2267 #ifndef NO_COMPRESS_SUPPORT 2268 #include "zuncompress.c" 2269 #endif 2270 #ifndef NO_PACK_SUPPORT 2271 #include "unpack.c" 2272 #endif 2273 #ifndef NO_XZ_SUPPORT 2274 #include "unxz.c" 2275 #endif 2276 #ifndef NO_LZ_SUPPORT 2277 #include "unlz.c" 2278 #endif 2279 2280 static ssize_t 2281 read_retry(int fd, void *buf, size_t sz) 2282 { 2283 char *cp = buf; 2284 size_t left = MIN(sz, (size_t) SSIZE_MAX); 2285 2286 while (left > 0) { 2287 ssize_t ret; 2288 2289 ret = read(fd, cp, left); 2290 if (ret == -1) { 2291 return ret; 2292 } else if (ret == 0) { 2293 break; /* EOF */ 2294 } 2295 cp += ret; 2296 left -= ret; 2297 } 2298 2299 return sz - left; 2300 } 2301 2302 static ssize_t 2303 write_retry(int fd, const void *buf, size_t sz) 2304 { 2305 const char *cp = buf; 2306 size_t left = MIN(sz, (size_t) SSIZE_MAX); 2307 2308 while (left > 0) { 2309 ssize_t ret; 2310 2311 ret = write(fd, cp, left); 2312 if (ret == -1) { 2313 return ret; 2314 } else if (ret == 0) { 2315 abort(); /* Can't happen */ 2316 } 2317 cp += ret; 2318 left -= ret; 2319 } 2320 2321 return sz - left; 2322 } 2323