[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.53

1.53    ! millert     1: /*     $OpenBSD: main.c,v 1.52 2003/12/16 23:32:24 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.53    ! millert    39: static const char main_rcsid[] = "$OpenBSD: main.c,v 1.52 2003/12/16 23:32:24 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.53    ! millert   389:                                        if (!recurse) {
1.19      millert   390:                                                warnx("%s: unknown suffix: "
                    391:                                                    "ignored", infile);
1.53    ! millert   392:                                                rc = rc ? rc : WARNING;
        !           393:                                        }
1.19      millert   394:                                        continue;
                    395:                                }
                    396:                        } else {
                    397:                                if (snprintf(outfile, sizeof(outfile),
                    398:                                    "%s%s", infile, suffix) >= sizeof(outfile)) {
                    399:                                        warnx("%s%s: name too long",
                    400:                                            infile, suffix);
1.53    ! millert   401:                                        rc = rc ? rc : WARNING;
1.19      millert   402:                                        continue;
                    403:                                }
                    404:                        }
1.1       mickey    405:                }
                    406:
1.19      millert   407:                exists = !stat(outfile, &osb);
                    408:                if (!force && exists && S_ISREG(osb.st_mode) &&
1.37      millert   409:                    !permission(outfile)) {
                    410:                        rc = rc ? rc : WARNING;
1.1       mickey    411:                        continue;
1.37      millert   412:                }
1.1       mickey    413:
1.19      millert   414:                oreg = !exists || S_ISREG(osb.st_mode);
1.1       mickey    415:
1.37      millert   416:                if (verbose > 0 && !pipin && !list)
1.1       mickey    417:                        fprintf(stderr, "%s:\t", infile);
                    418:
1.49      henning   419:                error = (decomp ? dodecompress : docompress)
1.19      millert   420:                        (infile, outfile, method, bits, entry->fts_statp);
1.1       mickey    421:
1.37      millert   422:                switch (error) {
                    423:                case SUCCESS:
                    424:                        if (!cat && !testmode) {
1.19      millert   425:                                setfile(outfile, entry->fts_statp);
1.37      millert   426:                                if (!pipin && unlink(infile) && verbose >= 0)
1.18      mickey    427:                                        warn("input: %s", infile);
1.1       mickey    428:                        }
1.37      millert   429:                        break;
                    430:                case WARNING:
                    431:                        rc = rc ? rc : WARNING;
                    432:                        break;
                    433:                default:
                    434:                        rc = FAILURE;
                    435:                        if (oreg && unlink(outfile) && errno != ENOENT &&
                    436:                            verbose >= 0) {
                    437:                                if (force)
                    438:                                        warn("output: %s", outfile);
                    439:                                else
                    440:                                        err(1, "output: %s", outfile);
                    441:                        }
                    442:                        break;
1.1       mickey    443:                }
1.19      millert   444:        }
1.37      millert   445:        if (list)
                    446:                list_stats(NULL, NULL, NULL);
1.1       mickey    447:
1.18      mickey    448:        exit(rc);
1.1       mickey    449: }
                    450:
                    451: int
1.49      henning   452: docompress(const char *in, char *out, const struct compressor *method,
1.24      deraadt   453:     int bits, struct stat *sb)
1.1       mickey    454: {
1.18      mickey    455:        u_char buf[Z_BUFSIZE];
1.37      millert   456:        char *name;
                    457:        int error, ifd, ofd, flags;
1.16      mpech     458:        void *cookie;
                    459:        ssize_t nr;
1.37      millert   460:        u_int32_t mtime;
                    461:        struct z_info info;
1.1       mickey    462:
1.37      millert   463:        mtime = 0;
                    464:        flags = 0;
                    465:        error = SUCCESS;
                    466:        name = NULL;
1.1       mickey    467:        cookie  = NULL;
1.3       mickey    468:
1.21      millert   469:        if ((ifd = open(in, O_RDONLY)) < 0) {
                    470:                if (verbose >= 0)
                    471:                        warn("%s", out);
1.37      millert   472:                return (FAILURE);
1.21      millert   473:        }
                    474:
1.3       mickey    475:        if ((ofd = open(out, O_WRONLY|O_CREAT, S_IWUSR)) < 0) {
                    476:                if (verbose >= 0)
                    477:                        warn("%s", out);
1.32      mickey    478:                (void) close(ifd);
1.37      millert   479:                return (FAILURE);
1.3       mickey    480:        }
                    481:
1.4       mickey    482:        if (method != M_COMPRESS && !force && isatty(ofd)) {
1.3       mickey    483:                if (verbose >= 0)
                    484:                        warnx("%s: won't write compressed data to terminal",
1.25      deraadt   485:                            out);
1.32      mickey    486:                (void) close(ofd);
                    487:                (void) close(ifd);
1.37      millert   488:                return (FAILURE);
1.3       mickey    489:        }
1.1       mickey    490:
1.38      millert   491:        if (!pipin && !nosave) {
1.37      millert   492:                name = basename(in);
                    493:                mtime = (u_int32_t)sb->st_mtime;
                    494:        }
                    495:        if ((cookie = (*method->open)(ofd, "w", name, bits, mtime, flags)) == NULL) {
1.32      mickey    496:                if (verbose >= 0)
                    497:                        warn("%s", in);
                    498:                (void) close(ofd);
                    499:                (void) close(ifd);
1.37      millert   500:                return (FAILURE);
1.32      mickey    501:        }
1.1       mickey    502:
1.32      mickey    503:        while ((nr = read(ifd, buf, sizeof(buf))) > 0)
                    504:                if ((method->write)(cookie, buf, nr) != nr) {
                    505:                        if (verbose >= 0)
                    506:                                warn("%s", out);
1.37      millert   507:                        error = FAILURE;
1.32      mickey    508:                        break;
                    509:                }
1.1       mickey    510:
1.32      mickey    511:        if (!error && nr < 0) {
                    512:                if (verbose >= 0)
1.1       mickey    513:                        warn("%s", in);
1.37      millert   514:                error = FAILURE;
1.1       mickey    515:        }
                    516:
1.37      millert   517:        if ((method->close)(cookie, &info)) {
1.1       mickey    518:                if (!error && verbose >= 0)
                    519:                        warn("%s", out);
1.37      millert   520:                error = FAILURE;
1.1       mickey    521:        }
                    522:
1.18      mickey    523:        if (close(ifd)) {
                    524:                if (!error && verbose >= 0)
1.32      mickey    525:                        warn("%s", in);
1.37      millert   526:                error = FAILURE;
1.18      mickey    527:        }
1.37      millert   528:
                    529:        if (!force && info.total_out >= info.total_in) {
                    530:                if (verbose > 0)
                    531:                        fprintf(stderr, "file would grow; left unmodified\n");
1.41      millert   532:                error = FAILURE;
1.37      millert   533:        }
                    534:
                    535:        if (!error && verbose > 0)
                    536:                verbose_info(out, info.total_out, info.total_in, info.hlen);
1.44      deraadt   537:
1.21      millert   538:        return (error);
1.1       mickey    539: }
                    540:
1.18      mickey    541: const struct compressor *
1.37      millert   542: check_method(int fd)
1.1       mickey    543: {
1.18      mickey    544:        const struct compressor *method;
1.33      millert   545:        u_char magic[2];
1.1       mickey    546:
1.33      millert   547:        if (read(fd, magic, sizeof(magic)) != 2)
                    548:                return (NULL);
                    549:        for (method = &c_table[0]; method->name != NULL; method++) {
                    550:                if (magic[0] == method->magic[0] &&
                    551:                    magic[1] == method->magic[1])
                    552:                        return (method);
                    553:        }
1.45      tedu      554: #ifndef SMALL
                    555:        if (force && cat) {
                    556:                null_magic[0] = magic[0];
                    557:                null_magic[1] = magic[1];
                    558:                return (&null_method);
                    559:        }
                    560: #endif /* SMALL */
1.33      millert   561:        return (NULL);
1.1       mickey    562: }
                    563:
                    564: int
1.49      henning   565: dodecompress(const char *in, char *out, const struct compressor *method,
1.24      deraadt   566:     int bits, struct stat *sb)
1.1       mickey    567: {
1.18      mickey    568:        u_char buf[Z_BUFSIZE];
                    569:        int error, ifd, ofd;
1.16      mpech     570:        void *cookie;
                    571:        ssize_t nr;
1.37      millert   572:        struct z_info info;
1.1       mickey    573:
1.37      millert   574:        error = SUCCESS;
1.1       mickey    575:        cookie = NULL;
                    576:
1.3       mickey    577:        if ((ifd = open(in, O_RDONLY)) < 0) {
                    578:                if (verbose >= 0)
                    579:                        warn("%s", in);
                    580:                return -1;
                    581:        }
                    582:
                    583:        if (!force && isatty(ifd)) {
                    584:                if (verbose >= 0)
                    585:                        warnx("%s: won't read compressed data from terminal",
1.25      deraadt   586:                            in);
1.3       mickey    587:                close (ifd);
                    588:                return -1;
                    589:        }
                    590:
1.37      millert   591:        if ((method = check_method(ifd)) == NULL) {
1.3       mickey    592:                if (verbose >= 0)
                    593:                        warnx("%s: unrecognized file format", in);
1.13      d         594:                close (ifd);
1.3       mickey    595:                return -1;
                    596:        }
                    597:
1.37      millert   598:        /* XXX - open constrains outfile to MAXPATHLEN so this is safe */
1.38      millert   599:        if ((cookie = (*method->open)(ifd, "r", nosave ? NULL : out,
1.37      millert   600:            bits, 0, 1)) == NULL) {
1.32      mickey    601:                if (verbose >= 0)
                    602:                        warn("%s", in);
                    603:                close (ifd);
1.37      millert   604:                return (FAILURE);
1.32      mickey    605:        }
                    606:
1.37      millert   607:        if (testmode)
                    608:                ofd = -1;
                    609:        else if ((ofd = open(out, O_WRONLY|O_CREAT|O_TRUNC, S_IWUSR)) < 0) {
1.32      mickey    610:                if (verbose >= 0)
                    611:                        warn("%s", in);
1.37      millert   612:                (method->close)(cookie, NULL);
                    613:                return (FAILURE);
1.32      mickey    614:        }
                    615:
1.37      millert   616:        while ((nr = (method->read)(cookie, buf, sizeof(buf))) > 0) {
                    617:                if (ofd != -1 && write(ofd, buf, nr) != nr) {
1.21      millert   618:                        if (verbose >= 0)
1.32      mickey    619:                                warn("%s", out);
1.37      millert   620:                        error = FAILURE;
1.32      mickey    621:                        break;
1.21      millert   622:                }
1.37      millert   623:        }
1.1       mickey    624:
1.32      mickey    625:        if (!error && nr < 0) {
                    626:                if (verbose >= 0)
                    627:                        warnx("%s: %s", in,
                    628:                            errno == EINVAL ? "crc error" : strerror(errno));
1.37      millert   629:                error = errno == EINVAL ? WARNING : FAILURE;
1.1       mickey    630:        }
                    631:
1.37      millert   632:        if ((method->close)(cookie, &info)) {
1.1       mickey    633:                if (!error && verbose >= 0)
1.32      mickey    634:                        warnx("%s", in);
1.37      millert   635:                error = FAILURE;
                    636:        }
                    637:
1.38      millert   638:        if (!nosave) {
1.40      millert   639:                if (info.mtime != 0) {
                    640:                        sb->st_mtimespec.tv_sec =
                    641:                            sb->st_atimespec.tv_sec = info.mtime;
                    642:                        sb->st_mtimespec.tv_nsec =
                    643:                            sb->st_atimespec.tv_nsec = 0;
                    644:                } else
                    645:                        nosave = 1;             /* no timestamp to restore */
                    646:
                    647:                if (cat && strcmp(out, "/dev/stdout") != 0)
                    648:                        cat = 0;                /* have a real output name */
1.1       mickey    649:        }
                    650:
1.37      millert   651:        if (ofd != -1 && close(ofd)) {
1.1       mickey    652:                if (!error && verbose >= 0)
1.18      mickey    653:                        warn("%s", out);
1.37      millert   654:                error = FAILURE;
                    655:        }
                    656:
                    657:        if (!error) {
                    658:                if (list) {
                    659:                        if (info.mtime == 0)
                    660:                                info.mtime = (u_int32_t)sb->st_mtime;
1.43      millert   661:                        list_stats(out, method, &info);
1.37      millert   662:                } else if (verbose > 0) {
                    663:                        verbose_info(out, info.total_in, info.total_out,
                    664:                            info.hlen);
                    665:                }
1.1       mickey    666:        }
                    667:
1.21      millert   668:        return (error);
1.1       mickey    669: }
                    670:
                    671: void
1.24      deraadt   672: setfile(const char *name, struct stat *fs)
1.1       mickey    673: {
1.18      mickey    674:        struct timeval tv[2];
1.1       mickey    675:
1.40      millert   676:        if (!pipin || !nosave) {
                    677:                TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
                    678:                TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
                    679:                if (utimes(name, tv))
                    680:                        warn("utimes: %s", name);
                    681:        }
1.1       mickey    682:
1.40      millert   683:        /*
                    684:         * If input was a pipe we don't have any info to restore but we
                    685:         * must set the mode since the current mode on the file is 0200.
                    686:         */
                    687:        if (pipin) {
                    688:                mode_t mask = umask(022);
                    689:                chmod(name, DEFFILEMODE & ~mask);
                    690:                umask(mask);
                    691:                return;
                    692:        }
1.1       mickey    693:
                    694:        /*
                    695:         * Changing the ownership probably won't succeed, unless we're root
                    696:         * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
                    697:         * the mode; current BSD behavior is to remove all setuid bits on
                    698:         * chown.  If chown fails, lose setuid/setgid bits.
                    699:         */
1.40      millert   700:        fs->st_mode &= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
1.1       mickey    701:        if (chown(name, fs->st_uid, fs->st_gid)) {
                    702:                if (errno != EPERM)
                    703:                        warn("chown: %s", name);
                    704:                fs->st_mode &= ~(S_ISUID|S_ISGID);
                    705:        }
                    706:        if (chmod(name, fs->st_mode))
                    707:                warn("chown: %s", name);
                    708:
1.8       millert   709:        if (fs->st_flags && chflags(name, fs->st_flags))
1.1       mickey    710:                warn("chflags: %s", name);
                    711: }
                    712:
                    713: int
1.24      deraadt   714: permission(const char *fname)
1.1       mickey    715: {
                    716:        int ch, first;
                    717:
                    718:        if (!isatty(fileno(stderr)))
                    719:                return (0);
                    720:        (void)fprintf(stderr, "overwrite %s? ", fname);
                    721:        first = ch = getchar();
                    722:        while (ch != '\n' && ch != EOF)
                    723:                ch = getchar();
                    724:        return (first == 'y');
1.35      millert   725: }
                    726:
                    727: /*
1.36      millert   728:  * Check infile for a known suffix and return the suffix portion or NULL.
                    729:  */
                    730: const char *
                    731: check_suffix(const char *infile)
                    732: {
                    733:        int i;
                    734:        char *suf, *sep, *separators = ".-_";
                    735:        static char *suffixes[] = { "Z", "gz", "z", "tgz", "taz", NULL };
                    736:
                    737:        for (sep = separators; *sep != '\0'; sep++) {
                    738:                if ((suf = strrchr(infile, *sep)) == NULL)
                    739:                        continue;
                    740:                suf++;
                    741:
                    742:                for (i = 0; suffixes[i] != NULL; i++) {
                    743:                        if (strcmp(suf, suffixes[i]) == 0)
                    744:                                return (suf - 1);
                    745:                }
                    746:        }
                    747:        return (NULL);
                    748: }
                    749:
                    750: /*
1.35      millert   751:  * Set outfile based on the suffix.  In most cases we just strip
                    752:  * off the suffix but things like .tgz and .taz are special.
                    753:  */
                    754: char *
1.36      millert   755: set_outfile(const char *infile, char *outfile, size_t osize)
1.35      millert   756: {
1.36      millert   757:        const char *s;
                    758:        char *cp;
                    759:
                    760:        if ((s = check_suffix(infile)) == NULL)
1.35      millert   761:                return (NULL);
                    762:
1.36      millert   763:        (void)strlcpy(outfile, infile, osize);
                    764:        cp = outfile + (s - infile) + 1;
                    765:        /*
                    766:         * Convert tgz and taz -> tar, else drop the suffix.
                    767:         */
                    768:        if (strcmp(cp, "tgz") == 0) {
                    769:                cp[1] = 'a';
                    770:                cp[2] = 'r';
                    771:        } else if (strcmp(cp, "taz") == 0)
                    772:                cp[2] = 'r';
                    773:        else
                    774:                cp[-1] = '\0';
                    775:        return (outfile);
1.37      millert   776: }
                    777:
                    778: /*
                    779:  * Print output for the -l option.
                    780:  */
                    781: void
                    782: list_stats(const char *name, const struct compressor *method,
                    783:     struct z_info *info)
                    784: {
                    785:        static off_t compressed_total, uncompressed_total, header_total;
                    786:        static u_int nruns;
                    787:        char *timestr;
1.43      millert   788:
1.37      millert   789:        if (nruns == 0) {
                    790:                if (verbose >= 0) {
                    791:                        if (verbose > 0)
1.48      millert   792:                                fputs("method  crc      date   time  ", stdout);
                    793:                        puts("compressed  uncompressed  ratio  uncompressed_name");
1.37      millert   794:                }
                    795:        }
                    796:        nruns++;
                    797:
                    798:        if (name != NULL) {
1.48      millert   799:                if (strcmp(name, "/dev/stdout") == 0)
                    800:                        name += 5;
1.37      millert   801:                if (verbose > 0) {
                    802:                        timestr = ctime(&info->mtime) + 4;
                    803:                        timestr[12] = '\0';
1.48      millert   804:                        if (timestr[4] == ' ')
                    805:                                timestr[4] = '0';
                    806:                        printf("%-7.7s %08x %s ", method->name, info->crc,
                    807:                                timestr);
1.37      millert   808:                }
1.48      millert   809:                printf("%10lld    %10lld  %4.1f%%  %s\n",
1.37      millert   810:                    (long long)(info->total_in + info->hlen),
                    811:                    (long long)info->total_out,
                    812:                    (info->total_out - info->total_in) *
                    813:                    100.0 / info->total_out, name);
                    814:                compressed_total += info->total_in;
                    815:                uncompressed_total += info->total_out;
                    816:                header_total += info->hlen;
                    817:        } else if (verbose >= 0) {
                    818:                if (nruns < 3)          /* only do totals for > 1 files */
                    819:                        return;
                    820:                if (verbose > 0)
1.48      millert   821:                        fputs("                              ", stdout);
                    822:                printf("%10lld    %10lld  %4.1f%%  (totals)\n",
1.37      millert   823:                    (long long)(compressed_total + header_total),
                    824:                    (long long)uncompressed_total,
                    825:                    (uncompressed_total - compressed_total) *
                    826:                    100.0 / uncompressed_total);
                    827:        }
                    828: }
                    829:
                    830: void
                    831: verbose_info(const char *file, off_t compressed, off_t uncompressed,
                    832:     u_int32_t hlen)
                    833: {
                    834:        if (testmode) {
                    835:                fputs("OK\n", stderr);
                    836:                return;
                    837:        }
                    838:        if (!pipin) {
                    839:                fprintf(stderr, "\t%4.1f%% -- replaced with %s\n",
                    840:                    (uncompressed - compressed) * 100.0 / uncompressed, file);
                    841:        }
                    842:        compressed += hlen;
1.44      deraadt   843:        fprintf(stderr, "%lld bytes in, %lld bytes out\n",
1.37      millert   844:            (long long)(decomp ? compressed : uncompressed),
                    845:            (long long)(decomp ? uncompressed : compressed));
1.1       mickey    846: }
                    847:
1.31      millert   848: __dead void
                    849: usage(int status)
1.1       mickey    850: {
                    851:        fprintf(stderr,
1.31      millert   852:            "usage: %s [-cdfghOqrtvV] [-b bits] [-S suffix] [-[1-9]] [file ...]\n",
1.18      mickey    853:            __progname);
1.31      millert   854:        exit(status);
1.1       mickey    855: }