xref: /freebsd/usr.bin/compress/compress.c (revision 09e8dea79366f1e5b3a73e8a271b26e4b6bf2e6a)
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
35 static 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
42 static char sccsid[] = "@(#)compress.c	8.2 (Berkeley) 1/7/94";
43 #endif
44 #endif
45 
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
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 
63 void	compress(const char *, const char *, int);
64 void	cwarn(const char *, ...) __printflike(1, 2);
65 void	cwarnx(const char *, ...) __printflike(1, 2);
66 void	decompress(const char *, const char *, int);
67 int	permission(const char *);
68 void	setfile(const char *, struct stat *);
69 void	usage(int);
70 
71 int eval, force, verbose;
72 
73 int
74 main(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 (strcmp(*argv, "-") == 0) {
144 				compress("/dev/stdin", "/dev/stdout", bits);
145 				break;
146 			} else if (cat) {
147 				compress(*argv, "/dev/stdout", bits);
148 				break;
149 			}
150 			if ((p = rindex(*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 			if (strcmp(*argv, "-") == 0) {
169 				decompress("/dev/stdin", "/dev/stdout", bits);
170 				break;
171 			}
172 			len = strlen(*argv);
173 			if ((p = rindex(*argv, '.')) == NULL ||
174 			    strcmp(p, ".Z")) {
175 				if (len > sizeof(newname) - 3) {
176 					cwarnx("%s: name too long", *argv);
177 					break;
178 				}
179 				memmove(newname, *argv, len);
180 				newname[len] = '.';
181 				newname[len + 1] = 'Z';
182 				newname[len + 2] = '\0';
183 				decompress(newname,
184 				    cat ? "/dev/stdout" : *argv, bits);
185 			} else {
186 				if (len - 2 > sizeof(newname) - 1) {
187 					cwarnx("%s: name too long", *argv);
188 					break;
189 				}
190 				memmove(newname, *argv, len - 2);
191 				newname[len - 2] = '\0';
192 				decompress(*argv,
193 				    cat ? "/dev/stdout" : newname, bits);
194 			}
195 			break;
196 		}
197 	exit (eval);
198 }
199 
200 void
201 compress(in, out, bits)
202 	const char *in, *out;
203 	int bits;
204 {
205 	size_t nr;
206 	struct stat isb, sb;
207 	FILE *ifp, *ofp;
208 	int exists, isreg, oreg;
209 	u_char buf[1024];
210 
211 	exists = !stat(out, &sb);
212 	if (!force && exists && S_ISREG(sb.st_mode) && !permission(out))
213 		return;
214 	isreg = oreg = !exists || S_ISREG(sb.st_mode);
215 
216 	ifp = ofp = NULL;
217 	if ((ifp = fopen(in, "r")) == NULL) {
218 		cwarn("%s", in);
219 		return;
220 	}
221 	if (stat(in, &isb)) {		/* DON'T FSTAT! */
222 		cwarn("%s", in);
223 		goto err;
224 	}
225 	if (!S_ISREG(isb.st_mode))
226 		isreg = 0;
227 
228 	if ((ofp = zopen(out, "w", bits)) == NULL) {
229 		cwarn("%s", out);
230 		goto err;
231 	}
232 	while ((nr = fread(buf, 1, sizeof(buf), ifp)) != 0)
233 		if (fwrite(buf, 1, nr, ofp) != nr) {
234 			cwarn("%s", out);
235 			goto err;
236 		}
237 
238 	if (ferror(ifp) || fclose(ifp)) {
239 		cwarn("%s", in);
240 		goto err;
241 	}
242 	ifp = NULL;
243 
244 	if (fclose(ofp)) {
245 		cwarn("%s", out);
246 		goto err;
247 	}
248 	ofp = NULL;
249 
250 	if (isreg) {
251 		if (stat(out, &sb)) {
252 			cwarn("%s", out);
253 			goto err;
254 		}
255 
256 		if (!force && sb.st_size >= isb.st_size) {
257 			if (verbose)
258 		(void)fprintf(stderr, "%s: file would grow; left unmodified\n",
259 		    in);
260 			eval = 2;
261 			if (unlink(out))
262 				cwarn("%s", out);
263 			goto err;
264 		}
265 
266 		setfile(out, &isb);
267 
268 		if (unlink(in))
269 			cwarn("%s", in);
270 
271 		if (verbose) {
272 			(void)fprintf(stderr, "%s: ", out);
273 			if (isb.st_size > sb.st_size)
274 				(void)fprintf(stderr, "%.0f%% compression\n",
275 				    ((float)sb.st_size / isb.st_size) * 100.0);
276 			else
277 				(void)fprintf(stderr, "%.0f%% expansion\n",
278 				    ((float)isb.st_size / sb.st_size) * 100.0);
279 		}
280 	}
281 	return;
282 
283 err:	if (ofp) {
284 		if (oreg)
285 			(void)unlink(out);
286 		(void)fclose(ofp);
287 	}
288 	if (ifp)
289 		(void)fclose(ifp);
290 }
291 
292 void
293 decompress(in, out, bits)
294 	const char *in, *out;
295 	int bits;
296 {
297 	size_t nr;
298 	struct stat sb;
299 	FILE *ifp, *ofp;
300 	int exists, isreg, oreg;
301 	u_char buf[1024];
302 
303 	exists = !stat(out, &sb);
304 	if (!force && exists && S_ISREG(sb.st_mode) && !permission(out))
305 		return;
306 	isreg = oreg = !exists || S_ISREG(sb.st_mode);
307 
308 	ifp = ofp = NULL;
309 	if ((ofp = fopen(out, "w")) == NULL) {
310 		cwarn("%s", out);
311 		return;
312 	}
313 
314 	if ((ifp = zopen(in, "r", bits)) == NULL) {
315 		cwarn("%s", in);
316 		goto err;
317 	}
318 	if (stat(in, &sb)) {
319 		cwarn("%s", in);
320 		goto err;
321 	}
322 	if (!S_ISREG(sb.st_mode))
323 		isreg = 0;
324 
325 	while ((nr = fread(buf, 1, sizeof(buf), ifp)) != 0)
326 		if (fwrite(buf, 1, nr, ofp) != nr) {
327 			cwarn("%s", out);
328 			goto err;
329 		}
330 
331 	if (ferror(ifp) || fclose(ifp)) {
332 		cwarn("%s", in);
333 		goto err;
334 	}
335 	ifp = NULL;
336 
337 	if (fclose(ofp)) {
338 		cwarn("%s", out);
339 		goto err;
340 	}
341 
342 	if (isreg) {
343 		setfile(out, &sb);
344 
345 		if (unlink(in))
346 			cwarn("%s", in);
347 	}
348 	return;
349 
350 err:	if (ofp) {
351 		if (oreg)
352 			(void)unlink(out);
353 		(void)fclose(ofp);
354 	}
355 	if (ifp)
356 		(void)fclose(ifp);
357 }
358 
359 void
360 setfile(name, fs)
361 	const char *name;
362 	struct stat *fs;
363 {
364 	static struct timeval tv[2];
365 
366 	fs->st_mode &= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
367 
368 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
369 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
370 	if (utimes(name, tv))
371 		cwarn("utimes: %s", name);
372 
373 	/*
374 	 * Changing the ownership probably won't succeed, unless we're root
375 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
376 	 * the mode; current BSD behavior is to remove all setuid bits on
377 	 * chown.  If chown fails, lose setuid/setgid bits.
378 	 */
379 	if (chown(name, fs->st_uid, fs->st_gid)) {
380 		if (errno != EPERM)
381 			cwarn("chown: %s", name);
382 		fs->st_mode &= ~(S_ISUID|S_ISGID);
383 	}
384 	if (chmod(name, fs->st_mode) && errno != EOPNOTSUPP)
385 		cwarn("chmod: %s", name);
386 
387 	if (chflags(name, fs->st_flags) && errno != EOPNOTSUPP)
388 		cwarn("chflags: %s", name);
389 }
390 
391 int
392 permission(fname)
393 	const char *fname;
394 {
395 	int ch, first;
396 
397 	if (!isatty(fileno(stderr)))
398 		return (0);
399 	(void)fprintf(stderr, "overwrite %s? ", fname);
400 	first = ch = getchar();
401 	while (ch != '\n' && ch != EOF)
402 		ch = getchar();
403 	return (first == 'y');
404 }
405 
406 void
407 usage(iscompress)
408 	int iscompress;
409 {
410 	if (iscompress)
411 		(void)fprintf(stderr,
412 		    "usage: compress [-cfv] [-b bits] [file ...]\n");
413 	else
414 		(void)fprintf(stderr,
415 		    "usage: uncompress [-c] [-b bits] [file ...]\n");
416 	exit(1);
417 }
418 
419 void
420 cwarnx(const char *fmt, ...)
421 {
422 	va_list ap;
423 
424 	va_start(ap, fmt);
425 	vwarnx(fmt, ap);
426 	va_end(ap);
427 	eval = 1;
428 }
429 
430 void
431 cwarn(const char *fmt, ...)
432 {
433 	va_list ap;
434 
435 	va_start(ap, fmt);
436 	vwarn(fmt, ap);
437 	va_end(ap);
438 	eval = 1;
439 }
440