Home | History | Annotate | Line # | Download | only in compress
compress.c revision 1.24
      1 /*	$NetBSD: compress.c,v 1.24 2008/07/21 14:19:22 lukem Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1992, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 __COPYRIGHT("@(#) Copyright (c) 1992, 1993\
     35  The Regents of the University of California.  All rights reserved.");
     36 #endif /* not lint */
     37 
     38 #ifndef lint
     39 #if 0
     40 static char sccsid[] = "@(#)compress.c	8.2 (Berkeley) 1/7/94";
     41 #else
     42 __RCSID("$NetBSD: compress.c,v 1.24 2008/07/21 14:19:22 lukem Exp $");
     43 #endif
     44 #endif /* not lint */
     45 
     46 #include <sys/param.h>
     47 #include <sys/time.h>
     48 #include <sys/stat.h>
     49 
     50 #include <err.h>
     51 #include <errno.h>
     52 #include <stdarg.h>
     53 #include <stdio.h>
     54 #include <stdlib.h>
     55 #include <string.h>
     56 #include <unistd.h>
     57 
     58 void	compress(char *, char *, int);
     59 void	cwarn(const char *, ...) __attribute__((__format__(__printf__,1,2)));
     60 void	cwarnx(const char *, ...) __attribute__((__format__(__printf__,1,2)));
     61 void	decompress(char *, char *, int);
     62 int	permission(char *);
     63 void	setfile(char *, struct stat *);
     64 void	usage(int);
     65 
     66 int	main(int, char *[]);
     67 extern FILE *zopen(const char *fname, const char *mode, int bits);
     68 
     69 int eval, force, verbose;
     70 int isstdout, isstdin;
     71 
     72 int
     73 main(int argc, char **argv)
     74 {
     75         enum {COMPRESS, DECOMPRESS} style = COMPRESS;
     76 	size_t len;
     77 	int bits, cat, ch;
     78 	char *p, newname[MAXPATHLEN];
     79 
     80 	if ((p = strrchr(argv[0], '/')) == NULL)
     81 		p = argv[0];
     82 	else
     83 		++p;
     84 	if (!strcmp(p, "uncompress"))
     85 		style = DECOMPRESS;
     86         else if (!strcmp(p, "compress"))
     87                 style = COMPRESS;
     88         else if (!strcmp(p, "zcat")) {
     89                 style = DECOMPRESS;
     90                 cat = 1;
     91         }
     92 	else
     93 		errx(1, "unknown program name");
     94 
     95 	bits = cat = 0;
     96 	while ((ch = getopt(argc, argv, "b:cdfv")) != -1)
     97 		switch(ch) {
     98 		case 'b':
     99 			bits = strtol(optarg, &p, 10);
    100 			if (*p)
    101 				errx(1, "illegal bit count -- %s", optarg);
    102 			break;
    103 		case 'c':
    104 			cat = 1;
    105 			break;
    106 		case 'd':		/* Backward compatible. */
    107 			style = DECOMPRESS;
    108 			break;
    109 		case 'f':
    110 			force = 1;
    111 			break;
    112 		case 'v':
    113 			verbose = 1;
    114 			break;
    115 		case '?':
    116 		default:
    117 			usage(style == COMPRESS);
    118 		}
    119 	argc -= optind;
    120 	argv += optind;
    121 
    122 	if (argc == 0) {
    123 		switch(style) {
    124 		case COMPRESS:
    125 			isstdout = 1;
    126 			isstdin = 1;
    127 			(void)compress("/dev/stdin", "/dev/stdout", bits);
    128 			break;
    129 		case DECOMPRESS:
    130 			isstdout = 1;
    131 			isstdin = 1;
    132 			(void)decompress("/dev/stdin", "/dev/stdout", bits);
    133 			break;
    134 		}
    135 		exit (eval);
    136 	}
    137 
    138 	if (cat == 1 && argc > 1)
    139 		errx(1, "the -c option permits only a single file argument");
    140 
    141 	for (; *argv; ++argv) {
    142 		isstdout = 0;
    143 		switch(style) {
    144 		case COMPRESS:
    145 			if (cat) {
    146 				isstdout = 1;
    147 				compress(*argv, "/dev/stdout", bits);
    148 				break;
    149 			}
    150 			if ((p = strrchr(*argv, '.')) != NULL &&
    151 			    !strcmp(p, ".Z")) {
    152 				cwarnx("%s: name already has trailing .Z",
    153 				    *argv);
    154 				break;
    155 			}
    156 			len = strlen(*argv);
    157 			if (len > sizeof(newname) - 3) {
    158 				cwarnx("%s: name too long", *argv);
    159 				break;
    160 			}
    161 			memmove(newname, *argv, len);
    162 			newname[len] = '.';
    163 			newname[len + 1] = 'Z';
    164 			newname[len + 2] = '\0';
    165 			compress(*argv, newname, bits);
    166 			break;
    167 		case DECOMPRESS:
    168 			len = strlen(*argv);
    169 			if ((p = strrchr(*argv, '.')) == NULL ||
    170 			    strcmp(p, ".Z")) {
    171 				if (len > sizeof(newname) - 3) {
    172 					cwarnx("%s: name too long", *argv);
    173 					break;
    174 				}
    175 				memmove(newname, *argv, len);
    176 				newname[len] = '.';
    177 				newname[len + 1] = 'Z';
    178 				newname[len + 2] = '\0';
    179 				decompress(newname,
    180 				    cat ? "/dev/stdout" : *argv, bits);
    181 				if (cat)
    182 					isstdout = 1;
    183 			} else {
    184 				if (len - 2 > sizeof(newname) - 1) {
    185 					cwarnx("%s: name too long", *argv);
    186 					break;
    187 				}
    188 				memmove(newname, *argv, len - 2);
    189 				newname[len - 2] = '\0';
    190 				decompress(*argv,
    191 				    cat ? "/dev/stdout" : newname, bits);
    192 				if (cat)
    193 					isstdout = 1;
    194 			}
    195 			break;
    196 		}
    197 	}
    198 	exit (eval);
    199 }
    200 
    201 void
    202 compress(char *in, char *out, int bits)
    203 {
    204 	int nr;
    205 	struct stat isb, sb;
    206 	const char *error = NULL;
    207 	FILE *ifp, *ofp;
    208 	int exists, isreg, oreg;
    209 	u_char buf[BUFSIZ];
    210 
    211 	if (!isstdout) {
    212 		exists = !stat(out, &sb);
    213 		if (!force && exists && S_ISREG(sb.st_mode) && !permission(out))
    214 			return;
    215 		oreg = !exists || S_ISREG(sb.st_mode);
    216 	} else
    217 		oreg = 0;
    218 
    219 	ifp = ofp = NULL;
    220 	if ((ifp = fopen(in, "r")) == NULL) {
    221 		cwarn("%s", in);
    222 		return;
    223 	}
    224 
    225 	if (!isstdin) {
    226 		if (stat(in, &isb)) {		/* DON'T FSTAT! */
    227 			cwarn("%s", in);
    228 			goto err;
    229 		}
    230 		if (!S_ISREG(isb.st_mode))
    231 			isreg = 0;
    232 		else
    233 			isreg = 1;
    234 	} else
    235 		isreg = 0;
    236 
    237 	if ((ofp = zopen(out, "w", bits)) == NULL) {
    238 		cwarn("%s", out);
    239 		goto err;
    240 	}
    241 	oreg <<= 1;
    242 	while ((nr = fread(buf, 1, sizeof(buf), ifp)) != 0)
    243 		if (fwrite(buf, 1, nr, ofp) != nr) {
    244 			cwarn("%s", out);
    245 			goto err;
    246 		}
    247 
    248 	if (ferror(ifp))
    249 		error = in;
    250 	if (fclose(ifp))
    251 		if (error == NULL)
    252 			error = in;
    253 	if (fclose(ofp))
    254 		if (error == NULL)
    255 			error = out;
    256 	ifp = NULL;
    257 	ofp = NULL;
    258 	if (error) {
    259 		cwarn("%s", error);
    260 		goto err;
    261 	}
    262 
    263 	if (isreg && oreg) {
    264 		if (stat(out, &sb)) {
    265 			cwarn("%s", out);
    266 			goto err;
    267 		}
    268 
    269 		if (!force && sb.st_size >= isb.st_size) {
    270 			if (verbose)
    271 		(void)printf("%s: file would grow; left unmodified\n", in);
    272 			goto err;
    273 		}
    274 
    275 		setfile(out, &isb);
    276 
    277 		if (unlink(in))
    278 			cwarn("%s", in);
    279 
    280 		if (verbose) {
    281 			(void)printf("%s: ", out);
    282 			if (isb.st_size > sb.st_size)
    283 				(void)printf("%.0f%% compression\n",
    284 				    ((double)sb.st_size / isb.st_size) * 100.0);
    285 			else
    286 				(void)printf("%.0f%% expansion\n",
    287 				    ((double)isb.st_size / sb.st_size) * 100.0);
    288 		}
    289 	}
    290 	return;
    291 
    292 err:	if (ofp)
    293 		(void)fclose(ofp);
    294 	if (oreg == 2)
    295 		(void)unlink(out);
    296 	if (ifp)
    297 		(void)fclose(ifp);
    298 }
    299 
    300 void
    301 decompress(char *in, char *out, int bits)
    302 {
    303 	int nr;
    304 	struct stat sb;
    305 	FILE *ifp, *ofp;
    306 	int exists, isreg, oreg;
    307 	u_char buf[BUFSIZ];
    308 
    309 	if (!isstdout) {
    310 		exists = !stat(out, &sb);
    311 		if (!force && exists && S_ISREG(sb.st_mode) && !permission(out))
    312 			return;
    313 		oreg = !exists || S_ISREG(sb.st_mode);
    314 	} else
    315 		oreg = 0;
    316 
    317 	ifp = ofp = NULL;
    318 	if ((ofp = fopen(out, "w")) == NULL) {
    319 		cwarn("%s", out);
    320 		return;
    321 	}
    322 
    323 	if ((ifp = zopen(in, "r", bits)) == NULL) {
    324 		cwarn("%s", in);
    325 		goto err;
    326 	}
    327 	if (!isstdin) {
    328 		if (stat(in, &sb)) {
    329 			cwarn("%s", in);
    330 			goto err;
    331 		}
    332 		if (!S_ISREG(sb.st_mode))
    333 			isreg = 0;
    334 		else
    335 			isreg = 1;
    336 	} else
    337 		isreg = 0;
    338 
    339 	oreg <<= 1;
    340 	while ((nr = fread(buf, 1, sizeof(buf), ifp)) != 0)
    341 		if (fwrite(buf, 1, nr, ofp) != nr) {
    342 			cwarn("%s", out);
    343 			goto err;
    344 		}
    345 
    346 	if (ferror(ifp)) {
    347 		cwarn("%s", in);
    348 		goto err;
    349 	}
    350 	if (fclose(ifp)) {
    351 		ifp = NULL;
    352 		cwarn("%s", in);
    353 		goto err;
    354 	}
    355 	ifp = NULL;
    356 
    357 	if (fclose(ofp)) {
    358 		ofp = NULL;
    359 		cwarn("%s", out);
    360 		goto err;
    361 	}
    362 
    363 	if (isreg && oreg) {
    364 		setfile(out, &sb);
    365 
    366 		if (unlink(in))
    367 			cwarn("%s", in);
    368 	}
    369 	return;
    370 
    371 err:	if (ofp)
    372 		(void)fclose(ofp);
    373 	if (oreg == 2)
    374 		(void)unlink(out);
    375 	if (ifp)
    376 		(void)fclose(ifp);
    377 }
    378 
    379 void
    380 setfile(char *name, struct stat *fs)
    381 {
    382 	static struct timeval tv[2];
    383 
    384 	fs->st_mode &= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
    385 
    386 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
    387 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
    388 	if (utimes(name, tv))
    389 		cwarn("utimes: %s", name);
    390 
    391 	/*
    392 	 * Changing the ownership probably won't succeed, unless we're root
    393 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
    394 	 * the mode; current BSD behavior is to remove all setuid bits on
    395 	 * chown.  If chown fails, lose setuid/setgid bits.
    396 	 */
    397 	if (chown(name, fs->st_uid, fs->st_gid)) {
    398 		if (errno != EPERM)
    399 			cwarn("chown: %s", name);
    400 		fs->st_mode &= ~(S_ISUID|S_ISGID);
    401 	}
    402 	if (chmod(name, fs->st_mode))
    403 		cwarn("chown: %s", name);
    404 
    405 	/*
    406 	 * Restore the file's flags.  However, do this only if the original
    407 	 * file had any flags set; this avoids a warning on file-systems that
    408 	 * do not support flags.
    409 	 */
    410 	if (fs->st_flags != 0 && chflags(name, fs->st_flags))
    411 		cwarn("chflags: %s", name);
    412 }
    413 
    414 int
    415 permission(char *fname)
    416 {
    417 	int ch, first;
    418 
    419 	if (!isatty(fileno(stderr)))
    420 		return (0);
    421 	(void)fprintf(stderr, "overwrite %s? ", fname);
    422 	first = ch = getchar();
    423 	while (ch != '\n' && ch != EOF)
    424 		ch = getchar();
    425 	return (first == 'y');
    426 }
    427 
    428 void
    429 usage(int iscompress)
    430 {
    431 	if (iscompress)
    432 		(void)fprintf(stderr,
    433 		    "usage: compress [-cdfv] [-b bits] [file ...]\n");
    434 	else
    435 		(void)fprintf(stderr,
    436 		    "usage: uncompress [-cdfv] [-b bits] [file ...]\n");
    437 	exit(1);
    438 }
    439 
    440 void
    441 cwarnx(const char *fmt, ...)
    442 {
    443 	va_list ap;
    444 
    445 	va_start(ap, fmt);
    446 	vwarnx(fmt, ap);
    447 	va_end(ap);
    448 	eval = 1;
    449 }
    450 
    451 void
    452 cwarn(const char *fmt, ...)
    453 {
    454 	va_list ap;
    455 
    456 	va_start(ap, fmt);
    457 	vwarn(fmt, ap);
    458 	va_end(ap);
    459 	eval = 1;
    460 }
    461