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