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