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