xref: /freebsd/usr.bin/compress/compress.c (revision fae643c5795db2d9bf031c6db8a70ba8d6978c62)
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 /* not lint */
39 
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)compress.c	8.2 (Berkeley) 1/7/94";
43 #endif
44 static const char rcsid[] =
45   "$FreeBSD$";
46 #endif /* not lint */
47 
48 #include <sys/param.h>
49 #include <sys/stat.h>
50 
51 #include <err.h>
52 #include <errno.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 
58 #ifdef __STDC__
59 #include <stdarg.h>
60 #else
61 #include <varargs.h>
62 #endif
63 
64 #include "zopen.h"
65 
66 void	compress __P((char *, char *, int));
67 void	cwarn __P((const char *, ...));
68 void	cwarnx __P((const char *, ...));
69 void	decompress __P((char *, char *, int));
70 int	permission __P((char *));
71 void	setfile __P((char *, struct stat *));
72 void	usage __P((int));
73 
74 int eval, force, verbose;
75 
76 int
77 main(argc, argv)
78 	int argc;
79 	char *argv[];
80 {
81 	enum {COMPRESS, DECOMPRESS} style;
82 	size_t len;
83 	int bits, cat, ch;
84 	char *p, newname[MAXPATHLEN];
85 
86 	cat = 0;
87 	if ((p = rindex(argv[0], '/')) == NULL)
88 		p = argv[0];
89 	else
90 		++p;
91 	if (!strcmp(p, "uncompress"))
92 		style = DECOMPRESS;
93 	else if (!strcmp(p, "compress"))
94 		style = COMPRESS;
95 	else if (!strcmp(p, "zcat")) {
96 		cat = 1;
97 		style = DECOMPRESS;
98 	} else
99 		errx(1, "unknown program name");
100 
101 	bits = 0;
102 	while ((ch = getopt(argc, argv, "b:cdfv")) != -1)
103 		switch(ch) {
104 		case 'b':
105 			bits = strtol(optarg, &p, 10);
106 			if (*p)
107 				errx(1, "illegal bit count -- %s", optarg);
108 			break;
109 		case 'c':
110 			cat = 1;
111 			break;
112 		case 'd':		/* Backward compatible. */
113 			style = DECOMPRESS;
114 			break;
115 		case 'f':
116 			force = 1;
117 			break;
118 		case 'v':
119 			verbose = 1;
120 			break;
121 		case '?':
122 		default:
123 			usage(style == COMPRESS);
124 		}
125 	argc -= optind;
126 	argv += optind;
127 
128 	if (argc == 0) {
129 		switch(style) {
130 		case COMPRESS:
131 			(void)compress("/dev/stdin", "/dev/stdout", bits);
132 			break;
133 		case DECOMPRESS:
134 			(void)decompress("/dev/stdin", "/dev/stdout", bits);
135 			break;
136 		}
137 		exit (eval);
138 	}
139 
140 	if (cat == 1 && argc > 1)
141 		errx(1, "the -c option permits only a single file argument");
142 
143 	for (; *argv; ++argv)
144 		switch(style) {
145 		case COMPRESS:
146 			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 			len = strlen(*argv);
169 			if ((p = rindex(*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 			} else {
182 				if (len - 2 > sizeof(newname) - 1) {
183 					cwarnx("%s: name too long", *argv);
184 					break;
185 				}
186 				memmove(newname, *argv, len - 2);
187 				newname[len - 2] = '\0';
188 				decompress(*argv,
189 				    cat ? "/dev/stdout" : newname, bits);
190 			}
191 			break;
192 		}
193 	exit (eval);
194 }
195 
196 void
197 compress(in, out, bits)
198 	char *in, *out;
199 	int bits;
200 {
201 	register int nr;
202 	struct stat isb, sb;
203 	FILE *ifp, *ofp;
204 	int exists, isreg, oreg;
205 	u_char buf[1024];
206 
207 	exists = !stat(out, &sb);
208 	if (!force && exists && S_ISREG(sb.st_mode) && !permission(out))
209 		return;
210 	isreg = oreg = !exists || S_ISREG(sb.st_mode);
211 
212 	ifp = ofp = NULL;
213 	if ((ifp = fopen(in, "r")) == NULL) {
214 		cwarn("%s", in);
215 		return;
216 	}
217 	if (stat(in, &isb)) {		/* DON'T FSTAT! */
218 		cwarn("%s", in);
219 		goto err;
220 	}
221 	if (!S_ISREG(isb.st_mode))
222 		isreg = 0;
223 
224 	if ((ofp = zopen(out, "w", bits)) == NULL) {
225 		cwarn("%s", out);
226 		goto err;
227 	}
228 	while ((nr = fread(buf, 1, sizeof(buf), ifp)) != 0)
229 		if (fwrite(buf, 1, nr, ofp) != nr) {
230 			cwarn("%s", out);
231 			goto err;
232 		}
233 
234 	if (ferror(ifp) || fclose(ifp)) {
235 		cwarn("%s", in);
236 		goto err;
237 	}
238 	ifp = NULL;
239 
240 	if (fclose(ofp)) {
241 		cwarn("%s", out);
242 		goto err;
243 	}
244 	ofp = NULL;
245 
246 	if (isreg) {
247 		if (stat(out, &sb)) {
248 			cwarn("%s", out);
249 			goto err;
250 		}
251 
252 		if (!force && sb.st_size >= isb.st_size) {
253 			if (verbose)
254 		(void)printf("%s: file would grow; left unmodified\n", in);
255 			if (unlink(out))
256 				cwarn("%s", out);
257 			goto err;
258 		}
259 
260 		setfile(out, &isb);
261 
262 		if (unlink(in))
263 			cwarn("%s", in);
264 
265 		if (verbose) {
266 			(void)printf("%s: ", out);
267 			if (isb.st_size > sb.st_size)
268 				(void)printf("%.0f%% compression\n",
269 				    ((float)sb.st_size / isb.st_size) * 100.0);
270 			else
271 				(void)printf("%.0f%% expansion\n",
272 				    ((float)isb.st_size / sb.st_size) * 100.0);
273 		}
274 	}
275 	return;
276 
277 err:	if (ofp) {
278 		if (oreg)
279 			(void)unlink(out);
280 		(void)fclose(ofp);
281 	}
282 	if (ifp)
283 		(void)fclose(ifp);
284 }
285 
286 void
287 decompress(in, out, bits)
288 	char *in, *out;
289 	int bits;
290 {
291 	register int nr;
292 	struct stat sb;
293 	FILE *ifp, *ofp;
294 	int exists, isreg, oreg;
295 	u_char buf[1024];
296 
297 	exists = !stat(out, &sb);
298 	if (!force && exists && S_ISREG(sb.st_mode) && !permission(out))
299 		return;
300 	isreg = oreg = !exists || S_ISREG(sb.st_mode);
301 
302 	ifp = ofp = NULL;
303 	if ((ofp = fopen(out, "w")) == NULL) {
304 		cwarn("%s", out);
305 		return;
306 	}
307 
308 	if ((ifp = zopen(in, "r", bits)) == NULL) {
309 		cwarn("%s", in);
310 		goto err;
311 	}
312 	if (stat(in, &sb)) {
313 		cwarn("%s", in);
314 		goto err;
315 	}
316 	if (!S_ISREG(sb.st_mode))
317 		isreg = 0;
318 
319 	while ((nr = fread(buf, 1, sizeof(buf), ifp)) != 0)
320 		if (fwrite(buf, 1, nr, ofp) != nr) {
321 			cwarn("%s", out);
322 			goto err;
323 		}
324 
325 	if (ferror(ifp) || fclose(ifp)) {
326 		cwarn("%s", in);
327 		goto err;
328 	}
329 	ifp = NULL;
330 
331 	if (fclose(ofp)) {
332 		cwarn("%s", out);
333 		goto err;
334 	}
335 
336 	if (isreg) {
337 		setfile(out, &sb);
338 
339 		if (unlink(in))
340 			cwarn("%s", in);
341 	}
342 	return;
343 
344 err:	if (ofp) {
345 		if (oreg)
346 			(void)unlink(out);
347 		(void)fclose(ofp);
348 	}
349 	if (ifp)
350 		(void)fclose(ifp);
351 }
352 
353 void
354 setfile(name, fs)
355 	char *name;
356 	register struct stat *fs;
357 {
358 	static struct timeval tv[2];
359 
360 	fs->st_mode &= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
361 
362 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
363 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
364 	if (utimes(name, tv))
365 		cwarn("utimes: %s", name);
366 
367 	/*
368 	 * Changing the ownership probably won't succeed, unless we're root
369 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
370 	 * the mode; current BSD behavior is to remove all setuid bits on
371 	 * chown.  If chown fails, lose setuid/setgid bits.
372 	 */
373 	if (chown(name, fs->st_uid, fs->st_gid)) {
374 		if (errno != EPERM)
375 			cwarn("chown: %s", name);
376 		fs->st_mode &= ~(S_ISUID|S_ISGID);
377 	}
378 	if (chmod(name, fs->st_mode))
379 		cwarn("chmod: %s", name);
380 
381 	if (chflags(name, fs->st_flags))
382 		cwarn("chflags: %s", name);
383 }
384 
385 int
386 permission(fname)
387 	char *fname;
388 {
389 	int ch, first;
390 
391 	if (!isatty(fileno(stderr)))
392 		return (0);
393 	(void)fprintf(stderr, "overwrite %s? ", fname);
394 	first = ch = getchar();
395 	while (ch != '\n' && ch != EOF)
396 		ch = getchar();
397 	return (first == 'y');
398 }
399 
400 void
401 usage(iscompress)
402 	int iscompress;
403 {
404 	if (iscompress)
405 		(void)fprintf(stderr,
406 		    "usage: compress [-cfv] [-b bits] [file ...]\n");
407 	else
408 		(void)fprintf(stderr,
409 		    "usage: uncompress [-c] [-b bits] [file ...]\n");
410 	exit(1);
411 }
412 
413 void
414 #if __STDC__
415 cwarnx(const char *fmt, ...)
416 #else
417 cwarnx(fmt, va_alist)
418 	int eval;
419 	const char *fmt;
420 	va_dcl
421 #endif
422 {
423 	va_list ap;
424 #if __STDC__
425 	va_start(ap, fmt);
426 #else
427 	va_start(ap);
428 #endif
429 	vwarnx(fmt, ap);
430 	va_end(ap);
431 	eval = 1;
432 }
433 
434 void
435 #if __STDC__
436 cwarn(const char *fmt, ...)
437 #else
438 cwarn(fmt, va_alist)
439 	int eval;
440 	const char *fmt;
441 	va_dcl
442 #endif
443 {
444 	va_list ap;
445 #if __STDC__
446 	va_start(ap, fmt);
447 #else
448 	va_start(ap);
449 #endif
450 	vwarn(fmt, ap);
451 	va_end(ap);
452 	eval = 1;
453 }
454