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