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

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