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