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