[BACK]Return to main.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / compress

Annotation of src/usr.bin/compress/main.c, Revision 1.52

1.52    ! henning     1: /*     $OpenBSD: main.c,v 1.51 2003/12/16 23:23:50 henning Exp $       */
1.1       mickey      2:
1.52    ! henning     3: #ifndef SMALL
1.18      mickey      4: static const char copyright[] =
                      5: "@(#) Copyright (c) 1992, 1993\n\
                      6:        The Regents of the University of California.  All rights reserved.\n"
                      7: "Copyright (c) 1997-2002 Michael Shalayeff\n";
1.52    ! henning     8: #endif
1.1       mickey      9:
1.45      tedu       10: #ifndef SMALL
1.18      mickey     11: static const char license[] =
                     12: "\n"
                     13: " Redistribution and use in source and binary forms, with or without\n"
                     14: " modification, are permitted provided that the following conditions\n"
                     15: " are met:\n"
                     16: " 1. Redistributions of source code must retain the above copyright\n"
                     17: "    notice, this list of conditions and the following disclaimer.\n"
                     18: " 2. Redistributions in binary form must reproduce the above copyright\n"
                     19: "    notice, this list of conditions and the following disclaimer in the\n"
                     20: "    documentation and/or other materials provided with the distribution.\n"
1.23      deraadt    21: " 3. Neither the name of the University nor the names of its contributors\n"
                     22: "    may be used to endorse or promote products derived from this software\n"
                     23: "    without specific prior written permission.\n"
1.18      mickey     24: "\n"
                     25: " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
                     26: " IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
                     27: " OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
                     28: " IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT,\n"
                     29: " INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n"
                     30: " (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n"
                     31: " SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n"
                     32: " HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n"
                     33: " STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n"
                     34: " IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n"
                     35: " THE POSSIBILITY OF SUCH DAMAGE.\n";
1.45      tedu       36: #endif /* SMALL */
1.1       mickey     37:
1.50      henning    38: #ifndef SMALL
1.52    ! henning    39: static const char main_rcsid[] = "$OpenBSD: main.c,v 1.51 2003/12/16 23:23:50 henning Exp $";
1.1       mickey     40: #endif
                     41:
                     42: #include <sys/param.h>
                     43: #include <sys/time.h>
                     44: #include <sys/stat.h>
                     45:
1.18      mickey     46: #include <getopt.h>
1.1       mickey     47: #include <err.h>
                     48: #include <errno.h>
1.19      millert    49: #include <fts.h>
1.37      millert    50: #include <libgen.h>
1.1       mickey     51: #include <stdio.h>
                     52: #include <stdlib.h>
                     53: #include <string.h>
                     54: #include <unistd.h>
                     55: #include <fcntl.h>
                     56: #include <paths.h>
                     57: #include "compress.h"
                     58:
                     59: #define min(a,b) ((a) < (b)? (a) : (b))
                     60:
1.18      mickey     61: int pipin, force, verbose, testmode, list, nosave;
                     62: int savename, recurse;
1.37      millert    63: int cat, decomp;
1.1       mickey     64: extern char *__progname;
                     65:
1.18      mickey     66: const struct compressor {
1.1       mickey     67:        char *name;
                     68:        char *suffix;
1.33      millert    69:        u_char *magic;
1.37      millert    70:        void *(*open)(int, const char *, char *, int, u_int32_t, int);
1.17      millert    71:        int (*read)(void *, char *, int);
                     72:        int (*write)(void *, const char *, int);
1.37      millert    73:        int (*close)(void *, struct z_info *);
1.1       mickey     74: } c_table[] = {
1.45      tedu       75: #define M_DEFLATE (&c_table[0])
                     76:   { "deflate", ".gz", "\037\213", gz_open, gz_read, gz_write, gz_close },
                     77: #define M_COMPRESS (&c_table[1])
                     78: #ifndef SMALL
1.37      millert    79:   { "compress", ".Z", "\037\235", z_open,  zread,   zwrite,   z_close },
1.45      tedu       80: #endif /* SMALL */
1.18      mickey     81: #if 0
                     82: #define M_LZH (&c_table[2])
1.33      millert    83:   { "lzh", ".lzh", "\037\240", lzh_open, lzh_read, lzh_write, lzh_close },
1.18      mickey     84: #define M_ZIP (&c_table[3])
1.33      millert    85:   { "zip", ".zip", "PK", zip_open, zip_read, zip_write, zip_close },
1.18      mickey     86: #define M_PACK (&c_table[4])
1.33      millert    87:   { "pack", ".pak", "\037\036", pak_open, pak_read, pak_write, pak_close },
1.18      mickey     88: #endif
1.1       mickey     89:   { NULL }
                     90: };
                     91:
1.45      tedu       92: #ifndef SMALL
                     93: const struct compressor null_method =
                     94: { "null", ".nul", "XX", null_open, null_read, null_write, null_close };
                     95: #endif /* SMALL */
                     96:
1.18      mickey     97: int permission(const char *);
                     98: void setfile(const char *, struct stat *);
1.31      millert    99: __dead void usage(int);
1.49      henning   100: int docompress(const char *, char *, const struct compressor *,
1.25      deraadt   101:     int, struct stat *);
1.49      henning   102: int dodecompress(const char *, char *, const struct compressor *,
1.25      deraadt   103:     int, struct stat *);
1.37      millert   104: const struct compressor *check_method(int);
1.36      millert   105: const char *check_suffix(const char *);
                    106: char *set_outfile(const char *, char *, size_t);
1.37      millert   107: void list_stats(const char *, const struct compressor *, struct z_info *);
                    108: void verbose_info(const char *, off_t, off_t, u_int32_t);
1.18      mickey    109:
1.19      millert   110: #define        OPTSTRING       "123456789ab:cdfghlLnNOo:qrS:tvV"
1.18      mickey    111: const struct option longopts[] = {
1.45      tedu      112: #ifndef SMALL
1.18      mickey    113:        { "ascii",      no_argument,            0, 'a' },
                    114:        { "stdout",     no_argument,            0, 'c' },
                    115:        { "to-stdout",  no_argument,            0, 'c' },
                    116:        { "decompress", no_argument,            0, 'd' },
                    117:        { "uncompress", no_argument,            0, 'd' },
                    118:        { "force",      no_argument,            0, 'f' },
                    119:        { "help",       no_argument,            0, 'h' },
                    120:        { "list",       no_argument,            0, 'l' },
                    121:        { "license",    no_argument,            0, 'L' },
                    122:        { "no-name",    no_argument,            0, 'n' },
                    123:        { "name",       no_argument,            0, 'N' },
                    124:        { "quiet",      no_argument,            0, 'q' },
                    125:        { "recursive",  no_argument,            0, 'r' },
                    126:        { "suffix",     required_argument,      0, 'S' },
                    127:        { "test",       no_argument,            0, 't' },
                    128:        { "verbose",    no_argument,            0, 'v' },
                    129:        { "version",    no_argument,            0, 'V' },
                    130:        { "fast",       no_argument,            0, '1' },
                    131:        { "best",       no_argument,            0, '9' },
1.45      tedu      132: #endif /* SMALL */
1.18      mickey    133:        { NULL }
                    134: };
1.1       mickey    135:
                    136: int
1.24      deraadt   137: main(int argc, char *argv[])
1.1       mickey    138: {
1.19      millert   139:        FTS *ftsp;
                    140:        FTSENT *entry;
                    141:        struct stat osb;
1.18      mickey    142:        const struct compressor *method;
1.36      millert   143:        const char *s;
                    144:        char *p, *infile;
1.19      millert   145:        char outfile[MAXPATHLEN], _infile[MAXPATHLEN], suffix[16];
1.18      mickey    146:        char *nargv[512];       /* some estimate based on ARG_MAX */
1.37      millert   147:        int bits, exists, oreg, ch, error, i, rc, oflag;
1.1       mickey    148:
1.48      millert   149:        bits = oflag = 0;
1.38      millert   150:        nosave = -1;
1.1       mickey    151:        p = __progname;
                    152:        if (p[0] == 'g') {
                    153:                method = M_DEFLATE;
1.18      mickey    154:                bits = 6;
1.1       mickey    155:                p++;
                    156:        } else
1.45      tedu      157: #ifdef SMALL
                    158:                method = M_DEFLATE;
                    159: #else
1.1       mickey    160:                method = M_COMPRESS;
1.45      tedu      161: #endif /* SMALL */
1.1       mickey    162:
                    163:        decomp = 0;
                    164:        if (!strcmp(p, "zcat")) {
                    165:                decomp++;
1.20      mickey    166:                cat = 1;
1.1       mickey    167:        } else {
                    168:                if (p[0] == 'u' && p[1] == 'n') {
                    169:                        p += 2;
                    170:                        decomp++;
                    171:                }
                    172:
1.2       mickey    173:                if (strcmp(p, "zip") &&
                    174:                    strcmp(p, "compress"))
1.1       mickey    175:                        errx(1, "unknown program name");
                    176:        }
                    177:
1.18      mickey    178:        strlcpy(suffix, method->suffix, sizeof(suffix));
                    179:
1.19      millert   180:        nargv[0] = NULL;
1.36      millert   181:        if ((p = getenv("GZIP")) != NULL) {
1.18      mickey    182:                char *last;
                    183:
                    184:                nargv[0] = *argv++;
1.36      millert   185:                for (i = 1, (p = strtok_r(p, " ", &last)); p != NULL;
1.18      mickey    186:                    (p = strtok_r(NULL, " ", &last)), i++)
                    187:                        if (i < sizeof(nargv)/sizeof(nargv[1]) - argc - 1)
                    188:                                nargv[i] = p;
                    189:                        else {
                    190:                                errx(1, "GZIP is too long");
                    191:                        }
                    192:                argc += i - 1;
                    193:                while ((nargv[i++] = *argv++))
                    194:                        ;
                    195:                argv = nargv;
                    196:        }
                    197:
                    198:        while ((ch = getopt_long(argc, argv, OPTSTRING, longopts, NULL)) != -1)
1.1       mickey    199:                switch(ch) {
                    200:                case '1':
                    201:                case '2':
                    202:                case '3':
                    203:                case '4':
                    204:                case '5':
                    205:                case '6':
                    206:                case '7':
                    207:                case '8':
                    208:                case '9':
                    209:                        method = M_DEFLATE;
1.18      mickey    210:                        strlcpy(suffix, method->suffix, sizeof(suffix));
1.1       mickey    211:                        bits = ch - '0';
                    212:                        break;
1.18      mickey    213:                case 'a':
                    214:                        warnx("option -a is ignored on this system");
                    215:                        break;
1.1       mickey    216:                case 'b':
                    217:                        bits = strtol(optarg, &p, 10);
1.7       denny     218:                        /*
                    219:                         * POSIX 1002.3 says 9 <= bits <= 14 for portable
                    220:                         * apps, but says the implementation may allow
                    221:                         * greater.
                    222:                         */
1.1       mickey    223:                        if (*p)
                    224:                                errx(1, "illegal bit count -- %s", optarg);
                    225:                        break;
                    226:                case 'c':
1.20      mickey    227:                        cat = 1;
1.1       mickey    228:                        break;
                    229:                case 'd':               /* Backward compatible. */
                    230:                        decomp++;
                    231:                        break;
                    232:                case 'f':
                    233:                        force++;
                    234:                        break;
                    235:                case 'g':
                    236:                        method = M_DEFLATE;
1.18      mickey    237:                        strlcpy(suffix, method->suffix, sizeof(suffix));
                    238:                        bits = 6;
1.1       mickey    239:                        break;
                    240:                case 'l':
                    241:                        list++;
1.37      millert   242:                        testmode++;
                    243:                        decomp++;
1.1       mickey    244:                        break;
                    245:                case 'n':
1.37      millert   246:                        nosave = 1;
1.1       mickey    247:                        break;
                    248:                case 'N':
1.38      millert   249:                        nosave = 0;
1.1       mickey    250:                        break;
1.45      tedu      251: #ifndef SMALL
1.1       mickey    252:                case 'O':
                    253:                        method = M_COMPRESS;
1.18      mickey    254:                        strlcpy(suffix, method->suffix, sizeof(suffix));
1.1       mickey    255:                        break;
1.45      tedu      256: #endif /* SMALL */
1.1       mickey    257:                case 'o':
1.18      mickey    258:                        if (strlcpy(outfile, optarg,
                    259:                            sizeof(outfile)) >= sizeof(outfile))
                    260:                                errx(1, "-o argument is too long");
1.20      mickey    261:                        oflag = 1;
1.1       mickey    262:                        break;
                    263:                case 'q':
                    264:                        verbose = -1;
                    265:                        break;
                    266:                case 'S':
                    267:                        p = suffix;
                    268:                        if (optarg[0] != '.')
                    269:                                *p++ = '.';
1.18      mickey    270:                        strlcpy(p, optarg, sizeof(suffix) - (p - suffix));
                    271:                        p = optarg;
1.1       mickey    272:                        break;
                    273:                case 't':
1.20      mickey    274:                        testmode = 1;
1.29      millert   275:                        decomp++;
1.1       mickey    276:                        break;
1.51      henning   277: #ifndef SMALL
1.18      mickey    278:                case 'V':
1.48      millert   279:                        printf("%s\n%s\n", main_rcsid, gz_rcsid);
                    280:                        printf("%s\n%s\n", z_rcsid, null_rcsid);
1.45      tedu      281: #endif
1.19      millert   282:                        exit (0);
1.1       mickey    283:                case 'v':
                    284:                        verbose++;
                    285:                        break;
1.52    ! henning   286: #ifndef SMALL
1.18      mickey    287:                case 'L':
                    288:                        fputs(copyright, stderr);
                    289:                        fputs(license, stderr);
1.45      tedu      290: #endif
1.19      millert   291:                        exit (0);
1.18      mickey    292:                case 'r':
1.19      millert   293:                        recurse++;
1.18      mickey    294:                        break;
                    295:
1.1       mickey    296:                case 'h':
1.31      millert   297:                        usage(0);
                    298:                        break;
1.1       mickey    299:                default:
1.31      millert   300:                        usage(1);
1.1       mickey    301:                }
                    302:        argc -= optind;
                    303:        argv += optind;
                    304:
1.19      millert   305:        if (argc == 0) {
                    306:                if (nargv[0] == NULL)
                    307:                        argv = nargv;
                    308:                /* XXX - make sure we don't oflow nargv in $GZIP case (millert) */
                    309:                argv[0] = "/dev/stdin";
                    310:                argv[1] = NULL;
                    311:                pipin++;
1.39      millert   312:                if (!oflag)
                    313:                        cat = 1;
1.28      millert   314:        } else {
                    315:                for (i = 0; i < argc; i++) {
                    316:                        if (argv[i][0] == '-' && argv[i][1] == '\0') {
                    317:                                argv[i] = "/dev/stdin";
                    318:                                pipin++;
                    319:                                cat = 1;
                    320:                        }
                    321:                }
1.19      millert   322:        }
                    323:        if (oflag && (recurse || argc > 1))
                    324:                errx(1, "-o option may only be used with a single input file");
1.20      mickey    325:
1.34      mickey    326:        if ((cat && argc) + testmode + oflag > 1)
1.19      millert   327:                errx(1, "may not mix -o, -c, or -t options");
1.38      millert   328:        if (nosave == -1)
                    329:                nosave = decomp;
1.19      millert   330:
                    331:        if ((ftsp = fts_open(argv, FTS_PHYSICAL|FTS_NOCHDIR, 0)) == NULL)
                    332:                err(1, NULL);
1.37      millert   333:        for (rc = SUCCESS; (entry = fts_read(ftsp)) != NULL;) {
1.19      millert   334:                infile = entry->fts_path;
                    335:                switch (entry->fts_info) {
                    336:                case FTS_D:
                    337:                        if (!recurse) {
                    338:                                warnx("%s is a directory: ignored",
                    339:                                    infile);
                    340:                                fts_set(ftsp, entry, FTS_SKIP);
                    341:                        }
                    342:                        continue;
                    343:                case FTS_DP:
                    344:                        continue;
                    345:                case FTS_NS:
                    346:                        /*
                    347:                         * If file does not exist and has no suffix,
                    348:                         * tack on the default suffix and try that.
                    349:                         */
                    350:                        /* XXX - is overwriting fts_statp legal? (millert) */
                    351:                        if (entry->fts_errno == ENOENT &&
                    352:                            strchr(entry->fts_accpath, '.') == NULL &&
                    353:                            snprintf(_infile, sizeof(_infile), "%s%s", infile,
                    354:                            suffix) < sizeof(_infile) &&
                    355:                            stat(_infile, entry->fts_statp) == 0 &&
                    356:                            S_ISREG(entry->fts_statp->st_mode)) {
                    357:                                infile = _infile;
                    358:                                break;
                    359:                        }
                    360:                case FTS_ERR:
                    361:                case FTS_DNR:
                    362:                        warnx("%s: %s", infile, strerror(entry->fts_errno));
1.37      millert   363:                        rc = rc ? rc : WARNING;
1.19      millert   364:                        continue;
                    365:                default:
1.47      henning   366:                        if (!S_ISREG(entry->fts_statp->st_mode) && !pipin &&
                    367:                            !(S_ISLNK(entry->fts_statp->st_mode) && cat)) {
1.27      millert   368:                                warnx("%s not a regular file%s",
1.28      millert   369:                                    infile, cat ? "" : ": unchanged");
1.37      millert   370:                                rc = rc ? rc : WARNING;
1.19      millert   371:                                continue;
1.18      mickey    372:                        }
1.19      millert   373:                        break;
1.9       mickey    374:                }
1.1       mickey    375:
1.36      millert   376:                if (!decomp && !pipin && (s = check_suffix(infile)) != NULL) {
                    377:                        warnx("%s already has %s suffix -- unchanged",
                    378:                            infile, s);
1.37      millert   379:                        rc = rc ? rc : WARNING;
1.36      millert   380:                        continue;
                    381:                }
                    382:
1.37      millert   383:                if (cat)
1.22      deraadt   384:                        strlcpy(outfile, "/dev/stdout", sizeof outfile);
1.19      millert   385:                else if (!oflag) {
                    386:                        if (decomp) {
1.35      millert   387:                                if (set_outfile(infile, outfile,
                    388:                                    sizeof outfile) == NULL) {
1.19      millert   389:                                        if (!recurse)
                    390:                                                warnx("%s: unknown suffix: "
                    391:                                                    "ignored", infile);
                    392:                                        continue;
                    393:                                }
                    394:                        } else {
                    395:                                if (snprintf(outfile, sizeof(outfile),
                    396:                                    "%s%s", infile, suffix) >= sizeof(outfile)) {
                    397:                                        warnx("%s%s: name too long",
                    398:                                            infile, suffix);
                    399:                                        continue;
                    400:                                }
                    401:                        }
1.1       mickey    402:                }
                    403:
1.19      millert   404:                exists = !stat(outfile, &osb);
                    405:                if (!force && exists && S_ISREG(osb.st_mode) &&
1.37      millert   406:                    !permission(outfile)) {
                    407:                        rc = rc ? rc : WARNING;
1.1       mickey    408:                        continue;
1.37      millert   409:                }
1.1       mickey    410:
1.19      millert   411:                oreg = !exists || S_ISREG(osb.st_mode);
1.1       mickey    412:
1.37      millert   413:                if (verbose > 0 && !pipin && !list)
1.1       mickey    414:                        fprintf(stderr, "%s:\t", infile);
                    415:
1.49      henning   416:                error = (decomp ? dodecompress : docompress)
1.19      millert   417:                        (infile, outfile, method, bits, entry->fts_statp);
1.1       mickey    418:
1.37      millert   419:                switch (error) {
                    420:                case SUCCESS:
                    421:                        if (!cat && !testmode) {
1.19      millert   422:                                setfile(outfile, entry->fts_statp);
1.37      millert   423:                                if (!pipin && unlink(infile) && verbose >= 0)
1.18      mickey    424:                                        warn("input: %s", infile);
1.1       mickey    425:                        }
1.37      millert   426:                        break;
                    427:                case WARNING:
                    428:                        rc = rc ? rc : WARNING;
                    429:                        break;
                    430:                default:
                    431:                        rc = FAILURE;
                    432:                        if (oreg && unlink(outfile) && errno != ENOENT &&
                    433:                            verbose >= 0) {
                    434:                                if (force)
                    435:                                        warn("output: %s", outfile);
                    436:                                else
                    437:                                        err(1, "output: %s", outfile);
                    438:                        }
                    439:                        break;
1.1       mickey    440:                }
1.19      millert   441:        }
1.37      millert   442:        if (list)
                    443:                list_stats(NULL, NULL, NULL);
1.1       mickey    444:
1.18      mickey    445:        exit(rc);
1.1       mickey    446: }
                    447:
                    448: int
1.49      henning   449: docompress(const char *in, char *out, const struct compressor *method,
1.24      deraadt   450:     int bits, struct stat *sb)
1.1       mickey    451: {
1.18      mickey    452:        u_char buf[Z_BUFSIZE];
1.37      millert   453:        char *name;
                    454:        int error, ifd, ofd, flags;
1.16      mpech     455:        void *cookie;
                    456:        ssize_t nr;
1.37      millert   457:        u_int32_t mtime;
                    458:        struct z_info info;
1.1       mickey    459:
1.37      millert   460:        mtime = 0;
                    461:        flags = 0;
                    462:        error = SUCCESS;
                    463:        name = NULL;
1.1       mickey    464:        cookie  = NULL;
1.3       mickey    465:
1.21      millert   466:        if ((ifd = open(in, O_RDONLY)) < 0) {
                    467:                if (verbose >= 0)
                    468:                        warn("%s", out);
1.37      millert   469:                return (FAILURE);
1.21      millert   470:        }
                    471:
1.3       mickey    472:        if ((ofd = open(out, O_WRONLY|O_CREAT, S_IWUSR)) < 0) {
                    473:                if (verbose >= 0)
                    474:                        warn("%s", out);
1.32      mickey    475:                (void) close(ifd);
1.37      millert   476:                return (FAILURE);
1.3       mickey    477:        }
                    478:
1.4       mickey    479:        if (method != M_COMPRESS && !force && isatty(ofd)) {
1.3       mickey    480:                if (verbose >= 0)
                    481:                        warnx("%s: won't write compressed data to terminal",
1.25      deraadt   482:                            out);
1.32      mickey    483:                (void) close(ofd);
                    484:                (void) close(ifd);
1.37      millert   485:                return (FAILURE);
1.3       mickey    486:        }
1.1       mickey    487:
1.38      millert   488:        if (!pipin && !nosave) {
1.37      millert   489:                name = basename(in);
                    490:                mtime = (u_int32_t)sb->st_mtime;
                    491:        }
                    492:        if ((cookie = (*method->open)(ofd, "w", name, bits, mtime, flags)) == NULL) {
1.32      mickey    493:                if (verbose >= 0)
                    494:                        warn("%s", in);
                    495:                (void) close(ofd);
                    496:                (void) close(ifd);
1.37      millert   497:                return (FAILURE);
1.32      mickey    498:        }
1.1       mickey    499:
1.32      mickey    500:        while ((nr = read(ifd, buf, sizeof(buf))) > 0)
                    501:                if ((method->write)(cookie, buf, nr) != nr) {
                    502:                        if (verbose >= 0)
                    503:                                warn("%s", out);
1.37      millert   504:                        error = FAILURE;
1.32      mickey    505:                        break;
                    506:                }
1.1       mickey    507:
1.32      mickey    508:        if (!error && nr < 0) {
                    509:                if (verbose >= 0)
1.1       mickey    510:                        warn("%s", in);
1.37      millert   511:                error = FAILURE;
1.1       mickey    512:        }
                    513:
1.37      millert   514:        if ((method->close)(cookie, &info)) {
1.1       mickey    515:                if (!error && verbose >= 0)
                    516:                        warn("%s", out);
1.37      millert   517:                error = FAILURE;
1.1       mickey    518:        }
                    519:
1.18      mickey    520:        if (close(ifd)) {
                    521:                if (!error && verbose >= 0)
1.32      mickey    522:                        warn("%s", in);
1.37      millert   523:                error = FAILURE;
1.18      mickey    524:        }
1.37      millert   525:
                    526:        if (!force && info.total_out >= info.total_in) {
                    527:                if (verbose > 0)
                    528:                        fprintf(stderr, "file would grow; left unmodified\n");
1.41      millert   529:                error = FAILURE;
1.37      millert   530:        }
                    531:
                    532:        if (!error && verbose > 0)
                    533:                verbose_info(out, info.total_out, info.total_in, info.hlen);
1.44      deraadt   534:
1.21      millert   535:        return (error);
1.1       mickey    536: }
                    537:
1.18      mickey    538: const struct compressor *
1.37      millert   539: check_method(int fd)
1.1       mickey    540: {
1.18      mickey    541:        const struct compressor *method;
1.33      millert   542:        u_char magic[2];
1.1       mickey    543:
1.33      millert   544:        if (read(fd, magic, sizeof(magic)) != 2)
                    545:                return (NULL);
                    546:        for (method = &c_table[0]; method->name != NULL; method++) {
                    547:                if (magic[0] == method->magic[0] &&
                    548:                    magic[1] == method->magic[1])
                    549:                        return (method);
                    550:        }
1.45      tedu      551: #ifndef SMALL
                    552:        if (force && cat) {
                    553:                null_magic[0] = magic[0];
                    554:                null_magic[1] = magic[1];
                    555:                return (&null_method);
                    556:        }
                    557: #endif /* SMALL */
1.33      millert   558:        return (NULL);
1.1       mickey    559: }
                    560:
                    561: int
1.49      henning   562: dodecompress(const char *in, char *out, const struct compressor *method,
1.24      deraadt   563:     int bits, struct stat *sb)
1.1       mickey    564: {
1.18      mickey    565:        u_char buf[Z_BUFSIZE];
                    566:        int error, ifd, ofd;
1.16      mpech     567:        void *cookie;
                    568:        ssize_t nr;
1.37      millert   569:        struct z_info info;
1.1       mickey    570:
1.37      millert   571:        error = SUCCESS;
1.1       mickey    572:        cookie = NULL;
                    573:
1.3       mickey    574:        if ((ifd = open(in, O_RDONLY)) < 0) {
                    575:                if (verbose >= 0)
                    576:                        warn("%s", in);
                    577:                return -1;
                    578:        }
                    579:
                    580:        if (!force && isatty(ifd)) {
                    581:                if (verbose >= 0)
                    582:                        warnx("%s: won't read compressed data from terminal",
1.25      deraadt   583:                            in);
1.3       mickey    584:                close (ifd);
                    585:                return -1;
                    586:        }
                    587:
1.37      millert   588:        if ((method = check_method(ifd)) == NULL) {
1.3       mickey    589:                if (verbose >= 0)
                    590:                        warnx("%s: unrecognized file format", in);
1.13      d         591:                close (ifd);
1.3       mickey    592:                return -1;
                    593:        }
                    594:
1.37      millert   595:        /* XXX - open constrains outfile to MAXPATHLEN so this is safe */
1.38      millert   596:        if ((cookie = (*method->open)(ifd, "r", nosave ? NULL : out,
1.37      millert   597:            bits, 0, 1)) == NULL) {
1.32      mickey    598:                if (verbose >= 0)
                    599:                        warn("%s", in);
                    600:                close (ifd);
1.37      millert   601:                return (FAILURE);
1.32      mickey    602:        }
                    603:
1.37      millert   604:        if (testmode)
                    605:                ofd = -1;
                    606:        else if ((ofd = open(out, O_WRONLY|O_CREAT|O_TRUNC, S_IWUSR)) < 0) {
1.32      mickey    607:                if (verbose >= 0)
                    608:                        warn("%s", in);
1.37      millert   609:                (method->close)(cookie, NULL);
                    610:                return (FAILURE);
1.32      mickey    611:        }
                    612:
1.37      millert   613:        while ((nr = (method->read)(cookie, buf, sizeof(buf))) > 0) {
                    614:                if (ofd != -1 && write(ofd, buf, nr) != nr) {
1.21      millert   615:                        if (verbose >= 0)
1.32      mickey    616:                                warn("%s", out);
1.37      millert   617:                        error = FAILURE;
1.32      mickey    618:                        break;
1.21      millert   619:                }
1.37      millert   620:        }
1.1       mickey    621:
1.32      mickey    622:        if (!error && nr < 0) {
                    623:                if (verbose >= 0)
                    624:                        warnx("%s: %s", in,
                    625:                            errno == EINVAL ? "crc error" : strerror(errno));
1.37      millert   626:                error = errno == EINVAL ? WARNING : FAILURE;
1.1       mickey    627:        }
                    628:
1.37      millert   629:        if ((method->close)(cookie, &info)) {
1.1       mickey    630:                if (!error && verbose >= 0)
1.32      mickey    631:                        warnx("%s", in);
1.37      millert   632:                error = FAILURE;
                    633:        }
                    634:
1.38      millert   635:        if (!nosave) {
1.40      millert   636:                if (info.mtime != 0) {
                    637:                        sb->st_mtimespec.tv_sec =
                    638:                            sb->st_atimespec.tv_sec = info.mtime;
                    639:                        sb->st_mtimespec.tv_nsec =
                    640:                            sb->st_atimespec.tv_nsec = 0;
                    641:                } else
                    642:                        nosave = 1;             /* no timestamp to restore */
                    643:
                    644:                if (cat && strcmp(out, "/dev/stdout") != 0)
                    645:                        cat = 0;                /* have a real output name */
1.1       mickey    646:        }
                    647:
1.37      millert   648:        if (ofd != -1 && close(ofd)) {
1.1       mickey    649:                if (!error && verbose >= 0)
1.18      mickey    650:                        warn("%s", out);
1.37      millert   651:                error = FAILURE;
                    652:        }
                    653:
                    654:        if (!error) {
                    655:                if (list) {
                    656:                        if (info.mtime == 0)
                    657:                                info.mtime = (u_int32_t)sb->st_mtime;
1.43      millert   658:                        list_stats(out, method, &info);
1.37      millert   659:                } else if (verbose > 0) {
                    660:                        verbose_info(out, info.total_in, info.total_out,
                    661:                            info.hlen);
                    662:                }
1.1       mickey    663:        }
                    664:
1.21      millert   665:        return (error);
1.1       mickey    666: }
                    667:
                    668: void
1.24      deraadt   669: setfile(const char *name, struct stat *fs)
1.1       mickey    670: {
1.18      mickey    671:        struct timeval tv[2];
1.1       mickey    672:
1.40      millert   673:        if (!pipin || !nosave) {
                    674:                TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
                    675:                TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
                    676:                if (utimes(name, tv))
                    677:                        warn("utimes: %s", name);
                    678:        }
1.1       mickey    679:
1.40      millert   680:        /*
                    681:         * If input was a pipe we don't have any info to restore but we
                    682:         * must set the mode since the current mode on the file is 0200.
                    683:         */
                    684:        if (pipin) {
                    685:                mode_t mask = umask(022);
                    686:                chmod(name, DEFFILEMODE & ~mask);
                    687:                umask(mask);
                    688:                return;
                    689:        }
1.1       mickey    690:
                    691:        /*
                    692:         * Changing the ownership probably won't succeed, unless we're root
                    693:         * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
                    694:         * the mode; current BSD behavior is to remove all setuid bits on
                    695:         * chown.  If chown fails, lose setuid/setgid bits.
                    696:         */
1.40      millert   697:        fs->st_mode &= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
1.1       mickey    698:        if (chown(name, fs->st_uid, fs->st_gid)) {
                    699:                if (errno != EPERM)
                    700:                        warn("chown: %s", name);
                    701:                fs->st_mode &= ~(S_ISUID|S_ISGID);
                    702:        }
                    703:        if (chmod(name, fs->st_mode))
                    704:                warn("chown: %s", name);
                    705:
1.8       millert   706:        if (fs->st_flags && chflags(name, fs->st_flags))
1.1       mickey    707:                warn("chflags: %s", name);
                    708: }
                    709:
                    710: int
1.24      deraadt   711: permission(const char *fname)
1.1       mickey    712: {
                    713:        int ch, first;
                    714:
                    715:        if (!isatty(fileno(stderr)))
                    716:                return (0);
                    717:        (void)fprintf(stderr, "overwrite %s? ", fname);
                    718:        first = ch = getchar();
                    719:        while (ch != '\n' && ch != EOF)
                    720:                ch = getchar();
                    721:        return (first == 'y');
1.35      millert   722: }
                    723:
                    724: /*
1.36      millert   725:  * Check infile for a known suffix and return the suffix portion or NULL.
                    726:  */
                    727: const char *
                    728: check_suffix(const char *infile)
                    729: {
                    730:        int i;
                    731:        char *suf, *sep, *separators = ".-_";
                    732:        static char *suffixes[] = { "Z", "gz", "z", "tgz", "taz", NULL };
                    733:
                    734:        for (sep = separators; *sep != '\0'; sep++) {
                    735:                if ((suf = strrchr(infile, *sep)) == NULL)
                    736:                        continue;
                    737:                suf++;
                    738:
                    739:                for (i = 0; suffixes[i] != NULL; i++) {
                    740:                        if (strcmp(suf, suffixes[i]) == 0)
                    741:                                return (suf - 1);
                    742:                }
                    743:        }
                    744:        return (NULL);
                    745: }
                    746:
                    747: /*
1.35      millert   748:  * Set outfile based on the suffix.  In most cases we just strip
                    749:  * off the suffix but things like .tgz and .taz are special.
                    750:  */
                    751: char *
1.36      millert   752: set_outfile(const char *infile, char *outfile, size_t osize)
1.35      millert   753: {
1.36      millert   754:        const char *s;
                    755:        char *cp;
                    756:
                    757:        if ((s = check_suffix(infile)) == NULL)
1.35      millert   758:                return (NULL);
                    759:
1.36      millert   760:        (void)strlcpy(outfile, infile, osize);
                    761:        cp = outfile + (s - infile) + 1;
                    762:        /*
                    763:         * Convert tgz and taz -> tar, else drop the suffix.
                    764:         */
                    765:        if (strcmp(cp, "tgz") == 0) {
                    766:                cp[1] = 'a';
                    767:                cp[2] = 'r';
                    768:        } else if (strcmp(cp, "taz") == 0)
                    769:                cp[2] = 'r';
                    770:        else
                    771:                cp[-1] = '\0';
                    772:        return (outfile);
1.37      millert   773: }
                    774:
                    775: /*
                    776:  * Print output for the -l option.
                    777:  */
                    778: void
                    779: list_stats(const char *name, const struct compressor *method,
                    780:     struct z_info *info)
                    781: {
                    782:        static off_t compressed_total, uncompressed_total, header_total;
                    783:        static u_int nruns;
                    784:        char *timestr;
1.43      millert   785:
1.37      millert   786:        if (nruns == 0) {
                    787:                if (verbose >= 0) {
                    788:                        if (verbose > 0)
1.48      millert   789:                                fputs("method  crc      date   time  ", stdout);
                    790:                        puts("compressed  uncompressed  ratio  uncompressed_name");
1.37      millert   791:                }
                    792:        }
                    793:        nruns++;
                    794:
                    795:        if (name != NULL) {
1.48      millert   796:                if (strcmp(name, "/dev/stdout") == 0)
                    797:                        name += 5;
1.37      millert   798:                if (verbose > 0) {
                    799:                        timestr = ctime(&info->mtime) + 4;
                    800:                        timestr[12] = '\0';
1.48      millert   801:                        if (timestr[4] == ' ')
                    802:                                timestr[4] = '0';
                    803:                        printf("%-7.7s %08x %s ", method->name, info->crc,
                    804:                                timestr);
1.37      millert   805:                }
1.48      millert   806:                printf("%10lld    %10lld  %4.1f%%  %s\n",
1.37      millert   807:                    (long long)(info->total_in + info->hlen),
                    808:                    (long long)info->total_out,
                    809:                    (info->total_out - info->total_in) *
                    810:                    100.0 / info->total_out, name);
                    811:                compressed_total += info->total_in;
                    812:                uncompressed_total += info->total_out;
                    813:                header_total += info->hlen;
                    814:        } else if (verbose >= 0) {
                    815:                if (nruns < 3)          /* only do totals for > 1 files */
                    816:                        return;
                    817:                if (verbose > 0)
1.48      millert   818:                        fputs("                              ", stdout);
                    819:                printf("%10lld    %10lld  %4.1f%%  (totals)\n",
1.37      millert   820:                    (long long)(compressed_total + header_total),
                    821:                    (long long)uncompressed_total,
                    822:                    (uncompressed_total - compressed_total) *
                    823:                    100.0 / uncompressed_total);
                    824:        }
                    825: }
                    826:
                    827: void
                    828: verbose_info(const char *file, off_t compressed, off_t uncompressed,
                    829:     u_int32_t hlen)
                    830: {
                    831:        if (testmode) {
                    832:                fputs("OK\n", stderr);
                    833:                return;
                    834:        }
                    835:        if (!pipin) {
                    836:                fprintf(stderr, "\t%4.1f%% -- replaced with %s\n",
                    837:                    (uncompressed - compressed) * 100.0 / uncompressed, file);
                    838:        }
                    839:        compressed += hlen;
1.44      deraadt   840:        fprintf(stderr, "%lld bytes in, %lld bytes out\n",
1.37      millert   841:            (long long)(decomp ? compressed : uncompressed),
                    842:            (long long)(decomp ? uncompressed : compressed));
1.1       mickey    843: }
                    844:
1.31      millert   845: __dead void
                    846: usage(int status)
1.1       mickey    847: {
                    848:        fprintf(stderr,
1.31      millert   849:            "usage: %s [-cdfghOqrtvV] [-b bits] [-S suffix] [-[1-9]] [file ...]\n",
1.18      mickey    850:            __progname);
1.31      millert   851:        exit(status);
1.1       mickey    852: }