xref: /netbsd-src/usr.bin/compress/compress.c (revision deb6f0161a9109e7de9b519dc8dfb9478668dcdd)
1 /*	$NetBSD: compress.c,v 1.26 2011/08/30 23:08:05 joerg 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. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1992, 1993\
35  The Regents of the University of California.  All rights reserved.");
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)compress.c	8.2 (Berkeley) 1/7/94";
41 #else
42 __RCSID("$NetBSD: compress.c,v 1.26 2011/08/30 23:08:05 joerg Exp $");
43 #endif
44 #endif /* not lint */
45 
46 #include <sys/param.h>
47 #include <sys/time.h>
48 #include <sys/stat.h>
49 
50 #include <err.h>
51 #include <errno.h>
52 #include <stdarg.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 
58 static void	compress(const char *, const char *, int);
59 static void	cwarn(const char *, ...) __printflike(1, 2);
60 static void	cwarnx(const char *, ...) __printflike(1, 2);
61 static void	decompress(const char *, const char *, int);
62 static int	permission(const char *);
63 static void	setfile(const char *, struct stat *);
64 __dead static void	usage(int);
65 
66 extern FILE *zopen(const char *fname, const char *mode, int bits);
67 
68 static int eval, force, verbose;
69 static int isstdout, isstdin;
70 
71 int
72 main(int argc, char **argv)
73 {
74         enum {COMPRESS, DECOMPRESS} style = COMPRESS;
75 	size_t len;
76 	int bits, cat, ch;
77 	char *p, newname[MAXPATHLEN];
78 
79 	if ((p = strrchr(argv[0], '/')) == NULL)
80 		p = argv[0];
81 	else
82 		++p;
83 	if (!strcmp(p, "uncompress"))
84 		style = DECOMPRESS;
85         else if (!strcmp(p, "compress"))
86                 style = COMPRESS;
87         else if (!strcmp(p, "zcat")) {
88                 style = DECOMPRESS;
89                 cat = 1;
90         }
91 	else
92 		errx(1, "unknown program name");
93 
94 	bits = cat = 0;
95 	while ((ch = getopt(argc, argv, "b:cdfv")) != -1)
96 		switch(ch) {
97 		case 'b':
98 			bits = strtol(optarg, &p, 10);
99 			if (*p)
100 				errx(1, "illegal bit count -- %s", optarg);
101 			break;
102 		case 'c':
103 			cat = 1;
104 			break;
105 		case 'd':		/* Backward compatible. */
106 			style = DECOMPRESS;
107 			break;
108 		case 'f':
109 			force = 1;
110 			break;
111 		case 'v':
112 			verbose = 1;
113 			break;
114 		case '?':
115 		default:
116 			usage(style == COMPRESS);
117 		}
118 	argc -= optind;
119 	argv += optind;
120 
121 	if (argc == 0) {
122 		switch(style) {
123 		case COMPRESS:
124 			isstdout = 1;
125 			isstdin = 1;
126 			(void)compress("/dev/stdin", "/dev/stdout", bits);
127 			break;
128 		case DECOMPRESS:
129 			isstdout = 1;
130 			isstdin = 1;
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 		isstdout = 0;
142 		switch(style) {
143 		case COMPRESS:
144 			if (cat) {
145 				isstdout = 1;
146 				compress(*argv, "/dev/stdout", bits);
147 				break;
148 			}
149 			if ((p = strrchr(*argv, '.')) != NULL &&
150 			    !strcmp(p, ".Z")) {
151 				cwarnx("%s: name already has trailing .Z",
152 				    *argv);
153 				break;
154 			}
155 			len = strlen(*argv);
156 			if (len > sizeof(newname) - 3) {
157 				cwarnx("%s: name too long", *argv);
158 				break;
159 			}
160 			memmove(newname, *argv, len);
161 			newname[len] = '.';
162 			newname[len + 1] = 'Z';
163 			newname[len + 2] = '\0';
164 			compress(*argv, newname, bits);
165 			break;
166 		case DECOMPRESS:
167 			len = strlen(*argv);
168 			if ((p = strrchr(*argv, '.')) == NULL ||
169 			    strcmp(p, ".Z")) {
170 				if (len > sizeof(newname) - 3) {
171 					cwarnx("%s: name too long", *argv);
172 					break;
173 				}
174 				memmove(newname, *argv, len);
175 				newname[len] = '.';
176 				newname[len + 1] = 'Z';
177 				newname[len + 2] = '\0';
178 				decompress(newname,
179 				    cat ? "/dev/stdout" : *argv, bits);
180 				if (cat)
181 					isstdout = 1;
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 				if (cat)
192 					isstdout = 1;
193 			}
194 			break;
195 		}
196 	}
197 	exit (eval);
198 }
199 
200 static void
201 compress(const char *in, const char *out, int bits)
202 {
203 	size_t nr;
204 	struct stat isb, sb;
205 	const char *error = NULL;
206 	FILE *ifp, *ofp;
207 	int exists, isreg, oreg;
208 	u_char buf[BUFSIZ];
209 
210 	if (!isstdout) {
211 		exists = !stat(out, &sb);
212 		if (!force && exists && S_ISREG(sb.st_mode) && !permission(out))
213 			return;
214 		oreg = !exists || S_ISREG(sb.st_mode);
215 	} else
216 		oreg = 0;
217 
218 	ifp = ofp = NULL;
219 	if ((ifp = fopen(in, "r")) == NULL) {
220 		cwarn("%s", in);
221 		return;
222 	}
223 
224 	if (!isstdin) {
225 		if (stat(in, &isb)) {		/* DON'T FSTAT! */
226 			cwarn("%s", in);
227 			goto err;
228 		}
229 		if (!S_ISREG(isb.st_mode))
230 			isreg = 0;
231 		else
232 			isreg = 1;
233 	} else
234 		isreg = 0;
235 
236 	if ((ofp = zopen(out, "w", bits)) == NULL) {
237 		cwarn("%s", out);
238 		goto err;
239 	}
240 	oreg <<= 1;
241 	while ((nr = fread(buf, 1, sizeof(buf), ifp)) != 0)
242 		if (fwrite(buf, 1, nr, ofp) != nr) {
243 			cwarn("%s", out);
244 			goto err;
245 		}
246 
247 	if (ferror(ifp))
248 		error = in;
249 	if (fclose(ifp))
250 		if (error == NULL)
251 			error = in;
252 	if (fclose(ofp))
253 		if (error == NULL)
254 			error = out;
255 	ifp = NULL;
256 	ofp = NULL;
257 	if (error) {
258 		cwarn("%s", error);
259 		goto err;
260 	}
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 			goto err;
272 		}
273 
274 		setfile(out, &isb);
275 
276 		if (unlink(in))
277 			cwarn("%s", in);
278 
279 		if (verbose) {
280 			(void)printf("%s: ", out);
281 			if (isb.st_size > sb.st_size)
282 				(void)printf("%.0f%% compression\n",
283 				    ((double)sb.st_size / isb.st_size) * 100.0);
284 			else
285 				(void)printf("%.0f%% expansion\n",
286 				    ((double)isb.st_size / sb.st_size) * 100.0);
287 		}
288 	}
289 	return;
290 
291 err:	if (ofp)
292 		(void)fclose(ofp);
293 	if (oreg == 2)
294 		(void)unlink(out);
295 	if (ifp)
296 		(void)fclose(ifp);
297 }
298 
299 static void
300 decompress(const char *in, const char *out, int bits)
301 {
302 	size_t nr;
303 	struct stat sb;
304 	FILE *ifp, *ofp;
305 	int exists, isreg, oreg;
306 	u_char buf[BUFSIZ];
307 
308 	if (!isstdout) {
309 		exists = !stat(out, &sb);
310 		if (!force && exists && S_ISREG(sb.st_mode) && !permission(out))
311 			return;
312 		oreg = !exists || S_ISREG(sb.st_mode);
313 	} else
314 		oreg = 0;
315 
316 	ifp = ofp = NULL;
317 	if ((ofp = fopen(out, "w")) == NULL) {
318 		cwarn("%s", out);
319 		return;
320 	}
321 
322 	if ((ifp = zopen(in, "r", bits)) == NULL) {
323 		cwarn("%s", in);
324 		goto err;
325 	}
326 	if (!isstdin) {
327 		if (stat(in, &sb)) {
328 			cwarn("%s", in);
329 			goto err;
330 		}
331 		if (!S_ISREG(sb.st_mode))
332 			isreg = 0;
333 		else
334 			isreg = 1;
335 	} else
336 		isreg = 0;
337 
338 	oreg <<= 1;
339 	while ((nr = fread(buf, 1, sizeof(buf), ifp)) != 0)
340 		if (fwrite(buf, 1, nr, ofp) != nr) {
341 			cwarn("%s", out);
342 			goto err;
343 		}
344 
345 	if (ferror(ifp)) {
346 		cwarn("%s", in);
347 		goto err;
348 	}
349 	if (fclose(ifp)) {
350 		ifp = NULL;
351 		cwarn("%s", in);
352 		goto err;
353 	}
354 	ifp = NULL;
355 
356 	if (fclose(ofp)) {
357 		ofp = NULL;
358 		cwarn("%s", out);
359 		goto err;
360 	}
361 
362 	if (isreg && oreg) {
363 		setfile(out, &sb);
364 
365 		if (unlink(in))
366 			cwarn("%s", in);
367 	}
368 	return;
369 
370 err:	if (ofp)
371 		(void)fclose(ofp);
372 	if (oreg == 2)
373 		(void)unlink(out);
374 	if (ifp)
375 		(void)fclose(ifp);
376 }
377 
378 static void
379 setfile(const char *name, struct stat *fs)
380 {
381 	static struct timeval tv[2];
382 
383 	fs->st_mode &= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
384 
385 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
386 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
387 	if (utimes(name, tv))
388 		cwarn("utimes: %s", name);
389 
390 	/*
391 	 * Changing the ownership probably won't succeed, unless we're root
392 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
393 	 * the mode; current BSD behavior is to remove all setuid bits on
394 	 * chown.  If chown fails, lose setuid/setgid bits.
395 	 */
396 	if (chown(name, fs->st_uid, fs->st_gid)) {
397 		if (errno != EPERM)
398 			cwarn("chown: %s", name);
399 		fs->st_mode &= ~(S_ISUID|S_ISGID);
400 	}
401 	if (chmod(name, fs->st_mode))
402 		cwarn("chown: %s", name);
403 
404 	/*
405 	 * Restore the file's flags.  However, do this only if the original
406 	 * file had any flags set; this avoids a warning on file-systems that
407 	 * do not support flags.
408 	 */
409 	if (fs->st_flags != 0 && chflags(name, fs->st_flags))
410 		cwarn("chflags: %s", name);
411 }
412 
413 static int
414 permission(const char *fname)
415 {
416 	int ch, first;
417 
418 	if (!isatty(fileno(stderr)))
419 		return (0);
420 	(void)fprintf(stderr, "overwrite %s? ", fname);
421 	first = ch = getchar();
422 	while (ch != '\n' && ch != EOF)
423 		ch = getchar();
424 	return (first == 'y');
425 }
426 
427 static void
428 usage(int iscompress)
429 {
430 	if (iscompress)
431 		(void)fprintf(stderr,
432 		    "usage: compress [-cdfv] [-b bits] [file ...]\n");
433 	else
434 		(void)fprintf(stderr,
435 		    "usage: uncompress [-cdfv] [-b bits] [file ...]\n");
436 	exit(1);
437 }
438 
439 static void
440 cwarnx(const char *fmt, ...)
441 {
442 	va_list ap;
443 
444 	va_start(ap, fmt);
445 	vwarnx(fmt, ap);
446 	va_end(ap);
447 	eval = 1;
448 }
449 
450 static void
451 cwarn(const char *fmt, ...)
452 {
453 	va_list ap;
454 
455 	va_start(ap, fmt);
456 	vwarn(fmt, ap);
457 	va_end(ap);
458 	eval = 1;
459 }
460