xref: /freebsd/usr.bin/compress/compress.c (revision fa146c53357ea20afd3661d8093ea1db44198d5f)
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 static const char sccsid[] = "@(#)compress.c	8.2 (Berkeley) 1/7/94";
42 #endif /* not lint */
43 
44 #include <sys/param.h>
45 #include <sys/time.h>
46 #include <sys/stat.h>
47 
48 #include <err.h>
49 #include <errno.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 
55 #ifdef __STDC__
56 #include <stdarg.h>
57 #else
58 #include <varargs.h>
59 #endif
60 
61 #include "zopen.h"
62 
63 void	compress __P((char *, char *, int));
64 void	cwarn __P((const char *, ...));
65 void	cwarnx __P((const char *, ...));
66 void	decompress __P((char *, char *, int));
67 int	permission __P((char *));
68 void	setfile __P((char *, struct stat *));
69 void	usage __P((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 (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 
193 void
194 compress(in, out, bits)
195 	char *in, *out;
196 	int bits;
197 {
198 	register int 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)printf("%s: file would grow; left unmodified\n", in);
252 			if (unlink(out))
253 				cwarn("%s", out);
254 			goto err;
255 		}
256 
257 		setfile(out, &isb);
258 
259 		if (unlink(in))
260 			cwarn("%s", in);
261 
262 		if (verbose) {
263 			(void)printf("%s: ", out);
264 			if (isb.st_size > sb.st_size)
265 				(void)printf("%.0f%% compression\n",
266 				    ((float)sb.st_size / isb.st_size) * 100.0);
267 			else
268 				(void)printf("%.0f%% expansion\n",
269 				    ((float)isb.st_size / sb.st_size) * 100.0);
270 		}
271 	}
272 	return;
273 
274 err:	if (ofp) {
275 		if (oreg)
276 			(void)unlink(out);
277 		(void)fclose(ofp);
278 	}
279 	if (ifp)
280 		(void)fclose(ifp);
281 }
282 
283 void
284 decompress(in, out, bits)
285 	char *in, *out;
286 	int bits;
287 {
288 	register int nr;
289 	struct stat sb;
290 	FILE *ifp, *ofp;
291 	int exists, isreg, oreg;
292 	u_char buf[1024];
293 
294 	exists = !stat(out, &sb);
295 	if (!force && exists && S_ISREG(sb.st_mode) && !permission(out))
296 		return;
297 	isreg = oreg = !exists || S_ISREG(sb.st_mode);
298 
299 	ifp = ofp = NULL;
300 	if ((ofp = fopen(out, "w")) == NULL) {
301 		cwarn("%s", out);
302 		return;
303 	}
304 
305 	if ((ifp = zopen(in, "r", bits)) == NULL) {
306 		cwarn("%s", in);
307 		goto err;
308 	}
309 	if (stat(in, &sb)) {
310 		cwarn("%s", in);
311 		goto err;
312 	}
313 	if (!S_ISREG(sb.st_mode))
314 		isreg = 0;
315 
316 	while ((nr = fread(buf, 1, sizeof(buf), ifp)) != 0)
317 		if (fwrite(buf, 1, nr, ofp) != nr) {
318 			cwarn("%s", out);
319 			goto err;
320 		}
321 
322 	if (ferror(ifp) || fclose(ifp)) {
323 		cwarn("%s", in);
324 		goto err;
325 	}
326 	ifp = NULL;
327 
328 	if (fclose(ofp)) {
329 		cwarn("%s", out);
330 		goto err;
331 	}
332 
333 	if (isreg) {
334 		setfile(out, &sb);
335 
336 		if (unlink(in))
337 			cwarn("%s", in);
338 	}
339 	return;
340 
341 err:	if (ofp) {
342 		if (oreg)
343 			(void)unlink(out);
344 		(void)fclose(ofp);
345 	}
346 	if (ifp)
347 		(void)fclose(ifp);
348 }
349 
350 void
351 setfile(name, fs)
352 	char *name;
353 	register struct stat *fs;
354 {
355 	static struct timeval tv[2];
356 
357 	fs->st_mode &= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
358 
359 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
360 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
361 	if (utimes(name, tv))
362 		cwarn("utimes: %s", name);
363 
364 	/*
365 	 * Changing the ownership probably won't succeed, unless we're root
366 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
367 	 * the mode; current BSD behavior is to remove all setuid bits on
368 	 * chown.  If chown fails, lose setuid/setgid bits.
369 	 */
370 	if (chown(name, fs->st_uid, fs->st_gid)) {
371 		if (errno != EPERM)
372 			cwarn("chown: %s", name);
373 		fs->st_mode &= ~(S_ISUID|S_ISGID);
374 	}
375 	if (chmod(name, fs->st_mode))
376 		cwarn("chown: %s", name);
377 
378 	if (chflags(name, fs->st_flags))
379 		cwarn("chflags: %s", name);
380 }
381 
382 int
383 permission(fname)
384 	char *fname;
385 {
386 	int ch, first;
387 
388 	if (!isatty(fileno(stderr)))
389 		return (0);
390 	(void)fprintf(stderr, "overwrite %s? ", fname);
391 	first = ch = getchar();
392 	while (ch != '\n' && ch != EOF)
393 		ch = getchar();
394 	return (first == 'y');
395 }
396 
397 void
398 usage(iscompress)
399 	int iscompress;
400 {
401 	if (iscompress)
402 		(void)fprintf(stderr,
403 		    "usage: compress [-cfv] [-b bits] [file ...]\n");
404 	else
405 		(void)fprintf(stderr,
406 		    "usage: uncompress [-c] [-b bits] [file ...]\n");
407 	exit(1);
408 }
409 
410 void
411 #if __STDC__
412 cwarnx(const char *fmt, ...)
413 #else
414 cwarnx(fmt, va_alist)
415 	int eval;
416 	const char *fmt;
417 	va_dcl
418 #endif
419 {
420 	va_list ap;
421 #if __STDC__
422 	va_start(ap, fmt);
423 #else
424 	va_start(ap);
425 #endif
426 	vwarnx(fmt, ap);
427 	va_end(ap);
428 	eval = 1;
429 }
430 
431 void
432 #if __STDC__
433 cwarn(const char *fmt, ...)
434 #else
435 cwarn(fmt, va_alist)
436 	int eval;
437 	const char *fmt;
438 	va_dcl
439 #endif
440 {
441 	va_list ap;
442 #if __STDC__
443 	va_start(ap, fmt);
444 #else
445 	va_start(ap);
446 #endif
447 	vwarn(fmt, ap);
448 	va_end(ap);
449 	eval = 1;
450 }
451