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