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