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