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

1.77    ! millert     1: /*     $OpenBSD: main.c,v 1.76 2010/07/28 23:52:01 millert 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.77    ! millert    39: static const char main_rcsid[] = "$OpenBSD: main.c,v 1.76 2010/07/28 23:52:01 millert 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.70      millert    61: int cat, decomp, pipin, force, verbose, testmode, list, recurse, storename;
1.1       mickey     62: extern char *__progname;
                     63:
1.18      mickey     64: const struct compressor {
1.1       mickey     65:        char *name;
                     66:        char *suffix;
1.33      millert    67:        u_char *magic;
1.37      millert    68:        void *(*open)(int, const char *, char *, int, u_int32_t, int);
1.17      millert    69:        int (*read)(void *, char *, int);
                     70:        int (*write)(void *, const char *, int);
1.63      otto       71:        int (*close)(void *, struct z_info *, const char *, struct stat *);
1.1       mickey     72: } c_table[] = {
1.45      tedu       73: #define M_DEFLATE (&c_table[0])
                     74:   { "deflate", ".gz", "\037\213", gz_open, gz_read, gz_write, gz_close },
                     75: #define M_COMPRESS (&c_table[1])
                     76: #ifndef SMALL
1.37      millert    77:   { "compress", ".Z", "\037\235", z_open,  zread,   zwrite,   z_close },
1.45      tedu       78: #endif /* SMALL */
1.18      mickey     79: #if 0
                     80: #define M_LZH (&c_table[2])
1.33      millert    81:   { "lzh", ".lzh", "\037\240", lzh_open, lzh_read, lzh_write, lzh_close },
1.18      mickey     82: #define M_ZIP (&c_table[3])
1.33      millert    83:   { "zip", ".zip", "PK", zip_open, zip_read, zip_write, zip_close },
1.18      mickey     84: #define M_PACK (&c_table[4])
1.33      millert    85:   { "pack", ".pak", "\037\036", pak_open, pak_read, pak_write, pak_close },
1.18      mickey     86: #endif
1.1       mickey     87:   { NULL }
                     88: };
                     89:
1.45      tedu       90: #ifndef SMALL
                     91: const struct compressor null_method =
                     92: { "null", ".nul", "XX", null_open, null_read, null_write, null_close };
                     93: #endif /* SMALL */
                     94:
1.18      mickey     95: int permission(const char *);
1.73      sobrado    96: __dead void usage(int);
1.49      henning    97: int docompress(const char *, char *, const struct compressor *,
1.25      deraadt    98:     int, struct stat *);
1.49      henning    99: int dodecompress(const char *, char *, const struct compressor *,
1.25      deraadt   100:     int, struct stat *);
1.37      millert   101: const struct compressor *check_method(int);
1.36      millert   102: const char *check_suffix(const char *);
                    103: char *set_outfile(const char *, char *, size_t);
1.37      millert   104: void list_stats(const char *, const struct compressor *, struct z_info *);
                    105: void verbose_info(const char *, off_t, off_t, u_int32_t);
1.18      mickey    106:
                    107: const struct option longopts[] = {
1.45      tedu      108: #ifndef SMALL
1.18      mickey    109:        { "ascii",      no_argument,            0, 'a' },
                    110:        { "stdout",     no_argument,            0, 'c' },
                    111:        { "to-stdout",  no_argument,            0, 'c' },
                    112:        { "decompress", no_argument,            0, 'd' },
                    113:        { "uncompress", no_argument,            0, 'd' },
                    114:        { "force",      no_argument,            0, 'f' },
                    115:        { "help",       no_argument,            0, 'h' },
                    116:        { "list",       no_argument,            0, 'l' },
                    117:        { "license",    no_argument,            0, 'L' },
                    118:        { "no-name",    no_argument,            0, 'n' },
                    119:        { "name",       no_argument,            0, 'N' },
                    120:        { "quiet",      no_argument,            0, 'q' },
                    121:        { "recursive",  no_argument,            0, 'r' },
                    122:        { "suffix",     required_argument,      0, 'S' },
                    123:        { "test",       no_argument,            0, 't' },
                    124:        { "verbose",    no_argument,            0, 'v' },
                    125:        { "version",    no_argument,            0, 'V' },
                    126:        { "fast",       no_argument,            0, '1' },
                    127:        { "best",       no_argument,            0, '9' },
1.45      tedu      128: #endif /* SMALL */
1.18      mickey    129:        { NULL }
                    130: };
1.1       mickey    131:
                    132: int
1.24      deraadt   133: main(int argc, char *argv[])
1.1       mickey    134: {
1.19      millert   135:        FTS *ftsp;
                    136:        FTSENT *entry;
1.18      mickey    137:        const struct compressor *method;
1.36      millert   138:        const char *s;
                    139:        char *p, *infile;
1.19      millert   140:        char outfile[MAXPATHLEN], _infile[MAXPATHLEN], suffix[16];
1.77    ! millert   141:        int bits, ch, error, rc, cflag, oflag;
1.72      sobrado   142:        static const char *optstr[3] = {
1.75      naddy     143:                "123456789ab:cdfghLlNnOo:qrS:tVv",
                    144:                "cfhlNno:qrtVv",
1.72      sobrado   145:                "fghqr"
                    146:        };
1.1       mickey    147:
1.73      sobrado   148:        bits = cflag = oflag = 0;
1.70      millert   149:        storename = -1;
1.1       mickey    150:        p = __progname;
                    151:        if (p[0] == 'g') {
                    152:                method = M_DEFLATE;
1.18      mickey    153:                bits = 6;
1.1       mickey    154:                p++;
                    155:        } else
1.45      tedu      156: #ifdef SMALL
                    157:                method = M_DEFLATE;
                    158: #else
1.1       mickey    159:                method = M_COMPRESS;
1.45      tedu      160: #endif /* SMALL */
1.1       mickey    161:
                    162:        decomp = 0;
1.73      sobrado   163:        pmode = MODE_COMP;
1.1       mickey    164:        if (!strcmp(p, "zcat")) {
                    165:                decomp++;
1.66      millert   166:                cflag = 1;
1.73      sobrado   167:                pmode = MODE_CAT;
1.1       mickey    168:        } else {
                    169:                if (p[0] == 'u' && p[1] == 'n') {
                    170:                        p += 2;
                    171:                        decomp++;
1.73      sobrado   172:                        pmode = MODE_DECOMP;
1.1       mickey    173:                }
                    174:
1.2       mickey    175:                if (strcmp(p, "zip") &&
                    176:                    strcmp(p, "compress"))
1.1       mickey    177:                        errx(1, "unknown program name");
                    178:        }
                    179:
1.18      mickey    180:        strlcpy(suffix, method->suffix, sizeof(suffix));
                    181:
1.68      millert   182:        if (method == M_DEFLATE && (p = getenv("GZIP")) != NULL) {
1.77    ! millert   183:                char *evbuf, *last, **nargv = NULL;
        !           184:                int argc_extra = 0, nargc = 0;
1.18      mickey    185:
1.77    ! millert   186:                if ((evbuf = strdup(p)) == NULL)
        !           187:                        err(1, NULL);
        !           188:                for ((p = strtok_r(evbuf, " ", &last)); p != NULL;
        !           189:                    (p = strtok_r(NULL, " ", &last))) {
        !           190:                        if (nargc + 1 >= argc_extra) {
        !           191:                                argc_extra += 1024;
        !           192:                                nargv = realloc(nargv,
        !           193:                                    (argc + argc_extra + 1) * sizeof(char *));
        !           194:                                if (nargv == NULL)
        !           195:                                        err(1, NULL);
        !           196:                        }
        !           197:                        nargv[++nargc] = p;
        !           198:                }
        !           199:                if (nargv != NULL) {
        !           200:                        nargv[0] = *argv++;
        !           201:                        while ((nargv[++nargc] = *argv++))
        !           202:                                ;
        !           203:                        argv = nargv;
        !           204:                        argc = nargc;
        !           205:                }
1.18      mickey    206:        }
                    207:
1.73      sobrado   208:        while ((ch = getopt_long(argc, argv, optstr[pmode], longopts, NULL)) != -1)
1.1       mickey    209:                switch(ch) {
                    210:                case '1':
                    211:                case '2':
                    212:                case '3':
                    213:                case '4':
                    214:                case '5':
                    215:                case '6':
                    216:                case '7':
                    217:                case '8':
                    218:                case '9':
                    219:                        method = M_DEFLATE;
1.18      mickey    220:                        strlcpy(suffix, method->suffix, sizeof(suffix));
1.1       mickey    221:                        bits = ch - '0';
                    222:                        break;
1.18      mickey    223:                case 'a':
                    224:                        warnx("option -a is ignored on this system");
                    225:                        break;
1.1       mickey    226:                case 'b':
                    227:                        bits = strtol(optarg, &p, 10);
1.7       denny     228:                        /*
                    229:                         * POSIX 1002.3 says 9 <= bits <= 14 for portable
                    230:                         * apps, but says the implementation may allow
                    231:                         * greater.
                    232:                         */
1.1       mickey    233:                        if (*p)
                    234:                                errx(1, "illegal bit count -- %s", optarg);
                    235:                        break;
                    236:                case 'c':
1.66      millert   237:                        cflag = 1;
1.1       mickey    238:                        break;
                    239:                case 'd':               /* Backward compatible. */
                    240:                        decomp++;
                    241:                        break;
                    242:                case 'f':
                    243:                        force++;
                    244:                        break;
                    245:                case 'g':
                    246:                        method = M_DEFLATE;
1.18      mickey    247:                        strlcpy(suffix, method->suffix, sizeof(suffix));
                    248:                        bits = 6;
1.1       mickey    249:                        break;
                    250:                case 'l':
                    251:                        list++;
1.71      millert   252:                        testmode = 1;
1.37      millert   253:                        decomp++;
1.1       mickey    254:                        break;
                    255:                case 'n':
1.70      millert   256:                        storename = 0;
1.1       mickey    257:                        break;
                    258:                case 'N':
1.70      millert   259:                        storename = 1;
1.1       mickey    260:                        break;
1.45      tedu      261: #ifndef SMALL
1.1       mickey    262:                case 'O':
                    263:                        method = M_COMPRESS;
1.18      mickey    264:                        strlcpy(suffix, method->suffix, sizeof(suffix));
1.1       mickey    265:                        break;
1.45      tedu      266: #endif /* SMALL */
1.1       mickey    267:                case 'o':
1.18      mickey    268:                        if (strlcpy(outfile, optarg,
                    269:                            sizeof(outfile)) >= sizeof(outfile))
                    270:                                errx(1, "-o argument is too long");
1.20      mickey    271:                        oflag = 1;
1.1       mickey    272:                        break;
                    273:                case 'q':
                    274:                        verbose = -1;
                    275:                        break;
                    276:                case 'S':
                    277:                        p = suffix;
                    278:                        if (optarg[0] != '.')
                    279:                                *p++ = '.';
1.18      mickey    280:                        strlcpy(p, optarg, sizeof(suffix) - (p - suffix));
                    281:                        p = optarg;
1.1       mickey    282:                        break;
                    283:                case 't':
1.20      mickey    284:                        testmode = 1;
1.29      millert   285:                        decomp++;
1.1       mickey    286:                        break;
1.51      henning   287: #ifndef SMALL
1.18      mickey    288:                case 'V':
1.48      millert   289:                        printf("%s\n%s\n", main_rcsid, gz_rcsid);
                    290:                        printf("%s\n%s\n", z_rcsid, null_rcsid);
1.45      tedu      291: #endif
1.19      millert   292:                        exit (0);
1.1       mickey    293:                case 'v':
                    294:                        verbose++;
                    295:                        break;
1.52      henning   296: #ifndef SMALL
1.18      mickey    297:                case 'L':
                    298:                        fputs(copyright, stderr);
                    299:                        fputs(license, stderr);
1.45      tedu      300: #endif
1.19      millert   301:                        exit (0);
1.18      mickey    302:                case 'r':
1.19      millert   303:                        recurse++;
1.18      mickey    304:                        break;
                    305:
1.1       mickey    306:                case 'h':
1.73      sobrado   307:                        usage(0);
1.31      millert   308:                        break;
1.1       mickey    309:                default:
1.73      sobrado   310:                        usage(1);
1.1       mickey    311:                }
                    312:        argc -= optind;
                    313:        argv += optind;
                    314:
1.19      millert   315:        if (argc == 0) {
1.77    ! millert   316:                argv = calloc(2, sizeof(char *));
        !           317:                if (argv == NULL)
        !           318:                        err(1, NULL);
1.66      millert   319:                argv[0] = "-";
1.77    ! millert   320:                argc = 1;
1.19      millert   321:        }
                    322:        if (oflag && (recurse || argc > 1))
                    323:                errx(1, "-o option may only be used with a single input file");
1.20      mickey    324:
1.34      mickey    325:        if ((cat && argc) + testmode + oflag > 1)
1.19      millert   326:                errx(1, "may not mix -o, -c, or -t options");
1.70      millert   327:        /*
                    328:         * By default, when compressing store the original name and timestamp
                    329:         * in the header.  Do not restore these when decompressing unless
                    330:         * the -N option is given.
                    331:         */
                    332:        if (storename == -1)
                    333:                storename = !decomp;
1.19      millert   334:
                    335:        if ((ftsp = fts_open(argv, FTS_PHYSICAL|FTS_NOCHDIR, 0)) == NULL)
                    336:                err(1, NULL);
1.37      millert   337:        for (rc = SUCCESS; (entry = fts_read(ftsp)) != NULL;) {
1.66      millert   338:                cat = cflag;
                    339:                pipin = 0;
1.19      millert   340:                infile = entry->fts_path;
1.67      otto      341:                if (infile[0] == '-' && infile[1] == '\0') {
                    342:                        infile = "stdin";
                    343:                        pipin++;
                    344:                        if (!oflag)
                    345:                                cat = 1;
                    346:                }
                    347:                else
                    348:                        switch (entry->fts_info) {
                    349:                        case FTS_D:
                    350:                                if (!recurse) {
                    351:                                        warnx("%s is a directory: ignored",
                    352:                                            infile);
                    353:                                        fts_set(ftsp, entry, FTS_SKIP);
1.66      millert   354:                                }
1.67      otto      355:                                continue;
                    356:                        case FTS_DP:
                    357:                                continue;
                    358:                        case FTS_NS:
                    359:                                /*
                    360:                                 * If file does not exist and has no suffix,
                    361:                                 * tack on the default suffix and try that.
                    362:                                 */
                    363:                                if (entry->fts_errno == ENOENT) {
                    364:                                        p = strrchr(entry->fts_accpath, '.');
                    365:                                        if ((p == NULL ||
                    366:                                            strcmp(p, suffix) != 0) &&
                    367:                                            snprintf(_infile, sizeof(_infile),
                    368:                                            "%s%s", infile, suffix) <
                    369:                                            sizeof(_infile) &&
                    370:                                            stat(_infile, entry->fts_statp) ==
                    371:                                            0 &&
                    372:                                            S_ISREG(entry->fts_statp->st_mode)) {
                    373:                                                infile = _infile;
                    374:                                                break;
                    375:                                        }
1.66      millert   376:                                }
1.67      otto      377:                        case FTS_ERR:
                    378:                        case FTS_DNR:
                    379:                                warnx("%s: %s", infile,
                    380:                                    strerror(entry->fts_errno));
1.37      millert   381:                                rc = rc ? rc : WARNING;
1.19      millert   382:                                continue;
1.67      otto      383:                        default:
                    384:                                if (!S_ISREG(entry->fts_statp->st_mode) &&
                    385:                                    !(S_ISLNK(entry->fts_statp->st_mode) &&
                    386:                                    cat)) {
                    387:                                        warnx("%s not a regular file%s",
                    388:                                            infile, cat ? "" : ": unchanged");
                    389:                                        rc = rc ? rc : WARNING;
                    390:                                        continue;
                    391:                                }
                    392:                                break;
1.18      mickey    393:                        }
1.1       mickey    394:
1.36      millert   395:                if (!decomp && !pipin && (s = check_suffix(infile)) != NULL) {
                    396:                        warnx("%s already has %s suffix -- unchanged",
                    397:                            infile, s);
1.37      millert   398:                        rc = rc ? rc : WARNING;
1.36      millert   399:                        continue;
                    400:                }
                    401:
1.66      millert   402:                if (!oflag) {
                    403:                        if (cat)
                    404:                                strlcpy(outfile, "stdout", sizeof(outfile));
                    405:                        else if (decomp) {
1.35      millert   406:                                if (set_outfile(infile, outfile,
                    407:                                    sizeof outfile) == NULL) {
1.53      millert   408:                                        if (!recurse) {
1.19      millert   409:                                                warnx("%s: unknown suffix: "
                    410:                                                    "ignored", infile);
1.53      millert   411:                                                rc = rc ? rc : WARNING;
                    412:                                        }
1.19      millert   413:                                        continue;
                    414:                                }
                    415:                        } else {
                    416:                                if (snprintf(outfile, sizeof(outfile),
                    417:                                    "%s%s", infile, suffix) >= sizeof(outfile)) {
                    418:                                        warnx("%s%s: name too long",
                    419:                                            infile, suffix);
1.53      millert   420:                                        rc = rc ? rc : WARNING;
1.19      millert   421:                                        continue;
                    422:                                }
                    423:                        }
1.1       mickey    424:                }
                    425:
1.37      millert   426:                if (verbose > 0 && !pipin && !list)
1.1       mickey    427:                        fprintf(stderr, "%s:\t", infile);
                    428:
1.49      henning   429:                error = (decomp ? dodecompress : docompress)
1.60      deraadt   430:                    (infile, outfile, method, bits, entry->fts_statp);
1.1       mickey    431:
1.37      millert   432:                switch (error) {
                    433:                case SUCCESS:
                    434:                        if (!cat && !testmode) {
                    435:                                if (!pipin && unlink(infile) && verbose >= 0)
1.18      mickey    436:                                        warn("input: %s", infile);
1.1       mickey    437:                        }
1.37      millert   438:                        break;
                    439:                case WARNING:
                    440:                        rc = rc ? rc : WARNING;
                    441:                        break;
                    442:                default:
                    443:                        rc = FAILURE;
                    444:                        break;
1.1       mickey    445:                }
1.19      millert   446:        }
1.37      millert   447:        if (list)
                    448:                list_stats(NULL, NULL, NULL);
1.1       mickey    449:
1.18      mickey    450:        exit(rc);
1.1       mickey    451: }
                    452:
                    453: int
1.49      henning   454: docompress(const char *in, char *out, const struct compressor *method,
1.24      deraadt   455:     int bits, struct stat *sb)
1.1       mickey    456: {
1.59      moritz    457: #ifndef SMALL
1.18      mickey    458:        u_char buf[Z_BUFSIZE];
1.37      millert   459:        char *name;
1.66      millert   460:        int error, ifd, ofd, flags, oreg;
1.16      mpech     461:        void *cookie;
                    462:        ssize_t nr;
1.37      millert   463:        u_int32_t mtime;
                    464:        struct z_info info;
1.66      millert   465:        struct stat osb;
1.1       mickey    466:
1.37      millert   467:        mtime = 0;
1.66      millert   468:        flags = oreg = 0;
1.37      millert   469:        error = SUCCESS;
                    470:        name = NULL;
1.1       mickey    471:        cookie  = NULL;
1.3       mickey    472:
1.66      millert   473:        if (pipin)
                    474:                ifd = dup(STDIN_FILENO);
                    475:        else
                    476:                ifd = open(in, O_RDONLY);
                    477:        if (ifd < 0) {
1.21      millert   478:                if (verbose >= 0)
1.64      millert   479:                        warn("%s", in);
1.37      millert   480:                return (FAILURE);
1.21      millert   481:        }
                    482:
1.66      millert   483:        if (cat)
                    484:                ofd = dup(STDOUT_FILENO);
                    485:        else {
                    486:                if (stat(out, &osb) == 0) {
                    487:                        oreg = S_ISREG(osb.st_mode);
                    488:                        if (!force && oreg && !permission(out)) {
                    489:                                (void) close(ifd);
                    490:                                return (WARNING);
                    491:                        }
                    492:                }
1.76      millert   493:                ofd = open(out, O_WRONLY|O_CREAT|O_TRUNC, S_IWUSR);
1.66      millert   494:        }
                    495:        if (ofd < 0) {
1.3       mickey    496:                if (verbose >= 0)
                    497:                        warn("%s", out);
1.32      mickey    498:                (void) close(ifd);
1.37      millert   499:                return (FAILURE);
1.3       mickey    500:        }
                    501:
1.4       mickey    502:        if (method != M_COMPRESS && !force && isatty(ofd)) {
1.3       mickey    503:                if (verbose >= 0)
                    504:                        warnx("%s: won't write compressed data to terminal",
1.25      deraadt   505:                            out);
1.32      mickey    506:                (void) close(ofd);
                    507:                (void) close(ifd);
1.37      millert   508:                return (FAILURE);
1.3       mickey    509:        }
1.1       mickey    510:
1.70      millert   511:        if (!pipin && storename) {
1.37      millert   512:                name = basename(in);
                    513:                mtime = (u_int32_t)sb->st_mtime;
                    514:        }
                    515:        if ((cookie = (*method->open)(ofd, "w", name, bits, mtime, flags)) == NULL) {
1.32      mickey    516:                if (verbose >= 0)
1.66      millert   517:                        warn("%s", out);
                    518:                if (oreg)
                    519:                        (void) unlink(out);
1.32      mickey    520:                (void) close(ofd);
                    521:                (void) close(ifd);
1.37      millert   522:                return (FAILURE);
1.32      mickey    523:        }
1.1       mickey    524:
1.32      mickey    525:        while ((nr = read(ifd, buf, sizeof(buf))) > 0)
                    526:                if ((method->write)(cookie, buf, nr) != nr) {
                    527:                        if (verbose >= 0)
                    528:                                warn("%s", out);
1.37      millert   529:                        error = FAILURE;
1.32      mickey    530:                        break;
                    531:                }
1.1       mickey    532:
1.32      mickey    533:        if (!error && nr < 0) {
                    534:                if (verbose >= 0)
1.1       mickey    535:                        warn("%s", in);
1.37      millert   536:                error = FAILURE;
1.1       mickey    537:        }
                    538:
1.63      otto      539:        if ((method->close)(cookie, &info, out, sb)) {
1.1       mickey    540:                if (!error && verbose >= 0)
                    541:                        warn("%s", out);
1.37      millert   542:                error = FAILURE;
1.1       mickey    543:        }
                    544:
1.18      mickey    545:        if (close(ifd)) {
                    546:                if (!error && verbose >= 0)
1.32      mickey    547:                        warn("%s", in);
1.37      millert   548:                error = FAILURE;
1.18      mickey    549:        }
1.37      millert   550:
                    551:        if (!force && info.total_out >= info.total_in) {
                    552:                if (verbose > 0)
                    553:                        fprintf(stderr, "file would grow; left unmodified\n");
1.66      millert   554:                (void) unlink(out);
                    555:                error = WARNING;
1.37      millert   556:        }
                    557:
1.66      millert   558:        if (error) {
                    559:                if (oreg)
                    560:                        (void) unlink(out);
                    561:        } else if (verbose > 0)
1.37      millert   562:                verbose_info(out, info.total_out, info.total_in, info.hlen);
1.44      deraadt   563:
1.21      millert   564:        return (error);
1.59      moritz    565: #else
                    566:        warnx("compression not supported");
                    567:        return (FAILURE);
                    568: #endif
1.1       mickey    569: }
                    570:
1.18      mickey    571: const struct compressor *
1.37      millert   572: check_method(int fd)
1.1       mickey    573: {
1.18      mickey    574:        const struct compressor *method;
1.33      millert   575:        u_char magic[2];
1.1       mickey    576:
1.33      millert   577:        if (read(fd, magic, sizeof(magic)) != 2)
                    578:                return (NULL);
                    579:        for (method = &c_table[0]; method->name != NULL; method++) {
                    580:                if (magic[0] == method->magic[0] &&
                    581:                    magic[1] == method->magic[1])
                    582:                        return (method);
                    583:        }
1.45      tedu      584: #ifndef SMALL
                    585:        if (force && cat) {
                    586:                null_magic[0] = magic[0];
                    587:                null_magic[1] = magic[1];
                    588:                return (&null_method);
                    589:        }
                    590: #endif /* SMALL */
1.33      millert   591:        return (NULL);
1.1       mickey    592: }
                    593:
                    594: int
1.49      henning   595: dodecompress(const char *in, char *out, const struct compressor *method,
1.24      deraadt   596:     int bits, struct stat *sb)
1.1       mickey    597: {
1.18      mickey    598:        u_char buf[Z_BUFSIZE];
1.66      millert   599:        char oldname[MAXPATHLEN];
                    600:        int error, oreg, ifd, ofd;
1.16      mpech     601:        void *cookie;
                    602:        ssize_t nr;
1.37      millert   603:        struct z_info info;
1.66      millert   604:        struct stat osb;
1.1       mickey    605:
1.66      millert   606:        oreg = 0;
1.37      millert   607:        error = SUCCESS;
1.1       mickey    608:        cookie = NULL;
                    609:
1.66      millert   610:        if (pipin)
                    611:                ifd = dup(STDIN_FILENO);
                    612:        else
                    613:                ifd = open(in, O_RDONLY);
                    614:        if (ifd < 0) {
1.3       mickey    615:                if (verbose >= 0)
                    616:                        warn("%s", in);
                    617:                return -1;
                    618:        }
                    619:
                    620:        if (!force && isatty(ifd)) {
                    621:                if (verbose >= 0)
                    622:                        warnx("%s: won't read compressed data from terminal",
1.25      deraadt   623:                            in);
1.3       mickey    624:                close (ifd);
                    625:                return -1;
                    626:        }
                    627:
1.37      millert   628:        if ((method = check_method(ifd)) == NULL) {
1.3       mickey    629:                if (verbose >= 0)
                    630:                        warnx("%s: unrecognized file format", in);
1.13      d         631:                close (ifd);
1.3       mickey    632:                return -1;
                    633:        }
                    634:
1.37      millert   635:        /* XXX - open constrains outfile to MAXPATHLEN so this is safe */
1.66      millert   636:        oldname[0] = '\0';
                    637:        if ((cookie = (*method->open)(ifd, "r", oldname, bits, 0, 1)) == NULL) {
1.32      mickey    638:                if (verbose >= 0)
                    639:                        warn("%s", in);
                    640:                close (ifd);
1.37      millert   641:                return (FAILURE);
1.32      mickey    642:        }
1.70      millert   643:        if (storename && oldname[0] != '\0') {
1.74      millert   644:                char *cp = strrchr(out, '/');
                    645:                if (cp != NULL) {
                    646:                        *(cp + 1) = '\0';
                    647:                        strlcat(out, oldname, MAXPATHLEN);
                    648:                } else
                    649:                        strlcpy(out, oldname, MAXPATHLEN);
1.66      millert   650:                cat = 0;                        /* XXX should -c override? */
                    651:        }
1.32      mickey    652:
1.37      millert   653:        if (testmode)
                    654:                ofd = -1;
1.66      millert   655:        else {
                    656:                if (cat)
                    657:                        ofd = dup(STDOUT_FILENO);
                    658:                else {
                    659:                        if (stat(out, &osb) == 0) {
                    660:                                oreg = S_ISREG(osb.st_mode);
                    661:                                if (!force && oreg && !permission(out)) {
                    662:                                        (void) close(ifd);
                    663:                                        return (WARNING);
                    664:                                }
                    665:                        }
                    666:                        ofd = open(out, O_WRONLY|O_CREAT|O_TRUNC, S_IWUSR);
                    667:                }
                    668:                if (ofd < 0) {
                    669:                        if (verbose >= 0)
                    670:                                warn("%s", in);
                    671:                        (method->close)(cookie, NULL, NULL, NULL);
                    672:                        return (FAILURE);
                    673:                }
1.32      mickey    674:        }
                    675:
1.37      millert   676:        while ((nr = (method->read)(cookie, buf, sizeof(buf))) > 0) {
                    677:                if (ofd != -1 && write(ofd, buf, nr) != nr) {
1.21      millert   678:                        if (verbose >= 0)
1.32      mickey    679:                                warn("%s", out);
1.37      millert   680:                        error = FAILURE;
1.32      mickey    681:                        break;
1.21      millert   682:                }
1.37      millert   683:        }
1.1       mickey    684:
1.32      mickey    685:        if (!error && nr < 0) {
                    686:                if (verbose >= 0)
                    687:                        warnx("%s: %s", in,
                    688:                            errno == EINVAL ? "crc error" : strerror(errno));
1.37      millert   689:                error = errno == EINVAL ? WARNING : FAILURE;
1.1       mickey    690:        }
                    691:
1.63      otto      692:        if ((method->close)(cookie, &info, NULL, NULL)) {
1.1       mickey    693:                if (!error && verbose >= 0)
1.32      mickey    694:                        warnx("%s", in);
1.37      millert   695:                error = FAILURE;
                    696:        }
1.70      millert   697:        if (storename && !cat) {
1.40      millert   698:                if (info.mtime != 0) {
                    699:                        sb->st_mtimespec.tv_sec =
                    700:                            sb->st_atimespec.tv_sec = info.mtime;
                    701:                        sb->st_mtimespec.tv_nsec =
                    702:                            sb->st_atimespec.tv_nsec = 0;
                    703:                } else
1.70      millert   704:                        storename = 0;          /* no timestamp to restore */
1.1       mickey    705:        }
1.63      otto      706:        if (error == SUCCESS)
                    707:                setfile(out, ofd, sb);
1.1       mickey    708:
1.37      millert   709:        if (ofd != -1 && close(ofd)) {
1.1       mickey    710:                if (!error && verbose >= 0)
1.18      mickey    711:                        warn("%s", out);
1.37      millert   712:                error = FAILURE;
                    713:        }
                    714:
                    715:        if (!error) {
                    716:                if (list) {
                    717:                        if (info.mtime == 0)
                    718:                                info.mtime = (u_int32_t)sb->st_mtime;
1.43      millert   719:                        list_stats(out, method, &info);
1.37      millert   720:                } else if (verbose > 0) {
                    721:                        verbose_info(out, info.total_in, info.total_out,
                    722:                            info.hlen);
                    723:                }
1.1       mickey    724:        }
                    725:
1.66      millert   726:        /* On error, clean up the file we created but preserve errno. */
                    727:        if (error && oreg)
                    728:                unlink(out);
                    729:
1.21      millert   730:        return (error);
1.1       mickey    731: }
                    732:
                    733: void
1.60      deraadt   734: setfile(const char *name, int fd, struct stat *fs)
1.1       mickey    735: {
1.18      mickey    736:        struct timeval tv[2];
1.1       mickey    737:
1.63      otto      738:        if (name == NULL || cat || testmode)
1.60      deraadt   739:                return;
                    740:
1.40      millert   741:        /*
                    742:         * If input was a pipe we don't have any info to restore but we
                    743:         * must set the mode since the current mode on the file is 0200.
                    744:         */
                    745:        if (pipin) {
                    746:                mode_t mask = umask(022);
1.60      deraadt   747:                fchmod(fd, DEFFILEMODE & ~mask);
1.40      millert   748:                umask(mask);
                    749:                return;
                    750:        }
1.1       mickey    751:
                    752:        /*
                    753:         * Changing the ownership probably won't succeed, unless we're root
                    754:         * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
                    755:         * the mode; current BSD behavior is to remove all setuid bits on
                    756:         * chown.  If chown fails, lose setuid/setgid bits.
                    757:         */
1.40      millert   758:        fs->st_mode &= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
1.60      deraadt   759:        if (fchown(fd, fs->st_uid, fs->st_gid)) {
1.1       mickey    760:                if (errno != EPERM)
1.61      hshoexer  761:                        warn("fchown: %s", name);
1.1       mickey    762:                fs->st_mode &= ~(S_ISUID|S_ISGID);
                    763:        }
1.60      deraadt   764:        if (fchmod(fd, fs->st_mode))
1.61      hshoexer  765:                warn("fchmod: %s", name);
1.1       mickey    766:
1.60      deraadt   767:        if (fs->st_flags && fchflags(fd, fs->st_flags))
1.61      hshoexer  768:                warn("fchflags: %s", name);
1.64      millert   769:
1.69      millert   770:        TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
                    771:        TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
                    772:        if (futimes(fd, tv))
                    773:                warn("futimes: %s", name);
1.1       mickey    774: }
                    775:
                    776: int
1.24      deraadt   777: permission(const char *fname)
1.1       mickey    778: {
                    779:        int ch, first;
                    780:
                    781:        if (!isatty(fileno(stderr)))
                    782:                return (0);
                    783:        (void)fprintf(stderr, "overwrite %s? ", fname);
                    784:        first = ch = getchar();
                    785:        while (ch != '\n' && ch != EOF)
                    786:                ch = getchar();
                    787:        return (first == 'y');
1.35      millert   788: }
                    789:
                    790: /*
1.36      millert   791:  * Check infile for a known suffix and return the suffix portion or NULL.
                    792:  */
                    793: const char *
                    794: check_suffix(const char *infile)
                    795: {
                    796:        int i;
                    797:        char *suf, *sep, *separators = ".-_";
                    798:        static char *suffixes[] = { "Z", "gz", "z", "tgz", "taz", NULL };
                    799:
                    800:        for (sep = separators; *sep != '\0'; sep++) {
                    801:                if ((suf = strrchr(infile, *sep)) == NULL)
                    802:                        continue;
                    803:                suf++;
                    804:
                    805:                for (i = 0; suffixes[i] != NULL; i++) {
                    806:                        if (strcmp(suf, suffixes[i]) == 0)
                    807:                                return (suf - 1);
                    808:                }
                    809:        }
                    810:        return (NULL);
                    811: }
                    812:
                    813: /*
1.35      millert   814:  * Set outfile based on the suffix.  In most cases we just strip
                    815:  * off the suffix but things like .tgz and .taz are special.
                    816:  */
                    817: char *
1.36      millert   818: set_outfile(const char *infile, char *outfile, size_t osize)
1.35      millert   819: {
1.36      millert   820:        const char *s;
                    821:        char *cp;
                    822:
                    823:        if ((s = check_suffix(infile)) == NULL)
1.35      millert   824:                return (NULL);
                    825:
1.36      millert   826:        (void)strlcpy(outfile, infile, osize);
                    827:        cp = outfile + (s - infile) + 1;
                    828:        /*
                    829:         * Convert tgz and taz -> tar, else drop the suffix.
                    830:         */
                    831:        if (strcmp(cp, "tgz") == 0) {
                    832:                cp[1] = 'a';
                    833:                cp[2] = 'r';
                    834:        } else if (strcmp(cp, "taz") == 0)
                    835:                cp[2] = 'r';
                    836:        else
                    837:                cp[-1] = '\0';
                    838:        return (outfile);
1.37      millert   839: }
                    840:
                    841: /*
                    842:  * Print output for the -l option.
                    843:  */
                    844: void
                    845: list_stats(const char *name, const struct compressor *method,
                    846:     struct z_info *info)
                    847: {
                    848:        static off_t compressed_total, uncompressed_total, header_total;
                    849:        static u_int nruns;
                    850:        char *timestr;
1.43      millert   851:
1.37      millert   852:        if (nruns == 0) {
                    853:                if (verbose >= 0) {
                    854:                        if (verbose > 0)
1.48      millert   855:                                fputs("method  crc      date   time  ", stdout);
                    856:                        puts("compressed  uncompressed  ratio  uncompressed_name");
1.37      millert   857:                }
                    858:        }
                    859:        nruns++;
                    860:
                    861:        if (name != NULL) {
                    862:                if (verbose > 0) {
                    863:                        timestr = ctime(&info->mtime) + 4;
                    864:                        timestr[12] = '\0';
1.48      millert   865:                        if (timestr[4] == ' ')
                    866:                                timestr[4] = '0';
                    867:                        printf("%-7.7s %08x %s ", method->name, info->crc,
1.62      deraadt   868:                            timestr);
1.37      millert   869:                }
1.48      millert   870:                printf("%10lld    %10lld  %4.1f%%  %s\n",
1.37      millert   871:                    (long long)(info->total_in + info->hlen),
                    872:                    (long long)info->total_out,
1.57      otto      873:                    ((long long)info->total_out - (long long)info->total_in) *
1.37      millert   874:                    100.0 / info->total_out, name);
                    875:                compressed_total += info->total_in;
                    876:                uncompressed_total += info->total_out;
                    877:                header_total += info->hlen;
                    878:        } else if (verbose >= 0) {
                    879:                if (nruns < 3)          /* only do totals for > 1 files */
                    880:                        return;
                    881:                if (verbose > 0)
1.48      millert   882:                        fputs("                              ", stdout);
                    883:                printf("%10lld    %10lld  %4.1f%%  (totals)\n",
1.37      millert   884:                    (long long)(compressed_total + header_total),
                    885:                    (long long)uncompressed_total,
                    886:                    (uncompressed_total - compressed_total) *
                    887:                    100.0 / uncompressed_total);
                    888:        }
                    889: }
                    890:
                    891: void
                    892: verbose_info(const char *file, off_t compressed, off_t uncompressed,
                    893:     u_int32_t hlen)
                    894: {
                    895:        if (testmode) {
                    896:                fputs("OK\n", stderr);
                    897:                return;
                    898:        }
                    899:        if (!pipin) {
                    900:                fprintf(stderr, "\t%4.1f%% -- replaced with %s\n",
                    901:                    (uncompressed - compressed) * 100.0 / uncompressed, file);
                    902:        }
                    903:        compressed += hlen;
1.44      deraadt   904:        fprintf(stderr, "%lld bytes in, %lld bytes out\n",
1.37      millert   905:            (long long)(decomp ? compressed : uncompressed),
                    906:            (long long)(decomp ? uncompressed : compressed));
1.1       mickey    907: }
                    908:
1.31      millert   909: __dead void
1.73      sobrado   910: usage(int status)
1.1       mickey    911: {
1.73      sobrado   912:        switch (pmode) {
1.72      sobrado   913:        case MODE_COMP:
                    914:                fprintf(stderr, "usage: %s [-123456789cdfghLlNnOqrtVv] "
                    915:                    "[-b bits] [-o filename] [-S suffix]\n"
                    916:                    "       %*s [file ...]\n",
                    917:                    __progname, (int)strlen(__progname), "");
                    918:                break;
                    919:        case MODE_DECOMP:
1.75      naddy     920:                fprintf(stderr, "usage: %s [-cfhlNnqrtVv] [-o filename] "
1.72      sobrado   921:                    "[file ...]\n", __progname);
                    922:                break;
                    923:        case MODE_CAT:
                    924:                fprintf(stderr, "usage: %s [-fghqr] [file ...]\n", __progname);
                    925:                break;
                    926:        }
1.31      millert   927:        exit(status);
1.1       mickey    928: }