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