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

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