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